diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/main/java/com/server/HandleUDP.java b/src/main/java/com/server/HandleUDP.java
index f31ab2a..16f35f1 100644
--- a/src/main/java/com/server/HandleUDP.java
+++ b/src/main/java/com/server/HandleUDP.java
@@ -1,183 +1,184 @@
package com.server;
import java.net.*;
import java.io.*;
import java.util.*;
/**
* This class handles most the primary UDP Upload and Download functionality for
* the server. All of the various handling of packets, whether it be dumping or
* recieving is handled inside. A side note: ALL of the methods used for building
* the 'willdp' aka: the baby protocol on top of UDP the server uses to specifically
* consider '0' (that is, the char value of 0), to be the finishing bit for the connection.
* once that is reached, the respective sender is expected to send, in this order: a packet
* containing the ipAddress to bind to, as well as a port number.
*
*@author William Daniels
*@version 1.1
*/
class HandleUDP{
protected Map<String, TimeStampValue> addressTable;
private final static int ONE_MINUTE_IN_MILLISECONDS = 60000;
private final static int MAXIMUM_PACKET_SIZE = 1024 * 20;
private DatagramSocket client;
private final int whichPort;
/**
* constructor for the class, takes two parameters, as well as starts the thread.
*
* @param client The DatagramSocket that is connected to.
* @param whichPort an int that tells which port has been passed in.
*/
public HandleUDP(DatagramSocket client, int whichPort){
this.whichPort = whichPort;
this.client = client;
run();
}
/**
*simply chooses a port and runs it.
*/
public void run(){
if (whichPort == 6667)
uploadBlackHole();
else if (whichPort == 9999)
downloadDataDump();
}
/**
* This method handles all of the upload logic for the UDP protocol. When a connection
* is made to it, it 'black holes' all of the given information, and disposes it. It waits
* until the exit character (0) is sent to it, and then tries to connect to a remote host with
* the next two packets.
*
*/
private void uploadBlackHole(){
double length = 0.0;
addressTable = new HashMap<String, TimeStampValue>();
try{
//build a buffer for holding the packets.
byte[] buf = new byte[MAXIMUM_PACKET_SIZE];
//make a new packet object
DatagramPacket packet = new DatagramPacket(buf, buf.length);
//wait until you receive a packet
//***WARNING*** this IS a blocking call, due to the threaded nature of the
//server, this is not the end of the world, but be aware.
while(true){
client.receive(packet);
TimeStampValue compoundTimeValue = new TimeStampValue(packet.getLength(), System.currentTimeMillis());
byte[] data = packet.getData();
String temp = packet.getSocketAddress().toString();
if (addressTable.get(temp) == null){
System.out.println("New Connection established");
addressTable.put(temp, compoundTimeValue);
}
else{
addressTable.get(temp).value += packet.getLength();
+ addressTable.get(temp).timeStamp = System.currentTimeMillis();
}
//tempBuf = packet.getData();
//tempBufTwo = ("Well Hello back!").getBytes();
//DatagramPacket reSend = new DatagramPacket(tempBufTwo, tempBufTwo.length, packet.getAddress(), packet.getPort());
//client.send(reSend);
if (((char)packet.getData()[0]) == '0'){
System.out.println("About to send connection information to: " + packet.getAddress());
byte[] tempBuf = new byte[MAXIMUM_PACKET_SIZE];
//Write back a packet containing how many total bytes were written.
tempBuf = ("You sent " + addressTable.get(temp).value + " bytes of data via UDP\r\n").getBytes();
DatagramPacket tempPacket = new DatagramPacket(tempBuf, tempBuf.length, packet.getAddress(), packet.getPort());
//send the packet to the remote destination.
client.send(tempPacket);
}
//check the time of all current values in the addressTablem, delete all over 2 minutes old.
for (String iteration: addressTable.keySet()){
if ((addressTable.get(iteration).timeStamp - System.currentTimeMillis()) > ONE_MINUTE_IN_MILLISECONDS)
addressTable.remove(iteration);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
private void downloadDataDump(){;
try{
//build a buffer for holding the packets.
byte[] buf = new byte[MAXIMUM_PACKET_SIZE];
//make a new packet object
DatagramPacket packet = new DatagramPacket(buf, buf.length);
while(true){
client.receive(packet);
byte[] tempBuf = ("Get ready for 100 MB of fun!").getBytes();
System.out.println("I'm about to throw 100MB of the best data in the world at: " + packet.getAddress());
DatagramPacket sendPacket = new DatagramPacket(tempBuf, tempBuf.length, packet.getAddress(), packet.getPort());
client.send(sendPacket);
Thread.sleep(100);
(new DumpData(packet.getAddress(), packet.getPort(), client)).start();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
/**
* This class is simply a compound object for holding both a value and a timestamp for cleaning out the
* UDP map above.
*
*@author William Daniels
*/
class TimeStampValue {
public int value;
public long timeStamp;
public TimeStampValue(int value, long timeStamp){
this.value = value;
this.timeStamp = timeStamp;
}
}
class DumpData extends Thread{
private final static int MAXIMUM_PACKET_SIZE = 1400;
private final int BYTES_IN_MEGABYTES = 1048576;
private InetAddress sendAddress;
private int port;
private DatagramSocket client;
public DumpData(InetAddress sendAddress, int port, DatagramSocket client){
this.sendAddress = sendAddress;
this.port = port;
this.client = client;
}
public void run(){
try{
double totalBytes = 0.0;
byte[] b = new byte[MAXIMUM_PACKET_SIZE];
DatagramPacket sendPacket = new DatagramPacket(b, b.length, sendAddress, port);
new Random().nextBytes(b);
while ( totalBytes < (BYTES_IN_MEGABYTES * 100)){
client.send(sendPacket);
totalBytes = totalBytes + MAXIMUM_PACKET_SIZE;
}
b = ("All done! :) ").getBytes();
DatagramPacket sendPacketTwo = new DatagramPacket(b, b.length, sendAddress, port);
client.send(sendPacketTwo);
}catch(IOException e){
e.printStackTrace();
}
}
}
| true | true | private void uploadBlackHole(){
double length = 0.0;
addressTable = new HashMap<String, TimeStampValue>();
try{
//build a buffer for holding the packets.
byte[] buf = new byte[MAXIMUM_PACKET_SIZE];
//make a new packet object
DatagramPacket packet = new DatagramPacket(buf, buf.length);
//wait until you receive a packet
//***WARNING*** this IS a blocking call, due to the threaded nature of the
//server, this is not the end of the world, but be aware.
while(true){
client.receive(packet);
TimeStampValue compoundTimeValue = new TimeStampValue(packet.getLength(), System.currentTimeMillis());
byte[] data = packet.getData();
String temp = packet.getSocketAddress().toString();
if (addressTable.get(temp) == null){
System.out.println("New Connection established");
addressTable.put(temp, compoundTimeValue);
}
else{
addressTable.get(temp).value += packet.getLength();
}
//tempBuf = packet.getData();
//tempBufTwo = ("Well Hello back!").getBytes();
//DatagramPacket reSend = new DatagramPacket(tempBufTwo, tempBufTwo.length, packet.getAddress(), packet.getPort());
//client.send(reSend);
if (((char)packet.getData()[0]) == '0'){
System.out.println("About to send connection information to: " + packet.getAddress());
byte[] tempBuf = new byte[MAXIMUM_PACKET_SIZE];
//Write back a packet containing how many total bytes were written.
tempBuf = ("You sent " + addressTable.get(temp).value + " bytes of data via UDP\r\n").getBytes();
DatagramPacket tempPacket = new DatagramPacket(tempBuf, tempBuf.length, packet.getAddress(), packet.getPort());
//send the packet to the remote destination.
client.send(tempPacket);
}
//check the time of all current values in the addressTablem, delete all over 2 minutes old.
for (String iteration: addressTable.keySet()){
if ((addressTable.get(iteration).timeStamp - System.currentTimeMillis()) > ONE_MINUTE_IN_MILLISECONDS)
addressTable.remove(iteration);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
| private void uploadBlackHole(){
double length = 0.0;
addressTable = new HashMap<String, TimeStampValue>();
try{
//build a buffer for holding the packets.
byte[] buf = new byte[MAXIMUM_PACKET_SIZE];
//make a new packet object
DatagramPacket packet = new DatagramPacket(buf, buf.length);
//wait until you receive a packet
//***WARNING*** this IS a blocking call, due to the threaded nature of the
//server, this is not the end of the world, but be aware.
while(true){
client.receive(packet);
TimeStampValue compoundTimeValue = new TimeStampValue(packet.getLength(), System.currentTimeMillis());
byte[] data = packet.getData();
String temp = packet.getSocketAddress().toString();
if (addressTable.get(temp) == null){
System.out.println("New Connection established");
addressTable.put(temp, compoundTimeValue);
}
else{
addressTable.get(temp).value += packet.getLength();
addressTable.get(temp).timeStamp = System.currentTimeMillis();
}
//tempBuf = packet.getData();
//tempBufTwo = ("Well Hello back!").getBytes();
//DatagramPacket reSend = new DatagramPacket(tempBufTwo, tempBufTwo.length, packet.getAddress(), packet.getPort());
//client.send(reSend);
if (((char)packet.getData()[0]) == '0'){
System.out.println("About to send connection information to: " + packet.getAddress());
byte[] tempBuf = new byte[MAXIMUM_PACKET_SIZE];
//Write back a packet containing how many total bytes were written.
tempBuf = ("You sent " + addressTable.get(temp).value + " bytes of data via UDP\r\n").getBytes();
DatagramPacket tempPacket = new DatagramPacket(tempBuf, tempBuf.length, packet.getAddress(), packet.getPort());
//send the packet to the remote destination.
client.send(tempPacket);
}
//check the time of all current values in the addressTablem, delete all over 2 minutes old.
for (String iteration: addressTable.keySet()){
if ((addressTable.get(iteration).timeStamp - System.currentTimeMillis()) > ONE_MINUTE_IN_MILLISECONDS)
addressTable.remove(iteration);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
|
diff --git a/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/xobject/PDJpeg.java b/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/xobject/PDJpeg.java
index 0b50a261..59874ea2 100644
--- a/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/xobject/PDJpeg.java
+++ b/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/graphics/xobject/PDJpeg.java
@@ -1,531 +1,533 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.pdmodel.graphics.xobject;
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.imageio.IIOException;
import javax.imageio.ImageReader;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageInputStream;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.common.PDStream;
import org.apache.pdfbox.pdmodel.common.function.PDFunction;
import org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceCMYK;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceGray;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceN;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB;
import org.apache.pdfbox.pdmodel.graphics.color.PDICCBased;
import org.apache.pdfbox.pdmodel.graphics.color.PDSeparation;
import org.apache.pdfbox.util.ImageIOUtil;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* An image class for JPegs.
*
* @author mathiak
* @version $Revision: 1.5 $
*/
public class PDJpeg extends PDXObjectImage
{
private BufferedImage image = null;
private static final String JPG = "jpg";
private static final List<String> DCT_FILTERS = new ArrayList<String>();
private static final float DEFAULT_COMPRESSION_LEVEL = 0.75f;
static
{
DCT_FILTERS.add( COSName.DCT_DECODE.getName() );
DCT_FILTERS.add( COSName.DCT_DECODE_ABBREVIATION.getName() );
}
/**
* Standard constructor.
*
* @param jpeg The COSStream from which to extract the JPeg
*/
public PDJpeg(PDStream jpeg)
{
super(jpeg, JPG);
}
/**
* Construct from a stream.
*
* @param doc The document to create the image as part of.
* @param is The stream that contains the jpeg data.
* @throws IOException If there is an error reading the jpeg data.
*/
public PDJpeg( PDDocument doc, InputStream is ) throws IOException
{
super( new PDStream( doc, is, true ), JPG);
COSDictionary dic = getCOSStream();
dic.setItem( COSName.FILTER, COSName.DCT_DECODE );
dic.setItem( COSName.SUBTYPE, COSName.IMAGE);
dic.setItem( COSName.TYPE, COSName.XOBJECT );
getRGBImage();
if (image != null)
{
setBitsPerComponent( 8 );
setColorSpace( PDDeviceRGB.INSTANCE );
setHeight( image.getHeight() );
setWidth( image.getWidth() );
}
}
/**
* Construct from a buffered image.
* The default compression level of 0.75 will be used.
*
* @param doc The document to create the image as part of.
* @param bi The image to convert to a jpeg
* @throws IOException If there is an error processing the jpeg data.
*/
public PDJpeg( PDDocument doc, BufferedImage bi ) throws IOException
{
super( new PDStream( doc ) , JPG);
createImageStream(doc, bi, DEFAULT_COMPRESSION_LEVEL);
}
/**
* Construct from a buffered image.
*
* @param doc The document to create the image as part of.
* @param bi The image to convert to a jpeg
* @param compressionQuality The quality level which is used to compress the image
* @throws IOException If there is an error processing the jpeg data.
*/
public PDJpeg( PDDocument doc, BufferedImage bi, float compressionQuality ) throws IOException
{
super( new PDStream( doc ), JPG);
createImageStream(doc, bi, compressionQuality);
}
private void createImageStream(PDDocument doc, BufferedImage bi, float compressionQuality) throws IOException
{
BufferedImage alpha = null;
if (bi.getColorModel().hasAlpha())
{
// extract the alpha information
WritableRaster alphaRaster = bi.getAlphaRaster();
ColorModel cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY),
false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
alpha = new BufferedImage(cm, alphaRaster, false, null);
// create a RGB image without alpha
image = new BufferedImage(bi.getWidth(), bi.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setComposite(AlphaComposite.Src);
g.drawImage(bi, 0, 0, null);
bi = image;
}
java.io.OutputStream os = getCOSStream().createFilteredStream();
try
{
ImageIOUtil.writeImage(bi, JPG, os, ImageIOUtil.DEFAULT_SCREEN_RESOLUTION, compressionQuality);
COSDictionary dic = getCOSStream();
dic.setItem( COSName.FILTER, COSName.DCT_DECODE );
dic.setItem( COSName.SUBTYPE, COSName.IMAGE);
dic.setItem( COSName.TYPE, COSName.XOBJECT );
PDXObjectImage alphaPdImage = null;
if(alpha != null)
{
alphaPdImage = new PDJpeg(doc, alpha, compressionQuality);
dic.setItem(COSName.SMASK, alphaPdImage);
}
setBitsPerComponent( 8 );
if (bi.getColorModel().getNumComponents() == 3)
{
setColorSpace( PDDeviceRGB.INSTANCE );
}
else
{
if (bi.getColorModel().getNumComponents() == 1)
{
setColorSpace( new PDDeviceGray() );
}
else
{
throw new IllegalStateException();
}
}
setHeight( bi.getHeight() );
setWidth( bi.getWidth() );
}
finally
{
os.close();
}
}
/**
* Returns an image of the JPeg, or null if JPegs are not supported. (They should be. )
* {@inheritDoc}
*/
public BufferedImage getRGBImage() throws IOException
{
if (image != null)
{
+ // use the cached image
return image;
}
BufferedImage bi = null;
boolean readError = false;
ByteArrayOutputStream os = new ByteArrayOutputStream();
removeAllFiltersButDCT(os);
os.close();
byte[] img = os.toByteArray();
PDColorSpace cs = getColorSpace();
try
{
if (cs instanceof PDDeviceCMYK
|| (cs instanceof PDICCBased && cs.getNumberOfComponents() == 4))
{
// JPEGs may contain CMYK, YCbCr or YCCK decoded image data
int transform = getApp14AdobeTransform(img);
// create BufferedImage based on the converted color values
if (transform == 0)
{
bi = convertCMYK2RGB(readImage(img), cs);
}
else if (transform == 1)
{
// TODO YCbCr
}
else if (transform == 2)
{
bi = convertYCCK2RGB(readImage(img));
}
}
else if (cs instanceof PDSeparation)
{
// create BufferedImage based on the converted color values
bi = processTintTransformation(readImage(img),
((PDSeparation)cs).getTintTransform(), cs.getJavaColorSpace());
}
else if (cs instanceof PDDeviceN)
{
// create BufferedImage based on the converted color values
bi = processTintTransformation(readImage(img),
((PDDeviceN)cs).getTintTransform(), cs.getJavaColorSpace());
}
else
{
ByteArrayInputStream bai = new ByteArrayInputStream(img);
bi = ImageIO.read(bai);
}
}
catch(IIOException exception)
{
readError = true;
}
// 2. try to read jpeg again. some jpegs have some strange header containing
// "Adobe " at some place. so just replace the header with a valid jpeg header.
// TODO : not sure if it works for all cases
if (bi == null && readError)
{
byte[] newImage = replaceHeader(img);
ByteArrayInputStream bai = new ByteArrayInputStream(newImage);
bi = ImageIO.read(bai);
}
// If there is a 'soft mask' or 'mask' image then we use that as a transparency mask.
- return applyMasks(bi);
+ image = applyMasks(bi);
+ return image;
}
/**
* This writes the JPeg to out.
* {@inheritDoc}
*/
public void write2OutputStream(OutputStream out) throws IOException
{
getRGBImage();
if (image != null)
{
ImageIOUtil.writeImage(image, JPG, out);
}
}
private void removeAllFiltersButDCT(OutputStream out) throws IOException
{
InputStream data = getPDStream().getPartiallyFilteredStream( DCT_FILTERS );
byte[] buf = new byte[1024];
int amountRead = -1;
while( (amountRead = data.read( buf )) != -1 )
{
out.write( buf, 0, amountRead );
}
}
private int getHeaderEndPos(byte[] imageAsBytes)
{
for (int i = 0; i < imageAsBytes.length; i++)
{
byte b = imageAsBytes[i];
if (b == (byte) 0xDB)
{
// TODO : check for ff db
return i -2;
}
}
return 0;
}
private byte[] replaceHeader(byte[] imageAsBytes)
{
// get end position of wrong header respectively startposition of "real jpeg data"
int pos = getHeaderEndPos(imageAsBytes);
// simple correct header
byte[] header = new byte[]{(byte) 0xFF, (byte) 0xD8, (byte) 0xFF, (byte) 0xE0, (byte) 0x00,
(byte) 0x10, (byte) 0x4A, (byte) 0x46, (byte) 0x49, (byte) 0x46, (byte) 0x00, (byte) 0x01,
(byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x60, (byte) 0x00, (byte) 0x60, (byte) 0x00, (byte) 0x00};
// concat
byte[] newImage = new byte[imageAsBytes.length - pos + header.length - 1];
System.arraycopy(header, 0, newImage, 0, header.length);
System.arraycopy(imageAsBytes, pos + 1, newImage, header.length, imageAsBytes.length - pos - 1);
return newImage;
}
private int getApp14AdobeTransform(byte[] bytes)
{
int transformType = 0;
ImageReader reader = null;
ImageInputStream input = null;
try
{
input = ImageIO.createImageInputStream(new ByteArrayInputStream(bytes));
Iterator<ImageReader> readers = ImageIO.getImageReaders(input);
if (readers == null || !readers.hasNext())
{
input.close();
throw new RuntimeException("No ImageReaders found");
}
reader = (ImageReader) readers.next();
reader.setInput(input);
IIOMetadata meta = reader.getImageMetadata(0);
if (meta != null)
{
Node tree = meta.getAsTree("javax_imageio_jpeg_image_1.0");
NodeList children = tree.getChildNodes();
for (int i=0;i<children.getLength();i++)
{
Node markerSequence = children.item(i);
if ("markerSequence".equals(markerSequence.getNodeName()))
{
NodeList markerSequenceChildren = markerSequence.getChildNodes();
for (int j=0;j<markerSequenceChildren.getLength();j++)
{
Node child = markerSequenceChildren.item(j);
if ("app14Adobe".equals(child.getNodeName()) && child.hasAttributes())
{
NamedNodeMap attribs = child.getAttributes();
Node transformNode = attribs.getNamedItem("transform");
transformType = Integer.parseInt(transformNode.getNodeValue());
break;
}
}
}
}
}
}
catch(IOException exception)
{
}
finally
{
if (reader != null)
{
reader.dispose();
}
}
return transformType;
}
private Raster readImage(byte[] bytes) throws IOException
{
ImageInputStream input = ImageIO.createImageInputStream(new ByteArrayInputStream(bytes));
Iterator<ImageReader> readers = ImageIO.getImageReaders(input);
if (readers == null || !readers.hasNext())
{
input.close();
throw new RuntimeException("No ImageReaders found");
}
// read the raster information only
// avoid to access the meta information
ImageReader reader = (ImageReader) readers.next();
reader.setInput(input);
Raster raster = reader.readRaster(0, reader.getDefaultReadParam());
input.close();
reader.dispose();
return raster;
}
// CMYK jpegs are not supported by JAI, so that we have to do the conversion on our own
private BufferedImage convertCMYK2RGB(Raster raster, PDColorSpace colorspace) throws IOException
{
// create a java color space to be used for conversion
ColorSpace cs = colorspace.getJavaColorSpace();
int width = raster.getWidth();
int height = raster.getHeight();
byte[] rgb = new byte[width * height * 3];
int rgbIndex = 0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
// get the source color values
float[] srcColorValues = raster.getPixel(j,i, (float[])null);
// convert values from 0..255 to 0..1
for (int k = 0; k < 4; k++)
{
srcColorValues[k] /= 255f;
}
// convert CMYK to RGB
float[] rgbValues = cs.toRGB(srcColorValues);
// convert values from 0..1 to 0..255
for (int k = 0; k < 3; k++)
{
rgb[rgbIndex+k] = (byte)(rgbValues[k] * 255);
}
rgbIndex +=3;
}
}
return createRGBBufferedImage(ColorSpace.getInstance(ColorSpace.CS_sRGB), rgb, width, height);
}
// YCbCrK jpegs are not supported by JAI, so that we have to do the conversion on our own
private BufferedImage convertYCCK2RGB(Raster raster) throws IOException
{
int width = raster.getWidth();
int height = raster.getHeight();
byte[] rgb = new byte[width * height * 3];
int rgbIndex = 0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
float[] srcColorValues = raster.getPixel(j,i, (float[])null);
float k = srcColorValues[3];
float y = srcColorValues[0];
float c1=srcColorValues[1];
float c2=srcColorValues[2];
double val = y + 1.402 * ( c2 - 128 ) - k;
rgb[rgbIndex] = val < 0.0 ? (byte)0 : (val>255.0? (byte)0xff : (byte)(val+0.5));
val = y - 0.34414 * ( c1 - 128 ) - 0.71414 * ( c2 - 128 ) - k;
rgb[rgbIndex+1] = val<0.0? (byte)0: val>255.0? (byte)0xff: (byte)(val+0.5);
val = y + 1.772 * ( c1 - 128 ) - k;
rgb[rgbIndex+2] = val<0.0? (byte)0: val>255.0? (byte)0xff: (byte)(val+0.5);
rgbIndex +=3;
}
}
return createRGBBufferedImage(ColorSpace.getInstance(ColorSpace.CS_sRGB), rgb, width, height);
}
// Separation and DeviceN colorspaces are using a tint transform function to convert color values
private BufferedImage processTintTransformation(Raster raster, PDFunction function, ColorSpace colorspace)
throws IOException
{
int numberOfInputValues = function.getNumberOfInputParameters();
int numberOfOutputValues = function.getNumberOfOutputParameters();
int width = raster.getWidth();
int height = raster.getHeight();
byte[] rgb = new byte[width * height * numberOfOutputValues];
int bufferIndex = 0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
// get the source color values
float[] srcColorValues = raster.getPixel(j,i, (float[])null);
// convert values from 0..255 to 0..1
for (int k = 0; k < numberOfInputValues; k++)
{
srcColorValues[k] /= 255f;
}
// transform the color values using the tint function
float[] convertedValues = function.eval(srcColorValues);
// convert values from 0..1 to 0..255
for (int k = 0; k < numberOfOutputValues; k++)
{
rgb[bufferIndex+k] = (byte)(convertedValues[k] * 255);
}
bufferIndex +=numberOfOutputValues;
}
}
return createRGBBufferedImage(colorspace, rgb, width, height);
}
private BufferedImage createRGBBufferedImage(ColorSpace cs, byte[] rgb, int width, int height)
{
// create a RGB color model
ColorModel cm = new ComponentColorModel(cs, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
// create the target raster
WritableRaster writeableRaster = cm.createCompatibleWritableRaster(width, height);
// get the data buffer of the raster
DataBufferByte buffer = (DataBufferByte)writeableRaster.getDataBuffer();
byte[] bufferData = buffer.getData();
// copy all the converted data to the raster buffer
System.arraycopy( rgb, 0,bufferData, 0,rgb.length );
// create an image using the converted color values
return new BufferedImage(cm, writeableRaster, true, null);
}
}
| false | true | public BufferedImage getRGBImage() throws IOException
{
if (image != null)
{
return image;
}
BufferedImage bi = null;
boolean readError = false;
ByteArrayOutputStream os = new ByteArrayOutputStream();
removeAllFiltersButDCT(os);
os.close();
byte[] img = os.toByteArray();
PDColorSpace cs = getColorSpace();
try
{
if (cs instanceof PDDeviceCMYK
|| (cs instanceof PDICCBased && cs.getNumberOfComponents() == 4))
{
// JPEGs may contain CMYK, YCbCr or YCCK decoded image data
int transform = getApp14AdobeTransform(img);
// create BufferedImage based on the converted color values
if (transform == 0)
{
bi = convertCMYK2RGB(readImage(img), cs);
}
else if (transform == 1)
{
// TODO YCbCr
}
else if (transform == 2)
{
bi = convertYCCK2RGB(readImage(img));
}
}
else if (cs instanceof PDSeparation)
{
// create BufferedImage based on the converted color values
bi = processTintTransformation(readImage(img),
((PDSeparation)cs).getTintTransform(), cs.getJavaColorSpace());
}
else if (cs instanceof PDDeviceN)
{
// create BufferedImage based on the converted color values
bi = processTintTransformation(readImage(img),
((PDDeviceN)cs).getTintTransform(), cs.getJavaColorSpace());
}
else
{
ByteArrayInputStream bai = new ByteArrayInputStream(img);
bi = ImageIO.read(bai);
}
}
catch(IIOException exception)
{
readError = true;
}
// 2. try to read jpeg again. some jpegs have some strange header containing
// "Adobe " at some place. so just replace the header with a valid jpeg header.
// TODO : not sure if it works for all cases
if (bi == null && readError)
{
byte[] newImage = replaceHeader(img);
ByteArrayInputStream bai = new ByteArrayInputStream(newImage);
bi = ImageIO.read(bai);
}
// If there is a 'soft mask' or 'mask' image then we use that as a transparency mask.
return applyMasks(bi);
}
| public BufferedImage getRGBImage() throws IOException
{
if (image != null)
{
// use the cached image
return image;
}
BufferedImage bi = null;
boolean readError = false;
ByteArrayOutputStream os = new ByteArrayOutputStream();
removeAllFiltersButDCT(os);
os.close();
byte[] img = os.toByteArray();
PDColorSpace cs = getColorSpace();
try
{
if (cs instanceof PDDeviceCMYK
|| (cs instanceof PDICCBased && cs.getNumberOfComponents() == 4))
{
// JPEGs may contain CMYK, YCbCr or YCCK decoded image data
int transform = getApp14AdobeTransform(img);
// create BufferedImage based on the converted color values
if (transform == 0)
{
bi = convertCMYK2RGB(readImage(img), cs);
}
else if (transform == 1)
{
// TODO YCbCr
}
else if (transform == 2)
{
bi = convertYCCK2RGB(readImage(img));
}
}
else if (cs instanceof PDSeparation)
{
// create BufferedImage based on the converted color values
bi = processTintTransformation(readImage(img),
((PDSeparation)cs).getTintTransform(), cs.getJavaColorSpace());
}
else if (cs instanceof PDDeviceN)
{
// create BufferedImage based on the converted color values
bi = processTintTransformation(readImage(img),
((PDDeviceN)cs).getTintTransform(), cs.getJavaColorSpace());
}
else
{
ByteArrayInputStream bai = new ByteArrayInputStream(img);
bi = ImageIO.read(bai);
}
}
catch(IIOException exception)
{
readError = true;
}
// 2. try to read jpeg again. some jpegs have some strange header containing
// "Adobe " at some place. so just replace the header with a valid jpeg header.
// TODO : not sure if it works for all cases
if (bi == null && readError)
{
byte[] newImage = replaceHeader(img);
ByteArrayInputStream bai = new ByteArrayInputStream(newImage);
bi = ImageIO.read(bai);
}
// If there is a 'soft mask' or 'mask' image then we use that as a transparency mask.
image = applyMasks(bi);
return image;
}
|
diff --git a/core/src/com/google/zxing/qrcode/decoder/DecodedBitStreamParser.java b/core/src/com/google/zxing/qrcode/decoder/DecodedBitStreamParser.java
index f271ac34..e69ca8d5 100644
--- a/core/src/com/google/zxing/qrcode/decoder/DecodedBitStreamParser.java
+++ b/core/src/com/google/zxing/qrcode/decoder/DecodedBitStreamParser.java
@@ -1,235 +1,235 @@
/*
* Copyright 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.qrcode.decoder;
import com.google.zxing.ReaderException;
import java.io.UnsupportedEncodingException;
/**
* <p>QR Codes can encode text as bits in one of several modes, and can use multiple modes
* in one QR Code. This class decodes the bits back into text.</p>
*
* <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p>
*
* @author [email protected] (Sean Owen)
*/
final class DecodedBitStreamParser {
/**
* See ISO 18004:2006, 6.4.4 Table 5
*/
private static final char[] ALPHANUMERIC_CHARS = new char[]{
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
' ', '$', '%', '*', '+', '-', '.', '/', ':'
};
private static final String SHIFT_JIS = "Shift_JIS";
private static final boolean ASSUME_SHIFT_JIS;
private static final String UTF8 = "UTF-8";
private static final String ISO88591 = "ISO-8859-1";
static {
String platformDefault = System.getProperty("file.encoding");
ASSUME_SHIFT_JIS = SHIFT_JIS.equalsIgnoreCase(platformDefault) ||
"EUC-JP".equalsIgnoreCase(platformDefault);
}
private DecodedBitStreamParser() {
}
static String decode(byte[] bytes, Version version) throws ReaderException {
BitSource bits = new BitSource(bytes);
StringBuffer result = new StringBuffer();
Mode mode;
do {
// While still another segment to read...
mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits
if (!mode.equals(Mode.TERMINATOR)) {
// How many characters will follow, encoded in this mode?
int count = bits.readBits(mode.getCharacterCountBits(version));
if (mode.equals(Mode.NUMERIC)) {
decodeNumericSegment(bits, result, count);
} else if (mode.equals(Mode.ALPHANUMERIC)) {
decodeAlphanumericSegment(bits, result, count);
} else if (mode.equals(Mode.BYTE)) {
decodeByteSegment(bits, result, count);
} else if (mode.equals(Mode.KANJI)) {
decodeKanjiSegment(bits, result, count);
} else {
throw new ReaderException("Unsupported mode indicator");
}
}
} while (!mode.equals(Mode.TERMINATOR));
// I thought it wasn't allowed to leave extra bytes after the terminator but it happens
/*
int bitsLeft = bits.available();
if (bitsLeft > 0) {
if (bitsLeft > 6 || bits.readBits(bitsLeft) != 0) {
throw new ReaderException("Excess bits or non-zero bits after terminator mode indicator");
}
}
*/
return result.toString();
}
private static void decodeKanjiSegment(BitSource bits,
StringBuffer result,
int count) throws ReaderException {
// Each character will require 2 bytes. Read the characters as 2-byte pairs
// and decode as Shift_JIS afterwards
byte[] buffer = new byte[2 * count];
int offset = 0;
while (count > 0) {
// Each 13 bits encodes a 2-byte character
int twoBytes = bits.readBits(13);
int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0);
if (assembledTwoBytes < 0x01F00) {
// In the 0x8140 to 0x9FFC range
assembledTwoBytes += 0x08140;
} else {
// In the 0xE040 to 0xEBBF range
assembledTwoBytes += 0x0C140;
}
buffer[offset] = (byte) (assembledTwoBytes >> 8);
buffer[offset + 1] = (byte) assembledTwoBytes;
offset += 2;
count--;
}
// Shift_JIS may not be supported in some environments:
try {
result.append(new String(buffer, SHIFT_JIS));
} catch (UnsupportedEncodingException uee) {
throw new ReaderException(SHIFT_JIS + " encoding is not supported on this device");
}
}
private static void decodeByteSegment(BitSource bits,
StringBuffer result,
int count) throws ReaderException {
byte[] readBytes = new byte[count];
if (count << 3 > bits.available()) {
throw new ReaderException("Count too large: " + count);
}
for (int i = 0; i < count; i++) {
readBytes[i] = (byte) bits.readBits(8);
}
// The spec isn't clear on this mode; see
// section 6.4.5: t does not say which encoding to assuming
// upon decoding. I have seen ISO-8859-1 used as well as
// Shift_JIS -- without anything like an ECI designator to
// give a hint.
String encoding = guessEncoding(readBytes);
try {
result.append(new String(readBytes, encoding));
} catch (UnsupportedEncodingException uce) {
throw new ReaderException(uce.toString());
}
}
private static void decodeAlphanumericSegment(BitSource bits,
StringBuffer result,
int count) {
// Read two characters at a time
while (count > 1) {
int nextTwoCharsBits = bits.readBits(11);
result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits / 45]);
result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits % 45]);
count -= 2;
}
if (count == 1) {
// special case: one character left
result.append(ALPHANUMERIC_CHARS[bits.readBits(6)]);
}
}
private static void decodeNumericSegment(BitSource bits,
StringBuffer result,
int count) throws ReaderException {
// Read three digits at a time
while (count >= 3) {
// Each 10 bits encodes three digits
int threeDigitsBits = bits.readBits(10);
if (threeDigitsBits >= 1000) {
throw new ReaderException("Illegal value for 3-digit unit: " + threeDigitsBits);
}
result.append(ALPHANUMERIC_CHARS[threeDigitsBits / 100]);
result.append(ALPHANUMERIC_CHARS[(threeDigitsBits / 10) % 10]);
result.append(ALPHANUMERIC_CHARS[threeDigitsBits % 10]);
count -= 3;
}
if (count == 2) {
// Two digits left over to read, encoded in 7 bits
int twoDigitsBits = bits.readBits(7);
if (twoDigitsBits >= 100) {
throw new ReaderException("Illegal value for 2-digit unit: " + twoDigitsBits);
}
result.append(ALPHANUMERIC_CHARS[twoDigitsBits / 10]);
result.append(ALPHANUMERIC_CHARS[twoDigitsBits % 10]);
} else if (count == 1) {
// One digit left over to read
int digitBits = bits.readBits(4);
if (digitBits >= 10) {
throw new ReaderException("Illegal value for digit unit: " + digitBits);
}
result.append(ALPHANUMERIC_CHARS[digitBits]);
}
}
private static String guessEncoding(byte[] bytes) {
if (ASSUME_SHIFT_JIS) {
return SHIFT_JIS;
}
// Does it start with the UTF-8 byte order mark? then guess it's UTF-8
if (bytes.length > 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) {
return UTF8;
}
// For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS,
// which should be by far the most common encodings. ISO-8859-1
// should not have bytes in the 0x80 - 0x9F range, while Shift_JIS
// uses this as a first byte of a two-byte character. If we see this
// followed by a valid second byte in Shift_JIS, assume it is Shift_JIS.
// If we see something else in that second byte, we'll make the risky guess
// that it's UTF-8.
int length = bytes.length;
for (int i = 0; i < length; i++) {
int value = bytes[i] & 0xFF;
if (value >= 0x80 && value <= 0x9F && i < length - 1) {
// ISO-8859-1 shouldn't use this, but before we decide it is Shift_JIS,
// just double check that it is followed by a byte that's valid in
// the Shift_JIS encoding
int nextValue = bytes[i + 1] & 0xFF;
if ((value & 0x1) == 0) {
// if even,
- if (nextValue >= 0x9F && nextValue <= 0x7C) {
+ if (nextValue >= 0x9F && nextValue <= 0xFC) {
return SHIFT_JIS;
}
} else {
if (nextValue >= 0x40 && nextValue <= 0x9E) {
return SHIFT_JIS;
}
}
// otherwise we're going to take a guess that it's UTF-8
return UTF8;
}
}
return ISO88591;
}
}
| true | true | private static String guessEncoding(byte[] bytes) {
if (ASSUME_SHIFT_JIS) {
return SHIFT_JIS;
}
// Does it start with the UTF-8 byte order mark? then guess it's UTF-8
if (bytes.length > 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) {
return UTF8;
}
// For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS,
// which should be by far the most common encodings. ISO-8859-1
// should not have bytes in the 0x80 - 0x9F range, while Shift_JIS
// uses this as a first byte of a two-byte character. If we see this
// followed by a valid second byte in Shift_JIS, assume it is Shift_JIS.
// If we see something else in that second byte, we'll make the risky guess
// that it's UTF-8.
int length = bytes.length;
for (int i = 0; i < length; i++) {
int value = bytes[i] & 0xFF;
if (value >= 0x80 && value <= 0x9F && i < length - 1) {
// ISO-8859-1 shouldn't use this, but before we decide it is Shift_JIS,
// just double check that it is followed by a byte that's valid in
// the Shift_JIS encoding
int nextValue = bytes[i + 1] & 0xFF;
if ((value & 0x1) == 0) {
// if even,
if (nextValue >= 0x9F && nextValue <= 0x7C) {
return SHIFT_JIS;
}
} else {
if (nextValue >= 0x40 && nextValue <= 0x9E) {
return SHIFT_JIS;
}
}
// otherwise we're going to take a guess that it's UTF-8
return UTF8;
}
}
return ISO88591;
}
| private static String guessEncoding(byte[] bytes) {
if (ASSUME_SHIFT_JIS) {
return SHIFT_JIS;
}
// Does it start with the UTF-8 byte order mark? then guess it's UTF-8
if (bytes.length > 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) {
return UTF8;
}
// For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS,
// which should be by far the most common encodings. ISO-8859-1
// should not have bytes in the 0x80 - 0x9F range, while Shift_JIS
// uses this as a first byte of a two-byte character. If we see this
// followed by a valid second byte in Shift_JIS, assume it is Shift_JIS.
// If we see something else in that second byte, we'll make the risky guess
// that it's UTF-8.
int length = bytes.length;
for (int i = 0; i < length; i++) {
int value = bytes[i] & 0xFF;
if (value >= 0x80 && value <= 0x9F && i < length - 1) {
// ISO-8859-1 shouldn't use this, but before we decide it is Shift_JIS,
// just double check that it is followed by a byte that's valid in
// the Shift_JIS encoding
int nextValue = bytes[i + 1] & 0xFF;
if ((value & 0x1) == 0) {
// if even,
if (nextValue >= 0x9F && nextValue <= 0xFC) {
return SHIFT_JIS;
}
} else {
if (nextValue >= 0x40 && nextValue <= 0x9E) {
return SHIFT_JIS;
}
}
// otherwise we're going to take a guess that it's UTF-8
return UTF8;
}
}
return ISO88591;
}
|
diff --git a/src/org/mozilla/javascript/optimizer/Optimizer.java b/src/org/mozilla/javascript/optimizer/Optimizer.java
index 55294307..746bd0dd 100644
--- a/src/org/mozilla/javascript/optimizer/Optimizer.java
+++ b/src/org/mozilla/javascript/optimizer/Optimizer.java
@@ -1,507 +1,510 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Norris Boyd
* Roger Lawrence
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript.optimizer;
import org.mozilla.javascript.*;
import org.mozilla.javascript.ast.ScriptNode;
class Optimizer
{
static final int NoType = 0;
static final int NumberType = 1;
static final int AnyType = 3;
// It is assumed that (NumberType | AnyType) == AnyType
void optimize(ScriptNode scriptOrFn)
{
// run on one function at a time for now
int functionCount = scriptOrFn.getFunctionCount();
for (int i = 0; i != functionCount; ++i) {
OptFunctionNode f = OptFunctionNode.get(scriptOrFn, i);
optimizeFunction(f);
}
}
private void optimizeFunction(OptFunctionNode theFunction)
{
if (theFunction.fnode.requiresActivation()) return;
inDirectCallFunction = theFunction.isTargetOfDirectCall();
this.theFunction = theFunction;
ObjArray statementsArray = new ObjArray();
buildStatementList_r(theFunction.fnode, statementsArray);
Node[] theStatementNodes = new Node[statementsArray.size()];
statementsArray.toArray(theStatementNodes);
Block.runFlowAnalyzes(theFunction, theStatementNodes);
if (!theFunction.fnode.requiresActivation()) {
/*
* Now that we know which local vars are in fact always
* Numbers, we re-write the tree to take advantage of
* that. Any arithmetic or assignment op involving just
* Number typed vars is marked so that the codegen will
* generate non-object code.
*/
parameterUsedInNumberContext = false;
for (int i = 0; i < theStatementNodes.length; i++) {
rewriteForNumberVariables(theStatementNodes[i], NumberType);
}
theFunction.setParameterNumberContext(parameterUsedInNumberContext);
}
}
/*
Each directCall parameter is passed as a pair of values - an object
and a double. The value passed depends on the type of value available at
the call site. If a double is available, the object in java/lang/Void.TYPE
is passed as the object value, and if an object value is available, then
0.0 is passed as the double value.
The receiving routine always tests the object value before proceeding.
If the parameter is being accessed in a 'Number Context' then the code
sequence is :
if ("parameter_objectValue" == java/lang/Void.TYPE)
...fine..., use the parameter_doubleValue
else
toNumber(parameter_objectValue)
and if the parameter is being referenced in an Object context, the code is
if ("parameter_objectValue" == java/lang/Void.TYPE)
new Double(parameter_doubleValue)
else
...fine..., use the parameter_objectValue
If the receiving code never uses the doubleValue, it is converted on
entry to a Double instead.
*/
/*
We're referencing a node in a Number context (i.e. we'd prefer it
was a double value). If the node is a parameter in a directCall
function, mark it as being referenced in this context.
*/
private void markDCPNumberContext(Node n)
{
if (inDirectCallFunction && n.getType() == Token.GETVAR) {
int varIndex = theFunction.getVarIndex(n);
if (theFunction.isParameter(varIndex)) {
parameterUsedInNumberContext = true;
}
}
}
private boolean convertParameter(Node n)
{
if (inDirectCallFunction && n.getType() == Token.GETVAR) {
int varIndex = theFunction.getVarIndex(n);
if (theFunction.isParameter(varIndex)) {
n.removeProp(Node.ISNUMBER_PROP);
return true;
}
}
return false;
}
private int rewriteForNumberVariables(Node n, int desired)
{
switch (n.getType()) {
case Token.EXPR_VOID : {
Node child = n.getFirstChild();
int type = rewriteForNumberVariables(child, NumberType);
if (type == NumberType)
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NoType;
}
case Token.NUMBER :
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
case Token.GETVAR :
{
int varIndex = theFunction.getVarIndex(n);
if (inDirectCallFunction
&& theFunction.isParameter(varIndex)
&& desired == NumberType)
{
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
else if (theFunction.isNumberVar(varIndex)) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
return NoType;
}
case Token.INC :
case Token.DEC : {
Node child = n.getFirstChild();
// "child" will be GETVAR or GETPROP or GETELEM
if (child.getType() == Token.GETVAR) {
- if (rewriteForNumberVariables(child, NumberType) == NumberType) {
+ ;
+ if (rewriteForNumberVariables(child, NumberType) == NumberType &&
+ !convertParameter(child))
+ {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
markDCPNumberContext(child);
return NumberType;
}
return NoType;
}
else if (child.getType() == Token.GETELEM) {
return rewriteForNumberVariables(child, NumberType);
}
return NoType;
}
case Token.SETVAR : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int rType = rewriteForNumberVariables(rChild, NumberType);
int varIndex = theFunction.getVarIndex(n);
if (inDirectCallFunction
&& theFunction.isParameter(varIndex))
{
if (rType == NumberType) {
if (!convertParameter(rChild)) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
markDCPNumberContext(rChild);
return NoType;
}
else
return rType;
}
else if (theFunction.isNumberVar(varIndex)) {
if (rType != NumberType) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_DOUBLE, rChild));
}
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
markDCPNumberContext(rChild);
return NumberType;
}
else {
if (rType == NumberType) {
if (!convertParameter(rChild)) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_OBJECT, rChild));
}
}
return NoType;
}
}
case Token.LE :
case Token.LT :
case Token.GE :
case Token.GT : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int lType = rewriteForNumberVariables(lChild, NumberType);
int rType = rewriteForNumberVariables(rChild, NumberType);
markDCPNumberContext(lChild);
markDCPNumberContext(rChild);
if (convertParameter(lChild)) {
if (convertParameter(rChild)) {
return NoType;
} else if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
else if (convertParameter(rChild)) {
if (lType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (lType == NumberType) {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
}
else {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
}
// we actually build a boolean value
return NoType;
}
case Token.ADD : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int lType = rewriteForNumberVariables(lChild, NumberType);
int rType = rewriteForNumberVariables(rChild, NumberType);
if (convertParameter(lChild)) {
if (convertParameter(rChild)) {
return NoType;
}
else {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
}
else {
if (convertParameter(rChild)) {
if (lType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (lType == NumberType) {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
else {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP,
Node.RIGHT);
}
}
}
}
return NoType;
}
case Token.BITXOR :
case Token.BITOR :
case Token.BITAND :
case Token.RSH :
case Token.LSH :
case Token.SUB :
case Token.MUL :
case Token.DIV :
case Token.MOD : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int lType = rewriteForNumberVariables(lChild, NumberType);
int rType = rewriteForNumberVariables(rChild, NumberType);
markDCPNumberContext(lChild);
markDCPNumberContext(rChild);
if (lType == NumberType) {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
else {
if (!convertParameter(rChild)) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_DOUBLE, rChild));
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
}
return NumberType;
}
}
else {
if (rType == NumberType) {
if (!convertParameter(lChild)) {
n.removeChild(lChild);
n.addChildToFront(
new Node(Token.TO_DOUBLE, lChild));
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
}
return NumberType;
}
else {
if (!convertParameter(lChild)) {
n.removeChild(lChild);
n.addChildToFront(
new Node(Token.TO_DOUBLE, lChild));
}
if (!convertParameter(rChild)) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_DOUBLE, rChild));
}
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
}
}
case Token.SETELEM :
case Token.SETELEM_OP : {
Node arrayBase = n.getFirstChild();
Node arrayIndex = arrayBase.getNext();
Node rValue = arrayIndex.getNext();
int baseType = rewriteForNumberVariables(arrayBase, NumberType);
if (baseType == NumberType) {// can never happen ???
if (!convertParameter(arrayBase)) {
n.removeChild(arrayBase);
n.addChildToFront(
new Node(Token.TO_OBJECT, arrayBase));
}
}
int indexType = rewriteForNumberVariables(arrayIndex, NumberType);
if (indexType == NumberType) {
if (!convertParameter(arrayIndex)) {
// setting the ISNUMBER_PROP signals the codegen
// to use the OptRuntime.setObjectIndex that takes
// a double index
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
int rValueType = rewriteForNumberVariables(rValue, NumberType);
if (rValueType == NumberType) {
if (!convertParameter(rValue)) {
n.removeChild(rValue);
n.addChildToBack(
new Node(Token.TO_OBJECT, rValue));
}
}
return NoType;
}
case Token.GETELEM : {
Node arrayBase = n.getFirstChild();
Node arrayIndex = arrayBase.getNext();
int baseType = rewriteForNumberVariables(arrayBase, NumberType);
if (baseType == NumberType) {// can never happen ???
if (!convertParameter(arrayBase)) {
n.removeChild(arrayBase);
n.addChildToFront(
new Node(Token.TO_OBJECT, arrayBase));
}
}
int indexType = rewriteForNumberVariables(arrayIndex, NumberType);
if (indexType == NumberType) {
if (!convertParameter(arrayIndex)) {
// setting the ISNUMBER_PROP signals the codegen
// to use the OptRuntime.getObjectIndex that takes
// a double index
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
return NoType;
}
case Token.CALL :
{
Node child = n.getFirstChild(); // the function node
// must be an object
rewriteAsObjectChildren(child, child.getFirstChild());
child = child.getNext(); // the first arg
OptFunctionNode target
= (OptFunctionNode)n.getProp(Node.DIRECTCALL_PROP);
if (target != null) {
/*
we leave each child as a Number if it can be. The codegen will
handle moving the pairs of parameters.
*/
while (child != null) {
int type = rewriteForNumberVariables(child, NumberType);
if (type == NumberType) {
markDCPNumberContext(child);
}
child = child.getNext();
}
} else {
rewriteAsObjectChildren(n, child);
}
return NoType;
}
default : {
rewriteAsObjectChildren(n, n.getFirstChild());
return NoType;
}
}
}
private void rewriteAsObjectChildren(Node n, Node child)
{
// Force optimized children to be objects
while (child != null) {
Node nextChild = child.getNext();
int type = rewriteForNumberVariables(child, NoType);
if (type == NumberType) {
if (!convertParameter(child)) {
n.removeChild(child);
Node nuChild = new Node(Token.TO_OBJECT, child);
if (nextChild == null)
n.addChildToBack(nuChild);
else
n.addChildBefore(nuChild, nextChild);
}
}
child = nextChild;
}
}
private static void buildStatementList_r(Node node, ObjArray statements)
{
int type = node.getType();
if (type == Token.BLOCK
|| type == Token.LOCAL_BLOCK
|| type == Token.LOOP
|| type == Token.FUNCTION)
{
Node child = node.getFirstChild();
while (child != null) {
buildStatementList_r(child, statements);
child = child.getNext();
}
} else {
statements.add(node);
}
}
private boolean inDirectCallFunction;
OptFunctionNode theFunction;
private boolean parameterUsedInNumberContext;
}
| true | true | private int rewriteForNumberVariables(Node n, int desired)
{
switch (n.getType()) {
case Token.EXPR_VOID : {
Node child = n.getFirstChild();
int type = rewriteForNumberVariables(child, NumberType);
if (type == NumberType)
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NoType;
}
case Token.NUMBER :
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
case Token.GETVAR :
{
int varIndex = theFunction.getVarIndex(n);
if (inDirectCallFunction
&& theFunction.isParameter(varIndex)
&& desired == NumberType)
{
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
else if (theFunction.isNumberVar(varIndex)) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
return NoType;
}
case Token.INC :
case Token.DEC : {
Node child = n.getFirstChild();
// "child" will be GETVAR or GETPROP or GETELEM
if (child.getType() == Token.GETVAR) {
if (rewriteForNumberVariables(child, NumberType) == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
markDCPNumberContext(child);
return NumberType;
}
return NoType;
}
else if (child.getType() == Token.GETELEM) {
return rewriteForNumberVariables(child, NumberType);
}
return NoType;
}
case Token.SETVAR : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int rType = rewriteForNumberVariables(rChild, NumberType);
int varIndex = theFunction.getVarIndex(n);
if (inDirectCallFunction
&& theFunction.isParameter(varIndex))
{
if (rType == NumberType) {
if (!convertParameter(rChild)) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
markDCPNumberContext(rChild);
return NoType;
}
else
return rType;
}
else if (theFunction.isNumberVar(varIndex)) {
if (rType != NumberType) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_DOUBLE, rChild));
}
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
markDCPNumberContext(rChild);
return NumberType;
}
else {
if (rType == NumberType) {
if (!convertParameter(rChild)) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_OBJECT, rChild));
}
}
return NoType;
}
}
case Token.LE :
case Token.LT :
case Token.GE :
case Token.GT : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int lType = rewriteForNumberVariables(lChild, NumberType);
int rType = rewriteForNumberVariables(rChild, NumberType);
markDCPNumberContext(lChild);
markDCPNumberContext(rChild);
if (convertParameter(lChild)) {
if (convertParameter(rChild)) {
return NoType;
} else if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
else if (convertParameter(rChild)) {
if (lType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (lType == NumberType) {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
}
else {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
}
// we actually build a boolean value
return NoType;
}
case Token.ADD : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int lType = rewriteForNumberVariables(lChild, NumberType);
int rType = rewriteForNumberVariables(rChild, NumberType);
if (convertParameter(lChild)) {
if (convertParameter(rChild)) {
return NoType;
}
else {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
}
else {
if (convertParameter(rChild)) {
if (lType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (lType == NumberType) {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
else {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP,
Node.RIGHT);
}
}
}
}
return NoType;
}
case Token.BITXOR :
case Token.BITOR :
case Token.BITAND :
case Token.RSH :
case Token.LSH :
case Token.SUB :
case Token.MUL :
case Token.DIV :
case Token.MOD : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int lType = rewriteForNumberVariables(lChild, NumberType);
int rType = rewriteForNumberVariables(rChild, NumberType);
markDCPNumberContext(lChild);
markDCPNumberContext(rChild);
if (lType == NumberType) {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
else {
if (!convertParameter(rChild)) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_DOUBLE, rChild));
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
}
return NumberType;
}
}
else {
if (rType == NumberType) {
if (!convertParameter(lChild)) {
n.removeChild(lChild);
n.addChildToFront(
new Node(Token.TO_DOUBLE, lChild));
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
}
return NumberType;
}
else {
if (!convertParameter(lChild)) {
n.removeChild(lChild);
n.addChildToFront(
new Node(Token.TO_DOUBLE, lChild));
}
if (!convertParameter(rChild)) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_DOUBLE, rChild));
}
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
}
}
case Token.SETELEM :
case Token.SETELEM_OP : {
Node arrayBase = n.getFirstChild();
Node arrayIndex = arrayBase.getNext();
Node rValue = arrayIndex.getNext();
int baseType = rewriteForNumberVariables(arrayBase, NumberType);
if (baseType == NumberType) {// can never happen ???
if (!convertParameter(arrayBase)) {
n.removeChild(arrayBase);
n.addChildToFront(
new Node(Token.TO_OBJECT, arrayBase));
}
}
int indexType = rewriteForNumberVariables(arrayIndex, NumberType);
if (indexType == NumberType) {
if (!convertParameter(arrayIndex)) {
// setting the ISNUMBER_PROP signals the codegen
// to use the OptRuntime.setObjectIndex that takes
// a double index
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
int rValueType = rewriteForNumberVariables(rValue, NumberType);
if (rValueType == NumberType) {
if (!convertParameter(rValue)) {
n.removeChild(rValue);
n.addChildToBack(
new Node(Token.TO_OBJECT, rValue));
}
}
return NoType;
}
case Token.GETELEM : {
Node arrayBase = n.getFirstChild();
Node arrayIndex = arrayBase.getNext();
int baseType = rewriteForNumberVariables(arrayBase, NumberType);
if (baseType == NumberType) {// can never happen ???
if (!convertParameter(arrayBase)) {
n.removeChild(arrayBase);
n.addChildToFront(
new Node(Token.TO_OBJECT, arrayBase));
}
}
int indexType = rewriteForNumberVariables(arrayIndex, NumberType);
if (indexType == NumberType) {
if (!convertParameter(arrayIndex)) {
// setting the ISNUMBER_PROP signals the codegen
// to use the OptRuntime.getObjectIndex that takes
// a double index
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
return NoType;
}
case Token.CALL :
{
Node child = n.getFirstChild(); // the function node
// must be an object
rewriteAsObjectChildren(child, child.getFirstChild());
child = child.getNext(); // the first arg
OptFunctionNode target
= (OptFunctionNode)n.getProp(Node.DIRECTCALL_PROP);
if (target != null) {
/*
we leave each child as a Number if it can be. The codegen will
handle moving the pairs of parameters.
*/
while (child != null) {
int type = rewriteForNumberVariables(child, NumberType);
if (type == NumberType) {
markDCPNumberContext(child);
}
child = child.getNext();
}
} else {
rewriteAsObjectChildren(n, child);
}
return NoType;
}
default : {
rewriteAsObjectChildren(n, n.getFirstChild());
return NoType;
}
}
}
| private int rewriteForNumberVariables(Node n, int desired)
{
switch (n.getType()) {
case Token.EXPR_VOID : {
Node child = n.getFirstChild();
int type = rewriteForNumberVariables(child, NumberType);
if (type == NumberType)
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NoType;
}
case Token.NUMBER :
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
case Token.GETVAR :
{
int varIndex = theFunction.getVarIndex(n);
if (inDirectCallFunction
&& theFunction.isParameter(varIndex)
&& desired == NumberType)
{
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
else if (theFunction.isNumberVar(varIndex)) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
return NoType;
}
case Token.INC :
case Token.DEC : {
Node child = n.getFirstChild();
// "child" will be GETVAR or GETPROP or GETELEM
if (child.getType() == Token.GETVAR) {
;
if (rewriteForNumberVariables(child, NumberType) == NumberType &&
!convertParameter(child))
{
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
markDCPNumberContext(child);
return NumberType;
}
return NoType;
}
else if (child.getType() == Token.GETELEM) {
return rewriteForNumberVariables(child, NumberType);
}
return NoType;
}
case Token.SETVAR : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int rType = rewriteForNumberVariables(rChild, NumberType);
int varIndex = theFunction.getVarIndex(n);
if (inDirectCallFunction
&& theFunction.isParameter(varIndex))
{
if (rType == NumberType) {
if (!convertParameter(rChild)) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
markDCPNumberContext(rChild);
return NoType;
}
else
return rType;
}
else if (theFunction.isNumberVar(varIndex)) {
if (rType != NumberType) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_DOUBLE, rChild));
}
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
markDCPNumberContext(rChild);
return NumberType;
}
else {
if (rType == NumberType) {
if (!convertParameter(rChild)) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_OBJECT, rChild));
}
}
return NoType;
}
}
case Token.LE :
case Token.LT :
case Token.GE :
case Token.GT : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int lType = rewriteForNumberVariables(lChild, NumberType);
int rType = rewriteForNumberVariables(rChild, NumberType);
markDCPNumberContext(lChild);
markDCPNumberContext(rChild);
if (convertParameter(lChild)) {
if (convertParameter(rChild)) {
return NoType;
} else if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
else if (convertParameter(rChild)) {
if (lType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (lType == NumberType) {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
}
else {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
}
// we actually build a boolean value
return NoType;
}
case Token.ADD : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int lType = rewriteForNumberVariables(lChild, NumberType);
int rType = rewriteForNumberVariables(rChild, NumberType);
if (convertParameter(lChild)) {
if (convertParameter(rChild)) {
return NoType;
}
else {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
}
else {
if (convertParameter(rChild)) {
if (lType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (lType == NumberType) {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
else {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP,
Node.RIGHT);
}
}
}
}
return NoType;
}
case Token.BITXOR :
case Token.BITOR :
case Token.BITAND :
case Token.RSH :
case Token.LSH :
case Token.SUB :
case Token.MUL :
case Token.DIV :
case Token.MOD : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int lType = rewriteForNumberVariables(lChild, NumberType);
int rType = rewriteForNumberVariables(rChild, NumberType);
markDCPNumberContext(lChild);
markDCPNumberContext(rChild);
if (lType == NumberType) {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
else {
if (!convertParameter(rChild)) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_DOUBLE, rChild));
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
}
return NumberType;
}
}
else {
if (rType == NumberType) {
if (!convertParameter(lChild)) {
n.removeChild(lChild);
n.addChildToFront(
new Node(Token.TO_DOUBLE, lChild));
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
}
return NumberType;
}
else {
if (!convertParameter(lChild)) {
n.removeChild(lChild);
n.addChildToFront(
new Node(Token.TO_DOUBLE, lChild));
}
if (!convertParameter(rChild)) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_DOUBLE, rChild));
}
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
}
}
case Token.SETELEM :
case Token.SETELEM_OP : {
Node arrayBase = n.getFirstChild();
Node arrayIndex = arrayBase.getNext();
Node rValue = arrayIndex.getNext();
int baseType = rewriteForNumberVariables(arrayBase, NumberType);
if (baseType == NumberType) {// can never happen ???
if (!convertParameter(arrayBase)) {
n.removeChild(arrayBase);
n.addChildToFront(
new Node(Token.TO_OBJECT, arrayBase));
}
}
int indexType = rewriteForNumberVariables(arrayIndex, NumberType);
if (indexType == NumberType) {
if (!convertParameter(arrayIndex)) {
// setting the ISNUMBER_PROP signals the codegen
// to use the OptRuntime.setObjectIndex that takes
// a double index
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
int rValueType = rewriteForNumberVariables(rValue, NumberType);
if (rValueType == NumberType) {
if (!convertParameter(rValue)) {
n.removeChild(rValue);
n.addChildToBack(
new Node(Token.TO_OBJECT, rValue));
}
}
return NoType;
}
case Token.GETELEM : {
Node arrayBase = n.getFirstChild();
Node arrayIndex = arrayBase.getNext();
int baseType = rewriteForNumberVariables(arrayBase, NumberType);
if (baseType == NumberType) {// can never happen ???
if (!convertParameter(arrayBase)) {
n.removeChild(arrayBase);
n.addChildToFront(
new Node(Token.TO_OBJECT, arrayBase));
}
}
int indexType = rewriteForNumberVariables(arrayIndex, NumberType);
if (indexType == NumberType) {
if (!convertParameter(arrayIndex)) {
// setting the ISNUMBER_PROP signals the codegen
// to use the OptRuntime.getObjectIndex that takes
// a double index
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
return NoType;
}
case Token.CALL :
{
Node child = n.getFirstChild(); // the function node
// must be an object
rewriteAsObjectChildren(child, child.getFirstChild());
child = child.getNext(); // the first arg
OptFunctionNode target
= (OptFunctionNode)n.getProp(Node.DIRECTCALL_PROP);
if (target != null) {
/*
we leave each child as a Number if it can be. The codegen will
handle moving the pairs of parameters.
*/
while (child != null) {
int type = rewriteForNumberVariables(child, NumberType);
if (type == NumberType) {
markDCPNumberContext(child);
}
child = child.getNext();
}
} else {
rewriteAsObjectChildren(n, child);
}
return NoType;
}
default : {
rewriteAsObjectChildren(n, n.getFirstChild());
return NoType;
}
}
}
|
diff --git a/public/java/src/org/broadinstitute/sting/gatk/walkers/annotator/VariantAnnotator.java b/public/java/src/org/broadinstitute/sting/gatk/walkers/annotator/VariantAnnotator.java
index 20e72dd57..c9ea7a3b5 100755
--- a/public/java/src/org/broadinstitute/sting/gatk/walkers/annotator/VariantAnnotator.java
+++ b/public/java/src/org/broadinstitute/sting/gatk/walkers/annotator/VariantAnnotator.java
@@ -1,362 +1,366 @@
/*
* Copyright (c) 2010 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.broadinstitute.sting.gatk.walkers.annotator;
import org.broadinstitute.sting.commandline.*;
import org.broadinstitute.sting.gatk.arguments.DbsnpArgumentCollection;
import org.broadinstitute.sting.gatk.arguments.StandardVariantContextInputArgumentCollection;
import org.broadinstitute.sting.gatk.contexts.AlignmentContext;
import org.broadinstitute.sting.gatk.contexts.AlignmentContextUtils;
import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker;
import org.broadinstitute.sting.gatk.walkers.*;
import org.broadinstitute.sting.gatk.walkers.annotator.interfaces.*;
import org.broadinstitute.sting.utils.BaseUtils;
import org.broadinstitute.sting.utils.SampleUtils;
import org.broadinstitute.sting.utils.classloader.PluginManager;
import org.broadinstitute.sting.utils.codecs.vcf.*;
import org.broadinstitute.sting.utils.variantcontext.VariantContext;
import org.broadinstitute.sting.utils.variantcontext.VariantContextUtils;
import java.util.*;
/**
* Annotates variant calls with context information.
*
* <p>
* VariantAnnotator is a GATK tool for annotating variant calls based on their context.
* The tool is modular; new annotations can be written easily without modifying VariantAnnotator itself.
*
* <h2>Input</h2>
* <p>
* A variant set to annotate and optionally one or more BAM files.
* </p>
*
* <h2>Output</h2>
* <p>
* An annotated VCF.
* </p>
*
* <h2>Examples</h2>
* <pre>
* java -Xmx2g -jar GenomeAnalysisTK.jar \
* -R ref.fasta \
* -T VariantAnnotator \
* -I input.bam \
* -o output.vcf \
* -A DepthOfCoverage \
* --variant input.vcf \
* -L input.vcf \
* --dbsnp dbsnp.vcf
* </pre>
*
*/
@Requires(value={})
@Allows(value={DataSource.READS, DataSource.REFERENCE})
@Reference(window=@Window(start=-50,stop=50))
@By(DataSource.REFERENCE)
public class VariantAnnotator extends RodWalker<Integer, Integer> implements AnnotatorCompatibleWalker {
@ArgumentCollection
protected StandardVariantContextInputArgumentCollection variantCollection = new StandardVariantContextInputArgumentCollection();
public RodBinding<VariantContext> getVariantRodBinding() { return variantCollection.variants; }
/**
* The INFO field will be annotated with information on the most biologically-significant effect
* listed in the SnpEff output file for each variant.
*/
@Input(fullName="snpEffFile", shortName = "snpEffFile", doc="A SnpEff output file from which to add annotations", required=false)
public RodBinding<VariantContext> snpEffFile;
public RodBinding<VariantContext> getSnpEffRodBinding() { return snpEffFile; }
/**
* rsIDs from this file are used to populate the ID column of the output. Also, the DB INFO flag will be set when appropriate.
*/
@ArgumentCollection
protected DbsnpArgumentCollection dbsnp = new DbsnpArgumentCollection();
public RodBinding<VariantContext> getDbsnpRodBinding() { return dbsnp.dbsnp; }
/**
* If a record in the 'variant' track overlaps with a record from the provided comp track, the INFO field will be annotated
* as such in the output with the track name (e.g. -comp:FOO will have 'FOO' in the INFO field). Records that are filtered in the comp track will be ignored.
* Note that 'dbSNP' has been special-cased (see the --dbsnp argument).
*/
@Input(fullName="comp", shortName = "comp", doc="comparison VCF file", required=false)
public List<RodBinding<VariantContext>> comps = Collections.emptyList();
public List<RodBinding<VariantContext>> getCompRodBindings() { return comps; }
/**
* An external resource VCF file or files from which to annotate.
*
* One can add annotations from one of the resource VCFs to the output.
* For example, if you want to annotate your 'variant' VCF with the AC field value from the rod bound to 'resource',
* you can specify '-E resource.AC' and records in the output VCF will be annotated with 'resource.AC=N' when a record exists in that rod at the given position.
* If multiple records in the rod overlap the given position, one is chosen arbitrarily.
*/
@Input(fullName="resource", shortName = "resource", doc="external resource VCF file", required=false)
public List<RodBinding<VariantContext>> resources = Collections.emptyList();
public List<RodBinding<VariantContext>> getResourceRodBindings() { return resources; }
@Output(doc="File to which variants should be written",required=true)
protected VCFWriter vcfWriter = null;
/**
* See the -list argument to view available annotations.
*/
@Argument(fullName="annotation", shortName="A", doc="One or more specific annotations to apply to variant calls", required=false)
protected List<String> annotationsToUse = new ArrayList<String>();
/**
* Note that this argument has higher priority than the -A or -G arguments,
* so annotations will be excluded even if they are explicitly included with the other options.
*/
@Argument(fullName="excludeAnnotation", shortName="XA", doc="One or more specific annotations to exclude", required=false)
protected List<String> annotationsToExclude = new ArrayList<String>();
/**
* See the -list argument to view available groups.
*/
@Argument(fullName="group", shortName="G", doc="One or more classes/groups of annotations to apply to variant calls", required=false)
protected List<String> annotationGroupsToUse = new ArrayList<String>();
/**
* This option enables you to add annotations from one VCF to another.
*
* For example, if you want to annotate your 'variant' VCF with the AC field value from the rod bound to 'resource',
* you can specify '-E resource.AC' and records in the output VCF will be annotated with 'resource.AC=N' when a record exists in that rod at the given position.
* If multiple records in the rod overlap the given position, one is chosen arbitrarily.
*/
@Argument(fullName="expression", shortName="E", doc="One or more specific expressions to apply to variant calls; see documentation for more details", required=false)
protected List<String> expressionsToUse = new ArrayList<String>();
/**
* Note that the -XL argument can be used along with this one to exclude annotations.
*/
@Argument(fullName="useAllAnnotations", shortName="all", doc="Use all possible annotations (not for the faint of heart)", required=false)
protected Boolean USE_ALL_ANNOTATIONS = false;
@Argument(fullName="list", shortName="ls", doc="List the available annotations and exit")
protected Boolean LIST = false;
@Hidden
@Argument(fullName="vcfContainsOnlyIndels", shortName="dels",doc="Use if you are annotating an indel vcf, currently VERY experimental", required = false)
protected boolean indelsOnly = false;
@Argument(fullName="family_string",shortName="family",required=false,doc="A family string of the form mom+dad=child for use with the mendelian violation ratio annotation")
public String familyStr = null;
@Argument(fullName="MendelViolationGenotypeQualityThreshold",shortName="mvq",required=false,doc="The genotype quality treshold in order to annotate mendelian violation ratio")
public double minGenotypeQualityP = 0.0;
private VariantAnnotatorEngine engine;
private Collection<VariantContext> indelBufferContext;
private void listAnnotationsAndExit() {
System.out.println("\nStandard annotations in the list below are marked with a '*'.");
List<Class<? extends InfoFieldAnnotation>> infoAnnotationClasses = new PluginManager<InfoFieldAnnotation>(InfoFieldAnnotation.class).getPlugins();
System.out.println("\nAvailable annotations for the VCF INFO field:");
for (int i = 0; i < infoAnnotationClasses.size(); i++)
System.out.println("\t" + (StandardAnnotation.class.isAssignableFrom(infoAnnotationClasses.get(i)) ? "*" : "") + infoAnnotationClasses.get(i).getSimpleName());
System.out.println();
List<Class<? extends GenotypeAnnotation>> genotypeAnnotationClasses = new PluginManager<GenotypeAnnotation>(GenotypeAnnotation.class).getPlugins();
System.out.println("\nAvailable annotations for the VCF FORMAT field:");
for (int i = 0; i < genotypeAnnotationClasses.size(); i++)
System.out.println("\t" + (StandardAnnotation.class.isAssignableFrom(genotypeAnnotationClasses.get(i)) ? "*" : "") + genotypeAnnotationClasses.get(i).getSimpleName());
System.out.println();
System.out.println("\nAvailable classes/groups of annotations:");
for ( Class c : new PluginManager<AnnotationType>(AnnotationType.class).getInterfaces() )
System.out.println("\t" + c.getSimpleName());
System.out.println();
System.exit(0);
}
/**
* Prepare the output file and the list of available features.
*/
public void initialize() {
if ( LIST )
listAnnotationsAndExit();
// get the list of all sample names from the variant VCF input rod, if applicable
List<String> rodName = Arrays.asList(variantCollection.variants.getName());
Set<String> samples = SampleUtils.getUniqueSamplesFromRods(getToolkit(), rodName);
if ( USE_ALL_ANNOTATIONS )
engine = new VariantAnnotatorEngine(annotationsToExclude, this, getToolkit());
else
engine = new VariantAnnotatorEngine(annotationGroupsToUse, annotationsToUse, annotationsToExclude, this, getToolkit());
engine.initializeExpressions(expressionsToUse);
// setup the header fields
// note that if any of the definitions conflict with our new ones, then we want to overwrite the old ones
Set<VCFHeaderLine> hInfo = new HashSet<VCFHeaderLine>();
hInfo.addAll(engine.getVCFAnnotationDescriptions());
for ( VCFHeaderLine line : VCFUtils.getHeaderFields(getToolkit(), Arrays.asList(variantCollection.variants.getName())) ) {
if ( isUniqueHeaderLine(line, hInfo) )
hInfo.add(line);
}
// for the expressions, pull the info header line from the header of the resource rod
for ( VariantAnnotatorEngine.VAExpression expression : engine.getRequestedExpressions() ) {
// special case the ID field
if ( expression.fieldName.equals("ID") ) {
hInfo.add(new VCFInfoHeaderLine(expression.fullName, 1, VCFHeaderLineType.String, "ID field transferred from external VCF resource"));
continue;
}
VCFInfoHeaderLine targetHeaderLine = null;
for ( VCFHeaderLine line : VCFUtils.getHeaderFields(getToolkit(), Arrays.asList(expression.binding.getName())) ) {
if ( line instanceof VCFInfoHeaderLine ) {
VCFInfoHeaderLine infoline = (VCFInfoHeaderLine)line;
if ( infoline.getName().equals(expression.fieldName) ) {
targetHeaderLine = infoline;
break;
}
}
}
- if ( targetHeaderLine != null )
- hInfo.add(new VCFInfoHeaderLine(expression.fullName, targetHeaderLine.getCountType(), targetHeaderLine.getType(), targetHeaderLine.getDescription()));
- else
+ if ( targetHeaderLine != null ) {
+ if ( targetHeaderLine.getCountType() == VCFHeaderLineCount.INTEGER )
+ hInfo.add(new VCFInfoHeaderLine(expression.fullName, targetHeaderLine.getCount(), targetHeaderLine.getType(), targetHeaderLine.getDescription()));
+ else
+ hInfo.add(new VCFInfoHeaderLine(expression.fullName, targetHeaderLine.getCountType(), targetHeaderLine.getType(), targetHeaderLine.getDescription()));
+ } else {
hInfo.add(new VCFInfoHeaderLine(expression.fullName, VCFHeaderLineCount.UNBOUNDED, VCFHeaderLineType.String, "Value transferred from another external VCF resource"));
+ }
}
engine.invokeAnnotationInitializationMethods(hInfo);
VCFHeader vcfHeader = new VCFHeader(hInfo, samples);
vcfWriter.writeHeader(vcfHeader);
if ( indelsOnly ) {
indelBufferContext = null;
}
}
public static boolean isUniqueHeaderLine(VCFHeaderLine line, Set<VCFHeaderLine> currentSet) {
if ( !(line instanceof VCFCompoundHeaderLine) )
return true;
for ( VCFHeaderLine hLine : currentSet ) {
if ( hLine instanceof VCFCompoundHeaderLine && ((VCFCompoundHeaderLine)line).sameLineTypeAndName((VCFCompoundHeaderLine)hLine) )
return false;
}
return true;
}
/**
* Initialize the number of loci processed to zero.
*
* @return 0
*/
public Integer reduceInit() { return 0; }
/**
* We want reads that span deletions
*
* @return true
*/
public boolean includeReadsWithDeletionAtLoci() { return true; }
/**
* We want to see extended events if annotating indels
*
* @return true
*/
public boolean generateExtendedEvents() { return indelsOnly; }
/**
* For each site of interest, annotate based on the requested annotation types
*
* @param tracker the meta-data tracker
* @param ref the reference base
* @param context the context for the given locus
* @return 1 if the locus was successfully processed, 0 if otherwise
*/
public Integer map(RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) {
if ( tracker == null )
return 0;
Collection<VariantContext> VCs = tracker.getValues(variantCollection.variants, context.getLocation());
if ( VCs.size() == 0 )
return 0;
Collection<VariantContext> annotatedVCs = VCs;
// if the reference base is not ambiguous, we can annotate
Map<String, AlignmentContext> stratifiedContexts;
if ( BaseUtils.simpleBaseToBaseIndex(ref.getBase()) != -1 ) {
if ( ! context.hasExtendedEventPileup() ) {
stratifiedContexts = AlignmentContextUtils.splitContextBySampleName(context.getBasePileup());
} else {
stratifiedContexts = AlignmentContextUtils.splitContextBySampleName(context.getExtendedEventPileup());
}
if ( stratifiedContexts != null ) {
annotatedVCs = new ArrayList<VariantContext>(VCs.size());
for ( VariantContext vc : VCs )
annotatedVCs.add(engine.annotateContext(tracker, ref, stratifiedContexts, vc));
}
}
if ( ! indelsOnly ) {
for ( VariantContext annotatedVC : annotatedVCs )
vcfWriter.add(annotatedVC);
} else {
// check to see if the buffered context is different (in location) this context
if ( indelBufferContext != null && ! VariantContextUtils.getLocation(getToolkit().getGenomeLocParser(),indelBufferContext.iterator().next()).equals(VariantContextUtils.getLocation(getToolkit().getGenomeLocParser(),annotatedVCs.iterator().next())) ) {
for ( VariantContext annotatedVC : indelBufferContext )
vcfWriter.add(annotatedVC);
indelBufferContext = annotatedVCs;
} else {
indelBufferContext = annotatedVCs;
}
}
return 1;
}
/**
* Increment the number of loci processed.
*
* @param value result of the map.
* @param sum accumulator for the reduce.
* @return the new number of loci processed.
*/
public Integer reduce(Integer value, Integer sum) {
return sum + value;
}
/**
* Tell the user the number of loci processed and close out the new variants file.
*
* @param result the number of loci seen.
*/
public void onTraversalDone(Integer result) {
logger.info("Processed " + result + " loci.\n");
}
}
| false | true | public void initialize() {
if ( LIST )
listAnnotationsAndExit();
// get the list of all sample names from the variant VCF input rod, if applicable
List<String> rodName = Arrays.asList(variantCollection.variants.getName());
Set<String> samples = SampleUtils.getUniqueSamplesFromRods(getToolkit(), rodName);
if ( USE_ALL_ANNOTATIONS )
engine = new VariantAnnotatorEngine(annotationsToExclude, this, getToolkit());
else
engine = new VariantAnnotatorEngine(annotationGroupsToUse, annotationsToUse, annotationsToExclude, this, getToolkit());
engine.initializeExpressions(expressionsToUse);
// setup the header fields
// note that if any of the definitions conflict with our new ones, then we want to overwrite the old ones
Set<VCFHeaderLine> hInfo = new HashSet<VCFHeaderLine>();
hInfo.addAll(engine.getVCFAnnotationDescriptions());
for ( VCFHeaderLine line : VCFUtils.getHeaderFields(getToolkit(), Arrays.asList(variantCollection.variants.getName())) ) {
if ( isUniqueHeaderLine(line, hInfo) )
hInfo.add(line);
}
// for the expressions, pull the info header line from the header of the resource rod
for ( VariantAnnotatorEngine.VAExpression expression : engine.getRequestedExpressions() ) {
// special case the ID field
if ( expression.fieldName.equals("ID") ) {
hInfo.add(new VCFInfoHeaderLine(expression.fullName, 1, VCFHeaderLineType.String, "ID field transferred from external VCF resource"));
continue;
}
VCFInfoHeaderLine targetHeaderLine = null;
for ( VCFHeaderLine line : VCFUtils.getHeaderFields(getToolkit(), Arrays.asList(expression.binding.getName())) ) {
if ( line instanceof VCFInfoHeaderLine ) {
VCFInfoHeaderLine infoline = (VCFInfoHeaderLine)line;
if ( infoline.getName().equals(expression.fieldName) ) {
targetHeaderLine = infoline;
break;
}
}
}
if ( targetHeaderLine != null )
hInfo.add(new VCFInfoHeaderLine(expression.fullName, targetHeaderLine.getCountType(), targetHeaderLine.getType(), targetHeaderLine.getDescription()));
else
hInfo.add(new VCFInfoHeaderLine(expression.fullName, VCFHeaderLineCount.UNBOUNDED, VCFHeaderLineType.String, "Value transferred from another external VCF resource"));
}
engine.invokeAnnotationInitializationMethods(hInfo);
VCFHeader vcfHeader = new VCFHeader(hInfo, samples);
vcfWriter.writeHeader(vcfHeader);
if ( indelsOnly ) {
indelBufferContext = null;
}
}
| public void initialize() {
if ( LIST )
listAnnotationsAndExit();
// get the list of all sample names from the variant VCF input rod, if applicable
List<String> rodName = Arrays.asList(variantCollection.variants.getName());
Set<String> samples = SampleUtils.getUniqueSamplesFromRods(getToolkit(), rodName);
if ( USE_ALL_ANNOTATIONS )
engine = new VariantAnnotatorEngine(annotationsToExclude, this, getToolkit());
else
engine = new VariantAnnotatorEngine(annotationGroupsToUse, annotationsToUse, annotationsToExclude, this, getToolkit());
engine.initializeExpressions(expressionsToUse);
// setup the header fields
// note that if any of the definitions conflict with our new ones, then we want to overwrite the old ones
Set<VCFHeaderLine> hInfo = new HashSet<VCFHeaderLine>();
hInfo.addAll(engine.getVCFAnnotationDescriptions());
for ( VCFHeaderLine line : VCFUtils.getHeaderFields(getToolkit(), Arrays.asList(variantCollection.variants.getName())) ) {
if ( isUniqueHeaderLine(line, hInfo) )
hInfo.add(line);
}
// for the expressions, pull the info header line from the header of the resource rod
for ( VariantAnnotatorEngine.VAExpression expression : engine.getRequestedExpressions() ) {
// special case the ID field
if ( expression.fieldName.equals("ID") ) {
hInfo.add(new VCFInfoHeaderLine(expression.fullName, 1, VCFHeaderLineType.String, "ID field transferred from external VCF resource"));
continue;
}
VCFInfoHeaderLine targetHeaderLine = null;
for ( VCFHeaderLine line : VCFUtils.getHeaderFields(getToolkit(), Arrays.asList(expression.binding.getName())) ) {
if ( line instanceof VCFInfoHeaderLine ) {
VCFInfoHeaderLine infoline = (VCFInfoHeaderLine)line;
if ( infoline.getName().equals(expression.fieldName) ) {
targetHeaderLine = infoline;
break;
}
}
}
if ( targetHeaderLine != null ) {
if ( targetHeaderLine.getCountType() == VCFHeaderLineCount.INTEGER )
hInfo.add(new VCFInfoHeaderLine(expression.fullName, targetHeaderLine.getCount(), targetHeaderLine.getType(), targetHeaderLine.getDescription()));
else
hInfo.add(new VCFInfoHeaderLine(expression.fullName, targetHeaderLine.getCountType(), targetHeaderLine.getType(), targetHeaderLine.getDescription()));
} else {
hInfo.add(new VCFInfoHeaderLine(expression.fullName, VCFHeaderLineCount.UNBOUNDED, VCFHeaderLineType.String, "Value transferred from another external VCF resource"));
}
}
engine.invokeAnnotationInitializationMethods(hInfo);
VCFHeader vcfHeader = new VCFHeader(hInfo, samples);
vcfWriter.writeHeader(vcfHeader);
if ( indelsOnly ) {
indelBufferContext = null;
}
}
|
diff --git a/main/adapter/src/main/java/net/java/messageapi/adapter/PojoInvoker.java b/main/adapter/src/main/java/net/java/messageapi/adapter/PojoInvoker.java
index 56d6566..5643164 100644
--- a/main/adapter/src/main/java/net/java/messageapi/adapter/PojoInvoker.java
+++ b/main/adapter/src/main/java/net/java/messageapi/adapter/PojoInvoker.java
@@ -1,66 +1,66 @@
package net.java.messageapi.adapter;
import java.lang.reflect.Method;
import java.util.List;
import net.java.messageapi.MessageApi;
import net.java.messageapi.reflection.Parameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Calls methods from an implementation of an {@link MessageApi} by converting instances of the generated POJOs back to
* method calls.
*/
public class PojoInvoker<T> {
final Logger log = LoggerFactory.getLogger(PojoInvoker.class);
public static <T> PojoInvoker<T> of(Class<T> api, T impl) {
return new PojoInvoker<T>(api, impl);
}
/** the impl is *not* enough: it may be a proxy, so reflection would return the wrong methods */
private final Class<T> api;
private final T impl;
public PojoInvoker(Class<T> api, T impl) {
if (api == null)
throw new RuntimeException("api must not be null");
if (impl == null)
throw new RuntimeException("impl must not be null");
if (!api.isInstance(impl))
throw new IllegalArgumentException(api.getName() + " is not implemented by " + impl.getClass());
this.api = api;
this.impl = impl;
}
public void invoke(Object pojo) {
- log.debug("invoke for {}", pojo);
+ log.trace("invoke for {}", pojo);
PojoProperties pojoProperties = PojoProperties.of(pojo);
String methodName = getMethodNameFor(pojo);
- log.debug("search {} with {}", methodName, pojoProperties);
+ log.trace("search {} with {}", methodName, pojoProperties);
for (Method method : api.getMethods()) {
- log.debug("compare {}", method);
+ log.trace("compare {}", method);
if (method.getName().equals(methodName)) {
List<Parameter> methodParameters = Parameter.allOf(method);
if (pojoProperties.matches(methodParameters)) {
- log.debug("parameters match... invoke");
+ log.trace("parameters match... invoke");
pojoProperties.invoke(impl, method, methodParameters);
return;
}
}
}
throw new RuntimeException("method [" + methodName + "] with properties " + pojoProperties + " not found in "
+ api);
}
private String getMethodNameFor(Object pojo) {
String[] names = pojo.getClass().getSimpleName().split("\\$");
String name = names[names.length - 1];
return Character.toLowerCase(name.charAt(0)) + name.substring(1);
}
}
| false | true | public void invoke(Object pojo) {
log.debug("invoke for {}", pojo);
PojoProperties pojoProperties = PojoProperties.of(pojo);
String methodName = getMethodNameFor(pojo);
log.debug("search {} with {}", methodName, pojoProperties);
for (Method method : api.getMethods()) {
log.debug("compare {}", method);
if (method.getName().equals(methodName)) {
List<Parameter> methodParameters = Parameter.allOf(method);
if (pojoProperties.matches(methodParameters)) {
log.debug("parameters match... invoke");
pojoProperties.invoke(impl, method, methodParameters);
return;
}
}
}
throw new RuntimeException("method [" + methodName + "] with properties " + pojoProperties + " not found in "
+ api);
}
| public void invoke(Object pojo) {
log.trace("invoke for {}", pojo);
PojoProperties pojoProperties = PojoProperties.of(pojo);
String methodName = getMethodNameFor(pojo);
log.trace("search {} with {}", methodName, pojoProperties);
for (Method method : api.getMethods()) {
log.trace("compare {}", method);
if (method.getName().equals(methodName)) {
List<Parameter> methodParameters = Parameter.allOf(method);
if (pojoProperties.matches(methodParameters)) {
log.trace("parameters match... invoke");
pojoProperties.invoke(impl, method, methodParameters);
return;
}
}
}
throw new RuntimeException("method [" + methodName + "] with properties " + pojoProperties + " not found in "
+ api);
}
|
diff --git a/src/test/java/npanday/its/NPandayIT9903ResGenWithErrorInFileNameTest.java b/src/test/java/npanday/its/NPandayIT9903ResGenWithErrorInFileNameTest.java
index 3be3e54..fc6576e 100644
--- a/src/test/java/npanday/its/NPandayIT9903ResGenWithErrorInFileNameTest.java
+++ b/src/test/java/npanday/its/NPandayIT9903ResGenWithErrorInFileNameTest.java
@@ -1,43 +1,43 @@
package npanday.its;
/*
* Copyright 2009
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File;
import org.apache.maven.it.VerificationException;
import org.apache.maven.it.Verifier;
import org.apache.maven.it.util.ResourceExtractor;
public class NPandayIT9903ResGenWithErrorInFileNameTest
extends AbstractNPandayIntegrationTestCase
{
public NPandayIT9903ResGenWithErrorInFileNameTest()
{
super( "(1.0,)" ); // 1.0.1+
}
public void testResGenWithErrorInFileName()
throws Exception
{
File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/npanday-9903" );
Verifier verifier = getVerifier( testDir );
verifier.executeGoal( "install" );
- verifier.assertFilePresent( new File( "npanday-9903", getAssemblyFile( "npanday-9903", "1.0.0", "dll" ) ).getAbsolutePath() );
+ verifier.assertFilePresent( new File( testDir, "npanday-9903/" + getAssemblyFile( "npanday-9903", "1.0.0", "zip" ) ).getAbsolutePath() );
verifier.verifyErrorFreeLog();
verifier.resetStreams();
}
}
| true | true | public void testResGenWithErrorInFileName()
throws Exception
{
File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/npanday-9903" );
Verifier verifier = getVerifier( testDir );
verifier.executeGoal( "install" );
verifier.assertFilePresent( new File( "npanday-9903", getAssemblyFile( "npanday-9903", "1.0.0", "dll" ) ).getAbsolutePath() );
verifier.verifyErrorFreeLog();
verifier.resetStreams();
}
| public void testResGenWithErrorInFileName()
throws Exception
{
File testDir = ResourceExtractor.simpleExtractResources( getClass(), "/npanday-9903" );
Verifier verifier = getVerifier( testDir );
verifier.executeGoal( "install" );
verifier.assertFilePresent( new File( testDir, "npanday-9903/" + getAssemblyFile( "npanday-9903", "1.0.0", "zip" ) ).getAbsolutePath() );
verifier.verifyErrorFreeLog();
verifier.resetStreams();
}
|
diff --git a/bundles/extensions/discovery/impl/src/main/java/org/apache/sling/discovery/impl/cluster/ClusterViewServiceImpl.java b/bundles/extensions/discovery/impl/src/main/java/org/apache/sling/discovery/impl/cluster/ClusterViewServiceImpl.java
index e817af8d78..816efb91c5 100644
--- a/bundles/extensions/discovery/impl/src/main/java/org/apache/sling/discovery/impl/cluster/ClusterViewServiceImpl.java
+++ b/bundles/extensions/discovery/impl/src/main/java/org/apache/sling/discovery/impl/cluster/ClusterViewServiceImpl.java
@@ -1,170 +1,170 @@
/*
* 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.sling.discovery.impl.cluster;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.discovery.ClusterView;
import org.apache.sling.discovery.InstanceDescription;
import org.apache.sling.discovery.impl.Config;
import org.apache.sling.discovery.impl.common.View;
import org.apache.sling.discovery.impl.common.ViewHelper;
import org.apache.sling.discovery.impl.common.resource.EstablishedClusterView;
import org.apache.sling.discovery.impl.common.resource.IsolatedInstanceDescription;
import org.apache.sling.settings.SlingSettingsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Default implementation of the ClusterViewService interface.
* <p>
* This class is a reader only - it accesses the repository to read the
* currently established view
*/
@Component
@Service(value = ClusterViewService.class)
public class ClusterViewServiceImpl implements ClusterViewService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Reference
private SlingSettingsService settingsService;
@Reference
private ResourceResolverFactory resourceResolverFactory;
@Reference
private Config config;
/** the cluster view id of the isolated cluster view */
private String isolatedClusterViewId = UUID.randomUUID().toString();
public String getIsolatedClusterViewId() {
return isolatedClusterViewId;
}
private ClusterView getIsolatedClusterView() {
ResourceResolver resourceResolver = null;
try {
resourceResolver = resourceResolverFactory
.getAdministrativeResourceResolver(null);
Resource instanceResource = resourceResolver
.getResource(config.getClusterInstancesPath() + "/"
+ getSlingId());
IsolatedInstanceDescription ownInstance = new IsolatedInstanceDescription(instanceResource,
isolatedClusterViewId, getSlingId());
return ownInstance.getClusterView();
} catch (LoginException e) {
logger.error("Could not do a login: " + e, e);
throw new RuntimeException("Could not do a login", e);
} finally {
if (resourceResolver != null) {
resourceResolver.close();
}
}
}
public String getSlingId() {
if (settingsService==null) {
return null;
}
return settingsService.getSlingId();
}
public boolean contains(final String slingId) {
List<InstanceDescription> localInstances = getClusterView()
.getInstances();
for (Iterator<InstanceDescription> it = localInstances.iterator(); it
.hasNext();) {
InstanceDescription aLocalInstance = it.next();
if (aLocalInstance.getSlingId().equals(slingId)) {
return true;
}
}
return false;
}
public boolean containsAny(Collection<InstanceDescription> listInstances) {
for (Iterator<InstanceDescription> it = listInstances.iterator(); it
.hasNext();) {
InstanceDescription instanceDescription = it.next();
if (contains(instanceDescription.getSlingId())) {
return true;
}
}
return false;
}
public ClusterView getClusterView() {
if (resourceResolverFactory==null) {
logger.warn("getClusterView: no resourceResolverFactory set at the moment.");
return null;
}
ResourceResolver resourceResolver = null;
try {
resourceResolver = resourceResolverFactory
.getAdministrativeResourceResolver(null);
View view = ViewHelper.getEstablishedView(resourceResolver, config);
if (view == null) {
logger.debug("getEstablishedView: no view established at the moment. isolated mode");
return getIsolatedClusterView();
}
EstablishedClusterView clusterViewImpl = new EstablishedClusterView(
config, view, getSlingId());
boolean foundLocal = false;
for (Iterator<InstanceDescription> it = clusterViewImpl
.getInstances().iterator(); it.hasNext();) {
InstanceDescription instance = it.next();
if (instance.isLocal()) {
foundLocal = true;
break;
}
}
if (foundLocal) {
return clusterViewImpl;
} else {
- logger.error("getEstablishedView: the existing established view does not incude the local instance yet! Assming isolated mode.");
+ logger.info("getEstablishedView: the existing established view does not incude the local instance yet! Assuming isolated mode.");
return getIsolatedClusterView();
}
} catch (LoginException e) {
logger.error(
"handleEvent: could not log in administratively: " + e, e);
return null;
} finally {
if (resourceResolver != null) {
resourceResolver.close();
}
}
}
}
| true | true | public ClusterView getClusterView() {
if (resourceResolverFactory==null) {
logger.warn("getClusterView: no resourceResolverFactory set at the moment.");
return null;
}
ResourceResolver resourceResolver = null;
try {
resourceResolver = resourceResolverFactory
.getAdministrativeResourceResolver(null);
View view = ViewHelper.getEstablishedView(resourceResolver, config);
if (view == null) {
logger.debug("getEstablishedView: no view established at the moment. isolated mode");
return getIsolatedClusterView();
}
EstablishedClusterView clusterViewImpl = new EstablishedClusterView(
config, view, getSlingId());
boolean foundLocal = false;
for (Iterator<InstanceDescription> it = clusterViewImpl
.getInstances().iterator(); it.hasNext();) {
InstanceDescription instance = it.next();
if (instance.isLocal()) {
foundLocal = true;
break;
}
}
if (foundLocal) {
return clusterViewImpl;
} else {
logger.error("getEstablishedView: the existing established view does not incude the local instance yet! Assming isolated mode.");
return getIsolatedClusterView();
}
} catch (LoginException e) {
logger.error(
"handleEvent: could not log in administratively: " + e, e);
return null;
} finally {
if (resourceResolver != null) {
resourceResolver.close();
}
}
}
| public ClusterView getClusterView() {
if (resourceResolverFactory==null) {
logger.warn("getClusterView: no resourceResolverFactory set at the moment.");
return null;
}
ResourceResolver resourceResolver = null;
try {
resourceResolver = resourceResolverFactory
.getAdministrativeResourceResolver(null);
View view = ViewHelper.getEstablishedView(resourceResolver, config);
if (view == null) {
logger.debug("getEstablishedView: no view established at the moment. isolated mode");
return getIsolatedClusterView();
}
EstablishedClusterView clusterViewImpl = new EstablishedClusterView(
config, view, getSlingId());
boolean foundLocal = false;
for (Iterator<InstanceDescription> it = clusterViewImpl
.getInstances().iterator(); it.hasNext();) {
InstanceDescription instance = it.next();
if (instance.isLocal()) {
foundLocal = true;
break;
}
}
if (foundLocal) {
return clusterViewImpl;
} else {
logger.info("getEstablishedView: the existing established view does not incude the local instance yet! Assuming isolated mode.");
return getIsolatedClusterView();
}
} catch (LoginException e) {
logger.error(
"handleEvent: could not log in administratively: " + e, e);
return null;
} finally {
if (resourceResolver != null) {
resourceResolver.close();
}
}
}
|
diff --git a/src/SearchController.java b/src/SearchController.java
index 5555b3e..034f8a7 100644
--- a/src/SearchController.java
+++ b/src/SearchController.java
@@ -1,92 +1,96 @@
package ca.awesome;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.Collection;
import java.util.ArrayList;
public class SearchController extends Controller {
public static String QUERY_FIELD = "QUERY";
public static String START_FIELD = "TIME_FROM";
public static String END_FIELD = "TIME_UNTIL";
public static String RANKING_FIELD = "RANKING";
public Collection<Record> results;
public SearchQuery query;
public SearchController(ServletContext context,
HttpServletRequest request, HttpServletResponse response,
HttpSession session) {
super(context, request, response, session);
results = new ArrayList<Record>();
}
public boolean doSearch() {
query = new SearchQuery(request.getParameter(QUERY_FIELD),
parseDateOrGetNull(request.getParameter(START_FIELD)),
parseDateOrGetNull(request.getParameter(END_FIELD)));
String rankBy = request.getParameter(RANKING_FIELD);
if (rankBy != null && rankBy.equals("DATE_ASC")) {
query.setRankingPolicy(SearchQuery.RANK_BY_DATE_ASC);
} else if (rankBy != null && rankBy.equals("DATE_DES")) {
query.setRankingPolicy(SearchQuery.RANK_BY_DATE_DES);
} else {
query.setRankingPolicy(SearchQuery.RANK_BY_SCORE);
}
query.addClause(createSecurityConstraint());
- results = query.executeSearch(getDatabaseConnection());
+ try {
+ results = query.executeSearch(getDatabaseConnection());
+ } catch (Exception e) {
+ return false;
+ }
return true;
}
public Date parseDateOrGetNull(String date) {
try {
return parseDate(date);
} catch (Exception e) {
return null;
}
}
public SearchQuery.WhereClause createSecurityConstraint() {
switch (user.getType()) {
case User.PATIENT_T:
return new ColumnEqualsClause("patient_name",
user.getUserName());
case User.DOCTOR_T:
return new ColumnEqualsClause("doctor_name",
user.getUserName());
case User.RADIOLOGIST_T:
return new ColumnEqualsClause("radiologist_name",
user.getUserName());
// admin
default:
return null;
}
}
public static class ColumnEqualsClause implements SearchQuery.WhereClause {
String column;
String value;
ColumnEqualsClause(String column, String value) {
this.column = column;
this.value = value;
}
@Override
public String getClause() {
return " AND " + column + " = ? ";
}
@Override
public int addData(PreparedStatement s, int position)
throws SQLException {
s.setString(position, value);
return 1;
}
}
}
| true | true | public boolean doSearch() {
query = new SearchQuery(request.getParameter(QUERY_FIELD),
parseDateOrGetNull(request.getParameter(START_FIELD)),
parseDateOrGetNull(request.getParameter(END_FIELD)));
String rankBy = request.getParameter(RANKING_FIELD);
if (rankBy != null && rankBy.equals("DATE_ASC")) {
query.setRankingPolicy(SearchQuery.RANK_BY_DATE_ASC);
} else if (rankBy != null && rankBy.equals("DATE_DES")) {
query.setRankingPolicy(SearchQuery.RANK_BY_DATE_DES);
} else {
query.setRankingPolicy(SearchQuery.RANK_BY_SCORE);
}
query.addClause(createSecurityConstraint());
results = query.executeSearch(getDatabaseConnection());
return true;
}
| public boolean doSearch() {
query = new SearchQuery(request.getParameter(QUERY_FIELD),
parseDateOrGetNull(request.getParameter(START_FIELD)),
parseDateOrGetNull(request.getParameter(END_FIELD)));
String rankBy = request.getParameter(RANKING_FIELD);
if (rankBy != null && rankBy.equals("DATE_ASC")) {
query.setRankingPolicy(SearchQuery.RANK_BY_DATE_ASC);
} else if (rankBy != null && rankBy.equals("DATE_DES")) {
query.setRankingPolicy(SearchQuery.RANK_BY_DATE_DES);
} else {
query.setRankingPolicy(SearchQuery.RANK_BY_SCORE);
}
query.addClause(createSecurityConstraint());
try {
results = query.executeSearch(getDatabaseConnection());
} catch (Exception e) {
return false;
}
return true;
}
|
diff --git a/src/jipdbs/web/SearchServlet.java b/src/jipdbs/web/SearchServlet.java
index 8e4c414..ca3082d 100644
--- a/src/jipdbs/web/SearchServlet.java
+++ b/src/jipdbs/web/SearchServlet.java
@@ -1,145 +1,145 @@
package jipdbs.web;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jipdbs.JIPDBS;
import jipdbs.PageLink;
import jipdbs.Parameters;
import jipdbs.bean.SearchResult;
import jipdbs.util.Functions;
import org.datanucleus.util.StringUtils;
public class SearchServlet extends HttpServlet {
private static final int DEFAULT_PAGE_SIZE = 20;
private static final long serialVersionUID = -729953187311026007L;
private JIPDBS app;
private final static String IP_RE = "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d|[\\*])){3}$";
private final static Pattern IP_VALIDATOR = Pattern.compile(IP_RE);
private static final Logger log = Logger.getLogger(SearchServlet.class.getName());
@Override
public void init() throws ServletException {
app = (JIPDBS) getServletContext().getAttribute("jipdbs");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
int page = 1;
int pageSize = DEFAULT_PAGE_SIZE;
try {
page = Integer.parseInt(req.getParameter("p"));
} catch (NumberFormatException e) {
// Ignore.
}
try {
pageSize = Integer.parseInt(req.getParameter("ps"));
} catch (NumberFormatException e) {
// Ignore.
}
int offset = (page - 1) * pageSize;
int limit = pageSize;
String query = req.getParameter("q");
String type = "";
try {
type = req.getParameter("t");
} catch (Exception e) {
}
List<SearchResult> list = new ArrayList<SearchResult>();
int[] total = new int[1];
long time = System.currentTimeMillis();
// this is to get the modified value and show it in search box
String queryValue = query;
- if (StringUtils.isEmpty(query)) {
- log.fine("Empty");
- list = app.rootQuery(offset, limit, total);
- } else if ("s".equals(type)) {
+ if ("s".equals(type)) {
log.finest("Buscando SERVER");
queryValue = "";
list = app.byServerSearch(query, offset, limit, total);
} else if ("ban".equals(type)) {
log.finest("Buscando BAN");
queryValue = "";
list = app.bannedQuery(offset, limit, total);
- } else {
+ } else if (StringUtils.notEmpty(query)) {
Matcher matcher = IP_VALIDATOR.matcher(query);
if (matcher.matches()) {
log.finest("Buscando IP " + query);
query = Functions.fixIp(query);
queryValue = query;
list = app.ipSearch(query, offset, limit, total);
} else {
log.finest("Buscando Alias " + query);
if (validPlayerNameChars(query)) {
boolean[] exactMatch = new boolean[1];
exactMatch[0] = true;
list = app.aliasSearch(query, offset, limit, total, exactMatch);
if (!exactMatch[0] && list.size() > 0) {
Flash.info(
req,
"No se encontraron resultados precisos. "
+ "Los resultados mostrados son variaciones del nombre.");
if (total[0] > Parameters.MAX_NGRAM_QUERY / 2) {
Flash.warn(req, "Su búsqueda arroja demasiados resultados."
+ " Por favor, sea más específico.");
}
}
} else
Flash.error(req, "Consulta inválida. Caracteres inválidos.");
}
+ } else {
+ log.fine("Empty");
+ list = app.rootQuery(offset, limit, total);
}
time = System.currentTimeMillis() - time;
int totalPages = (int) Math.ceil((double) total[0] / pageSize);
req.setAttribute("list", list);
req.setAttribute("queryValue", queryValue);
req.setAttribute("query", query);
req.setAttribute("type", type);
req.setAttribute("count", total[0]);
req.setAttribute("time", time);
req.setAttribute("pageLink", new PageLink(page, pageSize, totalPages));
}
private static boolean validPlayerNameChars(String query) {
if (query == null)
return false;
for (int i = 0; i < query.length(); i++)
if (!validPlayerNameChar(query.charAt(i)))
return false;
return true;
}
private static boolean validPlayerNameChar(char c) {
// Continuously improve this.
return c < 256 && c != ' ';
}
}
| false | true | protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
int page = 1;
int pageSize = DEFAULT_PAGE_SIZE;
try {
page = Integer.parseInt(req.getParameter("p"));
} catch (NumberFormatException e) {
// Ignore.
}
try {
pageSize = Integer.parseInt(req.getParameter("ps"));
} catch (NumberFormatException e) {
// Ignore.
}
int offset = (page - 1) * pageSize;
int limit = pageSize;
String query = req.getParameter("q");
String type = "";
try {
type = req.getParameter("t");
} catch (Exception e) {
}
List<SearchResult> list = new ArrayList<SearchResult>();
int[] total = new int[1];
long time = System.currentTimeMillis();
// this is to get the modified value and show it in search box
String queryValue = query;
if (StringUtils.isEmpty(query)) {
log.fine("Empty");
list = app.rootQuery(offset, limit, total);
} else if ("s".equals(type)) {
log.finest("Buscando SERVER");
queryValue = "";
list = app.byServerSearch(query, offset, limit, total);
} else if ("ban".equals(type)) {
log.finest("Buscando BAN");
queryValue = "";
list = app.bannedQuery(offset, limit, total);
} else {
Matcher matcher = IP_VALIDATOR.matcher(query);
if (matcher.matches()) {
log.finest("Buscando IP " + query);
query = Functions.fixIp(query);
queryValue = query;
list = app.ipSearch(query, offset, limit, total);
} else {
log.finest("Buscando Alias " + query);
if (validPlayerNameChars(query)) {
boolean[] exactMatch = new boolean[1];
exactMatch[0] = true;
list = app.aliasSearch(query, offset, limit, total, exactMatch);
if (!exactMatch[0] && list.size() > 0) {
Flash.info(
req,
"No se encontraron resultados precisos. "
+ "Los resultados mostrados son variaciones del nombre.");
if (total[0] > Parameters.MAX_NGRAM_QUERY / 2) {
Flash.warn(req, "Su búsqueda arroja demasiados resultados."
+ " Por favor, sea más específico.");
}
}
} else
Flash.error(req, "Consulta inválida. Caracteres inválidos.");
}
}
time = System.currentTimeMillis() - time;
int totalPages = (int) Math.ceil((double) total[0] / pageSize);
req.setAttribute("list", list);
req.setAttribute("queryValue", queryValue);
req.setAttribute("query", query);
req.setAttribute("type", type);
req.setAttribute("count", total[0]);
req.setAttribute("time", time);
req.setAttribute("pageLink", new PageLink(page, pageSize, totalPages));
}
| protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
int page = 1;
int pageSize = DEFAULT_PAGE_SIZE;
try {
page = Integer.parseInt(req.getParameter("p"));
} catch (NumberFormatException e) {
// Ignore.
}
try {
pageSize = Integer.parseInt(req.getParameter("ps"));
} catch (NumberFormatException e) {
// Ignore.
}
int offset = (page - 1) * pageSize;
int limit = pageSize;
String query = req.getParameter("q");
String type = "";
try {
type = req.getParameter("t");
} catch (Exception e) {
}
List<SearchResult> list = new ArrayList<SearchResult>();
int[] total = new int[1];
long time = System.currentTimeMillis();
// this is to get the modified value and show it in search box
String queryValue = query;
if ("s".equals(type)) {
log.finest("Buscando SERVER");
queryValue = "";
list = app.byServerSearch(query, offset, limit, total);
} else if ("ban".equals(type)) {
log.finest("Buscando BAN");
queryValue = "";
list = app.bannedQuery(offset, limit, total);
} else if (StringUtils.notEmpty(query)) {
Matcher matcher = IP_VALIDATOR.matcher(query);
if (matcher.matches()) {
log.finest("Buscando IP " + query);
query = Functions.fixIp(query);
queryValue = query;
list = app.ipSearch(query, offset, limit, total);
} else {
log.finest("Buscando Alias " + query);
if (validPlayerNameChars(query)) {
boolean[] exactMatch = new boolean[1];
exactMatch[0] = true;
list = app.aliasSearch(query, offset, limit, total, exactMatch);
if (!exactMatch[0] && list.size() > 0) {
Flash.info(
req,
"No se encontraron resultados precisos. "
+ "Los resultados mostrados son variaciones del nombre.");
if (total[0] > Parameters.MAX_NGRAM_QUERY / 2) {
Flash.warn(req, "Su búsqueda arroja demasiados resultados."
+ " Por favor, sea más específico.");
}
}
} else
Flash.error(req, "Consulta inválida. Caracteres inválidos.");
}
} else {
log.fine("Empty");
list = app.rootQuery(offset, limit, total);
}
time = System.currentTimeMillis() - time;
int totalPages = (int) Math.ceil((double) total[0] / pageSize);
req.setAttribute("list", list);
req.setAttribute("queryValue", queryValue);
req.setAttribute("query", query);
req.setAttribute("type", type);
req.setAttribute("count", total[0]);
req.setAttribute("time", time);
req.setAttribute("pageLink", new PageLink(page, pageSize, totalPages));
}
|
diff --git a/perftest/src/test/org/apache/ftpserver/perftest/PerformanceTestTemplate.java b/perftest/src/test/org/apache/ftpserver/perftest/PerformanceTestTemplate.java
index 64fcb77d..75b33822 100644
--- a/perftest/src/test/org/apache/ftpserver/perftest/PerformanceTestTemplate.java
+++ b/perftest/src/test/org/apache/ftpserver/perftest/PerformanceTestTemplate.java
@@ -1,248 +1,248 @@
/*
* 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.ftpserver.perftest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Hashtable;
import java.util.Properties;
import junit.framework.TestCase;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.ftpserver.ConfigurableFtpServerContext;
import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.config.PropertiesConfiguration;
import org.apache.ftpserver.interfaces.FtpServerContext;
import org.apache.ftpserver.util.IoUtils;
public abstract class PerformanceTestTemplate extends TestCase {
public static class ClientRunner implements Runnable {
private FTPClient client;
private ClientTask task;
private int repeats;
public ClientRunner(FTPClient client, ClientTask task, int repeats) {
this.client = client;
this.task = task;
this.repeats = repeats;
}
public void run() {
for (int round = 0; round < repeats; round++) {
try {
task.doWithClient(client);
} catch (Exception e) {
// activeThreads.remove(Thread.currentThread());
// throw new RuntimeException(e);
e.printStackTrace();
}
}
activeThreads.remove(Thread.currentThread());
}
}
public static interface ClientTask {
public void doWithClient(FTPClient client) throws Exception;
}
public static final int DEFAULT_PORT = 12321;
protected static final String ADMIN_PASSWORD = "admin";
protected static final String ADMIN_USERNAME = "admin";
protected static final String ANONYMOUS_PASSWORD = "[email protected]";
protected static final String ANONYMOUS_USERNAME = "anonymous";
protected static final String TESTUSER2_USERNAME = "testuser2";
protected static Hashtable activeThreads = new Hashtable();
protected static final String TESTUSER1_USERNAME = "testuser1";
protected static final String TESTUSER_PASSWORD = "password";
protected FtpServer server;
protected int port = DEFAULT_PORT;
private FtpServerContext serverContext;
private long startTime;
private static final File USERS_FILE = new File(getBaseDir(),
"src/test/users.gen");
private static final File TEST_TMP_DIR = new File("test-tmp");
protected static final File ROOT_DIR = new File(TEST_TMP_DIR, "ftproot");
public static File getBaseDir() {
// check Maven system prop first and use if set
String basedir = System.getProperty("basedir");
if (basedir != null) {
return new File(basedir);
} else {
return new File(".");
}
}
protected Properties createConfig() {
return createDefaultConfig();
}
protected Properties createDefaultConfig() {
assertTrue(USERS_FILE.getAbsolutePath() + " must exist", USERS_FILE
.exists());
Properties configProps = new Properties();
- configProps.setProperty("serverContext.socket-factory.port", Integer
+ configProps.setProperty("config.socket-factory.port", Integer
.toString(port));
- configProps.setProperty("serverContext.user-manager.class",
+ configProps.setProperty("config.user-manager.class",
"org.apache.ftpserver.usermanager.PropertiesUserManager");
- configProps.setProperty("serverContext.user-manager.admin", "admin");
- configProps.setProperty("serverContext.user-manager.prop-password-encrypt",
+ configProps.setProperty("config.user-manager.admin", "admin");
+ configProps.setProperty("config.user-manager.prop-password-encrypt",
"false");
- configProps.setProperty("serverContext.user-manager.prop-file", USERS_FILE
+ configProps.setProperty("config.user-manager.prop-file", USERS_FILE
.getAbsolutePath());
- configProps.setProperty("serverContext.create-default-user", "false");
- configProps.setProperty("serverContext.connection-manager.max-connection", "0");
- configProps.setProperty("serverContext.connection-manager.max-login", "0");
+ configProps.setProperty("config.create-default-user", "false");
+ configProps.setProperty("config.connection-manager.max-connection", "0");
+ configProps.setProperty("config.connection-manager.max-login", "0");
return configProps;
}
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
initDirs();
initServer();
}
/**
* @throws IOException
*/
protected void initDirs() throws IOException {
cleanTmpDirs();
TEST_TMP_DIR.mkdirs();
ROOT_DIR.mkdirs();
}
/**
* @throws IOException
* @throws Exception
*/
protected void initServer() throws IOException, Exception {
serverContext = new ConfigurableFtpServerContext(new PropertiesConfiguration(createConfig()));
server = new FtpServer(serverContext);
server.start();
Thread.sleep(200);
}
protected void cleanTmpDirs() throws IOException {
if (TEST_TMP_DIR.exists()) {
IoUtils.delete(TEST_TMP_DIR);
}
}
/**
* Ugly but working way of knowing when the test is complete
*/
protected void waitForTestRun() throws InterruptedException {
while (true) {
Thread.sleep(20);
if (activeThreads.size() == 0) {
break;
}
}
}
protected void doClients(ClientTask task, int noOfClients, int repeats) {
for (int i = 0; i < noOfClients; i++) {
FTPClient client = new FTPClient();
String clientId = "client" + i;
client.addProtocolCommandListener(new FtpClientLogger(clientId));
Thread clientThread = new Thread(new ClientRunner(client, task,
repeats), clientId);
activeThreads.put(clientThread, client);
clientThread.start();
}
}
protected void writeDataToFile(File file, byte[] data) throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(data);
} finally {
IoUtils.close(fos);
}
}
protected void endMeasureTime(String testName, int numberOfClients,
int numberOfRepeats) {
StringBuffer msg = new StringBuffer();
msg.append(testName).append(" took ")
.append(new Date().getTime() - startTime)
.append(" ms to complete. No of clients: ")
.append(numberOfClients)
.append(", number of repeats: ")
.append(numberOfRepeats);
System.out.println(msg.toString());
}
protected void startMeasureTime() {
startTime = new Date().getTime();
}
/*
* (non-Javadoc)
*
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception {
if (server != null) {
server.stop();
}
cleanTmpDirs();
}
}
| false | true | protected Properties createDefaultConfig() {
assertTrue(USERS_FILE.getAbsolutePath() + " must exist", USERS_FILE
.exists());
Properties configProps = new Properties();
configProps.setProperty("serverContext.socket-factory.port", Integer
.toString(port));
configProps.setProperty("serverContext.user-manager.class",
"org.apache.ftpserver.usermanager.PropertiesUserManager");
configProps.setProperty("serverContext.user-manager.admin", "admin");
configProps.setProperty("serverContext.user-manager.prop-password-encrypt",
"false");
configProps.setProperty("serverContext.user-manager.prop-file", USERS_FILE
.getAbsolutePath());
configProps.setProperty("serverContext.create-default-user", "false");
configProps.setProperty("serverContext.connection-manager.max-connection", "0");
configProps.setProperty("serverContext.connection-manager.max-login", "0");
return configProps;
}
| protected Properties createDefaultConfig() {
assertTrue(USERS_FILE.getAbsolutePath() + " must exist", USERS_FILE
.exists());
Properties configProps = new Properties();
configProps.setProperty("config.socket-factory.port", Integer
.toString(port));
configProps.setProperty("config.user-manager.class",
"org.apache.ftpserver.usermanager.PropertiesUserManager");
configProps.setProperty("config.user-manager.admin", "admin");
configProps.setProperty("config.user-manager.prop-password-encrypt",
"false");
configProps.setProperty("config.user-manager.prop-file", USERS_FILE
.getAbsolutePath());
configProps.setProperty("config.create-default-user", "false");
configProps.setProperty("config.connection-manager.max-connection", "0");
configProps.setProperty("config.connection-manager.max-login", "0");
return configProps;
}
|
diff --git a/src/helpers/Evaluator.java b/src/helpers/Evaluator.java
index 5cb2799..8bff72d 100644
--- a/src/helpers/Evaluator.java
+++ b/src/helpers/Evaluator.java
@@ -1,107 +1,108 @@
package helpers;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.util.Calendar;
import org.encog.ensemble.Ensemble.TrainingAborted;
import org.encog.neural.data.basic.BasicNeuralDataSet;
import techniques.EvaluationTechnique;
public class Evaluator {
private EvaluationTechnique technique;
private DataLoader dataLoader;
Evaluator(EvaluationTechnique technique, DataMapper mapper, int inputCols, int inputs, String dataFile, boolean inputsReversed, int nFolds, double targetTrainingError, double selectionError, int fold) {
this.setTechnique(technique);
dataLoader = new DataLoader(mapper,inputCols,inputs,inputsReversed,nFolds);
dataLoader.readData(dataFile);
this.technique.init(dataLoader,fold);
this.technique.setParams(targetTrainingError, selectionError);
this.technique.train(false);
}
public Evaluator(EvaluationTechnique technique, DataLoader dataLoader, double targetTrainingError, double selectionError, boolean verbose, int fold) {
this.setTechnique(technique);
this.dataLoader = dataLoader;
this.technique.init(dataLoader,fold);
this.technique.setParams(targetTrainingError, selectionError);
this.technique.train(verbose);
}
- public void makeLine(boolean isTest, double training_error, ChainParams chainPars, BasicNeuralDataSet dataSet, Statement sqlStatement, long chainId) throws SQLException {
+ public void makeLine(boolean isTest, double trainingError, ChainParams chainPars, BasicNeuralDataSet dataSet, Statement sqlStatement, long chainId) throws SQLException {
DataMapper dataMapper = dataLoader.getMapper();
PerfResults perf = this.technique.testPerformance(dataSet, dataMapper,false);
- sqlStatement.executeUpdate("INSERT INTO runs (chain, ml_technique, training_error, dataset_size, misclassified_samples," +
+ sqlStatement.executeUpdate("INSERT INTO runs (chain, ml_technique, training_error, selection_error, dataset_size, misclassified_samples," +
"is_test, macro_accuracy, macro_precision, macro_recall, macro_f1, micro_accuracy, micro_precision," +
"micro_recall, micro_f1, misclassification, ensemble_size) VALUES (" + chainId +
", '" + chainPars.getMLF() + "'" +
- ", " + training_error +
+ ", " + trainingError +
+ ", " + this.technique.selectionError +
", " + this.technique.getTrainingSet().size() +
", " + this.technique.getMisclassificationCount(dataSet,dataMapper) +
", " + (isTest ? 1 : 0) +
", " + perf.getAccuracy(PerfResults.AveragingMethod.MACRO) +
", " + perf.getPrecision(PerfResults.AveragingMethod.MACRO) +
", " + perf.getRecall(PerfResults.AveragingMethod.MACRO) +
", " + perf.FScore(1.0, PerfResults.AveragingMethod.MACRO) +
", " + perf.getAccuracy(PerfResults.AveragingMethod.MICRO) +
", " + perf.getPrecision(PerfResults.AveragingMethod.MICRO) +
", " + perf.getRecall(PerfResults.AveragingMethod.MICRO) +
", " + perf.FScore(1.0, PerfResults.AveragingMethod.MICRO) +
", " + this.technique.getMisclassification(dataSet,dataMapper) +
", " + technique.getCurrentSize() +
");"
, Statement.RETURN_GENERATED_KEYS
);
ResultSet rs = sqlStatement.getGeneratedKeys();
long runId = 0;
if(rs.next()) {
runId = rs.getLong(1);
}
rs.close();
int outputs = dataSet.getIdealSize();
for (int output = 0; output < outputs; output ++)
{
sqlStatement.executeUpdate("INSERT INTO class_details (run, class, is_test, tp, tn, fp, fn) VALUES (" + runId +
", '" + dataMapper.getClassLabel(output) + "'" +
", " + (isTest ? 1 : 0) +
", " + perf.getTP(output) +
", " + perf.getTN(output) +
", " + perf.getFP(output) +
", " + perf.getFN(output) +
");"
);
}
}
public void getResults (ChainParams prefix, double te, int fold, DBConnect reconnect, long chainId) throws SQLException, FileNotFoundException, IOException {
while(technique.hasStepsLeft()) {
Connection sqlConnection = reconnect.connect();
Statement sqlStatement = sqlConnection.createStatement();
makeLine(false,te,prefix,this.dataLoader.getTrainingSet(fold), sqlStatement, chainId);
makeLine(true,te,prefix,this.dataLoader.getTestSet(fold), sqlStatement, chainId);
sqlConnection.close();
try {
technique.step(false);
}
catch (TrainingAborted e) {
System.out.println("Training aborted on E_t = " + te + ", fold = " + fold + " in chain" + chainId);
}
}
}
public EvaluationTechnique getTechnique() {
return technique;
}
public void setTechnique(EvaluationTechnique technique) {
this.technique = technique;
}
}
| false | true | public void makeLine(boolean isTest, double training_error, ChainParams chainPars, BasicNeuralDataSet dataSet, Statement sqlStatement, long chainId) throws SQLException {
DataMapper dataMapper = dataLoader.getMapper();
PerfResults perf = this.technique.testPerformance(dataSet, dataMapper,false);
sqlStatement.executeUpdate("INSERT INTO runs (chain, ml_technique, training_error, dataset_size, misclassified_samples," +
"is_test, macro_accuracy, macro_precision, macro_recall, macro_f1, micro_accuracy, micro_precision," +
"micro_recall, micro_f1, misclassification, ensemble_size) VALUES (" + chainId +
", '" + chainPars.getMLF() + "'" +
", " + training_error +
", " + this.technique.getTrainingSet().size() +
", " + this.technique.getMisclassificationCount(dataSet,dataMapper) +
", " + (isTest ? 1 : 0) +
", " + perf.getAccuracy(PerfResults.AveragingMethod.MACRO) +
", " + perf.getPrecision(PerfResults.AveragingMethod.MACRO) +
", " + perf.getRecall(PerfResults.AveragingMethod.MACRO) +
", " + perf.FScore(1.0, PerfResults.AveragingMethod.MACRO) +
", " + perf.getAccuracy(PerfResults.AveragingMethod.MICRO) +
", " + perf.getPrecision(PerfResults.AveragingMethod.MICRO) +
", " + perf.getRecall(PerfResults.AveragingMethod.MICRO) +
", " + perf.FScore(1.0, PerfResults.AveragingMethod.MICRO) +
", " + this.technique.getMisclassification(dataSet,dataMapper) +
", " + technique.getCurrentSize() +
");"
, Statement.RETURN_GENERATED_KEYS
);
ResultSet rs = sqlStatement.getGeneratedKeys();
long runId = 0;
if(rs.next()) {
runId = rs.getLong(1);
}
rs.close();
int outputs = dataSet.getIdealSize();
for (int output = 0; output < outputs; output ++)
{
sqlStatement.executeUpdate("INSERT INTO class_details (run, class, is_test, tp, tn, fp, fn) VALUES (" + runId +
", '" + dataMapper.getClassLabel(output) + "'" +
", " + (isTest ? 1 : 0) +
", " + perf.getTP(output) +
", " + perf.getTN(output) +
", " + perf.getFP(output) +
", " + perf.getFN(output) +
");"
);
}
}
| public void makeLine(boolean isTest, double trainingError, ChainParams chainPars, BasicNeuralDataSet dataSet, Statement sqlStatement, long chainId) throws SQLException {
DataMapper dataMapper = dataLoader.getMapper();
PerfResults perf = this.technique.testPerformance(dataSet, dataMapper,false);
sqlStatement.executeUpdate("INSERT INTO runs (chain, ml_technique, training_error, selection_error, dataset_size, misclassified_samples," +
"is_test, macro_accuracy, macro_precision, macro_recall, macro_f1, micro_accuracy, micro_precision," +
"micro_recall, micro_f1, misclassification, ensemble_size) VALUES (" + chainId +
", '" + chainPars.getMLF() + "'" +
", " + trainingError +
", " + this.technique.selectionError +
", " + this.technique.getTrainingSet().size() +
", " + this.technique.getMisclassificationCount(dataSet,dataMapper) +
", " + (isTest ? 1 : 0) +
", " + perf.getAccuracy(PerfResults.AveragingMethod.MACRO) +
", " + perf.getPrecision(PerfResults.AveragingMethod.MACRO) +
", " + perf.getRecall(PerfResults.AveragingMethod.MACRO) +
", " + perf.FScore(1.0, PerfResults.AveragingMethod.MACRO) +
", " + perf.getAccuracy(PerfResults.AveragingMethod.MICRO) +
", " + perf.getPrecision(PerfResults.AveragingMethod.MICRO) +
", " + perf.getRecall(PerfResults.AveragingMethod.MICRO) +
", " + perf.FScore(1.0, PerfResults.AveragingMethod.MICRO) +
", " + this.technique.getMisclassification(dataSet,dataMapper) +
", " + technique.getCurrentSize() +
");"
, Statement.RETURN_GENERATED_KEYS
);
ResultSet rs = sqlStatement.getGeneratedKeys();
long runId = 0;
if(rs.next()) {
runId = rs.getLong(1);
}
rs.close();
int outputs = dataSet.getIdealSize();
for (int output = 0; output < outputs; output ++)
{
sqlStatement.executeUpdate("INSERT INTO class_details (run, class, is_test, tp, tn, fp, fn) VALUES (" + runId +
", '" + dataMapper.getClassLabel(output) + "'" +
", " + (isTest ? 1 : 0) +
", " + perf.getTP(output) +
", " + perf.getTN(output) +
", " + perf.getFP(output) +
", " + perf.getFN(output) +
");"
);
}
}
|
diff --git a/src/com/android/exchange/eas/EasOperation.java b/src/com/android/exchange/eas/EasOperation.java
index 6d615d77..1c695e08 100644
--- a/src/com/android/exchange/eas/EasOperation.java
+++ b/src/com/android/exchange/eas/EasOperation.java
@@ -1,554 +1,556 @@
/*
* Copyright (C) 2013 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.exchange.eas;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.SyncResult;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.format.DateUtils;
import com.android.emailcommon.provider.Account;
import com.android.emailcommon.provider.EmailContent;
import com.android.emailcommon.provider.HostAuth;
import com.android.emailcommon.provider.Mailbox;
import com.android.emailcommon.utility.Utility;
import com.android.exchange.Eas;
import com.android.exchange.EasResponse;
import com.android.exchange.adapter.Serializer;
import com.android.exchange.adapter.Tags;
import com.android.exchange.service.EasServerConnection;
import com.android.mail.utils.LogUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ByteArrayEntity;
import java.io.IOException;
/**
* Base class for all Exchange operations that use a POST to talk to the server.
*
* The core of this class is {@link #performOperation}, which provides the skeleton of making
* a request, handling common errors, and setting fields on the {@link SyncResult} if there is one.
* This class abstracts the connection handling from its subclasses and callers.
*
* A subclass must implement the abstract functions below that create the request and parse the
* response. There are also a set of functions that a subclass may override if it's substantially
* different from the "normal" operation (e.g. most requests use the same request URI, but auto
* discover deviates since it's not account-specific), but the default implementation should suffice
* for most. The subclass must also define a public function which calls {@link #performOperation},
* possibly doing nothing other than that. (I chose to force subclasses to do this, rather than
* provide that function in the base class, in order to force subclasses to consider, for example,
* whether it needs a {@link SyncResult} parameter, and what the proper name for the "doWork"
* function ought to be for the subclass.)
*/
public abstract class EasOperation {
public static final String LOG_TAG = Eas.LOG_TAG;
/** The maximum number of server redirects we allow before returning failure. */
private static final int MAX_REDIRECTS = 3;
/** Message MIME type for EAS version 14 and later. */
private static final String EAS_14_MIME_TYPE = "application/vnd.ms-sync.wbxml";
/** Error code indicating the operation was cancelled via {@link #abort}. */
public static final int RESULT_ABORT = -1;
/** Error code indicating the operation was cancelled via {@link #restart}. */
public static final int RESULT_RESTART = -2;
/** Error code indicating the Exchange servers redirected too many times. */
public static final int RESULT_TOO_MANY_REDIRECTS = -3;
/** Error code indicating the request failed due to a network problem. */
public static final int RESULT_REQUEST_FAILURE = -4;
/** Error code indicating a 403 (forbidden) error. */
public static final int RESULT_FORBIDDEN = -5;
/** Error code indicating an unresolved provisioning error. */
public static final int RESULT_PROVISIONING_ERROR = -6;
/** Error code indicating an authentication problem. */
public static final int RESULT_AUTHENTICATION_ERROR = -7;
/** Error code indicating the client is missing a certificate. */
public static final int RESULT_CLIENT_CERTIFICATE_REQUIRED = -8;
/** Error code indicating we don't have a protocol version in common with the server. */
public static final int RESULT_PROTOCOL_VERSION_UNSUPPORTED = -9;
/** Error code indicating some other failure. */
public static final int RESULT_OTHER_FAILURE = -10;
protected final Context mContext;
/**
* The account id for this operation.
* NOTE: You will be tempted to add a reference to the {@link Account} here. Resist.
* It's too easy for that to lead to creep and stale data.
*/
protected final long mAccountId;
private final EasServerConnection mConnection;
// TODO: Make this private again when EasSyncHandler is converted to be a subclass.
protected EasOperation(final Context context, final long accountId,
final EasServerConnection connection) {
mContext = context;
mAccountId = accountId;
mConnection = connection;
}
protected EasOperation(final Context context, final Account account, final HostAuth hostAuth) {
this(context, account.mId, new EasServerConnection(context, account, hostAuth));
}
protected EasOperation(final Context context, final Account account) {
this(context, account, HostAuth.restoreHostAuthWithId(context, account.mHostAuthKeyRecv));
}
/**
* This constructor is for use by operations that are created by other operations, e.g.
* {@link EasProvision}.
* @param parentOperation The {@link EasOperation} that is creating us.
*/
protected EasOperation(final EasOperation parentOperation) {
this(parentOperation.mContext, parentOperation.mAccountId, parentOperation.mConnection);
}
/**
* Request that this operation terminate. Intended for use by the sync service to interrupt
* running operations, primarily Ping.
*/
public final void abort() {
mConnection.stop(EasServerConnection.STOPPED_REASON_ABORT);
}
/**
* Request that this operation restart. Intended for use by the sync service to interrupt
* running operations, primarily Ping.
*/
public final void restart() {
mConnection.stop(EasServerConnection.STOPPED_REASON_RESTART);
}
/**
* The skeleton of performing an operation. This function handles all the common code and
* error handling, calling into virtual functions that are implemented or overridden by the
* subclass to do the operation-specific logic.
*
* The result codes work as follows:
* - Negative values indicate common error codes and are defined above (the various RESULT_*
* constants).
* - Non-negative values indicate the result of {@link #handleResponse}. These are obviously
* specific to the subclass, and may indicate success or error conditions.
*
* The common error codes primarily indicate conditions that occur when performing the POST
* itself, such as network errors and handling of the HTTP response. However, some errors that
* can be indicated in the HTTP response code can also be indicated in the payload of the
* response as well, so {@link #handleResponse} should in those cases return the appropriate
* negative result code, which will be handled the same as if it had been indicated in the HTTP
* response code.
*
* @param syncResult If this operation is a sync, the {@link SyncResult} object that should
* be written to for this sync; otherwise null.
* @return A result code for the outcome of this operation, as described above.
*/
protected final int performOperation(final SyncResult syncResult) {
// We handle server redirects by looping, but we need to protect against too much looping.
int redirectCount = 0;
do {
// Perform the HTTP request and handle exceptions.
final EasResponse response;
try {
if (registerClientCert()) {
response = mConnection.executeHttpUriRequest(makeRequest(), getTimeout());
} else {
+ LogUtils.e(LOG_TAG, "Problem registering client cert");
// TODO: Is this the best stat to increment?
if (syncResult != null) {
++syncResult.stats.numAuthExceptions;
}
return RESULT_CLIENT_CERTIFICATE_REQUIRED;
}
} catch (final IOException e) {
// If we were stopped, return the appropriate result code.
switch (mConnection.getStoppedReason()) {
case EasServerConnection.STOPPED_REASON_ABORT:
return RESULT_ABORT;
case EasServerConnection.STOPPED_REASON_RESTART:
return RESULT_RESTART;
default:
break;
}
// If we're here, then we had a IOException that's not from a stop request.
LogUtils.e(LOG_TAG, e, "Exception while sending request");
if (syncResult != null) {
++syncResult.stats.numIoExceptions;
}
return RESULT_REQUEST_FAILURE;
} catch (final IllegalStateException e) {
// Subclasses use ISE to signal a hard error when building the request.
// TODO: Switch away from ISEs.
LogUtils.e(LOG_TAG, e, "Exception while sending request");
if (syncResult != null) {
syncResult.databaseError = true;
}
return RESULT_OTHER_FAILURE;
}
// The POST completed, so process the response.
try {
final int result;
// First off, the success case.
if (response.isSuccess()) {
try {
result = handleResponse(response, syncResult);
if (result >= 0) {
return result;
}
} catch (final IOException e) {
LogUtils.e(LOG_TAG, e, "Exception while handling response");
if (syncResult != null) {
++syncResult.stats.numIoExceptions;
}
return RESULT_REQUEST_FAILURE;
}
} else {
result = RESULT_OTHER_FAILURE;
}
// If this operation has distinct handling for 403 errors, do that.
if (result == RESULT_FORBIDDEN || (response.isForbidden() && handleForbidden())) {
LogUtils.e(LOG_TAG, "Forbidden response");
if (syncResult != null) {
// TODO: Is this the best stat to increment?
++syncResult.stats.numAuthExceptions;
}
return RESULT_FORBIDDEN;
}
// Handle provisioning errors.
if (result == RESULT_PROVISIONING_ERROR || response.isProvisionError()) {
if (handleProvisionError(syncResult, mAccountId)) {
// The provisioning error has been taken care of, so we should re-do this
// request.
continue;
}
if (syncResult != null) {
+ LogUtils.e(LOG_TAG, "Issue with provisioning");
// TODO: Is this the best stat to increment?
++syncResult.stats.numAuthExceptions;
}
return RESULT_PROVISIONING_ERROR;
}
// Handle authentication errors.
if (response.isAuthError()) {
LogUtils.e(LOG_TAG, "Authentication error");
if (syncResult != null) {
++syncResult.stats.numAuthExceptions;
}
if (response.isMissingCertificate()) {
return RESULT_CLIENT_CERTIFICATE_REQUIRED;
}
return RESULT_AUTHENTICATION_ERROR;
}
// Handle redirects.
if (response.isRedirectError()) {
++redirectCount;
mConnection.redirectHostAuth(response.getRedirectAddress());
// Note that unlike other errors, we do NOT return here; we just keep looping.
} else {
// All other errors.
LogUtils.e(LOG_TAG, "Generic error for operation %s: status %d, result %d",
getCommand(), response.getStatus(), result);
if (syncResult != null) {
// TODO: Is this the best stat to increment?
++syncResult.stats.numIoExceptions;
}
return RESULT_OTHER_FAILURE;
}
} finally {
response.close();
}
} while (redirectCount < MAX_REDIRECTS);
// Non-redirects return immediately after handling, so the only way to reach here is if we
// looped too many times.
LogUtils.e(LOG_TAG, "Too many redirects");
if (syncResult != null) {
syncResult.tooManyRetries = true;
}
return RESULT_TOO_MANY_REDIRECTS;
}
/**
* Reset the protocol version to use for this connection. If it's changed, and our account is
* persisted, also write back the changes to the DB.
* @param protocolVersion The new protocol version to use, as a string.
*/
protected final void setProtocolVersion(final String protocolVersion) {
if (mConnection.setProtocolVersion(protocolVersion) && mAccountId != Account.NOT_SAVED) {
final Uri uri = ContentUris.withAppendedId(Account.CONTENT_URI, mAccountId);
final ContentValues cv = new ContentValues(2);
if (getProtocolVersion() >= 12.0) {
final int oldFlags = Utility.getFirstRowInt(mContext, uri,
Account.ACCOUNT_FLAGS_PROJECTION, null, null, null,
Account.ACCOUNT_FLAGS_COLUMN_FLAGS, 0);
final int newFlags = oldFlags
| Account.FLAGS_SUPPORTS_GLOBAL_SEARCH + Account.FLAGS_SUPPORTS_SEARCH;
if (oldFlags != newFlags) {
cv.put(EmailContent.AccountColumns.FLAGS, newFlags);
}
}
cv.put(EmailContent.AccountColumns.PROTOCOL_VERSION, protocolVersion);
mContext.getContentResolver().update(uri, cv, null, null);
}
}
/**
* Create the request object for this operation.
* Most operations use a POST, but some use other request types (e.g. Options).
* @return An {@link HttpUriRequest}.
* @throws IOException
*/
private final HttpUriRequest makeRequest() throws IOException {
final String requestUri = getRequestUri();
if (requestUri == null) {
return mConnection.makeOptions();
}
return mConnection.makePost(requestUri, getRequestEntity(),
getRequestContentType(), addPolicyKeyHeaderToRequest());
}
/**
* The following functions MUST be overridden by subclasses; these are things that are unique
* to each operation.
*/
/**
* Get the name of the operation, used as the "Cmd=XXX" query param in the request URI. Note
* that if you override {@link #getRequestUri}, then this function may be unused for normal
* operation, but all subclasses should return something non-null for use with logging.
* @return The name of the command for this operation as defined by the EAS protocol, or for
* commands that don't need it, a suitable descriptive name for logging.
*/
protected abstract String getCommand();
/**
* Build the {@link HttpEntity} which is used to construct the POST. Typically this function
* will build the Exchange request using a {@link Serializer} and then call {@link #makeEntity}.
* If the subclass is not using a POST, then it should override this to return null.
* @return The {@link HttpEntity} to pass to {@link EasServerConnection#makePost}.
* @throws IOException
*/
protected abstract HttpEntity getRequestEntity() throws IOException;
/**
* Parse the response from the Exchange perform whatever actions are dictated by that.
* @param response The {@link EasResponse} to our request.
* @param syncResult The {@link SyncResult} object for this operation, or null if we're not
* handling a sync.
* @return A result code. Non-negative values are returned directly to the caller; negative
* values
*
* that is returned to the caller of {@link #performOperation}.
* @throws IOException
*/
protected abstract int handleResponse(final EasResponse response, final SyncResult syncResult)
throws IOException;
/**
* The following functions may be overriden by a subclass, but most operations will not need
* to do so.
*/
/**
* Get the URI for the Exchange server and this operation. Most (signed in) operations need
* not override this; the notable operation that needs to override it is auto-discover.
* @return
*/
protected String getRequestUri() {
return mConnection.makeUriString(getCommand());
}
/**
* @return Whether to set the X-MS-PolicyKey header. Only Ping does not want this header.
*/
protected boolean addPolicyKeyHeaderToRequest() {
return true;
}
/**
* @return The content type of this request.
*/
protected String getRequestContentType() {
return EAS_14_MIME_TYPE;
}
/**
* @return The timeout to use for the POST.
*/
protected long getTimeout() {
return 30 * DateUtils.SECOND_IN_MILLIS;
}
/**
* If 403 responses should be handled in a special way, this function should be overridden to
* do that.
* @return Whether we handle 403 responses; if false, then treat 403 as a provisioning error.
*/
protected boolean handleForbidden() {
return false;
}
/**
* Handle a provisioning error. Subclasses may override this to do something different, e.g.
* to validate rather than actually do the provisioning.
* @param syncResult
* @param accountId
* @return
*/
protected boolean handleProvisionError(final SyncResult syncResult, final long accountId) {
final EasProvision provisionOperation = new EasProvision(this);
return provisionOperation.provision(syncResult, accountId);
}
/**
* Convenience methods for subclasses to use.
*/
/**
* Convenience method to make an {@link HttpEntity} from {@link Serializer}.
*/
protected final HttpEntity makeEntity(final Serializer s) {
return new ByteArrayEntity(s.toByteArray());
}
/**
* Check whether we should ask the server what protocol versions it supports and set this
* account to use that version.
* @return Whether we need a new protocol version from the server.
*/
protected final boolean shouldGetProtocolVersion() {
// TODO: Find conditions under which we should check other than not having one yet.
return !mConnection.isProtocolVersionSet();
}
/**
* @return The protocol version to use.
*/
protected final double getProtocolVersion() {
return mConnection.getProtocolVersion();
}
/**
* @return Our useragent.
*/
protected final String getUserAgent() {
return mConnection.getUserAgent();
}
/**
* @return Whether we succeeeded in registering the client cert.
*/
protected final boolean registerClientCert() {
return mConnection.registerClientCert();
}
/**
* Add the device information to the current request.
* @param s The {@link Serializer} for our current request.
* @throws IOException
*/
protected final void addDeviceInformationToSerlializer(final Serializer s) throws IOException {
final TelephonyManager tm = (TelephonyManager)mContext.getSystemService(
Context.TELEPHONY_SERVICE);
final String deviceId;
final String phoneNumber;
final String operator;
if (tm != null) {
deviceId = tm.getDeviceId();
phoneNumber = tm.getLine1Number();
operator = tm.getNetworkOperator();
} else {
deviceId = null;
phoneNumber = null;
operator = null;
}
// TODO: Right now, we won't send this information unless the device is provisioned again.
// Potentially, this means that our phone number could be out of date if the user
// switches sims. Is there something we can do to force a reprovision?
s.start(Tags.SETTINGS_DEVICE_INFORMATION).start(Tags.SETTINGS_SET);
s.data(Tags.SETTINGS_MODEL, Build.MODEL);
if (deviceId != null) {
s.data(Tags.SETTINGS_IMEI, tm.getDeviceId());
}
// TODO: What should we use for friendly name?
//s.data(Tags.SETTINGS_FRIENDLY_NAME, "Friendly Name");
s.data(Tags.SETTINGS_OS, "Android " + Build.VERSION.RELEASE);
if (phoneNumber != null) {
s.data(Tags.SETTINGS_PHONE_NUMBER, phoneNumber);
}
// TODO: Consider setting this, but make sure we know what it's used for.
// If the user changes the device's locale and we don't do a reprovision, the server's
// idea of the language will be wrong. Since we're not sure what this is used for,
// right now we're leaving it out.
//s.data(Tags.SETTINGS_OS_LANGUAGE, Locale.getDefault().getDisplayLanguage());
s.data(Tags.SETTINGS_USER_AGENT, getUserAgent());
if (operator != null) {
s.data(Tags.SETTINGS_MOBILE_OPERATOR, operator);
}
s.end().end(); // SETTINGS_SET, SETTINGS_DEVICE_INFORMATION
}
/**
* Convenience method for adding a Message to an account's outbox
* @param account The {@link Account} from which to send the message.
* @param msg the message to send
*/
protected final void sendMessage(final Account account, final EmailContent.Message msg) {
long mailboxId = Mailbox.findMailboxOfType(mContext, account.mId, Mailbox.TYPE_OUTBOX);
// TODO: Improve system mailbox handling.
if (mailboxId == Mailbox.NO_MAILBOX) {
LogUtils.d(LOG_TAG, "No outbox for account %d, creating it", account.mId);
final Mailbox outbox =
Mailbox.newSystemMailbox(mContext, account.mId, Mailbox.TYPE_OUTBOX);
outbox.save(mContext);
mailboxId = outbox.mId;
}
msg.mMailboxKey = mailboxId;
msg.mAccountKey = account.mId;
msg.save(mContext);
requestSyncForMailbox(new android.accounts.Account(account.mEmailAddress,
Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), EmailContent.AUTHORITY, mailboxId);
}
/**
* Issue a {@link android.content.ContentResolver#requestSync} for a specific mailbox.
* @param amAccount The {@link android.accounts.Account} for the account we're pinging.
* @param authority The authority for the mailbox that needs to sync.
* @param mailboxId The id of the mailbox that needs to sync.
*/
protected static void requestSyncForMailbox(final android.accounts.Account amAccount,
final String authority, final long mailboxId) {
final Bundle extras = new Bundle(1);
extras.putLong(Mailbox.SYNC_EXTRA_MAILBOX_ID, mailboxId);
ContentResolver.requestSync(amAccount, authority, extras);
LogUtils.i(LOG_TAG, "requestSync EasOperation requestSyncForMailbox %s, %s",
amAccount.toString(), extras.toString());
}
}
| false | true | protected final int performOperation(final SyncResult syncResult) {
// We handle server redirects by looping, but we need to protect against too much looping.
int redirectCount = 0;
do {
// Perform the HTTP request and handle exceptions.
final EasResponse response;
try {
if (registerClientCert()) {
response = mConnection.executeHttpUriRequest(makeRequest(), getTimeout());
} else {
// TODO: Is this the best stat to increment?
if (syncResult != null) {
++syncResult.stats.numAuthExceptions;
}
return RESULT_CLIENT_CERTIFICATE_REQUIRED;
}
} catch (final IOException e) {
// If we were stopped, return the appropriate result code.
switch (mConnection.getStoppedReason()) {
case EasServerConnection.STOPPED_REASON_ABORT:
return RESULT_ABORT;
case EasServerConnection.STOPPED_REASON_RESTART:
return RESULT_RESTART;
default:
break;
}
// If we're here, then we had a IOException that's not from a stop request.
LogUtils.e(LOG_TAG, e, "Exception while sending request");
if (syncResult != null) {
++syncResult.stats.numIoExceptions;
}
return RESULT_REQUEST_FAILURE;
} catch (final IllegalStateException e) {
// Subclasses use ISE to signal a hard error when building the request.
// TODO: Switch away from ISEs.
LogUtils.e(LOG_TAG, e, "Exception while sending request");
if (syncResult != null) {
syncResult.databaseError = true;
}
return RESULT_OTHER_FAILURE;
}
// The POST completed, so process the response.
try {
final int result;
// First off, the success case.
if (response.isSuccess()) {
try {
result = handleResponse(response, syncResult);
if (result >= 0) {
return result;
}
} catch (final IOException e) {
LogUtils.e(LOG_TAG, e, "Exception while handling response");
if (syncResult != null) {
++syncResult.stats.numIoExceptions;
}
return RESULT_REQUEST_FAILURE;
}
} else {
result = RESULT_OTHER_FAILURE;
}
// If this operation has distinct handling for 403 errors, do that.
if (result == RESULT_FORBIDDEN || (response.isForbidden() && handleForbidden())) {
LogUtils.e(LOG_TAG, "Forbidden response");
if (syncResult != null) {
// TODO: Is this the best stat to increment?
++syncResult.stats.numAuthExceptions;
}
return RESULT_FORBIDDEN;
}
// Handle provisioning errors.
if (result == RESULT_PROVISIONING_ERROR || response.isProvisionError()) {
if (handleProvisionError(syncResult, mAccountId)) {
// The provisioning error has been taken care of, so we should re-do this
// request.
continue;
}
if (syncResult != null) {
// TODO: Is this the best stat to increment?
++syncResult.stats.numAuthExceptions;
}
return RESULT_PROVISIONING_ERROR;
}
// Handle authentication errors.
if (response.isAuthError()) {
LogUtils.e(LOG_TAG, "Authentication error");
if (syncResult != null) {
++syncResult.stats.numAuthExceptions;
}
if (response.isMissingCertificate()) {
return RESULT_CLIENT_CERTIFICATE_REQUIRED;
}
return RESULT_AUTHENTICATION_ERROR;
}
// Handle redirects.
if (response.isRedirectError()) {
++redirectCount;
mConnection.redirectHostAuth(response.getRedirectAddress());
// Note that unlike other errors, we do NOT return here; we just keep looping.
} else {
// All other errors.
LogUtils.e(LOG_TAG, "Generic error for operation %s: status %d, result %d",
getCommand(), response.getStatus(), result);
if (syncResult != null) {
// TODO: Is this the best stat to increment?
++syncResult.stats.numIoExceptions;
}
return RESULT_OTHER_FAILURE;
}
} finally {
response.close();
}
} while (redirectCount < MAX_REDIRECTS);
// Non-redirects return immediately after handling, so the only way to reach here is if we
// looped too many times.
LogUtils.e(LOG_TAG, "Too many redirects");
if (syncResult != null) {
syncResult.tooManyRetries = true;
}
return RESULT_TOO_MANY_REDIRECTS;
}
| protected final int performOperation(final SyncResult syncResult) {
// We handle server redirects by looping, but we need to protect against too much looping.
int redirectCount = 0;
do {
// Perform the HTTP request and handle exceptions.
final EasResponse response;
try {
if (registerClientCert()) {
response = mConnection.executeHttpUriRequest(makeRequest(), getTimeout());
} else {
LogUtils.e(LOG_TAG, "Problem registering client cert");
// TODO: Is this the best stat to increment?
if (syncResult != null) {
++syncResult.stats.numAuthExceptions;
}
return RESULT_CLIENT_CERTIFICATE_REQUIRED;
}
} catch (final IOException e) {
// If we were stopped, return the appropriate result code.
switch (mConnection.getStoppedReason()) {
case EasServerConnection.STOPPED_REASON_ABORT:
return RESULT_ABORT;
case EasServerConnection.STOPPED_REASON_RESTART:
return RESULT_RESTART;
default:
break;
}
// If we're here, then we had a IOException that's not from a stop request.
LogUtils.e(LOG_TAG, e, "Exception while sending request");
if (syncResult != null) {
++syncResult.stats.numIoExceptions;
}
return RESULT_REQUEST_FAILURE;
} catch (final IllegalStateException e) {
// Subclasses use ISE to signal a hard error when building the request.
// TODO: Switch away from ISEs.
LogUtils.e(LOG_TAG, e, "Exception while sending request");
if (syncResult != null) {
syncResult.databaseError = true;
}
return RESULT_OTHER_FAILURE;
}
// The POST completed, so process the response.
try {
final int result;
// First off, the success case.
if (response.isSuccess()) {
try {
result = handleResponse(response, syncResult);
if (result >= 0) {
return result;
}
} catch (final IOException e) {
LogUtils.e(LOG_TAG, e, "Exception while handling response");
if (syncResult != null) {
++syncResult.stats.numIoExceptions;
}
return RESULT_REQUEST_FAILURE;
}
} else {
result = RESULT_OTHER_FAILURE;
}
// If this operation has distinct handling for 403 errors, do that.
if (result == RESULT_FORBIDDEN || (response.isForbidden() && handleForbidden())) {
LogUtils.e(LOG_TAG, "Forbidden response");
if (syncResult != null) {
// TODO: Is this the best stat to increment?
++syncResult.stats.numAuthExceptions;
}
return RESULT_FORBIDDEN;
}
// Handle provisioning errors.
if (result == RESULT_PROVISIONING_ERROR || response.isProvisionError()) {
if (handleProvisionError(syncResult, mAccountId)) {
// The provisioning error has been taken care of, so we should re-do this
// request.
continue;
}
if (syncResult != null) {
LogUtils.e(LOG_TAG, "Issue with provisioning");
// TODO: Is this the best stat to increment?
++syncResult.stats.numAuthExceptions;
}
return RESULT_PROVISIONING_ERROR;
}
// Handle authentication errors.
if (response.isAuthError()) {
LogUtils.e(LOG_TAG, "Authentication error");
if (syncResult != null) {
++syncResult.stats.numAuthExceptions;
}
if (response.isMissingCertificate()) {
return RESULT_CLIENT_CERTIFICATE_REQUIRED;
}
return RESULT_AUTHENTICATION_ERROR;
}
// Handle redirects.
if (response.isRedirectError()) {
++redirectCount;
mConnection.redirectHostAuth(response.getRedirectAddress());
// Note that unlike other errors, we do NOT return here; we just keep looping.
} else {
// All other errors.
LogUtils.e(LOG_TAG, "Generic error for operation %s: status %d, result %d",
getCommand(), response.getStatus(), result);
if (syncResult != null) {
// TODO: Is this the best stat to increment?
++syncResult.stats.numIoExceptions;
}
return RESULT_OTHER_FAILURE;
}
} finally {
response.close();
}
} while (redirectCount < MAX_REDIRECTS);
// Non-redirects return immediately after handling, so the only way to reach here is if we
// looped too many times.
LogUtils.e(LOG_TAG, "Too many redirects");
if (syncResult != null) {
syncResult.tooManyRetries = true;
}
return RESULT_TOO_MANY_REDIRECTS;
}
|
diff --git a/ItineRennes/src/fr/itinerennes/ui/activity/BusStationActivity.java b/ItineRennes/src/fr/itinerennes/ui/activity/BusStationActivity.java
index 2450d1f..f65a891 100644
--- a/ItineRennes/src/fr/itinerennes/ui/activity/BusStationActivity.java
+++ b/ItineRennes/src/fr/itinerennes/ui/activity/BusStationActivity.java
@@ -1,156 +1,157 @@
package fr.itinerennes.ui.activity;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.impl.ItinerennesLoggerFactory;
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import fr.itinerennes.R;
import fr.itinerennes.business.facade.BusDepartureService;
import fr.itinerennes.business.facade.BusRouteService;
import fr.itinerennes.business.facade.BusService;
import fr.itinerennes.business.http.keolis.KeolisService;
import fr.itinerennes.database.DatabaseHelper;
import fr.itinerennes.exceptions.GenericException;
import fr.itinerennes.model.BusDeparture;
import fr.itinerennes.model.BusRoute;
import fr.itinerennes.model.BusStation;
import fr.itinerennes.model.LineIcon;
import fr.itinerennes.ui.adapter.BusTimeAdapter;
/**
* This activity uses the <code>bus_station.xml</code> layout and displays a window with
* informations about a bus station.
*
* @author Jérémie Huchet
* @author Olivier Boudet
*/
public class BusStationActivity extends Activity {
/** The event logger. */
private static final Logger LOGGER = ItinerennesLoggerFactory
.getLogger(BusStationActivity.class);
/** The Bus Service. */
private BusService busService;
/** The Bus Route Service. */
private BusRouteService busRouteService;
/** The Departure Service. */
BusDepartureService busDepartureService;
/**
* {@inheritDoc}
*
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected final void onCreate(final Bundle savedInstanceState) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("onCreate.start");
}
super.onCreate(savedInstanceState);
setContentView(R.layout.bus_station);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("onCreate.end");
}
}
/**
* {@inheritDoc}
*
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
final DatabaseHelper dbHelper = new DatabaseHelper(getBaseContext());
busService = new BusService(dbHelper.getWritableDatabase());
busRouteService = new BusRouteService(dbHelper.getWritableDatabase());
busDepartureService = new BusDepartureService(dbHelper.getWritableDatabase());
final String stationId = getIntent().getExtras().getString("item");
try {
/* Displaying bus stop title */
BusStation station = busService.getStation(stationId);
final TextView name = (TextView) findViewById(R.station.name);
name.setText(station.getName());
LOGGER.debug("Bus stop title height = {}", name.getMeasuredHeight());
} catch (final GenericException e) {
LOGGER.debug(
String.format("Can't load station informations for the station %s.", stationId),
e);
}
/* TJHU this must be replaced - start */
final KeolisService keoServ = new KeolisService();
List<LineIcon> allIcons = null;
try {
allIcons = keoServ.getAllLineIcons();
} catch (final GenericException e) {
LOGGER.error("error", e);
}
/* TJHU this must be replaced - end */
try {
/* Fetching routes informations for this station. */
final List<BusRoute> busRoutes = busRouteService.getStationRoutes(stationId);
/* Displaying routes icons. */
final ViewGroup lineList = (ViewGroup) findViewById(R.station.line_icon_list);
+ lineList.removeAllViews();
if (busRoutes != null) {
for (final BusRoute busRoute : busRoutes) {
final ImageView lineIcon = (ImageView) getLayoutInflater().inflate(
R.layout.line_icon, null);
lineIcon.setImageDrawable(getBaseContext().getResources().getDrawable(
R.drawable.tmp_lm1));
lineList.addView(lineIcon);
LOGGER.debug("Showing icon for line {}.", busRoute.getId());
}
}
} catch (final GenericException e) {
LOGGER.debug(
String.format("Can't load routes informations for the station %s.", stationId),
e);
}
try {
/* Fetching and displaying departures informations for this station. */
final ListView listTimes = (ListView) findViewById(R.station.list_bus);
final List<BusDeparture> departures = busDepartureService
.getStationDepartures(stationId);
listTimes.setAdapter(new BusTimeAdapter(getBaseContext(), departures));
} catch (final GenericException e) {
LOGGER.debug(String.format("Can't load departures informations for the station %s.",
stationId), e);
}
}
/**
* {@inheritDoc}
*
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause() {
busService.release();
busRouteService.release();
super.onPause();
}
}
| true | true | protected void onResume() {
super.onResume();
final DatabaseHelper dbHelper = new DatabaseHelper(getBaseContext());
busService = new BusService(dbHelper.getWritableDatabase());
busRouteService = new BusRouteService(dbHelper.getWritableDatabase());
busDepartureService = new BusDepartureService(dbHelper.getWritableDatabase());
final String stationId = getIntent().getExtras().getString("item");
try {
/* Displaying bus stop title */
BusStation station = busService.getStation(stationId);
final TextView name = (TextView) findViewById(R.station.name);
name.setText(station.getName());
LOGGER.debug("Bus stop title height = {}", name.getMeasuredHeight());
} catch (final GenericException e) {
LOGGER.debug(
String.format("Can't load station informations for the station %s.", stationId),
e);
}
/* TJHU this must be replaced - start */
final KeolisService keoServ = new KeolisService();
List<LineIcon> allIcons = null;
try {
allIcons = keoServ.getAllLineIcons();
} catch (final GenericException e) {
LOGGER.error("error", e);
}
/* TJHU this must be replaced - end */
try {
/* Fetching routes informations for this station. */
final List<BusRoute> busRoutes = busRouteService.getStationRoutes(stationId);
/* Displaying routes icons. */
final ViewGroup lineList = (ViewGroup) findViewById(R.station.line_icon_list);
if (busRoutes != null) {
for (final BusRoute busRoute : busRoutes) {
final ImageView lineIcon = (ImageView) getLayoutInflater().inflate(
R.layout.line_icon, null);
lineIcon.setImageDrawable(getBaseContext().getResources().getDrawable(
R.drawable.tmp_lm1));
lineList.addView(lineIcon);
LOGGER.debug("Showing icon for line {}.", busRoute.getId());
}
}
} catch (final GenericException e) {
LOGGER.debug(
String.format("Can't load routes informations for the station %s.", stationId),
e);
}
try {
/* Fetching and displaying departures informations for this station. */
final ListView listTimes = (ListView) findViewById(R.station.list_bus);
final List<BusDeparture> departures = busDepartureService
.getStationDepartures(stationId);
listTimes.setAdapter(new BusTimeAdapter(getBaseContext(), departures));
} catch (final GenericException e) {
LOGGER.debug(String.format("Can't load departures informations for the station %s.",
stationId), e);
}
}
| protected void onResume() {
super.onResume();
final DatabaseHelper dbHelper = new DatabaseHelper(getBaseContext());
busService = new BusService(dbHelper.getWritableDatabase());
busRouteService = new BusRouteService(dbHelper.getWritableDatabase());
busDepartureService = new BusDepartureService(dbHelper.getWritableDatabase());
final String stationId = getIntent().getExtras().getString("item");
try {
/* Displaying bus stop title */
BusStation station = busService.getStation(stationId);
final TextView name = (TextView) findViewById(R.station.name);
name.setText(station.getName());
LOGGER.debug("Bus stop title height = {}", name.getMeasuredHeight());
} catch (final GenericException e) {
LOGGER.debug(
String.format("Can't load station informations for the station %s.", stationId),
e);
}
/* TJHU this must be replaced - start */
final KeolisService keoServ = new KeolisService();
List<LineIcon> allIcons = null;
try {
allIcons = keoServ.getAllLineIcons();
} catch (final GenericException e) {
LOGGER.error("error", e);
}
/* TJHU this must be replaced - end */
try {
/* Fetching routes informations for this station. */
final List<BusRoute> busRoutes = busRouteService.getStationRoutes(stationId);
/* Displaying routes icons. */
final ViewGroup lineList = (ViewGroup) findViewById(R.station.line_icon_list);
lineList.removeAllViews();
if (busRoutes != null) {
for (final BusRoute busRoute : busRoutes) {
final ImageView lineIcon = (ImageView) getLayoutInflater().inflate(
R.layout.line_icon, null);
lineIcon.setImageDrawable(getBaseContext().getResources().getDrawable(
R.drawable.tmp_lm1));
lineList.addView(lineIcon);
LOGGER.debug("Showing icon for line {}.", busRoute.getId());
}
}
} catch (final GenericException e) {
LOGGER.debug(
String.format("Can't load routes informations for the station %s.", stationId),
e);
}
try {
/* Fetching and displaying departures informations for this station. */
final ListView listTimes = (ListView) findViewById(R.station.list_bus);
final List<BusDeparture> departures = busDepartureService
.getStationDepartures(stationId);
listTimes.setAdapter(new BusTimeAdapter(getBaseContext(), departures));
} catch (final GenericException e) {
LOGGER.debug(String.format("Can't load departures informations for the station %s.",
stationId), e);
}
}
|
diff --git a/src/main/java/dk/frv/eavdam/utils/RoundCoverage.java b/src/main/java/dk/frv/eavdam/utils/RoundCoverage.java
index fef3786..6a4df9e 100644
--- a/src/main/java/dk/frv/eavdam/utils/RoundCoverage.java
+++ b/src/main/java/dk/frv/eavdam/utils/RoundCoverage.java
@@ -1,332 +1,332 @@
package dk.frv.eavdam.utils;
import java.util.ArrayList;
import java.util.List;
/**
* Calculates the round coverage area given the antenna height.
*
* @author TTETMJ
*
*/
public class RoundCoverage {
public static final double DEFAULT_RECEIVER_HEIGHT = 4.0;
private static final double DEGREES_TO_RADIANS = (Math.PI / 180.0);
public static final double EARTH_RADIUS = 6371.0;
/**
* Gets the coverage area in a polygon form.
*
* @param antennaHeight Height of the antenna.
* @param receiverHeight Height of the receiver. Default is 4.0 meters.
* @param centerLat Location of the base station (lat)
* @param centerLon Location of the base station (lon)
* @param numberOfPoints Number of points in the polygon. Should be at least 10.
* @return List of points (lat,lon) in the polygon. The first and the last point is the same. The index 0 in the double array has the latitude and the index 1 has the longitude.
*/
public static List<double[]> getRoundCoverage(double antennaHeight, double receiverHeight, double centerLat, double centerLon, int numberOfPoints){
List<double[]> points = new ArrayList<double[]>();
double radius = getRoundCoverageRadius(antennaHeight, receiverHeight);
if(numberOfPoints < 10) numberOfPoints = 10;
double partOfCircleAngle = 360.0/numberOfPoints;
double[] startPoint = null;
for(double angle = 0; angle <= 360.0; angle += partOfCircleAngle){
double[] point = getCoordinates(centerLat, centerLon, radius, angle);
if(angle == 0){
startPoint = point;
}
points.add(point);
}
if(points.get(points.size()-1)[0] != startPoint[0] || points.get(points.size()-1)[1] != startPoint[1]){
points.add(startPoint);
}
return points;
}
/**
* Gets the partial coverage area (for directional antennas) in a polygon form.
*
* @param antennaHeight Height of the antenna.
* @param receiverHeight Height of the receiver. Default is 4.0 meters.
* @param centerLat Location of the base station (lat)
* @param centerLon Location of the base station (lon)
* @param heading Heading
* @param fieldOfViewAngle Field of view angle
* @param numberOfPoints Number of points in the polygon. Should be at least 10.
* @return List of points (lat,lon) in the polygon. The first and the last point is the same. The index 0 in the double array has the latitude and the index 1 has the longitude.
*/
public static List<double[]> getRoundCoverage(double antennaHeight, double receiverHeight, double centerLat, double centerLon, double heading, double fieldOfViewAngle, int numberOfPoints) {
List<double[]> points = new ArrayList<double[]>();
double[] stationPoint = new double[2];
if(numberOfPoints < 10) numberOfPoints = 10;
double partOfCircleAngle = (fieldOfViewAngle/5)/Math.round(numberOfPoints/2);
for(double angle = heading+(fieldOfViewAngle/10); angle >= heading-(fieldOfViewAngle/10); angle -= partOfCircleAngle){
double[] point = getCoordinates(centerLat, centerLon, 0.01, angle);
points.add(point);
}
double[] point = getCoordinates(centerLat, centerLon, 0.01, heading-(fieldOfViewAngle/10));
points.add(point);
double radius = getRoundCoverageRadius(antennaHeight, receiverHeight);
partOfCircleAngle = fieldOfViewAngle/Math.round(numberOfPoints/2);
for(double angle = heading-(fieldOfViewAngle/2); angle <= heading+(fieldOfViewAngle/2); angle += partOfCircleAngle){
point = getCoordinates(centerLat, centerLon, radius, angle);
points.add(point);
}
point = getCoordinates(centerLat, centerLon, radius, heading+(fieldOfViewAngle/2));
points.add(point);
points.add(getCoordinates(centerLat, centerLon, 0.01, heading+(fieldOfViewAngle/10))); // first point
return points;
}
/**
* Gets the coverage area in a polygon form.
*
* @param antennaHeight Height of the antenna.
* @param receiverHeight Height of the receiver. Default is 4.0 meters.
* @param centerLat Location of the base station (lat)
* @param centerLon Location of the base station (lon)
* @param numberOfPoints Number of points in the polygon. Should be at least 10.
* @return List of points (lat,lon) in the polygon. The first and the last point is the same. The index 0 in the double array has the latitude and the index 1 has the longitude.
*/
public static List<double[]> getRoundInterferenceCoverage(double centerLat, double centerLon, int numberOfPoints){
List<double[]> points = new ArrayList<double[]>();
double radius = 120*1.852;
if(numberOfPoints < 10) numberOfPoints = 10;
double partOfCircleAngle = 360.0/numberOfPoints;
double[] startPoint = null;
for(double angle = 0; angle <= 360.0; angle += partOfCircleAngle){
double[] point = getCoordinates(centerLat, centerLon, radius, angle);
if(angle == 0){
startPoint = point;
}
points.add(point);
}
if(points.get(points.size()-1)[0] != startPoint[0] || points.get(points.size()-1)[1] != startPoint[1]){
points.add(startPoint);
}
return points;
}
/**
* Gets the coverage area (for directional antennas) in a polygon form.
*
* @param antennaHeight Height of the antenna.
* @param receiverHeight Height of the receiver. Default is 4.0 meters.
* @param centerLat Location of the base station (lat)
* @param centerLon Location of the base station (lon)
* @param heading Heading
* @param fieldOfViewAngle Field of view angle
* @param numberOfPoints Number of points in the polygon. Should be at least 10.
* @return List of points (lat,lon) in the polygon. The first and the last point is the same. The index 0 in the double array has the latitude and the index 1 has the longitude.
*/
public static List<double[]> getRoundInterferenceCoverage(double antennaHeight, double receiverHeight, double centerLat, double centerLon, double heading, double fieldOfViewAngle, int numberOfPoints){
List<double[]> points = new ArrayList<double[]>();
double radius1 = getRoundCoverageRadius(antennaHeight, receiverHeight);
if(numberOfPoints < 10) numberOfPoints = 10;
double partOfCircleAngle = 180.0/Math.round(numberOfPoints/2);
double radius2 = 120*1.852;
double startAngle = heading + 90;
if (startAngle > 360) {
startAngle = startAngle - 360;
}
double endAngle = heading - 90;
if (endAngle < 0) {
endAngle = 360 + endAngle; //e.g., 360 + (-60)
}
double temp = -1;
//Add line from the station to the start point:
- double[] p1 = {centerLat,centerLon};
- points.add(p1);
+// double[] p1 = {centerLat,centerLon};
+// points.add(p1);
if(endAngle < startAngle) endAngle += 360;
//First, do the half circle behind the heading
for (double angle = startAngle; angle <= endAngle; angle += partOfCircleAngle){
double realAngle = angle;
if(realAngle > 360) realAngle -= 360;
double[] point = getCoordinates(centerLat, centerLon, radius1, realAngle);
points.add(point);
temp = realAngle;
}
if(endAngle > 360) endAngle -= 360;
if (temp != endAngle) { //Adds the last point if the points were not evenly distributed
double[] point = getCoordinates(centerLat, centerLon, radius1, endAngle);
points.add(point);
}
//Line from the end point to the station
// double[] p2 = {centerLat,centerLon};
// points.add(p2);
double partStartAngle = heading-(fieldOfViewAngle/2);
double partEndAngle = heading+(fieldOfViewAngle/2);
if(partStartAngle > partEndAngle) partEndAngle += 360;
//Coverage to the front of the heading
partOfCircleAngle = fieldOfViewAngle/Math.round(numberOfPoints/2);
for(double angle = partStartAngle; angle <= partEndAngle; angle += partOfCircleAngle){
double realAngle = angle;
if(realAngle > 360) realAngle -= 360;
double[] point = getCoordinates(centerLat, centerLon, radius2, realAngle);
points.add(point);
temp = realAngle;
}
if(partEndAngle > 360) partEndAngle -= 360;
if (temp != partEndAngle) {
double[] point = getCoordinates(centerLat, centerLon, radius2, partEndAngle);
points.add(point);
}
// double[] point = {centerLat,centerLon}; // first point
double[] point = getCoordinates(centerLat, centerLon, radius1, startAngle);
points.add(point);
return points;
}
/**
* Calculates the radius for the circle.
*
* @param antennaHeight Height of the antenna. Either antennaHeight or antennaHeight + terrainHeight
* @param receiverHeight The height of the receiving antenna. Default: 4m (if less than 0 is given, the default is used).
* @return The radius in kilometers
*/
public static double getRoundCoverageRadius(double antennaHeight, double receiverHeight){
if(receiverHeight < 0) receiverHeight = DEFAULT_RECEIVER_HEIGHT;
return 2.5*(Math.pow(antennaHeight, 0.5) + Math.pow(receiverHeight, 0.5))*1.852;
}
public static double degrees2radians(double d) {
return d * Math.PI / 180;
}
public static double radians2degrees(double r) {
return r * 180 / Math.PI;
}
/**
* Converts the D'M.S degree to the decimal degree.
*
* @param D Degree
* @param M Minutes
* @param S Seconds
* @return Decimal degree
*/
public static double convertToDecimalDegrees(double D, double M, double S) {
return (D + M / 60 + S / 3600);
}
/**
* Returns the distance between two coordinates.
*
* @param lat1
* @param lon1
* @param lat2
* @param lon2
* @return
*/
private static double greatCircleDistance(double lat1, double lon1, double lat2, double lon2) {
lat1 = degrees2radians(lat1);
lat2 = degrees2radians(lat2);
lon1 = degrees2radians(lon1);
lon2 = degrees2radians(lon2);
double p1 = Math.cos(lat1) * Math.cos(lon1) * Math.cos(lat2) * Math.cos(lon2);
double p2 = Math.cos(lat1) * Math.sin(lon1) * Math.cos(lat2) * Math.sin(lon2);
double p3 = Math.sin(lat1) * Math.sin(lat2);
return (Math.acos(p1 + p2 + p3) * EARTH_RADIUS);
}
/**
* Returns the coordinates
*
* @param lat1 starting point (lat)
* @param lon1 starting point (lon)
* @param dist distance to the other coordinate.
* @param angle angle to the other coordinate.
*
* @return double array where index 0 has the latitude and the index 1 longitude.
*/
public static double[] getCoordinates(double lat1, double lon1, double dist, double angle) {
lat1 = degrees2radians(lat1);
lon1 = degrees2radians(lon1);
angle = degrees2radians(angle);
dist = dist / EARTH_RADIUS;
double lat = 0;
double lon = 0;
lat = Math.asin(Math.sin(lat1) * Math.cos(dist) + Math.cos(lat1) * Math.sin(dist) * Math.cos(angle));
if (Math.cos(lat) == 0 || Math.abs(Math.cos(lat)) < 0.000001) {
lon = lon1;
} else {
lon = lon1 + Math.atan2(Math.sin(angle) * Math.sin(dist) * Math.cos(lat1), Math.cos(dist) - Math.sin(lat1) * Math.sin(lat));
//lon = ((lon1 - Math.asin(Math.sin(angle) * Math.sin(dist) / Math.cos(lat)) + Math.PI) % (2 * Math.PI)) - Math.PI;
}
lat = radians2degrees(lat);
lon = radians2degrees(lon);
//System.out.println(lat + ";" + lon);
double[] coord = new double[2];
coord[0] = lat;
coord[1] = lon;
return coord;
}
/**
* Just for testing...
*
* @param args
*/
public static void main(String[] args){
List<double[]> points = getRoundCoverage(10, 4, 12.0, 55.0, 11);
for(double[] p : points){
System.out.println(p[0]+","+p[1]);
}
}
}
| true | true | public static List<double[]> getRoundInterferenceCoverage(double antennaHeight, double receiverHeight, double centerLat, double centerLon, double heading, double fieldOfViewAngle, int numberOfPoints){
List<double[]> points = new ArrayList<double[]>();
double radius1 = getRoundCoverageRadius(antennaHeight, receiverHeight);
if(numberOfPoints < 10) numberOfPoints = 10;
double partOfCircleAngle = 180.0/Math.round(numberOfPoints/2);
double radius2 = 120*1.852;
double startAngle = heading + 90;
if (startAngle > 360) {
startAngle = startAngle - 360;
}
double endAngle = heading - 90;
if (endAngle < 0) {
endAngle = 360 + endAngle; //e.g., 360 + (-60)
}
double temp = -1;
//Add line from the station to the start point:
double[] p1 = {centerLat,centerLon};
points.add(p1);
if(endAngle < startAngle) endAngle += 360;
//First, do the half circle behind the heading
for (double angle = startAngle; angle <= endAngle; angle += partOfCircleAngle){
double realAngle = angle;
if(realAngle > 360) realAngle -= 360;
double[] point = getCoordinates(centerLat, centerLon, radius1, realAngle);
points.add(point);
temp = realAngle;
}
if(endAngle > 360) endAngle -= 360;
if (temp != endAngle) { //Adds the last point if the points were not evenly distributed
double[] point = getCoordinates(centerLat, centerLon, radius1, endAngle);
points.add(point);
}
//Line from the end point to the station
// double[] p2 = {centerLat,centerLon};
// points.add(p2);
double partStartAngle = heading-(fieldOfViewAngle/2);
double partEndAngle = heading+(fieldOfViewAngle/2);
if(partStartAngle > partEndAngle) partEndAngle += 360;
//Coverage to the front of the heading
partOfCircleAngle = fieldOfViewAngle/Math.round(numberOfPoints/2);
for(double angle = partStartAngle; angle <= partEndAngle; angle += partOfCircleAngle){
double realAngle = angle;
if(realAngle > 360) realAngle -= 360;
double[] point = getCoordinates(centerLat, centerLon, radius2, realAngle);
points.add(point);
temp = realAngle;
}
if(partEndAngle > 360) partEndAngle -= 360;
if (temp != partEndAngle) {
double[] point = getCoordinates(centerLat, centerLon, radius2, partEndAngle);
points.add(point);
}
// double[] point = {centerLat,centerLon}; // first point
double[] point = getCoordinates(centerLat, centerLon, radius1, startAngle);
points.add(point);
return points;
}
| public static List<double[]> getRoundInterferenceCoverage(double antennaHeight, double receiverHeight, double centerLat, double centerLon, double heading, double fieldOfViewAngle, int numberOfPoints){
List<double[]> points = new ArrayList<double[]>();
double radius1 = getRoundCoverageRadius(antennaHeight, receiverHeight);
if(numberOfPoints < 10) numberOfPoints = 10;
double partOfCircleAngle = 180.0/Math.round(numberOfPoints/2);
double radius2 = 120*1.852;
double startAngle = heading + 90;
if (startAngle > 360) {
startAngle = startAngle - 360;
}
double endAngle = heading - 90;
if (endAngle < 0) {
endAngle = 360 + endAngle; //e.g., 360 + (-60)
}
double temp = -1;
//Add line from the station to the start point:
// double[] p1 = {centerLat,centerLon};
// points.add(p1);
if(endAngle < startAngle) endAngle += 360;
//First, do the half circle behind the heading
for (double angle = startAngle; angle <= endAngle; angle += partOfCircleAngle){
double realAngle = angle;
if(realAngle > 360) realAngle -= 360;
double[] point = getCoordinates(centerLat, centerLon, radius1, realAngle);
points.add(point);
temp = realAngle;
}
if(endAngle > 360) endAngle -= 360;
if (temp != endAngle) { //Adds the last point if the points were not evenly distributed
double[] point = getCoordinates(centerLat, centerLon, radius1, endAngle);
points.add(point);
}
//Line from the end point to the station
// double[] p2 = {centerLat,centerLon};
// points.add(p2);
double partStartAngle = heading-(fieldOfViewAngle/2);
double partEndAngle = heading+(fieldOfViewAngle/2);
if(partStartAngle > partEndAngle) partEndAngle += 360;
//Coverage to the front of the heading
partOfCircleAngle = fieldOfViewAngle/Math.round(numberOfPoints/2);
for(double angle = partStartAngle; angle <= partEndAngle; angle += partOfCircleAngle){
double realAngle = angle;
if(realAngle > 360) realAngle -= 360;
double[] point = getCoordinates(centerLat, centerLon, radius2, realAngle);
points.add(point);
temp = realAngle;
}
if(partEndAngle > 360) partEndAngle -= 360;
if (temp != partEndAngle) {
double[] point = getCoordinates(centerLat, centerLon, radius2, partEndAngle);
points.add(point);
}
// double[] point = {centerLat,centerLon}; // first point
double[] point = getCoordinates(centerLat, centerLon, radius1, startAngle);
points.add(point);
return points;
}
|
diff --git a/core/src/main/java/org/springframework/security/config/HttpSecurityBeanDefinitionParser.java b/core/src/main/java/org/springframework/security/config/HttpSecurityBeanDefinitionParser.java
index bfa42b552..cef6812ba 100644
--- a/core/src/main/java/org/springframework/security/config/HttpSecurityBeanDefinitionParser.java
+++ b/core/src/main/java/org/springframework/security/config/HttpSecurityBeanDefinitionParser.java
@@ -1,503 +1,503 @@
package org.springframework.security.config;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.security.ConfigAttributeDefinition;
import org.springframework.security.ConfigAttributeEditor;
import org.springframework.security.wrapper.SecurityContextHolderAwareRequestFilter;
import org.springframework.security.context.HttpSessionContextIntegrationFilter;
import org.springframework.security.intercept.web.DefaultFilterInvocationDefinitionSource;
import org.springframework.security.intercept.web.FilterSecurityInterceptor;
import org.springframework.security.intercept.web.RequestKey;
import org.springframework.security.securechannel.ChannelDecisionManagerImpl;
import org.springframework.security.securechannel.ChannelProcessingFilter;
import org.springframework.security.securechannel.InsecureChannelProcessor;
import org.springframework.security.securechannel.SecureChannelProcessor;
import org.springframework.security.securechannel.RetryWithHttpEntryPoint;
import org.springframework.security.securechannel.RetryWithHttpsEntryPoint;
import org.springframework.security.ui.ExceptionTranslationFilter;
import org.springframework.security.ui.SessionFixationProtectionFilter;
import org.springframework.security.ui.webapp.DefaultLoginPageGeneratingFilter;
import org.springframework.security.util.FilterChainProxy;
import org.springframework.security.util.RegexUrlPathMatcher;
import org.springframework.security.util.AntUrlPathMatcher;
import org.springframework.security.util.UrlMatcher;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
/**
* Sets up HTTP security: filter stack and protected URLs.
*
* @author Luke Taylor
* @author Ben Alex
* @version $Id$
*/
public class HttpSecurityBeanDefinitionParser implements BeanDefinitionParser {
protected final Log logger = LogFactory.getLog(getClass());
static final String ATT_REALM = "realm";
static final String DEF_REALM = "Spring Security Application";
static final String ATT_PATH_PATTERN = "pattern";
static final String ATT_SESSION_FIXATION_PROTECTION = "session-fixation-protection";
static final String OPT_SESSION_FIXATION_NO_PROTECTION = "none";
static final String OPT_SESSION_FIXATION_CLEAN_SESSION = "newSession";
static final String OPT_SESSION_FIXATION_MIGRATE_SESSION = "migrateSession";
static final String ATT_PATH_TYPE = "path-type";
static final String DEF_PATH_TYPE_ANT = "ant";
static final String OPT_PATH_TYPE_REGEX = "regex";
static final String ATT_FILTERS = "filters";
static final String OPT_FILTERS_NONE = "none";
static final String ATT_ACCESS_CONFIG = "access";
static final String ATT_REQUIRES_CHANNEL = "requires-channel";
static final String OPT_REQUIRES_HTTP = "http";
static final String OPT_REQUIRES_HTTPS = "https";
static final String OPT_ANY_CHANNEL = "any";
static final String ATT_HTTP_METHOD = "method";
static final String ATT_CREATE_SESSION = "create-session";
static final String DEF_CREATE_SESSION_IF_REQUIRED = "ifRequired";
static final String OPT_CREATE_SESSION_ALWAYS = "always";
static final String OPT_CREATE_SESSION_NEVER = "never";
static final String ATT_LOWERCASE_COMPARISONS = "lowercase-comparisons";
static final String DEF_LOWERCASE_COMPARISONS = "true";
static final String ATT_AUTO_CONFIG = "auto-config";
static final String DEF_AUTO_CONFIG = "false";
static final String ATT_SERVLET_API_PROVISION = "servlet-api-provision";
static final String DEF_SERVLET_API_PROVISION = "true";
static final String ATT_ACCESS_MGR = "access-decision-manager-ref";
static final String ATT_USER_SERVICE_REF = "user-service-ref";
public BeanDefinition parse(Element element, ParserContext parserContext) {
BeanDefinitionRegistry registry = parserContext.getRegistry();
RootBeanDefinition filterChainProxy = new RootBeanDefinition(FilterChainProxy.class);
RootBeanDefinition httpScif = new RootBeanDefinition(HttpSessionContextIntegrationFilter.class);
BeanDefinition portMapper = new PortMappingsBeanDefinitionParser().parse(
DomUtils.getChildElementByTagName(element, Elements.PORT_MAPPINGS), parserContext);
registry.registerBeanDefinition(BeanIds.PORT_MAPPER, portMapper);
RuntimeBeanReference portMapperRef = new RuntimeBeanReference(BeanIds.PORT_MAPPER);
String createSession = element.getAttribute(ATT_CREATE_SESSION);
if (OPT_CREATE_SESSION_ALWAYS.equals(createSession)) {
httpScif.getPropertyValues().addPropertyValue("allowSessionCreation", Boolean.TRUE);
httpScif.getPropertyValues().addPropertyValue("forceEagerSessionCreation", Boolean.TRUE);
} else if (OPT_CREATE_SESSION_NEVER.equals(createSession)) {
httpScif.getPropertyValues().addPropertyValue("allowSessionCreation", Boolean.FALSE);
httpScif.getPropertyValues().addPropertyValue("forceEagerSessionCreation", Boolean.FALSE);
} else {
createSession = DEF_CREATE_SESSION_IF_REQUIRED;
httpScif.getPropertyValues().addPropertyValue("allowSessionCreation", Boolean.TRUE);
httpScif.getPropertyValues().addPropertyValue("forceEagerSessionCreation", Boolean.FALSE);
}
String sessionFixationAttribute = element.getAttribute(ATT_SESSION_FIXATION_PROTECTION);
if(!StringUtils.hasText(sessionFixationAttribute)) {
sessionFixationAttribute = OPT_SESSION_FIXATION_MIGRATE_SESSION;
}
if (!sessionFixationAttribute.equals(OPT_SESSION_FIXATION_NO_PROTECTION)) {
BeanDefinitionBuilder sessionFixationFilter =
BeanDefinitionBuilder.rootBeanDefinition(SessionFixationProtectionFilter.class);
sessionFixationFilter.addPropertyValue("migrateSessionAttributes",
- sessionFixationAttribute.equals(OPT_SESSION_FIXATION_MIGRATE_SESSION));
+ Boolean.valueOf(sessionFixationAttribute.equals(OPT_SESSION_FIXATION_MIGRATE_SESSION)));
parserContext.getRegistry().registerBeanDefinition(BeanIds.SESSION_FIXATION_PROTECTION_FILTER,
sessionFixationFilter.getBeanDefinition());
}
BeanDefinitionBuilder filterSecurityInterceptorBuilder
= BeanDefinitionBuilder.rootBeanDefinition(FilterSecurityInterceptor.class);
BeanDefinitionBuilder exceptionTranslationFilterBuilder
= BeanDefinitionBuilder.rootBeanDefinition(ExceptionTranslationFilter.class);
Map filterChainMap = new LinkedHashMap();
UrlMatcher matcher = createUrlMatcher(element);
filterChainProxy.getPropertyValues().addPropertyValue("matcher", matcher);
// Add servlet-api integration filter if required
String provideServletApi = element.getAttribute(ATT_SERVLET_API_PROVISION);
if (!StringUtils.hasText(provideServletApi)) {
provideServletApi = DEF_SERVLET_API_PROVISION;
}
if ("true".equals(provideServletApi)) {
parserContext.getRegistry().registerBeanDefinition(BeanIds.SECURITY_CONTEXT_HOLDER_AWARE_REQUEST_FILTER,
new RootBeanDefinition(SecurityContextHolderAwareRequestFilter.class));
}
filterChainProxy.getPropertyValues().addPropertyValue("filterChainMap", filterChainMap);
// Set up the access manager and authentication manager references for http
String accessManagerId = element.getAttribute(ATT_ACCESS_MGR);
if (!StringUtils.hasText(accessManagerId)) {
ConfigUtils.registerDefaultAccessManagerIfNecessary(parserContext);
accessManagerId = BeanIds.ACCESS_MANAGER;
}
filterSecurityInterceptorBuilder.addPropertyValue("accessDecisionManager",
new RuntimeBeanReference(accessManagerId));
filterSecurityInterceptorBuilder.addPropertyValue("authenticationManager",
ConfigUtils.registerProviderManagerIfNecessary(parserContext));
// SEC-501 - should paths stored in request maps be converted to lower case
// true if Ant path and using lower case
boolean convertPathsToLowerCase = (matcher instanceof AntUrlPathMatcher) && matcher.requiresLowerCaseUrl();
LinkedHashMap channelRequestMap = new LinkedHashMap();
LinkedHashMap filterInvocationDefinitionMap = new LinkedHashMap();
List interceptUrlElts = DomUtils.getChildElementsByTagName(element, "intercept-url");
parseInterceptUrlsForChannelSecurityAndFilterChain(interceptUrlElts, filterChainMap, channelRequestMap,
convertPathsToLowerCase, parserContext);
parseInterceptUrlsForFilterInvocationRequestMap(interceptUrlElts, filterInvocationDefinitionMap,
convertPathsToLowerCase, parserContext);
DefaultFilterInvocationDefinitionSource interceptorFilterInvDefSource =
new DefaultFilterInvocationDefinitionSource(matcher, filterInvocationDefinitionMap);
DefaultFilterInvocationDefinitionSource channelFilterInvDefSource =
new DefaultFilterInvocationDefinitionSource(matcher, channelRequestMap);
filterSecurityInterceptorBuilder.addPropertyValue("objectDefinitionSource", interceptorFilterInvDefSource);
// Check if we need to register the channel processing beans
if (channelRequestMap.size() > 0) {
// At least one channel requirement has been specified
RootBeanDefinition channelFilter = new RootBeanDefinition(ChannelProcessingFilter.class);
channelFilter.getPropertyValues().addPropertyValue("channelDecisionManager",
new RuntimeBeanReference(BeanIds.CHANNEL_DECISION_MANAGER));
channelFilter.getPropertyValues().addPropertyValue("filterInvocationDefinitionSource",
channelFilterInvDefSource);
RootBeanDefinition channelDecisionManager = new RootBeanDefinition(ChannelDecisionManagerImpl.class);
ManagedList channelProcessors = new ManagedList(3);
RootBeanDefinition secureChannelProcessor = new RootBeanDefinition(SecureChannelProcessor.class);
RootBeanDefinition retryWithHttp = new RootBeanDefinition(RetryWithHttpEntryPoint.class);
RootBeanDefinition retryWithHttps = new RootBeanDefinition(RetryWithHttpsEntryPoint.class);
retryWithHttp.getPropertyValues().addPropertyValue("portMapper", portMapperRef);
retryWithHttps.getPropertyValues().addPropertyValue("portMapper", portMapperRef);
secureChannelProcessor.getPropertyValues().addPropertyValue("entryPoint", retryWithHttps);
RootBeanDefinition inSecureChannelProcessor = new RootBeanDefinition(InsecureChannelProcessor.class);
inSecureChannelProcessor.getPropertyValues().addPropertyValue("entryPoint", retryWithHttp);
channelProcessors.add(secureChannelProcessor);
channelProcessors.add(inSecureChannelProcessor);
channelDecisionManager.getPropertyValues().addPropertyValue("channelProcessors", channelProcessors);
registry.registerBeanDefinition(BeanIds.CHANNEL_PROCESSING_FILTER, channelFilter);
registry.registerBeanDefinition(BeanIds.CHANNEL_DECISION_MANAGER, channelDecisionManager);
}
Element sessionControlElt = DomUtils.getChildElementByTagName(element, Elements.CONCURRENT_SESSIONS);
if (sessionControlElt != null) {
new ConcurrentSessionsBeanDefinitionParser().parse(sessionControlElt, parserContext);
}
boolean autoConfig = false;
if ("true".equals(element.getAttribute(ATT_AUTO_CONFIG))) {
autoConfig = true;
}
Element anonymousElt = DomUtils.getChildElementByTagName(element, Elements.ANONYMOUS);
if (anonymousElt != null || autoConfig) {
new AnonymousBeanDefinitionParser().parse(anonymousElt, parserContext);
}
// Parse remember me before logout as RememberMeServices is also a LogoutHandler implementation.
Element rememberMeElt = DomUtils.getChildElementByTagName(element, Elements.REMEMBER_ME);
if (rememberMeElt != null || autoConfig) {
new RememberMeBeanDefinitionParser().parse(rememberMeElt, parserContext);
}
Element logoutElt = DomUtils.getChildElementByTagName(element, Elements.LOGOUT);
if (logoutElt != null || autoConfig) {
new LogoutBeanDefinitionParser().parse(logoutElt, parserContext);
}
parseBasicFormLoginAndOpenID(element, parserContext, autoConfig);
Element x509Elt = DomUtils.getChildElementByTagName(element, Elements.X509);
if (x509Elt != null) {
new X509BeanDefinitionParser().parse(x509Elt, parserContext);
}
registry.registerBeanDefinition(BeanIds.FILTER_CHAIN_PROXY, filterChainProxy);
registry.registerAlias(BeanIds.FILTER_CHAIN_PROXY, BeanIds.SPRING_SECURITY_FILTER_CHAIN);
registry.registerBeanDefinition(BeanIds.HTTP_SESSION_CONTEXT_INTEGRATION_FILTER, httpScif);
registry.registerBeanDefinition(BeanIds.EXCEPTION_TRANSLATION_FILTER, exceptionTranslationFilterBuilder.getBeanDefinition());
registry.registerBeanDefinition(BeanIds.FILTER_SECURITY_INTERCEPTOR, filterSecurityInterceptorBuilder.getBeanDefinition());
// Register the post processor which will tie up the loose ends in the configuration once the app context has been created and all beans are available.
registry.registerBeanDefinition(BeanIds.HTTP_POST_PROCESSOR, new RootBeanDefinition(HttpSecurityConfigPostProcessor.class));
return null;
}
private void parseBasicFormLoginAndOpenID(Element element, ParserContext parserContext, boolean autoConfig) {
RootBeanDefinition formLoginFilter = null;
RootBeanDefinition formLoginEntryPoint = null;
String formLoginPage = null;
RootBeanDefinition openIDFilter = null;
RootBeanDefinition openIDEntryPoint = null;
String openIDLoginPage = null;
String realm = element.getAttribute(ATT_REALM);
if (!StringUtils.hasText(realm)) {
realm = DEF_REALM;
}
Element basicAuthElt = DomUtils.getChildElementByTagName(element, Elements.BASIC_AUTH);
if (basicAuthElt != null || autoConfig) {
new BasicAuthenticationBeanDefinitionParser(realm).parse(basicAuthElt, parserContext);
}
Element formLoginElt = DomUtils.getChildElementByTagName(element, Elements.FORM_LOGIN);
if (formLoginElt != null || autoConfig) {
FormLoginBeanDefinitionParser parser = new FormLoginBeanDefinitionParser("/j_spring_security_check",
"org.springframework.security.ui.webapp.AuthenticationProcessingFilter");
parser.parse(formLoginElt, parserContext);
formLoginFilter = parser.getFilterBean();
formLoginEntryPoint = parser.getEntryPointBean();
formLoginPage = parser.getLoginPage();
}
Element openIDLoginElt = DomUtils.getChildElementByTagName(element, Elements.OPENID_LOGIN);
if (openIDLoginElt != null) {
FormLoginBeanDefinitionParser parser = new FormLoginBeanDefinitionParser("/j_spring_openid_security_check",
"org.springframework.security.ui.openid.OpenIDAuthenticationProcessingFilter");
parser.parse(openIDLoginElt, parserContext);
openIDFilter = parser.getFilterBean();
openIDEntryPoint = parser.getEntryPointBean();
openIDLoginPage = parser.getLoginPage();
BeanDefinitionBuilder openIDProviderBuilder =
BeanDefinitionBuilder.rootBeanDefinition("org.springframework.security.providers.openid.OpenIDAuthenticationProvider");
String userService = openIDLoginElt.getAttribute(ATT_USER_SERVICE_REF);
if (StringUtils.hasText(userService)) {
openIDProviderBuilder.addPropertyReference("userDetailsService", userService);
}
BeanDefinition openIDProvider = openIDProviderBuilder.getBeanDefinition();
ConfigUtils.getRegisteredProviders(parserContext).add(openIDProvider);
parserContext.getRegistry().registerBeanDefinition(BeanIds.OPEN_ID_PROVIDER, openIDProvider);
}
if (formLoginFilter == null && openIDFilter == null) {
return;
}
if (formLoginFilter != null) {
parserContext.getRegistry().registerBeanDefinition(BeanIds.FORM_LOGIN_FILTER, formLoginFilter);
parserContext.getRegistry().registerBeanDefinition(BeanIds.FORM_LOGIN_ENTRY_POINT, formLoginEntryPoint);
}
if (openIDFilter != null) {
parserContext.getRegistry().registerBeanDefinition(BeanIds.OPEN_ID_FILTER, openIDFilter);
parserContext.getRegistry().registerBeanDefinition(BeanIds.OPEN_ID_ENTRY_POINT, openIDEntryPoint);
}
// If no login page has been defined, add in the default page generator.
if (formLoginPage == null && openIDLoginPage == null) {
logger.info("No login page configured. The default internal one will be used. Use the '"
+ FormLoginBeanDefinitionParser.ATT_LOGIN_PAGE + "' attribute to set the URL of the login page.");
BeanDefinitionBuilder loginPageFilter =
BeanDefinitionBuilder.rootBeanDefinition(DefaultLoginPageGeneratingFilter.class);
if (formLoginFilter != null) {
loginPageFilter.addConstructorArg(new RuntimeBeanReference(BeanIds.FORM_LOGIN_FILTER));
}
if (openIDFilter != null) {
loginPageFilter.addConstructorArg(new RuntimeBeanReference(BeanIds.OPEN_ID_FILTER));
}
parserContext.getRegistry().registerBeanDefinition(BeanIds.DEFAULT_LOGIN_PAGE_GENERATING_FILTER,
loginPageFilter.getBeanDefinition());
}
// We need to establish the main entry point.
// Basic takes precedence if explicit element is used and no others are configured
if (basicAuthElt != null && formLoginElt == null && openIDLoginElt == null) {
parserContext.getRegistry().registerAlias(BeanIds.BASIC_AUTHENTICATION_ENTRY_POINT, BeanIds.MAIN_ENTRY_POINT);
return;
}
// If formLogin has been enabled either through an element or auto-config, then it is used if no openID login page
// has been set
if (formLoginFilter != null && openIDLoginPage == null) {
parserContext.getRegistry().registerAlias(BeanIds.FORM_LOGIN_ENTRY_POINT, BeanIds.MAIN_ENTRY_POINT);
return;
}
// Otherwise use OpenID
if (openIDFilter != null && formLoginFilter == null) {
parserContext.getRegistry().registerAlias(BeanIds.OPEN_ID_ENTRY_POINT, BeanIds.MAIN_ENTRY_POINT);
return;
}
throw new IllegalStateException("Couldn't set entry point");
}
static UrlMatcher createUrlMatcher(Element element) {
String patternType = element.getAttribute(ATT_PATH_TYPE);
if (!StringUtils.hasText(patternType)) {
patternType = DEF_PATH_TYPE_ANT;
}
boolean useRegex = patternType.equals(OPT_PATH_TYPE_REGEX);
UrlMatcher matcher = new AntUrlPathMatcher();
if (useRegex) {
matcher = new RegexUrlPathMatcher();
}
// Deal with lowercase conversion requests
String lowercaseComparisons = element.getAttribute(ATT_LOWERCASE_COMPARISONS);
if (!StringUtils.hasText(lowercaseComparisons)) {
lowercaseComparisons = null;
}
// Only change from the defaults if the attribute has been set
if ("true".equals(lowercaseComparisons)) {
if (useRegex) {
((RegexUrlPathMatcher)matcher).setRequiresLowerCaseUrl(true);
}
// Default for ant is already to force lower case
} else if ("false".equals(lowercaseComparisons)) {
if (!useRegex) {
((AntUrlPathMatcher)matcher).setRequiresLowerCaseUrl(false);
}
// Default for regex is no change
}
return matcher;
}
/**
* Parses the intercept-url elements and populates the FilterChainProxy's filter chain Map and the
* map used to create the FilterInvocationDefintionSource for the FilterSecurityInterceptor.
*/
void parseInterceptUrlsForChannelSecurityAndFilterChain(List urlElts, Map filterChainMap, Map channelRequestMap,
boolean useLowerCasePaths, ParserContext parserContext) {
Iterator urlEltsIterator = urlElts.iterator();
ConfigAttributeEditor editor = new ConfigAttributeEditor();
while (urlEltsIterator.hasNext()) {
Element urlElt = (Element) urlEltsIterator.next();
String path = urlElt.getAttribute(ATT_PATH_PATTERN);
if(!StringUtils.hasText(path)) {
parserContext.getReaderContext().error("path attribute cannot be empty or null", urlElt);
}
if (useLowerCasePaths) {
path = path.toLowerCase();
}
String requiredChannel = urlElt.getAttribute(ATT_REQUIRES_CHANNEL);
if (StringUtils.hasText(requiredChannel)) {
String channelConfigAttribute = null;
if (requiredChannel.equals(OPT_REQUIRES_HTTPS)) {
channelConfigAttribute = "REQUIRES_SECURE_CHANNEL";
} else if (requiredChannel.equals(OPT_REQUIRES_HTTP)) {
channelConfigAttribute = "REQUIRES_INSECURE_CHANNEL";
} else if (requiredChannel.equals(OPT_ANY_CHANNEL)) {
channelConfigAttribute = ChannelDecisionManagerImpl.ANY_CHANNEL;
} else {
parserContext.getReaderContext().error("Unsupported channel " + requiredChannel, urlElt);
}
editor.setAsText(channelConfigAttribute);
channelRequestMap.put(new RequestKey(path), (ConfigAttributeDefinition) editor.getValue());
}
String filters = urlElt.getAttribute(ATT_FILTERS);
if (StringUtils.hasText(filters)) {
if (!filters.equals(OPT_FILTERS_NONE)) {
parserContext.getReaderContext().error("Currently only 'none' is supported as the custom " +
"filters attribute", urlElt);
}
filterChainMap.put(path, Collections.EMPTY_LIST);
}
}
}
static void parseInterceptUrlsForFilterInvocationRequestMap(List urlElts, Map filterInvocationDefinitionMap,
boolean useLowerCasePaths, ParserContext parserContext) {
Iterator urlEltsIterator = urlElts.iterator();
ConfigAttributeEditor editor = new ConfigAttributeEditor();
while (urlEltsIterator.hasNext()) {
Element urlElt = (Element) urlEltsIterator.next();
String path = urlElt.getAttribute(ATT_PATH_PATTERN);
if(!StringUtils.hasText(path)) {
parserContext.getReaderContext().error("path attribute cannot be empty or null", urlElt);
}
if (useLowerCasePaths) {
path = path.toLowerCase();
}
String method = urlElt.getAttribute(ATT_HTTP_METHOD);
if (!StringUtils.hasText(method)) {
method = null;
}
String access = urlElt.getAttribute(ATT_ACCESS_CONFIG);
// Convert the comma-separated list of access attributes to a ConfigAttributeDefinition
if (StringUtils.hasText(access)) {
editor.setAsText(access);
filterInvocationDefinitionMap.put(new RequestKey(path, method), editor.getValue());
}
}
}
}
| true | true | public BeanDefinition parse(Element element, ParserContext parserContext) {
BeanDefinitionRegistry registry = parserContext.getRegistry();
RootBeanDefinition filterChainProxy = new RootBeanDefinition(FilterChainProxy.class);
RootBeanDefinition httpScif = new RootBeanDefinition(HttpSessionContextIntegrationFilter.class);
BeanDefinition portMapper = new PortMappingsBeanDefinitionParser().parse(
DomUtils.getChildElementByTagName(element, Elements.PORT_MAPPINGS), parserContext);
registry.registerBeanDefinition(BeanIds.PORT_MAPPER, portMapper);
RuntimeBeanReference portMapperRef = new RuntimeBeanReference(BeanIds.PORT_MAPPER);
String createSession = element.getAttribute(ATT_CREATE_SESSION);
if (OPT_CREATE_SESSION_ALWAYS.equals(createSession)) {
httpScif.getPropertyValues().addPropertyValue("allowSessionCreation", Boolean.TRUE);
httpScif.getPropertyValues().addPropertyValue("forceEagerSessionCreation", Boolean.TRUE);
} else if (OPT_CREATE_SESSION_NEVER.equals(createSession)) {
httpScif.getPropertyValues().addPropertyValue("allowSessionCreation", Boolean.FALSE);
httpScif.getPropertyValues().addPropertyValue("forceEagerSessionCreation", Boolean.FALSE);
} else {
createSession = DEF_CREATE_SESSION_IF_REQUIRED;
httpScif.getPropertyValues().addPropertyValue("allowSessionCreation", Boolean.TRUE);
httpScif.getPropertyValues().addPropertyValue("forceEagerSessionCreation", Boolean.FALSE);
}
String sessionFixationAttribute = element.getAttribute(ATT_SESSION_FIXATION_PROTECTION);
if(!StringUtils.hasText(sessionFixationAttribute)) {
sessionFixationAttribute = OPT_SESSION_FIXATION_MIGRATE_SESSION;
}
if (!sessionFixationAttribute.equals(OPT_SESSION_FIXATION_NO_PROTECTION)) {
BeanDefinitionBuilder sessionFixationFilter =
BeanDefinitionBuilder.rootBeanDefinition(SessionFixationProtectionFilter.class);
sessionFixationFilter.addPropertyValue("migrateSessionAttributes",
sessionFixationAttribute.equals(OPT_SESSION_FIXATION_MIGRATE_SESSION));
parserContext.getRegistry().registerBeanDefinition(BeanIds.SESSION_FIXATION_PROTECTION_FILTER,
sessionFixationFilter.getBeanDefinition());
}
BeanDefinitionBuilder filterSecurityInterceptorBuilder
= BeanDefinitionBuilder.rootBeanDefinition(FilterSecurityInterceptor.class);
BeanDefinitionBuilder exceptionTranslationFilterBuilder
= BeanDefinitionBuilder.rootBeanDefinition(ExceptionTranslationFilter.class);
Map filterChainMap = new LinkedHashMap();
UrlMatcher matcher = createUrlMatcher(element);
filterChainProxy.getPropertyValues().addPropertyValue("matcher", matcher);
// Add servlet-api integration filter if required
String provideServletApi = element.getAttribute(ATT_SERVLET_API_PROVISION);
if (!StringUtils.hasText(provideServletApi)) {
provideServletApi = DEF_SERVLET_API_PROVISION;
}
if ("true".equals(provideServletApi)) {
parserContext.getRegistry().registerBeanDefinition(BeanIds.SECURITY_CONTEXT_HOLDER_AWARE_REQUEST_FILTER,
new RootBeanDefinition(SecurityContextHolderAwareRequestFilter.class));
}
filterChainProxy.getPropertyValues().addPropertyValue("filterChainMap", filterChainMap);
// Set up the access manager and authentication manager references for http
String accessManagerId = element.getAttribute(ATT_ACCESS_MGR);
if (!StringUtils.hasText(accessManagerId)) {
ConfigUtils.registerDefaultAccessManagerIfNecessary(parserContext);
accessManagerId = BeanIds.ACCESS_MANAGER;
}
filterSecurityInterceptorBuilder.addPropertyValue("accessDecisionManager",
new RuntimeBeanReference(accessManagerId));
filterSecurityInterceptorBuilder.addPropertyValue("authenticationManager",
ConfigUtils.registerProviderManagerIfNecessary(parserContext));
// SEC-501 - should paths stored in request maps be converted to lower case
// true if Ant path and using lower case
boolean convertPathsToLowerCase = (matcher instanceof AntUrlPathMatcher) && matcher.requiresLowerCaseUrl();
LinkedHashMap channelRequestMap = new LinkedHashMap();
LinkedHashMap filterInvocationDefinitionMap = new LinkedHashMap();
List interceptUrlElts = DomUtils.getChildElementsByTagName(element, "intercept-url");
parseInterceptUrlsForChannelSecurityAndFilterChain(interceptUrlElts, filterChainMap, channelRequestMap,
convertPathsToLowerCase, parserContext);
parseInterceptUrlsForFilterInvocationRequestMap(interceptUrlElts, filterInvocationDefinitionMap,
convertPathsToLowerCase, parserContext);
DefaultFilterInvocationDefinitionSource interceptorFilterInvDefSource =
new DefaultFilterInvocationDefinitionSource(matcher, filterInvocationDefinitionMap);
DefaultFilterInvocationDefinitionSource channelFilterInvDefSource =
new DefaultFilterInvocationDefinitionSource(matcher, channelRequestMap);
filterSecurityInterceptorBuilder.addPropertyValue("objectDefinitionSource", interceptorFilterInvDefSource);
// Check if we need to register the channel processing beans
if (channelRequestMap.size() > 0) {
// At least one channel requirement has been specified
RootBeanDefinition channelFilter = new RootBeanDefinition(ChannelProcessingFilter.class);
channelFilter.getPropertyValues().addPropertyValue("channelDecisionManager",
new RuntimeBeanReference(BeanIds.CHANNEL_DECISION_MANAGER));
channelFilter.getPropertyValues().addPropertyValue("filterInvocationDefinitionSource",
channelFilterInvDefSource);
RootBeanDefinition channelDecisionManager = new RootBeanDefinition(ChannelDecisionManagerImpl.class);
ManagedList channelProcessors = new ManagedList(3);
RootBeanDefinition secureChannelProcessor = new RootBeanDefinition(SecureChannelProcessor.class);
RootBeanDefinition retryWithHttp = new RootBeanDefinition(RetryWithHttpEntryPoint.class);
RootBeanDefinition retryWithHttps = new RootBeanDefinition(RetryWithHttpsEntryPoint.class);
retryWithHttp.getPropertyValues().addPropertyValue("portMapper", portMapperRef);
retryWithHttps.getPropertyValues().addPropertyValue("portMapper", portMapperRef);
secureChannelProcessor.getPropertyValues().addPropertyValue("entryPoint", retryWithHttps);
RootBeanDefinition inSecureChannelProcessor = new RootBeanDefinition(InsecureChannelProcessor.class);
inSecureChannelProcessor.getPropertyValues().addPropertyValue("entryPoint", retryWithHttp);
channelProcessors.add(secureChannelProcessor);
channelProcessors.add(inSecureChannelProcessor);
channelDecisionManager.getPropertyValues().addPropertyValue("channelProcessors", channelProcessors);
registry.registerBeanDefinition(BeanIds.CHANNEL_PROCESSING_FILTER, channelFilter);
registry.registerBeanDefinition(BeanIds.CHANNEL_DECISION_MANAGER, channelDecisionManager);
}
Element sessionControlElt = DomUtils.getChildElementByTagName(element, Elements.CONCURRENT_SESSIONS);
if (sessionControlElt != null) {
new ConcurrentSessionsBeanDefinitionParser().parse(sessionControlElt, parserContext);
}
boolean autoConfig = false;
if ("true".equals(element.getAttribute(ATT_AUTO_CONFIG))) {
autoConfig = true;
}
Element anonymousElt = DomUtils.getChildElementByTagName(element, Elements.ANONYMOUS);
if (anonymousElt != null || autoConfig) {
new AnonymousBeanDefinitionParser().parse(anonymousElt, parserContext);
}
// Parse remember me before logout as RememberMeServices is also a LogoutHandler implementation.
Element rememberMeElt = DomUtils.getChildElementByTagName(element, Elements.REMEMBER_ME);
if (rememberMeElt != null || autoConfig) {
new RememberMeBeanDefinitionParser().parse(rememberMeElt, parserContext);
}
Element logoutElt = DomUtils.getChildElementByTagName(element, Elements.LOGOUT);
if (logoutElt != null || autoConfig) {
new LogoutBeanDefinitionParser().parse(logoutElt, parserContext);
}
parseBasicFormLoginAndOpenID(element, parserContext, autoConfig);
Element x509Elt = DomUtils.getChildElementByTagName(element, Elements.X509);
if (x509Elt != null) {
new X509BeanDefinitionParser().parse(x509Elt, parserContext);
}
registry.registerBeanDefinition(BeanIds.FILTER_CHAIN_PROXY, filterChainProxy);
registry.registerAlias(BeanIds.FILTER_CHAIN_PROXY, BeanIds.SPRING_SECURITY_FILTER_CHAIN);
registry.registerBeanDefinition(BeanIds.HTTP_SESSION_CONTEXT_INTEGRATION_FILTER, httpScif);
registry.registerBeanDefinition(BeanIds.EXCEPTION_TRANSLATION_FILTER, exceptionTranslationFilterBuilder.getBeanDefinition());
registry.registerBeanDefinition(BeanIds.FILTER_SECURITY_INTERCEPTOR, filterSecurityInterceptorBuilder.getBeanDefinition());
// Register the post processor which will tie up the loose ends in the configuration once the app context has been created and all beans are available.
registry.registerBeanDefinition(BeanIds.HTTP_POST_PROCESSOR, new RootBeanDefinition(HttpSecurityConfigPostProcessor.class));
return null;
}
| public BeanDefinition parse(Element element, ParserContext parserContext) {
BeanDefinitionRegistry registry = parserContext.getRegistry();
RootBeanDefinition filterChainProxy = new RootBeanDefinition(FilterChainProxy.class);
RootBeanDefinition httpScif = new RootBeanDefinition(HttpSessionContextIntegrationFilter.class);
BeanDefinition portMapper = new PortMappingsBeanDefinitionParser().parse(
DomUtils.getChildElementByTagName(element, Elements.PORT_MAPPINGS), parserContext);
registry.registerBeanDefinition(BeanIds.PORT_MAPPER, portMapper);
RuntimeBeanReference portMapperRef = new RuntimeBeanReference(BeanIds.PORT_MAPPER);
String createSession = element.getAttribute(ATT_CREATE_SESSION);
if (OPT_CREATE_SESSION_ALWAYS.equals(createSession)) {
httpScif.getPropertyValues().addPropertyValue("allowSessionCreation", Boolean.TRUE);
httpScif.getPropertyValues().addPropertyValue("forceEagerSessionCreation", Boolean.TRUE);
} else if (OPT_CREATE_SESSION_NEVER.equals(createSession)) {
httpScif.getPropertyValues().addPropertyValue("allowSessionCreation", Boolean.FALSE);
httpScif.getPropertyValues().addPropertyValue("forceEagerSessionCreation", Boolean.FALSE);
} else {
createSession = DEF_CREATE_SESSION_IF_REQUIRED;
httpScif.getPropertyValues().addPropertyValue("allowSessionCreation", Boolean.TRUE);
httpScif.getPropertyValues().addPropertyValue("forceEagerSessionCreation", Boolean.FALSE);
}
String sessionFixationAttribute = element.getAttribute(ATT_SESSION_FIXATION_PROTECTION);
if(!StringUtils.hasText(sessionFixationAttribute)) {
sessionFixationAttribute = OPT_SESSION_FIXATION_MIGRATE_SESSION;
}
if (!sessionFixationAttribute.equals(OPT_SESSION_FIXATION_NO_PROTECTION)) {
BeanDefinitionBuilder sessionFixationFilter =
BeanDefinitionBuilder.rootBeanDefinition(SessionFixationProtectionFilter.class);
sessionFixationFilter.addPropertyValue("migrateSessionAttributes",
Boolean.valueOf(sessionFixationAttribute.equals(OPT_SESSION_FIXATION_MIGRATE_SESSION)));
parserContext.getRegistry().registerBeanDefinition(BeanIds.SESSION_FIXATION_PROTECTION_FILTER,
sessionFixationFilter.getBeanDefinition());
}
BeanDefinitionBuilder filterSecurityInterceptorBuilder
= BeanDefinitionBuilder.rootBeanDefinition(FilterSecurityInterceptor.class);
BeanDefinitionBuilder exceptionTranslationFilterBuilder
= BeanDefinitionBuilder.rootBeanDefinition(ExceptionTranslationFilter.class);
Map filterChainMap = new LinkedHashMap();
UrlMatcher matcher = createUrlMatcher(element);
filterChainProxy.getPropertyValues().addPropertyValue("matcher", matcher);
// Add servlet-api integration filter if required
String provideServletApi = element.getAttribute(ATT_SERVLET_API_PROVISION);
if (!StringUtils.hasText(provideServletApi)) {
provideServletApi = DEF_SERVLET_API_PROVISION;
}
if ("true".equals(provideServletApi)) {
parserContext.getRegistry().registerBeanDefinition(BeanIds.SECURITY_CONTEXT_HOLDER_AWARE_REQUEST_FILTER,
new RootBeanDefinition(SecurityContextHolderAwareRequestFilter.class));
}
filterChainProxy.getPropertyValues().addPropertyValue("filterChainMap", filterChainMap);
// Set up the access manager and authentication manager references for http
String accessManagerId = element.getAttribute(ATT_ACCESS_MGR);
if (!StringUtils.hasText(accessManagerId)) {
ConfigUtils.registerDefaultAccessManagerIfNecessary(parserContext);
accessManagerId = BeanIds.ACCESS_MANAGER;
}
filterSecurityInterceptorBuilder.addPropertyValue("accessDecisionManager",
new RuntimeBeanReference(accessManagerId));
filterSecurityInterceptorBuilder.addPropertyValue("authenticationManager",
ConfigUtils.registerProviderManagerIfNecessary(parserContext));
// SEC-501 - should paths stored in request maps be converted to lower case
// true if Ant path and using lower case
boolean convertPathsToLowerCase = (matcher instanceof AntUrlPathMatcher) && matcher.requiresLowerCaseUrl();
LinkedHashMap channelRequestMap = new LinkedHashMap();
LinkedHashMap filterInvocationDefinitionMap = new LinkedHashMap();
List interceptUrlElts = DomUtils.getChildElementsByTagName(element, "intercept-url");
parseInterceptUrlsForChannelSecurityAndFilterChain(interceptUrlElts, filterChainMap, channelRequestMap,
convertPathsToLowerCase, parserContext);
parseInterceptUrlsForFilterInvocationRequestMap(interceptUrlElts, filterInvocationDefinitionMap,
convertPathsToLowerCase, parserContext);
DefaultFilterInvocationDefinitionSource interceptorFilterInvDefSource =
new DefaultFilterInvocationDefinitionSource(matcher, filterInvocationDefinitionMap);
DefaultFilterInvocationDefinitionSource channelFilterInvDefSource =
new DefaultFilterInvocationDefinitionSource(matcher, channelRequestMap);
filterSecurityInterceptorBuilder.addPropertyValue("objectDefinitionSource", interceptorFilterInvDefSource);
// Check if we need to register the channel processing beans
if (channelRequestMap.size() > 0) {
// At least one channel requirement has been specified
RootBeanDefinition channelFilter = new RootBeanDefinition(ChannelProcessingFilter.class);
channelFilter.getPropertyValues().addPropertyValue("channelDecisionManager",
new RuntimeBeanReference(BeanIds.CHANNEL_DECISION_MANAGER));
channelFilter.getPropertyValues().addPropertyValue("filterInvocationDefinitionSource",
channelFilterInvDefSource);
RootBeanDefinition channelDecisionManager = new RootBeanDefinition(ChannelDecisionManagerImpl.class);
ManagedList channelProcessors = new ManagedList(3);
RootBeanDefinition secureChannelProcessor = new RootBeanDefinition(SecureChannelProcessor.class);
RootBeanDefinition retryWithHttp = new RootBeanDefinition(RetryWithHttpEntryPoint.class);
RootBeanDefinition retryWithHttps = new RootBeanDefinition(RetryWithHttpsEntryPoint.class);
retryWithHttp.getPropertyValues().addPropertyValue("portMapper", portMapperRef);
retryWithHttps.getPropertyValues().addPropertyValue("portMapper", portMapperRef);
secureChannelProcessor.getPropertyValues().addPropertyValue("entryPoint", retryWithHttps);
RootBeanDefinition inSecureChannelProcessor = new RootBeanDefinition(InsecureChannelProcessor.class);
inSecureChannelProcessor.getPropertyValues().addPropertyValue("entryPoint", retryWithHttp);
channelProcessors.add(secureChannelProcessor);
channelProcessors.add(inSecureChannelProcessor);
channelDecisionManager.getPropertyValues().addPropertyValue("channelProcessors", channelProcessors);
registry.registerBeanDefinition(BeanIds.CHANNEL_PROCESSING_FILTER, channelFilter);
registry.registerBeanDefinition(BeanIds.CHANNEL_DECISION_MANAGER, channelDecisionManager);
}
Element sessionControlElt = DomUtils.getChildElementByTagName(element, Elements.CONCURRENT_SESSIONS);
if (sessionControlElt != null) {
new ConcurrentSessionsBeanDefinitionParser().parse(sessionControlElt, parserContext);
}
boolean autoConfig = false;
if ("true".equals(element.getAttribute(ATT_AUTO_CONFIG))) {
autoConfig = true;
}
Element anonymousElt = DomUtils.getChildElementByTagName(element, Elements.ANONYMOUS);
if (anonymousElt != null || autoConfig) {
new AnonymousBeanDefinitionParser().parse(anonymousElt, parserContext);
}
// Parse remember me before logout as RememberMeServices is also a LogoutHandler implementation.
Element rememberMeElt = DomUtils.getChildElementByTagName(element, Elements.REMEMBER_ME);
if (rememberMeElt != null || autoConfig) {
new RememberMeBeanDefinitionParser().parse(rememberMeElt, parserContext);
}
Element logoutElt = DomUtils.getChildElementByTagName(element, Elements.LOGOUT);
if (logoutElt != null || autoConfig) {
new LogoutBeanDefinitionParser().parse(logoutElt, parserContext);
}
parseBasicFormLoginAndOpenID(element, parserContext, autoConfig);
Element x509Elt = DomUtils.getChildElementByTagName(element, Elements.X509);
if (x509Elt != null) {
new X509BeanDefinitionParser().parse(x509Elt, parserContext);
}
registry.registerBeanDefinition(BeanIds.FILTER_CHAIN_PROXY, filterChainProxy);
registry.registerAlias(BeanIds.FILTER_CHAIN_PROXY, BeanIds.SPRING_SECURITY_FILTER_CHAIN);
registry.registerBeanDefinition(BeanIds.HTTP_SESSION_CONTEXT_INTEGRATION_FILTER, httpScif);
registry.registerBeanDefinition(BeanIds.EXCEPTION_TRANSLATION_FILTER, exceptionTranslationFilterBuilder.getBeanDefinition());
registry.registerBeanDefinition(BeanIds.FILTER_SECURITY_INTERCEPTOR, filterSecurityInterceptorBuilder.getBeanDefinition());
// Register the post processor which will tie up the loose ends in the configuration once the app context has been created and all beans are available.
registry.registerBeanDefinition(BeanIds.HTTP_POST_PROCESSOR, new RootBeanDefinition(HttpSecurityConfigPostProcessor.class));
return null;
}
|
diff --git a/jamwiki-web/src/main/java/org/jamwiki/db/WikiDatabase.java b/jamwiki-web/src/main/java/org/jamwiki/db/WikiDatabase.java
index a26bf32f..4aa714ac 100644
--- a/jamwiki-web/src/main/java/org/jamwiki/db/WikiDatabase.java
+++ b/jamwiki-web/src/main/java/org/jamwiki/db/WikiDatabase.java
@@ -1,403 +1,421 @@
/**
* 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.db;
import java.io.File;
import java.sql.Connection;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.Vector;
import org.apache.commons.lang.StringUtils;
import org.jamwiki.Environment;
import org.jamwiki.WikiBase;
import org.jamwiki.model.Role;
import org.jamwiki.model.Topic;
import org.jamwiki.model.TopicVersion;
import org.jamwiki.model.VirtualWiki;
import org.jamwiki.model.WikiGroup;
import org.jamwiki.model.WikiUser;
import org.jamwiki.model.WikiUserInfo;
import org.jamwiki.parser.ParserUtil;
import org.jamwiki.parser.ParserOutput;
import org.jamwiki.utils.WikiLogger;
import org.jamwiki.utils.WikiUtil;
/**
* This class contains general database utility methods that are useful for a
* variety of JAMWiki database functions, including setup and upgrades.
*/
public class WikiDatabase {
private static String CONNECTION_VALIDATION_QUERY = null;
private static String EXISTENCE_VALIDATION_QUERY = null;
private static final WikiLogger logger = WikiLogger.getLogger(WikiDatabase.class.getName());
/**
*
*/
private WikiDatabase() {
}
/**
* Dump the database to a CSV file. This is an HSQL-specific method useful
* for individuals who want to convert from HSQL to another database.
*/
public static void exportToCsv() throws Exception {
if (!(WikiBase.getDataHandler() instanceof HSqlDataHandler)) {
throw new IllegalStateException("Exporting to CSV is allowed only when the wiki is configured to use the internal database setting.");
}
Connection conn = null;
WikiPreparedStatement stmt = null;
String sql = null;
String exportTableName = null;
String[] tableNames = {
"jam_category",
"jam_group",
"jam_recent_change",
"jam_role_map",
"jam_role",
"jam_topic",
"jam_topic_version",
"jam_virtual_wiki",
"jam_watchlist",
"jam_file",
"jam_file_version",
"jam_wiki_user",
"jam_wiki_user_info"
};
+ String csvDirectory = new File(Environment.getValue(Environment.PROP_BASE_FILE_DIR), "database").getPath();
+ File csvFile = null;
try {
conn = WikiDatabase.getConnection(null);
+ // make sure CSV files are encoded UTF-8
+ // TODO: this does not seem to be working currently - HSQL bug?
+ sql = "set property \"textdb.encoding\" 'UTF-8'";
+ stmt = new WikiPreparedStatement(sql);
+ stmt.executeUpdate();
for (int i=0; i < tableNames.length; i++) {
- // HSQL will not create the CSV file if a file of the same name exists,
- // so first drop any existing table that may have previously been exported
exportTableName = tableNames[i] + "_export";
+ // first drop any pre-existing CSV database files.
sql = "drop table " + exportTableName + " if exists";
stmt = new WikiPreparedStatement(sql);
stmt.executeUpdate();
- // FIXME - if the CSV file already exists then the SQL below appends to it,
- // which is wrong.
+ // now delete the CSV file if it exists
+ csvFile = new File(csvDirectory, exportTableName + ".csv");
+ if (csvFile.exists()) {
+ if (csvFile.delete()) {
+ logger.info("Deleted existing CSV file: " + csvFile.getPath());
+ } else {
+ logger.warning("Could not delete existing CSV file: " + csvFile.getPath());
+ }
+ }
+ // create the CSV files
sql = "select * into text " + exportTableName + " from " + tableNames[i];
stmt = new WikiPreparedStatement(sql);
stmt.executeUpdate();
}
+ // rebuild the data files to make sure everything is committed to disk
+ sql = "checkpoint";
+ stmt = new WikiPreparedStatement(sql);
+ stmt.executeUpdate();
} catch (Exception e) {
DatabaseConnection.handleErrors(conn);
throw e;
} finally {
WikiDatabase.releaseConnection(conn);
}
}
/**
*
*/
private static Connection getConnection() throws Exception {
// add a connection to the conn array. BE SURE TO RELEASE IT!
Connection conn = DatabaseConnection.getConnection();
conn.setAutoCommit(false);
return conn;
}
/**
*
*/
protected static Connection getConnection(Object transactionObject) throws Exception {
if (transactionObject instanceof Connection) {
return (Connection)transactionObject;
}
return WikiDatabase.getConnection();
}
/**
*
*/
protected static String getConnectionValidationQuery() {
return (!StringUtils.isBlank(CONNECTION_VALIDATION_QUERY)) ? CONNECTION_VALIDATION_QUERY : null;
}
/**
*
*/
protected static String getExistenceValidationQuery() {
return (!StringUtils.isBlank(EXISTENCE_VALIDATION_QUERY)) ? EXISTENCE_VALIDATION_QUERY : null;
}
/**
*
*/
public synchronized static void initialize() {
try {
WikiDatabase.CONNECTION_VALIDATION_QUERY = WikiDatabase.queryHandler().connectionValidationQuery();
WikiDatabase.EXISTENCE_VALIDATION_QUERY = WikiDatabase.queryHandler().existenceValidationQuery();
// initialize connection pool in its own try-catch to avoid an error
// causing property values not to be saved.
DatabaseConnection.setPoolInitialized(false);
} catch (Exception e) {
logger.severe("Unable to initialize database", e);
}
}
public synchronized static void shutdown() {
try {
DatabaseConnection.closeConnectionPool();
} catch (Exception e) {
logger.severe("Unable to close the connection pool on shutdown", e);
}
}
/**
* This method causes all existing data to be deleted from the Wiki. Use only
* when totally re-initializing a system. To reiterate: CALLING THIS METHOD WILL
* DELETE ALL WIKI DATA!
*/
protected static void purgeData(Connection conn) throws Exception {
// BOOM! Everything gone...
WikiDatabase.queryHandler().dropTables(conn);
try {
// re-create empty tables
WikiDatabase.queryHandler().createTables(conn);
} catch (Exception e) {
// creation failure, don't leave tables half-committed
WikiDatabase.queryHandler().dropTables(conn);
}
}
/**
*
*/
protected static QueryHandler queryHandler() throws Exception {
// FIXME - this is ugly
if (WikiBase.getDataHandler() instanceof AnsiDataHandler) {
AnsiDataHandler dataHandler = (AnsiDataHandler)WikiBase.getDataHandler();
return dataHandler.queryHandler();
}
throw new Exception("Unable to determine query handler");
}
/**
*
*/
protected static void releaseConnection(Connection conn, Object transactionObject) throws Exception {
if (transactionObject instanceof Connection) {
// transaction objects will be released elsewhere
return;
}
WikiDatabase.releaseConnection(conn);
}
/**
*
*/
private static void releaseConnection(Connection conn) throws Exception {
if (conn == null) {
return;
}
try {
conn.commit();
} finally {
DatabaseConnection.closeConnection(conn);
}
}
/**
*
*/
protected static void setup(Locale locale, WikiUser user) throws Exception {
Connection conn = null;
try {
try {
conn = WikiDatabase.getConnection();
// set up tables
WikiDatabase.queryHandler().createTables(conn);
} catch (Exception e) {
logger.severe("Unable to set up database tables", e);
// clean up anything that might have been created
WikiDatabase.queryHandler().dropTables(conn);
throw e;
}
try {
WikiDatabase.setupDefaultVirtualWiki(conn);
WikiDatabase.setupRoles(conn);
WikiDatabase.setupGroups(conn);
WikiDatabase.setupAdminUser(user, conn);
WikiDatabase.setupSpecialPages(locale, user, conn);
} catch (Exception e) {
DatabaseConnection.handleErrors(conn);
throw e;
}
} finally {
WikiDatabase.releaseConnection(conn);
}
}
/**
*
*/
private static void setupAdminUser(WikiUser user, Connection conn) throws Exception {
if (user == null) {
throw new IllegalArgumentException("Cannot pass null or anonymous WikiUser object to setupAdminUser");
}
if (WikiBase.getDataHandler().lookupWikiUser(user.getUserId(), conn) != null) {
logger.warning("Admin user already exists");
}
WikiUserInfo userInfo = null;
if (WikiBase.getUserHandler().isWriteable()) {
userInfo = new WikiUserInfo();
userInfo.setEncodedPassword(user.getPassword());
userInfo.setUsername(user.getUsername());
userInfo.setUserId(user.getUserId());
}
WikiBase.getDataHandler().writeWikiUser(user, userInfo, conn);
Vector roles = new Vector();
roles.add(Role.ROLE_ADMIN.getAuthority());
roles.add(Role.ROLE_SYSADMIN.getAuthority());
roles.add(Role.ROLE_TRANSLATE.getAuthority());
WikiBase.getDataHandler().writeRoleMapUser(user.getUserId(), roles, conn);
}
/**
*
*/
public static void setupDefaultDatabase(Properties props) {
props.setProperty(Environment.PROP_DB_DRIVER, "org.hsqldb.jdbcDriver");
props.setProperty(Environment.PROP_DB_TYPE, WikiBase.DATA_HANDLER_HSQL);
props.setProperty(Environment.PROP_DB_USERNAME, "sa");
props.setProperty(Environment.PROP_DB_PASSWORD, "");
File file = new File(props.getProperty(Environment.PROP_BASE_FILE_DIR), "database");
if (!file.exists()) {
file.mkdirs();
}
String url = "jdbc:hsqldb:file:" + new File(file.getPath(), "jamwiki").getPath() + ";shutdown=true";
props.setProperty(Environment.PROP_DB_URL, url);
}
/**
*
*/
private static void setupDefaultVirtualWiki(Connection conn) throws Exception {
VirtualWiki virtualWiki = new VirtualWiki();
virtualWiki.setName(WikiBase.DEFAULT_VWIKI);
virtualWiki.setDefaultTopicName(Environment.getValue(Environment.PROP_BASE_DEFAULT_TOPIC));
WikiBase.getDataHandler().writeVirtualWiki(virtualWiki, conn);
}
/**
*
*/
protected static void setupGroups(Connection conn) throws Exception {
WikiGroup group = new WikiGroup();
group.setName(WikiGroup.GROUP_ANONYMOUS);
// FIXME - use message key
group.setDescription("All non-logged in users are automatically assigned to the anonymous group.");
WikiBase.getDataHandler().writeWikiGroup(group, conn);
List anonymousRoles = new Vector();
anonymousRoles.add(Role.ROLE_EDIT_EXISTING.getAuthority());
anonymousRoles.add(Role.ROLE_EDIT_NEW.getAuthority());
anonymousRoles.add(Role.ROLE_UPLOAD.getAuthority());
anonymousRoles.add(Role.ROLE_VIEW.getAuthority());
WikiBase.getDataHandler().writeRoleMapGroup(group.getGroupId(), anonymousRoles, conn);
group = new WikiGroup();
group.setName(WikiGroup.GROUP_REGISTERED_USER);
// FIXME - use message key
group.setDescription("All logged in users are automatically assigned to the registered user group.");
WikiBase.getDataHandler().writeWikiGroup(group, conn);
List userRoles = new Vector();
userRoles.add(Role.ROLE_EDIT_EXISTING.getAuthority());
userRoles.add(Role.ROLE_EDIT_NEW.getAuthority());
userRoles.add(Role.ROLE_MOVE.getAuthority());
userRoles.add(Role.ROLE_UPLOAD.getAuthority());
userRoles.add(Role.ROLE_VIEW.getAuthority());
WikiBase.getDataHandler().writeRoleMapGroup(group.getGroupId(), userRoles, conn);
}
/**
*
*/
protected static void setupRoles(Connection conn) throws Exception {
Role role = Role.ROLE_ADMIN;
// FIXME - use message key
role.setDescription("Provides the ability to perform wiki maintenance tasks not available to normal users.");
WikiBase.getDataHandler().writeRole(role, conn, false);
role = Role.ROLE_EDIT_EXISTING;
// FIXME - use message key
role.setDescription("Allows a user to edit an existing topic.");
WikiBase.getDataHandler().writeRole(role, conn, false);
role = Role.ROLE_EDIT_NEW;
// FIXME - use message key
role.setDescription("Allows a user to create a new topic.");
WikiBase.getDataHandler().writeRole(role, conn, false);
role = Role.ROLE_MOVE;
// FIXME - use message key
role.setDescription("Allows a user to move a topic to a different name.");
WikiBase.getDataHandler().writeRole(role, conn, false);
role = Role.ROLE_SYSADMIN;
// FIXME - use message key
role.setDescription("Allows access to set database parameters, modify parser settings, and set other wiki system settings.");
WikiBase.getDataHandler().writeRole(role, conn, false);
role = Role.ROLE_TRANSLATE;
// FIXME - use message key
role.setDescription("Allows access to the translation tool used for modifying the values of message keys used to display text on the wiki.");
WikiBase.getDataHandler().writeRole(role, conn, false);
role = Role.ROLE_UPLOAD;
// FIXME - use message key
role.setDescription("Allows a user to upload a file to the wiki.");
WikiBase.getDataHandler().writeRole(role, conn, false);
role = Role.ROLE_VIEW;
// FIXME - use message key
role.setDescription("Allows a user to view topics on the wiki.");
WikiBase.getDataHandler().writeRole(role, conn, false);
}
/**
*
*/
protected static void setupSpecialPage(Locale locale, String virtualWiki, String topicName, WikiUser user, boolean adminOnly, Connection conn) throws Exception {
logger.info("Setting up special page " + virtualWiki + " / " + topicName);
if (user == null) {
throw new IllegalArgumentException("Cannot pass null WikiUser object to setupSpecialPage");
}
String contents = WikiUtil.readSpecialPage(locale, topicName);
Topic topic = new Topic();
topic.setName(topicName);
topic.setVirtualWiki(virtualWiki);
topic.setTopicContent(contents);
topic.setAdminOnly(adminOnly);
// FIXME - hard coding
TopicVersion topicVersion = new TopicVersion(user, user.getLastLoginIpAddress(), "Automatically created by system setup", contents);
// FIXME - it is not connection-safe to parse for metadata since we are already holding a connection
// ParserOutput parserOutput = ParserUtil.parserOutput(topic.getTopicContent(), virtualWiki, topicName);
// WikiBase.getDataHandler().writeTopic(topic, topicVersion, parserOutput.getCategories(), parserOutput.getLinks(), true, conn);
WikiBase.getDataHandler().writeTopic(topic, topicVersion, null, null, true, conn);
}
/**
*
*/
private static void setupSpecialPages(Locale locale, WikiUser user, Connection conn) throws Exception {
List all = WikiBase.getDataHandler().getVirtualWikiList(conn);
for (Iterator iterator = all.iterator(); iterator.hasNext();) {
VirtualWiki virtualWiki = (VirtualWiki)iterator.next();
// create the default topics
setupSpecialPage(locale, virtualWiki.getName(), WikiBase.SPECIAL_PAGE_STARTING_POINTS, user, false, conn);
setupSpecialPage(locale, virtualWiki.getName(), WikiBase.SPECIAL_PAGE_LEFT_MENU, user, true, conn);
setupSpecialPage(locale, virtualWiki.getName(), WikiBase.SPECIAL_PAGE_BOTTOM_AREA, user, true, conn);
setupSpecialPage(locale, virtualWiki.getName(), WikiBase.SPECIAL_PAGE_STYLESHEET, user, true, conn);
}
}
}
| false | true | public static void exportToCsv() throws Exception {
if (!(WikiBase.getDataHandler() instanceof HSqlDataHandler)) {
throw new IllegalStateException("Exporting to CSV is allowed only when the wiki is configured to use the internal database setting.");
}
Connection conn = null;
WikiPreparedStatement stmt = null;
String sql = null;
String exportTableName = null;
String[] tableNames = {
"jam_category",
"jam_group",
"jam_recent_change",
"jam_role_map",
"jam_role",
"jam_topic",
"jam_topic_version",
"jam_virtual_wiki",
"jam_watchlist",
"jam_file",
"jam_file_version",
"jam_wiki_user",
"jam_wiki_user_info"
};
try {
conn = WikiDatabase.getConnection(null);
for (int i=0; i < tableNames.length; i++) {
// HSQL will not create the CSV file if a file of the same name exists,
// so first drop any existing table that may have previously been exported
exportTableName = tableNames[i] + "_export";
sql = "drop table " + exportTableName + " if exists";
stmt = new WikiPreparedStatement(sql);
stmt.executeUpdate();
// FIXME - if the CSV file already exists then the SQL below appends to it,
// which is wrong.
sql = "select * into text " + exportTableName + " from " + tableNames[i];
stmt = new WikiPreparedStatement(sql);
stmt.executeUpdate();
}
} catch (Exception e) {
DatabaseConnection.handleErrors(conn);
throw e;
} finally {
WikiDatabase.releaseConnection(conn);
}
}
| public static void exportToCsv() throws Exception {
if (!(WikiBase.getDataHandler() instanceof HSqlDataHandler)) {
throw new IllegalStateException("Exporting to CSV is allowed only when the wiki is configured to use the internal database setting.");
}
Connection conn = null;
WikiPreparedStatement stmt = null;
String sql = null;
String exportTableName = null;
String[] tableNames = {
"jam_category",
"jam_group",
"jam_recent_change",
"jam_role_map",
"jam_role",
"jam_topic",
"jam_topic_version",
"jam_virtual_wiki",
"jam_watchlist",
"jam_file",
"jam_file_version",
"jam_wiki_user",
"jam_wiki_user_info"
};
String csvDirectory = new File(Environment.getValue(Environment.PROP_BASE_FILE_DIR), "database").getPath();
File csvFile = null;
try {
conn = WikiDatabase.getConnection(null);
// make sure CSV files are encoded UTF-8
// TODO: this does not seem to be working currently - HSQL bug?
sql = "set property \"textdb.encoding\" 'UTF-8'";
stmt = new WikiPreparedStatement(sql);
stmt.executeUpdate();
for (int i=0; i < tableNames.length; i++) {
exportTableName = tableNames[i] + "_export";
// first drop any pre-existing CSV database files.
sql = "drop table " + exportTableName + " if exists";
stmt = new WikiPreparedStatement(sql);
stmt.executeUpdate();
// now delete the CSV file if it exists
csvFile = new File(csvDirectory, exportTableName + ".csv");
if (csvFile.exists()) {
if (csvFile.delete()) {
logger.info("Deleted existing CSV file: " + csvFile.getPath());
} else {
logger.warning("Could not delete existing CSV file: " + csvFile.getPath());
}
}
// create the CSV files
sql = "select * into text " + exportTableName + " from " + tableNames[i];
stmt = new WikiPreparedStatement(sql);
stmt.executeUpdate();
}
// rebuild the data files to make sure everything is committed to disk
sql = "checkpoint";
stmt = new WikiPreparedStatement(sql);
stmt.executeUpdate();
} catch (Exception e) {
DatabaseConnection.handleErrors(conn);
throw e;
} finally {
WikiDatabase.releaseConnection(conn);
}
}
|
diff --git a/core/src/main/java/hudson/maven/reporters/SurefireArchiver.java b/core/src/main/java/hudson/maven/reporters/SurefireArchiver.java
index 69f2cfafb..385ff9213 100644
--- a/core/src/main/java/hudson/maven/reporters/SurefireArchiver.java
+++ b/core/src/main/java/hudson/maven/reporters/SurefireArchiver.java
@@ -1,129 +1,129 @@
package hudson.maven.reporters;
import hudson.Util;
import hudson.maven.MavenBuild;
import hudson.maven.MavenBuildProxy;
import hudson.maven.MavenBuildProxy.BuildCallable;
import hudson.maven.MavenBuilder;
import hudson.maven.MavenModule;
import hudson.maven.MavenReporter;
import hudson.maven.MavenReporterDescriptor;
import hudson.maven.MojoInfo;
import hudson.model.Action;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.tasks.junit.TestResult;
import hudson.tasks.test.TestResultProjectAction;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.types.FileSet;
import org.codehaus.plexus.component.configurator.ComponentConfigurationException;
import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration;
import java.io.File;
import java.io.IOException;
/**
* Records the surefire test result.
* @author Kohsuke Kawaguchi
*/
public class SurefireArchiver extends MavenReporter {
private TestResult result;
public boolean preExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener) throws InterruptedException, IOException {
if (isSurefireTest(mojo)) {
// tell surefire:test to keep going even if there was a failure,
// so that we can record this as yellow.
// note that because of the way Maven works, just updating system property at this point is too late
XmlPlexusConfiguration c = (XmlPlexusConfiguration) mojo.configuration.getChild("testFailureIgnore");
if(c!=null && c.getValue().equals("${maven.test.failure.ignore}") && System.getProperty("maven.test.failure.ignore")==null)
c.setValue("true");
}
return true;
}
public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, final BuildListener listener, Throwable error) throws InterruptedException, IOException {
if (!isSurefireTest(mojo)) return true;
listener.getLogger().println(Messages.SurefireArchiver_Recording());
File reportsDir;
try {
reportsDir = mojo.getConfigurationValue("reportsDirectory", File.class);
} catch (ComponentConfigurationException e) {
e.printStackTrace(listener.fatalError(Messages.SurefireArchiver_NoReportsDir()));
build.setResult(Result.FAILURE);
return true;
}
if(reportsDir.exists()) {
// surefire:test just skips itself when the current project is not a java project
- FileSet fs = Util.createFileSet(reportsDir,"*.xml");
+ FileSet fs = Util.createFileSet(reportsDir,"*.xml","testng-results.xml,testng-failed.xml");
DirectoryScanner ds = fs.getDirectoryScanner();
if(ds.getIncludedFiles().length==0)
// no test in this module
return true;
if(result==null)
result = new TestResult(build.getTimestamp().getTimeInMillis() - 1000/*error margin*/, ds);
else
result.parse(build.getTimestamp().getTimeInMillis() - 1000/*error margin*/, ds);
int failCount = build.execute(new BuildCallable<Integer, IOException>() {
public Integer call(MavenBuild build) throws IOException, InterruptedException {
SurefireReport sr = build.getAction(SurefireReport.class);
if(sr==null)
build.getActions().add(new SurefireReport(build, result, listener));
else
sr.setResult(result,listener);
if(result.getFailCount()>0)
build.setResult(Result.UNSTABLE);
build.registerAsProjectAction(SurefireArchiver.this);
return result.getFailCount();
}
});
// if surefire plugin is going to kill maven because of a test failure,
// intercept that (or otherwise build will be marked as failure)
if(failCount>0 && error instanceof MojoFailureException) {
MavenBuilder.markAsSuccess = true;
}
}
return true;
}
public Action getProjectAction(MavenModule module) {
return new TestResultProjectAction(module);
}
private boolean isSurefireTest(MojoInfo mojo) {
return mojo.pluginName.matches("org.apache.maven.plugins", "maven-surefire-plugin") && mojo.getGoal().equals("test");
}
public DescriptorImpl getDescriptor() {
return DescriptorImpl.DESCRIPTOR;
}
public static final class DescriptorImpl extends MavenReporterDescriptor {
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
private DescriptorImpl() {
super(SurefireArchiver.class);
}
public String getDisplayName() {
return Messages.SurefireArchiver_DisplayName();
}
public SurefireArchiver newAutoInstance(MavenModule module) {
return new SurefireArchiver();
}
}
private static final long serialVersionUID = 1L;
}
| true | true | public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, final BuildListener listener, Throwable error) throws InterruptedException, IOException {
if (!isSurefireTest(mojo)) return true;
listener.getLogger().println(Messages.SurefireArchiver_Recording());
File reportsDir;
try {
reportsDir = mojo.getConfigurationValue("reportsDirectory", File.class);
} catch (ComponentConfigurationException e) {
e.printStackTrace(listener.fatalError(Messages.SurefireArchiver_NoReportsDir()));
build.setResult(Result.FAILURE);
return true;
}
if(reportsDir.exists()) {
// surefire:test just skips itself when the current project is not a java project
FileSet fs = Util.createFileSet(reportsDir,"*.xml");
DirectoryScanner ds = fs.getDirectoryScanner();
if(ds.getIncludedFiles().length==0)
// no test in this module
return true;
if(result==null)
result = new TestResult(build.getTimestamp().getTimeInMillis() - 1000/*error margin*/, ds);
else
result.parse(build.getTimestamp().getTimeInMillis() - 1000/*error margin*/, ds);
int failCount = build.execute(new BuildCallable<Integer, IOException>() {
public Integer call(MavenBuild build) throws IOException, InterruptedException {
SurefireReport sr = build.getAction(SurefireReport.class);
if(sr==null)
build.getActions().add(new SurefireReport(build, result, listener));
else
sr.setResult(result,listener);
if(result.getFailCount()>0)
build.setResult(Result.UNSTABLE);
build.registerAsProjectAction(SurefireArchiver.this);
return result.getFailCount();
}
});
// if surefire plugin is going to kill maven because of a test failure,
// intercept that (or otherwise build will be marked as failure)
if(failCount>0 && error instanceof MojoFailureException) {
MavenBuilder.markAsSuccess = true;
}
}
return true;
}
| public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, final BuildListener listener, Throwable error) throws InterruptedException, IOException {
if (!isSurefireTest(mojo)) return true;
listener.getLogger().println(Messages.SurefireArchiver_Recording());
File reportsDir;
try {
reportsDir = mojo.getConfigurationValue("reportsDirectory", File.class);
} catch (ComponentConfigurationException e) {
e.printStackTrace(listener.fatalError(Messages.SurefireArchiver_NoReportsDir()));
build.setResult(Result.FAILURE);
return true;
}
if(reportsDir.exists()) {
// surefire:test just skips itself when the current project is not a java project
FileSet fs = Util.createFileSet(reportsDir,"*.xml","testng-results.xml,testng-failed.xml");
DirectoryScanner ds = fs.getDirectoryScanner();
if(ds.getIncludedFiles().length==0)
// no test in this module
return true;
if(result==null)
result = new TestResult(build.getTimestamp().getTimeInMillis() - 1000/*error margin*/, ds);
else
result.parse(build.getTimestamp().getTimeInMillis() - 1000/*error margin*/, ds);
int failCount = build.execute(new BuildCallable<Integer, IOException>() {
public Integer call(MavenBuild build) throws IOException, InterruptedException {
SurefireReport sr = build.getAction(SurefireReport.class);
if(sr==null)
build.getActions().add(new SurefireReport(build, result, listener));
else
sr.setResult(result,listener);
if(result.getFailCount()>0)
build.setResult(Result.UNSTABLE);
build.registerAsProjectAction(SurefireArchiver.this);
return result.getFailCount();
}
});
// if surefire plugin is going to kill maven because of a test failure,
// intercept that (or otherwise build will be marked as failure)
if(failCount>0 && error instanceof MojoFailureException) {
MavenBuilder.markAsSuccess = true;
}
}
return true;
}
|
diff --git a/core/src/visad/trunk/ShadowFunctionOrSetType.java b/core/src/visad/trunk/ShadowFunctionOrSetType.java
index 52341aea1..f253c1dbc 100644
--- a/core/src/visad/trunk/ShadowFunctionOrSetType.java
+++ b/core/src/visad/trunk/ShadowFunctionOrSetType.java
@@ -1,3338 +1,3348 @@
//
// ShadowFunctionOrSetType.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 2002 Bill Hibbard, Curtis Rueden, Tom
Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and
Tommy Jasmin.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA
*/
/*
MEM - memory use reduction strategy:
changes marked by MEM_WLH
1. if (isTexture) no assembleSpatial NOT NEEDED
but if (isTexture) then domain_values = null,
so spatial display_values[i] = null so assembleSpatial
does nothing (except construct a SingletonSet spatial_set)
2. byte[][] assembleColor DONE
this has a bad space / time tradeoff in makeIso*,
so create a boolean in GMC to choose between
(Irregular3DSet, Gridded3DSet) and their slower extensions
3. after use, set display_values[i] = null; DONE
done in many ShadowType.assemble* - marked by MEM_WLH
4. don't fill arrays that won't get used
are there any of these ??
5. replace getValues() by getFloats(false)
already done for getSamples
6. assembleColors first DONE
7. boolean[] range_select
8. in-line byteToFloat and floatToByte DONE
VisADCanvasJ2D, Gridded3DSet, Irregular3DSet
N. iso-surface computation uses:
Irregular3DSet.makeIsosurface:
float[len] fieldValues
float[3 or 4][len] auxValues (color_values)
float[3][nvertex] fieldVertices
float[3 or 4][nvertex] auxLevels
int[1][npolygons][3 or 4] polyToVert
int[1][nvertex][nverts[i]] vertToPoly
int[Delan.Tri.length][4] polys
int[Delan.NumEdges] globalToVertex
float[DomainDimension][Delan.NumEdges] edgeInterp
float[3 or 4][Delan.NumEdges] auxInterp
Gridded3DSet.makeIsoSurface:
start with nvertex_estimate = 4 * npolygons + 100
int[num_cubes] ptFLAG
int[xdim_x_ydim_x_zdim] ptAUX
int[num_cubes+1] pcube
float[1][4 * npolygons] VX
float[1][4 * npolygons] VY
float[1][4 * npolygons] VZ
float[3 or 4][nvet] color_temps
float[3 or 4][len] cfloat
int[7 * npolygons] Vert_f_Pol
int[1][36 * npolygons] Pol_f_Vert
number of bytes = 268 (or 284) * npolygons +
24 (or 28) * len
isosurf:
float[3][len] samples
float[3 or 4][nvertex_estimate] tempaux
number of bytes = 48 (or 64) * npolygons +
12 * len
float[npolygons] NxA, NxB, NyA, NyB, NzA, NzB
float[npolygons] Pnx, Pny, Pnz
float[nvertex] NX, NY, NZ
number of bytes = 84 * npolygons
make_normals:
none
total number of bytes = 36 (or 40) * len +
400 (to 432) * npolygons
so if len = 0.5M and npolygons = 0.1M
bytes = 20M + 43.2M = 63.2M
*/
package visad;
import java.util.*;
import java.text.*;
import java.rmi.*;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.awt.image.DataBufferInt;
import java.awt.image.DataBuffer;
import java.awt.*;
/**
The ShadowFunctionOrSetType class is an abstract parent for
classes that implement ShadowFunctionType or ShadowSetType.<P>
*/
public abstract class ShadowFunctionOrSetType extends ShadowType {
ShadowRealTupleType Domain;
ShadowType Range; // null for ShadowSetType
/** RangeComponents is an array of ShadowRealType-s that are
ShadowRealType components of Range or ShadowRealType
components of ShadowRealTupleType components of Range;
a non-ShadowRealType and non-ShadowTupleType Range is marked
by null;
components of a ShadowTupleType Range that are neither
ShadowRealType nor ShadowRealTupleType are ignored */
ShadowRealType[] RangeComponents; // null for ShadowSetType
ShadowRealType[] DomainComponents;
ShadowRealType[] DomainReferenceComponents;
/** true if range is ShadowRealType or Flat ShadowTupleType
not the same as FunctionType.Flat;
also true for ShadowSetType */
boolean Flat;
/** value_indices from parent */
int[] inherited_values;
/** this constructor is a bit of a kludge to get around
single inheritance problems */
public ShadowFunctionOrSetType(MathType t, DataDisplayLink link, ShadowType parent,
ShadowRealTupleType domain, ShadowType range)
throws VisADException, RemoteException {
super(t, link, parent);
Domain = domain;
Range = range;
if (this instanceof ShadowFunctionType) {
Flat = (Range instanceof ShadowRealType) ||
(Range instanceof ShadowTextType) ||
(Range instanceof ShadowTupleType &&
((ShadowTupleType) Range).isFlat());
MultipleSpatialDisplayScalar = Domain.getMultipleSpatialDisplayScalar() ||
Range.getMultipleSpatialDisplayScalar();
MultipleDisplayScalar = Domain.getMultipleDisplayScalar() ||
Range.getMultipleDisplayScalar();
MappedDisplayScalar = Domain.getMappedDisplayScalar() ||
Range.getMappedDisplayScalar();
RangeComponents = getComponents(Range, true);
}
else if (this instanceof ShadowSetType) {
Flat = true;
MultipleDisplayScalar = Domain.getMultipleDisplayScalar();
MappedDisplayScalar = Domain.getMappedDisplayScalar();
RangeComponents = null;
}
else {
throw new DisplayException("ShadowFunctionOrSetType: must be " +
"ShadowFunctionType or ShadowSetType");
}
DomainComponents = getComponents(Domain, false);
DomainReferenceComponents = getComponents(Domain.getReference(), false);
}
public boolean getFlat() {
return Flat;
}
public ShadowRealType[] getRangeComponents() {
return RangeComponents;
}
public ShadowRealType[] getDomainComponents() {
return DomainComponents;
}
public ShadowRealType[] getDomainReferenceComponents() {
return DomainReferenceComponents;
}
/** used by FlatField.computeRanges */
int[] getRangeDisplayIndices() throws VisADException {
if (!(this instanceof ShadowFunctionType)) {
throw new DisplayException("ShadowFunctionOrSetType.getRangeDisplay" +
"Indices: must be ShadowFunctionType");
}
int n = RangeComponents.length;
int[] indices = new int[n];
for (int i=0; i<n; i++) {
indices[i] = RangeComponents[i].getIndex();
}
return indices;
}
public int[] getInheritedValues() {
return inherited_values;
}
/** checkIndices: check for rendering difficulty, etc */
public int checkIndices(int[] indices, int[] display_indices,
int[] value_indices, boolean[] isTransform, int levelOfDifficulty)
throws VisADException, RemoteException {
// add indices & display_indices from Domain
int[] local_indices = Domain.sumIndices(indices);
int[] local_display_indices = Domain.sumDisplayIndices(display_indices);
int[] local_value_indices = Domain.sumValueIndices(value_indices);
if (Domain.testTransform()) Domain.markTransform(isTransform);
if (this instanceof ShadowFunctionType) {
Range.markTransform(isTransform);
}
// get value_indices arrays used by doTransform
inherited_values = copyIndices(value_indices);
// check for any mapped
if (levelOfDifficulty == NOTHING_MAPPED) {
if (checkAny(local_display_indices)) {
levelOfDifficulty = NESTED;
}
}
// test legality of Animation and SelectValue in Domain
int avCount = checkAnimationOrValue(Domain.getDisplayIndices());
if (Domain.getDimension() != 1) {
if (avCount > 0) {
throw new BadMappingException("Animation and SelectValue may only occur " +
"in 1-D Function domain: " +
"ShadowFunctionOrSetType.checkIndices");
}
else {
// eventually ShadowType.testTransform is used to mark Animation,
// Value or Range as isTransform when multiple occur in Domain;
// however, temporary hack in Renderer.isTransformControl requires
// multiple occurence of Animation and Value to throw an Exception
if (avCount > 1) {
throw new BadMappingException("only one Animation and SelectValue may " +
"occur Set domain: " +
"ShadowFunctionOrSetType.checkIndices");
}
}
}
if (Flat || this instanceof ShadowSetType) {
if (this instanceof ShadowFunctionType) {
if (Range instanceof ShadowTupleType) {
local_indices =
((ShadowTupleType) Range).sumIndices(local_indices);
local_display_indices =
((ShadowTupleType) Range).sumDisplayIndices(local_display_indices);
local_value_indices =
((ShadowTupleType) Range).sumValueIndices(local_value_indices);
}
else if (Range instanceof ShadowScalarType) {
((ShadowScalarType) Range).incrementIndices(local_indices);
local_display_indices = addIndices(local_display_indices,
((ShadowScalarType) Range).getDisplayIndices());
local_value_indices = addIndices(local_value_indices,
((ShadowScalarType) Range).getValueIndices());
}
// test legality of Animation and SelectValue in Range
if (checkAnimationOrValue(Range.getDisplayIndices()) > 0) {
throw new BadMappingException("Animation and SelectValue may not " +
"occur in Function range: " +
"ShadowFunctionOrSetType.checkIndices");
}
} // end if (this instanceof ShadowFunctionType)
anyContour = checkContour(local_display_indices);
anyFlow = checkFlow(local_display_indices);
anyShape = checkShape(local_display_indices);
anyText = checkText(local_display_indices);
LevelOfDifficulty =
testIndices(local_indices, local_display_indices, levelOfDifficulty);
/*
System.out.println("ShadowFunctionOrSetType.checkIndices 1:" +
" LevelOfDifficulty = " + LevelOfDifficulty +
" isTerminal = " + isTerminal +
" Type = " + Type.prettyString());
*/
// compute Domain type
if (!Domain.getMappedDisplayScalar()) {
Dtype = D0;
}
else if (Domain.getAllSpatial() && checkR4(Domain.getDisplayIndices())) {
Dtype = D1;
}
else if (checkR1D3(Domain.getDisplayIndices())) {
Dtype = D3;
}
else if (checkR2D2(Domain.getDisplayIndices())) {
Dtype = D2;
}
else if (checkAnimationOrValue(Domain.getDisplayIndices()) > 0) {
Dtype = D4;
}
else {
Dtype = Dbad;
}
if (this instanceof ShadowFunctionType) {
// compute Range type
if (!Range.getMappedDisplayScalar()) {
Rtype = R0;
}
else if (checkR1D3(Range.getDisplayIndices())) {
Rtype = R1;
}
else if (checkR2D2(Range.getDisplayIndices())) {
Rtype = R2;
}
else if (checkR3(Range.getDisplayIndices())) {
Rtype = R3;
}
else if (checkR4(Range.getDisplayIndices())) {
Rtype = R4;
}
else {
Rtype = Rbad;
}
}
else { // this instanceof ShadowSetType
Rtype = R0; // implicit - Set has no range
}
if (LevelOfDifficulty == NESTED) {
if (Dtype != Dbad && Rtype != Rbad) {
if (Dtype == D4) {
LevelOfDifficulty = SIMPLE_ANIMATE_FIELD;
}
else {
LevelOfDifficulty = SIMPLE_FIELD;
}
}
else {
LevelOfDifficulty = LEGAL;
}
}
/*
System.out.println("ShadowFunctionOrSetType.checkIndices 2:" +
" LevelOfDifficulty = " + LevelOfDifficulty +
" Dtype = " + Dtype + " Rtype = " + Rtype);
*/
if (this instanceof ShadowFunctionType) {
// test for texture mapping
// WLH 30 April 99
isTextureMap = !getMultipleDisplayScalar() &&
getLevelOfDifficulty() == ShadowType.SIMPLE_FIELD &&
((FunctionType) getType()).getReal() && // ??
Domain.getDimension() == 2 &&
Domain.getAllSpatial() &&
!Domain.getSpatialReference() &&
Display.DisplaySpatialCartesianTuple.equals(
Domain.getDisplaySpatialTuple() ) &&
checkColorAlphaRange(Range.getDisplayIndices()) &&
checkAny(Range.getDisplayIndices()) &&
display.getGraphicsModeControl().getTextureEnable() &&
!display.getGraphicsModeControl().getPointMode();
curvedTexture = getLevelOfDifficulty() == ShadowType.SIMPLE_FIELD &&
// Domain.getDimension() == 2 && WLH 22 Aug 2002 Lak's bug
Domain.getAllSpatial() &&
checkSpatialOffsetColorAlphaRange(Domain.getDisplayIndices()) &&
checkSpatialOffsetColorAlphaRange(Range.getDisplayIndices()) &&
checkAny(Range.getDisplayIndices()) &&
display.getGraphicsModeControl().getTextureEnable() &&
!display.getGraphicsModeControl().getPointMode();
// WLH 15 March 2000
// isTexture3D = !getMultipleDisplayScalar() &&
isTexture3D = getLevelOfDifficulty() == ShadowType.SIMPLE_FIELD &&
((FunctionType) getType()).getReal() && // ??
Domain.getDimension() == 3 &&
Domain.getAllSpatial() &&
// WLH 1 April 2000
// !Domain.getMultipleDisplayScalar() && // WLH 15 March 2000
checkSpatialRange(Domain.getDisplayIndices()) && // WLH 1 April 2000
!Domain.getSpatialReference() &&
Display.DisplaySpatialCartesianTuple.equals(
Domain.getDisplaySpatialTuple() ) &&
checkColorAlphaRange(Range.getDisplayIndices()) &&
checkAny(Range.getDisplayIndices()) &&
display.getGraphicsModeControl().getTextureEnable() &&
!display.getGraphicsModeControl().getPointMode();
// note GgraphicsModeControl.setTextureEnable(false) disables this
isLinearContour3D =
getLevelOfDifficulty() == ShadowType.SIMPLE_FIELD &&
((FunctionType) getType()).getReal() && // ??
Domain.getDimension() == 3 &&
Domain.getAllSpatial() &&
!Domain.getMultipleDisplayScalar() &&
!Domain.getSpatialReference() &&
Display.DisplaySpatialCartesianTuple.equals(
Domain.getDisplaySpatialTuple() ) &&
checkContourColorAlphaRange(Range.getDisplayIndices()) &&
checkContour(Range.getDisplayIndices());
/*
System.out.println("checkIndices.isTexture3D = " + isTexture3D + " " +
(getLevelOfDifficulty() == ShadowType.SIMPLE_FIELD) + " " +
((FunctionType) getType()).getReal() + " " +
(Domain.getDimension() == 3) + " " +
Domain.getAllSpatial() + " " +
checkSpatialRange(Domain.getDisplayIndices()) + " " +
!Domain.getSpatialReference() + " " +
Display.DisplaySpatialCartesianTuple.equals(
Domain.getDisplaySpatialTuple() ) + " " +
checkColorAlphaRange(Range.getDisplayIndices()) + " " +
checkAny(Range.getDisplayIndices()) + " " +
display.getGraphicsModeControl().getTextureEnable() + " " +
!display.getGraphicsModeControl().getPointMode() );
*/
/*
System.out.println("checkIndices.isTextureMap = " + isTextureMap + " " +
!getMultipleDisplayScalar() + " " +
(getLevelOfDifficulty() == ShadowType.SIMPLE_FIELD) + " " +
((FunctionType) getType()).getReal() + " " +
(Domain.getDimension() == 2) + " " +
Domain.getAllSpatial() + " " +
!Domain.getSpatialReference() + " " +
Display.DisplaySpatialCartesianTuple.equals(
Domain.getDisplaySpatialTuple() ) + " " +
checkColorAlphaRange(Range.getDisplayIndices()) + " " +
checkAny(Range.getDisplayIndices()) + " " +
display.getGraphicsModeControl().getTextureEnable() + " " +
!display.getGraphicsModeControl().getPointMode() );
System.out.println("checkIndices.curvedTexture = " + curvedTexture + " " +
(getLevelOfDifficulty() == ShadowType.SIMPLE_FIELD) + " " +
(Domain.getDimension() == 2) + " " +
Domain.getAllSpatial() + " " +
checkSpatialOffsetColorAlphaRange(Domain.getDisplayIndices()) + " " +
checkSpatialOffsetColorAlphaRange(Range.getDisplayIndices()) + " " +
checkAny(Range.getDisplayIndices()) + " " +
display.getGraphicsModeControl().getTextureEnable() + " " +
!display.getGraphicsModeControl().getPointMode() );
*/
}
}
else { // !Flat && this instanceof ShadowFunctionType
if (levelOfDifficulty == NESTED) {
if (!checkNested(Domain.getDisplayIndices())) {
levelOfDifficulty = LEGAL;
}
}
LevelOfDifficulty = Range.checkIndices(local_indices, local_display_indices,
local_value_indices, isTransform,
levelOfDifficulty);
/*
System.out.println("ShadowFunctionOrSetType.checkIndices 3:" +
" LevelOfDifficulty = " + LevelOfDifficulty);
*/
}
return LevelOfDifficulty;
}
public ShadowRealTupleType getDomain() {
return Domain;
}
public ShadowType getRange() {
return Range;
}
/** mark Control-s as needing re-Transform */
void markTransform(boolean[] isTransform) {
if (Range != null) Range.markTransform(isTransform);
}
/** transform data into a (Java3D or Java2D) scene graph;
add generated scene graph components as children of group;
group is Group (Java3D) or VisADGroup (Java2D);
value_array are inherited valueArray values;
default_values are defaults for each display.DisplayRealTypeVector;
return true if need post-process */
public boolean doTransform(Object group, Data data, float[] value_array,
float[] default_values, DataRenderer renderer,
ShadowType shadow_api)
throws VisADException, RemoteException {
// return if data is missing or no ScalarMaps
if (data.isMissing()) return false;
if (LevelOfDifficulty == NOTHING_MAPPED) return false;
// if transform has taken more than 500 milliseconds and there is
// a flag requesting re-transform, throw a DisplayInterruptException
DataDisplayLink link = renderer.getLink();
// if (link != null) System.out.println("\nstart doTransform " + (System.currentTimeMillis() - link.start_time));
if (link != null) {
boolean time_flag = false;
if (link.time_flag) {
time_flag = true;
}
else {
if (500 < System.currentTimeMillis() - link.start_time) {
link.time_flag = true;
time_flag = true;
}
}
if (time_flag) {
if (link.peekTicks()) {
throw new DisplayInterruptException("please wait . . .");
}
Enumeration maps = link.getSelectedMapVector().elements();
while(maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
if (map.peekTicks(renderer, link)) {
throw new DisplayInterruptException("please wait . . .");
}
}
}
} // end if (link != null)
// get 'shape' flags
boolean anyContour = getAnyContour();
boolean anyFlow = getAnyFlow();
boolean anyShape = getAnyShape();
boolean anyText = getAnyText();
boolean indexed = shadow_api.wantIndexed();
// get some precomputed values useful for transform
// length of ValueArray
int valueArrayLength = display.getValueArrayLength();
// mapping from ValueArray to DisplayScalar
int[] valueToScalar = display.getValueToScalar();
// mapping from ValueArray to MapVector
int[] valueToMap = display.getValueToMap();
Vector MapVector = display.getMapVector();
// array to hold values for various mappings
float[][] display_values = new float[valueArrayLength][];
// get values inherited from parent;
// assume these do not include SelectRange, SelectValue
// or Animation values - see temporary hack in
// DataRenderer.isTransformControl
for (int i=0; i<valueArrayLength; i++) {
if (inherited_values[i] > 0) {
display_values[i] = new float[1];
display_values[i][0] = value_array[i];
}
}
// check for only contours and only disabled contours
if (getIsTerminal() && anyContour &&
!anyFlow && !anyShape && !anyText) { // WLH 13 March 99
boolean any_enabled = false;
for (int i=0; i<valueArrayLength; i++) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType real = display.getDisplayScalar(displayScalarIndex);
if (real.equals(Display.IsoContour) && inherited_values[i] == 0) {
// non-inherited IsoContour, so generate contours
ContourControl control = (ContourControl)
((ScalarMap) MapVector.elementAt(valueToMap[i])).getControl();
boolean[] bvalues = new boolean[2];
float[] fvalues = new float[5];
control.getMainContours(bvalues, fvalues);
if (bvalues[0]) any_enabled = true;
}
}
if (!any_enabled) return false;
}
Set domain_set = null;
Unit[] dataUnits = null;
CoordinateSystem dataCoordinateSystem = null;
if (this instanceof ShadowFunctionType) {
// currently only implemented for Field
// must eventually extend to Function
if (!(data instanceof Field)) {
throw new UnimplementedException("data must be Field: " +
"ShadowFunctionOrSetType.doTransform: ");
}
domain_set = ((Field) data).getDomainSet();
dataUnits = ((Function) data).getDomainUnits();
dataCoordinateSystem = ((Function) data).getDomainCoordinateSystem();
}
else if (this instanceof ShadowSetType) {
domain_set = (Set) data;
dataUnits = ((Set) data).getSetUnits();
dataCoordinateSystem = ((Set) data).getCoordinateSystem();
}
else {
throw new DisplayException(
"must be ShadowFunctionType or ShadowSetType: " +
"ShadowFunctionOrSetType.doTransform");
}
float[][] domain_values = null;
double[][] domain_doubles = null;
Unit[] domain_units = ((RealTupleType) Domain.getType()).getDefaultUnits();
int domain_length;
int domain_dimension;
try {
domain_length = domain_set.getLength();
domain_dimension = domain_set.getDimension();
}
catch (SetException e) {
return false;
}
// ShadowRealTypes of Domain
ShadowRealType[] DomainComponents = getDomainComponents();
int alpha_index = display.getDisplayScalarIndex(Display.Alpha);
// array to hold values for Text mapping (can only be one)
String[] text_values = null;
// get any text String and TextControl inherited from parent
TextControl text_control = shadow_api.getParentTextControl();
String inherited_text = shadow_api.getParentText();
if (inherited_text != null) {
text_values = new String[domain_length];
for (int i=0; i<domain_length; i++) {
text_values[i] = inherited_text;
}
}
boolean isTextureMap = getIsTextureMap() &&
// default_values[alpha_index] > 0.99 &&
renderer.isLegalTextureMap() &&
(domain_set instanceof Linear2DSet ||
(domain_set instanceof LinearNDSet &&
domain_set.getDimension() == 2));
int curved_size = display.getGraphicsModeControl().getCurvedSize();
boolean curvedTexture = getCurvedTexture() &&
!isTextureMap &&
curved_size > 0 &&
getIsTerminal() && // implied by getCurvedTexture()?
shadow_api.allowCurvedTexture() &&
default_values[alpha_index] > 0.99 &&
renderer.isLegalTextureMap() &&
domain_set.getManifoldDimension() == 2 &&
domain_set instanceof GriddedSet; // WLH 22 Aug 2002 Lak's bug
/* // WLH 22 Aug 2002 Lak's bug
(domain_set instanceof Gridded2DSet ||
(domain_set instanceof GriddedSet &&
domain_set.getDimension() == 2));
*/
boolean domainOnlySpatial =
Domain.getAllSpatial() && !Domain.getMultipleDisplayScalar();
boolean isTexture3D = getIsTexture3D() &&
// default_values[alpha_index] > 0.99 &&
renderer.isLegalTextureMap() &&
(domain_set instanceof Linear3DSet ||
(domain_set instanceof LinearNDSet &&
domain_set.getDimension() == 3));
// WLH 1 April 2000
boolean range3D = isTexture3D && anyRange(Domain.getDisplayIndices());
boolean isLinearContour3D = getIsLinearContour3D() &&
domain_set instanceof Linear3DSet &&
shadow_api.allowLinearContour();
/*
System.out.println("doTransform.isTextureMap = " + isTextureMap + " " +
getIsTextureMap() + " " +
// (default_values[alpha_index] > 0.99) + " " +
renderer.isLegalTextureMap() + " " +
(domain_set instanceof Linear2DSet) + " " +
(domain_set instanceof LinearNDSet) + " " +
(domain_set.getDimension() == 2));
System.out.println("doTransform.curvedTexture = " + curvedTexture + " " +
getCurvedTexture() + " " +
!isTextureMap + " " +
(curved_size > 0) + " " +
getIsTerminal() + " " +
shadow_api.allowCurvedTexture() + " " +
(default_values[alpha_index] > 0.99) + " " +
renderer.isLegalTextureMap() + " " +
(domain_set instanceof Gridded2DSet) + " " +
(domain_set instanceof GriddedSet) + " " +
(domain_set.getDimension() == 2) );
*/
float[] coordinates = null;
float[] texCoords = null;
float[] normals = null;
byte[] colors = null;
int data_width = 0;
int data_height = 0;
int data_depth = 0;
int texture_width = 1;
int texture_height = 1;
int texture_depth = 1;
float[] coordinatesX = null;
float[] texCoordsX = null;
float[] normalsX = null;
byte[] colorsX = null;
float[] coordinatesY = null;
float[] texCoordsY = null;
float[] normalsY = null;
byte[] colorsY = null;
float[] coordinatesZ = null;
float[] texCoordsZ = null;
float[] normalsZ = null;
byte[] colorsZ = null;
int[] volume_tuple_index = null;
// if (link != null) System.out.println("test isTextureMap " + (System.currentTimeMillis() - link.start_time));
if (isTextureMap) {
Linear1DSet X = null;
Linear1DSet Y = null;
if (domain_set instanceof Linear2DSet) {
X = ((Linear2DSet) domain_set).getX();
Y = ((Linear2DSet) domain_set).getY();
}
else {
X = ((LinearNDSet) domain_set).getLinear1DComponent(0);
Y = ((LinearNDSet) domain_set).getLinear1DComponent(1);
}
float[][] limits = new float[2][2];
limits[0][0] = (float) X.getFirst();
limits[0][1] = (float) X.getLast();
limits[1][0] = (float) Y.getFirst();
limits[1][1] = (float) Y.getLast();
// convert values to default units (used in display)
limits = Unit.convertTuple(limits, dataUnits, domain_units);
// get domain_set sizes
data_width = X.getLength();
data_height = Y.getLength();
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
int[] tuple_index = new int[3];
if (DomainComponents.length != 2) {
throw new DisplayException("texture domain dimension != 2:" +
"ShadowFunctionOrSetType.doTransform");
}
for (int i=0; i<DomainComponents.length; i++) {
Enumeration maps = DomainComponents[i].getSelectedMapVector().elements();
while (maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
DisplayRealType real = map.getDisplayScalar();
DisplayTupleType tuple = real.getTuple();
if (Display.DisplaySpatialCartesianTuple.equals(tuple)) {
// scale values
limits[i] = map.scaleValues(limits[i]);
// get spatial index
tuple_index[i] = real.getTupleIndex();
break;
}
}
/*
if (tuple == null ||
!tuple.equals(Display.DisplaySpatialCartesianTuple)) {
throw new DisplayException("texture with bad tuple: " +
"ShadowFunctionOrSetType.doTransform");
}
if (maps.hasMoreElements()) {
throw new DisplayException("texture with multiple spatial: " +
"ShadowFunctionOrSetType.doTransform");
}
*/
} // end for (int i=0; i<DomainComponents.length; i++)
// get spatial index not mapped from domain_set
tuple_index[2] = 3 - (tuple_index[0] + tuple_index[1]);
DisplayRealType real = (DisplayRealType)
Display.DisplaySpatialCartesianTuple.getComponent(tuple_index[2]);
int value2_index = display.getDisplayScalarIndex(real);
float value2 = default_values[value2_index];
// float value2 = 0.0f; WLH 30 Aug 99
for (int i=0; i<valueArrayLength; i++) {
if (inherited_values[i] > 0 &&
real.equals(display.getDisplayScalar(valueToScalar[i])) ) {
value2 = value_array[i];
break;
}
}
coordinates = new float[12];
// corner 0
coordinates[tuple_index[0]] = limits[0][0];
coordinates[tuple_index[1]] = limits[1][0];
coordinates[tuple_index[2]] = value2;
// corner 1
coordinates[3 + tuple_index[0]] = limits[0][1];
coordinates[3 + tuple_index[1]] = limits[1][0];
coordinates[3 + tuple_index[2]] = value2;
// corner 2
coordinates[6 + tuple_index[0]] = limits[0][1];
coordinates[6 + tuple_index[1]] = limits[1][1];
coordinates[6 + tuple_index[2]] = value2;
// corner 3
coordinates[9 + tuple_index[0]] = limits[0][0];
coordinates[9 + tuple_index[1]] = limits[1][1];
coordinates[9 + tuple_index[2]] = value2;
// move image back in Java3D 2-D mode
shadow_api.adjustZ(coordinates);
texCoords = new float[8];
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
shadow_api.setTexCoords(texCoords, ratiow, ratioh);
normals = new float[12];
float n0 = ((coordinates[3+2]-coordinates[0+2]) *
(coordinates[6+1]-coordinates[0+1])) -
((coordinates[3+1]-coordinates[0+1]) *
(coordinates[6+2]-coordinates[0+2]));
float n1 = ((coordinates[3+0]-coordinates[0+0]) *
(coordinates[6+2]-coordinates[0+2])) -
((coordinates[3+2]-coordinates[0+2]) *
(coordinates[6+0]-coordinates[0+0]));
float n2 = ((coordinates[3+1]-coordinates[0+1]) *
(coordinates[6+0]-coordinates[0+0])) -
((coordinates[3+0]-coordinates[0+0]) *
(coordinates[6+1]-coordinates[0+1]));
float nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
// corner 0
normals[0] = n0;
normals[1] = n1;
normals[2] = n2;
// corner 1
normals[3] = n0;
normals[4] = n1;
normals[5] = n2;
// corner 2
normals[6] = n0;
normals[7] = n1;
normals[8] = n2;
// corner 3
normals[9] = n0;
normals[10] = n1;
normals[11] = n2;
colors = new byte[12];
for (int i=0; i<12; i++) colors[i] = (byte) 127;
/*
for (int i=0; i < 4; i++) {
System.out.println("i = " + i + " texCoords = " + texCoords[2 * i] + " " +
texCoords[2 * i + 1]);
System.out.println(" coordinates = " + coordinates[3 * i] + " " +
coordinates[3 * i + 1] + " " + coordinates[3 * i + 2]);
System.out.println(" normals = " + normals[3 * i] + " " + normals[3 * i + 1] +
" " + normals[3 * i + 2]);
}
*/
}
else if (isTexture3D) {
Linear1DSet X = null;
Linear1DSet Y = null;
Linear1DSet Z = null;
if (domain_set instanceof Linear3DSet) {
X = ((Linear3DSet) domain_set).getX();
Y = ((Linear3DSet) domain_set).getY();
Z = ((Linear3DSet) domain_set).getZ();
}
else {
X = ((LinearNDSet) domain_set).getLinear1DComponent(0);
Y = ((LinearNDSet) domain_set).getLinear1DComponent(1);
Z = ((LinearNDSet) domain_set).getLinear1DComponent(2);
}
float[][] limits = new float[3][2];
limits[0][0] = (float) X.getFirst();
limits[0][1] = (float) X.getLast();
limits[1][0] = (float) Y.getFirst();
limits[1][1] = (float) Y.getLast();
limits[2][0] = (float) Z.getFirst();
limits[2][1] = (float) Z.getLast();
// convert values to default units (used in display)
limits = Unit.convertTuple(limits, dataUnits, domain_units);
// get domain_set sizes
data_width = X.getLength();
data_height = Y.getLength();
data_depth = Z.getLength();
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
texture_depth = shadow_api.textureDepth(data_depth);
int[] tuple_index = new int[3];
if (DomainComponents.length != 3) {
throw new DisplayException("texture3D domain dimension != 3:" +
"ShadowFunctionOrSetType.doTransform");
}
for (int i=0; i<DomainComponents.length; i++) {
Enumeration maps = DomainComponents[i].getSelectedMapVector().elements();
while (maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
DisplayRealType real = map.getDisplayScalar();
DisplayTupleType tuple = real.getTuple();
if (Display.DisplaySpatialCartesianTuple.equals(tuple)) {
// scale values
limits[i] = map.scaleValues(limits[i]);
// get spatial index
tuple_index[i] = real.getTupleIndex();
break;
}
}
/*
if (tuple == null ||
!tuple.equals(Display.DisplaySpatialCartesianTuple)) {
throw new DisplayException("texture with bad tuple: " +
"ShadowFunctionOrSetType.doTransform");
}
if (maps.hasMoreElements()) {
throw new DisplayException("texture with multiple spatial: " +
"ShadowFunctionOrSetType.doTransform");
}
*/
} // end for (int i=0; i<DomainComponents.length; i++)
volume_tuple_index = tuple_index;
coordinatesX = new float[12 * data_width];
coordinatesY = new float[12 * data_height];
coordinatesZ = new float[12 * data_depth];
for (int i=0; i<data_depth; i++) {
int i12 = i * 12;
float depth = limits[2][0] +
(limits[2][1] - limits[2][0]) * i / (data_depth - 1.0f);
// corner 0
coordinatesZ[i12 + tuple_index[0]] = limits[0][0];
coordinatesZ[i12 + tuple_index[1]] = limits[1][0];
coordinatesZ[i12 + tuple_index[2]] = depth;
// corner 1
coordinatesZ[i12 + 3 + tuple_index[0]] = limits[0][1];
coordinatesZ[i12 + 3 + tuple_index[1]] = limits[1][0];
coordinatesZ[i12 + 3 + tuple_index[2]] = depth;
// corner 2
coordinatesZ[i12 + 6 + tuple_index[0]] = limits[0][1];
coordinatesZ[i12 + 6 + tuple_index[1]] = limits[1][1];
coordinatesZ[i12 + 6 + tuple_index[2]] = depth;
// corner 3
coordinatesZ[i12 + 9 + tuple_index[0]] = limits[0][0];
coordinatesZ[i12 + 9 + tuple_index[1]] = limits[1][1];
coordinatesZ[i12 + 9 + tuple_index[2]] = depth;
}
for (int i=0; i<data_height; i++) {
int i12 = i * 12;
float height = limits[1][0] +
(limits[1][1] - limits[1][0]) * i / (data_height - 1.0f);
// corner 0
coordinatesY[i12 + tuple_index[0]] = limits[0][0];
coordinatesY[i12 + tuple_index[1]] = height;
coordinatesY[i12 + tuple_index[2]] = limits[2][0];
// corner 1
coordinatesY[i12 + 3 + tuple_index[0]] = limits[0][1];
coordinatesY[i12 + 3 + tuple_index[1]] = height;
coordinatesY[i12 + 3 + tuple_index[2]] = limits[2][0];
// corner 2
coordinatesY[i12 + 6 + tuple_index[0]] = limits[0][1];
coordinatesY[i12 + 6 + tuple_index[1]] = height;
coordinatesY[i12 + 6 + tuple_index[2]] = limits[2][1];
// corner 3
coordinatesY[i12 + 9 + tuple_index[0]] = limits[0][0];
coordinatesY[i12 + 9 + tuple_index[1]] = height;
coordinatesY[i12 + 9 + tuple_index[2]] = limits[2][1];
}
for (int i=0; i<data_width; i++) {
int i12 = i * 12;
float width = limits[0][0] +
(limits[0][1] - limits[0][0]) * i / (data_width - 1.0f);
// corner 0
coordinatesX[i12 + tuple_index[0]] = width;
coordinatesX[i12 + tuple_index[1]] = limits[1][0];
coordinatesX[i12 + tuple_index[2]] = limits[2][0];
// corner 1
coordinatesX[i12 + 3 + tuple_index[0]] = width;
coordinatesX[i12 + 3 + tuple_index[1]] = limits[1][1];
coordinatesX[i12 + 3 + tuple_index[2]] = limits[2][0];
// corner 2
coordinatesX[i12 + 6 + tuple_index[0]] = width;
coordinatesX[i12 + 6 + tuple_index[1]] = limits[1][1];
coordinatesX[i12 + 6 + tuple_index[2]] = limits[2][1];
// corner 3
coordinatesX[i12 + 9 + tuple_index[0]] = width;
coordinatesX[i12 + 9 + tuple_index[1]] = limits[1][0];
coordinatesX[i12 + 9 + tuple_index[2]] = limits[2][1];
}
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
float ratiod = ((float) data_depth) / ((float) texture_depth);
/* WLH 3 June 99 - comment this out until Texture3D works on NT (etc)
texCoordsX =
shadow_api.setTex3DCoords(data_width, 0, ratiow, ratioh, ratiod);
texCoordsY =
shadow_api.setTex3DCoords(data_height, 1, ratiow, ratioh, ratiod);
texCoordsZ =
shadow_api.setTex3DCoords(data_depth, 2, ratiow, ratioh, ratiod);
*/
texCoordsX =
shadow_api.setTexStackCoords(data_width, 0, ratiow, ratioh, ratiod);
texCoordsY =
shadow_api.setTexStackCoords(data_height, 1, ratiow, ratioh, ratiod);
texCoordsZ =
shadow_api.setTexStackCoords(data_depth, 2, ratiow, ratioh, ratiod);
normalsX = new float[12 * data_width];
normalsY = new float[12 * data_height];
normalsZ = new float[12 * data_depth];
float n0, n1, n2, nlen;
n0 = ((coordinatesX[3+2]-coordinatesX[0+2]) *
(coordinatesX[6+1]-coordinatesX[0+1])) -
((coordinatesX[3+1]-coordinatesX[0+1]) *
(coordinatesX[6+2]-coordinatesX[0+2]));
n1 = ((coordinatesX[3+0]-coordinatesX[0+0]) *
(coordinatesX[6+2]-coordinatesX[0+2])) -
((coordinatesX[3+2]-coordinatesX[0+2]) *
(coordinatesX[6+0]-coordinatesX[0+0]));
n2 = ((coordinatesX[3+1]-coordinatesX[0+1]) *
(coordinatesX[6+0]-coordinatesX[0+0])) -
((coordinatesX[3+0]-coordinatesX[0+0]) *
(coordinatesX[6+1]-coordinatesX[0+1]));
nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
for (int i=0; i<normalsX.length; i+=3) {
normalsX[i] = n0;
normalsX[i + 1] = n1;
normalsX[i + 2] = n2;
}
n0 = ((coordinatesY[3+2]-coordinatesY[0+2]) *
(coordinatesY[6+1]-coordinatesY[0+1])) -
((coordinatesY[3+1]-coordinatesY[0+1]) *
(coordinatesY[6+2]-coordinatesY[0+2]));
n1 = ((coordinatesY[3+0]-coordinatesY[0+0]) *
(coordinatesY[6+2]-coordinatesY[0+2])) -
((coordinatesY[3+2]-coordinatesY[0+2]) *
(coordinatesY[6+0]-coordinatesY[0+0]));
n2 = ((coordinatesY[3+1]-coordinatesY[0+1]) *
(coordinatesY[6+0]-coordinatesY[0+0])) -
((coordinatesY[3+0]-coordinatesY[0+0]) *
(coordinatesY[6+1]-coordinatesY[0+1]));
nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
for (int i=0; i<normalsY.length; i+=3) {
normalsY[i] = n0;
normalsY[i + 1] = n1;
normalsY[i + 2] = n2;
}
n0 = ((coordinatesZ[3+2]-coordinatesZ[0+2]) *
(coordinatesZ[6+1]-coordinatesZ[0+1])) -
((coordinatesZ[3+1]-coordinatesZ[0+1]) *
(coordinatesZ[6+2]-coordinatesZ[0+2]));
n1 = ((coordinatesZ[3+0]-coordinatesZ[0+0]) *
(coordinatesZ[6+2]-coordinatesZ[0+2])) -
((coordinatesZ[3+2]-coordinatesZ[0+2]) *
(coordinatesZ[6+0]-coordinatesZ[0+0]));
n2 = ((coordinatesZ[3+1]-coordinatesZ[0+1]) *
(coordinatesZ[6+0]-coordinatesZ[0+0])) -
((coordinatesZ[3+0]-coordinatesZ[0+0]) *
(coordinatesZ[6+1]-coordinatesZ[0+1]));
nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
for (int i=0; i<normalsZ.length; i+=3) {
normalsZ[i] = n0;
normalsZ[i + 1] = n1;
normalsZ[i + 2] = n2;
}
colorsX = new byte[12 * data_width];
colorsY = new byte[12 * data_height];
colorsZ = new byte[12 * data_depth];
for (int i=0; i<12*data_width; i++) colorsX[i] = (byte) 127;
for (int i=0; i<12*data_height; i++) colorsY[i] = (byte) 127;
for (int i=0; i<12*data_depth; i++) colorsZ[i] = (byte) 127;
/*
for (int i=0; i < 4; i++) {
System.out.println("i = " + i + " texCoordsX = " + texCoordsX[3 * i] + " " +
texCoordsX[3 * i + 1]);
System.out.println(" coordinatesX = " + coordinatesX[3 * i] + " " +
coordinatesX[3 * i + 1] + " " + coordinatesX[3 * i + 2]);
System.out.println(" normalsX = " + normalsX[3 * i] + " " +
normalsX[3 * i + 1] + " " + normalsX[3 * i + 2]);
}
*/
}
// WLH 1 April 2000
// else { // !isTextureMap && !isTexture3D
// WLH 16 July 2000 - add '&& !isLinearContour3D'
if (!isTextureMap && (!isTexture3D || range3D) && !isLinearContour3D) {
// if (link != null) System.out.println("start domain " + (System.currentTimeMillis() - link.start_time));
// get values from Function Domain
// NOTE - may defer this until needed, if needed
if (domain_dimension == 1) {
domain_doubles = domain_set.getDoubles(false);
domain_doubles = Unit.convertTuple(domain_doubles, dataUnits, domain_units);
mapValues(display_values, domain_doubles, DomainComponents);
}
else {
domain_values = domain_set.getSamples(false);
// convert values to default units (used in display)
// MEM & FREE
domain_values = Unit.convertTuple(domain_values, dataUnits, domain_units);
// System.out.println("got domain_values: domain_length = " + domain_length);
// map domain_values to appropriate DisplayRealType-s
// MEM
mapValues(display_values, domain_values, DomainComponents);
}
// System.out.println("mapped domain_values");
ShadowRealTupleType domain_reference = Domain.getReference();
/*
System.out.println("domain_reference = " + domain_reference);
if (domain_reference != null) {
System.out.println("getMappedDisplayScalar = " +
domain_reference.getMappedDisplayScalar());
}
*/
// if (link != null) System.out.println("end domain " + (System.currentTimeMillis() - link.start_time));
if (domain_reference != null && domain_reference.getMappedDisplayScalar()) {
// apply coordinate transform to domain values
RealTupleType ref = (RealTupleType) domain_reference.getType();
// MEM
float[][] reference_values = null;
double[][] reference_doubles = null;
if (domain_dimension == 1) {
reference_doubles =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) Domain.getType(), dataCoordinateSystem,
domain_units, null, domain_doubles);
}
else {
// WLH 23 June 99
if (curvedTexture && domainOnlySpatial) {
//if (link != null) System.out.println("start compute spline " + (System.currentTimeMillis() - link.start_time));
int[] lengths = ((GriddedSet) domain_set).getLengths();
data_width = lengths[0];
data_height = lengths[1];
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
int size = (data_width + data_height) / 2;
curved_size = Math.max(1, Math.min(curved_size, size / 32));
int nwidth = 2 + (data_width - 1) / curved_size;
int nheight = 2 + (data_height - 1) / curved_size;
/*
System.out.println("data_width = " + data_width + " data_height = " + data_height +
" texture_width = " + texture_width + " texture_height = " + texture_height +
" nwidth = " + nwidth + " nheight = " + nheight);
*/
int nn = nwidth * nheight;
int[] is = new int[nwidth];
int[] js = new int[nheight];
for (int i=0; i<nwidth; i++) {
is[i] = Math.min(i * curved_size, data_width - 1);
}
for (int j=0; j<nheight; j++) {
js[j] = Math.min(j * curved_size, data_height - 1);
}
- float[][] spline_domain = new float[2][nwidth * nheight];
+// int domain_dimension = domain_values.length;
+if (domain_dimension != domain_values.length) {
+ throw new VisADException("domain_dimension = " + domain_dimension +
+ " domain_values.length = " + domain_values.length);
+}
+ // float[][] spline_domain = new float[2][nwidth * nheight]; WLH 22 Aug 2002
+float[][] spline_domain = new float[domain_dimension][nwidth * nheight];
int k = 0;
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
int ij = is[i] + data_width * js[j];
spline_domain[0][k] = domain_values[0][ij];
spline_domain[1][k] = domain_values[1][ij];
+if (domain_dimension == 3) spline_domain[2][k] = domain_values[2][ij];
k++;
}
}
float[][] spline_reference =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) Domain.getType(), dataCoordinateSystem,
domain_units, null, spline_domain);
- reference_values = new float[2][domain_length];
+ // reference_values = new float[2][domain_length]; WLH 22 Aug 2002
+reference_values = new float[domain_dimension][domain_length];
for (int i=0; i<domain_length; i++) {
reference_values[0][i] = Float.NaN;
reference_values[1][i] = Float.NaN;
+if (domain_dimension == 3) reference_values[2][i] = Float.NaN;
}
k = 0;
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
int ij = is[i] + data_width * js[j];
reference_values[0][ij] = spline_reference[0][k];
reference_values[1][ij] = spline_reference[1][k];
+if (domain_dimension == 3) reference_values[2][ij] = spline_reference[2][k];
k++;
}
}
// if (link != null) System.out.println("end compute spline " + (System.currentTimeMillis() - link.start_time));
}
else { // if !(curvedTexture && domainOnlySpatial)
reference_values =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) Domain.getType(), dataCoordinateSystem,
domain_units, null, domain_values);
}
} // end if !(domain_dimension == 1)
// WLH 13 Macrh 2000
// if (anyFlow) {
renderer.setEarthSpatialData(Domain, domain_reference, ref,
ref.getDefaultUnits(), (RealTupleType) Domain.getType(),
new CoordinateSystem[] {dataCoordinateSystem},
domain_units);
// WLH 13 Macrh 2000
// }
//
// TO_DO
// adjust any RealVectorTypes in range
// see FlatField.resample and FieldImpl.resample
//
// if (link != null) System.out.println("start map reference " + (System.currentTimeMillis() - link.start_time));
// map reference_values to appropriate DisplayRealType-s
ShadowRealType[] DomainReferenceComponents = getDomainReferenceComponents();
// MEM
if (domain_dimension == 1) {
mapValues(display_values, reference_doubles, DomainReferenceComponents);
}
else {
mapValues(display_values, reference_values, DomainReferenceComponents);
}
// if (link != null) System.out.println("end map reference " + (System.currentTimeMillis() - link.start_time));
/*
for (int i=0; i<DomainReferenceComponents.length; i++) {
System.out.println("DomainReferenceComponents[" + i + "] = " +
DomainReferenceComponents[i]);
System.out.println("reference_values[" + i + "].length = " +
reference_values[i].length);
}
System.out.println("mapped domain_reference values");
*/
// FREE
reference_values = null;
reference_doubles = null;
}
else { // if !(domain_reference != null &&
// domain_reference.getMappedDisplayScalar())
// WLH 13 March 2000
// if (anyFlow) {
/* WLH 23 May 99
renderer.setEarthSpatialData(Domain, null, null,
null, (RealTupleType) Domain.getType(),
new CoordinateSystem[] {dataCoordinateSystem},
domain_units);
*/
RealTupleType ref = (domain_reference == null) ? null :
(RealTupleType) domain_reference.getType();
Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits();
renderer.setEarthSpatialData(Domain, domain_reference, ref,
ref_units, (RealTupleType) Domain.getType(),
new CoordinateSystem[] {dataCoordinateSystem},
domain_units);
// WLH 13 March 2000
// }
}
// FREE
domain_values = null;
domain_doubles = null;
} // end if (!isTextureMap && (!isTexture3D || range3D) &&
// !isLinearContour3D)
if (this instanceof ShadowFunctionType) {
// if (link != null) System.out.println("start range " + (System.currentTimeMillis() - link.start_time));
// get range_values for RealType and RealTupleType
// components, in defaultUnits for RealType-s
// MEM - may copy (in convertTuple)
float[][] range_values = ((Field) data).getFloats(false);
// System.out.println("got range_values");
if (range_values != null) {
// map range_values to appropriate DisplayRealType-s
ShadowRealType[] RangeComponents = getRangeComponents();
// MEM
mapValues(display_values, range_values, RangeComponents);
// System.out.println("mapped range_values");
//
// transform any range CoordinateSystem-s
// into display_values, then mapValues
//
int[] refToComponent = getRefToComponent();
ShadowRealTupleType[] componentWithRef = getComponentWithRef();
int[] componentIndex = getComponentIndex();
if (refToComponent != null) {
for (int i=0; i<refToComponent.length; i++) {
int n = componentWithRef[i].getDimension();
int start = refToComponent[i];
float[][] values = new float[n][];
for (int j=0; j<n; j++) values[j] = range_values[j + start];
ShadowRealTupleType component_reference =
componentWithRef[i].getReference();
RealTupleType ref = (RealTupleType) component_reference.getType();
Unit[] range_units;
CoordinateSystem[] range_coord_sys;
if (i == 0 && componentWithRef[i].equals(Range)) {
range_units = ((Field) data).getDefaultRangeUnits();
range_coord_sys = ((Field) data).getRangeCoordinateSystem();
}
else {
Unit[] dummy_units = ((Field) data).getDefaultRangeUnits();
range_units = new Unit[n];
for (int j=0; j<n; j++) range_units[j] = dummy_units[j + start];
range_coord_sys =
((Field) data).getRangeCoordinateSystem(componentIndex[i]);
}
float[][] reference_values = null;
if (range_coord_sys.length == 1) {
// MEM
reference_values =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys[0], range_units, null, values);
// WLH 13 March 2000
// if (anyFlow) {
renderer.setEarthSpatialData(componentWithRef[i],
component_reference, ref, ref.getDefaultUnits(),
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys, range_units);
// WLH 13 March 2000
// }
}
else {
// MEM
reference_values = new float[n][domain_length];
float[][] temp = new float[n][1];
for (int j=0; j<domain_length; j++) {
for (int k=0; k<n; k++) temp[k][0] = values[k][j];
temp =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys[j], range_units, null, temp);
for (int k=0; k<n; k++) reference_values[k][j] = temp[k][0];
}
// WLH 13 March 2000
// if (anyFlow) {
renderer.setEarthSpatialData(componentWithRef[i],
component_reference, ref, ref.getDefaultUnits(),
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys, range_units);
// WLH 13 March 2000
// }
}
// map reference_values to appropriate DisplayRealType-s
// MEM
/* WLH 17 April 99
mapValues(display_values, reference_values,
getComponents(componentWithRef[i], false));
*/
mapValues(display_values, reference_values,
getComponents(component_reference, false));
// FREE
reference_values = null;
// FREE (redundant reference to range_values)
values = null;
} // end for (int i=0; i<refToComponent.length; i++)
} // end (refToComponent != null)
// if (link != null) System.out.println("end range " + (System.currentTimeMillis() - link.start_time));
// setEarthSpatialData calls when no CoordinateSystem
// WLH 13 March 2000
// if (Range instanceof ShadowTupleType && anyFlow) {
if (Range instanceof ShadowTupleType) {
if (Range instanceof ShadowRealTupleType) {
Unit[] range_units = ((Field) data).getDefaultRangeUnits();
CoordinateSystem[] range_coord_sys =
((Field) data).getRangeCoordinateSystem();
/* WLH 23 May 99
renderer.setEarthSpatialData((ShadowRealTupleType) Range,
null, null, null, (RealTupleType) Range.getType(),
range_coord_sys, range_units);
*/
ShadowRealTupleType component_reference =
((ShadowRealTupleType) Range).getReference();
RealTupleType ref = (component_reference == null) ? null :
(RealTupleType) component_reference.getType();
Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits();
renderer.setEarthSpatialData((ShadowRealTupleType) Range,
component_reference, ref, ref_units,
(RealTupleType) Range.getType(),
range_coord_sys, range_units);
}
else { // if (!(Range instanceof ShadowRealTupleType))
Unit[] dummy_units = ((Field) data).getDefaultRangeUnits();
int start = 0;
int n = ((ShadowTupleType) Range).getDimension();
for (int i=0; i<n ;i++) {
ShadowType range_component =
((ShadowTupleType) Range).getComponent(i);
if (range_component instanceof ShadowRealTupleType) {
int m = ((ShadowRealTupleType) range_component).getDimension();
Unit[] range_units = new Unit[m];
for (int j=0; j<m; j++) range_units[j] = dummy_units[j + start];
CoordinateSystem[] range_coord_sys =
((Field) data).getRangeCoordinateSystem(i);
/* WLH 23 May 99
renderer.setEarthSpatialData((ShadowRealTupleType)
range_component, null, null,
null, (RealTupleType) range_component.getType(),
range_coord_sys, range_units);
*/
ShadowRealTupleType component_reference =
((ShadowRealTupleType) range_component).getReference();
RealTupleType ref = (component_reference == null) ? null :
(RealTupleType) component_reference.getType();
Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits();
renderer.setEarthSpatialData((ShadowRealTupleType) range_component,
component_reference, ref, ref_units,
(RealTupleType) range_component.getType(),
range_coord_sys, range_units);
start += ((ShadowRealTupleType) range_component).getDimension();
}
else if (range_component instanceof ShadowRealType) {
start++;
}
}
} // end if (!(Range instanceof ShadowRealTupleType))
} // end if (Range instanceof ShadowTupleType)
// FREE
range_values = null;
} // end if (range_values != null)
if (anyText && text_values == null) {
for (int i=0; i<valueArrayLength; i++) {
if (display_values[i] != null) {
int displayScalarIndex = valueToScalar[i];
ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]);
ScalarType real = map.getScalar();
DisplayRealType dreal = display.getDisplayScalar(displayScalarIndex);
if (dreal.equals(Display.Text) && real instanceof RealType) {
text_control = (TextControl) map.getControl();
text_values = new String[domain_length];
NumberFormat format = text_control.getNumberFormat();
if (display_values[i].length == 1) {
String text = null;
if (display_values[i][0] != display_values[i][0]) {
text = "";
}
else if (format == null) {
text = PlotText.shortString(display_values[i][0]);
}
else {
text = format.format(display_values[i][0]);
}
for (int j=0; j<domain_length; j++) {
text_values[j] = text;
}
}
else {
if (format == null) {
for (int j=0; j<domain_length; j++) {
if (display_values[i][j] != display_values[i][j]) {
text_values[j] = "";
}
else {
text_values[j] = PlotText.shortString(display_values[i][j]);
}
}
}
else {
for (int j=0; j<domain_length; j++) {
if (display_values[i][j] != display_values[i][j]) {
text_values[j] = "";
}
else {
text_values[j] = format.format(display_values[i][j]);
}
}
}
}
break;
}
}
}
if (text_values == null) {
String[][] string_values = ((Field) data).getStringValues();
if (string_values != null) {
int[] textIndices = ((FunctionType) getType()).getTextIndices();
int n = string_values.length;
if (Range instanceof ShadowTextType) {
Vector maps = shadow_api.getTextMaps(-1, textIndices);
if (!maps.isEmpty()) {
text_values = string_values[0];
ScalarMap map = (ScalarMap) maps.firstElement();
text_control = (TextControl) map.getControl();
/*
System.out.println("Range is ShadowTextType, text_values[0] = " +
text_values[0] + " n = " + n);
*/
}
}
else if (Range instanceof ShadowTupleType) {
for (int i=0; i<n; i++) {
Vector maps = shadow_api.getTextMaps(i, textIndices);
if (!maps.isEmpty()) {
text_values = string_values[i];
ScalarMap map = (ScalarMap) maps.firstElement();
text_control = (TextControl) map.getControl();
/*
System.out.println("Range is ShadowTupleType, text_values[0] = " +
text_values[0] + " n = " + n + " i = " + i);
*/
}
}
} // end if (Range instanceof ShadowTupleType)
} // end if (string_values != null)
} // end if (text_values == null)
} // end if (anyText && text_values == null)
} // end if (this instanceof ShadowFunctionType)
// if (link != null) System.out.println("start assembleSelect " + (System.currentTimeMillis() - link.start_time));
//
// NOTE -
// currently assuming SelectRange changes require Transform
// see DataRenderer.isTransformControl
//
// get array that composites SelectRange components
// range_select is null if all selected
// MEM
boolean[][] range_select =
shadow_api.assembleSelect(display_values, domain_length, valueArrayLength,
valueToScalar, display, shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleSelect: numforced = " + numforced);
}
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// if (link != null) System.out.println("end assembleSelect " + (System.currentTimeMillis() - link.start_time));
// System.out.println("assembleSelect");
/*
System.out.println("doTerminal: isTerminal = " + getIsTerminal() +
" LevelOfDifficulty = " + LevelOfDifficulty);
*/
if (getIsTerminal()) {
if (!getFlat()) {
throw new DisplayException("terminal but not Flat");
}
GraphicsModeControl mode = (GraphicsModeControl)
display.getGraphicsModeControl().clone();
float pointSize =
default_values[display.getDisplayScalarIndex(Display.PointSize)];
mode.setPointSize(pointSize, true);
float lineWidth =
default_values[display.getDisplayScalarIndex(Display.LineWidth)];
mode.setLineWidth(lineWidth, true);
int lineStyle = (int)
default_values[display.getDisplayScalarIndex(Display.LineStyle)];
mode.setLineStyle(lineStyle, true);
boolean pointMode = mode.getPointMode();
byte missing_transparent = (byte) (mode.getMissingTransparent() ? 0 : -1);
// if (link != null) System.out.println("start assembleColor " + (System.currentTimeMillis() - link.start_time));
// MEM_WLH - this moved
boolean[] single_missing = {false, false, false, false};
// assemble an array of RGBA values
// MEM
byte[][] color_values =
shadow_api.assembleColor(display_values, valueArrayLength, valueToScalar,
display, default_values, range_select,
single_missing, shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleColor: numforced = " + numforced);
}
*/
/*
if (color_values != null) {
System.out.println("color_values.length = " + color_values.length +
" color_values[0].length = " + color_values[0].length);
System.out.println(color_values[0][0] + " " + color_values[1][0] +
" " + color_values[2][0]);
}
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// if (link != null) System.out.println("end assembleColor " + (System.currentTimeMillis() - link.start_time));
float[][] flow1_values = new float[3][];
float[][] flow2_values = new float[3][];
float[] flowScale = new float[2];
// MEM
shadow_api.assembleFlow(flow1_values, flow2_values, flowScale,
display_values, valueArrayLength, valueToScalar,
display, default_values, range_select, renderer,
shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleFlow: numforced = " + numforced);
}
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// System.out.println("assembleFlow");
// assemble an array of Display.DisplaySpatialCartesianTuple values
// and possibly spatial_set
float[][] spatial_values = new float[3][];
// spatialDimensions[0] = spatialDomainDimension and
// spatialDimensions[1] = spatialManifoldDimension
int[] spatialDimensions = new int[2];
// flags for swapping rows and columns in contour labels
boolean[] swap = {false, false, false};
// if (link != null) System.out.println("start assembleSpatial " + (System.currentTimeMillis() - link.start_time));
// WLH 29 April 99
boolean[][] spatial_range_select = new boolean[1][];
// MEM - but not if isTextureMap
Set spatial_set =
shadow_api.assembleSpatial(spatial_values, display_values, valueArrayLength,
valueToScalar, display, default_values,
inherited_values, domain_set, Domain.getAllSpatial(),
anyContour && !isLinearContour3D,
spatialDimensions, spatial_range_select,
flow1_values, flow2_values, flowScale, swap, renderer,
shadow_api);
if (isLinearContour3D) {
spatial_set = domain_set;
spatialDimensions[0] = 3;
spatialDimensions[1] = 3;
}
// WLH 29 April 99
boolean spatial_all_select = true;
if (spatial_range_select[0] != null) {
spatial_all_select = false;
if (range_select[0] == null) {
range_select[0] = spatial_range_select[0];
}
else if (spatial_range_select[0].length == 1) {
for (int j=0; j<range_select[0].length; j++) {
range_select[0][j] =
range_select[0][j] && spatial_range_select[0][0];
}
}
else {
for (int j=0; j<range_select[0].length; j++) {
range_select[0][j] =
range_select[0][j] && spatial_range_select[0][j];
}
}
}
spatial_range_select = null;
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleSpatial: numforced = " + numforced);
}
*/
/*
System.out.println("assembleSpatial (spatial_set == null) = " +
(spatial_set == null));
if (spatial_set != null) {
System.out.println("spatial_set.length = " + spatial_set.getLength());
}
System.out.println(" spatial_values lengths = " + spatial_values[0].length +
" " + spatial_values[1].length + " " + spatial_values[2].length);
System.out.println(" isTextureMap = " + isTextureMap);
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// if (link != null) System.out.println("end assembleSpatial " + (System.currentTimeMillis() - link.start_time));
int spatialDomainDimension = spatialDimensions[0];
int spatialManifoldDimension = spatialDimensions[1];
// System.out.println("assembleSpatial");
int spatial_length = Math.min(domain_length, spatial_values[0].length);
int color_length = Math.min(domain_length, color_values[0].length);
int alpha_length = color_values[3].length;
/*
System.out.println("assembleColor, color_length = " + color_length +
" " + color_values.length);
*/
// if (link != null) System.out.println("start missing color " + (System.currentTimeMillis() - link.start_time));
float constant_alpha = Float.NaN;
float[] constant_color = null;
// note alpha_length <= color_length
if (alpha_length == 1) {
/* MEM_WLH
if (color_values[3][0] != color_values[3][0]) {
*/
if (single_missing[3]) {
// a single missing alpha value, so render nothing
// System.out.println("single missing alpha");
return false;
}
// System.out.println("single alpha " + color_values[3][0]);
// constant alpha, so put it in appearance
/* MEM_WLH
if (color_values[3][0] > 0.999999f) {
*/
if (color_values[3][0] == -1) { // = 255 unsigned
constant_alpha = 0.0f;
// constant_alpha = 1.0f; WLH 26 May 99
// remove alpha from color_values
byte[][] c = new byte[3][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
color_values = c;
}
else { // not opaque
/* TransparencyAttributes with constant alpha seems to have broken
from The Java 3D API Specification: p. 118 transparency = 1 - alpha,
p. 116 transparency 0.0 = opaque, 1.0 = clear */
/*
broken alpha - put it back when alpha fixed
constant_alpha =
new TransparencyAttributes(TransparencyAttributes.NICEST,
1.0f - byteToFloat(color_values[3][0]));
so expand constant alpha to variable alpha
and note no alpha in Java2D:
*/
byte v = color_values[3][0];
color_values[3] = new byte[color_values[0].length];
for (int i=0; i<color_values[0].length; i++) {
color_values[3][i] = v;
}
/*
System.out.println("replicate alpha = " + v + " " + constant_alpha +
" " + color_values[0].length + " " +
color_values[3].length);
*/
} // end not opaque
/*
broken alpha - put it back when alpha fixed
// remove alpha from color_values
byte[][] c = new byte[3][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
color_values = c;
*/
} // end if (alpha_length == 1)
if (color_length == 1) {
if (spatialManifoldDimension == 1 ||
shadow_api.allowConstantColorSurfaces()) {
/* MEM_WLH
if (color_values[0][0] != color_values[0][0] ||
color_values[1][0] != color_values[1][0] ||
color_values[2][0] != color_values[2][0]) {
*/
if (single_missing[0] || single_missing[1] ||
single_missing[2]) {
// System.out.println("single missing color");
// a single missing color value, so render nothing
return false;
}
/* MEM_WLH
constant_color = new float[] {color_values[0][0], color_values[1][0],
color_values[2][0]};
*/
constant_color = new float[] {byteToFloat(color_values[0][0]),
byteToFloat(color_values[1][0]),
byteToFloat(color_values[2][0])};
color_values = null; // in this case, alpha doesn't matter
}
else {
// constant color doesn't work for surfaces in Java3D
// because of lighting
byte[][] c = new byte[color_values.length][domain_length];
for (int i=0; i<color_values.length; i++) {
for (int j=0; j<domain_length; j++) {
c[i][j] = color_values[i][0];
}
}
color_values = c;
}
} // end if (color_length == 1)
// if (link != null) System.out.println("end missing color " + (System.currentTimeMillis() - link.start_time));
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
if (LevelOfDifficulty == SIMPLE_FIELD) {
// only manage Spatial, Contour, Flow, Color, Alpha and
// SelectRange here
//
// TO_DO
// Flow rendering trajectories, which will be tricky -
// FlowControl must contain trajectory start points
//
/* MISSING TEST
for (int i=0; i<spatial_values[0].length; i+=3) {
spatial_values[0][i] = Float.NaN;
}
END MISSING TEST */
//
// TO_DO
// missing color_values and range_select
//
// in Java3D:
// NaN color component values are rendered as 1.0
// NaN spatial component values of points are NOT rendered
// NaN spatial component values of lines are rendered at infinity
// NaN spatial component values of triangles are a mess ??
//
/*
System.out.println("spatialDomainDimension = " +
spatialDomainDimension +
" spatialManifoldDimension = " +
spatialManifoldDimension +
" anyContour = " + anyContour +
" pointMode = " + pointMode);
*/
VisADGeometryArray array;
boolean anyShapeCreated = false;
VisADGeometryArray[] arrays =
shadow_api.assembleShape(display_values, valueArrayLength, valueToMap,
MapVector, valueToScalar, display, default_values,
inherited_values, spatial_values, color_values,
range_select, -1, shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleShape: numforced = " + numforced);
}
*/
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
array = arrays[i];
shadow_api.addToGroup(group, array, mode,
constant_alpha, constant_color);
array = null;
/* WLH 13 March 99 - why null in place of constant_alpha?
appearance = makeAppearance(mode, null, constant_color, geometry);
*/
}
anyShapeCreated = true;
arrays = null;
}
boolean anyTextCreated = false;
if (anyText && text_values != null && text_control != null) {
array = shadow_api.makeText(text_values, text_control, spatial_values,
color_values, range_select);
shadow_api.addTextToGroup(group, array, mode,
constant_alpha, constant_color);
array = null;
anyTextCreated = true;
}
boolean anyFlowCreated = false;
if (anyFlow) {
// try Flow1
arrays = shadow_api.makeStreamline(0, flow1_values, flowScale[0],
spatial_values, spatial_set, spatialManifoldDimension,
color_values, range_select);
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
if (arrays[i] != null) {
shadow_api.addToGroup(group, arrays[i], mode,
constant_alpha, constant_color);
arrays[i] = null;
}
}
}
else {
arrays = shadow_api.makeFlow(0, flow1_values, flowScale[0],
spatial_values, color_values, range_select);
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
if (arrays[i] != null) {
shadow_api.addToGroup(group, arrays[i], mode,
constant_alpha, constant_color);
arrays[i] = null;
}
}
}
}
anyFlowCreated = true;
// try Flow2
arrays = shadow_api.makeStreamline(1, flow2_values, flowScale[1],
spatial_values, spatial_set, spatialManifoldDimension,
color_values, range_select);
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
if (arrays[i] != null) {
shadow_api.addToGroup(group, arrays[i], mode,
constant_alpha, constant_color);
arrays[i] = null;
}
}
}
else {
arrays = shadow_api.makeFlow(1, flow2_values, flowScale[1],
spatial_values, color_values, range_select);
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
if (arrays[i] != null) {
shadow_api.addToGroup(group, arrays[i], mode,
constant_alpha, constant_color);
arrays[i] = null;
}
}
}
}
anyFlowCreated = true;
}
boolean anyContourCreated = false;
if (anyContour) {
/* Test01 at 64 x 64 x 64
domain 701, 491
range 20, 20
assembleColor 210, 201
assembleSpatial 130, 140
makeIsoSurface 381, 520
makeGeometry 350, 171
all makeGeometry time in calls to Java3D constructors, setCoordinates, etc
*/
// if (link != null) System.out.println("start makeContour " + (System.currentTimeMillis() - link.start_time));
anyContourCreated =
shadow_api.makeContour(valueArrayLength, valueToScalar,
display_values, inherited_values, MapVector, valueToMap,
domain_length, range_select, spatialManifoldDimension,
spatial_set, color_values, indexed, group, mode,
swap, constant_alpha, constant_color, shadow_api);
// if (link != null) System.out.println("end makeContour " + (System.currentTimeMillis() - link.start_time));
} // end if (anyContour)
if (!anyContourCreated && !anyFlowCreated &&
!anyTextCreated && !anyShapeCreated) {
// MEM
if (isTextureMap) {
if (color_values == null) {
// must be color_values array for texture mapping
color_values = new byte[3][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
if (range_select[0] != null && range_select[0].length > 1) {
int len = range_select[0].length;
/* can be misleading because of the way transparency composites
float alpha =
default_values[display.getDisplayScalarIndex(Display.Alpha)];
// System.out.println("alpha = " + alpha);
if (constant_alpha == constant_alpha) {
alpha = 1.0f - constant_alpha;
// System.out.println("constant_alpha = " + alpha);
}
if (color_values.length < 4) {
byte[][] c = new byte[4][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
c[3] = new byte[len];
for (int i=0; i<len; i++) c[3][i] = floatToByte(alpha);
constant_alpha = Float.NaN;
color_values = c;
}
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel invisible (transparent)
color_values[3][i] = 0;
}
}
*/
// WLH 27 March 2000
float alpha =
default_values[display.getDisplayScalarIndex(Display.Alpha)];
// System.out.println("alpha = " + alpha);
if (constant_alpha == constant_alpha) {
alpha = 1.0f - constant_alpha;
// System.out.println("constant_alpha = " + alpha);
}
if (color_values.length < 4) {
byte[][] c = new byte[4][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
c[3] = new byte[len];
for (int i=0; i<len; i++) c[3][i] = floatToByte(alpha);
constant_alpha = Float.NaN;
color_values = c;
}
if (mode.getMissingTransparent()) {
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel invisible (transparent)
color_values[3][i] = 0;
}
}
}
else {
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel black
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
} // end if (range_select[0] != null)
// MEM
VisADQuadArray qarray = new VisADQuadArray();
qarray.vertexCount = 4;
qarray.coordinates = coordinates;
qarray.texCoords = texCoords;
qarray.colors = colors;
qarray.normals = normals;
BufferedImage image =
createImage(data_width, data_height, texture_width,
texture_height, color_values);
shadow_api.textureToGroup(group, qarray, image, mode,
constant_alpha, constant_color,
texture_width, texture_height);
// System.out.println("isTextureMap done");
return false;
} // end if (isTextureMap)
else if (curvedTexture) {
// if (link != null) System.out.println("start texture " + (System.currentTimeMillis() - link.start_time));
if (color_values == null) { // never true?
// must be color_values array for texture mapping
color_values = new byte[3][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
if (range_select[0] != null) {
// WLH 27 March 2000
if (mode.getMissingTransparent()) {
spatial_set.cram_missing(range_select[0]);
spatial_all_select = false;
}
else {
for (int i=0; i<domain_length; i++) {
if (!range_select[0][i]) {
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
/* WLH 6 May 99
color_values =
selectToColor(range_select, color_values, constant_color,
constant_alpha, missing_transparent);
constant_alpha = Float.NaN;
*/
}
// get domain_set sizes
int[] lengths = ((GriddedSet) domain_set).getLengths();
data_width = lengths[0];
data_height = lengths[1];
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
int size = (data_width + data_height) / 2;
curved_size = Math.max(2, Math.min(curved_size, size / 32));
int nwidth = 2 + (data_width - 1) / curved_size;
int nheight = 2 + (data_height - 1) / curved_size;
// WLH 14 Aug 2001
if (range_select[0] != null && !domainOnlySpatial) {
// System.out.println("force curved_size = 1");
curved_size = 1;
nwidth = data_width;
nheight = data_height;
}
// System.out.println("curved_size = " + curved_size);
int nn = nwidth * nheight;
coordinates = new float[3 * nn];
int k = 0;
int[] is = new int[nwidth];
int[] js = new int[nheight];
for (int i=0; i<nwidth; i++) {
is[i] = Math.min(i * curved_size, data_width - 1);
}
for (int j=0; j<nheight; j++) {
js[j] = Math.min(j * curved_size, data_height - 1);
}
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
int ij = is[i] + data_width * js[j];
coordinates[k++] = spatial_values[0][ij];
coordinates[k++] = spatial_values[1][ij];
coordinates[k++] = spatial_values[2][ij];
/*
double size = Math.sqrt(spatial_values[0][ij] * spatial_values[0][ij] +
spatial_values[1][ij] * spatial_values[1][ij] +
spatial_values[2][ij] * spatial_values[2][ij]);
if (size < 0.2) {
System.out.println("spatial_values " + is[i] + " " + js[j] + " " +
spatial_values[0][ij] + " " + spatial_values[1][ij] + " " + spatial_values[2][ij]);
}
*/
}
}
normals = Gridded3DSet.makeNormals(coordinates, nwidth, nheight);
colors = new byte[3 * nn];
for (int i=0; i<3*nn; i++) colors[i] = (byte) 127;
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
int mt = 0;
texCoords = new float[2 * nn];
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
texCoords[mt++] = ratiow * is[i] / (data_width - 1.0f);
texCoords[mt++] = 1.0f - ratioh * js[j] / (data_height - 1.0f);
}
}
VisADTriangleStripArray tarray = new VisADTriangleStripArray();
tarray.stripVertexCounts = new int[nheight - 1];
for (int i=0; i<nheight - 1; i++) {
tarray.stripVertexCounts[i] = 2 * nwidth;
}
int len = (nheight - 1) * (2 * nwidth);
tarray.vertexCount = len;
tarray.normals = new float[3 * len];
tarray.coordinates = new float[3 * len];
tarray.colors = new byte[3 * len];
tarray.texCoords = new float[2 * len];
// shuffle normals into tarray.normals, etc
k = 0;
int kt = 0;
int nwidth3 = 3 * nwidth;
int nwidth2 = 2 * nwidth;
for (int i=0; i<nheight-1; i++) {
int m = i * nwidth3;
mt = i * nwidth2;
for (int j=0; j<nwidth; j++) {
tarray.coordinates[k] = coordinates[m];
tarray.coordinates[k+1] = coordinates[m+1];
tarray.coordinates[k+2] = coordinates[m+2];
tarray.coordinates[k+3] = coordinates[m+nwidth3];
tarray.coordinates[k+4] = coordinates[m+nwidth3+1];
tarray.coordinates[k+5] = coordinates[m+nwidth3+2];
tarray.normals[k] = normals[m];
tarray.normals[k+1] = normals[m+1];
tarray.normals[k+2] = normals[m+2];
tarray.normals[k+3] = normals[m+nwidth3];
tarray.normals[k+4] = normals[m+nwidth3+1];
tarray.normals[k+5] = normals[m+nwidth3+2];
tarray.colors[k] = colors[m];
tarray.colors[k+1] = colors[m+1];
tarray.colors[k+2] = colors[m+2];
tarray.colors[k+3] = colors[m+nwidth3];
tarray.colors[k+4] = colors[m+nwidth3+1];
tarray.colors[k+5] = colors[m+nwidth3+2];
tarray.texCoords[kt] = texCoords[mt];
tarray.texCoords[kt+1] = texCoords[mt+1];
tarray.texCoords[kt+2] = texCoords[mt+nwidth2];
tarray.texCoords[kt+3] = texCoords[mt+nwidth2+1];
k += 6;
m += 3;
kt += 4;
mt += 2;
}
}
if (!spatial_all_select) {
tarray = (VisADTriangleStripArray) tarray.removeMissing();
}
tarray = (VisADTriangleStripArray) tarray.adjustLongitude(renderer);
tarray = (VisADTriangleStripArray) tarray.adjustSeam(renderer);
BufferedImage image =
createImage(data_width, data_height, texture_width,
texture_height, color_values);
shadow_api.textureToGroup(group, tarray, image, mode,
constant_alpha, constant_color,
texture_width, texture_height);
// System.out.println("curvedTexture done");
// if (link != null) System.out.println("end texture " + (System.currentTimeMillis() - link.start_time));
return false;
} // end if (curvedTexture)
else if (isTexture3D) {
if (color_values == null) {
// must be color_values array for texture mapping
color_values = new byte[3][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
if (range_select[0] != null && range_select[0].length > 1) {
int len = range_select[0].length;
/* can be misleading because of the way transparency composites
WLH 15 March 2000 */
float alpha =
default_values[display.getDisplayScalarIndex(Display.Alpha)];
if (constant_alpha == constant_alpha) {
alpha = 1.0f - constant_alpha;
}
if (color_values.length < 4) {
byte[][] c = new byte[4][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
c[3] = new byte[len];
for (int i=0; i<len; i++) c[3][i] = floatToByte(alpha);
constant_alpha = Float.NaN;
color_values = c;
}
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel invisible (transparent)
color_values[3][i] = 0;
// WLH 15 March 2000
// make missing pixel black
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
/* WLH 15 March 2000 */
/* WLH 15 March 2000
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel black
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
*/
} // end if (range_select[0] != null)
// MEM
VisADQuadArray[] qarray =
{new VisADQuadArray(), new VisADQuadArray(), new VisADQuadArray()};
qarray[0].vertexCount = coordinatesX.length / 3;
qarray[0].coordinates = coordinatesX;
qarray[0].texCoords = texCoordsX;
qarray[0].colors = colorsX;
qarray[0].normals = normalsX;
qarray[1].vertexCount = coordinatesY.length / 3;
qarray[1].coordinates = coordinatesY;
qarray[1].texCoords = texCoordsY;
qarray[1].colors = colorsY;
qarray[1].normals = normalsY;
qarray[2].vertexCount = coordinatesZ.length / 3;
qarray[2].coordinates = coordinatesZ;
qarray[2].texCoords = texCoordsZ;
qarray[2].colors = colorsZ;
qarray[2].normals = normalsZ;
// WLH 3 June 99 - until Texture3D works on NT (etc)
BufferedImage[][] images = new BufferedImage[3][];
for (int i=0; i<3; i++) {
images[i] = createImages(i, data_width, data_height, data_depth,
texture_width, texture_height, texture_depth,
color_values);
}
BufferedImage[] imagesX = null;
BufferedImage[] imagesY = null;
BufferedImage[] imagesZ = null;
VisADQuadArray qarrayX = null;
VisADQuadArray qarrayY = null;
VisADQuadArray qarrayZ = null;
for (int i=0; i<3; i++) {
if (volume_tuple_index[i] == 0) {
qarrayX = qarray[i];
imagesX = images[i];
}
else if (volume_tuple_index[i] == 1) {
qarrayY = qarray[i];
imagesY = images[i];
}
else if (volume_tuple_index[i] == 2) {
qarrayZ = qarray[i];
imagesZ = images[i];
}
}
VisADQuadArray qarrayXrev = reverse(qarrayX);
VisADQuadArray qarrayYrev = reverse(qarrayY);
VisADQuadArray qarrayZrev = reverse(qarrayZ);
/* WLH 3 June 99 - comment this out until Texture3D works on NT (etc)
BufferedImage[] images =
createImages(2, data_width, data_height, data_depth,
texture_width, texture_height, texture_depth,
color_values);
shadow_api.texture3DToGroup(group, qarrayX, qarrayY, qarrayZ,
qarrayXrev, qarrayYrev, qarrayZrev,
images, mode, constant_alpha,
constant_color, texture_width,
texture_height, texture_depth, renderer);
*/
shadow_api.textureStackToGroup(group, qarrayX, qarrayY, qarrayZ,
qarrayXrev, qarrayYrev, qarrayZrev,
imagesX, imagesY, imagesZ,
mode, constant_alpha, constant_color,
texture_width, texture_height, texture_depth,
renderer);
// System.out.println("isTexture3D done");
return false;
} // end if (isTexture3D)
else if (pointMode || spatial_set == null ||
spatialManifoldDimension == 0 ||
spatialManifoldDimension == 3) {
if (range_select[0] != null) {
int len = range_select[0].length;
if (len == 1 || spatial_values[0].length == 1) {
return false;
}
for (int j=0; j<len; j++) {
// range_select[0][j] is either 0.0f or Float.NaN -
// setting to Float.NaN will move points off the screen
if (!range_select[0][j]) {
spatial_values[0][j] = Float.NaN;
}
}
/* CTR: 13 Oct 1998 - call new makePointGeometry signature */
array = makePointGeometry(spatial_values, color_values, true);
// System.out.println("makePointGeometry for some missing");
}
else {
array = makePointGeometry(spatial_values, color_values);
// System.out.println("makePointGeometry for pointMode");
}
}
else if (spatialManifoldDimension == 1) {
if (range_select[0] != null) {
// WLH 27 March 2000
if (mode.getMissingTransparent()) {
spatial_set.cram_missing(range_select[0]);
spatial_all_select = false;
}
else {
if (color_values == null) {
color_values = new byte[4][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
for (int i=0; i<domain_length; i++) {
if (!range_select[0][i]) {
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
/* WLH 6 May 99
color_values =
selectToColor(range_select, color_values, constant_color,
constant_alpha, missing_transparent);
constant_alpha = Float.NaN;
*/
}
array = spatial_set.make1DGeometry(color_values);
if (!spatial_all_select) array = array.removeMissing();
array = array.adjustLongitude(renderer);
array = array.adjustSeam(renderer);
// System.out.println("make1DGeometry");
}
else if (spatialManifoldDimension == 2) {
if (range_select[0] != null) {
// WLH 27 March 2000
if (mode.getMissingTransparent()) {
spatial_set.cram_missing(range_select[0]);
spatial_all_select = false;
}
else {
if (color_values == null) {
color_values = new byte[4][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
for (int i=0; i<domain_length; i++) {
if (!range_select[0][i]) {
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
/* WLH 6 May 99
color_values =
selectToColor(range_select, color_values, constant_color,
constant_alpha, missing_transparent);
constant_alpha = Float.NaN;
*/
}
array = spatial_set.make2DGeometry(color_values, indexed);
if (!spatial_all_select) array = array.removeMissing();
array = array.adjustLongitude(renderer);
array = array.adjustSeam(renderer);
// System.out.println("make2DGeometry vertexCount = " +
// array.vertexCount);
}
else {
throw new DisplayException("bad spatialManifoldDimension: " +
"ShadowFunctionOrSetType.doTransform");
}
if (array != null && array.vertexCount > 0) {
shadow_api.addToGroup(group, array, mode,
constant_alpha, constant_color);
// System.out.println("array.makeGeometry");
// FREE
array = null;
/* WLH 25 June 2000
if (renderer.getIsDirectManipulation()) {
renderer.setSpatialValues(spatial_values);
}
*/
}
} // end if (!anyContourCreated && !anyFlowCreated &&
// !anyTextCreated && !anyShapeCreated)
// WLH 25 June 2000
if (renderer.getIsDirectManipulation()) {
renderer.setSpatialValues(spatial_values);
}
// if (link != null) System.out.println("end doTransform " + (System.currentTimeMillis() - link.start_time));
return false;
} // end if (LevelOfDifficulty == SIMPLE_FIELD)
else if (LevelOfDifficulty == SIMPLE_ANIMATE_FIELD) {
Control control = null;
Object swit = null;
int index = -1;
if (DomainComponents.length == 1) {
RealType real = (RealType) DomainComponents[0].getType();
for (int i=0; i<valueArrayLength; i++) {
ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]);
float[] values = display_values[i];
if (values != null && real.equals(map.getScalar())) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType dreal =
display.getDisplayScalar(displayScalarIndex);
if (dreal.equals(Display.Animation) ||
dreal.equals(Display.SelectValue)) {
swit = shadow_api.makeSwitch();
index = i;
control = map.getControl();
break;
}
} // end if (values != null && && real.equals(map.getScalar()))
} // end for (int i=0; i<valueArrayLength; i++)
} // end if (DomainComponents.length == 1)
if (control == null) {
throw new DisplayException("bad SIMPLE_ANIMATE_FIELD: " +
"ShadowFunctionOrSetType.doTransform");
}
for (int i=0; i<domain_length; i++) {
Object branch = shadow_api.makeBranch();
if (range_select[0] == null || range_select[0].length == 1 ||
range_select[0][i]) {
VisADGeometryArray array = null;
float[][] sp = new float[3][1];
if (spatial_values[0].length > 1) {
sp[0][0] = spatial_values[0][i];
sp[1][0] = spatial_values[1][i];
sp[2][0] = spatial_values[2][i];
}
else {
sp[0][0] = spatial_values[0][0];
sp[1][0] = spatial_values[1][0];
sp[2][0] = spatial_values[2][0];
}
byte[][] co = new byte[3][1];
if (color_values == null) {
co[0][0] = floatToByte(constant_color[0]);
co[1][0] = floatToByte(constant_color[1]);
co[2][0] = floatToByte(constant_color[2]);
}
else if (color_values[0].length > 1) {
co[0][0] = color_values[0][i];
co[1][0] = color_values[1][i];
co[2][0] = color_values[2][i];
}
else {
co[0][0] = color_values[0][0];
co[1][0] = color_values[1][0];
co[2][0] = color_values[2][0];
}
boolean[][] ra = {{true}};
boolean anyShapeCreated = false;
VisADGeometryArray[] arrays =
shadow_api.assembleShape(display_values, valueArrayLength,
valueToMap, MapVector, valueToScalar, display,
default_values, inherited_values,
sp, co, ra, i, shadow_api);
if (arrays != null) {
for (int j=0; j<arrays.length; j++) {
array = arrays[j];
shadow_api.addToGroup(branch, array, mode,
constant_alpha, constant_color);
array = null;
/* why null constant_alpha?
appearance = makeAppearance(mode, null, constant_color, geometry);
*/
}
anyShapeCreated = true;
arrays = null;
}
boolean anyTextCreated = false;
if (anyText && text_values != null && text_control != null) {
String[] te = new String[1];
if (text_values.length > 1) {
te[0] = text_values[i];
}
else {
te[0] = text_values[0];
}
array = shadow_api.makeText(te, text_control, spatial_values, co, ra);
if (array != null) {
shadow_api.addTextToGroup(branch, array, mode,
constant_alpha, constant_color);
array = null;
anyTextCreated = true;
}
}
boolean anyFlowCreated = false;
if (anyFlow) {
if (flow1_values != null && flow1_values[0] != null) {
// try Flow1
float[][] f1 = new float[3][1];
if (flow1_values[0].length > 1) {
f1[0][0] = flow1_values[0][i];
f1[1][0] = flow1_values[1][i];
f1[2][0] = flow1_values[2][i];
}
else {
f1[0][0] = flow1_values[0][0];
f1[1][0] = flow1_values[1][0];
f1[2][0] = flow1_values[2][0];
}
arrays = shadow_api.makeFlow(0, f1, flowScale[0], sp, co, ra);
if (arrays != null) {
for (int j=0; j<arrays.length; j++) {
if (arrays[j] != null) {
shadow_api.addToGroup(branch, arrays[j], mode,
constant_alpha, constant_color);
arrays[j] = null;
}
}
}
anyFlowCreated = true;
}
// try Flow2
if (flow2_values != null && flow2_values[0] != null) {
float[][] f2 = new float[3][1];
if (flow2_values[0].length > 1) {
f2[0][0] = flow2_values[0][i];
f2[1][0] = flow2_values[1][i];
f2[2][0] = flow2_values[2][i];
}
else {
f2[0][0] = flow2_values[0][0];
f2[1][0] = flow2_values[1][0];
f2[2][0] = flow2_values[2][0];
}
arrays = shadow_api.makeFlow(1, f2, flowScale[1], sp, co, ra);
if (arrays != null) {
for (int j=0; j<arrays.length; j++) {
if (arrays[j] != null) {
shadow_api.addToGroup(branch, arrays[j], mode,
constant_alpha, constant_color);
arrays[j] = null;
}
}
}
anyFlowCreated = true;
}
}
if (!anyShapeCreated && !anyTextCreated &&
!anyFlowCreated) {
array = new VisADPointArray();
array.vertexCount = 1;
coordinates = new float[3];
coordinates[0] = sp[0][0];
coordinates[1] = sp[1][0];
coordinates[2] = sp[2][0];
array.coordinates = coordinates;
if (color_values != null) {
colors = new byte[3];
colors[0] = co[0][0];
colors[1] = co[1][0];
colors[2] = co[2][0];
array.colors = colors;
}
shadow_api.addToGroup(branch, array, mode,
constant_alpha, constant_color);
array = null;
// System.out.println("addChild " + i + " of " + domain_length);
}
}
else { // if (range_select[0][i])
/* WLH 18 Aug 98
empty BranchGroup or Shape3D may cause NullPointerException
from Shape3DRetained.setLive
// add null BranchGroup as child to maintain order
branch.addChild(new Shape3D());
*/
// System.out.println("addChild " + i + " of " + domain_length +
// " MISSING");
}
shadow_api.addToSwitch(swit, branch);
} // end for (int i=0; i<domain_length; i++)
shadow_api.addSwitch(group, swit, control, domain_set, renderer);
return false;
} // end if (LevelOfDifficulty == SIMPLE_ANIMATE_FIELD)
else { // must be LevelOfDifficulty == LEGAL
// add values to value_array according to SelectedMapVector-s
// of RealType-s in Domain (including Reference) and Range
//
// accumulate Vector of value_array-s at this ShadowType,
// to be rendered in a post-process to scanning data
//
// ** OR JUST EACH FIELD INDEPENDENTLY **
//
/*
return true;
*/
throw new UnimplementedException("terminal LEGAL unimplemented: " +
"ShadowFunctionOrSetType.doTransform");
}
}
else { // !isTerminal
// domain_values and range_values, as well as their References,
// already converted to default Units and added to display_values
// add values to value_array according to SelectedMapVector-s
// of RealType-s in Domain (including Reference), and
// recursively call doTransform on Range values
//
// TO_DO
// SelectRange (use boolean[][] range_select from assembleSelect),
// SelectValue, Animation
// DataRenderer.isTransformControl temporary hack:
// SelectRange.isTransform,
// !SelectValue.isTransform, !Animation.isTransform
//
// may need to split ShadowType.checkAnimationOrValue
// Display.Animation has no range, is single
// Display.Value has no range, is not single
//
// see Set.merge1DSets
boolean post = false;
Control control = null;
Object swit = null;
int index = -1;
if (DomainComponents.length == 1) {
RealType real = (RealType) DomainComponents[0].getType();
for (int i=0; i<valueArrayLength; i++) {
ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]);
float[] values = display_values[i];
if (values != null && real.equals(map.getScalar())) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType dreal =
display.getDisplayScalar(displayScalarIndex);
if (dreal.equals(Display.Animation) ||
dreal.equals(Display.SelectValue)) {
swit = shadow_api.makeSwitch();
index = i;
control = map.getControl();
break;
}
} // end if (values != null && real.equals(map.getScalar()))
} // end for (int i=0; i<valueArrayLength; i++)
} // end if (DomainComponents.length == 1)
if (control != null) {
shadow_api.addSwitch(group, swit, control, domain_set, renderer);
/*
group.addChild(swit);
control.addPair(swit, domain_set, renderer);
*/
}
float[] range_value_array = new float[valueArrayLength];
for (int j=0; j<display.getValueArrayLength(); j++) {
range_value_array[j] = Float.NaN;
}
for (int i=0; i<domain_length; i++) {
if (range_select[0] == null || range_select[0].length == 1 ||
range_select[0][i]) {
if (text_values != null && text_control != null) {
shadow_api.setText(text_values[i], text_control);
}
else {
shadow_api.setText(null, null);
}
for (int j=0; j<valueArrayLength; j++) {
if (display_values[j] != null) {
if (display_values[j].length == 1) {
range_value_array[j] = display_values[j][0];
}
else {
range_value_array[j] = display_values[j][i];
}
}
}
// push lat_index and lon_index for flow navigation
int[] lat_lon_indices = renderer.getLatLonIndices();
if (control != null) {
Object branch = shadow_api.makeBranch();
post |= shadow_api.recurseRange(branch, ((Field) data).getSample(i),
range_value_array, default_values,
renderer);
shadow_api.addToSwitch(swit, branch);
// System.out.println("addChild " + i + " of " + domain_length);
}
else {
Object branch = shadow_api.makeBranch();
post |= shadow_api.recurseRange(branch, ((Field) data).getSample(i),
range_value_array, default_values,
renderer);
shadow_api.addToGroup(group, branch);
}
// pop lat_index and lon_index for flow navigation
renderer.setLatLonIndices(lat_lon_indices);
}
else { // if (!range_select[0][i])
if (control != null) {
// add null BranchGroup as child to maintain order
Object branch = shadow_api.makeBranch();
shadow_api.addToSwitch(swit, branch);
// System.out.println("addChild " + i + " of " + domain_length +
// " MISSING");
}
}
}
/* why later than addPair & addChild(swit) ??
if (control != null) {
// initialize swit child selection
control.init();
}
*/
return post;
/*
throw new UnimplementedException("ShadowFunctionOrSetType.doTransform: " +
"not terminal");
*/
} // end if (!isTerminal)
}
public byte[][] selectToColor(boolean[][] range_select,
byte[][] color_values, float[] constant_color,
float constant_alpha, byte missing_transparent) {
int len = range_select[0].length;
byte[][] cv = new byte[4][];
if (color_values != null) {
for (int i=0; i<color_values.length; i++) {
cv[i] = color_values[i];
}
}
color_values = cv;
for (int i=0; i<4; i++) {
byte miss = (i < 3) ? 0 : missing_transparent;
if (color_values == null || color_values[i] == null) {
color_values[i] = new byte[len];
if (i < 3 && constant_color != null) {
byte c = floatToByte(constant_color[i]);
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? c : miss;
}
}
else if (i == 3 && constant_alpha == constant_alpha) {
if (constant_alpha < 0.99f) miss = 0;
byte c = floatToByte(constant_alpha);
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? c : miss;
}
}
else {
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? (byte) -1 : miss;
}
}
}
else if (color_values[i].length == 1) {
byte c = color_values[i][0];
if (i == 3 && c != -1) miss = 0;
color_values[i] = new byte[len];
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? c : miss;
}
}
else {
if (i == 3) miss = 0;
for (int j=0; j<len; j++) {
if (!range_select[0][j]) color_values[i][j] = miss;
}
}
}
return color_values;
}
public BufferedImage createImage(int data_width, int data_height,
int texture_width, int texture_height,
byte[][] color_values) throws VisADException {
BufferedImage image = null;
if (color_values.length > 3) {
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
image = new BufferedImage(colorModel, raster, false, null);
int[] intData = ((DataBufferInt)db).getData();
int k = 0;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = (color_values[3][k] < 0) ? color_values[3][k] + 256 :
color_values[3][k];
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
k++;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
}
else { // (color_values.length == 3)
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
// WLH 2 Nov 2000
DataBuffer db = raster.getDataBuffer();
int[] intData = null;
if (db instanceof DataBufferInt) {
intData = ((DataBufferInt)db).getData();
image = new BufferedImage(colorModel, raster, false, null);
}
else {
// System.out.println("byteData 3 1");
image = new BufferedImage(texture_width, texture_height,
BufferedImage.TYPE_INT_RGB);
intData = new int[texture_width * texture_height];
/*
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
int[] nBits = {8, 8, 8};
colorModel =
new ComponentColorModel(cs, nBits, false, false, Transparency.OPAQUE, 0);
raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
*/
}
// image = new BufferedImage(colorModel, raster, false, null);
// int[] intData = ((DataBufferInt)raster.getDataBuffer()).getData();
int k = 0;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = 255;
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
k++;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
// WLH 2 Nov 2000
if (!(db instanceof DataBufferInt)) {
// System.out.println("byteData 3 2");
image.setRGB(0, 0, texture_width, texture_height, intData, 0, texture_width);
/*
byte[] byteData = ((DataBufferByte)raster.getDataBuffer()).getData();
k = 0;
for (int i=0; i<intData.length; i++) {
byteData[k++] = (byte) (intData[i] & 255);
byteData[k++] = (byte) ((intData[i] >> 8) & 255);
byteData[k++] = (byte) ((intData[i] >> 16) & 255);
}
*/
/* WLH 4 Nov 2000, from com.sun.j3d.utils.geometry.Text2D
// For now, jdk 1.2 only handles ARGB format, not the RGBA we want
BufferedImage bImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
Graphics offscreenGraphics = bImage.createGraphics();
// First, erase the background to the text panel - set alpha to 0
Color myFill = new Color(0f, 0f, 0f, 0f);
offscreenGraphics.setColor(myFill);
offscreenGraphics.fillRect(0, 0, width, height);
// Next, set desired text properties (font, color) and draw String
offscreenGraphics.setFont(font);
Color myTextColor = new Color(color.x, color.y, color.z, 1f);
offscreenGraphics.setColor(myTextColor);
offscreenGraphics.drawString(text, 0, height - descent);
*/
} // end if (!(db instanceof DataBufferInt))
} // end if (color_values.length == 3)
return image;
}
public BufferedImage[] createImages(int axis, int data_width_in,
int data_height_in, int data_depth_in, int texture_width_in,
int texture_height_in, int texture_depth_in, byte[][] color_values)
throws VisADException {
int data_width, data_height, data_depth;
int texture_width, texture_height, texture_depth;
int kwidth, kheight, kdepth;
if (axis == 2) {
kwidth = 1;
kheight = data_width_in;
kdepth = data_width_in * data_height_in;
data_width = data_width_in;
data_height = data_height_in;
data_depth = data_depth_in;
texture_width = texture_width_in;
texture_height = texture_height_in;
texture_depth = texture_depth_in;
}
else if (axis == 1) {
kwidth = 1;
kdepth = data_width_in;
kheight = data_width_in * data_height_in;
data_width = data_width_in;
data_depth = data_height_in;
data_height = data_depth_in;
texture_width = texture_width_in;
texture_depth = texture_height_in;
texture_height = texture_depth_in;
}
else if (axis == 0) {
kdepth = 1;
kwidth = data_width_in;
kheight = data_width_in * data_height_in;
data_depth = data_width_in;
data_width = data_height_in;
data_height = data_depth_in;
texture_depth = texture_width_in;
texture_width = texture_height_in;
texture_height = texture_depth_in;
}
else {
return null;
}
BufferedImage[] images = new BufferedImage[texture_depth];
for (int d=0; d<data_depth; d++) {
if (color_values.length > 3) {
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
images[d] = new BufferedImage(colorModel, raster, false, null);
/* WLH 23 Feb 2000
if (axis == 1) {
images[(data_depth-1) - d] =
new BufferedImage(colorModel, raster, false, null);
}
else {
images[d] = new BufferedImage(colorModel, raster, false, null);
}
*/
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
int[] intData = ((DataBufferInt)db).getData();
// int k = d * data_width * data_height;
int kk = d * kdepth;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
int k = kk + j * kheight;
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = (color_values[3][k] < 0) ? color_values[3][k] + 256 :
color_values[3][k];
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
// k++;
k += kwidth;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
}
else { // (color_values.length == 3)
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
images[d] = new BufferedImage(colorModel, raster, false, null);
/* WLH 23 Feb 2000
if (axis == 1) {
images[(data_depth-1) - d] =
new BufferedImage(colorModel, raster, false, null);
}
else {
images[d] = new BufferedImage(colorModel, raster, false, null);
}
*/
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
int[] intData = ((DataBufferInt)db).getData();
// int k = d * data_width * data_height;
int kk = d * kdepth;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
int k = kk + j * kheight;
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = 255;
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
// k++;
k += kwidth;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
} // end if (color_values.length == 3)
} // end for (int d=0; d<data_depth; d++)
for (int d=data_depth; d<texture_depth; d++) {
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
images[d] = new BufferedImage(colorModel, raster, false, null);
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
int[] intData = ((DataBufferInt)db).getData();
for (int i=0; i<texture_width*texture_height; i++) {
intData[i] = 0;
}
}
return images;
}
public VisADQuadArray reverse(VisADQuadArray array) {
VisADQuadArray qarray = new VisADQuadArray();
qarray.coordinates = new float[array.coordinates.length];
qarray.texCoords = new float[array.texCoords.length];
qarray.colors = new byte[array.colors.length];
qarray.normals = new float[array.normals.length];
int count = array.vertexCount;
qarray.vertexCount = count;
int color_length = array.colors.length / count;
int tex_length = array.texCoords.length / count;
int i3 = 0;
int k3 = 3 * (count - 1);
int ic = 0;
int kc = color_length * (count - 1);
int it = 0;
int kt = tex_length * (count - 1);
for (int i=0; i<count; i++) {
qarray.coordinates[i3] = array.coordinates[k3];
qarray.coordinates[i3 + 1] = array.coordinates[k3 + 1];
qarray.coordinates[i3 + 2] = array.coordinates[k3 + 2];
qarray.texCoords[it] = array.texCoords[kt];
qarray.texCoords[it + 1] = array.texCoords[kt + 1];
if (tex_length == 3) qarray.texCoords[it + 2] = array.texCoords[kt + 2];
qarray.normals[i3] = array.normals[k3];
qarray.normals[i3 + 1] = array.normals[k3 + 1];
qarray.normals[i3 + 2] = array.normals[k3 + 2];
qarray.colors[ic] = array.colors[kc];
qarray.colors[ic + 1] = array.colors[kc + 1];
qarray.colors[ic + 2] = array.colors[kc + 2];
if (color_length == 4) qarray.colors[ic + 3] = array.colors[kc + 3];
i3 += 3;
k3 -= 3;
ic += color_length;
kc -= color_length;
it += tex_length;
kt -= tex_length;
}
return qarray;
}
}
| false | true | public boolean doTransform(Object group, Data data, float[] value_array,
float[] default_values, DataRenderer renderer,
ShadowType shadow_api)
throws VisADException, RemoteException {
// return if data is missing or no ScalarMaps
if (data.isMissing()) return false;
if (LevelOfDifficulty == NOTHING_MAPPED) return false;
// if transform has taken more than 500 milliseconds and there is
// a flag requesting re-transform, throw a DisplayInterruptException
DataDisplayLink link = renderer.getLink();
// if (link != null) System.out.println("\nstart doTransform " + (System.currentTimeMillis() - link.start_time));
if (link != null) {
boolean time_flag = false;
if (link.time_flag) {
time_flag = true;
}
else {
if (500 < System.currentTimeMillis() - link.start_time) {
link.time_flag = true;
time_flag = true;
}
}
if (time_flag) {
if (link.peekTicks()) {
throw new DisplayInterruptException("please wait . . .");
}
Enumeration maps = link.getSelectedMapVector().elements();
while(maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
if (map.peekTicks(renderer, link)) {
throw new DisplayInterruptException("please wait . . .");
}
}
}
} // end if (link != null)
// get 'shape' flags
boolean anyContour = getAnyContour();
boolean anyFlow = getAnyFlow();
boolean anyShape = getAnyShape();
boolean anyText = getAnyText();
boolean indexed = shadow_api.wantIndexed();
// get some precomputed values useful for transform
// length of ValueArray
int valueArrayLength = display.getValueArrayLength();
// mapping from ValueArray to DisplayScalar
int[] valueToScalar = display.getValueToScalar();
// mapping from ValueArray to MapVector
int[] valueToMap = display.getValueToMap();
Vector MapVector = display.getMapVector();
// array to hold values for various mappings
float[][] display_values = new float[valueArrayLength][];
// get values inherited from parent;
// assume these do not include SelectRange, SelectValue
// or Animation values - see temporary hack in
// DataRenderer.isTransformControl
for (int i=0; i<valueArrayLength; i++) {
if (inherited_values[i] > 0) {
display_values[i] = new float[1];
display_values[i][0] = value_array[i];
}
}
// check for only contours and only disabled contours
if (getIsTerminal() && anyContour &&
!anyFlow && !anyShape && !anyText) { // WLH 13 March 99
boolean any_enabled = false;
for (int i=0; i<valueArrayLength; i++) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType real = display.getDisplayScalar(displayScalarIndex);
if (real.equals(Display.IsoContour) && inherited_values[i] == 0) {
// non-inherited IsoContour, so generate contours
ContourControl control = (ContourControl)
((ScalarMap) MapVector.elementAt(valueToMap[i])).getControl();
boolean[] bvalues = new boolean[2];
float[] fvalues = new float[5];
control.getMainContours(bvalues, fvalues);
if (bvalues[0]) any_enabled = true;
}
}
if (!any_enabled) return false;
}
Set domain_set = null;
Unit[] dataUnits = null;
CoordinateSystem dataCoordinateSystem = null;
if (this instanceof ShadowFunctionType) {
// currently only implemented for Field
// must eventually extend to Function
if (!(data instanceof Field)) {
throw new UnimplementedException("data must be Field: " +
"ShadowFunctionOrSetType.doTransform: ");
}
domain_set = ((Field) data).getDomainSet();
dataUnits = ((Function) data).getDomainUnits();
dataCoordinateSystem = ((Function) data).getDomainCoordinateSystem();
}
else if (this instanceof ShadowSetType) {
domain_set = (Set) data;
dataUnits = ((Set) data).getSetUnits();
dataCoordinateSystem = ((Set) data).getCoordinateSystem();
}
else {
throw new DisplayException(
"must be ShadowFunctionType or ShadowSetType: " +
"ShadowFunctionOrSetType.doTransform");
}
float[][] domain_values = null;
double[][] domain_doubles = null;
Unit[] domain_units = ((RealTupleType) Domain.getType()).getDefaultUnits();
int domain_length;
int domain_dimension;
try {
domain_length = domain_set.getLength();
domain_dimension = domain_set.getDimension();
}
catch (SetException e) {
return false;
}
// ShadowRealTypes of Domain
ShadowRealType[] DomainComponents = getDomainComponents();
int alpha_index = display.getDisplayScalarIndex(Display.Alpha);
// array to hold values for Text mapping (can only be one)
String[] text_values = null;
// get any text String and TextControl inherited from parent
TextControl text_control = shadow_api.getParentTextControl();
String inherited_text = shadow_api.getParentText();
if (inherited_text != null) {
text_values = new String[domain_length];
for (int i=0; i<domain_length; i++) {
text_values[i] = inherited_text;
}
}
boolean isTextureMap = getIsTextureMap() &&
// default_values[alpha_index] > 0.99 &&
renderer.isLegalTextureMap() &&
(domain_set instanceof Linear2DSet ||
(domain_set instanceof LinearNDSet &&
domain_set.getDimension() == 2));
int curved_size = display.getGraphicsModeControl().getCurvedSize();
boolean curvedTexture = getCurvedTexture() &&
!isTextureMap &&
curved_size > 0 &&
getIsTerminal() && // implied by getCurvedTexture()?
shadow_api.allowCurvedTexture() &&
default_values[alpha_index] > 0.99 &&
renderer.isLegalTextureMap() &&
domain_set.getManifoldDimension() == 2 &&
domain_set instanceof GriddedSet; // WLH 22 Aug 2002 Lak's bug
/* // WLH 22 Aug 2002 Lak's bug
(domain_set instanceof Gridded2DSet ||
(domain_set instanceof GriddedSet &&
domain_set.getDimension() == 2));
*/
boolean domainOnlySpatial =
Domain.getAllSpatial() && !Domain.getMultipleDisplayScalar();
boolean isTexture3D = getIsTexture3D() &&
// default_values[alpha_index] > 0.99 &&
renderer.isLegalTextureMap() &&
(domain_set instanceof Linear3DSet ||
(domain_set instanceof LinearNDSet &&
domain_set.getDimension() == 3));
// WLH 1 April 2000
boolean range3D = isTexture3D && anyRange(Domain.getDisplayIndices());
boolean isLinearContour3D = getIsLinearContour3D() &&
domain_set instanceof Linear3DSet &&
shadow_api.allowLinearContour();
/*
System.out.println("doTransform.isTextureMap = " + isTextureMap + " " +
getIsTextureMap() + " " +
// (default_values[alpha_index] > 0.99) + " " +
renderer.isLegalTextureMap() + " " +
(domain_set instanceof Linear2DSet) + " " +
(domain_set instanceof LinearNDSet) + " " +
(domain_set.getDimension() == 2));
System.out.println("doTransform.curvedTexture = " + curvedTexture + " " +
getCurvedTexture() + " " +
!isTextureMap + " " +
(curved_size > 0) + " " +
getIsTerminal() + " " +
shadow_api.allowCurvedTexture() + " " +
(default_values[alpha_index] > 0.99) + " " +
renderer.isLegalTextureMap() + " " +
(domain_set instanceof Gridded2DSet) + " " +
(domain_set instanceof GriddedSet) + " " +
(domain_set.getDimension() == 2) );
*/
float[] coordinates = null;
float[] texCoords = null;
float[] normals = null;
byte[] colors = null;
int data_width = 0;
int data_height = 0;
int data_depth = 0;
int texture_width = 1;
int texture_height = 1;
int texture_depth = 1;
float[] coordinatesX = null;
float[] texCoordsX = null;
float[] normalsX = null;
byte[] colorsX = null;
float[] coordinatesY = null;
float[] texCoordsY = null;
float[] normalsY = null;
byte[] colorsY = null;
float[] coordinatesZ = null;
float[] texCoordsZ = null;
float[] normalsZ = null;
byte[] colorsZ = null;
int[] volume_tuple_index = null;
// if (link != null) System.out.println("test isTextureMap " + (System.currentTimeMillis() - link.start_time));
if (isTextureMap) {
Linear1DSet X = null;
Linear1DSet Y = null;
if (domain_set instanceof Linear2DSet) {
X = ((Linear2DSet) domain_set).getX();
Y = ((Linear2DSet) domain_set).getY();
}
else {
X = ((LinearNDSet) domain_set).getLinear1DComponent(0);
Y = ((LinearNDSet) domain_set).getLinear1DComponent(1);
}
float[][] limits = new float[2][2];
limits[0][0] = (float) X.getFirst();
limits[0][1] = (float) X.getLast();
limits[1][0] = (float) Y.getFirst();
limits[1][1] = (float) Y.getLast();
// convert values to default units (used in display)
limits = Unit.convertTuple(limits, dataUnits, domain_units);
// get domain_set sizes
data_width = X.getLength();
data_height = Y.getLength();
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
int[] tuple_index = new int[3];
if (DomainComponents.length != 2) {
throw new DisplayException("texture domain dimension != 2:" +
"ShadowFunctionOrSetType.doTransform");
}
for (int i=0; i<DomainComponents.length; i++) {
Enumeration maps = DomainComponents[i].getSelectedMapVector().elements();
while (maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
DisplayRealType real = map.getDisplayScalar();
DisplayTupleType tuple = real.getTuple();
if (Display.DisplaySpatialCartesianTuple.equals(tuple)) {
// scale values
limits[i] = map.scaleValues(limits[i]);
// get spatial index
tuple_index[i] = real.getTupleIndex();
break;
}
}
/*
if (tuple == null ||
!tuple.equals(Display.DisplaySpatialCartesianTuple)) {
throw new DisplayException("texture with bad tuple: " +
"ShadowFunctionOrSetType.doTransform");
}
if (maps.hasMoreElements()) {
throw new DisplayException("texture with multiple spatial: " +
"ShadowFunctionOrSetType.doTransform");
}
*/
} // end for (int i=0; i<DomainComponents.length; i++)
// get spatial index not mapped from domain_set
tuple_index[2] = 3 - (tuple_index[0] + tuple_index[1]);
DisplayRealType real = (DisplayRealType)
Display.DisplaySpatialCartesianTuple.getComponent(tuple_index[2]);
int value2_index = display.getDisplayScalarIndex(real);
float value2 = default_values[value2_index];
// float value2 = 0.0f; WLH 30 Aug 99
for (int i=0; i<valueArrayLength; i++) {
if (inherited_values[i] > 0 &&
real.equals(display.getDisplayScalar(valueToScalar[i])) ) {
value2 = value_array[i];
break;
}
}
coordinates = new float[12];
// corner 0
coordinates[tuple_index[0]] = limits[0][0];
coordinates[tuple_index[1]] = limits[1][0];
coordinates[tuple_index[2]] = value2;
// corner 1
coordinates[3 + tuple_index[0]] = limits[0][1];
coordinates[3 + tuple_index[1]] = limits[1][0];
coordinates[3 + tuple_index[2]] = value2;
// corner 2
coordinates[6 + tuple_index[0]] = limits[0][1];
coordinates[6 + tuple_index[1]] = limits[1][1];
coordinates[6 + tuple_index[2]] = value2;
// corner 3
coordinates[9 + tuple_index[0]] = limits[0][0];
coordinates[9 + tuple_index[1]] = limits[1][1];
coordinates[9 + tuple_index[2]] = value2;
// move image back in Java3D 2-D mode
shadow_api.adjustZ(coordinates);
texCoords = new float[8];
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
shadow_api.setTexCoords(texCoords, ratiow, ratioh);
normals = new float[12];
float n0 = ((coordinates[3+2]-coordinates[0+2]) *
(coordinates[6+1]-coordinates[0+1])) -
((coordinates[3+1]-coordinates[0+1]) *
(coordinates[6+2]-coordinates[0+2]));
float n1 = ((coordinates[3+0]-coordinates[0+0]) *
(coordinates[6+2]-coordinates[0+2])) -
((coordinates[3+2]-coordinates[0+2]) *
(coordinates[6+0]-coordinates[0+0]));
float n2 = ((coordinates[3+1]-coordinates[0+1]) *
(coordinates[6+0]-coordinates[0+0])) -
((coordinates[3+0]-coordinates[0+0]) *
(coordinates[6+1]-coordinates[0+1]));
float nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
// corner 0
normals[0] = n0;
normals[1] = n1;
normals[2] = n2;
// corner 1
normals[3] = n0;
normals[4] = n1;
normals[5] = n2;
// corner 2
normals[6] = n0;
normals[7] = n1;
normals[8] = n2;
// corner 3
normals[9] = n0;
normals[10] = n1;
normals[11] = n2;
colors = new byte[12];
for (int i=0; i<12; i++) colors[i] = (byte) 127;
/*
for (int i=0; i < 4; i++) {
System.out.println("i = " + i + " texCoords = " + texCoords[2 * i] + " " +
texCoords[2 * i + 1]);
System.out.println(" coordinates = " + coordinates[3 * i] + " " +
coordinates[3 * i + 1] + " " + coordinates[3 * i + 2]);
System.out.println(" normals = " + normals[3 * i] + " " + normals[3 * i + 1] +
" " + normals[3 * i + 2]);
}
*/
}
else if (isTexture3D) {
Linear1DSet X = null;
Linear1DSet Y = null;
Linear1DSet Z = null;
if (domain_set instanceof Linear3DSet) {
X = ((Linear3DSet) domain_set).getX();
Y = ((Linear3DSet) domain_set).getY();
Z = ((Linear3DSet) domain_set).getZ();
}
else {
X = ((LinearNDSet) domain_set).getLinear1DComponent(0);
Y = ((LinearNDSet) domain_set).getLinear1DComponent(1);
Z = ((LinearNDSet) domain_set).getLinear1DComponent(2);
}
float[][] limits = new float[3][2];
limits[0][0] = (float) X.getFirst();
limits[0][1] = (float) X.getLast();
limits[1][0] = (float) Y.getFirst();
limits[1][1] = (float) Y.getLast();
limits[2][0] = (float) Z.getFirst();
limits[2][1] = (float) Z.getLast();
// convert values to default units (used in display)
limits = Unit.convertTuple(limits, dataUnits, domain_units);
// get domain_set sizes
data_width = X.getLength();
data_height = Y.getLength();
data_depth = Z.getLength();
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
texture_depth = shadow_api.textureDepth(data_depth);
int[] tuple_index = new int[3];
if (DomainComponents.length != 3) {
throw new DisplayException("texture3D domain dimension != 3:" +
"ShadowFunctionOrSetType.doTransform");
}
for (int i=0; i<DomainComponents.length; i++) {
Enumeration maps = DomainComponents[i].getSelectedMapVector().elements();
while (maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
DisplayRealType real = map.getDisplayScalar();
DisplayTupleType tuple = real.getTuple();
if (Display.DisplaySpatialCartesianTuple.equals(tuple)) {
// scale values
limits[i] = map.scaleValues(limits[i]);
// get spatial index
tuple_index[i] = real.getTupleIndex();
break;
}
}
/*
if (tuple == null ||
!tuple.equals(Display.DisplaySpatialCartesianTuple)) {
throw new DisplayException("texture with bad tuple: " +
"ShadowFunctionOrSetType.doTransform");
}
if (maps.hasMoreElements()) {
throw new DisplayException("texture with multiple spatial: " +
"ShadowFunctionOrSetType.doTransform");
}
*/
} // end for (int i=0; i<DomainComponents.length; i++)
volume_tuple_index = tuple_index;
coordinatesX = new float[12 * data_width];
coordinatesY = new float[12 * data_height];
coordinatesZ = new float[12 * data_depth];
for (int i=0; i<data_depth; i++) {
int i12 = i * 12;
float depth = limits[2][0] +
(limits[2][1] - limits[2][0]) * i / (data_depth - 1.0f);
// corner 0
coordinatesZ[i12 + tuple_index[0]] = limits[0][0];
coordinatesZ[i12 + tuple_index[1]] = limits[1][0];
coordinatesZ[i12 + tuple_index[2]] = depth;
// corner 1
coordinatesZ[i12 + 3 + tuple_index[0]] = limits[0][1];
coordinatesZ[i12 + 3 + tuple_index[1]] = limits[1][0];
coordinatesZ[i12 + 3 + tuple_index[2]] = depth;
// corner 2
coordinatesZ[i12 + 6 + tuple_index[0]] = limits[0][1];
coordinatesZ[i12 + 6 + tuple_index[1]] = limits[1][1];
coordinatesZ[i12 + 6 + tuple_index[2]] = depth;
// corner 3
coordinatesZ[i12 + 9 + tuple_index[0]] = limits[0][0];
coordinatesZ[i12 + 9 + tuple_index[1]] = limits[1][1];
coordinatesZ[i12 + 9 + tuple_index[2]] = depth;
}
for (int i=0; i<data_height; i++) {
int i12 = i * 12;
float height = limits[1][0] +
(limits[1][1] - limits[1][0]) * i / (data_height - 1.0f);
// corner 0
coordinatesY[i12 + tuple_index[0]] = limits[0][0];
coordinatesY[i12 + tuple_index[1]] = height;
coordinatesY[i12 + tuple_index[2]] = limits[2][0];
// corner 1
coordinatesY[i12 + 3 + tuple_index[0]] = limits[0][1];
coordinatesY[i12 + 3 + tuple_index[1]] = height;
coordinatesY[i12 + 3 + tuple_index[2]] = limits[2][0];
// corner 2
coordinatesY[i12 + 6 + tuple_index[0]] = limits[0][1];
coordinatesY[i12 + 6 + tuple_index[1]] = height;
coordinatesY[i12 + 6 + tuple_index[2]] = limits[2][1];
// corner 3
coordinatesY[i12 + 9 + tuple_index[0]] = limits[0][0];
coordinatesY[i12 + 9 + tuple_index[1]] = height;
coordinatesY[i12 + 9 + tuple_index[2]] = limits[2][1];
}
for (int i=0; i<data_width; i++) {
int i12 = i * 12;
float width = limits[0][0] +
(limits[0][1] - limits[0][0]) * i / (data_width - 1.0f);
// corner 0
coordinatesX[i12 + tuple_index[0]] = width;
coordinatesX[i12 + tuple_index[1]] = limits[1][0];
coordinatesX[i12 + tuple_index[2]] = limits[2][0];
// corner 1
coordinatesX[i12 + 3 + tuple_index[0]] = width;
coordinatesX[i12 + 3 + tuple_index[1]] = limits[1][1];
coordinatesX[i12 + 3 + tuple_index[2]] = limits[2][0];
// corner 2
coordinatesX[i12 + 6 + tuple_index[0]] = width;
coordinatesX[i12 + 6 + tuple_index[1]] = limits[1][1];
coordinatesX[i12 + 6 + tuple_index[2]] = limits[2][1];
// corner 3
coordinatesX[i12 + 9 + tuple_index[0]] = width;
coordinatesX[i12 + 9 + tuple_index[1]] = limits[1][0];
coordinatesX[i12 + 9 + tuple_index[2]] = limits[2][1];
}
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
float ratiod = ((float) data_depth) / ((float) texture_depth);
/* WLH 3 June 99 - comment this out until Texture3D works on NT (etc)
texCoordsX =
shadow_api.setTex3DCoords(data_width, 0, ratiow, ratioh, ratiod);
texCoordsY =
shadow_api.setTex3DCoords(data_height, 1, ratiow, ratioh, ratiod);
texCoordsZ =
shadow_api.setTex3DCoords(data_depth, 2, ratiow, ratioh, ratiod);
*/
texCoordsX =
shadow_api.setTexStackCoords(data_width, 0, ratiow, ratioh, ratiod);
texCoordsY =
shadow_api.setTexStackCoords(data_height, 1, ratiow, ratioh, ratiod);
texCoordsZ =
shadow_api.setTexStackCoords(data_depth, 2, ratiow, ratioh, ratiod);
normalsX = new float[12 * data_width];
normalsY = new float[12 * data_height];
normalsZ = new float[12 * data_depth];
float n0, n1, n2, nlen;
n0 = ((coordinatesX[3+2]-coordinatesX[0+2]) *
(coordinatesX[6+1]-coordinatesX[0+1])) -
((coordinatesX[3+1]-coordinatesX[0+1]) *
(coordinatesX[6+2]-coordinatesX[0+2]));
n1 = ((coordinatesX[3+0]-coordinatesX[0+0]) *
(coordinatesX[6+2]-coordinatesX[0+2])) -
((coordinatesX[3+2]-coordinatesX[0+2]) *
(coordinatesX[6+0]-coordinatesX[0+0]));
n2 = ((coordinatesX[3+1]-coordinatesX[0+1]) *
(coordinatesX[6+0]-coordinatesX[0+0])) -
((coordinatesX[3+0]-coordinatesX[0+0]) *
(coordinatesX[6+1]-coordinatesX[0+1]));
nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
for (int i=0; i<normalsX.length; i+=3) {
normalsX[i] = n0;
normalsX[i + 1] = n1;
normalsX[i + 2] = n2;
}
n0 = ((coordinatesY[3+2]-coordinatesY[0+2]) *
(coordinatesY[6+1]-coordinatesY[0+1])) -
((coordinatesY[3+1]-coordinatesY[0+1]) *
(coordinatesY[6+2]-coordinatesY[0+2]));
n1 = ((coordinatesY[3+0]-coordinatesY[0+0]) *
(coordinatesY[6+2]-coordinatesY[0+2])) -
((coordinatesY[3+2]-coordinatesY[0+2]) *
(coordinatesY[6+0]-coordinatesY[0+0]));
n2 = ((coordinatesY[3+1]-coordinatesY[0+1]) *
(coordinatesY[6+0]-coordinatesY[0+0])) -
((coordinatesY[3+0]-coordinatesY[0+0]) *
(coordinatesY[6+1]-coordinatesY[0+1]));
nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
for (int i=0; i<normalsY.length; i+=3) {
normalsY[i] = n0;
normalsY[i + 1] = n1;
normalsY[i + 2] = n2;
}
n0 = ((coordinatesZ[3+2]-coordinatesZ[0+2]) *
(coordinatesZ[6+1]-coordinatesZ[0+1])) -
((coordinatesZ[3+1]-coordinatesZ[0+1]) *
(coordinatesZ[6+2]-coordinatesZ[0+2]));
n1 = ((coordinatesZ[3+0]-coordinatesZ[0+0]) *
(coordinatesZ[6+2]-coordinatesZ[0+2])) -
((coordinatesZ[3+2]-coordinatesZ[0+2]) *
(coordinatesZ[6+0]-coordinatesZ[0+0]));
n2 = ((coordinatesZ[3+1]-coordinatesZ[0+1]) *
(coordinatesZ[6+0]-coordinatesZ[0+0])) -
((coordinatesZ[3+0]-coordinatesZ[0+0]) *
(coordinatesZ[6+1]-coordinatesZ[0+1]));
nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
for (int i=0; i<normalsZ.length; i+=3) {
normalsZ[i] = n0;
normalsZ[i + 1] = n1;
normalsZ[i + 2] = n2;
}
colorsX = new byte[12 * data_width];
colorsY = new byte[12 * data_height];
colorsZ = new byte[12 * data_depth];
for (int i=0; i<12*data_width; i++) colorsX[i] = (byte) 127;
for (int i=0; i<12*data_height; i++) colorsY[i] = (byte) 127;
for (int i=0; i<12*data_depth; i++) colorsZ[i] = (byte) 127;
/*
for (int i=0; i < 4; i++) {
System.out.println("i = " + i + " texCoordsX = " + texCoordsX[3 * i] + " " +
texCoordsX[3 * i + 1]);
System.out.println(" coordinatesX = " + coordinatesX[3 * i] + " " +
coordinatesX[3 * i + 1] + " " + coordinatesX[3 * i + 2]);
System.out.println(" normalsX = " + normalsX[3 * i] + " " +
normalsX[3 * i + 1] + " " + normalsX[3 * i + 2]);
}
*/
}
// WLH 1 April 2000
// else { // !isTextureMap && !isTexture3D
// WLH 16 July 2000 - add '&& !isLinearContour3D'
if (!isTextureMap && (!isTexture3D || range3D) && !isLinearContour3D) {
// if (link != null) System.out.println("start domain " + (System.currentTimeMillis() - link.start_time));
// get values from Function Domain
// NOTE - may defer this until needed, if needed
if (domain_dimension == 1) {
domain_doubles = domain_set.getDoubles(false);
domain_doubles = Unit.convertTuple(domain_doubles, dataUnits, domain_units);
mapValues(display_values, domain_doubles, DomainComponents);
}
else {
domain_values = domain_set.getSamples(false);
// convert values to default units (used in display)
// MEM & FREE
domain_values = Unit.convertTuple(domain_values, dataUnits, domain_units);
// System.out.println("got domain_values: domain_length = " + domain_length);
// map domain_values to appropriate DisplayRealType-s
// MEM
mapValues(display_values, domain_values, DomainComponents);
}
// System.out.println("mapped domain_values");
ShadowRealTupleType domain_reference = Domain.getReference();
/*
System.out.println("domain_reference = " + domain_reference);
if (domain_reference != null) {
System.out.println("getMappedDisplayScalar = " +
domain_reference.getMappedDisplayScalar());
}
*/
// if (link != null) System.out.println("end domain " + (System.currentTimeMillis() - link.start_time));
if (domain_reference != null && domain_reference.getMappedDisplayScalar()) {
// apply coordinate transform to domain values
RealTupleType ref = (RealTupleType) domain_reference.getType();
// MEM
float[][] reference_values = null;
double[][] reference_doubles = null;
if (domain_dimension == 1) {
reference_doubles =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) Domain.getType(), dataCoordinateSystem,
domain_units, null, domain_doubles);
}
else {
// WLH 23 June 99
if (curvedTexture && domainOnlySpatial) {
//if (link != null) System.out.println("start compute spline " + (System.currentTimeMillis() - link.start_time));
int[] lengths = ((GriddedSet) domain_set).getLengths();
data_width = lengths[0];
data_height = lengths[1];
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
int size = (data_width + data_height) / 2;
curved_size = Math.max(1, Math.min(curved_size, size / 32));
int nwidth = 2 + (data_width - 1) / curved_size;
int nheight = 2 + (data_height - 1) / curved_size;
/*
System.out.println("data_width = " + data_width + " data_height = " + data_height +
" texture_width = " + texture_width + " texture_height = " + texture_height +
" nwidth = " + nwidth + " nheight = " + nheight);
*/
int nn = nwidth * nheight;
int[] is = new int[nwidth];
int[] js = new int[nheight];
for (int i=0; i<nwidth; i++) {
is[i] = Math.min(i * curved_size, data_width - 1);
}
for (int j=0; j<nheight; j++) {
js[j] = Math.min(j * curved_size, data_height - 1);
}
float[][] spline_domain = new float[2][nwidth * nheight];
int k = 0;
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
int ij = is[i] + data_width * js[j];
spline_domain[0][k] = domain_values[0][ij];
spline_domain[1][k] = domain_values[1][ij];
k++;
}
}
float[][] spline_reference =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) Domain.getType(), dataCoordinateSystem,
domain_units, null, spline_domain);
reference_values = new float[2][domain_length];
for (int i=0; i<domain_length; i++) {
reference_values[0][i] = Float.NaN;
reference_values[1][i] = Float.NaN;
}
k = 0;
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
int ij = is[i] + data_width * js[j];
reference_values[0][ij] = spline_reference[0][k];
reference_values[1][ij] = spline_reference[1][k];
k++;
}
}
// if (link != null) System.out.println("end compute spline " + (System.currentTimeMillis() - link.start_time));
}
else { // if !(curvedTexture && domainOnlySpatial)
reference_values =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) Domain.getType(), dataCoordinateSystem,
domain_units, null, domain_values);
}
} // end if !(domain_dimension == 1)
// WLH 13 Macrh 2000
// if (anyFlow) {
renderer.setEarthSpatialData(Domain, domain_reference, ref,
ref.getDefaultUnits(), (RealTupleType) Domain.getType(),
new CoordinateSystem[] {dataCoordinateSystem},
domain_units);
// WLH 13 Macrh 2000
// }
//
// TO_DO
// adjust any RealVectorTypes in range
// see FlatField.resample and FieldImpl.resample
//
// if (link != null) System.out.println("start map reference " + (System.currentTimeMillis() - link.start_time));
// map reference_values to appropriate DisplayRealType-s
ShadowRealType[] DomainReferenceComponents = getDomainReferenceComponents();
// MEM
if (domain_dimension == 1) {
mapValues(display_values, reference_doubles, DomainReferenceComponents);
}
else {
mapValues(display_values, reference_values, DomainReferenceComponents);
}
// if (link != null) System.out.println("end map reference " + (System.currentTimeMillis() - link.start_time));
/*
for (int i=0; i<DomainReferenceComponents.length; i++) {
System.out.println("DomainReferenceComponents[" + i + "] = " +
DomainReferenceComponents[i]);
System.out.println("reference_values[" + i + "].length = " +
reference_values[i].length);
}
System.out.println("mapped domain_reference values");
*/
// FREE
reference_values = null;
reference_doubles = null;
}
else { // if !(domain_reference != null &&
// domain_reference.getMappedDisplayScalar())
// WLH 13 March 2000
// if (anyFlow) {
/* WLH 23 May 99
renderer.setEarthSpatialData(Domain, null, null,
null, (RealTupleType) Domain.getType(),
new CoordinateSystem[] {dataCoordinateSystem},
domain_units);
*/
RealTupleType ref = (domain_reference == null) ? null :
(RealTupleType) domain_reference.getType();
Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits();
renderer.setEarthSpatialData(Domain, domain_reference, ref,
ref_units, (RealTupleType) Domain.getType(),
new CoordinateSystem[] {dataCoordinateSystem},
domain_units);
// WLH 13 March 2000
// }
}
// FREE
domain_values = null;
domain_doubles = null;
} // end if (!isTextureMap && (!isTexture3D || range3D) &&
// !isLinearContour3D)
if (this instanceof ShadowFunctionType) {
// if (link != null) System.out.println("start range " + (System.currentTimeMillis() - link.start_time));
// get range_values for RealType and RealTupleType
// components, in defaultUnits for RealType-s
// MEM - may copy (in convertTuple)
float[][] range_values = ((Field) data).getFloats(false);
// System.out.println("got range_values");
if (range_values != null) {
// map range_values to appropriate DisplayRealType-s
ShadowRealType[] RangeComponents = getRangeComponents();
// MEM
mapValues(display_values, range_values, RangeComponents);
// System.out.println("mapped range_values");
//
// transform any range CoordinateSystem-s
// into display_values, then mapValues
//
int[] refToComponent = getRefToComponent();
ShadowRealTupleType[] componentWithRef = getComponentWithRef();
int[] componentIndex = getComponentIndex();
if (refToComponent != null) {
for (int i=0; i<refToComponent.length; i++) {
int n = componentWithRef[i].getDimension();
int start = refToComponent[i];
float[][] values = new float[n][];
for (int j=0; j<n; j++) values[j] = range_values[j + start];
ShadowRealTupleType component_reference =
componentWithRef[i].getReference();
RealTupleType ref = (RealTupleType) component_reference.getType();
Unit[] range_units;
CoordinateSystem[] range_coord_sys;
if (i == 0 && componentWithRef[i].equals(Range)) {
range_units = ((Field) data).getDefaultRangeUnits();
range_coord_sys = ((Field) data).getRangeCoordinateSystem();
}
else {
Unit[] dummy_units = ((Field) data).getDefaultRangeUnits();
range_units = new Unit[n];
for (int j=0; j<n; j++) range_units[j] = dummy_units[j + start];
range_coord_sys =
((Field) data).getRangeCoordinateSystem(componentIndex[i]);
}
float[][] reference_values = null;
if (range_coord_sys.length == 1) {
// MEM
reference_values =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys[0], range_units, null, values);
// WLH 13 March 2000
// if (anyFlow) {
renderer.setEarthSpatialData(componentWithRef[i],
component_reference, ref, ref.getDefaultUnits(),
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys, range_units);
// WLH 13 March 2000
// }
}
else {
// MEM
reference_values = new float[n][domain_length];
float[][] temp = new float[n][1];
for (int j=0; j<domain_length; j++) {
for (int k=0; k<n; k++) temp[k][0] = values[k][j];
temp =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys[j], range_units, null, temp);
for (int k=0; k<n; k++) reference_values[k][j] = temp[k][0];
}
// WLH 13 March 2000
// if (anyFlow) {
renderer.setEarthSpatialData(componentWithRef[i],
component_reference, ref, ref.getDefaultUnits(),
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys, range_units);
// WLH 13 March 2000
// }
}
// map reference_values to appropriate DisplayRealType-s
// MEM
/* WLH 17 April 99
mapValues(display_values, reference_values,
getComponents(componentWithRef[i], false));
*/
mapValues(display_values, reference_values,
getComponents(component_reference, false));
// FREE
reference_values = null;
// FREE (redundant reference to range_values)
values = null;
} // end for (int i=0; i<refToComponent.length; i++)
} // end (refToComponent != null)
// if (link != null) System.out.println("end range " + (System.currentTimeMillis() - link.start_time));
// setEarthSpatialData calls when no CoordinateSystem
// WLH 13 March 2000
// if (Range instanceof ShadowTupleType && anyFlow) {
if (Range instanceof ShadowTupleType) {
if (Range instanceof ShadowRealTupleType) {
Unit[] range_units = ((Field) data).getDefaultRangeUnits();
CoordinateSystem[] range_coord_sys =
((Field) data).getRangeCoordinateSystem();
/* WLH 23 May 99
renderer.setEarthSpatialData((ShadowRealTupleType) Range,
null, null, null, (RealTupleType) Range.getType(),
range_coord_sys, range_units);
*/
ShadowRealTupleType component_reference =
((ShadowRealTupleType) Range).getReference();
RealTupleType ref = (component_reference == null) ? null :
(RealTupleType) component_reference.getType();
Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits();
renderer.setEarthSpatialData((ShadowRealTupleType) Range,
component_reference, ref, ref_units,
(RealTupleType) Range.getType(),
range_coord_sys, range_units);
}
else { // if (!(Range instanceof ShadowRealTupleType))
Unit[] dummy_units = ((Field) data).getDefaultRangeUnits();
int start = 0;
int n = ((ShadowTupleType) Range).getDimension();
for (int i=0; i<n ;i++) {
ShadowType range_component =
((ShadowTupleType) Range).getComponent(i);
if (range_component instanceof ShadowRealTupleType) {
int m = ((ShadowRealTupleType) range_component).getDimension();
Unit[] range_units = new Unit[m];
for (int j=0; j<m; j++) range_units[j] = dummy_units[j + start];
CoordinateSystem[] range_coord_sys =
((Field) data).getRangeCoordinateSystem(i);
/* WLH 23 May 99
renderer.setEarthSpatialData((ShadowRealTupleType)
range_component, null, null,
null, (RealTupleType) range_component.getType(),
range_coord_sys, range_units);
*/
ShadowRealTupleType component_reference =
((ShadowRealTupleType) range_component).getReference();
RealTupleType ref = (component_reference == null) ? null :
(RealTupleType) component_reference.getType();
Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits();
renderer.setEarthSpatialData((ShadowRealTupleType) range_component,
component_reference, ref, ref_units,
(RealTupleType) range_component.getType(),
range_coord_sys, range_units);
start += ((ShadowRealTupleType) range_component).getDimension();
}
else if (range_component instanceof ShadowRealType) {
start++;
}
}
} // end if (!(Range instanceof ShadowRealTupleType))
} // end if (Range instanceof ShadowTupleType)
// FREE
range_values = null;
} // end if (range_values != null)
if (anyText && text_values == null) {
for (int i=0; i<valueArrayLength; i++) {
if (display_values[i] != null) {
int displayScalarIndex = valueToScalar[i];
ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]);
ScalarType real = map.getScalar();
DisplayRealType dreal = display.getDisplayScalar(displayScalarIndex);
if (dreal.equals(Display.Text) && real instanceof RealType) {
text_control = (TextControl) map.getControl();
text_values = new String[domain_length];
NumberFormat format = text_control.getNumberFormat();
if (display_values[i].length == 1) {
String text = null;
if (display_values[i][0] != display_values[i][0]) {
text = "";
}
else if (format == null) {
text = PlotText.shortString(display_values[i][0]);
}
else {
text = format.format(display_values[i][0]);
}
for (int j=0; j<domain_length; j++) {
text_values[j] = text;
}
}
else {
if (format == null) {
for (int j=0; j<domain_length; j++) {
if (display_values[i][j] != display_values[i][j]) {
text_values[j] = "";
}
else {
text_values[j] = PlotText.shortString(display_values[i][j]);
}
}
}
else {
for (int j=0; j<domain_length; j++) {
if (display_values[i][j] != display_values[i][j]) {
text_values[j] = "";
}
else {
text_values[j] = format.format(display_values[i][j]);
}
}
}
}
break;
}
}
}
if (text_values == null) {
String[][] string_values = ((Field) data).getStringValues();
if (string_values != null) {
int[] textIndices = ((FunctionType) getType()).getTextIndices();
int n = string_values.length;
if (Range instanceof ShadowTextType) {
Vector maps = shadow_api.getTextMaps(-1, textIndices);
if (!maps.isEmpty()) {
text_values = string_values[0];
ScalarMap map = (ScalarMap) maps.firstElement();
text_control = (TextControl) map.getControl();
/*
System.out.println("Range is ShadowTextType, text_values[0] = " +
text_values[0] + " n = " + n);
*/
}
}
else if (Range instanceof ShadowTupleType) {
for (int i=0; i<n; i++) {
Vector maps = shadow_api.getTextMaps(i, textIndices);
if (!maps.isEmpty()) {
text_values = string_values[i];
ScalarMap map = (ScalarMap) maps.firstElement();
text_control = (TextControl) map.getControl();
/*
System.out.println("Range is ShadowTupleType, text_values[0] = " +
text_values[0] + " n = " + n + " i = " + i);
*/
}
}
} // end if (Range instanceof ShadowTupleType)
} // end if (string_values != null)
} // end if (text_values == null)
} // end if (anyText && text_values == null)
} // end if (this instanceof ShadowFunctionType)
// if (link != null) System.out.println("start assembleSelect " + (System.currentTimeMillis() - link.start_time));
//
// NOTE -
// currently assuming SelectRange changes require Transform
// see DataRenderer.isTransformControl
//
// get array that composites SelectRange components
// range_select is null if all selected
// MEM
boolean[][] range_select =
shadow_api.assembleSelect(display_values, domain_length, valueArrayLength,
valueToScalar, display, shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleSelect: numforced = " + numforced);
}
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// if (link != null) System.out.println("end assembleSelect " + (System.currentTimeMillis() - link.start_time));
// System.out.println("assembleSelect");
/*
System.out.println("doTerminal: isTerminal = " + getIsTerminal() +
" LevelOfDifficulty = " + LevelOfDifficulty);
*/
if (getIsTerminal()) {
if (!getFlat()) {
throw new DisplayException("terminal but not Flat");
}
GraphicsModeControl mode = (GraphicsModeControl)
display.getGraphicsModeControl().clone();
float pointSize =
default_values[display.getDisplayScalarIndex(Display.PointSize)];
mode.setPointSize(pointSize, true);
float lineWidth =
default_values[display.getDisplayScalarIndex(Display.LineWidth)];
mode.setLineWidth(lineWidth, true);
int lineStyle = (int)
default_values[display.getDisplayScalarIndex(Display.LineStyle)];
mode.setLineStyle(lineStyle, true);
boolean pointMode = mode.getPointMode();
byte missing_transparent = (byte) (mode.getMissingTransparent() ? 0 : -1);
// if (link != null) System.out.println("start assembleColor " + (System.currentTimeMillis() - link.start_time));
// MEM_WLH - this moved
boolean[] single_missing = {false, false, false, false};
// assemble an array of RGBA values
// MEM
byte[][] color_values =
shadow_api.assembleColor(display_values, valueArrayLength, valueToScalar,
display, default_values, range_select,
single_missing, shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleColor: numforced = " + numforced);
}
*/
/*
if (color_values != null) {
System.out.println("color_values.length = " + color_values.length +
" color_values[0].length = " + color_values[0].length);
System.out.println(color_values[0][0] + " " + color_values[1][0] +
" " + color_values[2][0]);
}
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// if (link != null) System.out.println("end assembleColor " + (System.currentTimeMillis() - link.start_time));
float[][] flow1_values = new float[3][];
float[][] flow2_values = new float[3][];
float[] flowScale = new float[2];
// MEM
shadow_api.assembleFlow(flow1_values, flow2_values, flowScale,
display_values, valueArrayLength, valueToScalar,
display, default_values, range_select, renderer,
shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleFlow: numforced = " + numforced);
}
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// System.out.println("assembleFlow");
// assemble an array of Display.DisplaySpatialCartesianTuple values
// and possibly spatial_set
float[][] spatial_values = new float[3][];
// spatialDimensions[0] = spatialDomainDimension and
// spatialDimensions[1] = spatialManifoldDimension
int[] spatialDimensions = new int[2];
// flags for swapping rows and columns in contour labels
boolean[] swap = {false, false, false};
// if (link != null) System.out.println("start assembleSpatial " + (System.currentTimeMillis() - link.start_time));
// WLH 29 April 99
boolean[][] spatial_range_select = new boolean[1][];
// MEM - but not if isTextureMap
Set spatial_set =
shadow_api.assembleSpatial(spatial_values, display_values, valueArrayLength,
valueToScalar, display, default_values,
inherited_values, domain_set, Domain.getAllSpatial(),
anyContour && !isLinearContour3D,
spatialDimensions, spatial_range_select,
flow1_values, flow2_values, flowScale, swap, renderer,
shadow_api);
if (isLinearContour3D) {
spatial_set = domain_set;
spatialDimensions[0] = 3;
spatialDimensions[1] = 3;
}
// WLH 29 April 99
boolean spatial_all_select = true;
if (spatial_range_select[0] != null) {
spatial_all_select = false;
if (range_select[0] == null) {
range_select[0] = spatial_range_select[0];
}
else if (spatial_range_select[0].length == 1) {
for (int j=0; j<range_select[0].length; j++) {
range_select[0][j] =
range_select[0][j] && spatial_range_select[0][0];
}
}
else {
for (int j=0; j<range_select[0].length; j++) {
range_select[0][j] =
range_select[0][j] && spatial_range_select[0][j];
}
}
}
spatial_range_select = null;
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleSpatial: numforced = " + numforced);
}
*/
/*
System.out.println("assembleSpatial (spatial_set == null) = " +
(spatial_set == null));
if (spatial_set != null) {
System.out.println("spatial_set.length = " + spatial_set.getLength());
}
System.out.println(" spatial_values lengths = " + spatial_values[0].length +
" " + spatial_values[1].length + " " + spatial_values[2].length);
System.out.println(" isTextureMap = " + isTextureMap);
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// if (link != null) System.out.println("end assembleSpatial " + (System.currentTimeMillis() - link.start_time));
int spatialDomainDimension = spatialDimensions[0];
int spatialManifoldDimension = spatialDimensions[1];
// System.out.println("assembleSpatial");
int spatial_length = Math.min(domain_length, spatial_values[0].length);
int color_length = Math.min(domain_length, color_values[0].length);
int alpha_length = color_values[3].length;
/*
System.out.println("assembleColor, color_length = " + color_length +
" " + color_values.length);
*/
// if (link != null) System.out.println("start missing color " + (System.currentTimeMillis() - link.start_time));
float constant_alpha = Float.NaN;
float[] constant_color = null;
// note alpha_length <= color_length
if (alpha_length == 1) {
/* MEM_WLH
if (color_values[3][0] != color_values[3][0]) {
*/
if (single_missing[3]) {
// a single missing alpha value, so render nothing
// System.out.println("single missing alpha");
return false;
}
// System.out.println("single alpha " + color_values[3][0]);
// constant alpha, so put it in appearance
/* MEM_WLH
if (color_values[3][0] > 0.999999f) {
*/
if (color_values[3][0] == -1) { // = 255 unsigned
constant_alpha = 0.0f;
// constant_alpha = 1.0f; WLH 26 May 99
// remove alpha from color_values
byte[][] c = new byte[3][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
color_values = c;
}
else { // not opaque
/* TransparencyAttributes with constant alpha seems to have broken
from The Java 3D API Specification: p. 118 transparency = 1 - alpha,
p. 116 transparency 0.0 = opaque, 1.0 = clear */
/*
broken alpha - put it back when alpha fixed
constant_alpha =
new TransparencyAttributes(TransparencyAttributes.NICEST,
1.0f - byteToFloat(color_values[3][0]));
so expand constant alpha to variable alpha
and note no alpha in Java2D:
*/
byte v = color_values[3][0];
color_values[3] = new byte[color_values[0].length];
for (int i=0; i<color_values[0].length; i++) {
color_values[3][i] = v;
}
/*
System.out.println("replicate alpha = " + v + " " + constant_alpha +
" " + color_values[0].length + " " +
color_values[3].length);
*/
} // end not opaque
/*
broken alpha - put it back when alpha fixed
// remove alpha from color_values
byte[][] c = new byte[3][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
color_values = c;
*/
} // end if (alpha_length == 1)
if (color_length == 1) {
if (spatialManifoldDimension == 1 ||
shadow_api.allowConstantColorSurfaces()) {
/* MEM_WLH
if (color_values[0][0] != color_values[0][0] ||
color_values[1][0] != color_values[1][0] ||
color_values[2][0] != color_values[2][0]) {
*/
if (single_missing[0] || single_missing[1] ||
single_missing[2]) {
// System.out.println("single missing color");
// a single missing color value, so render nothing
return false;
}
/* MEM_WLH
constant_color = new float[] {color_values[0][0], color_values[1][0],
color_values[2][0]};
*/
constant_color = new float[] {byteToFloat(color_values[0][0]),
byteToFloat(color_values[1][0]),
byteToFloat(color_values[2][0])};
color_values = null; // in this case, alpha doesn't matter
}
else {
// constant color doesn't work for surfaces in Java3D
// because of lighting
byte[][] c = new byte[color_values.length][domain_length];
for (int i=0; i<color_values.length; i++) {
for (int j=0; j<domain_length; j++) {
c[i][j] = color_values[i][0];
}
}
color_values = c;
}
} // end if (color_length == 1)
// if (link != null) System.out.println("end missing color " + (System.currentTimeMillis() - link.start_time));
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
if (LevelOfDifficulty == SIMPLE_FIELD) {
// only manage Spatial, Contour, Flow, Color, Alpha and
// SelectRange here
//
// TO_DO
// Flow rendering trajectories, which will be tricky -
// FlowControl must contain trajectory start points
//
/* MISSING TEST
for (int i=0; i<spatial_values[0].length; i+=3) {
spatial_values[0][i] = Float.NaN;
}
END MISSING TEST */
//
// TO_DO
// missing color_values and range_select
//
// in Java3D:
// NaN color component values are rendered as 1.0
// NaN spatial component values of points are NOT rendered
// NaN spatial component values of lines are rendered at infinity
// NaN spatial component values of triangles are a mess ??
//
/*
System.out.println("spatialDomainDimension = " +
spatialDomainDimension +
" spatialManifoldDimension = " +
spatialManifoldDimension +
" anyContour = " + anyContour +
" pointMode = " + pointMode);
*/
VisADGeometryArray array;
boolean anyShapeCreated = false;
VisADGeometryArray[] arrays =
shadow_api.assembleShape(display_values, valueArrayLength, valueToMap,
MapVector, valueToScalar, display, default_values,
inherited_values, spatial_values, color_values,
range_select, -1, shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleShape: numforced = " + numforced);
}
*/
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
array = arrays[i];
shadow_api.addToGroup(group, array, mode,
constant_alpha, constant_color);
array = null;
/* WLH 13 March 99 - why null in place of constant_alpha?
appearance = makeAppearance(mode, null, constant_color, geometry);
*/
}
anyShapeCreated = true;
arrays = null;
}
boolean anyTextCreated = false;
if (anyText && text_values != null && text_control != null) {
array = shadow_api.makeText(text_values, text_control, spatial_values,
color_values, range_select);
shadow_api.addTextToGroup(group, array, mode,
constant_alpha, constant_color);
array = null;
anyTextCreated = true;
}
boolean anyFlowCreated = false;
if (anyFlow) {
// try Flow1
arrays = shadow_api.makeStreamline(0, flow1_values, flowScale[0],
spatial_values, spatial_set, spatialManifoldDimension,
color_values, range_select);
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
if (arrays[i] != null) {
shadow_api.addToGroup(group, arrays[i], mode,
constant_alpha, constant_color);
arrays[i] = null;
}
}
}
else {
arrays = shadow_api.makeFlow(0, flow1_values, flowScale[0],
spatial_values, color_values, range_select);
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
if (arrays[i] != null) {
shadow_api.addToGroup(group, arrays[i], mode,
constant_alpha, constant_color);
arrays[i] = null;
}
}
}
}
anyFlowCreated = true;
// try Flow2
arrays = shadow_api.makeStreamline(1, flow2_values, flowScale[1],
spatial_values, spatial_set, spatialManifoldDimension,
color_values, range_select);
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
if (arrays[i] != null) {
shadow_api.addToGroup(group, arrays[i], mode,
constant_alpha, constant_color);
arrays[i] = null;
}
}
}
else {
arrays = shadow_api.makeFlow(1, flow2_values, flowScale[1],
spatial_values, color_values, range_select);
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
if (arrays[i] != null) {
shadow_api.addToGroup(group, arrays[i], mode,
constant_alpha, constant_color);
arrays[i] = null;
}
}
}
}
anyFlowCreated = true;
}
boolean anyContourCreated = false;
if (anyContour) {
/* Test01 at 64 x 64 x 64
domain 701, 491
range 20, 20
assembleColor 210, 201
assembleSpatial 130, 140
makeIsoSurface 381, 520
makeGeometry 350, 171
all makeGeometry time in calls to Java3D constructors, setCoordinates, etc
*/
// if (link != null) System.out.println("start makeContour " + (System.currentTimeMillis() - link.start_time));
anyContourCreated =
shadow_api.makeContour(valueArrayLength, valueToScalar,
display_values, inherited_values, MapVector, valueToMap,
domain_length, range_select, spatialManifoldDimension,
spatial_set, color_values, indexed, group, mode,
swap, constant_alpha, constant_color, shadow_api);
// if (link != null) System.out.println("end makeContour " + (System.currentTimeMillis() - link.start_time));
} // end if (anyContour)
if (!anyContourCreated && !anyFlowCreated &&
!anyTextCreated && !anyShapeCreated) {
// MEM
if (isTextureMap) {
if (color_values == null) {
// must be color_values array for texture mapping
color_values = new byte[3][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
if (range_select[0] != null && range_select[0].length > 1) {
int len = range_select[0].length;
/* can be misleading because of the way transparency composites
float alpha =
default_values[display.getDisplayScalarIndex(Display.Alpha)];
// System.out.println("alpha = " + alpha);
if (constant_alpha == constant_alpha) {
alpha = 1.0f - constant_alpha;
// System.out.println("constant_alpha = " + alpha);
}
if (color_values.length < 4) {
byte[][] c = new byte[4][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
c[3] = new byte[len];
for (int i=0; i<len; i++) c[3][i] = floatToByte(alpha);
constant_alpha = Float.NaN;
color_values = c;
}
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel invisible (transparent)
color_values[3][i] = 0;
}
}
*/
// WLH 27 March 2000
float alpha =
default_values[display.getDisplayScalarIndex(Display.Alpha)];
// System.out.println("alpha = " + alpha);
if (constant_alpha == constant_alpha) {
alpha = 1.0f - constant_alpha;
// System.out.println("constant_alpha = " + alpha);
}
if (color_values.length < 4) {
byte[][] c = new byte[4][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
c[3] = new byte[len];
for (int i=0; i<len; i++) c[3][i] = floatToByte(alpha);
constant_alpha = Float.NaN;
color_values = c;
}
if (mode.getMissingTransparent()) {
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel invisible (transparent)
color_values[3][i] = 0;
}
}
}
else {
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel black
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
} // end if (range_select[0] != null)
// MEM
VisADQuadArray qarray = new VisADQuadArray();
qarray.vertexCount = 4;
qarray.coordinates = coordinates;
qarray.texCoords = texCoords;
qarray.colors = colors;
qarray.normals = normals;
BufferedImage image =
createImage(data_width, data_height, texture_width,
texture_height, color_values);
shadow_api.textureToGroup(group, qarray, image, mode,
constant_alpha, constant_color,
texture_width, texture_height);
// System.out.println("isTextureMap done");
return false;
} // end if (isTextureMap)
else if (curvedTexture) {
// if (link != null) System.out.println("start texture " + (System.currentTimeMillis() - link.start_time));
if (color_values == null) { // never true?
// must be color_values array for texture mapping
color_values = new byte[3][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
if (range_select[0] != null) {
// WLH 27 March 2000
if (mode.getMissingTransparent()) {
spatial_set.cram_missing(range_select[0]);
spatial_all_select = false;
}
else {
for (int i=0; i<domain_length; i++) {
if (!range_select[0][i]) {
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
/* WLH 6 May 99
color_values =
selectToColor(range_select, color_values, constant_color,
constant_alpha, missing_transparent);
constant_alpha = Float.NaN;
*/
}
// get domain_set sizes
int[] lengths = ((GriddedSet) domain_set).getLengths();
data_width = lengths[0];
data_height = lengths[1];
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
int size = (data_width + data_height) / 2;
curved_size = Math.max(2, Math.min(curved_size, size / 32));
int nwidth = 2 + (data_width - 1) / curved_size;
int nheight = 2 + (data_height - 1) / curved_size;
// WLH 14 Aug 2001
if (range_select[0] != null && !domainOnlySpatial) {
// System.out.println("force curved_size = 1");
curved_size = 1;
nwidth = data_width;
nheight = data_height;
}
// System.out.println("curved_size = " + curved_size);
int nn = nwidth * nheight;
coordinates = new float[3 * nn];
int k = 0;
int[] is = new int[nwidth];
int[] js = new int[nheight];
for (int i=0; i<nwidth; i++) {
is[i] = Math.min(i * curved_size, data_width - 1);
}
for (int j=0; j<nheight; j++) {
js[j] = Math.min(j * curved_size, data_height - 1);
}
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
int ij = is[i] + data_width * js[j];
coordinates[k++] = spatial_values[0][ij];
coordinates[k++] = spatial_values[1][ij];
coordinates[k++] = spatial_values[2][ij];
/*
double size = Math.sqrt(spatial_values[0][ij] * spatial_values[0][ij] +
spatial_values[1][ij] * spatial_values[1][ij] +
spatial_values[2][ij] * spatial_values[2][ij]);
if (size < 0.2) {
System.out.println("spatial_values " + is[i] + " " + js[j] + " " +
spatial_values[0][ij] + " " + spatial_values[1][ij] + " " + spatial_values[2][ij]);
}
*/
}
}
normals = Gridded3DSet.makeNormals(coordinates, nwidth, nheight);
colors = new byte[3 * nn];
for (int i=0; i<3*nn; i++) colors[i] = (byte) 127;
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
int mt = 0;
texCoords = new float[2 * nn];
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
texCoords[mt++] = ratiow * is[i] / (data_width - 1.0f);
texCoords[mt++] = 1.0f - ratioh * js[j] / (data_height - 1.0f);
}
}
VisADTriangleStripArray tarray = new VisADTriangleStripArray();
tarray.stripVertexCounts = new int[nheight - 1];
for (int i=0; i<nheight - 1; i++) {
tarray.stripVertexCounts[i] = 2 * nwidth;
}
int len = (nheight - 1) * (2 * nwidth);
tarray.vertexCount = len;
tarray.normals = new float[3 * len];
tarray.coordinates = new float[3 * len];
tarray.colors = new byte[3 * len];
tarray.texCoords = new float[2 * len];
// shuffle normals into tarray.normals, etc
k = 0;
int kt = 0;
int nwidth3 = 3 * nwidth;
int nwidth2 = 2 * nwidth;
for (int i=0; i<nheight-1; i++) {
int m = i * nwidth3;
mt = i * nwidth2;
for (int j=0; j<nwidth; j++) {
tarray.coordinates[k] = coordinates[m];
tarray.coordinates[k+1] = coordinates[m+1];
tarray.coordinates[k+2] = coordinates[m+2];
tarray.coordinates[k+3] = coordinates[m+nwidth3];
tarray.coordinates[k+4] = coordinates[m+nwidth3+1];
tarray.coordinates[k+5] = coordinates[m+nwidth3+2];
tarray.normals[k] = normals[m];
tarray.normals[k+1] = normals[m+1];
tarray.normals[k+2] = normals[m+2];
tarray.normals[k+3] = normals[m+nwidth3];
tarray.normals[k+4] = normals[m+nwidth3+1];
tarray.normals[k+5] = normals[m+nwidth3+2];
tarray.colors[k] = colors[m];
tarray.colors[k+1] = colors[m+1];
tarray.colors[k+2] = colors[m+2];
tarray.colors[k+3] = colors[m+nwidth3];
tarray.colors[k+4] = colors[m+nwidth3+1];
tarray.colors[k+5] = colors[m+nwidth3+2];
tarray.texCoords[kt] = texCoords[mt];
tarray.texCoords[kt+1] = texCoords[mt+1];
tarray.texCoords[kt+2] = texCoords[mt+nwidth2];
tarray.texCoords[kt+3] = texCoords[mt+nwidth2+1];
k += 6;
m += 3;
kt += 4;
mt += 2;
}
}
if (!spatial_all_select) {
tarray = (VisADTriangleStripArray) tarray.removeMissing();
}
tarray = (VisADTriangleStripArray) tarray.adjustLongitude(renderer);
tarray = (VisADTriangleStripArray) tarray.adjustSeam(renderer);
BufferedImage image =
createImage(data_width, data_height, texture_width,
texture_height, color_values);
shadow_api.textureToGroup(group, tarray, image, mode,
constant_alpha, constant_color,
texture_width, texture_height);
// System.out.println("curvedTexture done");
// if (link != null) System.out.println("end texture " + (System.currentTimeMillis() - link.start_time));
return false;
} // end if (curvedTexture)
else if (isTexture3D) {
if (color_values == null) {
// must be color_values array for texture mapping
color_values = new byte[3][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
if (range_select[0] != null && range_select[0].length > 1) {
int len = range_select[0].length;
/* can be misleading because of the way transparency composites
WLH 15 March 2000 */
float alpha =
default_values[display.getDisplayScalarIndex(Display.Alpha)];
if (constant_alpha == constant_alpha) {
alpha = 1.0f - constant_alpha;
}
if (color_values.length < 4) {
byte[][] c = new byte[4][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
c[3] = new byte[len];
for (int i=0; i<len; i++) c[3][i] = floatToByte(alpha);
constant_alpha = Float.NaN;
color_values = c;
}
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel invisible (transparent)
color_values[3][i] = 0;
// WLH 15 March 2000
// make missing pixel black
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
/* WLH 15 March 2000 */
/* WLH 15 March 2000
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel black
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
*/
} // end if (range_select[0] != null)
// MEM
VisADQuadArray[] qarray =
{new VisADQuadArray(), new VisADQuadArray(), new VisADQuadArray()};
qarray[0].vertexCount = coordinatesX.length / 3;
qarray[0].coordinates = coordinatesX;
qarray[0].texCoords = texCoordsX;
qarray[0].colors = colorsX;
qarray[0].normals = normalsX;
qarray[1].vertexCount = coordinatesY.length / 3;
qarray[1].coordinates = coordinatesY;
qarray[1].texCoords = texCoordsY;
qarray[1].colors = colorsY;
qarray[1].normals = normalsY;
qarray[2].vertexCount = coordinatesZ.length / 3;
qarray[2].coordinates = coordinatesZ;
qarray[2].texCoords = texCoordsZ;
qarray[2].colors = colorsZ;
qarray[2].normals = normalsZ;
// WLH 3 June 99 - until Texture3D works on NT (etc)
BufferedImage[][] images = new BufferedImage[3][];
for (int i=0; i<3; i++) {
images[i] = createImages(i, data_width, data_height, data_depth,
texture_width, texture_height, texture_depth,
color_values);
}
BufferedImage[] imagesX = null;
BufferedImage[] imagesY = null;
BufferedImage[] imagesZ = null;
VisADQuadArray qarrayX = null;
VisADQuadArray qarrayY = null;
VisADQuadArray qarrayZ = null;
for (int i=0; i<3; i++) {
if (volume_tuple_index[i] == 0) {
qarrayX = qarray[i];
imagesX = images[i];
}
else if (volume_tuple_index[i] == 1) {
qarrayY = qarray[i];
imagesY = images[i];
}
else if (volume_tuple_index[i] == 2) {
qarrayZ = qarray[i];
imagesZ = images[i];
}
}
VisADQuadArray qarrayXrev = reverse(qarrayX);
VisADQuadArray qarrayYrev = reverse(qarrayY);
VisADQuadArray qarrayZrev = reverse(qarrayZ);
/* WLH 3 June 99 - comment this out until Texture3D works on NT (etc)
BufferedImage[] images =
createImages(2, data_width, data_height, data_depth,
texture_width, texture_height, texture_depth,
color_values);
shadow_api.texture3DToGroup(group, qarrayX, qarrayY, qarrayZ,
qarrayXrev, qarrayYrev, qarrayZrev,
images, mode, constant_alpha,
constant_color, texture_width,
texture_height, texture_depth, renderer);
*/
shadow_api.textureStackToGroup(group, qarrayX, qarrayY, qarrayZ,
qarrayXrev, qarrayYrev, qarrayZrev,
imagesX, imagesY, imagesZ,
mode, constant_alpha, constant_color,
texture_width, texture_height, texture_depth,
renderer);
// System.out.println("isTexture3D done");
return false;
} // end if (isTexture3D)
else if (pointMode || spatial_set == null ||
spatialManifoldDimension == 0 ||
spatialManifoldDimension == 3) {
if (range_select[0] != null) {
int len = range_select[0].length;
if (len == 1 || spatial_values[0].length == 1) {
return false;
}
for (int j=0; j<len; j++) {
// range_select[0][j] is either 0.0f or Float.NaN -
// setting to Float.NaN will move points off the screen
if (!range_select[0][j]) {
spatial_values[0][j] = Float.NaN;
}
}
/* CTR: 13 Oct 1998 - call new makePointGeometry signature */
array = makePointGeometry(spatial_values, color_values, true);
// System.out.println("makePointGeometry for some missing");
}
else {
array = makePointGeometry(spatial_values, color_values);
// System.out.println("makePointGeometry for pointMode");
}
}
else if (spatialManifoldDimension == 1) {
if (range_select[0] != null) {
// WLH 27 March 2000
if (mode.getMissingTransparent()) {
spatial_set.cram_missing(range_select[0]);
spatial_all_select = false;
}
else {
if (color_values == null) {
color_values = new byte[4][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
for (int i=0; i<domain_length; i++) {
if (!range_select[0][i]) {
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
/* WLH 6 May 99
color_values =
selectToColor(range_select, color_values, constant_color,
constant_alpha, missing_transparent);
constant_alpha = Float.NaN;
*/
}
array = spatial_set.make1DGeometry(color_values);
if (!spatial_all_select) array = array.removeMissing();
array = array.adjustLongitude(renderer);
array = array.adjustSeam(renderer);
// System.out.println("make1DGeometry");
}
else if (spatialManifoldDimension == 2) {
if (range_select[0] != null) {
// WLH 27 March 2000
if (mode.getMissingTransparent()) {
spatial_set.cram_missing(range_select[0]);
spatial_all_select = false;
}
else {
if (color_values == null) {
color_values = new byte[4][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
for (int i=0; i<domain_length; i++) {
if (!range_select[0][i]) {
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
/* WLH 6 May 99
color_values =
selectToColor(range_select, color_values, constant_color,
constant_alpha, missing_transparent);
constant_alpha = Float.NaN;
*/
}
array = spatial_set.make2DGeometry(color_values, indexed);
if (!spatial_all_select) array = array.removeMissing();
array = array.adjustLongitude(renderer);
array = array.adjustSeam(renderer);
// System.out.println("make2DGeometry vertexCount = " +
// array.vertexCount);
}
else {
throw new DisplayException("bad spatialManifoldDimension: " +
"ShadowFunctionOrSetType.doTransform");
}
if (array != null && array.vertexCount > 0) {
shadow_api.addToGroup(group, array, mode,
constant_alpha, constant_color);
// System.out.println("array.makeGeometry");
// FREE
array = null;
/* WLH 25 June 2000
if (renderer.getIsDirectManipulation()) {
renderer.setSpatialValues(spatial_values);
}
*/
}
} // end if (!anyContourCreated && !anyFlowCreated &&
// !anyTextCreated && !anyShapeCreated)
// WLH 25 June 2000
if (renderer.getIsDirectManipulation()) {
renderer.setSpatialValues(spatial_values);
}
// if (link != null) System.out.println("end doTransform " + (System.currentTimeMillis() - link.start_time));
return false;
} // end if (LevelOfDifficulty == SIMPLE_FIELD)
else if (LevelOfDifficulty == SIMPLE_ANIMATE_FIELD) {
Control control = null;
Object swit = null;
int index = -1;
if (DomainComponents.length == 1) {
RealType real = (RealType) DomainComponents[0].getType();
for (int i=0; i<valueArrayLength; i++) {
ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]);
float[] values = display_values[i];
if (values != null && real.equals(map.getScalar())) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType dreal =
display.getDisplayScalar(displayScalarIndex);
if (dreal.equals(Display.Animation) ||
dreal.equals(Display.SelectValue)) {
swit = shadow_api.makeSwitch();
index = i;
control = map.getControl();
break;
}
} // end if (values != null && && real.equals(map.getScalar()))
} // end for (int i=0; i<valueArrayLength; i++)
} // end if (DomainComponents.length == 1)
if (control == null) {
throw new DisplayException("bad SIMPLE_ANIMATE_FIELD: " +
"ShadowFunctionOrSetType.doTransform");
}
for (int i=0; i<domain_length; i++) {
Object branch = shadow_api.makeBranch();
if (range_select[0] == null || range_select[0].length == 1 ||
range_select[0][i]) {
VisADGeometryArray array = null;
float[][] sp = new float[3][1];
if (spatial_values[0].length > 1) {
sp[0][0] = spatial_values[0][i];
sp[1][0] = spatial_values[1][i];
sp[2][0] = spatial_values[2][i];
}
else {
sp[0][0] = spatial_values[0][0];
sp[1][0] = spatial_values[1][0];
sp[2][0] = spatial_values[2][0];
}
byte[][] co = new byte[3][1];
if (color_values == null) {
co[0][0] = floatToByte(constant_color[0]);
co[1][0] = floatToByte(constant_color[1]);
co[2][0] = floatToByte(constant_color[2]);
}
else if (color_values[0].length > 1) {
co[0][0] = color_values[0][i];
co[1][0] = color_values[1][i];
co[2][0] = color_values[2][i];
}
else {
co[0][0] = color_values[0][0];
co[1][0] = color_values[1][0];
co[2][0] = color_values[2][0];
}
boolean[][] ra = {{true}};
boolean anyShapeCreated = false;
VisADGeometryArray[] arrays =
shadow_api.assembleShape(display_values, valueArrayLength,
valueToMap, MapVector, valueToScalar, display,
default_values, inherited_values,
sp, co, ra, i, shadow_api);
if (arrays != null) {
for (int j=0; j<arrays.length; j++) {
array = arrays[j];
shadow_api.addToGroup(branch, array, mode,
constant_alpha, constant_color);
array = null;
/* why null constant_alpha?
appearance = makeAppearance(mode, null, constant_color, geometry);
*/
}
anyShapeCreated = true;
arrays = null;
}
boolean anyTextCreated = false;
if (anyText && text_values != null && text_control != null) {
String[] te = new String[1];
if (text_values.length > 1) {
te[0] = text_values[i];
}
else {
te[0] = text_values[0];
}
array = shadow_api.makeText(te, text_control, spatial_values, co, ra);
if (array != null) {
shadow_api.addTextToGroup(branch, array, mode,
constant_alpha, constant_color);
array = null;
anyTextCreated = true;
}
}
boolean anyFlowCreated = false;
if (anyFlow) {
if (flow1_values != null && flow1_values[0] != null) {
// try Flow1
float[][] f1 = new float[3][1];
if (flow1_values[0].length > 1) {
f1[0][0] = flow1_values[0][i];
f1[1][0] = flow1_values[1][i];
f1[2][0] = flow1_values[2][i];
}
else {
f1[0][0] = flow1_values[0][0];
f1[1][0] = flow1_values[1][0];
f1[2][0] = flow1_values[2][0];
}
arrays = shadow_api.makeFlow(0, f1, flowScale[0], sp, co, ra);
if (arrays != null) {
for (int j=0; j<arrays.length; j++) {
if (arrays[j] != null) {
shadow_api.addToGroup(branch, arrays[j], mode,
constant_alpha, constant_color);
arrays[j] = null;
}
}
}
anyFlowCreated = true;
}
// try Flow2
if (flow2_values != null && flow2_values[0] != null) {
float[][] f2 = new float[3][1];
if (flow2_values[0].length > 1) {
f2[0][0] = flow2_values[0][i];
f2[1][0] = flow2_values[1][i];
f2[2][0] = flow2_values[2][i];
}
else {
f2[0][0] = flow2_values[0][0];
f2[1][0] = flow2_values[1][0];
f2[2][0] = flow2_values[2][0];
}
arrays = shadow_api.makeFlow(1, f2, flowScale[1], sp, co, ra);
if (arrays != null) {
for (int j=0; j<arrays.length; j++) {
if (arrays[j] != null) {
shadow_api.addToGroup(branch, arrays[j], mode,
constant_alpha, constant_color);
arrays[j] = null;
}
}
}
anyFlowCreated = true;
}
}
if (!anyShapeCreated && !anyTextCreated &&
!anyFlowCreated) {
array = new VisADPointArray();
array.vertexCount = 1;
coordinates = new float[3];
coordinates[0] = sp[0][0];
coordinates[1] = sp[1][0];
coordinates[2] = sp[2][0];
array.coordinates = coordinates;
if (color_values != null) {
colors = new byte[3];
colors[0] = co[0][0];
colors[1] = co[1][0];
colors[2] = co[2][0];
array.colors = colors;
}
shadow_api.addToGroup(branch, array, mode,
constant_alpha, constant_color);
array = null;
// System.out.println("addChild " + i + " of " + domain_length);
}
}
else { // if (range_select[0][i])
/* WLH 18 Aug 98
empty BranchGroup or Shape3D may cause NullPointerException
from Shape3DRetained.setLive
// add null BranchGroup as child to maintain order
branch.addChild(new Shape3D());
*/
// System.out.println("addChild " + i + " of " + domain_length +
// " MISSING");
}
shadow_api.addToSwitch(swit, branch);
} // end for (int i=0; i<domain_length; i++)
shadow_api.addSwitch(group, swit, control, domain_set, renderer);
return false;
} // end if (LevelOfDifficulty == SIMPLE_ANIMATE_FIELD)
else { // must be LevelOfDifficulty == LEGAL
// add values to value_array according to SelectedMapVector-s
// of RealType-s in Domain (including Reference) and Range
//
// accumulate Vector of value_array-s at this ShadowType,
// to be rendered in a post-process to scanning data
//
// ** OR JUST EACH FIELD INDEPENDENTLY **
//
/*
return true;
*/
throw new UnimplementedException("terminal LEGAL unimplemented: " +
"ShadowFunctionOrSetType.doTransform");
}
}
else { // !isTerminal
// domain_values and range_values, as well as their References,
// already converted to default Units and added to display_values
// add values to value_array according to SelectedMapVector-s
// of RealType-s in Domain (including Reference), and
// recursively call doTransform on Range values
//
// TO_DO
// SelectRange (use boolean[][] range_select from assembleSelect),
// SelectValue, Animation
// DataRenderer.isTransformControl temporary hack:
// SelectRange.isTransform,
// !SelectValue.isTransform, !Animation.isTransform
//
// may need to split ShadowType.checkAnimationOrValue
// Display.Animation has no range, is single
// Display.Value has no range, is not single
//
// see Set.merge1DSets
boolean post = false;
Control control = null;
Object swit = null;
int index = -1;
if (DomainComponents.length == 1) {
RealType real = (RealType) DomainComponents[0].getType();
for (int i=0; i<valueArrayLength; i++) {
ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]);
float[] values = display_values[i];
if (values != null && real.equals(map.getScalar())) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType dreal =
display.getDisplayScalar(displayScalarIndex);
if (dreal.equals(Display.Animation) ||
dreal.equals(Display.SelectValue)) {
swit = shadow_api.makeSwitch();
index = i;
control = map.getControl();
break;
}
} // end if (values != null && real.equals(map.getScalar()))
} // end for (int i=0; i<valueArrayLength; i++)
} // end if (DomainComponents.length == 1)
if (control != null) {
shadow_api.addSwitch(group, swit, control, domain_set, renderer);
/*
group.addChild(swit);
control.addPair(swit, domain_set, renderer);
*/
}
float[] range_value_array = new float[valueArrayLength];
for (int j=0; j<display.getValueArrayLength(); j++) {
range_value_array[j] = Float.NaN;
}
for (int i=0; i<domain_length; i++) {
if (range_select[0] == null || range_select[0].length == 1 ||
range_select[0][i]) {
if (text_values != null && text_control != null) {
shadow_api.setText(text_values[i], text_control);
}
else {
shadow_api.setText(null, null);
}
for (int j=0; j<valueArrayLength; j++) {
if (display_values[j] != null) {
if (display_values[j].length == 1) {
range_value_array[j] = display_values[j][0];
}
else {
range_value_array[j] = display_values[j][i];
}
}
}
// push lat_index and lon_index for flow navigation
int[] lat_lon_indices = renderer.getLatLonIndices();
if (control != null) {
Object branch = shadow_api.makeBranch();
post |= shadow_api.recurseRange(branch, ((Field) data).getSample(i),
range_value_array, default_values,
renderer);
shadow_api.addToSwitch(swit, branch);
// System.out.println("addChild " + i + " of " + domain_length);
}
else {
Object branch = shadow_api.makeBranch();
post |= shadow_api.recurseRange(branch, ((Field) data).getSample(i),
range_value_array, default_values,
renderer);
shadow_api.addToGroup(group, branch);
}
// pop lat_index and lon_index for flow navigation
renderer.setLatLonIndices(lat_lon_indices);
}
else { // if (!range_select[0][i])
if (control != null) {
// add null BranchGroup as child to maintain order
Object branch = shadow_api.makeBranch();
shadow_api.addToSwitch(swit, branch);
// System.out.println("addChild " + i + " of " + domain_length +
// " MISSING");
}
}
}
/* why later than addPair & addChild(swit) ??
if (control != null) {
// initialize swit child selection
control.init();
}
*/
return post;
/*
throw new UnimplementedException("ShadowFunctionOrSetType.doTransform: " +
"not terminal");
*/
} // end if (!isTerminal)
}
public byte[][] selectToColor(boolean[][] range_select,
byte[][] color_values, float[] constant_color,
float constant_alpha, byte missing_transparent) {
int len = range_select[0].length;
byte[][] cv = new byte[4][];
if (color_values != null) {
for (int i=0; i<color_values.length; i++) {
cv[i] = color_values[i];
}
}
color_values = cv;
for (int i=0; i<4; i++) {
byte miss = (i < 3) ? 0 : missing_transparent;
if (color_values == null || color_values[i] == null) {
color_values[i] = new byte[len];
if (i < 3 && constant_color != null) {
byte c = floatToByte(constant_color[i]);
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? c : miss;
}
}
else if (i == 3 && constant_alpha == constant_alpha) {
if (constant_alpha < 0.99f) miss = 0;
byte c = floatToByte(constant_alpha);
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? c : miss;
}
}
else {
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? (byte) -1 : miss;
}
}
}
else if (color_values[i].length == 1) {
byte c = color_values[i][0];
if (i == 3 && c != -1) miss = 0;
color_values[i] = new byte[len];
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? c : miss;
}
}
else {
if (i == 3) miss = 0;
for (int j=0; j<len; j++) {
if (!range_select[0][j]) color_values[i][j] = miss;
}
}
}
return color_values;
}
public BufferedImage createImage(int data_width, int data_height,
int texture_width, int texture_height,
byte[][] color_values) throws VisADException {
BufferedImage image = null;
if (color_values.length > 3) {
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
image = new BufferedImage(colorModel, raster, false, null);
int[] intData = ((DataBufferInt)db).getData();
int k = 0;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = (color_values[3][k] < 0) ? color_values[3][k] + 256 :
color_values[3][k];
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
k++;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
}
else { // (color_values.length == 3)
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
// WLH 2 Nov 2000
DataBuffer db = raster.getDataBuffer();
int[] intData = null;
if (db instanceof DataBufferInt) {
intData = ((DataBufferInt)db).getData();
image = new BufferedImage(colorModel, raster, false, null);
}
else {
// System.out.println("byteData 3 1");
image = new BufferedImage(texture_width, texture_height,
BufferedImage.TYPE_INT_RGB);
intData = new int[texture_width * texture_height];
/*
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
int[] nBits = {8, 8, 8};
colorModel =
new ComponentColorModel(cs, nBits, false, false, Transparency.OPAQUE, 0);
raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
*/
}
// image = new BufferedImage(colorModel, raster, false, null);
// int[] intData = ((DataBufferInt)raster.getDataBuffer()).getData();
int k = 0;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = 255;
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
k++;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
// WLH 2 Nov 2000
if (!(db instanceof DataBufferInt)) {
// System.out.println("byteData 3 2");
image.setRGB(0, 0, texture_width, texture_height, intData, 0, texture_width);
/*
byte[] byteData = ((DataBufferByte)raster.getDataBuffer()).getData();
k = 0;
for (int i=0; i<intData.length; i++) {
byteData[k++] = (byte) (intData[i] & 255);
byteData[k++] = (byte) ((intData[i] >> 8) & 255);
byteData[k++] = (byte) ((intData[i] >> 16) & 255);
}
*/
/* WLH 4 Nov 2000, from com.sun.j3d.utils.geometry.Text2D
// For now, jdk 1.2 only handles ARGB format, not the RGBA we want
BufferedImage bImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
Graphics offscreenGraphics = bImage.createGraphics();
// First, erase the background to the text panel - set alpha to 0
Color myFill = new Color(0f, 0f, 0f, 0f);
offscreenGraphics.setColor(myFill);
offscreenGraphics.fillRect(0, 0, width, height);
// Next, set desired text properties (font, color) and draw String
offscreenGraphics.setFont(font);
Color myTextColor = new Color(color.x, color.y, color.z, 1f);
offscreenGraphics.setColor(myTextColor);
offscreenGraphics.drawString(text, 0, height - descent);
*/
} // end if (!(db instanceof DataBufferInt))
} // end if (color_values.length == 3)
return image;
}
public BufferedImage[] createImages(int axis, int data_width_in,
int data_height_in, int data_depth_in, int texture_width_in,
int texture_height_in, int texture_depth_in, byte[][] color_values)
throws VisADException {
int data_width, data_height, data_depth;
int texture_width, texture_height, texture_depth;
int kwidth, kheight, kdepth;
if (axis == 2) {
kwidth = 1;
kheight = data_width_in;
kdepth = data_width_in * data_height_in;
data_width = data_width_in;
data_height = data_height_in;
data_depth = data_depth_in;
texture_width = texture_width_in;
texture_height = texture_height_in;
texture_depth = texture_depth_in;
}
else if (axis == 1) {
kwidth = 1;
kdepth = data_width_in;
kheight = data_width_in * data_height_in;
data_width = data_width_in;
data_depth = data_height_in;
data_height = data_depth_in;
texture_width = texture_width_in;
texture_depth = texture_height_in;
texture_height = texture_depth_in;
}
else if (axis == 0) {
kdepth = 1;
kwidth = data_width_in;
kheight = data_width_in * data_height_in;
data_depth = data_width_in;
data_width = data_height_in;
data_height = data_depth_in;
texture_depth = texture_width_in;
texture_width = texture_height_in;
texture_height = texture_depth_in;
}
else {
return null;
}
BufferedImage[] images = new BufferedImage[texture_depth];
for (int d=0; d<data_depth; d++) {
if (color_values.length > 3) {
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
images[d] = new BufferedImage(colorModel, raster, false, null);
/* WLH 23 Feb 2000
if (axis == 1) {
images[(data_depth-1) - d] =
new BufferedImage(colorModel, raster, false, null);
}
else {
images[d] = new BufferedImage(colorModel, raster, false, null);
}
*/
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
int[] intData = ((DataBufferInt)db).getData();
// int k = d * data_width * data_height;
int kk = d * kdepth;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
int k = kk + j * kheight;
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = (color_values[3][k] < 0) ? color_values[3][k] + 256 :
color_values[3][k];
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
// k++;
k += kwidth;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
}
else { // (color_values.length == 3)
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
images[d] = new BufferedImage(colorModel, raster, false, null);
/* WLH 23 Feb 2000
if (axis == 1) {
images[(data_depth-1) - d] =
new BufferedImage(colorModel, raster, false, null);
}
else {
images[d] = new BufferedImage(colorModel, raster, false, null);
}
*/
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
int[] intData = ((DataBufferInt)db).getData();
// int k = d * data_width * data_height;
int kk = d * kdepth;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
int k = kk + j * kheight;
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = 255;
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
// k++;
k += kwidth;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
} // end if (color_values.length == 3)
} // end for (int d=0; d<data_depth; d++)
for (int d=data_depth; d<texture_depth; d++) {
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
images[d] = new BufferedImage(colorModel, raster, false, null);
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
int[] intData = ((DataBufferInt)db).getData();
for (int i=0; i<texture_width*texture_height; i++) {
intData[i] = 0;
}
}
return images;
}
public VisADQuadArray reverse(VisADQuadArray array) {
VisADQuadArray qarray = new VisADQuadArray();
qarray.coordinates = new float[array.coordinates.length];
qarray.texCoords = new float[array.texCoords.length];
qarray.colors = new byte[array.colors.length];
qarray.normals = new float[array.normals.length];
int count = array.vertexCount;
qarray.vertexCount = count;
int color_length = array.colors.length / count;
int tex_length = array.texCoords.length / count;
int i3 = 0;
int k3 = 3 * (count - 1);
int ic = 0;
int kc = color_length * (count - 1);
int it = 0;
int kt = tex_length * (count - 1);
for (int i=0; i<count; i++) {
qarray.coordinates[i3] = array.coordinates[k3];
qarray.coordinates[i3 + 1] = array.coordinates[k3 + 1];
qarray.coordinates[i3 + 2] = array.coordinates[k3 + 2];
qarray.texCoords[it] = array.texCoords[kt];
qarray.texCoords[it + 1] = array.texCoords[kt + 1];
if (tex_length == 3) qarray.texCoords[it + 2] = array.texCoords[kt + 2];
qarray.normals[i3] = array.normals[k3];
qarray.normals[i3 + 1] = array.normals[k3 + 1];
qarray.normals[i3 + 2] = array.normals[k3 + 2];
qarray.colors[ic] = array.colors[kc];
qarray.colors[ic + 1] = array.colors[kc + 1];
qarray.colors[ic + 2] = array.colors[kc + 2];
if (color_length == 4) qarray.colors[ic + 3] = array.colors[kc + 3];
i3 += 3;
k3 -= 3;
ic += color_length;
kc -= color_length;
it += tex_length;
kt -= tex_length;
}
return qarray;
}
}
| public boolean doTransform(Object group, Data data, float[] value_array,
float[] default_values, DataRenderer renderer,
ShadowType shadow_api)
throws VisADException, RemoteException {
// return if data is missing or no ScalarMaps
if (data.isMissing()) return false;
if (LevelOfDifficulty == NOTHING_MAPPED) return false;
// if transform has taken more than 500 milliseconds and there is
// a flag requesting re-transform, throw a DisplayInterruptException
DataDisplayLink link = renderer.getLink();
// if (link != null) System.out.println("\nstart doTransform " + (System.currentTimeMillis() - link.start_time));
if (link != null) {
boolean time_flag = false;
if (link.time_flag) {
time_flag = true;
}
else {
if (500 < System.currentTimeMillis() - link.start_time) {
link.time_flag = true;
time_flag = true;
}
}
if (time_flag) {
if (link.peekTicks()) {
throw new DisplayInterruptException("please wait . . .");
}
Enumeration maps = link.getSelectedMapVector().elements();
while(maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
if (map.peekTicks(renderer, link)) {
throw new DisplayInterruptException("please wait . . .");
}
}
}
} // end if (link != null)
// get 'shape' flags
boolean anyContour = getAnyContour();
boolean anyFlow = getAnyFlow();
boolean anyShape = getAnyShape();
boolean anyText = getAnyText();
boolean indexed = shadow_api.wantIndexed();
// get some precomputed values useful for transform
// length of ValueArray
int valueArrayLength = display.getValueArrayLength();
// mapping from ValueArray to DisplayScalar
int[] valueToScalar = display.getValueToScalar();
// mapping from ValueArray to MapVector
int[] valueToMap = display.getValueToMap();
Vector MapVector = display.getMapVector();
// array to hold values for various mappings
float[][] display_values = new float[valueArrayLength][];
// get values inherited from parent;
// assume these do not include SelectRange, SelectValue
// or Animation values - see temporary hack in
// DataRenderer.isTransformControl
for (int i=0; i<valueArrayLength; i++) {
if (inherited_values[i] > 0) {
display_values[i] = new float[1];
display_values[i][0] = value_array[i];
}
}
// check for only contours and only disabled contours
if (getIsTerminal() && anyContour &&
!anyFlow && !anyShape && !anyText) { // WLH 13 March 99
boolean any_enabled = false;
for (int i=0; i<valueArrayLength; i++) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType real = display.getDisplayScalar(displayScalarIndex);
if (real.equals(Display.IsoContour) && inherited_values[i] == 0) {
// non-inherited IsoContour, so generate contours
ContourControl control = (ContourControl)
((ScalarMap) MapVector.elementAt(valueToMap[i])).getControl();
boolean[] bvalues = new boolean[2];
float[] fvalues = new float[5];
control.getMainContours(bvalues, fvalues);
if (bvalues[0]) any_enabled = true;
}
}
if (!any_enabled) return false;
}
Set domain_set = null;
Unit[] dataUnits = null;
CoordinateSystem dataCoordinateSystem = null;
if (this instanceof ShadowFunctionType) {
// currently only implemented for Field
// must eventually extend to Function
if (!(data instanceof Field)) {
throw new UnimplementedException("data must be Field: " +
"ShadowFunctionOrSetType.doTransform: ");
}
domain_set = ((Field) data).getDomainSet();
dataUnits = ((Function) data).getDomainUnits();
dataCoordinateSystem = ((Function) data).getDomainCoordinateSystem();
}
else if (this instanceof ShadowSetType) {
domain_set = (Set) data;
dataUnits = ((Set) data).getSetUnits();
dataCoordinateSystem = ((Set) data).getCoordinateSystem();
}
else {
throw new DisplayException(
"must be ShadowFunctionType or ShadowSetType: " +
"ShadowFunctionOrSetType.doTransform");
}
float[][] domain_values = null;
double[][] domain_doubles = null;
Unit[] domain_units = ((RealTupleType) Domain.getType()).getDefaultUnits();
int domain_length;
int domain_dimension;
try {
domain_length = domain_set.getLength();
domain_dimension = domain_set.getDimension();
}
catch (SetException e) {
return false;
}
// ShadowRealTypes of Domain
ShadowRealType[] DomainComponents = getDomainComponents();
int alpha_index = display.getDisplayScalarIndex(Display.Alpha);
// array to hold values for Text mapping (can only be one)
String[] text_values = null;
// get any text String and TextControl inherited from parent
TextControl text_control = shadow_api.getParentTextControl();
String inherited_text = shadow_api.getParentText();
if (inherited_text != null) {
text_values = new String[domain_length];
for (int i=0; i<domain_length; i++) {
text_values[i] = inherited_text;
}
}
boolean isTextureMap = getIsTextureMap() &&
// default_values[alpha_index] > 0.99 &&
renderer.isLegalTextureMap() &&
(domain_set instanceof Linear2DSet ||
(domain_set instanceof LinearNDSet &&
domain_set.getDimension() == 2));
int curved_size = display.getGraphicsModeControl().getCurvedSize();
boolean curvedTexture = getCurvedTexture() &&
!isTextureMap &&
curved_size > 0 &&
getIsTerminal() && // implied by getCurvedTexture()?
shadow_api.allowCurvedTexture() &&
default_values[alpha_index] > 0.99 &&
renderer.isLegalTextureMap() &&
domain_set.getManifoldDimension() == 2 &&
domain_set instanceof GriddedSet; // WLH 22 Aug 2002 Lak's bug
/* // WLH 22 Aug 2002 Lak's bug
(domain_set instanceof Gridded2DSet ||
(domain_set instanceof GriddedSet &&
domain_set.getDimension() == 2));
*/
boolean domainOnlySpatial =
Domain.getAllSpatial() && !Domain.getMultipleDisplayScalar();
boolean isTexture3D = getIsTexture3D() &&
// default_values[alpha_index] > 0.99 &&
renderer.isLegalTextureMap() &&
(domain_set instanceof Linear3DSet ||
(domain_set instanceof LinearNDSet &&
domain_set.getDimension() == 3));
// WLH 1 April 2000
boolean range3D = isTexture3D && anyRange(Domain.getDisplayIndices());
boolean isLinearContour3D = getIsLinearContour3D() &&
domain_set instanceof Linear3DSet &&
shadow_api.allowLinearContour();
/*
System.out.println("doTransform.isTextureMap = " + isTextureMap + " " +
getIsTextureMap() + " " +
// (default_values[alpha_index] > 0.99) + " " +
renderer.isLegalTextureMap() + " " +
(domain_set instanceof Linear2DSet) + " " +
(domain_set instanceof LinearNDSet) + " " +
(domain_set.getDimension() == 2));
System.out.println("doTransform.curvedTexture = " + curvedTexture + " " +
getCurvedTexture() + " " +
!isTextureMap + " " +
(curved_size > 0) + " " +
getIsTerminal() + " " +
shadow_api.allowCurvedTexture() + " " +
(default_values[alpha_index] > 0.99) + " " +
renderer.isLegalTextureMap() + " " +
(domain_set instanceof Gridded2DSet) + " " +
(domain_set instanceof GriddedSet) + " " +
(domain_set.getDimension() == 2) );
*/
float[] coordinates = null;
float[] texCoords = null;
float[] normals = null;
byte[] colors = null;
int data_width = 0;
int data_height = 0;
int data_depth = 0;
int texture_width = 1;
int texture_height = 1;
int texture_depth = 1;
float[] coordinatesX = null;
float[] texCoordsX = null;
float[] normalsX = null;
byte[] colorsX = null;
float[] coordinatesY = null;
float[] texCoordsY = null;
float[] normalsY = null;
byte[] colorsY = null;
float[] coordinatesZ = null;
float[] texCoordsZ = null;
float[] normalsZ = null;
byte[] colorsZ = null;
int[] volume_tuple_index = null;
// if (link != null) System.out.println("test isTextureMap " + (System.currentTimeMillis() - link.start_time));
if (isTextureMap) {
Linear1DSet X = null;
Linear1DSet Y = null;
if (domain_set instanceof Linear2DSet) {
X = ((Linear2DSet) domain_set).getX();
Y = ((Linear2DSet) domain_set).getY();
}
else {
X = ((LinearNDSet) domain_set).getLinear1DComponent(0);
Y = ((LinearNDSet) domain_set).getLinear1DComponent(1);
}
float[][] limits = new float[2][2];
limits[0][0] = (float) X.getFirst();
limits[0][1] = (float) X.getLast();
limits[1][0] = (float) Y.getFirst();
limits[1][1] = (float) Y.getLast();
// convert values to default units (used in display)
limits = Unit.convertTuple(limits, dataUnits, domain_units);
// get domain_set sizes
data_width = X.getLength();
data_height = Y.getLength();
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
int[] tuple_index = new int[3];
if (DomainComponents.length != 2) {
throw new DisplayException("texture domain dimension != 2:" +
"ShadowFunctionOrSetType.doTransform");
}
for (int i=0; i<DomainComponents.length; i++) {
Enumeration maps = DomainComponents[i].getSelectedMapVector().elements();
while (maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
DisplayRealType real = map.getDisplayScalar();
DisplayTupleType tuple = real.getTuple();
if (Display.DisplaySpatialCartesianTuple.equals(tuple)) {
// scale values
limits[i] = map.scaleValues(limits[i]);
// get spatial index
tuple_index[i] = real.getTupleIndex();
break;
}
}
/*
if (tuple == null ||
!tuple.equals(Display.DisplaySpatialCartesianTuple)) {
throw new DisplayException("texture with bad tuple: " +
"ShadowFunctionOrSetType.doTransform");
}
if (maps.hasMoreElements()) {
throw new DisplayException("texture with multiple spatial: " +
"ShadowFunctionOrSetType.doTransform");
}
*/
} // end for (int i=0; i<DomainComponents.length; i++)
// get spatial index not mapped from domain_set
tuple_index[2] = 3 - (tuple_index[0] + tuple_index[1]);
DisplayRealType real = (DisplayRealType)
Display.DisplaySpatialCartesianTuple.getComponent(tuple_index[2]);
int value2_index = display.getDisplayScalarIndex(real);
float value2 = default_values[value2_index];
// float value2 = 0.0f; WLH 30 Aug 99
for (int i=0; i<valueArrayLength; i++) {
if (inherited_values[i] > 0 &&
real.equals(display.getDisplayScalar(valueToScalar[i])) ) {
value2 = value_array[i];
break;
}
}
coordinates = new float[12];
// corner 0
coordinates[tuple_index[0]] = limits[0][0];
coordinates[tuple_index[1]] = limits[1][0];
coordinates[tuple_index[2]] = value2;
// corner 1
coordinates[3 + tuple_index[0]] = limits[0][1];
coordinates[3 + tuple_index[1]] = limits[1][0];
coordinates[3 + tuple_index[2]] = value2;
// corner 2
coordinates[6 + tuple_index[0]] = limits[0][1];
coordinates[6 + tuple_index[1]] = limits[1][1];
coordinates[6 + tuple_index[2]] = value2;
// corner 3
coordinates[9 + tuple_index[0]] = limits[0][0];
coordinates[9 + tuple_index[1]] = limits[1][1];
coordinates[9 + tuple_index[2]] = value2;
// move image back in Java3D 2-D mode
shadow_api.adjustZ(coordinates);
texCoords = new float[8];
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
shadow_api.setTexCoords(texCoords, ratiow, ratioh);
normals = new float[12];
float n0 = ((coordinates[3+2]-coordinates[0+2]) *
(coordinates[6+1]-coordinates[0+1])) -
((coordinates[3+1]-coordinates[0+1]) *
(coordinates[6+2]-coordinates[0+2]));
float n1 = ((coordinates[3+0]-coordinates[0+0]) *
(coordinates[6+2]-coordinates[0+2])) -
((coordinates[3+2]-coordinates[0+2]) *
(coordinates[6+0]-coordinates[0+0]));
float n2 = ((coordinates[3+1]-coordinates[0+1]) *
(coordinates[6+0]-coordinates[0+0])) -
((coordinates[3+0]-coordinates[0+0]) *
(coordinates[6+1]-coordinates[0+1]));
float nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
// corner 0
normals[0] = n0;
normals[1] = n1;
normals[2] = n2;
// corner 1
normals[3] = n0;
normals[4] = n1;
normals[5] = n2;
// corner 2
normals[6] = n0;
normals[7] = n1;
normals[8] = n2;
// corner 3
normals[9] = n0;
normals[10] = n1;
normals[11] = n2;
colors = new byte[12];
for (int i=0; i<12; i++) colors[i] = (byte) 127;
/*
for (int i=0; i < 4; i++) {
System.out.println("i = " + i + " texCoords = " + texCoords[2 * i] + " " +
texCoords[2 * i + 1]);
System.out.println(" coordinates = " + coordinates[3 * i] + " " +
coordinates[3 * i + 1] + " " + coordinates[3 * i + 2]);
System.out.println(" normals = " + normals[3 * i] + " " + normals[3 * i + 1] +
" " + normals[3 * i + 2]);
}
*/
}
else if (isTexture3D) {
Linear1DSet X = null;
Linear1DSet Y = null;
Linear1DSet Z = null;
if (domain_set instanceof Linear3DSet) {
X = ((Linear3DSet) domain_set).getX();
Y = ((Linear3DSet) domain_set).getY();
Z = ((Linear3DSet) domain_set).getZ();
}
else {
X = ((LinearNDSet) domain_set).getLinear1DComponent(0);
Y = ((LinearNDSet) domain_set).getLinear1DComponent(1);
Z = ((LinearNDSet) domain_set).getLinear1DComponent(2);
}
float[][] limits = new float[3][2];
limits[0][0] = (float) X.getFirst();
limits[0][1] = (float) X.getLast();
limits[1][0] = (float) Y.getFirst();
limits[1][1] = (float) Y.getLast();
limits[2][0] = (float) Z.getFirst();
limits[2][1] = (float) Z.getLast();
// convert values to default units (used in display)
limits = Unit.convertTuple(limits, dataUnits, domain_units);
// get domain_set sizes
data_width = X.getLength();
data_height = Y.getLength();
data_depth = Z.getLength();
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
texture_depth = shadow_api.textureDepth(data_depth);
int[] tuple_index = new int[3];
if (DomainComponents.length != 3) {
throw new DisplayException("texture3D domain dimension != 3:" +
"ShadowFunctionOrSetType.doTransform");
}
for (int i=0; i<DomainComponents.length; i++) {
Enumeration maps = DomainComponents[i].getSelectedMapVector().elements();
while (maps.hasMoreElements()) {
ScalarMap map = (ScalarMap) maps.nextElement();
DisplayRealType real = map.getDisplayScalar();
DisplayTupleType tuple = real.getTuple();
if (Display.DisplaySpatialCartesianTuple.equals(tuple)) {
// scale values
limits[i] = map.scaleValues(limits[i]);
// get spatial index
tuple_index[i] = real.getTupleIndex();
break;
}
}
/*
if (tuple == null ||
!tuple.equals(Display.DisplaySpatialCartesianTuple)) {
throw new DisplayException("texture with bad tuple: " +
"ShadowFunctionOrSetType.doTransform");
}
if (maps.hasMoreElements()) {
throw new DisplayException("texture with multiple spatial: " +
"ShadowFunctionOrSetType.doTransform");
}
*/
} // end for (int i=0; i<DomainComponents.length; i++)
volume_tuple_index = tuple_index;
coordinatesX = new float[12 * data_width];
coordinatesY = new float[12 * data_height];
coordinatesZ = new float[12 * data_depth];
for (int i=0; i<data_depth; i++) {
int i12 = i * 12;
float depth = limits[2][0] +
(limits[2][1] - limits[2][0]) * i / (data_depth - 1.0f);
// corner 0
coordinatesZ[i12 + tuple_index[0]] = limits[0][0];
coordinatesZ[i12 + tuple_index[1]] = limits[1][0];
coordinatesZ[i12 + tuple_index[2]] = depth;
// corner 1
coordinatesZ[i12 + 3 + tuple_index[0]] = limits[0][1];
coordinatesZ[i12 + 3 + tuple_index[1]] = limits[1][0];
coordinatesZ[i12 + 3 + tuple_index[2]] = depth;
// corner 2
coordinatesZ[i12 + 6 + tuple_index[0]] = limits[0][1];
coordinatesZ[i12 + 6 + tuple_index[1]] = limits[1][1];
coordinatesZ[i12 + 6 + tuple_index[2]] = depth;
// corner 3
coordinatesZ[i12 + 9 + tuple_index[0]] = limits[0][0];
coordinatesZ[i12 + 9 + tuple_index[1]] = limits[1][1];
coordinatesZ[i12 + 9 + tuple_index[2]] = depth;
}
for (int i=0; i<data_height; i++) {
int i12 = i * 12;
float height = limits[1][0] +
(limits[1][1] - limits[1][0]) * i / (data_height - 1.0f);
// corner 0
coordinatesY[i12 + tuple_index[0]] = limits[0][0];
coordinatesY[i12 + tuple_index[1]] = height;
coordinatesY[i12 + tuple_index[2]] = limits[2][0];
// corner 1
coordinatesY[i12 + 3 + tuple_index[0]] = limits[0][1];
coordinatesY[i12 + 3 + tuple_index[1]] = height;
coordinatesY[i12 + 3 + tuple_index[2]] = limits[2][0];
// corner 2
coordinatesY[i12 + 6 + tuple_index[0]] = limits[0][1];
coordinatesY[i12 + 6 + tuple_index[1]] = height;
coordinatesY[i12 + 6 + tuple_index[2]] = limits[2][1];
// corner 3
coordinatesY[i12 + 9 + tuple_index[0]] = limits[0][0];
coordinatesY[i12 + 9 + tuple_index[1]] = height;
coordinatesY[i12 + 9 + tuple_index[2]] = limits[2][1];
}
for (int i=0; i<data_width; i++) {
int i12 = i * 12;
float width = limits[0][0] +
(limits[0][1] - limits[0][0]) * i / (data_width - 1.0f);
// corner 0
coordinatesX[i12 + tuple_index[0]] = width;
coordinatesX[i12 + tuple_index[1]] = limits[1][0];
coordinatesX[i12 + tuple_index[2]] = limits[2][0];
// corner 1
coordinatesX[i12 + 3 + tuple_index[0]] = width;
coordinatesX[i12 + 3 + tuple_index[1]] = limits[1][1];
coordinatesX[i12 + 3 + tuple_index[2]] = limits[2][0];
// corner 2
coordinatesX[i12 + 6 + tuple_index[0]] = width;
coordinatesX[i12 + 6 + tuple_index[1]] = limits[1][1];
coordinatesX[i12 + 6 + tuple_index[2]] = limits[2][1];
// corner 3
coordinatesX[i12 + 9 + tuple_index[0]] = width;
coordinatesX[i12 + 9 + tuple_index[1]] = limits[1][0];
coordinatesX[i12 + 9 + tuple_index[2]] = limits[2][1];
}
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
float ratiod = ((float) data_depth) / ((float) texture_depth);
/* WLH 3 June 99 - comment this out until Texture3D works on NT (etc)
texCoordsX =
shadow_api.setTex3DCoords(data_width, 0, ratiow, ratioh, ratiod);
texCoordsY =
shadow_api.setTex3DCoords(data_height, 1, ratiow, ratioh, ratiod);
texCoordsZ =
shadow_api.setTex3DCoords(data_depth, 2, ratiow, ratioh, ratiod);
*/
texCoordsX =
shadow_api.setTexStackCoords(data_width, 0, ratiow, ratioh, ratiod);
texCoordsY =
shadow_api.setTexStackCoords(data_height, 1, ratiow, ratioh, ratiod);
texCoordsZ =
shadow_api.setTexStackCoords(data_depth, 2, ratiow, ratioh, ratiod);
normalsX = new float[12 * data_width];
normalsY = new float[12 * data_height];
normalsZ = new float[12 * data_depth];
float n0, n1, n2, nlen;
n0 = ((coordinatesX[3+2]-coordinatesX[0+2]) *
(coordinatesX[6+1]-coordinatesX[0+1])) -
((coordinatesX[3+1]-coordinatesX[0+1]) *
(coordinatesX[6+2]-coordinatesX[0+2]));
n1 = ((coordinatesX[3+0]-coordinatesX[0+0]) *
(coordinatesX[6+2]-coordinatesX[0+2])) -
((coordinatesX[3+2]-coordinatesX[0+2]) *
(coordinatesX[6+0]-coordinatesX[0+0]));
n2 = ((coordinatesX[3+1]-coordinatesX[0+1]) *
(coordinatesX[6+0]-coordinatesX[0+0])) -
((coordinatesX[3+0]-coordinatesX[0+0]) *
(coordinatesX[6+1]-coordinatesX[0+1]));
nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
for (int i=0; i<normalsX.length; i+=3) {
normalsX[i] = n0;
normalsX[i + 1] = n1;
normalsX[i + 2] = n2;
}
n0 = ((coordinatesY[3+2]-coordinatesY[0+2]) *
(coordinatesY[6+1]-coordinatesY[0+1])) -
((coordinatesY[3+1]-coordinatesY[0+1]) *
(coordinatesY[6+2]-coordinatesY[0+2]));
n1 = ((coordinatesY[3+0]-coordinatesY[0+0]) *
(coordinatesY[6+2]-coordinatesY[0+2])) -
((coordinatesY[3+2]-coordinatesY[0+2]) *
(coordinatesY[6+0]-coordinatesY[0+0]));
n2 = ((coordinatesY[3+1]-coordinatesY[0+1]) *
(coordinatesY[6+0]-coordinatesY[0+0])) -
((coordinatesY[3+0]-coordinatesY[0+0]) *
(coordinatesY[6+1]-coordinatesY[0+1]));
nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
for (int i=0; i<normalsY.length; i+=3) {
normalsY[i] = n0;
normalsY[i + 1] = n1;
normalsY[i + 2] = n2;
}
n0 = ((coordinatesZ[3+2]-coordinatesZ[0+2]) *
(coordinatesZ[6+1]-coordinatesZ[0+1])) -
((coordinatesZ[3+1]-coordinatesZ[0+1]) *
(coordinatesZ[6+2]-coordinatesZ[0+2]));
n1 = ((coordinatesZ[3+0]-coordinatesZ[0+0]) *
(coordinatesZ[6+2]-coordinatesZ[0+2])) -
((coordinatesZ[3+2]-coordinatesZ[0+2]) *
(coordinatesZ[6+0]-coordinatesZ[0+0]));
n2 = ((coordinatesZ[3+1]-coordinatesZ[0+1]) *
(coordinatesZ[6+0]-coordinatesZ[0+0])) -
((coordinatesZ[3+0]-coordinatesZ[0+0]) *
(coordinatesZ[6+1]-coordinatesZ[0+1]));
nlen = (float) Math.sqrt(n0 * n0 + n1 * n1 + n2 * n2);
n0 = n0 / nlen;
n1 = n1 / nlen;
n2 = n2 / nlen;
for (int i=0; i<normalsZ.length; i+=3) {
normalsZ[i] = n0;
normalsZ[i + 1] = n1;
normalsZ[i + 2] = n2;
}
colorsX = new byte[12 * data_width];
colorsY = new byte[12 * data_height];
colorsZ = new byte[12 * data_depth];
for (int i=0; i<12*data_width; i++) colorsX[i] = (byte) 127;
for (int i=0; i<12*data_height; i++) colorsY[i] = (byte) 127;
for (int i=0; i<12*data_depth; i++) colorsZ[i] = (byte) 127;
/*
for (int i=0; i < 4; i++) {
System.out.println("i = " + i + " texCoordsX = " + texCoordsX[3 * i] + " " +
texCoordsX[3 * i + 1]);
System.out.println(" coordinatesX = " + coordinatesX[3 * i] + " " +
coordinatesX[3 * i + 1] + " " + coordinatesX[3 * i + 2]);
System.out.println(" normalsX = " + normalsX[3 * i] + " " +
normalsX[3 * i + 1] + " " + normalsX[3 * i + 2]);
}
*/
}
// WLH 1 April 2000
// else { // !isTextureMap && !isTexture3D
// WLH 16 July 2000 - add '&& !isLinearContour3D'
if (!isTextureMap && (!isTexture3D || range3D) && !isLinearContour3D) {
// if (link != null) System.out.println("start domain " + (System.currentTimeMillis() - link.start_time));
// get values from Function Domain
// NOTE - may defer this until needed, if needed
if (domain_dimension == 1) {
domain_doubles = domain_set.getDoubles(false);
domain_doubles = Unit.convertTuple(domain_doubles, dataUnits, domain_units);
mapValues(display_values, domain_doubles, DomainComponents);
}
else {
domain_values = domain_set.getSamples(false);
// convert values to default units (used in display)
// MEM & FREE
domain_values = Unit.convertTuple(domain_values, dataUnits, domain_units);
// System.out.println("got domain_values: domain_length = " + domain_length);
// map domain_values to appropriate DisplayRealType-s
// MEM
mapValues(display_values, domain_values, DomainComponents);
}
// System.out.println("mapped domain_values");
ShadowRealTupleType domain_reference = Domain.getReference();
/*
System.out.println("domain_reference = " + domain_reference);
if (domain_reference != null) {
System.out.println("getMappedDisplayScalar = " +
domain_reference.getMappedDisplayScalar());
}
*/
// if (link != null) System.out.println("end domain " + (System.currentTimeMillis() - link.start_time));
if (domain_reference != null && domain_reference.getMappedDisplayScalar()) {
// apply coordinate transform to domain values
RealTupleType ref = (RealTupleType) domain_reference.getType();
// MEM
float[][] reference_values = null;
double[][] reference_doubles = null;
if (domain_dimension == 1) {
reference_doubles =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) Domain.getType(), dataCoordinateSystem,
domain_units, null, domain_doubles);
}
else {
// WLH 23 June 99
if (curvedTexture && domainOnlySpatial) {
//if (link != null) System.out.println("start compute spline " + (System.currentTimeMillis() - link.start_time));
int[] lengths = ((GriddedSet) domain_set).getLengths();
data_width = lengths[0];
data_height = lengths[1];
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
int size = (data_width + data_height) / 2;
curved_size = Math.max(1, Math.min(curved_size, size / 32));
int nwidth = 2 + (data_width - 1) / curved_size;
int nheight = 2 + (data_height - 1) / curved_size;
/*
System.out.println("data_width = " + data_width + " data_height = " + data_height +
" texture_width = " + texture_width + " texture_height = " + texture_height +
" nwidth = " + nwidth + " nheight = " + nheight);
*/
int nn = nwidth * nheight;
int[] is = new int[nwidth];
int[] js = new int[nheight];
for (int i=0; i<nwidth; i++) {
is[i] = Math.min(i * curved_size, data_width - 1);
}
for (int j=0; j<nheight; j++) {
js[j] = Math.min(j * curved_size, data_height - 1);
}
// int domain_dimension = domain_values.length;
if (domain_dimension != domain_values.length) {
throw new VisADException("domain_dimension = " + domain_dimension +
" domain_values.length = " + domain_values.length);
}
// float[][] spline_domain = new float[2][nwidth * nheight]; WLH 22 Aug 2002
float[][] spline_domain = new float[domain_dimension][nwidth * nheight];
int k = 0;
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
int ij = is[i] + data_width * js[j];
spline_domain[0][k] = domain_values[0][ij];
spline_domain[1][k] = domain_values[1][ij];
if (domain_dimension == 3) spline_domain[2][k] = domain_values[2][ij];
k++;
}
}
float[][] spline_reference =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) Domain.getType(), dataCoordinateSystem,
domain_units, null, spline_domain);
// reference_values = new float[2][domain_length]; WLH 22 Aug 2002
reference_values = new float[domain_dimension][domain_length];
for (int i=0; i<domain_length; i++) {
reference_values[0][i] = Float.NaN;
reference_values[1][i] = Float.NaN;
if (domain_dimension == 3) reference_values[2][i] = Float.NaN;
}
k = 0;
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
int ij = is[i] + data_width * js[j];
reference_values[0][ij] = spline_reference[0][k];
reference_values[1][ij] = spline_reference[1][k];
if (domain_dimension == 3) reference_values[2][ij] = spline_reference[2][k];
k++;
}
}
// if (link != null) System.out.println("end compute spline " + (System.currentTimeMillis() - link.start_time));
}
else { // if !(curvedTexture && domainOnlySpatial)
reference_values =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) Domain.getType(), dataCoordinateSystem,
domain_units, null, domain_values);
}
} // end if !(domain_dimension == 1)
// WLH 13 Macrh 2000
// if (anyFlow) {
renderer.setEarthSpatialData(Domain, domain_reference, ref,
ref.getDefaultUnits(), (RealTupleType) Domain.getType(),
new CoordinateSystem[] {dataCoordinateSystem},
domain_units);
// WLH 13 Macrh 2000
// }
//
// TO_DO
// adjust any RealVectorTypes in range
// see FlatField.resample and FieldImpl.resample
//
// if (link != null) System.out.println("start map reference " + (System.currentTimeMillis() - link.start_time));
// map reference_values to appropriate DisplayRealType-s
ShadowRealType[] DomainReferenceComponents = getDomainReferenceComponents();
// MEM
if (domain_dimension == 1) {
mapValues(display_values, reference_doubles, DomainReferenceComponents);
}
else {
mapValues(display_values, reference_values, DomainReferenceComponents);
}
// if (link != null) System.out.println("end map reference " + (System.currentTimeMillis() - link.start_time));
/*
for (int i=0; i<DomainReferenceComponents.length; i++) {
System.out.println("DomainReferenceComponents[" + i + "] = " +
DomainReferenceComponents[i]);
System.out.println("reference_values[" + i + "].length = " +
reference_values[i].length);
}
System.out.println("mapped domain_reference values");
*/
// FREE
reference_values = null;
reference_doubles = null;
}
else { // if !(domain_reference != null &&
// domain_reference.getMappedDisplayScalar())
// WLH 13 March 2000
// if (anyFlow) {
/* WLH 23 May 99
renderer.setEarthSpatialData(Domain, null, null,
null, (RealTupleType) Domain.getType(),
new CoordinateSystem[] {dataCoordinateSystem},
domain_units);
*/
RealTupleType ref = (domain_reference == null) ? null :
(RealTupleType) domain_reference.getType();
Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits();
renderer.setEarthSpatialData(Domain, domain_reference, ref,
ref_units, (RealTupleType) Domain.getType(),
new CoordinateSystem[] {dataCoordinateSystem},
domain_units);
// WLH 13 March 2000
// }
}
// FREE
domain_values = null;
domain_doubles = null;
} // end if (!isTextureMap && (!isTexture3D || range3D) &&
// !isLinearContour3D)
if (this instanceof ShadowFunctionType) {
// if (link != null) System.out.println("start range " + (System.currentTimeMillis() - link.start_time));
// get range_values for RealType and RealTupleType
// components, in defaultUnits for RealType-s
// MEM - may copy (in convertTuple)
float[][] range_values = ((Field) data).getFloats(false);
// System.out.println("got range_values");
if (range_values != null) {
// map range_values to appropriate DisplayRealType-s
ShadowRealType[] RangeComponents = getRangeComponents();
// MEM
mapValues(display_values, range_values, RangeComponents);
// System.out.println("mapped range_values");
//
// transform any range CoordinateSystem-s
// into display_values, then mapValues
//
int[] refToComponent = getRefToComponent();
ShadowRealTupleType[] componentWithRef = getComponentWithRef();
int[] componentIndex = getComponentIndex();
if (refToComponent != null) {
for (int i=0; i<refToComponent.length; i++) {
int n = componentWithRef[i].getDimension();
int start = refToComponent[i];
float[][] values = new float[n][];
for (int j=0; j<n; j++) values[j] = range_values[j + start];
ShadowRealTupleType component_reference =
componentWithRef[i].getReference();
RealTupleType ref = (RealTupleType) component_reference.getType();
Unit[] range_units;
CoordinateSystem[] range_coord_sys;
if (i == 0 && componentWithRef[i].equals(Range)) {
range_units = ((Field) data).getDefaultRangeUnits();
range_coord_sys = ((Field) data).getRangeCoordinateSystem();
}
else {
Unit[] dummy_units = ((Field) data).getDefaultRangeUnits();
range_units = new Unit[n];
for (int j=0; j<n; j++) range_units[j] = dummy_units[j + start];
range_coord_sys =
((Field) data).getRangeCoordinateSystem(componentIndex[i]);
}
float[][] reference_values = null;
if (range_coord_sys.length == 1) {
// MEM
reference_values =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys[0], range_units, null, values);
// WLH 13 March 2000
// if (anyFlow) {
renderer.setEarthSpatialData(componentWithRef[i],
component_reference, ref, ref.getDefaultUnits(),
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys, range_units);
// WLH 13 March 2000
// }
}
else {
// MEM
reference_values = new float[n][domain_length];
float[][] temp = new float[n][1];
for (int j=0; j<domain_length; j++) {
for (int k=0; k<n; k++) temp[k][0] = values[k][j];
temp =
CoordinateSystem.transformCoordinates(
ref, null, ref.getDefaultUnits(), null,
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys[j], range_units, null, temp);
for (int k=0; k<n; k++) reference_values[k][j] = temp[k][0];
}
// WLH 13 March 2000
// if (anyFlow) {
renderer.setEarthSpatialData(componentWithRef[i],
component_reference, ref, ref.getDefaultUnits(),
(RealTupleType) componentWithRef[i].getType(),
range_coord_sys, range_units);
// WLH 13 March 2000
// }
}
// map reference_values to appropriate DisplayRealType-s
// MEM
/* WLH 17 April 99
mapValues(display_values, reference_values,
getComponents(componentWithRef[i], false));
*/
mapValues(display_values, reference_values,
getComponents(component_reference, false));
// FREE
reference_values = null;
// FREE (redundant reference to range_values)
values = null;
} // end for (int i=0; i<refToComponent.length; i++)
} // end (refToComponent != null)
// if (link != null) System.out.println("end range " + (System.currentTimeMillis() - link.start_time));
// setEarthSpatialData calls when no CoordinateSystem
// WLH 13 March 2000
// if (Range instanceof ShadowTupleType && anyFlow) {
if (Range instanceof ShadowTupleType) {
if (Range instanceof ShadowRealTupleType) {
Unit[] range_units = ((Field) data).getDefaultRangeUnits();
CoordinateSystem[] range_coord_sys =
((Field) data).getRangeCoordinateSystem();
/* WLH 23 May 99
renderer.setEarthSpatialData((ShadowRealTupleType) Range,
null, null, null, (RealTupleType) Range.getType(),
range_coord_sys, range_units);
*/
ShadowRealTupleType component_reference =
((ShadowRealTupleType) Range).getReference();
RealTupleType ref = (component_reference == null) ? null :
(RealTupleType) component_reference.getType();
Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits();
renderer.setEarthSpatialData((ShadowRealTupleType) Range,
component_reference, ref, ref_units,
(RealTupleType) Range.getType(),
range_coord_sys, range_units);
}
else { // if (!(Range instanceof ShadowRealTupleType))
Unit[] dummy_units = ((Field) data).getDefaultRangeUnits();
int start = 0;
int n = ((ShadowTupleType) Range).getDimension();
for (int i=0; i<n ;i++) {
ShadowType range_component =
((ShadowTupleType) Range).getComponent(i);
if (range_component instanceof ShadowRealTupleType) {
int m = ((ShadowRealTupleType) range_component).getDimension();
Unit[] range_units = new Unit[m];
for (int j=0; j<m; j++) range_units[j] = dummy_units[j + start];
CoordinateSystem[] range_coord_sys =
((Field) data).getRangeCoordinateSystem(i);
/* WLH 23 May 99
renderer.setEarthSpatialData((ShadowRealTupleType)
range_component, null, null,
null, (RealTupleType) range_component.getType(),
range_coord_sys, range_units);
*/
ShadowRealTupleType component_reference =
((ShadowRealTupleType) range_component).getReference();
RealTupleType ref = (component_reference == null) ? null :
(RealTupleType) component_reference.getType();
Unit[] ref_units = (ref == null) ? null : ref.getDefaultUnits();
renderer.setEarthSpatialData((ShadowRealTupleType) range_component,
component_reference, ref, ref_units,
(RealTupleType) range_component.getType(),
range_coord_sys, range_units);
start += ((ShadowRealTupleType) range_component).getDimension();
}
else if (range_component instanceof ShadowRealType) {
start++;
}
}
} // end if (!(Range instanceof ShadowRealTupleType))
} // end if (Range instanceof ShadowTupleType)
// FREE
range_values = null;
} // end if (range_values != null)
if (anyText && text_values == null) {
for (int i=0; i<valueArrayLength; i++) {
if (display_values[i] != null) {
int displayScalarIndex = valueToScalar[i];
ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]);
ScalarType real = map.getScalar();
DisplayRealType dreal = display.getDisplayScalar(displayScalarIndex);
if (dreal.equals(Display.Text) && real instanceof RealType) {
text_control = (TextControl) map.getControl();
text_values = new String[domain_length];
NumberFormat format = text_control.getNumberFormat();
if (display_values[i].length == 1) {
String text = null;
if (display_values[i][0] != display_values[i][0]) {
text = "";
}
else if (format == null) {
text = PlotText.shortString(display_values[i][0]);
}
else {
text = format.format(display_values[i][0]);
}
for (int j=0; j<domain_length; j++) {
text_values[j] = text;
}
}
else {
if (format == null) {
for (int j=0; j<domain_length; j++) {
if (display_values[i][j] != display_values[i][j]) {
text_values[j] = "";
}
else {
text_values[j] = PlotText.shortString(display_values[i][j]);
}
}
}
else {
for (int j=0; j<domain_length; j++) {
if (display_values[i][j] != display_values[i][j]) {
text_values[j] = "";
}
else {
text_values[j] = format.format(display_values[i][j]);
}
}
}
}
break;
}
}
}
if (text_values == null) {
String[][] string_values = ((Field) data).getStringValues();
if (string_values != null) {
int[] textIndices = ((FunctionType) getType()).getTextIndices();
int n = string_values.length;
if (Range instanceof ShadowTextType) {
Vector maps = shadow_api.getTextMaps(-1, textIndices);
if (!maps.isEmpty()) {
text_values = string_values[0];
ScalarMap map = (ScalarMap) maps.firstElement();
text_control = (TextControl) map.getControl();
/*
System.out.println("Range is ShadowTextType, text_values[0] = " +
text_values[0] + " n = " + n);
*/
}
}
else if (Range instanceof ShadowTupleType) {
for (int i=0; i<n; i++) {
Vector maps = shadow_api.getTextMaps(i, textIndices);
if (!maps.isEmpty()) {
text_values = string_values[i];
ScalarMap map = (ScalarMap) maps.firstElement();
text_control = (TextControl) map.getControl();
/*
System.out.println("Range is ShadowTupleType, text_values[0] = " +
text_values[0] + " n = " + n + " i = " + i);
*/
}
}
} // end if (Range instanceof ShadowTupleType)
} // end if (string_values != null)
} // end if (text_values == null)
} // end if (anyText && text_values == null)
} // end if (this instanceof ShadowFunctionType)
// if (link != null) System.out.println("start assembleSelect " + (System.currentTimeMillis() - link.start_time));
//
// NOTE -
// currently assuming SelectRange changes require Transform
// see DataRenderer.isTransformControl
//
// get array that composites SelectRange components
// range_select is null if all selected
// MEM
boolean[][] range_select =
shadow_api.assembleSelect(display_values, domain_length, valueArrayLength,
valueToScalar, display, shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleSelect: numforced = " + numforced);
}
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// if (link != null) System.out.println("end assembleSelect " + (System.currentTimeMillis() - link.start_time));
// System.out.println("assembleSelect");
/*
System.out.println("doTerminal: isTerminal = " + getIsTerminal() +
" LevelOfDifficulty = " + LevelOfDifficulty);
*/
if (getIsTerminal()) {
if (!getFlat()) {
throw new DisplayException("terminal but not Flat");
}
GraphicsModeControl mode = (GraphicsModeControl)
display.getGraphicsModeControl().clone();
float pointSize =
default_values[display.getDisplayScalarIndex(Display.PointSize)];
mode.setPointSize(pointSize, true);
float lineWidth =
default_values[display.getDisplayScalarIndex(Display.LineWidth)];
mode.setLineWidth(lineWidth, true);
int lineStyle = (int)
default_values[display.getDisplayScalarIndex(Display.LineStyle)];
mode.setLineStyle(lineStyle, true);
boolean pointMode = mode.getPointMode();
byte missing_transparent = (byte) (mode.getMissingTransparent() ? 0 : -1);
// if (link != null) System.out.println("start assembleColor " + (System.currentTimeMillis() - link.start_time));
// MEM_WLH - this moved
boolean[] single_missing = {false, false, false, false};
// assemble an array of RGBA values
// MEM
byte[][] color_values =
shadow_api.assembleColor(display_values, valueArrayLength, valueToScalar,
display, default_values, range_select,
single_missing, shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleColor: numforced = " + numforced);
}
*/
/*
if (color_values != null) {
System.out.println("color_values.length = " + color_values.length +
" color_values[0].length = " + color_values[0].length);
System.out.println(color_values[0][0] + " " + color_values[1][0] +
" " + color_values[2][0]);
}
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// if (link != null) System.out.println("end assembleColor " + (System.currentTimeMillis() - link.start_time));
float[][] flow1_values = new float[3][];
float[][] flow2_values = new float[3][];
float[] flowScale = new float[2];
// MEM
shadow_api.assembleFlow(flow1_values, flow2_values, flowScale,
display_values, valueArrayLength, valueToScalar,
display, default_values, range_select, renderer,
shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleFlow: numforced = " + numforced);
}
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// System.out.println("assembleFlow");
// assemble an array of Display.DisplaySpatialCartesianTuple values
// and possibly spatial_set
float[][] spatial_values = new float[3][];
// spatialDimensions[0] = spatialDomainDimension and
// spatialDimensions[1] = spatialManifoldDimension
int[] spatialDimensions = new int[2];
// flags for swapping rows and columns in contour labels
boolean[] swap = {false, false, false};
// if (link != null) System.out.println("start assembleSpatial " + (System.currentTimeMillis() - link.start_time));
// WLH 29 April 99
boolean[][] spatial_range_select = new boolean[1][];
// MEM - but not if isTextureMap
Set spatial_set =
shadow_api.assembleSpatial(spatial_values, display_values, valueArrayLength,
valueToScalar, display, default_values,
inherited_values, domain_set, Domain.getAllSpatial(),
anyContour && !isLinearContour3D,
spatialDimensions, spatial_range_select,
flow1_values, flow2_values, flowScale, swap, renderer,
shadow_api);
if (isLinearContour3D) {
spatial_set = domain_set;
spatialDimensions[0] = 3;
spatialDimensions[1] = 3;
}
// WLH 29 April 99
boolean spatial_all_select = true;
if (spatial_range_select[0] != null) {
spatial_all_select = false;
if (range_select[0] == null) {
range_select[0] = spatial_range_select[0];
}
else if (spatial_range_select[0].length == 1) {
for (int j=0; j<range_select[0].length; j++) {
range_select[0][j] =
range_select[0][j] && spatial_range_select[0][0];
}
}
else {
for (int j=0; j<range_select[0].length; j++) {
range_select[0][j] =
range_select[0][j] && spatial_range_select[0][j];
}
}
}
spatial_range_select = null;
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleSpatial: numforced = " + numforced);
}
*/
/*
System.out.println("assembleSpatial (spatial_set == null) = " +
(spatial_set == null));
if (spatial_set != null) {
System.out.println("spatial_set.length = " + spatial_set.getLength());
}
System.out.println(" spatial_values lengths = " + spatial_values[0].length +
" " + spatial_values[1].length + " " + spatial_values[2].length);
System.out.println(" isTextureMap = " + isTextureMap);
*/
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
// if (link != null) System.out.println("end assembleSpatial " + (System.currentTimeMillis() - link.start_time));
int spatialDomainDimension = spatialDimensions[0];
int spatialManifoldDimension = spatialDimensions[1];
// System.out.println("assembleSpatial");
int spatial_length = Math.min(domain_length, spatial_values[0].length);
int color_length = Math.min(domain_length, color_values[0].length);
int alpha_length = color_values[3].length;
/*
System.out.println("assembleColor, color_length = " + color_length +
" " + color_values.length);
*/
// if (link != null) System.out.println("start missing color " + (System.currentTimeMillis() - link.start_time));
float constant_alpha = Float.NaN;
float[] constant_color = null;
// note alpha_length <= color_length
if (alpha_length == 1) {
/* MEM_WLH
if (color_values[3][0] != color_values[3][0]) {
*/
if (single_missing[3]) {
// a single missing alpha value, so render nothing
// System.out.println("single missing alpha");
return false;
}
// System.out.println("single alpha " + color_values[3][0]);
// constant alpha, so put it in appearance
/* MEM_WLH
if (color_values[3][0] > 0.999999f) {
*/
if (color_values[3][0] == -1) { // = 255 unsigned
constant_alpha = 0.0f;
// constant_alpha = 1.0f; WLH 26 May 99
// remove alpha from color_values
byte[][] c = new byte[3][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
color_values = c;
}
else { // not opaque
/* TransparencyAttributes with constant alpha seems to have broken
from The Java 3D API Specification: p. 118 transparency = 1 - alpha,
p. 116 transparency 0.0 = opaque, 1.0 = clear */
/*
broken alpha - put it back when alpha fixed
constant_alpha =
new TransparencyAttributes(TransparencyAttributes.NICEST,
1.0f - byteToFloat(color_values[3][0]));
so expand constant alpha to variable alpha
and note no alpha in Java2D:
*/
byte v = color_values[3][0];
color_values[3] = new byte[color_values[0].length];
for (int i=0; i<color_values[0].length; i++) {
color_values[3][i] = v;
}
/*
System.out.println("replicate alpha = " + v + " " + constant_alpha +
" " + color_values[0].length + " " +
color_values[3].length);
*/
} // end not opaque
/*
broken alpha - put it back when alpha fixed
// remove alpha from color_values
byte[][] c = new byte[3][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
color_values = c;
*/
} // end if (alpha_length == 1)
if (color_length == 1) {
if (spatialManifoldDimension == 1 ||
shadow_api.allowConstantColorSurfaces()) {
/* MEM_WLH
if (color_values[0][0] != color_values[0][0] ||
color_values[1][0] != color_values[1][0] ||
color_values[2][0] != color_values[2][0]) {
*/
if (single_missing[0] || single_missing[1] ||
single_missing[2]) {
// System.out.println("single missing color");
// a single missing color value, so render nothing
return false;
}
/* MEM_WLH
constant_color = new float[] {color_values[0][0], color_values[1][0],
color_values[2][0]};
*/
constant_color = new float[] {byteToFloat(color_values[0][0]),
byteToFloat(color_values[1][0]),
byteToFloat(color_values[2][0])};
color_values = null; // in this case, alpha doesn't matter
}
else {
// constant color doesn't work for surfaces in Java3D
// because of lighting
byte[][] c = new byte[color_values.length][domain_length];
for (int i=0; i<color_values.length; i++) {
for (int j=0; j<domain_length; j++) {
c[i][j] = color_values[i][0];
}
}
color_values = c;
}
} // end if (color_length == 1)
// if (link != null) System.out.println("end missing color " + (System.currentTimeMillis() - link.start_time));
if (range_select[0] != null && range_select[0].length == 1 &&
!range_select[0][0]) {
// single missing value in range_select[0], so render nothing
return false;
}
if (LevelOfDifficulty == SIMPLE_FIELD) {
// only manage Spatial, Contour, Flow, Color, Alpha and
// SelectRange here
//
// TO_DO
// Flow rendering trajectories, which will be tricky -
// FlowControl must contain trajectory start points
//
/* MISSING TEST
for (int i=0; i<spatial_values[0].length; i+=3) {
spatial_values[0][i] = Float.NaN;
}
END MISSING TEST */
//
// TO_DO
// missing color_values and range_select
//
// in Java3D:
// NaN color component values are rendered as 1.0
// NaN spatial component values of points are NOT rendered
// NaN spatial component values of lines are rendered at infinity
// NaN spatial component values of triangles are a mess ??
//
/*
System.out.println("spatialDomainDimension = " +
spatialDomainDimension +
" spatialManifoldDimension = " +
spatialManifoldDimension +
" anyContour = " + anyContour +
" pointMode = " + pointMode);
*/
VisADGeometryArray array;
boolean anyShapeCreated = false;
VisADGeometryArray[] arrays =
shadow_api.assembleShape(display_values, valueArrayLength, valueToMap,
MapVector, valueToScalar, display, default_values,
inherited_values, spatial_values, color_values,
range_select, -1, shadow_api);
/*
if (range_select[0] != null) {
int numforced = 0;
for (int k=0; k<range_select[0].length; k++) {
if (!range_select[0][k]) numforced++;
}
System.out.println("assembleShape: numforced = " + numforced);
}
*/
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
array = arrays[i];
shadow_api.addToGroup(group, array, mode,
constant_alpha, constant_color);
array = null;
/* WLH 13 March 99 - why null in place of constant_alpha?
appearance = makeAppearance(mode, null, constant_color, geometry);
*/
}
anyShapeCreated = true;
arrays = null;
}
boolean anyTextCreated = false;
if (anyText && text_values != null && text_control != null) {
array = shadow_api.makeText(text_values, text_control, spatial_values,
color_values, range_select);
shadow_api.addTextToGroup(group, array, mode,
constant_alpha, constant_color);
array = null;
anyTextCreated = true;
}
boolean anyFlowCreated = false;
if (anyFlow) {
// try Flow1
arrays = shadow_api.makeStreamline(0, flow1_values, flowScale[0],
spatial_values, spatial_set, spatialManifoldDimension,
color_values, range_select);
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
if (arrays[i] != null) {
shadow_api.addToGroup(group, arrays[i], mode,
constant_alpha, constant_color);
arrays[i] = null;
}
}
}
else {
arrays = shadow_api.makeFlow(0, flow1_values, flowScale[0],
spatial_values, color_values, range_select);
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
if (arrays[i] != null) {
shadow_api.addToGroup(group, arrays[i], mode,
constant_alpha, constant_color);
arrays[i] = null;
}
}
}
}
anyFlowCreated = true;
// try Flow2
arrays = shadow_api.makeStreamline(1, flow2_values, flowScale[1],
spatial_values, spatial_set, spatialManifoldDimension,
color_values, range_select);
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
if (arrays[i] != null) {
shadow_api.addToGroup(group, arrays[i], mode,
constant_alpha, constant_color);
arrays[i] = null;
}
}
}
else {
arrays = shadow_api.makeFlow(1, flow2_values, flowScale[1],
spatial_values, color_values, range_select);
if (arrays != null) {
for (int i=0; i<arrays.length; i++) {
if (arrays[i] != null) {
shadow_api.addToGroup(group, arrays[i], mode,
constant_alpha, constant_color);
arrays[i] = null;
}
}
}
}
anyFlowCreated = true;
}
boolean anyContourCreated = false;
if (anyContour) {
/* Test01 at 64 x 64 x 64
domain 701, 491
range 20, 20
assembleColor 210, 201
assembleSpatial 130, 140
makeIsoSurface 381, 520
makeGeometry 350, 171
all makeGeometry time in calls to Java3D constructors, setCoordinates, etc
*/
// if (link != null) System.out.println("start makeContour " + (System.currentTimeMillis() - link.start_time));
anyContourCreated =
shadow_api.makeContour(valueArrayLength, valueToScalar,
display_values, inherited_values, MapVector, valueToMap,
domain_length, range_select, spatialManifoldDimension,
spatial_set, color_values, indexed, group, mode,
swap, constant_alpha, constant_color, shadow_api);
// if (link != null) System.out.println("end makeContour " + (System.currentTimeMillis() - link.start_time));
} // end if (anyContour)
if (!anyContourCreated && !anyFlowCreated &&
!anyTextCreated && !anyShapeCreated) {
// MEM
if (isTextureMap) {
if (color_values == null) {
// must be color_values array for texture mapping
color_values = new byte[3][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
if (range_select[0] != null && range_select[0].length > 1) {
int len = range_select[0].length;
/* can be misleading because of the way transparency composites
float alpha =
default_values[display.getDisplayScalarIndex(Display.Alpha)];
// System.out.println("alpha = " + alpha);
if (constant_alpha == constant_alpha) {
alpha = 1.0f - constant_alpha;
// System.out.println("constant_alpha = " + alpha);
}
if (color_values.length < 4) {
byte[][] c = new byte[4][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
c[3] = new byte[len];
for (int i=0; i<len; i++) c[3][i] = floatToByte(alpha);
constant_alpha = Float.NaN;
color_values = c;
}
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel invisible (transparent)
color_values[3][i] = 0;
}
}
*/
// WLH 27 March 2000
float alpha =
default_values[display.getDisplayScalarIndex(Display.Alpha)];
// System.out.println("alpha = " + alpha);
if (constant_alpha == constant_alpha) {
alpha = 1.0f - constant_alpha;
// System.out.println("constant_alpha = " + alpha);
}
if (color_values.length < 4) {
byte[][] c = new byte[4][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
c[3] = new byte[len];
for (int i=0; i<len; i++) c[3][i] = floatToByte(alpha);
constant_alpha = Float.NaN;
color_values = c;
}
if (mode.getMissingTransparent()) {
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel invisible (transparent)
color_values[3][i] = 0;
}
}
}
else {
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel black
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
} // end if (range_select[0] != null)
// MEM
VisADQuadArray qarray = new VisADQuadArray();
qarray.vertexCount = 4;
qarray.coordinates = coordinates;
qarray.texCoords = texCoords;
qarray.colors = colors;
qarray.normals = normals;
BufferedImage image =
createImage(data_width, data_height, texture_width,
texture_height, color_values);
shadow_api.textureToGroup(group, qarray, image, mode,
constant_alpha, constant_color,
texture_width, texture_height);
// System.out.println("isTextureMap done");
return false;
} // end if (isTextureMap)
else if (curvedTexture) {
// if (link != null) System.out.println("start texture " + (System.currentTimeMillis() - link.start_time));
if (color_values == null) { // never true?
// must be color_values array for texture mapping
color_values = new byte[3][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
if (range_select[0] != null) {
// WLH 27 March 2000
if (mode.getMissingTransparent()) {
spatial_set.cram_missing(range_select[0]);
spatial_all_select = false;
}
else {
for (int i=0; i<domain_length; i++) {
if (!range_select[0][i]) {
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
/* WLH 6 May 99
color_values =
selectToColor(range_select, color_values, constant_color,
constant_alpha, missing_transparent);
constant_alpha = Float.NaN;
*/
}
// get domain_set sizes
int[] lengths = ((GriddedSet) domain_set).getLengths();
data_width = lengths[0];
data_height = lengths[1];
texture_width = shadow_api.textureWidth(data_width);
texture_height = shadow_api.textureHeight(data_height);
int size = (data_width + data_height) / 2;
curved_size = Math.max(2, Math.min(curved_size, size / 32));
int nwidth = 2 + (data_width - 1) / curved_size;
int nheight = 2 + (data_height - 1) / curved_size;
// WLH 14 Aug 2001
if (range_select[0] != null && !domainOnlySpatial) {
// System.out.println("force curved_size = 1");
curved_size = 1;
nwidth = data_width;
nheight = data_height;
}
// System.out.println("curved_size = " + curved_size);
int nn = nwidth * nheight;
coordinates = new float[3 * nn];
int k = 0;
int[] is = new int[nwidth];
int[] js = new int[nheight];
for (int i=0; i<nwidth; i++) {
is[i] = Math.min(i * curved_size, data_width - 1);
}
for (int j=0; j<nheight; j++) {
js[j] = Math.min(j * curved_size, data_height - 1);
}
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
int ij = is[i] + data_width * js[j];
coordinates[k++] = spatial_values[0][ij];
coordinates[k++] = spatial_values[1][ij];
coordinates[k++] = spatial_values[2][ij];
/*
double size = Math.sqrt(spatial_values[0][ij] * spatial_values[0][ij] +
spatial_values[1][ij] * spatial_values[1][ij] +
spatial_values[2][ij] * spatial_values[2][ij]);
if (size < 0.2) {
System.out.println("spatial_values " + is[i] + " " + js[j] + " " +
spatial_values[0][ij] + " " + spatial_values[1][ij] + " " + spatial_values[2][ij]);
}
*/
}
}
normals = Gridded3DSet.makeNormals(coordinates, nwidth, nheight);
colors = new byte[3 * nn];
for (int i=0; i<3*nn; i++) colors[i] = (byte) 127;
float ratiow = ((float) data_width) / ((float) texture_width);
float ratioh = ((float) data_height) / ((float) texture_height);
int mt = 0;
texCoords = new float[2 * nn];
for (int j=0; j<nheight; j++) {
for (int i=0; i<nwidth; i++) {
texCoords[mt++] = ratiow * is[i] / (data_width - 1.0f);
texCoords[mt++] = 1.0f - ratioh * js[j] / (data_height - 1.0f);
}
}
VisADTriangleStripArray tarray = new VisADTriangleStripArray();
tarray.stripVertexCounts = new int[nheight - 1];
for (int i=0; i<nheight - 1; i++) {
tarray.stripVertexCounts[i] = 2 * nwidth;
}
int len = (nheight - 1) * (2 * nwidth);
tarray.vertexCount = len;
tarray.normals = new float[3 * len];
tarray.coordinates = new float[3 * len];
tarray.colors = new byte[3 * len];
tarray.texCoords = new float[2 * len];
// shuffle normals into tarray.normals, etc
k = 0;
int kt = 0;
int nwidth3 = 3 * nwidth;
int nwidth2 = 2 * nwidth;
for (int i=0; i<nheight-1; i++) {
int m = i * nwidth3;
mt = i * nwidth2;
for (int j=0; j<nwidth; j++) {
tarray.coordinates[k] = coordinates[m];
tarray.coordinates[k+1] = coordinates[m+1];
tarray.coordinates[k+2] = coordinates[m+2];
tarray.coordinates[k+3] = coordinates[m+nwidth3];
tarray.coordinates[k+4] = coordinates[m+nwidth3+1];
tarray.coordinates[k+5] = coordinates[m+nwidth3+2];
tarray.normals[k] = normals[m];
tarray.normals[k+1] = normals[m+1];
tarray.normals[k+2] = normals[m+2];
tarray.normals[k+3] = normals[m+nwidth3];
tarray.normals[k+4] = normals[m+nwidth3+1];
tarray.normals[k+5] = normals[m+nwidth3+2];
tarray.colors[k] = colors[m];
tarray.colors[k+1] = colors[m+1];
tarray.colors[k+2] = colors[m+2];
tarray.colors[k+3] = colors[m+nwidth3];
tarray.colors[k+4] = colors[m+nwidth3+1];
tarray.colors[k+5] = colors[m+nwidth3+2];
tarray.texCoords[kt] = texCoords[mt];
tarray.texCoords[kt+1] = texCoords[mt+1];
tarray.texCoords[kt+2] = texCoords[mt+nwidth2];
tarray.texCoords[kt+3] = texCoords[mt+nwidth2+1];
k += 6;
m += 3;
kt += 4;
mt += 2;
}
}
if (!spatial_all_select) {
tarray = (VisADTriangleStripArray) tarray.removeMissing();
}
tarray = (VisADTriangleStripArray) tarray.adjustLongitude(renderer);
tarray = (VisADTriangleStripArray) tarray.adjustSeam(renderer);
BufferedImage image =
createImage(data_width, data_height, texture_width,
texture_height, color_values);
shadow_api.textureToGroup(group, tarray, image, mode,
constant_alpha, constant_color,
texture_width, texture_height);
// System.out.println("curvedTexture done");
// if (link != null) System.out.println("end texture " + (System.currentTimeMillis() - link.start_time));
return false;
} // end if (curvedTexture)
else if (isTexture3D) {
if (color_values == null) {
// must be color_values array for texture mapping
color_values = new byte[3][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
if (range_select[0] != null && range_select[0].length > 1) {
int len = range_select[0].length;
/* can be misleading because of the way transparency composites
WLH 15 March 2000 */
float alpha =
default_values[display.getDisplayScalarIndex(Display.Alpha)];
if (constant_alpha == constant_alpha) {
alpha = 1.0f - constant_alpha;
}
if (color_values.length < 4) {
byte[][] c = new byte[4][];
c[0] = color_values[0];
c[1] = color_values[1];
c[2] = color_values[2];
c[3] = new byte[len];
for (int i=0; i<len; i++) c[3][i] = floatToByte(alpha);
constant_alpha = Float.NaN;
color_values = c;
}
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel invisible (transparent)
color_values[3][i] = 0;
// WLH 15 March 2000
// make missing pixel black
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
/* WLH 15 March 2000 */
/* WLH 15 March 2000
for (int i=0; i<len; i++) {
if (!range_select[0][i]) {
// make missing pixel black
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
*/
} // end if (range_select[0] != null)
// MEM
VisADQuadArray[] qarray =
{new VisADQuadArray(), new VisADQuadArray(), new VisADQuadArray()};
qarray[0].vertexCount = coordinatesX.length / 3;
qarray[0].coordinates = coordinatesX;
qarray[0].texCoords = texCoordsX;
qarray[0].colors = colorsX;
qarray[0].normals = normalsX;
qarray[1].vertexCount = coordinatesY.length / 3;
qarray[1].coordinates = coordinatesY;
qarray[1].texCoords = texCoordsY;
qarray[1].colors = colorsY;
qarray[1].normals = normalsY;
qarray[2].vertexCount = coordinatesZ.length / 3;
qarray[2].coordinates = coordinatesZ;
qarray[2].texCoords = texCoordsZ;
qarray[2].colors = colorsZ;
qarray[2].normals = normalsZ;
// WLH 3 June 99 - until Texture3D works on NT (etc)
BufferedImage[][] images = new BufferedImage[3][];
for (int i=0; i<3; i++) {
images[i] = createImages(i, data_width, data_height, data_depth,
texture_width, texture_height, texture_depth,
color_values);
}
BufferedImage[] imagesX = null;
BufferedImage[] imagesY = null;
BufferedImage[] imagesZ = null;
VisADQuadArray qarrayX = null;
VisADQuadArray qarrayY = null;
VisADQuadArray qarrayZ = null;
for (int i=0; i<3; i++) {
if (volume_tuple_index[i] == 0) {
qarrayX = qarray[i];
imagesX = images[i];
}
else if (volume_tuple_index[i] == 1) {
qarrayY = qarray[i];
imagesY = images[i];
}
else if (volume_tuple_index[i] == 2) {
qarrayZ = qarray[i];
imagesZ = images[i];
}
}
VisADQuadArray qarrayXrev = reverse(qarrayX);
VisADQuadArray qarrayYrev = reverse(qarrayY);
VisADQuadArray qarrayZrev = reverse(qarrayZ);
/* WLH 3 June 99 - comment this out until Texture3D works on NT (etc)
BufferedImage[] images =
createImages(2, data_width, data_height, data_depth,
texture_width, texture_height, texture_depth,
color_values);
shadow_api.texture3DToGroup(group, qarrayX, qarrayY, qarrayZ,
qarrayXrev, qarrayYrev, qarrayZrev,
images, mode, constant_alpha,
constant_color, texture_width,
texture_height, texture_depth, renderer);
*/
shadow_api.textureStackToGroup(group, qarrayX, qarrayY, qarrayZ,
qarrayXrev, qarrayYrev, qarrayZrev,
imagesX, imagesY, imagesZ,
mode, constant_alpha, constant_color,
texture_width, texture_height, texture_depth,
renderer);
// System.out.println("isTexture3D done");
return false;
} // end if (isTexture3D)
else if (pointMode || spatial_set == null ||
spatialManifoldDimension == 0 ||
spatialManifoldDimension == 3) {
if (range_select[0] != null) {
int len = range_select[0].length;
if (len == 1 || spatial_values[0].length == 1) {
return false;
}
for (int j=0; j<len; j++) {
// range_select[0][j] is either 0.0f or Float.NaN -
// setting to Float.NaN will move points off the screen
if (!range_select[0][j]) {
spatial_values[0][j] = Float.NaN;
}
}
/* CTR: 13 Oct 1998 - call new makePointGeometry signature */
array = makePointGeometry(spatial_values, color_values, true);
// System.out.println("makePointGeometry for some missing");
}
else {
array = makePointGeometry(spatial_values, color_values);
// System.out.println("makePointGeometry for pointMode");
}
}
else if (spatialManifoldDimension == 1) {
if (range_select[0] != null) {
// WLH 27 March 2000
if (mode.getMissingTransparent()) {
spatial_set.cram_missing(range_select[0]);
spatial_all_select = false;
}
else {
if (color_values == null) {
color_values = new byte[4][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
for (int i=0; i<domain_length; i++) {
if (!range_select[0][i]) {
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
/* WLH 6 May 99
color_values =
selectToColor(range_select, color_values, constant_color,
constant_alpha, missing_transparent);
constant_alpha = Float.NaN;
*/
}
array = spatial_set.make1DGeometry(color_values);
if (!spatial_all_select) array = array.removeMissing();
array = array.adjustLongitude(renderer);
array = array.adjustSeam(renderer);
// System.out.println("make1DGeometry");
}
else if (spatialManifoldDimension == 2) {
if (range_select[0] != null) {
// WLH 27 March 2000
if (mode.getMissingTransparent()) {
spatial_set.cram_missing(range_select[0]);
spatial_all_select = false;
}
else {
if (color_values == null) {
color_values = new byte[4][domain_length];
for (int i=0; i<domain_length; i++) {
color_values[0][i] = floatToByte(constant_color[0]);
color_values[1][i] = floatToByte(constant_color[1]);
color_values[2][i] = floatToByte(constant_color[2]);
}
}
for (int i=0; i<domain_length; i++) {
if (!range_select[0][i]) {
color_values[0][i] = 0;
color_values[1][i] = 0;
color_values[2][i] = 0;
}
}
}
/* WLH 6 May 99
color_values =
selectToColor(range_select, color_values, constant_color,
constant_alpha, missing_transparent);
constant_alpha = Float.NaN;
*/
}
array = spatial_set.make2DGeometry(color_values, indexed);
if (!spatial_all_select) array = array.removeMissing();
array = array.adjustLongitude(renderer);
array = array.adjustSeam(renderer);
// System.out.println("make2DGeometry vertexCount = " +
// array.vertexCount);
}
else {
throw new DisplayException("bad spatialManifoldDimension: " +
"ShadowFunctionOrSetType.doTransform");
}
if (array != null && array.vertexCount > 0) {
shadow_api.addToGroup(group, array, mode,
constant_alpha, constant_color);
// System.out.println("array.makeGeometry");
// FREE
array = null;
/* WLH 25 June 2000
if (renderer.getIsDirectManipulation()) {
renderer.setSpatialValues(spatial_values);
}
*/
}
} // end if (!anyContourCreated && !anyFlowCreated &&
// !anyTextCreated && !anyShapeCreated)
// WLH 25 June 2000
if (renderer.getIsDirectManipulation()) {
renderer.setSpatialValues(spatial_values);
}
// if (link != null) System.out.println("end doTransform " + (System.currentTimeMillis() - link.start_time));
return false;
} // end if (LevelOfDifficulty == SIMPLE_FIELD)
else if (LevelOfDifficulty == SIMPLE_ANIMATE_FIELD) {
Control control = null;
Object swit = null;
int index = -1;
if (DomainComponents.length == 1) {
RealType real = (RealType) DomainComponents[0].getType();
for (int i=0; i<valueArrayLength; i++) {
ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]);
float[] values = display_values[i];
if (values != null && real.equals(map.getScalar())) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType dreal =
display.getDisplayScalar(displayScalarIndex);
if (dreal.equals(Display.Animation) ||
dreal.equals(Display.SelectValue)) {
swit = shadow_api.makeSwitch();
index = i;
control = map.getControl();
break;
}
} // end if (values != null && && real.equals(map.getScalar()))
} // end for (int i=0; i<valueArrayLength; i++)
} // end if (DomainComponents.length == 1)
if (control == null) {
throw new DisplayException("bad SIMPLE_ANIMATE_FIELD: " +
"ShadowFunctionOrSetType.doTransform");
}
for (int i=0; i<domain_length; i++) {
Object branch = shadow_api.makeBranch();
if (range_select[0] == null || range_select[0].length == 1 ||
range_select[0][i]) {
VisADGeometryArray array = null;
float[][] sp = new float[3][1];
if (spatial_values[0].length > 1) {
sp[0][0] = spatial_values[0][i];
sp[1][0] = spatial_values[1][i];
sp[2][0] = spatial_values[2][i];
}
else {
sp[0][0] = spatial_values[0][0];
sp[1][0] = spatial_values[1][0];
sp[2][0] = spatial_values[2][0];
}
byte[][] co = new byte[3][1];
if (color_values == null) {
co[0][0] = floatToByte(constant_color[0]);
co[1][0] = floatToByte(constant_color[1]);
co[2][0] = floatToByte(constant_color[2]);
}
else if (color_values[0].length > 1) {
co[0][0] = color_values[0][i];
co[1][0] = color_values[1][i];
co[2][0] = color_values[2][i];
}
else {
co[0][0] = color_values[0][0];
co[1][0] = color_values[1][0];
co[2][0] = color_values[2][0];
}
boolean[][] ra = {{true}};
boolean anyShapeCreated = false;
VisADGeometryArray[] arrays =
shadow_api.assembleShape(display_values, valueArrayLength,
valueToMap, MapVector, valueToScalar, display,
default_values, inherited_values,
sp, co, ra, i, shadow_api);
if (arrays != null) {
for (int j=0; j<arrays.length; j++) {
array = arrays[j];
shadow_api.addToGroup(branch, array, mode,
constant_alpha, constant_color);
array = null;
/* why null constant_alpha?
appearance = makeAppearance(mode, null, constant_color, geometry);
*/
}
anyShapeCreated = true;
arrays = null;
}
boolean anyTextCreated = false;
if (anyText && text_values != null && text_control != null) {
String[] te = new String[1];
if (text_values.length > 1) {
te[0] = text_values[i];
}
else {
te[0] = text_values[0];
}
array = shadow_api.makeText(te, text_control, spatial_values, co, ra);
if (array != null) {
shadow_api.addTextToGroup(branch, array, mode,
constant_alpha, constant_color);
array = null;
anyTextCreated = true;
}
}
boolean anyFlowCreated = false;
if (anyFlow) {
if (flow1_values != null && flow1_values[0] != null) {
// try Flow1
float[][] f1 = new float[3][1];
if (flow1_values[0].length > 1) {
f1[0][0] = flow1_values[0][i];
f1[1][0] = flow1_values[1][i];
f1[2][0] = flow1_values[2][i];
}
else {
f1[0][0] = flow1_values[0][0];
f1[1][0] = flow1_values[1][0];
f1[2][0] = flow1_values[2][0];
}
arrays = shadow_api.makeFlow(0, f1, flowScale[0], sp, co, ra);
if (arrays != null) {
for (int j=0; j<arrays.length; j++) {
if (arrays[j] != null) {
shadow_api.addToGroup(branch, arrays[j], mode,
constant_alpha, constant_color);
arrays[j] = null;
}
}
}
anyFlowCreated = true;
}
// try Flow2
if (flow2_values != null && flow2_values[0] != null) {
float[][] f2 = new float[3][1];
if (flow2_values[0].length > 1) {
f2[0][0] = flow2_values[0][i];
f2[1][0] = flow2_values[1][i];
f2[2][0] = flow2_values[2][i];
}
else {
f2[0][0] = flow2_values[0][0];
f2[1][0] = flow2_values[1][0];
f2[2][0] = flow2_values[2][0];
}
arrays = shadow_api.makeFlow(1, f2, flowScale[1], sp, co, ra);
if (arrays != null) {
for (int j=0; j<arrays.length; j++) {
if (arrays[j] != null) {
shadow_api.addToGroup(branch, arrays[j], mode,
constant_alpha, constant_color);
arrays[j] = null;
}
}
}
anyFlowCreated = true;
}
}
if (!anyShapeCreated && !anyTextCreated &&
!anyFlowCreated) {
array = new VisADPointArray();
array.vertexCount = 1;
coordinates = new float[3];
coordinates[0] = sp[0][0];
coordinates[1] = sp[1][0];
coordinates[2] = sp[2][0];
array.coordinates = coordinates;
if (color_values != null) {
colors = new byte[3];
colors[0] = co[0][0];
colors[1] = co[1][0];
colors[2] = co[2][0];
array.colors = colors;
}
shadow_api.addToGroup(branch, array, mode,
constant_alpha, constant_color);
array = null;
// System.out.println("addChild " + i + " of " + domain_length);
}
}
else { // if (range_select[0][i])
/* WLH 18 Aug 98
empty BranchGroup or Shape3D may cause NullPointerException
from Shape3DRetained.setLive
// add null BranchGroup as child to maintain order
branch.addChild(new Shape3D());
*/
// System.out.println("addChild " + i + " of " + domain_length +
// " MISSING");
}
shadow_api.addToSwitch(swit, branch);
} // end for (int i=0; i<domain_length; i++)
shadow_api.addSwitch(group, swit, control, domain_set, renderer);
return false;
} // end if (LevelOfDifficulty == SIMPLE_ANIMATE_FIELD)
else { // must be LevelOfDifficulty == LEGAL
// add values to value_array according to SelectedMapVector-s
// of RealType-s in Domain (including Reference) and Range
//
// accumulate Vector of value_array-s at this ShadowType,
// to be rendered in a post-process to scanning data
//
// ** OR JUST EACH FIELD INDEPENDENTLY **
//
/*
return true;
*/
throw new UnimplementedException("terminal LEGAL unimplemented: " +
"ShadowFunctionOrSetType.doTransform");
}
}
else { // !isTerminal
// domain_values and range_values, as well as their References,
// already converted to default Units and added to display_values
// add values to value_array according to SelectedMapVector-s
// of RealType-s in Domain (including Reference), and
// recursively call doTransform on Range values
//
// TO_DO
// SelectRange (use boolean[][] range_select from assembleSelect),
// SelectValue, Animation
// DataRenderer.isTransformControl temporary hack:
// SelectRange.isTransform,
// !SelectValue.isTransform, !Animation.isTransform
//
// may need to split ShadowType.checkAnimationOrValue
// Display.Animation has no range, is single
// Display.Value has no range, is not single
//
// see Set.merge1DSets
boolean post = false;
Control control = null;
Object swit = null;
int index = -1;
if (DomainComponents.length == 1) {
RealType real = (RealType) DomainComponents[0].getType();
for (int i=0; i<valueArrayLength; i++) {
ScalarMap map = (ScalarMap) MapVector.elementAt(valueToMap[i]);
float[] values = display_values[i];
if (values != null && real.equals(map.getScalar())) {
int displayScalarIndex = valueToScalar[i];
DisplayRealType dreal =
display.getDisplayScalar(displayScalarIndex);
if (dreal.equals(Display.Animation) ||
dreal.equals(Display.SelectValue)) {
swit = shadow_api.makeSwitch();
index = i;
control = map.getControl();
break;
}
} // end if (values != null && real.equals(map.getScalar()))
} // end for (int i=0; i<valueArrayLength; i++)
} // end if (DomainComponents.length == 1)
if (control != null) {
shadow_api.addSwitch(group, swit, control, domain_set, renderer);
/*
group.addChild(swit);
control.addPair(swit, domain_set, renderer);
*/
}
float[] range_value_array = new float[valueArrayLength];
for (int j=0; j<display.getValueArrayLength(); j++) {
range_value_array[j] = Float.NaN;
}
for (int i=0; i<domain_length; i++) {
if (range_select[0] == null || range_select[0].length == 1 ||
range_select[0][i]) {
if (text_values != null && text_control != null) {
shadow_api.setText(text_values[i], text_control);
}
else {
shadow_api.setText(null, null);
}
for (int j=0; j<valueArrayLength; j++) {
if (display_values[j] != null) {
if (display_values[j].length == 1) {
range_value_array[j] = display_values[j][0];
}
else {
range_value_array[j] = display_values[j][i];
}
}
}
// push lat_index and lon_index for flow navigation
int[] lat_lon_indices = renderer.getLatLonIndices();
if (control != null) {
Object branch = shadow_api.makeBranch();
post |= shadow_api.recurseRange(branch, ((Field) data).getSample(i),
range_value_array, default_values,
renderer);
shadow_api.addToSwitch(swit, branch);
// System.out.println("addChild " + i + " of " + domain_length);
}
else {
Object branch = shadow_api.makeBranch();
post |= shadow_api.recurseRange(branch, ((Field) data).getSample(i),
range_value_array, default_values,
renderer);
shadow_api.addToGroup(group, branch);
}
// pop lat_index and lon_index for flow navigation
renderer.setLatLonIndices(lat_lon_indices);
}
else { // if (!range_select[0][i])
if (control != null) {
// add null BranchGroup as child to maintain order
Object branch = shadow_api.makeBranch();
shadow_api.addToSwitch(swit, branch);
// System.out.println("addChild " + i + " of " + domain_length +
// " MISSING");
}
}
}
/* why later than addPair & addChild(swit) ??
if (control != null) {
// initialize swit child selection
control.init();
}
*/
return post;
/*
throw new UnimplementedException("ShadowFunctionOrSetType.doTransform: " +
"not terminal");
*/
} // end if (!isTerminal)
}
public byte[][] selectToColor(boolean[][] range_select,
byte[][] color_values, float[] constant_color,
float constant_alpha, byte missing_transparent) {
int len = range_select[0].length;
byte[][] cv = new byte[4][];
if (color_values != null) {
for (int i=0; i<color_values.length; i++) {
cv[i] = color_values[i];
}
}
color_values = cv;
for (int i=0; i<4; i++) {
byte miss = (i < 3) ? 0 : missing_transparent;
if (color_values == null || color_values[i] == null) {
color_values[i] = new byte[len];
if (i < 3 && constant_color != null) {
byte c = floatToByte(constant_color[i]);
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? c : miss;
}
}
else if (i == 3 && constant_alpha == constant_alpha) {
if (constant_alpha < 0.99f) miss = 0;
byte c = floatToByte(constant_alpha);
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? c : miss;
}
}
else {
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? (byte) -1 : miss;
}
}
}
else if (color_values[i].length == 1) {
byte c = color_values[i][0];
if (i == 3 && c != -1) miss = 0;
color_values[i] = new byte[len];
for (int j=0; j<len; j++) {
color_values[i][j] = range_select[0][j] ? c : miss;
}
}
else {
if (i == 3) miss = 0;
for (int j=0; j<len; j++) {
if (!range_select[0][j]) color_values[i][j] = miss;
}
}
}
return color_values;
}
public BufferedImage createImage(int data_width, int data_height,
int texture_width, int texture_height,
byte[][] color_values) throws VisADException {
BufferedImage image = null;
if (color_values.length > 3) {
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
image = new BufferedImage(colorModel, raster, false, null);
int[] intData = ((DataBufferInt)db).getData();
int k = 0;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = (color_values[3][k] < 0) ? color_values[3][k] + 256 :
color_values[3][k];
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
k++;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
}
else { // (color_values.length == 3)
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
// WLH 2 Nov 2000
DataBuffer db = raster.getDataBuffer();
int[] intData = null;
if (db instanceof DataBufferInt) {
intData = ((DataBufferInt)db).getData();
image = new BufferedImage(colorModel, raster, false, null);
}
else {
// System.out.println("byteData 3 1");
image = new BufferedImage(texture_width, texture_height,
BufferedImage.TYPE_INT_RGB);
intData = new int[texture_width * texture_height];
/*
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
int[] nBits = {8, 8, 8};
colorModel =
new ComponentColorModel(cs, nBits, false, false, Transparency.OPAQUE, 0);
raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
*/
}
// image = new BufferedImage(colorModel, raster, false, null);
// int[] intData = ((DataBufferInt)raster.getDataBuffer()).getData();
int k = 0;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = 255;
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
k++;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
// WLH 2 Nov 2000
if (!(db instanceof DataBufferInt)) {
// System.out.println("byteData 3 2");
image.setRGB(0, 0, texture_width, texture_height, intData, 0, texture_width);
/*
byte[] byteData = ((DataBufferByte)raster.getDataBuffer()).getData();
k = 0;
for (int i=0; i<intData.length; i++) {
byteData[k++] = (byte) (intData[i] & 255);
byteData[k++] = (byte) ((intData[i] >> 8) & 255);
byteData[k++] = (byte) ((intData[i] >> 16) & 255);
}
*/
/* WLH 4 Nov 2000, from com.sun.j3d.utils.geometry.Text2D
// For now, jdk 1.2 only handles ARGB format, not the RGBA we want
BufferedImage bImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
Graphics offscreenGraphics = bImage.createGraphics();
// First, erase the background to the text panel - set alpha to 0
Color myFill = new Color(0f, 0f, 0f, 0f);
offscreenGraphics.setColor(myFill);
offscreenGraphics.fillRect(0, 0, width, height);
// Next, set desired text properties (font, color) and draw String
offscreenGraphics.setFont(font);
Color myTextColor = new Color(color.x, color.y, color.z, 1f);
offscreenGraphics.setColor(myTextColor);
offscreenGraphics.drawString(text, 0, height - descent);
*/
} // end if (!(db instanceof DataBufferInt))
} // end if (color_values.length == 3)
return image;
}
public BufferedImage[] createImages(int axis, int data_width_in,
int data_height_in, int data_depth_in, int texture_width_in,
int texture_height_in, int texture_depth_in, byte[][] color_values)
throws VisADException {
int data_width, data_height, data_depth;
int texture_width, texture_height, texture_depth;
int kwidth, kheight, kdepth;
if (axis == 2) {
kwidth = 1;
kheight = data_width_in;
kdepth = data_width_in * data_height_in;
data_width = data_width_in;
data_height = data_height_in;
data_depth = data_depth_in;
texture_width = texture_width_in;
texture_height = texture_height_in;
texture_depth = texture_depth_in;
}
else if (axis == 1) {
kwidth = 1;
kdepth = data_width_in;
kheight = data_width_in * data_height_in;
data_width = data_width_in;
data_depth = data_height_in;
data_height = data_depth_in;
texture_width = texture_width_in;
texture_depth = texture_height_in;
texture_height = texture_depth_in;
}
else if (axis == 0) {
kdepth = 1;
kwidth = data_width_in;
kheight = data_width_in * data_height_in;
data_depth = data_width_in;
data_width = data_height_in;
data_height = data_depth_in;
texture_depth = texture_width_in;
texture_width = texture_height_in;
texture_height = texture_depth_in;
}
else {
return null;
}
BufferedImage[] images = new BufferedImage[texture_depth];
for (int d=0; d<data_depth; d++) {
if (color_values.length > 3) {
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
images[d] = new BufferedImage(colorModel, raster, false, null);
/* WLH 23 Feb 2000
if (axis == 1) {
images[(data_depth-1) - d] =
new BufferedImage(colorModel, raster, false, null);
}
else {
images[d] = new BufferedImage(colorModel, raster, false, null);
}
*/
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
int[] intData = ((DataBufferInt)db).getData();
// int k = d * data_width * data_height;
int kk = d * kdepth;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
int k = kk + j * kheight;
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = (color_values[3][k] < 0) ? color_values[3][k] + 256 :
color_values[3][k];
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
// k++;
k += kwidth;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
}
else { // (color_values.length == 3)
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
images[d] = new BufferedImage(colorModel, raster, false, null);
/* WLH 23 Feb 2000
if (axis == 1) {
images[(data_depth-1) - d] =
new BufferedImage(colorModel, raster, false, null);
}
else {
images[d] = new BufferedImage(colorModel, raster, false, null);
}
*/
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
int[] intData = ((DataBufferInt)db).getData();
// int k = d * data_width * data_height;
int kk = d * kdepth;
int m = 0;
int r, g, b, a;
for (int j=0; j<data_height; j++) {
int k = kk + j * kheight;
for (int i=0; i<data_width; i++) {
r = (color_values[0][k] < 0) ? color_values[0][k] + 256 :
color_values[0][k];
g = (color_values[1][k] < 0) ? color_values[1][k] + 256 :
color_values[1][k];
b = (color_values[2][k] < 0) ? color_values[2][k] + 256 :
color_values[2][k];
a = 255;
intData[m++] = ((a << 24) | (r << 16) | (g << 8) | b);
// k++;
k += kwidth;
}
for (int i=data_width; i<texture_width; i++) {
intData[m++] = 0;
}
}
for (int j=data_height; j<texture_height; j++) {
for (int i=0; i<texture_width; i++) {
intData[m++] = 0;
}
}
} // end if (color_values.length == 3)
} // end for (int d=0; d<data_depth; d++)
for (int d=data_depth; d<texture_depth; d++) {
ColorModel colorModel = ColorModel.getRGBdefault();
WritableRaster raster =
colorModel.createCompatibleWritableRaster(texture_width, texture_height);
images[d] = new BufferedImage(colorModel, raster, false, null);
DataBuffer db = raster.getDataBuffer();
if (!(db instanceof DataBufferInt)) {
throw new UnimplementedException("getRGBdefault isn't DataBufferInt");
}
int[] intData = ((DataBufferInt)db).getData();
for (int i=0; i<texture_width*texture_height; i++) {
intData[i] = 0;
}
}
return images;
}
public VisADQuadArray reverse(VisADQuadArray array) {
VisADQuadArray qarray = new VisADQuadArray();
qarray.coordinates = new float[array.coordinates.length];
qarray.texCoords = new float[array.texCoords.length];
qarray.colors = new byte[array.colors.length];
qarray.normals = new float[array.normals.length];
int count = array.vertexCount;
qarray.vertexCount = count;
int color_length = array.colors.length / count;
int tex_length = array.texCoords.length / count;
int i3 = 0;
int k3 = 3 * (count - 1);
int ic = 0;
int kc = color_length * (count - 1);
int it = 0;
int kt = tex_length * (count - 1);
for (int i=0; i<count; i++) {
qarray.coordinates[i3] = array.coordinates[k3];
qarray.coordinates[i3 + 1] = array.coordinates[k3 + 1];
qarray.coordinates[i3 + 2] = array.coordinates[k3 + 2];
qarray.texCoords[it] = array.texCoords[kt];
qarray.texCoords[it + 1] = array.texCoords[kt + 1];
if (tex_length == 3) qarray.texCoords[it + 2] = array.texCoords[kt + 2];
qarray.normals[i3] = array.normals[k3];
qarray.normals[i3 + 1] = array.normals[k3 + 1];
qarray.normals[i3 + 2] = array.normals[k3 + 2];
qarray.colors[ic] = array.colors[kc];
qarray.colors[ic + 1] = array.colors[kc + 1];
qarray.colors[ic + 2] = array.colors[kc + 2];
if (color_length == 4) qarray.colors[ic + 3] = array.colors[kc + 3];
i3 += 3;
k3 -= 3;
ic += color_length;
kc -= color_length;
it += tex_length;
kt -= tex_length;
}
return qarray;
}
}
|
diff --git a/src/main/java/net/aufdemrand/denizen/objects/dPlayer.java b/src/main/java/net/aufdemrand/denizen/objects/dPlayer.java
index 13ce7a328..b579c46c6 100644
--- a/src/main/java/net/aufdemrand/denizen/objects/dPlayer.java
+++ b/src/main/java/net/aufdemrand/denizen/objects/dPlayer.java
@@ -1,1016 +1,1017 @@
package net.aufdemrand.denizen.objects;
import net.aufdemrand.denizen.flags.FlagManager;
import net.aufdemrand.denizen.tags.Attribute;
import net.aufdemrand.denizen.tags.core.PlayerTags;
import net.aufdemrand.denizen.utilities.DenizenAPI;
import net.aufdemrand.denizen.utilities.debugging.dB;
import net.aufdemrand.denizen.utilities.depends.Depends;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryType;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
public class dPlayer implements dObject {
/////////////////////
// STATIC METHODS
/////////////////
static Map<String, dPlayer> players = new HashMap<String, dPlayer>();
public static dPlayer mirrorBukkitPlayer(OfflinePlayer player) {
if (player == null) return null;
if (players.containsKey(player.getName())) return players.get(player.getName());
else return new dPlayer(player);
}
/////////////////////
// OBJECT FETCHER
/////////////////
@ObjectFetcher("p")
public static dPlayer valueOf(String string) {
if (string == null) return null;
string = string.replace("p@", "");
////////
// Match player name
OfflinePlayer returnable = null;
for (OfflinePlayer player : Bukkit.getOfflinePlayers())
if (player.getName().equalsIgnoreCase(string)) {
returnable = player;
break;
}
if (returnable != null) {
if (players.containsKey(returnable.getName())) return players.get(returnable.getName());
else return new dPlayer(returnable);
}
else dB.echoError("Invalid Player! '" + string
+ "' could not be found. Has the player logged off?");
return null;
}
public static boolean matches(String arg) {
if (arg == null) return false;
arg = arg.replace("p@", "");
OfflinePlayer returnable = null;
for (OfflinePlayer player : Bukkit.getOfflinePlayers())
if (player.getName().equalsIgnoreCase(arg)) {
returnable = player;
break;
}
return returnable != null;
}
/////////////////////
// STATIC CONSTRUCTORS
/////////////////
public dPlayer(OfflinePlayer player) {
if (player == null) return;
this.player_name = player.getName();
// Keep in a map to avoid multiple instances of a dPlayer per player.
players.put(this.player_name, this);
}
/////////////////////
// INSTANCE FIELDS/METHODS
/////////////////
String player_name = null;
public boolean isValid() {
if (player_name == null) return false;
return (!(getPlayerEntity() == null && getOfflinePlayer() == null));
}
public Player getPlayerEntity() {
if (player_name == null) return null;
return Bukkit.getPlayer(player_name);
}
public OfflinePlayer getOfflinePlayer() {
if (player_name == null) return null;
return Bukkit.getOfflinePlayer(player_name);
}
public dEntity getDenizenEntity() {
return new dEntity(getPlayerEntity());
}
public dNPC getSelectedNPC() {
if (getPlayerEntity().hasMetadata("selected"))
return dNPC.valueOf(getPlayerEntity().getMetadata("selected").get(0).asString());
else return null;
}
public String getName() {
return player_name;
}
public dLocation getLocation() {
if (isOnline()) return new dLocation(getPlayerEntity().getLocation());
else return null;
}
public dLocation getEyeLocation() {
if (isOnline()) return new dLocation(getPlayerEntity().getEyeLocation());
else return null;
}
public World getWorld() {
if (isOnline()) return getPlayerEntity().getWorld();
else return null;
}
public boolean isOnline() {
if (player_name == null) return false;
return Bukkit.getPlayer(player_name) != null;
}
/////////////////////
// dObject Methods
/////////////////
private String prefix = "Player";
@Override
public String getPrefix() {
return prefix;
}
@Override
public dPlayer setPrefix(String prefix) {
this.prefix = prefix;
return this;
}
@Override
public String debug() {
return (prefix + "='<A>" + identify() + "<G>' ");
}
@Override
public boolean isUnique() {
return true;
}
@Override
public String getObjectType() {
return "Player";
}
@Override
public String identify() {
return "p@" + player_name;
}
@Override
public String toString() {
return identify();
}
@Override
public String getAttribute(Attribute attribute) {
if (attribute == null) return "null";
if (player_name == null) return "null";
/////////////////////
// OFFLINE ATTRIBUTES
/////////////////
/////////////////////
// DEBUG ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Boolean)
// @description
// Debugs the player in the log and returns true.
// -->
if (attribute.startsWith("debug.log")) {
dB.log(debug());
return new Element(Boolean.TRUE.toString())
.getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]_color>
// @returns Element
// @description
// Returns the player's debug with no color.
// -->
if (attribute.startsWith("debug.no_color")) {
return new Element(ChatColor.stripColor(debug()))
.getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the player's debug.
// -->
if (attribute.startsWith("debug")) {
return new Element(debug())
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the dObject's prefix.
// -->
if (attribute.startsWith("prefix"))
return new Element(prefix)
.getAttribute(attribute.fulfill(1));
/////////////////////
// DENIZEN ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]_history_list>
// @returns dList
// @description
// Returns a list of the last 10 things the player has said, less
// if the player hasn't said all that much.
// -->
if (attribute.startsWith("chat_history_list"))
return new dList(PlayerTags.playerChatHistory.get(player_name))
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_history>
// @returns Element
// @description
// returns the last thing the player said.
// -->
if (attribute.startsWith("chat_history")) {
int x = 1;
if (attribute.hasContext(1) && aH.matchesInteger(attribute.getContext(1)))
x = attribute.getIntContext(1);
// No playerchathistory? Return null.
if (!PlayerTags.playerChatHistory.containsKey(player_name)) return "null";
else return new Element(PlayerTags.playerChatHistory.get(player_name).get(x - 1))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected][flag_name]>
// @returns Flag dList
// @description
// returns 'flag dList' of the player's flag_name specified.
// -->
if (attribute.startsWith("flag")) {
String flag_name;
if (attribute.hasContext(1)) flag_name = attribute.getContext(1);
else return "null";
attribute.fulfill(1);
if (attribute.startsWith("is_expired")
|| attribute.startsWith("isexpired"))
return new Element(!FlagManager.playerHasFlag(this, flag_name))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("size") && !FlagManager.playerHasFlag(this, flag_name))
return new Element(0).getAttribute(attribute.fulfill(1));
if (FlagManager.playerHasFlag(this, flag_name))
return new dList(DenizenAPI.getCurrentInstance().flagManager()
.getPlayerFlag(getName(), flag_name))
.getAttribute(attribute);
else return "null";
}
/////////////////////
// ECONOMY ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns Element(number)
// @description
// returns the amount of money the player has with the registered
// Economy system.
// -->
if (attribute.startsWith("money")) {
if(Depends.economy != null) {
// <--[tag]
// @attribute <[email protected]_singular>
// @returns Element
// @description
// returns the 'singular currency' string, if supported by the
// registered Economy system.
// -->
if (attribute.startsWith("money.currency_singular"))
return new Element(Depends.economy.currencyNameSingular())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the 'currency' string, if supported by the
// registered Economy system.
// -->
if (attribute.startsWith("money.currency"))
return new Element(Depends.economy.currencyNamePlural())
.getAttribute(attribute.fulfill(2));
return new Element(Depends.economy.getBalance(player_name))
.getAttribute(attribute.fulfill(1));
} else {
dB.echoError("No economy loaded! Have you installed Vault and a compatible economy plugin?");
return null;
}
}
/////////////////////
// ENTITY LIST ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns dList(dPlayer)
// @description
// Returns all players that have ever played on the server, online or not.
// **NOTE: This will only work if there is a player attached to the current script.
// If you need it anywhere else, use <server.list_players>**
// -->
if (attribute.startsWith("list")) {
List<String> players = new ArrayList<String>();
// <--[tag]
// @attribute <[email protected]>
// @returns dList(dPlayer)
// @description
// Returns all online players.
// **NOTE: This will only work if there is a player attached to the current script.
// If you need it anywhere else, use <server.list_online_players>**
// -->
if (attribute.startsWith("list.online")) {
for(Player player : Bukkit.getOnlinePlayers())
players.add(player.getName());
return new dList(players).getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]>
// @returns dList(dPlayer)
// @description
// Returns all offline players.
// **NOTE: This will only work if there is a player attached to the current script.
// If you need it anywhere else, use <server.list_offline_players>**
// -->
else if (attribute.startsWith("list.offline")) {
for(OfflinePlayer player : Bukkit.getOfflinePlayers()) {
if (!Bukkit.getOnlinePlayers().toString().contains(player.getName()))
players.add(player.getName());
}
return new dList(players).getAttribute(attribute.fulfill(2));
}
else {
for(OfflinePlayer player : Bukkit.getOfflinePlayers())
players.add(player.getName());
return new dList(players).getAttribute(attribute.fulfill(1));
}
}
/////////////////////
// IDENTIFICATION ATTRIBUTES
/////////////////
if (attribute.startsWith("name") && !isOnline())
// This can be parsed later with more detail if the player is online, so only check for offline.
return new Element(player_name).getAttribute(attribute.fulfill(1));
/////////////////////
// LOCATION ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]_spawn>
// @returns dLocation
// @description
// Returns a dLocation of the player's bed spawn location, 'null' if
// it doesn't exist.
// -->
if (attribute.startsWith("bed_spawn"))
return new dLocation(getOfflinePlayer().getBedSpawnLocation())
.getAttribute(attribute.fulfill(2));
/////////////////////
// STATE ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]_played>
// @returns Element(number)
// @description
// returns the 'System.currentTimeMillis()' of when the player
// first logged on. Will return '0' if player has never played.
// -->
if (attribute.startsWith("first_played"))
return new Element(getOfflinePlayer().getFirstPlayed())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_played_before>
// @returns Element(boolean)
// @description
// returns true if the player has played before
// -->
if (attribute.startsWith("has_played_before"))
return new Element(getOfflinePlayer().hasPlayedBefore())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_banned>
// @returns Element(boolean)
// @description
// returns true if the player is banned
// -->
if (attribute.startsWith("is_banned"))
return new Element(getOfflinePlayer().isBanned())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_online>
// @returns Element(boolean)
// @description
// returns true if the player is currently online
// -->
if (attribute.startsWith("is_online"))
return new Element(isOnline()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_op>
// @returns Element(boolean)
// @description
// returns true if the player has 'op status'
// -->
if (attribute.startsWith("is_op"))
return new Element(getOfflinePlayer().isOp())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_whitelisted>
// @returns Element(boolean)
// @description
// returns true if the player is whitelisted
// -->
if (attribute.startsWith("is_whitelisted"))
return new Element(getOfflinePlayer().isWhitelisted())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_played>
// @returns Element(number)
// @description
// returns the 'System.currentTimeMillis()' of when the player
// was last seen. Will return '0' if player has never played.
// -->
if (attribute.startsWith("last_played"))
return new Element(getOfflinePlayer().getLastPlayed())
.getAttribute(attribute.fulfill(1));
/////////////////////
// ONLINE ATTRIBUTES
/////////////////
// Player is required to be online after this point...
+ if (!isOnline()) return new Element(identify()).getAttribute(attribute);
/////////////////////
// CITIZENS ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]_npc>
// @returns dNPC
// @description
// returns the dNPC that the player currently has selected with
// '/npc sel', null if no player selected.
// -->
if (attribute.startsWith("selected_npc")) {
if (getPlayerEntity().hasMetadata("selected"))
return dNPC.valueOf(getPlayerEntity().getMetadata("selected").get(0).asString())
.getAttribute(attribute.fulfill(1));
else return "null";
}
/////////////////////
// CONVERSION ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns dEntity
// @description
// returns the dEntity object of the player
// -->
if (attribute.startsWith("entity"))
return new dEntity(getPlayerEntity())
.getAttribute(attribute.fulfill(1));
/////////////////////
// IDENTIFICATION ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the player's IP address.
// -->
if (attribute.startsWith("ip") ||
attribute.startsWith("host_name"))
return new Element(getPlayerEntity().getAddress().getHostName())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the 'display name' of the player, which may contain
// prefixes and suffixes/color, etc.
// -->
if (attribute.startsWith("name.display"))
return new Element(getPlayerEntity().getDisplayName())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the name of the player as shown in the 'player list'.
// -->
if (attribute.startsWith("name.list"))
return new Element(getPlayerEntity().getPlayerListName())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the name of the player.
// -->
if (attribute.startsWith("name"))
return new Element(player_name).getAttribute(attribute.fulfill(1));
/////////////////////
// INVENTORY ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns dItem
// @description
// returns the item the player is wearing as boots, or null
// if none.
// -->
if (attribute.startsWith("equipment.boots"))
if (getPlayerEntity().getInventory().getBoots() != null)
return new dItem(getPlayerEntity().getInventory().getBoots())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dItem
// @description
// returns the item the player is wearing as a chestplate, or null
// if none.
// -->
if (attribute.startsWith("equipment.chestplate"))
if (getPlayerEntity().getInventory().getChestplate() != null)
return new dItem(getPlayerEntity().getInventory().getChestplate())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dItem
// @description
// returns the item the player is wearing as a helmet, or null
// if none.
// -->
if (attribute.startsWith("equipment.helmet"))
if (getPlayerEntity().getInventory().getHelmet() != null)
return new dItem(getPlayerEntity().getInventory().getHelmet())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dItem
// @description
// returns the item the player is wearing as leggings, or null
// if none.
// -->
if (attribute.startsWith("equipment.leggings"))
if (getPlayerEntity().getInventory().getLeggings() != null)
return new dItem(getPlayerEntity().getInventory().getLeggings())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dInventory
// @description
// returns a dInventory containing the player's equipment
// -->
if (attribute.startsWith("equipment"))
// The only way to return correct size for dInventory
// created from equipment is to use a CRAFTING type
// that has the expected 4 slots
return new dInventory(InventoryType.CRAFTING).add(getPlayerEntity().getInventory().getArmorContents())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns dInventory
// @description
// returns a dInventory of the player's current inventory.
// -->
if (attribute.startsWith("inventory"))
return new dInventory(getPlayerEntity().getInventory())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_in_hand>
// @returns dItem
// @description
// returns the item the player is holding, or null
// if none.
// -->
if (attribute.startsWith("item_in_hand"))
return new dItem(getPlayerEntity().getItemInHand())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_on_cursor>
// @returns dItem
// @description
// returns a dItem that the player's cursor is on, if any. This includes
// chest interfaces, inventories, and hotbars, etc.
// -->
if (attribute.startsWith("item_on_cursor"))
return new dItem(getPlayerEntity().getItemOnCursor())
.getAttribute(attribute.fulfill(1));
/////////////////////
// PERMISSION ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]_permission[permission.node]>
// @returns Element(boolean)
// @description
// returns true if the player has the specified node, false otherwise
// -->
if (attribute.startsWith("permission")
|| attribute.startsWith("has_permission")) {
if (Depends.permissions == null) {
dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?");
return null;
}
String permission = attribute.getContext(1);
// <--[tag]
// @attribute <[email protected]_permission[permission.node].global>
// @returns Element(boolean)
// @description
// returns true if the player has the specified node, regardless of world.
// this may or may not be functional with your permissions system.
// -->
// Non-world specific permission
if (attribute.getAttribute(2).startsWith("global"))
return new Element(Depends.permissions.has((World) null, player_name, permission))
.getAttribute(attribute.fulfill(2));
// Permission in certain world
else if (attribute.getAttribute(2).startsWith("world"))
return new Element(Depends.permissions.has(attribute.getContext(2), player_name, permission))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]_permission[permission.node].world>
// @returns Element(boolean)
// @description
// returns true if the player has the specified node in regards to the
// player's current world. This may or may not be functional with your
// permissions system.
// -->
// Permission in current world
return new Element(Depends.permissions.has(getPlayerEntity(), permission))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]_group[group_name]>
// @returns Element(boolean)
// @description
// returns true if the player has the specified group, false otherwise
// -->
if (attribute.startsWith("group")
|| attribute.startsWith("in_group")) {
if (Depends.permissions == null) {
dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?");
return "null";
}
String group = attribute.getContext(1);
// <--[tag]
// @attribute <[email protected]_group[group_name].global>
// @returns Element(boolean)
// @description
// returns true if the player has the group with no regard to the
// player's current world. This may or may not be functional with your
// permissions system.
// -->
// Non-world specific permission
if (attribute.getAttribute(2).startsWith("global"))
return new Element(Depends.permissions.playerInGroup((World) null, player_name, group))
.getAttribute(attribute.fulfill(2));
// Permission in certain world
else if (attribute.getAttribute(2).startsWith("world"))
return new Element(Depends.permissions.playerInGroup(attribute.getContext(2), player_name, group))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]_group[group_name].world>
// @returns Element(boolean)
// @description
// returns true if the player has the group in regards to the
// player's current world. This may or may not be functional with your
// permissions system.
// -->
// Permission in current world
return new Element(Depends.permissions.playerInGroup(getPlayerEntity(), group))
.getAttribute(attribute.fulfill(1));
}
/////////////////////
// LOCATION ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// returns a dLocation of the player's 'compass target'.
// -->
if (attribute.startsWith("compass_target"))
return new dLocation(getPlayerEntity().getCompassTarget())
.getAttribute(attribute.fulfill(2));
/////////////////////
// STATE ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]_flight>
// @returns Element(boolean)
// @description
// returns true if the player is allowed to fly, and false otherwise
// -->
if (attribute.startsWith("allowed_flight"))
return new Element(getPlayerEntity().getAllowFlight())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_speed>
// @returns Element(Float)
// @description
// returns the speed the player can fly at
// -->
if (attribute.startsWith("fly_speed"))
return new Element(getPlayerEntity().getFlySpeed())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_level.formatted>
// @returns Element
// @description
// returns a 'formatted' value of the player's current food level.
// May be 'starving', 'famished', 'parched, 'hungry' or 'healthy'
// -->
if (attribute.startsWith("food_level.formatted")) {
double maxHunger = getPlayerEntity().getMaxHealth();
if (attribute.hasContext(2))
maxHunger = attribute.getIntContext(2);
if ((float) getPlayerEntity().getFoodLevel() / maxHunger < .10)
return new Element("starving").getAttribute(attribute.fulfill(2));
else if ((float) getPlayerEntity().getFoodLevel() / maxHunger < .40)
return new Element("famished").getAttribute(attribute.fulfill(2));
else if ((float) getPlayerEntity().getFoodLevel() / maxHunger < .75)
return new Element("parched").getAttribute(attribute.fulfill(2));
else if ((float) getPlayerEntity().getFoodLevel() / maxHunger < 1)
return new Element("hungry").getAttribute(attribute.fulfill(2));
else return new Element("healthy").getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]_level>
// @returns Element(number)
// @description
// returns the current food level of the player.
// -->
if (attribute.startsWith("food_level"))
return new Element(getPlayerEntity().getFoodLevel())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(number)
// @description
// returns 'gamemode id' of the player. 0 = survival, 1 = creative, 2 = adventure
// -->
if (attribute.startsWith("gamemode.id"))
return new Element(getPlayerEntity().getGameMode().getValue())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the name of the gamemode the player is currently set to.
// -->
if (attribute.startsWith("gamemode"))
return new Element(getPlayerEntity().getGameMode().name())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_blocking>
// @returns Element(boolean)
// @description
// returns true if the player is currently blocking, false otherwise
// -->
if (attribute.startsWith("is_blocking"))
return new Element(getPlayerEntity().isBlocking())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_flying>
// @returns Element(boolean)
// @description
// returns true if the player is currently flying, false otherwise
// -->
if (attribute.startsWith("is_flying"))
return new Element(getPlayerEntity().isFlying())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_sleeping>
// @returns Element(boolean)
// @description
// returns true if the player is currently sleeping, false otherwise
// -->
if (attribute.startsWith("is_sleeping"))
return new Element(getPlayerEntity().isSleeping())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_sneaking>
// @returns Element(boolean)
// @description
// returns true if the player is currently sneaking, false otherwise
// -->
if (attribute.startsWith("is_sneaking"))
return new Element(getPlayerEntity().isSneaking())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_sprinting>
// @returns Element(boolean)
// @description
// returns true if the player is currently sprinting, false otherwise
// -->
if (attribute.startsWith("is_sprinting"))
return new Element(getPlayerEntity().isSprinting())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_asleep>
// @returns Duration
// @description
// returns a Duration of the time the player has been asleep.
// -->
if (attribute.startsWith("time_asleep"))
return new Duration(getPlayerEntity().getSleepTicks() / 20)
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_speed>
// @returns Element(Float)
// @description
// returns the speed the player can walk at
// -->
if (attribute.startsWith("walk_speed"))
return new Element(getPlayerEntity().getWalkSpeed())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(String)
// @description
// returns the type of weather the player is experiencing.
// -->
if (attribute.startsWith("weather"))
return new Element(getPlayerEntity().getPlayerWeather().name())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(number)
// @description
// returns the number of levels the player has.
// -->
if (attribute.startsWith("xp.level"))
return new Element(getPlayerEntity().getLevel())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]_next_level>
// @returns Element(number)
// @description
// returns the amount of experience to the next level.
// -->
if (attribute.startsWith("xp.to_next_level"))
return new Element(getPlayerEntity().getExpToLevel())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(number)
// @description
// returns the total amount of experience points.
// -->
if (attribute.startsWith("xp.total"))
return new Element(getPlayerEntity().getTotalExperience())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(number)
// @description
// returns the percentage of experience points to the next level.
// -->
if (attribute.startsWith("xp"))
return new Element(getPlayerEntity().getExp() * 100)
.getAttribute(attribute.fulfill(1));
return new dEntity(getPlayerEntity()).getAttribute(attribute);
}
}
| true | true | public String getAttribute(Attribute attribute) {
if (attribute == null) return "null";
if (player_name == null) return "null";
/////////////////////
// OFFLINE ATTRIBUTES
/////////////////
/////////////////////
// DEBUG ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Boolean)
// @description
// Debugs the player in the log and returns true.
// -->
if (attribute.startsWith("debug.log")) {
dB.log(debug());
return new Element(Boolean.TRUE.toString())
.getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]_color>
// @returns Element
// @description
// Returns the player's debug with no color.
// -->
if (attribute.startsWith("debug.no_color")) {
return new Element(ChatColor.stripColor(debug()))
.getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the player's debug.
// -->
if (attribute.startsWith("debug")) {
return new Element(debug())
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the dObject's prefix.
// -->
if (attribute.startsWith("prefix"))
return new Element(prefix)
.getAttribute(attribute.fulfill(1));
/////////////////////
// DENIZEN ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]_history_list>
// @returns dList
// @description
// Returns a list of the last 10 things the player has said, less
// if the player hasn't said all that much.
// -->
if (attribute.startsWith("chat_history_list"))
return new dList(PlayerTags.playerChatHistory.get(player_name))
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_history>
// @returns Element
// @description
// returns the last thing the player said.
// -->
if (attribute.startsWith("chat_history")) {
int x = 1;
if (attribute.hasContext(1) && aH.matchesInteger(attribute.getContext(1)))
x = attribute.getIntContext(1);
// No playerchathistory? Return null.
if (!PlayerTags.playerChatHistory.containsKey(player_name)) return "null";
else return new Element(PlayerTags.playerChatHistory.get(player_name).get(x - 1))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected][flag_name]>
// @returns Flag dList
// @description
// returns 'flag dList' of the player's flag_name specified.
// -->
if (attribute.startsWith("flag")) {
String flag_name;
if (attribute.hasContext(1)) flag_name = attribute.getContext(1);
else return "null";
attribute.fulfill(1);
if (attribute.startsWith("is_expired")
|| attribute.startsWith("isexpired"))
return new Element(!FlagManager.playerHasFlag(this, flag_name))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("size") && !FlagManager.playerHasFlag(this, flag_name))
return new Element(0).getAttribute(attribute.fulfill(1));
if (FlagManager.playerHasFlag(this, flag_name))
return new dList(DenizenAPI.getCurrentInstance().flagManager()
.getPlayerFlag(getName(), flag_name))
.getAttribute(attribute);
else return "null";
}
/////////////////////
// ECONOMY ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns Element(number)
// @description
// returns the amount of money the player has with the registered
// Economy system.
// -->
if (attribute.startsWith("money")) {
if(Depends.economy != null) {
// <--[tag]
// @attribute <[email protected]_singular>
// @returns Element
// @description
// returns the 'singular currency' string, if supported by the
// registered Economy system.
// -->
if (attribute.startsWith("money.currency_singular"))
return new Element(Depends.economy.currencyNameSingular())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the 'currency' string, if supported by the
// registered Economy system.
// -->
if (attribute.startsWith("money.currency"))
return new Element(Depends.economy.currencyNamePlural())
.getAttribute(attribute.fulfill(2));
return new Element(Depends.economy.getBalance(player_name))
.getAttribute(attribute.fulfill(1));
} else {
dB.echoError("No economy loaded! Have you installed Vault and a compatible economy plugin?");
return null;
}
}
/////////////////////
// ENTITY LIST ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns dList(dPlayer)
// @description
// Returns all players that have ever played on the server, online or not.
// **NOTE: This will only work if there is a player attached to the current script.
// If you need it anywhere else, use <server.list_players>**
// -->
if (attribute.startsWith("list")) {
List<String> players = new ArrayList<String>();
// <--[tag]
// @attribute <[email protected]>
// @returns dList(dPlayer)
// @description
// Returns all online players.
// **NOTE: This will only work if there is a player attached to the current script.
// If you need it anywhere else, use <server.list_online_players>**
// -->
if (attribute.startsWith("list.online")) {
for(Player player : Bukkit.getOnlinePlayers())
players.add(player.getName());
return new dList(players).getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]>
// @returns dList(dPlayer)
// @description
// Returns all offline players.
// **NOTE: This will only work if there is a player attached to the current script.
// If you need it anywhere else, use <server.list_offline_players>**
// -->
else if (attribute.startsWith("list.offline")) {
for(OfflinePlayer player : Bukkit.getOfflinePlayers()) {
if (!Bukkit.getOnlinePlayers().toString().contains(player.getName()))
players.add(player.getName());
}
return new dList(players).getAttribute(attribute.fulfill(2));
}
else {
for(OfflinePlayer player : Bukkit.getOfflinePlayers())
players.add(player.getName());
return new dList(players).getAttribute(attribute.fulfill(1));
}
}
/////////////////////
// IDENTIFICATION ATTRIBUTES
/////////////////
if (attribute.startsWith("name") && !isOnline())
// This can be parsed later with more detail if the player is online, so only check for offline.
return new Element(player_name).getAttribute(attribute.fulfill(1));
/////////////////////
// LOCATION ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]_spawn>
// @returns dLocation
// @description
// Returns a dLocation of the player's bed spawn location, 'null' if
// it doesn't exist.
// -->
if (attribute.startsWith("bed_spawn"))
return new dLocation(getOfflinePlayer().getBedSpawnLocation())
.getAttribute(attribute.fulfill(2));
/////////////////////
// STATE ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]_played>
// @returns Element(number)
// @description
// returns the 'System.currentTimeMillis()' of when the player
// first logged on. Will return '0' if player has never played.
// -->
if (attribute.startsWith("first_played"))
return new Element(getOfflinePlayer().getFirstPlayed())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_played_before>
// @returns Element(boolean)
// @description
// returns true if the player has played before
// -->
if (attribute.startsWith("has_played_before"))
return new Element(getOfflinePlayer().hasPlayedBefore())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_banned>
// @returns Element(boolean)
// @description
// returns true if the player is banned
// -->
if (attribute.startsWith("is_banned"))
return new Element(getOfflinePlayer().isBanned())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_online>
// @returns Element(boolean)
// @description
// returns true if the player is currently online
// -->
if (attribute.startsWith("is_online"))
return new Element(isOnline()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_op>
// @returns Element(boolean)
// @description
// returns true if the player has 'op status'
// -->
if (attribute.startsWith("is_op"))
return new Element(getOfflinePlayer().isOp())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_whitelisted>
// @returns Element(boolean)
// @description
// returns true if the player is whitelisted
// -->
if (attribute.startsWith("is_whitelisted"))
return new Element(getOfflinePlayer().isWhitelisted())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_played>
// @returns Element(number)
// @description
// returns the 'System.currentTimeMillis()' of when the player
// was last seen. Will return '0' if player has never played.
// -->
if (attribute.startsWith("last_played"))
return new Element(getOfflinePlayer().getLastPlayed())
.getAttribute(attribute.fulfill(1));
/////////////////////
// ONLINE ATTRIBUTES
/////////////////
// Player is required to be online after this point...
/////////////////////
// CITIZENS ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]_npc>
// @returns dNPC
// @description
// returns the dNPC that the player currently has selected with
// '/npc sel', null if no player selected.
// -->
if (attribute.startsWith("selected_npc")) {
if (getPlayerEntity().hasMetadata("selected"))
return dNPC.valueOf(getPlayerEntity().getMetadata("selected").get(0).asString())
.getAttribute(attribute.fulfill(1));
else return "null";
}
/////////////////////
// CONVERSION ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns dEntity
// @description
// returns the dEntity object of the player
// -->
if (attribute.startsWith("entity"))
return new dEntity(getPlayerEntity())
.getAttribute(attribute.fulfill(1));
/////////////////////
// IDENTIFICATION ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the player's IP address.
// -->
if (attribute.startsWith("ip") ||
attribute.startsWith("host_name"))
return new Element(getPlayerEntity().getAddress().getHostName())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the 'display name' of the player, which may contain
// prefixes and suffixes/color, etc.
// -->
if (attribute.startsWith("name.display"))
return new Element(getPlayerEntity().getDisplayName())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the name of the player as shown in the 'player list'.
// -->
if (attribute.startsWith("name.list"))
return new Element(getPlayerEntity().getPlayerListName())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the name of the player.
// -->
if (attribute.startsWith("name"))
return new Element(player_name).getAttribute(attribute.fulfill(1));
/////////////////////
// INVENTORY ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns dItem
// @description
// returns the item the player is wearing as boots, or null
// if none.
// -->
if (attribute.startsWith("equipment.boots"))
if (getPlayerEntity().getInventory().getBoots() != null)
return new dItem(getPlayerEntity().getInventory().getBoots())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dItem
// @description
// returns the item the player is wearing as a chestplate, or null
// if none.
// -->
if (attribute.startsWith("equipment.chestplate"))
if (getPlayerEntity().getInventory().getChestplate() != null)
return new dItem(getPlayerEntity().getInventory().getChestplate())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dItem
// @description
// returns the item the player is wearing as a helmet, or null
// if none.
// -->
if (attribute.startsWith("equipment.helmet"))
if (getPlayerEntity().getInventory().getHelmet() != null)
return new dItem(getPlayerEntity().getInventory().getHelmet())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dItem
// @description
// returns the item the player is wearing as leggings, or null
// if none.
// -->
if (attribute.startsWith("equipment.leggings"))
if (getPlayerEntity().getInventory().getLeggings() != null)
return new dItem(getPlayerEntity().getInventory().getLeggings())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dInventory
// @description
// returns a dInventory containing the player's equipment
// -->
if (attribute.startsWith("equipment"))
// The only way to return correct size for dInventory
// created from equipment is to use a CRAFTING type
// that has the expected 4 slots
return new dInventory(InventoryType.CRAFTING).add(getPlayerEntity().getInventory().getArmorContents())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns dInventory
// @description
// returns a dInventory of the player's current inventory.
// -->
if (attribute.startsWith("inventory"))
return new dInventory(getPlayerEntity().getInventory())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_in_hand>
// @returns dItem
// @description
// returns the item the player is holding, or null
// if none.
// -->
if (attribute.startsWith("item_in_hand"))
return new dItem(getPlayerEntity().getItemInHand())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_on_cursor>
// @returns dItem
// @description
// returns a dItem that the player's cursor is on, if any. This includes
// chest interfaces, inventories, and hotbars, etc.
// -->
if (attribute.startsWith("item_on_cursor"))
return new dItem(getPlayerEntity().getItemOnCursor())
.getAttribute(attribute.fulfill(1));
/////////////////////
// PERMISSION ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]_permission[permission.node]>
// @returns Element(boolean)
// @description
// returns true if the player has the specified node, false otherwise
// -->
if (attribute.startsWith("permission")
|| attribute.startsWith("has_permission")) {
if (Depends.permissions == null) {
dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?");
return null;
}
String permission = attribute.getContext(1);
// <--[tag]
// @attribute <[email protected]_permission[permission.node].global>
// @returns Element(boolean)
// @description
// returns true if the player has the specified node, regardless of world.
// this may or may not be functional with your permissions system.
// -->
// Non-world specific permission
if (attribute.getAttribute(2).startsWith("global"))
return new Element(Depends.permissions.has((World) null, player_name, permission))
.getAttribute(attribute.fulfill(2));
// Permission in certain world
else if (attribute.getAttribute(2).startsWith("world"))
return new Element(Depends.permissions.has(attribute.getContext(2), player_name, permission))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]_permission[permission.node].world>
// @returns Element(boolean)
// @description
// returns true if the player has the specified node in regards to the
// player's current world. This may or may not be functional with your
// permissions system.
// -->
// Permission in current world
return new Element(Depends.permissions.has(getPlayerEntity(), permission))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]_group[group_name]>
// @returns Element(boolean)
// @description
// returns true if the player has the specified group, false otherwise
// -->
if (attribute.startsWith("group")
|| attribute.startsWith("in_group")) {
if (Depends.permissions == null) {
dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?");
return "null";
}
String group = attribute.getContext(1);
// <--[tag]
// @attribute <[email protected]_group[group_name].global>
// @returns Element(boolean)
// @description
// returns true if the player has the group with no regard to the
// player's current world. This may or may not be functional with your
// permissions system.
// -->
// Non-world specific permission
if (attribute.getAttribute(2).startsWith("global"))
return new Element(Depends.permissions.playerInGroup((World) null, player_name, group))
.getAttribute(attribute.fulfill(2));
// Permission in certain world
else if (attribute.getAttribute(2).startsWith("world"))
return new Element(Depends.permissions.playerInGroup(attribute.getContext(2), player_name, group))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]_group[group_name].world>
// @returns Element(boolean)
// @description
// returns true if the player has the group in regards to the
// player's current world. This may or may not be functional with your
// permissions system.
// -->
// Permission in current world
return new Element(Depends.permissions.playerInGroup(getPlayerEntity(), group))
.getAttribute(attribute.fulfill(1));
}
/////////////////////
// LOCATION ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// returns a dLocation of the player's 'compass target'.
// -->
if (attribute.startsWith("compass_target"))
return new dLocation(getPlayerEntity().getCompassTarget())
.getAttribute(attribute.fulfill(2));
/////////////////////
// STATE ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]_flight>
// @returns Element(boolean)
// @description
// returns true if the player is allowed to fly, and false otherwise
// -->
if (attribute.startsWith("allowed_flight"))
return new Element(getPlayerEntity().getAllowFlight())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_speed>
// @returns Element(Float)
// @description
// returns the speed the player can fly at
// -->
if (attribute.startsWith("fly_speed"))
return new Element(getPlayerEntity().getFlySpeed())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_level.formatted>
// @returns Element
// @description
// returns a 'formatted' value of the player's current food level.
// May be 'starving', 'famished', 'parched, 'hungry' or 'healthy'
// -->
if (attribute.startsWith("food_level.formatted")) {
double maxHunger = getPlayerEntity().getMaxHealth();
if (attribute.hasContext(2))
maxHunger = attribute.getIntContext(2);
if ((float) getPlayerEntity().getFoodLevel() / maxHunger < .10)
return new Element("starving").getAttribute(attribute.fulfill(2));
else if ((float) getPlayerEntity().getFoodLevel() / maxHunger < .40)
return new Element("famished").getAttribute(attribute.fulfill(2));
else if ((float) getPlayerEntity().getFoodLevel() / maxHunger < .75)
return new Element("parched").getAttribute(attribute.fulfill(2));
else if ((float) getPlayerEntity().getFoodLevel() / maxHunger < 1)
return new Element("hungry").getAttribute(attribute.fulfill(2));
else return new Element("healthy").getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]_level>
// @returns Element(number)
// @description
// returns the current food level of the player.
// -->
if (attribute.startsWith("food_level"))
return new Element(getPlayerEntity().getFoodLevel())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(number)
// @description
// returns 'gamemode id' of the player. 0 = survival, 1 = creative, 2 = adventure
// -->
if (attribute.startsWith("gamemode.id"))
return new Element(getPlayerEntity().getGameMode().getValue())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the name of the gamemode the player is currently set to.
// -->
if (attribute.startsWith("gamemode"))
return new Element(getPlayerEntity().getGameMode().name())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_blocking>
// @returns Element(boolean)
// @description
// returns true if the player is currently blocking, false otherwise
// -->
if (attribute.startsWith("is_blocking"))
return new Element(getPlayerEntity().isBlocking())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_flying>
// @returns Element(boolean)
// @description
// returns true if the player is currently flying, false otherwise
// -->
if (attribute.startsWith("is_flying"))
return new Element(getPlayerEntity().isFlying())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_sleeping>
// @returns Element(boolean)
// @description
// returns true if the player is currently sleeping, false otherwise
// -->
if (attribute.startsWith("is_sleeping"))
return new Element(getPlayerEntity().isSleeping())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_sneaking>
// @returns Element(boolean)
// @description
// returns true if the player is currently sneaking, false otherwise
// -->
if (attribute.startsWith("is_sneaking"))
return new Element(getPlayerEntity().isSneaking())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_sprinting>
// @returns Element(boolean)
// @description
// returns true if the player is currently sprinting, false otherwise
// -->
if (attribute.startsWith("is_sprinting"))
return new Element(getPlayerEntity().isSprinting())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_asleep>
// @returns Duration
// @description
// returns a Duration of the time the player has been asleep.
// -->
if (attribute.startsWith("time_asleep"))
return new Duration(getPlayerEntity().getSleepTicks() / 20)
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_speed>
// @returns Element(Float)
// @description
// returns the speed the player can walk at
// -->
if (attribute.startsWith("walk_speed"))
return new Element(getPlayerEntity().getWalkSpeed())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(String)
// @description
// returns the type of weather the player is experiencing.
// -->
if (attribute.startsWith("weather"))
return new Element(getPlayerEntity().getPlayerWeather().name())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(number)
// @description
// returns the number of levels the player has.
// -->
if (attribute.startsWith("xp.level"))
return new Element(getPlayerEntity().getLevel())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]_next_level>
// @returns Element(number)
// @description
// returns the amount of experience to the next level.
// -->
if (attribute.startsWith("xp.to_next_level"))
return new Element(getPlayerEntity().getExpToLevel())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(number)
// @description
// returns the total amount of experience points.
// -->
if (attribute.startsWith("xp.total"))
return new Element(getPlayerEntity().getTotalExperience())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(number)
// @description
// returns the percentage of experience points to the next level.
// -->
if (attribute.startsWith("xp"))
return new Element(getPlayerEntity().getExp() * 100)
.getAttribute(attribute.fulfill(1));
return new dEntity(getPlayerEntity()).getAttribute(attribute);
}
| public String getAttribute(Attribute attribute) {
if (attribute == null) return "null";
if (player_name == null) return "null";
/////////////////////
// OFFLINE ATTRIBUTES
/////////////////
/////////////////////
// DEBUG ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns Element(Boolean)
// @description
// Debugs the player in the log and returns true.
// -->
if (attribute.startsWith("debug.log")) {
dB.log(debug());
return new Element(Boolean.TRUE.toString())
.getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]_color>
// @returns Element
// @description
// Returns the player's debug with no color.
// -->
if (attribute.startsWith("debug.no_color")) {
return new Element(ChatColor.stripColor(debug()))
.getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the player's debug.
// -->
if (attribute.startsWith("debug")) {
return new Element(debug())
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// Returns the dObject's prefix.
// -->
if (attribute.startsWith("prefix"))
return new Element(prefix)
.getAttribute(attribute.fulfill(1));
/////////////////////
// DENIZEN ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]_history_list>
// @returns dList
// @description
// Returns a list of the last 10 things the player has said, less
// if the player hasn't said all that much.
// -->
if (attribute.startsWith("chat_history_list"))
return new dList(PlayerTags.playerChatHistory.get(player_name))
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_history>
// @returns Element
// @description
// returns the last thing the player said.
// -->
if (attribute.startsWith("chat_history")) {
int x = 1;
if (attribute.hasContext(1) && aH.matchesInteger(attribute.getContext(1)))
x = attribute.getIntContext(1);
// No playerchathistory? Return null.
if (!PlayerTags.playerChatHistory.containsKey(player_name)) return "null";
else return new Element(PlayerTags.playerChatHistory.get(player_name).get(x - 1))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected][flag_name]>
// @returns Flag dList
// @description
// returns 'flag dList' of the player's flag_name specified.
// -->
if (attribute.startsWith("flag")) {
String flag_name;
if (attribute.hasContext(1)) flag_name = attribute.getContext(1);
else return "null";
attribute.fulfill(1);
if (attribute.startsWith("is_expired")
|| attribute.startsWith("isexpired"))
return new Element(!FlagManager.playerHasFlag(this, flag_name))
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("size") && !FlagManager.playerHasFlag(this, flag_name))
return new Element(0).getAttribute(attribute.fulfill(1));
if (FlagManager.playerHasFlag(this, flag_name))
return new dList(DenizenAPI.getCurrentInstance().flagManager()
.getPlayerFlag(getName(), flag_name))
.getAttribute(attribute);
else return "null";
}
/////////////////////
// ECONOMY ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns Element(number)
// @description
// returns the amount of money the player has with the registered
// Economy system.
// -->
if (attribute.startsWith("money")) {
if(Depends.economy != null) {
// <--[tag]
// @attribute <[email protected]_singular>
// @returns Element
// @description
// returns the 'singular currency' string, if supported by the
// registered Economy system.
// -->
if (attribute.startsWith("money.currency_singular"))
return new Element(Depends.economy.currencyNameSingular())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the 'currency' string, if supported by the
// registered Economy system.
// -->
if (attribute.startsWith("money.currency"))
return new Element(Depends.economy.currencyNamePlural())
.getAttribute(attribute.fulfill(2));
return new Element(Depends.economy.getBalance(player_name))
.getAttribute(attribute.fulfill(1));
} else {
dB.echoError("No economy loaded! Have you installed Vault and a compatible economy plugin?");
return null;
}
}
/////////////////////
// ENTITY LIST ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns dList(dPlayer)
// @description
// Returns all players that have ever played on the server, online or not.
// **NOTE: This will only work if there is a player attached to the current script.
// If you need it anywhere else, use <server.list_players>**
// -->
if (attribute.startsWith("list")) {
List<String> players = new ArrayList<String>();
// <--[tag]
// @attribute <[email protected]>
// @returns dList(dPlayer)
// @description
// Returns all online players.
// **NOTE: This will only work if there is a player attached to the current script.
// If you need it anywhere else, use <server.list_online_players>**
// -->
if (attribute.startsWith("list.online")) {
for(Player player : Bukkit.getOnlinePlayers())
players.add(player.getName());
return new dList(players).getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]>
// @returns dList(dPlayer)
// @description
// Returns all offline players.
// **NOTE: This will only work if there is a player attached to the current script.
// If you need it anywhere else, use <server.list_offline_players>**
// -->
else if (attribute.startsWith("list.offline")) {
for(OfflinePlayer player : Bukkit.getOfflinePlayers()) {
if (!Bukkit.getOnlinePlayers().toString().contains(player.getName()))
players.add(player.getName());
}
return new dList(players).getAttribute(attribute.fulfill(2));
}
else {
for(OfflinePlayer player : Bukkit.getOfflinePlayers())
players.add(player.getName());
return new dList(players).getAttribute(attribute.fulfill(1));
}
}
/////////////////////
// IDENTIFICATION ATTRIBUTES
/////////////////
if (attribute.startsWith("name") && !isOnline())
// This can be parsed later with more detail if the player is online, so only check for offline.
return new Element(player_name).getAttribute(attribute.fulfill(1));
/////////////////////
// LOCATION ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]_spawn>
// @returns dLocation
// @description
// Returns a dLocation of the player's bed spawn location, 'null' if
// it doesn't exist.
// -->
if (attribute.startsWith("bed_spawn"))
return new dLocation(getOfflinePlayer().getBedSpawnLocation())
.getAttribute(attribute.fulfill(2));
/////////////////////
// STATE ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]_played>
// @returns Element(number)
// @description
// returns the 'System.currentTimeMillis()' of when the player
// first logged on. Will return '0' if player has never played.
// -->
if (attribute.startsWith("first_played"))
return new Element(getOfflinePlayer().getFirstPlayed())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_played_before>
// @returns Element(boolean)
// @description
// returns true if the player has played before
// -->
if (attribute.startsWith("has_played_before"))
return new Element(getOfflinePlayer().hasPlayedBefore())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_banned>
// @returns Element(boolean)
// @description
// returns true if the player is banned
// -->
if (attribute.startsWith("is_banned"))
return new Element(getOfflinePlayer().isBanned())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_online>
// @returns Element(boolean)
// @description
// returns true if the player is currently online
// -->
if (attribute.startsWith("is_online"))
return new Element(isOnline()).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_op>
// @returns Element(boolean)
// @description
// returns true if the player has 'op status'
// -->
if (attribute.startsWith("is_op"))
return new Element(getOfflinePlayer().isOp())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_whitelisted>
// @returns Element(boolean)
// @description
// returns true if the player is whitelisted
// -->
if (attribute.startsWith("is_whitelisted"))
return new Element(getOfflinePlayer().isWhitelisted())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_played>
// @returns Element(number)
// @description
// returns the 'System.currentTimeMillis()' of when the player
// was last seen. Will return '0' if player has never played.
// -->
if (attribute.startsWith("last_played"))
return new Element(getOfflinePlayer().getLastPlayed())
.getAttribute(attribute.fulfill(1));
/////////////////////
// ONLINE ATTRIBUTES
/////////////////
// Player is required to be online after this point...
if (!isOnline()) return new Element(identify()).getAttribute(attribute);
/////////////////////
// CITIZENS ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]_npc>
// @returns dNPC
// @description
// returns the dNPC that the player currently has selected with
// '/npc sel', null if no player selected.
// -->
if (attribute.startsWith("selected_npc")) {
if (getPlayerEntity().hasMetadata("selected"))
return dNPC.valueOf(getPlayerEntity().getMetadata("selected").get(0).asString())
.getAttribute(attribute.fulfill(1));
else return "null";
}
/////////////////////
// CONVERSION ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns dEntity
// @description
// returns the dEntity object of the player
// -->
if (attribute.startsWith("entity"))
return new dEntity(getPlayerEntity())
.getAttribute(attribute.fulfill(1));
/////////////////////
// IDENTIFICATION ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the player's IP address.
// -->
if (attribute.startsWith("ip") ||
attribute.startsWith("host_name"))
return new Element(getPlayerEntity().getAddress().getHostName())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the 'display name' of the player, which may contain
// prefixes and suffixes/color, etc.
// -->
if (attribute.startsWith("name.display"))
return new Element(getPlayerEntity().getDisplayName())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the name of the player as shown in the 'player list'.
// -->
if (attribute.startsWith("name.list"))
return new Element(getPlayerEntity().getPlayerListName())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the name of the player.
// -->
if (attribute.startsWith("name"))
return new Element(player_name).getAttribute(attribute.fulfill(1));
/////////////////////
// INVENTORY ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns dItem
// @description
// returns the item the player is wearing as boots, or null
// if none.
// -->
if (attribute.startsWith("equipment.boots"))
if (getPlayerEntity().getInventory().getBoots() != null)
return new dItem(getPlayerEntity().getInventory().getBoots())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dItem
// @description
// returns the item the player is wearing as a chestplate, or null
// if none.
// -->
if (attribute.startsWith("equipment.chestplate"))
if (getPlayerEntity().getInventory().getChestplate() != null)
return new dItem(getPlayerEntity().getInventory().getChestplate())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dItem
// @description
// returns the item the player is wearing as a helmet, or null
// if none.
// -->
if (attribute.startsWith("equipment.helmet"))
if (getPlayerEntity().getInventory().getHelmet() != null)
return new dItem(getPlayerEntity().getInventory().getHelmet())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dItem
// @description
// returns the item the player is wearing as leggings, or null
// if none.
// -->
if (attribute.startsWith("equipment.leggings"))
if (getPlayerEntity().getInventory().getLeggings() != null)
return new dItem(getPlayerEntity().getInventory().getLeggings())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns dInventory
// @description
// returns a dInventory containing the player's equipment
// -->
if (attribute.startsWith("equipment"))
// The only way to return correct size for dInventory
// created from equipment is to use a CRAFTING type
// that has the expected 4 slots
return new dInventory(InventoryType.CRAFTING).add(getPlayerEntity().getInventory().getArmorContents())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns dInventory
// @description
// returns a dInventory of the player's current inventory.
// -->
if (attribute.startsWith("inventory"))
return new dInventory(getPlayerEntity().getInventory())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_in_hand>
// @returns dItem
// @description
// returns the item the player is holding, or null
// if none.
// -->
if (attribute.startsWith("item_in_hand"))
return new dItem(getPlayerEntity().getItemInHand())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_on_cursor>
// @returns dItem
// @description
// returns a dItem that the player's cursor is on, if any. This includes
// chest interfaces, inventories, and hotbars, etc.
// -->
if (attribute.startsWith("item_on_cursor"))
return new dItem(getPlayerEntity().getItemOnCursor())
.getAttribute(attribute.fulfill(1));
/////////////////////
// PERMISSION ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]_permission[permission.node]>
// @returns Element(boolean)
// @description
// returns true if the player has the specified node, false otherwise
// -->
if (attribute.startsWith("permission")
|| attribute.startsWith("has_permission")) {
if (Depends.permissions == null) {
dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?");
return null;
}
String permission = attribute.getContext(1);
// <--[tag]
// @attribute <[email protected]_permission[permission.node].global>
// @returns Element(boolean)
// @description
// returns true if the player has the specified node, regardless of world.
// this may or may not be functional with your permissions system.
// -->
// Non-world specific permission
if (attribute.getAttribute(2).startsWith("global"))
return new Element(Depends.permissions.has((World) null, player_name, permission))
.getAttribute(attribute.fulfill(2));
// Permission in certain world
else if (attribute.getAttribute(2).startsWith("world"))
return new Element(Depends.permissions.has(attribute.getContext(2), player_name, permission))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]_permission[permission.node].world>
// @returns Element(boolean)
// @description
// returns true if the player has the specified node in regards to the
// player's current world. This may or may not be functional with your
// permissions system.
// -->
// Permission in current world
return new Element(Depends.permissions.has(getPlayerEntity(), permission))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <[email protected]_group[group_name]>
// @returns Element(boolean)
// @description
// returns true if the player has the specified group, false otherwise
// -->
if (attribute.startsWith("group")
|| attribute.startsWith("in_group")) {
if (Depends.permissions == null) {
dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?");
return "null";
}
String group = attribute.getContext(1);
// <--[tag]
// @attribute <[email protected]_group[group_name].global>
// @returns Element(boolean)
// @description
// returns true if the player has the group with no regard to the
// player's current world. This may or may not be functional with your
// permissions system.
// -->
// Non-world specific permission
if (attribute.getAttribute(2).startsWith("global"))
return new Element(Depends.permissions.playerInGroup((World) null, player_name, group))
.getAttribute(attribute.fulfill(2));
// Permission in certain world
else if (attribute.getAttribute(2).startsWith("world"))
return new Element(Depends.permissions.playerInGroup(attribute.getContext(2), player_name, group))
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]_group[group_name].world>
// @returns Element(boolean)
// @description
// returns true if the player has the group in regards to the
// player's current world. This may or may not be functional with your
// permissions system.
// -->
// Permission in current world
return new Element(Depends.permissions.playerInGroup(getPlayerEntity(), group))
.getAttribute(attribute.fulfill(1));
}
/////////////////////
// LOCATION ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]>
// @returns dLocation
// @description
// returns a dLocation of the player's 'compass target'.
// -->
if (attribute.startsWith("compass_target"))
return new dLocation(getPlayerEntity().getCompassTarget())
.getAttribute(attribute.fulfill(2));
/////////////////////
// STATE ATTRIBUTES
/////////////////
// <--[tag]
// @attribute <[email protected]_flight>
// @returns Element(boolean)
// @description
// returns true if the player is allowed to fly, and false otherwise
// -->
if (attribute.startsWith("allowed_flight"))
return new Element(getPlayerEntity().getAllowFlight())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_speed>
// @returns Element(Float)
// @description
// returns the speed the player can fly at
// -->
if (attribute.startsWith("fly_speed"))
return new Element(getPlayerEntity().getFlySpeed())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_level.formatted>
// @returns Element
// @description
// returns a 'formatted' value of the player's current food level.
// May be 'starving', 'famished', 'parched, 'hungry' or 'healthy'
// -->
if (attribute.startsWith("food_level.formatted")) {
double maxHunger = getPlayerEntity().getMaxHealth();
if (attribute.hasContext(2))
maxHunger = attribute.getIntContext(2);
if ((float) getPlayerEntity().getFoodLevel() / maxHunger < .10)
return new Element("starving").getAttribute(attribute.fulfill(2));
else if ((float) getPlayerEntity().getFoodLevel() / maxHunger < .40)
return new Element("famished").getAttribute(attribute.fulfill(2));
else if ((float) getPlayerEntity().getFoodLevel() / maxHunger < .75)
return new Element("parched").getAttribute(attribute.fulfill(2));
else if ((float) getPlayerEntity().getFoodLevel() / maxHunger < 1)
return new Element("hungry").getAttribute(attribute.fulfill(2));
else return new Element("healthy").getAttribute(attribute.fulfill(2));
}
// <--[tag]
// @attribute <[email protected]_level>
// @returns Element(number)
// @description
// returns the current food level of the player.
// -->
if (attribute.startsWith("food_level"))
return new Element(getPlayerEntity().getFoodLevel())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(number)
// @description
// returns 'gamemode id' of the player. 0 = survival, 1 = creative, 2 = adventure
// -->
if (attribute.startsWith("gamemode.id"))
return new Element(getPlayerEntity().getGameMode().getValue())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element
// @description
// returns the name of the gamemode the player is currently set to.
// -->
if (attribute.startsWith("gamemode"))
return new Element(getPlayerEntity().getGameMode().name())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_blocking>
// @returns Element(boolean)
// @description
// returns true if the player is currently blocking, false otherwise
// -->
if (attribute.startsWith("is_blocking"))
return new Element(getPlayerEntity().isBlocking())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_flying>
// @returns Element(boolean)
// @description
// returns true if the player is currently flying, false otherwise
// -->
if (attribute.startsWith("is_flying"))
return new Element(getPlayerEntity().isFlying())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_sleeping>
// @returns Element(boolean)
// @description
// returns true if the player is currently sleeping, false otherwise
// -->
if (attribute.startsWith("is_sleeping"))
return new Element(getPlayerEntity().isSleeping())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_sneaking>
// @returns Element(boolean)
// @description
// returns true if the player is currently sneaking, false otherwise
// -->
if (attribute.startsWith("is_sneaking"))
return new Element(getPlayerEntity().isSneaking())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_sprinting>
// @returns Element(boolean)
// @description
// returns true if the player is currently sprinting, false otherwise
// -->
if (attribute.startsWith("is_sprinting"))
return new Element(getPlayerEntity().isSprinting())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_asleep>
// @returns Duration
// @description
// returns a Duration of the time the player has been asleep.
// -->
if (attribute.startsWith("time_asleep"))
return new Duration(getPlayerEntity().getSleepTicks() / 20)
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]_speed>
// @returns Element(Float)
// @description
// returns the speed the player can walk at
// -->
if (attribute.startsWith("walk_speed"))
return new Element(getPlayerEntity().getWalkSpeed())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(String)
// @description
// returns the type of weather the player is experiencing.
// -->
if (attribute.startsWith("weather"))
return new Element(getPlayerEntity().getPlayerWeather().name())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(number)
// @description
// returns the number of levels the player has.
// -->
if (attribute.startsWith("xp.level"))
return new Element(getPlayerEntity().getLevel())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]_next_level>
// @returns Element(number)
// @description
// returns the amount of experience to the next level.
// -->
if (attribute.startsWith("xp.to_next_level"))
return new Element(getPlayerEntity().getExpToLevel())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(number)
// @description
// returns the total amount of experience points.
// -->
if (attribute.startsWith("xp.total"))
return new Element(getPlayerEntity().getTotalExperience())
.getAttribute(attribute.fulfill(2));
// <--[tag]
// @attribute <[email protected]>
// @returns Element(number)
// @description
// returns the percentage of experience points to the next level.
// -->
if (attribute.startsWith("xp"))
return new Element(getPlayerEntity().getExp() * 100)
.getAttribute(attribute.fulfill(1));
return new dEntity(getPlayerEntity()).getAttribute(attribute);
}
|
diff --git a/src/com/dmdirc/parser/irc/ProcessListModes.java b/src/com/dmdirc/parser/irc/ProcessListModes.java
index 9a640acdf..1008d19a2 100644
--- a/src/com/dmdirc/parser/irc/ProcessListModes.java
+++ b/src/com/dmdirc/parser/irc/ProcessListModes.java
@@ -1,241 +1,241 @@
/*
* Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.parser.irc;
import java.util.List;
import java.util.LinkedList;
import java.util.Queue;
/**
* Process a List Modes.
*/
public class ProcessListModes extends IRCProcessor {
/**
* Process a ListModes.
*
* @param sParam Type of line to process
* @param token IRCTokenised line to process
*/
@SuppressWarnings("unchecked")
@Override
public void process(String sParam, String[] token) {
ChannelInfo channel = getChannelInfo(token[3]);
String thisIRCD = myParser.getIRCD(true).toLowerCase();
String item = "";
String owner = "";
byte tokenStart = 4; // Where do the relevent tokens start?
boolean isCleverMode = false;
long time = 0;
char mode = 'b';
boolean isItem = true; // true if item listing, false if "end of .." item
if (channel == null) { return; }
if (sParam.equals("367") || sParam.equals("368")) {
// Ban List/Item.
// (Also used for +d and +q on hyperion... -_-)
mode = 'b';
isItem = sParam.equals("367");
} else if (sParam.equals("348") || sParam.equals("349")) {
// Except / Exempt List etc
mode = 'e';
isItem = sParam.equals("348");
} else if (sParam.equals("346") || sParam.equals("347")) {
// Invite List
mode = 'I';
isItem = sParam.equals("346");
} else if (sParam.equals("940") || sParam.equals("941")) {
// Censored words List
mode = 'g';
isItem = sParam.equals("941");
} else if (sParam.equals("344") || sParam.equals("345")) {
// Reop List, or bad words list, or quiet list. god damn.
if (thisIRCD.equals("euircd")) {
mode = 'w';
} else if (thisIRCD.equals("oftc-hybrid")) {
mode = 'q';
} else {
mode = 'R';
}
isItem = sParam.equals("344");
} else if (thisIRCD.equals("swiftirc") && (sParam.equals("386") || sParam.equals("387"))) {
// Channel Owner list
mode = 'q';
isItem = sParam.equals("387");
} else if (thisIRCD.equals("swiftirc") && (sParam.equals("388") || sParam.equals("389"))) {
// Protected User list
mode = 'a';
isItem = sParam.equals("389");
} else if (sParam.equals(myParser.h005Info.get("LISTMODE")) || sParam.equals(myParser.h005Info.get("LISTMODEEND"))) {
// Support for potential future decent mode listing in the protocol
//
// See my proposal: http://shane.dmdirc.com/listmodes.php
mode = token[4].charAt(0);
isItem = sParam.equals(myParser.h005Info.get("LISTMODE"));
tokenStart = 5;
isCleverMode = true;
}
final Queue<Character> listModeQueue = channel.getListModeQueue();
if (!isCleverMode && listModeQueue != null) {
if (sParam.equals("482")) {
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "Dropped LMQ mode "+listModeQueue.poll());
return;
} else {
if (listModeQueue.peek() != null) {
Character oldMode = mode;
mode = listModeQueue.peek();
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "LMQ says this is "+mode);
boolean error = true;
// b or q are given in the same list, d is separate.
// b and q remove each other from the LMQ.
//
// Only raise an LMQ error if the lmqmode isn't one of bdq if the
// guess is one of bdq
if ((thisIRCD.equals("hyperion") || thisIRCD.equals("dancer")) && (mode == 'b' || mode == 'q' || mode == 'd')) {
LinkedList<Character> lmq = (LinkedList<Character>)listModeQueue;
if (mode == 'b') {
error = !(oldMode == 'q' || oldMode == 'd');
lmq.remove((Character)'q');
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "Dropping q from list");
} else if (mode == 'q') {
error = !(oldMode == 'b' || oldMode == 'd');
lmq.remove((Character)'b');
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "Dropping b from list");
} else if (mode == 'd') {
error = !(oldMode == 'b' || oldMode == 'q');
}
}
if (oldMode != mode && error) {
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "LMQ disagrees with guess. LMQ: "+mode+" Guess: "+oldMode);
- myParser.callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "LMQ disagrees with guess. LMQ: "+mode+" Guess: "+oldMode, myParser.getLastLine()));
+// myParser.callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "LMQ disagrees with guess. LMQ: "+mode+" Guess: "+oldMode, myParser.getLastLine()));
}
if (!isItem) {
listModeQueue.poll();
}
}
}
}
if (isItem) {
if ((!isCleverMode) && listModeQueue == null && (thisIRCD.equals("hyperion") || thisIRCD.equals("dancer")) && token.length > 4 && mode == 'b') {
// Assume mode is a 'd' mode
mode = 'd';
// Now work out if its not (or attempt to.)
int identstart = token[tokenStart].indexOf('!');
int hoststart = token[tokenStart].indexOf('@');
// Check that ! and @ are both in the string - as required by +b and +q
if ((identstart >= 0) && (identstart < hoststart)) {
if (thisIRCD.equals("hyperion") && token[tokenStart].charAt(0) == '%') { mode = 'q'; }
else { mode = 'b'; }
}
} // End Hyperian stupidness of using the same numeric for 3 different things..
if (!channel.getAddState(mode)) {
callDebugInfo(IRCParser.DEBUG_INFO, "New List Mode Batch ("+mode+"): Clearing!");
final List<ChannelListModeItem> list = channel.getListModeParam(mode);
if (list == null) {
myParser.callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got list mode: '"+mode+"' - but channel object doesn't agree.", myParser.getLastLine()));
} else {
list.clear();
if ((thisIRCD.equals("hyperion") || thisIRCD.equals("dancer")) && (mode == 'b' || mode == 'q')) {
// Also clear the other list if b or q.
final Character otherMode = (mode == 'b') ? 'q' : 'b';
if (!channel.getAddState(otherMode)) {
callDebugInfo(IRCParser.DEBUG_INFO, "New List Mode Batch ("+mode+"): Clearing!");
final List<ChannelListModeItem> otherList = channel.getListModeParam(otherMode);
if (otherList == null) {
myParser.callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got list mode: '"+otherMode+"' - but channel object doesn't agree.", myParser.getLastLine()));
} else {
otherList.clear();
}
}
}
}
channel.setAddState(mode, true);
}
if (token.length > (tokenStart+2)) {
try { time = Long.parseLong(token[tokenStart+2]); } catch (NumberFormatException e) { time = 0; }
}
if (token.length > (tokenStart+1)) { owner = token[tokenStart+1]; }
if (token.length > tokenStart) { item = token[tokenStart]; }
if (!item.isEmpty()) {
ChannelListModeItem clmi = new ChannelListModeItem(item, owner, time);
callDebugInfo(IRCParser.DEBUG_INFO, "List Mode: %c [%s/%s/%d]",mode, item, owner, time);
channel.setListModeParam(mode, clmi, true);
}
} else {
callDebugInfo(IRCParser.DEBUG_INFO, "List Mode Batch over");
channel.resetAddState();
if (isCleverMode || listModeQueue == null || ((LinkedList<Character>)listModeQueue).size() == 0) {
callDebugInfo(IRCParser.DEBUG_INFO, "Calling GotListModes");
channel.setHasGotListModes(true);
callChannelGotListModes(channel);
}
}
}
/**
* What does this IRCProcessor handle.
*
* @return String[] with the names of the tokens we handle.
*/
@Override
public String[] handles() {
return new String[]{"367", "368", /* Bans */
"344", "345", /* Reop list (ircnet) or bad words (euirc) */
"346", "347", /* Invite List */
"348", "349", /* Except/Exempt List */
"386", "387", /* Channel Owner List (swiftirc ) */
"388", "389", /* Protected User List (swiftirc) */
"940", "941", /* Censored words list */
"482", /* Permission Denied */
"__LISTMODE__" /* Sensible List Modes */
};
}
/**
* Callback to all objects implementing the ChannelGotListModes Callback.
*
* @see IChannelGotListModes
* @param cChannel Channel which the ListModes reply is for
* @return true if a method was called, false otherwise
*/
protected boolean callChannelGotListModes(ChannelInfo cChannel) {
return getCallbackManager().getCallbackType("OnChannelGotListModes").call(cChannel);
}
/**
* Create a new instance of the IRCProcessor Object.
*
* @param parser IRCParser That owns this IRCProcessor
* @param manager ProcessingManager that is in charge of this IRCProcessor
*/
protected ProcessListModes (IRCParser parser, ProcessingManager manager) { super(parser, manager); }
}
| true | true | public void process(String sParam, String[] token) {
ChannelInfo channel = getChannelInfo(token[3]);
String thisIRCD = myParser.getIRCD(true).toLowerCase();
String item = "";
String owner = "";
byte tokenStart = 4; // Where do the relevent tokens start?
boolean isCleverMode = false;
long time = 0;
char mode = 'b';
boolean isItem = true; // true if item listing, false if "end of .." item
if (channel == null) { return; }
if (sParam.equals("367") || sParam.equals("368")) {
// Ban List/Item.
// (Also used for +d and +q on hyperion... -_-)
mode = 'b';
isItem = sParam.equals("367");
} else if (sParam.equals("348") || sParam.equals("349")) {
// Except / Exempt List etc
mode = 'e';
isItem = sParam.equals("348");
} else if (sParam.equals("346") || sParam.equals("347")) {
// Invite List
mode = 'I';
isItem = sParam.equals("346");
} else if (sParam.equals("940") || sParam.equals("941")) {
// Censored words List
mode = 'g';
isItem = sParam.equals("941");
} else if (sParam.equals("344") || sParam.equals("345")) {
// Reop List, or bad words list, or quiet list. god damn.
if (thisIRCD.equals("euircd")) {
mode = 'w';
} else if (thisIRCD.equals("oftc-hybrid")) {
mode = 'q';
} else {
mode = 'R';
}
isItem = sParam.equals("344");
} else if (thisIRCD.equals("swiftirc") && (sParam.equals("386") || sParam.equals("387"))) {
// Channel Owner list
mode = 'q';
isItem = sParam.equals("387");
} else if (thisIRCD.equals("swiftirc") && (sParam.equals("388") || sParam.equals("389"))) {
// Protected User list
mode = 'a';
isItem = sParam.equals("389");
} else if (sParam.equals(myParser.h005Info.get("LISTMODE")) || sParam.equals(myParser.h005Info.get("LISTMODEEND"))) {
// Support for potential future decent mode listing in the protocol
//
// See my proposal: http://shane.dmdirc.com/listmodes.php
mode = token[4].charAt(0);
isItem = sParam.equals(myParser.h005Info.get("LISTMODE"));
tokenStart = 5;
isCleverMode = true;
}
final Queue<Character> listModeQueue = channel.getListModeQueue();
if (!isCleverMode && listModeQueue != null) {
if (sParam.equals("482")) {
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "Dropped LMQ mode "+listModeQueue.poll());
return;
} else {
if (listModeQueue.peek() != null) {
Character oldMode = mode;
mode = listModeQueue.peek();
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "LMQ says this is "+mode);
boolean error = true;
// b or q are given in the same list, d is separate.
// b and q remove each other from the LMQ.
//
// Only raise an LMQ error if the lmqmode isn't one of bdq if the
// guess is one of bdq
if ((thisIRCD.equals("hyperion") || thisIRCD.equals("dancer")) && (mode == 'b' || mode == 'q' || mode == 'd')) {
LinkedList<Character> lmq = (LinkedList<Character>)listModeQueue;
if (mode == 'b') {
error = !(oldMode == 'q' || oldMode == 'd');
lmq.remove((Character)'q');
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "Dropping q from list");
} else if (mode == 'q') {
error = !(oldMode == 'b' || oldMode == 'd');
lmq.remove((Character)'b');
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "Dropping b from list");
} else if (mode == 'd') {
error = !(oldMode == 'b' || oldMode == 'q');
}
}
if (oldMode != mode && error) {
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "LMQ disagrees with guess. LMQ: "+mode+" Guess: "+oldMode);
myParser.callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "LMQ disagrees with guess. LMQ: "+mode+" Guess: "+oldMode, myParser.getLastLine()));
}
if (!isItem) {
listModeQueue.poll();
}
}
}
}
if (isItem) {
if ((!isCleverMode) && listModeQueue == null && (thisIRCD.equals("hyperion") || thisIRCD.equals("dancer")) && token.length > 4 && mode == 'b') {
// Assume mode is a 'd' mode
mode = 'd';
// Now work out if its not (or attempt to.)
int identstart = token[tokenStart].indexOf('!');
int hoststart = token[tokenStart].indexOf('@');
// Check that ! and @ are both in the string - as required by +b and +q
if ((identstart >= 0) && (identstart < hoststart)) {
if (thisIRCD.equals("hyperion") && token[tokenStart].charAt(0) == '%') { mode = 'q'; }
else { mode = 'b'; }
}
} // End Hyperian stupidness of using the same numeric for 3 different things..
if (!channel.getAddState(mode)) {
callDebugInfo(IRCParser.DEBUG_INFO, "New List Mode Batch ("+mode+"): Clearing!");
final List<ChannelListModeItem> list = channel.getListModeParam(mode);
if (list == null) {
myParser.callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got list mode: '"+mode+"' - but channel object doesn't agree.", myParser.getLastLine()));
} else {
list.clear();
if ((thisIRCD.equals("hyperion") || thisIRCD.equals("dancer")) && (mode == 'b' || mode == 'q')) {
// Also clear the other list if b or q.
final Character otherMode = (mode == 'b') ? 'q' : 'b';
if (!channel.getAddState(otherMode)) {
callDebugInfo(IRCParser.DEBUG_INFO, "New List Mode Batch ("+mode+"): Clearing!");
final List<ChannelListModeItem> otherList = channel.getListModeParam(otherMode);
if (otherList == null) {
myParser.callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got list mode: '"+otherMode+"' - but channel object doesn't agree.", myParser.getLastLine()));
} else {
otherList.clear();
}
}
}
}
channel.setAddState(mode, true);
}
if (token.length > (tokenStart+2)) {
try { time = Long.parseLong(token[tokenStart+2]); } catch (NumberFormatException e) { time = 0; }
}
if (token.length > (tokenStart+1)) { owner = token[tokenStart+1]; }
if (token.length > tokenStart) { item = token[tokenStart]; }
if (!item.isEmpty()) {
ChannelListModeItem clmi = new ChannelListModeItem(item, owner, time);
callDebugInfo(IRCParser.DEBUG_INFO, "List Mode: %c [%s/%s/%d]",mode, item, owner, time);
channel.setListModeParam(mode, clmi, true);
}
} else {
| public void process(String sParam, String[] token) {
ChannelInfo channel = getChannelInfo(token[3]);
String thisIRCD = myParser.getIRCD(true).toLowerCase();
String item = "";
String owner = "";
byte tokenStart = 4; // Where do the relevent tokens start?
boolean isCleverMode = false;
long time = 0;
char mode = 'b';
boolean isItem = true; // true if item listing, false if "end of .." item
if (channel == null) { return; }
if (sParam.equals("367") || sParam.equals("368")) {
// Ban List/Item.
// (Also used for +d and +q on hyperion... -_-)
mode = 'b';
isItem = sParam.equals("367");
} else if (sParam.equals("348") || sParam.equals("349")) {
// Except / Exempt List etc
mode = 'e';
isItem = sParam.equals("348");
} else if (sParam.equals("346") || sParam.equals("347")) {
// Invite List
mode = 'I';
isItem = sParam.equals("346");
} else if (sParam.equals("940") || sParam.equals("941")) {
// Censored words List
mode = 'g';
isItem = sParam.equals("941");
} else if (sParam.equals("344") || sParam.equals("345")) {
// Reop List, or bad words list, or quiet list. god damn.
if (thisIRCD.equals("euircd")) {
mode = 'w';
} else if (thisIRCD.equals("oftc-hybrid")) {
mode = 'q';
} else {
mode = 'R';
}
isItem = sParam.equals("344");
} else if (thisIRCD.equals("swiftirc") && (sParam.equals("386") || sParam.equals("387"))) {
// Channel Owner list
mode = 'q';
isItem = sParam.equals("387");
} else if (thisIRCD.equals("swiftirc") && (sParam.equals("388") || sParam.equals("389"))) {
// Protected User list
mode = 'a';
isItem = sParam.equals("389");
} else if (sParam.equals(myParser.h005Info.get("LISTMODE")) || sParam.equals(myParser.h005Info.get("LISTMODEEND"))) {
// Support for potential future decent mode listing in the protocol
//
// See my proposal: http://shane.dmdirc.com/listmodes.php
mode = token[4].charAt(0);
isItem = sParam.equals(myParser.h005Info.get("LISTMODE"));
tokenStart = 5;
isCleverMode = true;
}
final Queue<Character> listModeQueue = channel.getListModeQueue();
if (!isCleverMode && listModeQueue != null) {
if (sParam.equals("482")) {
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "Dropped LMQ mode "+listModeQueue.poll());
return;
} else {
if (listModeQueue.peek() != null) {
Character oldMode = mode;
mode = listModeQueue.peek();
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "LMQ says this is "+mode);
boolean error = true;
// b or q are given in the same list, d is separate.
// b and q remove each other from the LMQ.
//
// Only raise an LMQ error if the lmqmode isn't one of bdq if the
// guess is one of bdq
if ((thisIRCD.equals("hyperion") || thisIRCD.equals("dancer")) && (mode == 'b' || mode == 'q' || mode == 'd')) {
LinkedList<Character> lmq = (LinkedList<Character>)listModeQueue;
if (mode == 'b') {
error = !(oldMode == 'q' || oldMode == 'd');
lmq.remove((Character)'q');
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "Dropping q from list");
} else if (mode == 'q') {
error = !(oldMode == 'b' || oldMode == 'd');
lmq.remove((Character)'b');
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "Dropping b from list");
} else if (mode == 'd') {
error = !(oldMode == 'b' || oldMode == 'q');
}
}
if (oldMode != mode && error) {
myParser.callDebugInfo(IRCParser.DEBUG_LMQ, "LMQ disagrees with guess. LMQ: "+mode+" Guess: "+oldMode);
// myParser.callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "LMQ disagrees with guess. LMQ: "+mode+" Guess: "+oldMode, myParser.getLastLine()));
}
if (!isItem) {
listModeQueue.poll();
}
}
}
}
if (isItem) {
if ((!isCleverMode) && listModeQueue == null && (thisIRCD.equals("hyperion") || thisIRCD.equals("dancer")) && token.length > 4 && mode == 'b') {
// Assume mode is a 'd' mode
mode = 'd';
// Now work out if its not (or attempt to.)
int identstart = token[tokenStart].indexOf('!');
int hoststart = token[tokenStart].indexOf('@');
// Check that ! and @ are both in the string - as required by +b and +q
if ((identstart >= 0) && (identstart < hoststart)) {
if (thisIRCD.equals("hyperion") && token[tokenStart].charAt(0) == '%') { mode = 'q'; }
else { mode = 'b'; }
}
} // End Hyperian stupidness of using the same numeric for 3 different things..
if (!channel.getAddState(mode)) {
callDebugInfo(IRCParser.DEBUG_INFO, "New List Mode Batch ("+mode+"): Clearing!");
final List<ChannelListModeItem> list = channel.getListModeParam(mode);
if (list == null) {
myParser.callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got list mode: '"+mode+"' - but channel object doesn't agree.", myParser.getLastLine()));
} else {
list.clear();
if ((thisIRCD.equals("hyperion") || thisIRCD.equals("dancer")) && (mode == 'b' || mode == 'q')) {
// Also clear the other list if b or q.
final Character otherMode = (mode == 'b') ? 'q' : 'b';
if (!channel.getAddState(otherMode)) {
callDebugInfo(IRCParser.DEBUG_INFO, "New List Mode Batch ("+mode+"): Clearing!");
final List<ChannelListModeItem> otherList = channel.getListModeParam(otherMode);
if (otherList == null) {
myParser.callErrorInfo(new ParserError(ParserError.ERROR_WARNING, "Got list mode: '"+otherMode+"' - but channel object doesn't agree.", myParser.getLastLine()));
} else {
otherList.clear();
}
}
}
}
channel.setAddState(mode, true);
}
if (token.length > (tokenStart+2)) {
try { time = Long.parseLong(token[tokenStart+2]); } catch (NumberFormatException e) { time = 0; }
}
if (token.length > (tokenStart+1)) { owner = token[tokenStart+1]; }
if (token.length > tokenStart) { item = token[tokenStart]; }
if (!item.isEmpty()) {
ChannelListModeItem clmi = new ChannelListModeItem(item, owner, time);
callDebugInfo(IRCParser.DEBUG_INFO, "List Mode: %c [%s/%s/%d]",mode, item, owner, time);
channel.setListModeParam(mode, clmi, true);
}
} else {
|
diff --git a/openejb2/modules/openejb-core/src/main/java/org/apache/openejb/corba/NameService.java b/openejb2/modules/openejb-core/src/main/java/org/apache/openejb/corba/NameService.java
index 99279d2ce..ed55b8f8c 100644
--- a/openejb2/modules/openejb-core/src/main/java/org/apache/openejb/corba/NameService.java
+++ b/openejb2/modules/openejb-core/src/main/java/org/apache/openejb/corba/NameService.java
@@ -1,186 +1,186 @@
/**
* 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.openejb.corba;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.geronimo.gbean.GBeanLifecycle;
import org.apache.geronimo.system.serverinfo.ServerInfo;
import org.apache.openejb.corba.security.config.ConfigAdapter;
import java.net.InetSocketAddress;
/**
* Starts the openejb transient cos naming service.
* <p/>
* <gbean name="NameServer" class="org.apache.openejb.corba.NameService">
* <reference name="ServerInfo">
* <reference name="ConfigAdapter">
* <attribute name="port">2809</attribute>
* <attribute name="host">localhost</attribute>
* </gbean>
*
* @version $Revision$ $Date$
*/
public class NameService implements GBeanLifecycle {
private static final Log log = LogFactory.getLog(NameService.class);
// the ORB configurator
private final ConfigAdapter config;
// the name service instance
private Object service;
// the name service listening port
private final int port;
// the published port name (defaults to "localhost").
private String host;
// indicates whether we start and host this server locally.
private boolean localServer;
protected NameService() {
service = null;
config = null;
port = -1;
host = "localhost";
localServer = true;
}
/**
* GBean constructor to create a NameService instance.
*
* @param serverInfo The dependent ServerInfo. This value is not used,
* but is in the constructor to create an ordering
* dependency.
* @param config The ORB ConfigAdapter used to create the real
* NameService instance.
* @param host The advertised host name.
* @param port The listener port.
*
* @exception Exception
*/
public NameService(ServerInfo serverInfo, ConfigAdapter config, String host, int port) throws Exception {
this.host = host;
this.port = port;
this.config = config;
localServer = true;
service = null;
// if not specified, our default host is "localhost".
- if (host == null) {
- host = "localhost";
+ if (this.host == null) {
+ this.host = "localhost";
}
}
/**
* Retrieve the host name for this NameService instance.
*
* @return The String host name.
*/
public String getHost() {
return host;
}
/**
* Get the port information for this NameService instance.
*
* @return The configured name service listener port.
*/
public int getPort() {
return port;
}
/**
* Get the "local" value for this server. If true, an
* in-process NameService instance will be created when
* the service is started. If false, this is an
* indirect reference to a NameService (possibly located
* elsewhere).
*
* @return The current localServer value. The default is
* true.
*/
public boolean getLocal() {
return localServer;
}
/**
* Get the "local" value for this server. If true, an
* in-process NameService instance will be created when
* the service is started. If false, this is an
* indirect reference to a NameService (possibly located
* elsewhere).
*
* @param l The new local setting.
*/
public void setLocal(boolean l) {
localServer = l;
}
/**
* Get the InetSocketAddress for this NameService.
*
* @return An InetSocketAddress containing the host and port
* information.
*/
public InetSocketAddress getAddress() {
return new InetSocketAddress(host, getPort());
}
/**
* Return the NameService locator as a URI (generally
* using the corbaloc:: protocol);
*
* @return The URI in String format.
*/
public String getURI() {
return "corbaloc::" + host + ":" + port + "/NameService";
}
/**
* Start the NameService instance. If the local
* setting is true, will launch an appropriate
* in-process name server instance.
*
* @exception Exception
*/
public void doStart() throws Exception {
if (localServer) {
service = config.createNameService(host, port);
log.debug("Started transient CORBA name service on port " + port);
}
}
/**
* Stop the name server. Only has an effect if doStart()
* launched an NameServer instance.
*
* @exception Exception
*/
public void doStop() throws Exception {
if (service != null) {
config.destroyNameService(service);
log.debug("Stopped transient CORBA name service on port " + port);
}
}
public void doFail() {
if (service != null) {
config.destroyNameService(service);
log.warn("Failed transient CORBA name service on port " + port);
}
}
}
| true | true | public NameService(ServerInfo serverInfo, ConfigAdapter config, String host, int port) throws Exception {
this.host = host;
this.port = port;
this.config = config;
localServer = true;
service = null;
// if not specified, our default host is "localhost".
if (host == null) {
host = "localhost";
}
}
| public NameService(ServerInfo serverInfo, ConfigAdapter config, String host, int port) throws Exception {
this.host = host;
this.port = port;
this.config = config;
localServer = true;
service = null;
// if not specified, our default host is "localhost".
if (this.host == null) {
this.host = "localhost";
}
}
|
diff --git a/src/com/mycompany/reservationsystem/peer/client/booking/BookingClientWorker.java b/src/com/mycompany/reservationsystem/peer/client/booking/BookingClientWorker.java
index 933edf1..106439c 100644
--- a/src/com/mycompany/reservationsystem/peer/client/booking/BookingClientWorker.java
+++ b/src/com/mycompany/reservationsystem/peer/client/booking/BookingClientWorker.java
@@ -1,170 +1,171 @@
package com.mycompany.reservationsystem.peer.client.booking;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import com.mycompany.reservationsystem.peer.communication.COMMUNICATION_MESSAGES;
import com.mycompany.reservationsystem.peer.data.FlightBooking;
import com.mycompany.reservationsystem.peer.data.FlightBookingTable;
import com.mycompany.reservationsystem.peer.data.PeerTable;
public class BookingClientWorker extends Thread{
private static final int PORT_NUMBER = 50001;
private Socket requestSocket;
private ObjectOutputStream out;
private ObjectInputStream in;
private String ipAddress;
private boolean isFinished;
public BookingClientWorker(String ipAddress){
this.ipAddress = ipAddress;
this.isFinished = false;
}
public void run(){
try{
requestSocket = new Socket(this.ipAddress, PORT_NUMBER);
out = new ObjectOutputStream(requestSocket.getOutputStream());
out.flush();
in = new ObjectInputStream(requestSocket.getInputStream());
while(isFinished == false){
sendMessage(COMMUNICATION_MESSAGES.TRANSACTION_REQUEST);
String message = (String) in.readObject();
+ System.out.println("Got message " + message);
if(message.startsWith(COMMUNICATION_MESSAGES.TRANSACTION_RESPONSE.toString())){
/*
* Message with no booking shows that server has given all bookings,
* server will return TRANSACTION_RESPONSE: (21 chars)
*/
System.out.println("Got message " + message);
if(message.length() != 21){ //Got a booking
String dataPartOfMessage = message.substring(message.indexOf(":")+1, message.length());
FlightBooking booking = parseBookingMessage(dataPartOfMessage);
FlightBookingTable flightTable = FlightBookingTable.getInstance();
flightTable.connect();
if(flightTable.findFlightBooking(booking.getTransactionTime(), booking.getEmail()) == null){
flightTable.addBooking(booking);
}
flightTable.disconnect();
}
else{ //Got blank booking
isFinished = true;
}
}
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
PeerTable peerTable = PeerTable.getInstance();
peerTable.connect();
peerTable.logPeerInactive(ipAddress); //Log that this peer ip address is inactive
peerTable.disconnect();
}
catch(IOException ioException){
ioException.printStackTrace();
PeerTable peerTable = PeerTable.getInstance();
peerTable.connect();
peerTable.logPeerInactive(ipAddress); //Log that this peer ip address is inactive
peerTable.disconnect();
}
finally{
//Closing connection
try{
in.close();
out.close();
requestSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
PeerTable peerTable = PeerTable.getInstance();
peerTable.connect();
peerTable.logPeerInactive(ipAddress); //Log that this peer ip address is inactive
peerTable.disconnect();
}
}
}
private void sendMessage(COMMUNICATION_MESSAGES communicationMessage){
String message = "";
if(communicationMessage.toString().equals(COMMUNICATION_MESSAGES.TRANSACTION_REQUEST.toString())){
message += COMMUNICATION_MESSAGES.TRANSACTION_REQUEST.toString();
}
try{
out.writeObject(message);
out.flush();
}
catch(IOException ioException){
ioException.printStackTrace();
PeerTable peerTable = PeerTable.getInstance();
peerTable.connect();
peerTable.logPeerInactive(ipAddress); //Log that this peer ip address is inactive
peerTable.disconnect();
}
}
//1351858413975,[email protected],31/08/2012@1200,NA,0,1,0,REQUESTED,
//TODO substring could be wrong for all data
private FlightBooking parseBookingMessage(String dataPartOfMessage){
FlightBooking booking = new FlightBooking();
String transactionEpoch = dataPartOfMessage.substring(0,dataPartOfMessage.indexOf(","));
dataPartOfMessage = dataPartOfMessage.substring(dataPartOfMessage.indexOf(",")+1, dataPartOfMessage.length());
String email = dataPartOfMessage.substring(0,dataPartOfMessage.indexOf(","));
dataPartOfMessage = dataPartOfMessage.substring(dataPartOfMessage.indexOf(",")+1, dataPartOfMessage.length());
String flightToCityAt = dataPartOfMessage.substring(0,dataPartOfMessage.indexOf(","));
dataPartOfMessage = dataPartOfMessage.substring(dataPartOfMessage.indexOf(",")+1, dataPartOfMessage.length());
String flightToCampAt = dataPartOfMessage.substring(0,dataPartOfMessage.indexOf(","));
dataPartOfMessage = dataPartOfMessage.substring(dataPartOfMessage.indexOf(",")+1, dataPartOfMessage.length());
String fromCity = dataPartOfMessage.substring(0,dataPartOfMessage.indexOf(","));
dataPartOfMessage = dataPartOfMessage.substring(dataPartOfMessage.indexOf(",")+1, dataPartOfMessage.length());
String fromCamp = dataPartOfMessage.substring(0,dataPartOfMessage.indexOf(","));
dataPartOfMessage = dataPartOfMessage.substring(dataPartOfMessage.indexOf(",")+1, dataPartOfMessage.length());
String price = dataPartOfMessage.substring(0,dataPartOfMessage.indexOf(","));
dataPartOfMessage = dataPartOfMessage.substring(dataPartOfMessage.indexOf(",")+1, dataPartOfMessage.length());
String state = dataPartOfMessage.substring(0,dataPartOfMessage.indexOf(","));
System.out.println(transactionEpoch + " " + email);
booking.setTransactionTime(Long.parseLong(transactionEpoch));
booking.setEmail(email);
booking.setFlightToCityAt(flightToCityAt);
booking.setFlightToCampAt(flightToCampAt);
booking.setPrice(Double.parseDouble(price));
if(Integer.parseInt(fromCity) == 1){
booking.setFromCity(true);
}
else{
booking.setFromCity(false);
}
if(Integer.parseInt(fromCamp) == 1){
booking.setFromCamp(true);
}
else{
booking.setFromCamp(false);
}
if(state.equals(FlightBooking.STATE.REQUESTED.toString())){
booking.setState(FlightBooking.STATE.REQUESTED);
}
else if(state.equals(FlightBooking.STATE.CONFIRMED.toString())){
booking.setState(FlightBooking.STATE.CONFIRMED);
}
else if(state.equals(FlightBooking.STATE.CANCEL.toString())){
booking.setState(FlightBooking.STATE.CANCEL);
}
else if(state.equals(FlightBooking.STATE.CANCELED.toString())){
booking.setState(FlightBooking.STATE.CANCELED);
}
return booking;
}
}
| true | true | public void run(){
try{
requestSocket = new Socket(this.ipAddress, PORT_NUMBER);
out = new ObjectOutputStream(requestSocket.getOutputStream());
out.flush();
in = new ObjectInputStream(requestSocket.getInputStream());
while(isFinished == false){
sendMessage(COMMUNICATION_MESSAGES.TRANSACTION_REQUEST);
String message = (String) in.readObject();
if(message.startsWith(COMMUNICATION_MESSAGES.TRANSACTION_RESPONSE.toString())){
/*
* Message with no booking shows that server has given all bookings,
* server will return TRANSACTION_RESPONSE: (21 chars)
*/
System.out.println("Got message " + message);
if(message.length() != 21){ //Got a booking
String dataPartOfMessage = message.substring(message.indexOf(":")+1, message.length());
FlightBooking booking = parseBookingMessage(dataPartOfMessage);
FlightBookingTable flightTable = FlightBookingTable.getInstance();
flightTable.connect();
if(flightTable.findFlightBooking(booking.getTransactionTime(), booking.getEmail()) == null){
flightTable.addBooking(booking);
}
flightTable.disconnect();
}
else{ //Got blank booking
isFinished = true;
}
}
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
PeerTable peerTable = PeerTable.getInstance();
peerTable.connect();
peerTable.logPeerInactive(ipAddress); //Log that this peer ip address is inactive
peerTable.disconnect();
}
catch(IOException ioException){
ioException.printStackTrace();
PeerTable peerTable = PeerTable.getInstance();
peerTable.connect();
peerTable.logPeerInactive(ipAddress); //Log that this peer ip address is inactive
peerTable.disconnect();
}
finally{
//Closing connection
try{
in.close();
out.close();
requestSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
PeerTable peerTable = PeerTable.getInstance();
peerTable.connect();
peerTable.logPeerInactive(ipAddress); //Log that this peer ip address is inactive
peerTable.disconnect();
}
}
}
| public void run(){
try{
requestSocket = new Socket(this.ipAddress, PORT_NUMBER);
out = new ObjectOutputStream(requestSocket.getOutputStream());
out.flush();
in = new ObjectInputStream(requestSocket.getInputStream());
while(isFinished == false){
sendMessage(COMMUNICATION_MESSAGES.TRANSACTION_REQUEST);
String message = (String) in.readObject();
System.out.println("Got message " + message);
if(message.startsWith(COMMUNICATION_MESSAGES.TRANSACTION_RESPONSE.toString())){
/*
* Message with no booking shows that server has given all bookings,
* server will return TRANSACTION_RESPONSE: (21 chars)
*/
System.out.println("Got message " + message);
if(message.length() != 21){ //Got a booking
String dataPartOfMessage = message.substring(message.indexOf(":")+1, message.length());
FlightBooking booking = parseBookingMessage(dataPartOfMessage);
FlightBookingTable flightTable = FlightBookingTable.getInstance();
flightTable.connect();
if(flightTable.findFlightBooking(booking.getTransactionTime(), booking.getEmail()) == null){
flightTable.addBooking(booking);
}
flightTable.disconnect();
}
else{ //Got blank booking
isFinished = true;
}
}
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
PeerTable peerTable = PeerTable.getInstance();
peerTable.connect();
peerTable.logPeerInactive(ipAddress); //Log that this peer ip address is inactive
peerTable.disconnect();
}
catch(IOException ioException){
ioException.printStackTrace();
PeerTable peerTable = PeerTable.getInstance();
peerTable.connect();
peerTable.logPeerInactive(ipAddress); //Log that this peer ip address is inactive
peerTable.disconnect();
}
finally{
//Closing connection
try{
in.close();
out.close();
requestSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
PeerTable peerTable = PeerTable.getInstance();
peerTable.connect();
peerTable.logPeerInactive(ipAddress); //Log that this peer ip address is inactive
peerTable.disconnect();
}
}
}
|
diff --git a/src/jpcsp/graphics/VideoEngine.java b/src/jpcsp/graphics/VideoEngine.java
index 5abe47b8..e32d69b0 100644
--- a/src/jpcsp/graphics/VideoEngine.java
+++ b/src/jpcsp/graphics/VideoEngine.java
@@ -1,2413 +1,2418 @@
/*
Parts based on soywiz's pspemulator.
This file is part of jpcsp.
Jpcsp 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.
Jpcsp 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 Jpcsp. If not, see <http://www.gnu.org/licenses/>.
*/
package jpcsp.graphics;
import static jpcsp.graphics.GeCommands.*;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import java.util.Iterator;
import javax.media.opengl.GL;
import javax.media.opengl.GLException;
import jpcsp.Emulator;
import jpcsp.Memory;
import jpcsp.MemoryMap;
import jpcsp.HLE.pspdisplay;
import jpcsp.util.Utilities;
import org.apache.log4j.Logger;
public class VideoEngine {
private static VideoEngine instance;
private GL gl;
public static Logger log = Logger.getLogger("ge");
public static final boolean isDebugMode = true;
private static GeCommands helper;
private VertexInfo vinfo = new VertexInfo();
private static final char SPACE = ' ';
// TODO these currently here for testing only
private int fbp, fbw; // frame buffer pointer and width
private int zbp, zbw; // depth buffer pointer and width
private int psm; // pixel format
private boolean proj_upload_start;
private int proj_upload_x;
private int proj_upload_y;
private float[] proj_matrix = new float[4 * 4];
private float[] proj_uploaded_matrix = new float[4 * 4];
private boolean texture_upload_start;
private int texture_upload_x;
private int texture_upload_y;
private float[] texture_matrix = new float[4 * 4];
private float[] texture_uploaded_matrix = new float[4 * 4];
private boolean model_upload_start;
private int model_upload_x;
private int model_upload_y;
private float[] model_matrix = new float[4 * 4];
private float[] model_uploaded_matrix = new float[4 * 4];
private boolean view_upload_start;
private int view_upload_x;
private int view_upload_y;
private float[] view_matrix = new float[4 * 4];
private float[] view_uploaded_matrix = new float[4 * 4];
private boolean bone_upload_start;
private int bone_upload_x;
private int bone_upload_y;
private int bone_matrix_offset;
private float[] bone_matrix = new float[4 * 3];
private float[][] bone_uploaded_matrix = new float[8][4 * 3];
private float[] morph_weight = new float[8];
private float[] tex_envmap_matrix = new float[4*4];
private float[][] light_pos = new float[4][4];
int[] light_type = new int[4];
float[] fog_color = new float[4];
float fog_far = 0.0f,fog_dist = 0.0f;
private float nearZ = 0.0f,farZ = 0.0f;
int mat_flags = 0;
float[] mat_ambient = new float[4];
float[] mat_diffuse = new float[4];
float[] mat_specular = new float[4];
float[] mat_emissive = new float[4];
int texture_storage, texture_num_mip_maps;
boolean texture_swizzle;
int texture_base_pointer0, texture_width0, texture_height0;
int texture_buffer_width0;
int tex_min_filter = GL.GL_NEAREST;
int tex_mag_filter = GL.GL_NEAREST;
float tex_translate_x = 0.f, tex_translate_y = 0.f;
float tex_scale_x = 1.f, tex_scale_y = 1.f;
float[] tex_env_color = new float[4];
private int tex_clut_addr;
private int tex_clut_num_blocks;
private int tex_clut_mode, tex_clut_shift, tex_clut_mask, tex_clut_start;
private int transform_mode;
private int textureTx_sourceAddress;
private int textureTx_sourceLineWidth;
private int textureTx_destinationAddress;
private int textureTx_destinationLineWidth;
private int textureTx_width;
private int textureTx_height;
private int textureTx_sx;
private int textureTx_sy;
private int textureTx_dx;
private int textureTx_dy;
private int textureTx_pixelSize;
// opengl needed information/buffers
int[] gl_texture_id = new int[1];
int[] tmp_texture_buffer32 = new int[1024*1024];
short[] tmp_texture_buffer16 = new short[1024*1024];
int tex_map_mode = TMAP_TEXTURE_MAP_MODE_TEXTURE_COORDIATES_UV;
private boolean listHasEnded;
private boolean listHasFinished;
private DisplayList actualList; // The currently executing list
private int clearFlags;
private static void log(String msg) {
log.debug(msg);
/*if (isDebugMode) {
System.out.println("sceGe DEBUG > " + msg);
}*/
}
public static VideoEngine getEngine(GL gl, boolean fullScreen, boolean hardwareAccelerate) {
VideoEngine engine = getEngine();
engine.setFullScreenShoot(fullScreen);
engine.setHardwareAcc(hardwareAccelerate);
engine.gl = gl;
return engine;
}
private static VideoEngine getEngine() {
if (instance == null) {
instance = new VideoEngine();
helper = new GeCommands();
}
return instance;
}
private VideoEngine() {
model_matrix[0] = model_matrix[5] = model_matrix[10] = model_matrix[15] = 1.f;
view_matrix[0] = view_matrix[5] = view_matrix[10] = view_matrix[15] = 1.f;
tex_envmap_matrix[0] = tex_envmap_matrix[5] = tex_envmap_matrix[10] = tex_envmap_matrix[15] = 1.f;
light_pos[0][3] = light_pos[1][3] = light_pos[2][3] = light_pos[3][3] = 1.f;
}
/** call from GL thread
* @return true if an update was made
*/
public boolean update() {
//System.err.println("update start");
// Don't draw anything until we get sync signal
if (!jpcsp.HLE.pspge.get_instance().waitingForSync)
return false;
boolean updated = false;
DisplayList.Lock();
Iterator<DisplayList> it = DisplayList.iterator();
while(it.hasNext() && !Emulator.pause) {
DisplayList list = it.next();
if (list.status == DisplayList.QUEUED && list.HasFinish()) {
executeList(list);
if (list.status == DisplayList.DRAWING_DONE) {
updated = true;
} else if (list.status == DisplayList.DONE) {
it.remove();
updated = true;
}
}
}
DisplayList.Unlock();
if (updated)
jpcsp.HLE.pspge.get_instance().syncDone = true;
//System.err.println("update done");
return updated;
}
// call from GL thread
private void executeList(DisplayList list) {
actualList = list;
listHasEnded = false;
listHasFinished = false;
log("executeList id " + list.id);
Memory mem = Memory.getInstance();
while (!listHasEnded && !listHasFinished &&
actualList.pc != actualList.stallAddress && !Emulator.pause) {
int ins = mem.read32(actualList.pc);
actualList.pc += 4;
executeCommand(ins);
}
if (actualList.pc == actualList.stallAddress) {
actualList.status = DisplayList.STALL_REACHED;
log("list " + actualList.id + " stalled at " + String.format("%08x", actualList.stallAddress));
}
if (listHasFinished) {
// List can still be updated
// TODO we should probably recycle lists if they never reach the end state
actualList.status = DisplayList.DRAWING_DONE;
}
if (listHasEnded) {
// Now we can remove the list context
actualList.status = DisplayList.DONE;
}
}
private static int command(int instruction) {
return (instruction >>> 24);
}
private static int intArgument(int instruction) {
return (instruction & 0x00FFFFFF);
}
private static float floatArgument(int instruction) {
return Float.intBitsToFloat(instruction << 8);
}
private int getStencilOp (int pspOP) {
switch (pspOP) {
case SOP_KEEP_STENCIL_VALUE:
return GL.GL_KEEP;
case SOP_ZERO_STENCIL_VALUE:
return GL.GL_ZERO;
case SOP_REPLACE_STENCIL_VALUE:
return GL.GL_REPLACE;
case SOP_INVERT_STENCIL_VALUE:
return GL.GL_INVERT;
case SOP_INCREMENT_STENCIL_VALUE:
return GL.GL_INCR;
case SOP_DECREMENT_STENCIL_VALUE:
return GL.GL_DECR;
}
log ("UNKNOWN stencil op "+ pspOP);
return GL.GL_KEEP;
}
//hack based on pspplayer
private int getBlendSrc (int pspSrc)
{
switch(pspSrc)
{
case 0x0:
return GL.GL_DST_COLOR;
case 0x1:
return GL.GL_ONE_MINUS_DST_COLOR;
case 0x2:
return GL.GL_SRC_ALPHA;
case 0x3:
return GL.GL_ONE_MINUS_SRC_ALPHA;
case 0x4:
return GL.GL_DST_ALPHA;
case 0x5:
return GL.GL_ONE_MINUS_DST_ALPHA;
case 0x6:
return GL.GL_SRC_ALPHA;
case 0x7:
return GL.GL_ONE_MINUS_SRC_ALPHA;
case 0x8:
return GL.GL_DST_ALPHA;
case 0x9:
return GL.GL_ONE_MINUS_DST_ALPHA;
case 0xa:
return GL.GL_SRC_ALPHA;
}
VideoEngine.log.error("Unhandled alpha blend src used " + pspSrc);
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
return GL.GL_DST_COLOR;
}
private int getBlendOp (int pspOP) {
switch (pspOP) {
case ALPHA_SOURCE_COLOR:
return GL.GL_SRC_COLOR;
case ALPHA_ONE_MINUS_SOURCE_COLOR:
return GL.GL_ONE_MINUS_SRC_COLOR;
case ALPHA_SOURCE_ALPHA:
return GL.GL_SRC_ALPHA;
case ALPHA_ONE_MINUS_SOURCE_ALPHA:
return GL.GL_ONE_MINUS_SRC_ALPHA;
// hacks based on pspplayer
case ALPHA_DESTINATION_COLOR:
return GL.GL_DST_ALPHA;
case ALPHA_ONE_MINUS_DESTINATION_COLOR:
return GL.GL_ONE_MINUS_DST_ALPHA;
case ALPHA_DESTINATION_ALPHA:
return GL.GL_SRC_ALPHA;
case ALPHA_ONE_MINUS_DESTINATION_ALPHA:
return GL.GL_ONE_MINUS_SRC_ALPHA;
case 0x8:
return GL.GL_DST_ALPHA;
case 0x9:
return GL.GL_ONE_MINUS_DST_ALPHA;
case 0xa:
return GL.GL_ONE_MINUS_SRC_ALPHA;
}
VideoEngine.log.error("Unhandled alpha blend op used " + pspOP);
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
return GL.GL_ONE;
}
private int getClutIndex(int index) {
return ((tex_clut_start + index) >> tex_clut_shift) & tex_clut_mask;
}
// UnSwizzling based on pspplayer
// This won't work if you can't unswizzle inplace!
private Buffer unswizzleTexture32() {
int rowWidth = texture_width0 * 4;
int pitch = ( rowWidth - 16 ) / 4;
int bxc = rowWidth / 16;
int byc = texture_height0 / 8;
int src = 0, ydest = 0;
for( int by = 0; by < byc; by++ )
{
int xdest = ydest;
for( int bx = 0; bx < bxc; bx++ )
{
int dest = xdest;
for( int n = 0; n < 8; n++ )
{
tmp_texture_buffer32[dest] = tmp_texture_buffer32[src];
tmp_texture_buffer32[dest+1] = tmp_texture_buffer32[src + 1];
tmp_texture_buffer32[dest+2] = tmp_texture_buffer32[src + 2];
tmp_texture_buffer32[dest+3] = tmp_texture_buffer32[src + 3];
src += 4;
dest += pitch+4;
}
xdest += (16/4);
}
ydest += (rowWidth * 8)/4;
}
return IntBuffer.wrap(tmp_texture_buffer32);
}
// UnSwizzling based on pspplayer
private Buffer unswizzleTextureFromMemory(int texaddr, int bytesPerPixel) {
Memory mem = Memory.getInstance();
int rowWidth = texture_width0 * bytesPerPixel;
int pitch = ( rowWidth - 16 ) / 4;
int bxc = rowWidth / 16;
int byc = texture_height0 / 8;
int src = texaddr, ydest = 0;
for( int by = 0; by < byc; by++ )
{
int xdest = ydest;
for( int bx = 0; bx < bxc; bx++ )
{
int dest = xdest;
for( int n = 0; n < 8; n++ )
{
tmp_texture_buffer32[dest] = mem.read32(src);
tmp_texture_buffer32[dest+1] = mem.read32(src + 4);
tmp_texture_buffer32[dest+2] = mem.read32(src + 8);
tmp_texture_buffer32[dest+3] = mem.read32(src + 12);
src += 4*4;
dest += pitch+4;
}
xdest += (16/4);
}
ydest += (rowWidth * 8)/4;
}
return IntBuffer.wrap(tmp_texture_buffer32);
}
public void executeCommand(int instruction) {
int normalArgument = intArgument(instruction);
float floatArgument = floatArgument(instruction);
switch (command(instruction)) {
case END:
listHasEnded = true;
log(helper.getCommandString(END));
break;
case FINISH:
listHasFinished = true;
log(helper.getCommandString(FINISH));
break;
case BASE:
actualList.base = normalArgument << 8;
log(helper.getCommandString(BASE) + " " + String.format("%08x", actualList.base));
break;
case IADDR:
vinfo.ptr_index = actualList.base | normalArgument;
log(helper.getCommandString(IADDR) + " " + String.format("%08x", vinfo.ptr_index));
break;
case VADDR:
vinfo.ptr_vertex = actualList.base | normalArgument;
log(helper.getCommandString(VADDR) + " " + String.format("%08x", vinfo.ptr_vertex));
break;
case VTYPE:
vinfo.processType(normalArgument);
transform_mode = (normalArgument >> 23) & 0x1;
log(helper.getCommandString(VTYPE) + " " + vinfo.toString());
break;
case TME:
if (normalArgument != 0) {
gl.glEnable(GL.GL_TEXTURE_2D);
log("sceGuEnable(GU_TEXTURE_2D)");
} else {
gl.glDisable(GL.GL_TEXTURE_2D);
log("sceGuDisable(GU_TEXTURE_2D)");
}
break;
case VMS:
view_upload_start = true;
log("sceGumMatrixMode GU_VIEW");
break;
case VIEW:
if (view_upload_start) {
view_upload_x = 0;
view_upload_y = 0;
view_upload_start = false;
}
if (view_upload_y < 4) {
if (view_upload_x < 3) {
view_matrix[view_upload_x + view_upload_y * 4] = floatArgument;
view_upload_x++;
if (view_upload_x == 3) {
view_matrix[view_upload_x + view_upload_y * 4] = (view_upload_y == 3) ? 1.0f : 0.0f;
view_upload_x = 0;
view_upload_y++;
if (view_upload_y == 4) {
log("glLoadMatrixf", view_matrix);
for (int i = 0; i < 4*4; i++)
view_uploaded_matrix[i] = view_matrix[i];
}
}
}
}
break;
case MMS:
model_upload_start = true;
log("sceGumMatrixMode GU_MODEL");
break;
case MODEL:
if (model_upload_start) {
model_upload_x = 0;
model_upload_y = 0;
model_upload_start = false;
}
if (model_upload_y < 4) {
if (model_upload_x < 3) {
model_matrix[model_upload_x + model_upload_y * 4] = floatArgument;
model_upload_x++;
if (model_upload_x == 3) {
model_matrix[model_upload_x + model_upload_y * 4] = (model_upload_y == 3) ? 1.0f : 0.0f;
model_upload_x = 0;
model_upload_y++;
if (model_upload_y == 4) {
log("glLoadMatrixf", model_matrix);
for (int i = 0; i < 4*4; i++)
model_uploaded_matrix[i] = model_matrix[i];
}
}
}
}
break;
/*
* Light 0 attributes
*/
// Position
case LXP0:
light_pos[0][0] = floatArgument;
break;
case LYP0:
light_pos[0][1] = floatArgument;
break;
case LZP0:
light_pos[0][2] = floatArgument;
break;
// Color
case ALC0: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT0, GL.GL_AMBIENT, color, 0);
log("sceGuLightColor (GU_LIGHT0, GU_AMBIENT)");
break;
}
case DLC0: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, color, 0);
log("sceGuLightColor (GU_LIGHT0, GU_DIFFUSE)");
break;
}
case SLC0: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT0, GL.GL_SPECULAR, color, 0);
log("sceGuLightColor (GU_LIGHT0, GU_SPECULAR)");
break;
}
// Attenuation
case LCA0:
gl.glLightf(GL.GL_LIGHT0, GL.GL_CONSTANT_ATTENUATION, floatArgument);
break;
case LLA0:
gl.glLightf(GL.GL_LIGHT0, GL.GL_LINEAR_ATTENUATION, floatArgument);
break;
case LQA0:
gl.glLightf(GL.GL_LIGHT0, GL.GL_QUADRATIC_ATTENUATION, floatArgument);
break;
/*
* Light 1 attributes
*/
// Position
case LXP1:
light_pos[1][0] = floatArgument;
break;
case LYP1:
light_pos[1][1] = floatArgument;
break;
case LZP1:
light_pos[1][2] = floatArgument;
break;
// Color
case ALC1: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT1, GL.GL_AMBIENT, color, 0);
log("sceGuLightColor (GU_LIGHT1, GU_AMBIENT)");
break;
}
case DLC1: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT1, GL.GL_DIFFUSE, color, 0);
log("sceGuLightColor (GU_LIGHT1, GU_DIFFUSE)");
break;
}
case SLC1: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT1, GL.GL_SPECULAR, color, 0);
log("sceGuLightColor (GU_LIGHT1, GU_SPECULAR)");
break;
}
// Attenuation
case LCA1:
gl.glLightf(GL.GL_LIGHT1, GL.GL_CONSTANT_ATTENUATION, floatArgument);
break;
case LLA1:
gl.glLightf(GL.GL_LIGHT1, GL.GL_LINEAR_ATTENUATION, floatArgument);
break;
case LQA1:
gl.glLightf(GL.GL_LIGHT1, GL.GL_QUADRATIC_ATTENUATION, floatArgument);
break;
/*
* Light 2 attributes
*/
// Position
case LXP2:
light_pos[2][0] = floatArgument;
break;
case LYP2:
light_pos[2][1] = floatArgument;
break;
case LZP2:
light_pos[2][2] = floatArgument;
break;
// Color
case ALC2: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT2, GL.GL_AMBIENT, color, 0);
log("sceGuLightColor (GU_LIGHT2, GU_AMBIENT)");
break;
}
case DLC2: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT2, GL.GL_DIFFUSE, color, 0);
log("sceGuLightColor (GU_LIGHT2, GU_DIFFUSE)");
break;
}
case SLC2: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT2, GL.GL_SPECULAR, color, 0);
log("sceGuLightColor (GU_LIGHT2, GU_SPECULAR)");
break;
}
// Attenuation
case LCA2:
gl.glLightf(GL.GL_LIGHT2, GL.GL_CONSTANT_ATTENUATION, floatArgument);
break;
case LLA2:
gl.glLightf(GL.GL_LIGHT2, GL.GL_LINEAR_ATTENUATION, floatArgument);
break;
case LQA2:
gl.glLightf(GL.GL_LIGHT2, GL.GL_QUADRATIC_ATTENUATION, floatArgument);
break;
/*
* Light 3 attributes
*/
// Position
case LXP3:
light_pos[3][0] = floatArgument;
break;
case LYP3:
light_pos[3][1] = floatArgument;
break;
case LZP3:
light_pos[3][2] = floatArgument;
break;
// Color
case ALC3: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT3, GL.GL_AMBIENT, color, 0);
log("sceGuLightColor (GU_LIGHT3, GU_AMBIENT)");
break;
}
case DLC3: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT3, GL.GL_DIFFUSE, color, 0);
log("sceGuLightColor (GU_LIGHT3, GU_DIFFUSE)");
break;
}
case SLC3: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT3, GL.GL_SPECULAR, color, 0);
log("sceGuLightColor (GU_LIGHT3, GU_SPECULAR)");
break;
}
// Attenuation
case LCA3:
gl.glLightf(GL.GL_LIGHT3, GL.GL_CONSTANT_ATTENUATION, floatArgument);
break;
case LLA3:
gl.glLightf(GL.GL_LIGHT3, GL.GL_LINEAR_ATTENUATION, floatArgument);
break;
case LQA3:
gl.glLightf(GL.GL_LIGHT3, GL.GL_QUADRATIC_ATTENUATION, floatArgument);
break;
/*
* Light types
*/
case LT0: {
light_type[0] = normalArgument;
if (light_type[0] == LIGTH_DIRECTIONAL)
light_pos[0][3] = 0.f;
else
light_pos[0][3] = 1.f;
break;
}
case LT1: {
light_type[1] = normalArgument;
if (light_type[1] == LIGTH_DIRECTIONAL)
light_pos[1][3] = 0.f;
else
light_pos[1][3] = 1.f;
break;
}
case LT2: {
light_type[2] = normalArgument;
if (light_type[2] == LIGTH_DIRECTIONAL)
light_pos[2][3] = 0.f;
else
light_pos[2][3] = 1.f;
break;
}
case LT3: {
light_type[3] = normalArgument;
if (light_type[3] == LIGTH_DIRECTIONAL)
light_pos[3][3] = 0.f;
else
light_pos[3][3] = 1.f;
break;
}
/*
* Individual lights enable/disable
*/
case LTE0:
if (normalArgument != 0) {
gl.glEnable(GL.GL_LIGHT0);
log("sceGuEnable(GL_LIGHT0)");
} else {
gl.glDisable(GL.GL_LIGHT0);
log("sceGuDisable(GL_LIGHT0)");
}
break;
case LTE1:
if (normalArgument != 0) {
gl.glEnable(GL.GL_LIGHT1);
log("sceGuEnable(GL_LIGHT1)");
} else {
gl.glDisable(GL.GL_LIGHT1);
log("sceGuDisable(GL_LIGHT1)");
}
break;
case LTE2:
if (normalArgument != 0) {
gl.glEnable(GL.GL_LIGHT2);
log("sceGuEnable(GL_LIGHT2)");
} else {
gl.glDisable(GL.GL_LIGHT2);
log("sceGuDisable(GL_LIGHT2)");
}
break;
case LTE3:
if (normalArgument != 0) {
gl.glEnable(GL.GL_LIGHT3);
log("sceGuEnable(GL_LIGHT3)");
} else {
gl.glDisable(GL.GL_LIGHT3);
log("sceGuDisable(GL_LIGHT3)");
}
break;
/*
* Lighting enable/disable
*/
case LTE:
if (normalArgument != 0) {
gl.glEnable(GL.GL_LIGHTING);
log("sceGuEnable(GL_LIGHTING)");
} else {
gl.glDisable(GL.GL_LIGHTING);
log("sceGuDisable(GL_LIGHTING)");
}
break;
/*
* Material setup
*/
case CMAT:
mat_flags = normalArgument & 7;
log("cmat");
break;
case AMA:
mat_ambient[3] = ((normalArgument ) & 255) / 255.f;
if((mat_flags & 1) != 0)
gl.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, mat_ambient, 0);
break;
case AMC:
mat_ambient[0] = ((normalArgument ) & 255) / 255.f;
mat_ambient[1] = ((normalArgument >> 8) & 255) / 255.f;
mat_ambient[2] = ((normalArgument >> 16) & 255) / 255.f;
if((mat_flags & 1) != 0)
gl.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, mat_ambient, 0);
log("sceGuAmbient " + String.format("r=%.1f g=%.1f b=%.1f (%08X)",
mat_ambient[0], mat_ambient[1], mat_ambient[2], normalArgument));
break;
case DMC:
mat_diffuse[0] = ((normalArgument ) & 255) / 255.f;
mat_diffuse[1] = ((normalArgument >> 8) & 255) / 255.f;
mat_diffuse[2] = ((normalArgument >> 16) & 255) / 255.f;
mat_diffuse[3] = 1.f;
if((mat_flags & 2) != 0)
gl.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, mat_diffuse, 0);
log("sceGuColor " + String.format("r=%.1f g=%.1f b=%.1f (%08X)",
mat_diffuse[0], mat_diffuse[1], mat_diffuse[2], normalArgument));
break;
case EMC:
mat_emissive[0] = ((normalArgument ) & 255) / 255.f;
mat_emissive[1] = ((normalArgument >> 8) & 255) / 255.f;
mat_emissive[2] = ((normalArgument >> 16) & 255) / 255.f;
mat_emissive[3] = 1.f;
gl.glMaterialfv(GL.GL_FRONT, GL.GL_EMISSION, mat_emissive, 0);
log("material emission " + String.format("r=%.1f g=%.1f b=%.1f (%08X)",
mat_emissive[0], mat_emissive[1], mat_emissive[2], normalArgument));
break;
case SMC:
mat_specular[0] = ((normalArgument ) & 255) / 255.f;
mat_specular[1] = ((normalArgument >> 8) & 255) / 255.f;
mat_specular[2] = ((normalArgument >> 16) & 255) / 255.f;
mat_specular[3] = 1.f;
if((mat_flags & 4) != 0)
gl.glMaterialfv(GL.GL_FRONT, GL.GL_SPECULAR, mat_specular, 0);
log("material specular " + String.format("r=%.1f g=%.1f b=%.1f (%08X)",
mat_specular[0], mat_specular[1], mat_specular[2], normalArgument));
break;
case SPOW:
gl.glMaterialf(GL.GL_FRONT, GL.GL_SHININESS, floatArgument);
log("material shininess");
break;
case TMS:
texture_upload_start = true;
log("sceGumMatrixMode GU_TEXTURE");
break;
case TMATRIX:
if (texture_upload_start) {
texture_upload_x = 0;
texture_upload_y = 0;
texture_upload_start = false;
}
if (texture_upload_y < 4) {
if (texture_upload_x < 4) {
texture_matrix[texture_upload_x + texture_upload_y * 4] = floatArgument;
texture_upload_x++;
if (texture_upload_x == 4) {
texture_upload_x = 0;
texture_upload_y++;
if (texture_upload_y == 4) {
log("glLoadMatrixf", texture_matrix);
for (int i = 0; i < 4*4; i++)
texture_uploaded_matrix[i] = texture_matrix[i];
}
}
}
}
break;
case PMS:
proj_upload_start = true;
log("sceGumMatrixMode GU_PROJECTION");
break;
case PROJ:
if (proj_upload_start) {
proj_upload_x = 0;
proj_upload_y = 0;
proj_upload_start = false;
}
if (proj_upload_y < 4) {
if (proj_upload_x < 4) {
proj_matrix[proj_upload_x + proj_upload_y * 4] = floatArgument;
proj_upload_x++;
if (proj_upload_x == 4) {
proj_upload_x = 0;
proj_upload_y++;
if (proj_upload_y == 4) {
log("glLoadMatrixf", proj_matrix);
for (int i = 0; i < 4*4; i++)
proj_uploaded_matrix[i] = proj_matrix[i];
}
}
}
}
break;
/*
*
*/
case TBW0:
texture_base_pointer0 = (texture_base_pointer0 & 0x00ffffff) | ((normalArgument << 8) & 0xff000000);
texture_buffer_width0 = normalArgument & 0xffff;
log ("sceGuTexImage(X,X,X,texWidth=" + texture_buffer_width0 + ",hi(pointer=0x" + Integer.toHexString(texture_base_pointer0) + "))");
break;
case TBP0:
texture_base_pointer0 = normalArgument;
log ("sceGuTexImage(X,X,X,X,lo(pointer=0x" + Integer.toHexString(texture_base_pointer0) + "))");
break;
case TSIZE0:
texture_height0 = 1 << ((normalArgument>>8) & 0xFF);
texture_width0 = 1 << ((normalArgument ) & 0xFF);
log ("sceGuTexImage(X,width=" + texture_width0 + ",height=" + texture_height0 + ",X,0)");
break;
case TMODE:
texture_num_mip_maps = (normalArgument>>16) & 0xFF;
texture_swizzle = ((normalArgument ) & 0xFF) != 0;
break;
case TPSM:
texture_storage = normalArgument;
break;
case CBP: {
tex_clut_addr = (tex_clut_addr & 0xff000000) | normalArgument;
log ("sceGuClutLoad(X, lo(cbp=0x" + Integer.toHexString(tex_clut_addr) + "))");
break;
}
case CBPH: {
tex_clut_addr = (tex_clut_addr & 0x00ffffff) | ((normalArgument << 8) & 0x0f000000);
log ("sceGuClutLoad(X, hi(cbp=0x" + Integer.toHexString(tex_clut_addr) + "))");
break;
}
case CLOAD: {
tex_clut_num_blocks = normalArgument;
log ("sceGuClutLoad(num_blocks=" + tex_clut_num_blocks + ", X)");
break;
}
case CMODE: {
tex_clut_mode = normalArgument & 0x03;
tex_clut_shift = (normalArgument >> 2) & 0x3F;
tex_clut_mask = (normalArgument >> 8) & 0xFF;
tex_clut_start = (normalArgument >> 16) & 0xFF;
log ("sceGuClutMode(cpsm=" + tex_clut_mode + ", shift=" + tex_clut_shift + ", mask=0x" + Integer.toHexString(tex_clut_mask) + ", start=" + tex_clut_start + ")");
break;
}
case TFLUSH:
{
// HACK: avoid texture uploads of null pointers
if (texture_base_pointer0 == 0)
break;
// Generate a texture id if we don't have one
if (gl_texture_id[0] == 0)
gl.glGenTextures(1, gl_texture_id, 0);
log(helper.getCommandString(TFLUSH) + " 0x" + Integer.toHexString(texture_base_pointer0) + "(" + texture_width0 + "," + texture_height0 + ")");
// Extract texture information with the minor conversion possible
// TODO: Get rid of information copying, and implement all the available formats
Memory mem = Memory.getInstance();
Buffer final_buffer = null;
int texture_type = 0;
int texclut = tex_clut_addr;
int texaddr = texture_base_pointer0;
texaddr &= 0xFFFFFFF;
final int[] texturetype_mapping = {
GL.GL_UNSIGNED_SHORT_5_6_5_REV,
GL.GL_UNSIGNED_SHORT_1_5_5_5_REV,
GL.GL_UNSIGNED_SHORT_4_4_4_4_REV,
GL.GL_UNSIGNED_BYTE,
};
int textureByteAlignment = 4; // 32 bits
switch (texture_storage) {
case TPSM_PIXEL_STORAGE_MODE_4BIT_INDEXED: {
switch (tex_clut_mode) {
case CMODE_FORMAT_16BIT_BGR5650:
case CMODE_FORMAT_16BIT_ABGR5551:
case CMODE_FORMAT_16BIT_ABGR4444: {
if (texclut == 0)
return;
texture_type = texturetype_mapping[tex_clut_mode];
textureByteAlignment = 2; // 16 bits
if (!texture_swizzle) {
for (int i = 0, j = 0; i < texture_width0*texture_height0; i += 2, j++) {
int index = mem.read8(texaddr+j);
// TODO: I don't know if it's correct, or should read the 4bits in
// reverse order
tmp_texture_buffer16[i] = (short)mem.read16(texclut + getClutIndex((index >> 4) & 0xF) * 2);
tmp_texture_buffer16[i+1] = (short)mem.read16(texclut + getClutIndex( index & 0xF) * 2);
}
final_buffer = ShortBuffer.wrap(tmp_texture_buffer16);
} else {
VideoEngine.log.error("Unhandled swizzling on clut4/16 textures");
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
break;
}
break;
}
case CMODE_FORMAT_32BIT_ABGR8888: {
if (texclut == 0)
return;
texture_type = GL.GL_UNSIGNED_BYTE;
if (!texture_swizzle) {
for (int i = 0, j = 0; i < texture_width0*texture_height0; i += 2, j++) {
int index = mem.read8(texaddr+j);
// TODO: I don't know if it's correct, or should read the 4bits in
// reverse order
tmp_texture_buffer32[i] = mem.read32(texclut + getClutIndex((index >> 4) & 0xF) * 4);
tmp_texture_buffer32[i+1] = mem.read32(texclut + getClutIndex( index & 0xF) * 4);
}
final_buffer = IntBuffer.wrap(tmp_texture_buffer32);
} else {
//VideoEngine.log.error("Unhandled swizzling on clut4/32 textures");
//Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
final_buffer = unswizzleTexture32();
break;
}
break;
}
default: {
VideoEngine.log.error("Unhandled clut4 texture mode " + tex_clut_mode);
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
break;
}
}
break;
}
case TPSM_PIXEL_STORAGE_MODE_8BIT_INDEXED: {
switch (tex_clut_mode) {
case CMODE_FORMAT_16BIT_BGR5650:
case CMODE_FORMAT_16BIT_ABGR5551:
case CMODE_FORMAT_16BIT_ABGR4444: {
if (texclut == 0)
return;
texture_type = texturetype_mapping[tex_clut_mode];
textureByteAlignment = 2; // 16 bits
if (!texture_swizzle) {
for (int i = 0; i < texture_width0*texture_height0; i++) {
int index = mem.read8(texaddr+i);
tmp_texture_buffer16[i] = (short)mem.read16(texclut + getClutIndex(index) * 2);
}
final_buffer = ShortBuffer.wrap(tmp_texture_buffer16);
} else {
VideoEngine.log.error("Unhandled swizzling on clut8/16 textures");
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
break;
}
break;
}
case CMODE_FORMAT_32BIT_ABGR8888: {
if (texclut == 0)
return;
texture_type = GL.GL_UNSIGNED_BYTE;
if (!texture_swizzle) {
for (int i = 0; i < texture_width0*texture_height0; i++) {
int index = mem.read8(texaddr+i);
tmp_texture_buffer32[i] = mem.read32(texclut + getClutIndex(index) * 4);
}
final_buffer = IntBuffer.wrap(tmp_texture_buffer32);
} else {
//VideoEngine.log.error("Unhandled swizzling on clut8/32 textures");
//Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
final_buffer = unswizzleTexture32();
break;
}
break;
}
default: {
VideoEngine.log.error("Unhandled clut8 texture mode " + tex_clut_mode);
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
break;
}
}
break;
}
case TPSM_PIXEL_STORAGE_MODE_16BIT_BGR5650:
case TPSM_PIXEL_STORAGE_MODE_16BIT_ABGR5551:
case TPSM_PIXEL_STORAGE_MODE_16BIT_ABGR4444: {
texture_type = texturetype_mapping[texture_storage];
textureByteAlignment = 2; // 16 bits
if (!texture_swizzle) {
/* TODO replace the loop with 1 line to ShortBuffer.wrap
* but be careful of vram/mainram addresses
final_buffer = ShortBuffer.wrap(
memory.videoram.array(),
texaddr - MemoryMap.START_VRAM + memory.videoram.arrayOffset(),
texture_width0 * texture_height0).slice();
final_buffer = ShortBuffer.wrap(
memory.mainmemory.array(),
texaddr - MemoryMap.START_RAM + memory.mainmemory.arrayOffset(),
texture_width0 * texture_height0).slice();
*/
for (int i = 0; i < texture_width0*texture_height0; i++) {
int pixel = mem.read16(texaddr+i*2);
tmp_texture_buffer16[i] = (short)pixel;
}
final_buffer = ShortBuffer.wrap(tmp_texture_buffer16);
} else {
final_buffer = unswizzleTextureFromMemory(texaddr, 2);
}
break;
}
case TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888: {
texture_type = GL.GL_UNSIGNED_INT_8_8_8_8_REV;
if (!texture_swizzle) {
/* TODO replace the loop with 1 line to IntBuffer.wrap
* but be careful of vram/mainram addresses
final_buffer = IntBuffer.wrap(
memory.videoram.array(),
texaddr - MemoryMap.START_VRAM + memory.videoram.arrayOffset(),
texture_width0 * texture_height0).slice();
final_buffer = IntBuffer.wrap(
memory.mainmemory.array(),
texaddr - MemoryMap.START_RAM + memory.mainmemory.arrayOffset(),
texture_width0 * texture_height0).slice();
*/
for (int i = 0; i < texture_width0*texture_height0; i++) {
tmp_texture_buffer32[i] = mem.read32(texaddr+i*4);
}
final_buffer = IntBuffer.wrap(tmp_texture_buffer32);
} else {
final_buffer = unswizzleTextureFromMemory(texaddr, 4);
}
break;
}
default: {
System.out.println("Unhandled texture storage " + texture_storage);
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
break;
}
}
// Upload texture to openGL
// TODO: Write a texture cache :)
gl.glBindTexture (GL.GL_TEXTURE_2D, gl_texture_id[0]);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, tex_min_filter);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, tex_mag_filter);
gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, textureByteAlignment);
gl.glPixelStorei(GL.GL_UNPACK_ROW_LENGTH, 0); // ROW_LENGTH = width
int texture_format = texture_type == GL.GL_UNSIGNED_SHORT_5_6_5_REV ? GL.GL_RGB : GL.GL_RGBA;
gl.glTexImage2D ( GL.GL_TEXTURE_2D,
0,
texture_format,
texture_width0, texture_height0,
0,
texture_format,
texture_type,
final_buffer);
break;
}
case TFLT: {
log ("sceGuTexFilter(min, mag)");
switch ((normalArgument>>8) & 0xFF)
{
case TFLT_MAGNIFYING_FILTER_NEAREST: {
tex_mag_filter = GL.GL_NEAREST;
break;
}
case TFLT_MAGNIFYING_FILTER_LINEAR: {
tex_mag_filter = GL.GL_LINEAR;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_NEAREST_NEAREST: {
tex_mag_filter = GL.GL_NEAREST_MIPMAP_NEAREST;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_NEAREST_LINEAR: {
tex_mag_filter = GL.GL_NEAREST_MIPMAP_LINEAR;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_LINEAR_NEAREST: {
tex_mag_filter = GL.GL_LINEAR_MIPMAP_NEAREST;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_LINEAR_LINEAR: {
tex_mag_filter = GL.GL_LINEAR_MIPMAP_LINEAR;
break;
}
default: {
log ("Unknown magnifiying filter " + ((normalArgument>>8) & 0xFF));
break;
}
}
switch (normalArgument & 0xFF)
{
case TFLT_MAGNIFYING_FILTER_NEAREST: {
tex_min_filter = GL.GL_NEAREST;
break;
}
case TFLT_MAGNIFYING_FILTER_LINEAR: {
tex_min_filter = GL.GL_LINEAR;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_NEAREST_NEAREST: {
tex_min_filter = GL.GL_NEAREST_MIPMAP_NEAREST;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_NEAREST_LINEAR: {
tex_min_filter = GL.GL_NEAREST_MIPMAP_LINEAR;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_LINEAR_NEAREST: {
tex_min_filter = GL.GL_LINEAR_MIPMAP_NEAREST;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_LINEAR_LINEAR: {
tex_min_filter = GL.GL_LINEAR_MIPMAP_LINEAR;
break;
}
default: {
log ("Unknown minimizing filter " + (normalArgument & 0xFF));
break;
}
}
break;
}
/*
* Texture transformations
*/
case UOFFSET: {
tex_translate_x = floatArgument;
log ("sceGuTexOffset(float u, X)");
break;
}
case VOFFSET: {
tex_translate_y = floatArgument;
log ("sceGuTexOffset(X, float v)");
break;
}
case USCALE: {
tex_scale_x = floatArgument;
log (String.format("sceGuTexScale(u=%.2f, X)", tex_scale_x));
break;
}
case VSCALE: {
tex_scale_y = floatArgument;
log (String.format("sceGuTexScale(X, v=%.2f)", tex_scale_y));
break;
}
case TMAP: {
log ("sceGuTexMapMode(mode, X, X)");
tex_map_mode = normalArgument & 3;
break;
}
case TEXTURE_ENV_MAP_MATRIX: {
log ("sceGuTexMapMode(X, column1, column2)");
if (normalArgument != 0) {
int column0 = normalArgument & 0xFF,
column1 = (normalArgument>>8) & 0xFF;
for (int i = 0; i < 3; i++) {
tex_envmap_matrix [i+0] = light_pos[column0][i];
tex_envmap_matrix [i+4] = light_pos[column1][i];
}
}
break;
}
case TFUNC:
gl.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_RGB_SCALE, (normalArgument & 0x10000) != 0 ? 1.0f : 2.0f);
int env_mode = GL.GL_MODULATE;
switch(normalArgument & 7) {
case 0: env_mode = GL.GL_MODULATE; break;
case 1: env_mode = GL.GL_DECAL; break;
case 2: env_mode = GL.GL_BLEND; break;
case 3: env_mode = GL.GL_REPLACE; break;
case 4: env_mode = GL.GL_ADD; break;
default: VideoEngine.log.warn("Unimplemented tfunc mode");
}
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, env_mode);
// TODO : check this
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_SRC0_ALPHA, (normalArgument & 0x100) == 0 ? GL.GL_PREVIOUS : GL.GL_TEXTURE);
log("sceGuTexFunc");
/*log(String.format("sceGuTexFunc mode %08X", normalArgument)
+ (((normalArgument & 0x10000) != 0) ? " SCALE" : "")
+ (((normalArgument & 0x100) != 0) ? " ALPHA" : ""));*/
break;
case TEC:
tex_env_color[0] = ((normalArgument ) & 255) / 255.f;
tex_env_color[1] = ((normalArgument >> 8) & 255) / 255.f;
tex_env_color[2] = ((normalArgument >> 16) & 255) / 255.f;
tex_env_color[3] = 1.f;
gl.glTexEnvfv(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_COLOR, tex_env_color, 0);
log("tec");
break;
/*
*
*/
case XSCALE:
log("sceGuViewport width = " + (floatArgument * 2));
break;
case YSCALE:
log("sceGuViewport height = " + (- floatArgument * 2));
break;
// sceGuViewport cx/cy, can we discard these settings? it's only for clipping?
case XPOS:
log("sceGuViewport cx = " + floatArgument);
break;
case YPOS:
log("sceGuViewport cy = " + floatArgument);
break;
case ZPOS:
log(helper.getCommandString(ZPOS), floatArgument);
break;
// sceGuOffset, can we discard these settings? it's only for clipping?
case OFFSETX:
log("sceGuOffset x = " + (normalArgument >> 4));
break;
case OFFSETY:
log("sceGuOffset y = " + (normalArgument >> 4));
break;
case FBP:
// assign or OR lower 24-bits?
fbp = normalArgument;
break;
case FBW:
fbp &= 0xffffff;
fbp |= (normalArgument << 8) & 0xff000000;
fbw = (normalArgument) & 0xffff;
log("fbp=" + Integer.toHexString(fbp) + ", fbw=" + fbw);
jpcsp.HLE.pspdisplay.get_instance().hleDisplaySetGeBuf(fbp, fbw, psm);
break;
case ZBP:
// assign or OR lower 24-bits?
zbp = normalArgument;
break;
case ZBW:
zbp &= 0xffffff;
zbp |= (normalArgument << 8) & 0xff000000;
zbw = (normalArgument) & 0xffff;
log("zbp=" + Integer.toHexString(zbp) + ", zbw=" + zbw);
break;
case PSM:
psm = normalArgument;
log("psm=" + normalArgument);
break;
case PRIM:
{
int[] mapping = new int[] { GL.GL_POINTS, GL.GL_LINES, GL.GL_LINE_STRIP, GL.GL_TRIANGLES, GL.GL_TRIANGLE_STRIP, GL.GL_TRIANGLE_FAN };
int numberOfVertex = normalArgument & 0xFFFF;
int type = ((normalArgument >> 16) & 0x7);
// Logging
switch (type) {
case PRIM_POINT:
log(helper.getCommandString(PRIM) + " point " + numberOfVertex + "x");
break;
case PRIM_LINE:
log(helper.getCommandString(PRIM) + " line " + (numberOfVertex / 2) + "x");
break;
case PRIM_LINES_STRIPS:
log(helper.getCommandString(PRIM) + " lines_strips " + (numberOfVertex - 1) + "x");
break;
case PRIM_TRIANGLE:
log(helper.getCommandString(PRIM) + " triangle " + (numberOfVertex / 3) + "x");
break;
case PRIM_TRIANGLE_STRIPS:
log(helper.getCommandString(PRIM) + " triangle_strips " + (numberOfVertex - 2) + "x");
break;
case PRIM_TRIANGLE_FANS:
log(helper.getCommandString(PRIM) + " triangle_fans " + (numberOfVertex - 2) + "x");
break;
case PRIM_SPRITES:
log(helper.getCommandString(PRIM) + " sprites " + (numberOfVertex / 2) + "x");
break;
}
/*
* Defer transformations until primitive rendering
*/
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glPushMatrix ();
gl.glLoadIdentity();
if (transform_mode == VTYPE_TRANSFORM_PIPELINE_TRANS_COORD)
gl.glLoadMatrixf(proj_uploaded_matrix, 0);
else
gl.glOrtho(0.0, 480, 272, 0, -1.0, 1.0);
/*
* Apply texture transforms
*/
gl.glMatrixMode(GL.GL_TEXTURE);
gl.glPushMatrix ();
gl.glLoadIdentity();
gl.glTranslatef(tex_translate_x, tex_translate_y, 0.f);
if (transform_mode == VTYPE_TRANSFORM_PIPELINE_TRANS_COORD)
gl.glScalef(tex_scale_x, tex_scale_y, 1.f);
switch (tex_map_mode) {
case TMAP_TEXTURE_MAP_MODE_TEXTURE_COORDIATES_UV:
break;
case TMAP_TEXTURE_MAP_MODE_TEXTURE_MATRIX:
gl.glMultMatrixf (texture_uploaded_matrix, 0);
break;
case TMAP_TEXTURE_MAP_MODE_ENVIRONMENT_MAP: {
// First, setup texture uv generation
gl.glTexGeni(GL.GL_S, GL.GL_TEXTURE_GEN_MODE, GL.GL_SPHERE_MAP);
gl.glEnable (GL.GL_TEXTURE_GEN_S);
gl.glTexGeni(GL.GL_T, GL.GL_TEXTURE_GEN_MODE, GL.GL_SPHERE_MAP);
gl.glEnable (GL.GL_TEXTURE_GEN_T);
// Setup also texture matrix
gl.glMultMatrixf (tex_envmap_matrix, 0);
break;
}
default:
log ("Unhandled texture matrix mode " + tex_map_mode);
}
/*
* Apply view matrix
*/
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glPushMatrix ();
gl.glLoadIdentity();
if (transform_mode == VTYPE_TRANSFORM_PIPELINE_TRANS_COORD)
gl.glLoadMatrixf(view_uploaded_matrix, 0);
/*
* Setup lights on when view transformation is set up
*/
gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, light_pos[0], 0);
gl.glLightfv(GL.GL_LIGHT1, GL.GL_POSITION, light_pos[1], 0);
gl.glLightfv(GL.GL_LIGHT2, GL.GL_POSITION, light_pos[2], 0);
gl.glLightfv(GL.GL_LIGHT3, GL.GL_POSITION, light_pos[3], 0);
// Apply model matrix
if (transform_mode == VTYPE_TRANSFORM_PIPELINE_TRANS_COORD)
gl.glMultMatrixf(model_uploaded_matrix, 0);
// HACK: If we don't have a material set up, and have colors per vertex, this will
// override materials, so at least we'll see something, otherwise it would be black
if (vinfo.color != 0)
gl.glEnable(GL.GL_COLOR_MATERIAL);
Memory mem = Memory.getInstance();
switch (type) {
case PRIM_POINT:
case PRIM_LINE:
case PRIM_LINES_STRIPS:
case PRIM_TRIANGLE:
case PRIM_TRIANGLE_STRIPS:
case PRIM_TRIANGLE_FANS:
gl.glBegin(mapping[type]);
for (int i = 0; i < numberOfVertex; i++) {
int addr = vinfo.getAddress(mem, i);
VertexState v = vinfo.readVertex(mem, addr);
if (vinfo.texture != 0)
if(transform_mode == VTYPE_TRANSFORM_PIPELINE_RAW_COORD)
gl.glTexCoord2f(v.u / texture_width0, v.v / texture_height0);
else
gl.glTexCoord2f(v.u, v.v);
if (vinfo.color != 0) gl.glColor4f(v.r, v.g, v.b, v.a);
if (vinfo.normal != 0) gl.glNormal3f(v.nx, v.ny, v.nz);
if (vinfo.position != 0) {
if(vinfo.weight != 0)
doSkinning(vinfo, v);
gl.glVertex3f(v.px, v.py, v.pz);
}
}
gl.glEnd();
break;
case PRIM_SPRITES:
gl.glPushAttrib(GL.GL_ENABLE_BIT);
gl.glDisable(GL.GL_CULL_FACE);
gl.glBegin(GL.GL_QUADS);
for (int i = 0; i < numberOfVertex; i += 2) {
int addr1 = vinfo.getAddress(mem, i);
int addr2 = vinfo.getAddress(mem, i + 1);
VertexState v1 = vinfo.readVertex(mem, addr1);
VertexState v2 = vinfo.readVertex(mem, addr2);
// V1
if (vinfo.normal != 0) gl.glNormal3f(v1.nx, v1.ny, v1.nz);
if (vinfo.color != 0) gl.glColor4f(v2.r, v2.g, v2.b, v2.a); // color from v2 not v1
if (vinfo.texture != 0)
if(transform_mode == VTYPE_TRANSFORM_PIPELINE_RAW_COORD)
gl.glTexCoord2f(v1.u / texture_width0, v1.v / texture_height0);
else
gl.glTexCoord2f(v1.u, v1.v);
if (vinfo.position != 0) gl.glVertex3f(v1.px, v1.py, v1.pz);
if (vinfo.texture != 0)
if(transform_mode == VTYPE_TRANSFORM_PIPELINE_RAW_COORD)
gl.glTexCoord2f(v2.u / texture_width0, v1.v / texture_height0);
else
gl.glTexCoord2f(v2.u, v1.v);
if (vinfo.position != 0) gl.glVertex3f(v2.px, v1.py, v1.pz);
// V2
if (vinfo.normal != 0) gl.glNormal3f(v2.nx, v2.ny, v2.nz);
if (vinfo.color != 0) gl.glColor4f(v2.r, v2.g, v2.b, v2.a);
if (vinfo.texture != 0)
if(transform_mode == VTYPE_TRANSFORM_PIPELINE_RAW_COORD)
gl.glTexCoord2f(v2.u / texture_width0, v2.v / texture_height0);
else
gl.glTexCoord2f(v2.u, v2.v);
if (vinfo.position != 0) gl.glVertex3f(v2.px, v2.py, v1.pz);
if (vinfo.texture != 0)
if(transform_mode == VTYPE_TRANSFORM_PIPELINE_RAW_COORD)
gl.glTexCoord2f(v1.u / texture_width0, v2.v / texture_height0);
else
gl.glTexCoord2f(v1.u, v2.v);
if (vinfo.position != 0) gl.glVertex3f(v1.px, v2.py, v1.pz);
}
gl.glEnd();
gl.glPopAttrib();
break;
}
switch (tex_map_mode) {
case TMAP_TEXTURE_MAP_MODE_ENVIRONMENT_MAP: {
gl.glDisable (GL.GL_TEXTURE_GEN_S);
gl.glDisable (GL.GL_TEXTURE_GEN_T);
break;
}
}
gl.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_RGB_SCALE, 1.0f);
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_MODULATE);
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_SRC0_ALPHA, GL.GL_TEXTURE);
if (vinfo.color != 0)
gl.glDisable (GL.GL_COLOR_MATERIAL);
gl.glPopMatrix ();
gl.glMatrixMode (GL.GL_TEXTURE);
gl.glPopMatrix ();
gl.glMatrixMode (GL.GL_PROJECTION);
gl.glPopMatrix ();
gl.glMatrixMode (GL.GL_MODELVIEW);
break;
}
case ALPHA: {
int blend_mode = GL.GL_FUNC_ADD;
int src = getBlendSrc( normalArgument & 0xF);
int dst = getBlendOp((normalArgument >> 4 ) & 0xF);
int op = (normalArgument >> 8 ) & 0xF;
switch (op) {
case ALPHA_SOURCE_BLEND_OPERATION_ADD:
blend_mode = GL.GL_FUNC_ADD;
break;
case ALPHA_SOURCE_BLEND_OPERATION_SUBTRACT:
blend_mode = GL.GL_FUNC_SUBTRACT;
break;
case ALPHA_SOURCE_BLEND_OPERATION_REVERSE_SUBTRACT:
blend_mode = GL.GL_FUNC_REVERSE_SUBTRACT;
break;
case ALPHA_SOURCE_BLEND_OPERATION_MINIMUM_VALUE:
blend_mode = GL.GL_MIN;
break;
case ALPHA_SOURCE_BLEND_OPERATION_MAXIMUM_VALUE:
blend_mode = GL.GL_MAX;
break;
case ALPHA_SOURCE_BLEND_OPERATION_ABSOLUTE_VALUE:
blend_mode = GL.GL_FUNC_ADD;
break;
default:
VideoEngine.log.error("Unhandled blend mode " + op);
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
break;
}
try {
gl.glBlendEquation(blend_mode);
} catch (GLException e) {
log.warn("VideoEngine: " + e.getMessage());
}
gl.glBlendFunc(src, dst);
log ("sceGuBlendFunc(int op, int src, int dest, X, X)");
break;
}
case SHADE: {
int SETTED_MODEL = (normalArgument != 0) ? GL.GL_SMOOTH : GL.GL_FLAT;
gl.glShadeModel(SETTED_MODEL);
log(helper.getCommandString(SHADE) + " " + ((normalArgument != 0) ? "smooth" : "flat"));
break;
}
case FFACE: {
int frontFace = (normalArgument != 0) ? GL.GL_CW : GL.GL_CCW;
gl.glFrontFace(frontFace);
log(helper.getCommandString(FFACE) + " " + ((normalArgument != 0) ? "clockwise" : "counter-clockwise"));
break;
}
case DTE:
if(normalArgument != 0)
{
gl.glEnable(GL.GL_DITHER);
log("sceGuEnable(GL_DITHER)");
}
else
{
gl.glDisable(GL.GL_DITHER);
log("sceGuDisable(GL_DITHER)");
}
break;
case BCE:
if(normalArgument != 0)
{
gl.glEnable(GL.GL_CULL_FACE);
log("sceGuEnable(GU_CULL_FACE)");
}
else
{
gl.glDisable(GL.GL_CULL_FACE);
log("sceGuDisable(GU_CULL_FACE)");
}
break;
case FGE:
if(normalArgument != 0)
{
gl.glEnable(GL.GL_FOG);
gl.glFogi(GL.GL_FOG_MODE, GL.GL_LINEAR);
gl.glFogf(GL.GL_FOG_DENSITY, 0.1f);
gl.glHint(GL.GL_FOG_HINT, GL.GL_DONT_CARE);
log("sceGuEnable(GL_FOG)");
}
else
{
gl.glDisable(GL.GL_FOG);
log("sceGuDisable(GL_FOG)");
}
break;
case FCOL:
fog_color[0] = ((normalArgument ) & 255) / 255.f;
fog_color[1] = ((normalArgument >> 8) & 255) / 255.f;
fog_color[2] = ((normalArgument >> 16) & 255) / 255.f;
fog_color[3] = 1.f;
gl.glFogfv(GL.GL_FOG_COLOR, fog_color, 0);
log("FCOL");
break;
case FFAR:
fog_far = floatArgument;
break;
case FDIST:
fog_dist = floatArgument;
if((fog_far != 0.0f) && (fog_dist != 0.0f))
{
float end = fog_far;
float start = end - (1/floatArgument);
gl.glFogf( GL.GL_FOG_START, start );
gl.glFogf( GL.GL_FOG_END, end );
}
break;
case ABE:
if(normalArgument != 0) {
gl.glEnable(GL.GL_BLEND);
log("sceGuEnable(GU_BLEND)");
}
else {
gl.glDisable(GL.GL_BLEND);
log("sceGuDisable(GU_BLEND)");
}
break;
case ATE:
if(normalArgument != 0) {
gl.glEnable(GL.GL_ALPHA_TEST);
log("sceGuEnable(GL_ALPHA_TEST)");
}
else {
gl.glDisable(GL.GL_ALPHA_TEST);
log("sceGuDisable(GL_ALPHA_TEST)");
}
break;
case ZTE:
if(normalArgument != 0) {
gl.glEnable(GL.GL_DEPTH_TEST);
log("sceGuEnable(GU_DEPTH_TEST)");
}
else {
gl.glDisable(GL.GL_DEPTH_TEST);
log("sceGuDisable(GU_DEPTH_TEST)");
}
break;
case STE:
if(normalArgument != 0) {
gl.glEnable(GL.GL_STENCIL_TEST);
log("sceGuEnable(GU_STENCIL_TEST)");
}
else {
gl.glDisable(GL.GL_STENCIL_TEST);
log("sceGuDisable(GU_STENCIL_TEST)");
}
break;
case AAE:
if(normalArgument != 0)
{
gl.glEnable(GL.GL_LINE_SMOOTH);
gl.glHint(GL.GL_LINE_SMOOTH_HINT, GL.GL_NICEST);
log("sceGuEnable(GL_LINE_SMOOTH)");
}else
{
gl.glDisable(GL.GL_LINE_SMOOTH);
log("sceGuDisable(GL_LINE_SMOOTH)");
}
break;
case LOE:
if(normalArgument != 0)
{
gl.glEnable(GL.GL_COLOR_LOGIC_OP);
log("sceGuEnable(GU_COLOR_LOGIC_OP)");
}
else
{
gl.glDisable(GL.GL_COLOR_LOGIC_OP);
log("sceGuDisable(GU_COLOR_LOGIC_OP)");
}
break;
case JUMP:
{
int npc = (normalArgument | actualList.base) & 0xFFFFFFFC;
//I guess it must be unsign as psp player emulator
log(helper.getCommandString(JUMP) + " old PC:" + String.format("%08x", actualList.pc)
+ " new PC:" + String.format("%08x", npc));
actualList.pc = npc;
break;
}
case CALL:
{
actualList.stack[actualList.stackIndex++] = actualList.pc;
int npc = (normalArgument | actualList.base) & 0xFFFFFFFC;
log(helper.getCommandString(CALL) + " old PC:" + String.format("%08x", actualList.pc)
+ " new PC:" + String.format("%08x", npc));
actualList.pc = npc;
break;
}
case RET:
{
int npc = actualList.stack[--actualList.stackIndex];
log(helper.getCommandString(RET) + " old PC:" + String.format("%08x", actualList.pc)
+ " new PC:" + String.format("%08x", npc));
actualList.pc = npc;
break;
}
case ZMSK: {
// NOTE: PSP depth mask as 1 is meant to avoid depth writes,
// on pc it's the opposite
gl.glDepthMask(normalArgument == 1 ? false : true);
log ("sceGuDepthMask(disableWrites)");
break;
}
case ATST: {
int func = GL.GL_ALWAYS;
switch(normalArgument & 0xFF) {
case ATST_NEVER_PASS_PIXEL:
func = GL.GL_NEVER;
break;
case ATST_ALWAYS_PASS_PIXEL:
func = GL.GL_ALWAYS;
break;
case ATST_PASS_PIXEL_IF_MATCHES:
func = GL.GL_EQUAL;
break;
case ATST_PASS_PIXEL_IF_DIFFERS:
func = GL.GL_NOTEQUAL;
break;
case ATST_PASS_PIXEL_IF_LESS:
func = GL.GL_LESS;
break;
case ATST_PASS_PIXEL_IF_LESS_OR_EQUAL:
func = GL.GL_LEQUAL;
break;
case ATST_PASS_PIXEL_IF_GREATER:
func = GL.GL_GREATER;
break;
case ATST_PASS_PIXEL_IF_GREATER_OR_EQUAL:
func = GL.GL_GEQUAL;
break;
}
gl.glAlphaFunc(func,floatArgument);
log ("sceGuAlphaFunc(" + func + "," + floatArgument + ")");
break;
}
case STST: {
int func = GL.GL_ALWAYS;
switch (normalArgument & 0xFF) {
case STST_FUNCTION_NEVER_PASS_STENCIL_TEST:
func = GL.GL_NEVER;
break;
case STST_FUNCTION_ALWAYS_PASS_STENCIL_TEST:
func = GL.GL_ALWAYS;
break;
case STST_FUNCTION_PASS_TEST_IF_MATCHES:
func = GL.GL_EQUAL;
break;
case STST_FUNCTION_PASS_TEST_IF_DIFFERS:
func = GL.GL_NOTEQUAL;
break;
case STST_FUNCTION_PASS_TEST_IF_LESS:
func = GL.GL_LESS;
break;
case STST_FUNCTION_PASS_TEST_IF_LESS_OR_EQUAL:
func = GL.GL_LEQUAL;
break;
case STST_FUNCTION_PASS_TEST_IF_GREATER:
func = GL.GL_GREATER;
break;
case STST_FUNCTION_PASS_TEST_IF_GREATER_OR_EQUAL:
func = GL.GL_GEQUAL;
break;
}
gl.glStencilFunc (func, ((normalArgument>>8) & 0xff), (normalArgument>>16) & 0xff);
log ("sceGuStencilFunc(func, ref, mask)");
break;
}
case NEARZ : {
nearZ = ( float )( int )( short )normalArgument;
}
break;
case FARZ : {
if(nearZ > ( float )( int )( short )normalArgument)
{
farZ = nearZ;
nearZ = ( float )( int )( short )normalArgument;
}
else
farZ = ( float )( int )( short )normalArgument;
gl.glDepthRange(nearZ, farZ);
log ("sceGuDepthRange("+ nearZ + " ," + farZ + ")");
}
break;
case SOP: {
int fail = getStencilOp (normalArgument & 0xFF);
int zfail = getStencilOp ((normalArgument>> 8) & 0xFF);
int zpass = getStencilOp ((normalArgument>>16) & 0xFF);
gl.glStencilOp(fail, zfail, zpass);
break;
}
case CLEAR:
if ((normalArgument & 0x1)==0) {
// set clear color, actarus/sam
gl.glClearColor(vinfo.lastVertex.r, vinfo.lastVertex.g, vinfo.lastVertex.b, vinfo.lastVertex.a);
gl.glClear(clearFlags);
log(String.format("guclear r=%.1f g=%.1f b=%.1f a=%.1f", vinfo.lastVertex.r, vinfo.lastVertex.g, vinfo.lastVertex.b, vinfo.lastVertex.a));
} else {
clearFlags = 0;
if ((normalArgument & 0x100)!=0) clearFlags |= GL.GL_COLOR_BUFFER_BIT; // target
if ((normalArgument & 0x200)!=0) clearFlags |= GL.GL_STENCIL_BUFFER_BIT; // stencil/alpha
if ((normalArgument & 0x400)!=0) clearFlags |= GL.GL_DEPTH_BUFFER_BIT; // zbuffer
log("setting clear flags");
}
break;
case NOP:
log(helper.getCommandString(NOP));
break;
/*
* Skinning
*/
case BOFS: {
log("bone matrix offset", normalArgument);
if(normalArgument % 12 != 0)
VideoEngine.log.warn("bone matrix offset " + normalArgument + " isn't a multiple of 12");
bone_matrix_offset = normalArgument / (4*3);
bone_upload_start = true;
break;
}
case BONE: {
if (bone_upload_start) {
bone_upload_x = 0;
bone_upload_y = 0;
bone_upload_start = false;
}
if (bone_upload_x < 4) {
if (bone_upload_y < 3) {
bone_matrix[bone_upload_x + bone_upload_y * 4] = floatArgument;
bone_upload_x++;
if (bone_upload_x == 4) {
bone_upload_x = 0;
bone_upload_y++;
if (bone_upload_y == 3) {
log("bone matrix " + bone_matrix_offset, model_matrix);
for (int i = 0; i < 4*3; i++)
bone_uploaded_matrix[bone_matrix_offset][i] = bone_matrix[i];
}
}
}
}
break;
}
case MW0:
case MW1:
case MW2:
case MW3:
case MW4:
case MW5:
case MW6:
case MW7:
log("morph weight " + (command(instruction) - MW0), floatArgument);
morph_weight[command(instruction) - MW0] = floatArgument;
break;
case TRXSBP:
textureTx_sourceAddress = normalArgument;
break;
case TRXSBW:
textureTx_sourceAddress |= (normalArgument << 8) & 0xFF000000;
textureTx_sourceLineWidth = normalArgument & 0x0000FFFF;
break;
case TRXDBP:
textureTx_destinationAddress = normalArgument;
break;
case TRXDBW:
textureTx_destinationAddress |= (normalArgument << 8) & 0xFF000000;
textureTx_destinationLineWidth = normalArgument & 0x0000FFFF;
break;
case TRXSIZE:
textureTx_width = (normalArgument & 0x3FF) + 1;
textureTx_height = ((normalArgument >> 10) & 0x1FF) + 1;
break;
case TRXPOS:
textureTx_sx = normalArgument & 0x1FF;
textureTx_sy = (normalArgument >> 10) & 0x1FF;
break;
case TRXDPOS:
textureTx_dx = normalArgument & 0x1FF;
textureTx_dy = (normalArgument >> 10) & 0x1FF;
break;
case TRXKICK:
textureTx_pixelSize = normalArgument & 0x1;
log(helper.getCommandString(TRXKICK) + " from 0x" + Integer.toHexString(textureTx_sourceAddress) + "(" + textureTx_sx + "," + textureTx_sy + ") to 0x" + Integer.toHexString(textureTx_destinationAddress) + "(" + textureTx_dx + "," + textureTx_dy + "), width=" + textureTx_width + ", height=" + textureTx_height);
if (!pspdisplay.get_instance().isGeAddress(textureTx_destinationAddress)) {
log(helper.getCommandString(TRXKICK) + " not in Ge Address space");
int width = textureTx_width;
int height = textureTx_height;
int bpp = ( textureTx_pixelSize == TRXKICK_16BIT_TEXEL_SIZE ) ? 2 : 4;
int srcAddress = textureTx_sourceAddress + (textureTx_sy * textureTx_sourceLineWidth + textureTx_sx) * bpp;
int dstAddress = textureTx_destinationAddress + (textureTx_dy * textureTx_destinationLineWidth + textureTx_dx) * bpp;
Memory memory = Memory.getInstance();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
memory.write32(dstAddress, memory.read32(srcAddress));
srcAddress += bpp;
dstAddress += bpp;
}
srcAddress += (textureTx_sourceLineWidth - width) * bpp;
dstAddress += (textureTx_destinationLineWidth - width) * bpp;
}
} else {
log(helper.getCommandString(TRXKICK) + " in Ge Address space");
if (textureTx_pixelSize == TRXKICK_16BIT_TEXEL_SIZE) {
log("Unsupported 16bit for video command [ " + helper.getCommandString(command(instruction)) + " ]");
break;
}
int width = textureTx_width;
int height = textureTx_height;
int dx = textureTx_dx;
int dy = textureTx_dy;
int lineWidth = textureTx_sourceLineWidth;
int bpp = (textureTx_pixelSize == TRXKICK_16BIT_TEXEL_SIZE) ? 2 : 4;
int[] textures = new int[1];
gl.glGenTextures(1, textures, 0);
int texture = textures[0];
gl.glBindTexture(GL.GL_TEXTURE_2D, texture);
gl.glPushAttrib(GL.GL_ENABLE_BIT);
gl.glDisable(GL.GL_DEPTH_TEST);
gl.glDisable(GL.GL_BLEND);
+ gl.glDisable(GL.GL_ALPHA_TEST);
+ gl.glDisable(GL.GL_FOG);
+ gl.glDisable(GL.GL_LIGHTING);
+ gl.glDisable(GL.GL_LOGIC_OP);
+ gl.glDisable(GL.GL_STENCIL_TEST);
gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, bpp);
gl.glPixelStorei(GL.GL_UNPACK_ROW_LENGTH, lineWidth);
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glPushMatrix();
gl.glLoadIdentity();
gl.glOrtho(0, 480, 272, 0, -1, 1);
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glPushMatrix ();
gl.glLoadIdentity();
ByteBuffer buffer = ByteBuffer.wrap(
Memory.getInstance().mainmemory.array(),
Memory.getInstance().mainmemory.arrayOffset() + textureTx_sourceAddress - MemoryMap.START_RAM,
lineWidth * height * bpp).slice();
//
// glTexImage2D only supports
// width = (1 << n) for some integer n
// height = (1 << m) for some integer m
//
// This the reason why we are also using glTexSubImage2D.
//
int bufferHeight = Utilities.makePow2(height);
gl.glTexImage2D(
GL.GL_TEXTURE_2D, 0,
GL.GL_RGBA,
lineWidth, bufferHeight, 0,
GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, null);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP);
gl.glTexSubImage2D(
GL.GL_TEXTURE_2D, 0,
textureTx_sx, textureTx_sy, width, height,
GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, buffer);
gl.glEnable(GL.GL_TEXTURE_2D);
gl.glBegin(GL.GL_QUADS);
gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
float texCoordX = width / (float) lineWidth;
float texCoordY = height / (float) bufferHeight;
gl.glTexCoord2f(0.0f, 0.0f);
gl.glVertex2i(dx, dy);
gl.glTexCoord2f(texCoordX, 0.0f);
gl.glVertex2i(dx + width, dy);
gl.glTexCoord2f(texCoordX, texCoordY);
gl.glVertex2i(dx + width, dy + height);
gl.glTexCoord2f(0.0f, texCoordY);
gl.glVertex2i(dx, dy + height);
gl.glEnd();
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glPopMatrix();
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glPopMatrix();
gl.glPopAttrib();
gl.glDeleteTextures(1, textures, 0);
}
break;
default:
log("Unknown/unimplemented video command [ " + helper.getCommandString(command(instruction)) + " ]");
}
}
private void doSkinning(VertexInfo vinfo, VertexState v) {
float x = 0, y = 0, z = 0;
float nx = 0, ny = 0, nz = 0;
for(int i = 0; i < vinfo.skinningWeightCount; ++i) {
if(v.boneWeights[i] != 0.f) {
x += ( v.px * bone_uploaded_matrix[i][0]
+ v.py * bone_uploaded_matrix[i][3]
+ v.pz * bone_uploaded_matrix[i][6]
+ bone_uploaded_matrix[i][9]) * v.boneWeights[i];
y += ( v.px * bone_uploaded_matrix[i][1]
+ v.py * bone_uploaded_matrix[i][4]
+ v.pz * bone_uploaded_matrix[i][7]
+ bone_uploaded_matrix[i][10]) * v.boneWeights[i];
z += ( v.px * bone_uploaded_matrix[i][2]
+ v.py * bone_uploaded_matrix[i][5]
+ v.pz * bone_uploaded_matrix[i][8]
+ bone_uploaded_matrix[i][11]) * v.boneWeights[i];
// Normals shouldn't be translated :)
nx += ( v.nx * bone_uploaded_matrix[i][0]
+ v.ny * bone_uploaded_matrix[i][3]
+ v.nz * bone_uploaded_matrix[i][6]) * v.boneWeights[i];
ny += ( v.nx * bone_uploaded_matrix[i][1]
+ v.ny * bone_uploaded_matrix[i][4]
+ v.nz * bone_uploaded_matrix[i][7]) * v.boneWeights[i];
nz += ( v.nx * bone_uploaded_matrix[i][2]
+ v.ny * bone_uploaded_matrix[i][5]
+ v.nz * bone_uploaded_matrix[i][8]) * v.boneWeights[i];
}
}
v.px = x; v.py = y; v.pz = z;
/*
// TODO: I doubt psp hardware normalizes normals after skinning,
// but if it does, this should be uncommented :)
float length = nx*nx + ny*ny + nz*nz;
if (length > 0.f) {
length = 1.f / (float)Math.sqrt(length);
nx *= length;
ny *= length;
nz *= length;
}
*/
v.nx = nx; v.ny = ny; v.nz = nz;
}
public void setFullScreenShoot(boolean b) {
}
public void setLineSize(int linesize) {
}
public void setMode(int mode) {
}
public void setPixelSize(int pixelsize) {
}
public void setup(int mode, int xres, int yres) {
}
public void show() {
}
public void waitVBlank() {
}
private void log(String commandString, float floatArgument) {
log(commandString+SPACE+floatArgument);
}
private void log(String commandString, int value) {
log(commandString+SPACE+value);
}
private void log(String commandString, float[] matrix) {
for (int y = 0; y < 4; y++) {
log(commandString+SPACE+String.format("%.1f %.1f %.1f %.1f", matrix[0 + y * 4], matrix[1 + y * 4], matrix[2 + y * 4], matrix[3 + y * 4]));
}
}
private void setHardwareAcc(boolean hardwareAccelerate) {
}
}
| true | true | public void executeCommand(int instruction) {
int normalArgument = intArgument(instruction);
float floatArgument = floatArgument(instruction);
switch (command(instruction)) {
case END:
listHasEnded = true;
log(helper.getCommandString(END));
break;
case FINISH:
listHasFinished = true;
log(helper.getCommandString(FINISH));
break;
case BASE:
actualList.base = normalArgument << 8;
log(helper.getCommandString(BASE) + " " + String.format("%08x", actualList.base));
break;
case IADDR:
vinfo.ptr_index = actualList.base | normalArgument;
log(helper.getCommandString(IADDR) + " " + String.format("%08x", vinfo.ptr_index));
break;
case VADDR:
vinfo.ptr_vertex = actualList.base | normalArgument;
log(helper.getCommandString(VADDR) + " " + String.format("%08x", vinfo.ptr_vertex));
break;
case VTYPE:
vinfo.processType(normalArgument);
transform_mode = (normalArgument >> 23) & 0x1;
log(helper.getCommandString(VTYPE) + " " + vinfo.toString());
break;
case TME:
if (normalArgument != 0) {
gl.glEnable(GL.GL_TEXTURE_2D);
log("sceGuEnable(GU_TEXTURE_2D)");
} else {
gl.glDisable(GL.GL_TEXTURE_2D);
log("sceGuDisable(GU_TEXTURE_2D)");
}
break;
case VMS:
view_upload_start = true;
log("sceGumMatrixMode GU_VIEW");
break;
case VIEW:
if (view_upload_start) {
view_upload_x = 0;
view_upload_y = 0;
view_upload_start = false;
}
if (view_upload_y < 4) {
if (view_upload_x < 3) {
view_matrix[view_upload_x + view_upload_y * 4] = floatArgument;
view_upload_x++;
if (view_upload_x == 3) {
view_matrix[view_upload_x + view_upload_y * 4] = (view_upload_y == 3) ? 1.0f : 0.0f;
view_upload_x = 0;
view_upload_y++;
if (view_upload_y == 4) {
log("glLoadMatrixf", view_matrix);
for (int i = 0; i < 4*4; i++)
view_uploaded_matrix[i] = view_matrix[i];
}
}
}
}
break;
case MMS:
model_upload_start = true;
log("sceGumMatrixMode GU_MODEL");
break;
case MODEL:
if (model_upload_start) {
model_upload_x = 0;
model_upload_y = 0;
model_upload_start = false;
}
if (model_upload_y < 4) {
if (model_upload_x < 3) {
model_matrix[model_upload_x + model_upload_y * 4] = floatArgument;
model_upload_x++;
if (model_upload_x == 3) {
model_matrix[model_upload_x + model_upload_y * 4] = (model_upload_y == 3) ? 1.0f : 0.0f;
model_upload_x = 0;
model_upload_y++;
if (model_upload_y == 4) {
log("glLoadMatrixf", model_matrix);
for (int i = 0; i < 4*4; i++)
model_uploaded_matrix[i] = model_matrix[i];
}
}
}
}
break;
/*
* Light 0 attributes
*/
// Position
case LXP0:
light_pos[0][0] = floatArgument;
break;
case LYP0:
light_pos[0][1] = floatArgument;
break;
case LZP0:
light_pos[0][2] = floatArgument;
break;
// Color
case ALC0: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT0, GL.GL_AMBIENT, color, 0);
log("sceGuLightColor (GU_LIGHT0, GU_AMBIENT)");
break;
}
case DLC0: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, color, 0);
log("sceGuLightColor (GU_LIGHT0, GU_DIFFUSE)");
break;
}
case SLC0: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT0, GL.GL_SPECULAR, color, 0);
log("sceGuLightColor (GU_LIGHT0, GU_SPECULAR)");
break;
}
// Attenuation
case LCA0:
gl.glLightf(GL.GL_LIGHT0, GL.GL_CONSTANT_ATTENUATION, floatArgument);
break;
case LLA0:
gl.glLightf(GL.GL_LIGHT0, GL.GL_LINEAR_ATTENUATION, floatArgument);
break;
case LQA0:
gl.glLightf(GL.GL_LIGHT0, GL.GL_QUADRATIC_ATTENUATION, floatArgument);
break;
/*
* Light 1 attributes
*/
// Position
case LXP1:
light_pos[1][0] = floatArgument;
break;
case LYP1:
light_pos[1][1] = floatArgument;
break;
case LZP1:
light_pos[1][2] = floatArgument;
break;
// Color
case ALC1: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT1, GL.GL_AMBIENT, color, 0);
log("sceGuLightColor (GU_LIGHT1, GU_AMBIENT)");
break;
}
case DLC1: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT1, GL.GL_DIFFUSE, color, 0);
log("sceGuLightColor (GU_LIGHT1, GU_DIFFUSE)");
break;
}
case SLC1: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT1, GL.GL_SPECULAR, color, 0);
log("sceGuLightColor (GU_LIGHT1, GU_SPECULAR)");
break;
}
// Attenuation
case LCA1:
gl.glLightf(GL.GL_LIGHT1, GL.GL_CONSTANT_ATTENUATION, floatArgument);
break;
case LLA1:
gl.glLightf(GL.GL_LIGHT1, GL.GL_LINEAR_ATTENUATION, floatArgument);
break;
case LQA1:
gl.glLightf(GL.GL_LIGHT1, GL.GL_QUADRATIC_ATTENUATION, floatArgument);
break;
/*
* Light 2 attributes
*/
// Position
case LXP2:
light_pos[2][0] = floatArgument;
break;
case LYP2:
light_pos[2][1] = floatArgument;
break;
case LZP2:
light_pos[2][2] = floatArgument;
break;
// Color
case ALC2: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT2, GL.GL_AMBIENT, color, 0);
log("sceGuLightColor (GU_LIGHT2, GU_AMBIENT)");
break;
}
case DLC2: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT2, GL.GL_DIFFUSE, color, 0);
log("sceGuLightColor (GU_LIGHT2, GU_DIFFUSE)");
break;
}
case SLC2: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT2, GL.GL_SPECULAR, color, 0);
log("sceGuLightColor (GU_LIGHT2, GU_SPECULAR)");
break;
}
// Attenuation
case LCA2:
gl.glLightf(GL.GL_LIGHT2, GL.GL_CONSTANT_ATTENUATION, floatArgument);
break;
case LLA2:
gl.glLightf(GL.GL_LIGHT2, GL.GL_LINEAR_ATTENUATION, floatArgument);
break;
case LQA2:
gl.glLightf(GL.GL_LIGHT2, GL.GL_QUADRATIC_ATTENUATION, floatArgument);
break;
/*
* Light 3 attributes
*/
// Position
case LXP3:
light_pos[3][0] = floatArgument;
break;
case LYP3:
light_pos[3][1] = floatArgument;
break;
case LZP3:
light_pos[3][2] = floatArgument;
break;
// Color
case ALC3: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT3, GL.GL_AMBIENT, color, 0);
log("sceGuLightColor (GU_LIGHT3, GU_AMBIENT)");
break;
}
case DLC3: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT3, GL.GL_DIFFUSE, color, 0);
log("sceGuLightColor (GU_LIGHT3, GU_DIFFUSE)");
break;
}
case SLC3: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT3, GL.GL_SPECULAR, color, 0);
log("sceGuLightColor (GU_LIGHT3, GU_SPECULAR)");
break;
}
// Attenuation
case LCA3:
gl.glLightf(GL.GL_LIGHT3, GL.GL_CONSTANT_ATTENUATION, floatArgument);
break;
case LLA3:
gl.glLightf(GL.GL_LIGHT3, GL.GL_LINEAR_ATTENUATION, floatArgument);
break;
case LQA3:
gl.glLightf(GL.GL_LIGHT3, GL.GL_QUADRATIC_ATTENUATION, floatArgument);
break;
/*
* Light types
*/
case LT0: {
light_type[0] = normalArgument;
if (light_type[0] == LIGTH_DIRECTIONAL)
light_pos[0][3] = 0.f;
else
light_pos[0][3] = 1.f;
break;
}
case LT1: {
light_type[1] = normalArgument;
if (light_type[1] == LIGTH_DIRECTIONAL)
light_pos[1][3] = 0.f;
else
light_pos[1][3] = 1.f;
break;
}
case LT2: {
light_type[2] = normalArgument;
if (light_type[2] == LIGTH_DIRECTIONAL)
light_pos[2][3] = 0.f;
else
light_pos[2][3] = 1.f;
break;
}
case LT3: {
light_type[3] = normalArgument;
if (light_type[3] == LIGTH_DIRECTIONAL)
light_pos[3][3] = 0.f;
else
light_pos[3][3] = 1.f;
break;
}
/*
* Individual lights enable/disable
*/
case LTE0:
if (normalArgument != 0) {
gl.glEnable(GL.GL_LIGHT0);
log("sceGuEnable(GL_LIGHT0)");
} else {
gl.glDisable(GL.GL_LIGHT0);
log("sceGuDisable(GL_LIGHT0)");
}
break;
case LTE1:
if (normalArgument != 0) {
gl.glEnable(GL.GL_LIGHT1);
log("sceGuEnable(GL_LIGHT1)");
} else {
gl.glDisable(GL.GL_LIGHT1);
log("sceGuDisable(GL_LIGHT1)");
}
break;
case LTE2:
if (normalArgument != 0) {
gl.glEnable(GL.GL_LIGHT2);
log("sceGuEnable(GL_LIGHT2)");
} else {
gl.glDisable(GL.GL_LIGHT2);
log("sceGuDisable(GL_LIGHT2)");
}
break;
case LTE3:
if (normalArgument != 0) {
gl.glEnable(GL.GL_LIGHT3);
log("sceGuEnable(GL_LIGHT3)");
} else {
gl.glDisable(GL.GL_LIGHT3);
log("sceGuDisable(GL_LIGHT3)");
}
break;
/*
* Lighting enable/disable
*/
case LTE:
if (normalArgument != 0) {
gl.glEnable(GL.GL_LIGHTING);
log("sceGuEnable(GL_LIGHTING)");
} else {
gl.glDisable(GL.GL_LIGHTING);
log("sceGuDisable(GL_LIGHTING)");
}
break;
/*
* Material setup
*/
case CMAT:
mat_flags = normalArgument & 7;
log("cmat");
break;
case AMA:
mat_ambient[3] = ((normalArgument ) & 255) / 255.f;
if((mat_flags & 1) != 0)
gl.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, mat_ambient, 0);
break;
case AMC:
mat_ambient[0] = ((normalArgument ) & 255) / 255.f;
mat_ambient[1] = ((normalArgument >> 8) & 255) / 255.f;
mat_ambient[2] = ((normalArgument >> 16) & 255) / 255.f;
if((mat_flags & 1) != 0)
gl.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, mat_ambient, 0);
log("sceGuAmbient " + String.format("r=%.1f g=%.1f b=%.1f (%08X)",
mat_ambient[0], mat_ambient[1], mat_ambient[2], normalArgument));
break;
case DMC:
mat_diffuse[0] = ((normalArgument ) & 255) / 255.f;
mat_diffuse[1] = ((normalArgument >> 8) & 255) / 255.f;
mat_diffuse[2] = ((normalArgument >> 16) & 255) / 255.f;
mat_diffuse[3] = 1.f;
if((mat_flags & 2) != 0)
gl.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, mat_diffuse, 0);
log("sceGuColor " + String.format("r=%.1f g=%.1f b=%.1f (%08X)",
mat_diffuse[0], mat_diffuse[1], mat_diffuse[2], normalArgument));
break;
case EMC:
mat_emissive[0] = ((normalArgument ) & 255) / 255.f;
mat_emissive[1] = ((normalArgument >> 8) & 255) / 255.f;
mat_emissive[2] = ((normalArgument >> 16) & 255) / 255.f;
mat_emissive[3] = 1.f;
gl.glMaterialfv(GL.GL_FRONT, GL.GL_EMISSION, mat_emissive, 0);
log("material emission " + String.format("r=%.1f g=%.1f b=%.1f (%08X)",
mat_emissive[0], mat_emissive[1], mat_emissive[2], normalArgument));
break;
case SMC:
mat_specular[0] = ((normalArgument ) & 255) / 255.f;
mat_specular[1] = ((normalArgument >> 8) & 255) / 255.f;
mat_specular[2] = ((normalArgument >> 16) & 255) / 255.f;
mat_specular[3] = 1.f;
if((mat_flags & 4) != 0)
gl.glMaterialfv(GL.GL_FRONT, GL.GL_SPECULAR, mat_specular, 0);
log("material specular " + String.format("r=%.1f g=%.1f b=%.1f (%08X)",
mat_specular[0], mat_specular[1], mat_specular[2], normalArgument));
break;
case SPOW:
gl.glMaterialf(GL.GL_FRONT, GL.GL_SHININESS, floatArgument);
log("material shininess");
break;
case TMS:
texture_upload_start = true;
log("sceGumMatrixMode GU_TEXTURE");
break;
case TMATRIX:
if (texture_upload_start) {
texture_upload_x = 0;
texture_upload_y = 0;
texture_upload_start = false;
}
if (texture_upload_y < 4) {
if (texture_upload_x < 4) {
texture_matrix[texture_upload_x + texture_upload_y * 4] = floatArgument;
texture_upload_x++;
if (texture_upload_x == 4) {
texture_upload_x = 0;
texture_upload_y++;
if (texture_upload_y == 4) {
log("glLoadMatrixf", texture_matrix);
for (int i = 0; i < 4*4; i++)
texture_uploaded_matrix[i] = texture_matrix[i];
}
}
}
}
break;
case PMS:
proj_upload_start = true;
log("sceGumMatrixMode GU_PROJECTION");
break;
case PROJ:
if (proj_upload_start) {
proj_upload_x = 0;
proj_upload_y = 0;
proj_upload_start = false;
}
if (proj_upload_y < 4) {
if (proj_upload_x < 4) {
proj_matrix[proj_upload_x + proj_upload_y * 4] = floatArgument;
proj_upload_x++;
if (proj_upload_x == 4) {
proj_upload_x = 0;
proj_upload_y++;
if (proj_upload_y == 4) {
log("glLoadMatrixf", proj_matrix);
for (int i = 0; i < 4*4; i++)
proj_uploaded_matrix[i] = proj_matrix[i];
}
}
}
}
break;
/*
*
*/
case TBW0:
texture_base_pointer0 = (texture_base_pointer0 & 0x00ffffff) | ((normalArgument << 8) & 0xff000000);
texture_buffer_width0 = normalArgument & 0xffff;
log ("sceGuTexImage(X,X,X,texWidth=" + texture_buffer_width0 + ",hi(pointer=0x" + Integer.toHexString(texture_base_pointer0) + "))");
break;
case TBP0:
texture_base_pointer0 = normalArgument;
log ("sceGuTexImage(X,X,X,X,lo(pointer=0x" + Integer.toHexString(texture_base_pointer0) + "))");
break;
case TSIZE0:
texture_height0 = 1 << ((normalArgument>>8) & 0xFF);
texture_width0 = 1 << ((normalArgument ) & 0xFF);
log ("sceGuTexImage(X,width=" + texture_width0 + ",height=" + texture_height0 + ",X,0)");
break;
case TMODE:
texture_num_mip_maps = (normalArgument>>16) & 0xFF;
texture_swizzle = ((normalArgument ) & 0xFF) != 0;
break;
case TPSM:
texture_storage = normalArgument;
break;
case CBP: {
tex_clut_addr = (tex_clut_addr & 0xff000000) | normalArgument;
log ("sceGuClutLoad(X, lo(cbp=0x" + Integer.toHexString(tex_clut_addr) + "))");
break;
}
case CBPH: {
tex_clut_addr = (tex_clut_addr & 0x00ffffff) | ((normalArgument << 8) & 0x0f000000);
log ("sceGuClutLoad(X, hi(cbp=0x" + Integer.toHexString(tex_clut_addr) + "))");
break;
}
case CLOAD: {
tex_clut_num_blocks = normalArgument;
log ("sceGuClutLoad(num_blocks=" + tex_clut_num_blocks + ", X)");
break;
}
case CMODE: {
tex_clut_mode = normalArgument & 0x03;
tex_clut_shift = (normalArgument >> 2) & 0x3F;
tex_clut_mask = (normalArgument >> 8) & 0xFF;
tex_clut_start = (normalArgument >> 16) & 0xFF;
log ("sceGuClutMode(cpsm=" + tex_clut_mode + ", shift=" + tex_clut_shift + ", mask=0x" + Integer.toHexString(tex_clut_mask) + ", start=" + tex_clut_start + ")");
break;
}
case TFLUSH:
{
// HACK: avoid texture uploads of null pointers
if (texture_base_pointer0 == 0)
break;
// Generate a texture id if we don't have one
if (gl_texture_id[0] == 0)
gl.glGenTextures(1, gl_texture_id, 0);
log(helper.getCommandString(TFLUSH) + " 0x" + Integer.toHexString(texture_base_pointer0) + "(" + texture_width0 + "," + texture_height0 + ")");
// Extract texture information with the minor conversion possible
// TODO: Get rid of information copying, and implement all the available formats
Memory mem = Memory.getInstance();
Buffer final_buffer = null;
int texture_type = 0;
int texclut = tex_clut_addr;
int texaddr = texture_base_pointer0;
texaddr &= 0xFFFFFFF;
final int[] texturetype_mapping = {
GL.GL_UNSIGNED_SHORT_5_6_5_REV,
GL.GL_UNSIGNED_SHORT_1_5_5_5_REV,
GL.GL_UNSIGNED_SHORT_4_4_4_4_REV,
GL.GL_UNSIGNED_BYTE,
};
int textureByteAlignment = 4; // 32 bits
switch (texture_storage) {
case TPSM_PIXEL_STORAGE_MODE_4BIT_INDEXED: {
switch (tex_clut_mode) {
case CMODE_FORMAT_16BIT_BGR5650:
case CMODE_FORMAT_16BIT_ABGR5551:
case CMODE_FORMAT_16BIT_ABGR4444: {
if (texclut == 0)
return;
texture_type = texturetype_mapping[tex_clut_mode];
textureByteAlignment = 2; // 16 bits
if (!texture_swizzle) {
for (int i = 0, j = 0; i < texture_width0*texture_height0; i += 2, j++) {
int index = mem.read8(texaddr+j);
// TODO: I don't know if it's correct, or should read the 4bits in
// reverse order
tmp_texture_buffer16[i] = (short)mem.read16(texclut + getClutIndex((index >> 4) & 0xF) * 2);
tmp_texture_buffer16[i+1] = (short)mem.read16(texclut + getClutIndex( index & 0xF) * 2);
}
final_buffer = ShortBuffer.wrap(tmp_texture_buffer16);
} else {
VideoEngine.log.error("Unhandled swizzling on clut4/16 textures");
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
break;
}
break;
}
case CMODE_FORMAT_32BIT_ABGR8888: {
if (texclut == 0)
return;
texture_type = GL.GL_UNSIGNED_BYTE;
if (!texture_swizzle) {
for (int i = 0, j = 0; i < texture_width0*texture_height0; i += 2, j++) {
int index = mem.read8(texaddr+j);
// TODO: I don't know if it's correct, or should read the 4bits in
// reverse order
tmp_texture_buffer32[i] = mem.read32(texclut + getClutIndex((index >> 4) & 0xF) * 4);
tmp_texture_buffer32[i+1] = mem.read32(texclut + getClutIndex( index & 0xF) * 4);
}
final_buffer = IntBuffer.wrap(tmp_texture_buffer32);
} else {
//VideoEngine.log.error("Unhandled swizzling on clut4/32 textures");
//Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
final_buffer = unswizzleTexture32();
break;
}
break;
}
default: {
VideoEngine.log.error("Unhandled clut4 texture mode " + tex_clut_mode);
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
break;
}
}
break;
}
case TPSM_PIXEL_STORAGE_MODE_8BIT_INDEXED: {
switch (tex_clut_mode) {
case CMODE_FORMAT_16BIT_BGR5650:
case CMODE_FORMAT_16BIT_ABGR5551:
case CMODE_FORMAT_16BIT_ABGR4444: {
if (texclut == 0)
return;
texture_type = texturetype_mapping[tex_clut_mode];
textureByteAlignment = 2; // 16 bits
if (!texture_swizzle) {
for (int i = 0; i < texture_width0*texture_height0; i++) {
int index = mem.read8(texaddr+i);
tmp_texture_buffer16[i] = (short)mem.read16(texclut + getClutIndex(index) * 2);
}
final_buffer = ShortBuffer.wrap(tmp_texture_buffer16);
} else {
VideoEngine.log.error("Unhandled swizzling on clut8/16 textures");
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
break;
}
break;
}
case CMODE_FORMAT_32BIT_ABGR8888: {
if (texclut == 0)
return;
texture_type = GL.GL_UNSIGNED_BYTE;
if (!texture_swizzle) {
for (int i = 0; i < texture_width0*texture_height0; i++) {
int index = mem.read8(texaddr+i);
tmp_texture_buffer32[i] = mem.read32(texclut + getClutIndex(index) * 4);
}
final_buffer = IntBuffer.wrap(tmp_texture_buffer32);
} else {
//VideoEngine.log.error("Unhandled swizzling on clut8/32 textures");
//Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
final_buffer = unswizzleTexture32();
break;
}
break;
}
default: {
VideoEngine.log.error("Unhandled clut8 texture mode " + tex_clut_mode);
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
break;
}
}
break;
}
case TPSM_PIXEL_STORAGE_MODE_16BIT_BGR5650:
case TPSM_PIXEL_STORAGE_MODE_16BIT_ABGR5551:
case TPSM_PIXEL_STORAGE_MODE_16BIT_ABGR4444: {
texture_type = texturetype_mapping[texture_storage];
textureByteAlignment = 2; // 16 bits
if (!texture_swizzle) {
/* TODO replace the loop with 1 line to ShortBuffer.wrap
* but be careful of vram/mainram addresses
final_buffer = ShortBuffer.wrap(
memory.videoram.array(),
texaddr - MemoryMap.START_VRAM + memory.videoram.arrayOffset(),
texture_width0 * texture_height0).slice();
final_buffer = ShortBuffer.wrap(
memory.mainmemory.array(),
texaddr - MemoryMap.START_RAM + memory.mainmemory.arrayOffset(),
texture_width0 * texture_height0).slice();
*/
for (int i = 0; i < texture_width0*texture_height0; i++) {
int pixel = mem.read16(texaddr+i*2);
tmp_texture_buffer16[i] = (short)pixel;
}
final_buffer = ShortBuffer.wrap(tmp_texture_buffer16);
} else {
final_buffer = unswizzleTextureFromMemory(texaddr, 2);
}
break;
}
case TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888: {
texture_type = GL.GL_UNSIGNED_INT_8_8_8_8_REV;
if (!texture_swizzle) {
/* TODO replace the loop with 1 line to IntBuffer.wrap
* but be careful of vram/mainram addresses
final_buffer = IntBuffer.wrap(
memory.videoram.array(),
texaddr - MemoryMap.START_VRAM + memory.videoram.arrayOffset(),
texture_width0 * texture_height0).slice();
final_buffer = IntBuffer.wrap(
memory.mainmemory.array(),
texaddr - MemoryMap.START_RAM + memory.mainmemory.arrayOffset(),
texture_width0 * texture_height0).slice();
*/
for (int i = 0; i < texture_width0*texture_height0; i++) {
tmp_texture_buffer32[i] = mem.read32(texaddr+i*4);
}
final_buffer = IntBuffer.wrap(tmp_texture_buffer32);
} else {
final_buffer = unswizzleTextureFromMemory(texaddr, 4);
}
break;
}
default: {
System.out.println("Unhandled texture storage " + texture_storage);
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
break;
}
}
// Upload texture to openGL
// TODO: Write a texture cache :)
gl.glBindTexture (GL.GL_TEXTURE_2D, gl_texture_id[0]);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, tex_min_filter);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, tex_mag_filter);
gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, textureByteAlignment);
gl.glPixelStorei(GL.GL_UNPACK_ROW_LENGTH, 0); // ROW_LENGTH = width
int texture_format = texture_type == GL.GL_UNSIGNED_SHORT_5_6_5_REV ? GL.GL_RGB : GL.GL_RGBA;
gl.glTexImage2D ( GL.GL_TEXTURE_2D,
0,
texture_format,
texture_width0, texture_height0,
0,
texture_format,
texture_type,
final_buffer);
break;
}
case TFLT: {
log ("sceGuTexFilter(min, mag)");
switch ((normalArgument>>8) & 0xFF)
{
case TFLT_MAGNIFYING_FILTER_NEAREST: {
tex_mag_filter = GL.GL_NEAREST;
break;
}
case TFLT_MAGNIFYING_FILTER_LINEAR: {
tex_mag_filter = GL.GL_LINEAR;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_NEAREST_NEAREST: {
tex_mag_filter = GL.GL_NEAREST_MIPMAP_NEAREST;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_NEAREST_LINEAR: {
tex_mag_filter = GL.GL_NEAREST_MIPMAP_LINEAR;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_LINEAR_NEAREST: {
tex_mag_filter = GL.GL_LINEAR_MIPMAP_NEAREST;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_LINEAR_LINEAR: {
tex_mag_filter = GL.GL_LINEAR_MIPMAP_LINEAR;
break;
}
default: {
log ("Unknown magnifiying filter " + ((normalArgument>>8) & 0xFF));
break;
}
}
switch (normalArgument & 0xFF)
{
case TFLT_MAGNIFYING_FILTER_NEAREST: {
tex_min_filter = GL.GL_NEAREST;
break;
}
case TFLT_MAGNIFYING_FILTER_LINEAR: {
tex_min_filter = GL.GL_LINEAR;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_NEAREST_NEAREST: {
tex_min_filter = GL.GL_NEAREST_MIPMAP_NEAREST;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_NEAREST_LINEAR: {
tex_min_filter = GL.GL_NEAREST_MIPMAP_LINEAR;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_LINEAR_NEAREST: {
tex_min_filter = GL.GL_LINEAR_MIPMAP_NEAREST;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_LINEAR_LINEAR: {
tex_min_filter = GL.GL_LINEAR_MIPMAP_LINEAR;
break;
}
default: {
log ("Unknown minimizing filter " + (normalArgument & 0xFF));
break;
}
}
break;
}
/*
* Texture transformations
*/
case UOFFSET: {
tex_translate_x = floatArgument;
log ("sceGuTexOffset(float u, X)");
break;
}
case VOFFSET: {
tex_translate_y = floatArgument;
log ("sceGuTexOffset(X, float v)");
break;
}
case USCALE: {
tex_scale_x = floatArgument;
log (String.format("sceGuTexScale(u=%.2f, X)", tex_scale_x));
break;
}
case VSCALE: {
tex_scale_y = floatArgument;
log (String.format("sceGuTexScale(X, v=%.2f)", tex_scale_y));
break;
}
case TMAP: {
log ("sceGuTexMapMode(mode, X, X)");
tex_map_mode = normalArgument & 3;
break;
}
case TEXTURE_ENV_MAP_MATRIX: {
log ("sceGuTexMapMode(X, column1, column2)");
if (normalArgument != 0) {
int column0 = normalArgument & 0xFF,
column1 = (normalArgument>>8) & 0xFF;
for (int i = 0; i < 3; i++) {
tex_envmap_matrix [i+0] = light_pos[column0][i];
tex_envmap_matrix [i+4] = light_pos[column1][i];
}
}
break;
}
case TFUNC:
gl.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_RGB_SCALE, (normalArgument & 0x10000) != 0 ? 1.0f : 2.0f);
int env_mode = GL.GL_MODULATE;
switch(normalArgument & 7) {
case 0: env_mode = GL.GL_MODULATE; break;
case 1: env_mode = GL.GL_DECAL; break;
case 2: env_mode = GL.GL_BLEND; break;
case 3: env_mode = GL.GL_REPLACE; break;
case 4: env_mode = GL.GL_ADD; break;
default: VideoEngine.log.warn("Unimplemented tfunc mode");
}
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, env_mode);
// TODO : check this
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_SRC0_ALPHA, (normalArgument & 0x100) == 0 ? GL.GL_PREVIOUS : GL.GL_TEXTURE);
log("sceGuTexFunc");
/*log(String.format("sceGuTexFunc mode %08X", normalArgument)
+ (((normalArgument & 0x10000) != 0) ? " SCALE" : "")
+ (((normalArgument & 0x100) != 0) ? " ALPHA" : ""));*/
break;
case TEC:
tex_env_color[0] = ((normalArgument ) & 255) / 255.f;
tex_env_color[1] = ((normalArgument >> 8) & 255) / 255.f;
tex_env_color[2] = ((normalArgument >> 16) & 255) / 255.f;
tex_env_color[3] = 1.f;
gl.glTexEnvfv(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_COLOR, tex_env_color, 0);
log("tec");
break;
/*
*
*/
case XSCALE:
log("sceGuViewport width = " + (floatArgument * 2));
break;
case YSCALE:
log("sceGuViewport height = " + (- floatArgument * 2));
break;
// sceGuViewport cx/cy, can we discard these settings? it's only for clipping?
case XPOS:
log("sceGuViewport cx = " + floatArgument);
break;
case YPOS:
log("sceGuViewport cy = " + floatArgument);
break;
case ZPOS:
log(helper.getCommandString(ZPOS), floatArgument);
break;
// sceGuOffset, can we discard these settings? it's only for clipping?
case OFFSETX:
log("sceGuOffset x = " + (normalArgument >> 4));
break;
case OFFSETY:
log("sceGuOffset y = " + (normalArgument >> 4));
break;
case FBP:
// assign or OR lower 24-bits?
fbp = normalArgument;
break;
case FBW:
fbp &= 0xffffff;
fbp |= (normalArgument << 8) & 0xff000000;
fbw = (normalArgument) & 0xffff;
log("fbp=" + Integer.toHexString(fbp) + ", fbw=" + fbw);
jpcsp.HLE.pspdisplay.get_instance().hleDisplaySetGeBuf(fbp, fbw, psm);
break;
case ZBP:
// assign or OR lower 24-bits?
zbp = normalArgument;
break;
case ZBW:
zbp &= 0xffffff;
zbp |= (normalArgument << 8) & 0xff000000;
zbw = (normalArgument) & 0xffff;
log("zbp=" + Integer.toHexString(zbp) + ", zbw=" + zbw);
break;
case PSM:
psm = normalArgument;
log("psm=" + normalArgument);
break;
case PRIM:
{
int[] mapping = new int[] { GL.GL_POINTS, GL.GL_LINES, GL.GL_LINE_STRIP, GL.GL_TRIANGLES, GL.GL_TRIANGLE_STRIP, GL.GL_TRIANGLE_FAN };
int numberOfVertex = normalArgument & 0xFFFF;
int type = ((normalArgument >> 16) & 0x7);
// Logging
switch (type) {
case PRIM_POINT:
log(helper.getCommandString(PRIM) + " point " + numberOfVertex + "x");
break;
case PRIM_LINE:
log(helper.getCommandString(PRIM) + " line " + (numberOfVertex / 2) + "x");
break;
case PRIM_LINES_STRIPS:
log(helper.getCommandString(PRIM) + " lines_strips " + (numberOfVertex - 1) + "x");
break;
case PRIM_TRIANGLE:
log(helper.getCommandString(PRIM) + " triangle " + (numberOfVertex / 3) + "x");
break;
case PRIM_TRIANGLE_STRIPS:
log(helper.getCommandString(PRIM) + " triangle_strips " + (numberOfVertex - 2) + "x");
break;
case PRIM_TRIANGLE_FANS:
log(helper.getCommandString(PRIM) + " triangle_fans " + (numberOfVertex - 2) + "x");
break;
case PRIM_SPRITES:
log(helper.getCommandString(PRIM) + " sprites " + (numberOfVertex / 2) + "x");
break;
}
/*
* Defer transformations until primitive rendering
*/
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glPushMatrix ();
gl.glLoadIdentity();
if (transform_mode == VTYPE_TRANSFORM_PIPELINE_TRANS_COORD)
gl.glLoadMatrixf(proj_uploaded_matrix, 0);
else
gl.glOrtho(0.0, 480, 272, 0, -1.0, 1.0);
/*
* Apply texture transforms
*/
gl.glMatrixMode(GL.GL_TEXTURE);
gl.glPushMatrix ();
gl.glLoadIdentity();
gl.glTranslatef(tex_translate_x, tex_translate_y, 0.f);
if (transform_mode == VTYPE_TRANSFORM_PIPELINE_TRANS_COORD)
gl.glScalef(tex_scale_x, tex_scale_y, 1.f);
switch (tex_map_mode) {
case TMAP_TEXTURE_MAP_MODE_TEXTURE_COORDIATES_UV:
break;
case TMAP_TEXTURE_MAP_MODE_TEXTURE_MATRIX:
gl.glMultMatrixf (texture_uploaded_matrix, 0);
break;
case TMAP_TEXTURE_MAP_MODE_ENVIRONMENT_MAP: {
// First, setup texture uv generation
gl.glTexGeni(GL.GL_S, GL.GL_TEXTURE_GEN_MODE, GL.GL_SPHERE_MAP);
gl.glEnable (GL.GL_TEXTURE_GEN_S);
gl.glTexGeni(GL.GL_T, GL.GL_TEXTURE_GEN_MODE, GL.GL_SPHERE_MAP);
gl.glEnable (GL.GL_TEXTURE_GEN_T);
// Setup also texture matrix
gl.glMultMatrixf (tex_envmap_matrix, 0);
break;
}
default:
log ("Unhandled texture matrix mode " + tex_map_mode);
}
/*
* Apply view matrix
*/
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glPushMatrix ();
gl.glLoadIdentity();
if (transform_mode == VTYPE_TRANSFORM_PIPELINE_TRANS_COORD)
gl.glLoadMatrixf(view_uploaded_matrix, 0);
/*
* Setup lights on when view transformation is set up
*/
gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, light_pos[0], 0);
gl.glLightfv(GL.GL_LIGHT1, GL.GL_POSITION, light_pos[1], 0);
gl.glLightfv(GL.GL_LIGHT2, GL.GL_POSITION, light_pos[2], 0);
gl.glLightfv(GL.GL_LIGHT3, GL.GL_POSITION, light_pos[3], 0);
// Apply model matrix
if (transform_mode == VTYPE_TRANSFORM_PIPELINE_TRANS_COORD)
gl.glMultMatrixf(model_uploaded_matrix, 0);
// HACK: If we don't have a material set up, and have colors per vertex, this will
// override materials, so at least we'll see something, otherwise it would be black
if (vinfo.color != 0)
gl.glEnable(GL.GL_COLOR_MATERIAL);
Memory mem = Memory.getInstance();
switch (type) {
case PRIM_POINT:
case PRIM_LINE:
case PRIM_LINES_STRIPS:
case PRIM_TRIANGLE:
case PRIM_TRIANGLE_STRIPS:
case PRIM_TRIANGLE_FANS:
gl.glBegin(mapping[type]);
for (int i = 0; i < numberOfVertex; i++) {
int addr = vinfo.getAddress(mem, i);
VertexState v = vinfo.readVertex(mem, addr);
if (vinfo.texture != 0)
if(transform_mode == VTYPE_TRANSFORM_PIPELINE_RAW_COORD)
gl.glTexCoord2f(v.u / texture_width0, v.v / texture_height0);
else
gl.glTexCoord2f(v.u, v.v);
if (vinfo.color != 0) gl.glColor4f(v.r, v.g, v.b, v.a);
if (vinfo.normal != 0) gl.glNormal3f(v.nx, v.ny, v.nz);
if (vinfo.position != 0) {
if(vinfo.weight != 0)
doSkinning(vinfo, v);
gl.glVertex3f(v.px, v.py, v.pz);
}
}
gl.glEnd();
break;
case PRIM_SPRITES:
gl.glPushAttrib(GL.GL_ENABLE_BIT);
gl.glDisable(GL.GL_CULL_FACE);
gl.glBegin(GL.GL_QUADS);
for (int i = 0; i < numberOfVertex; i += 2) {
int addr1 = vinfo.getAddress(mem, i);
int addr2 = vinfo.getAddress(mem, i + 1);
VertexState v1 = vinfo.readVertex(mem, addr1);
VertexState v2 = vinfo.readVertex(mem, addr2);
// V1
if (vinfo.normal != 0) gl.glNormal3f(v1.nx, v1.ny, v1.nz);
if (vinfo.color != 0) gl.glColor4f(v2.r, v2.g, v2.b, v2.a); // color from v2 not v1
if (vinfo.texture != 0)
if(transform_mode == VTYPE_TRANSFORM_PIPELINE_RAW_COORD)
gl.glTexCoord2f(v1.u / texture_width0, v1.v / texture_height0);
else
gl.glTexCoord2f(v1.u, v1.v);
if (vinfo.position != 0) gl.glVertex3f(v1.px, v1.py, v1.pz);
if (vinfo.texture != 0)
if(transform_mode == VTYPE_TRANSFORM_PIPELINE_RAW_COORD)
gl.glTexCoord2f(v2.u / texture_width0, v1.v / texture_height0);
else
gl.glTexCoord2f(v2.u, v1.v);
if (vinfo.position != 0) gl.glVertex3f(v2.px, v1.py, v1.pz);
// V2
if (vinfo.normal != 0) gl.glNormal3f(v2.nx, v2.ny, v2.nz);
if (vinfo.color != 0) gl.glColor4f(v2.r, v2.g, v2.b, v2.a);
if (vinfo.texture != 0)
if(transform_mode == VTYPE_TRANSFORM_PIPELINE_RAW_COORD)
gl.glTexCoord2f(v2.u / texture_width0, v2.v / texture_height0);
else
gl.glTexCoord2f(v2.u, v2.v);
if (vinfo.position != 0) gl.glVertex3f(v2.px, v2.py, v1.pz);
if (vinfo.texture != 0)
if(transform_mode == VTYPE_TRANSFORM_PIPELINE_RAW_COORD)
gl.glTexCoord2f(v1.u / texture_width0, v2.v / texture_height0);
else
gl.glTexCoord2f(v1.u, v2.v);
if (vinfo.position != 0) gl.glVertex3f(v1.px, v2.py, v1.pz);
}
gl.glEnd();
gl.glPopAttrib();
break;
}
switch (tex_map_mode) {
case TMAP_TEXTURE_MAP_MODE_ENVIRONMENT_MAP: {
gl.glDisable (GL.GL_TEXTURE_GEN_S);
gl.glDisable (GL.GL_TEXTURE_GEN_T);
break;
}
}
gl.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_RGB_SCALE, 1.0f);
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_MODULATE);
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_SRC0_ALPHA, GL.GL_TEXTURE);
if (vinfo.color != 0)
gl.glDisable (GL.GL_COLOR_MATERIAL);
gl.glPopMatrix ();
gl.glMatrixMode (GL.GL_TEXTURE);
gl.glPopMatrix ();
gl.glMatrixMode (GL.GL_PROJECTION);
gl.glPopMatrix ();
gl.glMatrixMode (GL.GL_MODELVIEW);
break;
}
case ALPHA: {
int blend_mode = GL.GL_FUNC_ADD;
int src = getBlendSrc( normalArgument & 0xF);
int dst = getBlendOp((normalArgument >> 4 ) & 0xF);
int op = (normalArgument >> 8 ) & 0xF;
switch (op) {
case ALPHA_SOURCE_BLEND_OPERATION_ADD:
blend_mode = GL.GL_FUNC_ADD;
break;
case ALPHA_SOURCE_BLEND_OPERATION_SUBTRACT:
blend_mode = GL.GL_FUNC_SUBTRACT;
break;
case ALPHA_SOURCE_BLEND_OPERATION_REVERSE_SUBTRACT:
blend_mode = GL.GL_FUNC_REVERSE_SUBTRACT;
break;
case ALPHA_SOURCE_BLEND_OPERATION_MINIMUM_VALUE:
blend_mode = GL.GL_MIN;
break;
case ALPHA_SOURCE_BLEND_OPERATION_MAXIMUM_VALUE:
blend_mode = GL.GL_MAX;
break;
case ALPHA_SOURCE_BLEND_OPERATION_ABSOLUTE_VALUE:
blend_mode = GL.GL_FUNC_ADD;
break;
default:
VideoEngine.log.error("Unhandled blend mode " + op);
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
break;
}
try {
gl.glBlendEquation(blend_mode);
} catch (GLException e) {
log.warn("VideoEngine: " + e.getMessage());
}
gl.glBlendFunc(src, dst);
log ("sceGuBlendFunc(int op, int src, int dest, X, X)");
break;
}
case SHADE: {
int SETTED_MODEL = (normalArgument != 0) ? GL.GL_SMOOTH : GL.GL_FLAT;
gl.glShadeModel(SETTED_MODEL);
log(helper.getCommandString(SHADE) + " " + ((normalArgument != 0) ? "smooth" : "flat"));
break;
}
case FFACE: {
int frontFace = (normalArgument != 0) ? GL.GL_CW : GL.GL_CCW;
gl.glFrontFace(frontFace);
log(helper.getCommandString(FFACE) + " " + ((normalArgument != 0) ? "clockwise" : "counter-clockwise"));
break;
}
case DTE:
if(normalArgument != 0)
{
gl.glEnable(GL.GL_DITHER);
log("sceGuEnable(GL_DITHER)");
}
else
{
gl.glDisable(GL.GL_DITHER);
log("sceGuDisable(GL_DITHER)");
}
break;
case BCE:
if(normalArgument != 0)
{
gl.glEnable(GL.GL_CULL_FACE);
log("sceGuEnable(GU_CULL_FACE)");
}
else
{
gl.glDisable(GL.GL_CULL_FACE);
log("sceGuDisable(GU_CULL_FACE)");
}
break;
case FGE:
if(normalArgument != 0)
{
gl.glEnable(GL.GL_FOG);
gl.glFogi(GL.GL_FOG_MODE, GL.GL_LINEAR);
gl.glFogf(GL.GL_FOG_DENSITY, 0.1f);
gl.glHint(GL.GL_FOG_HINT, GL.GL_DONT_CARE);
log("sceGuEnable(GL_FOG)");
}
else
{
gl.glDisable(GL.GL_FOG);
log("sceGuDisable(GL_FOG)");
}
break;
case FCOL:
fog_color[0] = ((normalArgument ) & 255) / 255.f;
fog_color[1] = ((normalArgument >> 8) & 255) / 255.f;
fog_color[2] = ((normalArgument >> 16) & 255) / 255.f;
fog_color[3] = 1.f;
gl.glFogfv(GL.GL_FOG_COLOR, fog_color, 0);
log("FCOL");
break;
case FFAR:
fog_far = floatArgument;
break;
case FDIST:
fog_dist = floatArgument;
if((fog_far != 0.0f) && (fog_dist != 0.0f))
{
float end = fog_far;
float start = end - (1/floatArgument);
gl.glFogf( GL.GL_FOG_START, start );
gl.glFogf( GL.GL_FOG_END, end );
}
break;
case ABE:
if(normalArgument != 0) {
gl.glEnable(GL.GL_BLEND);
log("sceGuEnable(GU_BLEND)");
}
else {
gl.glDisable(GL.GL_BLEND);
log("sceGuDisable(GU_BLEND)");
}
break;
case ATE:
if(normalArgument != 0) {
gl.glEnable(GL.GL_ALPHA_TEST);
log("sceGuEnable(GL_ALPHA_TEST)");
}
else {
gl.glDisable(GL.GL_ALPHA_TEST);
log("sceGuDisable(GL_ALPHA_TEST)");
}
break;
case ZTE:
if(normalArgument != 0) {
gl.glEnable(GL.GL_DEPTH_TEST);
log("sceGuEnable(GU_DEPTH_TEST)");
}
else {
gl.glDisable(GL.GL_DEPTH_TEST);
log("sceGuDisable(GU_DEPTH_TEST)");
}
break;
case STE:
if(normalArgument != 0) {
gl.glEnable(GL.GL_STENCIL_TEST);
log("sceGuEnable(GU_STENCIL_TEST)");
}
else {
gl.glDisable(GL.GL_STENCIL_TEST);
log("sceGuDisable(GU_STENCIL_TEST)");
}
break;
case AAE:
if(normalArgument != 0)
{
gl.glEnable(GL.GL_LINE_SMOOTH);
gl.glHint(GL.GL_LINE_SMOOTH_HINT, GL.GL_NICEST);
log("sceGuEnable(GL_LINE_SMOOTH)");
}else
{
gl.glDisable(GL.GL_LINE_SMOOTH);
log("sceGuDisable(GL_LINE_SMOOTH)");
}
break;
case LOE:
if(normalArgument != 0)
{
gl.glEnable(GL.GL_COLOR_LOGIC_OP);
log("sceGuEnable(GU_COLOR_LOGIC_OP)");
}
else
{
gl.glDisable(GL.GL_COLOR_LOGIC_OP);
log("sceGuDisable(GU_COLOR_LOGIC_OP)");
}
break;
case JUMP:
{
int npc = (normalArgument | actualList.base) & 0xFFFFFFFC;
//I guess it must be unsign as psp player emulator
log(helper.getCommandString(JUMP) + " old PC:" + String.format("%08x", actualList.pc)
+ " new PC:" + String.format("%08x", npc));
actualList.pc = npc;
break;
}
case CALL:
{
actualList.stack[actualList.stackIndex++] = actualList.pc;
int npc = (normalArgument | actualList.base) & 0xFFFFFFFC;
log(helper.getCommandString(CALL) + " old PC:" + String.format("%08x", actualList.pc)
+ " new PC:" + String.format("%08x", npc));
actualList.pc = npc;
break;
}
case RET:
{
int npc = actualList.stack[--actualList.stackIndex];
log(helper.getCommandString(RET) + " old PC:" + String.format("%08x", actualList.pc)
+ " new PC:" + String.format("%08x", npc));
actualList.pc = npc;
break;
}
case ZMSK: {
// NOTE: PSP depth mask as 1 is meant to avoid depth writes,
// on pc it's the opposite
gl.glDepthMask(normalArgument == 1 ? false : true);
log ("sceGuDepthMask(disableWrites)");
break;
}
case ATST: {
int func = GL.GL_ALWAYS;
switch(normalArgument & 0xFF) {
case ATST_NEVER_PASS_PIXEL:
func = GL.GL_NEVER;
break;
case ATST_ALWAYS_PASS_PIXEL:
func = GL.GL_ALWAYS;
break;
case ATST_PASS_PIXEL_IF_MATCHES:
func = GL.GL_EQUAL;
break;
case ATST_PASS_PIXEL_IF_DIFFERS:
func = GL.GL_NOTEQUAL;
break;
case ATST_PASS_PIXEL_IF_LESS:
func = GL.GL_LESS;
break;
case ATST_PASS_PIXEL_IF_LESS_OR_EQUAL:
func = GL.GL_LEQUAL;
break;
case ATST_PASS_PIXEL_IF_GREATER:
func = GL.GL_GREATER;
break;
case ATST_PASS_PIXEL_IF_GREATER_OR_EQUAL:
func = GL.GL_GEQUAL;
break;
}
gl.glAlphaFunc(func,floatArgument);
log ("sceGuAlphaFunc(" + func + "," + floatArgument + ")");
break;
}
case STST: {
int func = GL.GL_ALWAYS;
switch (normalArgument & 0xFF) {
case STST_FUNCTION_NEVER_PASS_STENCIL_TEST:
func = GL.GL_NEVER;
break;
case STST_FUNCTION_ALWAYS_PASS_STENCIL_TEST:
func = GL.GL_ALWAYS;
break;
case STST_FUNCTION_PASS_TEST_IF_MATCHES:
func = GL.GL_EQUAL;
break;
case STST_FUNCTION_PASS_TEST_IF_DIFFERS:
func = GL.GL_NOTEQUAL;
break;
case STST_FUNCTION_PASS_TEST_IF_LESS:
func = GL.GL_LESS;
break;
case STST_FUNCTION_PASS_TEST_IF_LESS_OR_EQUAL:
func = GL.GL_LEQUAL;
break;
case STST_FUNCTION_PASS_TEST_IF_GREATER:
func = GL.GL_GREATER;
break;
case STST_FUNCTION_PASS_TEST_IF_GREATER_OR_EQUAL:
func = GL.GL_GEQUAL;
break;
}
gl.glStencilFunc (func, ((normalArgument>>8) & 0xff), (normalArgument>>16) & 0xff);
log ("sceGuStencilFunc(func, ref, mask)");
break;
}
case NEARZ : {
nearZ = ( float )( int )( short )normalArgument;
}
break;
case FARZ : {
if(nearZ > ( float )( int )( short )normalArgument)
{
farZ = nearZ;
nearZ = ( float )( int )( short )normalArgument;
}
else
farZ = ( float )( int )( short )normalArgument;
gl.glDepthRange(nearZ, farZ);
log ("sceGuDepthRange("+ nearZ + " ," + farZ + ")");
}
break;
case SOP: {
int fail = getStencilOp (normalArgument & 0xFF);
int zfail = getStencilOp ((normalArgument>> 8) & 0xFF);
int zpass = getStencilOp ((normalArgument>>16) & 0xFF);
gl.glStencilOp(fail, zfail, zpass);
break;
}
case CLEAR:
if ((normalArgument & 0x1)==0) {
// set clear color, actarus/sam
gl.glClearColor(vinfo.lastVertex.r, vinfo.lastVertex.g, vinfo.lastVertex.b, vinfo.lastVertex.a);
gl.glClear(clearFlags);
log(String.format("guclear r=%.1f g=%.1f b=%.1f a=%.1f", vinfo.lastVertex.r, vinfo.lastVertex.g, vinfo.lastVertex.b, vinfo.lastVertex.a));
} else {
clearFlags = 0;
if ((normalArgument & 0x100)!=0) clearFlags |= GL.GL_COLOR_BUFFER_BIT; // target
if ((normalArgument & 0x200)!=0) clearFlags |= GL.GL_STENCIL_BUFFER_BIT; // stencil/alpha
if ((normalArgument & 0x400)!=0) clearFlags |= GL.GL_DEPTH_BUFFER_BIT; // zbuffer
log("setting clear flags");
}
break;
case NOP:
log(helper.getCommandString(NOP));
break;
/*
* Skinning
*/
case BOFS: {
log("bone matrix offset", normalArgument);
if(normalArgument % 12 != 0)
VideoEngine.log.warn("bone matrix offset " + normalArgument + " isn't a multiple of 12");
bone_matrix_offset = normalArgument / (4*3);
bone_upload_start = true;
break;
}
case BONE: {
if (bone_upload_start) {
bone_upload_x = 0;
bone_upload_y = 0;
bone_upload_start = false;
}
if (bone_upload_x < 4) {
if (bone_upload_y < 3) {
bone_matrix[bone_upload_x + bone_upload_y * 4] = floatArgument;
bone_upload_x++;
if (bone_upload_x == 4) {
bone_upload_x = 0;
bone_upload_y++;
if (bone_upload_y == 3) {
log("bone matrix " + bone_matrix_offset, model_matrix);
for (int i = 0; i < 4*3; i++)
bone_uploaded_matrix[bone_matrix_offset][i] = bone_matrix[i];
}
}
}
}
break;
}
case MW0:
case MW1:
case MW2:
case MW3:
case MW4:
case MW5:
case MW6:
case MW7:
log("morph weight " + (command(instruction) - MW0), floatArgument);
morph_weight[command(instruction) - MW0] = floatArgument;
break;
case TRXSBP:
textureTx_sourceAddress = normalArgument;
break;
case TRXSBW:
textureTx_sourceAddress |= (normalArgument << 8) & 0xFF000000;
textureTx_sourceLineWidth = normalArgument & 0x0000FFFF;
break;
case TRXDBP:
textureTx_destinationAddress = normalArgument;
break;
case TRXDBW:
textureTx_destinationAddress |= (normalArgument << 8) & 0xFF000000;
textureTx_destinationLineWidth = normalArgument & 0x0000FFFF;
break;
case TRXSIZE:
textureTx_width = (normalArgument & 0x3FF) + 1;
textureTx_height = ((normalArgument >> 10) & 0x1FF) + 1;
break;
case TRXPOS:
textureTx_sx = normalArgument & 0x1FF;
textureTx_sy = (normalArgument >> 10) & 0x1FF;
break;
case TRXDPOS:
textureTx_dx = normalArgument & 0x1FF;
textureTx_dy = (normalArgument >> 10) & 0x1FF;
break;
case TRXKICK:
textureTx_pixelSize = normalArgument & 0x1;
log(helper.getCommandString(TRXKICK) + " from 0x" + Integer.toHexString(textureTx_sourceAddress) + "(" + textureTx_sx + "," + textureTx_sy + ") to 0x" + Integer.toHexString(textureTx_destinationAddress) + "(" + textureTx_dx + "," + textureTx_dy + "), width=" + textureTx_width + ", height=" + textureTx_height);
if (!pspdisplay.get_instance().isGeAddress(textureTx_destinationAddress)) {
log(helper.getCommandString(TRXKICK) + " not in Ge Address space");
int width = textureTx_width;
int height = textureTx_height;
int bpp = ( textureTx_pixelSize == TRXKICK_16BIT_TEXEL_SIZE ) ? 2 : 4;
int srcAddress = textureTx_sourceAddress + (textureTx_sy * textureTx_sourceLineWidth + textureTx_sx) * bpp;
int dstAddress = textureTx_destinationAddress + (textureTx_dy * textureTx_destinationLineWidth + textureTx_dx) * bpp;
Memory memory = Memory.getInstance();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
memory.write32(dstAddress, memory.read32(srcAddress));
srcAddress += bpp;
dstAddress += bpp;
}
srcAddress += (textureTx_sourceLineWidth - width) * bpp;
dstAddress += (textureTx_destinationLineWidth - width) * bpp;
}
} else {
log(helper.getCommandString(TRXKICK) + " in Ge Address space");
if (textureTx_pixelSize == TRXKICK_16BIT_TEXEL_SIZE) {
log("Unsupported 16bit for video command [ " + helper.getCommandString(command(instruction)) + " ]");
break;
}
int width = textureTx_width;
int height = textureTx_height;
int dx = textureTx_dx;
int dy = textureTx_dy;
int lineWidth = textureTx_sourceLineWidth;
int bpp = (textureTx_pixelSize == TRXKICK_16BIT_TEXEL_SIZE) ? 2 : 4;
int[] textures = new int[1];
gl.glGenTextures(1, textures, 0);
int texture = textures[0];
gl.glBindTexture(GL.GL_TEXTURE_2D, texture);
gl.glPushAttrib(GL.GL_ENABLE_BIT);
gl.glDisable(GL.GL_DEPTH_TEST);
gl.glDisable(GL.GL_BLEND);
gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, bpp);
gl.glPixelStorei(GL.GL_UNPACK_ROW_LENGTH, lineWidth);
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glPushMatrix();
gl.glLoadIdentity();
gl.glOrtho(0, 480, 272, 0, -1, 1);
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glPushMatrix ();
gl.glLoadIdentity();
ByteBuffer buffer = ByteBuffer.wrap(
Memory.getInstance().mainmemory.array(),
Memory.getInstance().mainmemory.arrayOffset() + textureTx_sourceAddress - MemoryMap.START_RAM,
lineWidth * height * bpp).slice();
//
// glTexImage2D only supports
// width = (1 << n) for some integer n
// height = (1 << m) for some integer m
//
// This the reason why we are also using glTexSubImage2D.
//
int bufferHeight = Utilities.makePow2(height);
gl.glTexImage2D(
GL.GL_TEXTURE_2D, 0,
GL.GL_RGBA,
lineWidth, bufferHeight, 0,
GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, null);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP);
gl.glTexSubImage2D(
GL.GL_TEXTURE_2D, 0,
textureTx_sx, textureTx_sy, width, height,
GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, buffer);
gl.glEnable(GL.GL_TEXTURE_2D);
gl.glBegin(GL.GL_QUADS);
gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
float texCoordX = width / (float) lineWidth;
float texCoordY = height / (float) bufferHeight;
gl.glTexCoord2f(0.0f, 0.0f);
gl.glVertex2i(dx, dy);
gl.glTexCoord2f(texCoordX, 0.0f);
gl.glVertex2i(dx + width, dy);
gl.glTexCoord2f(texCoordX, texCoordY);
gl.glVertex2i(dx + width, dy + height);
gl.glTexCoord2f(0.0f, texCoordY);
gl.glVertex2i(dx, dy + height);
gl.glEnd();
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glPopMatrix();
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glPopMatrix();
gl.glPopAttrib();
gl.glDeleteTextures(1, textures, 0);
}
break;
default:
log("Unknown/unimplemented video command [ " + helper.getCommandString(command(instruction)) + " ]");
}
}
| public void executeCommand(int instruction) {
int normalArgument = intArgument(instruction);
float floatArgument = floatArgument(instruction);
switch (command(instruction)) {
case END:
listHasEnded = true;
log(helper.getCommandString(END));
break;
case FINISH:
listHasFinished = true;
log(helper.getCommandString(FINISH));
break;
case BASE:
actualList.base = normalArgument << 8;
log(helper.getCommandString(BASE) + " " + String.format("%08x", actualList.base));
break;
case IADDR:
vinfo.ptr_index = actualList.base | normalArgument;
log(helper.getCommandString(IADDR) + " " + String.format("%08x", vinfo.ptr_index));
break;
case VADDR:
vinfo.ptr_vertex = actualList.base | normalArgument;
log(helper.getCommandString(VADDR) + " " + String.format("%08x", vinfo.ptr_vertex));
break;
case VTYPE:
vinfo.processType(normalArgument);
transform_mode = (normalArgument >> 23) & 0x1;
log(helper.getCommandString(VTYPE) + " " + vinfo.toString());
break;
case TME:
if (normalArgument != 0) {
gl.glEnable(GL.GL_TEXTURE_2D);
log("sceGuEnable(GU_TEXTURE_2D)");
} else {
gl.glDisable(GL.GL_TEXTURE_2D);
log("sceGuDisable(GU_TEXTURE_2D)");
}
break;
case VMS:
view_upload_start = true;
log("sceGumMatrixMode GU_VIEW");
break;
case VIEW:
if (view_upload_start) {
view_upload_x = 0;
view_upload_y = 0;
view_upload_start = false;
}
if (view_upload_y < 4) {
if (view_upload_x < 3) {
view_matrix[view_upload_x + view_upload_y * 4] = floatArgument;
view_upload_x++;
if (view_upload_x == 3) {
view_matrix[view_upload_x + view_upload_y * 4] = (view_upload_y == 3) ? 1.0f : 0.0f;
view_upload_x = 0;
view_upload_y++;
if (view_upload_y == 4) {
log("glLoadMatrixf", view_matrix);
for (int i = 0; i < 4*4; i++)
view_uploaded_matrix[i] = view_matrix[i];
}
}
}
}
break;
case MMS:
model_upload_start = true;
log("sceGumMatrixMode GU_MODEL");
break;
case MODEL:
if (model_upload_start) {
model_upload_x = 0;
model_upload_y = 0;
model_upload_start = false;
}
if (model_upload_y < 4) {
if (model_upload_x < 3) {
model_matrix[model_upload_x + model_upload_y * 4] = floatArgument;
model_upload_x++;
if (model_upload_x == 3) {
model_matrix[model_upload_x + model_upload_y * 4] = (model_upload_y == 3) ? 1.0f : 0.0f;
model_upload_x = 0;
model_upload_y++;
if (model_upload_y == 4) {
log("glLoadMatrixf", model_matrix);
for (int i = 0; i < 4*4; i++)
model_uploaded_matrix[i] = model_matrix[i];
}
}
}
}
break;
/*
* Light 0 attributes
*/
// Position
case LXP0:
light_pos[0][0] = floatArgument;
break;
case LYP0:
light_pos[0][1] = floatArgument;
break;
case LZP0:
light_pos[0][2] = floatArgument;
break;
// Color
case ALC0: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT0, GL.GL_AMBIENT, color, 0);
log("sceGuLightColor (GU_LIGHT0, GU_AMBIENT)");
break;
}
case DLC0: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, color, 0);
log("sceGuLightColor (GU_LIGHT0, GU_DIFFUSE)");
break;
}
case SLC0: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT0, GL.GL_SPECULAR, color, 0);
log("sceGuLightColor (GU_LIGHT0, GU_SPECULAR)");
break;
}
// Attenuation
case LCA0:
gl.glLightf(GL.GL_LIGHT0, GL.GL_CONSTANT_ATTENUATION, floatArgument);
break;
case LLA0:
gl.glLightf(GL.GL_LIGHT0, GL.GL_LINEAR_ATTENUATION, floatArgument);
break;
case LQA0:
gl.glLightf(GL.GL_LIGHT0, GL.GL_QUADRATIC_ATTENUATION, floatArgument);
break;
/*
* Light 1 attributes
*/
// Position
case LXP1:
light_pos[1][0] = floatArgument;
break;
case LYP1:
light_pos[1][1] = floatArgument;
break;
case LZP1:
light_pos[1][2] = floatArgument;
break;
// Color
case ALC1: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT1, GL.GL_AMBIENT, color, 0);
log("sceGuLightColor (GU_LIGHT1, GU_AMBIENT)");
break;
}
case DLC1: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT1, GL.GL_DIFFUSE, color, 0);
log("sceGuLightColor (GU_LIGHT1, GU_DIFFUSE)");
break;
}
case SLC1: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT1, GL.GL_SPECULAR, color, 0);
log("sceGuLightColor (GU_LIGHT1, GU_SPECULAR)");
break;
}
// Attenuation
case LCA1:
gl.glLightf(GL.GL_LIGHT1, GL.GL_CONSTANT_ATTENUATION, floatArgument);
break;
case LLA1:
gl.glLightf(GL.GL_LIGHT1, GL.GL_LINEAR_ATTENUATION, floatArgument);
break;
case LQA1:
gl.glLightf(GL.GL_LIGHT1, GL.GL_QUADRATIC_ATTENUATION, floatArgument);
break;
/*
* Light 2 attributes
*/
// Position
case LXP2:
light_pos[2][0] = floatArgument;
break;
case LYP2:
light_pos[2][1] = floatArgument;
break;
case LZP2:
light_pos[2][2] = floatArgument;
break;
// Color
case ALC2: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT2, GL.GL_AMBIENT, color, 0);
log("sceGuLightColor (GU_LIGHT2, GU_AMBIENT)");
break;
}
case DLC2: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT2, GL.GL_DIFFUSE, color, 0);
log("sceGuLightColor (GU_LIGHT2, GU_DIFFUSE)");
break;
}
case SLC2: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT2, GL.GL_SPECULAR, color, 0);
log("sceGuLightColor (GU_LIGHT2, GU_SPECULAR)");
break;
}
// Attenuation
case LCA2:
gl.glLightf(GL.GL_LIGHT2, GL.GL_CONSTANT_ATTENUATION, floatArgument);
break;
case LLA2:
gl.glLightf(GL.GL_LIGHT2, GL.GL_LINEAR_ATTENUATION, floatArgument);
break;
case LQA2:
gl.glLightf(GL.GL_LIGHT2, GL.GL_QUADRATIC_ATTENUATION, floatArgument);
break;
/*
* Light 3 attributes
*/
// Position
case LXP3:
light_pos[3][0] = floatArgument;
break;
case LYP3:
light_pos[3][1] = floatArgument;
break;
case LZP3:
light_pos[3][2] = floatArgument;
break;
// Color
case ALC3: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT3, GL.GL_AMBIENT, color, 0);
log("sceGuLightColor (GU_LIGHT3, GU_AMBIENT)");
break;
}
case DLC3: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT3, GL.GL_DIFFUSE, color, 0);
log("sceGuLightColor (GU_LIGHT3, GU_DIFFUSE)");
break;
}
case SLC3: {
float [] color = new float[4];
color[0] = ((normalArgument ) & 255) / 255.f;
color[1] = ((normalArgument >> 8) & 255) / 255.f;
color[2] = ((normalArgument >> 16) & 255) / 255.f;
color[3] = 1.f;
gl.glLightfv(GL.GL_LIGHT3, GL.GL_SPECULAR, color, 0);
log("sceGuLightColor (GU_LIGHT3, GU_SPECULAR)");
break;
}
// Attenuation
case LCA3:
gl.glLightf(GL.GL_LIGHT3, GL.GL_CONSTANT_ATTENUATION, floatArgument);
break;
case LLA3:
gl.glLightf(GL.GL_LIGHT3, GL.GL_LINEAR_ATTENUATION, floatArgument);
break;
case LQA3:
gl.glLightf(GL.GL_LIGHT3, GL.GL_QUADRATIC_ATTENUATION, floatArgument);
break;
/*
* Light types
*/
case LT0: {
light_type[0] = normalArgument;
if (light_type[0] == LIGTH_DIRECTIONAL)
light_pos[0][3] = 0.f;
else
light_pos[0][3] = 1.f;
break;
}
case LT1: {
light_type[1] = normalArgument;
if (light_type[1] == LIGTH_DIRECTIONAL)
light_pos[1][3] = 0.f;
else
light_pos[1][3] = 1.f;
break;
}
case LT2: {
light_type[2] = normalArgument;
if (light_type[2] == LIGTH_DIRECTIONAL)
light_pos[2][3] = 0.f;
else
light_pos[2][3] = 1.f;
break;
}
case LT3: {
light_type[3] = normalArgument;
if (light_type[3] == LIGTH_DIRECTIONAL)
light_pos[3][3] = 0.f;
else
light_pos[3][3] = 1.f;
break;
}
/*
* Individual lights enable/disable
*/
case LTE0:
if (normalArgument != 0) {
gl.glEnable(GL.GL_LIGHT0);
log("sceGuEnable(GL_LIGHT0)");
} else {
gl.glDisable(GL.GL_LIGHT0);
log("sceGuDisable(GL_LIGHT0)");
}
break;
case LTE1:
if (normalArgument != 0) {
gl.glEnable(GL.GL_LIGHT1);
log("sceGuEnable(GL_LIGHT1)");
} else {
gl.glDisable(GL.GL_LIGHT1);
log("sceGuDisable(GL_LIGHT1)");
}
break;
case LTE2:
if (normalArgument != 0) {
gl.glEnable(GL.GL_LIGHT2);
log("sceGuEnable(GL_LIGHT2)");
} else {
gl.glDisable(GL.GL_LIGHT2);
log("sceGuDisable(GL_LIGHT2)");
}
break;
case LTE3:
if (normalArgument != 0) {
gl.glEnable(GL.GL_LIGHT3);
log("sceGuEnable(GL_LIGHT3)");
} else {
gl.glDisable(GL.GL_LIGHT3);
log("sceGuDisable(GL_LIGHT3)");
}
break;
/*
* Lighting enable/disable
*/
case LTE:
if (normalArgument != 0) {
gl.glEnable(GL.GL_LIGHTING);
log("sceGuEnable(GL_LIGHTING)");
} else {
gl.glDisable(GL.GL_LIGHTING);
log("sceGuDisable(GL_LIGHTING)");
}
break;
/*
* Material setup
*/
case CMAT:
mat_flags = normalArgument & 7;
log("cmat");
break;
case AMA:
mat_ambient[3] = ((normalArgument ) & 255) / 255.f;
if((mat_flags & 1) != 0)
gl.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, mat_ambient, 0);
break;
case AMC:
mat_ambient[0] = ((normalArgument ) & 255) / 255.f;
mat_ambient[1] = ((normalArgument >> 8) & 255) / 255.f;
mat_ambient[2] = ((normalArgument >> 16) & 255) / 255.f;
if((mat_flags & 1) != 0)
gl.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, mat_ambient, 0);
log("sceGuAmbient " + String.format("r=%.1f g=%.1f b=%.1f (%08X)",
mat_ambient[0], mat_ambient[1], mat_ambient[2], normalArgument));
break;
case DMC:
mat_diffuse[0] = ((normalArgument ) & 255) / 255.f;
mat_diffuse[1] = ((normalArgument >> 8) & 255) / 255.f;
mat_diffuse[2] = ((normalArgument >> 16) & 255) / 255.f;
mat_diffuse[3] = 1.f;
if((mat_flags & 2) != 0)
gl.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, mat_diffuse, 0);
log("sceGuColor " + String.format("r=%.1f g=%.1f b=%.1f (%08X)",
mat_diffuse[0], mat_diffuse[1], mat_diffuse[2], normalArgument));
break;
case EMC:
mat_emissive[0] = ((normalArgument ) & 255) / 255.f;
mat_emissive[1] = ((normalArgument >> 8) & 255) / 255.f;
mat_emissive[2] = ((normalArgument >> 16) & 255) / 255.f;
mat_emissive[3] = 1.f;
gl.glMaterialfv(GL.GL_FRONT, GL.GL_EMISSION, mat_emissive, 0);
log("material emission " + String.format("r=%.1f g=%.1f b=%.1f (%08X)",
mat_emissive[0], mat_emissive[1], mat_emissive[2], normalArgument));
break;
case SMC:
mat_specular[0] = ((normalArgument ) & 255) / 255.f;
mat_specular[1] = ((normalArgument >> 8) & 255) / 255.f;
mat_specular[2] = ((normalArgument >> 16) & 255) / 255.f;
mat_specular[3] = 1.f;
if((mat_flags & 4) != 0)
gl.glMaterialfv(GL.GL_FRONT, GL.GL_SPECULAR, mat_specular, 0);
log("material specular " + String.format("r=%.1f g=%.1f b=%.1f (%08X)",
mat_specular[0], mat_specular[1], mat_specular[2], normalArgument));
break;
case SPOW:
gl.glMaterialf(GL.GL_FRONT, GL.GL_SHININESS, floatArgument);
log("material shininess");
break;
case TMS:
texture_upload_start = true;
log("sceGumMatrixMode GU_TEXTURE");
break;
case TMATRIX:
if (texture_upload_start) {
texture_upload_x = 0;
texture_upload_y = 0;
texture_upload_start = false;
}
if (texture_upload_y < 4) {
if (texture_upload_x < 4) {
texture_matrix[texture_upload_x + texture_upload_y * 4] = floatArgument;
texture_upload_x++;
if (texture_upload_x == 4) {
texture_upload_x = 0;
texture_upload_y++;
if (texture_upload_y == 4) {
log("glLoadMatrixf", texture_matrix);
for (int i = 0; i < 4*4; i++)
texture_uploaded_matrix[i] = texture_matrix[i];
}
}
}
}
break;
case PMS:
proj_upload_start = true;
log("sceGumMatrixMode GU_PROJECTION");
break;
case PROJ:
if (proj_upload_start) {
proj_upload_x = 0;
proj_upload_y = 0;
proj_upload_start = false;
}
if (proj_upload_y < 4) {
if (proj_upload_x < 4) {
proj_matrix[proj_upload_x + proj_upload_y * 4] = floatArgument;
proj_upload_x++;
if (proj_upload_x == 4) {
proj_upload_x = 0;
proj_upload_y++;
if (proj_upload_y == 4) {
log("glLoadMatrixf", proj_matrix);
for (int i = 0; i < 4*4; i++)
proj_uploaded_matrix[i] = proj_matrix[i];
}
}
}
}
break;
/*
*
*/
case TBW0:
texture_base_pointer0 = (texture_base_pointer0 & 0x00ffffff) | ((normalArgument << 8) & 0xff000000);
texture_buffer_width0 = normalArgument & 0xffff;
log ("sceGuTexImage(X,X,X,texWidth=" + texture_buffer_width0 + ",hi(pointer=0x" + Integer.toHexString(texture_base_pointer0) + "))");
break;
case TBP0:
texture_base_pointer0 = normalArgument;
log ("sceGuTexImage(X,X,X,X,lo(pointer=0x" + Integer.toHexString(texture_base_pointer0) + "))");
break;
case TSIZE0:
texture_height0 = 1 << ((normalArgument>>8) & 0xFF);
texture_width0 = 1 << ((normalArgument ) & 0xFF);
log ("sceGuTexImage(X,width=" + texture_width0 + ",height=" + texture_height0 + ",X,0)");
break;
case TMODE:
texture_num_mip_maps = (normalArgument>>16) & 0xFF;
texture_swizzle = ((normalArgument ) & 0xFF) != 0;
break;
case TPSM:
texture_storage = normalArgument;
break;
case CBP: {
tex_clut_addr = (tex_clut_addr & 0xff000000) | normalArgument;
log ("sceGuClutLoad(X, lo(cbp=0x" + Integer.toHexString(tex_clut_addr) + "))");
break;
}
case CBPH: {
tex_clut_addr = (tex_clut_addr & 0x00ffffff) | ((normalArgument << 8) & 0x0f000000);
log ("sceGuClutLoad(X, hi(cbp=0x" + Integer.toHexString(tex_clut_addr) + "))");
break;
}
case CLOAD: {
tex_clut_num_blocks = normalArgument;
log ("sceGuClutLoad(num_blocks=" + tex_clut_num_blocks + ", X)");
break;
}
case CMODE: {
tex_clut_mode = normalArgument & 0x03;
tex_clut_shift = (normalArgument >> 2) & 0x3F;
tex_clut_mask = (normalArgument >> 8) & 0xFF;
tex_clut_start = (normalArgument >> 16) & 0xFF;
log ("sceGuClutMode(cpsm=" + tex_clut_mode + ", shift=" + tex_clut_shift + ", mask=0x" + Integer.toHexString(tex_clut_mask) + ", start=" + tex_clut_start + ")");
break;
}
case TFLUSH:
{
// HACK: avoid texture uploads of null pointers
if (texture_base_pointer0 == 0)
break;
// Generate a texture id if we don't have one
if (gl_texture_id[0] == 0)
gl.glGenTextures(1, gl_texture_id, 0);
log(helper.getCommandString(TFLUSH) + " 0x" + Integer.toHexString(texture_base_pointer0) + "(" + texture_width0 + "," + texture_height0 + ")");
// Extract texture information with the minor conversion possible
// TODO: Get rid of information copying, and implement all the available formats
Memory mem = Memory.getInstance();
Buffer final_buffer = null;
int texture_type = 0;
int texclut = tex_clut_addr;
int texaddr = texture_base_pointer0;
texaddr &= 0xFFFFFFF;
final int[] texturetype_mapping = {
GL.GL_UNSIGNED_SHORT_5_6_5_REV,
GL.GL_UNSIGNED_SHORT_1_5_5_5_REV,
GL.GL_UNSIGNED_SHORT_4_4_4_4_REV,
GL.GL_UNSIGNED_BYTE,
};
int textureByteAlignment = 4; // 32 bits
switch (texture_storage) {
case TPSM_PIXEL_STORAGE_MODE_4BIT_INDEXED: {
switch (tex_clut_mode) {
case CMODE_FORMAT_16BIT_BGR5650:
case CMODE_FORMAT_16BIT_ABGR5551:
case CMODE_FORMAT_16BIT_ABGR4444: {
if (texclut == 0)
return;
texture_type = texturetype_mapping[tex_clut_mode];
textureByteAlignment = 2; // 16 bits
if (!texture_swizzle) {
for (int i = 0, j = 0; i < texture_width0*texture_height0; i += 2, j++) {
int index = mem.read8(texaddr+j);
// TODO: I don't know if it's correct, or should read the 4bits in
// reverse order
tmp_texture_buffer16[i] = (short)mem.read16(texclut + getClutIndex((index >> 4) & 0xF) * 2);
tmp_texture_buffer16[i+1] = (short)mem.read16(texclut + getClutIndex( index & 0xF) * 2);
}
final_buffer = ShortBuffer.wrap(tmp_texture_buffer16);
} else {
VideoEngine.log.error("Unhandled swizzling on clut4/16 textures");
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
break;
}
break;
}
case CMODE_FORMAT_32BIT_ABGR8888: {
if (texclut == 0)
return;
texture_type = GL.GL_UNSIGNED_BYTE;
if (!texture_swizzle) {
for (int i = 0, j = 0; i < texture_width0*texture_height0; i += 2, j++) {
int index = mem.read8(texaddr+j);
// TODO: I don't know if it's correct, or should read the 4bits in
// reverse order
tmp_texture_buffer32[i] = mem.read32(texclut + getClutIndex((index >> 4) & 0xF) * 4);
tmp_texture_buffer32[i+1] = mem.read32(texclut + getClutIndex( index & 0xF) * 4);
}
final_buffer = IntBuffer.wrap(tmp_texture_buffer32);
} else {
//VideoEngine.log.error("Unhandled swizzling on clut4/32 textures");
//Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
final_buffer = unswizzleTexture32();
break;
}
break;
}
default: {
VideoEngine.log.error("Unhandled clut4 texture mode " + tex_clut_mode);
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
break;
}
}
break;
}
case TPSM_PIXEL_STORAGE_MODE_8BIT_INDEXED: {
switch (tex_clut_mode) {
case CMODE_FORMAT_16BIT_BGR5650:
case CMODE_FORMAT_16BIT_ABGR5551:
case CMODE_FORMAT_16BIT_ABGR4444: {
if (texclut == 0)
return;
texture_type = texturetype_mapping[tex_clut_mode];
textureByteAlignment = 2; // 16 bits
if (!texture_swizzle) {
for (int i = 0; i < texture_width0*texture_height0; i++) {
int index = mem.read8(texaddr+i);
tmp_texture_buffer16[i] = (short)mem.read16(texclut + getClutIndex(index) * 2);
}
final_buffer = ShortBuffer.wrap(tmp_texture_buffer16);
} else {
VideoEngine.log.error("Unhandled swizzling on clut8/16 textures");
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
break;
}
break;
}
case CMODE_FORMAT_32BIT_ABGR8888: {
if (texclut == 0)
return;
texture_type = GL.GL_UNSIGNED_BYTE;
if (!texture_swizzle) {
for (int i = 0; i < texture_width0*texture_height0; i++) {
int index = mem.read8(texaddr+i);
tmp_texture_buffer32[i] = mem.read32(texclut + getClutIndex(index) * 4);
}
final_buffer = IntBuffer.wrap(tmp_texture_buffer32);
} else {
//VideoEngine.log.error("Unhandled swizzling on clut8/32 textures");
//Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
final_buffer = unswizzleTexture32();
break;
}
break;
}
default: {
VideoEngine.log.error("Unhandled clut8 texture mode " + tex_clut_mode);
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
break;
}
}
break;
}
case TPSM_PIXEL_STORAGE_MODE_16BIT_BGR5650:
case TPSM_PIXEL_STORAGE_MODE_16BIT_ABGR5551:
case TPSM_PIXEL_STORAGE_MODE_16BIT_ABGR4444: {
texture_type = texturetype_mapping[texture_storage];
textureByteAlignment = 2; // 16 bits
if (!texture_swizzle) {
/* TODO replace the loop with 1 line to ShortBuffer.wrap
* but be careful of vram/mainram addresses
final_buffer = ShortBuffer.wrap(
memory.videoram.array(),
texaddr - MemoryMap.START_VRAM + memory.videoram.arrayOffset(),
texture_width0 * texture_height0).slice();
final_buffer = ShortBuffer.wrap(
memory.mainmemory.array(),
texaddr - MemoryMap.START_RAM + memory.mainmemory.arrayOffset(),
texture_width0 * texture_height0).slice();
*/
for (int i = 0; i < texture_width0*texture_height0; i++) {
int pixel = mem.read16(texaddr+i*2);
tmp_texture_buffer16[i] = (short)pixel;
}
final_buffer = ShortBuffer.wrap(tmp_texture_buffer16);
} else {
final_buffer = unswizzleTextureFromMemory(texaddr, 2);
}
break;
}
case TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888: {
texture_type = GL.GL_UNSIGNED_INT_8_8_8_8_REV;
if (!texture_swizzle) {
/* TODO replace the loop with 1 line to IntBuffer.wrap
* but be careful of vram/mainram addresses
final_buffer = IntBuffer.wrap(
memory.videoram.array(),
texaddr - MemoryMap.START_VRAM + memory.videoram.arrayOffset(),
texture_width0 * texture_height0).slice();
final_buffer = IntBuffer.wrap(
memory.mainmemory.array(),
texaddr - MemoryMap.START_RAM + memory.mainmemory.arrayOffset(),
texture_width0 * texture_height0).slice();
*/
for (int i = 0; i < texture_width0*texture_height0; i++) {
tmp_texture_buffer32[i] = mem.read32(texaddr+i*4);
}
final_buffer = IntBuffer.wrap(tmp_texture_buffer32);
} else {
final_buffer = unswizzleTextureFromMemory(texaddr, 4);
}
break;
}
default: {
System.out.println("Unhandled texture storage " + texture_storage);
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
break;
}
}
// Upload texture to openGL
// TODO: Write a texture cache :)
gl.glBindTexture (GL.GL_TEXTURE_2D, gl_texture_id[0]);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, tex_min_filter);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, tex_mag_filter);
gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, textureByteAlignment);
gl.glPixelStorei(GL.GL_UNPACK_ROW_LENGTH, 0); // ROW_LENGTH = width
int texture_format = texture_type == GL.GL_UNSIGNED_SHORT_5_6_5_REV ? GL.GL_RGB : GL.GL_RGBA;
gl.glTexImage2D ( GL.GL_TEXTURE_2D,
0,
texture_format,
texture_width0, texture_height0,
0,
texture_format,
texture_type,
final_buffer);
break;
}
case TFLT: {
log ("sceGuTexFilter(min, mag)");
switch ((normalArgument>>8) & 0xFF)
{
case TFLT_MAGNIFYING_FILTER_NEAREST: {
tex_mag_filter = GL.GL_NEAREST;
break;
}
case TFLT_MAGNIFYING_FILTER_LINEAR: {
tex_mag_filter = GL.GL_LINEAR;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_NEAREST_NEAREST: {
tex_mag_filter = GL.GL_NEAREST_MIPMAP_NEAREST;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_NEAREST_LINEAR: {
tex_mag_filter = GL.GL_NEAREST_MIPMAP_LINEAR;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_LINEAR_NEAREST: {
tex_mag_filter = GL.GL_LINEAR_MIPMAP_NEAREST;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_LINEAR_LINEAR: {
tex_mag_filter = GL.GL_LINEAR_MIPMAP_LINEAR;
break;
}
default: {
log ("Unknown magnifiying filter " + ((normalArgument>>8) & 0xFF));
break;
}
}
switch (normalArgument & 0xFF)
{
case TFLT_MAGNIFYING_FILTER_NEAREST: {
tex_min_filter = GL.GL_NEAREST;
break;
}
case TFLT_MAGNIFYING_FILTER_LINEAR: {
tex_min_filter = GL.GL_LINEAR;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_NEAREST_NEAREST: {
tex_min_filter = GL.GL_NEAREST_MIPMAP_NEAREST;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_NEAREST_LINEAR: {
tex_min_filter = GL.GL_NEAREST_MIPMAP_LINEAR;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_LINEAR_NEAREST: {
tex_min_filter = GL.GL_LINEAR_MIPMAP_NEAREST;
break;
}
case TFLT_MAGNIFYING_FILTER_MIPMAP_LINEAR_LINEAR: {
tex_min_filter = GL.GL_LINEAR_MIPMAP_LINEAR;
break;
}
default: {
log ("Unknown minimizing filter " + (normalArgument & 0xFF));
break;
}
}
break;
}
/*
* Texture transformations
*/
case UOFFSET: {
tex_translate_x = floatArgument;
log ("sceGuTexOffset(float u, X)");
break;
}
case VOFFSET: {
tex_translate_y = floatArgument;
log ("sceGuTexOffset(X, float v)");
break;
}
case USCALE: {
tex_scale_x = floatArgument;
log (String.format("sceGuTexScale(u=%.2f, X)", tex_scale_x));
break;
}
case VSCALE: {
tex_scale_y = floatArgument;
log (String.format("sceGuTexScale(X, v=%.2f)", tex_scale_y));
break;
}
case TMAP: {
log ("sceGuTexMapMode(mode, X, X)");
tex_map_mode = normalArgument & 3;
break;
}
case TEXTURE_ENV_MAP_MATRIX: {
log ("sceGuTexMapMode(X, column1, column2)");
if (normalArgument != 0) {
int column0 = normalArgument & 0xFF,
column1 = (normalArgument>>8) & 0xFF;
for (int i = 0; i < 3; i++) {
tex_envmap_matrix [i+0] = light_pos[column0][i];
tex_envmap_matrix [i+4] = light_pos[column1][i];
}
}
break;
}
case TFUNC:
gl.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_RGB_SCALE, (normalArgument & 0x10000) != 0 ? 1.0f : 2.0f);
int env_mode = GL.GL_MODULATE;
switch(normalArgument & 7) {
case 0: env_mode = GL.GL_MODULATE; break;
case 1: env_mode = GL.GL_DECAL; break;
case 2: env_mode = GL.GL_BLEND; break;
case 3: env_mode = GL.GL_REPLACE; break;
case 4: env_mode = GL.GL_ADD; break;
default: VideoEngine.log.warn("Unimplemented tfunc mode");
}
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, env_mode);
// TODO : check this
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_SRC0_ALPHA, (normalArgument & 0x100) == 0 ? GL.GL_PREVIOUS : GL.GL_TEXTURE);
log("sceGuTexFunc");
/*log(String.format("sceGuTexFunc mode %08X", normalArgument)
+ (((normalArgument & 0x10000) != 0) ? " SCALE" : "")
+ (((normalArgument & 0x100) != 0) ? " ALPHA" : ""));*/
break;
case TEC:
tex_env_color[0] = ((normalArgument ) & 255) / 255.f;
tex_env_color[1] = ((normalArgument >> 8) & 255) / 255.f;
tex_env_color[2] = ((normalArgument >> 16) & 255) / 255.f;
tex_env_color[3] = 1.f;
gl.glTexEnvfv(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_COLOR, tex_env_color, 0);
log("tec");
break;
/*
*
*/
case XSCALE:
log("sceGuViewport width = " + (floatArgument * 2));
break;
case YSCALE:
log("sceGuViewport height = " + (- floatArgument * 2));
break;
// sceGuViewport cx/cy, can we discard these settings? it's only for clipping?
case XPOS:
log("sceGuViewport cx = " + floatArgument);
break;
case YPOS:
log("sceGuViewport cy = " + floatArgument);
break;
case ZPOS:
log(helper.getCommandString(ZPOS), floatArgument);
break;
// sceGuOffset, can we discard these settings? it's only for clipping?
case OFFSETX:
log("sceGuOffset x = " + (normalArgument >> 4));
break;
case OFFSETY:
log("sceGuOffset y = " + (normalArgument >> 4));
break;
case FBP:
// assign or OR lower 24-bits?
fbp = normalArgument;
break;
case FBW:
fbp &= 0xffffff;
fbp |= (normalArgument << 8) & 0xff000000;
fbw = (normalArgument) & 0xffff;
log("fbp=" + Integer.toHexString(fbp) + ", fbw=" + fbw);
jpcsp.HLE.pspdisplay.get_instance().hleDisplaySetGeBuf(fbp, fbw, psm);
break;
case ZBP:
// assign or OR lower 24-bits?
zbp = normalArgument;
break;
case ZBW:
zbp &= 0xffffff;
zbp |= (normalArgument << 8) & 0xff000000;
zbw = (normalArgument) & 0xffff;
log("zbp=" + Integer.toHexString(zbp) + ", zbw=" + zbw);
break;
case PSM:
psm = normalArgument;
log("psm=" + normalArgument);
break;
case PRIM:
{
int[] mapping = new int[] { GL.GL_POINTS, GL.GL_LINES, GL.GL_LINE_STRIP, GL.GL_TRIANGLES, GL.GL_TRIANGLE_STRIP, GL.GL_TRIANGLE_FAN };
int numberOfVertex = normalArgument & 0xFFFF;
int type = ((normalArgument >> 16) & 0x7);
// Logging
switch (type) {
case PRIM_POINT:
log(helper.getCommandString(PRIM) + " point " + numberOfVertex + "x");
break;
case PRIM_LINE:
log(helper.getCommandString(PRIM) + " line " + (numberOfVertex / 2) + "x");
break;
case PRIM_LINES_STRIPS:
log(helper.getCommandString(PRIM) + " lines_strips " + (numberOfVertex - 1) + "x");
break;
case PRIM_TRIANGLE:
log(helper.getCommandString(PRIM) + " triangle " + (numberOfVertex / 3) + "x");
break;
case PRIM_TRIANGLE_STRIPS:
log(helper.getCommandString(PRIM) + " triangle_strips " + (numberOfVertex - 2) + "x");
break;
case PRIM_TRIANGLE_FANS:
log(helper.getCommandString(PRIM) + " triangle_fans " + (numberOfVertex - 2) + "x");
break;
case PRIM_SPRITES:
log(helper.getCommandString(PRIM) + " sprites " + (numberOfVertex / 2) + "x");
break;
}
/*
* Defer transformations until primitive rendering
*/
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glPushMatrix ();
gl.glLoadIdentity();
if (transform_mode == VTYPE_TRANSFORM_PIPELINE_TRANS_COORD)
gl.glLoadMatrixf(proj_uploaded_matrix, 0);
else
gl.glOrtho(0.0, 480, 272, 0, -1.0, 1.0);
/*
* Apply texture transforms
*/
gl.glMatrixMode(GL.GL_TEXTURE);
gl.glPushMatrix ();
gl.glLoadIdentity();
gl.glTranslatef(tex_translate_x, tex_translate_y, 0.f);
if (transform_mode == VTYPE_TRANSFORM_PIPELINE_TRANS_COORD)
gl.glScalef(tex_scale_x, tex_scale_y, 1.f);
switch (tex_map_mode) {
case TMAP_TEXTURE_MAP_MODE_TEXTURE_COORDIATES_UV:
break;
case TMAP_TEXTURE_MAP_MODE_TEXTURE_MATRIX:
gl.glMultMatrixf (texture_uploaded_matrix, 0);
break;
case TMAP_TEXTURE_MAP_MODE_ENVIRONMENT_MAP: {
// First, setup texture uv generation
gl.glTexGeni(GL.GL_S, GL.GL_TEXTURE_GEN_MODE, GL.GL_SPHERE_MAP);
gl.glEnable (GL.GL_TEXTURE_GEN_S);
gl.glTexGeni(GL.GL_T, GL.GL_TEXTURE_GEN_MODE, GL.GL_SPHERE_MAP);
gl.glEnable (GL.GL_TEXTURE_GEN_T);
// Setup also texture matrix
gl.glMultMatrixf (tex_envmap_matrix, 0);
break;
}
default:
log ("Unhandled texture matrix mode " + tex_map_mode);
}
/*
* Apply view matrix
*/
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glPushMatrix ();
gl.glLoadIdentity();
if (transform_mode == VTYPE_TRANSFORM_PIPELINE_TRANS_COORD)
gl.glLoadMatrixf(view_uploaded_matrix, 0);
/*
* Setup lights on when view transformation is set up
*/
gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, light_pos[0], 0);
gl.glLightfv(GL.GL_LIGHT1, GL.GL_POSITION, light_pos[1], 0);
gl.glLightfv(GL.GL_LIGHT2, GL.GL_POSITION, light_pos[2], 0);
gl.glLightfv(GL.GL_LIGHT3, GL.GL_POSITION, light_pos[3], 0);
// Apply model matrix
if (transform_mode == VTYPE_TRANSFORM_PIPELINE_TRANS_COORD)
gl.glMultMatrixf(model_uploaded_matrix, 0);
// HACK: If we don't have a material set up, and have colors per vertex, this will
// override materials, so at least we'll see something, otherwise it would be black
if (vinfo.color != 0)
gl.glEnable(GL.GL_COLOR_MATERIAL);
Memory mem = Memory.getInstance();
switch (type) {
case PRIM_POINT:
case PRIM_LINE:
case PRIM_LINES_STRIPS:
case PRIM_TRIANGLE:
case PRIM_TRIANGLE_STRIPS:
case PRIM_TRIANGLE_FANS:
gl.glBegin(mapping[type]);
for (int i = 0; i < numberOfVertex; i++) {
int addr = vinfo.getAddress(mem, i);
VertexState v = vinfo.readVertex(mem, addr);
if (vinfo.texture != 0)
if(transform_mode == VTYPE_TRANSFORM_PIPELINE_RAW_COORD)
gl.glTexCoord2f(v.u / texture_width0, v.v / texture_height0);
else
gl.glTexCoord2f(v.u, v.v);
if (vinfo.color != 0) gl.glColor4f(v.r, v.g, v.b, v.a);
if (vinfo.normal != 0) gl.glNormal3f(v.nx, v.ny, v.nz);
if (vinfo.position != 0) {
if(vinfo.weight != 0)
doSkinning(vinfo, v);
gl.glVertex3f(v.px, v.py, v.pz);
}
}
gl.glEnd();
break;
case PRIM_SPRITES:
gl.glPushAttrib(GL.GL_ENABLE_BIT);
gl.glDisable(GL.GL_CULL_FACE);
gl.glBegin(GL.GL_QUADS);
for (int i = 0; i < numberOfVertex; i += 2) {
int addr1 = vinfo.getAddress(mem, i);
int addr2 = vinfo.getAddress(mem, i + 1);
VertexState v1 = vinfo.readVertex(mem, addr1);
VertexState v2 = vinfo.readVertex(mem, addr2);
// V1
if (vinfo.normal != 0) gl.glNormal3f(v1.nx, v1.ny, v1.nz);
if (vinfo.color != 0) gl.glColor4f(v2.r, v2.g, v2.b, v2.a); // color from v2 not v1
if (vinfo.texture != 0)
if(transform_mode == VTYPE_TRANSFORM_PIPELINE_RAW_COORD)
gl.glTexCoord2f(v1.u / texture_width0, v1.v / texture_height0);
else
gl.glTexCoord2f(v1.u, v1.v);
if (vinfo.position != 0) gl.glVertex3f(v1.px, v1.py, v1.pz);
if (vinfo.texture != 0)
if(transform_mode == VTYPE_TRANSFORM_PIPELINE_RAW_COORD)
gl.glTexCoord2f(v2.u / texture_width0, v1.v / texture_height0);
else
gl.glTexCoord2f(v2.u, v1.v);
if (vinfo.position != 0) gl.glVertex3f(v2.px, v1.py, v1.pz);
// V2
if (vinfo.normal != 0) gl.glNormal3f(v2.nx, v2.ny, v2.nz);
if (vinfo.color != 0) gl.glColor4f(v2.r, v2.g, v2.b, v2.a);
if (vinfo.texture != 0)
if(transform_mode == VTYPE_TRANSFORM_PIPELINE_RAW_COORD)
gl.glTexCoord2f(v2.u / texture_width0, v2.v / texture_height0);
else
gl.glTexCoord2f(v2.u, v2.v);
if (vinfo.position != 0) gl.glVertex3f(v2.px, v2.py, v1.pz);
if (vinfo.texture != 0)
if(transform_mode == VTYPE_TRANSFORM_PIPELINE_RAW_COORD)
gl.glTexCoord2f(v1.u / texture_width0, v2.v / texture_height0);
else
gl.glTexCoord2f(v1.u, v2.v);
if (vinfo.position != 0) gl.glVertex3f(v1.px, v2.py, v1.pz);
}
gl.glEnd();
gl.glPopAttrib();
break;
}
switch (tex_map_mode) {
case TMAP_TEXTURE_MAP_MODE_ENVIRONMENT_MAP: {
gl.glDisable (GL.GL_TEXTURE_GEN_S);
gl.glDisable (GL.GL_TEXTURE_GEN_T);
break;
}
}
gl.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_RGB_SCALE, 1.0f);
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_MODULATE);
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_SRC0_ALPHA, GL.GL_TEXTURE);
if (vinfo.color != 0)
gl.glDisable (GL.GL_COLOR_MATERIAL);
gl.glPopMatrix ();
gl.glMatrixMode (GL.GL_TEXTURE);
gl.glPopMatrix ();
gl.glMatrixMode (GL.GL_PROJECTION);
gl.glPopMatrix ();
gl.glMatrixMode (GL.GL_MODELVIEW);
break;
}
case ALPHA: {
int blend_mode = GL.GL_FUNC_ADD;
int src = getBlendSrc( normalArgument & 0xF);
int dst = getBlendOp((normalArgument >> 4 ) & 0xF);
int op = (normalArgument >> 8 ) & 0xF;
switch (op) {
case ALPHA_SOURCE_BLEND_OPERATION_ADD:
blend_mode = GL.GL_FUNC_ADD;
break;
case ALPHA_SOURCE_BLEND_OPERATION_SUBTRACT:
blend_mode = GL.GL_FUNC_SUBTRACT;
break;
case ALPHA_SOURCE_BLEND_OPERATION_REVERSE_SUBTRACT:
blend_mode = GL.GL_FUNC_REVERSE_SUBTRACT;
break;
case ALPHA_SOURCE_BLEND_OPERATION_MINIMUM_VALUE:
blend_mode = GL.GL_MIN;
break;
case ALPHA_SOURCE_BLEND_OPERATION_MAXIMUM_VALUE:
blend_mode = GL.GL_MAX;
break;
case ALPHA_SOURCE_BLEND_OPERATION_ABSOLUTE_VALUE:
blend_mode = GL.GL_FUNC_ADD;
break;
default:
VideoEngine.log.error("Unhandled blend mode " + op);
Emulator.PauseEmuWithStatus(Emulator.EMU_STATUS_UNIMPLEMENTED);
break;
}
try {
gl.glBlendEquation(blend_mode);
} catch (GLException e) {
log.warn("VideoEngine: " + e.getMessage());
}
gl.glBlendFunc(src, dst);
log ("sceGuBlendFunc(int op, int src, int dest, X, X)");
break;
}
case SHADE: {
int SETTED_MODEL = (normalArgument != 0) ? GL.GL_SMOOTH : GL.GL_FLAT;
gl.glShadeModel(SETTED_MODEL);
log(helper.getCommandString(SHADE) + " " + ((normalArgument != 0) ? "smooth" : "flat"));
break;
}
case FFACE: {
int frontFace = (normalArgument != 0) ? GL.GL_CW : GL.GL_CCW;
gl.glFrontFace(frontFace);
log(helper.getCommandString(FFACE) + " " + ((normalArgument != 0) ? "clockwise" : "counter-clockwise"));
break;
}
case DTE:
if(normalArgument != 0)
{
gl.glEnable(GL.GL_DITHER);
log("sceGuEnable(GL_DITHER)");
}
else
{
gl.glDisable(GL.GL_DITHER);
log("sceGuDisable(GL_DITHER)");
}
break;
case BCE:
if(normalArgument != 0)
{
gl.glEnable(GL.GL_CULL_FACE);
log("sceGuEnable(GU_CULL_FACE)");
}
else
{
gl.glDisable(GL.GL_CULL_FACE);
log("sceGuDisable(GU_CULL_FACE)");
}
break;
case FGE:
if(normalArgument != 0)
{
gl.glEnable(GL.GL_FOG);
gl.glFogi(GL.GL_FOG_MODE, GL.GL_LINEAR);
gl.glFogf(GL.GL_FOG_DENSITY, 0.1f);
gl.glHint(GL.GL_FOG_HINT, GL.GL_DONT_CARE);
log("sceGuEnable(GL_FOG)");
}
else
{
gl.glDisable(GL.GL_FOG);
log("sceGuDisable(GL_FOG)");
}
break;
case FCOL:
fog_color[0] = ((normalArgument ) & 255) / 255.f;
fog_color[1] = ((normalArgument >> 8) & 255) / 255.f;
fog_color[2] = ((normalArgument >> 16) & 255) / 255.f;
fog_color[3] = 1.f;
gl.glFogfv(GL.GL_FOG_COLOR, fog_color, 0);
log("FCOL");
break;
case FFAR:
fog_far = floatArgument;
break;
case FDIST:
fog_dist = floatArgument;
if((fog_far != 0.0f) && (fog_dist != 0.0f))
{
float end = fog_far;
float start = end - (1/floatArgument);
gl.glFogf( GL.GL_FOG_START, start );
gl.glFogf( GL.GL_FOG_END, end );
}
break;
case ABE:
if(normalArgument != 0) {
gl.glEnable(GL.GL_BLEND);
log("sceGuEnable(GU_BLEND)");
}
else {
gl.glDisable(GL.GL_BLEND);
log("sceGuDisable(GU_BLEND)");
}
break;
case ATE:
if(normalArgument != 0) {
gl.glEnable(GL.GL_ALPHA_TEST);
log("sceGuEnable(GL_ALPHA_TEST)");
}
else {
gl.glDisable(GL.GL_ALPHA_TEST);
log("sceGuDisable(GL_ALPHA_TEST)");
}
break;
case ZTE:
if(normalArgument != 0) {
gl.glEnable(GL.GL_DEPTH_TEST);
log("sceGuEnable(GU_DEPTH_TEST)");
}
else {
gl.glDisable(GL.GL_DEPTH_TEST);
log("sceGuDisable(GU_DEPTH_TEST)");
}
break;
case STE:
if(normalArgument != 0) {
gl.glEnable(GL.GL_STENCIL_TEST);
log("sceGuEnable(GU_STENCIL_TEST)");
}
else {
gl.glDisable(GL.GL_STENCIL_TEST);
log("sceGuDisable(GU_STENCIL_TEST)");
}
break;
case AAE:
if(normalArgument != 0)
{
gl.glEnable(GL.GL_LINE_SMOOTH);
gl.glHint(GL.GL_LINE_SMOOTH_HINT, GL.GL_NICEST);
log("sceGuEnable(GL_LINE_SMOOTH)");
}else
{
gl.glDisable(GL.GL_LINE_SMOOTH);
log("sceGuDisable(GL_LINE_SMOOTH)");
}
break;
case LOE:
if(normalArgument != 0)
{
gl.glEnable(GL.GL_COLOR_LOGIC_OP);
log("sceGuEnable(GU_COLOR_LOGIC_OP)");
}
else
{
gl.glDisable(GL.GL_COLOR_LOGIC_OP);
log("sceGuDisable(GU_COLOR_LOGIC_OP)");
}
break;
case JUMP:
{
int npc = (normalArgument | actualList.base) & 0xFFFFFFFC;
//I guess it must be unsign as psp player emulator
log(helper.getCommandString(JUMP) + " old PC:" + String.format("%08x", actualList.pc)
+ " new PC:" + String.format("%08x", npc));
actualList.pc = npc;
break;
}
case CALL:
{
actualList.stack[actualList.stackIndex++] = actualList.pc;
int npc = (normalArgument | actualList.base) & 0xFFFFFFFC;
log(helper.getCommandString(CALL) + " old PC:" + String.format("%08x", actualList.pc)
+ " new PC:" + String.format("%08x", npc));
actualList.pc = npc;
break;
}
case RET:
{
int npc = actualList.stack[--actualList.stackIndex];
log(helper.getCommandString(RET) + " old PC:" + String.format("%08x", actualList.pc)
+ " new PC:" + String.format("%08x", npc));
actualList.pc = npc;
break;
}
case ZMSK: {
// NOTE: PSP depth mask as 1 is meant to avoid depth writes,
// on pc it's the opposite
gl.glDepthMask(normalArgument == 1 ? false : true);
log ("sceGuDepthMask(disableWrites)");
break;
}
case ATST: {
int func = GL.GL_ALWAYS;
switch(normalArgument & 0xFF) {
case ATST_NEVER_PASS_PIXEL:
func = GL.GL_NEVER;
break;
case ATST_ALWAYS_PASS_PIXEL:
func = GL.GL_ALWAYS;
break;
case ATST_PASS_PIXEL_IF_MATCHES:
func = GL.GL_EQUAL;
break;
case ATST_PASS_PIXEL_IF_DIFFERS:
func = GL.GL_NOTEQUAL;
break;
case ATST_PASS_PIXEL_IF_LESS:
func = GL.GL_LESS;
break;
case ATST_PASS_PIXEL_IF_LESS_OR_EQUAL:
func = GL.GL_LEQUAL;
break;
case ATST_PASS_PIXEL_IF_GREATER:
func = GL.GL_GREATER;
break;
case ATST_PASS_PIXEL_IF_GREATER_OR_EQUAL:
func = GL.GL_GEQUAL;
break;
}
gl.glAlphaFunc(func,floatArgument);
log ("sceGuAlphaFunc(" + func + "," + floatArgument + ")");
break;
}
case STST: {
int func = GL.GL_ALWAYS;
switch (normalArgument & 0xFF) {
case STST_FUNCTION_NEVER_PASS_STENCIL_TEST:
func = GL.GL_NEVER;
break;
case STST_FUNCTION_ALWAYS_PASS_STENCIL_TEST:
func = GL.GL_ALWAYS;
break;
case STST_FUNCTION_PASS_TEST_IF_MATCHES:
func = GL.GL_EQUAL;
break;
case STST_FUNCTION_PASS_TEST_IF_DIFFERS:
func = GL.GL_NOTEQUAL;
break;
case STST_FUNCTION_PASS_TEST_IF_LESS:
func = GL.GL_LESS;
break;
case STST_FUNCTION_PASS_TEST_IF_LESS_OR_EQUAL:
func = GL.GL_LEQUAL;
break;
case STST_FUNCTION_PASS_TEST_IF_GREATER:
func = GL.GL_GREATER;
break;
case STST_FUNCTION_PASS_TEST_IF_GREATER_OR_EQUAL:
func = GL.GL_GEQUAL;
break;
}
gl.glStencilFunc (func, ((normalArgument>>8) & 0xff), (normalArgument>>16) & 0xff);
log ("sceGuStencilFunc(func, ref, mask)");
break;
}
case NEARZ : {
nearZ = ( float )( int )( short )normalArgument;
}
break;
case FARZ : {
if(nearZ > ( float )( int )( short )normalArgument)
{
farZ = nearZ;
nearZ = ( float )( int )( short )normalArgument;
}
else
farZ = ( float )( int )( short )normalArgument;
gl.glDepthRange(nearZ, farZ);
log ("sceGuDepthRange("+ nearZ + " ," + farZ + ")");
}
break;
case SOP: {
int fail = getStencilOp (normalArgument & 0xFF);
int zfail = getStencilOp ((normalArgument>> 8) & 0xFF);
int zpass = getStencilOp ((normalArgument>>16) & 0xFF);
gl.glStencilOp(fail, zfail, zpass);
break;
}
case CLEAR:
if ((normalArgument & 0x1)==0) {
// set clear color, actarus/sam
gl.glClearColor(vinfo.lastVertex.r, vinfo.lastVertex.g, vinfo.lastVertex.b, vinfo.lastVertex.a);
gl.glClear(clearFlags);
log(String.format("guclear r=%.1f g=%.1f b=%.1f a=%.1f", vinfo.lastVertex.r, vinfo.lastVertex.g, vinfo.lastVertex.b, vinfo.lastVertex.a));
} else {
clearFlags = 0;
if ((normalArgument & 0x100)!=0) clearFlags |= GL.GL_COLOR_BUFFER_BIT; // target
if ((normalArgument & 0x200)!=0) clearFlags |= GL.GL_STENCIL_BUFFER_BIT; // stencil/alpha
if ((normalArgument & 0x400)!=0) clearFlags |= GL.GL_DEPTH_BUFFER_BIT; // zbuffer
log("setting clear flags");
}
break;
case NOP:
log(helper.getCommandString(NOP));
break;
/*
* Skinning
*/
case BOFS: {
log("bone matrix offset", normalArgument);
if(normalArgument % 12 != 0)
VideoEngine.log.warn("bone matrix offset " + normalArgument + " isn't a multiple of 12");
bone_matrix_offset = normalArgument / (4*3);
bone_upload_start = true;
break;
}
case BONE: {
if (bone_upload_start) {
bone_upload_x = 0;
bone_upload_y = 0;
bone_upload_start = false;
}
if (bone_upload_x < 4) {
if (bone_upload_y < 3) {
bone_matrix[bone_upload_x + bone_upload_y * 4] = floatArgument;
bone_upload_x++;
if (bone_upload_x == 4) {
bone_upload_x = 0;
bone_upload_y++;
if (bone_upload_y == 3) {
log("bone matrix " + bone_matrix_offset, model_matrix);
for (int i = 0; i < 4*3; i++)
bone_uploaded_matrix[bone_matrix_offset][i] = bone_matrix[i];
}
}
}
}
break;
}
case MW0:
case MW1:
case MW2:
case MW3:
case MW4:
case MW5:
case MW6:
case MW7:
log("morph weight " + (command(instruction) - MW0), floatArgument);
morph_weight[command(instruction) - MW0] = floatArgument;
break;
case TRXSBP:
textureTx_sourceAddress = normalArgument;
break;
case TRXSBW:
textureTx_sourceAddress |= (normalArgument << 8) & 0xFF000000;
textureTx_sourceLineWidth = normalArgument & 0x0000FFFF;
break;
case TRXDBP:
textureTx_destinationAddress = normalArgument;
break;
case TRXDBW:
textureTx_destinationAddress |= (normalArgument << 8) & 0xFF000000;
textureTx_destinationLineWidth = normalArgument & 0x0000FFFF;
break;
case TRXSIZE:
textureTx_width = (normalArgument & 0x3FF) + 1;
textureTx_height = ((normalArgument >> 10) & 0x1FF) + 1;
break;
case TRXPOS:
textureTx_sx = normalArgument & 0x1FF;
textureTx_sy = (normalArgument >> 10) & 0x1FF;
break;
case TRXDPOS:
textureTx_dx = normalArgument & 0x1FF;
textureTx_dy = (normalArgument >> 10) & 0x1FF;
break;
case TRXKICK:
textureTx_pixelSize = normalArgument & 0x1;
log(helper.getCommandString(TRXKICK) + " from 0x" + Integer.toHexString(textureTx_sourceAddress) + "(" + textureTx_sx + "," + textureTx_sy + ") to 0x" + Integer.toHexString(textureTx_destinationAddress) + "(" + textureTx_dx + "," + textureTx_dy + "), width=" + textureTx_width + ", height=" + textureTx_height);
if (!pspdisplay.get_instance().isGeAddress(textureTx_destinationAddress)) {
log(helper.getCommandString(TRXKICK) + " not in Ge Address space");
int width = textureTx_width;
int height = textureTx_height;
int bpp = ( textureTx_pixelSize == TRXKICK_16BIT_TEXEL_SIZE ) ? 2 : 4;
int srcAddress = textureTx_sourceAddress + (textureTx_sy * textureTx_sourceLineWidth + textureTx_sx) * bpp;
int dstAddress = textureTx_destinationAddress + (textureTx_dy * textureTx_destinationLineWidth + textureTx_dx) * bpp;
Memory memory = Memory.getInstance();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
memory.write32(dstAddress, memory.read32(srcAddress));
srcAddress += bpp;
dstAddress += bpp;
}
srcAddress += (textureTx_sourceLineWidth - width) * bpp;
dstAddress += (textureTx_destinationLineWidth - width) * bpp;
}
} else {
log(helper.getCommandString(TRXKICK) + " in Ge Address space");
if (textureTx_pixelSize == TRXKICK_16BIT_TEXEL_SIZE) {
log("Unsupported 16bit for video command [ " + helper.getCommandString(command(instruction)) + " ]");
break;
}
int width = textureTx_width;
int height = textureTx_height;
int dx = textureTx_dx;
int dy = textureTx_dy;
int lineWidth = textureTx_sourceLineWidth;
int bpp = (textureTx_pixelSize == TRXKICK_16BIT_TEXEL_SIZE) ? 2 : 4;
int[] textures = new int[1];
gl.glGenTextures(1, textures, 0);
int texture = textures[0];
gl.glBindTexture(GL.GL_TEXTURE_2D, texture);
gl.glPushAttrib(GL.GL_ENABLE_BIT);
gl.glDisable(GL.GL_DEPTH_TEST);
gl.glDisable(GL.GL_BLEND);
gl.glDisable(GL.GL_ALPHA_TEST);
gl.glDisable(GL.GL_FOG);
gl.glDisable(GL.GL_LIGHTING);
gl.glDisable(GL.GL_LOGIC_OP);
gl.glDisable(GL.GL_STENCIL_TEST);
gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, bpp);
gl.glPixelStorei(GL.GL_UNPACK_ROW_LENGTH, lineWidth);
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glPushMatrix();
gl.glLoadIdentity();
gl.glOrtho(0, 480, 272, 0, -1, 1);
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glPushMatrix ();
gl.glLoadIdentity();
ByteBuffer buffer = ByteBuffer.wrap(
Memory.getInstance().mainmemory.array(),
Memory.getInstance().mainmemory.arrayOffset() + textureTx_sourceAddress - MemoryMap.START_RAM,
lineWidth * height * bpp).slice();
//
// glTexImage2D only supports
// width = (1 << n) for some integer n
// height = (1 << m) for some integer m
//
// This the reason why we are also using glTexSubImage2D.
//
int bufferHeight = Utilities.makePow2(height);
gl.glTexImage2D(
GL.GL_TEXTURE_2D, 0,
GL.GL_RGBA,
lineWidth, bufferHeight, 0,
GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, null);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP);
gl.glTexSubImage2D(
GL.GL_TEXTURE_2D, 0,
textureTx_sx, textureTx_sy, width, height,
GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, buffer);
gl.glEnable(GL.GL_TEXTURE_2D);
gl.glBegin(GL.GL_QUADS);
gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
float texCoordX = width / (float) lineWidth;
float texCoordY = height / (float) bufferHeight;
gl.glTexCoord2f(0.0f, 0.0f);
gl.glVertex2i(dx, dy);
gl.glTexCoord2f(texCoordX, 0.0f);
gl.glVertex2i(dx + width, dy);
gl.glTexCoord2f(texCoordX, texCoordY);
gl.glVertex2i(dx + width, dy + height);
gl.glTexCoord2f(0.0f, texCoordY);
gl.glVertex2i(dx, dy + height);
gl.glEnd();
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glPopMatrix();
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glPopMatrix();
gl.glPopAttrib();
gl.glDeleteTextures(1, textures, 0);
}
break;
default:
log("Unknown/unimplemented video command [ " + helper.getCommandString(command(instruction)) + " ]");
}
}
|
diff --git a/org.amanzi.scripting.jruby/src/org/amanzi/scripting/jruby/ScriptUtils.java b/org.amanzi.scripting.jruby/src/org/amanzi/scripting/jruby/ScriptUtils.java
index 74eea7295..c5e7c57a2 100644
--- a/org.amanzi.scripting.jruby/src/org/amanzi/scripting/jruby/ScriptUtils.java
+++ b/org.amanzi.scripting.jruby/src/org/amanzi/scripting/jruby/ScriptUtils.java
@@ -1,215 +1,215 @@
package org.amanzi.scripting.jruby;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import net.refractions.udig.catalog.URLUtils;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;
/**
* This utility class has some static methods for investigating the environment
* and finding appropriate settings for JRuby. Originally this class started
* as shared code between the pure-swing and the swt-swing versions of the IRBConsole
* but it has expanded to include directory searching for ideal locations for JRuby.
* @author craig
*/
public class ScriptUtils {
/*
* Name of JRuby plugin
*/
private static final String JRUBY_PLUGIN_NAME = "org.jruby";
/*
* Name of scripting Plugin
*/
private static final String SCRIPTING_PLUGIN_NAME = "org.amanzi.scripting.jruby";
private static ScriptUtils instance = new ScriptUtils();
private String jRubyHome = null;
private String jRubyVersion = null;
/**
* Utility to setup fonts for the swing console. This was taken directly from the
* relevant code in org.jruby.demo.IRBConsole.
* @param otherwise
* @param style
* @param size
* @param families
* @return
*/
public static Font findFont(String otherwise, int style, int size, String[] families) {
String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
Arrays.sort(fonts);
Font font = null;
for (int i = 0; i < families.length; i++) {
if (Arrays.binarySearch(fonts, families[i]) >= 0) {
font = new Font(families[i], style, size);
break;
}
}
if (font == null)
font = new Font(otherwise, style, size);
return font;
}
/**
* Utility to find the best working location of JRuby. Set -Djruby.home
* to add an explicit location to the beginning of the search path.
* @return String path to JRuby installation (eg. "/usr/lib/jruby")
*/
public static String getJRubyHome() throws IOException {
return instance.ensureJRubyHome();
}
/**
* Utility to find the version of ruby supported by the current JRuby location.
* Set -Djruby.version to override this result.
* @return String describing supported ruby version (eg. "1.8")
*/
public static String getJRubyVersion() throws IOException {
return instance.ensureJRubyVersion();
}
/**
* Utility method to add default ruby variable names for specified java class names.
* This is used in some code to check dynamically the type of the class.
* @param globals
* @param classNames
*/
public static void makeGlobalsFromClassNames(HashMap<String, Object> globals, String[] classNames) {
for(String className:classNames){
try {
String[] fds = className.split("\\.");
//TODO: Rather have a proper Camel->Underscore conversion here (see if JRuby code has one we can use)
String var = fds[fds.length-1].toLowerCase().replace("reader", "_reader").concat("_class");
globals.put(var, Class.forName(className));
}
catch (ClassNotFoundException e) {
System.out.println("Error setting global Ruby variable for class '"+className+"': "+e.getMessage());
//e.printStackTrace(System.out);
}
}
}
/**
* Build a list of String paths to be added to the JRuby search paths
* for finding ruby libraries. We use this when starting the interpreter
* to ensure that any custom code we've written is found.
* @param extras
* @return
*/
public static List<String> makeLoadPath(String[] extras) throws IOException {
return instance.doMakeLoadPath(extras);
}
/** Actually construct the list of load paths */
private List<String> doMakeLoadPath(String[] extras) throws IOException {
// The following code finds the location of jruby on the computer and
// makes sure the right loadpath is provided to the interpreter
// The paths can be overridden by -Djruby.home and -Djruby.version
ensureJRubyHome();
ensureJRubyVersion();
List<String> loadPath = new ArrayList<String>();
if(extras!=null) for(String path:extras) loadPath.add(path);
loadPath.add(jRubyHome+"/lib/ruby/site_ruby/"+jRubyVersion);
loadPath.add(jRubyHome+"/lib/ruby/site_ruby");
loadPath.add(jRubyHome+"/lib/ruby/"+jRubyVersion);
loadPath.add(jRubyHome+"/lib/ruby/"+jRubyVersion+"/java");
loadPath.add(jRubyHome+"/lib");
//Lagutko, 20.08.2009, now we have Neo4j RubyGem inside current plugin but not inside org.jruby
- String neoRubyGemDir = getPluginRoot(SCRIPTING_PLUGIN_NAME) + "neo4j";
+ String neoRubyGemDir = getPluginRoot(SCRIPTING_PLUGIN_NAME) + "/neo4j";
loadPath.add(neoRubyGemDir + "/lib");
loadPath.add(neoRubyGemDir + "/lib/relations");
loadPath.add(neoRubyGemDir + "/lib/mixins");
loadPath.add(neoRubyGemDir + "/lib/jars");
loadPath.add(neoRubyGemDir + "/examples/imdb");
loadPath.add("lib/ruby/"+jRubyVersion);
loadPath.add(".");
return loadPath;
}
/** return JRubyHome, searching for it if necessary */
private String ensureJRubyHome() throws IOException {
if(jRubyHome==null){
jRubyHome = ScriptUtils.findJRubyHome(System.getProperty("jruby.home"));
}
return(jRubyHome);
}
/** return JRubyVersion, searching for it if necessary */
private String ensureJRubyVersion() throws IOException {
if(jRubyVersion==null){
jRubyVersion = ScriptUtils.findJRubyVersion(ensureJRubyHome(),System.getProperty("jruby.version"));
}
return(jRubyVersion);
}
/** search for jruby home, starting with passed value, if any */
private static String findJRubyHome(String suggested) throws IOException {
String jRubyHome = null;
//Lagutko, 22.06.2009, since now we search ruby home only in org.jruby plugin
jRubyHome = getPluginRoot(JRUBY_PLUGIN_NAME);
if (jRubyHome == null) {
jRubyHome = ".";
}
return jRubyHome;
}
/** try determine ruby version jruby.version property was not set. Default to "1.8" */
private static String findJRubyVersion(String jRubyHome, String jRubyVersion) {
if (jRubyVersion == null) {
for (String version : new String[] { "1.8", "1.9", "2.0", "2.1" }) {
String path = jRubyHome + "/lib/ruby/" + version;
try {
if ((new java.io.File(path)).isDirectory()) {
jRubyVersion = version;
break;
}
} catch (Exception e) {
System.err
.println("Failed to process possible JRuby path '"
+ path + "': " + e.getMessage());
}
}
}
if (jRubyVersion == null) {
jRubyVersion = "1.8";
}
return jRubyVersion;
}
/**
* Returns path to plugin that can be handled by JRuby
*
* @param pluginName name of plugin
* @return path to plugin
* @throws IOException throws Exception if path cannot be resolved
* @author Lagutko_N
*/
private static String getPluginRoot(String pluginName) throws IOException {
URL rubyLocationURL = Platform.getBundle(pluginName).getEntry("/");
String rubyLocation = URLUtils.urlToString(FileLocator.resolve(rubyLocationURL), false);
if (rubyLocation.startsWith("jar:file:")) {
rubyLocation = "file:/" + rubyLocation.substring(9);
}
else if (rubyLocation.startsWith("file:")) {
rubyLocation = rubyLocation.substring(5);
}
return rubyLocation;
}
}
| true | true | private List<String> doMakeLoadPath(String[] extras) throws IOException {
// The following code finds the location of jruby on the computer and
// makes sure the right loadpath is provided to the interpreter
// The paths can be overridden by -Djruby.home and -Djruby.version
ensureJRubyHome();
ensureJRubyVersion();
List<String> loadPath = new ArrayList<String>();
if(extras!=null) for(String path:extras) loadPath.add(path);
loadPath.add(jRubyHome+"/lib/ruby/site_ruby/"+jRubyVersion);
loadPath.add(jRubyHome+"/lib/ruby/site_ruby");
loadPath.add(jRubyHome+"/lib/ruby/"+jRubyVersion);
loadPath.add(jRubyHome+"/lib/ruby/"+jRubyVersion+"/java");
loadPath.add(jRubyHome+"/lib");
//Lagutko, 20.08.2009, now we have Neo4j RubyGem inside current plugin but not inside org.jruby
String neoRubyGemDir = getPluginRoot(SCRIPTING_PLUGIN_NAME) + "neo4j";
loadPath.add(neoRubyGemDir + "/lib");
loadPath.add(neoRubyGemDir + "/lib/relations");
loadPath.add(neoRubyGemDir + "/lib/mixins");
loadPath.add(neoRubyGemDir + "/lib/jars");
loadPath.add(neoRubyGemDir + "/examples/imdb");
loadPath.add("lib/ruby/"+jRubyVersion);
loadPath.add(".");
return loadPath;
}
| private List<String> doMakeLoadPath(String[] extras) throws IOException {
// The following code finds the location of jruby on the computer and
// makes sure the right loadpath is provided to the interpreter
// The paths can be overridden by -Djruby.home and -Djruby.version
ensureJRubyHome();
ensureJRubyVersion();
List<String> loadPath = new ArrayList<String>();
if(extras!=null) for(String path:extras) loadPath.add(path);
loadPath.add(jRubyHome+"/lib/ruby/site_ruby/"+jRubyVersion);
loadPath.add(jRubyHome+"/lib/ruby/site_ruby");
loadPath.add(jRubyHome+"/lib/ruby/"+jRubyVersion);
loadPath.add(jRubyHome+"/lib/ruby/"+jRubyVersion+"/java");
loadPath.add(jRubyHome+"/lib");
//Lagutko, 20.08.2009, now we have Neo4j RubyGem inside current plugin but not inside org.jruby
String neoRubyGemDir = getPluginRoot(SCRIPTING_PLUGIN_NAME) + "/neo4j";
loadPath.add(neoRubyGemDir + "/lib");
loadPath.add(neoRubyGemDir + "/lib/relations");
loadPath.add(neoRubyGemDir + "/lib/mixins");
loadPath.add(neoRubyGemDir + "/lib/jars");
loadPath.add(neoRubyGemDir + "/examples/imdb");
loadPath.add("lib/ruby/"+jRubyVersion);
loadPath.add(".");
return loadPath;
}
|
diff --git a/src/test/java/net/floodlightcontroller/loadbalancer/LoadBalancerTest.java b/src/test/java/net/floodlightcontroller/loadbalancer/LoadBalancerTest.java
index fba97343..8c970183 100644
--- a/src/test/java/net/floodlightcontroller/loadbalancer/LoadBalancerTest.java
+++ b/src/test/java/net/floodlightcontroller/loadbalancer/LoadBalancerTest.java
@@ -1,677 +1,677 @@
package net.floodlightcontroller.loadbalancer;
import static org.easymock.EasyMock.anyLong;
import static org.easymock.EasyMock.anyShort;
import static org.easymock.EasyMock.capture;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.reset;
import static org.easymock.EasyMock.verify;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.easymock.Capture;
import org.easymock.CaptureType;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import org.openflow.protocol.OFFlowMod;
import org.openflow.protocol.OFMatch;
import org.openflow.protocol.OFMessage;
import org.openflow.protocol.OFPacketIn;
import org.openflow.protocol.OFPacketOut;
import org.openflow.protocol.OFPort;
import org.openflow.protocol.OFType;
import org.openflow.protocol.OFPacketIn.OFPacketInReason;
import org.openflow.protocol.action.OFAction;
import org.openflow.protocol.action.OFActionOutput;
import org.openflow.util.HexString;
import net.floodlightcontroller.core.FloodlightContext;
import net.floodlightcontroller.core.IFloodlightProviderService;
import net.floodlightcontroller.core.IOFSwitch;
import net.floodlightcontroller.core.module.FloodlightModuleContext;
import net.floodlightcontroller.core.test.MockFloodlightProvider;
import net.floodlightcontroller.core.test.MockThreadPoolService;
import net.floodlightcontroller.counter.CounterStore;
import net.floodlightcontroller.counter.ICounterStoreService;
import net.floodlightcontroller.devicemanager.IDeviceService;
import net.floodlightcontroller.devicemanager.IEntityClassifierService;
import net.floodlightcontroller.devicemanager.internal.DefaultEntityClassifier;
import net.floodlightcontroller.devicemanager.test.MockDeviceManager;
import net.floodlightcontroller.flowcache.FlowReconcileManager;
import net.floodlightcontroller.flowcache.IFlowReconcileService;
import net.floodlightcontroller.packet.ARP;
import net.floodlightcontroller.packet.Ethernet;
import net.floodlightcontroller.packet.ICMP;
import net.floodlightcontroller.packet.IPacket;
import net.floodlightcontroller.packet.IPv4;
import net.floodlightcontroller.restserver.IRestApiService;
import net.floodlightcontroller.restserver.RestApiServer;
import net.floodlightcontroller.routing.IRoutingService;
import net.floodlightcontroller.routing.Route;
import net.floodlightcontroller.staticflowentry.IStaticFlowEntryPusherService;
import net.floodlightcontroller.staticflowentry.StaticFlowEntryPusher;
import net.floodlightcontroller.storage.IStorageSourceService;
import net.floodlightcontroller.storage.memory.MemoryStorageSource;
import net.floodlightcontroller.test.FloodlightTestCase;
import net.floodlightcontroller.threadpool.IThreadPoolService;
import net.floodlightcontroller.topology.ITopologyService;
import net.floodlightcontroller.topology.NodePortTuple;
public class LoadBalancerTest extends FloodlightTestCase {
protected LoadBalancer lb;
protected FloodlightContext cntx;
protected FloodlightModuleContext fmc;
protected MockFloodlightProvider mockFloodlightProvider;
protected MockDeviceManager deviceManager;
protected MockThreadPoolService tps;
protected FlowReconcileManager frm;
protected DefaultEntityClassifier entityClassifier;
protected IRoutingService routingEngine;
protected ITopologyService topology;
protected StaticFlowEntryPusher sfp;
protected MemoryStorageSource storage;
protected RestApiServer restApi;
protected VipsResource vipsResource;
protected PoolsResource poolsResource;
protected MembersResource membersResource;
protected LBVip vip1, vip2;
protected LBPool pool1, pool2, pool3;
protected LBMember member1, member2, member3, member4;
@Before
public void setUp() throws Exception {
super.setUp();
lb = new LoadBalancer();
cntx = new FloodlightContext();
fmc = new FloodlightModuleContext();
entityClassifier = new DefaultEntityClassifier(); // dependency for device manager
frm = new FlowReconcileManager(); //dependency for device manager
tps = new MockThreadPoolService(); //dependency for device manager
deviceManager = new MockDeviceManager();
topology = createMock(ITopologyService.class);
routingEngine = createMock(IRoutingService.class);
restApi = new RestApiServer();
sfp = new StaticFlowEntryPusher();
storage = new MemoryStorageSource(); //dependency for sfp
fmc.addService(IRestApiService.class, restApi);
fmc.addService(IFloodlightProviderService.class, getMockFloodlightProvider());
fmc.addService(IEntityClassifierService.class, entityClassifier);
fmc.addService(IFlowReconcileService.class, frm);
fmc.addService(IThreadPoolService.class, tps);
fmc.addService(IDeviceService.class, deviceManager);
fmc.addService(ITopologyService.class, topology);
fmc.addService(IRoutingService.class, routingEngine);
fmc.addService(ICounterStoreService.class, new CounterStore());
fmc.addService(IStaticFlowEntryPusherService.class, sfp);
fmc.addService(ILoadBalancerService.class, lb);
fmc.addService(IStorageSourceService.class, storage);
lb.init(fmc);
getMockFloodlightProvider().init(fmc);
entityClassifier.init(fmc);
frm.init(fmc);
tps.init(fmc);
deviceManager.init(fmc);
restApi.init(fmc);
sfp.init(fmc);
storage.init(fmc);
topology.addListener(deviceManager);
expectLastCall().times(1);
replay(topology);
lb.startUp(fmc);
getMockFloodlightProvider().startUp(fmc);
entityClassifier.startUp(fmc);
frm.startUp(fmc);
tps.startUp(fmc);
deviceManager.startUp(fmc);
restApi.startUp(fmc);
sfp.startUp(fmc);
storage.startUp(fmc);
verify(topology);
vipsResource = new VipsResource();
poolsResource = new PoolsResource();
membersResource = new MembersResource();
vip1=null;
vip2=null;
pool1=null;
pool2=null;
pool3=null;
member1=null;
member2=null;
member3=null;
member4=null;
}
@Test
public void testCreateVip() {
String postData1, postData2;
IOException error = null;
postData1 = "{\"id\":\"1\",\"name\":\"vip1\",\"protocol\":\"icmp\",\"address\":\"10.0.0.100\",\"port\":\"8\"}";
postData2 = "{\"id\":\"2\",\"name\":\"vip2\",\"protocol\":\"tcp\",\"address\":\"10.0.0.200\",\"port\":\"100\"}";
try {
vip1 = vipsResource.jsonToVip(postData1);
} catch (IOException e) {
error = e;
}
try {
vip2 = vipsResource.jsonToVip(postData2);
} catch (IOException e) {
error = e;
}
// verify correct parsing
assertFalse(vip1==null);
assertFalse(vip2==null);
assertTrue(error==null);
lb.createVip(vip1);
lb.createVip(vip2);
// verify correct creation
assertTrue(lb.vips.containsKey(vip1.id));
assertTrue(lb.vips.containsKey(vip2.id));
}
@Test
public void testRemoveVip() {
testCreateVip();
// verify correct initial condition
assertFalse(vip1==null);
assertFalse(vip2==null);
lb.removeVip(vip1.id);
lb.removeVip(vip2.id);
// verify correct removal
assertFalse(lb.vips.containsKey(vip1.id));
assertFalse(lb.vips.containsKey(vip2.id));
}
@Test
public void testCreatePool() {
String postData1, postData2, postData3;
IOException error = null;
testCreateVip();
postData1 = "{\"id\":\"1\",\"name\":\"pool1\",\"protocol\":\"icmp\",\"vip_id\":\"1\"}";
postData2 = "{\"id\":\"2\",\"name\":\"pool2\",\"protocol\":\"tcp\",\"vip_id\":\"2\"}";
postData3 = "{\"id\":\"3\",\"name\":\"pool3\",\"protocol\":\"udp\",\"vip_id\":\"3\"}";
try {
pool1 = poolsResource.jsonToPool(postData1);
} catch (IOException e) {
error = e;
}
try {
pool2 = poolsResource.jsonToPool(postData2);
} catch (IOException e) {
error = e;
}
try {
pool3 = poolsResource.jsonToPool(postData3);
} catch (IOException e) {
error = e;
}
// verify correct parsing
assertFalse(pool1==null);
assertFalse(pool2==null);
assertFalse(pool3==null);
assertTrue(error==null);
lb.createPool(pool1);
lb.createPool(pool2);
lb.createPool(pool3);
// verify successful creates; two registered with vips and one not
assertTrue(lb.pools.containsKey(pool1.id));
assertTrue(lb.vips.get(pool1.vipId).pools.contains(pool1.id));
assertTrue(lb.pools.containsKey(pool2.id));
assertTrue(lb.vips.get(pool2.vipId).pools.contains(pool2.id));
assertTrue(lb.pools.containsKey(pool3.id));
assertFalse(lb.vips.containsKey(pool3.vipId));
}
@Test
public void testRemovePool() {
testCreateVip();
testCreatePool();
// verify correct initial condition
assertFalse(vip1==null);
assertFalse(vip2==null);
assertFalse(pool1==null);
assertFalse(pool2==null);
assertFalse(pool3==null);
lb.removePool(pool1.id);
lb.removePool(pool2.id);
lb.removePool(pool3.id);
// verify correct removal
assertFalse(lb.pools.containsKey(pool1.id));
assertFalse(lb.pools.containsKey(pool2.id));
assertFalse(lb.pools.containsKey(pool3.id));
//verify pool cleanup from vip
assertFalse(lb.vips.get(pool1.vipId).pools.contains(pool1.id));
assertFalse(lb.vips.get(pool2.vipId).pools.contains(pool2.id));
}
@Test
public void testCreateMember() {
String postData1, postData2, postData3, postData4;
IOException error = null;
testCreateVip();
testCreatePool();
postData1 = "{\"id\":\"1\",\"address\":\"10.0.0.3\",\"port\":\"8\",\"pool_id\":\"1\"}";
postData2 = "{\"id\":\"2\",\"address\":\"10.0.0.4\",\"port\":\"8\",\"pool_id\":\"1\"}";
postData3 = "{\"id\":\"3\",\"address\":\"10.0.0.5\",\"port\":\"100\",\"pool_id\":\"2\"}";
postData4 = "{\"id\":\"4\",\"address\":\"10.0.0.6\",\"port\":\"100\",\"pool_id\":\"2\"}";
try {
member1 = membersResource.jsonToMember(postData1);
} catch (IOException e) {
error = e;
}
try {
member2 = membersResource.jsonToMember(postData2);
} catch (IOException e) {
error = e;
}
try {
member3 = membersResource.jsonToMember(postData3);
} catch (IOException e) {
error = e;
}
try {
member4 = membersResource.jsonToMember(postData4);
} catch (IOException e) {
error = e;
}
// verify correct parsing
assertFalse(member1==null);
assertFalse(member2==null);
assertFalse(member3==null);
assertFalse(member4==null);
assertTrue(error==null);
lb.createMember(member1);
lb.createMember(member2);
lb.createMember(member3);
lb.createMember(member4);
// add the same server a second time
lb.createMember(member1);
// verify successful creates
assertTrue(lb.members.containsKey(member1.id));
assertTrue(lb.members.containsKey(member2.id));
assertTrue(lb.members.containsKey(member3.id));
assertTrue(lb.members.containsKey(member4.id));
assertTrue(lb.pools.get(member1.poolId).members.size()==2);
assertTrue(lb.pools.get(member3.poolId).members.size()==2);
// member1 should inherit valid vipId from pool
assertTrue(lb.vips.get(member1.vipId)!=null);
}
@Test
public void testRemoveMember() {
testCreateVip();
testCreatePool();
testCreateMember();
// verify correct initial condition
assertFalse(vip1==null);
assertFalse(vip2==null);
assertFalse(pool1==null);
assertFalse(pool2==null);
assertFalse(pool3==null);
assertFalse(member1==null);
assertFalse(member2==null);
assertFalse(member3==null);
assertFalse(member4==null);
lb.removeMember(member1.id);
lb.removeMember(member2.id);
lb.removeMember(member3.id);
lb.removeMember(member4.id);
// verify correct removal
assertFalse(lb.members.containsKey(member1.id));
assertFalse(lb.members.containsKey(member2.id));
assertFalse(lb.members.containsKey(member3.id));
assertFalse(lb.members.containsKey(member4.id));
//verify member cleanup from pool
assertFalse(lb.pools.get(member1.poolId).members.contains(member1.id));
assertFalse(lb.pools.get(member2.poolId).members.contains(member2.id));
assertFalse(lb.pools.get(member3.poolId).members.contains(member3.id));
assertFalse(lb.pools.get(member4.poolId).members.contains(member4.id));
}
@Test
public void testTwoSubsequentIcmpRequests() throws Exception {
testCreateVip();
testCreatePool();
testCreateMember();
IOFSwitch sw1;
- IPacket arpRequest1, arpRequest2, arpReply1, arpReply2, icmpPacket1, icmpPacket2;
+ IPacket arpRequest1, arpReply1, icmpPacket1, icmpPacket2;
- byte[] arpRequest1Serialized, arpRequest2Serialized;
- byte[] arpReply1Serialized, arpReply2Serialized;
+ byte[] arpRequest1Serialized;
+ byte[] arpReply1Serialized;
byte[] icmpPacket1Serialized, icmpPacket2Serialized;
- OFPacketIn arpRequestPacketIn1, arpRequestPacketIn2;
+ OFPacketIn arpRequestPacketIn1;
OFPacketIn icmpPacketIn1, icmpPacketIn2;
- OFPacketOut arpReplyPacketOut1, arpReplyPacketOut2;
+ OFPacketOut arpReplyPacketOut1;
Capture<OFMessage> wc1 = new Capture<OFMessage>(CaptureType.ALL);
Capture<FloodlightContext> bc1 =
new Capture<FloodlightContext>(CaptureType.ALL);
int fastWildcards =
OFMatch.OFPFW_IN_PORT |
OFMatch.OFPFW_NW_PROTO |
OFMatch.OFPFW_TP_SRC |
OFMatch.OFPFW_TP_DST |
OFMatch.OFPFW_NW_SRC_ALL |
OFMatch.OFPFW_NW_DST_ALL |
OFMatch.OFPFW_NW_TOS;
sw1 = EasyMock.createNiceMock(IOFSwitch.class);
expect(sw1.getId()).andReturn(1L).anyTimes();
expect(sw1.getStringId()).andReturn("00:00:00:00:00:01").anyTimes();
expect(sw1.getAttribute(IOFSwitch.PROP_FASTWILDCARDS)).andReturn((Integer)fastWildcards).anyTimes();
expect(sw1.hasAttribute(IOFSwitch.PROP_SUPPORTS_OFPP_TABLE)).andReturn(true).anyTimes();
sw1.write(capture(wc1), capture(bc1));
expectLastCall().anyTimes();
sw1.flush();
expectLastCall().anyTimes();
replay(sw1);
sfp.addedSwitch(sw1);
verify(sw1);
/* Test plan:
* - two clients and two servers on sw1 port 1, 2, 3, 4
* - mock arp request received towards vip1 from (1L, 1)
* - proxy arp got pushed out to (1L, 1)- check sw1 getting the packetout
* - mock icmp request received towards vip1 from (1L, 1)
* - device manager list of devices queried to identify source and dest devices
* - routing engine queried to get inbound and outbound routes
* - check getRoute calls and responses
* - sfp called to install flows
* - check sfp calls
*/
// Build topology
reset(topology);
expect(topology.isIncomingBroadcastAllowed(anyLong(), anyShort())).andReturn(true).anyTimes();
expect(topology.getL2DomainId(1L)).andReturn(1L).anyTimes();
expect(topology.isAttachmentPointPort(1L, (short)1)).andReturn(true).anyTimes();
expect(topology.isAttachmentPointPort(1L, (short)2)).andReturn(true).anyTimes();
expect(topology.isAttachmentPointPort(1L, (short)3)).andReturn(true).anyTimes();
expect(topology.isAttachmentPointPort(1L, (short)4)).andReturn(true).anyTimes();
replay(topology);
// Build arp packets
arpRequest1 = new Ethernet()
.setSourceMACAddress("00:00:00:00:00:01")
.setDestinationMACAddress("ff:ff:ff:ff:ff:ff")
.setEtherType(Ethernet.TYPE_ARP)
.setVlanID((short) 0)
.setPriorityCode((byte) 0)
.setPayload(
new ARP()
.setHardwareType(ARP.HW_TYPE_ETHERNET)
.setProtocolType(ARP.PROTO_TYPE_IP)
.setHardwareAddressLength((byte) 6)
.setProtocolAddressLength((byte) 4)
.setOpCode(ARP.OP_REQUEST)
.setSenderHardwareAddress(HexString.fromHexString("00:00:00:00:00:01"))
.setSenderProtocolAddress(IPv4.toIPv4AddressBytes("10.0.0.1"))
.setTargetHardwareAddress(HexString.fromHexString("00:00:00:00:00:00"))
.setTargetProtocolAddress(IPv4.toIPv4AddressBytes("10.0.0.100")));
arpRequest1Serialized = arpRequest1.serialize();
arpRequestPacketIn1 =
((OFPacketIn) getMockFloodlightProvider().getOFMessageFactory().
getMessage(OFType.PACKET_IN))
.setBufferId(-1)
.setInPort((short) 1)
.setPacketData(arpRequest1Serialized)
.setReason(OFPacketInReason.NO_MATCH)
.setTotalLength((short) arpRequest1Serialized.length);
IFloodlightProviderService.bcStore.put(cntx,
IFloodlightProviderService.CONTEXT_PI_PAYLOAD,
(Ethernet) arpRequest1);
// Mock proxy arp packet-out
arpReply1 = new Ethernet()
.setSourceMACAddress(LBVip.LB_PROXY_MAC)
.setDestinationMACAddress(HexString.fromHexString("00:00:00:00:00:01"))
.setEtherType(Ethernet.TYPE_ARP)
.setVlanID((short) 0)
.setPriorityCode((byte) 0)
.setPayload(
new ARP()
.setHardwareType(ARP.HW_TYPE_ETHERNET)
.setProtocolType(ARP.PROTO_TYPE_IP)
.setHardwareAddressLength((byte) 6)
.setProtocolAddressLength((byte) 4)
.setOpCode(ARP.OP_REPLY)
.setSenderHardwareAddress(HexString.fromHexString(LBVip.LB_PROXY_MAC))
.setSenderProtocolAddress(IPv4.toIPv4AddressBytes("10.0.0.100"))
.setTargetHardwareAddress(HexString.fromHexString("00:00:00:00:00:01"))
.setTargetProtocolAddress(IPv4.toIPv4AddressBytes("10.0.0.1")));
arpReply1Serialized = arpReply1.serialize();
arpReplyPacketOut1 =
(OFPacketOut) getMockFloodlightProvider().getOFMessageFactory().
getMessage(OFType.PACKET_OUT);
arpReplyPacketOut1.setBufferId(OFPacketOut.BUFFER_ID_NONE)
.setInPort(OFPort.OFPP_NONE.getValue());
List<OFAction> poactions = new ArrayList<OFAction>();
poactions.add(new OFActionOutput(arpRequestPacketIn1.getInPort(), (short) 0xffff));
arpReplyPacketOut1.setActions(poactions)
.setActionsLength((short) OFActionOutput.MINIMUM_LENGTH)
.setPacketData(arpReply1Serialized)
.setLengthU(OFPacketOut.MINIMUM_LENGTH+
arpReplyPacketOut1.getActionsLength()+
arpReply1Serialized.length);
lb.receive(sw1, arpRequestPacketIn1, cntx);
verify(sw1, topology);
assertTrue(wc1.hasCaptured()); // wc1 should get packetout
List<OFMessage> msglist1 = wc1.getValues();
for (OFMessage m: msglist1) {
if (m instanceof OFPacketOut)
assertEquals(arpReplyPacketOut1, m);
else
assertTrue(false); // unexpected message
}
//
// Skip arpRequest2 test - in reality this will happen, but for unit test the same logic
// is already validated with arpRequest1 test above
//
// Build icmp packets
icmpPacket1 = new Ethernet()
.setSourceMACAddress("00:00:00:00:00:01")
.setDestinationMACAddress(LBVip.LB_PROXY_MAC)
.setEtherType(Ethernet.TYPE_IPv4)
.setVlanID((short) 0)
.setPriorityCode((byte) 0)
.setPayload(
new IPv4()
.setSourceAddress("10.0.0.1")
.setDestinationAddress("10.0.0.100")
.setProtocol(IPv4.PROTOCOL_ICMP)
.setPayload(new ICMP()
.setIcmpCode((byte) 0)
.setIcmpType((byte) 0)));
icmpPacket1Serialized = icmpPacket1.serialize();
icmpPacketIn1 =
((OFPacketIn) getMockFloodlightProvider().getOFMessageFactory().
getMessage(OFType.PACKET_IN))
.setBufferId(-1)
.setInPort((short) 1)
.setPacketData(icmpPacket1Serialized)
.setReason(OFPacketInReason.NO_MATCH)
.setTotalLength((short) icmpPacket1Serialized.length);
icmpPacket2 = new Ethernet()
.setSourceMACAddress("00:00:00:00:00:02")
.setDestinationMACAddress(LBVip.LB_PROXY_MAC)
.setEtherType(Ethernet.TYPE_IPv4)
.setVlanID((short) 0)
.setPriorityCode((byte) 0)
.setPayload(
new IPv4()
.setSourceAddress("10.0.0.2")
.setDestinationAddress("10.0.0.100")
.setProtocol(IPv4.PROTOCOL_ICMP)
.setPayload(new ICMP()
.setIcmpCode((byte) 0)
.setIcmpType((byte) 0)));
icmpPacket2Serialized = icmpPacket2.serialize();
icmpPacketIn2 =
((OFPacketIn) getMockFloodlightProvider().getOFMessageFactory().
getMessage(OFType.PACKET_IN))
.setBufferId(-1)
.setInPort((short) 2)
.setPacketData(icmpPacket2Serialized)
.setReason(OFPacketInReason.NO_MATCH)
.setTotalLength((short) icmpPacket2Serialized.length);
byte[] dataLayerSource1 = ((Ethernet)icmpPacket1).getSourceMACAddress();
int networkSource1 = ((IPv4)((Ethernet)icmpPacket1).getPayload()).getSourceAddress();
byte[] dataLayerDest1 = HexString.fromHexString("00:00:00:00:00:03");
int networkDest1 = IPv4.toIPv4Address("10.0.0.3");
byte[] dataLayerSource2 = ((Ethernet)icmpPacket2).getSourceMACAddress();
int networkSource2 = ((IPv4)((Ethernet)icmpPacket2).getPayload()).getSourceAddress();
byte[] dataLayerDest2 = HexString.fromHexString("00:00:00:00:00:04");
int networkDest2 = IPv4.toIPv4Address("10.0.0.4");
deviceManager.learnEntity(Ethernet.toLong(dataLayerSource1),
null, networkSource1,
1L, 1);
deviceManager.learnEntity(Ethernet.toLong(dataLayerSource2),
null, networkSource2,
1L, 2);
deviceManager.learnEntity(Ethernet.toLong(dataLayerDest1),
null, networkDest1,
1L, 3);
deviceManager.learnEntity(Ethernet.toLong(dataLayerDest2),
null, networkDest2,
1L, 4);
// in bound #1
Route route1 = new Route(1L, 1L);
List<NodePortTuple> nptList1 = new ArrayList<NodePortTuple>();
nptList1.add(new NodePortTuple(1L, (short)1));
nptList1.add(new NodePortTuple(1L, (short)3));
route1.setPath(nptList1);
expect(routingEngine.getRoute(1L, (short)1, 1L, (short)3, 0)).andReturn(route1).atLeastOnce();
// outbound #1
Route route2 = new Route(1L, 1L);
List<NodePortTuple> nptList2 = new ArrayList<NodePortTuple>();
nptList2.add(new NodePortTuple(1L, (short)3));
nptList2.add(new NodePortTuple(1L, (short)1));
route2.setPath(nptList2);
expect(routingEngine.getRoute(1L, (short)3, 1L, (short)1, 0)).andReturn(route2).atLeastOnce();
// inbound #2
Route route3 = new Route(1L, 1L);
List<NodePortTuple> nptList3 = new ArrayList<NodePortTuple>();
nptList3.add(new NodePortTuple(1L, (short)2));
nptList3.add(new NodePortTuple(1L, (short)4));
route3.setPath(nptList3);
expect(routingEngine.getRoute(1L, (short)2, 1L, (short)4, 0)).andReturn(route3).atLeastOnce();
// outbound #2
Route route4 = new Route(1L, 1L);
List<NodePortTuple> nptList4 = new ArrayList<NodePortTuple>();
nptList4.add(new NodePortTuple(1L, (short)4));
nptList4.add(new NodePortTuple(1L, (short)2));
route4.setPath(nptList3);
expect(routingEngine.getRoute(1L, (short)4, 1L, (short)2, 0)).andReturn(route4).atLeastOnce();
replay(routingEngine);
wc1.reset();
IFloodlightProviderService.bcStore.put(cntx,
IFloodlightProviderService.CONTEXT_PI_PAYLOAD,
(Ethernet) icmpPacket1);
lb.receive(sw1, icmpPacketIn1, cntx);
IFloodlightProviderService.bcStore.put(cntx,
IFloodlightProviderService.CONTEXT_PI_PAYLOAD,
(Ethernet) icmpPacket2);
lb.receive(sw1, icmpPacketIn2, cntx);
assertTrue(wc1.hasCaptured()); // wc1 should get packetout
List<OFMessage> msglist2 = wc1.getValues();
assertTrue(msglist2.size()==2); // has inbound and outbound packetouts
// TODO: not seeing flowmods yet ...
Map<String, OFFlowMod> map = sfp.getFlows("00:00:00:00:00:00:00:01");
assertTrue(map.size()==4);
}
}
| false | true | public void testTwoSubsequentIcmpRequests() throws Exception {
testCreateVip();
testCreatePool();
testCreateMember();
IOFSwitch sw1;
IPacket arpRequest1, arpRequest2, arpReply1, arpReply2, icmpPacket1, icmpPacket2;
byte[] arpRequest1Serialized, arpRequest2Serialized;
byte[] arpReply1Serialized, arpReply2Serialized;
byte[] icmpPacket1Serialized, icmpPacket2Serialized;
OFPacketIn arpRequestPacketIn1, arpRequestPacketIn2;
OFPacketIn icmpPacketIn1, icmpPacketIn2;
OFPacketOut arpReplyPacketOut1, arpReplyPacketOut2;
Capture<OFMessage> wc1 = new Capture<OFMessage>(CaptureType.ALL);
Capture<FloodlightContext> bc1 =
new Capture<FloodlightContext>(CaptureType.ALL);
int fastWildcards =
OFMatch.OFPFW_IN_PORT |
OFMatch.OFPFW_NW_PROTO |
OFMatch.OFPFW_TP_SRC |
OFMatch.OFPFW_TP_DST |
OFMatch.OFPFW_NW_SRC_ALL |
OFMatch.OFPFW_NW_DST_ALL |
OFMatch.OFPFW_NW_TOS;
sw1 = EasyMock.createNiceMock(IOFSwitch.class);
expect(sw1.getId()).andReturn(1L).anyTimes();
expect(sw1.getStringId()).andReturn("00:00:00:00:00:01").anyTimes();
expect(sw1.getAttribute(IOFSwitch.PROP_FASTWILDCARDS)).andReturn((Integer)fastWildcards).anyTimes();
expect(sw1.hasAttribute(IOFSwitch.PROP_SUPPORTS_OFPP_TABLE)).andReturn(true).anyTimes();
sw1.write(capture(wc1), capture(bc1));
expectLastCall().anyTimes();
sw1.flush();
expectLastCall().anyTimes();
replay(sw1);
sfp.addedSwitch(sw1);
verify(sw1);
/* Test plan:
* - two clients and two servers on sw1 port 1, 2, 3, 4
* - mock arp request received towards vip1 from (1L, 1)
* - proxy arp got pushed out to (1L, 1)- check sw1 getting the packetout
* - mock icmp request received towards vip1 from (1L, 1)
* - device manager list of devices queried to identify source and dest devices
* - routing engine queried to get inbound and outbound routes
* - check getRoute calls and responses
* - sfp called to install flows
* - check sfp calls
*/
// Build topology
reset(topology);
expect(topology.isIncomingBroadcastAllowed(anyLong(), anyShort())).andReturn(true).anyTimes();
expect(topology.getL2DomainId(1L)).andReturn(1L).anyTimes();
expect(topology.isAttachmentPointPort(1L, (short)1)).andReturn(true).anyTimes();
expect(topology.isAttachmentPointPort(1L, (short)2)).andReturn(true).anyTimes();
expect(topology.isAttachmentPointPort(1L, (short)3)).andReturn(true).anyTimes();
expect(topology.isAttachmentPointPort(1L, (short)4)).andReturn(true).anyTimes();
replay(topology);
// Build arp packets
arpRequest1 = new Ethernet()
.setSourceMACAddress("00:00:00:00:00:01")
.setDestinationMACAddress("ff:ff:ff:ff:ff:ff")
.setEtherType(Ethernet.TYPE_ARP)
.setVlanID((short) 0)
.setPriorityCode((byte) 0)
.setPayload(
new ARP()
.setHardwareType(ARP.HW_TYPE_ETHERNET)
.setProtocolType(ARP.PROTO_TYPE_IP)
.setHardwareAddressLength((byte) 6)
.setProtocolAddressLength((byte) 4)
.setOpCode(ARP.OP_REQUEST)
.setSenderHardwareAddress(HexString.fromHexString("00:00:00:00:00:01"))
.setSenderProtocolAddress(IPv4.toIPv4AddressBytes("10.0.0.1"))
.setTargetHardwareAddress(HexString.fromHexString("00:00:00:00:00:00"))
.setTargetProtocolAddress(IPv4.toIPv4AddressBytes("10.0.0.100")));
arpRequest1Serialized = arpRequest1.serialize();
arpRequestPacketIn1 =
((OFPacketIn) getMockFloodlightProvider().getOFMessageFactory().
getMessage(OFType.PACKET_IN))
.setBufferId(-1)
.setInPort((short) 1)
.setPacketData(arpRequest1Serialized)
.setReason(OFPacketInReason.NO_MATCH)
.setTotalLength((short) arpRequest1Serialized.length);
IFloodlightProviderService.bcStore.put(cntx,
IFloodlightProviderService.CONTEXT_PI_PAYLOAD,
(Ethernet) arpRequest1);
// Mock proxy arp packet-out
arpReply1 = new Ethernet()
.setSourceMACAddress(LBVip.LB_PROXY_MAC)
.setDestinationMACAddress(HexString.fromHexString("00:00:00:00:00:01"))
.setEtherType(Ethernet.TYPE_ARP)
.setVlanID((short) 0)
.setPriorityCode((byte) 0)
.setPayload(
new ARP()
.setHardwareType(ARP.HW_TYPE_ETHERNET)
.setProtocolType(ARP.PROTO_TYPE_IP)
.setHardwareAddressLength((byte) 6)
.setProtocolAddressLength((byte) 4)
.setOpCode(ARP.OP_REPLY)
.setSenderHardwareAddress(HexString.fromHexString(LBVip.LB_PROXY_MAC))
.setSenderProtocolAddress(IPv4.toIPv4AddressBytes("10.0.0.100"))
.setTargetHardwareAddress(HexString.fromHexString("00:00:00:00:00:01"))
.setTargetProtocolAddress(IPv4.toIPv4AddressBytes("10.0.0.1")));
arpReply1Serialized = arpReply1.serialize();
arpReplyPacketOut1 =
(OFPacketOut) getMockFloodlightProvider().getOFMessageFactory().
getMessage(OFType.PACKET_OUT);
arpReplyPacketOut1.setBufferId(OFPacketOut.BUFFER_ID_NONE)
.setInPort(OFPort.OFPP_NONE.getValue());
List<OFAction> poactions = new ArrayList<OFAction>();
poactions.add(new OFActionOutput(arpRequestPacketIn1.getInPort(), (short) 0xffff));
arpReplyPacketOut1.setActions(poactions)
.setActionsLength((short) OFActionOutput.MINIMUM_LENGTH)
.setPacketData(arpReply1Serialized)
.setLengthU(OFPacketOut.MINIMUM_LENGTH+
arpReplyPacketOut1.getActionsLength()+
arpReply1Serialized.length);
lb.receive(sw1, arpRequestPacketIn1, cntx);
verify(sw1, topology);
assertTrue(wc1.hasCaptured()); // wc1 should get packetout
List<OFMessage> msglist1 = wc1.getValues();
for (OFMessage m: msglist1) {
if (m instanceof OFPacketOut)
assertEquals(arpReplyPacketOut1, m);
else
assertTrue(false); // unexpected message
}
//
// Skip arpRequest2 test - in reality this will happen, but for unit test the same logic
// is already validated with arpRequest1 test above
//
// Build icmp packets
icmpPacket1 = new Ethernet()
.setSourceMACAddress("00:00:00:00:00:01")
.setDestinationMACAddress(LBVip.LB_PROXY_MAC)
.setEtherType(Ethernet.TYPE_IPv4)
.setVlanID((short) 0)
.setPriorityCode((byte) 0)
.setPayload(
new IPv4()
.setSourceAddress("10.0.0.1")
.setDestinationAddress("10.0.0.100")
.setProtocol(IPv4.PROTOCOL_ICMP)
.setPayload(new ICMP()
.setIcmpCode((byte) 0)
.setIcmpType((byte) 0)));
icmpPacket1Serialized = icmpPacket1.serialize();
icmpPacketIn1 =
((OFPacketIn) getMockFloodlightProvider().getOFMessageFactory().
getMessage(OFType.PACKET_IN))
.setBufferId(-1)
.setInPort((short) 1)
.setPacketData(icmpPacket1Serialized)
.setReason(OFPacketInReason.NO_MATCH)
.setTotalLength((short) icmpPacket1Serialized.length);
icmpPacket2 = new Ethernet()
.setSourceMACAddress("00:00:00:00:00:02")
.setDestinationMACAddress(LBVip.LB_PROXY_MAC)
.setEtherType(Ethernet.TYPE_IPv4)
.setVlanID((short) 0)
.setPriorityCode((byte) 0)
.setPayload(
new IPv4()
.setSourceAddress("10.0.0.2")
.setDestinationAddress("10.0.0.100")
.setProtocol(IPv4.PROTOCOL_ICMP)
.setPayload(new ICMP()
.setIcmpCode((byte) 0)
.setIcmpType((byte) 0)));
icmpPacket2Serialized = icmpPacket2.serialize();
icmpPacketIn2 =
((OFPacketIn) getMockFloodlightProvider().getOFMessageFactory().
getMessage(OFType.PACKET_IN))
.setBufferId(-1)
.setInPort((short) 2)
.setPacketData(icmpPacket2Serialized)
.setReason(OFPacketInReason.NO_MATCH)
.setTotalLength((short) icmpPacket2Serialized.length);
byte[] dataLayerSource1 = ((Ethernet)icmpPacket1).getSourceMACAddress();
int networkSource1 = ((IPv4)((Ethernet)icmpPacket1).getPayload()).getSourceAddress();
byte[] dataLayerDest1 = HexString.fromHexString("00:00:00:00:00:03");
int networkDest1 = IPv4.toIPv4Address("10.0.0.3");
byte[] dataLayerSource2 = ((Ethernet)icmpPacket2).getSourceMACAddress();
int networkSource2 = ((IPv4)((Ethernet)icmpPacket2).getPayload()).getSourceAddress();
byte[] dataLayerDest2 = HexString.fromHexString("00:00:00:00:00:04");
int networkDest2 = IPv4.toIPv4Address("10.0.0.4");
deviceManager.learnEntity(Ethernet.toLong(dataLayerSource1),
null, networkSource1,
1L, 1);
deviceManager.learnEntity(Ethernet.toLong(dataLayerSource2),
null, networkSource2,
1L, 2);
deviceManager.learnEntity(Ethernet.toLong(dataLayerDest1),
null, networkDest1,
1L, 3);
deviceManager.learnEntity(Ethernet.toLong(dataLayerDest2),
null, networkDest2,
1L, 4);
// in bound #1
Route route1 = new Route(1L, 1L);
List<NodePortTuple> nptList1 = new ArrayList<NodePortTuple>();
nptList1.add(new NodePortTuple(1L, (short)1));
nptList1.add(new NodePortTuple(1L, (short)3));
route1.setPath(nptList1);
expect(routingEngine.getRoute(1L, (short)1, 1L, (short)3, 0)).andReturn(route1).atLeastOnce();
// outbound #1
Route route2 = new Route(1L, 1L);
List<NodePortTuple> nptList2 = new ArrayList<NodePortTuple>();
nptList2.add(new NodePortTuple(1L, (short)3));
nptList2.add(new NodePortTuple(1L, (short)1));
route2.setPath(nptList2);
expect(routingEngine.getRoute(1L, (short)3, 1L, (short)1, 0)).andReturn(route2).atLeastOnce();
// inbound #2
Route route3 = new Route(1L, 1L);
List<NodePortTuple> nptList3 = new ArrayList<NodePortTuple>();
nptList3.add(new NodePortTuple(1L, (short)2));
nptList3.add(new NodePortTuple(1L, (short)4));
route3.setPath(nptList3);
expect(routingEngine.getRoute(1L, (short)2, 1L, (short)4, 0)).andReturn(route3).atLeastOnce();
// outbound #2
Route route4 = new Route(1L, 1L);
List<NodePortTuple> nptList4 = new ArrayList<NodePortTuple>();
nptList4.add(new NodePortTuple(1L, (short)4));
nptList4.add(new NodePortTuple(1L, (short)2));
route4.setPath(nptList3);
expect(routingEngine.getRoute(1L, (short)4, 1L, (short)2, 0)).andReturn(route4).atLeastOnce();
replay(routingEngine);
wc1.reset();
IFloodlightProviderService.bcStore.put(cntx,
IFloodlightProviderService.CONTEXT_PI_PAYLOAD,
(Ethernet) icmpPacket1);
lb.receive(sw1, icmpPacketIn1, cntx);
IFloodlightProviderService.bcStore.put(cntx,
IFloodlightProviderService.CONTEXT_PI_PAYLOAD,
(Ethernet) icmpPacket2);
lb.receive(sw1, icmpPacketIn2, cntx);
assertTrue(wc1.hasCaptured()); // wc1 should get packetout
List<OFMessage> msglist2 = wc1.getValues();
assertTrue(msglist2.size()==2); // has inbound and outbound packetouts
// TODO: not seeing flowmods yet ...
Map<String, OFFlowMod> map = sfp.getFlows("00:00:00:00:00:00:00:01");
assertTrue(map.size()==4);
}
| public void testTwoSubsequentIcmpRequests() throws Exception {
testCreateVip();
testCreatePool();
testCreateMember();
IOFSwitch sw1;
IPacket arpRequest1, arpReply1, icmpPacket1, icmpPacket2;
byte[] arpRequest1Serialized;
byte[] arpReply1Serialized;
byte[] icmpPacket1Serialized, icmpPacket2Serialized;
OFPacketIn arpRequestPacketIn1;
OFPacketIn icmpPacketIn1, icmpPacketIn2;
OFPacketOut arpReplyPacketOut1;
Capture<OFMessage> wc1 = new Capture<OFMessage>(CaptureType.ALL);
Capture<FloodlightContext> bc1 =
new Capture<FloodlightContext>(CaptureType.ALL);
int fastWildcards =
OFMatch.OFPFW_IN_PORT |
OFMatch.OFPFW_NW_PROTO |
OFMatch.OFPFW_TP_SRC |
OFMatch.OFPFW_TP_DST |
OFMatch.OFPFW_NW_SRC_ALL |
OFMatch.OFPFW_NW_DST_ALL |
OFMatch.OFPFW_NW_TOS;
sw1 = EasyMock.createNiceMock(IOFSwitch.class);
expect(sw1.getId()).andReturn(1L).anyTimes();
expect(sw1.getStringId()).andReturn("00:00:00:00:00:01").anyTimes();
expect(sw1.getAttribute(IOFSwitch.PROP_FASTWILDCARDS)).andReturn((Integer)fastWildcards).anyTimes();
expect(sw1.hasAttribute(IOFSwitch.PROP_SUPPORTS_OFPP_TABLE)).andReturn(true).anyTimes();
sw1.write(capture(wc1), capture(bc1));
expectLastCall().anyTimes();
sw1.flush();
expectLastCall().anyTimes();
replay(sw1);
sfp.addedSwitch(sw1);
verify(sw1);
/* Test plan:
* - two clients and two servers on sw1 port 1, 2, 3, 4
* - mock arp request received towards vip1 from (1L, 1)
* - proxy arp got pushed out to (1L, 1)- check sw1 getting the packetout
* - mock icmp request received towards vip1 from (1L, 1)
* - device manager list of devices queried to identify source and dest devices
* - routing engine queried to get inbound and outbound routes
* - check getRoute calls and responses
* - sfp called to install flows
* - check sfp calls
*/
// Build topology
reset(topology);
expect(topology.isIncomingBroadcastAllowed(anyLong(), anyShort())).andReturn(true).anyTimes();
expect(topology.getL2DomainId(1L)).andReturn(1L).anyTimes();
expect(topology.isAttachmentPointPort(1L, (short)1)).andReturn(true).anyTimes();
expect(topology.isAttachmentPointPort(1L, (short)2)).andReturn(true).anyTimes();
expect(topology.isAttachmentPointPort(1L, (short)3)).andReturn(true).anyTimes();
expect(topology.isAttachmentPointPort(1L, (short)4)).andReturn(true).anyTimes();
replay(topology);
// Build arp packets
arpRequest1 = new Ethernet()
.setSourceMACAddress("00:00:00:00:00:01")
.setDestinationMACAddress("ff:ff:ff:ff:ff:ff")
.setEtherType(Ethernet.TYPE_ARP)
.setVlanID((short) 0)
.setPriorityCode((byte) 0)
.setPayload(
new ARP()
.setHardwareType(ARP.HW_TYPE_ETHERNET)
.setProtocolType(ARP.PROTO_TYPE_IP)
.setHardwareAddressLength((byte) 6)
.setProtocolAddressLength((byte) 4)
.setOpCode(ARP.OP_REQUEST)
.setSenderHardwareAddress(HexString.fromHexString("00:00:00:00:00:01"))
.setSenderProtocolAddress(IPv4.toIPv4AddressBytes("10.0.0.1"))
.setTargetHardwareAddress(HexString.fromHexString("00:00:00:00:00:00"))
.setTargetProtocolAddress(IPv4.toIPv4AddressBytes("10.0.0.100")));
arpRequest1Serialized = arpRequest1.serialize();
arpRequestPacketIn1 =
((OFPacketIn) getMockFloodlightProvider().getOFMessageFactory().
getMessage(OFType.PACKET_IN))
.setBufferId(-1)
.setInPort((short) 1)
.setPacketData(arpRequest1Serialized)
.setReason(OFPacketInReason.NO_MATCH)
.setTotalLength((short) arpRequest1Serialized.length);
IFloodlightProviderService.bcStore.put(cntx,
IFloodlightProviderService.CONTEXT_PI_PAYLOAD,
(Ethernet) arpRequest1);
// Mock proxy arp packet-out
arpReply1 = new Ethernet()
.setSourceMACAddress(LBVip.LB_PROXY_MAC)
.setDestinationMACAddress(HexString.fromHexString("00:00:00:00:00:01"))
.setEtherType(Ethernet.TYPE_ARP)
.setVlanID((short) 0)
.setPriorityCode((byte) 0)
.setPayload(
new ARP()
.setHardwareType(ARP.HW_TYPE_ETHERNET)
.setProtocolType(ARP.PROTO_TYPE_IP)
.setHardwareAddressLength((byte) 6)
.setProtocolAddressLength((byte) 4)
.setOpCode(ARP.OP_REPLY)
.setSenderHardwareAddress(HexString.fromHexString(LBVip.LB_PROXY_MAC))
.setSenderProtocolAddress(IPv4.toIPv4AddressBytes("10.0.0.100"))
.setTargetHardwareAddress(HexString.fromHexString("00:00:00:00:00:01"))
.setTargetProtocolAddress(IPv4.toIPv4AddressBytes("10.0.0.1")));
arpReply1Serialized = arpReply1.serialize();
arpReplyPacketOut1 =
(OFPacketOut) getMockFloodlightProvider().getOFMessageFactory().
getMessage(OFType.PACKET_OUT);
arpReplyPacketOut1.setBufferId(OFPacketOut.BUFFER_ID_NONE)
.setInPort(OFPort.OFPP_NONE.getValue());
List<OFAction> poactions = new ArrayList<OFAction>();
poactions.add(new OFActionOutput(arpRequestPacketIn1.getInPort(), (short) 0xffff));
arpReplyPacketOut1.setActions(poactions)
.setActionsLength((short) OFActionOutput.MINIMUM_LENGTH)
.setPacketData(arpReply1Serialized)
.setLengthU(OFPacketOut.MINIMUM_LENGTH+
arpReplyPacketOut1.getActionsLength()+
arpReply1Serialized.length);
lb.receive(sw1, arpRequestPacketIn1, cntx);
verify(sw1, topology);
assertTrue(wc1.hasCaptured()); // wc1 should get packetout
List<OFMessage> msglist1 = wc1.getValues();
for (OFMessage m: msglist1) {
if (m instanceof OFPacketOut)
assertEquals(arpReplyPacketOut1, m);
else
assertTrue(false); // unexpected message
}
//
// Skip arpRequest2 test - in reality this will happen, but for unit test the same logic
// is already validated with arpRequest1 test above
//
// Build icmp packets
icmpPacket1 = new Ethernet()
.setSourceMACAddress("00:00:00:00:00:01")
.setDestinationMACAddress(LBVip.LB_PROXY_MAC)
.setEtherType(Ethernet.TYPE_IPv4)
.setVlanID((short) 0)
.setPriorityCode((byte) 0)
.setPayload(
new IPv4()
.setSourceAddress("10.0.0.1")
.setDestinationAddress("10.0.0.100")
.setProtocol(IPv4.PROTOCOL_ICMP)
.setPayload(new ICMP()
.setIcmpCode((byte) 0)
.setIcmpType((byte) 0)));
icmpPacket1Serialized = icmpPacket1.serialize();
icmpPacketIn1 =
((OFPacketIn) getMockFloodlightProvider().getOFMessageFactory().
getMessage(OFType.PACKET_IN))
.setBufferId(-1)
.setInPort((short) 1)
.setPacketData(icmpPacket1Serialized)
.setReason(OFPacketInReason.NO_MATCH)
.setTotalLength((short) icmpPacket1Serialized.length);
icmpPacket2 = new Ethernet()
.setSourceMACAddress("00:00:00:00:00:02")
.setDestinationMACAddress(LBVip.LB_PROXY_MAC)
.setEtherType(Ethernet.TYPE_IPv4)
.setVlanID((short) 0)
.setPriorityCode((byte) 0)
.setPayload(
new IPv4()
.setSourceAddress("10.0.0.2")
.setDestinationAddress("10.0.0.100")
.setProtocol(IPv4.PROTOCOL_ICMP)
.setPayload(new ICMP()
.setIcmpCode((byte) 0)
.setIcmpType((byte) 0)));
icmpPacket2Serialized = icmpPacket2.serialize();
icmpPacketIn2 =
((OFPacketIn) getMockFloodlightProvider().getOFMessageFactory().
getMessage(OFType.PACKET_IN))
.setBufferId(-1)
.setInPort((short) 2)
.setPacketData(icmpPacket2Serialized)
.setReason(OFPacketInReason.NO_MATCH)
.setTotalLength((short) icmpPacket2Serialized.length);
byte[] dataLayerSource1 = ((Ethernet)icmpPacket1).getSourceMACAddress();
int networkSource1 = ((IPv4)((Ethernet)icmpPacket1).getPayload()).getSourceAddress();
byte[] dataLayerDest1 = HexString.fromHexString("00:00:00:00:00:03");
int networkDest1 = IPv4.toIPv4Address("10.0.0.3");
byte[] dataLayerSource2 = ((Ethernet)icmpPacket2).getSourceMACAddress();
int networkSource2 = ((IPv4)((Ethernet)icmpPacket2).getPayload()).getSourceAddress();
byte[] dataLayerDest2 = HexString.fromHexString("00:00:00:00:00:04");
int networkDest2 = IPv4.toIPv4Address("10.0.0.4");
deviceManager.learnEntity(Ethernet.toLong(dataLayerSource1),
null, networkSource1,
1L, 1);
deviceManager.learnEntity(Ethernet.toLong(dataLayerSource2),
null, networkSource2,
1L, 2);
deviceManager.learnEntity(Ethernet.toLong(dataLayerDest1),
null, networkDest1,
1L, 3);
deviceManager.learnEntity(Ethernet.toLong(dataLayerDest2),
null, networkDest2,
1L, 4);
// in bound #1
Route route1 = new Route(1L, 1L);
List<NodePortTuple> nptList1 = new ArrayList<NodePortTuple>();
nptList1.add(new NodePortTuple(1L, (short)1));
nptList1.add(new NodePortTuple(1L, (short)3));
route1.setPath(nptList1);
expect(routingEngine.getRoute(1L, (short)1, 1L, (short)3, 0)).andReturn(route1).atLeastOnce();
// outbound #1
Route route2 = new Route(1L, 1L);
List<NodePortTuple> nptList2 = new ArrayList<NodePortTuple>();
nptList2.add(new NodePortTuple(1L, (short)3));
nptList2.add(new NodePortTuple(1L, (short)1));
route2.setPath(nptList2);
expect(routingEngine.getRoute(1L, (short)3, 1L, (short)1, 0)).andReturn(route2).atLeastOnce();
// inbound #2
Route route3 = new Route(1L, 1L);
List<NodePortTuple> nptList3 = new ArrayList<NodePortTuple>();
nptList3.add(new NodePortTuple(1L, (short)2));
nptList3.add(new NodePortTuple(1L, (short)4));
route3.setPath(nptList3);
expect(routingEngine.getRoute(1L, (short)2, 1L, (short)4, 0)).andReturn(route3).atLeastOnce();
// outbound #2
Route route4 = new Route(1L, 1L);
List<NodePortTuple> nptList4 = new ArrayList<NodePortTuple>();
nptList4.add(new NodePortTuple(1L, (short)4));
nptList4.add(new NodePortTuple(1L, (short)2));
route4.setPath(nptList3);
expect(routingEngine.getRoute(1L, (short)4, 1L, (short)2, 0)).andReturn(route4).atLeastOnce();
replay(routingEngine);
wc1.reset();
IFloodlightProviderService.bcStore.put(cntx,
IFloodlightProviderService.CONTEXT_PI_PAYLOAD,
(Ethernet) icmpPacket1);
lb.receive(sw1, icmpPacketIn1, cntx);
IFloodlightProviderService.bcStore.put(cntx,
IFloodlightProviderService.CONTEXT_PI_PAYLOAD,
(Ethernet) icmpPacket2);
lb.receive(sw1, icmpPacketIn2, cntx);
assertTrue(wc1.hasCaptured()); // wc1 should get packetout
List<OFMessage> msglist2 = wc1.getValues();
assertTrue(msglist2.size()==2); // has inbound and outbound packetouts
// TODO: not seeing flowmods yet ...
Map<String, OFFlowMod> map = sfp.getFlows("00:00:00:00:00:00:00:01");
assertTrue(map.size()==4);
}
|
diff --git a/src/main/java/com/ai/myplugin/sensor/RandomSensor.java b/src/main/java/com/ai/myplugin/sensor/RandomSensor.java
index 5082a5a..ec5ca4e 100644
--- a/src/main/java/com/ai/myplugin/sensor/RandomSensor.java
+++ b/src/main/java/com/ai/myplugin/sensor/RandomSensor.java
@@ -1,100 +1,100 @@
package com.ai.myplugin.sensor;
import com.ai.bayes.model.BayesianNetwork;
import com.ai.bayes.model.Pair;
import com.ai.bayes.plugins.BNSensorPlugin;
import com.ai.bayes.scenario.TestResult;
import com.ai.util.resource.NodeSessionParams;
import com.ai.util.resource.TestSessionContext;
import net.xeoh.plugins.base.annotations.PluginImplementation;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@PluginImplementation
public class RandomSensor implements BNSensorPlugin {
private static final String NAME = "Random";
private double res;
private Map<String, Object> map = new ConcurrentHashMap<String, Object>();
public TestResult execute(TestSessionContext testSessionContext) {
String nodeName = (String) testSessionContext.getAttribute(NodeSessionParams.NODE_NAME);
BayesianNetwork bayesianNetwork = (BayesianNetwork) testSessionContext.getAttribute(NodeSessionParams.BN_NETWORK);
List<Pair<Double, String>> probs = bayesianNetwork.getProbabilities(nodeName);
double [] coins = new double[probs.size()];
double incr = 0;
double value;
System.out.println("assign priors for the game");
for(int i = 0; i < probs.size(); i++ ){
value = probs.get(i).fst ;
coins[i] = value + incr;
incr += value;
System.out.println("for state" + probs.get(i).snd + " assign the coin value " + value);
}
res = Math.random();
final String observedState = probs.get(findStateIndexForVal(res, coins)).snd;
return new TestResult() {
public boolean isSuccess() {
return true;
}
public String getName() {
return "Random Result";
}
public String getObserverState() {
return observedState;
}
public String getRawData(){
return "{" +
- "\"observedState\" : " + observedState + "," +
- "\"randomValue\" : " + "\""+res + "\""+
+ "\"observedState\" : \"" + observedState + "\" ," +
+ "\"randomValue\" : " +res +
"}";
}
} ;
}
private int findStateIndexForVal(double val, double[] coins) {
for(int i = 0; i< coins.length; i ++){
if(val < coins [i]) {
return i;
}
}
return coins.length - 1;
}
public String getName() {
return NAME;
}
public String[] getSupportedStates() {
return new String[] {};
}
public String[] getRequiredProperties() {
return new String[]{};
}
public void setProperty(String string, Object obj) {
map.put(string, obj);
}
public Object getProperty(String string) {
return map.get(string);
}
public String getDescription() {
return "Random Plugin Sensor that generates random states (with prob. distribution according to the priors)";
}
}
| true | true | public TestResult execute(TestSessionContext testSessionContext) {
String nodeName = (String) testSessionContext.getAttribute(NodeSessionParams.NODE_NAME);
BayesianNetwork bayesianNetwork = (BayesianNetwork) testSessionContext.getAttribute(NodeSessionParams.BN_NETWORK);
List<Pair<Double, String>> probs = bayesianNetwork.getProbabilities(nodeName);
double [] coins = new double[probs.size()];
double incr = 0;
double value;
System.out.println("assign priors for the game");
for(int i = 0; i < probs.size(); i++ ){
value = probs.get(i).fst ;
coins[i] = value + incr;
incr += value;
System.out.println("for state" + probs.get(i).snd + " assign the coin value " + value);
}
res = Math.random();
final String observedState = probs.get(findStateIndexForVal(res, coins)).snd;
return new TestResult() {
public boolean isSuccess() {
return true;
}
public String getName() {
return "Random Result";
}
public String getObserverState() {
return observedState;
}
public String getRawData(){
return "{" +
"\"observedState\" : " + observedState + "," +
"\"randomValue\" : " + "\""+res + "\""+
"}";
}
} ;
}
| public TestResult execute(TestSessionContext testSessionContext) {
String nodeName = (String) testSessionContext.getAttribute(NodeSessionParams.NODE_NAME);
BayesianNetwork bayesianNetwork = (BayesianNetwork) testSessionContext.getAttribute(NodeSessionParams.BN_NETWORK);
List<Pair<Double, String>> probs = bayesianNetwork.getProbabilities(nodeName);
double [] coins = new double[probs.size()];
double incr = 0;
double value;
System.out.println("assign priors for the game");
for(int i = 0; i < probs.size(); i++ ){
value = probs.get(i).fst ;
coins[i] = value + incr;
incr += value;
System.out.println("for state" + probs.get(i).snd + " assign the coin value " + value);
}
res = Math.random();
final String observedState = probs.get(findStateIndexForVal(res, coins)).snd;
return new TestResult() {
public boolean isSuccess() {
return true;
}
public String getName() {
return "Random Result";
}
public String getObserverState() {
return observedState;
}
public String getRawData(){
return "{" +
"\"observedState\" : \"" + observedState + "\" ," +
"\"randomValue\" : " +res +
"}";
}
} ;
}
|
diff --git a/rms/org.eclipse.ptp.rm.mpi.openmpi.core/src/org/eclipse/ptp/rm/mpi/openmpi/core/rtsystem/OpenMPIRuntimeSystemJob.java b/rms/org.eclipse.ptp.rm.mpi.openmpi.core/src/org/eclipse/ptp/rm/mpi/openmpi/core/rtsystem/OpenMPIRuntimeSystemJob.java
index 29bd06447..7c29e0786 100644
--- a/rms/org.eclipse.ptp.rm.mpi.openmpi.core/src/org/eclipse/ptp/rm/mpi/openmpi/core/rtsystem/OpenMPIRuntimeSystemJob.java
+++ b/rms/org.eclipse.ptp.rm.mpi.openmpi.core/src/org/eclipse/ptp/rm/mpi/openmpi/core/rtsystem/OpenMPIRuntimeSystemJob.java
@@ -1,545 +1,552 @@
/*******************************************************************************
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.ptp.rm.mpi.openmpi.core.rtsystem;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.osgi.util.NLS;
import org.eclipse.ptp.core.PTPCorePlugin;
import org.eclipse.ptp.core.attributes.AttributeManager;
import org.eclipse.ptp.core.attributes.IAttribute;
import org.eclipse.ptp.core.attributes.IllegalValueException;
import org.eclipse.ptp.core.elementcontrols.IPNodeControl;
import org.eclipse.ptp.core.elementcontrols.IPProcessControl;
import org.eclipse.ptp.core.elements.IPJob;
import org.eclipse.ptp.core.elements.IPMachine;
import org.eclipse.ptp.core.elements.IPNode;
import org.eclipse.ptp.core.elements.IPProcess;
import org.eclipse.ptp.core.elements.IPQueue;
import org.eclipse.ptp.core.elements.IResourceManager;
import org.eclipse.ptp.core.elements.attributes.ElementAttributes;
import org.eclipse.ptp.core.elements.attributes.JobAttributes;
import org.eclipse.ptp.core.elements.attributes.ProcessAttributes;
import org.eclipse.ptp.core.elements.attributes.ProcessAttributes.State;
import org.eclipse.ptp.rm.core.ToolsRMPlugin;
import org.eclipse.ptp.rm.core.rtsystem.AbstractToolRuntimeSystem;
import org.eclipse.ptp.rm.core.rtsystem.AbstractToolRuntimeSystemJob;
import org.eclipse.ptp.rm.core.utils.DebugUtil;
import org.eclipse.ptp.rm.core.utils.InputStreamListenerToOutputStream;
import org.eclipse.ptp.rm.core.utils.InputStreamObserver;
import org.eclipse.ptp.rm.mpi.openmpi.core.OpenMPILaunchAttributes;
import org.eclipse.ptp.rm.mpi.openmpi.core.OpenMPIPlugin;
import org.eclipse.ptp.rm.mpi.openmpi.core.messages.Messages;
import org.eclipse.ptp.rm.mpi.openmpi.core.rmsystem.OpenMPIResourceManagerConfiguration;
import org.eclipse.ptp.rm.mpi.openmpi.core.rtsystem.OpenMPIProcessMap.Process;
import org.eclipse.ptp.rm.mpi.openmpi.core.rtsystem.OpenMPIProcessMapXml13Parser.IOpenMpiProcessMapXml13ParserListener;
/**
*
* @author Daniel Felix Ferber
*
*/
public class OpenMPIRuntimeSystemJob extends AbstractToolRuntimeSystemJob {
public Object lock1 = new Object();
private InputStreamObserver stderrObserver;
private InputStreamObserver stdoutObserver;
/** Information parsed from launch command. */
OpenMPIProcessMap map;
/**
* Process IDs created by this job. The first process (zero index) is special,
* because it is always created.
*/
String processIDs[];
/** Exception raised while parsing mpi map information. */
IOException parserException = null;
public OpenMPIRuntimeSystemJob(String jobID, String queueID, String name, AbstractToolRuntimeSystem rtSystem, AttributeManager attrMgr) {
super(jobID, queueID, name, rtSystem, attrMgr);
}
@Override
protected void doExecutionStarted(IProgressMonitor monitor) throws CoreException {
/*
* Create a zero index job.
*/
final OpenMPIRuntimeSystem rtSystem = (OpenMPIRuntimeSystem) getRtSystem();
final IPJob ipJob = PTPCorePlugin.getDefault().getUniverse().getResourceManager(rtSystem.getRmID()).getQueueById(getQueueID()).getJobById(getJobID());
final String zeroIndexProcessID = rtSystem.createProcess(getJobID(), Messages.OpenMPIRuntimeSystemJob_ProcessName, 0);
processIDs = new String[] { zeroIndexProcessID } ;
/*
* Listener that saves stdout.
*/
final PipedOutputStream stdoutOutputStream = new PipedOutputStream();
final PipedInputStream stdoutInputStream = new PipedInputStream();
try {
stdoutInputStream.connect(stdoutOutputStream);
} catch (IOException e) {
assert false; // This exception is not possible
}
final InputStreamListenerToOutputStream stdoutPipedStreamListener = new InputStreamListenerToOutputStream(stdoutOutputStream);
Thread stdoutThread = new Thread() {
@Override
public void run() {
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: stdout thread: started", getJobID()); //$NON-NLS-1$
BufferedReader stdoutBufferedReader = new BufferedReader(new InputStreamReader(stdoutInputStream));
IPProcess ipProc = ipJob.getProcessById(zeroIndexProcessID);
try {
String line = stdoutBufferedReader.readLine();
while (line != null) {
synchronized (lock1) {
ipProc.addAttribute(ProcessAttributes.getStdoutAttributeDefinition().create(line));
DebugUtil.trace(DebugUtil.RTS_JOB_OUTPUT_TRACING, "RTS job #{0}:> {1}", getJobID(), line); //$NON-NLS-1$
}
line = stdoutBufferedReader.readLine();
}
} catch (IOException e) {
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: stdout thread: {0}", e); //$NON-NLS-1$
OpenMPIPlugin.log(e);
} finally {
stdoutPipedStreamListener.disable();
}
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: stdout thread: finished", getJobID()); //$NON-NLS-1$
}
};
/*
* Listener that saves stderr.
*/
final PipedOutputStream stderrOutputStream = new PipedOutputStream();
final PipedInputStream stderrInputStream = new PipedInputStream();
try {
stderrInputStream.connect(stderrOutputStream);
} catch (IOException e) {
assert false; // This exception is not possible
}
final InputStreamListenerToOutputStream stderrPipedStreamListener = new InputStreamListenerToOutputStream(stderrOutputStream);
Thread stderrThread = new Thread() {
@Override
public void run() {
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: stderr thread: started", getJobID()); //$NON-NLS-1$
final BufferedReader stderrBufferedReader = new BufferedReader(new InputStreamReader(stderrInputStream));
IPProcess ipProc = ipJob.getProcessById(zeroIndexProcessID);
try {
String line = stderrBufferedReader.readLine();
while (line != null) {
synchronized (lock1) {
ipProc.addAttribute(ProcessAttributes.getStderrAttributeDefinition().create(line));
ipProc.addAttribute(ProcessAttributes.getStdoutAttributeDefinition().create(line));
DebugUtil.error(DebugUtil.RTS_JOB_OUTPUT_TRACING, "RTS job #{0}:> {1}", getJobID(), line); //$NON-NLS-1$
}
line = stderrBufferedReader.readLine();
}
} catch (IOException e) {
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: stderr thread: {0}", e); //$NON-NLS-1$
OpenMPIPlugin.log(e);
} finally {
stderrPipedStreamListener.disable();
}
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: stderr thread: finished", getJobID()); //$NON-NLS-1$
}
};
/*
* Thread that parses map information.
*/
final PipedOutputStream parserOutputStream = new PipedOutputStream();
final PipedInputStream parserInputStream = new PipedInputStream();
try {
parserInputStream.connect(parserOutputStream);
} catch (IOException e) {
assert false; // This exception is not possible
}
final InputStreamListenerToOutputStream parserPipedStreamListener = new InputStreamListenerToOutputStream(parserOutputStream);
Thread parserThread = new Thread() {
@Override
public void run() {
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: display-map parser thread: started", getJobID()); //$NON-NLS-1$
OpenMPIResourceManagerConfiguration configuration = (OpenMPIResourceManagerConfiguration) getRtSystem().getRmConfiguration();
try {
// Parse stdout or stderr, depending on mpi 1.2 or 1.3
if (configuration.getVersionId().equals(OpenMPIResourceManagerConfiguration.VERSION_12)) {
map = OpenMPIProcessMapText12Parser.parse(parserInputStream);
} else if (configuration.getVersionId().equals(OpenMPIResourceManagerConfiguration.VERSION_13)) {
map = OpenMPIProcessMapXml13Parser.parse(parserInputStream, new IOpenMpiProcessMapXml13ParserListener() {
public void startDocument() {
// Empty
}
public void endDocument() {
/*
* Turn off listener that generates input for parser when parsing finishes.
* If not done, the parser will close the piped inputstream, making the listener
* get IOExceptions for closed stream.
*/
parserPipedStreamListener.disable();
if (getStdoutObserver() != null) {
getStdoutObserver().removeListener(parserPipedStreamListener);
}
}
});
} else {
assert false;
}
} catch (IOException e) {
/*
* If output could not be parsed, the kill the mpi process.
*/
parserException = e;
// process.destroy();
DebugUtil.error(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: display-map parser thread: {0}", e); //$NON-NLS-1$
} finally {
if (configuration.getVersionId().equals(OpenMPIResourceManagerConfiguration.VERSION_12)) {
parserPipedStreamListener.disable();
if (getStderrObserver() != null) {
getStderrObserver().removeListener(parserPipedStreamListener);
}
}
}
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: display-map parser thread: finished", getJobID()); //$NON-NLS-1$
}
};
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: starting all threads", getJobID()); //$NON-NLS-1$
/*
* Create and start listeners.
*/
stdoutThread.start();
stderrThread.start();
parserThread.start();
setStderrObserver(new InputStreamObserver(process.getErrorStream()));
getStderrObserver().addListener(stderrPipedStreamListener);
setStdoutObserver(new InputStreamObserver(process.getInputStream()));
getStdoutObserver().addListener(stdoutPipedStreamListener);
// Parse stdout or stderr, depending on mpi 1.2 or 1.3
OpenMPIResourceManagerConfiguration configuration = (OpenMPIResourceManagerConfiguration) getRtSystem().getRmConfiguration();
if (configuration.getVersionId().equals(OpenMPIResourceManagerConfiguration.VERSION_12)) {
- getStderrObserver().addListener(parserPipedStreamListener);
+ /*
+ * Fix for bug #271810
+ */
+ if (!rtSystem.getRemoteServices().getId().equals("org.eclipse.ptp.remote.RSERemoteServices")) { //$NON-NLS-1$
+ stderrObserver.addListener(parserPipedStreamListener);
+ } else {
+ stdoutObserver.addListener(parserPipedStreamListener);
+ }
} else if (configuration.getVersionId().equals(OpenMPIResourceManagerConfiguration.VERSION_13)) {
getStdoutObserver().addListener(parserPipedStreamListener);
} else {
assert false;
}
getStderrObserver().start();
getStdoutObserver().start();
try {
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: waiting for display-map parser thread to finish", getJobID()); //$NON-NLS-1$
parserThread.join();
} catch (InterruptedException e) {
// Do nothing.
}
if (parserException != null) {
/*
* If process completed with error, then it display map parsing failed because of the error message.
* If process did not complete, the destroy it.
*/
boolean parseError = true;
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: destroy process due error while parsing display map", getJobID()); //$NON-NLS-1$
/*
* Wait until both stdout and stderr stop because stream are closed.
* Error messages may be still queued in the stream.
*/
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: waiting stderr thread to finish", getJobID()); //$NON-NLS-1$
try {
getStderrObserver().join();
} catch (InterruptedException e1) {
// Ignore
}
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: waiting stdout thread to finish", getJobID()); //$NON-NLS-1$
try {
getStdoutObserver().join();
} catch (InterruptedException e1) {
// Ignore
}
if (parseError) {
throw OpenMPIPlugin.coreErrorException("Failed to parse output of Open MPI command. Check output for errors.", parserException); //$NON-NLS-1$
}
throw OpenMPIPlugin.coreErrorException("Open MPI failed to launch parallel application. Check output for errors."); //$NON-NLS-1$
}
/*
* Copy job attributes from map.
*/
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: updating model with display-map information", getJobID()); //$NON-NLS-1$
rtSystem.changeJob(getJobID(), map.getAttributeManager());
/*
* Copy process attributes from map.
*/
List<Process> newProcesses = map.getProcesses();
processIDs = new String[newProcesses.size()];
IPMachine ipMachine = PTPCorePlugin.getDefault().getUniverse().getResourceManager(rtSystem.getRmID()).getMachineById(rtSystem.getMachineID());
for (Process newProcess : newProcesses) {
String nodename = newProcess.getNode().getResolvedName();
String nodeID = rtSystem.getNodeIDforName(nodename);
if (nodeID == null) {
process.destroy();
throw new CoreException(new Status(IStatus.ERROR, ToolsRMPlugin.getDefault().getBundle().getSymbolicName(), Messages.OpenMPIRuntimeSystemJob_Exception_HostnamesDoNotMatch, parserException));
}
String processName = newProcess.getName();
int processIndex = newProcess.getIndex();
String processID = null;
if (processIndex == 0) {
processID = zeroIndexProcessID;
} else {
processID = rtSystem.createProcess(getJobID(), processName, processIndex);
}
processIDs[processIndex] = processID;
AttributeManager attrMgr = new AttributeManager();
attrMgr.addAttribute(ElementAttributes.getNameAttributeDefinition().create(processName));
attrMgr.addAttribute(ProcessAttributes.getNodeIdAttributeDefinition().create(nodeID));
attrMgr.addAttribute(ProcessAttributes.getStateAttributeDefinition().create(ProcessAttributes.State.RUNNING));
try {
attrMgr.addAttribute(ProcessAttributes.getIndexAttributeDefinition().create(new Integer(newProcess.getIndex())));
} catch (IllegalValueException e) {
// Is always valid.
assert false;
}
attrMgr.addAttributes(newProcess.getAttributeManager().getAttributes());
rtSystem.changeProcess(processID, attrMgr);
IPProcessControl processControl = (IPProcessControl) ipJob.getProcessById(processID);
IPNode node = ipMachine.getNodeById(nodeID);
/*
* Although one could call processControl.addNode(node) to assign the process to the node, this does not work.
* It is necessary to call nodeControl.addProcesses(processControl) instead.
*/
IPNodeControl nodeControl = (IPNodeControl) node;
nodeControl.addProcesses(Arrays.asList(new IPProcessControl[] {processControl} ));
}
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: finished updating model", getJobID()); //$NON-NLS-1$
}
@Override
protected void doWaitExecution(IProgressMonitor monitor) throws CoreException {
/*
* Wait until both stdout and stderr stop because stream are closed.
* This means that the process has finished.
*/
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: waiting stderr thread to finish", getJobID()); //$NON-NLS-1$
try {
getStderrObserver().join();
} catch (InterruptedException e1) {
// Ignore
}
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: waiting stdout thread to finish", getJobID()); //$NON-NLS-1$
try {
getStdoutObserver().join();
} catch (InterruptedException e1) {
// Ignore
}
/*
* Still experience has shown that remote process might not have yet terminated, although stdout and stderr is closed.
*/
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: waiting mpi process to finish completely", getJobID()); //$NON-NLS-1$
try {
process.waitFor();
} catch (InterruptedException e) {
// Ignore
}
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: completely finished", getJobID()); //$NON-NLS-1$
}
@Override
protected void doTerminateJob() {
// Empty implementation.
}
@Override
protected JobAttributes.State doExecutionFinished(IProgressMonitor monitor) throws CoreException {
changeAllProcessesStatus(ProcessAttributes.State.EXITED);
if (process.exitValue() != 0) {
if (!terminateJobFlag) {
if ((process.exitValue() & 0177) == 0) {
int exit_code = (process.exitValue()>>8) & 0xff;
changeJobStatusMessage(NLS.bind(Messages.OpenMPIRuntimeSystemJob_Exception_ExecutionFailedWithExitValue, new Integer(exit_code)));
} else {
int signal = process.exitValue() & 0177;
changeJobStatusMessage(NLS.bind(Messages.OpenMPIRuntimeSystemJob_Exception_ExecutionFailedWithSignal, new Integer(signal)));
}
return JobAttributes.State.ERROR;
}
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING, "RTS job #{0}: ignoring exit value {1} because job was forced to terminate by user", getJobID(), new Integer(process.exitValue())); //$NON-NLS-1$
}
return JobAttributes.State.TERMINATED;
}
/**
* Change the state of all processes in a job.
*
* @param newState
*/
private void changeAllProcessesStatus(State newState) {
final OpenMPIRuntimeSystem rtSystem = (OpenMPIRuntimeSystem) getRtSystem();
final IResourceManager rm = PTPCorePlugin.getDefault().getUniverse().getResourceManager(rtSystem.getRmID());
if (rm != null) {
final IPQueue queue = rm.getQueueById(getQueueID());
if (queue != null) {
final IPJob ipJob = queue.getJobById(getJobID());
if (ipJob != null) {
/*
* Mark all running and starting processes as finished.
*/
List<String> ids = new ArrayList<String>();
for (IPProcess ipProcess : ipJob.getProcesses()) {
switch (ipProcess.getState()) {
case EXITED:
case ERROR:
case EXITED_SIGNALLED:
break;
case RUNNING:
case STARTING:
case SUSPENDED:
case UNKNOWN:
ids.add(ipProcess.getID());
break;
}
}
AttributeManager attrMrg = new AttributeManager();
attrMrg.addAttribute(ProcessAttributes.getStateAttributeDefinition().create(newState));
for (String processId : ids) {
rtSystem.changeProcess(processId, attrMrg);
}
}
}
}
}
@Override
protected void doExecutionCleanUp(IProgressMonitor monitor) {
if (process != null) {
process.destroy();
process = null;
}
if (getStderrObserver() != null) {
getStderrObserver().kill();
setStderrObserver(null);
}
if (getStdoutObserver() != null) {
getStdoutObserver().kill();
setStdoutObserver(null);
}
// TODO: more cleanup?
changeAllProcessesStatus(ProcessAttributes.State.EXITED);
}
@Override
protected void doBeforeExecution(IProgressMonitor monitor) throws CoreException {
// Nothing to do
}
@Override
protected IAttribute<?, ?, ?>[] doRetrieveToolBaseSubstitutionAttributes() throws CoreException {
// TODO make macros available for environment variables and work directory.
return null;
}
@Override
protected IAttribute<?, ?, ?>[] doRetrieveToolCommandSubstitutionAttributes(
AttributeManager baseSubstitutionAttributeManager,
String directory, Map<String, String> environment) {
List<IAttribute<?, ?, ?>> newAttributes = new ArrayList<IAttribute<?,?,?>>();
/*
* An OpenMPI specific attribute.
* Attribute that contains a list of names of environment variables.
*/
int p = 0;
String keys[] = new String[environment.size()];
for (String key : environment.keySet()) {
keys[p++] = key;
}
newAttributes.add(OpenMPILaunchAttributes.getEnvironmentKeysAttributeDefinition().create(keys));
/*
* An OpenMPI specific attribute.
* A shortcut that generates arguments for the OpenMPI run command.
*/
newAttributes.add(OpenMPILaunchAttributes.getEnvironmentArgsAttributeDefinition().create());
return newAttributes.toArray(new IAttribute<?, ?, ?>[newAttributes.size()]);
}
@Override
protected HashMap<String, String> doRetrieveToolEnvironment()
throws CoreException {
// No extra environment variables needs to be set for OpenMPI.
return null;
}
@Override
protected void doPrepareExecution(IProgressMonitor monitor) throws CoreException {
// Nothing to do
}
/**
* @return the stderrObserver
*/
protected InputStreamObserver getStderrObserver() {
return stderrObserver;
}
/**
* @param stderrObserver the stderrObserver to set
*/
protected void setStderrObserver(InputStreamObserver stderrObserver) {
this.stderrObserver = stderrObserver;
}
/**
* @return the stdoutObserver
*/
protected InputStreamObserver getStdoutObserver() {
return stdoutObserver;
}
/**
* @param stdoutObserver the stdoutObserver to set
*/
protected void setStdoutObserver(InputStreamObserver stdoutObserver) {
this.stdoutObserver = stdoutObserver;
}
}
| true | true | protected void doExecutionStarted(IProgressMonitor monitor) throws CoreException {
/*
* Create a zero index job.
*/
final OpenMPIRuntimeSystem rtSystem = (OpenMPIRuntimeSystem) getRtSystem();
final IPJob ipJob = PTPCorePlugin.getDefault().getUniverse().getResourceManager(rtSystem.getRmID()).getQueueById(getQueueID()).getJobById(getJobID());
final String zeroIndexProcessID = rtSystem.createProcess(getJobID(), Messages.OpenMPIRuntimeSystemJob_ProcessName, 0);
processIDs = new String[] { zeroIndexProcessID } ;
/*
* Listener that saves stdout.
*/
final PipedOutputStream stdoutOutputStream = new PipedOutputStream();
final PipedInputStream stdoutInputStream = new PipedInputStream();
try {
stdoutInputStream.connect(stdoutOutputStream);
} catch (IOException e) {
assert false; // This exception is not possible
}
final InputStreamListenerToOutputStream stdoutPipedStreamListener = new InputStreamListenerToOutputStream(stdoutOutputStream);
Thread stdoutThread = new Thread() {
@Override
public void run() {
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: stdout thread: started", getJobID()); //$NON-NLS-1$
BufferedReader stdoutBufferedReader = new BufferedReader(new InputStreamReader(stdoutInputStream));
IPProcess ipProc = ipJob.getProcessById(zeroIndexProcessID);
try {
String line = stdoutBufferedReader.readLine();
while (line != null) {
synchronized (lock1) {
ipProc.addAttribute(ProcessAttributes.getStdoutAttributeDefinition().create(line));
DebugUtil.trace(DebugUtil.RTS_JOB_OUTPUT_TRACING, "RTS job #{0}:> {1}", getJobID(), line); //$NON-NLS-1$
}
line = stdoutBufferedReader.readLine();
}
} catch (IOException e) {
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: stdout thread: {0}", e); //$NON-NLS-1$
OpenMPIPlugin.log(e);
} finally {
stdoutPipedStreamListener.disable();
}
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: stdout thread: finished", getJobID()); //$NON-NLS-1$
}
};
/*
* Listener that saves stderr.
*/
final PipedOutputStream stderrOutputStream = new PipedOutputStream();
final PipedInputStream stderrInputStream = new PipedInputStream();
try {
stderrInputStream.connect(stderrOutputStream);
} catch (IOException e) {
assert false; // This exception is not possible
}
final InputStreamListenerToOutputStream stderrPipedStreamListener = new InputStreamListenerToOutputStream(stderrOutputStream);
Thread stderrThread = new Thread() {
@Override
public void run() {
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: stderr thread: started", getJobID()); //$NON-NLS-1$
final BufferedReader stderrBufferedReader = new BufferedReader(new InputStreamReader(stderrInputStream));
IPProcess ipProc = ipJob.getProcessById(zeroIndexProcessID);
try {
String line = stderrBufferedReader.readLine();
while (line != null) {
synchronized (lock1) {
ipProc.addAttribute(ProcessAttributes.getStderrAttributeDefinition().create(line));
ipProc.addAttribute(ProcessAttributes.getStdoutAttributeDefinition().create(line));
DebugUtil.error(DebugUtil.RTS_JOB_OUTPUT_TRACING, "RTS job #{0}:> {1}", getJobID(), line); //$NON-NLS-1$
}
line = stderrBufferedReader.readLine();
}
} catch (IOException e) {
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: stderr thread: {0}", e); //$NON-NLS-1$
OpenMPIPlugin.log(e);
} finally {
stderrPipedStreamListener.disable();
}
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: stderr thread: finished", getJobID()); //$NON-NLS-1$
}
};
/*
* Thread that parses map information.
*/
final PipedOutputStream parserOutputStream = new PipedOutputStream();
final PipedInputStream parserInputStream = new PipedInputStream();
try {
parserInputStream.connect(parserOutputStream);
} catch (IOException e) {
assert false; // This exception is not possible
}
final InputStreamListenerToOutputStream parserPipedStreamListener = new InputStreamListenerToOutputStream(parserOutputStream);
Thread parserThread = new Thread() {
@Override
public void run() {
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: display-map parser thread: started", getJobID()); //$NON-NLS-1$
OpenMPIResourceManagerConfiguration configuration = (OpenMPIResourceManagerConfiguration) getRtSystem().getRmConfiguration();
try {
// Parse stdout or stderr, depending on mpi 1.2 or 1.3
if (configuration.getVersionId().equals(OpenMPIResourceManagerConfiguration.VERSION_12)) {
map = OpenMPIProcessMapText12Parser.parse(parserInputStream);
} else if (configuration.getVersionId().equals(OpenMPIResourceManagerConfiguration.VERSION_13)) {
map = OpenMPIProcessMapXml13Parser.parse(parserInputStream, new IOpenMpiProcessMapXml13ParserListener() {
public void startDocument() {
// Empty
}
public void endDocument() {
/*
* Turn off listener that generates input for parser when parsing finishes.
* If not done, the parser will close the piped inputstream, making the listener
* get IOExceptions for closed stream.
*/
parserPipedStreamListener.disable();
if (getStdoutObserver() != null) {
getStdoutObserver().removeListener(parserPipedStreamListener);
}
}
});
} else {
assert false;
}
} catch (IOException e) {
/*
* If output could not be parsed, the kill the mpi process.
*/
parserException = e;
// process.destroy();
DebugUtil.error(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: display-map parser thread: {0}", e); //$NON-NLS-1$
} finally {
if (configuration.getVersionId().equals(OpenMPIResourceManagerConfiguration.VERSION_12)) {
parserPipedStreamListener.disable();
if (getStderrObserver() != null) {
getStderrObserver().removeListener(parserPipedStreamListener);
}
}
}
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: display-map parser thread: finished", getJobID()); //$NON-NLS-1$
}
};
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: starting all threads", getJobID()); //$NON-NLS-1$
/*
* Create and start listeners.
*/
stdoutThread.start();
stderrThread.start();
parserThread.start();
setStderrObserver(new InputStreamObserver(process.getErrorStream()));
getStderrObserver().addListener(stderrPipedStreamListener);
setStdoutObserver(new InputStreamObserver(process.getInputStream()));
getStdoutObserver().addListener(stdoutPipedStreamListener);
// Parse stdout or stderr, depending on mpi 1.2 or 1.3
OpenMPIResourceManagerConfiguration configuration = (OpenMPIResourceManagerConfiguration) getRtSystem().getRmConfiguration();
if (configuration.getVersionId().equals(OpenMPIResourceManagerConfiguration.VERSION_12)) {
getStderrObserver().addListener(parserPipedStreamListener);
} else if (configuration.getVersionId().equals(OpenMPIResourceManagerConfiguration.VERSION_13)) {
getStdoutObserver().addListener(parserPipedStreamListener);
} else {
assert false;
}
getStderrObserver().start();
getStdoutObserver().start();
try {
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: waiting for display-map parser thread to finish", getJobID()); //$NON-NLS-1$
parserThread.join();
} catch (InterruptedException e) {
// Do nothing.
}
if (parserException != null) {
/*
* If process completed with error, then it display map parsing failed because of the error message.
* If process did not complete, the destroy it.
*/
boolean parseError = true;
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: destroy process due error while parsing display map", getJobID()); //$NON-NLS-1$
/*
* Wait until both stdout and stderr stop because stream are closed.
* Error messages may be still queued in the stream.
*/
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: waiting stderr thread to finish", getJobID()); //$NON-NLS-1$
try {
getStderrObserver().join();
} catch (InterruptedException e1) {
// Ignore
}
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: waiting stdout thread to finish", getJobID()); //$NON-NLS-1$
try {
getStdoutObserver().join();
} catch (InterruptedException e1) {
// Ignore
}
if (parseError) {
throw OpenMPIPlugin.coreErrorException("Failed to parse output of Open MPI command. Check output for errors.", parserException); //$NON-NLS-1$
}
throw OpenMPIPlugin.coreErrorException("Open MPI failed to launch parallel application. Check output for errors."); //$NON-NLS-1$
}
/*
* Copy job attributes from map.
*/
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: updating model with display-map information", getJobID()); //$NON-NLS-1$
rtSystem.changeJob(getJobID(), map.getAttributeManager());
/*
* Copy process attributes from map.
*/
List<Process> newProcesses = map.getProcesses();
processIDs = new String[newProcesses.size()];
IPMachine ipMachine = PTPCorePlugin.getDefault().getUniverse().getResourceManager(rtSystem.getRmID()).getMachineById(rtSystem.getMachineID());
for (Process newProcess : newProcesses) {
String nodename = newProcess.getNode().getResolvedName();
String nodeID = rtSystem.getNodeIDforName(nodename);
if (nodeID == null) {
process.destroy();
throw new CoreException(new Status(IStatus.ERROR, ToolsRMPlugin.getDefault().getBundle().getSymbolicName(), Messages.OpenMPIRuntimeSystemJob_Exception_HostnamesDoNotMatch, parserException));
}
String processName = newProcess.getName();
int processIndex = newProcess.getIndex();
String processID = null;
if (processIndex == 0) {
processID = zeroIndexProcessID;
} else {
processID = rtSystem.createProcess(getJobID(), processName, processIndex);
}
processIDs[processIndex] = processID;
AttributeManager attrMgr = new AttributeManager();
attrMgr.addAttribute(ElementAttributes.getNameAttributeDefinition().create(processName));
attrMgr.addAttribute(ProcessAttributes.getNodeIdAttributeDefinition().create(nodeID));
attrMgr.addAttribute(ProcessAttributes.getStateAttributeDefinition().create(ProcessAttributes.State.RUNNING));
try {
attrMgr.addAttribute(ProcessAttributes.getIndexAttributeDefinition().create(new Integer(newProcess.getIndex())));
} catch (IllegalValueException e) {
// Is always valid.
assert false;
}
attrMgr.addAttributes(newProcess.getAttributeManager().getAttributes());
rtSystem.changeProcess(processID, attrMgr);
IPProcessControl processControl = (IPProcessControl) ipJob.getProcessById(processID);
IPNode node = ipMachine.getNodeById(nodeID);
/*
* Although one could call processControl.addNode(node) to assign the process to the node, this does not work.
* It is necessary to call nodeControl.addProcesses(processControl) instead.
*/
IPNodeControl nodeControl = (IPNodeControl) node;
nodeControl.addProcesses(Arrays.asList(new IPProcessControl[] {processControl} ));
}
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: finished updating model", getJobID()); //$NON-NLS-1$
}
| protected void doExecutionStarted(IProgressMonitor monitor) throws CoreException {
/*
* Create a zero index job.
*/
final OpenMPIRuntimeSystem rtSystem = (OpenMPIRuntimeSystem) getRtSystem();
final IPJob ipJob = PTPCorePlugin.getDefault().getUniverse().getResourceManager(rtSystem.getRmID()).getQueueById(getQueueID()).getJobById(getJobID());
final String zeroIndexProcessID = rtSystem.createProcess(getJobID(), Messages.OpenMPIRuntimeSystemJob_ProcessName, 0);
processIDs = new String[] { zeroIndexProcessID } ;
/*
* Listener that saves stdout.
*/
final PipedOutputStream stdoutOutputStream = new PipedOutputStream();
final PipedInputStream stdoutInputStream = new PipedInputStream();
try {
stdoutInputStream.connect(stdoutOutputStream);
} catch (IOException e) {
assert false; // This exception is not possible
}
final InputStreamListenerToOutputStream stdoutPipedStreamListener = new InputStreamListenerToOutputStream(stdoutOutputStream);
Thread stdoutThread = new Thread() {
@Override
public void run() {
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: stdout thread: started", getJobID()); //$NON-NLS-1$
BufferedReader stdoutBufferedReader = new BufferedReader(new InputStreamReader(stdoutInputStream));
IPProcess ipProc = ipJob.getProcessById(zeroIndexProcessID);
try {
String line = stdoutBufferedReader.readLine();
while (line != null) {
synchronized (lock1) {
ipProc.addAttribute(ProcessAttributes.getStdoutAttributeDefinition().create(line));
DebugUtil.trace(DebugUtil.RTS_JOB_OUTPUT_TRACING, "RTS job #{0}:> {1}", getJobID(), line); //$NON-NLS-1$
}
line = stdoutBufferedReader.readLine();
}
} catch (IOException e) {
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: stdout thread: {0}", e); //$NON-NLS-1$
OpenMPIPlugin.log(e);
} finally {
stdoutPipedStreamListener.disable();
}
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: stdout thread: finished", getJobID()); //$NON-NLS-1$
}
};
/*
* Listener that saves stderr.
*/
final PipedOutputStream stderrOutputStream = new PipedOutputStream();
final PipedInputStream stderrInputStream = new PipedInputStream();
try {
stderrInputStream.connect(stderrOutputStream);
} catch (IOException e) {
assert false; // This exception is not possible
}
final InputStreamListenerToOutputStream stderrPipedStreamListener = new InputStreamListenerToOutputStream(stderrOutputStream);
Thread stderrThread = new Thread() {
@Override
public void run() {
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: stderr thread: started", getJobID()); //$NON-NLS-1$
final BufferedReader stderrBufferedReader = new BufferedReader(new InputStreamReader(stderrInputStream));
IPProcess ipProc = ipJob.getProcessById(zeroIndexProcessID);
try {
String line = stderrBufferedReader.readLine();
while (line != null) {
synchronized (lock1) {
ipProc.addAttribute(ProcessAttributes.getStderrAttributeDefinition().create(line));
ipProc.addAttribute(ProcessAttributes.getStdoutAttributeDefinition().create(line));
DebugUtil.error(DebugUtil.RTS_JOB_OUTPUT_TRACING, "RTS job #{0}:> {1}", getJobID(), line); //$NON-NLS-1$
}
line = stderrBufferedReader.readLine();
}
} catch (IOException e) {
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: stderr thread: {0}", e); //$NON-NLS-1$
OpenMPIPlugin.log(e);
} finally {
stderrPipedStreamListener.disable();
}
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: stderr thread: finished", getJobID()); //$NON-NLS-1$
}
};
/*
* Thread that parses map information.
*/
final PipedOutputStream parserOutputStream = new PipedOutputStream();
final PipedInputStream parserInputStream = new PipedInputStream();
try {
parserInputStream.connect(parserOutputStream);
} catch (IOException e) {
assert false; // This exception is not possible
}
final InputStreamListenerToOutputStream parserPipedStreamListener = new InputStreamListenerToOutputStream(parserOutputStream);
Thread parserThread = new Thread() {
@Override
public void run() {
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: display-map parser thread: started", getJobID()); //$NON-NLS-1$
OpenMPIResourceManagerConfiguration configuration = (OpenMPIResourceManagerConfiguration) getRtSystem().getRmConfiguration();
try {
// Parse stdout or stderr, depending on mpi 1.2 or 1.3
if (configuration.getVersionId().equals(OpenMPIResourceManagerConfiguration.VERSION_12)) {
map = OpenMPIProcessMapText12Parser.parse(parserInputStream);
} else if (configuration.getVersionId().equals(OpenMPIResourceManagerConfiguration.VERSION_13)) {
map = OpenMPIProcessMapXml13Parser.parse(parserInputStream, new IOpenMpiProcessMapXml13ParserListener() {
public void startDocument() {
// Empty
}
public void endDocument() {
/*
* Turn off listener that generates input for parser when parsing finishes.
* If not done, the parser will close the piped inputstream, making the listener
* get IOExceptions for closed stream.
*/
parserPipedStreamListener.disable();
if (getStdoutObserver() != null) {
getStdoutObserver().removeListener(parserPipedStreamListener);
}
}
});
} else {
assert false;
}
} catch (IOException e) {
/*
* If output could not be parsed, the kill the mpi process.
*/
parserException = e;
// process.destroy();
DebugUtil.error(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: display-map parser thread: {0}", e); //$NON-NLS-1$
} finally {
if (configuration.getVersionId().equals(OpenMPIResourceManagerConfiguration.VERSION_12)) {
parserPipedStreamListener.disable();
if (getStderrObserver() != null) {
getStderrObserver().removeListener(parserPipedStreamListener);
}
}
}
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: display-map parser thread: finished", getJobID()); //$NON-NLS-1$
}
};
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: starting all threads", getJobID()); //$NON-NLS-1$
/*
* Create and start listeners.
*/
stdoutThread.start();
stderrThread.start();
parserThread.start();
setStderrObserver(new InputStreamObserver(process.getErrorStream()));
getStderrObserver().addListener(stderrPipedStreamListener);
setStdoutObserver(new InputStreamObserver(process.getInputStream()));
getStdoutObserver().addListener(stdoutPipedStreamListener);
// Parse stdout or stderr, depending on mpi 1.2 or 1.3
OpenMPIResourceManagerConfiguration configuration = (OpenMPIResourceManagerConfiguration) getRtSystem().getRmConfiguration();
if (configuration.getVersionId().equals(OpenMPIResourceManagerConfiguration.VERSION_12)) {
/*
* Fix for bug #271810
*/
if (!rtSystem.getRemoteServices().getId().equals("org.eclipse.ptp.remote.RSERemoteServices")) { //$NON-NLS-1$
stderrObserver.addListener(parserPipedStreamListener);
} else {
stdoutObserver.addListener(parserPipedStreamListener);
}
} else if (configuration.getVersionId().equals(OpenMPIResourceManagerConfiguration.VERSION_13)) {
getStdoutObserver().addListener(parserPipedStreamListener);
} else {
assert false;
}
getStderrObserver().start();
getStdoutObserver().start();
try {
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: waiting for display-map parser thread to finish", getJobID()); //$NON-NLS-1$
parserThread.join();
} catch (InterruptedException e) {
// Do nothing.
}
if (parserException != null) {
/*
* If process completed with error, then it display map parsing failed because of the error message.
* If process did not complete, the destroy it.
*/
boolean parseError = true;
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: destroy process due error while parsing display map", getJobID()); //$NON-NLS-1$
/*
* Wait until both stdout and stderr stop because stream are closed.
* Error messages may be still queued in the stream.
*/
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: waiting stderr thread to finish", getJobID()); //$NON-NLS-1$
try {
getStderrObserver().join();
} catch (InterruptedException e1) {
// Ignore
}
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: waiting stdout thread to finish", getJobID()); //$NON-NLS-1$
try {
getStdoutObserver().join();
} catch (InterruptedException e1) {
// Ignore
}
if (parseError) {
throw OpenMPIPlugin.coreErrorException("Failed to parse output of Open MPI command. Check output for errors.", parserException); //$NON-NLS-1$
}
throw OpenMPIPlugin.coreErrorException("Open MPI failed to launch parallel application. Check output for errors."); //$NON-NLS-1$
}
/*
* Copy job attributes from map.
*/
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: updating model with display-map information", getJobID()); //$NON-NLS-1$
rtSystem.changeJob(getJobID(), map.getAttributeManager());
/*
* Copy process attributes from map.
*/
List<Process> newProcesses = map.getProcesses();
processIDs = new String[newProcesses.size()];
IPMachine ipMachine = PTPCorePlugin.getDefault().getUniverse().getResourceManager(rtSystem.getRmID()).getMachineById(rtSystem.getMachineID());
for (Process newProcess : newProcesses) {
String nodename = newProcess.getNode().getResolvedName();
String nodeID = rtSystem.getNodeIDforName(nodename);
if (nodeID == null) {
process.destroy();
throw new CoreException(new Status(IStatus.ERROR, ToolsRMPlugin.getDefault().getBundle().getSymbolicName(), Messages.OpenMPIRuntimeSystemJob_Exception_HostnamesDoNotMatch, parserException));
}
String processName = newProcess.getName();
int processIndex = newProcess.getIndex();
String processID = null;
if (processIndex == 0) {
processID = zeroIndexProcessID;
} else {
processID = rtSystem.createProcess(getJobID(), processName, processIndex);
}
processIDs[processIndex] = processID;
AttributeManager attrMgr = new AttributeManager();
attrMgr.addAttribute(ElementAttributes.getNameAttributeDefinition().create(processName));
attrMgr.addAttribute(ProcessAttributes.getNodeIdAttributeDefinition().create(nodeID));
attrMgr.addAttribute(ProcessAttributes.getStateAttributeDefinition().create(ProcessAttributes.State.RUNNING));
try {
attrMgr.addAttribute(ProcessAttributes.getIndexAttributeDefinition().create(new Integer(newProcess.getIndex())));
} catch (IllegalValueException e) {
// Is always valid.
assert false;
}
attrMgr.addAttributes(newProcess.getAttributeManager().getAttributes());
rtSystem.changeProcess(processID, attrMgr);
IPProcessControl processControl = (IPProcessControl) ipJob.getProcessById(processID);
IPNode node = ipMachine.getNodeById(nodeID);
/*
* Although one could call processControl.addNode(node) to assign the process to the node, this does not work.
* It is necessary to call nodeControl.addProcesses(processControl) instead.
*/
IPNodeControl nodeControl = (IPNodeControl) node;
nodeControl.addProcesses(Arrays.asList(new IPProcessControl[] {processControl} ));
}
DebugUtil.trace(DebugUtil.RTS_JOB_TRACING_MORE, "RTS job #{0}: finished updating model", getJobID()); //$NON-NLS-1$
}
|
diff --git a/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/vdc/VDCServiceBean.java b/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/vdc/VDCServiceBean.java
index c242edf26..7b79f37dd 100644
--- a/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/vdc/VDCServiceBean.java
+++ b/src/DVN-EJB/src/java/edu/harvard/iq/dvn/core/vdc/VDCServiceBean.java
@@ -1,1039 +1,1039 @@
/*
Copyright (C) 2005-2012, by the President and Fellows of Harvard College.
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.
Dataverse Network - A web application to share, preserve and analyze research data.
Developed at the Institute for Quantitative Social Science, Harvard University.
Version 3.0.
*/
/*
* VDCServiceBean.java
*
* Created on September 21, 2006, 1:46 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package edu.harvard.iq.dvn.core.vdc;
import edu.harvard.iq.dvn.core.admin.Role;
import edu.harvard.iq.dvn.core.admin.RoleRequest;
import edu.harvard.iq.dvn.core.admin.RoleServiceLocal;
import edu.harvard.iq.dvn.core.admin.UserServiceLocal;
import edu.harvard.iq.dvn.core.admin.VDCRole;
import edu.harvard.iq.dvn.core.admin.VDCUser;
import edu.harvard.iq.dvn.core.harvest.HarvesterServiceLocal;
import edu.harvard.iq.dvn.core.study.Study;
import edu.harvard.iq.dvn.core.study.StudyField;
import edu.harvard.iq.dvn.core.study.StudyFieldServiceLocal;
import edu.harvard.iq.dvn.core.study.StudyServiceLocal;
import edu.harvard.iq.dvn.core.study.Template;
import edu.harvard.iq.dvn.core.util.DateUtil;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.*;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
/**
*
* @author roberttreacy
*/
@Stateless
public class VDCServiceBean implements VDCServiceLocal {
@EJB
VDCCollectionServiceLocal vdcCollectionService;
@EJB
VDCNetworkServiceLocal vdcNetworkService;
@EJB
StudyFieldServiceLocal studyFieldService;
@EJB
RoleServiceLocal roleService;
@EJB
UserServiceLocal userService;
@EJB
StudyServiceLocal studyService;
@EJB
HarvesterServiceLocal harvesterService;
@EJB
OAISetServiceLocal oaiSetService;
@Resource(name = "jdbc/VDCNetDS")
DataSource dvnDatasource;
@PersistenceContext(unitName = "VDCNet-ejbPU")
private EntityManager em;
private static final Logger logger = Logger.getLogger("edu.harvard.iq.dvn.core.vdc.VDCServiceBean");
/**
* Creates a new instance of VDCServiceBean
*/
public VDCServiceBean() {
}
public void create(VDC vDC) {
em.persist(vDC);
}
public void createScholarDataverse(Long userId, String firstName, String lastName, String name, String affiliation, String alias, String dataverseType) {
List studyFields = studyFieldService.findAll();
createScholarDataverse(userId,firstName, lastName, name, affiliation, alias, dataverseType, studyFields);
}
/** scholar dataverse */
private void createScholarDataverse(Long userId, String firstName, String lastName, String name, String affiliation, String alias, String dataverseType, List studyFields) {
VDC sDV = new VDC();
em.persist(sDV);
sDV.setCreator(em.find(VDCUser.class, userId));
sDV.setName(name);
sDV.setFirstName(firstName);
sDV.setLastName(lastName);
sDV.setAffiliation(affiliation);
sDV.setName(name);
sDV.setAlias(alias);
sDV.setDtype(dataverseType);
sDV.setCreatedDate(DateUtil.getTimestamp());
sDV.getRootCollection().setName(name);
VDCNetwork vdcNetwork = vdcNetworkService.find(new Long(1));
sDV.setDefaultTemplate(vdcNetwork.getDefaultTemplate());
sDV.setHeader(vdcNetwork.getDefaultVDCHeader());
sDV.setFooter(vdcNetwork.getDefaultVDCFooter());
sDV.setRestricted(true);
sDV.setDisplayAnnouncements(false);
ArrayList advancedSearchFields = new ArrayList();
ArrayList searchResultsFields = new ArrayList();
for (Iterator it = studyFields.iterator(); it.hasNext();) {
StudyField elem = (StudyField) it.next();
if (elem.isAdvancedSearchField()) {
advancedSearchFields.add(elem);
}
if (elem.isSearchResultField()) {
searchResultsFields.add(elem);
}
}
sDV.setAdvSearchFields(advancedSearchFields);
sDV.setSearchResultFields(searchResultsFields);
userService.addVdcRole(userId, findByAlias(sDV.getAlias()).getId(), roleService.ADMIN);
}
public VDC findScholarDataverseByAlias(String alias) {
String query = "SELECT sd from VDC sd where sd.alias = :fieldName and sd.dtype = 'Scholar'";
VDC sDV = null;
try {
sDV = (VDC) em.createQuery(query).setParameter("fieldName", alias).getSingleResult();
} catch (javax.persistence.NoResultException e) {
// Do nothing, just return null.
}
return sDV;
}
public VDC findScholarDataverseById(Long id) {
VDC o = (VDC) em.find(VDC.class, id);
return o;
}
/* updateScholarDVs
*
* This is not currently used. It was
* developed for 16a, but there is an
* issue with casting and the java
* persistence layer.
* Leaving it here as a placeholder.
*
*
* @author wbossons
*/
public VDC updateScholarDVs(VDC scholarDV) {
//
String updateString = "update vdc set firstname = '" + scholarDV.getFirstName() + "', lastname='" + scholarDV.getLastName() + "', name='" + scholarDV.getName() + "', alias='" + scholarDV.getAlias() + "', affiliation='" + scholarDV.getAffiliation() + "', dtype = 'Scholar' where id = " + scholarDV.getId();
Connection conn = null;
PreparedStatement updateStatement = null;
try {
conn = dvnDatasource.getConnection();
updateStatement = conn.prepareStatement(updateString);
int rowcount = updateStatement.executeUpdate();
} catch (java.sql.SQLException e) {
// Do nothing, just return null.
}
em.flush();
VDC scholardataverse = em.find(VDC.class, scholarDV.getId());
return scholardataverse;
//
}
/** end scholar dataverse methods */
public void edit(VDC vDC) {
em.merge(vDC);
}
@Remove
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void save(VDC vDC) {
em.merge(vDC);
}
public void destroy(VDC vDC) {
em.merge(vDC);
em.remove(vDC);
}
public VDC find(Object pk) {
VDC vdc = (VDC) em.find(VDC.class, pk);
VDCCollection rootCollection = vdc.getRootCollection();
rootCollection.getId();
Collection<VDCCollection> subcollections = rootCollection.getSubCollections();
traverseCollections(subcollections);
return vdc;
}
private void traverseCollections(Collection<VDCCollection> collections) {
for (Iterator it = collections.iterator(); it.hasNext();) {
VDCCollection elem = (VDCCollection) it.next();
elem.getId();
Collection<VDCCollection> subcollections = elem.getSubCollections();
if (subcollections.size() > 0) {
traverseCollections(subcollections);
}
}
}
public VDC findByAlias(String alias) {
String query = "SELECT v from VDC v where lower(v.alias) = lower(:fieldName)";
VDC vdc = null;
try {
vdc = (VDC) em.createQuery(query).setParameter("fieldName", alias).getSingleResult();
em.refresh(vdc); // Refresh because the cached object doesn't include harvestingDataverse object - need to review why this is happening
} catch (javax.persistence.NoResultException e) {
// Do nothing, just return null.
}
return vdc;
}
public VDC findById(Long id) {
VDC o = (VDC) em.find(VDC.class, id);
return o;
}
public VDC findByName(String name) {
String query = "SELECT v from VDC v where v.name = :fieldName";
VDC vdc = null;
try {
vdc = (VDC) em.createQuery(query).setParameter("fieldName", name).getSingleResult();
} catch (javax.persistence.NoResultException e) {
// Do nothing, just return null.
}
return vdc;
}
// helper method used by findInfo methods
// findInfo methods return an Object[] with needed info rather than the whole VDC
// this is done for primarily for performance reasons
private List<Object[]> convertIntegerToLong(List<Object[]> list, int index) {
for (Object[] item : list) {
item[index] = new Long( (Integer) item[index]);
}
return list;
}
public List findAll() {
return em.createQuery("select object(o) from VDC as o order by o.name").getResultList();
}
public List<Long> findAllIds() {
String queryStr = "select id from VDC order by id";
Query query = em.createNativeQuery(queryStr);
List<Long> returnList = new ArrayList<Long>();
for (Object currentResult : query.getResultList()) {
// convert results into Longs
returnList.add(new Long(((Integer)currentResult).longValue()));
}
return returnList;
}
public List<Object[]> findInfoAll() {
String queryString = "SELECT vdc.id, vdc.name, vdc.affiliation, vdc.restricted from vdc order by name";
Query query = em.createNativeQuery(queryString);
return convertIntegerToLong(query.getResultList(),0);
}
public List<VDC> findAllPublic() {
return em.createQuery("select object(o) from VDC as o where o.restricted=false order by o.name").getResultList();
}
public List<Object[]> findInfoAllPublic() {
String queryString = "SELECT vdc.id, vdc.name from vdc where restricted=false order by name";
Query query = em.createNativeQuery(queryString);
return convertIntegerToLong(query.getResultList(),0);
}
public List findBasic() {
List myList = (List<VDC>) em.createQuery("select object(o) from VDC as o where o.dtype = 'Basic' order by o.name").getResultList();
Iterator iterator = myList.iterator();
return em.createQuery("select object(o) from VDC as o where o.dtype = 'Basic' order by o.name").getResultList();
}
private void create(VDCUser user, String name, String alias, String dtype, List studyFields) {
VDC addedSite = new VDC();
addedSite.setCreator(user);
VDCNetwork vdcNetwork = vdcNetworkService.findRootNetwork();
addedSite.setDefaultTemplate(vdcNetwork.getDefaultTemplate());
em.persist(addedSite);
addedSite.setName(name);
addedSite.setAlias(alias);
addedSite.setDtype(dtype);
addedSite.setCreatedDate(DateUtil.getTimestamp());
addedSite.getRootCollection().setName(name);
addedSite.setDefaultTemplate(vdcNetwork.getDefaultTemplate());
addedSite.setHeader(vdcNetwork.getDefaultVDCHeader());
addedSite.setFooter(vdcNetwork.getDefaultVDCFooter());
addedSite.setRestricted(true);
addedSite.setDisplayAnnouncements(false);
ArrayList advancedSearchFields = new ArrayList();
ArrayList searchResultsFields = new ArrayList();
for (Iterator it = studyFields.iterator(); it.hasNext();) {
StudyField elem = (StudyField) it.next();
if (elem.isAdvancedSearchField()) {
advancedSearchFields.add(elem);
}
if (elem.isSearchResultField()) {
searchResultsFields.add(elem);
}
}
addedSite.setAdvSearchFields(advancedSearchFields);
addedSite.setSearchResultFields(searchResultsFields);
userService.addVdcRole(user.getId(), findByAlias(addedSite.getAlias()).getId(), roleService.ADMIN);
}
public VDC getVDCFromRequest(HttpServletRequest request) {
VDC vdc = (VDC) request.getAttribute("vdc");
if (vdc == null) {
Iterator iter = request.getParameterMap().keySet().iterator();
while (iter.hasNext()) {
Object key = (Object) iter.next();
if (key instanceof String && ((String) key).indexOf("vdcId") != -1) {
try {
Long vdcId = new Long((String) request.getParameter((String) key));
vdc = find(vdcId);
request.setAttribute("vdc", vdc);
} catch (NumberFormatException e) {
} // param is not a Long, ignore it
break;
}
}
}
return vdc;
}
public void create(Long userId, String name, String alias, String dtype) {
List studyFields = studyFieldService.findAll();
VDCUser user = em.find(VDCUser.class, userId);
create(user, name, alias, dtype, studyFields);
}
public void addContributorRequest(Long vdcId, Long userId) {
Role contributor = (Role) roleService.findByName(RoleServiceLocal.CONTRIBUTOR);
VDC vdc = em.find(VDC.class, vdcId);
VDCUser user = em.find(VDCUser.class, userId);
RoleRequest roleRequest = new RoleRequest();
roleRequest.setRole(contributor);
roleRequest.setVdcUser(user);
roleRequest.setVdc(vdc);
vdc.getRoleRequests().add(roleRequest);
}
public List getLinkedCollections(VDC vdc) {
return getLinkedCollections(vdc, false);
}
public List getLinkedCollections(VDC vdc, boolean getHiddenCollections) {
// getHiddenCollections is no longer used
return vdc.getLinkedCollections();
}
public void delete(Long vdcId) {
VDC vdc = em.find(VDC.class, vdcId);
em.refresh(vdc);
List studyIds = new ArrayList();
// Get the studyIds separately, to avoid a ConcurrentAccess Exception
// (This is necessary because the studies are deleted in Native SQL)
for (Iterator it = vdc.getOwnedStudies().iterator(); it.hasNext();) {
Study elem = (Study) it.next();
studyIds.add(elem.getId());
}
if (!studyIds.isEmpty()) {
studyService.deleteStudyList(studyIds);
}
vdc.getOwnedStudies().clear();
vdc.setRootCollection(null);
for (Iterator it = vdc.getOwnedCollections().iterator(); it.hasNext();) {
VDCCollection elem = (VDCCollection) it.next();
elem.setParentCollection(null);
elem.setOwner(null);
// Remove this Collection from all linked VDCs
for (Iterator itc = elem.getLinkedVDCs().iterator(); itc.hasNext();) {
VDC linkedVDC = (VDC) itc.next();
linkedVDC.getLinkedCollections().remove(elem);
}
}
for (Iterator it = vdc.getLinkedCollections().iterator(); it.hasNext();) {
VDCCollection elem = (VDCCollection) it.next();
VDCCollection coll = em.find(VDCCollection.class, elem.getId());
coll.getLinkedVDCs().remove(vdc);
}
for (Iterator it = vdc.getVdcGroups().iterator(); it.hasNext();) {
VDCGroup vdcGroup = (VDCGroup) it.next();
vdcGroup.getVdcs().remove(vdc);
}
for (Iterator it = vdc.getVdcRoles().iterator(); it.hasNext();) {
VDCRole vdcRole = (VDCRole) it.next();
VDCUser vdcUser = vdcRole.getVdcUser();
vdcUser.getVdcRoles().remove(vdcRole);
}
// If the vdc Default Template is in the list of dataverse templates
// (not the Network Default Template), then remove the reference before deleting the dataverse.
// If not removed, you will get a foreign key violation when the persistence logic deletes
// the collection of templates.
if (vdc.getTemplates().contains(vdc.getDefaultTemplate())) {
vdc.setDefaultTemplate(null);
}
if (vdc.getLockssConfig()!=null) {
oaiSetService.remove(vdc.getLockssConfig().getOaiSet().getId());
}
em.remove(vdc);
}
public List findAllNonHarvesting() {
return em.createQuery("select object(o) from VDC as o where o.harvestingDataverse is null order by o.name").getResultList();
}
public List<Object[]> findInfoAllNonHarvesting() {
String queryString = "SELECT vdc.id, vdc.name from vdc where harvestingdataverse_id is null order by name";
Query query = em.createNativeQuery(queryString);
return convertIntegerToLong(query.getResultList(),0);
}
/**
* findVdcsNotInGroups
*
* A method to find vdcs
* that are not associated with
* a vdc group. This is for the network
* level (DVN) where the home page
* display will be a list.
*
*/
public List<VDC> findVdcsNotInGroups() {
String query = "select object(o) FROM VDC as o WHERE o.dtype = 'Scholar' AND o.id NOT IN (SELECT gvdcs.id FROM VDCGroup as groups JOIN groups.vdcs as gvdcs)";
return (List) em.createQuery(query).getResultList();
}
/** An overloaded method to make the transition to
* the scholar dataverses no longer being their own type
*
* @param dtype the dataverse type
* @ author wbossons
*/
public List<VDC> findVdcsNotInGroups(String dtype) {
String query = "select object(o) FROM VDC as o WHERE o.dtype = :fieldName AND o.id NOT IN (SELECT gvdcs.id FROM VDCGroup as groups JOIN groups.vdcs as gvdcs)";
return (List) em.createQuery(query).setParameter("fieldName", dtype).getResultList();
}
public List getUserVDCs(Long userId) {
String query = "select v from VDC v where v.id in (select vr.vdc.id from VDCRole vr where vr.vdcUser.id=" + userId + ")";
return em.createQuery(query).getResultList();
}
public Long getUserContributorOrBetterVDCCount(Long userId) {
String queryString = "select count(*) from VDC v where v.id in (select vr.vdc_id from VDCRole vr where vr.role_id < 4 and vr.vdcUser_id=" + userId + ")";
Query query = em.createNativeQuery(queryString);
return (Long) query.getSingleResult();
}
public void updateDefaultTemplate(Long vdcId, Long templateId) {
VDC vdc = em.find(VDC.class, vdcId);
Template template = em.find(Template.class, templateId);
vdc.setDefaultTemplate(template);
}
public java.util.List<Long> getOwnedStudyIds(Long vdcId) {
String queryStr = "SELECT s.id FROM VDC v JOIN v.ownedStudies s where v.id = " + vdcId;
return em.createQuery(queryStr).getResultList();
}
public Long getOwnedStudyCount(Long vdcId) {
String queryString = "select count(owner_id) from study s where s.owner_id = " + vdcId;
Long longValue = null;
Query query = em.createNativeQuery(queryString);
return (Long) query.getSingleResult();
}
public Long getReleasedStudyCount(Long vdcId) {
String queryString = "select count(owner_id) from study s, studyversion v "
+ " where s.id = v.study_id and v.releasetime is not null and " +
"s.owner_id = " + vdcId;
Long longValue = null;
Query query = em.createNativeQuery(queryString);
return (Long) query.getSingleResult();
}
public List getPagedData(Long vdcGroupId, int firstRow, int totalRows, String orderBy, String order) {
List<VDC> list = new ArrayList();
try {
String queryString = (vdcGroupId != 0) ? "SELECT vdc.id, name, alias, affiliation, releasedate, dvndescription, " +
"CASE WHEN sum(downloadcount) is null THEN 0 ELSE sum(downloadcount) END, " +
"CASE WHEN max(lastupdatetime) is null THEN vdc.releasedate ELSE max(lastupdatetime) END as lastupdated " +
"FROM vdc " +
"LEFT OUTER JOIN study on vdc.id = study.owner_id " +
"LEFT OUTER JOIN studyfileactivity on study.id = studyfileactivity.study_id " +
"WHERE vdc.restricted = false AND vdc.id in (Select vdc_id from vdcgroup_vdcs where vdcgroup_id = " + vdcGroupId +
") " +
"GROUP BY vdc.id, vdc.name, vdc.alias, vdc.affiliation, vdc.releasedate, vdc.dvndescription " +
"ORDER BY LOWER(" + orderBy + ") " + order + " LIMIT " + totalRows + " OFFSET " + firstRow : "SELECT vdc.id, name, alias, affiliation, releasedate, dvndescription, " +
"CASE WHEN sum(downloadcount) is null THEN 0 ELSE sum(downloadcount) END, " +
"CASE WHEN max(lastupdatetime) is null THEN vdc.releasedate ELSE max(lastupdatetime) END as lastupdated " +
"FROM vdc " +
"LEFT OUTER JOIN study on vdc.id = study.owner_id " +
"LEFT OUTER JOIN studyfileactivity on study.id = studyfileactivity.study_id " +
"WHERE vdc.restricted = false " +
"GROUP BY vdc.id, vdc.name, vdc.alias, vdc.affiliation, vdc.releasedate, vdc.dvndescription " +
"ORDER BY LOWER(" + orderBy + ") " + order + " LIMIT " + totalRows + " OFFSET " + firstRow;
// (vdcGroupId != 0) ? "Select count(vdcgroup_id) from vdc_group g where vdcgroup_id = " + vdcGroupId + " and vdc_id in (Select id from vdc where restricted = false" : "select count(id) from vdc v where restricted = false"
Query query = em.createNativeQuery(queryString);
list = (List<VDC>) query.getResultList();
} catch (Exception e) {
//do something here with the exception
list = new ArrayList();
} finally {
return list;
}
}
public List getPagedDataByActivity(Long vdcGroupId, int firstRow, int totalRows, String order) {
List<VDC> list = new ArrayList();
try {
String queryString = (vdcGroupId != 0) ? "SELECT vdc.id, name, alias, affiliation, releasedate, dvndescription, " +
"CASE WHEN sum(downloadcount) is null THEN 0 ELSE sum(downloadcount) END, " +
"CASE WHEN max(lastupdatetime) is null THEN vdc.releasedate ELSE max(lastupdatetime) END as lastupdated " +
"FROM vdc " +
"LEFT OUTER JOIN study on vdc.id = study.owner_id " +
"LEFT OUTER JOIN studyfileactivity on study.id = studyfileactivity.study_id " +
"WHERE vdc.restricted = false " +
"AND vdc.id in (Select vdc_id from vdcgroup_vdcs where vdcgroup_id = " + vdcGroupId + ") " +
"GROUP BY vdc.id, vdc.name, vdc.alias, vdc.affiliation, vdc.releasedate, vdc.dvndescription " +
"ORDER BY " +
"CASE WHEN sum(downloadcount) is null THEN 0 ELSE sum(downloadcount) END " + order +
" LIMIT " + totalRows +
" OFFSET " + firstRow : "SELECT vdc.id, name, alias, affiliation, releasedate, dvndescription, " +
"CASE WHEN sum(downloadcount) is null THEN 0 ELSE sum(downloadcount) END, " +
"CASE WHEN max(lastupdatetime) is null THEN vdc.releasedate ELSE max(lastupdatetime) END as lastupdated " +
"FROM vdc " +
"LEFT OUTER JOIN study on vdc.id = study.owner_id " +
"LEFT OUTER JOIN studyfileactivity on study.id = studyfileactivity.study_id " +
"WHERE vdc.restricted = false " +
"GROUP BY vdc.id, vdc.name, vdc.alias, vdc.affiliation, vdc.releasedate, vdc.dvndescription " +
"ORDER BY " +
"CASE WHEN sum(downloadcount) is null THEN 0 ELSE sum(downloadcount) END " + order +
" LIMIT " + totalRows +
" OFFSET " + firstRow;
Query query = em.createNativeQuery(queryString);
list = (List<VDC>) query.getResultList();
} catch (Exception e) {
//do something here with the exception
list = new ArrayList();
} finally {
return list;
}
}
public List getPagedDataByLastUpdateTime(Long vdcGroupId, int firstRow, int totalRows, String order) {
List<VDC> list = new ArrayList();
try {
String queryString = (vdcGroupId != 0) ? "SELECT vdc.id, name, alias, affiliation, releasedate, dvndescription, " +
"CASE WHEN sum(downloadcount) is null THEN 0 ELSE sum(downloadcount) END, " +
"CASE WHEN max(lastupdatetime) is null THEN vdc.releasedate ELSE max(lastupdatetime) END as lastupdated " +
"FROM vdc " +
"LEFT OUTER JOIN study on vdc.id = study.owner_id " +
"LEFT OUTER JOIN studyfileactivity on study.id = studyfileactivity.study_id " +
"WHERE vdc.restricted = false " +
"AND vdc.id in (Select vdc_id from vdcgroup_vdcs where vdcgroup_id = " + vdcGroupId + ") " +
"GROUP BY vdc.id, vdc.name, vdc.alias, vdc.affiliation, vdc.releasedate, vdc.dvndescription " +
"ORDER BY " +
"CASE WHEN max(lastupdatetime) is null THEN vdc.releasedate ELSE max(lastupdatetime) END " + order +
" LIMIT " + totalRows +
" OFFSET " + firstRow : "SELECT vdc.id, name, alias, affiliation, releasedate, dvndescription, " +
"CASE WHEN sum(downloadcount) is null THEN 0 ELSE sum(downloadcount) END, " +
"CASE WHEN max(lastupdatetime) is null THEN vdc.releasedate ELSE max(lastupdatetime) END as lastupdated " +
"FROM vdc " +
"LEFT OUTER JOIN study on vdc.id = study.owner_id " +
"LEFT OUTER JOIN studyfileactivity on study.id = studyfileactivity.study_id " +
"WHERE vdc.restricted = false " +
"GROUP BY vdc.id, vdc.name, vdc.alias, vdc.affiliation, vdc.releasedate, vdc.dvndescription " +
"ORDER BY " +
"CASE WHEN max(lastupdatetime) is null THEN vdc.releasedate ELSE max(lastupdatetime) END " + order +
" LIMIT " + totalRows +
" OFFSET " + firstRow;
Query query = em.createNativeQuery(queryString);
list = (List<VDC>) query.getResultList();
} catch (Exception e) {
//do something here with the exception
list = new ArrayList();
} finally {
return list;
}
}
/** getManagedPagedDataByOwnedStudies
*
* used by the manage dataverses page
*
* @param firstRow
* @param totalRows
* @param orderBy
* @param order
* @return list of dataverses ordered by owner
*/
public List getManagedPagedDataByOwnedStudies(int firstRow, int totalRows, String order) {
List<VDC> list = new ArrayList();
try {
String queryString = "SELECT vdc.id, vdc.name, vdc.alias, vdc.affiliation, vdc.releasedate, " +
"vdc.dtype, vdc.createddate, vdc.dvndescription, username, " +
"CASE WHEN count(owner_id) is null THEN 0 ELSE count(owner_id) END AS owned_studies, " +
"CASE WHEN max(lastupdatetime) is null THEN vdc.releasedate ELSE max(lastupdatetime) END as lastupdated, " +
"vdc.restricted " +
"FROM vdcuser, vdc " +
"LEFT OUTER JOIN study on vdc.id = study.owner_id " +
"LEFT OUTER JOIN studyfileactivity on study.id = studyfileactivity.study_id " +
"WHERE vdc.creator_id = vdcuser.id " +
"GROUP BY vdc.id, vdc.name, vdc.alias, vdc.affiliation, vdc.releasedate, vdc.dtype, vdc.createddate, vdc.dvndescription, username, vdc.restricted " +
"ORDER BY " +
"CASE WHEN count(owner_id) is null THEN 0 ELSE count(owner_id) END " + order +
" LIMIT " + totalRows +
" OFFSET " + firstRow;
Query query = em.createNativeQuery(queryString);
list = (List<VDC>) query.getResultList();
} catch (Exception e) {
//do something here with the exception
list = new ArrayList();
} finally {
return list;
}
}
/** getManagedPagedDataByActivity
*
* @param firstRow
* @param totalRows
* @param order
* @return list of dataverses ordered by activity
*/
public List getManagedPagedDataByLastUpdated(int firstRow, int totalRows, String order) {
List<VDC> list = new ArrayList();
try {
String queryString = "SELECT vdc.id, vdc.name, vdc.alias, vdc.affiliation, vdc.releasedate, " +
"vdc.dtype, vdc.createddate, vdc.dvndescription, username, " +
"CASE WHEN count(owner_id) is null THEN 0 ELSE count(owner_id) END AS owned_studies, " +
"CASE WHEN max(lastupdatetime) is null THEN vdc.releasedate ELSE max(lastupdatetime) END as lastupdated, " +
"vdc.restricted " +
"FROM vdcuser, vdc " +
"LEFT OUTER JOIN study on vdc.id = study.owner_id " +
"LEFT OUTER JOIN studyfileactivity on study.id = studyfileactivity.study_id " +
"WHERE vdc.creator_id = vdcuser.id " +
"GROUP BY vdc.id, vdc.name, vdc.alias, vdc.affiliation, vdc.releasedate, vdc.dtype, vdc.createddate, vdc.dvndescription, username, vdc.restricted " +
"ORDER BY " +
"CASE WHEN max(lastupdatetime) is null THEN vdc.releasedate ELSE max(lastupdatetime) END " + order +
" LIMIT " + totalRows +
" OFFSET " + firstRow;
Query query = em.createNativeQuery(queryString);
list = (List<VDC>) query.getResultList();
} catch (Exception e) {
//do something here with the exception
list = new ArrayList();
} finally {
return list;
}
}
/** getManagedPageData
*
* used by the manage dataverses page
*
* @param firstRow
* @param totalRows
* @param orderBy
* @param order
* @return list of dataverses ordered by creator
*/
public List getManagedPagedData(int firstRow, int totalRows, String orderBy, String order) {
List<VDC> list = new ArrayList();
orderBy = (orderBy.toLowerCase().equals("name")) ? "CASE WHEN dtype='Scholar' THEN Lower(vdc.lastname) ELSE Lower(vdc.name) END" : "Lower(" + orderBy + ")";
try {
String queryString = "SELECT vdc.id, " +
"CASE WHEN dtype = 'Scholar' THEN vdc.lastname || ', ' || vdc.firstname ELSE name END AS sortname, " +
"vdc.alias, vdc.affiliation, vdc.releasedate, " +
"vdc.dtype, vdc.createddate, vdc.dvndescription, username, " +
"CASE WHEN count(owner_id) is null THEN 0 ELSE count(owner_id) END AS owned_studies, " +
"CASE WHEN max(lastupdatetime) is null THEN vdc.releasedate ELSE max(lastupdatetime) END as lastupdated, " +
"vdc.restricted " +
"FROM vdcuser, vdc " +
"LEFT OUTER JOIN study on vdc.id = study.owner_id " +
"LEFT OUTER JOIN studyfileactivity on study.id = studyfileactivity.study_id " +
"WHERE vdc.creator_id = vdcuser.id " +
"GROUP BY vdc.id, vdc.name, vdc.lastname, sortname, vdc.alias, vdc.affiliation, vdc.releasedate, vdc.dtype, vdc.createddate, vdc.dvndescription, username, vdc.restricted " +
"ORDER BY " + orderBy + " " + order +
" LIMIT " + totalRows +
" OFFSET " + firstRow;
Query query = em.createNativeQuery(queryString);
list = (List<VDC>) query.getResultList();
} catch (Exception e) {
//do something here with the exception
list = new ArrayList();
} finally {
return list;
}
}
//Not used anywhere....
public Long getUnrestrictedVdcCount(long vdcGroupId) {
String queryString = (vdcGroupId != 0) ? "SELECT count(vdcgroup_id) FROM vdcgroup_vdcs g " +
"WHERE g.vdcgroup_id = " + vdcGroupId +
" AND g.vdc_id in (SELECT id FROM vdc WHERE restricted = false)" : "SELECT count(id) FROM vdc v WHERE restricted = false";
Long longValue = null;
Query query = em.createNativeQuery(queryString);
return (Long) query.getSingleResult();
}
public Long getVdcCount() {
return getVdcCount(null, null);
}
public Long getVdcCount( List<Long> vdcIds, Boolean restricted ) {
String queryString = "SELECT count(id) FROM vdc g where 1=1 ";
if (vdcIds !=null && !vdcIds.isEmpty()){
String varString = "(" + generateTempTableString(vdcIds) + ") ";
queryString += "and g.id in " + varString;
}
if ( restricted != null ) {
queryString += "and restricted = " + restricted.toString() + "" ;
}
Query query = em.createNativeQuery(queryString);
return (Long) query.getSingleResult();
}
private String generateTempTableString(List<Long> studyIds) {
// first step: create the temp table with the ids
em.createNativeQuery(" BEGIN; SET TRANSACTION READ WRITE; DROP TABLE IF EXISTS tempid; END;").executeUpdate();
em.createNativeQuery(" BEGIN; SET TRANSACTION READ WRITE; CREATE TEMPORARY TABLE tempid (tempid integer primary key, orderby integer); END;").executeUpdate();
em.createNativeQuery(" BEGIN; SET TRANSACTION READ WRITE; INSERT INTO tempid VALUES " + generateIDsforTempInsert(studyIds) + "; END;").executeUpdate();
return "select tempid from tempid";
}
private String generateIDsforTempInsert(List idList) {
int count = 0;
StringBuffer sb = new StringBuffer();
Iterator iter = idList.iterator();
while (iter.hasNext()) {
Long id = (Long) iter.next();
sb.append("(").append(id).append(",").append(count++).append(")");
if (iter.hasNext()) {
sb.append(",");
}
}
return sb.toString();
}
// metho to get an ordered list of vdcIds
public List<Long> getOrderedVDCIds(String orderBy) {
System.out.print("String orderBy " );
return getOrderedVDCIds(null, null, orderBy);
}
public List<Long> getOrderedVDCIds(String orderBy, boolean hideRestrictedVDCs) {
System.out.print("String orderBy, boolean hideRestrictedVDC " );
return getOrderedVDCIds(null, null, orderBy, hideRestrictedVDCs, null, null);
}
public List<Long> getOrderedVDCIds(String letter, String orderBy) {
System.out.print("String letter, String orderBy " );
return getOrderedVDCIds(null, letter, orderBy);
}
public List<Long> getOrderedVDCIds(Long classificationId, String orderBy) {
System.out.print("Long classificationId, String orderBy " );
return getOrderedVDCIds(classificationId, null, orderBy);
}
public List<Long> getOrderedVDCIds(Long classificationId, String letter, String orderBy) {
System.out.print("Long classificationId, String letter, String orderBy " );
return getOrderedVDCIds(classificationId, letter, orderBy, true, null, null);
}
@Override
public List<Long> getOrderedVDCIds(Long classificationId, String letter, String orderBy, boolean hideRestrictedVDCs) {
System.out.print("original call " );
return getOrderedVDCIds(classificationId, letter, orderBy, hideRestrictedVDCs, null, null);
}
public List<Long> getOrderedVDCIds(Long classificationId, String letter, String orderBy, boolean hideRestrictedVDCs, String filterString) {
System.out.print("original call " );
return getOrderedVDCIds(classificationId, letter, orderBy, hideRestrictedVDCs, filterString, null);
}
public List<Long> getOrderedVDCIds(Long classificationId, String letter, String orderBy, boolean hideRestrictedVDCs, String filterString, Long subNetworkId) {
List<Long> returnList = new ArrayList();
// this query will get all vdcids for the dvn or for a classification (and one level of children, per design)
String selectClause = "select distinct v.id ";
String fromClause = "from vdc v ";
String whereClause = "where 1=1 ";
String orderingClause = "";
// handle orderBy
if (VDC.ORDER_BY_ACTIVITY.equals(orderBy)) {
selectClause += ", (localstudylocaldownloadcount + localstudynetworkdownloadcount + (.5 * localstudyforeigndownloadcount) + (.5 * foreignstudylocaldownloadcount) ) as dlcount ";
fromClause += ", vdcactivity va ";
whereClause += "and v.id = va.vdc_id ";
orderingClause += "order by dlcount desc ";
} else if (VDC.ORDER_BY_OWNED_STUDIES.equals(orderBy)) {
selectClause += ", count(owner_id) ";
fromClause += "LEFT OUTER JOIN study on v.id = study.owner_id ";
orderingClause += "group by v.id ";
orderingClause += "order by count(owner_id) desc ";
} else if (VDC.ORDER_BY_LAST_STUDY_UPDATE_TIME.equals(orderBy)) {
selectClause += ", (CASE WHEN max(lastupdatetime) IS NULL THEN 0 ELSE 1 END) as updated, max(lastupdatetime) ";
fromClause += "LEFT OUTER JOIN study on v.id = study.owner_id ";
orderingClause = "group by v.id ";
orderingClause += "order by updated desc, max(lastupdatetime) desc ";
} else if (VDC.ORDER_BY_CREATOR.equals(orderBy)) {
selectClause += ", upper(u." + orderBy + ") as " + orderBy + " ";
fromClause += ", vdcuser u ";
whereClause += "AND v.creator_id = u.id ";
orderingClause += " ORDER BY " + orderBy;
} else if (VDC.ORDER_BY_NAME.equals(orderBy)) {
selectClause += ", upper( (CASE WHEN dtype = 'Scholar' THEN lastname || ', ' || firstname ELSE name END) ) as sortname ";
orderingClause += " order by sortname ";
} else if (VDC.ORDER_BY_AFFILIATION.equals(orderBy)) {
selectClause += ", (CASE WHEN affiliation IS NULL or affiliation = '' THEN 1 ELSE 0 END) as isempty, upper(affiliation) ";
orderingClause += " order by isempty, upper(affiliation) ";
} else if (VDC.ORDER_BY_SUBNETWORK.equals(orderBy)) {
- selectClause += ", upper(vdcn.name) as subnetwork ";
+ selectClause += ", upper(vdcn.name) as sortname, (CASE WHEN vdcn.id = 0 THEN 0 ELSE 1 END) as subnetwork ";
fromClause += ", vdcnetwork vdcn ";
whereClause += "AND v.vdcnetwork_id = vdcn.id ";
- orderingClause += " ORDER BY subnetwork";
+ orderingClause += " ORDER BY subnetwork desc, sortname";
} else if (VDC.ORDER_BY_CREATE_DATE.equals(orderBy)) {
selectClause += ", " + orderBy + " ";
orderingClause += " order by " + orderBy + " desc ";
} else if (VDC.ORDER_BY_RELEASE_DATE.equals(orderBy)) {
selectClause += ",(CASE WHEN releasedate IS NULL THEN 0 ELSE 1 END) as released, releasedate ";
orderingClause += " order by released desc, releasedate desc ";
} else if (VDC.ORDER_BY_TYPE.equals(orderBy)) {
selectClause += ", (CASE WHEN harvestingdataverse_id IS NOT NULL THEN 'Harvesting' ELSE dtype END) as vdcType ";
orderingClause += " order by vdcType";
}
// now additional clauses based on parameters
if (hideRestrictedVDCs) {
whereClause += "and v.restricted = false ";
}
if (classificationId != null) {
fromClause += ", vdcgroup_vdcs vv ";
whereClause += "and v.id = vv.vdc_id ";
whereClause += "and vv.vdcgroup_id in ( select id from vdcgroup where id = ? or parent = ?) ";
}
if (letter != null) {
if (letter.equals("#")) {
whereClause += "and ((dtype != 'Scholar' and v.name ~ '^[0-9]') ";
whereClause += "or (dtype = 'Scholar' and v.lastname ~ '^[0-9]')) ";
} else {
whereClause += "and ((dtype != 'Scholar' and upper(v.name) like '" + letter.toUpperCase() + "%') ";
whereClause += "or (dtype = 'Scholar' and upper(v.lastname) like '" + letter.toUpperCase() + "%')) ";
}
}
if (filterString != null) {
whereClause += "and ((upper(v.name) like '%" + filterString.replaceAll("'", "''").toUpperCase() + "%') ";
whereClause += " or (upper(affiliation) like '%" + filterString.replaceAll("'", "''").toUpperCase() + "%') ";
whereClause += "or (dtype = 'Scholar' and upper(v.lastname) like '%" + filterString.replaceAll("'", "''").toUpperCase() + "%')) ";
}
if (subNetworkId != null) {
whereClause += "and v.vdcnetwork_id = " + subNetworkId + " ";
}
System.out.print("whereClause " + whereClause);
String queryString = selectClause + fromClause + whereClause + orderingClause;
logger.info ("query: "+queryString);
// we are now ready to create the query
Query query = em.createNativeQuery(queryString);
if (classificationId != null) {
query.setParameter(1, classificationId);
query.setParameter(2, classificationId);
}
// Below is a good example of a conversion from EE5 to EE6:
//
// This is how we used to do things:
// since query is native, must parse through Vector results
//for (Object currentResult : query.getResultList()) {
// convert results into Longs
//returnList.add(new Long(((Integer) ((Vector) currentResult).get(0))).longValue());
//}
// We cannot cast Object to Vector anymore! (runtime exception thrown)
// (also, it's not entirely clear what the .longValue() above is for :)
//
// So this is how we are doing it now:
for (Iterator itr = query.getResultList().iterator(); itr.hasNext();) {
Object[] nextResult = (Object[])itr.next();
returnList.add(new Long((Integer)nextResult[0]));
}
// -- i.e., we have to use Object[] instead of a Vector.
// Note that we (apparently) can't just do "new Long(nextResult[0])" above;
// you will get a "Cannot cast Integer to Long" runtime exception.
// Which I guess means that the native type for the returned object id
// is integer, not long (?). Anyway, casting to Integer solves it.
return returnList;
}
public double getMaxDownloadCount() {
String queryString = "SELECT max( localstudylocaldownloadcount + localstudynetworkdownloadcount + " +
"(.5 * localstudyforeigndownloadcount) + (.5 * foreignstudylocaldownloadcount) ) " +
"FROM vdcactivity";
Query query = em.createNativeQuery(queryString);
//BigDecimal maxDLCount = (BigDecimal) ((List) query.getSingleResult()).get(0);
BigDecimal maxDLCount = (BigDecimal)(query.getSingleResult());
return (maxDLCount != null ? maxDLCount.doubleValue() : 0);
}
public void setTwitterCredentials(String accessToken, String accessTokenSecret, Long vdcId) {
TwitterCredentials tc;
VDC vdc = null;
if (vdcId != null) {
vdc = (VDC) em.find(VDC.class, new Long(vdcId));
tc = vdc.getTwitterCredentials();
} else {
tc = vdcNetworkService.getTwitterCredentials();
}
if (tc == null) {
tc = new TwitterCredentials();
em.persist(tc);
}
tc.setVDC(vdc);
tc.setAccessToken(accessToken);
tc.setAccessTokenSecret(accessTokenSecret);
em.merge(tc);
}
public void removeTwitterCredentials(Long vdcId) {
TwitterCredentials tc;
VDC vdc = null;
if (vdcId != null) {
vdc = (VDC) em.find(VDC.class, new Long(vdcId));
tc = vdc.getTwitterCredentials();
} else {
tc = vdcNetworkService.getTwitterCredentials();
}
em.remove(tc);
}
}
| false | true | public List<Long> getOrderedVDCIds(Long classificationId, String letter, String orderBy, boolean hideRestrictedVDCs, String filterString, Long subNetworkId) {
List<Long> returnList = new ArrayList();
// this query will get all vdcids for the dvn or for a classification (and one level of children, per design)
String selectClause = "select distinct v.id ";
String fromClause = "from vdc v ";
String whereClause = "where 1=1 ";
String orderingClause = "";
// handle orderBy
if (VDC.ORDER_BY_ACTIVITY.equals(orderBy)) {
selectClause += ", (localstudylocaldownloadcount + localstudynetworkdownloadcount + (.5 * localstudyforeigndownloadcount) + (.5 * foreignstudylocaldownloadcount) ) as dlcount ";
fromClause += ", vdcactivity va ";
whereClause += "and v.id = va.vdc_id ";
orderingClause += "order by dlcount desc ";
} else if (VDC.ORDER_BY_OWNED_STUDIES.equals(orderBy)) {
selectClause += ", count(owner_id) ";
fromClause += "LEFT OUTER JOIN study on v.id = study.owner_id ";
orderingClause += "group by v.id ";
orderingClause += "order by count(owner_id) desc ";
} else if (VDC.ORDER_BY_LAST_STUDY_UPDATE_TIME.equals(orderBy)) {
selectClause += ", (CASE WHEN max(lastupdatetime) IS NULL THEN 0 ELSE 1 END) as updated, max(lastupdatetime) ";
fromClause += "LEFT OUTER JOIN study on v.id = study.owner_id ";
orderingClause = "group by v.id ";
orderingClause += "order by updated desc, max(lastupdatetime) desc ";
} else if (VDC.ORDER_BY_CREATOR.equals(orderBy)) {
selectClause += ", upper(u." + orderBy + ") as " + orderBy + " ";
fromClause += ", vdcuser u ";
whereClause += "AND v.creator_id = u.id ";
orderingClause += " ORDER BY " + orderBy;
} else if (VDC.ORDER_BY_NAME.equals(orderBy)) {
selectClause += ", upper( (CASE WHEN dtype = 'Scholar' THEN lastname || ', ' || firstname ELSE name END) ) as sortname ";
orderingClause += " order by sortname ";
} else if (VDC.ORDER_BY_AFFILIATION.equals(orderBy)) {
selectClause += ", (CASE WHEN affiliation IS NULL or affiliation = '' THEN 1 ELSE 0 END) as isempty, upper(affiliation) ";
orderingClause += " order by isempty, upper(affiliation) ";
} else if (VDC.ORDER_BY_SUBNETWORK.equals(orderBy)) {
selectClause += ", upper(vdcn.name) as subnetwork ";
fromClause += ", vdcnetwork vdcn ";
whereClause += "AND v.vdcnetwork_id = vdcn.id ";
orderingClause += " ORDER BY subnetwork";
} else if (VDC.ORDER_BY_CREATE_DATE.equals(orderBy)) {
selectClause += ", " + orderBy + " ";
orderingClause += " order by " + orderBy + " desc ";
} else if (VDC.ORDER_BY_RELEASE_DATE.equals(orderBy)) {
selectClause += ",(CASE WHEN releasedate IS NULL THEN 0 ELSE 1 END) as released, releasedate ";
orderingClause += " order by released desc, releasedate desc ";
} else if (VDC.ORDER_BY_TYPE.equals(orderBy)) {
selectClause += ", (CASE WHEN harvestingdataverse_id IS NOT NULL THEN 'Harvesting' ELSE dtype END) as vdcType ";
orderingClause += " order by vdcType";
}
// now additional clauses based on parameters
if (hideRestrictedVDCs) {
whereClause += "and v.restricted = false ";
}
if (classificationId != null) {
fromClause += ", vdcgroup_vdcs vv ";
whereClause += "and v.id = vv.vdc_id ";
whereClause += "and vv.vdcgroup_id in ( select id from vdcgroup where id = ? or parent = ?) ";
}
if (letter != null) {
if (letter.equals("#")) {
whereClause += "and ((dtype != 'Scholar' and v.name ~ '^[0-9]') ";
whereClause += "or (dtype = 'Scholar' and v.lastname ~ '^[0-9]')) ";
} else {
whereClause += "and ((dtype != 'Scholar' and upper(v.name) like '" + letter.toUpperCase() + "%') ";
whereClause += "or (dtype = 'Scholar' and upper(v.lastname) like '" + letter.toUpperCase() + "%')) ";
}
}
if (filterString != null) {
whereClause += "and ((upper(v.name) like '%" + filterString.replaceAll("'", "''").toUpperCase() + "%') ";
whereClause += " or (upper(affiliation) like '%" + filterString.replaceAll("'", "''").toUpperCase() + "%') ";
whereClause += "or (dtype = 'Scholar' and upper(v.lastname) like '%" + filterString.replaceAll("'", "''").toUpperCase() + "%')) ";
}
if (subNetworkId != null) {
whereClause += "and v.vdcnetwork_id = " + subNetworkId + " ";
}
System.out.print("whereClause " + whereClause);
String queryString = selectClause + fromClause + whereClause + orderingClause;
logger.info ("query: "+queryString);
// we are now ready to create the query
Query query = em.createNativeQuery(queryString);
if (classificationId != null) {
query.setParameter(1, classificationId);
query.setParameter(2, classificationId);
}
// Below is a good example of a conversion from EE5 to EE6:
//
// This is how we used to do things:
// since query is native, must parse through Vector results
//for (Object currentResult : query.getResultList()) {
// convert results into Longs
//returnList.add(new Long(((Integer) ((Vector) currentResult).get(0))).longValue());
//}
// We cannot cast Object to Vector anymore! (runtime exception thrown)
// (also, it's not entirely clear what the .longValue() above is for :)
//
// So this is how we are doing it now:
for (Iterator itr = query.getResultList().iterator(); itr.hasNext();) {
Object[] nextResult = (Object[])itr.next();
returnList.add(new Long((Integer)nextResult[0]));
}
// -- i.e., we have to use Object[] instead of a Vector.
// Note that we (apparently) can't just do "new Long(nextResult[0])" above;
// you will get a "Cannot cast Integer to Long" runtime exception.
// Which I guess means that the native type for the returned object id
// is integer, not long (?). Anyway, casting to Integer solves it.
return returnList;
}
| public List<Long> getOrderedVDCIds(Long classificationId, String letter, String orderBy, boolean hideRestrictedVDCs, String filterString, Long subNetworkId) {
List<Long> returnList = new ArrayList();
// this query will get all vdcids for the dvn or for a classification (and one level of children, per design)
String selectClause = "select distinct v.id ";
String fromClause = "from vdc v ";
String whereClause = "where 1=1 ";
String orderingClause = "";
// handle orderBy
if (VDC.ORDER_BY_ACTIVITY.equals(orderBy)) {
selectClause += ", (localstudylocaldownloadcount + localstudynetworkdownloadcount + (.5 * localstudyforeigndownloadcount) + (.5 * foreignstudylocaldownloadcount) ) as dlcount ";
fromClause += ", vdcactivity va ";
whereClause += "and v.id = va.vdc_id ";
orderingClause += "order by dlcount desc ";
} else if (VDC.ORDER_BY_OWNED_STUDIES.equals(orderBy)) {
selectClause += ", count(owner_id) ";
fromClause += "LEFT OUTER JOIN study on v.id = study.owner_id ";
orderingClause += "group by v.id ";
orderingClause += "order by count(owner_id) desc ";
} else if (VDC.ORDER_BY_LAST_STUDY_UPDATE_TIME.equals(orderBy)) {
selectClause += ", (CASE WHEN max(lastupdatetime) IS NULL THEN 0 ELSE 1 END) as updated, max(lastupdatetime) ";
fromClause += "LEFT OUTER JOIN study on v.id = study.owner_id ";
orderingClause = "group by v.id ";
orderingClause += "order by updated desc, max(lastupdatetime) desc ";
} else if (VDC.ORDER_BY_CREATOR.equals(orderBy)) {
selectClause += ", upper(u." + orderBy + ") as " + orderBy + " ";
fromClause += ", vdcuser u ";
whereClause += "AND v.creator_id = u.id ";
orderingClause += " ORDER BY " + orderBy;
} else if (VDC.ORDER_BY_NAME.equals(orderBy)) {
selectClause += ", upper( (CASE WHEN dtype = 'Scholar' THEN lastname || ', ' || firstname ELSE name END) ) as sortname ";
orderingClause += " order by sortname ";
} else if (VDC.ORDER_BY_AFFILIATION.equals(orderBy)) {
selectClause += ", (CASE WHEN affiliation IS NULL or affiliation = '' THEN 1 ELSE 0 END) as isempty, upper(affiliation) ";
orderingClause += " order by isempty, upper(affiliation) ";
} else if (VDC.ORDER_BY_SUBNETWORK.equals(orderBy)) {
selectClause += ", upper(vdcn.name) as sortname, (CASE WHEN vdcn.id = 0 THEN 0 ELSE 1 END) as subnetwork ";
fromClause += ", vdcnetwork vdcn ";
whereClause += "AND v.vdcnetwork_id = vdcn.id ";
orderingClause += " ORDER BY subnetwork desc, sortname";
} else if (VDC.ORDER_BY_CREATE_DATE.equals(orderBy)) {
selectClause += ", " + orderBy + " ";
orderingClause += " order by " + orderBy + " desc ";
} else if (VDC.ORDER_BY_RELEASE_DATE.equals(orderBy)) {
selectClause += ",(CASE WHEN releasedate IS NULL THEN 0 ELSE 1 END) as released, releasedate ";
orderingClause += " order by released desc, releasedate desc ";
} else if (VDC.ORDER_BY_TYPE.equals(orderBy)) {
selectClause += ", (CASE WHEN harvestingdataverse_id IS NOT NULL THEN 'Harvesting' ELSE dtype END) as vdcType ";
orderingClause += " order by vdcType";
}
// now additional clauses based on parameters
if (hideRestrictedVDCs) {
whereClause += "and v.restricted = false ";
}
if (classificationId != null) {
fromClause += ", vdcgroup_vdcs vv ";
whereClause += "and v.id = vv.vdc_id ";
whereClause += "and vv.vdcgroup_id in ( select id from vdcgroup where id = ? or parent = ?) ";
}
if (letter != null) {
if (letter.equals("#")) {
whereClause += "and ((dtype != 'Scholar' and v.name ~ '^[0-9]') ";
whereClause += "or (dtype = 'Scholar' and v.lastname ~ '^[0-9]')) ";
} else {
whereClause += "and ((dtype != 'Scholar' and upper(v.name) like '" + letter.toUpperCase() + "%') ";
whereClause += "or (dtype = 'Scholar' and upper(v.lastname) like '" + letter.toUpperCase() + "%')) ";
}
}
if (filterString != null) {
whereClause += "and ((upper(v.name) like '%" + filterString.replaceAll("'", "''").toUpperCase() + "%') ";
whereClause += " or (upper(affiliation) like '%" + filterString.replaceAll("'", "''").toUpperCase() + "%') ";
whereClause += "or (dtype = 'Scholar' and upper(v.lastname) like '%" + filterString.replaceAll("'", "''").toUpperCase() + "%')) ";
}
if (subNetworkId != null) {
whereClause += "and v.vdcnetwork_id = " + subNetworkId + " ";
}
System.out.print("whereClause " + whereClause);
String queryString = selectClause + fromClause + whereClause + orderingClause;
logger.info ("query: "+queryString);
// we are now ready to create the query
Query query = em.createNativeQuery(queryString);
if (classificationId != null) {
query.setParameter(1, classificationId);
query.setParameter(2, classificationId);
}
// Below is a good example of a conversion from EE5 to EE6:
//
// This is how we used to do things:
// since query is native, must parse through Vector results
//for (Object currentResult : query.getResultList()) {
// convert results into Longs
//returnList.add(new Long(((Integer) ((Vector) currentResult).get(0))).longValue());
//}
// We cannot cast Object to Vector anymore! (runtime exception thrown)
// (also, it's not entirely clear what the .longValue() above is for :)
//
// So this is how we are doing it now:
for (Iterator itr = query.getResultList().iterator(); itr.hasNext();) {
Object[] nextResult = (Object[])itr.next();
returnList.add(new Long((Integer)nextResult[0]));
}
// -- i.e., we have to use Object[] instead of a Vector.
// Note that we (apparently) can't just do "new Long(nextResult[0])" above;
// you will get a "Cannot cast Integer to Long" runtime exception.
// Which I guess means that the native type for the returned object id
// is integer, not long (?). Anyway, casting to Integer solves it.
return returnList;
}
|
diff --git a/tez-tests/src/test/java/org/apache/tez/test/MiniTezCluster.java b/tez-tests/src/test/java/org/apache/tez/test/MiniTezCluster.java
index 8926ed8a..6bbc7b32 100644
--- a/tez-tests/src/test/java/org/apache/tez/test/MiniTezCluster.java
+++ b/tez-tests/src/test/java/org/apache/tez/test/MiniTezCluster.java
@@ -1,172 +1,173 @@
/**
* 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.tez.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.ShuffleHandler;
import org.apache.hadoop.mapreduce.v2.jobhistory.JobHistoryUtils;
import org.apache.hadoop.service.Service;
import org.apache.hadoop.util.JarFinder;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.server.MiniYARNCluster;
import org.apache.hadoop.yarn.server.nodemanager.ContainerExecutor;
import org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor;
import org.apache.tez.dag.api.TezConfiguration;
import org.apache.tez.dag.api.TezUncheckedException;
import org.apache.tez.dag.app.DAGAppMaster;
import org.apache.tez.mapreduce.hadoop.MRConfig;
import org.apache.tez.mapreduce.hadoop.MRJobConfig;
/**
* Configures and starts the Tez-specific components in the YARN cluster.
*
* When using this mini cluster, the user is expected to
*/
public class MiniTezCluster extends MiniYARNCluster {
public static final String APPJAR = JarFinder.getJar(DAGAppMaster.class);
private static final Log LOG = LogFactory.getLog(MiniTezCluster.class);
private static final String YARN_CLUSTER_CONFIG = "yarn-site.xml";
private Path confFilePath;
public MiniTezCluster(String testName) {
this(testName, 1);
}
public MiniTezCluster(String testName, int noOfNMs) {
super(testName, noOfNMs, 4, 4);
}
public MiniTezCluster(String testName, int noOfNMs,
int numLocalDirs, int numLogDirs) {
super(testName, noOfNMs, numLocalDirs, numLogDirs);
}
@Override
public void serviceInit(Configuration conf) throws Exception {
conf.set(MRConfig.FRAMEWORK_NAME, MRConfig.YARN_TEZ_FRAMEWORK_NAME);
if (conf.get(MRJobConfig.MR_AM_STAGING_DIR) == null) {
conf.set(MRJobConfig.MR_AM_STAGING_DIR, new File(getTestWorkDir(),
"apps_staging_dir" + Path.SEPARATOR).getAbsolutePath());
}
if (conf.get(YarnConfiguration.DEBUG_NM_DELETE_DELAY_SEC) == null) {
// nothing defined. set quick delete value
conf.setLong(YarnConfiguration.DEBUG_NM_DELETE_DELAY_SEC, 0l);
}
File appJarFile = new File(MiniTezCluster.APPJAR);
if (!appJarFile.exists()) {
String message = "TezAppJar " + MiniTezCluster.APPJAR
+ " not found. Exiting.";
LOG.info(message);
throw new TezUncheckedException(message);
} else {
- conf.set(TezConfiguration.TEZ_LIB_URIS, "file://" + appJarFile.getAbsolutePath());
+ conf.set(TezConfiguration.TEZ_LIB_URIS,
+ "file://" + new Path(appJarFile.getAbsolutePath()).toUri().getPath());
LOG.info("Set TEZ-LIB-URI to: " + conf.get(TezConfiguration.TEZ_LIB_URIS));
}
// VMEM monitoring disabled, PMEM monitoring enabled.
conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, false);
conf.setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, false);
conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "000");
try {
Path stagingPath = FileContext.getFileContext(conf).makeQualified(
new Path(conf.get(MRJobConfig.MR_AM_STAGING_DIR)));
FileContext fc=FileContext.getFileContext(stagingPath.toUri(), conf);
if (fc.util().exists(stagingPath)) {
LOG.info(stagingPath + " exists! deleting...");
fc.delete(stagingPath, true);
}
LOG.info("mkdir: " + stagingPath);
fc.mkdir(stagingPath, null, true);
//mkdir done directory as well
String doneDir =
JobHistoryUtils.getConfiguredHistoryServerDoneDirPrefix(conf);
Path doneDirPath = fc.makeQualified(new Path(doneDir));
fc.mkdir(doneDirPath, null, true);
} catch (IOException e) {
throw new TezUncheckedException("Could not create staging directory. ", e);
}
conf.set(MRConfig.MASTER_ADDRESS, "test");
//configure the shuffle service in NM
conf.setStrings(YarnConfiguration.NM_AUX_SERVICES,
new String[] { ShuffleHandler.MAPREDUCE_SHUFFLE_SERVICEID });
conf.setClass(String.format(YarnConfiguration.NM_AUX_SERVICE_FMT,
ShuffleHandler.MAPREDUCE_SHUFFLE_SERVICEID), ShuffleHandler.class,
Service.class);
// Non-standard shuffle port
conf.setInt(ShuffleHandler.SHUFFLE_PORT_CONFIG_KEY, 0);
conf.setClass(YarnConfiguration.NM_CONTAINER_EXECUTOR,
DefaultContainerExecutor.class, ContainerExecutor.class);
// TestMRJobs is for testing non-uberized operation only; see TestUberAM
// for corresponding uberized tests.
conf.setBoolean(MRJobConfig.JOB_UBERTASK_ENABLE, false);
super.serviceInit(conf);
}
@Override
public void serviceStart() throws Exception {
super.serviceStart();
File workDir = super.getTestWorkDir();
Configuration conf = super.getConfig();
confFilePath = new Path(workDir.getAbsolutePath(), YARN_CLUSTER_CONFIG);
File confFile = new File(confFilePath.toString());
try {
confFile.createNewFile();
conf.writeXml(new FileOutputStream(confFile));
confFile.deleteOnExit();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(e);
}
confFilePath = new Path(confFile.getAbsolutePath());
conf.setStrings(YarnConfiguration.YARN_APPLICATION_CLASSPATH,
workDir.getAbsolutePath(), System.getProperty("java.class.path"));
LOG.info("Setting yarn-site.xml via YARN-APP-CP at: "
+ conf.get(YarnConfiguration.YARN_APPLICATION_CLASSPATH));
}
public Path getConfigFilePath() {
return confFilePath;
}
}
| true | true | public void serviceInit(Configuration conf) throws Exception {
conf.set(MRConfig.FRAMEWORK_NAME, MRConfig.YARN_TEZ_FRAMEWORK_NAME);
if (conf.get(MRJobConfig.MR_AM_STAGING_DIR) == null) {
conf.set(MRJobConfig.MR_AM_STAGING_DIR, new File(getTestWorkDir(),
"apps_staging_dir" + Path.SEPARATOR).getAbsolutePath());
}
if (conf.get(YarnConfiguration.DEBUG_NM_DELETE_DELAY_SEC) == null) {
// nothing defined. set quick delete value
conf.setLong(YarnConfiguration.DEBUG_NM_DELETE_DELAY_SEC, 0l);
}
File appJarFile = new File(MiniTezCluster.APPJAR);
if (!appJarFile.exists()) {
String message = "TezAppJar " + MiniTezCluster.APPJAR
+ " not found. Exiting.";
LOG.info(message);
throw new TezUncheckedException(message);
} else {
conf.set(TezConfiguration.TEZ_LIB_URIS, "file://" + appJarFile.getAbsolutePath());
LOG.info("Set TEZ-LIB-URI to: " + conf.get(TezConfiguration.TEZ_LIB_URIS));
}
// VMEM monitoring disabled, PMEM monitoring enabled.
conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, false);
conf.setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, false);
conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "000");
try {
Path stagingPath = FileContext.getFileContext(conf).makeQualified(
new Path(conf.get(MRJobConfig.MR_AM_STAGING_DIR)));
FileContext fc=FileContext.getFileContext(stagingPath.toUri(), conf);
if (fc.util().exists(stagingPath)) {
LOG.info(stagingPath + " exists! deleting...");
fc.delete(stagingPath, true);
}
LOG.info("mkdir: " + stagingPath);
fc.mkdir(stagingPath, null, true);
//mkdir done directory as well
String doneDir =
JobHistoryUtils.getConfiguredHistoryServerDoneDirPrefix(conf);
Path doneDirPath = fc.makeQualified(new Path(doneDir));
fc.mkdir(doneDirPath, null, true);
} catch (IOException e) {
throw new TezUncheckedException("Could not create staging directory. ", e);
}
conf.set(MRConfig.MASTER_ADDRESS, "test");
//configure the shuffle service in NM
conf.setStrings(YarnConfiguration.NM_AUX_SERVICES,
new String[] { ShuffleHandler.MAPREDUCE_SHUFFLE_SERVICEID });
conf.setClass(String.format(YarnConfiguration.NM_AUX_SERVICE_FMT,
ShuffleHandler.MAPREDUCE_SHUFFLE_SERVICEID), ShuffleHandler.class,
Service.class);
// Non-standard shuffle port
conf.setInt(ShuffleHandler.SHUFFLE_PORT_CONFIG_KEY, 0);
conf.setClass(YarnConfiguration.NM_CONTAINER_EXECUTOR,
DefaultContainerExecutor.class, ContainerExecutor.class);
// TestMRJobs is for testing non-uberized operation only; see TestUberAM
// for corresponding uberized tests.
conf.setBoolean(MRJobConfig.JOB_UBERTASK_ENABLE, false);
super.serviceInit(conf);
}
| public void serviceInit(Configuration conf) throws Exception {
conf.set(MRConfig.FRAMEWORK_NAME, MRConfig.YARN_TEZ_FRAMEWORK_NAME);
if (conf.get(MRJobConfig.MR_AM_STAGING_DIR) == null) {
conf.set(MRJobConfig.MR_AM_STAGING_DIR, new File(getTestWorkDir(),
"apps_staging_dir" + Path.SEPARATOR).getAbsolutePath());
}
if (conf.get(YarnConfiguration.DEBUG_NM_DELETE_DELAY_SEC) == null) {
// nothing defined. set quick delete value
conf.setLong(YarnConfiguration.DEBUG_NM_DELETE_DELAY_SEC, 0l);
}
File appJarFile = new File(MiniTezCluster.APPJAR);
if (!appJarFile.exists()) {
String message = "TezAppJar " + MiniTezCluster.APPJAR
+ " not found. Exiting.";
LOG.info(message);
throw new TezUncheckedException(message);
} else {
conf.set(TezConfiguration.TEZ_LIB_URIS,
"file://" + new Path(appJarFile.getAbsolutePath()).toUri().getPath());
LOG.info("Set TEZ-LIB-URI to: " + conf.get(TezConfiguration.TEZ_LIB_URIS));
}
// VMEM monitoring disabled, PMEM monitoring enabled.
conf.setBoolean(YarnConfiguration.NM_PMEM_CHECK_ENABLED, false);
conf.setBoolean(YarnConfiguration.NM_VMEM_CHECK_ENABLED, false);
conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY, "000");
try {
Path stagingPath = FileContext.getFileContext(conf).makeQualified(
new Path(conf.get(MRJobConfig.MR_AM_STAGING_DIR)));
FileContext fc=FileContext.getFileContext(stagingPath.toUri(), conf);
if (fc.util().exists(stagingPath)) {
LOG.info(stagingPath + " exists! deleting...");
fc.delete(stagingPath, true);
}
LOG.info("mkdir: " + stagingPath);
fc.mkdir(stagingPath, null, true);
//mkdir done directory as well
String doneDir =
JobHistoryUtils.getConfiguredHistoryServerDoneDirPrefix(conf);
Path doneDirPath = fc.makeQualified(new Path(doneDir));
fc.mkdir(doneDirPath, null, true);
} catch (IOException e) {
throw new TezUncheckedException("Could not create staging directory. ", e);
}
conf.set(MRConfig.MASTER_ADDRESS, "test");
//configure the shuffle service in NM
conf.setStrings(YarnConfiguration.NM_AUX_SERVICES,
new String[] { ShuffleHandler.MAPREDUCE_SHUFFLE_SERVICEID });
conf.setClass(String.format(YarnConfiguration.NM_AUX_SERVICE_FMT,
ShuffleHandler.MAPREDUCE_SHUFFLE_SERVICEID), ShuffleHandler.class,
Service.class);
// Non-standard shuffle port
conf.setInt(ShuffleHandler.SHUFFLE_PORT_CONFIG_KEY, 0);
conf.setClass(YarnConfiguration.NM_CONTAINER_EXECUTOR,
DefaultContainerExecutor.class, ContainerExecutor.class);
// TestMRJobs is for testing non-uberized operation only; see TestUberAM
// for corresponding uberized tests.
conf.setBoolean(MRJobConfig.JOB_UBERTASK_ENABLE, false);
super.serviceInit(conf);
}
|
diff --git a/src/net/miz_hi/smileessence/listener/TimelineScrollListener.java b/src/net/miz_hi/smileessence/listener/TimelineScrollListener.java
index af9c6dc..412d120 100644
--- a/src/net/miz_hi/smileessence/listener/TimelineScrollListener.java
+++ b/src/net/miz_hi/smileessence/listener/TimelineScrollListener.java
@@ -1,47 +1,48 @@
package net.miz_hi.smileessence.listener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import net.miz_hi.smileessence.notification.Notificator;
import net.miz_hi.smileessence.util.CustomListAdapter;
public class TimelineScrollListener implements OnScrollListener
{
private CustomListAdapter<?> adapter;
public TimelineScrollListener(CustomListAdapter<?> adapter)
{
this.adapter = adapter;
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState)
{
adapter.setCanNotifyOnChange(false);
if (view.getFirstVisiblePosition() == 0 && view.getChildAt(0) != null && view.getChildAt(0).getTop() == 0)
{
if (scrollState == SCROLL_STATE_IDLE)
{
adapter.setCanNotifyOnChange(true);
int before = adapter.getCount();
adapter.notifyDataSetChanged();
int after = adapter.getCount();
int addCount = after - before;
((ListView) view).setSelectionFromTop(addCount, 0);
if (addCount > 0)
{
+ adapter.setCanNotifyOnChange(false);
Notificator.info(addCount + "件の新着があります");
}
}
}
}
}
| true | true | public void onScrollStateChanged(AbsListView view, int scrollState)
{
adapter.setCanNotifyOnChange(false);
if (view.getFirstVisiblePosition() == 0 && view.getChildAt(0) != null && view.getChildAt(0).getTop() == 0)
{
if (scrollState == SCROLL_STATE_IDLE)
{
adapter.setCanNotifyOnChange(true);
int before = adapter.getCount();
adapter.notifyDataSetChanged();
int after = adapter.getCount();
int addCount = after - before;
((ListView) view).setSelectionFromTop(addCount, 0);
if (addCount > 0)
{
Notificator.info(addCount + "件の新着があります");
}
}
}
}
| public void onScrollStateChanged(AbsListView view, int scrollState)
{
adapter.setCanNotifyOnChange(false);
if (view.getFirstVisiblePosition() == 0 && view.getChildAt(0) != null && view.getChildAt(0).getTop() == 0)
{
if (scrollState == SCROLL_STATE_IDLE)
{
adapter.setCanNotifyOnChange(true);
int before = adapter.getCount();
adapter.notifyDataSetChanged();
int after = adapter.getCount();
int addCount = after - before;
((ListView) view).setSelectionFromTop(addCount, 0);
if (addCount > 0)
{
adapter.setCanNotifyOnChange(false);
Notificator.info(addCount + "件の新着があります");
}
}
}
}
|
diff --git a/shell/core/src/main/java/org/crsh/command/CRaSHCommand.java b/shell/core/src/main/java/org/crsh/command/CRaSHCommand.java
index 5881fadb..4edab8f4 100644
--- a/shell/core/src/main/java/org/crsh/command/CRaSHCommand.java
+++ b/shell/core/src/main/java/org/crsh/command/CRaSHCommand.java
@@ -1,432 +1,432 @@
/*
* Copyright (C) 2012 eXo Platform SAS.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.crsh.command;
import org.crsh.SessionContext;
import org.crsh.cmdline.ClassDescriptor;
import org.crsh.cmdline.CommandCompletion;
import org.crsh.cmdline.CommandFactory;
import org.crsh.cmdline.Delimiter;
import org.crsh.cmdline.IntrospectionException;
import org.crsh.cmdline.annotations.Man;
import org.crsh.cmdline.annotations.Option;
import org.crsh.cmdline.OptionDescriptor;
import org.crsh.cmdline.ParameterDescriptor;
import org.crsh.cmdline.annotations.Usage;
import org.crsh.cmdline.matcher.ClassMatch;
import org.crsh.cmdline.matcher.CmdCompletionException;
import org.crsh.cmdline.matcher.CmdInvocationException;
import org.crsh.cmdline.matcher.CmdSyntaxException;
import org.crsh.cmdline.matcher.CommandMatch;
import org.crsh.cmdline.matcher.Matcher;
import org.crsh.cmdline.matcher.MethodMatch;
import org.crsh.cmdline.matcher.OptionMatch;
import org.crsh.cmdline.matcher.Resolver;
import org.crsh.cmdline.spi.Completer;
import org.crsh.cmdline.spi.ValueCompletion;
import org.crsh.io.ProducerContext;
import org.crsh.util.TypeResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
public abstract class CRaSHCommand extends GroovyCommand implements ShellCommand {
/** . */
private final Logger log = LoggerFactory.getLogger(getClass());
/** . */
private final ClassDescriptor<?> descriptor;
/** The unmatched text, only valid during an invocation. */
protected String unmatched;
/** . */
@Option(names = {"h","help"})
@Usage("command usage")
@Man("Provides command usage")
private boolean help;
protected CRaSHCommand() throws IntrospectionException {
this.descriptor = CommandFactory.create(getClass());
this.help = false;
this.unmatched = null;
}
/**
* Returns the command descriptor.
*
* @return the command descriptor
*/
public ClassDescriptor<?> getDescriptor() {
return descriptor;
}
protected final String readLine(String msg) {
return readLine(msg, true);
}
protected final String readLine(String msg, boolean echo) {
if (context instanceof InvocationContext) {
return ((InvocationContext)context).readLine(msg, echo);
} else {
throw new IllegalStateException("No current context of interaction with the term");
}
}
public final String getUnmatched() {
return unmatched;
}
public final CommandCompletion complete(SessionContext context, String line) {
// WTF
Matcher analyzer = descriptor.matcher("main");
//
Completer completer = this instanceof Completer ? (Completer)this : null;
//
try {
return analyzer.complete(completer, line);
}
catch (CmdCompletionException e) {
log.error("Error during completion of line " + line, e);
return new CommandCompletion(Delimiter.EMPTY, ValueCompletion.create());
}
}
public final String describe(String line, DescriptionFormat mode) {
// WTF
Matcher analyzer = descriptor.matcher("main");
//
CommandMatch match = analyzer.match(line);
//
try {
switch (mode) {
case DESCRIBE:
return match.getDescriptor().getUsage();
case MAN:
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
match.printMan(pw);
return sw.toString();
case USAGE:
StringWriter sw2 = new StringWriter();
PrintWriter pw2 = new PrintWriter(sw2);
match.printUsage(pw2);
return sw2.toString();
}
}
catch (IOException e) {
throw new AssertionError(e);
}
//
return null;
}
static ScriptException toScript(Throwable cause) {
if (cause instanceof ScriptException) {
return (ScriptException)cause;
} if (cause instanceof groovy.util.ScriptException) {
// Special handling for groovy.util.ScriptException
// which may be thrown by scripts because it is imported by default
// by groovy imports
String msg = cause.getMessage();
ScriptException translated;
if (msg != null) {
translated = new ScriptException(msg);
} else {
translated = new ScriptException();
}
translated.setStackTrace(cause.getStackTrace());
return translated;
} else {
return new ScriptException(cause);
}
}
public CommandInvoker<?, ?> resolveInvoker(String name, Map<String, ?> options, List<?> args) {
if (options.containsKey("h") || options.containsKey("help")) {
throw new UnsupportedOperationException("Implement me");
} else {
Matcher matcher = descriptor.matcher("main");
CommandMatch<CRaSHCommand, ?, ?> match = matcher.match(name, options, args);
return resolveInvoker(match);
}
}
public CommandInvoker<?, ?> resolveInvoker(String line) {
Matcher analyzer = descriptor.matcher("main");
final CommandMatch<CRaSHCommand, ?, ?> match = analyzer.match(line);
return resolveInvoker(match);
}
public final void eval(String s) throws ScriptException, IOException {
InvocationContext<?> context = peekContext();
CommandInvoker invoker = context.resolve(s);
invoker.open(context);
invoker.flush();
invoker.close();
}
public final CommandInvoker<?, ?> resolveInvoker(final CommandMatch<CRaSHCommand, ?, ?> match) {
if (match instanceof MethodMatch) {
//
final MethodMatch<CRaSHCommand> methodMatch = (MethodMatch<CRaSHCommand>)match;
//
boolean help = false;
for (OptionMatch optionMatch : methodMatch.getOwner().getOptionMatches()) {
ParameterDescriptor<?> parameterDesc = optionMatch.getParameter();
if (parameterDesc instanceof OptionDescriptor<?>) {
OptionDescriptor<?> optionDesc = (OptionDescriptor<?>)parameterDesc;
if (optionDesc.getNames().contains("h")) {
help = true;
}
}
}
final boolean doHelp = help;
//
Class consumedType;
Class producedType;
Method m = methodMatch.getDescriptor().getMethod();
if (PipeCommand.class.isAssignableFrom(m.getReturnType())) {
Type ret = m.getGenericReturnType();
consumedType = TypeResolver.resolveToClass(ret, PipeCommand.class, 0);
producedType = TypeResolver.resolveToClass(ret, PipeCommand.class, 1);
} else {
consumedType = Void.class;
producedType = Object.class;
Class<?>[] parameterTypes = m.getParameterTypes();
for (int i = 0;i < parameterTypes.length;i++) {
Class<?> parameterType = parameterTypes[i];
if (InvocationContext.class.isAssignableFrom(parameterType)) {
Type contextGenericParameterType = m.getGenericParameterTypes()[i];
producedType = TypeResolver.resolveToClass(contextGenericParameterType, InvocationContext.class, 0);
break;
}
}
}
final Class _consumedType = consumedType;
final Class _producedType = producedType;
if (doHelp) {
return new CommandInvoker<Object, Object>() {
public Class<Object> getProducedType() {
return _producedType;
}
public Class<Object> getConsumedType() {
return _consumedType;
}
public void open(ProducerContext<Object> context) {
try {
match.printUsage(new InvocationContextImpl(context).getWriter());
}
catch (IOException e) {
throw new AssertionError(e);
}
}
public void setPiped(boolean piped) {
}
public void provide(Object element) throws IOException {
}
public void flush() throws IOException {
}
public void close() {
}
};
} else {
if (consumedType == Void.class) {
return new CommandInvoker<Object, Object>() {
public Class<Object> getProducedType() {
return _producedType;
}
public Class<Object> getConsumedType() {
return _consumedType;
}
public void open(final ProducerContext<Object> context) {
//
pushContext(new InvocationContextImpl<Object>(context));
CRaSHCommand.this.unmatched = methodMatch.getRest();
final Resolver resolver = new Resolver() {
public <T> T resolve(Class<T> type) {
if (type.equals(InvocationContext.class)) {
return type.cast(peekContext());
} else {
return null;
}
}
};
//
Object o;
try {
o = methodMatch.invoke(resolver, CRaSHCommand.this);
} catch (CmdSyntaxException e) {
throw new SyntaxException(e.getMessage());
} catch (CmdInvocationException e) {
throw toScript(e.getCause());
}
if (o != null) {
peekContext().getWriter().print(o);
}
}
public void setPiped(boolean piped) {
}
public void provide(Object element) throws IOException {
// We just drop the elements
}
public void flush() throws IOException {
peekContext().flush();
}
public void close() {
CRaSHCommand.this.unmatched = null;
popContext();
}
};
} else {
return new CommandInvoker<Object, Object>() {
PipeCommand real;
boolean piped;
public Class<Object> getProducedType() {
return _producedType;
}
public Class<Object> getConsumedType() {
return _consumedType;
}
public void open(final ProducerContext<Object> context) {
//
- InvocationContextImpl<Object> invocationContext = new InvocationContextImpl<Object>(context);
+ final InvocationContextImpl<Object> invocationContext = new InvocationContextImpl<Object>(context);
//
pushContext(invocationContext);
CRaSHCommand.this.unmatched = methodMatch.getRest();
final Resolver resolver = new Resolver() {
public <T> T resolve(Class<T> type) {
if (type.equals(InvocationContext.class)) {
- return type.cast(context);
+ return type.cast(invocationContext);
} else {
return null;
}
}
};
try {
real = (PipeCommand)methodMatch.invoke(resolver, CRaSHCommand.this);
}
catch (CmdSyntaxException e) {
throw new SyntaxException(e.getMessage());
} catch (CmdInvocationException e) {
throw toScript(e.getCause());
}
//
real.setPiped(piped);
real.open(invocationContext);
}
public void setPiped(boolean piped) {
this.piped = piped;
}
public void close() {
popContext();
}
public void provide(Object element) throws IOException {
real.provide(element);
}
public void flush() throws IOException {
peekContext().flush();
}
};
}
}
} else if (match instanceof ClassMatch) {
//
final ClassMatch<?> classMatch = (ClassMatch)match;
//
boolean help = false;
for (OptionMatch optionMatch : classMatch.getOptionMatches()) {
ParameterDescriptor<?> parameterDesc = optionMatch.getParameter();
if (parameterDesc instanceof OptionDescriptor<?>) {
OptionDescriptor<?> optionDesc = (OptionDescriptor<?>)parameterDesc;
if (optionDesc.getNames().contains("h")) {
help = true;
}
}
}
final boolean doHelp = help;
//
return new CommandInvoker<Void, Object>() {
InvocationContext context;
public void open(ProducerContext<Object> producerContext) {
this.context = new InvocationContextImpl(producerContext);
try {
if (doHelp) {
match.printUsage(context.getWriter());
} else {
classMatch.printUsage(context.getWriter());
}
}
catch (IOException e) {
throw new AssertionError(e);
}
}
public void setPiped(boolean piped) {
}
public void close() {
this.context = null;
}
public void provide(Void element) throws IOException {
}
public void flush() throws IOException {
context.flush();
}
public Class<Object> getProducedType() {
return Object.class;
}
public Class<Void> getConsumedType() {
return Void.class;
}
};
} else {
return null;
}
}
}
| false | true | public final CommandInvoker<?, ?> resolveInvoker(final CommandMatch<CRaSHCommand, ?, ?> match) {
if (match instanceof MethodMatch) {
//
final MethodMatch<CRaSHCommand> methodMatch = (MethodMatch<CRaSHCommand>)match;
//
boolean help = false;
for (OptionMatch optionMatch : methodMatch.getOwner().getOptionMatches()) {
ParameterDescriptor<?> parameterDesc = optionMatch.getParameter();
if (parameterDesc instanceof OptionDescriptor<?>) {
OptionDescriptor<?> optionDesc = (OptionDescriptor<?>)parameterDesc;
if (optionDesc.getNames().contains("h")) {
help = true;
}
}
}
final boolean doHelp = help;
//
Class consumedType;
Class producedType;
Method m = methodMatch.getDescriptor().getMethod();
if (PipeCommand.class.isAssignableFrom(m.getReturnType())) {
Type ret = m.getGenericReturnType();
consumedType = TypeResolver.resolveToClass(ret, PipeCommand.class, 0);
producedType = TypeResolver.resolveToClass(ret, PipeCommand.class, 1);
} else {
consumedType = Void.class;
producedType = Object.class;
Class<?>[] parameterTypes = m.getParameterTypes();
for (int i = 0;i < parameterTypes.length;i++) {
Class<?> parameterType = parameterTypes[i];
if (InvocationContext.class.isAssignableFrom(parameterType)) {
Type contextGenericParameterType = m.getGenericParameterTypes()[i];
producedType = TypeResolver.resolveToClass(contextGenericParameterType, InvocationContext.class, 0);
break;
}
}
}
final Class _consumedType = consumedType;
final Class _producedType = producedType;
if (doHelp) {
return new CommandInvoker<Object, Object>() {
public Class<Object> getProducedType() {
return _producedType;
}
public Class<Object> getConsumedType() {
return _consumedType;
}
public void open(ProducerContext<Object> context) {
try {
match.printUsage(new InvocationContextImpl(context).getWriter());
}
catch (IOException e) {
throw new AssertionError(e);
}
}
public void setPiped(boolean piped) {
}
public void provide(Object element) throws IOException {
}
public void flush() throws IOException {
}
public void close() {
}
};
} else {
if (consumedType == Void.class) {
return new CommandInvoker<Object, Object>() {
public Class<Object> getProducedType() {
return _producedType;
}
public Class<Object> getConsumedType() {
return _consumedType;
}
public void open(final ProducerContext<Object> context) {
//
pushContext(new InvocationContextImpl<Object>(context));
CRaSHCommand.this.unmatched = methodMatch.getRest();
final Resolver resolver = new Resolver() {
public <T> T resolve(Class<T> type) {
if (type.equals(InvocationContext.class)) {
return type.cast(peekContext());
} else {
return null;
}
}
};
//
Object o;
try {
o = methodMatch.invoke(resolver, CRaSHCommand.this);
} catch (CmdSyntaxException e) {
throw new SyntaxException(e.getMessage());
} catch (CmdInvocationException e) {
throw toScript(e.getCause());
}
if (o != null) {
peekContext().getWriter().print(o);
}
}
public void setPiped(boolean piped) {
}
public void provide(Object element) throws IOException {
// We just drop the elements
}
public void flush() throws IOException {
peekContext().flush();
}
public void close() {
CRaSHCommand.this.unmatched = null;
popContext();
}
};
} else {
return new CommandInvoker<Object, Object>() {
PipeCommand real;
boolean piped;
public Class<Object> getProducedType() {
return _producedType;
}
public Class<Object> getConsumedType() {
return _consumedType;
}
public void open(final ProducerContext<Object> context) {
//
InvocationContextImpl<Object> invocationContext = new InvocationContextImpl<Object>(context);
//
pushContext(invocationContext);
CRaSHCommand.this.unmatched = methodMatch.getRest();
final Resolver resolver = new Resolver() {
public <T> T resolve(Class<T> type) {
if (type.equals(InvocationContext.class)) {
return type.cast(context);
} else {
return null;
}
}
};
try {
real = (PipeCommand)methodMatch.invoke(resolver, CRaSHCommand.this);
}
catch (CmdSyntaxException e) {
throw new SyntaxException(e.getMessage());
} catch (CmdInvocationException e) {
throw toScript(e.getCause());
}
//
real.setPiped(piped);
real.open(invocationContext);
}
public void setPiped(boolean piped) {
this.piped = piped;
}
public void close() {
popContext();
}
public void provide(Object element) throws IOException {
real.provide(element);
}
public void flush() throws IOException {
peekContext().flush();
}
};
}
}
} else if (match instanceof ClassMatch) {
//
final ClassMatch<?> classMatch = (ClassMatch)match;
//
boolean help = false;
for (OptionMatch optionMatch : classMatch.getOptionMatches()) {
ParameterDescriptor<?> parameterDesc = optionMatch.getParameter();
if (parameterDesc instanceof OptionDescriptor<?>) {
OptionDescriptor<?> optionDesc = (OptionDescriptor<?>)parameterDesc;
if (optionDesc.getNames().contains("h")) {
help = true;
}
}
}
final boolean doHelp = help;
//
return new CommandInvoker<Void, Object>() {
InvocationContext context;
public void open(ProducerContext<Object> producerContext) {
this.context = new InvocationContextImpl(producerContext);
try {
if (doHelp) {
match.printUsage(context.getWriter());
} else {
classMatch.printUsage(context.getWriter());
}
}
catch (IOException e) {
throw new AssertionError(e);
}
}
public void setPiped(boolean piped) {
}
public void close() {
this.context = null;
}
public void provide(Void element) throws IOException {
}
public void flush() throws IOException {
context.flush();
}
public Class<Object> getProducedType() {
return Object.class;
}
public Class<Void> getConsumedType() {
return Void.class;
}
};
} else {
return null;
}
}
| public final CommandInvoker<?, ?> resolveInvoker(final CommandMatch<CRaSHCommand, ?, ?> match) {
if (match instanceof MethodMatch) {
//
final MethodMatch<CRaSHCommand> methodMatch = (MethodMatch<CRaSHCommand>)match;
//
boolean help = false;
for (OptionMatch optionMatch : methodMatch.getOwner().getOptionMatches()) {
ParameterDescriptor<?> parameterDesc = optionMatch.getParameter();
if (parameterDesc instanceof OptionDescriptor<?>) {
OptionDescriptor<?> optionDesc = (OptionDescriptor<?>)parameterDesc;
if (optionDesc.getNames().contains("h")) {
help = true;
}
}
}
final boolean doHelp = help;
//
Class consumedType;
Class producedType;
Method m = methodMatch.getDescriptor().getMethod();
if (PipeCommand.class.isAssignableFrom(m.getReturnType())) {
Type ret = m.getGenericReturnType();
consumedType = TypeResolver.resolveToClass(ret, PipeCommand.class, 0);
producedType = TypeResolver.resolveToClass(ret, PipeCommand.class, 1);
} else {
consumedType = Void.class;
producedType = Object.class;
Class<?>[] parameterTypes = m.getParameterTypes();
for (int i = 0;i < parameterTypes.length;i++) {
Class<?> parameterType = parameterTypes[i];
if (InvocationContext.class.isAssignableFrom(parameterType)) {
Type contextGenericParameterType = m.getGenericParameterTypes()[i];
producedType = TypeResolver.resolveToClass(contextGenericParameterType, InvocationContext.class, 0);
break;
}
}
}
final Class _consumedType = consumedType;
final Class _producedType = producedType;
if (doHelp) {
return new CommandInvoker<Object, Object>() {
public Class<Object> getProducedType() {
return _producedType;
}
public Class<Object> getConsumedType() {
return _consumedType;
}
public void open(ProducerContext<Object> context) {
try {
match.printUsage(new InvocationContextImpl(context).getWriter());
}
catch (IOException e) {
throw new AssertionError(e);
}
}
public void setPiped(boolean piped) {
}
public void provide(Object element) throws IOException {
}
public void flush() throws IOException {
}
public void close() {
}
};
} else {
if (consumedType == Void.class) {
return new CommandInvoker<Object, Object>() {
public Class<Object> getProducedType() {
return _producedType;
}
public Class<Object> getConsumedType() {
return _consumedType;
}
public void open(final ProducerContext<Object> context) {
//
pushContext(new InvocationContextImpl<Object>(context));
CRaSHCommand.this.unmatched = methodMatch.getRest();
final Resolver resolver = new Resolver() {
public <T> T resolve(Class<T> type) {
if (type.equals(InvocationContext.class)) {
return type.cast(peekContext());
} else {
return null;
}
}
};
//
Object o;
try {
o = methodMatch.invoke(resolver, CRaSHCommand.this);
} catch (CmdSyntaxException e) {
throw new SyntaxException(e.getMessage());
} catch (CmdInvocationException e) {
throw toScript(e.getCause());
}
if (o != null) {
peekContext().getWriter().print(o);
}
}
public void setPiped(boolean piped) {
}
public void provide(Object element) throws IOException {
// We just drop the elements
}
public void flush() throws IOException {
peekContext().flush();
}
public void close() {
CRaSHCommand.this.unmatched = null;
popContext();
}
};
} else {
return new CommandInvoker<Object, Object>() {
PipeCommand real;
boolean piped;
public Class<Object> getProducedType() {
return _producedType;
}
public Class<Object> getConsumedType() {
return _consumedType;
}
public void open(final ProducerContext<Object> context) {
//
final InvocationContextImpl<Object> invocationContext = new InvocationContextImpl<Object>(context);
//
pushContext(invocationContext);
CRaSHCommand.this.unmatched = methodMatch.getRest();
final Resolver resolver = new Resolver() {
public <T> T resolve(Class<T> type) {
if (type.equals(InvocationContext.class)) {
return type.cast(invocationContext);
} else {
return null;
}
}
};
try {
real = (PipeCommand)methodMatch.invoke(resolver, CRaSHCommand.this);
}
catch (CmdSyntaxException e) {
throw new SyntaxException(e.getMessage());
} catch (CmdInvocationException e) {
throw toScript(e.getCause());
}
//
real.setPiped(piped);
real.open(invocationContext);
}
public void setPiped(boolean piped) {
this.piped = piped;
}
public void close() {
popContext();
}
public void provide(Object element) throws IOException {
real.provide(element);
}
public void flush() throws IOException {
peekContext().flush();
}
};
}
}
} else if (match instanceof ClassMatch) {
//
final ClassMatch<?> classMatch = (ClassMatch)match;
//
boolean help = false;
for (OptionMatch optionMatch : classMatch.getOptionMatches()) {
ParameterDescriptor<?> parameterDesc = optionMatch.getParameter();
if (parameterDesc instanceof OptionDescriptor<?>) {
OptionDescriptor<?> optionDesc = (OptionDescriptor<?>)parameterDesc;
if (optionDesc.getNames().contains("h")) {
help = true;
}
}
}
final boolean doHelp = help;
//
return new CommandInvoker<Void, Object>() {
InvocationContext context;
public void open(ProducerContext<Object> producerContext) {
this.context = new InvocationContextImpl(producerContext);
try {
if (doHelp) {
match.printUsage(context.getWriter());
} else {
classMatch.printUsage(context.getWriter());
}
}
catch (IOException e) {
throw new AssertionError(e);
}
}
public void setPiped(boolean piped) {
}
public void close() {
this.context = null;
}
public void provide(Void element) throws IOException {
}
public void flush() throws IOException {
context.flush();
}
public Class<Object> getProducedType() {
return Object.class;
}
public Class<Void> getConsumedType() {
return Void.class;
}
};
} else {
return null;
}
}
|
diff --git a/bundles/org.eclipse.rap.demo/src/org/eclipse/rap/demo/controls/ControlsDemo.java b/bundles/org.eclipse.rap.demo/src/org/eclipse/rap/demo/controls/ControlsDemo.java
index 0647a4b5a..c9e7ae432 100644
--- a/bundles/org.eclipse.rap.demo/src/org/eclipse/rap/demo/controls/ControlsDemo.java
+++ b/bundles/org.eclipse.rap.demo/src/org/eclipse/rap/demo/controls/ControlsDemo.java
@@ -1,102 +1,101 @@
/*******************************************************************************
* Copyright (c) 2002-2006 Innoopract Informationssysteme GmbH. 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: Innoopract Informationssysteme GmbH - initial API and
* implementation
******************************************************************************/
package org.eclipse.rap.demo.controls;
import org.eclipse.rwt.graphics.Graphics;
import org.eclipse.rwt.lifecycle.IEntryPoint;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.internal.graphics.FontSizeCalculator;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.*;
public class ControlsDemo implements IEntryPoint {
public Display createUI() {
Display display = new Display();
Shell shell = new Shell( display, SWT.TITLE | SWT.MAX | SWT.RESIZE );
shell.setBounds( 10, 10, 850, 600 );
createContent( shell );
shell.setText( "SWT Controls Demo" );
ClassLoader classLoader = getClass().getClassLoader();
Image image = Graphics.getImage( "resources/shell.gif", classLoader );
shell.setImage( image );
shell.layout();
shell.open();
return display;
}
private void createContent( final Composite parent ) {
parent.setLayout( new FillLayout() );
final CTabFolder topFolder = new CTabFolder( parent, SWT.TOP );
topFolder.marginWidth = 5;
topFolder.marginHeight = 5;
ensureMinTabHeight( topFolder );
Display display = parent.getDisplay();
Color selBg = display.getSystemColor( SWT.COLOR_LIST_SELECTION );
Color selFg = display.getSystemColor( SWT.COLOR_LIST_SELECTION_TEXT );
topFolder.setSelectionBackground( selBg );
topFolder.setSelectionForeground( selFg );
final ExampleTab[] tabs = new ExampleTab[] {
new ProgressBarTab( topFolder ),
new ButtonTab( topFolder ),
// new RequestTab( topFolder ),
new CBannerTab( topFolder ),
new CLabelTab( topFolder ),
new ComboTab( topFolder ),
new CompositeTab( topFolder ),
new CoolBarTab( topFolder ),
- new CustomControlTab( topFolder ),
new DialogsTab( topFolder ),
new GroupTab( topFolder ),
new LabelTab( topFolder ),
new ListTab( topFolder ),
new LinkTab( topFolder ),
new SashTab( topFolder ),
new SashFormTab( topFolder ),
new ShellTab( topFolder ),
new TabFolderTab( topFolder ),
// TODO [rh] bring back when layout problems are solved and demo tab is
// cleaned up
// new CTabFolderTab( topFolder ),
new TableTab( topFolder ),
new TableViewerTab( topFolder ),
new TextTab( topFolder ),
new TextSizeTab( topFolder ),
new SpinnerTab( topFolder ),
new ToolBarTab( topFolder ),
new TreeTab( topFolder ),
new BrowserTab( topFolder ),
new ContainmentTab( topFolder ),
new ZOrderTab( topFolder ),
new FocusTab( topFolder )
};
tabs[ 0 ].createContents();
topFolder.setSelection( 0 );
topFolder.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( final SelectionEvent evt ) {
int index = topFolder.getSelectionIndex();
tabs[ index ].createContents();
}
} );
}
private static void ensureMinTabHeight( final CTabFolder folder ) {
int result = FontSizeCalculator.getCharHeight( folder.getFont() );
if( result < 18 ) {
folder.setTabHeight( 18 );
}
}
}
| true | true | private void createContent( final Composite parent ) {
parent.setLayout( new FillLayout() );
final CTabFolder topFolder = new CTabFolder( parent, SWT.TOP );
topFolder.marginWidth = 5;
topFolder.marginHeight = 5;
ensureMinTabHeight( topFolder );
Display display = parent.getDisplay();
Color selBg = display.getSystemColor( SWT.COLOR_LIST_SELECTION );
Color selFg = display.getSystemColor( SWT.COLOR_LIST_SELECTION_TEXT );
topFolder.setSelectionBackground( selBg );
topFolder.setSelectionForeground( selFg );
final ExampleTab[] tabs = new ExampleTab[] {
new ProgressBarTab( topFolder ),
new ButtonTab( topFolder ),
// new RequestTab( topFolder ),
new CBannerTab( topFolder ),
new CLabelTab( topFolder ),
new ComboTab( topFolder ),
new CompositeTab( topFolder ),
new CoolBarTab( topFolder ),
new CustomControlTab( topFolder ),
new DialogsTab( topFolder ),
new GroupTab( topFolder ),
new LabelTab( topFolder ),
new ListTab( topFolder ),
new LinkTab( topFolder ),
new SashTab( topFolder ),
new SashFormTab( topFolder ),
new ShellTab( topFolder ),
new TabFolderTab( topFolder ),
// TODO [rh] bring back when layout problems are solved and demo tab is
// cleaned up
// new CTabFolderTab( topFolder ),
new TableTab( topFolder ),
new TableViewerTab( topFolder ),
new TextTab( topFolder ),
new TextSizeTab( topFolder ),
new SpinnerTab( topFolder ),
new ToolBarTab( topFolder ),
new TreeTab( topFolder ),
new BrowserTab( topFolder ),
new ContainmentTab( topFolder ),
new ZOrderTab( topFolder ),
new FocusTab( topFolder )
};
tabs[ 0 ].createContents();
topFolder.setSelection( 0 );
topFolder.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( final SelectionEvent evt ) {
int index = topFolder.getSelectionIndex();
tabs[ index ].createContents();
}
} );
}
| private void createContent( final Composite parent ) {
parent.setLayout( new FillLayout() );
final CTabFolder topFolder = new CTabFolder( parent, SWT.TOP );
topFolder.marginWidth = 5;
topFolder.marginHeight = 5;
ensureMinTabHeight( topFolder );
Display display = parent.getDisplay();
Color selBg = display.getSystemColor( SWT.COLOR_LIST_SELECTION );
Color selFg = display.getSystemColor( SWT.COLOR_LIST_SELECTION_TEXT );
topFolder.setSelectionBackground( selBg );
topFolder.setSelectionForeground( selFg );
final ExampleTab[] tabs = new ExampleTab[] {
new ProgressBarTab( topFolder ),
new ButtonTab( topFolder ),
// new RequestTab( topFolder ),
new CBannerTab( topFolder ),
new CLabelTab( topFolder ),
new ComboTab( topFolder ),
new CompositeTab( topFolder ),
new CoolBarTab( topFolder ),
new DialogsTab( topFolder ),
new GroupTab( topFolder ),
new LabelTab( topFolder ),
new ListTab( topFolder ),
new LinkTab( topFolder ),
new SashTab( topFolder ),
new SashFormTab( topFolder ),
new ShellTab( topFolder ),
new TabFolderTab( topFolder ),
// TODO [rh] bring back when layout problems are solved and demo tab is
// cleaned up
// new CTabFolderTab( topFolder ),
new TableTab( topFolder ),
new TableViewerTab( topFolder ),
new TextTab( topFolder ),
new TextSizeTab( topFolder ),
new SpinnerTab( topFolder ),
new ToolBarTab( topFolder ),
new TreeTab( topFolder ),
new BrowserTab( topFolder ),
new ContainmentTab( topFolder ),
new ZOrderTab( topFolder ),
new FocusTab( topFolder )
};
tabs[ 0 ].createContents();
topFolder.setSelection( 0 );
topFolder.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( final SelectionEvent evt ) {
int index = topFolder.getSelectionIndex();
tabs[ index ].createContents();
}
} );
}
|
diff --git a/MonitoringGae/src/main/java/cmg/org/monitor/app/schedule/MailServiceScheduler.java b/MonitoringGae/src/main/java/cmg/org/monitor/app/schedule/MailServiceScheduler.java
index 5e0ca52..bb5f208 100644
--- a/MonitoringGae/src/main/java/cmg/org/monitor/app/schedule/MailServiceScheduler.java
+++ b/MonitoringGae/src/main/java/cmg/org/monitor/app/schedule/MailServiceScheduler.java
@@ -1,170 +1,172 @@
package cmg.org.monitor.app.schedule;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cmg.org.monitor.dao.AlertDao;
import cmg.org.monitor.dao.MailMonitorDAO;
import cmg.org.monitor.dao.SystemDAO;
import cmg.org.monitor.dao.UtilityDAO;
import cmg.org.monitor.dao.impl.AlertDaoImpl;
import cmg.org.monitor.dao.impl.MailMonitorDaoImpl;
import cmg.org.monitor.dao.impl.SystemDaoImpl;
import cmg.org.monitor.dao.impl.UtilityDaoImpl;
import cmg.org.monitor.entity.shared.AlertMonitor;
import cmg.org.monitor.entity.shared.AlertStoreMonitor;
import cmg.org.monitor.entity.shared.MailConfigMonitor;
import cmg.org.monitor.entity.shared.NotifyMonitor;
import cmg.org.monitor.entity.shared.SystemMonitor;
import cmg.org.monitor.ext.model.shared.GroupMonitor;
import cmg.org.monitor.ext.model.shared.UserMonitor;
import cmg.org.monitor.ext.util.MonitorUtil;
import cmg.org.monitor.services.email.MailService;
import cmg.org.monitor.util.shared.MonitorConstant;
public class MailServiceScheduler extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -1934785013663672044L;
private static final Logger logger = Logger
.getLogger(MailServiceScheduler.class.getCanonicalName());
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
doPost(req, resp);
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
doSchedule();
}
public void doSchedule() {
// BEGIN LOG
long start = System.currentTimeMillis();
logger.log(Level.INFO, MonitorUtil.parseTime(start, true)
+ " -> START: Scheduled send alert mail ...");
// BEGIN LOG
String alertName = MonitorConstant.ALERTSTORE_DEFAULT_NAME + ": "
+ MonitorUtil.parseTime(start, false);
SystemDAO sysDAO = new SystemDaoImpl();
AlertDao alertDAO = new AlertDaoImpl();
ArrayList<SystemMonitor> systems = sysDAO
.listSystemsFromMemcache(false);
MailService mailService = new MailService();
MailMonitorDAO mailDAO = new MailMonitorDaoImpl();
UtilityDAO utilDAO = new UtilityDaoImpl();
if (systems != null && systems.size() > 0) {
ArrayList<UserMonitor> listUsers = utilDAO.listAllUsers();
for (int i = 0; i < listUsers.size(); i++) {
UserMonitor user = listUsers.get(i);
ArrayList<GroupMonitor> groups = user.getGroups();
for (int j = 0; j < groups.size(); j++) {
for (int k = 0; k < systems.size(); k++) {
SystemMonitor sys = systems.get(k);
String groupName = sys.getGroupEmail();
if (groupName.equals(groups.get(j).getName())) {
user.addSystem(sys);
}
}
}
}
for (int i = 0; i < listUsers.size(); i++) {
UserMonitor user = listUsers.get(i);
ArrayList<SystemMonitor> allSystem = listUsers.get(i)
.getSystems();
if (allSystem != null) {
for (int j = 0; j < allSystem.size(); j++) {
SystemMonitor tempSys = allSystem.get(j);
AlertStoreMonitor alertstore = alertDAO
.getLastestAlertStore(tempSys);
if (alertstore != null) {
alertstore.setName(alertName);
alertstore.setTimeStamp(new Date(start));
NotifyMonitor notify = null;
try {
notify = sysDAO.getNotifyOption(tempSys
.getCode());
- } catch (Exception e) {
+ } catch (Exception e) {
+ }
+ if (notify == null) {
notify = new NotifyMonitor();
}
alertstore.fixAlertList(notify);
if (alertstore.getAlerts().size() > 0) {
user.addAlertStore(alertstore);
}
}
}
}
}
if (listUsers != null && listUsers.size() > 0) {
for (int i = 0; i < listUsers.size(); i++) {
UserMonitor user = listUsers.get(i);
if (user.getStores() != null && user.getStores().size() > 0) {
MailConfigMonitor config = mailDAO.getMailConfig(user
.getId());
try {
String content = MailService.parseContent(
user.getStores(), config);
mailService.sendMail(alertName, content, config);
logger.log(Level.INFO, "send mail" + content);
} catch (Exception e) {
logger.log(Level.INFO, "Can not send mail"
+ e.getMessage().toString());
}
}
}
for (SystemMonitor sys : systems) {
AlertStoreMonitor store = alertDAO
.getLastestAlertStore(sys);
alertDAO.putAlertStore(store);
alertDAO.clearTempStore(sys);
}
}
for (SystemMonitor sys : systems) {
AlertStoreMonitor asm = alertDAO.getLastestAlertStore(sys);
if (asm == null) {
asm = new AlertStoreMonitor();
}
asm.setCpuUsage(sys.getLastestCpuUsage());
asm.setMemUsage(sys.getLastestMemoryUsage());
asm.setSysId(sys.getId());
asm.setName(alertName);
asm.setTimeStamp(new Date(start));
alertDAO.putAlertStore(asm);
alertDAO.clearTempStore(sys);
}
} else {
logger.log(Level.INFO, "NO SYSTEM FOUND");
}
/*
* mailDAO.getMailConfig(maiId); mailService.sendMail(subject, content,
* mailConfig);
*/
// END LOG
long end = System.currentTimeMillis();
long time = end - start;
logger.log(Level.INFO, MonitorUtil.parseTime(end, true)
+ " -> END: Scheduled send alert mail. Time executed: " + time
+ " ms");
// END LOG
}
}
| true | true | public void doSchedule() {
// BEGIN LOG
long start = System.currentTimeMillis();
logger.log(Level.INFO, MonitorUtil.parseTime(start, true)
+ " -> START: Scheduled send alert mail ...");
// BEGIN LOG
String alertName = MonitorConstant.ALERTSTORE_DEFAULT_NAME + ": "
+ MonitorUtil.parseTime(start, false);
SystemDAO sysDAO = new SystemDaoImpl();
AlertDao alertDAO = new AlertDaoImpl();
ArrayList<SystemMonitor> systems = sysDAO
.listSystemsFromMemcache(false);
MailService mailService = new MailService();
MailMonitorDAO mailDAO = new MailMonitorDaoImpl();
UtilityDAO utilDAO = new UtilityDaoImpl();
if (systems != null && systems.size() > 0) {
ArrayList<UserMonitor> listUsers = utilDAO.listAllUsers();
for (int i = 0; i < listUsers.size(); i++) {
UserMonitor user = listUsers.get(i);
ArrayList<GroupMonitor> groups = user.getGroups();
for (int j = 0; j < groups.size(); j++) {
for (int k = 0; k < systems.size(); k++) {
SystemMonitor sys = systems.get(k);
String groupName = sys.getGroupEmail();
if (groupName.equals(groups.get(j).getName())) {
user.addSystem(sys);
}
}
}
}
for (int i = 0; i < listUsers.size(); i++) {
UserMonitor user = listUsers.get(i);
ArrayList<SystemMonitor> allSystem = listUsers.get(i)
.getSystems();
if (allSystem != null) {
for (int j = 0; j < allSystem.size(); j++) {
SystemMonitor tempSys = allSystem.get(j);
AlertStoreMonitor alertstore = alertDAO
.getLastestAlertStore(tempSys);
if (alertstore != null) {
alertstore.setName(alertName);
alertstore.setTimeStamp(new Date(start));
NotifyMonitor notify = null;
try {
notify = sysDAO.getNotifyOption(tempSys
.getCode());
} catch (Exception e) {
notify = new NotifyMonitor();
}
alertstore.fixAlertList(notify);
if (alertstore.getAlerts().size() > 0) {
user.addAlertStore(alertstore);
}
}
}
}
}
if (listUsers != null && listUsers.size() > 0) {
for (int i = 0; i < listUsers.size(); i++) {
UserMonitor user = listUsers.get(i);
if (user.getStores() != null && user.getStores().size() > 0) {
MailConfigMonitor config = mailDAO.getMailConfig(user
.getId());
try {
String content = MailService.parseContent(
user.getStores(), config);
mailService.sendMail(alertName, content, config);
logger.log(Level.INFO, "send mail" + content);
} catch (Exception e) {
logger.log(Level.INFO, "Can not send mail"
+ e.getMessage().toString());
}
}
}
for (SystemMonitor sys : systems) {
AlertStoreMonitor store = alertDAO
.getLastestAlertStore(sys);
alertDAO.putAlertStore(store);
alertDAO.clearTempStore(sys);
}
}
for (SystemMonitor sys : systems) {
AlertStoreMonitor asm = alertDAO.getLastestAlertStore(sys);
if (asm == null) {
asm = new AlertStoreMonitor();
}
asm.setCpuUsage(sys.getLastestCpuUsage());
asm.setMemUsage(sys.getLastestMemoryUsage());
asm.setSysId(sys.getId());
asm.setName(alertName);
asm.setTimeStamp(new Date(start));
alertDAO.putAlertStore(asm);
alertDAO.clearTempStore(sys);
}
} else {
logger.log(Level.INFO, "NO SYSTEM FOUND");
}
/*
* mailDAO.getMailConfig(maiId); mailService.sendMail(subject, content,
* mailConfig);
*/
// END LOG
long end = System.currentTimeMillis();
long time = end - start;
logger.log(Level.INFO, MonitorUtil.parseTime(end, true)
+ " -> END: Scheduled send alert mail. Time executed: " + time
+ " ms");
// END LOG
}
| public void doSchedule() {
// BEGIN LOG
long start = System.currentTimeMillis();
logger.log(Level.INFO, MonitorUtil.parseTime(start, true)
+ " -> START: Scheduled send alert mail ...");
// BEGIN LOG
String alertName = MonitorConstant.ALERTSTORE_DEFAULT_NAME + ": "
+ MonitorUtil.parseTime(start, false);
SystemDAO sysDAO = new SystemDaoImpl();
AlertDao alertDAO = new AlertDaoImpl();
ArrayList<SystemMonitor> systems = sysDAO
.listSystemsFromMemcache(false);
MailService mailService = new MailService();
MailMonitorDAO mailDAO = new MailMonitorDaoImpl();
UtilityDAO utilDAO = new UtilityDaoImpl();
if (systems != null && systems.size() > 0) {
ArrayList<UserMonitor> listUsers = utilDAO.listAllUsers();
for (int i = 0; i < listUsers.size(); i++) {
UserMonitor user = listUsers.get(i);
ArrayList<GroupMonitor> groups = user.getGroups();
for (int j = 0; j < groups.size(); j++) {
for (int k = 0; k < systems.size(); k++) {
SystemMonitor sys = systems.get(k);
String groupName = sys.getGroupEmail();
if (groupName.equals(groups.get(j).getName())) {
user.addSystem(sys);
}
}
}
}
for (int i = 0; i < listUsers.size(); i++) {
UserMonitor user = listUsers.get(i);
ArrayList<SystemMonitor> allSystem = listUsers.get(i)
.getSystems();
if (allSystem != null) {
for (int j = 0; j < allSystem.size(); j++) {
SystemMonitor tempSys = allSystem.get(j);
AlertStoreMonitor alertstore = alertDAO
.getLastestAlertStore(tempSys);
if (alertstore != null) {
alertstore.setName(alertName);
alertstore.setTimeStamp(new Date(start));
NotifyMonitor notify = null;
try {
notify = sysDAO.getNotifyOption(tempSys
.getCode());
} catch (Exception e) {
}
if (notify == null) {
notify = new NotifyMonitor();
}
alertstore.fixAlertList(notify);
if (alertstore.getAlerts().size() > 0) {
user.addAlertStore(alertstore);
}
}
}
}
}
if (listUsers != null && listUsers.size() > 0) {
for (int i = 0; i < listUsers.size(); i++) {
UserMonitor user = listUsers.get(i);
if (user.getStores() != null && user.getStores().size() > 0) {
MailConfigMonitor config = mailDAO.getMailConfig(user
.getId());
try {
String content = MailService.parseContent(
user.getStores(), config);
mailService.sendMail(alertName, content, config);
logger.log(Level.INFO, "send mail" + content);
} catch (Exception e) {
logger.log(Level.INFO, "Can not send mail"
+ e.getMessage().toString());
}
}
}
for (SystemMonitor sys : systems) {
AlertStoreMonitor store = alertDAO
.getLastestAlertStore(sys);
alertDAO.putAlertStore(store);
alertDAO.clearTempStore(sys);
}
}
for (SystemMonitor sys : systems) {
AlertStoreMonitor asm = alertDAO.getLastestAlertStore(sys);
if (asm == null) {
asm = new AlertStoreMonitor();
}
asm.setCpuUsage(sys.getLastestCpuUsage());
asm.setMemUsage(sys.getLastestMemoryUsage());
asm.setSysId(sys.getId());
asm.setName(alertName);
asm.setTimeStamp(new Date(start));
alertDAO.putAlertStore(asm);
alertDAO.clearTempStore(sys);
}
} else {
logger.log(Level.INFO, "NO SYSTEM FOUND");
}
/*
* mailDAO.getMailConfig(maiId); mailService.sendMail(subject, content,
* mailConfig);
*/
// END LOG
long end = System.currentTimeMillis();
long time = end - start;
logger.log(Level.INFO, MonitorUtil.parseTime(end, true)
+ " -> END: Scheduled send alert mail. Time executed: " + time
+ " ms");
// END LOG
}
|
diff --git a/test/src/net/sf/freecol/common/model/AllTests.java b/test/src/net/sf/freecol/common/model/AllTests.java
index dba23c522..d1f205153 100644
--- a/test/src/net/sf/freecol/common/model/AllTests.java
+++ b/test/src/net/sf/freecol/common/model/AllTests.java
@@ -1,33 +1,32 @@
package net.sf.freecol.common.model;
import junit.framework.Test;
import junit.framework.TestSuite;
public class AllTests {
public static final String COPYRIGHT = "Copyright (C) 2003-2007 The FreeCol Team";
public static final String LICENSE = "http://www.gnu.org/licenses/gpl.html";
public static final String REVISION = "$Revision$";
public static Test suite() {
TestSuite suite = new TestSuite("Test for net.sf.freecol.common");
//$JUnit-BEGIN$
suite.addTestSuite(BuildingTest.class);
suite.addTestSuite(SchoolTest.class);
suite.addTestSuite(GoodsTest.class);
suite.addTestSuite(GameTest.class);
suite.addTestSuite(MapTest.class);
suite.addTestSuite(TileTest.class);
suite.addTestSuite(ColonyProductionTest.class);
- suite.addTest(AllTests.suite());
suite.addTestSuite(UnitTest.class);
suite.addTestSuite(ModelMessageTest.class);
suite.addTestSuite(PlayerTest.class);
suite.addTestSuite(NationTypeTest.class);
//$JUnit-END$
return suite;
}
}
| true | true | public static Test suite() {
TestSuite suite = new TestSuite("Test for net.sf.freecol.common");
//$JUnit-BEGIN$
suite.addTestSuite(BuildingTest.class);
suite.addTestSuite(SchoolTest.class);
suite.addTestSuite(GoodsTest.class);
suite.addTestSuite(GameTest.class);
suite.addTestSuite(MapTest.class);
suite.addTestSuite(TileTest.class);
suite.addTestSuite(ColonyProductionTest.class);
suite.addTest(AllTests.suite());
suite.addTestSuite(UnitTest.class);
suite.addTestSuite(ModelMessageTest.class);
suite.addTestSuite(PlayerTest.class);
suite.addTestSuite(NationTypeTest.class);
//$JUnit-END$
return suite;
}
| public static Test suite() {
TestSuite suite = new TestSuite("Test for net.sf.freecol.common");
//$JUnit-BEGIN$
suite.addTestSuite(BuildingTest.class);
suite.addTestSuite(SchoolTest.class);
suite.addTestSuite(GoodsTest.class);
suite.addTestSuite(GameTest.class);
suite.addTestSuite(MapTest.class);
suite.addTestSuite(TileTest.class);
suite.addTestSuite(ColonyProductionTest.class);
suite.addTestSuite(UnitTest.class);
suite.addTestSuite(ModelMessageTest.class);
suite.addTestSuite(PlayerTest.class);
suite.addTestSuite(NationTypeTest.class);
//$JUnit-END$
return suite;
}
|
diff --git a/source/com/mucommander/ui/dnd/ClipboardNotifier.java b/source/com/mucommander/ui/dnd/ClipboardNotifier.java
index 419d14fe..f9c6fb98 100644
--- a/source/com/mucommander/ui/dnd/ClipboardNotifier.java
+++ b/source/com/mucommander/ui/dnd/ClipboardNotifier.java
@@ -1,80 +1,80 @@
/*
* This file is part of muCommander, http://www.mucommander.com
* Copyright (C) 2002-2009 Maxence Bernard
*
* muCommander 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.
*
* muCommander is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mucommander.ui.dnd;
import com.mucommander.Debug;
import javax.swing.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.FlavorEvent;
import java.awt.datatransfer.FlavorListener;
/**
* ClipboardNotifier allows an action to be dynamically enabled when the clipboard contains files, and disabled otherwise.
*
* <p>ClipboardNotifier requires Java 1.5 and does not work under Mac OS X (tested under Tiger with Java 1.5.0_06).
*
* @author Maxence Bernard
*/
public class ClipboardNotifier implements FlavorListener {
/** The action to dynamically enable/disable */
private Action action;
/**
* Starts monitoring the clipboard for files and dynamically enable/disable the specified action accordingly.
* The action is initially enabled if the clipboard contains files.
*
* @param action the action to dynamically enable/disable when files are present/not present
*/
public ClipboardNotifier(Action action) {
this.action = action;
// Toggle initial state
toggleActionState();
// Monitor clipboard changes
ClipboardSupport.getClipboard().addFlavorListener(this);
}
/**
* Toggle the action depending on the clipboard contents.
*/
private void toggleActionState() {
try {
action.setEnabled(ClipboardSupport.getClipboard().isDataFlavorAvailable(DataFlavor.javaFileListFlavor));
}
catch(Exception e) {
- // Works around "java.lang.IllegalStateException: cannot open system clipboard" thrown without
- // an apparent reason (ticket #164).
+ // Works around "java.lang.IllegalStateException: cannot open system clipboard" thrown when the clipboard
+ // is currently unavailable (ticket #164).
if(Debug.ON)
Debug.trace("Caught an exception while querying the clipboard for files: "+ e);
}
}
///////////////////////////////////
// FlavorListener implementation //
///////////////////////////////////
public void flavorsChanged(FlavorEvent event) {
toggleActionState();
}
}
| true | true | private void toggleActionState() {
try {
action.setEnabled(ClipboardSupport.getClipboard().isDataFlavorAvailable(DataFlavor.javaFileListFlavor));
}
catch(Exception e) {
// Works around "java.lang.IllegalStateException: cannot open system clipboard" thrown without
// an apparent reason (ticket #164).
if(Debug.ON)
Debug.trace("Caught an exception while querying the clipboard for files: "+ e);
}
}
| private void toggleActionState() {
try {
action.setEnabled(ClipboardSupport.getClipboard().isDataFlavorAvailable(DataFlavor.javaFileListFlavor));
}
catch(Exception e) {
// Works around "java.lang.IllegalStateException: cannot open system clipboard" thrown when the clipboard
// is currently unavailable (ticket #164).
if(Debug.ON)
Debug.trace("Caught an exception while querying the clipboard for files: "+ e);
}
}
|
diff --git a/brut.apktool/apktool-lib/src/main/java/brut/androlib/src/SmaliDecoder.java b/brut.apktool/apktool-lib/src/main/java/brut/androlib/src/SmaliDecoder.java
index 134fb88..98ed63e 100644
--- a/brut.apktool/apktool-lib/src/main/java/brut/androlib/src/SmaliDecoder.java
+++ b/brut.apktool/apktool-lib/src/main/java/brut/androlib/src/SmaliDecoder.java
@@ -1,62 +1,62 @@
/**
* Copyright 2011 Ryszard Wiśniewski <[email protected]>
*
* 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 brut.androlib.src;
import brut.androlib.AndrolibException;
import java.io.File;
import java.io.IOException;
import org.jf.baksmali.baksmali;
import org.jf.baksmali.main;
import org.jf.dexlib.Code.Analysis.ClassPath;
import org.jf.dexlib.DexFile;
/**
* @author Ryszard Wiśniewski <[email protected]>
*/
public class SmaliDecoder {
public static void decode(File apkFile, File outDir, boolean debug, boolean bakdeb)
throws AndrolibException {
new SmaliDecoder(apkFile, outDir, debug, bakdeb).decode();
}
private SmaliDecoder(File apkFile, File outDir, boolean debug, boolean bakdeb) {
mApkFile = apkFile;
mOutDir = outDir;
mDebug = debug;
mBakDeb = bakdeb;
}
private void decode() throws AndrolibException {
if (mDebug) {
ClassPath.dontLoadClassPath = true;
}
try {
baksmali.disassembleDexFile(mApkFile.getAbsolutePath(),
new DexFile(mApkFile), false, mOutDir.getAbsolutePath(), null,
null, null, false, true, true, mBakDeb, false, false,
- mDebug ? main.DIFFPRE: 0, false, false, null);
+ mDebug ? main.DIFFPRE: 0, false, false, null, false);
} catch (IOException ex) {
throw new AndrolibException(ex);
}
}
private final File mApkFile;
private final File mOutDir;
private final boolean mDebug;
private final boolean mBakDeb;
}
| true | true | private void decode() throws AndrolibException {
if (mDebug) {
ClassPath.dontLoadClassPath = true;
}
try {
baksmali.disassembleDexFile(mApkFile.getAbsolutePath(),
new DexFile(mApkFile), false, mOutDir.getAbsolutePath(), null,
null, null, false, true, true, mBakDeb, false, false,
mDebug ? main.DIFFPRE: 0, false, false, null);
} catch (IOException ex) {
throw new AndrolibException(ex);
}
}
| private void decode() throws AndrolibException {
if (mDebug) {
ClassPath.dontLoadClassPath = true;
}
try {
baksmali.disassembleDexFile(mApkFile.getAbsolutePath(),
new DexFile(mApkFile), false, mOutDir.getAbsolutePath(), null,
null, null, false, true, true, mBakDeb, false, false,
mDebug ? main.DIFFPRE: 0, false, false, null, false);
} catch (IOException ex) {
throw new AndrolibException(ex);
}
}
|
diff --git a/src/main/java/org/vivoweb/harvester/fetch/JDBCFetch.java b/src/main/java/org/vivoweb/harvester/fetch/JDBCFetch.java
index 5fdab63c..4fc61164 100644
--- a/src/main/java/org/vivoweb/harvester/fetch/JDBCFetch.java
+++ b/src/main/java/org/vivoweb/harvester/fetch/JDBCFetch.java
@@ -1,816 +1,826 @@
/*******************************************************************************
* Copyright (c) 2010-2011 VIVO Harvester Team. For full list of contributors, please see the AUTHORS file provided.
* All rights reserved.
* This program and the accompanying materials are made available under the terms of the new BSD license which accompanies this distribution, and is available at http://www.opensource.org/licenses/bsd-license.html
******************************************************************************/
package org.vivoweb.harvester.fetch;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vivoweb.harvester.util.InitLog;
import org.vivoweb.harvester.util.SpecialEntities;
import org.vivoweb.harvester.util.args.ArgDef;
import org.vivoweb.harvester.util.args.ArgList;
import org.vivoweb.harvester.util.args.ArgParser;
import org.vivoweb.harvester.util.args.UsageException;
import org.vivoweb.harvester.util.repo.RecordHandler;
/**
* Fetches rdf data from a JDBC database placing the data in the supplied record handler.
* @author Christopher Haines ([email protected])
*/
public class JDBCFetch {
/**
* SLF4J Logger
*/
private static Logger log = LoggerFactory.getLogger(JDBCFetch.class);
/**
* Record Handler to write records to
*/
private RecordHandler rh;
/**
* Statement processor for the database
*/
private Statement cursor;
/**
* Mapping of tablename to idField name
*/
private Map<String, List<String>> idFields = null;
/**
* Mapping of tablename to mapping of fieldname to tablename
*/
private Map<String, Map<String, String>> fkRelations = null;
/**
* Mapping of tablename to list of datafields
*/
private Map<String, List<String>> dataFields = null;
/**
* Set of table names
*/
private Set<String> tableNames = null;
/**
* List of conditions
*/
private Map<String, List<String>> whereClauses;
/**
* Mapping of extra tables for the from section
*/
private Map<String, String> fromClauses;
/**
* Namespace for RDF made from this database
*/
private String uriNS;
/**
* Prefix each field in query with this
*/
private String queryPre;
/**
* Suffix each field in query with this
*/
private String querySuf;
/**
* The user defined SQL Query string
*/
private Map<String, String> queryStrings;
/**
* accepted table types
*/
private String[] tableTypes;
/**
* Constructor
* @param dbConn connection to the database
* @param output RecordHandler to write data to
* @param uriNameSpace namespace base for rdf records
* @throws IOException error talking with database
*/
public JDBCFetch(Connection dbConn, RecordHandler output, String uriNameSpace) throws IOException {
this(dbConn, output, uriNameSpace, null, null, null, null, null, null, null, null, null);
}
/**
* Constructor
* @param driverClass the jdbc driver
* @param connLine the jdbc connection line
* @param username the username
* @param password the password
* @param output RecordHandler to write data to
* @param uriNameSpace namespace base for rdf records
* @throws IOException error talking with database
*/
public JDBCFetch(String driverClass, String connLine, String username, String password, RecordHandler output, String uriNameSpace) throws IOException {
this(driverClass, connLine, username, password, output, uriNameSpace, null, null, null, null, null, null, null, null, null);
}
/**
* Command line Constructor
* @param args commandline arguments
* @throws IOException error creating task
* @throws UsageException user requested usage message
*/
private JDBCFetch(String[] args) throws IOException, UsageException {
this(getParser().parse(args));
}
/**
* Arglist Constructor
* @param args option set of parsed args
* @throws IOException error creating task
*/
private JDBCFetch(ArgList args) throws IOException {
this(
args.get("d"),
args.get("c"),
args.get("u"),
args.get("p"),
RecordHandler.parseConfig(args.get("o"), args.getValueMap("O")),
(args.has("n")?args.get("n"):(args.get("c")+"/")),
args.get("delimiterPrefix"),
args.get("delimiterSuffix"),
new TreeSet<String>(args.getAll("t")),
(args.has("T")?args.getValueMap("T"):null),
(args.has("F")?splitCommaList(args.getValueMap("F")):null),
(args.has("I")?splitCommaList(args.getValueMap("I")):null),
(args.has("W")?splitCommaList(args.getValueMap("W")):null),
(args.has("R")?splitTildeMap(args.getValueMap("R")):null),
(args.has("Q")?args.getValueMap("Q"):null),
args.getAll("v").toArray(new String[]{})
);
}
/**
* Library style Constructor
* @param dbConn The database Connection
* @param rh Record Handler to write records to
* @param uriNS the uri namespace to use
* @param queryPre Query prefix often "["
* @param querySuf Query suffix often "]"
* @param tableNames set of the table names
* @param fromClauses Mapping of extra tables for the from section
* @param dataFields Mapping of tablename to list of datafields
* @param idFields Mapping of tablename to idField name
* @param whereClauses List of conditions
* @param relations Mapping of tablename to mapping of fieldname to tablename
* @param queryStrings Mapping of tablename to query
* @param tableTypes accepted table types
* @throws IOException error accessing database
*/
public JDBCFetch(Connection dbConn, RecordHandler rh, String uriNS, String queryPre, String querySuf, Set<String> tableNames, Map<String, String> fromClauses, Map<String, List<String>> dataFields, Map<String, List<String>> idFields, Map<String, List<String>> whereClauses, Map<String, Map<String, String>> relations, Map<String, String> queryStrings, String... tableTypes) throws IOException {
try {
this.cursor = dbConn.createStatement();
} catch(SQLException e) {
throw new IOException(e);
}
this.rh = rh;
Set<String> argTables = tableNames;
this.fromClauses = fromClauses;
this.dataFields = dataFields;
this.idFields = idFields;
this.whereClauses = whereClauses;
this.fkRelations = relations;
this.uriNS = uriNS;
this.queryPre = queryPre;
this.querySuf = querySuf;
this.queryStrings = queryStrings;
if(tableTypes.length > 0 && tableTypes[0] != null) {
this.tableTypes = tableTypes;
for(int x=0; x<this.tableTypes.length; x++) {
this.tableTypes[x] = this.tableTypes[x].toUpperCase();
}
} else {
this.tableTypes = new String[]{"TABLE"};
}
if(this.rh == null) {
throw new IllegalArgumentException("Must provide output recordhandler!");
}
if(argTables == null) {
argTables = new TreeSet<String>();
}
if(this.fromClauses != null) {
argTables.addAll(this.fromClauses.keySet());
}
if(this.dataFields != null) {
argTables.addAll(this.dataFields.keySet());
}
if(this.idFields != null) {
argTables.addAll(this.idFields.keySet());
}
if(this.whereClauses != null) {
argTables.addAll(this.whereClauses.keySet());
}
if(this.fkRelations != null) {
argTables.addAll(this.fkRelations.keySet());
}
if(this.queryStrings != null) {
// tablenames for queries are arbitrary
argTables.removeAll(this.queryStrings.keySet());
}
this.tableNames = new TreeSet<String>();
try {
this.tableNames = getTableNames();
} catch(SQLException e) {
throw new IOException(e);
}
Set<String> realDBTables = this.tableNames;
this.tableNames = new TreeSet<String>();
//TODO: this is required as getTableNames loads data in and we want this to be a fresh start
// there should be a nicer way to do all of this, as this is very hacky at the moment
for(String argTable : argTables) {
boolean found = false;
for(String realTableName : realDBTables) {
realTableName = realTableName.trim();
if(argTable.trim().equalsIgnoreCase(realTableName)) {
this.tableNames.add(realTableName);
// fix the tablename in all the other structures >.>
if(this.fromClauses != null) {
Map<String, String> tempMap = new HashMap<String, String>();
for(String fromClausesTable : this.fromClauses.keySet()) {
if(fromClausesTable.trim().equalsIgnoreCase(realTableName)) {
tempMap.put(realTableName, this.fromClauses.get(fromClausesTable));
+ } else {
+ tempMap.put(fromClausesTable, this.fromClauses.get(fromClausesTable));
}
}
this.fromClauses = tempMap;
}
if(this.dataFields != null) {
Map<String, List<String>> tempMap = this.dataFields;
for(String dataFieldsTable : this.dataFields.keySet()) {
if(dataFieldsTable.trim().equalsIgnoreCase(realTableName)) {
tempMap.put(realTableName, this.dataFields.get(dataFieldsTable));
+ } else {
+ tempMap.put(dataFieldsTable, this.dataFields.get(dataFieldsTable));
}
}
this.dataFields = tempMap;
}
if(this.idFields != null) {
Map<String, List<String>> tempMap = this.idFields;
for(String idFieldsTable : this.idFields.keySet()) {
if(idFieldsTable.trim().equalsIgnoreCase(realTableName)) {
tempMap.put(realTableName, this.idFields.get(idFieldsTable));
+ } else {
+ tempMap.put(idFieldsTable, this.idFields.get(idFieldsTable));
}
}
this.idFields = tempMap;
}
if(this.whereClauses != null) {
Map<String, List<String>> tempMap = this.whereClauses;
for(String whereClausesTable : this.whereClauses.keySet()) {
if(whereClausesTable.trim().equalsIgnoreCase(realTableName)) {
tempMap.put(realTableName, this.whereClauses.get(whereClausesTable));
+ } else {
+ tempMap.put(whereClausesTable, this.whereClauses.get(whereClausesTable));
}
}
this.whereClauses = tempMap;
}
if(this.fkRelations != null) {
Map<String, Map<String, String>> tempMap = this.fkRelations;
for(String fkRelationsTable : this.fkRelations.keySet()) {
if(fkRelationsTable.trim().equalsIgnoreCase(realTableName)) {
tempMap.put(realTableName, this.fkRelations.get(fkRelationsTable));
+ } else {
+ tempMap.put(fkRelationsTable, this.fkRelations.get(fkRelationsTable));
}
}
this.fkRelations = tempMap;
}
found = true;
break;
}
}
if(!found) {
throw new IllegalArgumentException("Database Does Not Contain A Table Named '"+argTable+"'");
}
}
if(this.queryStrings != null) {
this.tableNames.addAll(this.queryStrings.keySet());
}
}
/**
* Library style Constructor
* @param driverClass the jdbc driver
* @param connLine the jdbc connection line
* @param username the username
* @param password the password
* @param rh Record Handler to write records to
* @param uriNS the uri namespace to use
* @param queryPre Query prefix often "["
* @param querySuf Query suffix often "]"
* @param tableNames set of the table names
* @param fromClauses Mapping of extra tables for the from section
* @param dataFields Mapping of tablename to list of datafields
* @param idFields Mapping of tablename to idField name
* @param whereClauses List of conditions
* @param relations Mapping of tablename to mapping of fieldname to tablename
* @param queryStrings Mapping of tablename to query
* @param tableTypes accepted table types
* @throws IOException error accessing database
*/
public JDBCFetch(String driverClass, String connLine, String username, String password, RecordHandler rh, String uriNS, String queryPre, String querySuf, Set<String> tableNames, Map<String, String> fromClauses, Map<String, List<String>> dataFields, Map<String, List<String>> idFields, Map<String, List<String>> whereClauses, Map<String, Map<String, String>> relations, Map<String, String> queryStrings, String... tableTypes) throws IOException {
this(createConnection(driverClass, connLine, username, password), rh, uriNS, queryPre, querySuf, tableNames, fromClauses, dataFields, idFields, whereClauses, relations, queryStrings, tableTypes);
}
/**
* Split the values of a comma separated list mapping
* @param list the original mapping
* @return the split mapping
*/
private static Map<String, List<String>> splitCommaList(Map<String, String> list) {
Map<String, List<String>> splitList = new HashMap<String, List<String>>();
for(String tableName : list.keySet()) {
splitList.put(tableName, Arrays.asList(list.get(tableName).split("\\s?,\\s?")));
}
return splitList;
}
/**
* Split the values of comma separated ~ maps mapping
* @param list the original mapping
* @return the split mappings
*/
private static Map<String, Map<String, String>> splitTildeMap(Map<String, String> list) {
Map<String, List<String>> splitList = splitCommaList(list);
Map<String, Map<String, String>> splitMaps = new HashMap<String, Map<String, String>>();
for(String tableName : splitList.keySet()) {
if(!splitMaps.containsKey(tableName)) {
splitMaps.put(tableName, new HashMap<String, String>());
}
for(String relLine : splitList.get(tableName)) {
String[] relPair = relLine.split("\\s?~\\s?", 2);
if(relPair.length != 2) {
throw new IllegalArgumentException("Bad Relation Line: " + relLine);
}
splitMaps.get(tableName).put(relPair[0], relPair[1]);
}
}
return splitMaps;
}
/**
* Create a connection
* @param driverClass the jdbc driver
* @param connLine the jdbc connection line
* @param username the username
* @param password the password
* @return the connection
* @throws IOException error connecting or loading driver
*/
private static Connection createConnection(String driverClass, String connLine, String username, String password) throws IOException {
try {
Class.forName(driverClass);
return DriverManager.getConnection(connLine, username, password);
} catch(SQLException e) {
throw new IOException(e);
} catch(ClassNotFoundException e) {
throw new IOException(e);
}
}
/**
* Get the field prefix
* @return the field prefix
*/
private String getFieldPrefix() {
if(this.queryPre == null) {
this.queryPre = getParser().getOptMap().get("delimiterPrefix").getDefaultValue();
}
return this.queryPre;
}
/**
* Set the field prefix
* @param fieldPrefix the field prefix to use
*/
public void setFieldPrefix(String fieldPrefix) {
this.queryPre = fieldPrefix;
}
/**
* Get the field suffix
* @return the field suffix
*/
private String getFieldSuffix() {
if(this.querySuf == null) {
this.querySuf = getParser().getOptMap().get("delimiterSuffix").getDefaultValue();
}
return this.querySuf;
}
/**
* Set the field suffix
* @param fieldSuffix the field suffix to use
*/
public void setFieldSuffix(String fieldSuffix) {
this.querySuf = fieldSuffix;
}
/**
* Get the data field information for a table from the database
* @param tableName the table to get the data field information for
* @return the data field list
* @throws SQLException error connecting to DB
*/
private List<String> getDataFields(String tableName) throws SQLException {
// TODO: the part after the OR looks like it should be on the next if statement, look into this
if((this.dataFields == null) || ((this.queryStrings != null) && this.queryStrings.containsKey(tableName))) {
this.dataFields = new HashMap<String, List<String>>();
}
if(!this.dataFields.containsKey(tableName)) {
log.debug("Finding data column names for table: "+tableName);
this.dataFields.put(tableName, new LinkedList<String>());
if((this.queryStrings == null) || !this.queryStrings.containsKey(tableName)) {
ResultSet columnData = this.cursor.getConnection().getMetaData().getColumns(this.cursor.getConnection().getCatalog(), null, tableName, "%");
while(columnData.next()) {
String colName = columnData.getString("COLUMN_NAME");
log.trace("Found data column: "+colName);
if(!getFkRelationFields(tableName).containsKey(colName)) {
this.dataFields.get(tableName).add(colName);
}
}
}
}
return this.dataFields.get(tableName);
}
/**
* Get the relation field information for a table from the database
* @param tableName the table to get the relation field information for
* @return the relation field mapping
* @throws SQLException error connecting to DB
*/
private Map<String, String> getFkRelationFields(String tableName) throws SQLException {
// TODO: the part after the OR looks like it should be on the next if statement, look into this
if(this.fkRelations == null) {
this.fkRelations = new HashMap<String, Map<String, String>>();
}
if(!this.fkRelations.containsKey(tableName)) {
this.fkRelations.put(tableName, new HashMap<String, String>());
}
if((this.queryStrings == null || !this.queryStrings.containsKey(tableName)) && this.fkRelations.get(tableName).isEmpty()) {
log.debug("Finding relation column names for table: "+tableName);
if((this.queryStrings == null) || !this.queryStrings.containsKey(tableName)) {
ResultSet foreignKeys = this.cursor.getConnection().getMetaData().getImportedKeys(this.cursor.getConnection().getCatalog(), null, tableName);
while(foreignKeys.next()) {
String colName = foreignKeys.getString("FKCOLUMN_NAME");
String foreignTable = foreignKeys.getString("PKTABLE_NAME");
log.trace("Found relation column: "+colName);
log.trace("links to table: "+foreignTable);
this.fkRelations.get(tableName).put(colName, foreignTable);
}
}
}
return this.fkRelations.get(tableName);
}
/**
* Get the where clauses for a table from the database
* @param tableName the table to get the where clauses for
* @return the where clauses
*/
private List<String> getWhereClauses(String tableName) {
if(this.whereClauses == null) {
this.whereClauses = new HashMap<String, List<String>>();
}
if(!this.whereClauses.containsKey(tableName)) {
this.whereClauses.put(tableName, new LinkedList<String>());
}
return this.whereClauses.get(tableName);
}
/**
* Get the id field list for a table from the database
* @param tableName the table to get the id field list for
* @return the id field list
* @throws SQLException error connecting to DB
*/
private List<String> getIDFields(String tableName) throws SQLException {
if(this.idFields == null) {
this.idFields = new HashMap<String, List<String>>();
}
if(!this.idFields.containsKey(tableName)) {
log.debug("Finding id column names for table: "+tableName);
this.idFields.put(tableName, new LinkedList<String>());
ResultSet primaryKeys = this.cursor.getConnection().getMetaData().getPrimaryKeys(this.cursor.getConnection().getCatalog(), null, tableName);
while(primaryKeys.next()) {
String colName = primaryKeys.getString("COLUMN_NAME");
log.trace("Found id column: "+colName);
this.idFields.get(tableName).add(colName);
}
}
if(this.idFields.get(tableName).isEmpty()) {
throw new IllegalArgumentException("ID fields for table '" + tableName + "' were not provided and no primary keys are present... please provide an ID field set for this table");
}
return this.idFields.get(tableName);
}
/**
* Gets the tablenames in database
* @return set of tablenames
* @throws SQLException error connecting to DB
*/
private Set<String> getTableNames() throws SQLException {
if(this.tableNames.isEmpty()) {
ResultSet tableData = this.cursor.getConnection().getMetaData().getTables(this.cursor.getConnection().getCatalog(), null, "%", this.tableTypes);
while(tableData.next()) {
this.tableNames.add(tableData.getString("TABLE_NAME"));
}
}
return this.tableNames;
}
/**
* Builds a select statement against the table using configured fields
* @param tableName the table to build the select statement for
* @return the select statement
* @throws SQLException error connecting to db
*/
private String buildSelect(String tableName) throws SQLException {
if((this.queryStrings != null) && this.queryStrings.containsKey(tableName)) {
String query = this.queryStrings.get(tableName);
log.trace("User defined SQL Query:\n" + query);
return query;
}
boolean multiTable = (this.fromClauses != null) && this.fromClauses.containsKey(tableName);
StringBuilder sb = new StringBuilder();
sb.append("SELECT ");
for(String dataField : getDataFields(tableName)) {
sb.append(getFieldPrefix());
if(multiTable && (dataField.split("\\.").length <= 1)) {
sb.append(tableName);
sb.append(".");
}
sb.append(dataField);
sb.append(getFieldSuffix());
sb.append(", ");
}
for(String relField : getFkRelationFields(tableName).keySet()) {
sb.append(getFieldPrefix());
if(multiTable && (relField.split("\\.").length <= 1)) {
sb.append(tableName);
sb.append(".");
}
sb.append(relField);
sb.append(getFieldSuffix());
sb.append(", ");
}
for(String idField : getIDFields(tableName)) {
sb.append(getFieldPrefix());
if(multiTable && (idField.split("\\.").length <= 1)) {
sb.append(tableName);
sb.append(".");
}
sb.append(idField);
sb.append(getFieldSuffix());
sb.append(", ");
}
sb.delete(sb.lastIndexOf(", "), sb.length());
sb.append(" FROM ");
sb.append(tableName);
if(multiTable) {
sb.append(", ");
sb.append(this.fromClauses.get(tableName));
}
if(getWhereClauses(tableName).size() > 0) {
sb.append(" WHERE ");
sb.append(StringUtils.join(getWhereClauses(tableName), " AND "));
}
log.trace("Generated SQL Query:\n" + sb.toString());
return sb.toString();
}
/**
* Builds a table's record namespace
* @param tableName the table to build the namespace for
* @return the namespace
*/
private String buildTableRecordNS(String tableName) {
return this.uriNS + tableName;
}
/**
* Builds a table's field description namespace
* @param tableName the table to build the namespace for
* @return the namespace
*/
private String buildTableFieldNS(String tableName) {
return this.uriNS + "fields/" + tableName + "/";
}
/**
* Builds a table's type description namespace
* @param tableName the table to build the namespace for
* @return the namespace
*/
private String buildTableType(String tableName) {
return this.uriNS + "types#" + tableName;
}
/**
* Get the fields from a result set
* @param rs the resultset
* @return the list of fields
* @throws SQLException error reading resultset
*/
private List<String> getResultSetFields(ResultSet rs) throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
List<String> fields = new ArrayList<String>(count);
for(int x = 1; x <= count; x++) {
fields.add(rsmd.getColumnLabel(x));
}
return fields;
}
/**
* Executes the task
* @throws IOException error processing record handler or jdbc connection
*/
public void execute() throws IOException {
int count = 0;
// For each Table
try {
for(String tableName : getTableNames()) {
StringBuilder sb = new StringBuilder();
// For each Record
ResultSet rs = this.cursor.executeQuery(buildSelect(tableName));
// ResultSetMetaData rsmd = rs.getMetaData();
// int ColumnCount = rsmd.getColumnCount();
// Map<String,String> columnData = new HashMap<String,String>();
while(rs.next()) {
StringBuilder recID = new StringBuilder();
recID.append("id");
for(String idField : getIDFields(tableName)) {
recID.append("_-_");
String id = rs.getString(idField);
if(id != null) {
id = id.trim();
}
id = SpecialEntities.xmlEncode(id);
recID.append(id);
}
// log.trace("Creating RDF for "+tableName+": "+recID);
// Build RDF BEGIN
// Header info
String tableNS = "db-" + tableName;
sb = new StringBuilder();
sb.append("<?xml version=\"1.0\"?>\n");
sb.append("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n");
sb.append(" xmlns:");
sb.append(tableNS);
sb.append("=\"");
sb.append(buildTableFieldNS(tableName));
sb.append("\"\n");
sb.append(" xml:base=\"");
sb.append(buildTableRecordNS(tableName));
sb.append("\">\n");
// Record info BEGIN
sb.append(" <rdf:Description rdf:ID=\"");
sb.append(recID);
sb.append("\">\n");
// insert type value
sb.append(" <rdf:type rdf:resource=\"");
sb.append(buildTableType(tableName));
sb.append("\"/>\n");
// DataFields
List<String> dataFieldList;
if((this.queryStrings != null) && this.queryStrings.containsKey(tableName)) {
dataFieldList = getResultSetFields(rs);
} else {
dataFieldList = getDataFields(tableName);
}
for(String dataField : dataFieldList) {
// Field BEGIN
String field = tableNS + ":" + dataField.replaceAll(" ", "_");
sb.append(" <");
sb.append(SpecialEntities.xmlEncode(field));
sb.append(">");
// insert field value
if(rs.getString(dataField) != null) {
sb.append(SpecialEntities.xmlEncode(rs.getString(dataField).trim()));
}
// Field END
sb.append("</");
sb.append(SpecialEntities.xmlEncode(field));
sb.append(">\n");
}
// Relation Fields
for(String relationField : getFkRelationFields(tableName).keySet()) {
// Field BEGIN
String field = tableNS + ":" + relationField.replaceAll(" ", "_");
sb.append(" <");
sb.append(SpecialEntities.xmlEncode(field));
sb.append(" rdf:resource=\"");
sb.append(buildTableRecordNS(getFkRelationFields(tableName).get(relationField)));
// insert field value
sb.append("#id_-_" + rs.getString(relationField).trim());
// Field END
sb.append("\"/>\n");
}
// Record info END
sb.append(" </rdf:Description>\n");
// Footer info
sb.append("</rdf:RDF>");
// Build RDF END
// Write RDF to RecordHandler
log.trace("Adding record: " + tableName + "_" + recID);
this.rh.addRecord(tableName + "_" + recID, sb.toString(), this.getClass());
count++;
}
}
} catch(SQLException e) {
throw new IOException(e);
}
log.info("Added " + count + " Records");
}
/**
* Get the ArgParser for this task
* @return the ArgParser
*/
private static ArgParser getParser() {
ArgParser parser = new ArgParser("JDBCFetch");
parser.addArgument(new ArgDef().setShortOption('d').setLongOpt("driver").withParameter(true, "JDBC_DRIVER").setDescription("jdbc driver class").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('c').setLongOpt("connection").withParameter(true, "JDBC_CONN").setDescription("jdbc connection string").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('u').setLongOpt("username").withParameter(true, "USERNAME").setDescription("database username").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('p').setLongOpt("password").withParameter(true, "PASSWORD").setDescription("database password").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('o').setLongOpt("output").withParameter(true, "CONFIG_FILE").setDescription("RecordHandler config file path").setRequired(false));
parser.addArgument(new ArgDef().setShortOption('t').setLongOpt("tableName").withParameters(true, "TABLE_NAME").setDescription("a single database table name [have multiple -t for more table names]").setRequired(false));
parser.addArgument(new ArgDef().setShortOption('v').setLongOpt("validTableType").withParameters(true, "TABLE_TYPE").setDescription("a single table type (TABLE, VIEW, etc) [have multiple -v for more table types]").setRequired(false));
parser.addArgument(new ArgDef().setShortOption('Q').setLongOpt("query").withParameterValueMap("TABLE_NAME", "SQL_QUERY").setDescription("use SQL_QUERY to select from TABLE_NAME").setRequired(false));
parser.addArgument(new ArgDef().setShortOption('I').setLongOpt("id").withParameterValueMap("TABLE_NAME", "ID_FIELD_LIST").setDescription("use columns in ID_FIELD_LIST[comma separated] as identifier for TABLE_NAME").setRequired(false));
parser.addArgument(new ArgDef().setShortOption('F').setLongOpt("fields").withParameterValueMap("TABLE_NAME", "FIELD_LIST").setDescription("fetch columns in FIELD_LIST[comma separated] for TABLE_NAME").setRequired(false));
parser.addArgument(new ArgDef().setShortOption('R').setLongOpt("relations").withParameterValueMap("TABLE_NAME", "RELATION_PAIR_LIST").setDescription("fetch columns in RELATION_PAIR_LIST[comma separated] for TABLE_NAME").setRequired(false));
parser.addArgument(new ArgDef().setShortOption('W').setLongOpt("whereClause").withParameterValueMap("TABLE_NAME", "CLAUSE_LIST").setDescription("filter TABLE_NAME records based on conditions in CLAUSE_LIST[comma separated]").setRequired(false));
parser.addArgument(new ArgDef().setShortOption('T').setLongOpt("tableFromClause").withParameterValueMap("TABLE_NAME", "TABLE_LIST").setDescription("add tables to use in from clauses for TABLE_NAME").setRequired(false));
parser.addArgument(new ArgDef().setShortOption('O').setLongOpt("outputOverride").withParameterValueMap("RH_PARAM", "VALUE").setDescription("override the RH_PARAM of output recordhandler using VALUE").setRequired(false));
parser.addArgument(new ArgDef().setShortOption('n').setLongOpt("namespaceBase").withParameter(true, "NAMESPACE_BASE").setDescription("the base namespace to use for each node created").setRequired(false));
parser.addArgument(new ArgDef().setLongOpt("delimiterPrefix").withParameter(true, "DELIMITER").setDescription("Prefix each field in the query with this character").setDefaultValue("").setRequired(false));
parser.addArgument(new ArgDef().setLongOpt("delimiterSuffix").withParameter(true, "DELIMITER").setDescription("Suffix each field in the query with this character").setDefaultValue("").setRequired(false));
return parser;
}
/**
* Main method
* @param args commandline arguments
*/
public static void main(String... args) {
Exception error = null;
try {
InitLog.initLogger(args, getParser());
log.info(getParser().getAppName() + ": Start");
new JDBCFetch(args).execute();
} catch(IllegalArgumentException e) {
log.error(e.getMessage());
log.debug("Stacktrace:",e);
System.out.println(getParser().getUsage());
error = e;
} catch(UsageException e) {
log.info("Printing Usage:");
System.out.println(getParser().getUsage());
error = e;
} catch(Exception e) {
log.error(e.getMessage());
log.debug("Stacktrace:",e);
error = e;
} finally {
log.info(getParser().getAppName() + ": End");
if(error != null) {
System.exit(1);
}
}
}
}
| false | true | public JDBCFetch(Connection dbConn, RecordHandler rh, String uriNS, String queryPre, String querySuf, Set<String> tableNames, Map<String, String> fromClauses, Map<String, List<String>> dataFields, Map<String, List<String>> idFields, Map<String, List<String>> whereClauses, Map<String, Map<String, String>> relations, Map<String, String> queryStrings, String... tableTypes) throws IOException {
try {
this.cursor = dbConn.createStatement();
} catch(SQLException e) {
throw new IOException(e);
}
this.rh = rh;
Set<String> argTables = tableNames;
this.fromClauses = fromClauses;
this.dataFields = dataFields;
this.idFields = idFields;
this.whereClauses = whereClauses;
this.fkRelations = relations;
this.uriNS = uriNS;
this.queryPre = queryPre;
this.querySuf = querySuf;
this.queryStrings = queryStrings;
if(tableTypes.length > 0 && tableTypes[0] != null) {
this.tableTypes = tableTypes;
for(int x=0; x<this.tableTypes.length; x++) {
this.tableTypes[x] = this.tableTypes[x].toUpperCase();
}
} else {
this.tableTypes = new String[]{"TABLE"};
}
if(this.rh == null) {
throw new IllegalArgumentException("Must provide output recordhandler!");
}
if(argTables == null) {
argTables = new TreeSet<String>();
}
if(this.fromClauses != null) {
argTables.addAll(this.fromClauses.keySet());
}
if(this.dataFields != null) {
argTables.addAll(this.dataFields.keySet());
}
if(this.idFields != null) {
argTables.addAll(this.idFields.keySet());
}
if(this.whereClauses != null) {
argTables.addAll(this.whereClauses.keySet());
}
if(this.fkRelations != null) {
argTables.addAll(this.fkRelations.keySet());
}
if(this.queryStrings != null) {
// tablenames for queries are arbitrary
argTables.removeAll(this.queryStrings.keySet());
}
this.tableNames = new TreeSet<String>();
try {
this.tableNames = getTableNames();
} catch(SQLException e) {
throw new IOException(e);
}
Set<String> realDBTables = this.tableNames;
this.tableNames = new TreeSet<String>();
//TODO: this is required as getTableNames loads data in and we want this to be a fresh start
// there should be a nicer way to do all of this, as this is very hacky at the moment
for(String argTable : argTables) {
boolean found = false;
for(String realTableName : realDBTables) {
realTableName = realTableName.trim();
if(argTable.trim().equalsIgnoreCase(realTableName)) {
this.tableNames.add(realTableName);
// fix the tablename in all the other structures >.>
if(this.fromClauses != null) {
Map<String, String> tempMap = new HashMap<String, String>();
for(String fromClausesTable : this.fromClauses.keySet()) {
if(fromClausesTable.trim().equalsIgnoreCase(realTableName)) {
tempMap.put(realTableName, this.fromClauses.get(fromClausesTable));
}
}
this.fromClauses = tempMap;
}
if(this.dataFields != null) {
Map<String, List<String>> tempMap = this.dataFields;
for(String dataFieldsTable : this.dataFields.keySet()) {
if(dataFieldsTable.trim().equalsIgnoreCase(realTableName)) {
tempMap.put(realTableName, this.dataFields.get(dataFieldsTable));
}
}
this.dataFields = tempMap;
}
if(this.idFields != null) {
Map<String, List<String>> tempMap = this.idFields;
for(String idFieldsTable : this.idFields.keySet()) {
if(idFieldsTable.trim().equalsIgnoreCase(realTableName)) {
tempMap.put(realTableName, this.idFields.get(idFieldsTable));
}
}
this.idFields = tempMap;
}
if(this.whereClauses != null) {
Map<String, List<String>> tempMap = this.whereClauses;
for(String whereClausesTable : this.whereClauses.keySet()) {
if(whereClausesTable.trim().equalsIgnoreCase(realTableName)) {
tempMap.put(realTableName, this.whereClauses.get(whereClausesTable));
}
}
this.whereClauses = tempMap;
}
if(this.fkRelations != null) {
Map<String, Map<String, String>> tempMap = this.fkRelations;
for(String fkRelationsTable : this.fkRelations.keySet()) {
if(fkRelationsTable.trim().equalsIgnoreCase(realTableName)) {
tempMap.put(realTableName, this.fkRelations.get(fkRelationsTable));
}
}
this.fkRelations = tempMap;
}
found = true;
break;
}
}
if(!found) {
throw new IllegalArgumentException("Database Does Not Contain A Table Named '"+argTable+"'");
}
}
if(this.queryStrings != null) {
this.tableNames.addAll(this.queryStrings.keySet());
}
}
| public JDBCFetch(Connection dbConn, RecordHandler rh, String uriNS, String queryPre, String querySuf, Set<String> tableNames, Map<String, String> fromClauses, Map<String, List<String>> dataFields, Map<String, List<String>> idFields, Map<String, List<String>> whereClauses, Map<String, Map<String, String>> relations, Map<String, String> queryStrings, String... tableTypes) throws IOException {
try {
this.cursor = dbConn.createStatement();
} catch(SQLException e) {
throw new IOException(e);
}
this.rh = rh;
Set<String> argTables = tableNames;
this.fromClauses = fromClauses;
this.dataFields = dataFields;
this.idFields = idFields;
this.whereClauses = whereClauses;
this.fkRelations = relations;
this.uriNS = uriNS;
this.queryPre = queryPre;
this.querySuf = querySuf;
this.queryStrings = queryStrings;
if(tableTypes.length > 0 && tableTypes[0] != null) {
this.tableTypes = tableTypes;
for(int x=0; x<this.tableTypes.length; x++) {
this.tableTypes[x] = this.tableTypes[x].toUpperCase();
}
} else {
this.tableTypes = new String[]{"TABLE"};
}
if(this.rh == null) {
throw new IllegalArgumentException("Must provide output recordhandler!");
}
if(argTables == null) {
argTables = new TreeSet<String>();
}
if(this.fromClauses != null) {
argTables.addAll(this.fromClauses.keySet());
}
if(this.dataFields != null) {
argTables.addAll(this.dataFields.keySet());
}
if(this.idFields != null) {
argTables.addAll(this.idFields.keySet());
}
if(this.whereClauses != null) {
argTables.addAll(this.whereClauses.keySet());
}
if(this.fkRelations != null) {
argTables.addAll(this.fkRelations.keySet());
}
if(this.queryStrings != null) {
// tablenames for queries are arbitrary
argTables.removeAll(this.queryStrings.keySet());
}
this.tableNames = new TreeSet<String>();
try {
this.tableNames = getTableNames();
} catch(SQLException e) {
throw new IOException(e);
}
Set<String> realDBTables = this.tableNames;
this.tableNames = new TreeSet<String>();
//TODO: this is required as getTableNames loads data in and we want this to be a fresh start
// there should be a nicer way to do all of this, as this is very hacky at the moment
for(String argTable : argTables) {
boolean found = false;
for(String realTableName : realDBTables) {
realTableName = realTableName.trim();
if(argTable.trim().equalsIgnoreCase(realTableName)) {
this.tableNames.add(realTableName);
// fix the tablename in all the other structures >.>
if(this.fromClauses != null) {
Map<String, String> tempMap = new HashMap<String, String>();
for(String fromClausesTable : this.fromClauses.keySet()) {
if(fromClausesTable.trim().equalsIgnoreCase(realTableName)) {
tempMap.put(realTableName, this.fromClauses.get(fromClausesTable));
} else {
tempMap.put(fromClausesTable, this.fromClauses.get(fromClausesTable));
}
}
this.fromClauses = tempMap;
}
if(this.dataFields != null) {
Map<String, List<String>> tempMap = this.dataFields;
for(String dataFieldsTable : this.dataFields.keySet()) {
if(dataFieldsTable.trim().equalsIgnoreCase(realTableName)) {
tempMap.put(realTableName, this.dataFields.get(dataFieldsTable));
} else {
tempMap.put(dataFieldsTable, this.dataFields.get(dataFieldsTable));
}
}
this.dataFields = tempMap;
}
if(this.idFields != null) {
Map<String, List<String>> tempMap = this.idFields;
for(String idFieldsTable : this.idFields.keySet()) {
if(idFieldsTable.trim().equalsIgnoreCase(realTableName)) {
tempMap.put(realTableName, this.idFields.get(idFieldsTable));
} else {
tempMap.put(idFieldsTable, this.idFields.get(idFieldsTable));
}
}
this.idFields = tempMap;
}
if(this.whereClauses != null) {
Map<String, List<String>> tempMap = this.whereClauses;
for(String whereClausesTable : this.whereClauses.keySet()) {
if(whereClausesTable.trim().equalsIgnoreCase(realTableName)) {
tempMap.put(realTableName, this.whereClauses.get(whereClausesTable));
} else {
tempMap.put(whereClausesTable, this.whereClauses.get(whereClausesTable));
}
}
this.whereClauses = tempMap;
}
if(this.fkRelations != null) {
Map<String, Map<String, String>> tempMap = this.fkRelations;
for(String fkRelationsTable : this.fkRelations.keySet()) {
if(fkRelationsTable.trim().equalsIgnoreCase(realTableName)) {
tempMap.put(realTableName, this.fkRelations.get(fkRelationsTable));
} else {
tempMap.put(fkRelationsTable, this.fkRelations.get(fkRelationsTable));
}
}
this.fkRelations = tempMap;
}
found = true;
break;
}
}
if(!found) {
throw new IllegalArgumentException("Database Does Not Contain A Table Named '"+argTable+"'");
}
}
if(this.queryStrings != null) {
this.tableNames.addAll(this.queryStrings.keySet());
}
}
|
diff --git a/java/src/com/google/appengine/tools/mapreduce/InputStreamIterator.java b/java/src/com/google/appengine/tools/mapreduce/InputStreamIterator.java
index 67c816f..d13711e 100644
--- a/java/src/com/google/appengine/tools/mapreduce/InputStreamIterator.java
+++ b/java/src/com/google/appengine/tools/mapreduce/InputStreamIterator.java
@@ -1,153 +1,163 @@
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.appengine.tools.mapreduce;
import com.google.common.base.Preconditions;
import com.google.common.io.ByteStreams;
import com.google.common.io.CountingInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* An iterator iterating over records in an input stream.
*
* @author [email protected] (Igor Kushnirskiy)
*/
class InputStreamIterator implements Iterator<InputStreamIterator.OffsetRecordPair> {
public static class OffsetRecordPair {
final private long offset;
final private byte[] record;
public OffsetRecordPair(long offset, byte[] record) {
this.offset = offset;
this.record = record;
}
public long getOffset() {
return offset;
}
public byte[] getRecord() {
return record;
}
public boolean equals(Object rhs) {
if (!(rhs instanceof OffsetRecordPair)) {
return false;
}
OffsetRecordPair rhsPair = (OffsetRecordPair) rhs;
return offset == rhsPair.getOffset()
&& Arrays.equals(record, rhsPair.getRecord());
}
public int hashCode() {
return new Long(offset).hashCode() ^ Arrays.hashCode(record);
}
}
private static final Logger log = Logger.getLogger(InputStreamIterator.class.getName());
private static final int READ_LIMIT = 1024 * 1024;
private final CountingInputStream input;
private final long length;
private final boolean skipFirstTerminator;
private final byte terminator;
private OffsetRecordPair currentValue;
// Note: length may be a negative value when we are reading beyond the split boundary.
InputStreamIterator(CountingInputStream input, long length,
boolean skipFirstTerminator, byte terminator) {
this.input = Preconditions.checkNotNull(input);
this.length = length;
this.skipFirstTerminator = skipFirstTerminator;
this.terminator = terminator;
}
// Returns false if the end of stream is reached and no characters have been
// read since the last terminator.
private boolean skipUntilNextRecord(InputStream stream) throws IOException {
boolean readCharSinceTerminator = false;
int value;
do {
value = stream.read();
if (value == -1) {
return readCharSinceTerminator;
}
readCharSinceTerminator = true;
} while (value != (terminator & 0xff));
return true;
}
@Override
public boolean hasNext() {
try {
if (input.getCount() == 0 && skipFirstTerminator) {
// find the first record start;
if (!skipUntilNextRecord(input)) {
return false;
}
}
// we are reading one record after split-end
// and are skipping first record for all splits except for the leading one.
// check if we read one byte ahead of the split.
if (input.getCount() - 1 >= length) {
return false;
}
long recordStart = input.getCount();
input.mark(READ_LIMIT);
if (!skipUntilNextRecord(input)) {
return false;
}
long recordEnd = input.getCount();
boolean eofReached = input.read() == -1;
input.reset();
int byteValueLen = (int) (recordEnd - recordStart);
if (!eofReached) {
// Skip separator
byteValueLen--;
}
byte[] byteValue = new byte[byteValueLen];
ByteStreams.readFully(input, byteValue);
if (!eofReached) {
Preconditions.checkState(1 == input.skip(1)); // skip the terminator
+ } else if (byteValue.length > 0
+ && byteValue[byteValue.length - 1] == terminator) {
+ // Lop the terminator off the end if we got the sequence
+ // {record} {terminator} EOF.
+ // Unfortunately, due to our underlying interface, we don't have
+ // enough information to do this without the possibility of a copy
+ // in one of the terminator/non-terminator before EOF cases.
+ byte[] newByteValue = new byte[byteValueLen - 1];
+ System.arraycopy(byteValue, 0, newByteValue, 0, byteValueLen - 1);
+ byteValue = newByteValue;
}
currentValue = new OffsetRecordPair(recordStart, byteValue);
return true;
} catch (IOException e) {
log.log(Level.WARNING, "Failed to read next record", e);
return false;
}
}
@Override
public OffsetRecordPair next() {
return currentValue;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
| true | true | public boolean hasNext() {
try {
if (input.getCount() == 0 && skipFirstTerminator) {
// find the first record start;
if (!skipUntilNextRecord(input)) {
return false;
}
}
// we are reading one record after split-end
// and are skipping first record for all splits except for the leading one.
// check if we read one byte ahead of the split.
if (input.getCount() - 1 >= length) {
return false;
}
long recordStart = input.getCount();
input.mark(READ_LIMIT);
if (!skipUntilNextRecord(input)) {
return false;
}
long recordEnd = input.getCount();
boolean eofReached = input.read() == -1;
input.reset();
int byteValueLen = (int) (recordEnd - recordStart);
if (!eofReached) {
// Skip separator
byteValueLen--;
}
byte[] byteValue = new byte[byteValueLen];
ByteStreams.readFully(input, byteValue);
if (!eofReached) {
Preconditions.checkState(1 == input.skip(1)); // skip the terminator
}
currentValue = new OffsetRecordPair(recordStart, byteValue);
return true;
} catch (IOException e) {
log.log(Level.WARNING, "Failed to read next record", e);
return false;
}
}
| public boolean hasNext() {
try {
if (input.getCount() == 0 && skipFirstTerminator) {
// find the first record start;
if (!skipUntilNextRecord(input)) {
return false;
}
}
// we are reading one record after split-end
// and are skipping first record for all splits except for the leading one.
// check if we read one byte ahead of the split.
if (input.getCount() - 1 >= length) {
return false;
}
long recordStart = input.getCount();
input.mark(READ_LIMIT);
if (!skipUntilNextRecord(input)) {
return false;
}
long recordEnd = input.getCount();
boolean eofReached = input.read() == -1;
input.reset();
int byteValueLen = (int) (recordEnd - recordStart);
if (!eofReached) {
// Skip separator
byteValueLen--;
}
byte[] byteValue = new byte[byteValueLen];
ByteStreams.readFully(input, byteValue);
if (!eofReached) {
Preconditions.checkState(1 == input.skip(1)); // skip the terminator
} else if (byteValue.length > 0
&& byteValue[byteValue.length - 1] == terminator) {
// Lop the terminator off the end if we got the sequence
// {record} {terminator} EOF.
// Unfortunately, due to our underlying interface, we don't have
// enough information to do this without the possibility of a copy
// in one of the terminator/non-terminator before EOF cases.
byte[] newByteValue = new byte[byteValueLen - 1];
System.arraycopy(byteValue, 0, newByteValue, 0, byteValueLen - 1);
byteValue = newByteValue;
}
currentValue = new OffsetRecordPair(recordStart, byteValue);
return true;
} catch (IOException e) {
log.log(Level.WARNING, "Failed to read next record", e);
return false;
}
}
|
diff --git a/src/edu/stanford/mobisocial/dungbeetle/App.java b/src/edu/stanford/mobisocial/dungbeetle/App.java
index 1018bb2..6ba06ab 100644
--- a/src/edu/stanford/mobisocial/dungbeetle/App.java
+++ b/src/edu/stanford/mobisocial/dungbeetle/App.java
@@ -1,161 +1,162 @@
package edu.stanford.mobisocial.dungbeetle;
import java.math.BigInteger;
import java.security.SecureRandom;
import mobisocial.socialkit.Obj;
import mobisocial.socialkit.musubi.Musubi;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.util.Log;
import edu.stanford.mobisocial.dungbeetle.feed.objects.ProfileObj;
import edu.stanford.mobisocial.dungbeetle.model.Contact;
import edu.stanford.mobisocial.dungbeetle.model.Feed;
import edu.stanford.mobisocial.dungbeetle.model.Group;
import edu.stanford.mobisocial.dungbeetle.util.ImageCache;
public class App extends Application {
/**
* The protocol version we speak, affecting things like wire protocol
* format and physical network support, available features, app api, etc.
*/
public static final String PREF_POSI_VERSION = "posi_version";
public static final int POSI_VERSION = 4;
public static final String TAG = "musubi";
public final ImageCache contactImages = new ImageCache(30);
public final ImageCache objectImages = new ImageCache(30);
private ScreenState mScreenState;
private static App instance;
private SecureRandom secureRandom;
private Uri mFeedUri;
private Musubi mMusubi;
private String mLocalPersonId;
public static App instance(){
if(instance != null) return instance;
else throw new IllegalStateException("WTF, why no App instance.");
}
public boolean isScreenOn(){
return !mScreenState.isOff;
}
public String getRandomString() {
return new BigInteger(130, secureRandom).toString(32);
}
@Override
public void onCreate() {
super.onCreate();
App.instance = this;
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mScreenState = new ScreenState();
getApplicationContext().registerReceiver(mScreenState, filter);
secureRandom = new SecureRandom();
mMusubi = Musubi.getInstance(getApplicationContext());
// Sync profile information.
SharedPreferences prefs = getSharedPreferences("main", 0);
int oldVersion = prefs.getInt(PREF_POSI_VERSION, 0);
if (oldVersion <= POSI_VERSION) {
Obj updateObj = ProfileObj.getLocalProperties(this);
Log.d(TAG, "Broadcasting new profile attributes: " + updateObj.getJson());
Helpers.sendToEveryone(this, updateObj);
prefs.edit().putInt(PREF_POSI_VERSION, POSI_VERSION).commit();
}
}
@Override
public void onTerminate() {
super.onTerminate();
}
private class ScreenState extends BroadcastReceiver {
public boolean isOff = false;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
isOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
isOff = false;
}
}
}
public String getLocalPersonId() {
if (mLocalPersonId == null) {
initLocalUser();
}
return mLocalPersonId;
}
private void initLocalUser() {
DBHelper mHelper = DBHelper.getGlobal(this);
DBIdentityProvider mIdent = new DBIdentityProvider(mHelper);
mLocalPersonId = mIdent.userPersonId();
mIdent.close();
mHelper.close();
}
public void setCurrentFeed(Uri feedUri) {
mFeedUri = feedUri;
if (feedUri != null) {
resetUnreadMessages(feedUri);
}
}
public Uri getCurrentFeed() {
return mFeedUri;
}
public Musubi getMusubi() {
return mMusubi;
}
private void resetUnreadMessages(Uri feedUri) {
try {
switch(Feed.typeOf(feedUri)) {
+ case Feed.FEED_FRIEND: {
+ String personId = Feed.personIdForFeed(feedUri);
+ ContentValues cv = new ContentValues();
+ cv.put(Contact.NUM_UNREAD, 0);
+ getContentResolver().update(
+ Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/" + Contact.TABLE), cv,
+ Contact.PERSON_ID + "='" + personId + "'", null);
+ // No break; do group feed too.
+ // TODO, get rid of person msg count?
+ }
case Feed.FEED_GROUP: {
String feedName = feedUri.getLastPathSegment();
ContentValues cv = new ContentValues();
cv.put(Group.NUM_UNREAD, 0);
getContentResolver().update(
Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/" + Group.TABLE), cv,
Group.FEED_NAME + "='" + feedName + "'", null);
getContentResolver().notifyChange(
Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/feedlist"), null);
break;
}
- case Feed.FEED_FRIEND: {
- long contact_id = Long.valueOf(feedUri.getLastPathSegment());
- ContentValues cv = new ContentValues();
- cv.put(Contact.NUM_UNREAD, 0);
- getContentResolver().update(
- Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/" + Contact.TABLE), cv,
- Contact._ID + "='" + contact_id + "'", null);
- break;
- }
case Feed.FEED_RELATED: {
//TODO: hmm?
break;
}
}
} catch (Exception e) {
Log.e(TAG, "Error clearing unread messages", e);
}
}
}
| false | true | private void resetUnreadMessages(Uri feedUri) {
try {
switch(Feed.typeOf(feedUri)) {
case Feed.FEED_GROUP: {
String feedName = feedUri.getLastPathSegment();
ContentValues cv = new ContentValues();
cv.put(Group.NUM_UNREAD, 0);
getContentResolver().update(
Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/" + Group.TABLE), cv,
Group.FEED_NAME + "='" + feedName + "'", null);
getContentResolver().notifyChange(
Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/feedlist"), null);
break;
}
case Feed.FEED_FRIEND: {
long contact_id = Long.valueOf(feedUri.getLastPathSegment());
ContentValues cv = new ContentValues();
cv.put(Contact.NUM_UNREAD, 0);
getContentResolver().update(
Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/" + Contact.TABLE), cv,
Contact._ID + "='" + contact_id + "'", null);
break;
}
case Feed.FEED_RELATED: {
//TODO: hmm?
break;
}
}
} catch (Exception e) {
Log.e(TAG, "Error clearing unread messages", e);
}
}
| private void resetUnreadMessages(Uri feedUri) {
try {
switch(Feed.typeOf(feedUri)) {
case Feed.FEED_FRIEND: {
String personId = Feed.personIdForFeed(feedUri);
ContentValues cv = new ContentValues();
cv.put(Contact.NUM_UNREAD, 0);
getContentResolver().update(
Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/" + Contact.TABLE), cv,
Contact.PERSON_ID + "='" + personId + "'", null);
// No break; do group feed too.
// TODO, get rid of person msg count?
}
case Feed.FEED_GROUP: {
String feedName = feedUri.getLastPathSegment();
ContentValues cv = new ContentValues();
cv.put(Group.NUM_UNREAD, 0);
getContentResolver().update(
Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/" + Group.TABLE), cv,
Group.FEED_NAME + "='" + feedName + "'", null);
getContentResolver().notifyChange(
Uri.parse(DungBeetleContentProvider.CONTENT_URI + "/feedlist"), null);
break;
}
case Feed.FEED_RELATED: {
//TODO: hmm?
break;
}
}
} catch (Exception e) {
Log.e(TAG, "Error clearing unread messages", e);
}
}
|
diff --git a/src/br/usp/cata/web/controller/IndexController.java b/src/br/usp/cata/web/controller/IndexController.java
index 1377abc..70cdf2d 100644
--- a/src/br/usp/cata/web/controller/IndexController.java
+++ b/src/br/usp/cata/web/controller/IndexController.java
@@ -1,175 +1,176 @@
/*
* Modificado de IndexController.java -
* http://vraptor3.googlecode.com/files/vraptor-blank-project-3.3.1.zip
*/
package br.usp.cata.web.controller;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.interceptor.multipart.UploadedFile;
import br.com.caelum.vraptor.validator.ValidationMessage;
import br.usp.cata.model.User;
import br.usp.cata.service.NewUserService;
import br.usp.cata.service.NewUserService.SignupResult;
import br.usp.cata.service.UserService;
import br.usp.cata.web.interceptor.IrrestrictAccess;
import br.usp.cata.web.interceptor.Transactional;
@Resource
@IrrestrictAccess
public class IndexController {
private final Result result;
private final Validator validator;
private final UserService userService;
private final NewUserService newUserService;
private final int PASSWORD_MIN_LENGTH = 6;
private final int PASSWORD_MAX_LENGTH = 32;
public IndexController(Result result, Validator validator,
UserService userService, NewUserService newUserService) {
this.result = result;
this.validator = validator;
this.userService = userService;
this.newUserService = newUserService;
}
@Get
@Path("/")
public void index() {
if(userService.isAuthenticatedUser())
result.redirectTo(HomeController.class).index();
}
@Post
@Path("/login")
@Transactional
public void login(User user) {
if(user.getEmail().equals(""))
validator.add(new ValidationMessage(
"O campo não pode ser vazio", "E-mail"));
if(user.getPassword().equals(""))
validator.add(new ValidationMessage(
"O campo não pode ser vazio", "Senha"));
validator.onErrorRedirectTo(IndexController.class).index();
final boolean success = userService.authenticate(user.getEmail(), user.getPassword());
if(!success) {
validator.add(new ValidationMessage("valores inválidos", "E-mail ou senha"));
validator.onErrorRedirectTo(IndexController.class).index();
}
result.redirectTo(HomeController.class).index();
}
@Post
@Path("/advice")
public void advice(UploadedFile file) {
if(file == null)
validator.add(new ValidationMessage(
"Selecione um arquivo no formato .txt", "Nenhum arquivo selecionado"));
else if(!file.getContentType().equals("text/plain")) {
validator.add(new ValidationMessage(
"O arquivo deve estar no formato .txt", "Formato do arquivo"));
}
validator.onErrorUsePageOf(IndexController.class).index();
result.forwardTo(SuggestionsController.class).results(file);
}
@Get
@Path("/about")
public void about() {
}
@Get
@Path("/signup")
public void signup()
{
}
@Post
@Path("/signup")
@Transactional
public void signup(User newUser, String password)
{
if(newUser.getName().equals(""))
validator.add(new ValidationMessage(
"O campo não pode ser vazio", "Nome"));
if(newUser.getEmail().equals(""))
validator.add(new ValidationMessage(
"O campo não pode ser vazio", "E-mail"));
if(newUser.getPassword().length() < PASSWORD_MIN_LENGTH)
validator.add(new ValidationMessage(
"A senha deve ter 6 caracteres no mínimo", "Senha"));
if(newUser.getPassword().length() > PASSWORD_MAX_LENGTH)
validator.add(new ValidationMessage(
"A senha deve ter 32 caracteres no máximo", "Senha"));
if(!newUser.getPassword().equals(password))
validator.add(new ValidationMessage(
"As senhas digitadas não são idênticas", "Senhas"));
validator.onErrorRedirectTo(IndexController.class).signup();
SignupResult signupResult = newUserService.register(newUser);
switch(signupResult) {
case SUCCESS:
result.include("messages", "Sua conta foi criada. " +
- "Um e-mail de ativação foi enviado para o endereço '" + newUser.getEmail() + "'.");
+ "Um e-mail de ativação foi enviado para o endereço " + newUser.getEmail() + ".");
break;
case USER_ALREADY_REGISTERED_ACTIVE:
validator.add(new ValidationMessage(
"Já existe um usuário cadastrado com este e-mail no sistema", "E-mail"));
break;
case USER_ALREADY_REGISTERED_INACTIVE:
result.include("messages",
"Já existe um usuário cadastrado com este e-mail no sistema - mas está inativo. " +
- "Um e-mail de ativação foi enviado para o endereço '" + newUser.getEmail() + "'.");
+ "Um e-mail de ativação foi enviado para o endereço " + newUser.getEmail() + ".");
break;
case NO_EMAIL_SENT:
validator.add(new ValidationMessage(
- "Não foi possível enviar o e-mail de ativação de conta para o endereço " + newUser.getEmail() + "." +
- "Tente novamente mais tarde ou use outro endereço de e-mail", "E-mail de ativação"));
+ "Não foi possível enviar o e-mail de ativação de conta para o endereço " + newUser.getEmail() + ". " +
+ "Tente novamente mais tarde ou use outro endereço de e-mail.", "E-mail de ativação"));
+ break;
default:
throw new IllegalStateException("Unexpected signup result");
}
validator.onErrorRedirectTo(IndexController.class).signup();
result.redirectTo(IndexController.class).index();
}
@Get
@Path("/signup/activate/{activationKey}")
@Transactional
public void activate(String activationKey)
{
SignupResult activationResult = newUserService.activate(activationKey);
switch(activationResult) {
case SUCCESS:
result.include("messages", "Sua conta foi ativada com sucesso.");
break;
case USER_ALREADY_REGISTERED_ACTIVE:
result.include("messages", "Sua conta já está ativada.");
break;
case ACTIVATION_KEY_NOT_FOUND:
validator.add(new ValidationMessage(
"Não ocorreu ativação de nenhuma conta porque o link é inválido", "Link inválido"));
break;
default:
throw new IllegalStateException("Unexpected activation result");
}
validator.onErrorRedirectTo(IndexController.class).index();
result.redirectTo(IndexController.class).index();
}
}
| false | true | public void signup(User newUser, String password)
{
if(newUser.getName().equals(""))
validator.add(new ValidationMessage(
"O campo não pode ser vazio", "Nome"));
if(newUser.getEmail().equals(""))
validator.add(new ValidationMessage(
"O campo não pode ser vazio", "E-mail"));
if(newUser.getPassword().length() < PASSWORD_MIN_LENGTH)
validator.add(new ValidationMessage(
"A senha deve ter 6 caracteres no mínimo", "Senha"));
if(newUser.getPassword().length() > PASSWORD_MAX_LENGTH)
validator.add(new ValidationMessage(
"A senha deve ter 32 caracteres no máximo", "Senha"));
if(!newUser.getPassword().equals(password))
validator.add(new ValidationMessage(
"As senhas digitadas não são idênticas", "Senhas"));
validator.onErrorRedirectTo(IndexController.class).signup();
SignupResult signupResult = newUserService.register(newUser);
switch(signupResult) {
case SUCCESS:
result.include("messages", "Sua conta foi criada. " +
"Um e-mail de ativação foi enviado para o endereço '" + newUser.getEmail() + "'.");
break;
case USER_ALREADY_REGISTERED_ACTIVE:
validator.add(new ValidationMessage(
"Já existe um usuário cadastrado com este e-mail no sistema", "E-mail"));
break;
case USER_ALREADY_REGISTERED_INACTIVE:
result.include("messages",
"Já existe um usuário cadastrado com este e-mail no sistema - mas está inativo. " +
"Um e-mail de ativação foi enviado para o endereço '" + newUser.getEmail() + "'.");
break;
case NO_EMAIL_SENT:
validator.add(new ValidationMessage(
"Não foi possível enviar o e-mail de ativação de conta para o endereço " + newUser.getEmail() + "." +
"Tente novamente mais tarde ou use outro endereço de e-mail", "E-mail de ativação"));
default:
throw new IllegalStateException("Unexpected signup result");
}
validator.onErrorRedirectTo(IndexController.class).signup();
result.redirectTo(IndexController.class).index();
}
| public void signup(User newUser, String password)
{
if(newUser.getName().equals(""))
validator.add(new ValidationMessage(
"O campo não pode ser vazio", "Nome"));
if(newUser.getEmail().equals(""))
validator.add(new ValidationMessage(
"O campo não pode ser vazio", "E-mail"));
if(newUser.getPassword().length() < PASSWORD_MIN_LENGTH)
validator.add(new ValidationMessage(
"A senha deve ter 6 caracteres no mínimo", "Senha"));
if(newUser.getPassword().length() > PASSWORD_MAX_LENGTH)
validator.add(new ValidationMessage(
"A senha deve ter 32 caracteres no máximo", "Senha"));
if(!newUser.getPassword().equals(password))
validator.add(new ValidationMessage(
"As senhas digitadas não são idênticas", "Senhas"));
validator.onErrorRedirectTo(IndexController.class).signup();
SignupResult signupResult = newUserService.register(newUser);
switch(signupResult) {
case SUCCESS:
result.include("messages", "Sua conta foi criada. " +
"Um e-mail de ativação foi enviado para o endereço " + newUser.getEmail() + ".");
break;
case USER_ALREADY_REGISTERED_ACTIVE:
validator.add(new ValidationMessage(
"Já existe um usuário cadastrado com este e-mail no sistema", "E-mail"));
break;
case USER_ALREADY_REGISTERED_INACTIVE:
result.include("messages",
"Já existe um usuário cadastrado com este e-mail no sistema - mas está inativo. " +
"Um e-mail de ativação foi enviado para o endereço " + newUser.getEmail() + ".");
break;
case NO_EMAIL_SENT:
validator.add(new ValidationMessage(
"Não foi possível enviar o e-mail de ativação de conta para o endereço " + newUser.getEmail() + ". " +
"Tente novamente mais tarde ou use outro endereço de e-mail.", "E-mail de ativação"));
break;
default:
throw new IllegalStateException("Unexpected signup result");
}
validator.onErrorRedirectTo(IndexController.class).signup();
result.redirectTo(IndexController.class).index();
}
|
diff --git a/src/java/org/codehaus/groovy/grails/orm/hibernate/proxy/GroovyAwareJavassistLazyInitializer.java b/src/java/org/codehaus/groovy/grails/orm/hibernate/proxy/GroovyAwareJavassistLazyInitializer.java
index 6a67260f3..84edba801 100644
--- a/src/java/org/codehaus/groovy/grails/orm/hibernate/proxy/GroovyAwareJavassistLazyInitializer.java
+++ b/src/java/org/codehaus/groovy/grails/orm/hibernate/proxy/GroovyAwareJavassistLazyInitializer.java
@@ -1,261 +1,260 @@
/* Copyright 2004-2005 Graeme Rocher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.orm.hibernate.proxy;
import groovy.lang.GroovyObject;
import groovy.lang.GroovySystem;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
import javassist.util.proxy.MethodFilter;
import javassist.util.proxy.MethodHandler;
import javassist.util.proxy.ProxyFactory;
import javassist.util.proxy.ProxyObject;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil;
import org.codehaus.groovy.grails.plugins.orm.hibernate.HibernatePluginSupport;
import org.hibernate.HibernateException;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.pojo.BasicLazyInitializer;
import org.hibernate.proxy.pojo.javassist.SerializableProxy;
import org.hibernate.type.AbstractComponentType;
import org.hibernate.util.ReflectHelper;
/**
* @author Graeme Rocher
* @since 1.0
* <p/>
* Created: Apr 21, 2009
*/
public class GroovyAwareJavassistLazyInitializer extends BasicLazyInitializer implements MethodHandler {
private static final String WRITE_CLASSES_DIRECTORY = System.getProperty("javassist.writeDirectory");
@SuppressWarnings("serial")
private static final Set<String> GROOVY_METHODS = new HashSet<String>() {{
add("invokeMethod");
add("getMetaClass");
add("setMetaClass");
add("metaClass");
add("getProperty");
add("setProperty");
add("$getStaticMetaClass");
}};
private static final MethodFilter METHOD_FILTERS = new MethodFilter() {
public boolean isHandled(Method m) {
// skip finalize methods
return m.getName().indexOf("super$") == -1 &&
!GROOVY_METHODS.contains(m.getName()) &&
!(m.getParameterTypes().length == 0 && (m.getName().equals("finalize")));
}
};
private Class<?>[] interfaces;
private boolean constructed = false;
private GroovyAwareJavassistLazyInitializer(
final String entityName,
final Class<?> persistentClass,
final Class<?>[] interfaces,
final Serializable id,
final Method getIdentifierMethod,
final Method setIdentifierMethod,
final AbstractComponentType componentIdType,
final SessionImplementor session) {
super(entityName, persistentClass, id, getIdentifierMethod, setIdentifierMethod, componentIdType, session);
this.interfaces = interfaces;
}
public static HibernateProxy getProxy(
final String entityName,
final Class persistentClass,
final Class[] interfaces,
final Method getIdentifierMethod,
final Method setIdentifierMethod,
AbstractComponentType componentIdType,
final Serializable id,
final SessionImplementor session) throws HibernateException {
// note: interface is assumed to already contain HibernateProxy.class
try {
final GroovyAwareJavassistLazyInitializer instance = new GroovyAwareJavassistLazyInitializer(
entityName,
persistentClass,
interfaces,
id,
getIdentifierMethod,
setIdentifierMethod,
componentIdType,
session
);
ProxyFactory factory = createProxyFactory(persistentClass, interfaces);
Class<?> proxyClass = factory.createClass();
HibernatePluginSupport.enhanceProxyClass(proxyClass);
final HibernateProxy proxy = (HibernateProxy)proxyClass.newInstance();
((ProxyObject) proxy).setHandler(instance);
HibernatePluginSupport.enhanceProxy(proxy);
instance.constructed = true;
return proxy;
}
catch (Throwable t) {
LogFactory.getLog(BasicLazyInitializer.class).error(
"Javassist Enhancement failed: " + entityName, t
);
throw new HibernateException(
"Javassist Enhancement failed: "
+ entityName, t
);
}
}
public static HibernateProxy getProxy(
final Class<?> factory,
final String entityName,
final Class persistentClass,
final Class<?>[] interfaces,
final Method getIdentifierMethod,
final Method setIdentifierMethod,
final AbstractComponentType componentIdType,
final Serializable id,
final SessionImplementor session) throws HibernateException {
final GroovyAwareJavassistLazyInitializer instance = new GroovyAwareJavassistLazyInitializer(
entityName,
persistentClass,
interfaces, id,
getIdentifierMethod,
setIdentifierMethod,
componentIdType,
session
);
final HibernateProxy proxy;
try {
proxy = (HibernateProxy)factory.newInstance();
}
catch (Exception e) {
throw new HibernateException(
"Javassist Enhancement failed: "
+ persistentClass.getName(), e
);
}
((ProxyObject) proxy).setHandler(instance);
instance.constructed = true;
HibernatePluginSupport.enhanceProxy(proxy);
HibernatePluginSupport.initializeDomain(persistentClass);
return proxy;
}
public static Class<?> getProxyFactory(
Class<?> persistentClass,
Class<?>[] interfaces) throws HibernateException {
// note: interfaces is assumed to already contain HibernateProxy.class
try {
ProxyFactory factory = createProxyFactory(persistentClass, interfaces);
Class<?> proxyClass = factory.createClass();
HibernatePluginSupport.enhanceProxyClass(proxyClass);
return proxyClass;
}
catch (Throwable t) {
LogFactory.getLog(BasicLazyInitializer.class).error(
"Javassist Enhancement failed: "
+ persistentClass.getName(), t
);
throw new HibernateException(
"Javassist Enhancement failed: "
+ persistentClass.getName(), t
);
}
}
private static ProxyFactory createProxyFactory(Class<?> persistentClass,
Class<?>[] interfaces) {
ProxyFactory factory = new ProxyFactory();
factory.setSuperclass(interfaces.length == 1 ? persistentClass : null);
factory.setInterfaces(interfaces);
factory.setFilter(METHOD_FILTERS);
if (WRITE_CLASSES_DIRECTORY != null) {
factory.writeDirectory = WRITE_CLASSES_DIRECTORY;
}
return factory;
}
public Object invoke(
final Object proxy,
final Method thisMethod,
final Method proceed,
final Object[] args) throws Throwable {
if (constructed) {
Object result;
try {
result = invoke(thisMethod, args, proxy);
}
catch (Throwable t) {
throw new Exception(t.getCause());
}
if (result == INVOKE_IMPLEMENTATION) {
- Object target = getImplementation();
- GrailsHibernateUtil.ensureCorrectGroovyMetaClass(target,persistentClass);
+ Object target = getImplementation();
final Object returnValue;
try {
if (ReflectHelper.isPublic(persistentClass, thisMethod)) {
if (!thisMethod.getDeclaringClass().isInstance(target)) {
throw new ClassCastException(target.getClass().getName());
}
returnValue = thisMethod.invoke(target, args);
}
else {
if (!thisMethod.isAccessible()) {
thisMethod.setAccessible(true);
}
returnValue = thisMethod.invoke(target, args);
}
return returnValue == target ? proxy : returnValue;
}
catch (InvocationTargetException ite) {
throw ite.getTargetException();
}
}
return result;
}
// while constructor is running
if (thisMethod.getName().equals("getHibernateLazyInitializer")) {
return this;
}
return proceed.invoke(proxy, args);
}
@Override
protected Object serializableProxy() {
return new SerializableProxy(
getEntityName(),
persistentClass,
interfaces,
getIdentifier(),
getIdentifierMethod,
setIdentifierMethod,
componentIdType
);
}
}
| true | true | public Object invoke(
final Object proxy,
final Method thisMethod,
final Method proceed,
final Object[] args) throws Throwable {
if (constructed) {
Object result;
try {
result = invoke(thisMethod, args, proxy);
}
catch (Throwable t) {
throw new Exception(t.getCause());
}
if (result == INVOKE_IMPLEMENTATION) {
Object target = getImplementation();
GrailsHibernateUtil.ensureCorrectGroovyMetaClass(target,persistentClass);
final Object returnValue;
try {
if (ReflectHelper.isPublic(persistentClass, thisMethod)) {
if (!thisMethod.getDeclaringClass().isInstance(target)) {
throw new ClassCastException(target.getClass().getName());
}
returnValue = thisMethod.invoke(target, args);
}
else {
if (!thisMethod.isAccessible()) {
thisMethod.setAccessible(true);
}
returnValue = thisMethod.invoke(target, args);
}
return returnValue == target ? proxy : returnValue;
}
catch (InvocationTargetException ite) {
throw ite.getTargetException();
}
}
return result;
}
// while constructor is running
if (thisMethod.getName().equals("getHibernateLazyInitializer")) {
return this;
}
return proceed.invoke(proxy, args);
}
| public Object invoke(
final Object proxy,
final Method thisMethod,
final Method proceed,
final Object[] args) throws Throwable {
if (constructed) {
Object result;
try {
result = invoke(thisMethod, args, proxy);
}
catch (Throwable t) {
throw new Exception(t.getCause());
}
if (result == INVOKE_IMPLEMENTATION) {
Object target = getImplementation();
final Object returnValue;
try {
if (ReflectHelper.isPublic(persistentClass, thisMethod)) {
if (!thisMethod.getDeclaringClass().isInstance(target)) {
throw new ClassCastException(target.getClass().getName());
}
returnValue = thisMethod.invoke(target, args);
}
else {
if (!thisMethod.isAccessible()) {
thisMethod.setAccessible(true);
}
returnValue = thisMethod.invoke(target, args);
}
return returnValue == target ? proxy : returnValue;
}
catch (InvocationTargetException ite) {
throw ite.getTargetException();
}
}
return result;
}
// while constructor is running
if (thisMethod.getName().equals("getHibernateLazyInitializer")) {
return this;
}
return proceed.invoke(proxy, args);
}
|
diff --git a/org.strategoxt.imp.runtime/src/org/strategoxt/imp/runtime/services/OnSaveService.java b/org.strategoxt.imp.runtime/src/org/strategoxt/imp/runtime/services/OnSaveService.java
index a0c2b0dc..369a32f9 100644
--- a/org.strategoxt.imp.runtime/src/org/strategoxt/imp/runtime/services/OnSaveService.java
+++ b/org.strategoxt.imp.runtime/src/org/strategoxt/imp/runtime/services/OnSaveService.java
@@ -1,104 +1,104 @@
/**
*
*/
package org.strategoxt.imp.runtime.services;
import static org.spoofax.interpreter.core.Tools.asJavaString;
import static org.spoofax.interpreter.core.Tools.isTermString;
import static org.spoofax.interpreter.core.Tools.isTermTuple;
import static org.spoofax.interpreter.core.Tools.termAt;
import static org.strategoxt.imp.runtime.dynamicloading.TermReader.cons;
import java.io.File;
import java.io.FileNotFoundException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.DocumentEvent;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.strategoxt.imp.runtime.EditorState;
import org.strategoxt.imp.runtime.Environment;
import org.strategoxt.imp.runtime.dynamicloading.IOnSaveService;
import org.strategoxt.imp.runtime.parser.ast.AstMessageHandler;
import org.strategoxt.imp.runtime.stratego.EditorIOAgent;
import org.strategoxt.imp.runtime.stratego.RefreshResourcePrimitive;
import org.strategoxt.imp.runtime.stratego.SourceAttachment;
/**
* @author Lennart Kats <lennart add lclnet.nl>
*/
public class OnSaveService implements IOnSaveService {
private final StrategoObserver runtime;
private final String function;
private EditorState editor;
public OnSaveService(StrategoObserver runtime, String function) {
this.runtime = runtime;
this.function = function;
}
public void initialize(EditorState editor) {
this.editor = editor;
}
public void documentAboutToBeChanged(DocumentEvent event) {
// Unused
}
public void documentChanged(DocumentEvent event) {
if (function == null) return;
//String contents = event.getDocument().get();
try {
Environment.getStrategoLock().lock();
try {
IStrategoTerm ast = editor.getCurrentAst();
if (ast == null) return;
IStrategoTerm result = runtime.invokeSilent(function, ast);
if (result == null) {
runtime.reportRewritingFailed();
String log = runtime.getLog();
Environment.logException(log.length() == 0 ? "Analysis failed" : "Analysis failed:\n" + log);
AstMessageHandler messages = runtime.getMessages();
messages.clearMarkers(SourceAttachment.getResource(ast));
messages.addMarkerFirstLine(SourceAttachment.getResource(ast), "Analysis failed (see error log)", IMarker.SEVERITY_ERROR);
messages.commitAllChanges();
} else if (isTermString(result)) {
// Function's returning a filename
- String file = asJavaString(termAt(result, 0));
+ String file = asJavaString(result);
if (new File(file).exists())
RefreshResourcePrimitive.call(runtime.getRuntime().getContext(), file);
} else if (isTermTuple(result) && result.getSubtermCount() == 2 && isTermString(termAt(result, 0)) && isTermString(termAt(result, 1))) {
// Function's returning a tuple like a builder
// let's be friendly and try to refresh the file
String file = asJavaString(termAt(result, 0));
String newContents = asJavaString(termAt(result, 1));
try {
IFile resource = EditorIOAgent.getFile(runtime.getRuntime().getContext(), file);
StrategoBuilder.setFileContentsDirect(resource, newContents);
} catch (FileNotFoundException e) {
Environment.logException("Problem when handling on save event", e);
} catch (CoreException e) {
Environment.logException("Problem when handling on save event", e);
}
} else if (!"None".equals(cons(result))) {
if (editor.getDescriptor().isDynamicallyLoaded())
Environment.logWarning("Unexpected result from 'on save' strategy: should be None() or (\"filename\", \"contents\"): " + result);
}
} finally {
Environment.getStrategoLock().unlock();
}
} catch (RuntimeException e) {
Environment.logException("Exception in OnSaveService", e);
} catch (Error e) {
Environment.logException("Exception in OnSaveService", e);
}
}
}
| true | true | public void documentChanged(DocumentEvent event) {
if (function == null) return;
//String contents = event.getDocument().get();
try {
Environment.getStrategoLock().lock();
try {
IStrategoTerm ast = editor.getCurrentAst();
if (ast == null) return;
IStrategoTerm result = runtime.invokeSilent(function, ast);
if (result == null) {
runtime.reportRewritingFailed();
String log = runtime.getLog();
Environment.logException(log.length() == 0 ? "Analysis failed" : "Analysis failed:\n" + log);
AstMessageHandler messages = runtime.getMessages();
messages.clearMarkers(SourceAttachment.getResource(ast));
messages.addMarkerFirstLine(SourceAttachment.getResource(ast), "Analysis failed (see error log)", IMarker.SEVERITY_ERROR);
messages.commitAllChanges();
} else if (isTermString(result)) {
// Function's returning a filename
String file = asJavaString(termAt(result, 0));
if (new File(file).exists())
RefreshResourcePrimitive.call(runtime.getRuntime().getContext(), file);
} else if (isTermTuple(result) && result.getSubtermCount() == 2 && isTermString(termAt(result, 0)) && isTermString(termAt(result, 1))) {
// Function's returning a tuple like a builder
// let's be friendly and try to refresh the file
String file = asJavaString(termAt(result, 0));
String newContents = asJavaString(termAt(result, 1));
try {
IFile resource = EditorIOAgent.getFile(runtime.getRuntime().getContext(), file);
StrategoBuilder.setFileContentsDirect(resource, newContents);
} catch (FileNotFoundException e) {
Environment.logException("Problem when handling on save event", e);
} catch (CoreException e) {
Environment.logException("Problem when handling on save event", e);
}
} else if (!"None".equals(cons(result))) {
if (editor.getDescriptor().isDynamicallyLoaded())
Environment.logWarning("Unexpected result from 'on save' strategy: should be None() or (\"filename\", \"contents\"): " + result);
}
} finally {
Environment.getStrategoLock().unlock();
}
} catch (RuntimeException e) {
Environment.logException("Exception in OnSaveService", e);
} catch (Error e) {
Environment.logException("Exception in OnSaveService", e);
}
}
| public void documentChanged(DocumentEvent event) {
if (function == null) return;
//String contents = event.getDocument().get();
try {
Environment.getStrategoLock().lock();
try {
IStrategoTerm ast = editor.getCurrentAst();
if (ast == null) return;
IStrategoTerm result = runtime.invokeSilent(function, ast);
if (result == null) {
runtime.reportRewritingFailed();
String log = runtime.getLog();
Environment.logException(log.length() == 0 ? "Analysis failed" : "Analysis failed:\n" + log);
AstMessageHandler messages = runtime.getMessages();
messages.clearMarkers(SourceAttachment.getResource(ast));
messages.addMarkerFirstLine(SourceAttachment.getResource(ast), "Analysis failed (see error log)", IMarker.SEVERITY_ERROR);
messages.commitAllChanges();
} else if (isTermString(result)) {
// Function's returning a filename
String file = asJavaString(result);
if (new File(file).exists())
RefreshResourcePrimitive.call(runtime.getRuntime().getContext(), file);
} else if (isTermTuple(result) && result.getSubtermCount() == 2 && isTermString(termAt(result, 0)) && isTermString(termAt(result, 1))) {
// Function's returning a tuple like a builder
// let's be friendly and try to refresh the file
String file = asJavaString(termAt(result, 0));
String newContents = asJavaString(termAt(result, 1));
try {
IFile resource = EditorIOAgent.getFile(runtime.getRuntime().getContext(), file);
StrategoBuilder.setFileContentsDirect(resource, newContents);
} catch (FileNotFoundException e) {
Environment.logException("Problem when handling on save event", e);
} catch (CoreException e) {
Environment.logException("Problem when handling on save event", e);
}
} else if (!"None".equals(cons(result))) {
if (editor.getDescriptor().isDynamicallyLoaded())
Environment.logWarning("Unexpected result from 'on save' strategy: should be None() or (\"filename\", \"contents\"): " + result);
}
} finally {
Environment.getStrategoLock().unlock();
}
} catch (RuntimeException e) {
Environment.logException("Exception in OnSaveService", e);
} catch (Error e) {
Environment.logException("Exception in OnSaveService", e);
}
}
|
diff --git a/integration/src/main/java/com/quartercode/quarterbukkit/QuarterBukkitIntegration.java b/integration/src/main/java/com/quartercode/quarterbukkit/QuarterBukkitIntegration.java
index 99d3db3..ea46c3f 100644
--- a/integration/src/main/java/com/quartercode/quarterbukkit/QuarterBukkitIntegration.java
+++ b/integration/src/main/java/com/quartercode/quarterbukkit/QuarterBukkitIntegration.java
@@ -1,181 +1,181 @@
/*
* This file is part of QuarterBukkit-Integration.
* Copyright (c) 2012 QuarterCode <http://www.quartercode.com/>
*
* QuarterBukkit-Integration 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.
*
* QuarterBukkit-Integration 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 QuarterBukkit-Integration. If not, see <http://www.gnu.org/licenses/>.
*/
package com.quartercode.quarterbukkit;
import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.InvalidDescriptionException;
import org.bukkit.plugin.InvalidPluginException;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.UnknownDependencyException;
import com.quartercode.quarterbukkit.api.FileUtils;
import com.quartercode.quarterbukkit.api.query.FilesQuery;
import com.quartercode.quarterbukkit.api.query.FilesQuery.ProjectFile;
import com.quartercode.quarterbukkit.api.query.FilesQuery.VersionParser;
import com.quartercode.quarterbukkit.api.query.QueryException;
/**
* This class is used for integrating QuarterBukkit into a {@link Plugin}.
*/
public class QuarterBukkitIntegration {
private static final String PLUGIN_NAME = "QuarterBukkit-Plugin";
private static final int PROJECT_ID = 47006;
// The plugins which called the integrate() method
private static Set<Plugin> callers = new HashSet<Plugin>();
// Determinates if the integration process was already invoked
private static boolean invoked = false;
/**
* Call this method in onEnable() for integrating QuarterBukkit into your plugin.
* It creates a config where the user has to turn a value to "Yes" for the actual installation.
* The class notfies him on the console and every time an op joins to the server.
*
* @param plugin The {@link Plugin} which tries to integrate QuarterBukkit.
* @return True if QuarterBukkit can be used after the call, false if not.
*/
public static boolean integrate(final Plugin plugin) {
// Register caller
callers.add(plugin);
if (!Bukkit.getPluginManager().isPluginEnabled(PLUGIN_NAME)) {
if (!invoked) {
// Block this part (it should only be called once)
invoked = true;
// Read installation confirmation file
File installConfigFile = new File("plugins/" + PLUGIN_NAME, "install.yml");
try {
if (!installConfigFile.exists()) {
// No installation confirmation file -> create a new one and wait until restart
YamlConfiguration installConfig = new YamlConfiguration();
installConfig.set("install-" + PLUGIN_NAME, true);
installConfig.save(installConfigFile);
} else {
YamlConfiguration installConfig = YamlConfiguration.loadConfiguration(installConfigFile);
if (installConfig.isBoolean("install-" + PLUGIN_NAME) && installConfig.getBoolean("install-" + PLUGIN_NAME)) {
// Installation confirmed -> install
installConfigFile.delete();
install(new File("plugins", PLUGIN_NAME + ".jar"));
return true;
}
}
// Schedule with a time because the integrating plugin might get disabled
new Timer().schedule(new TimerTask() {
@Override
public void run() {
Bukkit.broadcastMessage(ChatColor.YELLOW + "===============[ " + PLUGIN_NAME + " Installation ]===============");
String plugins = "";
for (Plugin caller : callers) {
plugins += ", " + caller.getName();
}
plugins = plugins.substring(2);
- Bukkit.broadcastMessage(ChatColor.RED + "For using " + plugins + " which requires " + PLUGIN_NAME + ", you should " + ChatColor.DARK_AQUA + "restart" + ChatColor.RED + " the server!");
+ Bukkit.broadcastMessage(ChatColor.RED + "For using " + plugins + " which requires " + PLUGIN_NAME + ", you need to " + ChatColor.DARK_AQUA + "restart" + ChatColor.RED + " the server!");
}
- }, 100, 3 * 1000);
+ }, 100, 10 * 1000);
}
catch (UnknownHostException e) {
Bukkit.getLogger().warning("Can't connect to dev.bukkit.org for installing " + PLUGIN_NAME + "!");
}
catch (Exception e) {
Bukkit.getLogger().severe("An error occurred while installing " + PLUGIN_NAME + " (" + e + ")");
e.printStackTrace();
}
}
return false;
} else {
return true;
}
}
private static void install(File target) throws QueryException, IOException, UnknownDependencyException, InvalidPluginException, InvalidDescriptionException {
// ----- Get Latest Version -----
Bukkit.getLogger().info("===============[ " + PLUGIN_NAME + " Installation ]===============");
Bukkit.getLogger().info("Querying server mods api ...");
// Get latest version
List<ProjectFile> avaiableFiles = new FilesQuery(PROJECT_ID, new VersionParser() {
@Override
public String parseVersion(ProjectFile file) {
return file.getName().replace("QuarterBukkit ", "");
}
}).execute();
if (avaiableFiles.size() == 0) {
// No file avaiable
return;
}
ProjectFile latestFile = avaiableFiles.get(avaiableFiles.size() - 1);
Bukkit.getLogger().info("Found the latest version of " + PLUGIN_NAME + ": " + latestFile.getVersion());
// ----- Download and Installation -----
Bukkit.getLogger().info("Installing " + PLUGIN_NAME + " " + latestFile.getVersion());
// Variables
File pluginDir = callers.iterator().next().getDataFolder().getParentFile();
// Download zip
File zip = new File(pluginDir, latestFile.getFileName());
FileUtils.download(latestFile.getLocation().toURL(), zip);
// Unzip zip
File unzipDir = new File(zip.getParent(), zip.getName() + "_extract");
FileUtils.unzip(zip, unzipDir);
FileUtils.delete(zip);
// Get inner directory
File innerUnzipDir = unzipDir.listFiles()[0];
// Overwrite current plugin jar
File pluginJar = new File(pluginDir, PLUGIN_NAME + ".jar");
// FileUtils.delete(pluginJar);
FileUtils.copy(new File(innerUnzipDir, pluginJar.getName()), pluginJar);
// Delete temporary unzip dir
FileUtils.delete(unzipDir);
// Load plugin from file
Bukkit.getPluginManager().enablePlugin(Bukkit.getPluginManager().loadPlugin(pluginJar));
Bukkit.getLogger().info("Successfully installed " + PLUGIN_NAME + " " + latestFile.getVersion() + "!");
}
}
| false | true | public static boolean integrate(final Plugin plugin) {
// Register caller
callers.add(plugin);
if (!Bukkit.getPluginManager().isPluginEnabled(PLUGIN_NAME)) {
if (!invoked) {
// Block this part (it should only be called once)
invoked = true;
// Read installation confirmation file
File installConfigFile = new File("plugins/" + PLUGIN_NAME, "install.yml");
try {
if (!installConfigFile.exists()) {
// No installation confirmation file -> create a new one and wait until restart
YamlConfiguration installConfig = new YamlConfiguration();
installConfig.set("install-" + PLUGIN_NAME, true);
installConfig.save(installConfigFile);
} else {
YamlConfiguration installConfig = YamlConfiguration.loadConfiguration(installConfigFile);
if (installConfig.isBoolean("install-" + PLUGIN_NAME) && installConfig.getBoolean("install-" + PLUGIN_NAME)) {
// Installation confirmed -> install
installConfigFile.delete();
install(new File("plugins", PLUGIN_NAME + ".jar"));
return true;
}
}
// Schedule with a time because the integrating plugin might get disabled
new Timer().schedule(new TimerTask() {
@Override
public void run() {
Bukkit.broadcastMessage(ChatColor.YELLOW + "===============[ " + PLUGIN_NAME + " Installation ]===============");
String plugins = "";
for (Plugin caller : callers) {
plugins += ", " + caller.getName();
}
plugins = plugins.substring(2);
Bukkit.broadcastMessage(ChatColor.RED + "For using " + plugins + " which requires " + PLUGIN_NAME + ", you should " + ChatColor.DARK_AQUA + "restart" + ChatColor.RED + " the server!");
}
}, 100, 3 * 1000);
}
catch (UnknownHostException e) {
Bukkit.getLogger().warning("Can't connect to dev.bukkit.org for installing " + PLUGIN_NAME + "!");
}
catch (Exception e) {
Bukkit.getLogger().severe("An error occurred while installing " + PLUGIN_NAME + " (" + e + ")");
e.printStackTrace();
}
}
return false;
} else {
return true;
}
}
| public static boolean integrate(final Plugin plugin) {
// Register caller
callers.add(plugin);
if (!Bukkit.getPluginManager().isPluginEnabled(PLUGIN_NAME)) {
if (!invoked) {
// Block this part (it should only be called once)
invoked = true;
// Read installation confirmation file
File installConfigFile = new File("plugins/" + PLUGIN_NAME, "install.yml");
try {
if (!installConfigFile.exists()) {
// No installation confirmation file -> create a new one and wait until restart
YamlConfiguration installConfig = new YamlConfiguration();
installConfig.set("install-" + PLUGIN_NAME, true);
installConfig.save(installConfigFile);
} else {
YamlConfiguration installConfig = YamlConfiguration.loadConfiguration(installConfigFile);
if (installConfig.isBoolean("install-" + PLUGIN_NAME) && installConfig.getBoolean("install-" + PLUGIN_NAME)) {
// Installation confirmed -> install
installConfigFile.delete();
install(new File("plugins", PLUGIN_NAME + ".jar"));
return true;
}
}
// Schedule with a time because the integrating plugin might get disabled
new Timer().schedule(new TimerTask() {
@Override
public void run() {
Bukkit.broadcastMessage(ChatColor.YELLOW + "===============[ " + PLUGIN_NAME + " Installation ]===============");
String plugins = "";
for (Plugin caller : callers) {
plugins += ", " + caller.getName();
}
plugins = plugins.substring(2);
Bukkit.broadcastMessage(ChatColor.RED + "For using " + plugins + " which requires " + PLUGIN_NAME + ", you need to " + ChatColor.DARK_AQUA + "restart" + ChatColor.RED + " the server!");
}
}, 100, 10 * 1000);
}
catch (UnknownHostException e) {
Bukkit.getLogger().warning("Can't connect to dev.bukkit.org for installing " + PLUGIN_NAME + "!");
}
catch (Exception e) {
Bukkit.getLogger().severe("An error occurred while installing " + PLUGIN_NAME + " (" + e + ")");
e.printStackTrace();
}
}
return false;
} else {
return true;
}
}
|
diff --git a/survey/src/com/gallatinsystems/survey/device/view/GeoQuestionView.java b/survey/src/com/gallatinsystems/survey/device/view/GeoQuestionView.java
index 9bef15d7..a1ee71a1 100644
--- a/survey/src/com/gallatinsystems/survey/device/view/GeoQuestionView.java
+++ b/survey/src/com/gallatinsystems/survey/device/view/GeoQuestionView.java
@@ -1,391 +1,392 @@
/*
* Copyright (C) 2010-2012 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo FLOW.
*
* Akvo FLOW is free software: you can redistribute it and modify it under the terms of
* the GNU Affero General Public License (AGPL) as published by the Free Software Foundation,
* either version 3 of the License or any later version.
*
* Akvo FLOW is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License included below for more details.
*
* The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>.
*/
package com.gallatinsystems.survey.device.view;
import java.text.DecimalFormat;
import java.util.StringTokenizer;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.method.DigitsKeyListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.gallatinsystems.survey.device.R;
import com.gallatinsystems.survey.device.domain.Question;
import com.gallatinsystems.survey.device.domain.QuestionResponse;
import com.gallatinsystems.survey.device.util.ConstantUtil;
import com.gallatinsystems.survey.device.util.StringUtil;
import com.gallatinsystems.survey.device.util.ViewUtil;
/**
* Question that can handle geographic location input. This question can also
* listen to location updates from the GPS sensor on the device.
*
* @author Christopher Fagiani
*/
public class GeoQuestionView extends QuestionView implements OnClickListener,
LocationListener, OnFocusChangeListener {
private static final int DEFAULT_WIDTH = 200;
private static final float UNKNOWN_ACCURACY = 99999999f;
private static final float ACCURACY_THRESHOLD = 25f;
private static final String DELIM = "|";
private Button geoButton;
private TextView latLabel;
private EditText latField;
private TextView lonLabel;
private EditText generatedCodeField;
private TextView generatedCodeLabel;
private EditText lonField;
private TextView elevationLabel;
private EditText elevationField;
private TextView statusIndicator;
private TextView searchingIndicator;
private float lastAccuracy;
private Resources res;
private boolean needUpdate = false;
private boolean generateCode;
public GeoQuestionView(Context context, Question q, String defaultLang,
String[] langCodes, boolean readOnly) {
super(context, q, defaultLang, langCodes, readOnly);
// TODO: parameterize (add to Question ?)
this.generateCode = true;
init();
}
protected void init() {
Context context = getContext();
TableRow tr = new TableRow(context);
TableLayout innerTable = new TableLayout(context);
TableRow innerRow = new TableRow(context);
DigitsKeyListener numericListener = new DigitsKeyListener(true, true);
res = getResources();
statusIndicator = new TextView(context);
statusIndicator.setText(res.getString(R.string.accuracy) + ": ");
statusIndicator.setTextColor(Color.WHITE);
searchingIndicator = new TextView(context);
searchingIndicator.setText("");
searchingIndicator.setTextColor(Color.WHITE);
latField = new EditText(context);
latField.setWidth(screenWidth / 2);
latField.setOnFocusChangeListener(this);
latField.setKeyListener(numericListener);
latLabel = new TextView(context);
latLabel.setText(R.string.lat);
innerRow.addView(latLabel);
innerRow.addView(latField);
innerTable.addView(innerRow);
innerRow = new TableRow(context);
lonField = new EditText(context);
lonField.setWidth(screenWidth / 2);
lonField.setKeyListener(numericListener);
lonField.setOnFocusChangeListener(this);
lonLabel = new TextView(context);
lonLabel.setText(R.string.lon);
innerRow.addView(lonLabel);
innerRow.addView(lonField);
innerRow.addView(searchingIndicator);
innerTable.addView(innerRow);
innerRow = new TableRow(context);
elevationField = new EditText(context);
elevationField.setWidth(screenWidth / 2);
elevationField.setKeyListener(numericListener);
elevationField.setOnFocusChangeListener(this);
elevationLabel = new TextView(context);
elevationLabel.setText(R.string.elevation);
innerRow.addView(elevationLabel);
innerRow.addView(elevationField);
innerRow.addView(statusIndicator);
innerTable.addView(innerRow);
tr.addView(innerTable);
addView(tr);
tr = new TableRow(context);
geoButton = new Button(context);
geoButton.setText(R.string.getgeo);
geoButton.setOnClickListener(this);
geoButton.setWidth(screenWidth - 50);
tr.addView(geoButton);
addView(tr);
if (generateCode) {
generatedCodeLabel = new TextView(context);
generatedCodeLabel.setText(R.string.generatedcode);
generatedCodeField = new EditText(context);
generatedCodeField.setWidth(DEFAULT_WIDTH);
tr = new TableRow(context);
tr.addView(generatedCodeLabel);
addView(tr);
tr = new TableRow(context);
tr.addView(generatedCodeField);
+ tr.setVisibility(View.GONE);
addView(tr);
}
if (readOnly) {
latField.setFocusable(false);
lonField.setFocusable(false);
elevationField.setFocusable(false);
if (generatedCodeField != null) {
generatedCodeField.setFocusable(false);
}
geoButton.setEnabled(false);
}
if (question.isLocked()) {
latField.setFocusable(false);
lonField.setFocusable(false);
elevationField.setFocusable(false);
if (generatedCodeField != null) {
generatedCodeField.setFocusable(false);
}
}
}
/**
* When the user clicks the "Populate Geo" button, start listening for
* location updates
*/
public void onClick(View v) {
LocationManager locMgr = (LocationManager) getContext()
.getSystemService(Context.LOCATION_SERVICE);
if (locMgr.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
statusIndicator.setText(res.getString(R.string.accuracy) + ": ");
statusIndicator.setTextColor(Color.WHITE);
latField.setText("");
lonField.setText("");
elevationField.setText("");
if (generatedCodeField != null) {
generatedCodeField.setText("");
}
needUpdate = true;
searchingIndicator.setText(R.string.searching);
lastAccuracy = UNKNOWN_ACCURACY;
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
this);
} else {
// we can't turn GPS on directly, the best we can do is launch the
// settings page
ViewUtil.showGPSDialog(getContext());
}
}
/**
* populates the fields on the UI with the location info from the event
*
* @param loc
*/
private void populateLocation(Location loc) {
if (loc.hasAccuracy()) {
statusIndicator.setText(res.getString(R.string.accuracy) + ": "
+ new DecimalFormat("#").format(loc.getAccuracy()) + "m");
if (loc.getAccuracy() <= ACCURACY_THRESHOLD) {
statusIndicator.setTextColor(Color.GREEN);
} else {
statusIndicator.setTextColor(Color.RED);
}
}
latField.setText(loc.getLatitude() + "");
lonField.setText(loc.getLongitude() + "");
// elevation is in meters, even one decimal is way more than GPS
// precision
elevationField.setText(new DecimalFormat("#.#").format(loc.getAltitude()));
if (generateCode) {
generatedCodeField.setText(generateCode(loc.getLatitude(),
loc.getLongitude()));
}
setResponse();
}
/**
* generates a unique code based on the lat/lon passed in. Current algorithm
* returns the concatenation of the integer portion of 1000 times absolute
* value of lat and lon in base 36
*
* @param lat
* @param lon
* @return
*/
private String generateCode(double lat, double lon) {
Long code = Long.parseLong((int) ((Math.abs(lat) * 100000d)) + ""
+ (int) ((Math.abs(lon) * 10000d)));
return Long.toString(code, 36);
}
/**
* clears out the UI fields
*/
@Override
public void resetQuestion(boolean fireEvent) {
super.resetQuestion(fireEvent);
latField.setText("");
lonField.setText("");
elevationField.setText("");
if (generatedCodeField != null) {
generatedCodeField.setText("");
}
searchingIndicator.setText("");
statusIndicator.setText(res.getString(R.string.accuracy) + ": ");
statusIndicator.setTextColor(Color.WHITE);
}
/**
* restores the file path for the file and turns on the complete icon if the
* file exists
*/
@Override
public void rehydrate(QuestionResponse resp) {
super.rehydrate(resp);
if (resp != null) {
if (resp.getValue() != null) {
StringTokenizer strTok = new StringTokenizer(resp.getValue(),
DELIM);
if (strTok.countTokens() >= 3) {
latField.setText(strTok.nextToken());
lonField.setText(strTok.nextToken());
elevationField.setText(strTok.nextToken());
if (generatedCodeField != null && strTok.hasMoreTokens()) {
generatedCodeField.setText(strTok.nextToken());
}
}
}
}
}
@Override
public void questionComplete(Bundle data) {
// completeIcon.setVisibility(View.VISIBLE);
}
/**
* called by the system when it gets location updates.
*/
public void onLocationChanged(Location location) {
float currentAccuracy = location.getAccuracy();
// if accuracy is 0 then the gps has no idea where we're at
if (currentAccuracy > 0) {
// If we are below the accuracy treshold, stop listening for
// updates.
// This means that after the geolocation is 'green', it stays the
// same,
// otherwise it keeps on listening
if (currentAccuracy <= ACCURACY_THRESHOLD) {
LocationManager locMgr = (LocationManager) getContext()
.getSystemService(Context.LOCATION_SERVICE);
locMgr.removeUpdates(this);
searchingIndicator.setText(R.string.ready);
}
// if the location reading is more accurate than the last, update
// the view
if (lastAccuracy > currentAccuracy || needUpdate) {
lastAccuracy = currentAccuracy;
needUpdate = false;
populateLocation(location);
}
} else if (needUpdate) {
needUpdate = true;
populateLocation(location);
}
}
public void onProviderDisabled(String provider) {
// no op. needed for LocationListener interface
}
public void onProviderEnabled(String provider) {
// no op. needed for LocationListener interface
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// no op. needed for LocationListener interface
}
/**
* used to capture lat/lon/elevation if manually typed
*/
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
if (generatedCodeField != null
&& (!StringUtil
.isNullOrEmpty(latField.getText().toString()) && !StringUtil
.isNullOrEmpty(lonField.getText().toString()))) {
generatedCodeField.setText(generateCode(
Double.parseDouble(latField.getText().toString()),
Double.parseDouble(lonField.getText().toString())));
}
setResponse();
}
}
private void setResponse() {
if (!generateCode) {
setResponse(new QuestionResponse(latField.getText() + DELIM
+ lonField.getText() + DELIM + elevationField.getText(),
ConstantUtil.GEO_RESPONSE_TYPE, getQuestion().getId()));
} else {
setResponse(new QuestionResponse(latField.getText() + DELIM
+ lonField.getText() + DELIM + elevationField.getText()
+ DELIM + generatedCodeField.getText(),
ConstantUtil.GEO_RESPONSE_TYPE, getQuestion().getId()));
}
}
@Override
public void releaseResources() {
// Remove updates from LocationManager, to allow this object being GC
// and avoid an unnecessary use of the GPS and battery draining.
LocationManager locMgr = (LocationManager) getContext()
.getSystemService(Context.LOCATION_SERVICE);
locMgr.removeUpdates(this);
// Update the UI in case we come back later to the same instance
searchingIndicator.setText("");
}
}
| true | true | protected void init() {
Context context = getContext();
TableRow tr = new TableRow(context);
TableLayout innerTable = new TableLayout(context);
TableRow innerRow = new TableRow(context);
DigitsKeyListener numericListener = new DigitsKeyListener(true, true);
res = getResources();
statusIndicator = new TextView(context);
statusIndicator.setText(res.getString(R.string.accuracy) + ": ");
statusIndicator.setTextColor(Color.WHITE);
searchingIndicator = new TextView(context);
searchingIndicator.setText("");
searchingIndicator.setTextColor(Color.WHITE);
latField = new EditText(context);
latField.setWidth(screenWidth / 2);
latField.setOnFocusChangeListener(this);
latField.setKeyListener(numericListener);
latLabel = new TextView(context);
latLabel.setText(R.string.lat);
innerRow.addView(latLabel);
innerRow.addView(latField);
innerTable.addView(innerRow);
innerRow = new TableRow(context);
lonField = new EditText(context);
lonField.setWidth(screenWidth / 2);
lonField.setKeyListener(numericListener);
lonField.setOnFocusChangeListener(this);
lonLabel = new TextView(context);
lonLabel.setText(R.string.lon);
innerRow.addView(lonLabel);
innerRow.addView(lonField);
innerRow.addView(searchingIndicator);
innerTable.addView(innerRow);
innerRow = new TableRow(context);
elevationField = new EditText(context);
elevationField.setWidth(screenWidth / 2);
elevationField.setKeyListener(numericListener);
elevationField.setOnFocusChangeListener(this);
elevationLabel = new TextView(context);
elevationLabel.setText(R.string.elevation);
innerRow.addView(elevationLabel);
innerRow.addView(elevationField);
innerRow.addView(statusIndicator);
innerTable.addView(innerRow);
tr.addView(innerTable);
addView(tr);
tr = new TableRow(context);
geoButton = new Button(context);
geoButton.setText(R.string.getgeo);
geoButton.setOnClickListener(this);
geoButton.setWidth(screenWidth - 50);
tr.addView(geoButton);
addView(tr);
if (generateCode) {
generatedCodeLabel = new TextView(context);
generatedCodeLabel.setText(R.string.generatedcode);
generatedCodeField = new EditText(context);
generatedCodeField.setWidth(DEFAULT_WIDTH);
tr = new TableRow(context);
tr.addView(generatedCodeLabel);
addView(tr);
tr = new TableRow(context);
tr.addView(generatedCodeField);
addView(tr);
}
if (readOnly) {
latField.setFocusable(false);
lonField.setFocusable(false);
elevationField.setFocusable(false);
if (generatedCodeField != null) {
generatedCodeField.setFocusable(false);
}
geoButton.setEnabled(false);
}
if (question.isLocked()) {
latField.setFocusable(false);
lonField.setFocusable(false);
elevationField.setFocusable(false);
if (generatedCodeField != null) {
generatedCodeField.setFocusable(false);
}
}
}
| protected void init() {
Context context = getContext();
TableRow tr = new TableRow(context);
TableLayout innerTable = new TableLayout(context);
TableRow innerRow = new TableRow(context);
DigitsKeyListener numericListener = new DigitsKeyListener(true, true);
res = getResources();
statusIndicator = new TextView(context);
statusIndicator.setText(res.getString(R.string.accuracy) + ": ");
statusIndicator.setTextColor(Color.WHITE);
searchingIndicator = new TextView(context);
searchingIndicator.setText("");
searchingIndicator.setTextColor(Color.WHITE);
latField = new EditText(context);
latField.setWidth(screenWidth / 2);
latField.setOnFocusChangeListener(this);
latField.setKeyListener(numericListener);
latLabel = new TextView(context);
latLabel.setText(R.string.lat);
innerRow.addView(latLabel);
innerRow.addView(latField);
innerTable.addView(innerRow);
innerRow = new TableRow(context);
lonField = new EditText(context);
lonField.setWidth(screenWidth / 2);
lonField.setKeyListener(numericListener);
lonField.setOnFocusChangeListener(this);
lonLabel = new TextView(context);
lonLabel.setText(R.string.lon);
innerRow.addView(lonLabel);
innerRow.addView(lonField);
innerRow.addView(searchingIndicator);
innerTable.addView(innerRow);
innerRow = new TableRow(context);
elevationField = new EditText(context);
elevationField.setWidth(screenWidth / 2);
elevationField.setKeyListener(numericListener);
elevationField.setOnFocusChangeListener(this);
elevationLabel = new TextView(context);
elevationLabel.setText(R.string.elevation);
innerRow.addView(elevationLabel);
innerRow.addView(elevationField);
innerRow.addView(statusIndicator);
innerTable.addView(innerRow);
tr.addView(innerTable);
addView(tr);
tr = new TableRow(context);
geoButton = new Button(context);
geoButton.setText(R.string.getgeo);
geoButton.setOnClickListener(this);
geoButton.setWidth(screenWidth - 50);
tr.addView(geoButton);
addView(tr);
if (generateCode) {
generatedCodeLabel = new TextView(context);
generatedCodeLabel.setText(R.string.generatedcode);
generatedCodeField = new EditText(context);
generatedCodeField.setWidth(DEFAULT_WIDTH);
tr = new TableRow(context);
tr.addView(generatedCodeLabel);
addView(tr);
tr = new TableRow(context);
tr.addView(generatedCodeField);
tr.setVisibility(View.GONE);
addView(tr);
}
if (readOnly) {
latField.setFocusable(false);
lonField.setFocusable(false);
elevationField.setFocusable(false);
if (generatedCodeField != null) {
generatedCodeField.setFocusable(false);
}
geoButton.setEnabled(false);
}
if (question.isLocked()) {
latField.setFocusable(false);
lonField.setFocusable(false);
elevationField.setFocusable(false);
if (generatedCodeField != null) {
generatedCodeField.setFocusable(false);
}
}
}
|
diff --git a/solr/src/java/org/apache/solr/search/ReturnFields.java b/solr/src/java/org/apache/solr/search/ReturnFields.java
index e3061f62d..9bc5411c0 100644
--- a/solr/src/java/org/apache/solr/search/ReturnFields.java
+++ b/solr/src/java/org/apache/solr/search/ReturnFields.java
@@ -1,362 +1,359 @@
/**
* 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.solr.search;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.io.FilenameUtils;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.Query;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.params.CommonParams;
import org.apache.solr.common.params.ShardParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.transform.DocIdAugmenter;
import org.apache.solr.response.transform.DocTransformer;
import org.apache.solr.response.transform.DocTransformers;
import org.apache.solr.response.transform.ExplainAugmenter;
import org.apache.solr.response.transform.RenameFieldsTransformer;
import org.apache.solr.response.transform.ScoreAugmenter;
import org.apache.solr.response.transform.ValueAugmenter;
import org.apache.solr.response.transform.ValueSourceAugmenter;
import org.apache.solr.search.function.FunctionQuery;
import org.apache.solr.search.function.QueryValueSource;
import org.apache.solr.search.function.ValueSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A class representing the return fields
*
* @version $Id: JSONResponseWriter.java 1065304 2011-01-30 15:10:15Z rmuir $
* @since solr 4.0
*/
public class ReturnFields
{
static final Logger log = LoggerFactory.getLogger( ReturnFields.class );
// Special Field Keys
public static final String SCORE = "score";
// some special syntax for these guys?
// Should these have factories... via plugin utils...
public static final String DOCID = "_docid_";
public static final String SHARD = "_shard_";
public static final String EXPLAIN = "_explain_";
private final List<String> globs = new ArrayList<String>(1);
private final Set<String> fields = new LinkedHashSet<String>(); // order is important for CSVResponseWriter
private Set<String> okFieldNames = new HashSet<String>(); // Collection of everything that could match
private DocTransformer transformer;
private boolean _wantsScore = false;
private boolean _wantsAllFields = false;
public ReturnFields() {
_wantsAllFields = true;
}
public ReturnFields(SolrQueryRequest req) {
this( req.getParams().get(CommonParams.FL), req );
}
public ReturnFields(String fl, SolrQueryRequest req) {
// this( (fl==null)?null:SolrPluginUtils.split(fl), req );
if( fl == null ) {
parseFieldList((String[])null, req);
}
else {
if( fl.trim().length() == 0 ) {
// legacy thing to support fl=' ' => fl=*,score!
// maybe time to drop support for this?
// See ConvertedLegacyTest
_wantsScore = true;
_wantsAllFields = true;
transformer = new ScoreAugmenter(SCORE);
}
else {
parseFieldList( new String[]{fl}, req);
}
}
req.getCore().log.info("fields=" + fields + "\t globs="+globs + "\t transformer="+transformer); // nocommit
}
public ReturnFields(String[] fl, SolrQueryRequest req) {
parseFieldList(fl, req);
req.getCore().log.info("fields=" + fields + "\t globs="+globs + "\t transformer="+transformer); // nocommit
}
private void parseFieldList(String[] fl, SolrQueryRequest req) {
_wantsScore = false;
_wantsAllFields = false;
if (fl == null || fl.length == 0 || fl.length == 1 && fl[0].length()==0) {
_wantsAllFields = true;
return;
}
NamedList<String> rename = new NamedList<String>();
DocTransformers augmenters = new DocTransformers();
for (String fieldList : fl) {
add(fieldList,rename,augmenters,req);
}
if( rename.size() > 0 ) {
for( int i=0; i<rename.size(); i++ ) {
okFieldNames.add( rename.getVal(i) );
}
augmenters.addTransformer( new RenameFieldsTransformer( rename ) );
}
// Legacy behavior? "score" == "*,score" Distributed tests for this
if( fields.size() == 1 && _wantsScore ) {
_wantsAllFields = true;
}
if( !_wantsAllFields ) {
if( !globs.isEmpty() ) {
// TODO??? need to fill up the fields with matching field names in the index
// and add them to okFieldNames?
// maybe just get all fields?
// this would disable field selection optimization... i think thatis OK
fields.clear(); // this will get all fields, and use wantsField to limit
}
okFieldNames.addAll( fields );
}
if( augmenters.size() == 1 ) {
transformer = augmenters.getTransformer(0);
}
else if( augmenters.size() > 1 ) {
transformer = augmenters;
}
}
private void add(String fl, NamedList<String> rename, DocTransformers augmenters, SolrQueryRequest req) {
if( fl == null ) {
return;
}
try {
QueryParsing.StrParser sp = new QueryParsing.StrParser(fl);
for(;;) {
sp.opt(',');
sp.eatws();
if (sp.pos >= sp.end) break;
int start = sp.pos;
// short circuit test for a really simple field name
String key = null;
String field = sp.getId(null);
char ch = sp.ch();
if (field != null) {
if (sp.opt('=')) {
// this was a key, not a field name
key = field;
field = null;
sp.eatws();
start = sp.pos;
} else {
if (ch==' ' || ch == ',' || ch==0) {
String disp = (key==null) ? field : key;
fields.add( field ); // need to put in the map to maintain order for things like CSVResponseWriter
okFieldNames.add( field );
okFieldNames.add( key );
// a valid field name
if(SCORE.equals(field)) {
_wantsScore = true;
augmenters.addTransformer( new ScoreAugmenter( disp ) );
}
else if( DOCID.equals( field ) ) {
augmenters.addTransformer( new DocIdAugmenter( disp ) );
}
else if( SHARD.equals( field ) ) {
String id = "TODO! getshardid???";
augmenters.addTransformer( new ValueAugmenter( disp, id ) );
}
else if( EXPLAIN.equals( field ) ) {
// TODO? pass params to transformers?
augmenters.addTransformer( new ExplainAugmenter( disp, ExplainAugmenter.Style.NL ) );
}
- else if( key != null ){
- rename.add(field, key);
- }
continue;
}
// an invalid field name... reset the position pointer to retry
sp.pos = start;
field = null;
}
}
- if (field == null && sp.pos > start) {
- // if we are here, we must have read "key = "
+ if (key != null) {
+ // we read "key = "
field = sp.getId(null);
ch = sp.ch();
if (field != null && (ch==' ' || ch == ',' || ch==0)) {
rename.add(field, key);
okFieldNames.add( field );
okFieldNames.add( key );
continue;
}
// an invalid field name... reset the position pointer to retry
sp.pos = start;
field = null;
}
if (field == null) {
// We didn't find a simple name, so let's see if it's a globbed field name.
// Globbing only works with recommended field names.
field = sp.getGlobbedId(null);
ch = sp.ch();
if (field != null && (ch==' ' || ch == ',' || ch==0)) {
// "*" looks and acts like a glob, but we give it special treatment
if ("*".equals(field)) {
_wantsAllFields = true;
} else {
globs.add(field);
}
continue;
}
// an invalid glob
sp.pos = start;
}
// let's try it as a function instead
String funcStr = sp.val.substring(start);
QParser parser = QParser.getParser(funcStr, FunctionQParserPlugin.NAME, req);
Query q = null;
ValueSource vs = null;
try {
if (parser instanceof FunctionQParser) {
FunctionQParser fparser = (FunctionQParser)parser;
fparser.setParseMultipleSources(false);
fparser.setParseToEnd(false);
q = fparser.getQuery();
if (fparser.localParams != null) {
if (fparser.valFollowedParams) {
// need to find the end of the function query via the string parser
int leftOver = fparser.sp.end - fparser.sp.pos;
sp.pos = sp.end - leftOver; // reset our parser to the same amount of leftover
} else {
// the value was via the "v" param in localParams, so we need to find
// the end of the local params themselves to pick up where we left off
sp.pos = start + fparser.localParamsEnd;
}
} else {
// need to find the end of the function query via the string parser
int leftOver = fparser.sp.end - fparser.sp.pos;
sp.pos = sp.end - leftOver; // reset our parser to the same amount of leftover
}
} else {
// A QParser that's not for function queries.
// It must have been specified via local params.
q = parser.getQuery();
assert parser.getLocalParams() != null;
sp.pos = start + parser.localParamsEnd;
}
if (q instanceof FunctionQuery) {
vs = ((FunctionQuery)q).getValueSource();
} else {
vs = new QueryValueSource(q, 0.0f);
}
if (key==null) {
SolrParams localParams = parser.getLocalParams();
if (localParams != null) {
key = localParams.get("key");
}
if (key == null) {
// use the function name itself as the field name
key = sp.val.substring(start, sp.pos);
}
}
augmenters.addTransformer( new ValueSourceAugmenter( key, parser, vs ) );
}
catch (ParseException e) {
// try again, simple rules for a field name with no whitespace
sp.pos = start;
field = sp.getSimpleString();
if (req.getSchema().getFieldOrNull(field) != null) {
// OK, it was an oddly named field
fields.add(field);
if( key != null ) {
rename.add(field, key);
}
} else {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Error parsing fieldname: " + e.getMessage(), e);
}
}
// end try as function
} // end for(;;)
} catch (ParseException e) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Error parsing fieldname", e);
}
}
public Set<String> getLuceneFieldNames()
{
return (_wantsAllFields || fields.isEmpty()) ? null : fields;
}
public boolean wantsAllFields()
{
return _wantsAllFields;
}
public boolean wantsScore()
{
return _wantsScore;
}
public boolean wantsField( String name )
{
if( _wantsAllFields || okFieldNames.contains( name ) ){
return true;
}
for( String s : globs ) {
// TODO something better?
if( FilenameUtils.wildcardMatch( name, s ) ) {
return true;
}
}
return false;
}
public DocTransformer getTransformer()
{
return transformer;
}
}
| false | true | private void add(String fl, NamedList<String> rename, DocTransformers augmenters, SolrQueryRequest req) {
if( fl == null ) {
return;
}
try {
QueryParsing.StrParser sp = new QueryParsing.StrParser(fl);
for(;;) {
sp.opt(',');
sp.eatws();
if (sp.pos >= sp.end) break;
int start = sp.pos;
// short circuit test for a really simple field name
String key = null;
String field = sp.getId(null);
char ch = sp.ch();
if (field != null) {
if (sp.opt('=')) {
// this was a key, not a field name
key = field;
field = null;
sp.eatws();
start = sp.pos;
} else {
if (ch==' ' || ch == ',' || ch==0) {
String disp = (key==null) ? field : key;
fields.add( field ); // need to put in the map to maintain order for things like CSVResponseWriter
okFieldNames.add( field );
okFieldNames.add( key );
// a valid field name
if(SCORE.equals(field)) {
_wantsScore = true;
augmenters.addTransformer( new ScoreAugmenter( disp ) );
}
else if( DOCID.equals( field ) ) {
augmenters.addTransformer( new DocIdAugmenter( disp ) );
}
else if( SHARD.equals( field ) ) {
String id = "TODO! getshardid???";
augmenters.addTransformer( new ValueAugmenter( disp, id ) );
}
else if( EXPLAIN.equals( field ) ) {
// TODO? pass params to transformers?
augmenters.addTransformer( new ExplainAugmenter( disp, ExplainAugmenter.Style.NL ) );
}
else if( key != null ){
rename.add(field, key);
}
continue;
}
// an invalid field name... reset the position pointer to retry
sp.pos = start;
field = null;
}
}
if (field == null && sp.pos > start) {
// if we are here, we must have read "key = "
field = sp.getId(null);
ch = sp.ch();
if (field != null && (ch==' ' || ch == ',' || ch==0)) {
rename.add(field, key);
okFieldNames.add( field );
okFieldNames.add( key );
continue;
}
// an invalid field name... reset the position pointer to retry
sp.pos = start;
field = null;
}
if (field == null) {
// We didn't find a simple name, so let's see if it's a globbed field name.
// Globbing only works with recommended field names.
field = sp.getGlobbedId(null);
ch = sp.ch();
if (field != null && (ch==' ' || ch == ',' || ch==0)) {
// "*" looks and acts like a glob, but we give it special treatment
if ("*".equals(field)) {
_wantsAllFields = true;
} else {
globs.add(field);
}
continue;
}
// an invalid glob
sp.pos = start;
}
// let's try it as a function instead
String funcStr = sp.val.substring(start);
QParser parser = QParser.getParser(funcStr, FunctionQParserPlugin.NAME, req);
Query q = null;
ValueSource vs = null;
try {
if (parser instanceof FunctionQParser) {
FunctionQParser fparser = (FunctionQParser)parser;
fparser.setParseMultipleSources(false);
fparser.setParseToEnd(false);
q = fparser.getQuery();
if (fparser.localParams != null) {
if (fparser.valFollowedParams) {
// need to find the end of the function query via the string parser
int leftOver = fparser.sp.end - fparser.sp.pos;
sp.pos = sp.end - leftOver; // reset our parser to the same amount of leftover
} else {
// the value was via the "v" param in localParams, so we need to find
// the end of the local params themselves to pick up where we left off
sp.pos = start + fparser.localParamsEnd;
}
} else {
// need to find the end of the function query via the string parser
int leftOver = fparser.sp.end - fparser.sp.pos;
sp.pos = sp.end - leftOver; // reset our parser to the same amount of leftover
}
} else {
// A QParser that's not for function queries.
// It must have been specified via local params.
q = parser.getQuery();
assert parser.getLocalParams() != null;
sp.pos = start + parser.localParamsEnd;
}
if (q instanceof FunctionQuery) {
vs = ((FunctionQuery)q).getValueSource();
} else {
vs = new QueryValueSource(q, 0.0f);
}
if (key==null) {
SolrParams localParams = parser.getLocalParams();
if (localParams != null) {
key = localParams.get("key");
}
if (key == null) {
// use the function name itself as the field name
key = sp.val.substring(start, sp.pos);
}
}
augmenters.addTransformer( new ValueSourceAugmenter( key, parser, vs ) );
}
catch (ParseException e) {
// try again, simple rules for a field name with no whitespace
sp.pos = start;
field = sp.getSimpleString();
if (req.getSchema().getFieldOrNull(field) != null) {
// OK, it was an oddly named field
fields.add(field);
if( key != null ) {
rename.add(field, key);
}
} else {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Error parsing fieldname: " + e.getMessage(), e);
}
}
// end try as function
} // end for(;;)
} catch (ParseException e) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Error parsing fieldname", e);
}
}
| private void add(String fl, NamedList<String> rename, DocTransformers augmenters, SolrQueryRequest req) {
if( fl == null ) {
return;
}
try {
QueryParsing.StrParser sp = new QueryParsing.StrParser(fl);
for(;;) {
sp.opt(',');
sp.eatws();
if (sp.pos >= sp.end) break;
int start = sp.pos;
// short circuit test for a really simple field name
String key = null;
String field = sp.getId(null);
char ch = sp.ch();
if (field != null) {
if (sp.opt('=')) {
// this was a key, not a field name
key = field;
field = null;
sp.eatws();
start = sp.pos;
} else {
if (ch==' ' || ch == ',' || ch==0) {
String disp = (key==null) ? field : key;
fields.add( field ); // need to put in the map to maintain order for things like CSVResponseWriter
okFieldNames.add( field );
okFieldNames.add( key );
// a valid field name
if(SCORE.equals(field)) {
_wantsScore = true;
augmenters.addTransformer( new ScoreAugmenter( disp ) );
}
else if( DOCID.equals( field ) ) {
augmenters.addTransformer( new DocIdAugmenter( disp ) );
}
else if( SHARD.equals( field ) ) {
String id = "TODO! getshardid???";
augmenters.addTransformer( new ValueAugmenter( disp, id ) );
}
else if( EXPLAIN.equals( field ) ) {
// TODO? pass params to transformers?
augmenters.addTransformer( new ExplainAugmenter( disp, ExplainAugmenter.Style.NL ) );
}
continue;
}
// an invalid field name... reset the position pointer to retry
sp.pos = start;
field = null;
}
}
if (key != null) {
// we read "key = "
field = sp.getId(null);
ch = sp.ch();
if (field != null && (ch==' ' || ch == ',' || ch==0)) {
rename.add(field, key);
okFieldNames.add( field );
okFieldNames.add( key );
continue;
}
// an invalid field name... reset the position pointer to retry
sp.pos = start;
field = null;
}
if (field == null) {
// We didn't find a simple name, so let's see if it's a globbed field name.
// Globbing only works with recommended field names.
field = sp.getGlobbedId(null);
ch = sp.ch();
if (field != null && (ch==' ' || ch == ',' || ch==0)) {
// "*" looks and acts like a glob, but we give it special treatment
if ("*".equals(field)) {
_wantsAllFields = true;
} else {
globs.add(field);
}
continue;
}
// an invalid glob
sp.pos = start;
}
// let's try it as a function instead
String funcStr = sp.val.substring(start);
QParser parser = QParser.getParser(funcStr, FunctionQParserPlugin.NAME, req);
Query q = null;
ValueSource vs = null;
try {
if (parser instanceof FunctionQParser) {
FunctionQParser fparser = (FunctionQParser)parser;
fparser.setParseMultipleSources(false);
fparser.setParseToEnd(false);
q = fparser.getQuery();
if (fparser.localParams != null) {
if (fparser.valFollowedParams) {
// need to find the end of the function query via the string parser
int leftOver = fparser.sp.end - fparser.sp.pos;
sp.pos = sp.end - leftOver; // reset our parser to the same amount of leftover
} else {
// the value was via the "v" param in localParams, so we need to find
// the end of the local params themselves to pick up where we left off
sp.pos = start + fparser.localParamsEnd;
}
} else {
// need to find the end of the function query via the string parser
int leftOver = fparser.sp.end - fparser.sp.pos;
sp.pos = sp.end - leftOver; // reset our parser to the same amount of leftover
}
} else {
// A QParser that's not for function queries.
// It must have been specified via local params.
q = parser.getQuery();
assert parser.getLocalParams() != null;
sp.pos = start + parser.localParamsEnd;
}
if (q instanceof FunctionQuery) {
vs = ((FunctionQuery)q).getValueSource();
} else {
vs = new QueryValueSource(q, 0.0f);
}
if (key==null) {
SolrParams localParams = parser.getLocalParams();
if (localParams != null) {
key = localParams.get("key");
}
if (key == null) {
// use the function name itself as the field name
key = sp.val.substring(start, sp.pos);
}
}
augmenters.addTransformer( new ValueSourceAugmenter( key, parser, vs ) );
}
catch (ParseException e) {
// try again, simple rules for a field name with no whitespace
sp.pos = start;
field = sp.getSimpleString();
if (req.getSchema().getFieldOrNull(field) != null) {
// OK, it was an oddly named field
fields.add(field);
if( key != null ) {
rename.add(field, key);
}
} else {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Error parsing fieldname: " + e.getMessage(), e);
}
}
// end try as function
} // end for(;;)
} catch (ParseException e) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Error parsing fieldname", e);
}
}
|
diff --git a/src/main/java/org/openengsb/connector/mavendep/internal/MavendepServiceInstanceFactory.java b/src/main/java/org/openengsb/connector/mavendep/internal/MavendepServiceInstanceFactory.java
index d3e7804..b3f4382 100644
--- a/src/main/java/org/openengsb/connector/mavendep/internal/MavendepServiceInstanceFactory.java
+++ b/src/main/java/org/openengsb/connector/mavendep/internal/MavendepServiceInstanceFactory.java
@@ -1,51 +1,51 @@
/**
* Licensed to the Austrian Association for Software Tool Integration (AASTI)
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. The AASTI 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.openengsb.connector.mavendep.internal;
import java.util.Map;
import org.openengsb.core.api.Connector;
import org.openengsb.core.common.AbstractConnectorInstanceFactory;
import org.openengsb.domain.dependency.DependencyDomainEvents;
public class MavendepServiceInstanceFactory extends AbstractConnectorInstanceFactory<MavendepServiceImpl> {
private DependencyDomainEvents dependencyEvents;
@Override
public Connector createNewInstance(String id) {
MavendepServiceImpl service = new MavendepServiceImpl(id);
service.setDependencyEvents(dependencyEvents);
return service;
}
public void setDependencyEvents(DependencyDomainEvents events) {
this.dependencyEvents = events;
}
@Override
public void doApplyAttributes(MavendepServiceImpl instance,
Map<String, String> attributes) {
if (attributes.containsKey("pomfile")) {
instance.setPomFile(attributes.get("pomfile"));
}
- if (attributes.containsKey("attribute")) {
- instance.setAttribute(attributes.get("attribute"));
+ if (attributes.containsKey("property")) {
+ instance.setAttribute(attributes.get("property"));
}
}
}
| true | true | public void doApplyAttributes(MavendepServiceImpl instance,
Map<String, String> attributes) {
if (attributes.containsKey("pomfile")) {
instance.setPomFile(attributes.get("pomfile"));
}
if (attributes.containsKey("attribute")) {
instance.setAttribute(attributes.get("attribute"));
}
}
| public void doApplyAttributes(MavendepServiceImpl instance,
Map<String, String> attributes) {
if (attributes.containsKey("pomfile")) {
instance.setPomFile(attributes.get("pomfile"));
}
if (attributes.containsKey("property")) {
instance.setAttribute(attributes.get("property"));
}
}
|
diff --git a/src/com/android/exchange/service/EasAutoDiscover.java b/src/com/android/exchange/service/EasAutoDiscover.java
index 4f7558ef..0713b0db 100644
--- a/src/com/android/exchange/service/EasAutoDiscover.java
+++ b/src/com/android/exchange/service/EasAutoDiscover.java
@@ -1,405 +1,405 @@
package com.android.exchange.service;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.util.Xml;
import com.android.emailcommon.mail.MessagingException;
import com.android.emailcommon.provider.Account;
import com.android.emailcommon.provider.HostAuth;
import com.android.emailcommon.service.EmailServiceProxy;
import com.android.exchange.Eas;
import com.android.exchange.EasResponse;
import com.android.mail.utils.LogUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
/**
* Performs Autodiscover for Exchange servers. This feature tries to find all the configuration
* options needed based on just a username and password.
*/
public class EasAutoDiscover extends EasServerConnection {
private static final String TAG = Eas.LOG_TAG;
private static final String AUTO_DISCOVER_SCHEMA_PREFIX =
"http://schemas.microsoft.com/exchange/autodiscover/mobilesync/";
private static final String AUTO_DISCOVER_PAGE = "/autodiscover/autodiscover.xml";
// Set of string constants for parsing the autodiscover response.
// TODO: Merge this into Tags.java? It's not quite the same but conceptually belongs there.
private static final String ELEMENT_NAME_SERVER = "Server";
private static final String ELEMENT_NAME_TYPE = "Type";
private static final String ELEMENT_NAME_MOBILE_SYNC = "MobileSync";
private static final String ELEMENT_NAME_URL = "Url";
private static final String ELEMENT_NAME_SETTINGS = "Settings";
private static final String ELEMENT_NAME_ACTION = "Action";
private static final String ELEMENT_NAME_ERROR = "Error";
private static final String ELEMENT_NAME_REDIRECT = "Redirect";
private static final String ELEMENT_NAME_USER = "User";
private static final String ELEMENT_NAME_EMAIL_ADDRESS = "EMailAddress";
private static final String ELEMENT_NAME_DISPLAY_NAME = "DisplayName";
private static final String ELEMENT_NAME_RESPONSE = "Response";
private static final String ELEMENT_NAME_AUTODISCOVER = "Autodiscover";
public EasAutoDiscover(final Context context, final String username, final String password) {
super(context, new Account(), new HostAuth());
mHostAuth.mLogin = username;
mHostAuth.mPassword = password;
mHostAuth.mFlags = HostAuth.FLAG_AUTHENTICATE | HostAuth.FLAG_SSL;
mHostAuth.mPort = 443;
}
/**
* Do all the work of autodiscovery.
* @return A {@link Bundle} with the host information if autodiscovery succeeded. If we failed
* due to an authentication failure, we return a {@link Bundle} with no host info but with
* an appropriate error code. Otherwise, we return null.
*/
public Bundle doAutodiscover() {
final String domain = getDomain();
if (domain == null) {
return null;
}
final StringEntity entity = buildRequestEntity();
if (entity == null) {
return null;
}
try {
final HttpPost post = makePost("https://" + domain + AUTO_DISCOVER_PAGE, entity,
"text/xml", false);
final EasResponse resp = getResponse(post, domain);
if (resp == null) {
return null;
}
try {
// resp is either an authentication error, or a good response.
final int code = resp.getStatus();
if (code == HttpStatus.SC_UNAUTHORIZED) {
- final Bundle bundle = new Bundle(1);
- bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE,
- MessagingException.AUTODISCOVER_AUTHENTICATION_FAILED);
- return bundle;
+ // We actually don't know if this is because it's an actual EAS auth error,
+ // or just HTTP 401 (e.g. you're just hitting some random server).
+ // Let's just dump them out of autodiscover in this case.
+ return null;
} else {
final HostAuth hostAuth = parseAutodiscover(resp);
if (hostAuth != null) {
// Fill in the rest of the HostAuth
// We use the user name and password that were successful during
// the autodiscover process
hostAuth.mLogin = mHostAuth.mLogin;
hostAuth.mPassword = mHostAuth.mPassword;
// Note: there is no way we can auto-discover the proper client
// SSL certificate to use, if one is needed.
hostAuth.mPort = 443;
hostAuth.mProtocol = Eas.PROTOCOL;
hostAuth.mFlags = HostAuth.FLAG_SSL | HostAuth.FLAG_AUTHENTICATE;
final Bundle bundle = new Bundle(2);
bundle.putParcelable(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_HOST_AUTH,
hostAuth);
bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE,
MessagingException.NO_ERROR);
return bundle;
}
}
} finally {
resp.close();
}
} catch (final IllegalArgumentException e) {
// This happens when the domain is malformatted.
// TODO: Fix sanitizing of the domain -- we try to in UI but apparently not correctly.
LogUtils.e(TAG, "ISE with domain: %s", domain);
}
return null;
}
/**
* Get the domain of our account.
* @return The domain of the email address.
*/
private String getDomain() {
final int amp = mHostAuth.mLogin.indexOf('@');
if (amp < 0) {
return null;
}
return mHostAuth.mLogin.substring(amp + 1);
}
/**
* Create the payload of the request.
* @return A {@link StringEntity} for the request XML.
*/
private StringEntity buildRequestEntity() {
try {
final XmlSerializer s = Xml.newSerializer();
final ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
s.setOutput(os, "UTF-8");
s.startDocument("UTF-8", false);
s.startTag(null, "Autodiscover");
s.attribute(null, "xmlns", AUTO_DISCOVER_SCHEMA_PREFIX + "requestschema/2006");
s.startTag(null, "Request");
s.startTag(null, "EMailAddress").text(mHostAuth.mLogin).endTag(null, "EMailAddress");
s.startTag(null, "AcceptableResponseSchema");
s.text(AUTO_DISCOVER_SCHEMA_PREFIX + "responseschema/2006");
s.endTag(null, "AcceptableResponseSchema");
s.endTag(null, "Request");
s.endTag(null, "Autodiscover");
s.endDocument();
return new StringEntity(os.toString());
} catch (final IOException e) {
// For all exception types, we can simply punt on autodiscover.
} catch (final IllegalArgumentException e) {
} catch (final IllegalStateException e) {
}
return null;
}
/**
* Perform all requests necessary and get the server response. If the post fails or is
* redirected, we alter the post and retry.
* @param post The initial {@link HttpPost} for this request.
* @param domain The domain for our account.
* @return If this request succeeded or has an unrecoverable authentication error, an
* {@link EasResponse} with the details. For other errors, we return null.
*/
private EasResponse getResponse(final HttpPost post, final String domain) {
EasResponse resp = doPost(post, true);
if (resp == null) {
LogUtils.d(TAG, "Error in autodiscover, trying aternate address");
post.setURI(URI.create("https://autodiscover." + domain + AUTO_DISCOVER_PAGE));
resp = doPost(post, true);
}
return resp;
}
/**
* Perform one attempt to get autodiscover information. Redirection and some authentication
* errors are handled by recursively calls with modified host information.
* @param post The {@link HttpPost} for this request.
* @param canRetry Whether we can retry after an authentication failure.
* @return If this request succeeded or has an unrecoverable authentication error, an
* {@link EasResponse} with the details. For other errors, we return null.
*/
private EasResponse doPost(final HttpPost post, final boolean canRetry) {
final EasResponse resp;
try {
resp = executePost(post);
} catch (final IOException e) {
return null;
}
final int code = resp.getStatus();
if (resp.isRedirectError()) {
final String loc = resp.getRedirectAddress();
if (loc != null && loc.startsWith("http")) {
LogUtils.d(TAG, "Posting autodiscover to redirect: " + loc);
redirectHostAuth(loc);
post.setURI(URI.create(loc));
return doPost(post, canRetry);
}
return null;
}
if (code == HttpStatus.SC_UNAUTHORIZED) {
if (canRetry && mHostAuth.mLogin.contains("@")) {
// Try again using the bare user name
final int atSignIndex = mHostAuth.mLogin.indexOf('@');
mHostAuth.mLogin = mHostAuth.mLogin.substring(0, atSignIndex);
LogUtils.d(TAG, "401 received; trying username: %s", mHostAuth.mLogin);
resetAuthorization(post);
return doPost(post, false);
}
} else if (code != HttpStatus.SC_OK) {
// We'll try the next address if this doesn't work
LogUtils.d(TAG, "Bad response code when posting autodiscover: %d", code);
return null;
}
return resp;
}
/**
* Parse the Server element of the server response.
* @param parser The {@link XmlPullParser}.
* @param hostAuth The {@link HostAuth} to populate with the results of parsing.
* @throws XmlPullParserException
* @throws IOException
*/
private static void parseServer(final XmlPullParser parser, final HostAuth hostAuth)
throws XmlPullParserException, IOException {
boolean mobileSync = false;
while (true) {
final int type = parser.next();
if (type == XmlPullParser.END_TAG && parser.getName().equals(ELEMENT_NAME_SERVER)) {
break;
} else if (type == XmlPullParser.START_TAG) {
final String name = parser.getName();
if (name.equals(ELEMENT_NAME_TYPE)) {
if (parser.nextText().equals(ELEMENT_NAME_MOBILE_SYNC)) {
mobileSync = true;
}
} else if (mobileSync && name.equals(ELEMENT_NAME_URL)) {
final String url = parser.nextText();
if (url != null) {
LogUtils.d(TAG, "Autodiscover URL: %s", url);
hostAuth.mAddress = Uri.parse(url).getHost();
}
}
}
}
}
/**
* Parse the Settings element of the server response.
* @param parser The {@link XmlPullParser}.
* @param hostAuth The {@link HostAuth} to populate with the results of parsing.
* @throws XmlPullParserException
* @throws IOException
*/
private static void parseSettings(final XmlPullParser parser, final HostAuth hostAuth)
throws XmlPullParserException, IOException {
while (true) {
final int type = parser.next();
if (type == XmlPullParser.END_TAG && parser.getName().equals(ELEMENT_NAME_SETTINGS)) {
break;
} else if (type == XmlPullParser.START_TAG) {
final String name = parser.getName();
if (name.equals(ELEMENT_NAME_SERVER)) {
parseServer(parser, hostAuth);
}
}
}
}
/**
* Parse the Action element of the server response.
* @param parser The {@link XmlPullParser}.
* @param hostAuth The {@link HostAuth} to populate with the results of parsing.
* @throws XmlPullParserException
* @throws IOException
*/
private static void parseAction(final XmlPullParser parser, final HostAuth hostAuth)
throws XmlPullParserException, IOException {
while (true) {
final int type = parser.next();
if (type == XmlPullParser.END_TAG && parser.getName().equals(ELEMENT_NAME_ACTION)) {
break;
} else if (type == XmlPullParser.START_TAG) {
final String name = parser.getName();
if (name.equals(ELEMENT_NAME_ERROR)) {
// Should parse the error
} else if (name.equals(ELEMENT_NAME_REDIRECT)) {
LogUtils.d(TAG, "Redirect: " + parser.nextText());
} else if (name.equals(ELEMENT_NAME_SETTINGS)) {
parseSettings(parser, hostAuth);
}
}
}
}
/**
* Parse the User element of the server response.
* @param parser The {@link XmlPullParser}.
* @param hostAuth The {@link HostAuth} to populate with the results of parsing.
* @throws XmlPullParserException
* @throws IOException
*/
private static void parseUser(final XmlPullParser parser, final HostAuth hostAuth)
throws XmlPullParserException, IOException {
while (true) {
int type = parser.next();
if (type == XmlPullParser.END_TAG && parser.getName().equals(ELEMENT_NAME_USER)) {
break;
} else if (type == XmlPullParser.START_TAG) {
String name = parser.getName();
if (name.equals(ELEMENT_NAME_EMAIL_ADDRESS)) {
final String addr = parser.nextText();
LogUtils.d(TAG, "Autodiscover, email: %s", addr);
} else if (name.equals(ELEMENT_NAME_DISPLAY_NAME)) {
final String dn = parser.nextText();
LogUtils.d(TAG, "Autodiscover, user: %s", dn);
}
}
}
}
/**
* Parse the Response element of the server response.
* @param parser The {@link XmlPullParser}.
* @param hostAuth The {@link HostAuth} to populate with the results of parsing.
* @throws XmlPullParserException
* @throws IOException
*/
private static void parseResponse(final XmlPullParser parser, final HostAuth hostAuth)
throws XmlPullParserException, IOException {
while (true) {
final int type = parser.next();
if (type == XmlPullParser.END_TAG && parser.getName().equals(ELEMENT_NAME_RESPONSE)) {
break;
} else if (type == XmlPullParser.START_TAG) {
final String name = parser.getName();
if (name.equals(ELEMENT_NAME_USER)) {
parseUser(parser, hostAuth);
} else if (name.equals(ELEMENT_NAME_ACTION)) {
parseAction(parser, hostAuth);
}
}
}
}
/**
* Parse the server response for the final {@link HostAuth}.
* @param resp The {@link EasResponse} from the server.
* @return The final {@link HostAuth} for this server.
*/
private static HostAuth parseAutodiscover(final EasResponse resp) {
// The response to Autodiscover is regular XML (not WBXML)
try {
final XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
parser.setInput(resp.getInputStream(), "UTF-8");
if (parser.getEventType() != XmlPullParser.START_DOCUMENT) {
return null;
}
if (parser.next() != XmlPullParser.START_TAG) {
return null;
}
if (!parser.getName().equals(ELEMENT_NAME_AUTODISCOVER)) {
return null;
}
final HostAuth hostAuth = new HostAuth();
while (true) {
final int type = parser.nextTag();
if (type == XmlPullParser.END_TAG && parser.getName()
.equals(ELEMENT_NAME_AUTODISCOVER)) {
break;
} else if (type == XmlPullParser.START_TAG && parser.getName()
.equals(ELEMENT_NAME_RESPONSE)) {
parseResponse(parser, hostAuth);
// Valid responses will set the address.
if (hostAuth.mAddress != null) {
return hostAuth;
}
}
}
} catch (final XmlPullParserException e) {
// Parse error.
} catch (final IOException e) {
// Error reading parser.
}
return null;
}
}
| true | true | public Bundle doAutodiscover() {
final String domain = getDomain();
if (domain == null) {
return null;
}
final StringEntity entity = buildRequestEntity();
if (entity == null) {
return null;
}
try {
final HttpPost post = makePost("https://" + domain + AUTO_DISCOVER_PAGE, entity,
"text/xml", false);
final EasResponse resp = getResponse(post, domain);
if (resp == null) {
return null;
}
try {
// resp is either an authentication error, or a good response.
final int code = resp.getStatus();
if (code == HttpStatus.SC_UNAUTHORIZED) {
final Bundle bundle = new Bundle(1);
bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE,
MessagingException.AUTODISCOVER_AUTHENTICATION_FAILED);
return bundle;
} else {
final HostAuth hostAuth = parseAutodiscover(resp);
if (hostAuth != null) {
// Fill in the rest of the HostAuth
// We use the user name and password that were successful during
// the autodiscover process
hostAuth.mLogin = mHostAuth.mLogin;
hostAuth.mPassword = mHostAuth.mPassword;
// Note: there is no way we can auto-discover the proper client
// SSL certificate to use, if one is needed.
hostAuth.mPort = 443;
hostAuth.mProtocol = Eas.PROTOCOL;
hostAuth.mFlags = HostAuth.FLAG_SSL | HostAuth.FLAG_AUTHENTICATE;
final Bundle bundle = new Bundle(2);
bundle.putParcelable(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_HOST_AUTH,
hostAuth);
bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE,
MessagingException.NO_ERROR);
return bundle;
}
}
} finally {
resp.close();
}
} catch (final IllegalArgumentException e) {
// This happens when the domain is malformatted.
// TODO: Fix sanitizing of the domain -- we try to in UI but apparently not correctly.
LogUtils.e(TAG, "ISE with domain: %s", domain);
}
return null;
}
| public Bundle doAutodiscover() {
final String domain = getDomain();
if (domain == null) {
return null;
}
final StringEntity entity = buildRequestEntity();
if (entity == null) {
return null;
}
try {
final HttpPost post = makePost("https://" + domain + AUTO_DISCOVER_PAGE, entity,
"text/xml", false);
final EasResponse resp = getResponse(post, domain);
if (resp == null) {
return null;
}
try {
// resp is either an authentication error, or a good response.
final int code = resp.getStatus();
if (code == HttpStatus.SC_UNAUTHORIZED) {
// We actually don't know if this is because it's an actual EAS auth error,
// or just HTTP 401 (e.g. you're just hitting some random server).
// Let's just dump them out of autodiscover in this case.
return null;
} else {
final HostAuth hostAuth = parseAutodiscover(resp);
if (hostAuth != null) {
// Fill in the rest of the HostAuth
// We use the user name and password that were successful during
// the autodiscover process
hostAuth.mLogin = mHostAuth.mLogin;
hostAuth.mPassword = mHostAuth.mPassword;
// Note: there is no way we can auto-discover the proper client
// SSL certificate to use, if one is needed.
hostAuth.mPort = 443;
hostAuth.mProtocol = Eas.PROTOCOL;
hostAuth.mFlags = HostAuth.FLAG_SSL | HostAuth.FLAG_AUTHENTICATE;
final Bundle bundle = new Bundle(2);
bundle.putParcelable(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_HOST_AUTH,
hostAuth);
bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE,
MessagingException.NO_ERROR);
return bundle;
}
}
} finally {
resp.close();
}
} catch (final IllegalArgumentException e) {
// This happens when the domain is malformatted.
// TODO: Fix sanitizing of the domain -- we try to in UI but apparently not correctly.
LogUtils.e(TAG, "ISE with domain: %s", domain);
}
return null;
}
|
diff --git a/hk2/auto-depends/src/java/org/jvnet/hk2/component/MultiMap.java b/hk2/auto-depends/src/java/org/jvnet/hk2/component/MultiMap.java
index ac325ccde..cadbfa3b6 100644
--- a/hk2/auto-depends/src/java/org/jvnet/hk2/component/MultiMap.java
+++ b/hk2/auto-depends/src/java/org/jvnet/hk2/component/MultiMap.java
@@ -1,149 +1,149 @@
package org.jvnet.hk2.component;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Map from a key to multiple values.
* Order is significant among values, and null values are allowed, although null keys are not.
*
* @author Kohsuke Kawaguchi
*/
public final class MultiMap<K,V> {
private final Map<K,List<V>> store;
public final String toString() {
final StringBuilder builder = new StringBuilder();
final String newline = System.getProperty( "line.separator" );
builder.append( "{" );
for ( final K key : store.keySet() ) {
builder.append( key + ": {" );
- for( final Object value : store.values() ) {
+ for( final V value : store.get(key) ) {
builder.append( value.toString() + "," );
}
// trailing comma is OK
builder.append( "}" + newline );
}
builder.append( "}" );
return builder.toString();
}
/**
* Creates an empty multi-map.
*/
public MultiMap() {
store = new HashMap<K, List<V>>();
}
/**
* Creates a multi-map backed by the given store.
*/
private MultiMap(Map<K,List<V>> store) {
this.store = store;
}
/**
* Adds one more value.
*/
public final void add(K k,V v) {
List<V> l = store.get(k);
if(l==null) {
l = new ArrayList<V>();
store.put(k,l);
}
l.add(v);
}
/**
* Replaces all the existing values associated with the key
* by the given value.
*
* @param v
* Can be null or empty.
*/
public void set(K k, List<V> v) {
store.put(k,new ArrayList<V>(v));
}
/**
* @return
* Can be empty but never null. Read-only.
*/
public final List<V> get(K k) {
List<V> l = store.get(k);
if(l==null) return Collections.emptyList();
return l;
}
/**
* Checks if the map contains the given key.
*/
public boolean containsKey(K key) {
return !get(key).isEmpty();
}
/**
* Gets the first value if any, or null.
* <p>
* This is useful when you know the given key only has one value and you'd like
* to get to that value.
*
* @return
* null if the key has no values or it has a value but the value is null.
*/
public final V getOne(K k) {
List<V> lst = store.get(k);
if(lst ==null) return null;
if(lst.isEmpty()) return null;
return lst.get(0);
}
/**
* Lists up all entries.
*/
public Set<Entry<K,List<V>>> entrySet() {
return store.entrySet();
}
/**
* Format the map as "key=value1,key=value2,...."
*/
public String toCommaSeparatedString() {
StringBuilder buf = new StringBuilder();
for (Entry<K,List<V>> e : entrySet()) {
for (V v : e.getValue()) {
if(buf.length()>0) buf.append(',');
buf.append(e.getKey()).append('=').append(v);
}
}
return buf.toString();
}
/**
* Creates a copy of the map that contains the exact same key and value set.
* Keys and values won't cloned.
*/
public MultiMap<K,V> clone() {
MultiMap<K,V> m = new MultiMap<K,V>();
for (Entry<K, List<V>> e : store.entrySet())
m.store.put(e.getKey(),new ArrayList<V>(e.getValue()));
return m;
}
private static final MultiMap EMPTY = new MultiMap(Collections.emptyMap());
/**
* Gets the singleton read-only empty multi-map.
*
* @see Collections#emptyMap()
*/
public static <K,V> MultiMap<K,V> emptyMap() {
return EMPTY;
}
}
| true | true | public final String toString() {
final StringBuilder builder = new StringBuilder();
final String newline = System.getProperty( "line.separator" );
builder.append( "{" );
for ( final K key : store.keySet() ) {
builder.append( key + ": {" );
for( final Object value : store.values() ) {
builder.append( value.toString() + "," );
}
// trailing comma is OK
builder.append( "}" + newline );
}
builder.append( "}" );
return builder.toString();
}
| public final String toString() {
final StringBuilder builder = new StringBuilder();
final String newline = System.getProperty( "line.separator" );
builder.append( "{" );
for ( final K key : store.keySet() ) {
builder.append( key + ": {" );
for( final V value : store.get(key) ) {
builder.append( value.toString() + "," );
}
// trailing comma is OK
builder.append( "}" + newline );
}
builder.append( "}" );
return builder.toString();
}
|
diff --git a/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java b/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java
index 8a20205..9dd7121 100644
--- a/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java
+++ b/src/uk/ac/gla/dcs/tp3/w/algorithm/Graph.java
@@ -1,186 +1,186 @@
package uk.ac.gla.dcs.tp3.w.algorithm;
import java.util.LinkedList;
import uk.ac.gla.dcs.tp3.w.league.League;
import uk.ac.gla.dcs.tp3.w.league.Match;
import uk.ac.gla.dcs.tp3.w.league.Team;
public class Graph {
private Vertex[] vertices;
private int[][] matrix;
private Vertex source;
private Vertex sink;
public Graph() {
this(null, null);
}
public Graph(League l, Team t) {
if (l == null || t == null)
return;
// Number of team nodes is one less than total number of teams.
// The team nodes do not include the team being tested for elimination.
int teamTotal = l.getTeams().length;
// The r-combination of teamTotal for length 2 is the number of possible
// combinations for matches between the list of Teams-{t}.
int gameTotal = comb(teamTotal - 1, 2);
// Total number of vertices is the number of teams-1 + number of match
// pairs + source + sink.
vertices = new Vertex[teamTotal + gameTotal + 1];
// Set first vertex to be source, and last vertex to be sink.
// Create blank vertices for source and sink.
source = new Vertex(0);
sink = new Vertex(vertices.length - 1);
vertices[0] = source;
vertices[vertices.length - 1] = sink;
// Create vertices for each team node, and make them adjacent to
// the sink.
Team[] teamsReal = l.getTeams();
Team[] teams = new Team[teamsReal.length - 1];
// Remove team T from the working list of Teams
int pos = 0;
for (Team to : teamsReal) {
if (!to.equals(t)) {
teams[pos] = to;
pos++;
}
}
// Create vertex for each team pair and make it adjacent from the
// source.
// Team[i] is in vertices[vertices.length -2 -i]
pos = vertices.length - 2;
- for (int i = 0; i < teams.length; i++) {
- vertices[pos] = new TeamVertex(teams[i], pos);
+ for (int i = 0; i < teamsReal.length; i++) {
+ vertices[pos] = new TeamVertex(teamsReal[i], pos);
vertices[pos].getAdjList().add(
- new AdjListNode(teams[i].getUpcomingMatches().length,
+ new AdjListNode(teamsReal[i].getUpcomingMatches().length,
vertices[vertices.length - 1]));
pos--;
}
// Create vertex for each team pair and make it adjacent from the
// source.
pos = 1;
int infinity = Integer.MAX_VALUE;
for (int i = 0; i < teamTotal + 1; i++) {
for (int j = 1; j < teamTotal; j++) {
vertices[pos] = new PairVertex(teams[i], teams[j], pos);
vertices[pos].getAdjList().add(
new AdjListNode(infinity, vertices[vertices.length - 2
- i]));
vertices[pos].getAdjList().add(
new AdjListNode(infinity, vertices[vertices.length - 2
- j]));
vertices[0].getAdjList().add(new AdjListNode(0, vertices[pos]));
pos++;
}
}
// For each match not yet played and not involving t, increment the
// capacity of the vertex going from home and away team node->sink and
// float->pair node of home and away
for (Match M : l.getFixtures()) {
if (!M.isPlayed() && !(M.getAwayTeam().equals(t))
|| M.getHomeTeam().equals(t)) {
Team home = M.getHomeTeam();
Team away = M.getAwayTeam();
for (int i = vertices.length - 2; i < teams.length; i--) {
TeamVertex TV = (TeamVertex) vertices[i];
if (TV.getTeam().equals(home)) {
vertices[i].getAdjList().peek().incCapacity();
} else if (TV.getTeam().equals(away)) {
vertices[i].getAdjList().peek().incCapacity();
}
}
for (AdjListNode A : vertices[0].getAdjList()) {
PairVertex PV = (PairVertex) A.getVertex();
if ((PV.getTeamA().equals(home) && PV.getTeamB().equals(
away))
|| PV.getTeamA().equals(away)
&& PV.getTeamB().equals(home)) {
A.incCapacity();
}
}
}
}
// TODO Create the adjacency matrix representation of the graph.
}
public Vertex[] getV() {
return vertices;
}
public void setV(Vertex[] v) {
this.vertices = v;
}
public int[][] getMatrix() {
return matrix;
}
public int getSize() {
return vertices.length;
}
public void setMatrix(int[][] matrix) {
this.matrix = matrix;
}
public Vertex getSource() {
return source;
}
public void setSource(Vertex source) {
this.source = source;
}
public Vertex getSink() {
return sink;
}
public void setSink(Vertex sink) {
this.sink = sink;
}
private static int fact(int s) {
// For s < 2, the factorial is 1. Otherwise, multiply s by fact(s-1)
return (s < 2) ? 1 : s * fact(s - 1);
}
private static int comb(int n, int r) {
// r-combination of size n is n!/r!(n-r)!
return (fact(n) / (fact(r) * fact(n - r)));
}
/**
* carry out a breadth first search/traversal of the graph
*/
public void bfs() {
// TODO Read over this code, I (GR) just dropped this in here from
// bfs-example.
for (Vertex v : vertices)
v.setVisited(false);
LinkedList<Vertex> queue = new LinkedList<Vertex>();
for (Vertex v : vertices) {
if (!v.getVisited()) {
v.setVisited(true);
v.setPredecessor(v.getIndex());
queue.add(v);
while (!queue.isEmpty()) {
Vertex u = queue.removeFirst();
LinkedList<AdjListNode> list = u.getAdjList();
for (AdjListNode node : list) {
Vertex w = node.getVertex();
if (!w.getVisited()) {
w.setVisited(true);
w.setPredecessor(u.getIndex());
queue.add(w);
}
}
}
}
}
}
}
| false | true | public Graph(League l, Team t) {
if (l == null || t == null)
return;
// Number of team nodes is one less than total number of teams.
// The team nodes do not include the team being tested for elimination.
int teamTotal = l.getTeams().length;
// The r-combination of teamTotal for length 2 is the number of possible
// combinations for matches between the list of Teams-{t}.
int gameTotal = comb(teamTotal - 1, 2);
// Total number of vertices is the number of teams-1 + number of match
// pairs + source + sink.
vertices = new Vertex[teamTotal + gameTotal + 1];
// Set first vertex to be source, and last vertex to be sink.
// Create blank vertices for source and sink.
source = new Vertex(0);
sink = new Vertex(vertices.length - 1);
vertices[0] = source;
vertices[vertices.length - 1] = sink;
// Create vertices for each team node, and make them adjacent to
// the sink.
Team[] teamsReal = l.getTeams();
Team[] teams = new Team[teamsReal.length - 1];
// Remove team T from the working list of Teams
int pos = 0;
for (Team to : teamsReal) {
if (!to.equals(t)) {
teams[pos] = to;
pos++;
}
}
// Create vertex for each team pair and make it adjacent from the
// source.
// Team[i] is in vertices[vertices.length -2 -i]
pos = vertices.length - 2;
for (int i = 0; i < teams.length; i++) {
vertices[pos] = new TeamVertex(teams[i], pos);
vertices[pos].getAdjList().add(
new AdjListNode(teams[i].getUpcomingMatches().length,
vertices[vertices.length - 1]));
pos--;
}
// Create vertex for each team pair and make it adjacent from the
// source.
pos = 1;
int infinity = Integer.MAX_VALUE;
for (int i = 0; i < teamTotal + 1; i++) {
for (int j = 1; j < teamTotal; j++) {
vertices[pos] = new PairVertex(teams[i], teams[j], pos);
vertices[pos].getAdjList().add(
new AdjListNode(infinity, vertices[vertices.length - 2
- i]));
vertices[pos].getAdjList().add(
new AdjListNode(infinity, vertices[vertices.length - 2
- j]));
vertices[0].getAdjList().add(new AdjListNode(0, vertices[pos]));
pos++;
}
}
// For each match not yet played and not involving t, increment the
// capacity of the vertex going from home and away team node->sink and
// float->pair node of home and away
for (Match M : l.getFixtures()) {
if (!M.isPlayed() && !(M.getAwayTeam().equals(t))
|| M.getHomeTeam().equals(t)) {
Team home = M.getHomeTeam();
Team away = M.getAwayTeam();
for (int i = vertices.length - 2; i < teams.length; i--) {
TeamVertex TV = (TeamVertex) vertices[i];
if (TV.getTeam().equals(home)) {
vertices[i].getAdjList().peek().incCapacity();
} else if (TV.getTeam().equals(away)) {
vertices[i].getAdjList().peek().incCapacity();
}
}
for (AdjListNode A : vertices[0].getAdjList()) {
PairVertex PV = (PairVertex) A.getVertex();
if ((PV.getTeamA().equals(home) && PV.getTeamB().equals(
away))
|| PV.getTeamA().equals(away)
&& PV.getTeamB().equals(home)) {
A.incCapacity();
}
}
}
}
// TODO Create the adjacency matrix representation of the graph.
}
| public Graph(League l, Team t) {
if (l == null || t == null)
return;
// Number of team nodes is one less than total number of teams.
// The team nodes do not include the team being tested for elimination.
int teamTotal = l.getTeams().length;
// The r-combination of teamTotal for length 2 is the number of possible
// combinations for matches between the list of Teams-{t}.
int gameTotal = comb(teamTotal - 1, 2);
// Total number of vertices is the number of teams-1 + number of match
// pairs + source + sink.
vertices = new Vertex[teamTotal + gameTotal + 1];
// Set first vertex to be source, and last vertex to be sink.
// Create blank vertices for source and sink.
source = new Vertex(0);
sink = new Vertex(vertices.length - 1);
vertices[0] = source;
vertices[vertices.length - 1] = sink;
// Create vertices for each team node, and make them adjacent to
// the sink.
Team[] teamsReal = l.getTeams();
Team[] teams = new Team[teamsReal.length - 1];
// Remove team T from the working list of Teams
int pos = 0;
for (Team to : teamsReal) {
if (!to.equals(t)) {
teams[pos] = to;
pos++;
}
}
// Create vertex for each team pair and make it adjacent from the
// source.
// Team[i] is in vertices[vertices.length -2 -i]
pos = vertices.length - 2;
for (int i = 0; i < teamsReal.length; i++) {
vertices[pos] = new TeamVertex(teamsReal[i], pos);
vertices[pos].getAdjList().add(
new AdjListNode(teamsReal[i].getUpcomingMatches().length,
vertices[vertices.length - 1]));
pos--;
}
// Create vertex for each team pair and make it adjacent from the
// source.
pos = 1;
int infinity = Integer.MAX_VALUE;
for (int i = 0; i < teamTotal + 1; i++) {
for (int j = 1; j < teamTotal; j++) {
vertices[pos] = new PairVertex(teams[i], teams[j], pos);
vertices[pos].getAdjList().add(
new AdjListNode(infinity, vertices[vertices.length - 2
- i]));
vertices[pos].getAdjList().add(
new AdjListNode(infinity, vertices[vertices.length - 2
- j]));
vertices[0].getAdjList().add(new AdjListNode(0, vertices[pos]));
pos++;
}
}
// For each match not yet played and not involving t, increment the
// capacity of the vertex going from home and away team node->sink and
// float->pair node of home and away
for (Match M : l.getFixtures()) {
if (!M.isPlayed() && !(M.getAwayTeam().equals(t))
|| M.getHomeTeam().equals(t)) {
Team home = M.getHomeTeam();
Team away = M.getAwayTeam();
for (int i = vertices.length - 2; i < teams.length; i--) {
TeamVertex TV = (TeamVertex) vertices[i];
if (TV.getTeam().equals(home)) {
vertices[i].getAdjList().peek().incCapacity();
} else if (TV.getTeam().equals(away)) {
vertices[i].getAdjList().peek().incCapacity();
}
}
for (AdjListNode A : vertices[0].getAdjList()) {
PairVertex PV = (PairVertex) A.getVertex();
if ((PV.getTeamA().equals(home) && PV.getTeamB().equals(
away))
|| PV.getTeamA().equals(away)
&& PV.getTeamB().equals(home)) {
A.incCapacity();
}
}
}
}
// TODO Create the adjacency matrix representation of the graph.
}
|
diff --git a/CASi/src/de/uniluebeck/imis/casi/simulation/model/AbstractInteractionComponent.java b/CASi/src/de/uniluebeck/imis/casi/simulation/model/AbstractInteractionComponent.java
index 1a360a0..de3aea2 100644
--- a/CASi/src/de/uniluebeck/imis/casi/simulation/model/AbstractInteractionComponent.java
+++ b/CASi/src/de/uniluebeck/imis/casi/simulation/model/AbstractInteractionComponent.java
@@ -1,474 +1,475 @@
/* CASi Context Awareness Simulation Software
* Copyright (C) 2011 2012 Moritz Bürger, Marvin Frick, Tobias Mende
*
* This program is free software. It is licensed under the
* GNU Lesser General Public License with one clarification.
*
* You should have received a copy of the
* GNU Lesser General Public License along with this program.
* See the LICENSE.txt file in this projects root folder or visit
* <http://www.gnu.org/licenses/lgpl.html> for more details.
*/
package de.uniluebeck.imis.casi.simulation.model;
import java.awt.Point;
import java.awt.Shape;
import java.awt.geom.Arc2D;
import java.awt.geom.Area;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.Collection;
import java.util.logging.Logger;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import de.uniluebeck.imis.casi.communication.ICommunicationComponent;
import de.uniluebeck.imis.casi.simulation.engine.ISimulationClockListener;
import de.uniluebeck.imis.casi.simulation.engine.SimulationEngine;
import de.uniluebeck.imis.casi.simulation.factory.WorldFactory;
import de.uniluebeck.imis.casi.simulation.model.Agent.STATE;
import de.uniluebeck.imis.casi.simulation.model.actionHandling.AbstractAction;
/**
* This class represents components that are able to interact with their
* surroundings and that have an area in which they are interested.
*
* @author Tobias Mende
*
*/
public abstract class AbstractInteractionComponent extends AbstractComponent
implements ICommunicationComponent, IExtendedAgentListener,
ISimulationClockListener {
/** The development logger */
private static final Logger log = Logger
.getLogger(AbstractInteractionComponent.class.getName());
/** Enumeration for possible directions in which this component looks */
public enum Face {
NORTH(90), SOUTH(270), EAST(0), WEST(180), NORTH_EAST(45), SOUTH_EAST(
315), NORTH_WEST(135), SOUTH_WEST(225);
/** The degree representation of this face */
private double degree;
/** Private Constructor */
private Face(double degree) {
this.degree = degree;
}
/**
* Getter for the degree value.
*
* @return the degree representation
*/
private double degree() {
return degree;
}
/**
* Getter for the radian value.
*
* @return the radian representation
*/
private double radian() {
return Math.toRadians(degree);
}
/**
* Getter for a normalized direction vector
*
* @return the direction vector
*/
private Point2D direction() {
return new Point2D.Double(Math.cos(radian()),
Math.sin(radian()));
}
}
/** Types this component can be */
public enum Type {
/** This component represents a sensor */
SENSOR,
/** This component represents an actuator */
ACTUATOR,
/** The component is as well a sensor as an actuator. */
MIXED;
}
/** Counter for created interaction components */
private static int idCounter;
/** The radius of the monitored shape */
protected int radius = -1;
/** The direction in which this component looks */
protected Face direction;
/** The extent of the monitored area */
protected double opening = -1;
/** The action to which this component is connected */
protected Agent agent = null;
/** is this component a wearable? */
protected boolean wearable = false;
/** List of actions, that can be recognized and vetoed by this component */
protected Collection<AbstractAction> interestingActions;
/** actual value this sensor has recognized */
protected Object lastValue;
/** Last message, the actuator has received from the network controller */
protected Object lastResponse;
/** Time for pulling values from the server in seconds */
public static final int PULL_INTERVALL = 10;
/** Is pull enabled? */
protected boolean pullEnabled = false;
/** Counts the ticks of the clock */
protected int clockTickCounter = 0;
/** The type of this component */
protected Type type = Type.SENSOR;
/** The {@link Arc2D} representation of the monitored area */
private Shape shapeRepresentation;
/**
* id for serialization
*/
private static final long serialVersionUID = -9016454038144232069L;
/**
* Constructor for a new interaction component with a given identifier and
* position
*
* @param identifier
* the identifier
* @param coordinates
* the coordinates of this component
*/
public AbstractInteractionComponent(String identifier, Point2D coordinates) {
super(identifier);
this.coordinates = coordinates;
}
/**
* Creates a wearable for the provided agent
*
* @param agent
* the agent which wears this component
*/
public AbstractInteractionComponent(Agent agent) {
this(agent.getCoordinates());
this.agent = agent;
wearable = true;
}
/**
* Sets the agents which wears this component
*
* @param agent
* the agent to set
*/
public void setAgent(Agent agent) {
this.agent = agent;
}
/**
* Getter for the agent which is connected to this component
*
* @return the agent which may wear this component
*/
public Agent getAgent() {
return agent;
}
/**
* Constructor for a new interaction component with a given position
*
* @param coordinates
* the coordinates of this component
*/
public AbstractInteractionComponent(Point2D coordinates) {
this("ioComponent-" + idCounter, coordinates);
idCounter++;
}
/**
* Constructor which creates an interaction component with a specified
* monitored area
*
* @param coordinates
* the position of this component
* @param radius
* the radius of the monitored area
* @param direction
* the direction in which this component "looks"
* @param opening
* the opening angle of the area
*/
public AbstractInteractionComponent(Point coordinates, int radius,
Face direction, int opening) {
this(coordinates);
this.radius = radius;
this.direction = direction;
this.opening = opening;
}
/**
* Checks whether this component actually is weared by an agent
*
* @return <code>true</code> if the wearing agent is not null,
* <code>false</code> otherwise.
*/
public boolean isWeared() {
return agent != null && isWearable();
}
/**
* Sets the wearable state of this component
*
* @param wearable
* if <code>true</code>, the assigned agent wears this component.
*/
public void setWearable(boolean wearable) {
this.wearable = wearable;
}
/**
* Is this component a wearable?
*
* @return the wearable
*/
public boolean isWearable() {
return wearable;
}
@Override
public Shape getShapeRepresentation() {
if (shapeRepresentation != null) {
// Shape was calculated before:
return shapeRepresentation;
}
if (radius < 0 && getCurrentPosition() != null) {
// Monitor the whole room:
shapeRepresentation = getCurrentPosition().getShapeRepresentation();
return shapeRepresentation;
}
// Calculate the new shape:
double currentOpening = opening < 0 ? 360 : opening;
Face currentDirection = direction == null ? Face.NORTH : direction;
double startAngle = currentDirection.degree()
- ((double) currentOpening / 2.0);
shapeRepresentation = new Arc2D.Double(calculateCircleBounds(),
startAngle, currentOpening, Arc2D.PIE);
- Point2D pointInRoom = new Point2D.Double(currentDirection.direction()
- .getX() + getCentralPoint().getX(), currentDirection
+ int scale = 3;
+ Point2D pointInRoom = new Point2D.Double(scale*currentDirection.direction()
+ .getX() + getCentralPoint().getX(), scale*currentDirection
.direction().getY() + getCentralPoint().getY());
Room room = WorldFactory.getRoomsWithPoint(pointInRoom).getFirst();
Area area = new Area(shapeRepresentation);
area.intersect(new Area(room.getShapeRepresentation()));
shapeRepresentation = area;
return shapeRepresentation;
}
/**
* Calculates a quadratic area which is exactly big enough to contain the
* circle which is used to calculate the monitored area
*
* @return the bounds
*/
private Rectangle2D calculateCircleBounds() {
double y = coordinates.getY() - radius;
double x = coordinates.getX() - radius;
return new Rectangle2D.Double(x, y, 2 * radius, 2 * radius);
}
@Override
public Point2D getCentralPoint() {
return getCoordinates();
}
/**
* Setter for a new monitored area
*
* @param direction
* the direction in which this component "looks"
* @param radius
* the radius of the monitored area
* @param opening
* the opening angle
*/
public void setMonitoredArea(Face direction, int radius, int opening) {
shapeRepresentation = null;
this.direction = direction;
this.radius = radius;
this.opening = opening;
}
/**
* Resets the monitored area. Components with unspecified monitored areas
* monitor the whole room in which they are contained.
*/
public void resetMonitoredArea() {
setMonitoredArea(null, -1, -1);
}
/**
* Method for handling an action internal. Overwrite for customized behavior
*
* @param action
* the action to handle
* @return <code>true</code> if the action is allowed, <code>false</code>
* otherwise
*/
protected abstract boolean handleInternal(AbstractAction action, Agent agent);
/**
* Getter for human readable version of the current value
*
* @return the value in a nicer format
*/
public abstract String getHumanReadableValue();
/**
* Getter for the type of this sensor
*
* @return the sensor type
*/
public String getType() {
return getClass().getSimpleName();
}
@Override
public String toString() {
return super.toString() + " (" + getType() + ", "+getHumanReadableValue()+")";
}
@Override
public boolean handle(AbstractAction action, Agent agent) {
return this.contains(agent) ? handleInternal(action, agent) : true;
}
@Override
public void positionChanged(Point2D oldPosition, Point2D newPosition,
Agent agent) {
if (isWeared() && this.agent.equals(agent)) {
setCoordinates(newPosition);
shapeRepresentation = null;
}
}
@Override
public void timeChanged(SimulationTime newTime) {
if ((clockTickCounter = (++clockTickCounter) % PULL_INTERVALL) == 0) {
makePullRequest(newTime);
}
}
/**
* Overwrite to let the component periodically pull informations from the
* communication handler
*/
protected void makePullRequest(SimulationTime newTime) {
// nothing to do here.
}
@Override
public void simulationPaused(boolean pause) {
// nothing to do here
}
@Override
public void simulationStopped() {
// nothing to do here
}
@Override
public void simulationStarted() {
// nothing to do here
}
/**
* Checks if this component has a veto right when an agent tries to perform
* an action. (Only actuators and mixed components have a veto right)
*
* @return <code>true</code> if this component is allowed to interrupt an
* action, <code>false</code> otherwise.
*/
public final boolean hasVetoRight() {
return !type.equals(Type.SENSOR);
}
/**
* Sets a new shape representation of the monitored area
*
* @param shape
* the shape do monitor
*/
public void setShapeRepresentation(Shape shape) {
this.shapeRepresentation = shape;
}
/**
* Checks whether this cube is interested in a given action and agent.
* (default: interested in nothing)
*
* @param action
* the action
* @param agent
* the agent
* @return <code>true</code> if the cube is interested, <code>false</code>
* otherwise.
*/
protected boolean checkInterest(AbstractAction action, Agent agent) {
return false;
}
/**
* Checks whether this cube is interested in a given agent (default:
* interested in nothing)
*
* @param agent
* the agent
* @return <code>true</code> if the cube is interested, <code>false</code>
* otherwise.
*/
protected boolean checkInterest(Agent agent) {
return false;
}
@Override
public void stateChanged(STATE newState, Agent agent) {
// nothing to do here
}
@Override
public void interruptibilityChanged(INTERRUPTIBILITY interruptibility,
Agent agent) {
// nothing to do here
}
@Override
public void startPerformingAction(AbstractAction action, Agent agent) {
// nothing to do here
}
@Override
public void finishPerformingAction(AbstractAction action, Agent agent) {
// nothing to do here
}
@Override
public void receive(Object message) {
/*
* Should be implemented by components that want to receive messages
* from the communication handler. On other components, this call should
* fail because it's an unexpected behavior.
*/
throw new NotImplementedException();
}
@Override
public void init() {
SimulationEngine.getInstance().getCommunicationHandler().register(this);
}
}
| true | true | public Shape getShapeRepresentation() {
if (shapeRepresentation != null) {
// Shape was calculated before:
return shapeRepresentation;
}
if (radius < 0 && getCurrentPosition() != null) {
// Monitor the whole room:
shapeRepresentation = getCurrentPosition().getShapeRepresentation();
return shapeRepresentation;
}
// Calculate the new shape:
double currentOpening = opening < 0 ? 360 : opening;
Face currentDirection = direction == null ? Face.NORTH : direction;
double startAngle = currentDirection.degree()
- ((double) currentOpening / 2.0);
shapeRepresentation = new Arc2D.Double(calculateCircleBounds(),
startAngle, currentOpening, Arc2D.PIE);
Point2D pointInRoom = new Point2D.Double(currentDirection.direction()
.getX() + getCentralPoint().getX(), currentDirection
.direction().getY() + getCentralPoint().getY());
Room room = WorldFactory.getRoomsWithPoint(pointInRoom).getFirst();
Area area = new Area(shapeRepresentation);
area.intersect(new Area(room.getShapeRepresentation()));
shapeRepresentation = area;
return shapeRepresentation;
}
| public Shape getShapeRepresentation() {
if (shapeRepresentation != null) {
// Shape was calculated before:
return shapeRepresentation;
}
if (radius < 0 && getCurrentPosition() != null) {
// Monitor the whole room:
shapeRepresentation = getCurrentPosition().getShapeRepresentation();
return shapeRepresentation;
}
// Calculate the new shape:
double currentOpening = opening < 0 ? 360 : opening;
Face currentDirection = direction == null ? Face.NORTH : direction;
double startAngle = currentDirection.degree()
- ((double) currentOpening / 2.0);
shapeRepresentation = new Arc2D.Double(calculateCircleBounds(),
startAngle, currentOpening, Arc2D.PIE);
int scale = 3;
Point2D pointInRoom = new Point2D.Double(scale*currentDirection.direction()
.getX() + getCentralPoint().getX(), scale*currentDirection
.direction().getY() + getCentralPoint().getY());
Room room = WorldFactory.getRoomsWithPoint(pointInRoom).getFirst();
Area area = new Area(shapeRepresentation);
area.intersect(new Area(room.getShapeRepresentation()));
shapeRepresentation = area;
return shapeRepresentation;
}
|
diff --git a/src/engine/God.java b/src/engine/God.java
index 7d66255..a843029 100644
--- a/src/engine/God.java
+++ b/src/engine/God.java
@@ -1,74 +1,74 @@
/*
* 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/>.
*/
/*
* Responsible for keeping the universe active. Specifically,
* 1. Manage patrols and traders - spawn replacements as needed - TODO
* 2. Manage stations - spawn replacements as needed - TODO
* 3. Add 'fun' disasters to the universe. - TODO
*/
package engine;
import java.util.ArrayList;
import lib.Faction;
import lib.Parser;
import lib.Parser.Term;
import lib.SuperFaction;
import universe.Universe;
/**
*
* @author nwiehoff
*/
public class God implements EngineElement {
private Universe universe;
private ArrayList<SuperFaction> factions = new ArrayList<>();
public God(Universe universe) {
this.universe = universe;
//generate lists
initFactions();
}
private void initFactions() {
//make a list of all factions
- ArrayList<Faction> factions = new ArrayList<>();
+ ArrayList<Faction> tmpF = new ArrayList<>();
Parser fParse = new Parser("FACTIONS.txt");
ArrayList<Term> terms = fParse.getTermsOfType("Faction");
for (int a = 0; a < terms.size(); a++) {
factions.add(new SuperFaction(terms.get(a).getValue("name")));
}
}
@Override
public void periodicUpdate() {
try {
checkPatrols();
checkStations();
} catch (Exception e) {
System.out.println("Error manipulating dynamic universe.");
e.printStackTrace();
}
}
private void checkPatrols() {
//TODO
}
private void checkStations() {
//TODO
}
}
| true | true | private void initFactions() {
//make a list of all factions
ArrayList<Faction> factions = new ArrayList<>();
Parser fParse = new Parser("FACTIONS.txt");
ArrayList<Term> terms = fParse.getTermsOfType("Faction");
for (int a = 0; a < terms.size(); a++) {
factions.add(new SuperFaction(terms.get(a).getValue("name")));
}
}
| private void initFactions() {
//make a list of all factions
ArrayList<Faction> tmpF = new ArrayList<>();
Parser fParse = new Parser("FACTIONS.txt");
ArrayList<Term> terms = fParse.getTermsOfType("Faction");
for (int a = 0; a < terms.size(); a++) {
factions.add(new SuperFaction(terms.get(a).getValue("name")));
}
}
|
diff --git a/src/com/cooliris/media/MediaFeed.java b/src/com/cooliris/media/MediaFeed.java
index 555c16d..73dcd0c 100644
--- a/src/com/cooliris/media/MediaFeed.java
+++ b/src/com/cooliris/media/MediaFeed.java
@@ -1,902 +1,903 @@
package com.cooliris.media;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;
import android.net.Uri;
import android.os.Handler;
import android.os.Process;
import com.cooliris.app.App;
import com.cooliris.app.Res;
import com.cooliris.media.MediaClustering.Cluster;
public final class MediaFeed implements Runnable {
private final String TAG = "MediaFeed";
public static final int OPERATION_DELETE = 0;
public static final int OPERATION_ROTATE = 1;
public static final int OPERATION_CROP = 2;
private static final int NUM_ITEMS_LOOKAHEAD = 60;
private IndexRange mVisibleRange = new IndexRange();
private IndexRange mBufferedRange = new IndexRange();
private ArrayList<MediaSet> mMediaSets = new ArrayList<MediaSet>();
private Listener mListener;
private DataSource mDataSource;
private boolean mListenerNeedsUpdate = false;
private boolean mMediaFeedNeedsToRun = false;
private MediaSet mSingleWrapper = new MediaSet();
private boolean mInClusteringMode = false;
private HashMap<MediaSet, MediaClustering> mClusterSets = new HashMap<MediaSet, MediaClustering>(32);
private int mExpandedMediaSetIndex = Shared.INVALID;
private MediaFilter mMediaFilter;
private MediaSet mMediaFilteredSet;
private Context mContext;
private Thread mDataSourceThread = null;
private Thread mAlbumSourceThread = null;
private boolean mListenerNeedsLayout;
private boolean mWaitingForMediaScanner;
private boolean mSingleImageMode;
private boolean mLoading;
private HashMap<String, ContentObserver> mContentObservers = new HashMap<String, ContentObserver>();
private ArrayList<String[]> mRequestedRefresh = new ArrayList<String[]>();
public interface Listener {
public abstract void onFeedAboutToChange(MediaFeed feed);
public abstract void onFeedChanged(MediaFeed feed, boolean needsLayout);
}
public MediaFeed(Context context, DataSource dataSource, Listener listener) {
mContext = context;
mListener = listener;
mDataSource = dataSource;
mSingleWrapper.setNumExpectedItems(1);
mLoading = true;
}
public void shutdown() {
if (mDataSourceThread != null) {
mDataSource.shutdown();
mDataSourceThread.interrupt();
mDataSourceThread = null;
}
if (mAlbumSourceThread != null) {
mAlbumSourceThread.interrupt();
mAlbumSourceThread = null;
}
int numSets = mMediaSets.size();
for (int i = 0; i < numSets; ++i) {
MediaSet set = mMediaSets.get(i);
set.clear();
}
synchronized (mMediaSets) {
mMediaSets.clear();
}
int numClusters = mClusterSets.size();
for (int i = 0; i < numClusters; ++i) {
MediaClustering mc = mClusterSets.get(i);
if (mc != null) {
mc.clear();
}
}
mClusterSets.clear();
mListener = null;
mDataSource = null;
mSingleWrapper = null;
}
public void setVisibleRange(int begin, int end) {
if (begin != mVisibleRange.begin || end != mVisibleRange.end) {
mVisibleRange.begin = begin;
mVisibleRange.end = end;
int numItems = 96;
int numItemsBy2 = numItems / 2;
int numItemsBy4 = numItems / 4;
mBufferedRange.begin = (begin / numItemsBy2) * numItemsBy2 - numItemsBy4;
mBufferedRange.end = mBufferedRange.begin + numItems;
mMediaFeedNeedsToRun = true;
}
}
public void setFilter(MediaFilter filter) {
mMediaFilter = filter;
mMediaFilteredSet = null;
if (mListener != null) {
mListener.onFeedAboutToChange(this);
}
mMediaFeedNeedsToRun = true;
}
public void removeFilter() {
mMediaFilter = null;
mMediaFilteredSet = null;
if (mListener != null) {
mListener.onFeedAboutToChange(this);
updateListener(true);
}
mMediaFeedNeedsToRun = true;
}
public ArrayList<MediaSet> getMediaSets() {
return mMediaSets;
}
public MediaSet getMediaSet(final long setId) {
if (setId != Shared.INVALID) {
try {
int mMediaSetsSize = mMediaSets.size();
for (int i = 0; i < mMediaSetsSize; i++) {
final MediaSet set = mMediaSets.get(i);
if (set.mId == setId) {
set.mFlagForDelete = false;
return set;
}
}
} catch (Exception e) {
return null;
}
}
return null;
}
public MediaSet getFilteredSet() {
return mMediaFilteredSet;
}
public MediaSet addMediaSet(final long setId, DataSource dataSource) {
MediaSet mediaSet = new MediaSet(dataSource);
mediaSet.mId = setId;
mMediaSets.add(mediaSet);
if (mDataSourceThread != null && !mDataSourceThread.isAlive()) {
mDataSourceThread.start();
}
mMediaFeedNeedsToRun = true;
return mediaSet;
}
public DataSource getDataSource() {
return mDataSource;
}
public MediaClustering getClustering() {
if (mExpandedMediaSetIndex != Shared.INVALID && mExpandedMediaSetIndex < mMediaSets.size()) {
return mClusterSets.get(mMediaSets.get(mExpandedMediaSetIndex));
}
return null;
}
public ArrayList<Cluster> getClustersForSet(final MediaSet set) {
ArrayList<Cluster> clusters = null;
if (mClusterSets != null && mClusterSets.containsKey(set)) {
MediaClustering mediaClustering = mClusterSets.get(set);
if (mediaClustering != null) {
clusters = mediaClustering.getClusters();
}
}
return clusters;
}
public void addItemToMediaSet(MediaItem item, MediaSet mediaSet) {
item.mParentMediaSet = mediaSet;
mediaSet.addItem(item);
synchronized (mClusterSets) {
if (item.mClusteringState == MediaItem.NOT_CLUSTERED) {
MediaClustering clustering = mClusterSets.get(mediaSet);
if (clustering == null) {
clustering = new MediaClustering(mediaSet.isPicassaAlbum());
mClusterSets.put(mediaSet, clustering);
}
clustering.setTimeRange(mediaSet.mMaxTimestamp - mediaSet.mMinTimestamp, mediaSet.getNumExpectedItems());
clustering.addItemForClustering(item);
item.mClusteringState = MediaItem.CLUSTERED;
}
}
mMediaFeedNeedsToRun = true;
}
public void performOperation(final int operation, final ArrayList<MediaBucket> mediaBuckets, final Object data) {
int numBuckets = mediaBuckets.size();
final ArrayList<MediaBucket> copyMediaBuckets = new ArrayList<MediaBucket>(numBuckets);
for (int i = 0; i < numBuckets; ++i) {
copyMediaBuckets.add(mediaBuckets.get(i));
}
if (operation == OPERATION_DELETE && mListener != null) {
mListener.onFeedAboutToChange(this);
}
Thread operationThread = new Thread(new Runnable() {
public void run() {
ArrayList<MediaBucket> mediaBuckets = copyMediaBuckets;
if (operation == OPERATION_DELETE) {
int numBuckets = mediaBuckets.size();
for (int i = 0; i < numBuckets; ++i) {
MediaBucket bucket = mediaBuckets.get(i);
MediaSet set = bucket.mediaSet;
ArrayList<MediaItem> items = bucket.mediaItems;
if (set != null && items == null) {
// Remove the entire bucket.
removeMediaSet(set);
} else if (set != null && items != null) {
// We need to remove these items from the set.
int numItems = items.size();
// We also need to delete the items from the
// cluster.
MediaClustering clustering = mClusterSets.get(set);
for (int j = 0; j < numItems; ++j) {
MediaItem item = items.get(j);
removeItemFromMediaSet(item, set);
if (clustering != null) {
clustering.removeItemFromClustering(item);
}
}
set.updateNumExpectedItems();
set.generateTitle(true);
}
}
updateListener(true);
mMediaFeedNeedsToRun = true;
if (mDataSource != null) {
mDataSource.performOperation(OPERATION_DELETE, mediaBuckets, null);
}
} else {
mDataSource.performOperation(operation, mediaBuckets, data);
}
}
});
operationThread.setName("Operation " + operation);
operationThread.start();
}
public void removeMediaSet(MediaSet set) {
synchronized (mMediaSets) {
mMediaSets.remove(set);
}
mMediaFeedNeedsToRun = true;
}
private void removeItemFromMediaSet(MediaItem item, MediaSet mediaSet) {
mediaSet.removeItem(item);
synchronized (mClusterSets) {
MediaClustering clustering = mClusterSets.get(mediaSet);
if (clustering != null) {
clustering.removeItemFromClustering(item);
}
}
mMediaFeedNeedsToRun = true;
}
public void updateListener(boolean needsLayout) {
mListenerNeedsUpdate = true;
mListenerNeedsLayout = needsLayout;
}
public int getNumSlots() {
int currentMediaSetIndex = mExpandedMediaSetIndex;
ArrayList<MediaSet> mediaSets = mMediaSets;
int mediaSetsSize = mediaSets.size();
if (mInClusteringMode == false) {
if (currentMediaSetIndex == Shared.INVALID || currentMediaSetIndex >= mediaSetsSize) {
return mediaSetsSize;
} else {
MediaSet setToUse = (mMediaFilteredSet == null) ? mediaSets.get(currentMediaSetIndex) : mMediaFilteredSet;
return setToUse.getNumExpectedItems();
}
} else if (currentMediaSetIndex != Shared.INVALID && currentMediaSetIndex < mediaSetsSize) {
MediaSet set = mediaSets.get(currentMediaSetIndex);
MediaClustering clustering = mClusterSets.get(set);
if (clustering != null) {
return clustering.getClustersForDisplay().size();
}
}
return 0;
}
public ArrayList<Integer> getBreaks() {
if (true)
return null;
int currentMediaSetIndex = mExpandedMediaSetIndex;
ArrayList<MediaSet> mediaSets = mMediaSets;
int mediaSetsSize = mediaSets.size();
if (currentMediaSetIndex == Shared.INVALID || currentMediaSetIndex >= mediaSetsSize)
return null;
MediaSet set = mediaSets.get(currentMediaSetIndex);
MediaClustering clustering = mClusterSets.get(set);
if (clustering != null) {
clustering.compute(null, true);
final ArrayList<Cluster> clusters = clustering.getClustersForDisplay();
int numClusters = clusters.size();
final ArrayList<Integer> retVal = new ArrayList<Integer>(numClusters);
int size = 0;
for (int i = 0; i < numClusters; ++i) {
size += clusters.get(i).getItems().size();
retVal.add(size);
}
return retVal;
} else {
return null;
}
}
public MediaSet getSetForSlot(int slotIndex) {
if (slotIndex < 0) {
return null;
}
ArrayList<MediaSet> mediaSets = mMediaSets;
int mediaSetsSize = mediaSets.size();
int currentMediaSetIndex = mExpandedMediaSetIndex;
if (mInClusteringMode == false) {
if (currentMediaSetIndex == Shared.INVALID || currentMediaSetIndex >= mediaSetsSize) {
if (slotIndex >= mediaSetsSize) {
return null;
}
return mMediaSets.get(slotIndex);
}
if (mSingleWrapper.getNumItems() == 0) {
mSingleWrapper.addItem(null);
}
MediaSet setToUse = (mMediaFilteredSet == null) ? mMediaSets.get(currentMediaSetIndex) : mMediaFilteredSet;
ArrayList<MediaItem> items = setToUse.getItems();
if (slotIndex >= setToUse.getNumItems()) {
return null;
}
mSingleWrapper.getItems().set(0, items.get(slotIndex));
return mSingleWrapper;
} else if (currentMediaSetIndex != Shared.INVALID && currentMediaSetIndex < mediaSetsSize) {
MediaSet set = mediaSets.get(currentMediaSetIndex);
MediaClustering clustering = mClusterSets.get(set);
if (clustering != null) {
ArrayList<MediaClustering.Cluster> clusters = clustering.getClustersForDisplay();
if (clusters.size() > slotIndex) {
MediaClustering.Cluster cluster = clusters.get(slotIndex);
cluster.generateCaption(mContext);
return cluster;
}
}
}
return null;
}
public boolean getWaitingForMediaScanner() {
return mWaitingForMediaScanner;
}
public boolean isLoading() {
return mLoading;
}
public void start() {
final MediaFeed feed = this;
onResume();
mLoading = true;
mDataSourceThread = new Thread(this);
mDataSourceThread.setName("MediaFeed");
mAlbumSourceThread = new Thread(new Runnable() {
public void run() {
if (mContext == null)
return;
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
DataSource dataSource = mDataSource;
// We must wait while the SD card is mounted or the MediaScanner
// is running.
if (dataSource != null) {
loadMediaSets();
}
mWaitingForMediaScanner = false;
while (ImageManager.isMediaScannerScanning(mContext.getContentResolver())) {
// MediaScanner is still running, wait
if (Thread.interrupted())
return;
mWaitingForMediaScanner = true;
try {
if (mContext == null)
return;
showToast(mContext.getResources().getString(Res.string.initializing), Toast.LENGTH_LONG);
if (dataSource != null) {
loadMediaSets();
}
Thread.sleep(10000);
} catch (InterruptedException e) {
return;
}
}
if (mWaitingForMediaScanner) {
showToast(mContext.getResources().getString(Res.string.loading_new), Toast.LENGTH_LONG);
mWaitingForMediaScanner = false;
loadMediaSets();
}
mLoading = false;
}
});
mAlbumSourceThread.setName("MediaSets");
mAlbumSourceThread.start();
}
private void loadMediaSets() {
if (mDataSource == null)
return;
final ArrayList<MediaSet> sets = mMediaSets;
final int numSets = sets.size();
for (int i = 0; i < numSets; ++i) {
final MediaSet set = sets.get(i);
set.mFlagForDelete = true;
}
synchronized (sets) {
mDataSource.refresh(MediaFeed.this, mDataSource.getDatabaseUris());
mDataSource.loadMediaSets(MediaFeed.this);
}
for (int i = 0; i < numSets; ++i) {
final MediaSet set = sets.get(i);
if (set.mFlagForDelete) {
removeMediaSet(set);
}
}
updateListener(false);
}
private void showToast(final String string, final int duration) {
showToast(string, duration, false);
}
private void showToast(final String string, final int duration, final boolean centered) {
if (mContext != null && !App.get(mContext).isPaused()) {
App.get(mContext).getHandler().post(new Runnable() {
public void run() {
if (mContext != null) {
Toast toast = Toast.makeText(mContext, string, duration);
if (centered) {
toast.setGravity(Gravity.CENTER, 0, 0);
}
toast.show();
}
}
});
}
}
public void run() {
DataSource dataSource = mDataSource;
int sleepMs = 10;
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
if (dataSource != null) {
while (!Thread.interrupted()) {
String[] databaseUris = null;
boolean performRefresh = false;
synchronized (mRequestedRefresh) {
if (mRequestedRefresh.size() > 0) {
// We prune this first.
int numRequests = mRequestedRefresh.size();
for (int i = 0; i < numRequests; ++i) {
databaseUris = ArrayUtils.addAll(databaseUris, mRequestedRefresh.get(i));
}
mRequestedRefresh.clear();
performRefresh = true;
// We need to eliminate duplicate uris in this array
final HashMap<String, String> uris = new HashMap<String, String>();
if (databaseUris != null) {
int numUris = databaseUris.length;
for (int i = 0; i < numUris; ++i) {
final String uri = databaseUris[i];
if (uri != null)
uris.put(uri, uri);
}
}
databaseUris = new String[0];
databaseUris = (String[]) uris.keySet().toArray(databaseUris);
}
}
if (performRefresh) {
if (dataSource != null) {
dataSource.refresh(this, databaseUris);
+ mMediaFeedNeedsToRun = true;
}
}
if (mListenerNeedsUpdate && !mMediaFeedNeedsToRun) {
mListenerNeedsUpdate = false;
if (mListener != null)
mListener.onFeedChanged(this, mListenerNeedsLayout);
try {
Thread.sleep(sleepMs);
} catch (InterruptedException e) {
return;
}
} else {
try {
Thread.sleep(sleepMs);
} catch (InterruptedException e) {
return;
}
}
sleepMs = 300;
if (!mMediaFeedNeedsToRun)
continue;
App app = App.get(mContext);
if (app == null || app.isPaused())
continue;
mMediaFeedNeedsToRun = false;
ArrayList<MediaSet> mediaSets = mMediaSets;
synchronized (mediaSets) {
int expandedSetIndex = mExpandedMediaSetIndex;
if (expandedSetIndex >= mMediaSets.size()) {
expandedSetIndex = Shared.INVALID;
}
if (expandedSetIndex == Shared.INVALID) {
// We purge the sets outside this visibleRange.
int numSets = mediaSets.size();
IndexRange visibleRange = mVisibleRange;
IndexRange bufferedRange = mBufferedRange;
boolean scanMediaSets = true;
for (int i = 0; i < numSets; ++i) {
if (i >= visibleRange.begin && i <= visibleRange.end && scanMediaSets) {
MediaSet set = mediaSets.get(i);
int numItemsLoaded = set.mNumItemsLoaded;
if (numItemsLoaded < set.getNumExpectedItems() && numItemsLoaded < 8) {
synchronized (set) {
dataSource.loadItemsForSet(this, set, numItemsLoaded, 8);
}
if (set.getNumExpectedItems() == 0) {
mediaSets.remove(set);
break;
}
if (mListener != null) {
mListenerNeedsUpdate = false;
mListener.onFeedChanged(this, mListenerNeedsLayout);
mListenerNeedsLayout = false;
}
sleepMs = 100;
scanMediaSets = false;
}
if (!set.setContainsValidItems()) {
mediaSets.remove(set);
if (mListener != null) {
mListenerNeedsUpdate = false;
mListener.onFeedChanged(this, mListenerNeedsLayout);
mListenerNeedsLayout = false;
}
break;
}
}
}
numSets = mediaSets.size();
for (int i = 0; i < numSets; ++i) {
MediaSet set = mediaSets.get(i);
if (i >= bufferedRange.begin && i <= bufferedRange.end) {
if (scanMediaSets) {
int numItemsLoaded = set.mNumItemsLoaded;
if (numItemsLoaded < set.getNumExpectedItems() && numItemsLoaded < 8) {
synchronized (set) {
dataSource.loadItemsForSet(this, set, numItemsLoaded, 8);
}
if (set.getNumExpectedItems() == 0) {
mediaSets.remove(set);
break;
}
if (mListener != null) {
mListenerNeedsUpdate = false;
mListener.onFeedChanged(this, mListenerNeedsLayout);
mListenerNeedsLayout = false;
}
sleepMs = 100;
scanMediaSets = false;
}
}
} else if (!mListenerNeedsUpdate && (i < bufferedRange.begin || i > bufferedRange.end)) {
// Purge this set to its initial status.
MediaClustering clustering = mClusterSets.get(set);
if (clustering != null) {
clustering.clear();
mClusterSets.remove(set);
}
if (set.getNumItems() != 0)
set.clear();
}
}
}
if (expandedSetIndex != Shared.INVALID) {
int numSets = mMediaSets.size();
for (int i = 0; i < numSets; ++i) {
// Purge other sets.
if (i != expandedSetIndex) {
MediaSet set = mediaSets.get(i);
MediaClustering clustering = mClusterSets.get(set);
if (clustering != null) {
clustering.clear();
mClusterSets.remove(set);
}
if (set.mNumItemsLoaded != 0)
set.clear();
}
}
// Make sure all the items are loaded for the album.
int numItemsLoaded = mediaSets.get(expandedSetIndex).mNumItemsLoaded;
int requestedItems = mVisibleRange.end;
// requestedItems count changes in clustering mode.
if (mInClusteringMode && mClusterSets != null) {
requestedItems = 0;
MediaClustering clustering = mClusterSets.get(mediaSets.get(expandedSetIndex));
if (clustering != null) {
ArrayList<Cluster> clusters = clustering.getClustersForDisplay();
int numClusters = clusters.size();
for (int i = 0; i < numClusters; i++) {
requestedItems += clusters.get(i).getNumExpectedItems();
}
}
}
MediaSet set = mediaSets.get(expandedSetIndex);
if (numItemsLoaded < set.getNumExpectedItems()) {
// We perform calculations for a window that gets
// anchored to a multiple of NUM_ITEMS_LOOKAHEAD.
// The start of the window is 0, x, 2x, 3x ... etc
// where x = NUM_ITEMS_LOOKAHEAD.
synchronized (set) {
dataSource.loadItemsForSet(this, set, numItemsLoaded, (requestedItems / NUM_ITEMS_LOOKAHEAD)
* NUM_ITEMS_LOOKAHEAD + NUM_ITEMS_LOOKAHEAD);
}
if (set.getNumExpectedItems() == 0) {
mediaSets.remove(set);
mListenerNeedsUpdate = false;
mListener.onFeedChanged(this, mListenerNeedsLayout);
mListenerNeedsLayout = false;
}
if (numItemsLoaded != set.mNumItemsLoaded && mListener != null) {
mListenerNeedsUpdate = false;
mListener.onFeedChanged(this, mListenerNeedsLayout);
mListenerNeedsLayout = false;
}
}
}
MediaFilter filter = mMediaFilter;
if (filter != null && mMediaFilteredSet == null) {
if (expandedSetIndex != Shared.INVALID) {
MediaSet set = mediaSets.get(expandedSetIndex);
ArrayList<MediaItem> items = set.getItems();
int numItems = set.getNumItems();
MediaSet filteredSet = new MediaSet();
filteredSet.setNumExpectedItems(numItems);
mMediaFilteredSet = filteredSet;
for (int i = 0; i < numItems; ++i) {
MediaItem item = items.get(i);
if (filter.pass(item)) {
filteredSet.addItem(item);
}
}
filteredSet.updateNumExpectedItems();
filteredSet.generateTitle(true);
}
updateListener(true);
}
}
}
}
}
public void expandMediaSet(int mediaSetIndex) {
// We need to check if this slot can be focused or not.
if (mListener != null) {
mListener.onFeedAboutToChange(this);
}
if (mExpandedMediaSetIndex > 0 && mediaSetIndex == Shared.INVALID) {
// We are collapsing a previously expanded media set
if (mediaSetIndex < mMediaSets.size() && mExpandedMediaSetIndex >= 0 && mExpandedMediaSetIndex < mMediaSets.size()) {
MediaSet set = mMediaSets.get(mExpandedMediaSetIndex);
if (set.getNumItems() == 0) {
set.clear();
}
}
}
mExpandedMediaSetIndex = mediaSetIndex;
if (mediaSetIndex < mMediaSets.size() && mediaSetIndex >= 0) {
// Notify Picasa that the user entered the album.
// MediaSet set = mMediaSets.get(mediaSetIndex);
// PicasaService.requestSync(mContext,
// PicasaService.TYPE_ALBUM_PHOTOS, set.mPicasaAlbumId);
}
updateListener(true);
mMediaFeedNeedsToRun = true;
}
public boolean canExpandSet(int slotIndex) {
int mediaSetIndex = slotIndex;
if (mediaSetIndex < mMediaSets.size() && mediaSetIndex >= 0) {
MediaSet set = mMediaSets.get(mediaSetIndex);
if (set.getNumItems() > 0) {
MediaItem item = set.getItems().get(0);
if (item.mId == Shared.INVALID) {
return false;
}
return true;
}
}
return false;
}
public boolean hasExpandedMediaSet() {
return (mExpandedMediaSetIndex != Shared.INVALID);
}
public boolean restorePreviousClusteringState() {
boolean retVal = disableClusteringIfNecessary();
if (retVal) {
if (mListener != null) {
mListener.onFeedAboutToChange(this);
}
updateListener(true);
mMediaFeedNeedsToRun = true;
}
return retVal;
}
private boolean disableClusteringIfNecessary() {
if (mInClusteringMode) {
// Disable clustering.
mInClusteringMode = false;
mMediaFeedNeedsToRun = true;
return true;
}
return false;
}
public boolean isClustered() {
return mInClusteringMode;
}
public MediaSet getCurrentSet() {
if (mExpandedMediaSetIndex != Shared.INVALID && mExpandedMediaSetIndex < mMediaSets.size()) {
return mMediaSets.get(mExpandedMediaSetIndex);
}
return null;
}
public void performClustering() {
if (mListener != null) {
mListener.onFeedAboutToChange(this);
}
MediaSet setToUse = null;
if (mExpandedMediaSetIndex != Shared.INVALID && mExpandedMediaSetIndex < mMediaSets.size()) {
setToUse = mMediaSets.get(mExpandedMediaSetIndex);
}
if (setToUse != null) {
MediaClustering clustering = null;
synchronized (mClusterSets) {
// Make sure the computation is completed to the end.
clustering = mClusterSets.get(setToUse);
if (clustering != null) {
clustering.compute(null, true);
} else {
return;
}
}
mInClusteringMode = true;
updateListener(true);
}
}
public void moveSetToFront(MediaSet mediaSet) {
ArrayList<MediaSet> mediaSets = mMediaSets;
int numSets = mediaSets.size();
if (numSets == 0) {
mediaSets.add(mediaSet);
return;
}
MediaSet setToFind = mediaSets.get(0);
if (setToFind == mediaSet) {
return;
}
mediaSets.set(0, mediaSet);
int indexToSwapTill = -1;
for (int i = 1; i < numSets; ++i) {
MediaSet set = mediaSets.get(i);
if (set == mediaSet) {
mediaSets.set(i, setToFind);
indexToSwapTill = i;
break;
}
}
if (indexToSwapTill != Shared.INVALID) {
for (int i = indexToSwapTill; i > 1; --i) {
MediaSet setEnd = mediaSets.get(i);
MediaSet setPrev = mediaSets.get(i - 1);
mediaSets.set(i, setPrev);
mediaSets.set(i - 1, setEnd);
}
}
mMediaFeedNeedsToRun = true;
}
public MediaSet replaceMediaSet(long setId, DataSource dataSource) {
Log.i(TAG, "Replacing media set " + setId);
final MediaSet set = getMediaSet(setId);
set.refresh();
return set;
}
public void setSingleImageMode(boolean singleImageMode) {
mSingleImageMode = singleImageMode;
}
public boolean isSingleImageMode() {
return mSingleImageMode;
}
public MediaSet getExpandedMediaSet() {
if (mExpandedMediaSetIndex == Shared.INVALID)
return null;
if (mExpandedMediaSetIndex >= mMediaSets.size())
return null;
return mMediaSets.get(mExpandedMediaSetIndex);
}
public void refresh() {
if (mDataSource != null) {
synchronized (mRequestedRefresh) {
mRequestedRefresh.add(mDataSource.getDatabaseUris());
}
}
}
private void refresh(final String[] databaseUris) {
synchronized (mMediaSets) {
if (mDataSource != null) {
synchronized (mRequestedRefresh) {
mRequestedRefresh.add(databaseUris);
}
}
}
}
public void onPause() {
final HashMap<String, ContentObserver> observers = mContentObservers;
String[] uris = new String[observers.size()];
uris = observers.keySet().toArray(uris);
final int numUris = uris.length;
final ContentResolver cr = mContext.getContentResolver();
for (int i = 0; i < numUris; ++i) {
final String uri = uris[i];
if (uri != null) {
final ContentObserver observer = observers.get(uri);
cr.unregisterContentObserver(observer);
observers.remove(uri);
}
}
observers.clear();
}
public void onResume() {
// We setup the listeners for this datasource
final String[] uris = mDataSource.getDatabaseUris();
final HashMap<String, ContentObserver> observers = mContentObservers;
if (mContext instanceof Gallery) {
final Gallery gallery = (Gallery) mContext;
final ContentResolver cr = mContext.getContentResolver();
if (uris != null) {
final int numUris = uris.length;
for (int i = 0; i < numUris; ++i) {
final String uri = uris[i];
final ContentObserver presentObserver = observers.get(uri);
if (presentObserver == null) {
final Handler handler = App.get(mContext).getHandler();
final ContentObserver observer = new ContentObserver(handler) {
public void onChange(boolean selfChange) {
if (!mWaitingForMediaScanner) {
MediaFeed.this.refresh(new String[] { uri });
}
}
};
cr.registerContentObserver(Uri.parse(uri), true, observer);
observers.put(uri, observer);
}
}
}
}
refresh();
}
}
| true | true | public void run() {
DataSource dataSource = mDataSource;
int sleepMs = 10;
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
if (dataSource != null) {
while (!Thread.interrupted()) {
String[] databaseUris = null;
boolean performRefresh = false;
synchronized (mRequestedRefresh) {
if (mRequestedRefresh.size() > 0) {
// We prune this first.
int numRequests = mRequestedRefresh.size();
for (int i = 0; i < numRequests; ++i) {
databaseUris = ArrayUtils.addAll(databaseUris, mRequestedRefresh.get(i));
}
mRequestedRefresh.clear();
performRefresh = true;
// We need to eliminate duplicate uris in this array
final HashMap<String, String> uris = new HashMap<String, String>();
if (databaseUris != null) {
int numUris = databaseUris.length;
for (int i = 0; i < numUris; ++i) {
final String uri = databaseUris[i];
if (uri != null)
uris.put(uri, uri);
}
}
databaseUris = new String[0];
databaseUris = (String[]) uris.keySet().toArray(databaseUris);
}
}
if (performRefresh) {
if (dataSource != null) {
dataSource.refresh(this, databaseUris);
}
}
if (mListenerNeedsUpdate && !mMediaFeedNeedsToRun) {
mListenerNeedsUpdate = false;
if (mListener != null)
mListener.onFeedChanged(this, mListenerNeedsLayout);
try {
Thread.sleep(sleepMs);
} catch (InterruptedException e) {
return;
}
} else {
try {
Thread.sleep(sleepMs);
} catch (InterruptedException e) {
return;
}
}
sleepMs = 300;
if (!mMediaFeedNeedsToRun)
continue;
App app = App.get(mContext);
if (app == null || app.isPaused())
continue;
mMediaFeedNeedsToRun = false;
ArrayList<MediaSet> mediaSets = mMediaSets;
synchronized (mediaSets) {
int expandedSetIndex = mExpandedMediaSetIndex;
if (expandedSetIndex >= mMediaSets.size()) {
expandedSetIndex = Shared.INVALID;
}
if (expandedSetIndex == Shared.INVALID) {
// We purge the sets outside this visibleRange.
int numSets = mediaSets.size();
IndexRange visibleRange = mVisibleRange;
IndexRange bufferedRange = mBufferedRange;
boolean scanMediaSets = true;
for (int i = 0; i < numSets; ++i) {
if (i >= visibleRange.begin && i <= visibleRange.end && scanMediaSets) {
MediaSet set = mediaSets.get(i);
int numItemsLoaded = set.mNumItemsLoaded;
if (numItemsLoaded < set.getNumExpectedItems() && numItemsLoaded < 8) {
synchronized (set) {
dataSource.loadItemsForSet(this, set, numItemsLoaded, 8);
}
if (set.getNumExpectedItems() == 0) {
mediaSets.remove(set);
break;
}
if (mListener != null) {
mListenerNeedsUpdate = false;
mListener.onFeedChanged(this, mListenerNeedsLayout);
mListenerNeedsLayout = false;
}
sleepMs = 100;
scanMediaSets = false;
}
if (!set.setContainsValidItems()) {
mediaSets.remove(set);
if (mListener != null) {
mListenerNeedsUpdate = false;
mListener.onFeedChanged(this, mListenerNeedsLayout);
mListenerNeedsLayout = false;
}
break;
}
}
}
numSets = mediaSets.size();
for (int i = 0; i < numSets; ++i) {
MediaSet set = mediaSets.get(i);
if (i >= bufferedRange.begin && i <= bufferedRange.end) {
if (scanMediaSets) {
int numItemsLoaded = set.mNumItemsLoaded;
if (numItemsLoaded < set.getNumExpectedItems() && numItemsLoaded < 8) {
synchronized (set) {
dataSource.loadItemsForSet(this, set, numItemsLoaded, 8);
}
if (set.getNumExpectedItems() == 0) {
mediaSets.remove(set);
break;
}
if (mListener != null) {
mListenerNeedsUpdate = false;
mListener.onFeedChanged(this, mListenerNeedsLayout);
mListenerNeedsLayout = false;
}
sleepMs = 100;
scanMediaSets = false;
}
}
} else if (!mListenerNeedsUpdate && (i < bufferedRange.begin || i > bufferedRange.end)) {
// Purge this set to its initial status.
MediaClustering clustering = mClusterSets.get(set);
if (clustering != null) {
clustering.clear();
mClusterSets.remove(set);
}
if (set.getNumItems() != 0)
set.clear();
}
}
}
if (expandedSetIndex != Shared.INVALID) {
int numSets = mMediaSets.size();
for (int i = 0; i < numSets; ++i) {
// Purge other sets.
if (i != expandedSetIndex) {
MediaSet set = mediaSets.get(i);
MediaClustering clustering = mClusterSets.get(set);
if (clustering != null) {
clustering.clear();
mClusterSets.remove(set);
}
if (set.mNumItemsLoaded != 0)
set.clear();
}
}
// Make sure all the items are loaded for the album.
int numItemsLoaded = mediaSets.get(expandedSetIndex).mNumItemsLoaded;
int requestedItems = mVisibleRange.end;
// requestedItems count changes in clustering mode.
if (mInClusteringMode && mClusterSets != null) {
requestedItems = 0;
MediaClustering clustering = mClusterSets.get(mediaSets.get(expandedSetIndex));
if (clustering != null) {
ArrayList<Cluster> clusters = clustering.getClustersForDisplay();
int numClusters = clusters.size();
for (int i = 0; i < numClusters; i++) {
requestedItems += clusters.get(i).getNumExpectedItems();
}
}
}
MediaSet set = mediaSets.get(expandedSetIndex);
if (numItemsLoaded < set.getNumExpectedItems()) {
// We perform calculations for a window that gets
// anchored to a multiple of NUM_ITEMS_LOOKAHEAD.
// The start of the window is 0, x, 2x, 3x ... etc
// where x = NUM_ITEMS_LOOKAHEAD.
synchronized (set) {
dataSource.loadItemsForSet(this, set, numItemsLoaded, (requestedItems / NUM_ITEMS_LOOKAHEAD)
* NUM_ITEMS_LOOKAHEAD + NUM_ITEMS_LOOKAHEAD);
}
if (set.getNumExpectedItems() == 0) {
mediaSets.remove(set);
mListenerNeedsUpdate = false;
mListener.onFeedChanged(this, mListenerNeedsLayout);
mListenerNeedsLayout = false;
}
if (numItemsLoaded != set.mNumItemsLoaded && mListener != null) {
mListenerNeedsUpdate = false;
mListener.onFeedChanged(this, mListenerNeedsLayout);
mListenerNeedsLayout = false;
}
}
}
MediaFilter filter = mMediaFilter;
if (filter != null && mMediaFilteredSet == null) {
if (expandedSetIndex != Shared.INVALID) {
MediaSet set = mediaSets.get(expandedSetIndex);
ArrayList<MediaItem> items = set.getItems();
int numItems = set.getNumItems();
MediaSet filteredSet = new MediaSet();
filteredSet.setNumExpectedItems(numItems);
mMediaFilteredSet = filteredSet;
for (int i = 0; i < numItems; ++i) {
MediaItem item = items.get(i);
if (filter.pass(item)) {
filteredSet.addItem(item);
}
}
filteredSet.updateNumExpectedItems();
filteredSet.generateTitle(true);
}
updateListener(true);
}
}
}
}
}
| public void run() {
DataSource dataSource = mDataSource;
int sleepMs = 10;
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
if (dataSource != null) {
while (!Thread.interrupted()) {
String[] databaseUris = null;
boolean performRefresh = false;
synchronized (mRequestedRefresh) {
if (mRequestedRefresh.size() > 0) {
// We prune this first.
int numRequests = mRequestedRefresh.size();
for (int i = 0; i < numRequests; ++i) {
databaseUris = ArrayUtils.addAll(databaseUris, mRequestedRefresh.get(i));
}
mRequestedRefresh.clear();
performRefresh = true;
// We need to eliminate duplicate uris in this array
final HashMap<String, String> uris = new HashMap<String, String>();
if (databaseUris != null) {
int numUris = databaseUris.length;
for (int i = 0; i < numUris; ++i) {
final String uri = databaseUris[i];
if (uri != null)
uris.put(uri, uri);
}
}
databaseUris = new String[0];
databaseUris = (String[]) uris.keySet().toArray(databaseUris);
}
}
if (performRefresh) {
if (dataSource != null) {
dataSource.refresh(this, databaseUris);
mMediaFeedNeedsToRun = true;
}
}
if (mListenerNeedsUpdate && !mMediaFeedNeedsToRun) {
mListenerNeedsUpdate = false;
if (mListener != null)
mListener.onFeedChanged(this, mListenerNeedsLayout);
try {
Thread.sleep(sleepMs);
} catch (InterruptedException e) {
return;
}
} else {
try {
Thread.sleep(sleepMs);
} catch (InterruptedException e) {
return;
}
}
sleepMs = 300;
if (!mMediaFeedNeedsToRun)
continue;
App app = App.get(mContext);
if (app == null || app.isPaused())
continue;
mMediaFeedNeedsToRun = false;
ArrayList<MediaSet> mediaSets = mMediaSets;
synchronized (mediaSets) {
int expandedSetIndex = mExpandedMediaSetIndex;
if (expandedSetIndex >= mMediaSets.size()) {
expandedSetIndex = Shared.INVALID;
}
if (expandedSetIndex == Shared.INVALID) {
// We purge the sets outside this visibleRange.
int numSets = mediaSets.size();
IndexRange visibleRange = mVisibleRange;
IndexRange bufferedRange = mBufferedRange;
boolean scanMediaSets = true;
for (int i = 0; i < numSets; ++i) {
if (i >= visibleRange.begin && i <= visibleRange.end && scanMediaSets) {
MediaSet set = mediaSets.get(i);
int numItemsLoaded = set.mNumItemsLoaded;
if (numItemsLoaded < set.getNumExpectedItems() && numItemsLoaded < 8) {
synchronized (set) {
dataSource.loadItemsForSet(this, set, numItemsLoaded, 8);
}
if (set.getNumExpectedItems() == 0) {
mediaSets.remove(set);
break;
}
if (mListener != null) {
mListenerNeedsUpdate = false;
mListener.onFeedChanged(this, mListenerNeedsLayout);
mListenerNeedsLayout = false;
}
sleepMs = 100;
scanMediaSets = false;
}
if (!set.setContainsValidItems()) {
mediaSets.remove(set);
if (mListener != null) {
mListenerNeedsUpdate = false;
mListener.onFeedChanged(this, mListenerNeedsLayout);
mListenerNeedsLayout = false;
}
break;
}
}
}
numSets = mediaSets.size();
for (int i = 0; i < numSets; ++i) {
MediaSet set = mediaSets.get(i);
if (i >= bufferedRange.begin && i <= bufferedRange.end) {
if (scanMediaSets) {
int numItemsLoaded = set.mNumItemsLoaded;
if (numItemsLoaded < set.getNumExpectedItems() && numItemsLoaded < 8) {
synchronized (set) {
dataSource.loadItemsForSet(this, set, numItemsLoaded, 8);
}
if (set.getNumExpectedItems() == 0) {
mediaSets.remove(set);
break;
}
if (mListener != null) {
mListenerNeedsUpdate = false;
mListener.onFeedChanged(this, mListenerNeedsLayout);
mListenerNeedsLayout = false;
}
sleepMs = 100;
scanMediaSets = false;
}
}
} else if (!mListenerNeedsUpdate && (i < bufferedRange.begin || i > bufferedRange.end)) {
// Purge this set to its initial status.
MediaClustering clustering = mClusterSets.get(set);
if (clustering != null) {
clustering.clear();
mClusterSets.remove(set);
}
if (set.getNumItems() != 0)
set.clear();
}
}
}
if (expandedSetIndex != Shared.INVALID) {
int numSets = mMediaSets.size();
for (int i = 0; i < numSets; ++i) {
// Purge other sets.
if (i != expandedSetIndex) {
MediaSet set = mediaSets.get(i);
MediaClustering clustering = mClusterSets.get(set);
if (clustering != null) {
clustering.clear();
mClusterSets.remove(set);
}
if (set.mNumItemsLoaded != 0)
set.clear();
}
}
// Make sure all the items are loaded for the album.
int numItemsLoaded = mediaSets.get(expandedSetIndex).mNumItemsLoaded;
int requestedItems = mVisibleRange.end;
// requestedItems count changes in clustering mode.
if (mInClusteringMode && mClusterSets != null) {
requestedItems = 0;
MediaClustering clustering = mClusterSets.get(mediaSets.get(expandedSetIndex));
if (clustering != null) {
ArrayList<Cluster> clusters = clustering.getClustersForDisplay();
int numClusters = clusters.size();
for (int i = 0; i < numClusters; i++) {
requestedItems += clusters.get(i).getNumExpectedItems();
}
}
}
MediaSet set = mediaSets.get(expandedSetIndex);
if (numItemsLoaded < set.getNumExpectedItems()) {
// We perform calculations for a window that gets
// anchored to a multiple of NUM_ITEMS_LOOKAHEAD.
// The start of the window is 0, x, 2x, 3x ... etc
// where x = NUM_ITEMS_LOOKAHEAD.
synchronized (set) {
dataSource.loadItemsForSet(this, set, numItemsLoaded, (requestedItems / NUM_ITEMS_LOOKAHEAD)
* NUM_ITEMS_LOOKAHEAD + NUM_ITEMS_LOOKAHEAD);
}
if (set.getNumExpectedItems() == 0) {
mediaSets.remove(set);
mListenerNeedsUpdate = false;
mListener.onFeedChanged(this, mListenerNeedsLayout);
mListenerNeedsLayout = false;
}
if (numItemsLoaded != set.mNumItemsLoaded && mListener != null) {
mListenerNeedsUpdate = false;
mListener.onFeedChanged(this, mListenerNeedsLayout);
mListenerNeedsLayout = false;
}
}
}
MediaFilter filter = mMediaFilter;
if (filter != null && mMediaFilteredSet == null) {
if (expandedSetIndex != Shared.INVALID) {
MediaSet set = mediaSets.get(expandedSetIndex);
ArrayList<MediaItem> items = set.getItems();
int numItems = set.getNumItems();
MediaSet filteredSet = new MediaSet();
filteredSet.setNumExpectedItems(numItems);
mMediaFilteredSet = filteredSet;
for (int i = 0; i < numItems; ++i) {
MediaItem item = items.get(i);
if (filter.pass(item)) {
filteredSet.addItem(item);
}
}
filteredSet.updateNumExpectedItems();
filteredSet.generateTitle(true);
}
updateListener(true);
}
}
}
}
}
|
diff --git a/portlet/exoadmin/src/main/java/org/exoplatform/organization/webui/component/UIUserInfo.java b/portlet/exoadmin/src/main/java/org/exoplatform/organization/webui/component/UIUserInfo.java
index a798451..00eaa2d 100644
--- a/portlet/exoadmin/src/main/java/org/exoplatform/organization/webui/component/UIUserInfo.java
+++ b/portlet/exoadmin/src/main/java/org/exoplatform/organization/webui/component/UIUserInfo.java
@@ -1,184 +1,184 @@
/**
* Copyright (C) 2009 eXo Platform SAS.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.exoplatform.organization.webui.component;
import org.exoplatform.commons.serialization.api.annotations.Serialized;
import org.exoplatform.portal.Constants;
import org.exoplatform.portal.application.PortalRequestContext;
import org.exoplatform.portal.webui.util.Util;
import org.exoplatform.portal.webui.workspace.UIPortalApplication;
import org.exoplatform.portal.webui.workspace.UIWorkingWorkspace;
import org.exoplatform.services.organization.OrganizationService;
import org.exoplatform.services.organization.Query;
import org.exoplatform.services.organization.User;
import org.exoplatform.services.organization.UserProfile;
import org.exoplatform.services.organization.UserProfileHandler;
import org.exoplatform.services.resources.LocaleConfig;
import org.exoplatform.services.resources.LocaleConfigService;
import org.exoplatform.webui.application.WebuiRequestContext;
import org.exoplatform.webui.config.annotation.ComponentConfig;
import org.exoplatform.webui.config.annotation.EventConfig;
import org.exoplatform.webui.core.UIPopupWindow;
import org.exoplatform.webui.core.lifecycle.UIFormLifecycle;
import org.exoplatform.webui.event.Event;
import org.exoplatform.webui.event.EventListener;
import org.exoplatform.webui.event.Event.Phase;
import org.exoplatform.webui.form.UIFormInputContainer;
import org.exoplatform.webui.form.UIFormInputSet;
import org.exoplatform.webui.form.UIFormTabPane;
import org.exoplatform.webui.organization.UIUserMembershipSelector;
import org.exoplatform.webui.organization.UIUserProfileInputSet;
/** Created by The eXo Platform SARL Author : chungnv [email protected] Jun 23, 2006 10:07:15 AM */
@ComponentConfig(lifecycle = UIFormLifecycle.class, template = "system:/groovy/webui/form/UIFormTabPane.gtmpl", events = {
@EventConfig(listeners = UIUserInfo.SaveActionListener.class),
@EventConfig(listeners = UIUserInfo.BackActionListener.class, phase = Phase.DECODE),
@EventConfig(listeners = UIUserInfo.ToggleChangePasswordActionListener.class, phase = Phase.DECODE)})
@Serialized
public class UIUserInfo extends UIFormTabPane
{
private String username_ = null;
public UIUserInfo() throws Exception
{
super("UIUserInfo");
UIFormInputSet accountInputSet = new UIAccountEditInputSet("UIAccountEditInputSet");
addChild(accountInputSet);
setSelectedTab(accountInputSet.getId());
UIFormInputSet userProfileSet = new UIUserProfileInputSet("UIUserProfileInputSet");
addChild(userProfileSet);
UIFormInputContainer<?> uiUserMembershipSelectorSet = new UIUserMembershipSelector();
addChild(uiUserMembershipSelectorSet);
setActions(new String[]{"Save", "Back"});
}
public void setUser(String userName) throws Exception
{
username_ = userName;
OrganizationService service = getApplicationComponent(OrganizationService.class);
User user = service.getUserHandler().findUserByName(userName);
getChild(UIAccountEditInputSet.class).setValue(user);
getChild(UIUserProfileInputSet.class).setUserProfile(userName);
UIUserMembershipSelector uiMembershipSelector = getChild(UIUserMembershipSelector.class);
uiMembershipSelector.setUser(user);
}
public String getUserName()
{
return username_;
}
public void processRender(WebuiRequestContext context) throws Exception
{
super.processRender(context);
UIUserMembershipSelector uiUserMembershipSelector = getChild(UIUserMembershipSelector.class);
if (uiUserMembershipSelector == null)
{
return;
}
UIPopupWindow uiPopupWindow = uiUserMembershipSelector.getChild(UIPopupWindow.class);
if (uiPopupWindow == null)
{
return;
}
uiPopupWindow.processRender(context);
}
static public class SaveActionListener extends EventListener<UIUserInfo>
{
public void execute(Event<UIUserInfo> event) throws Exception
{
UIUserInfo uiUserInfo = event.getSource();
OrganizationService service = uiUserInfo.getApplicationComponent(OrganizationService.class);
boolean save = uiUserInfo.getChild(UIAccountEditInputSet.class).save(service);
if (!save)
{
return;
}
uiUserInfo.getChild(UIUserProfileInputSet.class).save(service, uiUserInfo.getUserName(), false);
if (uiUserInfo.getUserName().equals(event.getRequestContext().getRemoteUser()))
{
UserProfileHandler hanlder = service.getUserProfileHandler();
UserProfile userProfile = hanlder.findUserProfileByName(event.getRequestContext().getRemoteUser());
String language = userProfile.getAttribute(Constants.USER_LANGUAGE);
UIPortalApplication uiApp = Util.getUIPortalApplication();
if (language == null || language.trim().length() < 1)
return;
LocaleConfigService localeConfigService =
event.getSource().getApplicationComponent(LocaleConfigService.class);
LocaleConfig localeConfig = localeConfigService.getLocaleConfig(language);
if (localeConfig == null)
localeConfig = localeConfigService.getDefaultLocaleConfig();
- PortalRequestContext prqCtx = PortalRequestContext.getCurrentInstance();
+ PortalRequestContext prqCtx = Util.getPortalRequestContext();
prqCtx.setLocale(localeConfig.getLocale());
Util.getPortalRequestContext().addUIComponentToUpdateByAjax(
uiApp.findFirstComponentOfType(UIWorkingWorkspace.class));
Util.getPortalRequestContext().setFullRender(true);
}
UIUserManagement userManagement = uiUserInfo.getParent();
UIListUsers listUser = userManagement.getChild(UIListUsers.class);
UIAccountEditInputSet accountInput = uiUserInfo.getChild(UIAccountEditInputSet.class);
UIUserProfileInputSet userProfile = uiUserInfo.getChild(UIUserProfileInputSet.class);
uiUserInfo.setRenderSibling(UIListUsers.class);
listUser.search(new Query());
accountInput.reset();
userProfile.reset();
event.getRequestContext().setProcessRender(true);
}
}
static public class BackActionListener extends EventListener<UIUserInfo>
{
public void execute(Event<UIUserInfo> event) throws Exception
{
UIUserInfo userInfo = event.getSource();
UIUserManagement userManagement = userInfo.getParent();
UIListUsers listUser = userManagement.getChild(UIListUsers.class);
UIAccountEditInputSet accountInput = userInfo.getChild(UIAccountEditInputSet.class);
UIUserProfileInputSet userProfile = userInfo.getChild(UIUserProfileInputSet.class);
userInfo.setRenderSibling(UIListUsers.class);
listUser.search(new Query());
accountInput.reset();
userProfile.reset();
event.getRequestContext().setProcessRender(true);
}
}
static public class ToggleChangePasswordActionListener extends EventListener<UIUserInfo>
{
public void execute(Event<UIUserInfo> event) throws Exception
{
UIUserInfo userInfo = event.getSource();
UIAccountEditInputSet uiAccountInput = userInfo.getChild(UIAccountEditInputSet.class);
uiAccountInput.checkChangePassword();
}
}
}
| true | true | public void execute(Event<UIUserInfo> event) throws Exception
{
UIUserInfo uiUserInfo = event.getSource();
OrganizationService service = uiUserInfo.getApplicationComponent(OrganizationService.class);
boolean save = uiUserInfo.getChild(UIAccountEditInputSet.class).save(service);
if (!save)
{
return;
}
uiUserInfo.getChild(UIUserProfileInputSet.class).save(service, uiUserInfo.getUserName(), false);
if (uiUserInfo.getUserName().equals(event.getRequestContext().getRemoteUser()))
{
UserProfileHandler hanlder = service.getUserProfileHandler();
UserProfile userProfile = hanlder.findUserProfileByName(event.getRequestContext().getRemoteUser());
String language = userProfile.getAttribute(Constants.USER_LANGUAGE);
UIPortalApplication uiApp = Util.getUIPortalApplication();
if (language == null || language.trim().length() < 1)
return;
LocaleConfigService localeConfigService =
event.getSource().getApplicationComponent(LocaleConfigService.class);
LocaleConfig localeConfig = localeConfigService.getLocaleConfig(language);
if (localeConfig == null)
localeConfig = localeConfigService.getDefaultLocaleConfig();
PortalRequestContext prqCtx = PortalRequestContext.getCurrentInstance();
prqCtx.setLocale(localeConfig.getLocale());
Util.getPortalRequestContext().addUIComponentToUpdateByAjax(
uiApp.findFirstComponentOfType(UIWorkingWorkspace.class));
Util.getPortalRequestContext().setFullRender(true);
}
UIUserManagement userManagement = uiUserInfo.getParent();
UIListUsers listUser = userManagement.getChild(UIListUsers.class);
UIAccountEditInputSet accountInput = uiUserInfo.getChild(UIAccountEditInputSet.class);
UIUserProfileInputSet userProfile = uiUserInfo.getChild(UIUserProfileInputSet.class);
uiUserInfo.setRenderSibling(UIListUsers.class);
listUser.search(new Query());
accountInput.reset();
userProfile.reset();
event.getRequestContext().setProcessRender(true);
}
| public void execute(Event<UIUserInfo> event) throws Exception
{
UIUserInfo uiUserInfo = event.getSource();
OrganizationService service = uiUserInfo.getApplicationComponent(OrganizationService.class);
boolean save = uiUserInfo.getChild(UIAccountEditInputSet.class).save(service);
if (!save)
{
return;
}
uiUserInfo.getChild(UIUserProfileInputSet.class).save(service, uiUserInfo.getUserName(), false);
if (uiUserInfo.getUserName().equals(event.getRequestContext().getRemoteUser()))
{
UserProfileHandler hanlder = service.getUserProfileHandler();
UserProfile userProfile = hanlder.findUserProfileByName(event.getRequestContext().getRemoteUser());
String language = userProfile.getAttribute(Constants.USER_LANGUAGE);
UIPortalApplication uiApp = Util.getUIPortalApplication();
if (language == null || language.trim().length() < 1)
return;
LocaleConfigService localeConfigService =
event.getSource().getApplicationComponent(LocaleConfigService.class);
LocaleConfig localeConfig = localeConfigService.getLocaleConfig(language);
if (localeConfig == null)
localeConfig = localeConfigService.getDefaultLocaleConfig();
PortalRequestContext prqCtx = Util.getPortalRequestContext();
prqCtx.setLocale(localeConfig.getLocale());
Util.getPortalRequestContext().addUIComponentToUpdateByAjax(
uiApp.findFirstComponentOfType(UIWorkingWorkspace.class));
Util.getPortalRequestContext().setFullRender(true);
}
UIUserManagement userManagement = uiUserInfo.getParent();
UIListUsers listUser = userManagement.getChild(UIListUsers.class);
UIAccountEditInputSet accountInput = uiUserInfo.getChild(UIAccountEditInputSet.class);
UIUserProfileInputSet userProfile = uiUserInfo.getChild(UIUserProfileInputSet.class);
uiUserInfo.setRenderSibling(UIListUsers.class);
listUser.search(new Query());
accountInput.reset();
userProfile.reset();
event.getRequestContext().setProcessRender(true);
}
|
diff --git a/src/com/android/calendar/alerts/AlertReceiver.java b/src/com/android/calendar/alerts/AlertReceiver.java
index 8894ae0d..611de683 100644
--- a/src/com/android/calendar/alerts/AlertReceiver.java
+++ b/src/com/android/calendar/alerts/AlertReceiver.java
@@ -1,442 +1,442 @@
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.calendar.alerts;
import com.android.calendar.R;
import com.android.calendar.Utils;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.PowerManager;
import android.provider.CalendarContract.Attendees;
import android.provider.CalendarContract.Calendars;
import android.provider.CalendarContract.Events;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Receives android.intent.action.EVENT_REMINDER intents and handles
* event reminders. The intent URI specifies an alert id in the
* CalendarAlerts database table. This class also receives the
* BOOT_COMPLETED intent so that it can add a status bar notification
* if there are Calendar event alarms that have not been dismissed.
* It also receives the TIME_CHANGED action so that it can fire off
* snoozed alarms that have become ready. The real work is done in
* the AlertService class.
*
* To trigger this code after pushing the apk to device:
* adb shell am broadcast -a "android.intent.action.EVENT_REMINDER"
* -n "com.android.calendar/.alerts.AlertReceiver"
*/
public class AlertReceiver extends BroadcastReceiver {
private static final String TAG = "AlertReceiver";
private static final String DELETE_ACTION = "delete";
static final Object mStartingServiceSync = new Object();
static PowerManager.WakeLock mStartingService;
public static final String ACTION_DISMISS_OLD_REMINDERS = "removeOldReminders";
private static final int NOTIFICATION_DIGEST_MAX_LENGTH = 3;
@Override
public void onReceive(Context context, Intent intent) {
if (AlertService.DEBUG) {
Log.d(TAG, "onReceive: a=" + intent.getAction() + " " + intent.toString());
}
if (DELETE_ACTION.equals(intent.getAction())) {
/* The user has clicked the "Clear All Notifications"
* buttons so dismiss all Calendar alerts.
*/
// TODO Grab a wake lock here?
Intent serviceIntent = new Intent(context, DismissAlarmsService.class);
context.startService(serviceIntent);
} else {
Intent i = new Intent();
i.setClass(context, AlertService.class);
i.putExtras(intent);
i.putExtra("action", intent.getAction());
Uri uri = intent.getData();
// This intent might be a BOOT_COMPLETED so it might not have a Uri.
if (uri != null) {
i.putExtra("uri", uri.toString());
}
beginStartingService(context, i);
}
}
/**
* Start the service to process the current event notifications, acquiring
* the wake lock before returning to ensure that the service will run.
*/
public static void beginStartingService(Context context, Intent intent) {
synchronized (mStartingServiceSync) {
if (mStartingService == null) {
PowerManager pm =
(PowerManager)context.getSystemService(Context.POWER_SERVICE);
mStartingService = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"StartingAlertService");
mStartingService.setReferenceCounted(false);
}
mStartingService.acquire();
context.startService(intent);
}
}
/**
* Called back by the service when it has finished processing notifications,
* releasing the wake lock if the service is now stopping.
*/
public static void finishStartingService(Service service, int startId) {
synchronized (mStartingServiceSync) {
if (mStartingService != null) {
if (service.stopSelfResult(startId)) {
mStartingService.release();
}
}
}
}
private static PendingIntent createClickEventIntent(Context context, long eventId,
long startMillis, long endMillis, int notificationId) {
return createDismissAlarmsIntent(context, eventId, startMillis, endMillis, notificationId,
"com.android.calendar.CLICK", true);
}
private static PendingIntent createDeleteEventIntent(Context context, long eventId,
long startMillis, long endMillis, int notificationId) {
return createDismissAlarmsIntent(context, eventId, startMillis, endMillis, notificationId,
"com.android.calendar.DELETE", false);
}
private static PendingIntent createDismissAlarmsIntent(Context context, long eventId,
long startMillis, long endMillis, int notificationId, String action,
boolean showEvent) {
Intent intent = new Intent();
intent.setClass(context, DismissAlarmsService.class);
intent.putExtra(AlertUtils.EVENT_ID_KEY, eventId);
intent.putExtra(AlertUtils.EVENT_START_KEY, startMillis);
intent.putExtra(AlertUtils.EVENT_END_KEY, endMillis);
intent.putExtra(AlertUtils.SHOW_EVENT_KEY, showEvent);
intent.putExtra(AlertUtils.NOTIFICATION_ID_KEY, notificationId);
// Must set a field that affects Intent.filterEquals so that the resulting
// PendingIntent will be a unique instance (the 'extras' don't achieve this).
// This must be unique for the click event across all reminders (so using
// event ID + startTime should be unique). This also must be unique from
// the delete event (which also uses DismissAlarmsService).
Uri.Builder builder = Events.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, eventId);
ContentUris.appendId(builder, startMillis);
intent.setData(builder.build());
intent.setAction(action);
return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
private static PendingIntent createSnoozeIntent(Context context, long eventId,
long startMillis, long endMillis, int notificationId) {
Intent intent = new Intent();
intent.setClass(context, SnoozeAlarmsService.class);
intent.putExtra(AlertUtils.EVENT_ID_KEY, eventId);
intent.putExtra(AlertUtils.EVENT_START_KEY, startMillis);
intent.putExtra(AlertUtils.EVENT_END_KEY, endMillis);
intent.putExtra(AlertUtils.NOTIFICATION_ID_KEY, notificationId);
Uri.Builder builder = Events.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, eventId);
ContentUris.appendId(builder, startMillis);
intent.setData(builder.build());
return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
public static Notification makeBasicNotification(Context context, String title,
String summaryText, long startMillis, long endMillis, long eventId,
int notificationId, boolean doPopup) {
return makeBasicNotificationBuilder(context, title, summaryText, startMillis, endMillis,
eventId, notificationId, doPopup, false, false).getNotification();
}
private static Notification.Builder makeBasicNotificationBuilder(Context context, String title,
String summaryText, long startMillis, long endMillis, long eventId,
int notificationId, boolean doPopup, boolean highPriority, boolean addActionButtons) {
Resources resources = context.getResources();
if (title == null || title.length() == 0) {
title = resources.getString(R.string.no_title_label);
}
// Create an intent triggered by clicking on the status icon, that dismisses the
// notification and shows the event.
PendingIntent clickIntent = createClickEventIntent(context, eventId, startMillis,
endMillis, notificationId);
// Create a delete intent triggered by dismissing the notification.
PendingIntent deleteIntent = createDeleteEventIntent(context, eventId, startMillis,
endMillis, notificationId);
// Create the base notification.
Notification.Builder notificationBuilder = new Notification.Builder(context);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(summaryText);
// TODO: change to the clock icon
notificationBuilder.setSmallIcon(R.drawable.stat_notify_calendar);
notificationBuilder.setContentIntent(clickIntent);
notificationBuilder.setDeleteIntent(deleteIntent);
if (addActionButtons) {
// Create a snooze button. TODO: change snooze to 10 minutes.
PendingIntent snoozeIntent = createSnoozeIntent(context, eventId, startMillis,
endMillis, notificationId);
notificationBuilder.addAction(R.drawable.snooze,
resources.getString(R.string.snooze_5min_label), snoozeIntent);
// Create an email button.
PendingIntent emailIntent = createEmailIntent(context, eventId, title);
if (emailIntent != null) {
notificationBuilder.addAction(R.drawable.ic_menu_email_holo_dark,
resources.getString(R.string.email_guests_label), emailIntent);
}
}
if (doPopup) {
notificationBuilder.setFullScreenIntent(clickIntent, true);
}
// Setting to a higher priority will encourage notification manager to expand the
// notification.
if (highPriority) {
notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
} else {
notificationBuilder.setPriority(Notification.PRIORITY_DEFAULT);
}
return notificationBuilder;
}
/**
* Creates an expanding notification. The initial expanded state is decided by
* the notification manager based on the priority.
*/
public static Notification makeExpandingNotification(Context context, String title,
String summaryText, String description, long startMillis, long endMillis, long eventId,
int notificationId, boolean doPopup, boolean highPriority) {
Notification.Builder basicBuilder = makeBasicNotificationBuilder(context, title,
summaryText, startMillis, endMillis, eventId, notificationId,
doPopup, highPriority, true);
if (TextUtils.isEmpty(description)) {
// When no description, don't use BigTextStyle since it puts too much whitespace.
// This still has the same desired behavior (expands with buttons, pinch closed, etc).
return basicBuilder.build();
} else {
// Create an expanded notification.
Notification.BigTextStyle expandedBuilder = new Notification.BigTextStyle(
basicBuilder);
String text = context.getResources().getString(
R.string.event_notification_big_text, summaryText, description);
expandedBuilder.bigText(text);
return expandedBuilder.build();
}
}
/**
* Creates an expanding digest notification for expired events.
*/
public static Notification makeDigestNotification(Context context,
List<AlertService.NotificationInfo> notificationInfos, String digestTitle) {
if (notificationInfos == null || notificationInfos.size() < 1) {
return null;
}
Resources res = context.getResources();
int numEvents = notificationInfos.size();
// Create an intent triggered by clicking on the status icon that shows the alerts list.
Intent clickIntent = new Intent();
clickIntent.setClass(context, AlertActivity.class);
clickIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingClickIntent = PendingIntent.getActivity(context, 0, clickIntent,
PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);
// Create an intent triggered by dismissing the digest notification that clears all
// expired events.
Intent deleteIntent = new Intent();
deleteIntent.setClass(context, DismissAlarmsService.class);
deleteIntent.setAction(DELETE_ACTION);
deleteIntent.putExtra(AlertUtils.DELETE_EXPIRED_ONLY_KEY, true);
PendingIntent pendingDeleteIntent = PendingIntent.getService(context, 0, deleteIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
if (digestTitle == null || digestTitle.length() == 0) {
digestTitle = res.getString(R.string.no_title_label);
}
Notification.Builder notificationBuilder = new Notification.Builder(context);
notificationBuilder.setContentTitle(digestTitle);
notificationBuilder.setSmallIcon(R.drawable.stat_notify_calendar);
notificationBuilder.setContentIntent(pendingClickIntent);
notificationBuilder.setDeleteIntent(pendingDeleteIntent);
String nEventsStr = res.getQuantityString(R.plurals.Nevents, numEvents, numEvents);
notificationBuilder.setContentText(nEventsStr);
// Multiple reminders. Combine into an expanded digest notification.
Notification.InboxStyle expandedBuilder = new Notification.InboxStyle(
notificationBuilder);
int i = 0;
for (AlertService.NotificationInfo info : notificationInfos) {
if (i < NOTIFICATION_DIGEST_MAX_LENGTH) {
String name = info.eventName;
if (TextUtils.isEmpty(name)) {
name = context.getResources().getString(R.string.no_title_label);
}
String timeLocation = AlertUtils.formatTimeLocation(context, info.startMillis,
info.allDay, info.location);
TextAppearanceSpan primaryTextSpan = new TextAppearanceSpan(context,
R.style.NotificationPrimaryText);
TextAppearanceSpan secondaryTextSpan = new TextAppearanceSpan(context,
R.style.NotificationSecondaryText);
// Event title in bold.
SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
stringBuilder.append(name);
stringBuilder.setSpan(primaryTextSpan, 0, stringBuilder.length(), 0);
stringBuilder.append(" ");
// Followed by time and location.
int secondaryIndex = stringBuilder.length();
stringBuilder.append(timeLocation);
stringBuilder.setSpan(secondaryTextSpan, secondaryIndex, stringBuilder.length(),
0);
expandedBuilder.addLine(stringBuilder);
i++;
} else {
break;
}
}
// If there are too many to display, add "+X missed events" for the last line.
int remaining = numEvents - i;
if (remaining > 0) {
String nMoreEventsStr = res.getQuantityString(R.plurals.N_missed_events, remaining,
remaining);
// TODO: Add highlighting and icon to this last entry once framework allows it.
expandedBuilder.setSummaryText(nMoreEventsStr);
}
// Remove the title in the expanded form (redundant with the listed items).
expandedBuilder.setBigContentTitle("");
- // Set to a low priority to encourage the notification manager to collapse it.
- notificationBuilder.setPriority(Notification.PRIORITY_LOW);
+ // Set to min priority to encourage the notification manager to collapse it.
+ notificationBuilder.setPriority(Notification.PRIORITY_MIN);
return expandedBuilder.build();
}
private static final String[] ATTENDEES_PROJECTION = new String[] {
Attendees.ATTENDEE_EMAIL, // 0
Attendees.ATTENDEE_STATUS, // 1
};
private static final int ATTENDEES_INDEX_EMAIL = 0;
private static final int ATTENDEES_INDEX_STATUS = 1;
private static final String ATTENDEES_WHERE = Attendees.EVENT_ID + "=?";
private static final String ATTENDEES_SORT_ORDER = Attendees.ATTENDEE_NAME + " ASC, "
+ Attendees.ATTENDEE_EMAIL + " ASC";
private static final String[] EVENT_PROJECTION = new String[] {
Calendars.OWNER_ACCOUNT, // 0
Calendars.ACCOUNT_NAME // 1
};
private static final int EVENT_INDEX_OWNER_ACCOUNT = 0;
private static final int EVENT_INDEX_ACCOUNT_NAME = 1;
/**
* Creates an Intent for emailing the attendees of the event. Returns null if there
* are no emailable attendees.
*/
private static PendingIntent createEmailIntent(Context context, long eventId,
String eventTitle) {
ContentResolver resolver = context.getContentResolver();
// TODO: Refactor to move query part into Utils.createEmailAttendeeIntent, to
// be shared with EventInfoFragment.
// Query for the owner account(s).
String ownerAccount = null;
String syncAccount = null;
Cursor eventCursor = resolver.query(
ContentUris.withAppendedId(Events.CONTENT_URI, eventId), EVENT_PROJECTION,
null, null, null);
if (eventCursor.moveToFirst()) {
ownerAccount = eventCursor.getString(EVENT_INDEX_OWNER_ACCOUNT);
syncAccount = eventCursor.getString(EVENT_INDEX_ACCOUNT_NAME);
}
// Query for the attendees.
List<String> toEmails = new ArrayList<String>();
List<String> ccEmails = new ArrayList<String>();
Cursor attendeesCursor = resolver.query(Attendees.CONTENT_URI, ATTENDEES_PROJECTION,
ATTENDEES_WHERE, new String[] { Long.toString(eventId) }, ATTENDEES_SORT_ORDER);
if (attendeesCursor.moveToFirst()) {
do {
int status = attendeesCursor.getInt(ATTENDEES_INDEX_STATUS);
String email = attendeesCursor.getString(ATTENDEES_INDEX_EMAIL);
switch(status) {
case Attendees.ATTENDEE_STATUS_DECLINED:
addIfEmailable(ccEmails, email, syncAccount);
break;
default:
addIfEmailable(toEmails, email, syncAccount);
}
} while (attendeesCursor.moveToNext());
}
Intent intent = null;
if (ownerAccount != null && (toEmails.size() > 0 || ccEmails.size() > 0)) {
intent = Utils.createEmailAttendeesIntent(context.getResources(), eventTitle,
toEmails, ccEmails, ownerAccount);
}
if (intent == null) {
return null;
}
else {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return PendingIntent.getActivity(context, Long.valueOf(eventId).hashCode(), intent,
PendingIntent.FLAG_CANCEL_CURRENT);
}
}
private static void addIfEmailable(List<String> emailList, String email, String syncAccount) {
if (Utils.isValidEmail(email) && !email.equals(syncAccount)) {
emailList.add(email);
}
}
}
| true | true | public static Notification makeDigestNotification(Context context,
List<AlertService.NotificationInfo> notificationInfos, String digestTitle) {
if (notificationInfos == null || notificationInfos.size() < 1) {
return null;
}
Resources res = context.getResources();
int numEvents = notificationInfos.size();
// Create an intent triggered by clicking on the status icon that shows the alerts list.
Intent clickIntent = new Intent();
clickIntent.setClass(context, AlertActivity.class);
clickIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingClickIntent = PendingIntent.getActivity(context, 0, clickIntent,
PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);
// Create an intent triggered by dismissing the digest notification that clears all
// expired events.
Intent deleteIntent = new Intent();
deleteIntent.setClass(context, DismissAlarmsService.class);
deleteIntent.setAction(DELETE_ACTION);
deleteIntent.putExtra(AlertUtils.DELETE_EXPIRED_ONLY_KEY, true);
PendingIntent pendingDeleteIntent = PendingIntent.getService(context, 0, deleteIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
if (digestTitle == null || digestTitle.length() == 0) {
digestTitle = res.getString(R.string.no_title_label);
}
Notification.Builder notificationBuilder = new Notification.Builder(context);
notificationBuilder.setContentTitle(digestTitle);
notificationBuilder.setSmallIcon(R.drawable.stat_notify_calendar);
notificationBuilder.setContentIntent(pendingClickIntent);
notificationBuilder.setDeleteIntent(pendingDeleteIntent);
String nEventsStr = res.getQuantityString(R.plurals.Nevents, numEvents, numEvents);
notificationBuilder.setContentText(nEventsStr);
// Multiple reminders. Combine into an expanded digest notification.
Notification.InboxStyle expandedBuilder = new Notification.InboxStyle(
notificationBuilder);
int i = 0;
for (AlertService.NotificationInfo info : notificationInfos) {
if (i < NOTIFICATION_DIGEST_MAX_LENGTH) {
String name = info.eventName;
if (TextUtils.isEmpty(name)) {
name = context.getResources().getString(R.string.no_title_label);
}
String timeLocation = AlertUtils.formatTimeLocation(context, info.startMillis,
info.allDay, info.location);
TextAppearanceSpan primaryTextSpan = new TextAppearanceSpan(context,
R.style.NotificationPrimaryText);
TextAppearanceSpan secondaryTextSpan = new TextAppearanceSpan(context,
R.style.NotificationSecondaryText);
// Event title in bold.
SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
stringBuilder.append(name);
stringBuilder.setSpan(primaryTextSpan, 0, stringBuilder.length(), 0);
stringBuilder.append(" ");
// Followed by time and location.
int secondaryIndex = stringBuilder.length();
stringBuilder.append(timeLocation);
stringBuilder.setSpan(secondaryTextSpan, secondaryIndex, stringBuilder.length(),
0);
expandedBuilder.addLine(stringBuilder);
i++;
} else {
break;
}
}
// If there are too many to display, add "+X missed events" for the last line.
int remaining = numEvents - i;
if (remaining > 0) {
String nMoreEventsStr = res.getQuantityString(R.plurals.N_missed_events, remaining,
remaining);
// TODO: Add highlighting and icon to this last entry once framework allows it.
expandedBuilder.setSummaryText(nMoreEventsStr);
}
// Remove the title in the expanded form (redundant with the listed items).
expandedBuilder.setBigContentTitle("");
// Set to a low priority to encourage the notification manager to collapse it.
notificationBuilder.setPriority(Notification.PRIORITY_LOW);
return expandedBuilder.build();
}
| public static Notification makeDigestNotification(Context context,
List<AlertService.NotificationInfo> notificationInfos, String digestTitle) {
if (notificationInfos == null || notificationInfos.size() < 1) {
return null;
}
Resources res = context.getResources();
int numEvents = notificationInfos.size();
// Create an intent triggered by clicking on the status icon that shows the alerts list.
Intent clickIntent = new Intent();
clickIntent.setClass(context, AlertActivity.class);
clickIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingClickIntent = PendingIntent.getActivity(context, 0, clickIntent,
PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);
// Create an intent triggered by dismissing the digest notification that clears all
// expired events.
Intent deleteIntent = new Intent();
deleteIntent.setClass(context, DismissAlarmsService.class);
deleteIntent.setAction(DELETE_ACTION);
deleteIntent.putExtra(AlertUtils.DELETE_EXPIRED_ONLY_KEY, true);
PendingIntent pendingDeleteIntent = PendingIntent.getService(context, 0, deleteIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
if (digestTitle == null || digestTitle.length() == 0) {
digestTitle = res.getString(R.string.no_title_label);
}
Notification.Builder notificationBuilder = new Notification.Builder(context);
notificationBuilder.setContentTitle(digestTitle);
notificationBuilder.setSmallIcon(R.drawable.stat_notify_calendar);
notificationBuilder.setContentIntent(pendingClickIntent);
notificationBuilder.setDeleteIntent(pendingDeleteIntent);
String nEventsStr = res.getQuantityString(R.plurals.Nevents, numEvents, numEvents);
notificationBuilder.setContentText(nEventsStr);
// Multiple reminders. Combine into an expanded digest notification.
Notification.InboxStyle expandedBuilder = new Notification.InboxStyle(
notificationBuilder);
int i = 0;
for (AlertService.NotificationInfo info : notificationInfos) {
if (i < NOTIFICATION_DIGEST_MAX_LENGTH) {
String name = info.eventName;
if (TextUtils.isEmpty(name)) {
name = context.getResources().getString(R.string.no_title_label);
}
String timeLocation = AlertUtils.formatTimeLocation(context, info.startMillis,
info.allDay, info.location);
TextAppearanceSpan primaryTextSpan = new TextAppearanceSpan(context,
R.style.NotificationPrimaryText);
TextAppearanceSpan secondaryTextSpan = new TextAppearanceSpan(context,
R.style.NotificationSecondaryText);
// Event title in bold.
SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
stringBuilder.append(name);
stringBuilder.setSpan(primaryTextSpan, 0, stringBuilder.length(), 0);
stringBuilder.append(" ");
// Followed by time and location.
int secondaryIndex = stringBuilder.length();
stringBuilder.append(timeLocation);
stringBuilder.setSpan(secondaryTextSpan, secondaryIndex, stringBuilder.length(),
0);
expandedBuilder.addLine(stringBuilder);
i++;
} else {
break;
}
}
// If there are too many to display, add "+X missed events" for the last line.
int remaining = numEvents - i;
if (remaining > 0) {
String nMoreEventsStr = res.getQuantityString(R.plurals.N_missed_events, remaining,
remaining);
// TODO: Add highlighting and icon to this last entry once framework allows it.
expandedBuilder.setSummaryText(nMoreEventsStr);
}
// Remove the title in the expanded form (redundant with the listed items).
expandedBuilder.setBigContentTitle("");
// Set to min priority to encourage the notification manager to collapse it.
notificationBuilder.setPriority(Notification.PRIORITY_MIN);
return expandedBuilder.build();
}
|
diff --git a/src/test/java/com/jcabi/aether/ClasspathTest.java b/src/test/java/com/jcabi/aether/ClasspathTest.java
index a1d3fb0..a7acac9 100644
--- a/src/test/java/com/jcabi/aether/ClasspathTest.java
+++ b/src/test/java/com/jcabi/aether/ClasspathTest.java
@@ -1,150 +1,157 @@
/**
* Copyright (c) 2012-2013, JCabi.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the jcabi.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jcabi.aether;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import org.apache.maven.model.Dependency;
import org.apache.maven.project.MavenProject;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.Mockito;
import org.sonatype.aether.repository.RemoteRepository;
import org.sonatype.aether.util.artifact.JavaScopes;
/**
* Test case for {@link Classpath}.
* @author Yegor Bugayenko ([email protected])
* @version $Id$
*/
@SuppressWarnings("unchecked")
public final class ClasspathTest {
/**
* Temp dir.
* @checkstyle VisibilityModifier (3 lines)
*/
@Rule
public final transient TemporaryFolder temp = new TemporaryFolder();
/**
* Classpath can build a classpath.
* @throws Exception If there is some problem inside
*/
@Test
public void buildsClasspath() throws Exception {
final Dependency dep = new Dependency();
final String group = "junit";
dep.setGroupId(group);
dep.setArtifactId(group);
dep.setVersion("4.10");
dep.setScope(JavaScopes.TEST);
MatcherAssert.assertThat(
new Classpath(
this.project(dep), this.temp.newFolder(), JavaScopes.TEST
),
Matchers.<File>hasItems(
- Matchers.hasToString(Matchers.endsWith("/as/directory")),
+ Matchers.hasToString(
+ Matchers.endsWith(
+ String.format(
+ "%sas%<sdirectory",
+ System.getProperty("file.separator")
+ )
+ )
+ ),
Matchers.hasToString(Matchers.endsWith("junit-4.10.jar")),
Matchers.hasToString(Matchers.endsWith("hamcrest-core-1.1.jar"))
)
);
}
/**
* Classpath can return a string when a dependency is broken.
* @throws Exception If there is some problem inside
*/
@Test
public void hasToStringWithBrokenDependency() throws Exception {
final Dependency dep = new Dependency();
dep.setGroupId("junit-broken");
dep.setArtifactId("junit-absent");
dep.setVersion("1.0");
dep.setScope(JavaScopes.TEST);
final Classpath classpath = new Classpath(
this.project(dep), this.temp.newFolder(), JavaScopes.TEST
);
MatcherAssert.assertThat(
classpath.toString(),
Matchers.containsString(
"failed to load 'junit-broken:junit-absent:jar:1.0 (compile)'"
)
);
}
/**
* Classpath can be compared to another classpath.
* @throws Exception If there is some problem inside
*/
@Test
public void comparesToAnotherClasspath() throws Exception {
final Dependency dep = new Dependency();
dep.setGroupId("org.apache.commons");
dep.setArtifactId("commons-lang3-absent");
dep.setVersion("3.0");
dep.setScope(JavaScopes.COMPILE);
final Classpath classpath = new Classpath(
this.project(dep), this.temp.newFolder(), JavaScopes.TEST
);
MatcherAssert.assertThat(classpath, Matchers.equalTo(classpath));
MatcherAssert.assertThat(
classpath.canEqual(classpath),
Matchers.is(true)
);
}
/**
* Creates project with this dependency.
* @param dep Dependency to add to the project
* @return Maven project mocked
* @throws Exception If there is some problem inside
*/
private MavenProject project(final Dependency dep) throws Exception {
final MavenProject project = Mockito.mock(MavenProject.class);
Mockito.doReturn(Arrays.asList("/some/path/as/directory"))
.when(project).getTestClasspathElements();
Mockito.doReturn(Arrays.asList(dep)).when(project).getDependencies();
final List<RemoteRepository> repos = Arrays.asList(
new RemoteRepository(
"maven-central",
"default",
"http://repo1.maven.org/maven2/"
)
);
Mockito.doReturn(repos).when(project).getRemoteProjectRepositories();
return project;
}
}
| true | true | public void buildsClasspath() throws Exception {
final Dependency dep = new Dependency();
final String group = "junit";
dep.setGroupId(group);
dep.setArtifactId(group);
dep.setVersion("4.10");
dep.setScope(JavaScopes.TEST);
MatcherAssert.assertThat(
new Classpath(
this.project(dep), this.temp.newFolder(), JavaScopes.TEST
),
Matchers.<File>hasItems(
Matchers.hasToString(Matchers.endsWith("/as/directory")),
Matchers.hasToString(Matchers.endsWith("junit-4.10.jar")),
Matchers.hasToString(Matchers.endsWith("hamcrest-core-1.1.jar"))
)
);
}
| public void buildsClasspath() throws Exception {
final Dependency dep = new Dependency();
final String group = "junit";
dep.setGroupId(group);
dep.setArtifactId(group);
dep.setVersion("4.10");
dep.setScope(JavaScopes.TEST);
MatcherAssert.assertThat(
new Classpath(
this.project(dep), this.temp.newFolder(), JavaScopes.TEST
),
Matchers.<File>hasItems(
Matchers.hasToString(
Matchers.endsWith(
String.format(
"%sas%<sdirectory",
System.getProperty("file.separator")
)
)
),
Matchers.hasToString(Matchers.endsWith("junit-4.10.jar")),
Matchers.hasToString(Matchers.endsWith("hamcrest-core-1.1.jar"))
)
);
}
|
diff --git a/software/examples/java/ExampleSwitchSocket.java b/software/examples/java/ExampleSwitchSocket.java
index 413bf3a..e6a4c99 100644
--- a/software/examples/java/ExampleSwitchSocket.java
+++ b/software/examples/java/ExampleSwitchSocket.java
@@ -1,27 +1,27 @@
import com.tinkerforge.BrickletRemoteSwitch;
import com.tinkerforge.IPConnection;
public class ExampleSwitchSocket {
private static final String host = "localhost";
private static final int port = 4223;
private static final String UID = "XYZ"; // Change to your UID
// Note: To make the example code cleaner we do not handle exceptions. Exceptions you
// might normally want to catch are described in the documentation
public static void main(String args[]) throws Exception {
IPConnection ipcon = new IPConnection(); // Create IP connection
BrickletRemoteSwitch rs = new BrickletRemoteSwitch(UID, ipcon); // Create device object
ipcon.connect(host, port); // Connect to brickd
// Don't use device before ipcon is connected
- // Switch socket with house code 17 and receiver code 16 on.
- // House code 17 is 10001 in binary and means that the
- // DIP switches 1 and 5 are on and 2-4 are off.
- // Receiver code 16 is 10000 in binary and means that the
- // DIP switch E is on and A-D are off.
- rs.switchSocket((short)17, (short)16, BrickletRemoteSwitch.SWITCH_TO_ON);
+ // Switch socket with house code 17 and receiver code 1 on.
+ // House code 17 is 10001 in binary (least-significant bit first)
+ // and means that the DIP switches 1 and 5 are on and 2-4 are off.
+ // Receiver code 1 is 10000 in binary (least-significant bit first)
+ // and means that the DIP switch A is on and B-E are off.
+ rs.switchSocketA((short)17, (short)1, BrickletRemoteSwitch.SWITCH_TO_ON);
System.console().readLine("Press key to exit\n");
}
}
| true | true | public static void main(String args[]) throws Exception {
IPConnection ipcon = new IPConnection(); // Create IP connection
BrickletRemoteSwitch rs = new BrickletRemoteSwitch(UID, ipcon); // Create device object
ipcon.connect(host, port); // Connect to brickd
// Don't use device before ipcon is connected
// Switch socket with house code 17 and receiver code 16 on.
// House code 17 is 10001 in binary and means that the
// DIP switches 1 and 5 are on and 2-4 are off.
// Receiver code 16 is 10000 in binary and means that the
// DIP switch E is on and A-D are off.
rs.switchSocket((short)17, (short)16, BrickletRemoteSwitch.SWITCH_TO_ON);
System.console().readLine("Press key to exit\n");
}
| public static void main(String args[]) throws Exception {
IPConnection ipcon = new IPConnection(); // Create IP connection
BrickletRemoteSwitch rs = new BrickletRemoteSwitch(UID, ipcon); // Create device object
ipcon.connect(host, port); // Connect to brickd
// Don't use device before ipcon is connected
// Switch socket with house code 17 and receiver code 1 on.
// House code 17 is 10001 in binary (least-significant bit first)
// and means that the DIP switches 1 and 5 are on and 2-4 are off.
// Receiver code 1 is 10000 in binary (least-significant bit first)
// and means that the DIP switch A is on and B-E are off.
rs.switchSocketA((short)17, (short)1, BrickletRemoteSwitch.SWITCH_TO_ON);
System.console().readLine("Press key to exit\n");
}
|
diff --git a/src/org/es/butler/logic/impl/AgendaLogic.java b/src/org/es/butler/logic/impl/AgendaLogic.java
index 97bcc35..43aa29b 100644
--- a/src/org/es/butler/logic/impl/AgendaLogic.java
+++ b/src/org/es/butler/logic/impl/AgendaLogic.java
@@ -1,74 +1,74 @@
package org.es.butler.logic.impl;
import android.content.Context;
import android.text.format.DateFormat;
import org.es.api.pojo.AgendaEvent;
import org.es.butler.R;
import org.es.butler.logic.PronunciationLogic;
import java.util.List;
/**
* Created by Cyril Leroux on 24/06/13.
*/
public class AgendaLogic implements PronunciationLogic {
List<AgendaEvent> mEvents;
boolean mToday;
public AgendaLogic(List<AgendaEvent> events, boolean today) {
mEvents = events;
mToday = today;
}
@Override
public String getPronunciation(Context context) {
return getPronunciationEn(mEvents, context);
}
private String getPronunciationEn(final List<AgendaEvent> events, Context context) {
int count = (events == null || events.isEmpty()) ? 0 : events.size();
StringBuilder sb = new StringBuilder();
if (mToday) {
- sb.append(context.getResources().getQuantityString(R.plurals.today_appointments, count, count));
+ sb.append(context.getResources().getQuantityString(R.plurals.today_appointments, count));
} else {
- sb.append(context.getResources().getQuantityString(R.plurals.upcoming_appointments, count, count));
+ sb.append(context.getResources().getQuantityString(R.plurals.upcoming_appointments, count));
}
if (count == 0) {
return sb.toString();
}
sb.append(" ");
for (AgendaEvent event : events) {
// Day of week (if not today)
if (!mToday) {
sb.append(getWeekDay(event.getStartDateMillis()));
sb.append(" ");
}
// Event title
sb.append(event.getTitle());
// Event start on (if not all day)
if (!event.isAllDay()) {
TimeLogic logic = new TimeLogic(event.getStartDateMillis(), false);
sb.append(" at ");
sb.append(logic.getPronunciation(context));
sb.append(" ");
}
}
//+ " Your Jujitsu course is at 8 30 pm.";
//return context.getString(R.plurals.appointment_count, count) + " Your Jujitsu course is at 8 30 pm.";
//return "You have no appointment today.";
return sb.toString();
}
private String getWeekDay(long timeMillis) {
return DateFormat.format("EEEE", timeMillis).toString();
}
}
| false | true | private String getPronunciationEn(final List<AgendaEvent> events, Context context) {
int count = (events == null || events.isEmpty()) ? 0 : events.size();
StringBuilder sb = new StringBuilder();
if (mToday) {
sb.append(context.getResources().getQuantityString(R.plurals.today_appointments, count, count));
} else {
sb.append(context.getResources().getQuantityString(R.plurals.upcoming_appointments, count, count));
}
if (count == 0) {
return sb.toString();
}
sb.append(" ");
for (AgendaEvent event : events) {
// Day of week (if not today)
if (!mToday) {
sb.append(getWeekDay(event.getStartDateMillis()));
sb.append(" ");
}
// Event title
sb.append(event.getTitle());
// Event start on (if not all day)
if (!event.isAllDay()) {
TimeLogic logic = new TimeLogic(event.getStartDateMillis(), false);
sb.append(" at ");
sb.append(logic.getPronunciation(context));
sb.append(" ");
}
}
//+ " Your Jujitsu course is at 8 30 pm.";
//return context.getString(R.plurals.appointment_count, count) + " Your Jujitsu course is at 8 30 pm.";
//return "You have no appointment today.";
return sb.toString();
}
| private String getPronunciationEn(final List<AgendaEvent> events, Context context) {
int count = (events == null || events.isEmpty()) ? 0 : events.size();
StringBuilder sb = new StringBuilder();
if (mToday) {
sb.append(context.getResources().getQuantityString(R.plurals.today_appointments, count));
} else {
sb.append(context.getResources().getQuantityString(R.plurals.upcoming_appointments, count));
}
if (count == 0) {
return sb.toString();
}
sb.append(" ");
for (AgendaEvent event : events) {
// Day of week (if not today)
if (!mToday) {
sb.append(getWeekDay(event.getStartDateMillis()));
sb.append(" ");
}
// Event title
sb.append(event.getTitle());
// Event start on (if not all day)
if (!event.isAllDay()) {
TimeLogic logic = new TimeLogic(event.getStartDateMillis(), false);
sb.append(" at ");
sb.append(logic.getPronunciation(context));
sb.append(" ");
}
}
//+ " Your Jujitsu course is at 8 30 pm.";
//return context.getString(R.plurals.appointment_count, count) + " Your Jujitsu course is at 8 30 pm.";
//return "You have no appointment today.";
return sb.toString();
}
|
diff --git a/src/concurrency/main/Main.java b/src/concurrency/main/Main.java
index d199a75..d894833 100644
--- a/src/concurrency/main/Main.java
+++ b/src/concurrency/main/Main.java
@@ -1,53 +1,53 @@
package concurrency.main;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import concurrency.data.SharedObject;
public class Main {
public static void main(String[] args) {
final SharedObject obj = new SharedObject(0);
final Object synchObj = new Object();
final int NUM_THREADS = 1000;
final int POOL_SIZE = 5;
ExecutorService pool = Executors.newFixedThreadPool(POOL_SIZE);
- final CountDownLatch cdl = new CountDownLatch(NUM_THREADS);
+ final CountDownLatch cdl = new CountDownLatch(POOL_SIZE);
for (int i = 0; i < NUM_THREADS; i++) {
pool.submit(new Runnable() {
@Override
public void run() {
cdl.countDown();
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (synchObj) {
int val = obj.getValue();
val++;
obj.setValue(val);
System.out.println(obj.getValue());
}
}
});
}
try {
pool.shutdown();
- while(pool.awaitTermination(60, TimeUnit.SECONDS)){}
+ while(!pool.awaitTermination(60, TimeUnit.SECONDS)){}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| false | true | public static void main(String[] args) {
final SharedObject obj = new SharedObject(0);
final Object synchObj = new Object();
final int NUM_THREADS = 1000;
final int POOL_SIZE = 5;
ExecutorService pool = Executors.newFixedThreadPool(POOL_SIZE);
final CountDownLatch cdl = new CountDownLatch(NUM_THREADS);
for (int i = 0; i < NUM_THREADS; i++) {
pool.submit(new Runnable() {
@Override
public void run() {
cdl.countDown();
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (synchObj) {
int val = obj.getValue();
val++;
obj.setValue(val);
System.out.println(obj.getValue());
}
}
});
}
try {
pool.shutdown();
while(pool.awaitTermination(60, TimeUnit.SECONDS)){}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
| public static void main(String[] args) {
final SharedObject obj = new SharedObject(0);
final Object synchObj = new Object();
final int NUM_THREADS = 1000;
final int POOL_SIZE = 5;
ExecutorService pool = Executors.newFixedThreadPool(POOL_SIZE);
final CountDownLatch cdl = new CountDownLatch(POOL_SIZE);
for (int i = 0; i < NUM_THREADS; i++) {
pool.submit(new Runnable() {
@Override
public void run() {
cdl.countDown();
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (synchObj) {
int val = obj.getValue();
val++;
obj.setValue(val);
System.out.println(obj.getValue());
}
}
});
}
try {
pool.shutdown();
while(!pool.awaitTermination(60, TimeUnit.SECONDS)){}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
|
diff --git a/src/test/java/org/healthonnet/spellchecker/client/test/JsonParsingTest.java b/src/test/java/org/healthonnet/spellchecker/client/test/JsonParsingTest.java
index ec2fafd..7980070 100644
--- a/src/test/java/org/healthonnet/spellchecker/client/test/JsonParsingTest.java
+++ b/src/test/java/org/healthonnet/spellchecker/client/test/JsonParsingTest.java
@@ -1,63 +1,63 @@
package org.healthonnet.spellchecker.client.test;
import static org.healthonnet.spellchecker.client.SpellcheckDictionary.English;
import java.io.IOException;
import java.util.List;
import org.healthonnet.spellchecker.client.SpellcheckRequester;
import org.healthonnet.spellchecker.client.data.SpellcheckResponse;
import org.healthonnet.spellchecker.client.data.Suggestion;
import org.junit.Assert;
import org.junit.Test;
public class JsonParsingTest {
@Test
public void testSingleWordSuggestion() throws IOException {
SpellcheckResponse spellcheckResponse = SpellcheckRequester.getSpellcheckResponse(English, 1, "alzeimer");
List<Suggestion> suggestions = spellcheckResponse.getSpellcheck().getSuggestions();
Assert.assertEquals(1, suggestions.size());
Assert.assertEquals("alzeimer", suggestions.get(0).getOriginalString());
Assert.assertEquals(1, suggestions.get(0).getSuggestedCorrections().size());
Assert.assertEquals("alzheimer", suggestions.get(0).getSuggestedCorrections().get(0).getWord());
}
@Test
public void testMultipleWordSuggestion() throws IOException {
SpellcheckResponse spellcheckResponse = SpellcheckRequester.getSpellcheckResponse(English, 1, "alzeimer", "diseas");
List<Suggestion> suggestions = spellcheckResponse.getSpellcheck().getSuggestions();
Assert.assertEquals(2, suggestions.size());
Assert.assertEquals("alzeimer", suggestions.get(0).getOriginalString());
Assert.assertEquals(1, suggestions.get(0).getSuggestedCorrections().size());
Assert.assertEquals("alzheimer", suggestions.get(0).getSuggestedCorrections().get(0).getWord());
Assert.assertEquals("diseas", suggestions.get(1).getOriginalString());
Assert.assertEquals(1, suggestions.get(1).getSuggestedCorrections().size());
Assert.assertEquals("disease", suggestions.get(1).getSuggestedCorrections().get(0).getWord());
}
@Test
public void testMultipleSuggestions() throws IOException {
SpellcheckResponse spellcheckResponse = SpellcheckRequester.getSpellcheckResponse(English, 15, "diabetis");
List<Suggestion> suggestions = spellcheckResponse.getSpellcheck().getSuggestions();
Assert.assertEquals(1, suggestions.size());
Assert.assertEquals("diabetis", suggestions.get(0).getOriginalString());
Assert.assertEquals(15, suggestions.get(0).getSuggestedCorrections().size());
// "diabetes" should have the highest score
Assert.assertEquals("diabetes", suggestions.get(0).getSuggestedCorrections().get(0).getWord());
Assert.assertEquals(15, suggestions.get(0).getNumFound());
Assert.assertEquals(0, suggestions.get(0).getStartOffset());
Assert.assertEquals(8, suggestions.get(0).getEndOffset());
- Assert.assertEquals(0, suggestions.get(0).getOrigFreq());
+ Assert.assertTrue(suggestions.get(0).getOrigFreq() >= 0);
}
}
| true | true | public void testMultipleSuggestions() throws IOException {
SpellcheckResponse spellcheckResponse = SpellcheckRequester.getSpellcheckResponse(English, 15, "diabetis");
List<Suggestion> suggestions = spellcheckResponse.getSpellcheck().getSuggestions();
Assert.assertEquals(1, suggestions.size());
Assert.assertEquals("diabetis", suggestions.get(0).getOriginalString());
Assert.assertEquals(15, suggestions.get(0).getSuggestedCorrections().size());
// "diabetes" should have the highest score
Assert.assertEquals("diabetes", suggestions.get(0).getSuggestedCorrections().get(0).getWord());
Assert.assertEquals(15, suggestions.get(0).getNumFound());
Assert.assertEquals(0, suggestions.get(0).getStartOffset());
Assert.assertEquals(8, suggestions.get(0).getEndOffset());
Assert.assertEquals(0, suggestions.get(0).getOrigFreq());
}
| public void testMultipleSuggestions() throws IOException {
SpellcheckResponse spellcheckResponse = SpellcheckRequester.getSpellcheckResponse(English, 15, "diabetis");
List<Suggestion> suggestions = spellcheckResponse.getSpellcheck().getSuggestions();
Assert.assertEquals(1, suggestions.size());
Assert.assertEquals("diabetis", suggestions.get(0).getOriginalString());
Assert.assertEquals(15, suggestions.get(0).getSuggestedCorrections().size());
// "diabetes" should have the highest score
Assert.assertEquals("diabetes", suggestions.get(0).getSuggestedCorrections().get(0).getWord());
Assert.assertEquals(15, suggestions.get(0).getNumFound());
Assert.assertEquals(0, suggestions.get(0).getStartOffset());
Assert.assertEquals(8, suggestions.get(0).getEndOffset());
Assert.assertTrue(suggestions.get(0).getOrigFreq() >= 0);
}
|
diff --git a/core/src/visad/trunk/python/JPythonMethods.java b/core/src/visad/trunk/python/JPythonMethods.java
index c5157fefe..f483dca98 100644
--- a/core/src/visad/trunk/python/JPythonMethods.java
+++ b/core/src/visad/trunk/python/JPythonMethods.java
@@ -1,600 +1,603 @@
//
// JPythonMethods.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 2000 Bill Hibbard, Curtis Rueden, Tom
Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and
Tommy Jasmin.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA
*/
package visad.python;
import java.util.Vector;
import java.awt.event.*;
import java.rmi.RemoteException;
import javax.swing.JFrame;
import java.lang.reflect.InvocationTargetException;
import visad.*;
import visad.math.*;
import visad.matrix.*;
import visad.java3d.DisplayImplJ3D;
import visad.java3d.TwoDDisplayRendererJ3D;
import visad.data.*;
import visad.ss.MappingDialog;
import visad.bom.ImageRendererJ3D;
/**
* A collection of methods for working with VisAD, callable from the
* JPython editor.
*/
public abstract class JPythonMethods {
private static final String ID = JPythonMethods.class.getName();
private static DefaultFamily form = new DefaultFamily(ID);
private static JFrame displayFrame = null;
private static JFrame widgetFrame = null;
/** reads in data from the given location (filename or URL) */
public static DataImpl load(String location) throws VisADException {
return form.open(location);
}
private static DisplayImpl display = null;
private static ScalarMap[] maps = null;
private static MappingDialog dialog = null;
private static Vector data_references = null;
/** displays the given data onscreen */
public static void plot(DataImpl data)
throws VisADException, RemoteException {
plot(data, 1.0, 1.0, 1.0);
}
/** displays the given data onscreen, with the given default color
(red, green and blue values between 0.0 and 1.0), which the user
may override by color mappings */
public static void plot(DataImpl data, double red, double green, double blue)
throws VisADException, RemoteException {
if (data == null) throw new VisADException("Data cannot be null");
if (display == null) {
displayFrame = new JFrame("VisAD Display Plot");
widgetFrame = new JFrame("VisAD Display Widgets");
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
synchronized (displayFrame) {
displayFrame.setVisible(false);
widgetFrame.setVisible(false);
}
}
};
// set up scalar maps
maps = data.getType().guessMaps(true);
// allow user to alter default mappings
dialog = new MappingDialog(null, data, maps, true, true);
dialog.display();
if (dialog.Confirm) maps = dialog.ScalarMaps;
boolean d3d = false;
for (int i=0; i<maps.length; i++) {
if (maps[i].getDisplayScalar().equals(Display.ZAxis) ||
maps[i].getDisplayScalar().equals(Display.Latitude) ||
+ maps[i].getDisplayScalar().equals(Display.Flow1Z) ||
+ maps[i].getDisplayScalar().equals(Display.Flow2Z) ||
+ maps[i].getDisplayScalar().equals(Display.ZAxisOffset) ||
maps[i].getDisplayScalar().equals(Display.Alpha)) d3d = true;
}
display = d3d ? new DisplayImplJ3D(ID) :
new DisplayImplJ3D(ID, new TwoDDisplayRendererJ3D());
for (int i=0; i<maps.length; i++) display.addMap(maps[i]);
GraphicsModeControl gmc = display.getGraphicsModeControl();
gmc.setScaleEnable(true);
// set up widget panel
widgetFrame.addWindowListener(l);
widgetFrame.getContentPane().add(display.getWidgetPanel());
widgetFrame.pack();
widgetFrame.setVisible(true);
// set up display frame
displayFrame.addWindowListener(l);
displayFrame.getContentPane().add(display.getComponent());
displayFrame.pack();
displayFrame.setSize(512, 512);
displayFrame.setVisible(true);
data_references = new Vector();
}
ConstantMap[] cmaps = {new ConstantMap(red, Display.Red),
new ConstantMap(green, Display.Green),
new ConstantMap(blue, Display.Blue)};
DataReferenceImpl ref = new DataReferenceImpl(ID);
data_references.addElement(ref);
ref.setData(data);
MathType type = data.getType();
try {
ImageRendererJ3D.verifyImageRendererUsable(type, maps);
display.addReferences(new ImageRendererJ3D(), ref, cmaps);
}
catch (VisADException exc) {
display.addReference(ref, cmaps);
}
}
// this is just a temporary and dumb hack
/** clear the plot */
public static void clearplot() throws VisADException, RemoteException {
if (display != null) {
displayFrame.setVisible(false);
displayFrame.dispose();
displayFrame = null;
widgetFrame.setVisible(false);
widgetFrame.dispose();
widgetFrame = null;
display.destroy();
display = null;
}
}
/** binary and unary methods from Data.java */
public static Data abs(Data data) throws VisADException, RemoteException {
return data.abs();
}
public static Data acos(Data data) throws VisADException, RemoteException {
return data.acos();
}
public static Data acosDegrees(Data data) throws VisADException, RemoteException {
return data.acosDegrees();
}
public static Data asin(Data data) throws VisADException, RemoteException {
return data.asin();
}
public static Data asinDegrees(Data data) throws VisADException, RemoteException {
return data.asinDegrees();
}
public static Data ceil(Data data) throws VisADException, RemoteException {
return data.ceil();
}
public static Data cos(Data data) throws VisADException, RemoteException {
return data.cos();
}
public static Data cosDegrees(Data data) throws VisADException, RemoteException {
return data.cosDegrees();
}
public static Data exp(Data data) throws VisADException, RemoteException {
return data.exp();
}
public static Data floor(Data data) throws VisADException, RemoteException {
return data.floor();
}
public static Data log(Data data) throws VisADException, RemoteException {
return data.log();
}
public static Data rint(Data data) throws VisADException, RemoteException {
return data.rint();
}
public static Data round(Data data) throws VisADException, RemoteException {
return data.round();
}
public static Data sin(Data data) throws VisADException, RemoteException {
return data.sin();
}
public static Data sinDegrees(Data data) throws VisADException, RemoteException {
return data.sinDegrees();
}
public static Data sqrt(Data data) throws VisADException, RemoteException {
return data.sqrt();
}
public static Data tan(Data data) throws VisADException, RemoteException {
return data.tan();
}
public static Data tanDegrees(Data data) throws VisADException, RemoteException {
return data.tanDegrees();
}
public static Data max(Data data1, Data data2)
throws VisADException, RemoteException {
return data1.max(data2);
}
public static Data min(Data data1, Data data2)
throws VisADException, RemoteException {
return data1.min(data2);
}
public static Data atan2(Data data1, Data data2)
throws VisADException, RemoteException {
return data1.atan2(data2);
}
public static Data atan2Degrees(Data data1, Data data2)
throws VisADException, RemoteException {
return data1.atan2Degrees(data2);
}
public static Data max(Data data1, double data2)
throws VisADException, RemoteException {
return data1.max(new Real(data2));
}
public static Data min(Data data1, double data2)
throws VisADException, RemoteException {
return data1.min(new Real(data2));
}
public static Data atan2(Data data1, double data2)
throws VisADException, RemoteException {
return data1.atan2(new Real(data2));
}
public static Data atan2Degrees(Data data1, double data2)
throws VisADException, RemoteException {
return data1.atan2Degrees(new Real(data2));
}
public static Data max(double data1, Data data2)
throws VisADException, RemoteException {
return new Real(data1).max(data2);
}
public static Data min(double data1, Data data2)
throws VisADException, RemoteException {
return new Real(data1).min(data2);
}
public static Data atan2(double data1, Data data2)
throws VisADException, RemoteException {
return new Real(data1).atan2(data2);
}
public static Data atan2Degrees(double data1, Data data2)
throws VisADException, RemoteException {
return new Real(data1).atan2Degrees(data2);
}
/* end of binary and unary methods from Data.java */
/** 1-D and 2-D forward Fourier transform, uses fft when possible */
public static FlatField fft(Field field)
throws VisADException, RemoteException {
return FFT.fourierTransform(field, true);
}
/** 1-D and 2-D backward Fourier transform, uses fft when possible */
public static FlatField ifft(Field field)
throws VisADException, RemoteException {
return FFT.fourierTransform(field, false);
}
/** multiply matrices using Jama */
public static JamaMatrix matrixMultiply(FlatField data1, FlatField data2)
throws VisADException, RemoteException, IllegalAccessException,
InstantiationException, InvocationTargetException {
JamaMatrix matrix1 = JamaMatrix.convertToMatrix(data1);
JamaMatrix matrix2 = JamaMatrix.convertToMatrix(data2);
return matrix1.times(matrix2);
}
/** solve a linear system using Jama */
public static JamaMatrix solve(FlatField data1, FlatField data2)
throws VisADException, RemoteException, IllegalAccessException,
InstantiationException, InvocationTargetException {
JamaMatrix matrix1 = JamaMatrix.convertToMatrix(data1);
JamaMatrix matrix2 = JamaMatrix.convertToMatrix(data2);
return matrix1.solve(matrix2);
}
/** invert a matrix using Jama */
public static JamaMatrix inverse(FlatField data)
throws VisADException, RemoteException, IllegalAccessException,
InstantiationException, InvocationTargetException {
JamaMatrix matrix = JamaMatrix.convertToMatrix(data);
return matrix.inverse();
}
/** get determinant of a matrix using Jama */
public static double det(FlatField data)
throws VisADException, RemoteException, IllegalAccessException,
InstantiationException, InvocationTargetException {
JamaMatrix matrix = JamaMatrix.convertToMatrix(data);
return matrix.det();
}
/** return Cholesky Decomposition using Jama */
public static JamaCholeskyDecomposition chol(FlatField data)
throws VisADException, RemoteException, IllegalAccessException,
InstantiationException, InvocationTargetException {
JamaMatrix matrix = JamaMatrix.convertToMatrix(data);
return matrix.chol();
}
/** return Eigenvalue Decomposition using Jama */
public static JamaEigenvalueDecomposition eig(FlatField data)
throws VisADException, RemoteException, IllegalAccessException,
InstantiationException, InvocationTargetException {
JamaMatrix matrix = JamaMatrix.convertToMatrix(data);
return matrix.eig();
}
/** return LU Decomposition using Jama */
public static JamaLUDecomposition lu(FlatField data)
throws VisADException, RemoteException, IllegalAccessException,
InstantiationException, InvocationTargetException {
JamaMatrix matrix = JamaMatrix.convertToMatrix(data);
return matrix.lu();
}
/** return QR Decomposition using Jama */
public static JamaQRDecomposition qr(FlatField data)
throws VisADException, RemoteException, IllegalAccessException,
InstantiationException, InvocationTargetException {
JamaMatrix matrix = JamaMatrix.convertToMatrix(data);
return matrix.qr();
}
/** return Singular Value Decomposition using Jama */
public static JamaSingularValueDecomposition svd(FlatField data)
throws VisADException, RemoteException, IllegalAccessException,
InstantiationException, InvocationTargetException {
JamaMatrix matrix = JamaMatrix.convertToMatrix(data);
return matrix.svd();
}
/** return histogram of field, with dimension and bin sampling
defined by set */
public static FlatField hist(Field field, Set set)
throws VisADException, RemoteException {
return Histogram.makeHistogram(field, set);
}
/** return histogram of range values of field selected
by indices in ranges, and with 64 equally spaced bins
in each dimension */
public static FlatField hist(Field field, int[] ranges)
throws VisADException, RemoteException {
if (ranges == null || ranges.length == 0) {
throw new VisADException("bad ranges");
}
int dim = ranges.length;
int[] sizes = new int[dim];
for (int i=0; i<dim; i++) sizes[i] = 64;
return hist(field, ranges, sizes);
}
/** return histogram of range values of field selected
by indices in ranges, and with number of equally spaced
bins defined by sizes */
public static FlatField hist(Field field, int[] ranges, int[] sizes)
throws VisADException, RemoteException {
if (ranges == null || ranges.length == 0) {
throw new VisADException("bad ranges");
}
if (sizes == null || sizes.length != ranges.length) {
throw new VisADException("bad sizes");
}
if (field == null) {
throw new VisADException("bad field");
}
FunctionType ftype = (FunctionType) field.getType();
RealType[] frealComponents = ftype.getRealComponents();
int n = frealComponents.length;
int dim = ranges.length;
RealType[] srealComponents = new RealType[dim];
for (int i=0; i<dim; i++) {
if (0 <= ranges[i] && ranges[i] < n) {
srealComponents[i] = frealComponents[ranges[i]];
}
else {
throw new VisADException("range index out of range " + ranges[i]);
}
}
RealTupleType rtt = new RealTupleType(srealComponents);
double[][] data_ranges = field.computeRanges(srealComponents);
Set set = null;
if (dim == 1) {
set = new Linear1DSet(rtt, data_ranges[0][0], data_ranges[0][1], sizes[0]);
}
else if (dim == 2) {
set = new Linear2DSet(rtt, data_ranges[0][0], data_ranges[0][1], sizes[0],
data_ranges[1][0], data_ranges[1][1], sizes[1]);
}
else if (dim == 3) {
set = new Linear3DSet(rtt, data_ranges[0][0], data_ranges[0][1], sizes[0],
data_ranges[1][0], data_ranges[1][1], sizes[1],
data_ranges[2][0], data_ranges[2][1], sizes[2]);
}
else {
double[] firsts = new double[dim];
double[] lasts = new double[dim];
for (int i=0; i<dim; i++) {
firsts[i] = data_ranges[i][0];
lasts[i] = data_ranges[i][1];
}
set = new LinearNDSet(rtt, firsts, lasts, sizes);
}
return Histogram.makeHistogram(field, set);
}
/** construct a FlatField with given values array */
public static FlatField field(float[] values)
throws VisADException, RemoteException {
return field("value", values);
}
/** construct a FlatField with given range RealType name
and values array */
public static FlatField field(String name, float[] values)
throws VisADException, RemoteException {
if (values == null || values.length == 0) {
throw new VisADException("bad values");
}
RealType domain = RealType.getRealType("domain");
return field(new Integer1DSet(domain, values.length), name, values);
}
/** construct a FlatField with given domain set, range RealType
name and values array */
public static FlatField field(Set set, String name, float[] values)
throws VisADException, RemoteException {
if (values == null) {
throw new VisADException("bad values");
}
if (set == null || set.getLength() < values.length) {
throw new VisADException("bad set " + set);
}
if (name == null) {
throw new VisADException("bad name");
}
MathType domain = ((SetType) set.getType()).getDomain();
if (((RealTupleType) domain).getDimension() == 1) {
domain = ((RealTupleType) domain).getComponent(0);
}
RealType range = RealType.getRealType(name);
FunctionType ftype = new FunctionType(domain, range);
FlatField field = new FlatField(ftype, set);
int len = set.getLength();
boolean copy = true;
if (values.length < len) {
float[] new_values = new float[len];
System.arraycopy(values, 0, new_values, 0, len);
for (int i=values.length; i<len; i++) new_values[i] = Float.NaN;
values = new_values;
copy = false;
}
float[][] field_values = {values};
field.setSamples(field_values, copy);
return field;
}
/** construct a FlatField with given 2-D values array */
public static FlatField field(float[][] values)
throws VisADException, RemoteException {
return field("value", values);
}
/** construct a FlatField with given range RealType name
and 2-D values array */
public static FlatField field(String name, float[][] values)
throws VisADException, RemoteException {
int[] temps = getValuesLengths(values);
int values_len = temps[0];
int min = temps[1];
int max = temps[2];
RealType line = RealType.getRealType("ImageLine");
RealType element = RealType.getRealType("ImageElement");
RealTupleType domain = new RealTupleType(element, line);
return field(new Integer2DSet(domain, max, values_len), name, values);
}
/** construct a FlatField with given domain set, range RealType
name and 2-D values array */
public static FlatField field(Set set, String name, float[][] values)
throws VisADException, RemoteException {
int[] temps = getValuesLengths(values);
int values_len = temps[0];
int min = temps[1];
int max = temps[2];
if (set == null || !(set instanceof GriddedSet) ||
set.getManifoldDimension() != 2) {
throw new VisADException("bad set " + set);
}
int len0 = ((GriddedSet) set).getLength(0);
int len1 = ((GriddedSet) set).getLength(1);
if (len0 < max || len1 < values_len) {
throw new VisADException("bad set length " + len0 + " " + len1);
}
if (name == null) {
throw new VisADException("bad name");
}
MathType domain = ((SetType) set.getType()).getDomain();
if (((RealTupleType) domain).getDimension() == 1) {
domain = ((RealTupleType) domain).getComponent(0);
}
RealType range = RealType.getRealType(name);
FunctionType ftype = new FunctionType(domain, range);
FlatField field = new FlatField(ftype, set);
int len = len0 * len1; // == set.getLength()
float[] new_values = new float[len];
for (int j=0; j<values_len; j++) {
int m = j * len0;
int n = values[j].length;
if (n > 0) System.arraycopy(values[j], 0, new_values, m, n);
for (int i=(m+n); i<(m+len0); i++) new_values[i] = Float.NaN;
}
for (int j=values_len; j<len1; j++) {
int m = j * len0;
for (int i=m; i<(m+len0); i++) new_values[i] = Float.NaN;
}
float[][] field_values = {new_values};
field.setSamples(field_values, false);
return field;
}
private static int[] getValuesLengths(float[][] values)
throws VisADException {
if (values == null) {
throw new VisADException("bad values");
}
int values_len = values.length;
int min = Integer.MAX_VALUE;
int max = 0;
for (int j=0; j<values_len; j++) {
if (values[j] == null) {
throw new VisADException("bad values");
}
int n = values[j].length;
if (n > max) max = n;
if (n < min) min = n;
}
if (max < min) {
min = 0;
}
return new int[] {values_len, min, max};
}
/** NOT DONE */
public static Set linear(MathType type, double first, double last, int length)
throws VisADException, RemoteException {
return null;
}
}
| true | true | public static void plot(DataImpl data, double red, double green, double blue)
throws VisADException, RemoteException {
if (data == null) throw new VisADException("Data cannot be null");
if (display == null) {
displayFrame = new JFrame("VisAD Display Plot");
widgetFrame = new JFrame("VisAD Display Widgets");
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
synchronized (displayFrame) {
displayFrame.setVisible(false);
widgetFrame.setVisible(false);
}
}
};
// set up scalar maps
maps = data.getType().guessMaps(true);
// allow user to alter default mappings
dialog = new MappingDialog(null, data, maps, true, true);
dialog.display();
if (dialog.Confirm) maps = dialog.ScalarMaps;
boolean d3d = false;
for (int i=0; i<maps.length; i++) {
if (maps[i].getDisplayScalar().equals(Display.ZAxis) ||
maps[i].getDisplayScalar().equals(Display.Latitude) ||
maps[i].getDisplayScalar().equals(Display.Alpha)) d3d = true;
}
display = d3d ? new DisplayImplJ3D(ID) :
new DisplayImplJ3D(ID, new TwoDDisplayRendererJ3D());
for (int i=0; i<maps.length; i++) display.addMap(maps[i]);
GraphicsModeControl gmc = display.getGraphicsModeControl();
gmc.setScaleEnable(true);
// set up widget panel
widgetFrame.addWindowListener(l);
widgetFrame.getContentPane().add(display.getWidgetPanel());
widgetFrame.pack();
widgetFrame.setVisible(true);
// set up display frame
displayFrame.addWindowListener(l);
displayFrame.getContentPane().add(display.getComponent());
displayFrame.pack();
displayFrame.setSize(512, 512);
displayFrame.setVisible(true);
data_references = new Vector();
}
ConstantMap[] cmaps = {new ConstantMap(red, Display.Red),
new ConstantMap(green, Display.Green),
new ConstantMap(blue, Display.Blue)};
DataReferenceImpl ref = new DataReferenceImpl(ID);
data_references.addElement(ref);
ref.setData(data);
MathType type = data.getType();
try {
ImageRendererJ3D.verifyImageRendererUsable(type, maps);
display.addReferences(new ImageRendererJ3D(), ref, cmaps);
}
catch (VisADException exc) {
display.addReference(ref, cmaps);
}
}
| public static void plot(DataImpl data, double red, double green, double blue)
throws VisADException, RemoteException {
if (data == null) throw new VisADException("Data cannot be null");
if (display == null) {
displayFrame = new JFrame("VisAD Display Plot");
widgetFrame = new JFrame("VisAD Display Widgets");
WindowListener l = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
synchronized (displayFrame) {
displayFrame.setVisible(false);
widgetFrame.setVisible(false);
}
}
};
// set up scalar maps
maps = data.getType().guessMaps(true);
// allow user to alter default mappings
dialog = new MappingDialog(null, data, maps, true, true);
dialog.display();
if (dialog.Confirm) maps = dialog.ScalarMaps;
boolean d3d = false;
for (int i=0; i<maps.length; i++) {
if (maps[i].getDisplayScalar().equals(Display.ZAxis) ||
maps[i].getDisplayScalar().equals(Display.Latitude) ||
maps[i].getDisplayScalar().equals(Display.Flow1Z) ||
maps[i].getDisplayScalar().equals(Display.Flow2Z) ||
maps[i].getDisplayScalar().equals(Display.ZAxisOffset) ||
maps[i].getDisplayScalar().equals(Display.Alpha)) d3d = true;
}
display = d3d ? new DisplayImplJ3D(ID) :
new DisplayImplJ3D(ID, new TwoDDisplayRendererJ3D());
for (int i=0; i<maps.length; i++) display.addMap(maps[i]);
GraphicsModeControl gmc = display.getGraphicsModeControl();
gmc.setScaleEnable(true);
// set up widget panel
widgetFrame.addWindowListener(l);
widgetFrame.getContentPane().add(display.getWidgetPanel());
widgetFrame.pack();
widgetFrame.setVisible(true);
// set up display frame
displayFrame.addWindowListener(l);
displayFrame.getContentPane().add(display.getComponent());
displayFrame.pack();
displayFrame.setSize(512, 512);
displayFrame.setVisible(true);
data_references = new Vector();
}
ConstantMap[] cmaps = {new ConstantMap(red, Display.Red),
new ConstantMap(green, Display.Green),
new ConstantMap(blue, Display.Blue)};
DataReferenceImpl ref = new DataReferenceImpl(ID);
data_references.addElement(ref);
ref.setData(data);
MathType type = data.getType();
try {
ImageRendererJ3D.verifyImageRendererUsable(type, maps);
display.addReferences(new ImageRendererJ3D(), ref, cmaps);
}
catch (VisADException exc) {
display.addReference(ref, cmaps);
}
}
|
diff --git a/user/src/com/google/gwt/user/client/impl/WindowImpl.java b/user/src/com/google/gwt/user/client/impl/WindowImpl.java
index 3d3339db1..61efc5a8b 100644
--- a/user/src/com/google/gwt/user/client/impl/WindowImpl.java
+++ b/user/src/com/google/gwt/user/client/impl/WindowImpl.java
@@ -1,43 +1,43 @@
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.user.client.impl;
/**
* Native implementation associated with
* {@link com.google.gwt.user.client.Window}.
*/
public class WindowImpl {
public native void enableScrolling(boolean enable) /*-{
@com.google.gwt.user.client.impl.DocumentRootImpl::documentRoot.style.overflow =
- enable ? "auto" : "hidden";
+ enable ? "" : "hidden";
}-*/;
public native int getClientHeight() /*-{
return @com.google.gwt.user.client.impl.DocumentRootImpl::documentRoot.clientHeight;
}-*/;
public native int getClientWidth() /*-{
return @com.google.gwt.user.client.impl.DocumentRootImpl::documentRoot.clientWidth;
}-*/;
public native int getScrollLeft() /*-{
return @com.google.gwt.user.client.impl.DocumentRootImpl::documentRoot.scrollLeft;
}-*/;
public native int getScrollTop() /*-{
return @com.google.gwt.user.client.impl.DocumentRootImpl::documentRoot.scrollTop;
}-*/;
}
| true | true | public native void enableScrolling(boolean enable) /*-{
@com.google.gwt.user.client.impl.DocumentRootImpl::documentRoot.style.overflow =
enable ? "auto" : "hidden";
}-*/;
| public native void enableScrolling(boolean enable) /*-{
@com.google.gwt.user.client.impl.DocumentRootImpl::documentRoot.style.overflow =
enable ? "" : "hidden";
}-*/;
|
diff --git a/src/main/java/org/vivoweb/ingest/score/Score.java b/src/main/java/org/vivoweb/ingest/score/Score.java
index 6214e70d..486dd31a 100644
--- a/src/main/java/org/vivoweb/ingest/score/Score.java
+++ b/src/main/java/org/vivoweb/ingest/score/Score.java
@@ -1,613 +1,612 @@
/*******************************************************************************
* Copyright (c) 2010 Christopher Haines, Dale Scheppler, Nicholas Skaggs, Stephen V. Williams.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the new BSD license
* which accompanies this distribution, and is available at
* http://www.opensource.org/licenses/bsd-license.html
*
* Contributors:
* Christopher Haines, Dale Scheppler, Nicholas Skaggs, Stephen V. Williams - initial API and implementation
* Christopher Barnes, Narayan Raum - scoring ideas and algorithim
* Yang Li - pairwise scoring algorithm
* Christopher Barnes - regex scoring algorithim
******************************************************************************/
package org.vivoweb.ingest.score;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.vivoweb.ingest.util.args.ArgDef;
import org.vivoweb.ingest.util.args.ArgList;
import org.vivoweb.ingest.util.args.ArgParser;
import org.vivoweb.ingest.util.repo.JenaConnect;
import org.vivoweb.ingest.util.repo.Record;
import org.vivoweb.ingest.util.repo.RecordHandler;
import org.xml.sax.SAXException;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.ResourceFactory;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;
/***
*
* VIVO Score
* @author Nicholas Skaggs [email protected]
*/
public class Score {
/**
* Log4J Logger
*/
private static Log log = LogFactory.getLog(Score.class);
/**
* Model for VIVO instance
*/
private Model vivo;
/**
* Model where input is stored
*/
private Model scoreInput;
/**
* Model where output is stored
*/
private Model scoreOutput;
/**
* Main method
* @param args command line arguments
*/
public static void main(String... args) {
log.info("Scoring: Start");
try {
ArgList opts = new ArgList(getParser(), args);
//Get optional inputs / set defaults
//Check for config files, before parsing name options
String workingModel = opts.get("T");
if (workingModel == null) workingModel = opts.get("t");
String outputModel = opts.get("O");
if (outputModel == null) outputModel = opts.get("o");
boolean allowNonEmptyWorkingModel = opts.has("n");
boolean retainWorkingModel = opts.has("k");
- int minChars = Integer.parseInt(opts.get("a"));
List<String> exactMatchArg = opts.getAll("e");
List<String> pairwiseArg = opts.getAll("p");
List<String> regexArg = opts.getAll("r");
int processCount = 0;
try {
log.info("Loading configuration and models");
RecordHandler rh = RecordHandler.parseConfig(opts.get("i"));
//Connect to vivo
JenaConnect jenaVivoDB = JenaConnect.parseConfig(opts.get("V"));
//Create working model
JenaConnect jenaTempDB = new JenaConnect(jenaVivoDB,workingModel);
//Create output model
JenaConnect jenaOutputDB = new JenaConnect(jenaVivoDB,outputModel);
//Load up rdf data from translate into temp model
Model jenaInputDB = jenaTempDB.getJenaModel();
if (!jenaInputDB.isEmpty() && !allowNonEmptyWorkingModel) {
log.warn("Working model was not empty! -- emptying model before execution");
jenaInputDB.removeAll();
}
//Read in records that need processing
for (Record r: rh) {
if (r.needsProcessed(Score.class) || opts.has("f")) {
log.trace("Record " + r.getID() + " added to incoming processing model");
jenaInputDB.read(new ByteArrayInputStream(r.getData().getBytes()), null);
r.setProcessed(Score.class);
processCount += 1;
}
}
//Speed Hack -- if no records to process, end
if (processCount != 0) {
//Init
Score scoring = new Score(jenaVivoDB.getJenaModel(), jenaInputDB, jenaOutputDB.getJenaModel());
//authorname matching
if (opts.has("a")) {
- scoring.authorNameMatch(minChars);
+ scoring.authorNameMatch(Integer.parseInt(opts.get("a")));
}
//Call each exactMatch
for (String attribute : exactMatchArg) {
scoring.exactMatch(attribute);
}
//Call each pairwise
for (String attribute : pairwiseArg) {
scoring.pairwise(attribute);
}
//Call each regex
for (String regex : regexArg) {
scoring.regex(regex);
}
//Empty working model
if (!retainWorkingModel) scoring.scoreInput.removeAll();
//Close and done
scoring.scoreInput.close();
scoring.scoreOutput.close();
scoring.vivo.close();
} else {
//nothing to do but end
}
} catch(ParserConfigurationException e) {
log.fatal(e.getMessage(),e);
} catch(SAXException e) {
log.fatal(e.getMessage(),e);
} catch(IOException e) {
log.fatal(e.getMessage(),e);
}
} catch(IllegalArgumentException e) {
System.out.println(getParser().getUsage());
} catch(Exception e) {
log.fatal(e.getMessage(),e);
}
log.info("Scoring: End");
}
/**
* Get the OptionParser
* @return the OptionParser
*/
private static ArgParser getParser() {
ArgParser parser = new ArgParser("Score");
parser.addArgument(new ArgDef().setShortOption('i').setLongOpt("rdfRecordHandler").setDescription("rdfRecordHandler config filename").withParameter(true, "CONFIG_FILE").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('V').setLongOpt("vivoJenaConfig").setDescription("vivoJenaConfig config filename").withParameter(true, "CONFIG_FILE").setRequired(true));
//TODO Nicholas: Implement individual RDF input
//parser.addArgument(new ArgDef().setShortOption('f').setLongOpt("rdfFilename").setDescription("RDF Filename").withParameter(true, "CONFIG_FILE"));
parser.addArgument(new ArgDef().setShortOption('T').setLongOpt("tempModelConfig").setDescription("tempModelConfig config filename").withParameter(true, "CONFIG_FILE"));
parser.addArgument(new ArgDef().setShortOption('O').setLongOpt("outputModelConfig").setDescription("outputModelConfig config filename").withParameter(true, "CONFIG_FILE"));
parser.addArgument(new ArgDef().setShortOption('e').setLongOpt("exactMatch").setDescription("perform an exact match scoring").withParameters(true, "RDF_PREDICATE"));
parser.addArgument(new ArgDef().setShortOption('p').setLongOpt("pairWise").setDescription("perform a pairwise scoring").withParameters(true, "RDF_PREDICATE"));
parser.addArgument(new ArgDef().setShortOption('a').setLongOpt("authorName").setDescription("perform a author name scoring").withParameter(true, "MIN_CHARS"));
parser.addArgument(new ArgDef().setShortOption('r').setLongOpt("regex").setDescription("perform a regular expression scoring").withParameters(true, "REGEX"));
parser.addArgument(new ArgDef().setShortOption('t').setLongOpt("tempModel").setDescription("temporary working model name").withParameter(true, "MODEL_NAME").setDefaultValue("tempModel"));
parser.addArgument(new ArgDef().setShortOption('o').setLongOpt("outputModel").setDescription("output model name").withParameter(true, "MODEL_NAME").setDefaultValue("staging"));
parser.addArgument(new ArgDef().setShortOption('f').setLongOpt("force-process").setDescription("If set, this will reprocess all RDF -- even if it's been processed before"));
parser.addArgument(new ArgDef().setShortOption('n').setLongOpt("allow-non-empty-working-model").setDescription("If set, this will not clear the working model before scoring begins"));
parser.addArgument(new ArgDef().setShortOption('k').setLongOpt("keep-working-model").setDescription("If set, this will not clear the working model after scoring is complete"));
return parser;
}
/**
* Constructor
* @param jenaVivo model containing vivo statements
* @param jenaScoreInput model containing statements to be scored
* @param jenaScoreOutput output model
*/
public Score(Model jenaVivo, Model jenaScoreInput, Model jenaScoreOutput) {
this.vivo = jenaVivo;
this.scoreInput = jenaScoreInput;
this.scoreOutput = jenaScoreOutput;
}
/**
* Executes a sparql query against a JENA model and returns a result set
* @param model a model containing statements
* @param queryString the query to execute against the model
* @return queryExec the executed query result set
*/
private static ResultSet executeQuery(Model model, String queryString) {
Query query = QueryFactory.create(queryString);
QueryExecution queryExec = QueryExecutionFactory.create(query, model);
return queryExec.execSelect();
}
/**
* Commits node to a matched model
* @param result a model containing vivo statements
* @param authorNode the node of the author
* @param paperResource the paper of the resource
* @param matchNode the node to match
* @param paperNode the node of the paper
*/
private static void commitResultNode(Model result, RDFNode authorNode, Resource paperResource, RDFNode matchNode, RDFNode paperNode) {
log.info("Found " + matchNode.toString() + " for person " + authorNode.toString());
log.info("Adding paper " + paperNode.toString());
result.add(recursiveSanitizeBuild(paperResource,null));
replaceResource(authorNode,paperNode, result);
//take results and store in matched model
result.commit();
}
/**
* Commits resultset to a matched model
* @param result a model containing vivo statements
* @param storeResult the result to be stored
* @param paperResource the paper of the resource
* @param matchNode the node to match
* @param paperNode the node of the paper
*/
private static void commitResultSet(Model result, ResultSet storeResult, Resource paperResource, RDFNode matchNode, RDFNode paperNode) {
RDFNode authorNode;
QuerySolution vivoSolution;
//loop thru resultset
while (storeResult.hasNext()) {
vivoSolution = storeResult.next();
//Grab person URI
authorNode = vivoSolution.get("x");
log.info("Found " + matchNode.toString() + " for person " + authorNode.toString());
log.info("Adding paper " + paperNode.toString());
result.add(recursiveSanitizeBuild(paperResource,null));
replaceResource(authorNode,paperNode, result);
//take results and store in matched model
result.commit();
}
}
/**
* Traverses paperNode and adds to toReplace model
* @param mainNode primary node
* @param paperNode node of paper
* @param toReplace model to replace
*/
private static void replaceResource(RDFNode mainNode, RDFNode paperNode, Model toReplace){
Resource authorship;
Property linkedAuthorOf = ResourceFactory.createProperty("http://vivoweb.org/ontology/core#linkedAuthor");
Property authorshipForPerson = ResourceFactory.createProperty("http://vivoweb.org/ontology/core#authorInAuthorship");
Property authorshipForPaper = ResourceFactory.createProperty("http://vivoweb.org/ontology/core#informationResourceInAuthorship");
Property paperOf = ResourceFactory.createProperty("http://vivoweb.org/ontology/core#linkedInformationResource");
Property rankOf = ResourceFactory.createProperty("http://vivoweb.org/ontology/core#authorRank");
Resource flag1 = ResourceFactory.createResource("http://vitro.mannlib.cornell.edu/ns/vitro/0.7#Flag1Value1Thing");
Resource authorshipClass = ResourceFactory.createResource("http://vivoweb.org/ontology/core#Authorship");
Property rdfType = ResourceFactory.createProperty("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
Property rdfLabel = ResourceFactory.createProperty("http://www.w3.org/2000/01/rdf-schema#label");
int authorRank = 1;
log.info("Link paper " + paperNode.toString() + " to person " + mainNode.toString() + " in VIVO");
authorship = ResourceFactory.createResource(paperNode.toString() + "/vivoAuthorship/l1");
//string that finds the last name of the person in VIVO
Statement authorLName = ((Resource)mainNode).getProperty(ResourceFactory.createProperty("http://xmlns.com/foaf/0.1/lastName"));
String authorQuery = "PREFIX core: <http://vivoweb.org/ontology/core#> " +
"PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
"SELECT ?badNode " +
"WHERE {?badNode foaf:lastName \"" + authorLName.getObject().toString() + "\" . " +
"?badNode core:authorInAuthorship ?authorship . " +
"?authorship core:linkedInformationResource <" + paperNode.toString() + "> }";
log.debug(authorQuery);
ResultSet killList = executeQuery(toReplace,authorQuery);
while(killList.hasNext()) {
QuerySolution killSolution = killList.next();
//Grab person URI
Resource removeAuthor = killSolution.getResource("badNode");
//query the paper for the first author node (assumption that affiliation matches first author)
log.debug("Delete Resource " + removeAuthor.toString());
//return a statement iterator with all the statements for the Author that matches, then remove those statements
//model.remove is broken so we are using statement.remove
StmtIterator deleteStmts = toReplace.listStatements(null, null, removeAuthor);
while (deleteStmts.hasNext()) {
Statement dStmt = deleteStmts.next();
log.debug("Delete Statement " + dStmt.toString());
if (!dStmt.getSubject().equals(removeAuthor)) {
Statement authorRankStmt = dStmt.getSubject().getProperty(rankOf);
authorRank = authorRankStmt.getObject().asLiteral().getInt();
StmtIterator authorshipStmts = dStmt.getSubject().listProperties();
while (authorshipStmts.hasNext()) {
log.debug("Delete Statement " + authorshipStmts.next().toString());
}
dStmt.getSubject().removeProperties();
StmtIterator deleteAuthorshipStmts = toReplace.listStatements(null, null, dStmt.getSubject());
while (deleteAuthorshipStmts.hasNext()) {
Statement dASStmt = deleteAuthorshipStmts.next();
log.debug("Delete Statement " + dASStmt.toString());
dASStmt.remove();
}
}
}
StmtIterator authorStmts = removeAuthor.listProperties();
while (authorStmts.hasNext()) {
log.debug("Delete Statement " + authorStmts.next().toString());
}
removeAuthor.removeProperties();
}
toReplace.add(authorship,linkedAuthorOf,mainNode);
log.trace("Link Statement [" + authorship.toString() + ", " + linkedAuthorOf.toString() + ", " + mainNode.toString() + "]");
toReplace.add((Resource)mainNode,authorshipForPerson,authorship);
log.trace("Link Statement [" + mainNode.toString() + ", " + authorshipForPerson.toString() + ", " + authorship.toString() + "]");
toReplace.add(authorship,paperOf,paperNode);
log.trace("Link Statement [" + authorship.toString() + ", " + paperOf.toString() + ", " + paperNode.toString() + "]");
toReplace.add((Resource)paperNode,authorshipForPaper,authorship);
log.trace("Link Statement [" + paperNode.toString() + ", " + authorshipForPaper.toString() + ", " + authorship.toString() + "]");
toReplace.add(authorship,rdfType,flag1);
log.trace("Link Statement [" + authorship.toString() + ", " + rdfType.toString() + ", " + flag1.toString() + "]");
toReplace.add(authorship,rdfType,authorshipClass);
log.trace("Link Statement [" + authorship.toString() + ", " + rdfType.toString() + ", " + authorshipClass.toString() + "]");
toReplace.add(authorship,rdfLabel,"Authorship for Paper");
log.trace("Link Statement [" + authorship.toString() + ", " + rdfLabel.toString() + ", " + "Authorship for Paper]");
toReplace.addLiteral(authorship,rankOf,authorRank);
log.trace("Link Statement [" + authorship.toString() + ", " + rankOf.toString() + ", " + String.valueOf(authorRank) + "]");
toReplace.commit();
}
/**
* Traverses paperNode and adds to toReplace model
* @param mainRes the main resource
* @param linkRes the resource to link it to
* @return the model containing the sanitized info so far
*/
private static Model recursiveSanitizeBuild(Resource mainRes, Resource linkRes){
Model returnModel = ModelFactory.createDefaultModel();
Statement stmt;
StmtIterator mainStmts = mainRes.listProperties();
while (mainStmts.hasNext()) {
stmt = mainStmts.nextStatement();
log.trace("Statement " + stmt.toString());
//Don't add any scoring statements
if (!stmt.getPredicate().toString().contains("/score")) {
returnModel.add(stmt);
if ((stmt.getObject().isResource() && !((Resource)stmt.getObject()).equals(linkRes)) && !((Resource)stmt.getObject()).equals(mainRes)) {
returnModel.add(recursiveSanitizeBuild((Resource)stmt.getObject(), mainRes));
}
if (!stmt.getSubject().equals(linkRes) && !stmt.getSubject().equals(mainRes)) {
returnModel.add(recursiveSanitizeBuild(stmt.getSubject(), mainRes));
}
}
}
return returnModel;
}
/**
* Executes a pair scoring method, utilizing the matchAttribute. This attribute is expected to
* return 2 to n results from the given query. This "pair" will then be utilized as a matching scheme
* to construct a sub dataset. This dataset can be scored and stored as a match
* @param attribute an attribute to perform the matching query
*/
public void pairwise(String attribute) {
//iterate thru scoringInput pairs against matched pairs
//TODO Nicholas: finish implementation
//if pairs match, store publication to matched author in Model
//Create pairs list from input
log.info("Executing pairWise for " + attribute);
log.warn("Pairwise is not complete");
//Log extra info message if none found
//Create pairs list from vivo
//Log extra info message if none found
//look for exact match in vivo
//create pairs of *attribute* from matched
}
/**
* Executes a regex scoring method
* @param regex string containing regular expression
*/
private void regex(String regex) {
//TODO Chris: finish implementation
log.info("Executing " + regex + " regular expression");
log.warn("Regex is not complete");
}
/**`
* Executes an author name matching algorithm for author disambiguation
* @param minChars minimum number of chars to require for first name portion of match
*/
public void authorNameMatch(int minChars) {
String queryString;
Resource paperResource;
RDFNode lastNameNode;
RDFNode foreNameNode;
RDFNode paperNode;
RDFNode authorNode = null;
RDFNode matchNode = null;
RDFNode loopNode;
ResultSet vivoResult;
QuerySolution scoreSolution;
QuerySolution vivoSolution;
ResultSet scoreInputResult;
String scoreMatch;
ArrayList<QuerySolution> matchNodes = new ArrayList<QuerySolution>();
int loop;
String matchQuery = "PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
"PREFIX score: <http://vivoweb.org/ontology/score#> " +
"SELECT ?x ?lastName ?foreName " +
"WHERE { ?x foaf:lastName ?lastName . ?x score:foreName ?foreName}";
//Exact Match
log.info("Executing authorNameMatch");
log.debug(matchQuery);
scoreInputResult = executeQuery(this.scoreInput, matchQuery);
//Log extra info message if none found
if (!scoreInputResult.hasNext()) {
log.info("No author names found in input");
} else {
log.info("Looping thru matching authors from input");
}
//look for exact match in vivo
while (scoreInputResult.hasNext()) {
scoreSolution = scoreInputResult.next();
lastNameNode = scoreSolution.get("lastName");
foreNameNode = scoreSolution.get("foreName");
paperNode = scoreSolution.get("x");
paperResource = scoreSolution.getResource("x");
matchNodes.clear();
matchNode = null;
authorNode = null;
log.info("Checking for " + lastNameNode.toString() + ", " + foreNameNode.toString() + " from " + paperNode.toString() + " in VIVO");
scoreMatch = lastNameNode.toString();
//Select all matching authors from vivo store
queryString = "PREFIX foaf: <http://xmlns.com/foaf/0.1/> " +
"SELECT ?x ?firstName " +
"WHERE { ?x foaf:lastName" + " \"" + scoreMatch + "\" . ?x foaf:firstName ?firstName}";
log.debug(queryString);
vivoResult = executeQuery(this.vivo, queryString);
//Loop thru results and only keep if the last name, and first initial match
while (vivoResult.hasNext()) {
vivoSolution = vivoResult.next();
log.trace(vivoSolution.toString());
loopNode = vivoSolution.get("firstName");
if (loopNode != null && foreNameNode != null) {
log.trace("Checking " + loopNode);
if (foreNameNode.toString().substring(0, 1).equals(loopNode.toString().substring(0, 1))) {
matchNodes.add(vivoSolution);
} else {
//do nothing
}
}
}
//Did we find a keeper? if so, store if meets threshold
//if more than 1 person find, keep the highest "best" match
Iterator<QuerySolution> matches = matchNodes.iterator();
while (matches.hasNext()) {
vivoSolution = matches.next();
loopNode = vivoSolution.get("firstName");
loop = 0;
while (loopNode.toString().regionMatches(true, 0, foreNameNode.toString(), 0, loop)) {
loop++;
}
loop--;
if (loop < minChars) {
log.trace(loopNode.toString() + " only matched " + loop + " of " + foreNameNode.toString().length() + ". Minimum needed to match is " + minChars);
} else {
//if loopNode matches more of foreNameNode, it's the new best match
//TODO Nicholas: Fix the preference for the first "best" match
if (matchNode == null || !matchNode.toString().regionMatches(true, 0, foreNameNode.toString(), 0, loop)) {
log.trace("Setting " + loopNode.toString() + " as best match, matched " + loop + " of " + foreNameNode.toString().length());
matchNode = loopNode;
authorNode = vivoSolution.get("x");
}
}
}
if (matchNode != null && authorNode != null) {
log.trace("Keeping " + matchNode.toString());
commitResultNode(this.scoreOutput,authorNode,paperResource,matchNode,paperNode);
}
}
}
/**
* Executes an exact matching algorithm for author disambiguation
* @param attribute an attribute to perform the exact match
*/
public void exactMatch(String attribute) {
String scoreMatch;
String queryString;
Resource paperResource;
RDFNode matchNode;
RDFNode paperNode;
ResultSet vivoResult;
QuerySolution scoreSolution;
ResultSet scoreInputResult;
String matchQuery = "PREFIX score: <http://vivoweb.org/ontology/score#> " +
"SELECT ?x ?" + attribute + " " +
"WHERE { ?x score:" + attribute + " ?" + attribute + "}";
String coreAttribute = "core:" + attribute;
//Exact Match
log.info("Executing exactMatch for " + attribute);
log.debug(matchQuery);
scoreInputResult = executeQuery(this.scoreInput, matchQuery);
//Log extra info message if none found
if (!scoreInputResult.hasNext()) {
log.info("No matches found for " + attribute + " in input");
} else {
log.info("Looping thru matching " + attribute + " from input");
}
//look for exact match in vivo
while (scoreInputResult.hasNext()) {
scoreSolution = scoreInputResult.next();
matchNode = scoreSolution.get(attribute);
paperNode = scoreSolution.get("x");
paperResource = scoreSolution.getResource("x");
scoreMatch = matchNode.toString();
log.info("Checking for " + scoreMatch + " from " + paperNode.toString() + " in VIVO");
//Select all matching attributes from vivo store
queryString =
"PREFIX core: <http://vivoweb.org/ontology/core#> " +
"SELECT ?x " +
"WHERE { ?x " + coreAttribute + " \"" + scoreMatch + "\" }";
log.debug(queryString);
vivoResult = executeQuery(this.vivo, queryString);
commitResultSet(this.scoreOutput,vivoResult,paperResource,matchNode,paperNode);
}
}
}
| false | true | public static void main(String... args) {
log.info("Scoring: Start");
try {
ArgList opts = new ArgList(getParser(), args);
//Get optional inputs / set defaults
//Check for config files, before parsing name options
String workingModel = opts.get("T");
if (workingModel == null) workingModel = opts.get("t");
String outputModel = opts.get("O");
if (outputModel == null) outputModel = opts.get("o");
boolean allowNonEmptyWorkingModel = opts.has("n");
boolean retainWorkingModel = opts.has("k");
int minChars = Integer.parseInt(opts.get("a"));
List<String> exactMatchArg = opts.getAll("e");
List<String> pairwiseArg = opts.getAll("p");
List<String> regexArg = opts.getAll("r");
int processCount = 0;
try {
log.info("Loading configuration and models");
RecordHandler rh = RecordHandler.parseConfig(opts.get("i"));
//Connect to vivo
JenaConnect jenaVivoDB = JenaConnect.parseConfig(opts.get("V"));
//Create working model
JenaConnect jenaTempDB = new JenaConnect(jenaVivoDB,workingModel);
//Create output model
JenaConnect jenaOutputDB = new JenaConnect(jenaVivoDB,outputModel);
//Load up rdf data from translate into temp model
Model jenaInputDB = jenaTempDB.getJenaModel();
if (!jenaInputDB.isEmpty() && !allowNonEmptyWorkingModel) {
log.warn("Working model was not empty! -- emptying model before execution");
jenaInputDB.removeAll();
}
//Read in records that need processing
for (Record r: rh) {
if (r.needsProcessed(Score.class) || opts.has("f")) {
log.trace("Record " + r.getID() + " added to incoming processing model");
jenaInputDB.read(new ByteArrayInputStream(r.getData().getBytes()), null);
r.setProcessed(Score.class);
processCount += 1;
}
}
//Speed Hack -- if no records to process, end
if (processCount != 0) {
//Init
Score scoring = new Score(jenaVivoDB.getJenaModel(), jenaInputDB, jenaOutputDB.getJenaModel());
//authorname matching
if (opts.has("a")) {
scoring.authorNameMatch(minChars);
}
//Call each exactMatch
for (String attribute : exactMatchArg) {
scoring.exactMatch(attribute);
}
//Call each pairwise
for (String attribute : pairwiseArg) {
scoring.pairwise(attribute);
}
//Call each regex
for (String regex : regexArg) {
scoring.regex(regex);
}
//Empty working model
if (!retainWorkingModel) scoring.scoreInput.removeAll();
//Close and done
scoring.scoreInput.close();
scoring.scoreOutput.close();
scoring.vivo.close();
} else {
//nothing to do but end
}
} catch(ParserConfigurationException e) {
log.fatal(e.getMessage(),e);
} catch(SAXException e) {
log.fatal(e.getMessage(),e);
} catch(IOException e) {
log.fatal(e.getMessage(),e);
}
} catch(IllegalArgumentException e) {
System.out.println(getParser().getUsage());
} catch(Exception e) {
log.fatal(e.getMessage(),e);
}
log.info("Scoring: End");
}
| public static void main(String... args) {
log.info("Scoring: Start");
try {
ArgList opts = new ArgList(getParser(), args);
//Get optional inputs / set defaults
//Check for config files, before parsing name options
String workingModel = opts.get("T");
if (workingModel == null) workingModel = opts.get("t");
String outputModel = opts.get("O");
if (outputModel == null) outputModel = opts.get("o");
boolean allowNonEmptyWorkingModel = opts.has("n");
boolean retainWorkingModel = opts.has("k");
List<String> exactMatchArg = opts.getAll("e");
List<String> pairwiseArg = opts.getAll("p");
List<String> regexArg = opts.getAll("r");
int processCount = 0;
try {
log.info("Loading configuration and models");
RecordHandler rh = RecordHandler.parseConfig(opts.get("i"));
//Connect to vivo
JenaConnect jenaVivoDB = JenaConnect.parseConfig(opts.get("V"));
//Create working model
JenaConnect jenaTempDB = new JenaConnect(jenaVivoDB,workingModel);
//Create output model
JenaConnect jenaOutputDB = new JenaConnect(jenaVivoDB,outputModel);
//Load up rdf data from translate into temp model
Model jenaInputDB = jenaTempDB.getJenaModel();
if (!jenaInputDB.isEmpty() && !allowNonEmptyWorkingModel) {
log.warn("Working model was not empty! -- emptying model before execution");
jenaInputDB.removeAll();
}
//Read in records that need processing
for (Record r: rh) {
if (r.needsProcessed(Score.class) || opts.has("f")) {
log.trace("Record " + r.getID() + " added to incoming processing model");
jenaInputDB.read(new ByteArrayInputStream(r.getData().getBytes()), null);
r.setProcessed(Score.class);
processCount += 1;
}
}
//Speed Hack -- if no records to process, end
if (processCount != 0) {
//Init
Score scoring = new Score(jenaVivoDB.getJenaModel(), jenaInputDB, jenaOutputDB.getJenaModel());
//authorname matching
if (opts.has("a")) {
scoring.authorNameMatch(Integer.parseInt(opts.get("a")));
}
//Call each exactMatch
for (String attribute : exactMatchArg) {
scoring.exactMatch(attribute);
}
//Call each pairwise
for (String attribute : pairwiseArg) {
scoring.pairwise(attribute);
}
//Call each regex
for (String regex : regexArg) {
scoring.regex(regex);
}
//Empty working model
if (!retainWorkingModel) scoring.scoreInput.removeAll();
//Close and done
scoring.scoreInput.close();
scoring.scoreOutput.close();
scoring.vivo.close();
} else {
//nothing to do but end
}
} catch(ParserConfigurationException e) {
log.fatal(e.getMessage(),e);
} catch(SAXException e) {
log.fatal(e.getMessage(),e);
} catch(IOException e) {
log.fatal(e.getMessage(),e);
}
} catch(IllegalArgumentException e) {
System.out.println(getParser().getUsage());
} catch(Exception e) {
log.fatal(e.getMessage(),e);
}
log.info("Scoring: End");
}
|
diff --git a/src/com/android/contacts/util/PhoneNumberFormatter.java b/src/com/android/contacts/util/PhoneNumberFormatter.java
index 6e63aac37..204ac69a8 100644
--- a/src/com/android/contacts/util/PhoneNumberFormatter.java
+++ b/src/com/android/contacts/util/PhoneNumberFormatter.java
@@ -1,75 +1,73 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.util;
import com.android.contacts.ContactsUtils;
import android.content.Context;
import android.os.AsyncTask;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.widget.TextView;
public final class PhoneNumberFormatter {
private PhoneNumberFormatter() {}
/**
* Load {@link TextWatcherLoadAsyncTask} in a worker thread and set it to a {@link TextView}.
*/
private static class TextWatcherLoadAsyncTask extends
AsyncTask<Void, Void, PhoneNumberFormattingTextWatcher> {
private final String mCountryCode;
private final TextView mTextView;
public TextWatcherLoadAsyncTask(String countryCode, TextView textView) {
mCountryCode = countryCode;
mTextView = textView;
}
@Override
protected PhoneNumberFormattingTextWatcher doInBackground(Void... params) {
return new PhoneNumberFormattingTextWatcher(mCountryCode);
}
@Override
protected void onPostExecute(PhoneNumberFormattingTextWatcher watcher) {
if (watcher == null || isCancelled()) {
return; // May happen if we cancel the task.
}
- if (mTextView.getHandler() == null) {
- return; // View is already detached.
- }
+ // Setting a text changed listener is safe even after the view is detached.
mTextView.addTextChangedListener(watcher);
// Note changes the user made before onPostExecute() will not be formatted, but
// once they type the next letter we format the entire text, so it's not a big deal.
// (And loading PhoneNumberFormattingTextWatcher is usually fast enough.)
// We could use watcher.afterTextChanged(mTextView.getEditableText()) to force format
// the existing content here, but that could cause unwanted results.
// (e.g. the contact editor thinks the user changed the content, and would save
// when closed even when the user didn't make other changes.)
}
}
/**
* Delay-set {@link PhoneNumberFormattingTextWatcher} to a {@link TextView}.
*/
public static final void setPhoneNumberFormattingTextWatcher(Context context,
TextView textView) {
new TextWatcherLoadAsyncTask(ContactsUtils.getCurrentCountryIso(context), textView)
.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
}
}
| true | true | protected void onPostExecute(PhoneNumberFormattingTextWatcher watcher) {
if (watcher == null || isCancelled()) {
return; // May happen if we cancel the task.
}
if (mTextView.getHandler() == null) {
return; // View is already detached.
}
mTextView.addTextChangedListener(watcher);
// Note changes the user made before onPostExecute() will not be formatted, but
// once they type the next letter we format the entire text, so it's not a big deal.
// (And loading PhoneNumberFormattingTextWatcher is usually fast enough.)
// We could use watcher.afterTextChanged(mTextView.getEditableText()) to force format
// the existing content here, but that could cause unwanted results.
// (e.g. the contact editor thinks the user changed the content, and would save
// when closed even when the user didn't make other changes.)
}
| protected void onPostExecute(PhoneNumberFormattingTextWatcher watcher) {
if (watcher == null || isCancelled()) {
return; // May happen if we cancel the task.
}
// Setting a text changed listener is safe even after the view is detached.
mTextView.addTextChangedListener(watcher);
// Note changes the user made before onPostExecute() will not be formatted, but
// once they type the next letter we format the entire text, so it's not a big deal.
// (And loading PhoneNumberFormattingTextWatcher is usually fast enough.)
// We could use watcher.afterTextChanged(mTextView.getEditableText()) to force format
// the existing content here, but that could cause unwanted results.
// (e.g. the contact editor thinks the user changed the content, and would save
// when closed even when the user didn't make other changes.)
}
|
diff --git a/src/algorithm/Palindrome_Partitioning.java b/src/algorithm/Palindrome_Partitioning.java
index af22865..9dbc9a2 100644
--- a/src/algorithm/Palindrome_Partitioning.java
+++ b/src/algorithm/Palindrome_Partitioning.java
@@ -1,53 +1,53 @@
package algorithm;
import java.util.ArrayList;
import java.util.HashMap;
public class Palindrome_Partitioning {
public ArrayList<ArrayList<String>> partition(String s) {
// Note: The Solution object is instantiated only once and is reused by each test case.
HashMap<String, ArrayList<ArrayList<String>>> map = new HashMap<String, ArrayList<ArrayList<String>>>();
return helper(s,map);
}
public ArrayList<ArrayList<String>> helper(String s, HashMap<String, ArrayList<ArrayList<String>>> map){
- if(map.containsKey(s)){
- return map.get(s);
- }
+ //if(map.containsKey(s)){
+ //return map.get(s);
+ //}
ArrayList<ArrayList<String>> ret = new ArrayList<ArrayList<String>>();
if(s.length()==0){
ret.add(new ArrayList<String>());
return ret;
}
for(int i=0; i<s.length(); i++){
String str = s.substring(0,i+1);
if(isP(str)){
ArrayList<ArrayList<String>> res = helper(s.substring(i+1),map);
for(ArrayList<String> list : res){
list.add(0, str);
ret.add(list);
}
}
}
ArrayList<ArrayList<String>> clone = new ArrayList<ArrayList<String>>();
for(ArrayList<String> list:ret){
clone.add((ArrayList<String>)list.clone());
}
- map.put(s, clone);
+ //map.put(s, clone);
return ret;
}
public boolean isP(String str){
int i=0;
int j=str.length()-1;
while(i<j){
if(str.charAt(i)!=str.charAt(j))
return false;
i++;
j--;
}
return true;
}
public static void main(String[] args){
System.out.println(new Palindrome_Partitioning().partition("aab"));
}
}
| false | true | public ArrayList<ArrayList<String>> helper(String s, HashMap<String, ArrayList<ArrayList<String>>> map){
if(map.containsKey(s)){
return map.get(s);
}
ArrayList<ArrayList<String>> ret = new ArrayList<ArrayList<String>>();
if(s.length()==0){
ret.add(new ArrayList<String>());
return ret;
}
for(int i=0; i<s.length(); i++){
String str = s.substring(0,i+1);
if(isP(str)){
ArrayList<ArrayList<String>> res = helper(s.substring(i+1),map);
for(ArrayList<String> list : res){
list.add(0, str);
ret.add(list);
}
}
}
ArrayList<ArrayList<String>> clone = new ArrayList<ArrayList<String>>();
for(ArrayList<String> list:ret){
clone.add((ArrayList<String>)list.clone());
}
map.put(s, clone);
return ret;
}
| public ArrayList<ArrayList<String>> helper(String s, HashMap<String, ArrayList<ArrayList<String>>> map){
//if(map.containsKey(s)){
//return map.get(s);
//}
ArrayList<ArrayList<String>> ret = new ArrayList<ArrayList<String>>();
if(s.length()==0){
ret.add(new ArrayList<String>());
return ret;
}
for(int i=0; i<s.length(); i++){
String str = s.substring(0,i+1);
if(isP(str)){
ArrayList<ArrayList<String>> res = helper(s.substring(i+1),map);
for(ArrayList<String> list : res){
list.add(0, str);
ret.add(list);
}
}
}
ArrayList<ArrayList<String>> clone = new ArrayList<ArrayList<String>>();
for(ArrayList<String> list:ret){
clone.add((ArrayList<String>)list.clone());
}
//map.put(s, clone);
return ret;
}
|
diff --git a/pivot4j-analytics/src/main/java/org/pivot4j/analytics/ui/WorkbenchHandler.java b/pivot4j-analytics/src/main/java/org/pivot4j/analytics/ui/WorkbenchHandler.java
index 1b7004de..de37ffa9 100644
--- a/pivot4j-analytics/src/main/java/org/pivot4j/analytics/ui/WorkbenchHandler.java
+++ b/pivot4j-analytics/src/main/java/org/pivot4j/analytics/ui/WorkbenchHandler.java
@@ -1,264 +1,265 @@
package org.pivot4j.analytics.ui;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.pivot4j.PivotModel;
import org.pivot4j.analytics.config.Settings;
import org.pivot4j.analytics.state.ViewState;
import org.primefaces.extensions.model.layout.LayoutOptions;
@ManagedBean(name = "workbenchHandler")
@RequestScoped
public class WorkbenchHandler {
@ManagedProperty(value = "#{settings}")
private Settings settings;
@ManagedProperty(value = "#{repositoryHandler}")
private RepositoryHandler repositoryHandler;
private boolean editorPaneVisible = false;
private boolean navigatorPaneVisible = true;
private LayoutOptions layoutOptions;
private LayoutOptions workspaceLayoutOptions;
/**
* @return the layoutOptions
*/
public LayoutOptions getLayoutOptions() {
if (layoutOptions == null) {
this.layoutOptions = new LayoutOptions();
layoutOptions.addOption("enableCursorHotkey", false);
LayoutOptions toolbarOptions = new LayoutOptions();
toolbarOptions.addOption("resizable", false);
toolbarOptions.addOption("closable", false);
layoutOptions.setNorthOptions(toolbarOptions);
LayoutOptions navigatorOptions = new LayoutOptions();
navigatorOptions.addOption("resizable", true);
navigatorOptions.addOption("closable", true);
navigatorOptions.addOption("slidable", true);
navigatorOptions.addOption("size", 280);
layoutOptions.setWestOptions(navigatorOptions);
LayoutOptions childWestOptions = new LayoutOptions();
navigatorOptions.setChildOptions(childWestOptions);
LayoutOptions cubeListOptions = new LayoutOptions();
cubeListOptions.addOption("resizable", false);
cubeListOptions.addOption("closable", false);
cubeListOptions.addOption("slidable", false);
cubeListOptions.addOption("size", 38);
childWestOptions.setNorthOptions(cubeListOptions);
LayoutOptions targetTreeOptions = new LayoutOptions();
targetTreeOptions.addOption("resizable", true);
targetTreeOptions.addOption("closable", true);
targetTreeOptions.addOption("slidable", true);
targetTreeOptions.addOption("size", 300);
childWestOptions.setSouthOptions(targetTreeOptions);
LayoutOptions contentOptions = new LayoutOptions();
layoutOptions.setCenterOptions(contentOptions);
LayoutOptions childCenterOptions = new LayoutOptions();
+ childCenterOptions.addOption("onresize_end", "onViewResize");
contentOptions.setChildOptions(childCenterOptions);
LayoutOptions filterOptions = new LayoutOptions();
filterOptions.addOption("resizable", false);
filterOptions.addOption("closable", true);
filterOptions.addOption("slidable", true);
filterOptions.addOption("size", 38);
childCenterOptions.setNorthOptions(filterOptions);
LayoutOptions editorOptions = new LayoutOptions();
editorOptions.addOption("resizable", true);
editorOptions.addOption("closable", true);
editorOptions.addOption("slidable", true);
editorOptions.addOption("size", 180);
childCenterOptions.setSouthOptions(editorOptions);
LayoutOptions editorToolBarOptions = new LayoutOptions();
editorToolBarOptions.addOption("resizable", false);
editorToolBarOptions.addOption("closable", false);
editorToolBarOptions.addOption("slidable", false);
editorToolBarOptions.addOption("size", 38);
editorOptions.setNorthOptions(editorToolBarOptions);
LayoutOptions editorContentOptions = new LayoutOptions();
editorContentOptions.addOption("resizable", false);
editorContentOptions.addOption("closable", false);
editorContentOptions.addOption("slidable", false);
editorContentOptions.addOption("spacing_open", 0);
editorContentOptions.addOption("spacing_closed", 0);
editorOptions.setChildOptions(editorContentOptions);
}
return layoutOptions;
}
/**
* @return the workspaceLayoutOptions
*/
public LayoutOptions getWorkspaceLayoutOptions() {
if (workspaceLayoutOptions == null) {
this.workspaceLayoutOptions = new LayoutOptions();
workspaceLayoutOptions.addOption("enableCursorHotkey", false);
LayoutOptions toolbarOptions = new LayoutOptions();
toolbarOptions.addOption("resizable", false);
toolbarOptions.addOption("resizable", false);
toolbarOptions.addOption("closable", false);
workspaceLayoutOptions.setNorthOptions(toolbarOptions);
LayoutOptions navigatorOptions = new LayoutOptions();
navigatorOptions.addOption("resizable", true);
navigatorOptions.addOption("closable", true);
navigatorOptions.addOption("slidable", true);
navigatorOptions.addOption("size", 200);
workspaceLayoutOptions.setWestOptions(navigatorOptions);
LayoutOptions contentOptions = new LayoutOptions();
contentOptions.addOption("contentSelector", "#tab-panel");
contentOptions.addOption("maskIframesOnResize", true);
workspaceLayoutOptions.setCenterOptions(contentOptions);
}
return workspaceLayoutOptions;
}
/**
* @return the theme
*/
public String getTheme() {
ExternalContext context = FacesContext.getCurrentInstance()
.getExternalContext();
String theme = (String) context.getSessionMap().get("ui-theme");
if (theme == null) {
theme = settings.getTheme();
}
return theme;
}
/**
* @param theme
* the theme to set
*/
public void setTheme(String theme) {
ExternalContext context = FacesContext.getCurrentInstance()
.getExternalContext();
if (theme == null) {
context.getSessionMap().remove("ui-theme");
} else {
context.getSessionMap().put("ui-theme", theme);
}
}
public boolean isDeleteEnabled() {
ViewState viewState = repositoryHandler.getActiveView();
return viewState != null && viewState.getFile() != null;
}
public boolean isSaveEnabled() {
ViewState viewState = repositoryHandler.getActiveView();
return viewState != null && viewState.isDirty();
}
public boolean isViewActive() {
ViewState viewState = repositoryHandler.getActiveView();
return viewState != null;
}
public boolean isViewValid() {
ViewState viewState = repositoryHandler.getActiveView();
if (viewState == null) {
return false;
}
PivotModel model = viewState.getModel();
return model != null && model.isInitialized();
}
/**
* @return the editorPaneVisible
*/
public boolean isEditorPaneVisible() {
return editorPaneVisible;
}
/**
* @param editorPaneVisible
* the editorPaneVisible to set
*/
public void setEditorPaneVisible(boolean editorPaneVisible) {
this.editorPaneVisible = editorPaneVisible;
}
/**
* @return the navigatorPaneVisible
*/
public boolean isNavigatorPaneVisible() {
return navigatorPaneVisible;
}
/**
* @param navigatorPaneVisible
* the navigatorPaneVisible to set
*/
public void setNavigatorPaneVisible(boolean navigatorPaneVisible) {
this.navigatorPaneVisible = navigatorPaneVisible;
}
/**
* @return the settings
*/
public Settings getSettings() {
return settings;
}
/**
* @param settings
* the settings to set
*/
public void setSettings(Settings settings) {
this.settings = settings;
}
/**
* @return the repositoryHandler
*/
public RepositoryHandler getRepositoryHandler() {
return repositoryHandler;
}
/**
* @param repositoryHandler
* the repositoryHandler to set
*/
public void setRepositoryHandler(RepositoryHandler repositoryHandler) {
this.repositoryHandler = repositoryHandler;
}
}
| true | true | public LayoutOptions getLayoutOptions() {
if (layoutOptions == null) {
this.layoutOptions = new LayoutOptions();
layoutOptions.addOption("enableCursorHotkey", false);
LayoutOptions toolbarOptions = new LayoutOptions();
toolbarOptions.addOption("resizable", false);
toolbarOptions.addOption("closable", false);
layoutOptions.setNorthOptions(toolbarOptions);
LayoutOptions navigatorOptions = new LayoutOptions();
navigatorOptions.addOption("resizable", true);
navigatorOptions.addOption("closable", true);
navigatorOptions.addOption("slidable", true);
navigatorOptions.addOption("size", 280);
layoutOptions.setWestOptions(navigatorOptions);
LayoutOptions childWestOptions = new LayoutOptions();
navigatorOptions.setChildOptions(childWestOptions);
LayoutOptions cubeListOptions = new LayoutOptions();
cubeListOptions.addOption("resizable", false);
cubeListOptions.addOption("closable", false);
cubeListOptions.addOption("slidable", false);
cubeListOptions.addOption("size", 38);
childWestOptions.setNorthOptions(cubeListOptions);
LayoutOptions targetTreeOptions = new LayoutOptions();
targetTreeOptions.addOption("resizable", true);
targetTreeOptions.addOption("closable", true);
targetTreeOptions.addOption("slidable", true);
targetTreeOptions.addOption("size", 300);
childWestOptions.setSouthOptions(targetTreeOptions);
LayoutOptions contentOptions = new LayoutOptions();
layoutOptions.setCenterOptions(contentOptions);
LayoutOptions childCenterOptions = new LayoutOptions();
contentOptions.setChildOptions(childCenterOptions);
LayoutOptions filterOptions = new LayoutOptions();
filterOptions.addOption("resizable", false);
filterOptions.addOption("closable", true);
filterOptions.addOption("slidable", true);
filterOptions.addOption("size", 38);
childCenterOptions.setNorthOptions(filterOptions);
LayoutOptions editorOptions = new LayoutOptions();
editorOptions.addOption("resizable", true);
editorOptions.addOption("closable", true);
editorOptions.addOption("slidable", true);
editorOptions.addOption("size", 180);
childCenterOptions.setSouthOptions(editorOptions);
LayoutOptions editorToolBarOptions = new LayoutOptions();
editorToolBarOptions.addOption("resizable", false);
editorToolBarOptions.addOption("closable", false);
editorToolBarOptions.addOption("slidable", false);
editorToolBarOptions.addOption("size", 38);
editorOptions.setNorthOptions(editorToolBarOptions);
LayoutOptions editorContentOptions = new LayoutOptions();
editorContentOptions.addOption("resizable", false);
editorContentOptions.addOption("closable", false);
editorContentOptions.addOption("slidable", false);
editorContentOptions.addOption("spacing_open", 0);
editorContentOptions.addOption("spacing_closed", 0);
editorOptions.setChildOptions(editorContentOptions);
}
return layoutOptions;
}
| public LayoutOptions getLayoutOptions() {
if (layoutOptions == null) {
this.layoutOptions = new LayoutOptions();
layoutOptions.addOption("enableCursorHotkey", false);
LayoutOptions toolbarOptions = new LayoutOptions();
toolbarOptions.addOption("resizable", false);
toolbarOptions.addOption("closable", false);
layoutOptions.setNorthOptions(toolbarOptions);
LayoutOptions navigatorOptions = new LayoutOptions();
navigatorOptions.addOption("resizable", true);
navigatorOptions.addOption("closable", true);
navigatorOptions.addOption("slidable", true);
navigatorOptions.addOption("size", 280);
layoutOptions.setWestOptions(navigatorOptions);
LayoutOptions childWestOptions = new LayoutOptions();
navigatorOptions.setChildOptions(childWestOptions);
LayoutOptions cubeListOptions = new LayoutOptions();
cubeListOptions.addOption("resizable", false);
cubeListOptions.addOption("closable", false);
cubeListOptions.addOption("slidable", false);
cubeListOptions.addOption("size", 38);
childWestOptions.setNorthOptions(cubeListOptions);
LayoutOptions targetTreeOptions = new LayoutOptions();
targetTreeOptions.addOption("resizable", true);
targetTreeOptions.addOption("closable", true);
targetTreeOptions.addOption("slidable", true);
targetTreeOptions.addOption("size", 300);
childWestOptions.setSouthOptions(targetTreeOptions);
LayoutOptions contentOptions = new LayoutOptions();
layoutOptions.setCenterOptions(contentOptions);
LayoutOptions childCenterOptions = new LayoutOptions();
childCenterOptions.addOption("onresize_end", "onViewResize");
contentOptions.setChildOptions(childCenterOptions);
LayoutOptions filterOptions = new LayoutOptions();
filterOptions.addOption("resizable", false);
filterOptions.addOption("closable", true);
filterOptions.addOption("slidable", true);
filterOptions.addOption("size", 38);
childCenterOptions.setNorthOptions(filterOptions);
LayoutOptions editorOptions = new LayoutOptions();
editorOptions.addOption("resizable", true);
editorOptions.addOption("closable", true);
editorOptions.addOption("slidable", true);
editorOptions.addOption("size", 180);
childCenterOptions.setSouthOptions(editorOptions);
LayoutOptions editorToolBarOptions = new LayoutOptions();
editorToolBarOptions.addOption("resizable", false);
editorToolBarOptions.addOption("closable", false);
editorToolBarOptions.addOption("slidable", false);
editorToolBarOptions.addOption("size", 38);
editorOptions.setNorthOptions(editorToolBarOptions);
LayoutOptions editorContentOptions = new LayoutOptions();
editorContentOptions.addOption("resizable", false);
editorContentOptions.addOption("closable", false);
editorContentOptions.addOption("slidable", false);
editorContentOptions.addOption("spacing_open", 0);
editorContentOptions.addOption("spacing_closed", 0);
editorOptions.setChildOptions(editorContentOptions);
}
return layoutOptions;
}
|
diff --git a/src/com/softcocoa/eightpuzzle/solvers/AStarSearching.java b/src/com/softcocoa/eightpuzzle/solvers/AStarSearching.java
index dc588e2..86d11d5 100644
--- a/src/com/softcocoa/eightpuzzle/solvers/AStarSearching.java
+++ b/src/com/softcocoa/eightpuzzle/solvers/AStarSearching.java
@@ -1,56 +1,56 @@
package com.softcocoa.eightpuzzle.solvers;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Stack;
import java.util.TreeSet;
import com.softcocoa.eightpuzzle.C;
import com.softcocoa.eightpuzzle.PuzzleState;
import com.softcocoa.eightpuzzle.heuristic.HeuristicCalculator;
public class AStarSearching extends PuzzleSolveAlgorithm {
private TreeSet<PuzzleState> nodes;
private ArrayList<PuzzleState> closedNodes;
public AStarSearching(PuzzleState initialState, HeuristicCalculator hCalculator) {
super(initialState, hCalculator);
nodes = new TreeSet<PuzzleState>(puzzleStateHeuristicComparator);
closedNodes = new ArrayList<PuzzleState>(C.INITIAL_CLOSED_LIST_SIZE);
nodes.add(initialState);
}
@Override
public ArrayList<PuzzleState> solvePuzzle() {
ArrayList<PuzzleState> solvingSteps = new ArrayList<PuzzleState>(C.INITIAL_STEP_LIST_SIZE);
// TODO expand PuzzleState in nodes TreeSet and keep expanded nodes in closedNodes
// until we reach the goal and extract the solution path from closedNodes into solvingSteps.
// testing dummy
- /*steps.add(initialState);
- steps.add(new PuzzleState(new int[]{1,0,3,4,2,5,7,8,6}));
- steps.add(new PuzzleState(new int[]{1,3,4,0,5,2,7,8,6}));
- steps.add(new PuzzleState(C.FINISH_PUZZLE_TILES()));
- steps.trimToSize();*/
+ /*solvingSteps.add(initialState);
+ solvingSteps.add(new PuzzleState(null, new int[]{1,0,3,4,2,5,7,8,6}));
+ solvingSteps.add(new PuzzleState(null, new int[]{1,3,4,0,5,2,7,8,6}));
+ solvingSteps.add(new PuzzleState(null, C.FINISH_PUZZLE_TILES()));
+ solvingSteps.trimToSize();*/
solvingSteps.trimToSize();
return solvingSteps;
}
private Comparator<PuzzleState> puzzleStateHeuristicComparator = new Comparator<PuzzleState>() {
@Override
public int compare(PuzzleState o1, PuzzleState o2) {
int result = 0;
if (o1.getHeuristic()<o2.getHeuristic())
result = -1;
else if (o1.getHeuristic()>o2.getHeuristic())
result = 1;
return result;
}
};
}
| true | true | public ArrayList<PuzzleState> solvePuzzle() {
ArrayList<PuzzleState> solvingSteps = new ArrayList<PuzzleState>(C.INITIAL_STEP_LIST_SIZE);
// TODO expand PuzzleState in nodes TreeSet and keep expanded nodes in closedNodes
// until we reach the goal and extract the solution path from closedNodes into solvingSteps.
// testing dummy
/*steps.add(initialState);
steps.add(new PuzzleState(new int[]{1,0,3,4,2,5,7,8,6}));
steps.add(new PuzzleState(new int[]{1,3,4,0,5,2,7,8,6}));
steps.add(new PuzzleState(C.FINISH_PUZZLE_TILES()));
steps.trimToSize();*/
solvingSteps.trimToSize();
return solvingSteps;
}
| public ArrayList<PuzzleState> solvePuzzle() {
ArrayList<PuzzleState> solvingSteps = new ArrayList<PuzzleState>(C.INITIAL_STEP_LIST_SIZE);
// TODO expand PuzzleState in nodes TreeSet and keep expanded nodes in closedNodes
// until we reach the goal and extract the solution path from closedNodes into solvingSteps.
// testing dummy
/*solvingSteps.add(initialState);
solvingSteps.add(new PuzzleState(null, new int[]{1,0,3,4,2,5,7,8,6}));
solvingSteps.add(new PuzzleState(null, new int[]{1,3,4,0,5,2,7,8,6}));
solvingSteps.add(new PuzzleState(null, C.FINISH_PUZZLE_TILES()));
solvingSteps.trimToSize();*/
solvingSteps.trimToSize();
return solvingSteps;
}
|
diff --git a/IDEtalk/src/idea/jetbrains/communicator/idea/toolWindow/IDEtalkToolWindow.java b/IDEtalk/src/idea/jetbrains/communicator/idea/toolWindow/IDEtalkToolWindow.java
index 6b76e4081c..1fc3185bd0 100644
--- a/IDEtalk/src/idea/jetbrains/communicator/idea/toolWindow/IDEtalkToolWindow.java
+++ b/IDEtalk/src/idea/jetbrains/communicator/idea/toolWindow/IDEtalkToolWindow.java
@@ -1,198 +1,200 @@
/*
* Copyright 2000-2006 JetBrains s.r.o.
*
* 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 jetbrains.communicator.idea.toolWindow;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.ActionToolbar;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupManager;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.wm.ToolWindowAnchor;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.ui.SeparatorComponent;
import com.intellij.ui.SeparatorOrientation;
import jetbrains.communicator.core.Pico;
import jetbrains.communicator.core.transport.Transport;
import jetbrains.communicator.ide.StatusToolbar;
import jetbrains.communicator.ide.UserListComponent;
import jetbrains.communicator.idea.BaseToolWindow;
import jetbrains.communicator.idea.IDEAFacade;
import jetbrains.communicator.idea.IDEtalkContainerRegistry;
import jetbrains.communicator.idea.actions.DropDownButton;
import jetbrains.communicator.idea.actions.FindUsersAction;
import jetbrains.communicator.idea.actions.OptionsButton;
import jetbrains.communicator.util.UIUtil;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.picocontainer.MutablePicoContainer;
import javax.swing.*;
import java.awt.*;
@SuppressWarnings({"RefusedBequest", "RefusedBequest", "RefusedBequest"})
public class IDEtalkToolWindow extends BaseToolWindow implements JDOMExternalizable {
@NonNls public static final String PLACE_TOOLBAR = "TOOLBAR";
@NonNls public static final String PLACE_POPUP = "POPUP";
@NonNls private static final String TOOL_WINDOW_ID = "IDEtalk";
private final UserListComponentImpl myUserListComponent;
private final MutablePicoContainer myContainer;
private JPanel myTopPanel;
public IDEtalkToolWindow(ToolWindowManager toolWindowManager,
ActionManager actionManager, Project project,
IDEtalkContainerRegistry containerRegistry) {
super(toolWindowManager, actionManager, project);
myContainer = containerRegistry.getContainer();
myContainer.registerComponentImplementation(UserListComponentImpl.class);
myContainer.registerComponentImplementation(StatusToolbarImpl.class);
myUserListComponent = (UserListComponentImpl) myContainer.getComponentInstanceOfType(UserListComponent.class);
}
public void initComponent() {
myTopPanel = new JPanel();
myTopPanel.setLayout(new BoxLayout(myTopPanel, BoxLayout.Y_AXIS));
}
protected Component getComponent() {
return myUserListComponent.getComponent();
}
protected String getToolWindowId() {
return TOOL_WINDOW_ID;
}
private void initializeTransports(String projectName) {
java.util.List transports = Pico.getInstance().getComponentInstancesOfType(Transport.class);
for (Object transport1 : transports) {
Transport transport = (Transport) transport1;
transport.initializeProject(projectName, myContainer);
}
}
public void projectClosed() {
UIUtil.removeListenersToPreventMemoryLeak(((Container) getComponent()));
super.projectClosed();
}
@NotNull
public String getComponentName() {
return "IDEtalkToolWindow";
}
public void readExternal(Element element) throws InvalidDataException {
}
public void writeExternal(Element element) throws WriteExternalException {
if (myUserListComponent != null) {
myUserListComponent.saveState();
}
throw new WriteExternalException();
}
protected void createToolWindowComponent() {
StartupManager.getInstance(myProject).registerPostStartupActivity(new Runnable() {
public void run() {
initializeTransports(myProject.getName());
}
});
StatusToolbar statusToolbar = ((StatusToolbar) myContainer.getComponentInstanceOfType(StatusToolbar.class));
ActionGroup toolbarActions = (ActionGroup) myActionManager.getAction("IDEtalk");
ActionGroup treeActions = (ActionGroup) myActionManager.getAction("IDEtalk_Tree");
JPanel toolbarPanel = new JPanel();
toolbarPanel.setLayout(new BoxLayout(toolbarPanel, BoxLayout.X_AXIS));
toolbarActions = buildToolbarActions(toolbarPanel, toolbarActions);
if (toolbarActions != null) {
JComponent toolbar = createToolbar(toolbarActions).getComponent();
toolbarPanel.add(toolbar);
}
toolbarPanel.add(Box.createHorizontalStrut(10));
toolbarPanel.add(new SeparatorComponent(Color.lightGray, SeparatorOrientation.VERTICAL));
toolbarPanel.add(Box.createHorizontalStrut(3));
toolbarPanel.add(OptionsButton.wrap(new OptionsButton()));
toolbarPanel.add(statusToolbar.createComponent());
toolbarPanel.add(new JPanel() {
public Dimension getPreferredSize() {
return new Dimension(Short.MAX_VALUE, 10);
}
});
if (treeActions != null) {
- toolbarPanel.add(createToolbar(treeActions).getComponent());
+ JComponent component = createToolbar(treeActions).getComponent();
+ component.setMinimumSize(component.getPreferredSize());
+ toolbarPanel.add(component);
}
toolbarPanel.setAlignmentX(0);
myTopPanel.add(toolbarPanel);
myPanel.add(myTopPanel, BorderLayout.NORTH);
myPanel.add(new JScrollPane(myUserListComponent.getComponent()));
ActionGroup group = (ActionGroup)myActionManager.getAction("IDEtalkPopup");
if (group != null) {
IDEAFacade.installPopupMenu(group, myUserListComponent.getTree(), myActionManager);
}
}
private ActionToolbar createToolbar(final ActionGroup toolbarActions) {
final ActionToolbar toolbar = myActionManager.createActionToolbar(PLACE_TOOLBAR, toolbarActions, true);
toolbar.setLayoutPolicy(ActionToolbar.NOWRAP_LAYOUT_POLICY);
return toolbar;
}
private ActionGroup buildToolbarActions(JPanel toolbarPanel, ActionGroup toolbarActions) {
FindUsersAction findUsersAction = new FindUsersAction();
toolbarPanel.add(DropDownButton.wrap(new DropDownButton(findUsersAction, IconLoader.getIcon("/general/add.png"))));
return toolbarActions;
}
protected ToolWindowAnchor getAnchor() {
return ToolWindowAnchor.RIGHT;
}
public static void main(String[] args) {
Box topPanel = Box.createHorizontalBox();
topPanel.add(new JPanel() {
{
setOpaque(true);
setBackground(Color.red);
}
public Dimension getPreferredSize() {
return new Dimension(Short.MAX_VALUE, 10);
}
});
topPanel.setPreferredSize(new Dimension(200, 30));
UIUtil.run(topPanel);
}
}
| true | true | protected void createToolWindowComponent() {
StartupManager.getInstance(myProject).registerPostStartupActivity(new Runnable() {
public void run() {
initializeTransports(myProject.getName());
}
});
StatusToolbar statusToolbar = ((StatusToolbar) myContainer.getComponentInstanceOfType(StatusToolbar.class));
ActionGroup toolbarActions = (ActionGroup) myActionManager.getAction("IDEtalk");
ActionGroup treeActions = (ActionGroup) myActionManager.getAction("IDEtalk_Tree");
JPanel toolbarPanel = new JPanel();
toolbarPanel.setLayout(new BoxLayout(toolbarPanel, BoxLayout.X_AXIS));
toolbarActions = buildToolbarActions(toolbarPanel, toolbarActions);
if (toolbarActions != null) {
JComponent toolbar = createToolbar(toolbarActions).getComponent();
toolbarPanel.add(toolbar);
}
toolbarPanel.add(Box.createHorizontalStrut(10));
toolbarPanel.add(new SeparatorComponent(Color.lightGray, SeparatorOrientation.VERTICAL));
toolbarPanel.add(Box.createHorizontalStrut(3));
toolbarPanel.add(OptionsButton.wrap(new OptionsButton()));
toolbarPanel.add(statusToolbar.createComponent());
toolbarPanel.add(new JPanel() {
public Dimension getPreferredSize() {
return new Dimension(Short.MAX_VALUE, 10);
}
});
if (treeActions != null) {
toolbarPanel.add(createToolbar(treeActions).getComponent());
}
toolbarPanel.setAlignmentX(0);
myTopPanel.add(toolbarPanel);
myPanel.add(myTopPanel, BorderLayout.NORTH);
myPanel.add(new JScrollPane(myUserListComponent.getComponent()));
ActionGroup group = (ActionGroup)myActionManager.getAction("IDEtalkPopup");
if (group != null) {
IDEAFacade.installPopupMenu(group, myUserListComponent.getTree(), myActionManager);
}
}
| protected void createToolWindowComponent() {
StartupManager.getInstance(myProject).registerPostStartupActivity(new Runnable() {
public void run() {
initializeTransports(myProject.getName());
}
});
StatusToolbar statusToolbar = ((StatusToolbar) myContainer.getComponentInstanceOfType(StatusToolbar.class));
ActionGroup toolbarActions = (ActionGroup) myActionManager.getAction("IDEtalk");
ActionGroup treeActions = (ActionGroup) myActionManager.getAction("IDEtalk_Tree");
JPanel toolbarPanel = new JPanel();
toolbarPanel.setLayout(new BoxLayout(toolbarPanel, BoxLayout.X_AXIS));
toolbarActions = buildToolbarActions(toolbarPanel, toolbarActions);
if (toolbarActions != null) {
JComponent toolbar = createToolbar(toolbarActions).getComponent();
toolbarPanel.add(toolbar);
}
toolbarPanel.add(Box.createHorizontalStrut(10));
toolbarPanel.add(new SeparatorComponent(Color.lightGray, SeparatorOrientation.VERTICAL));
toolbarPanel.add(Box.createHorizontalStrut(3));
toolbarPanel.add(OptionsButton.wrap(new OptionsButton()));
toolbarPanel.add(statusToolbar.createComponent());
toolbarPanel.add(new JPanel() {
public Dimension getPreferredSize() {
return new Dimension(Short.MAX_VALUE, 10);
}
});
if (treeActions != null) {
JComponent component = createToolbar(treeActions).getComponent();
component.setMinimumSize(component.getPreferredSize());
toolbarPanel.add(component);
}
toolbarPanel.setAlignmentX(0);
myTopPanel.add(toolbarPanel);
myPanel.add(myTopPanel, BorderLayout.NORTH);
myPanel.add(new JScrollPane(myUserListComponent.getComponent()));
ActionGroup group = (ActionGroup)myActionManager.getAction("IDEtalkPopup");
if (group != null) {
IDEAFacade.installPopupMenu(group, myUserListComponent.getTree(), myActionManager);
}
}
|
diff --git a/signserver/modules/SignServer-AdminCLI/src/org/signserver/admin/cli/defaultimpl/TestKeyCommand.java b/signserver/modules/SignServer-AdminCLI/src/org/signserver/admin/cli/defaultimpl/TestKeyCommand.java
index ab34b510e..5dc440604 100644
--- a/signserver/modules/SignServer-AdminCLI/src/org/signserver/admin/cli/defaultimpl/TestKeyCommand.java
+++ b/signserver/modules/SignServer-AdminCLI/src/org/signserver/admin/cli/defaultimpl/TestKeyCommand.java
@@ -1,153 +1,153 @@
/*************************************************************************
* *
* 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.admin.cli.defaultimpl;
import java.util.Collection;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.log4j.Logger;
import org.ejbca.ui.cli.util.ConsolePasswordReader;
import org.signserver.cli.spi.CommandFailureException;
import org.signserver.cli.spi.IllegalCommandArgumentsException;
import org.signserver.cli.spi.UnexpectedCommandFailureException;
import org.signserver.common.KeyTestResult;
/**
* Command used to test one or more keys associated with a Crypto Token.
*
* @author Markus Kilås
* @version $Id$
*/
public class TestKeyCommand extends AbstractAdminCommand {
/** Logger for this class. */
private static final Logger LOG = Logger.getLogger(TestKeyCommand.class);
/** Option authcode. */
public static final String AUTHCODE = "authcode";
/** Option verbose. */
public static final String VERBOSE = "v";
/** The command line options. */
private static final Options OPTIONS;
private static String USAGE = "Usage: signserver testkey <worker id | worker name> [alias or \"all\"] [-v]\n"
+ "Leaving out \"alias\" and \"all\" will use the value in DEFAULTKEY.\n\n"
+ "Specifying \"all\" tests all keys in the slot .\n"
+ "Example 1: signserver testkey 71\n"
+ "Example 2: signserver testkey 71 myKey1\n"
+ "Example 3: signserver testkey 71 all";
private char[] authCode;
private boolean verbose;
static {
OPTIONS = new Options();
OPTIONS.addOption(AUTHCODE, true, "Authentication code");
OPTIONS.addOption(VERBOSE, false, "Verbose output");
}
@Override
public String getDescription() {
return "Tests one or more keys in a Crypto Token";
}
@Override
public String getUsages() {
return USAGE;
}
/**
* Reads all the options from the command line.
*
* @param line The command line to read from
*/
private void parseCommandLine(final CommandLine line) {
if (line.hasOption(AUTHCODE)) {
authCode = line.getOptionValue(AUTHCODE, null).toCharArray();
}
verbose = line.hasOption(VERBOSE);
}
/**
* Checks that all mandadory options are given.
*/
private void validateOptions() {
// No mandatory options.
}
@Override
public int execute(String... args) throws IllegalCommandArgumentsException, CommandFailureException, UnexpectedCommandFailureException {
try {
// Parse the command line
parseCommandLine(new GnuParser().parse(OPTIONS, args));
} catch (ParseException ex) {
throw new IllegalArgumentException(ex.getLocalizedMessage(), ex);
}
validateOptions();
if (args.length < 1) {
throw new IllegalCommandArgumentsException(USAGE);
}
try {
if (authCode == null) {
getOutputStream().print("Enter authorization code: ");
// Read the password, but mask it so we don't display it on the console
final ConsolePasswordReader r = new ConsolePasswordReader();
authCode = r.readPassword();
}
int signerId = getWorkerId(args[0]);
checkThatWorkerIsProcessable(signerId);
String alias = null;
- if (args.length > 2) {
+ if (args.length >= 2) {
alias = args[1];
}
if (alias == null) {
LOG.info(
"Will test key with alias defined by DEFAULTKEY property");
} else if ("all".equals(alias)) {
LOG.info("Will test all keys");
} else {
LOG.info("Test key with alias " + alias + ".");
}
final Collection<KeyTestResult> results = getWorkerSession().testKey(signerId, alias, authCode);
for (KeyTestResult key : results) {
final StringBuilder sb = new StringBuilder();
sb.append(key.getAlias());
sb.append(" \t");
sb.append(key.isSuccess() ? "SUCCESS" : "FAILURE");
sb.append(" \t");
if (verbose) {
sb.append(" \t");
sb.append(key.getPublicKeyHash());
}
sb.append(" \t");
sb.append(key.getStatus());
System.out.println(sb.toString());
}
return 0;
} catch (Exception e) {
throw new UnexpectedCommandFailureException(e);
}
}
}
| true | true | public int execute(String... args) throws IllegalCommandArgumentsException, CommandFailureException, UnexpectedCommandFailureException {
try {
// Parse the command line
parseCommandLine(new GnuParser().parse(OPTIONS, args));
} catch (ParseException ex) {
throw new IllegalArgumentException(ex.getLocalizedMessage(), ex);
}
validateOptions();
if (args.length < 1) {
throw new IllegalCommandArgumentsException(USAGE);
}
try {
if (authCode == null) {
getOutputStream().print("Enter authorization code: ");
// Read the password, but mask it so we don't display it on the console
final ConsolePasswordReader r = new ConsolePasswordReader();
authCode = r.readPassword();
}
int signerId = getWorkerId(args[0]);
checkThatWorkerIsProcessable(signerId);
String alias = null;
if (args.length > 2) {
alias = args[1];
}
if (alias == null) {
LOG.info(
"Will test key with alias defined by DEFAULTKEY property");
} else if ("all".equals(alias)) {
LOG.info("Will test all keys");
} else {
LOG.info("Test key with alias " + alias + ".");
}
final Collection<KeyTestResult> results = getWorkerSession().testKey(signerId, alias, authCode);
for (KeyTestResult key : results) {
final StringBuilder sb = new StringBuilder();
sb.append(key.getAlias());
sb.append(" \t");
sb.append(key.isSuccess() ? "SUCCESS" : "FAILURE");
sb.append(" \t");
if (verbose) {
sb.append(" \t");
sb.append(key.getPublicKeyHash());
}
sb.append(" \t");
sb.append(key.getStatus());
System.out.println(sb.toString());
}
return 0;
} catch (Exception e) {
throw new UnexpectedCommandFailureException(e);
}
}
| public int execute(String... args) throws IllegalCommandArgumentsException, CommandFailureException, UnexpectedCommandFailureException {
try {
// Parse the command line
parseCommandLine(new GnuParser().parse(OPTIONS, args));
} catch (ParseException ex) {
throw new IllegalArgumentException(ex.getLocalizedMessage(), ex);
}
validateOptions();
if (args.length < 1) {
throw new IllegalCommandArgumentsException(USAGE);
}
try {
if (authCode == null) {
getOutputStream().print("Enter authorization code: ");
// Read the password, but mask it so we don't display it on the console
final ConsolePasswordReader r = new ConsolePasswordReader();
authCode = r.readPassword();
}
int signerId = getWorkerId(args[0]);
checkThatWorkerIsProcessable(signerId);
String alias = null;
if (args.length >= 2) {
alias = args[1];
}
if (alias == null) {
LOG.info(
"Will test key with alias defined by DEFAULTKEY property");
} else if ("all".equals(alias)) {
LOG.info("Will test all keys");
} else {
LOG.info("Test key with alias " + alias + ".");
}
final Collection<KeyTestResult> results = getWorkerSession().testKey(signerId, alias, authCode);
for (KeyTestResult key : results) {
final StringBuilder sb = new StringBuilder();
sb.append(key.getAlias());
sb.append(" \t");
sb.append(key.isSuccess() ? "SUCCESS" : "FAILURE");
sb.append(" \t");
if (verbose) {
sb.append(" \t");
sb.append(key.getPublicKeyHash());
}
sb.append(" \t");
sb.append(key.getStatus());
System.out.println(sb.toString());
}
return 0;
} catch (Exception e) {
throw new UnexpectedCommandFailureException(e);
}
}
|
diff --git a/app/EditorListener.java b/app/EditorListener.java
index 65b907cd9..f881fd397 100644
--- a/app/EditorListener.java
+++ b/app/EditorListener.java
@@ -1,647 +1,651 @@
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-06 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package processing.app;
import processing.app.syntax.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
/**
* Filters key events for tab expansion/indent/etc.
* <p/>
* For version 0099, some changes have been made to make the indents
* smarter. There are still issues though:
* + indent happens when it picks up a curly brace on the previous line,
* but not if there's a blank line between them.
* + It also doesn't handle single indent situations where a brace
* isn't used (i.e. an if statement or for loop that's a single line).
* It shouldn't actually be using braces.
* Solving these issues, however, would probably best be done by a
* smarter parser/formatter, rather than continuing to hack this class.
*/
public class EditorListener {
Editor editor;
JEditTextArea textarea;
boolean externalEditor;
boolean tabsExpand;
boolean tabsIndent;
int tabSize;
String tabString;
boolean autoIndent;
int selectionStart, selectionEnd;
int position;
public EditorListener(Editor editor, JEditTextArea textarea) {
this.editor = editor;
this.textarea = textarea;
// let him know that i'm leechin'
textarea.editorListener = this;
applyPreferences();
}
public void applyPreferences() {
tabsExpand = Preferences.getBoolean("editor.tabs.expand");
//tabsIndent = Preferences.getBoolean("editor.tabs.indent");
tabSize = Preferences.getInteger("editor.tabs.size");
tabString = Editor.EMPTY.substring(0, tabSize);
autoIndent = Preferences.getBoolean("editor.indent");
externalEditor = Preferences.getBoolean("editor.external");
}
//public void setExternalEditor(boolean externalEditor) {
//this.externalEditor = externalEditor;
//}
/**
* Intercepts key pressed events for JEditTextArea.
* <p/>
* Called by JEditTextArea inside processKeyEvent(). Note that this
* won't intercept actual characters, because those are fired on
* keyTyped().
*/
public boolean keyPressed(KeyEvent event) {
// don't do things if the textarea isn't editable
if (externalEditor) return false;
//deselect(); // this is for paren balancing
char c = event.getKeyChar();
int code = event.getKeyCode();
//System.out.println((int)c + " " + code + " " + event);
//System.out.println();
if ((event.getModifiers() & KeyEvent.META_MASK) != 0) {
//event.consume(); // does nothing
return false;
}
// TODO i don't like these accessors. clean em up later.
if (!editor.sketch.modified) {
if ((code == KeyEvent.VK_BACK_SPACE) || (code == KeyEvent.VK_TAB) ||
(code == KeyEvent.VK_ENTER) || ((c >= 32) && (c < 128))) {
editor.sketch.setModified(true);
}
}
if ((code == KeyEvent.VK_UP) &&
((event.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
// back up to the last empty line
char contents[] = textarea.getText().toCharArray();
//int origIndex = textarea.getCaretPosition() - 1;
int caretIndex = textarea.getCaretPosition();
int index = calcLineStart(caretIndex - 1, contents);
//System.out.println("line start " + (int) contents[index]);
index -= 2; // step over the newline
//System.out.println((int) contents[index]);
boolean onlySpaces = true;
while (index > 0) {
if (contents[index] == 10) {
if (onlySpaces) {
index++;
break;
} else {
onlySpaces = true; // reset
}
} else if (contents[index] != ' ') {
onlySpaces = false;
}
index--;
}
// if the first char, index will be -2
if (index < 0) index = 0;
if ((event.getModifiers() & KeyEvent.SHIFT_MASK) != 0) {
textarea.setSelectionStart(caretIndex);
textarea.setSelectionEnd(index);
} else {
textarea.setCaretPosition(index);
}
event.consume();
return true;
} else if ((code == KeyEvent.VK_DOWN) &&
((event.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
char contents[] = textarea.getText().toCharArray();
int caretIndex = textarea.getCaretPosition();
int index = caretIndex;
int lineStart = 0;
boolean onlySpaces = false; // don't count this line
while (index < contents.length) {
if (contents[index] == 10) {
if (onlySpaces) {
index = lineStart; // this is it
break;
} else {
lineStart = index + 1;
onlySpaces = true; // reset
}
} else if (contents[index] != ' ') {
onlySpaces = false;
}
index++;
}
// if the first char, index will be -2
//if (index < 0) index = 0;
//textarea.setSelectionStart(index);
//textarea.setSelectionEnd(index);
if ((event.getModifiers() & KeyEvent.SHIFT_MASK) != 0) {
textarea.setSelectionStart(caretIndex);
textarea.setSelectionEnd(index);
} else {
textarea.setCaretPosition(index);
}
event.consume();
return true;
}
switch ((int) c) {
case 9:
if (tabsExpand) { // expand tabs
textarea.setSelectedText(tabString);
event.consume();
return true;
} else if (tabsIndent) {
// this code is incomplete
// if this brace is the only thing on the line, outdent
//char contents[] = getCleanedContents();
char contents[] = textarea.getText().toCharArray();
// index to the character to the left of the caret
int prevCharIndex = textarea.getCaretPosition() - 1;
// now find the start of this line
int lineStart = calcLineStart(prevCharIndex, contents);
int lineEnd = lineStart;
while ((lineEnd < contents.length - 1) &&
(contents[lineEnd] != 10)) {
lineEnd++;
}
// get the number of braces, to determine whether this is an indent
int braceBalance = 0;
int index = lineStart;
while ((index < contents.length) &&
(contents[index] != 10)) {
if (contents[index] == '{') {
braceBalance++;
} else if (contents[index] == '}') {
braceBalance--;
}
index++;
}
// if it's a starting indent, need to ignore it, so lineStart
// will be the counting point. but if there's a closing indent,
// then the lineEnd should be used.
int where = (braceBalance > 0) ? lineStart : lineEnd;
int indent = calcBraceIndent(where, contents);
if (indent == -1) {
// no braces to speak of, do nothing
indent = 0;
} else {
indent += tabSize;
}
// and the number of spaces it has
int spaceCount = calcSpaceCount(prevCharIndex, contents);
textarea.setSelectionStart(lineStart);
textarea.setSelectionEnd(lineStart + spaceCount);
textarea.setSelectedText(Editor.EMPTY.substring(0, indent));
event.consume();
return true;
}
break;
case 10: // auto-indent
case 13:
if (autoIndent) {
char contents[] = textarea.getText().toCharArray();
// this is the previous character
// (i.e. when you hit return, it'll be the last character
// just before where the newline will be inserted)
int origIndex = textarea.getCaretPosition() - 1;
// NOTE all this cursing about CRLF stuff is probably moot
// NOTE since the switch to JEditTextArea, which seems to use
// NOTE only LFs internally (thank god). disabling for 0099.
// walk through the array to the current caret position,
// and count how many weirdo windows line endings there are,
// which would be throwing off the caret position number
/*
int offset = 0;
int realIndex = origIndex;
for (int i = 0; i < realIndex-1; i++) {
if ((contents[i] == 13) && (contents[i+1] == 10)) {
offset++;
realIndex++;
}
}
// back up until \r \r\n or \n.. @#($* cross platform
//System.out.println(origIndex + " offset = " + offset);
origIndex += offset; // ARGH!#(* WINDOWS#@($*
*/
// if the previous thing is a brace (whether prev line or
// up farther) then the correct indent is the number of spaces
// on that line + 'indent'.
// if the previous line is not a brace, then just use the
// identical indentation to the previous line
// calculate the amount of indent on the previous line
// this will be used *only if the prev line is not an indent*
int spaceCount = calcSpaceCount(origIndex, contents);
// If the last character was a left curly brace, then indent.
// For 0122, walk backwards a bit to make sure that the there
// isn't a curly brace several spaces (or lines) back. Also
// moved this before calculating extraCount, since it'll affect
// that as well.
int index2 = origIndex;
while ((index2 >= 0) &&
Character.isWhitespace(contents[index2])) {
index2--;
}
if (index2 != -1) {
// still won't catch a case where prev stuff is a comment
if (contents[index2] == '{') {
// intermediate lines be damned,
// use the indent for this line instead
spaceCount = calcSpaceCount(index2, contents);
spaceCount += tabSize;
}
}
//System.out.println("spaceCount should be " + spaceCount);
// now before inserting this many spaces, walk forward from
// the caret position and count the number of spaces,
// so that the number of spaces aren't duplicated again
int index = origIndex + 1;
int extraCount = 0;
while ((index < contents.length) &&
(contents[index] == ' ')) {
//spaceCount--;
extraCount++;
index++;
}
int braceCount = 0;
while ((index < contents.length) && (contents[index] != '\n')) {
if (contents[index] == '}') {
braceCount++;
}
index++;
}
// hitting return on a line with spaces *after* the caret
// can cause trouble. for 0099, was ignoring the case, but this is
// annoying, so in 0122 we're trying to fix that.
/*
if (spaceCount - extraCount > 0) {
spaceCount -= extraCount;
}
*/
spaceCount -= extraCount;
//if (spaceCount < 0) spaceCount = 0;
//System.out.println("extraCount is " + extraCount);
// now, check to see if the current line contains a } and if so,
// outdent again by indent
//if (braceCount > 0) {
//spaceCount -= 2;
//}
if (spaceCount < 0) {
// for rev 0122, actually delete extra space
//textarea.setSelectionStart(origIndex + 1);
textarea.setSelectionEnd(textarea.getSelectionEnd() - spaceCount);
textarea.setSelectedText("\n");
} else {
String insertion = "\n" + Editor.EMPTY.substring(0, spaceCount);
textarea.setSelectedText(insertion);
}
// not gonna bother handling more than one brace
if (braceCount > 0) {
int sel = textarea.getSelectionStart();
- textarea.select(sel - tabSize, sel);
- String s = Editor.EMPTY.substring(0, tabSize);
- // if these are spaces that we can delete
- if (textarea.getSelectedText().equals(s)) {
- textarea.setSelectedText("");
- } else {
- textarea.select(sel, sel);
+ // sel - tabSize will be -1 if start/end parens on the same line
+ // http://dev.processing.org/bugs/show_bug.cgi?id=484
+ if (sel - tabSize >= 0) {
+ textarea.select(sel - tabSize, sel);
+ String s = Editor.EMPTY.substring(0, tabSize);
+ // if these are spaces that we can delete
+ if (textarea.getSelectedText().equals(s)) {
+ textarea.setSelectedText("");
+ } else {
+ textarea.select(sel, sel);
+ }
}
}
// mark this event as already handled
event.consume();
return true;
}
break;
case '}':
if (autoIndent) {
// first remove anything that was there (in case this multiple
// characters are selected, so that it's not in the way of the
// spaces for the auto-indent
if (textarea.getSelectionStart() != textarea.getSelectionEnd()) {
textarea.setSelectedText("");
}
// if this brace is the only thing on the line, outdent
char contents[] = textarea.getText().toCharArray();
// index to the character to the left of the caret
int prevCharIndex = textarea.getCaretPosition() - 1;
// backup from the current caret position to the last newline,
// checking for anything besides whitespace along the way.
// if there's something besides whitespace, exit without
// messing any sort of indenting.
int index = prevCharIndex;
boolean finished = false;
while ((index != -1) && (!finished)) {
if (contents[index] == 10) {
finished = true;
index++;
} else if (contents[index] != ' ') {
// don't do anything, this line has other stuff on it
return false;
} else {
index--;
}
}
if (!finished) return false; // brace with no start
int lineStartIndex = index;
/*
// now that we know things are ok to be indented, walk
// backwards to the last { to see how far its line is indented.
// this isn't perfect cuz it'll pick up commented areas,
// but that's not really a big deal and can be fixed when
// this is all given a more complete (proper) solution.
index = prevCharIndex;
int braceDepth = 1;
finished = false;
while ((index != -1) && (!finished)) {
if (contents[index] == '}') {
// aww crap, this means we're one deeper
// and will have to find one more extra {
braceDepth++;
index--;
} else if (contents[index] == '{') {
braceDepth--;
if (braceDepth == 0) {
finished = true;
} // otherwise just teasing, keep going..
} else {
index--;
}
}
// never found a proper brace, be safe and don't do anything
if (!finished) return false;
// check how many spaces on the line with the matching open brace
int pairedSpaceCount = calcSpaceCount(index, contents);
//System.out.println(pairedSpaceCount);
*/
int pairedSpaceCount = calcBraceIndent(prevCharIndex, contents); //, 1);
if (pairedSpaceCount == -1) return false;
/*
// now walk forward and figure out how many spaces there are
while ((index < contents.length) && (index >= 0) &&
(contents[index++] == ' ')) {
spaceCount++;
}
*/
// number of spaces found on this line
//int newSpaceCount = Math.max(0, spaceCount - tabSize);
// number of spaces on this current line
//int spaceCount = calcSpaces(caretIndex, contents);
//System.out.println("spaces is " + spaceCount);
//String insertion = "\n" + Editor.EMPTY.substring(0, spaceCount);
//int differential = newSpaceCount - spaceCount;
//System.out.println("diff is " + differential);
//int newStart = textarea.getSelectionStart() + differential;
//textarea.setSelectionStart(newStart);
//textarea.setSelectedText("}");
textarea.setSelectionStart(lineStartIndex);
textarea.setSelectedText(Editor.EMPTY.substring(0, pairedSpaceCount));
// mark this event as already handled
event.consume();
return true;
}
break;
}
return false;
}
/** Cmd-Shift or Ctrl-Shift depending on the platform */
static final int CMD_SHIFT = ActionEvent.SHIFT_MASK |
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
public boolean keyTyped(KeyEvent event) {
char c = event.getKeyChar();
int code = event.getKeyCode();
//System.out.println((int)c + " " + code + " " + event);
//System.out.println();
if ((event.getModifiers() & CMD_SHIFT) != 0) {
if (c == '[') {
editor.sketch.prevCode();
return true;
} else if (c == ']') {
editor.sketch.nextCode();
return true;
}
}
return false;
}
/**
* Return the index for the first character on this line.
*/
protected int calcLineStart(int index, char contents[]) {
// backup from the current caret position to the last newline,
// so that we can figure out how far this line was indented
int spaceCount = 0;
boolean finished = false;
while ((index != -1) && (!finished)) {
if ((contents[index] == 10) ||
(contents[index] == 13)) {
finished = true;
//index++; // maybe ?
} else {
index--; // new
}
}
// add one because index is either -1 (the start of the document)
// or it's the newline character for the previous line
return index + 1;
}
/**
* Calculate the number of spaces on this line.
*/
protected int calcSpaceCount(int index, char contents[]) {
index = calcLineStart(index, contents);
int spaceCount = 0;
// now walk forward and figure out how many spaces there are
while ((index < contents.length) && (index >= 0) &&
(contents[index++] == ' ')) {
spaceCount++;
}
return spaceCount;
}
/**
* Walk back from 'index' until the brace that seems to be
* the beginning of the current block, and return the number of
* spaces found on that line.
*/
protected int calcBraceIndent(int index, char contents[]) {
// now that we know things are ok to be indented, walk
// backwards to the last { to see how far its line is indented.
// this isn't perfect cuz it'll pick up commented areas,
// but that's not really a big deal and can be fixed when
// this is all given a more complete (proper) solution.
int braceDepth = 1;
boolean finished = false;
while ((index != -1) && (!finished)) {
if (contents[index] == '}') {
// aww crap, this means we're one deeper
// and will have to find one more extra {
braceDepth++;
//if (braceDepth == 0) {
//finished = true;
//}
index--;
} else if (contents[index] == '{') {
braceDepth--;
if (braceDepth == 0) {
finished = true;
}
index--;
} else {
index--;
}
}
// never found a proper brace, be safe and don't do anything
if (!finished) return -1;
// check how many spaces on the line with the matching open brace
//int pairedSpaceCount = calcSpaceCount(index, contents);
//System.out.println(pairedSpaceCount);
return calcSpaceCount(index, contents);
}
/**
* Get the character array and blank out the commented areas.
* This hasn't yet been tested, the plan was to make auto-indent
* less gullible (it gets fooled by braces that are commented out).
*/
protected char[] getCleanedContents() {
char c[] = textarea.getText().toCharArray();
int index = 0;
while (index < c.length - 1) {
if ((c[index] == '/') && (c[index+1] == '*')) {
c[index++] = 0;
c[index++] = 0;
while ((index < c.length - 1) &&
!((c[index] == '*') && (c[index+1] == '/'))) {
c[index++] = 0;
}
} else if ((c[index] == '/') && (c[index+1] == '/')) {
// clear out until the end of the line
while ((index < c.length) && (c[index] != 10)) {
c[index++] = 0;
}
if (index != c.length) {
index++; // skip over the newline
}
}
}
return c;
}
/*
protected char[] getCleanedContents() {
char c[] = textarea.getText().toCharArray();
boolean insideMulti; // multi-line comment
boolean insideSingle; // single line double slash
//for (int i = 0; i < c.length - 1; i++) {
int index = 0;
while (index < c.length - 1) {
if (insideMulti && (c[index] == '*') && (c[index+1] == '/')) {
insideMulti = false;
index += 2;
} else if ((c[index] == '/') && (c[index+1] == '*')) {
insideMulti = true;
index += 2;
} else if ((c[index] == '/') && (c[index+1] == '/')) {
// clear out until the end of the line
while (c[index] != 10) {
c[index++] = 0;
}
index++;
}
}
}
*/
}
| true | true | public boolean keyPressed(KeyEvent event) {
// don't do things if the textarea isn't editable
if (externalEditor) return false;
//deselect(); // this is for paren balancing
char c = event.getKeyChar();
int code = event.getKeyCode();
//System.out.println((int)c + " " + code + " " + event);
//System.out.println();
if ((event.getModifiers() & KeyEvent.META_MASK) != 0) {
//event.consume(); // does nothing
return false;
}
// TODO i don't like these accessors. clean em up later.
if (!editor.sketch.modified) {
if ((code == KeyEvent.VK_BACK_SPACE) || (code == KeyEvent.VK_TAB) ||
(code == KeyEvent.VK_ENTER) || ((c >= 32) && (c < 128))) {
editor.sketch.setModified(true);
}
}
if ((code == KeyEvent.VK_UP) &&
((event.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
// back up to the last empty line
char contents[] = textarea.getText().toCharArray();
//int origIndex = textarea.getCaretPosition() - 1;
int caretIndex = textarea.getCaretPosition();
int index = calcLineStart(caretIndex - 1, contents);
//System.out.println("line start " + (int) contents[index]);
index -= 2; // step over the newline
//System.out.println((int) contents[index]);
boolean onlySpaces = true;
while (index > 0) {
if (contents[index] == 10) {
if (onlySpaces) {
index++;
break;
} else {
onlySpaces = true; // reset
}
} else if (contents[index] != ' ') {
onlySpaces = false;
}
index--;
}
// if the first char, index will be -2
if (index < 0) index = 0;
if ((event.getModifiers() & KeyEvent.SHIFT_MASK) != 0) {
textarea.setSelectionStart(caretIndex);
textarea.setSelectionEnd(index);
} else {
textarea.setCaretPosition(index);
}
event.consume();
return true;
} else if ((code == KeyEvent.VK_DOWN) &&
((event.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
char contents[] = textarea.getText().toCharArray();
int caretIndex = textarea.getCaretPosition();
int index = caretIndex;
int lineStart = 0;
boolean onlySpaces = false; // don't count this line
while (index < contents.length) {
if (contents[index] == 10) {
if (onlySpaces) {
index = lineStart; // this is it
break;
} else {
lineStart = index + 1;
onlySpaces = true; // reset
}
} else if (contents[index] != ' ') {
onlySpaces = false;
}
index++;
}
// if the first char, index will be -2
//if (index < 0) index = 0;
//textarea.setSelectionStart(index);
//textarea.setSelectionEnd(index);
if ((event.getModifiers() & KeyEvent.SHIFT_MASK) != 0) {
textarea.setSelectionStart(caretIndex);
textarea.setSelectionEnd(index);
} else {
textarea.setCaretPosition(index);
}
event.consume();
return true;
}
switch ((int) c) {
case 9:
if (tabsExpand) { // expand tabs
textarea.setSelectedText(tabString);
event.consume();
return true;
} else if (tabsIndent) {
// this code is incomplete
// if this brace is the only thing on the line, outdent
//char contents[] = getCleanedContents();
char contents[] = textarea.getText().toCharArray();
// index to the character to the left of the caret
int prevCharIndex = textarea.getCaretPosition() - 1;
// now find the start of this line
int lineStart = calcLineStart(prevCharIndex, contents);
int lineEnd = lineStart;
while ((lineEnd < contents.length - 1) &&
(contents[lineEnd] != 10)) {
lineEnd++;
}
// get the number of braces, to determine whether this is an indent
int braceBalance = 0;
int index = lineStart;
while ((index < contents.length) &&
(contents[index] != 10)) {
if (contents[index] == '{') {
braceBalance++;
} else if (contents[index] == '}') {
braceBalance--;
}
index++;
}
// if it's a starting indent, need to ignore it, so lineStart
// will be the counting point. but if there's a closing indent,
// then the lineEnd should be used.
int where = (braceBalance > 0) ? lineStart : lineEnd;
int indent = calcBraceIndent(where, contents);
if (indent == -1) {
// no braces to speak of, do nothing
indent = 0;
} else {
indent += tabSize;
}
// and the number of spaces it has
int spaceCount = calcSpaceCount(prevCharIndex, contents);
textarea.setSelectionStart(lineStart);
textarea.setSelectionEnd(lineStart + spaceCount);
textarea.setSelectedText(Editor.EMPTY.substring(0, indent));
event.consume();
return true;
}
break;
case 10: // auto-indent
case 13:
if (autoIndent) {
char contents[] = textarea.getText().toCharArray();
// this is the previous character
// (i.e. when you hit return, it'll be the last character
// just before where the newline will be inserted)
int origIndex = textarea.getCaretPosition() - 1;
// NOTE all this cursing about CRLF stuff is probably moot
// NOTE since the switch to JEditTextArea, which seems to use
// NOTE only LFs internally (thank god). disabling for 0099.
// walk through the array to the current caret position,
// and count how many weirdo windows line endings there are,
// which would be throwing off the caret position number
/*
int offset = 0;
int realIndex = origIndex;
for (int i = 0; i < realIndex-1; i++) {
if ((contents[i] == 13) && (contents[i+1] == 10)) {
offset++;
realIndex++;
}
}
// back up until \r \r\n or \n.. @#($* cross platform
//System.out.println(origIndex + " offset = " + offset);
origIndex += offset; // ARGH!#(* WINDOWS#@($*
*/
// if the previous thing is a brace (whether prev line or
// up farther) then the correct indent is the number of spaces
// on that line + 'indent'.
// if the previous line is not a brace, then just use the
// identical indentation to the previous line
// calculate the amount of indent on the previous line
// this will be used *only if the prev line is not an indent*
int spaceCount = calcSpaceCount(origIndex, contents);
// If the last character was a left curly brace, then indent.
// For 0122, walk backwards a bit to make sure that the there
// isn't a curly brace several spaces (or lines) back. Also
// moved this before calculating extraCount, since it'll affect
// that as well.
int index2 = origIndex;
while ((index2 >= 0) &&
Character.isWhitespace(contents[index2])) {
index2--;
}
if (index2 != -1) {
// still won't catch a case where prev stuff is a comment
if (contents[index2] == '{') {
// intermediate lines be damned,
// use the indent for this line instead
spaceCount = calcSpaceCount(index2, contents);
spaceCount += tabSize;
}
}
//System.out.println("spaceCount should be " + spaceCount);
// now before inserting this many spaces, walk forward from
// the caret position and count the number of spaces,
// so that the number of spaces aren't duplicated again
int index = origIndex + 1;
int extraCount = 0;
while ((index < contents.length) &&
(contents[index] == ' ')) {
//spaceCount--;
extraCount++;
index++;
}
int braceCount = 0;
while ((index < contents.length) && (contents[index] != '\n')) {
if (contents[index] == '}') {
braceCount++;
}
index++;
}
// hitting return on a line with spaces *after* the caret
// can cause trouble. for 0099, was ignoring the case, but this is
// annoying, so in 0122 we're trying to fix that.
/*
if (spaceCount - extraCount > 0) {
spaceCount -= extraCount;
}
*/
spaceCount -= extraCount;
//if (spaceCount < 0) spaceCount = 0;
//System.out.println("extraCount is " + extraCount);
// now, check to see if the current line contains a } and if so,
// outdent again by indent
//if (braceCount > 0) {
//spaceCount -= 2;
//}
if (spaceCount < 0) {
// for rev 0122, actually delete extra space
//textarea.setSelectionStart(origIndex + 1);
textarea.setSelectionEnd(textarea.getSelectionEnd() - spaceCount);
textarea.setSelectedText("\n");
} else {
String insertion = "\n" + Editor.EMPTY.substring(0, spaceCount);
textarea.setSelectedText(insertion);
}
// not gonna bother handling more than one brace
if (braceCount > 0) {
int sel = textarea.getSelectionStart();
textarea.select(sel - tabSize, sel);
String s = Editor.EMPTY.substring(0, tabSize);
// if these are spaces that we can delete
if (textarea.getSelectedText().equals(s)) {
textarea.setSelectedText("");
} else {
textarea.select(sel, sel);
}
}
// mark this event as already handled
event.consume();
return true;
}
break;
case '}':
if (autoIndent) {
// first remove anything that was there (in case this multiple
// characters are selected, so that it's not in the way of the
// spaces for the auto-indent
if (textarea.getSelectionStart() != textarea.getSelectionEnd()) {
textarea.setSelectedText("");
}
// if this brace is the only thing on the line, outdent
char contents[] = textarea.getText().toCharArray();
// index to the character to the left of the caret
int prevCharIndex = textarea.getCaretPosition() - 1;
// backup from the current caret position to the last newline,
// checking for anything besides whitespace along the way.
// if there's something besides whitespace, exit without
// messing any sort of indenting.
int index = prevCharIndex;
boolean finished = false;
while ((index != -1) && (!finished)) {
if (contents[index] == 10) {
finished = true;
index++;
} else if (contents[index] != ' ') {
// don't do anything, this line has other stuff on it
return false;
} else {
index--;
}
}
if (!finished) return false; // brace with no start
int lineStartIndex = index;
/*
// now that we know things are ok to be indented, walk
// backwards to the last { to see how far its line is indented.
// this isn't perfect cuz it'll pick up commented areas,
// but that's not really a big deal and can be fixed when
// this is all given a more complete (proper) solution.
index = prevCharIndex;
int braceDepth = 1;
finished = false;
while ((index != -1) && (!finished)) {
if (contents[index] == '}') {
// aww crap, this means we're one deeper
// and will have to find one more extra {
braceDepth++;
index--;
} else if (contents[index] == '{') {
braceDepth--;
if (braceDepth == 0) {
finished = true;
} // otherwise just teasing, keep going..
} else {
index--;
}
}
// never found a proper brace, be safe and don't do anything
if (!finished) return false;
// check how many spaces on the line with the matching open brace
int pairedSpaceCount = calcSpaceCount(index, contents);
//System.out.println(pairedSpaceCount);
*/
int pairedSpaceCount = calcBraceIndent(prevCharIndex, contents); //, 1);
if (pairedSpaceCount == -1) return false;
/*
// now walk forward and figure out how many spaces there are
while ((index < contents.length) && (index >= 0) &&
(contents[index++] == ' ')) {
spaceCount++;
}
*/
// number of spaces found on this line
//int newSpaceCount = Math.max(0, spaceCount - tabSize);
// number of spaces on this current line
//int spaceCount = calcSpaces(caretIndex, contents);
//System.out.println("spaces is " + spaceCount);
//String insertion = "\n" + Editor.EMPTY.substring(0, spaceCount);
//int differential = newSpaceCount - spaceCount;
//System.out.println("diff is " + differential);
//int newStart = textarea.getSelectionStart() + differential;
//textarea.setSelectionStart(newStart);
//textarea.setSelectedText("}");
textarea.setSelectionStart(lineStartIndex);
textarea.setSelectedText(Editor.EMPTY.substring(0, pairedSpaceCount));
// mark this event as already handled
event.consume();
return true;
}
break;
}
return false;
}
| public boolean keyPressed(KeyEvent event) {
// don't do things if the textarea isn't editable
if (externalEditor) return false;
//deselect(); // this is for paren balancing
char c = event.getKeyChar();
int code = event.getKeyCode();
//System.out.println((int)c + " " + code + " " + event);
//System.out.println();
if ((event.getModifiers() & KeyEvent.META_MASK) != 0) {
//event.consume(); // does nothing
return false;
}
// TODO i don't like these accessors. clean em up later.
if (!editor.sketch.modified) {
if ((code == KeyEvent.VK_BACK_SPACE) || (code == KeyEvent.VK_TAB) ||
(code == KeyEvent.VK_ENTER) || ((c >= 32) && (c < 128))) {
editor.sketch.setModified(true);
}
}
if ((code == KeyEvent.VK_UP) &&
((event.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
// back up to the last empty line
char contents[] = textarea.getText().toCharArray();
//int origIndex = textarea.getCaretPosition() - 1;
int caretIndex = textarea.getCaretPosition();
int index = calcLineStart(caretIndex - 1, contents);
//System.out.println("line start " + (int) contents[index]);
index -= 2; // step over the newline
//System.out.println((int) contents[index]);
boolean onlySpaces = true;
while (index > 0) {
if (contents[index] == 10) {
if (onlySpaces) {
index++;
break;
} else {
onlySpaces = true; // reset
}
} else if (contents[index] != ' ') {
onlySpaces = false;
}
index--;
}
// if the first char, index will be -2
if (index < 0) index = 0;
if ((event.getModifiers() & KeyEvent.SHIFT_MASK) != 0) {
textarea.setSelectionStart(caretIndex);
textarea.setSelectionEnd(index);
} else {
textarea.setCaretPosition(index);
}
event.consume();
return true;
} else if ((code == KeyEvent.VK_DOWN) &&
((event.getModifiers() & KeyEvent.CTRL_MASK) != 0)) {
char contents[] = textarea.getText().toCharArray();
int caretIndex = textarea.getCaretPosition();
int index = caretIndex;
int lineStart = 0;
boolean onlySpaces = false; // don't count this line
while (index < contents.length) {
if (contents[index] == 10) {
if (onlySpaces) {
index = lineStart; // this is it
break;
} else {
lineStart = index + 1;
onlySpaces = true; // reset
}
} else if (contents[index] != ' ') {
onlySpaces = false;
}
index++;
}
// if the first char, index will be -2
//if (index < 0) index = 0;
//textarea.setSelectionStart(index);
//textarea.setSelectionEnd(index);
if ((event.getModifiers() & KeyEvent.SHIFT_MASK) != 0) {
textarea.setSelectionStart(caretIndex);
textarea.setSelectionEnd(index);
} else {
textarea.setCaretPosition(index);
}
event.consume();
return true;
}
switch ((int) c) {
case 9:
if (tabsExpand) { // expand tabs
textarea.setSelectedText(tabString);
event.consume();
return true;
} else if (tabsIndent) {
// this code is incomplete
// if this brace is the only thing on the line, outdent
//char contents[] = getCleanedContents();
char contents[] = textarea.getText().toCharArray();
// index to the character to the left of the caret
int prevCharIndex = textarea.getCaretPosition() - 1;
// now find the start of this line
int lineStart = calcLineStart(prevCharIndex, contents);
int lineEnd = lineStart;
while ((lineEnd < contents.length - 1) &&
(contents[lineEnd] != 10)) {
lineEnd++;
}
// get the number of braces, to determine whether this is an indent
int braceBalance = 0;
int index = lineStart;
while ((index < contents.length) &&
(contents[index] != 10)) {
if (contents[index] == '{') {
braceBalance++;
} else if (contents[index] == '}') {
braceBalance--;
}
index++;
}
// if it's a starting indent, need to ignore it, so lineStart
// will be the counting point. but if there's a closing indent,
// then the lineEnd should be used.
int where = (braceBalance > 0) ? lineStart : lineEnd;
int indent = calcBraceIndent(where, contents);
if (indent == -1) {
// no braces to speak of, do nothing
indent = 0;
} else {
indent += tabSize;
}
// and the number of spaces it has
int spaceCount = calcSpaceCount(prevCharIndex, contents);
textarea.setSelectionStart(lineStart);
textarea.setSelectionEnd(lineStart + spaceCount);
textarea.setSelectedText(Editor.EMPTY.substring(0, indent));
event.consume();
return true;
}
break;
case 10: // auto-indent
case 13:
if (autoIndent) {
char contents[] = textarea.getText().toCharArray();
// this is the previous character
// (i.e. when you hit return, it'll be the last character
// just before where the newline will be inserted)
int origIndex = textarea.getCaretPosition() - 1;
// NOTE all this cursing about CRLF stuff is probably moot
// NOTE since the switch to JEditTextArea, which seems to use
// NOTE only LFs internally (thank god). disabling for 0099.
// walk through the array to the current caret position,
// and count how many weirdo windows line endings there are,
// which would be throwing off the caret position number
/*
int offset = 0;
int realIndex = origIndex;
for (int i = 0; i < realIndex-1; i++) {
if ((contents[i] == 13) && (contents[i+1] == 10)) {
offset++;
realIndex++;
}
}
// back up until \r \r\n or \n.. @#($* cross platform
//System.out.println(origIndex + " offset = " + offset);
origIndex += offset; // ARGH!#(* WINDOWS#@($*
*/
// if the previous thing is a brace (whether prev line or
// up farther) then the correct indent is the number of spaces
// on that line + 'indent'.
// if the previous line is not a brace, then just use the
// identical indentation to the previous line
// calculate the amount of indent on the previous line
// this will be used *only if the prev line is not an indent*
int spaceCount = calcSpaceCount(origIndex, contents);
// If the last character was a left curly brace, then indent.
// For 0122, walk backwards a bit to make sure that the there
// isn't a curly brace several spaces (or lines) back. Also
// moved this before calculating extraCount, since it'll affect
// that as well.
int index2 = origIndex;
while ((index2 >= 0) &&
Character.isWhitespace(contents[index2])) {
index2--;
}
if (index2 != -1) {
// still won't catch a case where prev stuff is a comment
if (contents[index2] == '{') {
// intermediate lines be damned,
// use the indent for this line instead
spaceCount = calcSpaceCount(index2, contents);
spaceCount += tabSize;
}
}
//System.out.println("spaceCount should be " + spaceCount);
// now before inserting this many spaces, walk forward from
// the caret position and count the number of spaces,
// so that the number of spaces aren't duplicated again
int index = origIndex + 1;
int extraCount = 0;
while ((index < contents.length) &&
(contents[index] == ' ')) {
//spaceCount--;
extraCount++;
index++;
}
int braceCount = 0;
while ((index < contents.length) && (contents[index] != '\n')) {
if (contents[index] == '}') {
braceCount++;
}
index++;
}
// hitting return on a line with spaces *after* the caret
// can cause trouble. for 0099, was ignoring the case, but this is
// annoying, so in 0122 we're trying to fix that.
/*
if (spaceCount - extraCount > 0) {
spaceCount -= extraCount;
}
*/
spaceCount -= extraCount;
//if (spaceCount < 0) spaceCount = 0;
//System.out.println("extraCount is " + extraCount);
// now, check to see if the current line contains a } and if so,
// outdent again by indent
//if (braceCount > 0) {
//spaceCount -= 2;
//}
if (spaceCount < 0) {
// for rev 0122, actually delete extra space
//textarea.setSelectionStart(origIndex + 1);
textarea.setSelectionEnd(textarea.getSelectionEnd() - spaceCount);
textarea.setSelectedText("\n");
} else {
String insertion = "\n" + Editor.EMPTY.substring(0, spaceCount);
textarea.setSelectedText(insertion);
}
// not gonna bother handling more than one brace
if (braceCount > 0) {
int sel = textarea.getSelectionStart();
// sel - tabSize will be -1 if start/end parens on the same line
// http://dev.processing.org/bugs/show_bug.cgi?id=484
if (sel - tabSize >= 0) {
textarea.select(sel - tabSize, sel);
String s = Editor.EMPTY.substring(0, tabSize);
// if these are spaces that we can delete
if (textarea.getSelectedText().equals(s)) {
textarea.setSelectedText("");
} else {
textarea.select(sel, sel);
}
}
}
// mark this event as already handled
event.consume();
return true;
}
break;
case '}':
if (autoIndent) {
// first remove anything that was there (in case this multiple
// characters are selected, so that it's not in the way of the
// spaces for the auto-indent
if (textarea.getSelectionStart() != textarea.getSelectionEnd()) {
textarea.setSelectedText("");
}
// if this brace is the only thing on the line, outdent
char contents[] = textarea.getText().toCharArray();
// index to the character to the left of the caret
int prevCharIndex = textarea.getCaretPosition() - 1;
// backup from the current caret position to the last newline,
// checking for anything besides whitespace along the way.
// if there's something besides whitespace, exit without
// messing any sort of indenting.
int index = prevCharIndex;
boolean finished = false;
while ((index != -1) && (!finished)) {
if (contents[index] == 10) {
finished = true;
index++;
} else if (contents[index] != ' ') {
// don't do anything, this line has other stuff on it
return false;
} else {
index--;
}
}
if (!finished) return false; // brace with no start
int lineStartIndex = index;
/*
// now that we know things are ok to be indented, walk
// backwards to the last { to see how far its line is indented.
// this isn't perfect cuz it'll pick up commented areas,
// but that's not really a big deal and can be fixed when
// this is all given a more complete (proper) solution.
index = prevCharIndex;
int braceDepth = 1;
finished = false;
while ((index != -1) && (!finished)) {
if (contents[index] == '}') {
// aww crap, this means we're one deeper
// and will have to find one more extra {
braceDepth++;
index--;
} else if (contents[index] == '{') {
braceDepth--;
if (braceDepth == 0) {
finished = true;
} // otherwise just teasing, keep going..
} else {
index--;
}
}
// never found a proper brace, be safe and don't do anything
if (!finished) return false;
// check how many spaces on the line with the matching open brace
int pairedSpaceCount = calcSpaceCount(index, contents);
//System.out.println(pairedSpaceCount);
*/
int pairedSpaceCount = calcBraceIndent(prevCharIndex, contents); //, 1);
if (pairedSpaceCount == -1) return false;
/*
// now walk forward and figure out how many spaces there are
while ((index < contents.length) && (index >= 0) &&
(contents[index++] == ' ')) {
spaceCount++;
}
*/
// number of spaces found on this line
//int newSpaceCount = Math.max(0, spaceCount - tabSize);
// number of spaces on this current line
//int spaceCount = calcSpaces(caretIndex, contents);
//System.out.println("spaces is " + spaceCount);
//String insertion = "\n" + Editor.EMPTY.substring(0, spaceCount);
//int differential = newSpaceCount - spaceCount;
//System.out.println("diff is " + differential);
//int newStart = textarea.getSelectionStart() + differential;
//textarea.setSelectionStart(newStart);
//textarea.setSelectedText("}");
textarea.setSelectionStart(lineStartIndex);
textarea.setSelectedText(Editor.EMPTY.substring(0, pairedSpaceCount));
// mark this event as already handled
event.consume();
return true;
}
break;
}
return false;
}
|
diff --git a/tests/frontend/org/voltdb/VoltJUnitFormatter.java b/tests/frontend/org/voltdb/VoltJUnitFormatter.java
index 535c21f3d..c2d2752ee 100644
--- a/tests/frontend/org/voltdb/VoltJUnitFormatter.java
+++ b/tests/frontend/org/voltdb/VoltJUnitFormatter.java
@@ -1,123 +1,124 @@
/* This file is part of VoltDB.
* Copyright (C) 2008-2010 VoltDB Inc.
*
* 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.voltdb;
import java.io.OutputStream;
import java.io.PrintStream;
import junit.framework.AssertionFailedError;
import junit.framework.Test;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.taskdefs.optional.junit.JUnitResultFormatter;
import org.apache.tools.ant.taskdefs.optional.junit.JUnitTest;
public class VoltJUnitFormatter implements JUnitResultFormatter {
PrintStream out = System.out;
JUnitTest m_currentSuite;
int m_tests;
int m_errs;
int m_failures;
long m_start;
@Override
public void setOutput(OutputStream outputStream) {
out = new PrintStream(outputStream);
}
@Override
public void setSystemError(String arg0) {
//out.println("SYSERR: " + arg0);
}
@Override
public void setSystemOutput(String arg0) {
//out.println("SYSOUT: " + arg0);
}
@Override
public void startTestSuite(JUnitTest suite) throws BuildException {
m_currentSuite = suite;
m_tests = m_errs = m_failures = 0;
m_start = System.currentTimeMillis();
out.println("Running " + suite.getName());
}
@Override
public void endTestSuite(JUnitTest suite) throws BuildException {
out.printf("Tests run: %3d, Failures: %3d, Errors: %3d, Time elapsed: %.2f sec\n",
m_tests, m_failures, m_errs, (System.currentTimeMillis() - m_start) / 1000.0);
}
@Override
public void startTest(Test arg0) {
}
@Override
public void endTest(Test arg0) {
out.flush();
m_tests++;
}
@Override
public void addError(Test arg0, Throwable arg1) {
String testName = "unknown";
if (arg0 != null) {
testName = arg0.toString();
- testName = testName.substring(0, testName.indexOf('('));
+ if (arg0.toString().indexOf('(') != -1)
+ testName = testName.substring(0, testName.indexOf('('));
}
out.println(" " + testName + " had an error.");
StackTraceElement[] st = arg1.getStackTrace();
int i = 0;
for (StackTraceElement ste : st) {
if (ste.getClassName().contains("org.voltdb") == false)
continue;
out.printf(" %s(%s:%d)\n", ste.getClassName(), ste.getFileName(), ste.getLineNumber());
if (++i == 3) break;
}
m_errs++;
}
@Override
public void addFailure(Test arg0, AssertionFailedError arg1) {
String testName = arg0.toString();
testName = testName.substring(0, testName.indexOf('('));
out.println(" " + testName + " failed an assertion.");
StackTraceElement[] st = arg1.getStackTrace();
int i = 0;
for (StackTraceElement ste : st) {
if (ste.getClassName().contains("org.voltdb") == false)
continue;
out.printf(" %s(%s:%d)\n", ste.getClassName(), ste.getFileName(), ste.getLineNumber());
if (++i == 3) break;
}
m_failures++;
}
}
| true | true | public void addError(Test arg0, Throwable arg1) {
String testName = "unknown";
if (arg0 != null) {
testName = arg0.toString();
testName = testName.substring(0, testName.indexOf('('));
}
out.println(" " + testName + " had an error.");
StackTraceElement[] st = arg1.getStackTrace();
int i = 0;
for (StackTraceElement ste : st) {
if (ste.getClassName().contains("org.voltdb") == false)
continue;
out.printf(" %s(%s:%d)\n", ste.getClassName(), ste.getFileName(), ste.getLineNumber());
if (++i == 3) break;
}
m_errs++;
}
| public void addError(Test arg0, Throwable arg1) {
String testName = "unknown";
if (arg0 != null) {
testName = arg0.toString();
if (arg0.toString().indexOf('(') != -1)
testName = testName.substring(0, testName.indexOf('('));
}
out.println(" " + testName + " had an error.");
StackTraceElement[] st = arg1.getStackTrace();
int i = 0;
for (StackTraceElement ste : st) {
if (ste.getClassName().contains("org.voltdb") == false)
continue;
out.printf(" %s(%s:%d)\n", ste.getClassName(), ste.getFileName(), ste.getLineNumber());
if (++i == 3) break;
}
m_errs++;
}
|
diff --git a/samples/buttonmanager-sample/src/com/sample/buttonmanager/ButtonManagerServlet.java b/samples/buttonmanager-sample/src/com/sample/buttonmanager/ButtonManagerServlet.java
index 6e1f175..f5c166b 100644
--- a/samples/buttonmanager-sample/src/com/sample/buttonmanager/ButtonManagerServlet.java
+++ b/samples/buttonmanager-sample/src/com/sample/buttonmanager/ButtonManagerServlet.java
@@ -1,458 +1,458 @@
package com.sample.buttonmanager;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import urn.ebay.api.PayPalAPI.BMButtonSearchReq;
import urn.ebay.api.PayPalAPI.BMButtonSearchRequestType;
import urn.ebay.api.PayPalAPI.BMButtonSearchResponseType;
import urn.ebay.api.PayPalAPI.BMCreateButtonReq;
import urn.ebay.api.PayPalAPI.BMCreateButtonRequestType;
import urn.ebay.api.PayPalAPI.BMCreateButtonResponseType;
import urn.ebay.api.PayPalAPI.BMGetButtonDetailsReq;
import urn.ebay.api.PayPalAPI.BMGetButtonDetailsRequestType;
import urn.ebay.api.PayPalAPI.BMGetButtonDetailsResponseType;
import urn.ebay.api.PayPalAPI.BMGetInventoryReq;
import urn.ebay.api.PayPalAPI.BMGetInventoryRequestType;
import urn.ebay.api.PayPalAPI.BMGetInventoryResponseType;
import urn.ebay.api.PayPalAPI.BMManageButtonStatusReq;
import urn.ebay.api.PayPalAPI.BMManageButtonStatusRequestType;
import urn.ebay.api.PayPalAPI.BMManageButtonStatusResponseType;
import urn.ebay.api.PayPalAPI.BMSetInventoryReq;
import urn.ebay.api.PayPalAPI.BMSetInventoryRequestType;
import urn.ebay.api.PayPalAPI.BMSetInventoryResponseType;
import urn.ebay.api.PayPalAPI.BMUpdateButtonReq;
import urn.ebay.api.PayPalAPI.BMUpdateButtonRequestType;
import urn.ebay.api.PayPalAPI.BMUpdateButtonResponseType;
import urn.ebay.api.PayPalAPI.InstallmentDetailsType;
import urn.ebay.api.PayPalAPI.OptionDetailsType;
import urn.ebay.api.PayPalAPI.OptionSelectionDetailsType;
import urn.ebay.api.PayPalAPI.PayPalAPIInterfaceServiceService;
import urn.ebay.apis.eBLBaseComponents.BillingPeriodType;
import urn.ebay.apis.eBLBaseComponents.ButtonCodeType;
import urn.ebay.apis.eBLBaseComponents.ButtonSearchResultType;
import urn.ebay.apis.eBLBaseComponents.ButtonStatusType;
import urn.ebay.apis.eBLBaseComponents.ButtonTypeType;
import urn.ebay.apis.eBLBaseComponents.ItemTrackingDetailsType;
import urn.ebay.apis.eBLBaseComponents.OptionTypeListType;
import com.paypal.exception.ClientActionRequiredException;
import com.paypal.exception.HttpErrorException;
import com.paypal.exception.InvalidCredentialException;
import com.paypal.exception.InvalidResponseDataException;
import com.paypal.exception.MissingCredentialException;
import com.paypal.exception.SSLConfigurationException;
import com.paypal.sdk.exceptions.OAuthException;
public class ButtonManagerServlet extends HttpServlet {
private static final long serialVersionUID = 12345456723541232L;
public ButtonManagerServlet() {
super();
}
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
if (req.getRequestURI().contains("BMCreateButton"))
getServletConfig().getServletContext()
.getRequestDispatcher("/ButtonManager/BMCreateButton.jsp")
.forward(req, res);
else if (req.getRequestURI().contains("BMUpdateButton"))
getServletConfig().getServletContext()
.getRequestDispatcher("/ButtonManager/BMUpdateButton.jsp")
.forward(req, res);
else if (req.getRequestURI().contains("BMButtonSearch"))
getServletConfig().getServletContext()
.getRequestDispatcher("/ButtonManager/BMButtonSearch.jsp")
.forward(req, res);
else if (req.getRequestURI().contains("BMGetButtonDetails"))
getServletConfig()
.getServletContext()
.getRequestDispatcher(
"/ButtonManager/BMGetButtonDetails.jsp")
.forward(req, res);
else if (req.getRequestURI().contains("BMManageButtonStatus"))
getServletConfig()
.getServletContext()
.getRequestDispatcher(
"/ButtonManager/BMManageButtonStatus.jsp")
.forward(req, res);
else if (req.getRequestURI().contains("BMGetInventory"))
getServletConfig().getServletContext()
.getRequestDispatcher("/ButtonManager/BMGetInventory.jsp")
.forward(req, res);
else if (req.getRequestURI().contains("BMSetInventory"))
getServletConfig().getServletContext()
.getRequestDispatcher("/ButtonManager/BMSetInventory.jsp")
.forward(req, res);
}
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession();
session.setAttribute("url", req.getRequestURI());
session.setAttribute(
"relatedUrl",
"<ul><li><a href='BM/BMCreateButton'>BMCreateButton</a></li><li><a href='BM/BMUpdateButton'>BMUpdateButton</a></li><li><a href='BM/BMButtonSearch'>BMButtonSearch</a></li><li><a href='BM/BMGetButtonDetails'>BMGetButtonDetails</a></li><li><a href='BM/BMManageButtonStatus'>BMManageButtonStatus</a></li><li><a href='BM/BMSetInventory'>BMSetInventory</a></li><li><a href='BM/BMGetInventory'>BMGetInventory</a></li></ul>");
res.setContentType("text/html");
try {
PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(
this.getServletContext().getRealPath("/")
+ "/WEB-INF/sdk_config.properties");
if (req.getRequestURI().contains("BMCreateButton")) {
BMCreateButtonReq request = new BMCreateButtonReq();
BMCreateButtonRequestType reqType = new BMCreateButtonRequestType();
reqType.setButtonType(ButtonTypeType.fromValue(req
.getParameter("buttonType")));
reqType.setButtonCode(ButtonCodeType.fromValue(req
.getParameter("buttonCode")));
List<String> lst = new ArrayList<String>();
lst.add("item_name=" + req.getParameter("itemName"));
lst.add("return=" + req.getParameter("returnURL"));
lst.add("business=" + req.getParameter("businessMail"));
lst.add("amount=" + req.getParameter("amt"));
reqType.setButtonVar(lst);
// Construct the request values according to the Button Type and
// Button Code. To know more about that
if (req.getParameter("buttonType").equalsIgnoreCase(
"PAYMENTPLAN")) {
OptionSelectionDetailsType detailsType = new OptionSelectionDetailsType(
"CreateButton");
List<InstallmentDetailsType> insList = new ArrayList<InstallmentDetailsType>();
InstallmentDetailsType insType = new InstallmentDetailsType();
insType.setTotalBillingCycles(Integer.parseInt(req
.getParameter("billingCycles")));
insType.setAmount(req.getParameter("installmentAmt"));
insType.setBillingFrequency(Integer.parseInt(req
.getParameter("billingFreq")));
insType.setBillingPeriod(BillingPeriodType.fromValue(req
.getParameter("billingPeriod")));
insList.add(insType);
detailsType.setOptionType(OptionTypeListType.fromValue(req
.getParameter("optionType")));
detailsType.setPaymentPeriod(insList);
OptionDetailsType optType = new OptionDetailsType(
"CreateButton");
List<OptionSelectionDetailsType> optSelectList = new ArrayList<OptionSelectionDetailsType>();
optSelectList.add(detailsType);
List<OptionDetailsType> optList = new ArrayList<OptionDetailsType>();
optType.setOptionSelectionDetails(optSelectList);
optList.add(optType);
reqType.setOptionDetails(optList);
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"AUTOBILLING")) {
- lst.add("min_amount=" + req.getParameter("minAmount"));
+ lst.add("min_amount=" + req.getParameter("minAmt"));
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"GIFTCERTIFICATE")) {
lst.add("shopping_url=" + req.getParameter("shoppingUrl"));
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"PAYMENT")) {
lst.add("subtotal=" + req.getParameter("subTotal"));
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"SUBSCRIBE")) {
lst.add("a3=" + req.getParameter("subAmt"));
lst.add("p3=" + req.getParameter("subPeriod"));
lst.add("t3=" + req.getParameter("subInterval"));
}
request.setBMCreateButtonRequest(reqType);
BMCreateButtonResponseType resp = service
.bMCreateButton(request);
if (resp != null) {
session.setAttribute("lastReq", service.getLastRequest());
session.setAttribute("lastResp", service.getLastResponse());
if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
map.put("Ack", resp.getAck());
map.put("Hosted Button ID", resp.getHostedButtonID());
session.setAttribute("map", map);
res.sendRedirect("/buttonmanager-sample/Response.jsp");
} else {
session.setAttribute("Error", resp.getErrors());
res.sendRedirect("/buttonmanager-sample/Error.jsp");
}
}
} else if (req.getRequestURI().contains("BMUpdateButton")) {
BMUpdateButtonReq request = new BMUpdateButtonReq();
BMUpdateButtonRequestType reqType = new BMUpdateButtonRequestType();
reqType.setButtonType(ButtonTypeType.fromValue(req
.getParameter("buttonType")));
reqType.setButtonCode(ButtonCodeType.fromValue(req
.getParameter("buttonCode")));
List<String> lst = new ArrayList<String>();
lst.add("item_name=Widget");
lst.add("return=" + req.getParameter("returnURL"));
lst.add("[email protected]");
reqType.setButtonVar(lst);
// Construct the request values according to the Button Type and
// Button Code
if (req.getParameter("buttonType").equalsIgnoreCase(
"PAYMENTPLAN")) {
OptionSelectionDetailsType detailsType = new OptionSelectionDetailsType(
"CreateButton");
List<InstallmentDetailsType> insList = new ArrayList<InstallmentDetailsType>();
InstallmentDetailsType insType = new InstallmentDetailsType();
insType.setTotalBillingCycles(3);
insType.setAmount("2.00");
insType.setBillingFrequency(2);
insType.setBillingPeriod(BillingPeriodType.MONTH);
insList.add(insType);
detailsType.setOptionType(OptionTypeListType.EMI);
detailsType.setPaymentPeriod(insList);
OptionDetailsType optType = new OptionDetailsType(
"CreateButton");
List<OptionSelectionDetailsType> optSelectList = new ArrayList<OptionSelectionDetailsType>();
optSelectList.add(detailsType);
List<OptionDetailsType> optList = new ArrayList<OptionDetailsType>();
optType.setOptionSelectionDetails(optSelectList);
optList.add(optType);
reqType.setOptionDetails(optList);
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"AUTOBILLING")) {
lst.add("min_amount=4.00");
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"GIFTCERTIFICATE")) {
lst.add("shopping_url=http://www.ebay.com");
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"PAYMENT")) {
lst.add("subtotal=2.00");
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"SUBSCRIBE")) {
lst.add("a3=2.00");
lst.add("p3=3");
lst.add("t3=W");
}
reqType.setHostedButtonID(req.getParameter("hostedID"));
request.setBMUpdateButtonRequest(reqType);
BMUpdateButtonResponseType resp = service
.bMUpdateButton(request);
if (resp != null) {
session.setAttribute("lastReq", service.getLastRequest());
session.setAttribute("lastResp", service.getLastResponse());
if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
map.put("Ack", resp.getAck());
map.put("Hosted Button ID", resp.getHostedButtonID());
session.setAttribute("map", map);
res.sendRedirect("/buttonmanager-sample/Response.jsp");
} else {
session.setAttribute("Error", resp.getErrors());
res.sendRedirect("/buttonmanager-sample/Error.jsp");
}
}
} else if (req.getRequestURI().contains("BMButtonSearch")) {
BMButtonSearchReq request = new BMButtonSearchReq();
BMButtonSearchRequestType reqType = new BMButtonSearchRequestType();
reqType.setStartDate(req.getParameter("startDate")
+ "T00:00:00.000Z");
reqType.setEndDate(req.getParameter("endDate")
+ "T23:59:59.000Z");
request.setBMButtonSearchRequest(reqType);
BMButtonSearchResponseType resp = service
.bMButtonSearch(request);
if (resp != null) {
session.setAttribute("lastReq", service.getLastRequest());
session.setAttribute("lastResp", service.getLastResponse());
if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
map.put("Ack", resp.getAck());
Iterator<ButtonSearchResultType> iterator = resp
.getButtonSearchResult().iterator();
while (iterator.hasNext()) {
ButtonSearchResultType result = (ButtonSearchResultType) iterator
.next();
map.put("ButtonType", result.getButtonType());
map.put("Hosted Button ID",
result.getHostedButtonID());
map.put("Item Name", result.getItemName());
}
session.setAttribute("map", map);
res.sendRedirect("/buttonmanager-sample/Response.jsp");
} else {
session.setAttribute("Error", resp.getErrors());
res.sendRedirect("/buttonmanager-sample/Error.jsp");
}
}
} else if (req.getRequestURI().contains("BMGetButtonDetails")) {
BMGetButtonDetailsReq request = new BMGetButtonDetailsReq();
BMGetButtonDetailsRequestType reqType = new BMGetButtonDetailsRequestType();
reqType.setHostedButtonID(req.getParameter("hostedID"));
request.setBMGetButtonDetailsRequest(reqType);
BMGetButtonDetailsResponseType resp = service
.bMGetButtonDetails(request);
if (resp != null) {
session.setAttribute("lastReq", service.getLastRequest());
session.setAttribute("lastResp", service.getLastResponse());
if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
map.put("Ack", resp.getAck());
map.put("ButtonType", resp.getButtonType());
map.put("ButtonCode", resp.getButtonCode());
map.put("Website", resp.getWebsite());
session.setAttribute("map", map);
res.sendRedirect("/buttonmanager-sample/Response.jsp");
} else {
session.setAttribute("Error", resp.getErrors());
res.sendRedirect("/buttonmanager-sample/Error.jsp");
}
}
} else if (req.getRequestURI().contains("BMManageButtonStatus")) {
BMManageButtonStatusReq request = new BMManageButtonStatusReq();
BMManageButtonStatusRequestType reqType = new BMManageButtonStatusRequestType();
reqType.setHostedButtonID(req.getParameter("hostedID"));
reqType.setButtonStatus(ButtonStatusType.fromValue(req
.getParameter("buttonStatus")));
request.setBMManageButtonStatusRequest(reqType);
BMManageButtonStatusResponseType resp = service
.bMManageButtonStatus(request);
if (resp != null) {
session.setAttribute("lastReq", service.getLastRequest());
session.setAttribute("lastResp", service.getLastResponse());
if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
map.put("Ack", resp.getAck());
session.setAttribute("map", map);
res.sendRedirect("/buttonmanager-sample/Response.jsp");
} else {
session.setAttribute("Error", resp.getErrors());
res.sendRedirect("/buttonmanager-sample/Error.jsp");
}
}
} else if (req.getRequestURI().contains("BMGetInventory")) {
BMGetInventoryReq request = new BMGetInventoryReq();
BMGetInventoryRequestType reqType = new BMGetInventoryRequestType();
reqType.setHostedButtonID(req.getParameter("hostedID"));
request.setBMGetInventoryRequest(reqType);
BMGetInventoryResponseType resp = service
.bMGetInventory(request);
if (resp != null) {
if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
session.setAttribute("lastReq",
service.getLastRequest());
session.setAttribute("lastResp",
service.getLastResponse());
if (resp.getAck().toString()
.equalsIgnoreCase("SUCCESS")) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
map.put("Ack", resp.getAck());
map.put("TrackInv", resp.getTrackInv());
map.put("TrackPnl", resp.getTrackPnl());
map.put("Hosted Button ID",
resp.getHostedButtonID());
map.put("Item Cost", resp.getItemTrackingDetails()
.getItemCost());
map.put("Item Quantity", resp
.getItemTrackingDetails().getItemQty());
session.setAttribute("map", map);
res.sendRedirect("/buttonmanager-sample/Response.jsp");
}
} else {
session.setAttribute("Error", resp.getErrors());
res.sendRedirect("/buttonmanager-sample/Error.jsp");
}
}
} else if (req.getRequestURI().contains("BMSetInventory")) {
BMSetInventoryReq request = new BMSetInventoryReq();
BMSetInventoryRequestType reqType = new BMSetInventoryRequestType();
reqType.setVersion("82");
reqType.setHostedButtonID(req.getParameter("hostedID"));
reqType.setTrackInv(req.getParameter("trackInv"));
reqType.setTrackPnl(req.getParameter("trackPnl"));
ItemTrackingDetailsType itemTrackDetails = new ItemTrackingDetailsType();
itemTrackDetails.setItemQty(req.getParameter("itemQty"));
itemTrackDetails.setItemCost(req.getParameter("itemCost"));
reqType.setItemTrackingDetails(itemTrackDetails);
request.setBMSetInventoryRequest(reqType);
BMSetInventoryResponseType resp = service
.bMSetInventory(request);
res.setContentType("text/html");
if (resp != null) {
session.setAttribute("lastReq", service.getLastRequest());
session.setAttribute("lastResp", service.getLastResponse());
if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
map.put("Ack", resp.getAck());
session.setAttribute("map", map);
res.sendRedirect("/buttonmanager-sample/Response.jsp");
} else {
session.setAttribute("Error", resp.getErrors());
res.sendRedirect("/buttonmanager-sample/Error.jsp");
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SSLConfigurationException e) {
e.printStackTrace();
} catch (InvalidCredentialException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (HttpErrorException e) {
e.printStackTrace();
} catch (InvalidResponseDataException e) {
e.printStackTrace();
} catch (ClientActionRequiredException e) {
e.printStackTrace();
} catch (MissingCredentialException e) {
e.printStackTrace();
} catch (OAuthException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| true | true | protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession();
session.setAttribute("url", req.getRequestURI());
session.setAttribute(
"relatedUrl",
"<ul><li><a href='BM/BMCreateButton'>BMCreateButton</a></li><li><a href='BM/BMUpdateButton'>BMUpdateButton</a></li><li><a href='BM/BMButtonSearch'>BMButtonSearch</a></li><li><a href='BM/BMGetButtonDetails'>BMGetButtonDetails</a></li><li><a href='BM/BMManageButtonStatus'>BMManageButtonStatus</a></li><li><a href='BM/BMSetInventory'>BMSetInventory</a></li><li><a href='BM/BMGetInventory'>BMGetInventory</a></li></ul>");
res.setContentType("text/html");
try {
PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(
this.getServletContext().getRealPath("/")
+ "/WEB-INF/sdk_config.properties");
if (req.getRequestURI().contains("BMCreateButton")) {
BMCreateButtonReq request = new BMCreateButtonReq();
BMCreateButtonRequestType reqType = new BMCreateButtonRequestType();
reqType.setButtonType(ButtonTypeType.fromValue(req
.getParameter("buttonType")));
reqType.setButtonCode(ButtonCodeType.fromValue(req
.getParameter("buttonCode")));
List<String> lst = new ArrayList<String>();
lst.add("item_name=" + req.getParameter("itemName"));
lst.add("return=" + req.getParameter("returnURL"));
lst.add("business=" + req.getParameter("businessMail"));
lst.add("amount=" + req.getParameter("amt"));
reqType.setButtonVar(lst);
// Construct the request values according to the Button Type and
// Button Code. To know more about that
if (req.getParameter("buttonType").equalsIgnoreCase(
"PAYMENTPLAN")) {
OptionSelectionDetailsType detailsType = new OptionSelectionDetailsType(
"CreateButton");
List<InstallmentDetailsType> insList = new ArrayList<InstallmentDetailsType>();
InstallmentDetailsType insType = new InstallmentDetailsType();
insType.setTotalBillingCycles(Integer.parseInt(req
.getParameter("billingCycles")));
insType.setAmount(req.getParameter("installmentAmt"));
insType.setBillingFrequency(Integer.parseInt(req
.getParameter("billingFreq")));
insType.setBillingPeriod(BillingPeriodType.fromValue(req
.getParameter("billingPeriod")));
insList.add(insType);
detailsType.setOptionType(OptionTypeListType.fromValue(req
.getParameter("optionType")));
detailsType.setPaymentPeriod(insList);
OptionDetailsType optType = new OptionDetailsType(
"CreateButton");
List<OptionSelectionDetailsType> optSelectList = new ArrayList<OptionSelectionDetailsType>();
optSelectList.add(detailsType);
List<OptionDetailsType> optList = new ArrayList<OptionDetailsType>();
optType.setOptionSelectionDetails(optSelectList);
optList.add(optType);
reqType.setOptionDetails(optList);
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"AUTOBILLING")) {
lst.add("min_amount=" + req.getParameter("minAmount"));
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"GIFTCERTIFICATE")) {
lst.add("shopping_url=" + req.getParameter("shoppingUrl"));
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"PAYMENT")) {
lst.add("subtotal=" + req.getParameter("subTotal"));
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"SUBSCRIBE")) {
lst.add("a3=" + req.getParameter("subAmt"));
lst.add("p3=" + req.getParameter("subPeriod"));
lst.add("t3=" + req.getParameter("subInterval"));
}
request.setBMCreateButtonRequest(reqType);
BMCreateButtonResponseType resp = service
.bMCreateButton(request);
if (resp != null) {
session.setAttribute("lastReq", service.getLastRequest());
session.setAttribute("lastResp", service.getLastResponse());
if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
map.put("Ack", resp.getAck());
map.put("Hosted Button ID", resp.getHostedButtonID());
session.setAttribute("map", map);
res.sendRedirect("/buttonmanager-sample/Response.jsp");
} else {
session.setAttribute("Error", resp.getErrors());
res.sendRedirect("/buttonmanager-sample/Error.jsp");
}
}
} else if (req.getRequestURI().contains("BMUpdateButton")) {
BMUpdateButtonReq request = new BMUpdateButtonReq();
BMUpdateButtonRequestType reqType = new BMUpdateButtonRequestType();
reqType.setButtonType(ButtonTypeType.fromValue(req
.getParameter("buttonType")));
reqType.setButtonCode(ButtonCodeType.fromValue(req
.getParameter("buttonCode")));
List<String> lst = new ArrayList<String>();
lst.add("item_name=Widget");
lst.add("return=" + req.getParameter("returnURL"));
lst.add("[email protected]");
reqType.setButtonVar(lst);
// Construct the request values according to the Button Type and
// Button Code
if (req.getParameter("buttonType").equalsIgnoreCase(
"PAYMENTPLAN")) {
OptionSelectionDetailsType detailsType = new OptionSelectionDetailsType(
"CreateButton");
List<InstallmentDetailsType> insList = new ArrayList<InstallmentDetailsType>();
InstallmentDetailsType insType = new InstallmentDetailsType();
insType.setTotalBillingCycles(3);
insType.setAmount("2.00");
insType.setBillingFrequency(2);
insType.setBillingPeriod(BillingPeriodType.MONTH);
insList.add(insType);
detailsType.setOptionType(OptionTypeListType.EMI);
detailsType.setPaymentPeriod(insList);
OptionDetailsType optType = new OptionDetailsType(
"CreateButton");
List<OptionSelectionDetailsType> optSelectList = new ArrayList<OptionSelectionDetailsType>();
optSelectList.add(detailsType);
List<OptionDetailsType> optList = new ArrayList<OptionDetailsType>();
optType.setOptionSelectionDetails(optSelectList);
optList.add(optType);
reqType.setOptionDetails(optList);
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"AUTOBILLING")) {
lst.add("min_amount=4.00");
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"GIFTCERTIFICATE")) {
lst.add("shopping_url=http://www.ebay.com");
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"PAYMENT")) {
lst.add("subtotal=2.00");
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"SUBSCRIBE")) {
lst.add("a3=2.00");
lst.add("p3=3");
lst.add("t3=W");
}
reqType.setHostedButtonID(req.getParameter("hostedID"));
request.setBMUpdateButtonRequest(reqType);
BMUpdateButtonResponseType resp = service
.bMUpdateButton(request);
if (resp != null) {
session.setAttribute("lastReq", service.getLastRequest());
session.setAttribute("lastResp", service.getLastResponse());
if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
map.put("Ack", resp.getAck());
map.put("Hosted Button ID", resp.getHostedButtonID());
session.setAttribute("map", map);
res.sendRedirect("/buttonmanager-sample/Response.jsp");
} else {
session.setAttribute("Error", resp.getErrors());
res.sendRedirect("/buttonmanager-sample/Error.jsp");
}
}
} else if (req.getRequestURI().contains("BMButtonSearch")) {
BMButtonSearchReq request = new BMButtonSearchReq();
BMButtonSearchRequestType reqType = new BMButtonSearchRequestType();
reqType.setStartDate(req.getParameter("startDate")
+ "T00:00:00.000Z");
reqType.setEndDate(req.getParameter("endDate")
+ "T23:59:59.000Z");
request.setBMButtonSearchRequest(reqType);
BMButtonSearchResponseType resp = service
.bMButtonSearch(request);
if (resp != null) {
session.setAttribute("lastReq", service.getLastRequest());
session.setAttribute("lastResp", service.getLastResponse());
if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
map.put("Ack", resp.getAck());
Iterator<ButtonSearchResultType> iterator = resp
.getButtonSearchResult().iterator();
while (iterator.hasNext()) {
ButtonSearchResultType result = (ButtonSearchResultType) iterator
.next();
map.put("ButtonType", result.getButtonType());
map.put("Hosted Button ID",
result.getHostedButtonID());
map.put("Item Name", result.getItemName());
}
session.setAttribute("map", map);
res.sendRedirect("/buttonmanager-sample/Response.jsp");
} else {
session.setAttribute("Error", resp.getErrors());
res.sendRedirect("/buttonmanager-sample/Error.jsp");
}
}
} else if (req.getRequestURI().contains("BMGetButtonDetails")) {
BMGetButtonDetailsReq request = new BMGetButtonDetailsReq();
BMGetButtonDetailsRequestType reqType = new BMGetButtonDetailsRequestType();
reqType.setHostedButtonID(req.getParameter("hostedID"));
request.setBMGetButtonDetailsRequest(reqType);
BMGetButtonDetailsResponseType resp = service
.bMGetButtonDetails(request);
if (resp != null) {
session.setAttribute("lastReq", service.getLastRequest());
session.setAttribute("lastResp", service.getLastResponse());
if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
map.put("Ack", resp.getAck());
map.put("ButtonType", resp.getButtonType());
map.put("ButtonCode", resp.getButtonCode());
map.put("Website", resp.getWebsite());
session.setAttribute("map", map);
res.sendRedirect("/buttonmanager-sample/Response.jsp");
} else {
session.setAttribute("Error", resp.getErrors());
res.sendRedirect("/buttonmanager-sample/Error.jsp");
}
}
} else if (req.getRequestURI().contains("BMManageButtonStatus")) {
BMManageButtonStatusReq request = new BMManageButtonStatusReq();
BMManageButtonStatusRequestType reqType = new BMManageButtonStatusRequestType();
reqType.setHostedButtonID(req.getParameter("hostedID"));
reqType.setButtonStatus(ButtonStatusType.fromValue(req
.getParameter("buttonStatus")));
request.setBMManageButtonStatusRequest(reqType);
BMManageButtonStatusResponseType resp = service
.bMManageButtonStatus(request);
if (resp != null) {
session.setAttribute("lastReq", service.getLastRequest());
session.setAttribute("lastResp", service.getLastResponse());
if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
map.put("Ack", resp.getAck());
session.setAttribute("map", map);
res.sendRedirect("/buttonmanager-sample/Response.jsp");
} else {
session.setAttribute("Error", resp.getErrors());
res.sendRedirect("/buttonmanager-sample/Error.jsp");
}
}
} else if (req.getRequestURI().contains("BMGetInventory")) {
BMGetInventoryReq request = new BMGetInventoryReq();
BMGetInventoryRequestType reqType = new BMGetInventoryRequestType();
reqType.setHostedButtonID(req.getParameter("hostedID"));
request.setBMGetInventoryRequest(reqType);
BMGetInventoryResponseType resp = service
.bMGetInventory(request);
if (resp != null) {
if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
session.setAttribute("lastReq",
service.getLastRequest());
session.setAttribute("lastResp",
service.getLastResponse());
if (resp.getAck().toString()
.equalsIgnoreCase("SUCCESS")) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
map.put("Ack", resp.getAck());
map.put("TrackInv", resp.getTrackInv());
map.put("TrackPnl", resp.getTrackPnl());
map.put("Hosted Button ID",
resp.getHostedButtonID());
map.put("Item Cost", resp.getItemTrackingDetails()
.getItemCost());
map.put("Item Quantity", resp
.getItemTrackingDetails().getItemQty());
session.setAttribute("map", map);
res.sendRedirect("/buttonmanager-sample/Response.jsp");
}
} else {
session.setAttribute("Error", resp.getErrors());
res.sendRedirect("/buttonmanager-sample/Error.jsp");
}
}
} else if (req.getRequestURI().contains("BMSetInventory")) {
BMSetInventoryReq request = new BMSetInventoryReq();
BMSetInventoryRequestType reqType = new BMSetInventoryRequestType();
reqType.setVersion("82");
reqType.setHostedButtonID(req.getParameter("hostedID"));
reqType.setTrackInv(req.getParameter("trackInv"));
reqType.setTrackPnl(req.getParameter("trackPnl"));
ItemTrackingDetailsType itemTrackDetails = new ItemTrackingDetailsType();
itemTrackDetails.setItemQty(req.getParameter("itemQty"));
itemTrackDetails.setItemCost(req.getParameter("itemCost"));
reqType.setItemTrackingDetails(itemTrackDetails);
request.setBMSetInventoryRequest(reqType);
BMSetInventoryResponseType resp = service
.bMSetInventory(request);
res.setContentType("text/html");
if (resp != null) {
session.setAttribute("lastReq", service.getLastRequest());
session.setAttribute("lastResp", service.getLastResponse());
if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
map.put("Ack", resp.getAck());
session.setAttribute("map", map);
res.sendRedirect("/buttonmanager-sample/Response.jsp");
} else {
session.setAttribute("Error", resp.getErrors());
res.sendRedirect("/buttonmanager-sample/Error.jsp");
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SSLConfigurationException e) {
e.printStackTrace();
} catch (InvalidCredentialException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (HttpErrorException e) {
e.printStackTrace();
} catch (InvalidResponseDataException e) {
e.printStackTrace();
} catch (ClientActionRequiredException e) {
e.printStackTrace();
} catch (MissingCredentialException e) {
e.printStackTrace();
} catch (OAuthException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
| protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession();
session.setAttribute("url", req.getRequestURI());
session.setAttribute(
"relatedUrl",
"<ul><li><a href='BM/BMCreateButton'>BMCreateButton</a></li><li><a href='BM/BMUpdateButton'>BMUpdateButton</a></li><li><a href='BM/BMButtonSearch'>BMButtonSearch</a></li><li><a href='BM/BMGetButtonDetails'>BMGetButtonDetails</a></li><li><a href='BM/BMManageButtonStatus'>BMManageButtonStatus</a></li><li><a href='BM/BMSetInventory'>BMSetInventory</a></li><li><a href='BM/BMGetInventory'>BMGetInventory</a></li></ul>");
res.setContentType("text/html");
try {
PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(
this.getServletContext().getRealPath("/")
+ "/WEB-INF/sdk_config.properties");
if (req.getRequestURI().contains("BMCreateButton")) {
BMCreateButtonReq request = new BMCreateButtonReq();
BMCreateButtonRequestType reqType = new BMCreateButtonRequestType();
reqType.setButtonType(ButtonTypeType.fromValue(req
.getParameter("buttonType")));
reqType.setButtonCode(ButtonCodeType.fromValue(req
.getParameter("buttonCode")));
List<String> lst = new ArrayList<String>();
lst.add("item_name=" + req.getParameter("itemName"));
lst.add("return=" + req.getParameter("returnURL"));
lst.add("business=" + req.getParameter("businessMail"));
lst.add("amount=" + req.getParameter("amt"));
reqType.setButtonVar(lst);
// Construct the request values according to the Button Type and
// Button Code. To know more about that
if (req.getParameter("buttonType").equalsIgnoreCase(
"PAYMENTPLAN")) {
OptionSelectionDetailsType detailsType = new OptionSelectionDetailsType(
"CreateButton");
List<InstallmentDetailsType> insList = new ArrayList<InstallmentDetailsType>();
InstallmentDetailsType insType = new InstallmentDetailsType();
insType.setTotalBillingCycles(Integer.parseInt(req
.getParameter("billingCycles")));
insType.setAmount(req.getParameter("installmentAmt"));
insType.setBillingFrequency(Integer.parseInt(req
.getParameter("billingFreq")));
insType.setBillingPeriod(BillingPeriodType.fromValue(req
.getParameter("billingPeriod")));
insList.add(insType);
detailsType.setOptionType(OptionTypeListType.fromValue(req
.getParameter("optionType")));
detailsType.setPaymentPeriod(insList);
OptionDetailsType optType = new OptionDetailsType(
"CreateButton");
List<OptionSelectionDetailsType> optSelectList = new ArrayList<OptionSelectionDetailsType>();
optSelectList.add(detailsType);
List<OptionDetailsType> optList = new ArrayList<OptionDetailsType>();
optType.setOptionSelectionDetails(optSelectList);
optList.add(optType);
reqType.setOptionDetails(optList);
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"AUTOBILLING")) {
lst.add("min_amount=" + req.getParameter("minAmt"));
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"GIFTCERTIFICATE")) {
lst.add("shopping_url=" + req.getParameter("shoppingUrl"));
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"PAYMENT")) {
lst.add("subtotal=" + req.getParameter("subTotal"));
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"SUBSCRIBE")) {
lst.add("a3=" + req.getParameter("subAmt"));
lst.add("p3=" + req.getParameter("subPeriod"));
lst.add("t3=" + req.getParameter("subInterval"));
}
request.setBMCreateButtonRequest(reqType);
BMCreateButtonResponseType resp = service
.bMCreateButton(request);
if (resp != null) {
session.setAttribute("lastReq", service.getLastRequest());
session.setAttribute("lastResp", service.getLastResponse());
if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
map.put("Ack", resp.getAck());
map.put("Hosted Button ID", resp.getHostedButtonID());
session.setAttribute("map", map);
res.sendRedirect("/buttonmanager-sample/Response.jsp");
} else {
session.setAttribute("Error", resp.getErrors());
res.sendRedirect("/buttonmanager-sample/Error.jsp");
}
}
} else if (req.getRequestURI().contains("BMUpdateButton")) {
BMUpdateButtonReq request = new BMUpdateButtonReq();
BMUpdateButtonRequestType reqType = new BMUpdateButtonRequestType();
reqType.setButtonType(ButtonTypeType.fromValue(req
.getParameter("buttonType")));
reqType.setButtonCode(ButtonCodeType.fromValue(req
.getParameter("buttonCode")));
List<String> lst = new ArrayList<String>();
lst.add("item_name=Widget");
lst.add("return=" + req.getParameter("returnURL"));
lst.add("[email protected]");
reqType.setButtonVar(lst);
// Construct the request values according to the Button Type and
// Button Code
if (req.getParameter("buttonType").equalsIgnoreCase(
"PAYMENTPLAN")) {
OptionSelectionDetailsType detailsType = new OptionSelectionDetailsType(
"CreateButton");
List<InstallmentDetailsType> insList = new ArrayList<InstallmentDetailsType>();
InstallmentDetailsType insType = new InstallmentDetailsType();
insType.setTotalBillingCycles(3);
insType.setAmount("2.00");
insType.setBillingFrequency(2);
insType.setBillingPeriod(BillingPeriodType.MONTH);
insList.add(insType);
detailsType.setOptionType(OptionTypeListType.EMI);
detailsType.setPaymentPeriod(insList);
OptionDetailsType optType = new OptionDetailsType(
"CreateButton");
List<OptionSelectionDetailsType> optSelectList = new ArrayList<OptionSelectionDetailsType>();
optSelectList.add(detailsType);
List<OptionDetailsType> optList = new ArrayList<OptionDetailsType>();
optType.setOptionSelectionDetails(optSelectList);
optList.add(optType);
reqType.setOptionDetails(optList);
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"AUTOBILLING")) {
lst.add("min_amount=4.00");
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"GIFTCERTIFICATE")) {
lst.add("shopping_url=http://www.ebay.com");
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"PAYMENT")) {
lst.add("subtotal=2.00");
} else if (req.getParameter("buttonType").equalsIgnoreCase(
"SUBSCRIBE")) {
lst.add("a3=2.00");
lst.add("p3=3");
lst.add("t3=W");
}
reqType.setHostedButtonID(req.getParameter("hostedID"));
request.setBMUpdateButtonRequest(reqType);
BMUpdateButtonResponseType resp = service
.bMUpdateButton(request);
if (resp != null) {
session.setAttribute("lastReq", service.getLastRequest());
session.setAttribute("lastResp", service.getLastResponse());
if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
map.put("Ack", resp.getAck());
map.put("Hosted Button ID", resp.getHostedButtonID());
session.setAttribute("map", map);
res.sendRedirect("/buttonmanager-sample/Response.jsp");
} else {
session.setAttribute("Error", resp.getErrors());
res.sendRedirect("/buttonmanager-sample/Error.jsp");
}
}
} else if (req.getRequestURI().contains("BMButtonSearch")) {
BMButtonSearchReq request = new BMButtonSearchReq();
BMButtonSearchRequestType reqType = new BMButtonSearchRequestType();
reqType.setStartDate(req.getParameter("startDate")
+ "T00:00:00.000Z");
reqType.setEndDate(req.getParameter("endDate")
+ "T23:59:59.000Z");
request.setBMButtonSearchRequest(reqType);
BMButtonSearchResponseType resp = service
.bMButtonSearch(request);
if (resp != null) {
session.setAttribute("lastReq", service.getLastRequest());
session.setAttribute("lastResp", service.getLastResponse());
if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
map.put("Ack", resp.getAck());
Iterator<ButtonSearchResultType> iterator = resp
.getButtonSearchResult().iterator();
while (iterator.hasNext()) {
ButtonSearchResultType result = (ButtonSearchResultType) iterator
.next();
map.put("ButtonType", result.getButtonType());
map.put("Hosted Button ID",
result.getHostedButtonID());
map.put("Item Name", result.getItemName());
}
session.setAttribute("map", map);
res.sendRedirect("/buttonmanager-sample/Response.jsp");
} else {
session.setAttribute("Error", resp.getErrors());
res.sendRedirect("/buttonmanager-sample/Error.jsp");
}
}
} else if (req.getRequestURI().contains("BMGetButtonDetails")) {
BMGetButtonDetailsReq request = new BMGetButtonDetailsReq();
BMGetButtonDetailsRequestType reqType = new BMGetButtonDetailsRequestType();
reqType.setHostedButtonID(req.getParameter("hostedID"));
request.setBMGetButtonDetailsRequest(reqType);
BMGetButtonDetailsResponseType resp = service
.bMGetButtonDetails(request);
if (resp != null) {
session.setAttribute("lastReq", service.getLastRequest());
session.setAttribute("lastResp", service.getLastResponse());
if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
map.put("Ack", resp.getAck());
map.put("ButtonType", resp.getButtonType());
map.put("ButtonCode", resp.getButtonCode());
map.put("Website", resp.getWebsite());
session.setAttribute("map", map);
res.sendRedirect("/buttonmanager-sample/Response.jsp");
} else {
session.setAttribute("Error", resp.getErrors());
res.sendRedirect("/buttonmanager-sample/Error.jsp");
}
}
} else if (req.getRequestURI().contains("BMManageButtonStatus")) {
BMManageButtonStatusReq request = new BMManageButtonStatusReq();
BMManageButtonStatusRequestType reqType = new BMManageButtonStatusRequestType();
reqType.setHostedButtonID(req.getParameter("hostedID"));
reqType.setButtonStatus(ButtonStatusType.fromValue(req
.getParameter("buttonStatus")));
request.setBMManageButtonStatusRequest(reqType);
BMManageButtonStatusResponseType resp = service
.bMManageButtonStatus(request);
if (resp != null) {
session.setAttribute("lastReq", service.getLastRequest());
session.setAttribute("lastResp", service.getLastResponse());
if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
map.put("Ack", resp.getAck());
session.setAttribute("map", map);
res.sendRedirect("/buttonmanager-sample/Response.jsp");
} else {
session.setAttribute("Error", resp.getErrors());
res.sendRedirect("/buttonmanager-sample/Error.jsp");
}
}
} else if (req.getRequestURI().contains("BMGetInventory")) {
BMGetInventoryReq request = new BMGetInventoryReq();
BMGetInventoryRequestType reqType = new BMGetInventoryRequestType();
reqType.setHostedButtonID(req.getParameter("hostedID"));
request.setBMGetInventoryRequest(reqType);
BMGetInventoryResponseType resp = service
.bMGetInventory(request);
if (resp != null) {
if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
session.setAttribute("lastReq",
service.getLastRequest());
session.setAttribute("lastResp",
service.getLastResponse());
if (resp.getAck().toString()
.equalsIgnoreCase("SUCCESS")) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
map.put("Ack", resp.getAck());
map.put("TrackInv", resp.getTrackInv());
map.put("TrackPnl", resp.getTrackPnl());
map.put("Hosted Button ID",
resp.getHostedButtonID());
map.put("Item Cost", resp.getItemTrackingDetails()
.getItemCost());
map.put("Item Quantity", resp
.getItemTrackingDetails().getItemQty());
session.setAttribute("map", map);
res.sendRedirect("/buttonmanager-sample/Response.jsp");
}
} else {
session.setAttribute("Error", resp.getErrors());
res.sendRedirect("/buttonmanager-sample/Error.jsp");
}
}
} else if (req.getRequestURI().contains("BMSetInventory")) {
BMSetInventoryReq request = new BMSetInventoryReq();
BMSetInventoryRequestType reqType = new BMSetInventoryRequestType();
reqType.setVersion("82");
reqType.setHostedButtonID(req.getParameter("hostedID"));
reqType.setTrackInv(req.getParameter("trackInv"));
reqType.setTrackPnl(req.getParameter("trackPnl"));
ItemTrackingDetailsType itemTrackDetails = new ItemTrackingDetailsType();
itemTrackDetails.setItemQty(req.getParameter("itemQty"));
itemTrackDetails.setItemCost(req.getParameter("itemCost"));
reqType.setItemTrackingDetails(itemTrackDetails);
request.setBMSetInventoryRequest(reqType);
BMSetInventoryResponseType resp = service
.bMSetInventory(request);
res.setContentType("text/html");
if (resp != null) {
session.setAttribute("lastReq", service.getLastRequest());
session.setAttribute("lastResp", service.getLastResponse());
if (resp.getAck().toString().equalsIgnoreCase("SUCCESS")) {
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
map.put("Ack", resp.getAck());
session.setAttribute("map", map);
res.sendRedirect("/buttonmanager-sample/Response.jsp");
} else {
session.setAttribute("Error", resp.getErrors());
res.sendRedirect("/buttonmanager-sample/Error.jsp");
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SSLConfigurationException e) {
e.printStackTrace();
} catch (InvalidCredentialException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (HttpErrorException e) {
e.printStackTrace();
} catch (InvalidResponseDataException e) {
e.printStackTrace();
} catch (ClientActionRequiredException e) {
e.printStackTrace();
} catch (MissingCredentialException e) {
e.printStackTrace();
} catch (OAuthException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
|
diff --git a/robocode.core/src/main/java/net/sf/robocode/host/RobotStatics.java b/robocode.core/src/main/java/net/sf/robocode/host/RobotStatics.java
index bae1293f7..c4692dd66 100644
--- a/robocode.core/src/main/java/net/sf/robocode/host/RobotStatics.java
+++ b/robocode.core/src/main/java/net/sf/robocode/host/RobotStatics.java
@@ -1,285 +1,285 @@
/*******************************************************************************
* Copyright (c) 2001, 2010 Mathew A. Nelson and Robocode contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://robocode.sourceforge.net/license/epl-v10.html
*
* Contributors:
* Pavel Savara
* - Initial implementation
*******************************************************************************/
package net.sf.robocode.host;
import net.sf.robocode.peer.IRobotStatics;
import net.sf.robocode.repository.IRobotRepositoryItem;
import net.sf.robocode.security.HiddenAccess;
import net.sf.robocode.serialization.ISerializableHelper;
import net.sf.robocode.serialization.RbSerializer;
import robocode.BattleRules;
import robocode.control.RobotSpecification;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
/**
* @author Pavel Savara (original)
*/
public final class RobotStatics implements IRobotStatics, Serializable {
private static final long serialVersionUID = 1L;
private final boolean isJuniorRobot;
private final boolean isInteractiveRobot;
private final boolean isPaintRobot;
private final boolean isAdvancedRobot;
private final boolean isTeamRobot;
private final boolean isTeamLeader;
private final boolean isDroid;
private final String name;
private final String shortName;
private final String veryShortName;
private final String fullClassName;
private final String shortClassName;
private final BattleRules battleRules;
private final String[] teammates;
private final String teamName;
private final int index;
private final int contestantIndex;
public RobotStatics(RobotSpecification robotSpecification, int duplicate, boolean isLeader, BattleRules rules, String teamName, List<String> teamMembers, int index, int contestantIndex) {
IRobotRepositoryItem specification = ((IRobotRepositoryItem) HiddenAccess.getFileSpecification(
robotSpecification));
shortClassName = specification.getShortClassName();
fullClassName = specification.getFullClassName();
if (duplicate >= 0) {
String countString = " (" + (duplicate + 1) + ')';
name = specification.getFullClassNameWithVersion() + countString;
shortName = specification.getUniqueShortClassNameWithVersion() + countString;
veryShortName = specification.getUniqueVeryShortClassNameWithVersion() + countString;
} else {
name = specification.getFullClassNameWithVersion();
shortName = specification.getUniqueShortClassNameWithVersion();
veryShortName = specification.getUniqueVeryShortClassNameWithVersion();
}
isJuniorRobot = specification.isJuniorRobot();
isInteractiveRobot = specification.isInteractiveRobot();
isPaintRobot = specification.isPaintRobot();
isAdvancedRobot = specification.isAdvancedRobot();
isTeamRobot = specification.isTeamRobot();
isDroid = specification.isDroid();
isTeamLeader = isLeader;
battleRules = rules;
this.index = index;
this.contestantIndex = contestantIndex;
if (teamMembers != null) {
- teammates = new String[teamMembers.size() - 1];
+ teammates = new String[teamMembers.size()];
int i = 0;
for (String mate : teamMembers) {
if (!name.equals(mate)) {
teammates[i++] = mate;
}
}
this.teamName = teamName;
} else {
teammates = null;
this.teamName = name;
}
}
RobotStatics(boolean isJuniorRobot, boolean isInteractiveRobot, boolean isPaintRobot, boolean isAdvancedRobot,
boolean isTeamRobot, boolean isTeamLeader, boolean isDroid, String name, String shortName,
String veryShortName, String fullClassName, String shortClassName, BattleRules battleRules,
String[] teammates, String teamName, int index, int contestantIndex) {
this.isJuniorRobot = isJuniorRobot;
this.isInteractiveRobot = isInteractiveRobot;
this.isPaintRobot = isPaintRobot;
this.isAdvancedRobot = isAdvancedRobot;
this.isTeamRobot = isTeamRobot;
this.isTeamLeader = isTeamLeader;
this.isDroid = isDroid;
this.name = name;
this.shortName = shortName;
this.veryShortName = veryShortName;
this.fullClassName = fullClassName;
this.shortClassName = shortClassName;
this.battleRules = battleRules;
this.teammates = teammates;
this.teamName = teamName;
this.index = index;
this.contestantIndex = contestantIndex;
}
public boolean isJuniorRobot() {
return isJuniorRobot;
}
public boolean isInteractiveRobot() {
return isInteractiveRobot;
}
public boolean isPaintRobot() {
return isPaintRobot;
}
public boolean isAdvancedRobot() {
return isAdvancedRobot;
}
public boolean isTeamRobot() {
return isTeamRobot;
}
public boolean isTeamLeader() {
return isTeamLeader;
}
public boolean isDroid() {
return isDroid;
}
public String getName() {
return name;
}
public String getShortName() {
return shortName;
}
public String getVeryShortName() {
return veryShortName;
}
public String getFullClassName() {
return fullClassName;
}
public String getShortClassName() {
return shortClassName;
}
public BattleRules getBattleRules() {
return battleRules;
}
public String[] getTeammates() {
return teammates == null ? null : teammates.clone();
}
public String getTeamName() {
return teamName;
}
public int getIndex() {
return index;
}
public int getContestIndex() {
return contestantIndex;
}
static ISerializableHelper createHiddenSerializer() {
return new SerializableHelper();
}
private static class SerializableHelper implements ISerializableHelper {
public int sizeOf(RbSerializer serializer, Object object) {
RobotStatics obj = (RobotStatics) object;
int size = RbSerializer.SIZEOF_TYPEINFO + RbSerializer.SIZEOF_BOOL * 7 + serializer.sizeOf(obj.name)
+ serializer.sizeOf(obj.shortName) + serializer.sizeOf(obj.veryShortName)
+ serializer.sizeOf(obj.fullClassName) + serializer.sizeOf(obj.shortClassName)
+ RbSerializer.SIZEOF_INT * 5 + RbSerializer.SIZEOF_DOUBLE + RbSerializer.SIZEOF_LONG;
if (obj.teammates != null) {
for (String mate : obj.teammates) {
size += serializer.sizeOf(mate);
}
}
size += RbSerializer.SIZEOF_INT;
size += serializer.sizeOf(obj.teamName);
return size;
}
public void serialize(RbSerializer serializer, ByteBuffer buffer, Object object) {
RobotStatics obj = (RobotStatics) object;
serializer.serialize(buffer, obj.isJuniorRobot);
serializer.serialize(buffer, obj.isInteractiveRobot);
serializer.serialize(buffer, obj.isPaintRobot);
serializer.serialize(buffer, obj.isAdvancedRobot);
serializer.serialize(buffer, obj.isTeamRobot);
serializer.serialize(buffer, obj.isTeamLeader);
serializer.serialize(buffer, obj.isDroid);
serializer.serialize(buffer, obj.name);
serializer.serialize(buffer, obj.shortName);
serializer.serialize(buffer, obj.veryShortName);
serializer.serialize(buffer, obj.fullClassName);
serializer.serialize(buffer, obj.shortClassName);
serializer.serialize(buffer, obj.battleRules.getBattlefieldWidth());
serializer.serialize(buffer, obj.battleRules.getBattlefieldHeight());
serializer.serialize(buffer, obj.battleRules.getNumRounds());
serializer.serialize(buffer, obj.battleRules.getGunCoolingRate());
serializer.serialize(buffer, obj.battleRules.getInactivityTime());
if (obj.teammates != null) {
for (String mate : obj.teammates) {
serializer.serialize(buffer, mate);
}
}
buffer.putInt(-1);
serializer.serialize(buffer, obj.teamName);
serializer.serialize(buffer, obj.index);
serializer.serialize(buffer, obj.contestantIndex);
}
public Object deserialize(RbSerializer serializer, ByteBuffer buffer) {
boolean isJuniorRobot = serializer.deserializeBoolean(buffer);
boolean isInteractiveRobot = serializer.deserializeBoolean(buffer);
boolean isPaintRobot = serializer.deserializeBoolean(buffer);
boolean isAdvancedRobot = serializer.deserializeBoolean(buffer);
boolean isTeamRobot = serializer.deserializeBoolean(buffer);
boolean isTeamLeader = serializer.deserializeBoolean(buffer);
boolean isDroid = serializer.deserializeBoolean(buffer);
String name = serializer.deserializeString(buffer);
String shortName = serializer.deserializeString(buffer);
String veryShortName = serializer.deserializeString(buffer);
String fullClassName = serializer.deserializeString(buffer);
String shortClassName = serializer.deserializeString(buffer);
BattleRules battleRules = HiddenAccess.createRules(serializer.deserializeInt(buffer),
serializer.deserializeInt(buffer), serializer.deserializeInt(buffer), serializer.deserializeDouble(buffer),
serializer.deserializeLong(buffer));
List<String> teammates = new ArrayList<String>();
Object item = serializer.deserializeString(buffer);
if (item == null) {
teammates = null;
}
while (item != null) {
if (item instanceof String) {
teammates.add((String) item);
}
item = serializer.deserializeString(buffer);
}
String teamName = serializer.deserializeString(buffer);
int index = serializer.deserializeInt(buffer);
int contestantIndex = serializer.deserializeInt(buffer);
return new RobotStatics(isJuniorRobot, isInteractiveRobot, isPaintRobot, isAdvancedRobot, isTeamRobot,
isTeamLeader, isDroid, name, shortName, veryShortName, fullClassName, shortClassName, battleRules,
teammates.toArray(new String[teammates.size()]), teamName, index, contestantIndex);
}
}
}
| true | true | public RobotStatics(RobotSpecification robotSpecification, int duplicate, boolean isLeader, BattleRules rules, String teamName, List<String> teamMembers, int index, int contestantIndex) {
IRobotRepositoryItem specification = ((IRobotRepositoryItem) HiddenAccess.getFileSpecification(
robotSpecification));
shortClassName = specification.getShortClassName();
fullClassName = specification.getFullClassName();
if (duplicate >= 0) {
String countString = " (" + (duplicate + 1) + ')';
name = specification.getFullClassNameWithVersion() + countString;
shortName = specification.getUniqueShortClassNameWithVersion() + countString;
veryShortName = specification.getUniqueVeryShortClassNameWithVersion() + countString;
} else {
name = specification.getFullClassNameWithVersion();
shortName = specification.getUniqueShortClassNameWithVersion();
veryShortName = specification.getUniqueVeryShortClassNameWithVersion();
}
isJuniorRobot = specification.isJuniorRobot();
isInteractiveRobot = specification.isInteractiveRobot();
isPaintRobot = specification.isPaintRobot();
isAdvancedRobot = specification.isAdvancedRobot();
isTeamRobot = specification.isTeamRobot();
isDroid = specification.isDroid();
isTeamLeader = isLeader;
battleRules = rules;
this.index = index;
this.contestantIndex = contestantIndex;
if (teamMembers != null) {
teammates = new String[teamMembers.size() - 1];
int i = 0;
for (String mate : teamMembers) {
if (!name.equals(mate)) {
teammates[i++] = mate;
}
}
this.teamName = teamName;
} else {
teammates = null;
this.teamName = name;
}
}
| public RobotStatics(RobotSpecification robotSpecification, int duplicate, boolean isLeader, BattleRules rules, String teamName, List<String> teamMembers, int index, int contestantIndex) {
IRobotRepositoryItem specification = ((IRobotRepositoryItem) HiddenAccess.getFileSpecification(
robotSpecification));
shortClassName = specification.getShortClassName();
fullClassName = specification.getFullClassName();
if (duplicate >= 0) {
String countString = " (" + (duplicate + 1) + ')';
name = specification.getFullClassNameWithVersion() + countString;
shortName = specification.getUniqueShortClassNameWithVersion() + countString;
veryShortName = specification.getUniqueVeryShortClassNameWithVersion() + countString;
} else {
name = specification.getFullClassNameWithVersion();
shortName = specification.getUniqueShortClassNameWithVersion();
veryShortName = specification.getUniqueVeryShortClassNameWithVersion();
}
isJuniorRobot = specification.isJuniorRobot();
isInteractiveRobot = specification.isInteractiveRobot();
isPaintRobot = specification.isPaintRobot();
isAdvancedRobot = specification.isAdvancedRobot();
isTeamRobot = specification.isTeamRobot();
isDroid = specification.isDroid();
isTeamLeader = isLeader;
battleRules = rules;
this.index = index;
this.contestantIndex = contestantIndex;
if (teamMembers != null) {
teammates = new String[teamMembers.size()];
int i = 0;
for (String mate : teamMembers) {
if (!name.equals(mate)) {
teammates[i++] = mate;
}
}
this.teamName = teamName;
} else {
teammates = null;
this.teamName = name;
}
}
|
diff --git a/src/com/android/providers/downloads/StorageManager.java b/src/com/android/providers/downloads/StorageManager.java
index 228f668..2766860 100644
--- a/src/com/android/providers/downloads/StorageManager.java
+++ b/src/com/android/providers/downloads/StorageManager.java
@@ -1,466 +1,467 @@
/*
* 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.providers.downloads;
import android.content.ContentUris;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.provider.Downloads;
import android.text.TextUtils;
import android.util.Log;
import com.android.internal.R;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Manages the storage space consumed by Downloads Data dir. When space falls below
* a threshold limit (set in resource xml files), starts cleanup of the Downloads data dir
* to free up space.
*/
class StorageManager {
/** the max amount of space allowed to be taken up by the downloads data dir */
private static final long sMaxdownloadDataDirSize =
Resources.getSystem().getInteger(R.integer.config_downloadDataDirSize) * 1024 * 1024;
/** threshold (in bytes) beyond which the low space warning kicks in and attempt is made to
* purge some downloaded files to make space
*/
private static final long sDownloadDataDirLowSpaceThreshold =
Resources.getSystem().getInteger(
R.integer.config_downloadDataDirLowSpaceThreshold)
* sMaxdownloadDataDirSize / 100;
/** see {@link Environment#getExternalStorageDirectory()} */
private final File mExternalStorageDir;
/** see {@link Environment#getDownloadCacheDirectory()} */
private final File mSystemCacheDir;
/** The downloaded files are saved to this dir. it is the value returned by
* {@link Context#getCacheDir()}.
*/
private final File mDownloadDataDir;
/** the Singleton instance of this class.
* TODO: once DownloadService is refactored into a long-living object, there is no need
* for this Singleton'ing.
*/
private static StorageManager sSingleton = null;
/** how often do we need to perform checks on space to make sure space is available */
private static final int FREQUENCY_OF_CHECKS_ON_SPACE_AVAILABILITY = 1024 * 1024; // 1MB
private int mBytesDownloadedSinceLastCheckOnSpace = 0;
/** misc members */
private final Context mContext;
/**
* maintains Singleton instance of this class
*/
synchronized static StorageManager getInstance(Context context) {
if (sSingleton == null) {
sSingleton = new StorageManager(context);
}
return sSingleton;
}
private StorageManager(Context context) { // constructor is private
mContext = context;
mDownloadDataDir = context.getCacheDir();
mExternalStorageDir = Environment.getExternalStorageDirectory();
mSystemCacheDir = Environment.getDownloadCacheDirectory();
startThreadToCleanupDatabaseAndPurgeFileSystem();
}
/** How often should database and filesystem be cleaned up to remove spurious files
* from the file system and
* The value is specified in terms of num of downloads since last time the cleanup was done.
*/
private static final int FREQUENCY_OF_DATABASE_N_FILESYSTEM_CLEANUP = 250;
private int mNumDownloadsSoFar = 0;
synchronized void incrementNumDownloadsSoFar() {
if (++mNumDownloadsSoFar % FREQUENCY_OF_DATABASE_N_FILESYSTEM_CLEANUP == 0) {
startThreadToCleanupDatabaseAndPurgeFileSystem();
}
}
/* start a thread to cleanup the following
* remove spurious files from the file system
* remove excess entries from the database
*/
private Thread mCleanupThread = null;
private synchronized void startThreadToCleanupDatabaseAndPurgeFileSystem() {
if (mCleanupThread != null && mCleanupThread.isAlive()) {
return;
}
mCleanupThread = new Thread() {
@Override public void run() {
removeSpuriousFiles();
trimDatabase();
}
};
mCleanupThread.start();
}
void verifySpaceBeforeWritingToFile(int destination, String path, long length)
throws StopRequestException {
// do this check only once for every 1MB of downloaded data
if (incrementBytesDownloadedSinceLastCheckOnSpace(length) <
FREQUENCY_OF_CHECKS_ON_SPACE_AVAILABILITY) {
return;
}
verifySpace(destination, path, length);
}
void verifySpace(int destination, String path, long length) throws StopRequestException {
resetBytesDownloadedSinceLastCheckOnSpace();
File dir = null;
if (Constants.LOGV) {
Log.i(Constants.TAG, "in verifySpace, destination: " + destination +
", path: " + path + ", length: " + length);
}
if (path == null) {
throw new IllegalArgumentException("path can't be null");
}
switch (destination) {
case Downloads.Impl.DESTINATION_CACHE_PARTITION:
case Downloads.Impl.DESTINATION_CACHE_PARTITION_NOROAMING:
case Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE:
dir = mDownloadDataDir;
break;
case Downloads.Impl.DESTINATION_EXTERNAL:
dir = mExternalStorageDir;
break;
case Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION:
dir = mSystemCacheDir;
break;
case Downloads.Impl.DESTINATION_FILE_URI:
if (path.startsWith(mExternalStorageDir.getPath())) {
dir = mExternalStorageDir;
} else if (path.startsWith(mDownloadDataDir.getPath())) {
dir = mDownloadDataDir;
} else if (path.startsWith(mSystemCacheDir.getPath())) {
dir = mSystemCacheDir;
}
break;
}
if (dir == null) {
throw new IllegalStateException("invalid combination of destination: " + destination +
", path: " + path);
}
findSpace(dir, length, destination);
}
/**
* finds space in the given filesystem (input param: root) to accommodate # of bytes
* specified by the input param(targetBytes).
* returns true if found. false otherwise.
*/
private synchronized void findSpace(File root, long targetBytes, int destination)
throws StopRequestException {
if (targetBytes == 0) {
return;
}
if (destination == Downloads.Impl.DESTINATION_FILE_URI ||
destination == Downloads.Impl.DESTINATION_EXTERNAL) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
throw new StopRequestException(Downloads.Impl.STATUS_DEVICE_NOT_FOUND_ERROR,
"external media not mounted");
}
}
// is there enough space in the file system of the given param 'root'.
long bytesAvailable = getAvailableBytesInFileSystemAtGivenRoot(root);
if (bytesAvailable < sDownloadDataDirLowSpaceThreshold) {
/* filesystem's available space is below threshold for low space warning.
* threshold typically is 10% of download data dir space quota.
* try to cleanup and see if the low space situation goes away.
*/
discardPurgeableFiles(destination, sDownloadDataDirLowSpaceThreshold);
removeSpuriousFiles();
bytesAvailable = getAvailableBytesInFileSystemAtGivenRoot(root);
if (bytesAvailable < sDownloadDataDirLowSpaceThreshold) {
/*
* available space is still below the threshold limit.
*
* If this is system cache dir, print a warning.
* otherwise, don't allow downloading until more space
* is available because downloadmanager shouldn't end up taking those last
* few MB of space left on the filesystem.
*/
if (root.equals(mSystemCacheDir)) {
Log.w(Constants.TAG, "System cache dir ('/cache') is running low on space." +
"space available (in bytes): " + bytesAvailable);
} else {
throw new StopRequestException(Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR,
"space in the filesystem rooted at: " + root +
" is below 10% availability. stopping this download.");
}
}
}
if (root.equals(mDownloadDataDir)) {
// this download is going into downloads data dir. check space in that specific dir.
- bytesAvailable = getAvailableBytesInDownloadsDataDir(mSystemCacheDir);
+ bytesAvailable = getAvailableBytesInDownloadsDataDir(mDownloadDataDir);
if (bytesAvailable < sDownloadDataDirLowSpaceThreshold) {
// print a warning
Log.w(Constants.TAG, "Downloads data dir: " + root +
- " is running low on space. space available (in b): " + bytesAvailable);
- } else if (bytesAvailable < targetBytes) {
+ " is running low on space. space available (in bytes): " + bytesAvailable);
+ }
+ if (bytesAvailable < targetBytes) {
// Insufficient space; make space.
discardPurgeableFiles(destination, sDownloadDataDirLowSpaceThreshold);
removeSpuriousFiles();
- bytesAvailable = getAvailableBytesInDownloadsDataDir(mSystemCacheDir);
+ bytesAvailable = getAvailableBytesInDownloadsDataDir(mDownloadDataDir);
}
}
if (bytesAvailable < targetBytes) {
throw new StopRequestException(Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR,
"not enough free space in the filesystem rooted at: " + root +
" and unable to free any more");
}
}
/**
* returns the number of bytes available in the downloads data dir
* TODO this implementation is too slow. optimize it.
*/
private long getAvailableBytesInDownloadsDataDir(File root) {
File[] files = root.listFiles();
long space = sMaxdownloadDataDirSize;
if (files == null) {
return space;
}
int size = files.length;
for (int i = 0; i < size; i++) {
space -= files[i].length();
}
if (Constants.LOGV) {
Log.i(Constants.TAG, "available space (in bytes) in downloads data dir: " + space);
}
return space;
}
private long getAvailableBytesInFileSystemAtGivenRoot(File root) {
StatFs stat = new StatFs(root.getPath());
// put a bit of margin (in case creating the file grows the system by a few blocks)
long availableBlocks = (long) stat.getAvailableBlocks() - 4;
long size = stat.getBlockSize() * availableBlocks;
if (Constants.LOGV) {
Log.i(Constants.TAG, "available space (in bytes) in filesystem rooted at: " +
root.getPath() + " is: " + size);
}
return size;
}
File locateDestinationDirectory(String mimeType, int destination, long contentLength)
throws StopRequestException {
switch (destination) {
case Downloads.Impl.DESTINATION_CACHE_PARTITION:
case Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE:
case Downloads.Impl.DESTINATION_CACHE_PARTITION_NOROAMING:
return mDownloadDataDir;
case Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION:
return mSystemCacheDir;
case Downloads.Impl.DESTINATION_EXTERNAL:
File base = new File(mExternalStorageDir.getPath() + Constants.DEFAULT_DL_SUBDIR);
if (!base.isDirectory() && !base.mkdir()) {
// Can't create download directory, e.g. because a file called "download"
// already exists at the root level, or the SD card filesystem is read-only.
throw new StopRequestException(Downloads.Impl.STATUS_FILE_ERROR,
"unable to create external downloads directory " + base.getPath());
}
return base;
default:
throw new IllegalStateException("unexpected value for destination: " + destination);
}
}
File getDownloadDataDirectory() {
return mDownloadDataDir;
}
/**
* Deletes purgeable files from the cache partition. This also deletes
* the matching database entries. Files are deleted in LRU order until
* the total byte size is greater than targetBytes
*/
private long discardPurgeableFiles(int destination, long targetBytes) {
if (Constants.LOGV) {
Log.i(Constants.TAG, "discardPurgeableFiles: destination = " + destination +
", targetBytes = " + targetBytes);
}
String destStr = (destination == Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION) ?
String.valueOf(destination) :
String.valueOf(Downloads.Impl.DESTINATION_CACHE_PARTITION_PURGEABLE);
String[] bindArgs = new String[]{destStr};
Cursor cursor = mContext.getContentResolver().query(
Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI,
null,
"( " +
Downloads.Impl.COLUMN_STATUS + " = '" + Downloads.Impl.STATUS_SUCCESS + "' AND " +
Downloads.Impl.COLUMN_DESTINATION + " = ? )",
bindArgs,
Downloads.Impl.COLUMN_LAST_MODIFICATION);
if (cursor == null) {
return 0;
}
long totalFreed = 0;
try {
while (cursor.moveToNext() && totalFreed < targetBytes) {
File file = new File(cursor.getString(cursor.getColumnIndex(Downloads.Impl._DATA)));
if (Constants.LOGV) {
Log.i(Constants.TAG, "purging " + file.getAbsolutePath() + " for " +
file.length() + " bytes");
}
totalFreed += file.length();
file.delete();
long id = cursor.getLong(cursor.getColumnIndex(Downloads.Impl._ID));
mContext.getContentResolver().delete(
ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, id),
null, null);
}
} finally {
cursor.close();
}
if (Constants.LOGV) {
Log.i(Constants.TAG, "Purged files, freed " + totalFreed + " for " +
targetBytes + " requested");
}
return totalFreed;
}
/**
* Removes files in the systemcache and downloads data dir without corresponding entries in
* the downloads database.
* This can occur if a delete is done on the database but the file is not removed from the
* filesystem (due to sudden death of the process, for example).
* This is not a very common occurrence. So, do this only once in a while.
*/
private void removeSpuriousFiles() {
if (Constants.LOGV) {
Log.i(Constants.TAG, "in removeSpuriousFiles");
}
// get a list of all files in system cache dir and downloads data dir
List<File> files = new ArrayList<File>();
File[] listOfFiles = mSystemCacheDir.listFiles();
if (listOfFiles != null) {
files.addAll(Arrays.asList(listOfFiles));
}
listOfFiles = mDownloadDataDir.listFiles();
if (listOfFiles != null) {
files.addAll(Arrays.asList(listOfFiles));
}
if (files.size() == 0) {
return;
}
Cursor cursor = mContext.getContentResolver().query(
Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI,
new String[] { Downloads.Impl._DATA }, null, null, null);
try {
if (cursor != null) {
while (cursor.moveToNext()) {
String filename = cursor.getString(0);
if (!TextUtils.isEmpty(filename)) {
if (Constants.LOGV) {
Log.i(Constants.TAG, "in removeSpuriousFiles, preserving file " +
filename);
}
files.remove(new File(filename));
}
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
// delete the files not found in the database
for (File file : files) {
if (file.getName().equals(Constants.KNOWN_SPURIOUS_FILENAME) ||
file.getName().equalsIgnoreCase(Constants.RECOVERY_DIRECTORY)) {
continue;
}
if (Constants.LOGV) {
Log.i(Constants.TAG, "deleting spurious file " + file.getAbsolutePath());
}
file.delete();
}
}
/**
* Drops old rows from the database to prevent it from growing too large
* TODO logic in this method needs to be optimized. maintain the number of downloads
* in memory - so that this method can limit the amount of data read.
*/
private void trimDatabase() {
if (Constants.LOGV) {
Log.i(Constants.TAG, "in trimDatabase");
}
Cursor cursor = null;
try {
cursor = mContext.getContentResolver().query(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI,
new String[] { Downloads.Impl._ID },
Downloads.Impl.COLUMN_STATUS + " >= '200'", null,
Downloads.Impl.COLUMN_LAST_MODIFICATION);
if (cursor == null) {
// This isn't good - if we can't do basic queries in our database,
// nothing's gonna work
Log.e(Constants.TAG, "null cursor in trimDatabase");
return;
}
if (cursor.moveToFirst()) {
int numDelete = cursor.getCount() - Constants.MAX_DOWNLOADS;
int columnId = cursor.getColumnIndexOrThrow(Downloads.Impl._ID);
while (numDelete > 0) {
Uri downloadUri = ContentUris.withAppendedId(
Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, cursor.getLong(columnId));
mContext.getContentResolver().delete(downloadUri, null, null);
if (!cursor.moveToNext()) {
break;
}
numDelete--;
}
}
} catch (SQLiteException e) {
// trimming the database raised an exception. alright, ignore the exception
// and return silently. trimming database is not exactly a critical operation
// and there is no need to propagate the exception.
Log.w(Constants.TAG, "trimDatabase failed with exception: " + e.getMessage());
return;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private synchronized int incrementBytesDownloadedSinceLastCheckOnSpace(long val) {
mBytesDownloadedSinceLastCheckOnSpace += val;
return mBytesDownloadedSinceLastCheckOnSpace;
}
private synchronized void resetBytesDownloadedSinceLastCheckOnSpace() {
mBytesDownloadedSinceLastCheckOnSpace = 0;
}
}
| false | true | private synchronized void findSpace(File root, long targetBytes, int destination)
throws StopRequestException {
if (targetBytes == 0) {
return;
}
if (destination == Downloads.Impl.DESTINATION_FILE_URI ||
destination == Downloads.Impl.DESTINATION_EXTERNAL) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
throw new StopRequestException(Downloads.Impl.STATUS_DEVICE_NOT_FOUND_ERROR,
"external media not mounted");
}
}
// is there enough space in the file system of the given param 'root'.
long bytesAvailable = getAvailableBytesInFileSystemAtGivenRoot(root);
if (bytesAvailable < sDownloadDataDirLowSpaceThreshold) {
/* filesystem's available space is below threshold for low space warning.
* threshold typically is 10% of download data dir space quota.
* try to cleanup and see if the low space situation goes away.
*/
discardPurgeableFiles(destination, sDownloadDataDirLowSpaceThreshold);
removeSpuriousFiles();
bytesAvailable = getAvailableBytesInFileSystemAtGivenRoot(root);
if (bytesAvailable < sDownloadDataDirLowSpaceThreshold) {
/*
* available space is still below the threshold limit.
*
* If this is system cache dir, print a warning.
* otherwise, don't allow downloading until more space
* is available because downloadmanager shouldn't end up taking those last
* few MB of space left on the filesystem.
*/
if (root.equals(mSystemCacheDir)) {
Log.w(Constants.TAG, "System cache dir ('/cache') is running low on space." +
"space available (in bytes): " + bytesAvailable);
} else {
throw new StopRequestException(Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR,
"space in the filesystem rooted at: " + root +
" is below 10% availability. stopping this download.");
}
}
}
if (root.equals(mDownloadDataDir)) {
// this download is going into downloads data dir. check space in that specific dir.
bytesAvailable = getAvailableBytesInDownloadsDataDir(mSystemCacheDir);
if (bytesAvailable < sDownloadDataDirLowSpaceThreshold) {
// print a warning
Log.w(Constants.TAG, "Downloads data dir: " + root +
" is running low on space. space available (in b): " + bytesAvailable);
} else if (bytesAvailable < targetBytes) {
// Insufficient space; make space.
discardPurgeableFiles(destination, sDownloadDataDirLowSpaceThreshold);
removeSpuriousFiles();
bytesAvailable = getAvailableBytesInDownloadsDataDir(mSystemCacheDir);
}
}
if (bytesAvailable < targetBytes) {
throw new StopRequestException(Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR,
"not enough free space in the filesystem rooted at: " + root +
" and unable to free any more");
}
}
| private synchronized void findSpace(File root, long targetBytes, int destination)
throws StopRequestException {
if (targetBytes == 0) {
return;
}
if (destination == Downloads.Impl.DESTINATION_FILE_URI ||
destination == Downloads.Impl.DESTINATION_EXTERNAL) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
throw new StopRequestException(Downloads.Impl.STATUS_DEVICE_NOT_FOUND_ERROR,
"external media not mounted");
}
}
// is there enough space in the file system of the given param 'root'.
long bytesAvailable = getAvailableBytesInFileSystemAtGivenRoot(root);
if (bytesAvailable < sDownloadDataDirLowSpaceThreshold) {
/* filesystem's available space is below threshold for low space warning.
* threshold typically is 10% of download data dir space quota.
* try to cleanup and see if the low space situation goes away.
*/
discardPurgeableFiles(destination, sDownloadDataDirLowSpaceThreshold);
removeSpuriousFiles();
bytesAvailable = getAvailableBytesInFileSystemAtGivenRoot(root);
if (bytesAvailable < sDownloadDataDirLowSpaceThreshold) {
/*
* available space is still below the threshold limit.
*
* If this is system cache dir, print a warning.
* otherwise, don't allow downloading until more space
* is available because downloadmanager shouldn't end up taking those last
* few MB of space left on the filesystem.
*/
if (root.equals(mSystemCacheDir)) {
Log.w(Constants.TAG, "System cache dir ('/cache') is running low on space." +
"space available (in bytes): " + bytesAvailable);
} else {
throw new StopRequestException(Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR,
"space in the filesystem rooted at: " + root +
" is below 10% availability. stopping this download.");
}
}
}
if (root.equals(mDownloadDataDir)) {
// this download is going into downloads data dir. check space in that specific dir.
bytesAvailable = getAvailableBytesInDownloadsDataDir(mDownloadDataDir);
if (bytesAvailable < sDownloadDataDirLowSpaceThreshold) {
// print a warning
Log.w(Constants.TAG, "Downloads data dir: " + root +
" is running low on space. space available (in bytes): " + bytesAvailable);
}
if (bytesAvailable < targetBytes) {
// Insufficient space; make space.
discardPurgeableFiles(destination, sDownloadDataDirLowSpaceThreshold);
removeSpuriousFiles();
bytesAvailable = getAvailableBytesInDownloadsDataDir(mDownloadDataDir);
}
}
if (bytesAvailable < targetBytes) {
throw new StopRequestException(Downloads.Impl.STATUS_INSUFFICIENT_SPACE_ERROR,
"not enough free space in the filesystem rooted at: " + root +
" and unable to free any more");
}
}
|
diff --git a/src/main/java/com/opentok/api/OpenTokSDK.java b/src/main/java/com/opentok/api/OpenTokSDK.java
index e2b0816..69a3f71 100644
--- a/src/main/java/com/opentok/api/OpenTokSDK.java
+++ b/src/main/java/com/opentok/api/OpenTokSDK.java
@@ -1,211 +1,211 @@
/*!
* OpenTok Java Library
* http://www.tokbox.com/
*
* Copyright 2010, TokBox, Inc.
*
* Last modified: @opentok.sdk.java.mod_time@
*/
package com.opentok.api;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.xml.bind.DatatypeConverter;
import com.opentok.api.constants.RoleConstants;
import com.opentok.api.constants.SessionProperties;
import com.opentok.exception.OpenTokException;
import com.opentok.util.Base64;
import com.opentok.util.GenerateMac;
import com.opentok.util.TokBoxXML;
public class OpenTokSDK {
protected int api_key;
protected String api_secret;
public OpenTokSDK(int api_key, String api_secret) {
this.api_key = api_key;
this.api_secret = api_secret.trim();
}
/**
*
* Generate a token which is passed to the JS API to enable widgets to connect to the Opentok api.
*
* * @session_id: Specify a session_id to make this token only valid for that session_id. Tokens generated without a valid sessionId will be rejected and the client might be disconnected.
* @role: One of the constants defined in RoleConstants. Default is publisher, look in the documentation to learn more about roles.
* @expire_time: Integer timestamp. You can override the default token expire time of 24h by choosing an explicit expire time. Can be up to 7d after create_time.
*/
public String generate_token(String session_id, String role, Long expire_time, String connection_data) throws OpenTokException {
if(session_id == null || session_id == "") {
- throw new OpenTokException("SessionId cannot be null or empty.");
+ throw new OpenTokException("Null or empty session ID are not valid");
}
String decodedSessionId = "";
try {
String subSessionId = session_id.substring(2);
for (int i = 0; i<3; i++){
String newSessionId = subSessionId.concat(repeatString("=",i));
decodedSessionId = new String(DatatypeConverter.parseBase64Binary(
newSessionId.replace('-', '+').replace('_', '/')), "ISO8859_1");
if (decodedSessionId.contains("~")){
break;
}
}
if(!decodedSessionId.split("~")[1].equals(String.valueOf(api_key))) {
- throw new OpenTokException("SessionId does not belong to the same partnerId");
+ throw new OpenTokException("An invalid session ID was passed");
}
} catch (Exception e) {
- throw new OpenTokException("SessionId cannot be invalid.");
+ throw new OpenTokException("An invalid session ID was passed");
}
Long create_time = new Long(System.currentTimeMillis() / 1000).longValue();
StringBuilder data_string_builder = new StringBuilder();
//Build the string
Random random = new Random();
int nonce = random.nextInt();
data_string_builder.append("session_id=");
data_string_builder.append(session_id);
data_string_builder.append("&create_time=");
data_string_builder.append(create_time);
data_string_builder.append("&nonce=");
data_string_builder.append(nonce);
data_string_builder.append("&role=");
data_string_builder.append(role);
if(!RoleConstants.SUBSCRIBER.equals(role) &&
!RoleConstants.PUBLISHER.equals(role) &&
!RoleConstants.MODERATOR.equals(role) &&
!"".equals(role))
throw new OpenTokException(role + " is not a recognized role");
if(expire_time != null) {
if(expire_time < (System.currentTimeMillis() / 1000)-1)
throw new OpenTokException("Expire time must be in the future");
if(expire_time > (System.currentTimeMillis() / 1000 + 2592000))
throw new OpenTokException("Expire time must be in the next 30 days");
data_string_builder.append("&expire_time=");
data_string_builder.append(expire_time);
}
if (connection_data != null) {
if(connection_data.length() > 1000)
throw new OpenTokException("Connection data must be less than 1000 characters");
data_string_builder.append("&connection_data=");
try {
data_string_builder.append(URLEncoder.encode(connection_data, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Error during URL encode of your connection_data.", e);
};
}
StringBuilder token_string_builder = new StringBuilder();
try {
token_string_builder.append("T1==");
StringBuilder inner_builder = new StringBuilder();
inner_builder.append("partner_id=");
inner_builder.append(this.api_key);
inner_builder.append("&sig=");
inner_builder.append(GenerateMac.calculateRFC2104HMAC(data_string_builder.toString(),
this.api_secret));
inner_builder.append(":");
inner_builder.append(data_string_builder.toString());
token_string_builder.append(Base64.encode(inner_builder.toString()));
}catch (java.security.SignatureException e) {
throw new OpenTokException(e.getMessage());
}
return token_string_builder.toString();
}
/**
* Creates a new session.
* @location: IP address to geolocate the call around.
* @session_properties: Optional array, keys are defined in SessionPropertyConstants
*/
public OpenTokSession create_session(String location, SessionProperties properties) throws OpenTokException {
Map<String, String> params;
if(properties != null)
params = properties.to_map();
else
params = new HashMap<String, String>();
return this.create_session(location, params);
}
/**
* Overloaded functions
* These work the same as those defined above, but with optional params filled in with defaults
*/
public String generate_token(String session_id) throws OpenTokException {
return this.generate_token(session_id, RoleConstants.PUBLISHER, null, null);
}
public String generate_token(String session_id, String role) throws OpenTokException {
return this.generate_token(session_id, role, null, null);
}
public String generate_token(String session_id, String role, Long expire_time) throws OpenTokException {
return this.generate_token(session_id, role, expire_time, null);
}
public OpenTokSession create_session() throws OpenTokException {
return create_session(null, new HashMap<String, String>());
}
public OpenTokSession create_session(String location) throws OpenTokException {
return create_session(location, new HashMap<String, String>());
}
public OpenTokSession create_session(String location, Map<String, String> params) throws OpenTokException {
params.put("location", location);
TokBoxXML xmlResponse = this.do_request("/session/create", params);
if(xmlResponse.hasElement("error", "Errors")) {
throw new OpenTokException("Unable to create session");
}
String session_id = xmlResponse.getElementValue("session_id", "Session");
return new OpenTokSession(session_id);
}
private static String repeatString(String str, int times){
StringBuilder ret = new StringBuilder();
for(int i = 0;i < times;i++) ret.append(str);
return ret.toString();
}
protected TokBoxXML do_request(String url, Map<String, String> params) throws OpenTokException {
TokBoxNetConnection n = new TokBoxNetConnection();
Map<String, String> headers = new HashMap<String, String>();
headers.put("X-TB-PARTNER-AUTH", this.api_key + ":" + this.api_secret);
return new TokBoxXML(n.request(API_Config.API_URL + url, params, headers));
}
protected static String join(List<String> s, String delimiter) throws java.io.UnsupportedEncodingException{
if (s.isEmpty()) return "";
Iterator<String> iter = s.iterator();
StringBuffer buffer = new StringBuffer(URLEncoder.encode(iter.next(),"UTF-8"));
while (iter.hasNext()) buffer.append(delimiter).append(URLEncoder.encode(iter.next(),"UTF-8"));
return buffer.toString();
}
}
| false | true | public String generate_token(String session_id, String role, Long expire_time, String connection_data) throws OpenTokException {
if(session_id == null || session_id == "") {
throw new OpenTokException("SessionId cannot be null or empty.");
}
String decodedSessionId = "";
try {
String subSessionId = session_id.substring(2);
for (int i = 0; i<3; i++){
String newSessionId = subSessionId.concat(repeatString("=",i));
decodedSessionId = new String(DatatypeConverter.parseBase64Binary(
newSessionId.replace('-', '+').replace('_', '/')), "ISO8859_1");
if (decodedSessionId.contains("~")){
break;
}
}
if(!decodedSessionId.split("~")[1].equals(String.valueOf(api_key))) {
throw new OpenTokException("SessionId does not belong to the same partnerId");
}
} catch (Exception e) {
throw new OpenTokException("SessionId cannot be invalid.");
}
Long create_time = new Long(System.currentTimeMillis() / 1000).longValue();
StringBuilder data_string_builder = new StringBuilder();
//Build the string
Random random = new Random();
int nonce = random.nextInt();
data_string_builder.append("session_id=");
data_string_builder.append(session_id);
data_string_builder.append("&create_time=");
data_string_builder.append(create_time);
data_string_builder.append("&nonce=");
data_string_builder.append(nonce);
data_string_builder.append("&role=");
data_string_builder.append(role);
if(!RoleConstants.SUBSCRIBER.equals(role) &&
!RoleConstants.PUBLISHER.equals(role) &&
!RoleConstants.MODERATOR.equals(role) &&
!"".equals(role))
throw new OpenTokException(role + " is not a recognized role");
if(expire_time != null) {
if(expire_time < (System.currentTimeMillis() / 1000)-1)
throw new OpenTokException("Expire time must be in the future");
if(expire_time > (System.currentTimeMillis() / 1000 + 2592000))
throw new OpenTokException("Expire time must be in the next 30 days");
data_string_builder.append("&expire_time=");
data_string_builder.append(expire_time);
}
if (connection_data != null) {
if(connection_data.length() > 1000)
throw new OpenTokException("Connection data must be less than 1000 characters");
data_string_builder.append("&connection_data=");
try {
data_string_builder.append(URLEncoder.encode(connection_data, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Error during URL encode of your connection_data.", e);
};
}
StringBuilder token_string_builder = new StringBuilder();
try {
token_string_builder.append("T1==");
StringBuilder inner_builder = new StringBuilder();
inner_builder.append("partner_id=");
inner_builder.append(this.api_key);
inner_builder.append("&sig=");
inner_builder.append(GenerateMac.calculateRFC2104HMAC(data_string_builder.toString(),
this.api_secret));
inner_builder.append(":");
inner_builder.append(data_string_builder.toString());
token_string_builder.append(Base64.encode(inner_builder.toString()));
}catch (java.security.SignatureException e) {
throw new OpenTokException(e.getMessage());
}
return token_string_builder.toString();
}
| public String generate_token(String session_id, String role, Long expire_time, String connection_data) throws OpenTokException {
if(session_id == null || session_id == "") {
throw new OpenTokException("Null or empty session ID are not valid");
}
String decodedSessionId = "";
try {
String subSessionId = session_id.substring(2);
for (int i = 0; i<3; i++){
String newSessionId = subSessionId.concat(repeatString("=",i));
decodedSessionId = new String(DatatypeConverter.parseBase64Binary(
newSessionId.replace('-', '+').replace('_', '/')), "ISO8859_1");
if (decodedSessionId.contains("~")){
break;
}
}
if(!decodedSessionId.split("~")[1].equals(String.valueOf(api_key))) {
throw new OpenTokException("An invalid session ID was passed");
}
} catch (Exception e) {
throw new OpenTokException("An invalid session ID was passed");
}
Long create_time = new Long(System.currentTimeMillis() / 1000).longValue();
StringBuilder data_string_builder = new StringBuilder();
//Build the string
Random random = new Random();
int nonce = random.nextInt();
data_string_builder.append("session_id=");
data_string_builder.append(session_id);
data_string_builder.append("&create_time=");
data_string_builder.append(create_time);
data_string_builder.append("&nonce=");
data_string_builder.append(nonce);
data_string_builder.append("&role=");
data_string_builder.append(role);
if(!RoleConstants.SUBSCRIBER.equals(role) &&
!RoleConstants.PUBLISHER.equals(role) &&
!RoleConstants.MODERATOR.equals(role) &&
!"".equals(role))
throw new OpenTokException(role + " is not a recognized role");
if(expire_time != null) {
if(expire_time < (System.currentTimeMillis() / 1000)-1)
throw new OpenTokException("Expire time must be in the future");
if(expire_time > (System.currentTimeMillis() / 1000 + 2592000))
throw new OpenTokException("Expire time must be in the next 30 days");
data_string_builder.append("&expire_time=");
data_string_builder.append(expire_time);
}
if (connection_data != null) {
if(connection_data.length() > 1000)
throw new OpenTokException("Connection data must be less than 1000 characters");
data_string_builder.append("&connection_data=");
try {
data_string_builder.append(URLEncoder.encode(connection_data, "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Error during URL encode of your connection_data.", e);
};
}
StringBuilder token_string_builder = new StringBuilder();
try {
token_string_builder.append("T1==");
StringBuilder inner_builder = new StringBuilder();
inner_builder.append("partner_id=");
inner_builder.append(this.api_key);
inner_builder.append("&sig=");
inner_builder.append(GenerateMac.calculateRFC2104HMAC(data_string_builder.toString(),
this.api_secret));
inner_builder.append(":");
inner_builder.append(data_string_builder.toString());
token_string_builder.append(Base64.encode(inner_builder.toString()));
}catch (java.security.SignatureException e) {
throw new OpenTokException(e.getMessage());
}
return token_string_builder.toString();
}
|
diff --git a/java/tools/src/joptimizer/optimizer/peephole/PeepGetfield.java b/java/tools/src/joptimizer/optimizer/peephole/PeepGetfield.java
index 5552f829..e5819bd8 100644
--- a/java/tools/src/joptimizer/optimizer/peephole/PeepGetfield.java
+++ b/java/tools/src/joptimizer/optimizer/peephole/PeepGetfield.java
@@ -1,73 +1,73 @@
/*
* Copyright (c) 2007,2008, Stefan Hepp
*
* This file is part of JOPtimizer.
*
* JOPtimizer 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.
*
* JOPtimizer 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 joptimizer.optimizer.peephole;
import com.jopdesign.libgraph.cfg.ControlFlowGraph;
import com.jopdesign.libgraph.cfg.statements.StmtHandle;
import com.jopdesign.libgraph.cfg.statements.common.GetfieldStmt;
import com.jopdesign.libgraph.cfg.statements.common.PutfieldStmt;
import com.jopdesign.libgraph.cfg.statements.stack.StackDup;
/**
* @author Stefan Hepp, [email protected]
*/
public class PeepGetfield implements PeepOptimization {
public PeepGetfield() {
}
public void startOptimizer() {
}
public void finishOptimizer() {
}
public boolean startGraph(ControlFlowGraph graph) {
return graph.getType() == ControlFlowGraph.TYPE_STACK;
}
public Class getFirstStmtClass() {
return PutfieldStmt.class;
}
public StmtHandle processStatement(StmtHandle stmt) {
PutfieldStmt put = (PutfieldStmt) stmt.getStatement();
StmtHandle nextStmt = stmt.getNext();
if ( nextStmt == null || !(nextStmt.getStatement() instanceof GetfieldStmt) ) {
return null;
}
GetfieldStmt get = (GetfieldStmt) nextStmt.getStatement();
if ( !get.getConstantField().equals(put.getConstantField()) ) {
return null;
}
- if ( get.getConstantField().isAnonymous() || get.getConstantField().getFieldInfo().isSynchronized() ) {
+ if ( get.getConstantField().isAnonymous() || get.getConstantField().getFieldInfo().isVolatile() ) {
return null;
}
stmt.setStatement(new StackDup(put.getConstantField().getFieldInfo().getType()));
nextStmt.setStatement(put);
return nextStmt;
}
}
| true | true | public StmtHandle processStatement(StmtHandle stmt) {
PutfieldStmt put = (PutfieldStmt) stmt.getStatement();
StmtHandle nextStmt = stmt.getNext();
if ( nextStmt == null || !(nextStmt.getStatement() instanceof GetfieldStmt) ) {
return null;
}
GetfieldStmt get = (GetfieldStmt) nextStmt.getStatement();
if ( !get.getConstantField().equals(put.getConstantField()) ) {
return null;
}
if ( get.getConstantField().isAnonymous() || get.getConstantField().getFieldInfo().isSynchronized() ) {
return null;
}
stmt.setStatement(new StackDup(put.getConstantField().getFieldInfo().getType()));
nextStmt.setStatement(put);
return nextStmt;
}
| public StmtHandle processStatement(StmtHandle stmt) {
PutfieldStmt put = (PutfieldStmt) stmt.getStatement();
StmtHandle nextStmt = stmt.getNext();
if ( nextStmt == null || !(nextStmt.getStatement() instanceof GetfieldStmt) ) {
return null;
}
GetfieldStmt get = (GetfieldStmt) nextStmt.getStatement();
if ( !get.getConstantField().equals(put.getConstantField()) ) {
return null;
}
if ( get.getConstantField().isAnonymous() || get.getConstantField().getFieldInfo().isVolatile() ) {
return null;
}
stmt.setStatement(new StackDup(put.getConstantField().getFieldInfo().getType()));
nextStmt.setStatement(put);
return nextStmt;
}
|
diff --git a/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/dispatchers/SubsequentRequestDispatcher.java b/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/dispatchers/SubsequentRequestDispatcher.java
index c066dd611..4d4e496b8 100644
--- a/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/dispatchers/SubsequentRequestDispatcher.java
+++ b/servers/sip-servlets/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/dispatchers/SubsequentRequestDispatcher.java
@@ -1,286 +1,286 @@
/*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.mobicents.servlet.sip.core.dispatchers;
import gov.nist.javax.sip.header.extensions.JoinHeader;
import gov.nist.javax.sip.header.extensions.ReplacesHeader;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.sip.ProxyBranch;
import javax.servlet.sip.SipServletResponse;
import javax.sip.Dialog;
import javax.sip.SipException;
import javax.sip.SipProvider;
import javax.sip.header.CSeqHeader;
import javax.sip.header.Parameters;
import javax.sip.header.RouteHeader;
import javax.sip.header.SubscriptionStateHeader;
import javax.sip.header.ToHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;
import org.apache.log4j.Logger;
import org.mobicents.servlet.sip.core.ApplicationRoutingHeaderComposer;
import org.mobicents.servlet.sip.core.SipApplicationDispatcher;
import org.mobicents.servlet.sip.core.session.MobicentsSipApplicationSession;
import org.mobicents.servlet.sip.core.session.MobicentsSipSession;
import org.mobicents.servlet.sip.core.session.SessionManagerUtil;
import org.mobicents.servlet.sip.core.session.SipApplicationSessionKey;
import org.mobicents.servlet.sip.core.session.SipManager;
import org.mobicents.servlet.sip.core.session.SipSessionKey;
import org.mobicents.servlet.sip.message.SipFactoryImpl;
import org.mobicents.servlet.sip.message.SipServletMessageImpl;
import org.mobicents.servlet.sip.message.SipServletRequestImpl;
import org.mobicents.servlet.sip.proxy.ProxyBranchImpl;
import org.mobicents.servlet.sip.proxy.ProxyImpl;
import org.mobicents.servlet.sip.startup.SipContext;
/**
* This class is responsible for routing and dispatching subsequent request to applications according to JSR 289 Section
* 15.6 Responses, Subsequent Requests and Application Path
*
* It uses route header parameters for proxy apps or to tag parameter for UAS/B2BUA apps
* that were previously set by the container on
* record route headers or to tag to know which app has to be called
*
* @author <A HREF="mailto:[email protected]">Jean Deruelle</A>
*
*/
public class SubsequentRequestDispatcher extends RequestDispatcher {
private static transient Logger logger = Logger.getLogger(SubsequentRequestDispatcher.class);
public SubsequentRequestDispatcher(
SipApplicationDispatcher sipApplicationDispatcher) {
super(sipApplicationDispatcher);
}
/**
* {@inheritDoc}
*/
public void dispatchMessage(final SipProvider sipProvider, SipServletMessageImpl sipServletMessage) throws DispatcherException {
final SipFactoryImpl sipFactoryImpl = sipApplicationDispatcher.getSipFactory();
final SipServletRequestImpl sipServletRequest = (SipServletRequestImpl) sipServletMessage;
if(logger.isDebugEnabled()) {
logger.debug("Routing of Subsequent Request " + sipServletRequest);
}
final Request request = (Request) sipServletRequest.getMessage();
final Dialog dialog = sipServletRequest.getDialog();
final RouteHeader poppedRouteHeader = sipServletRequest.getPoppedRouteHeader();
String applicationName = null;
String applicationId = null;
if(poppedRouteHeader != null){
final Parameters poppedAddress = (Parameters)poppedRouteHeader.getAddress().getURI();
//Extract information from the Route Header
final String applicationNameHashed = poppedAddress.getParameter(RR_PARAM_APPLICATION_NAME);
if(applicationNameHashed != null && applicationNameHashed.length() > 0) {
applicationName = sipApplicationDispatcher.getApplicationNameFromHash(applicationNameHashed);
applicationId = poppedAddress.getParameter(APP_ID);
}
}
if(applicationId == null) {
final ToHeader toHeader = (ToHeader) request.getHeader(ToHeader.NAME);
final String arText = toHeader.getTag();
final String[] tuple = ApplicationRoutingHeaderComposer.getAppNameAndSessionId(sipApplicationDispatcher, arText);
applicationName = tuple[0];
applicationId = tuple[1];
if(Request.ACK.equals(request.getMethod()) && applicationId == null && applicationName == null) {
//Means that this is an ACK to a container generated error response, so we can drop it
if(logger.isDebugEnabled()) {
logger.debug("The popped Route, application Id and name are null for an ACK, so this is an ACK to a container generated error response, so it is dropped");
}
return ;
}
}
boolean inverted = false;
if(dialog != null && !dialog.isServer()) {
inverted = true;
}
final SipContext sipContext = sipApplicationDispatcher.findSipApplication(applicationName);
if(sipContext == null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request +
"in this popped routed header " + poppedRouteHeader);
}
final SipManager sipManager = (SipManager)sipContext.getManager();
SipApplicationSessionKey sipApplicationSessionKey = SessionManagerUtil.getSipApplicationSessionKey(
applicationName,
applicationId);
MobicentsSipSession tmpSipSession = null;
MobicentsSipApplicationSession sipApplicationSession = sipManager.getSipApplicationSession(sipApplicationSessionKey, false);
if(sipApplicationSession == null) {
if(logger.isDebugEnabled()) {
sipManager.dumpSipApplicationSessions();
}
//trying the join or replaces matching sip app sessions
final SipApplicationSessionKey joinSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, JoinHeader.NAME);
final SipApplicationSessionKey replacesSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, ReplacesHeader.NAME);
if(joinSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(joinSipApplicationSessionKey, false);
sipApplicationSessionKey = joinSipApplicationSessionKey;
} else if(replacesSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(replacesSipApplicationSessionKey, false);
sipApplicationSessionKey = replacesSipApplicationSessionKey;
}
if(sipApplicationSession == null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip application session to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
}
}
SipSessionKey key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, inverted);
if(logger.isDebugEnabled()) {
logger.debug("Trying to find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
}
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
// Added by Vladimir because the inversion detection on proxied requests doesn't work
if(tmpSipSession == null) {
if(logger.isDebugEnabled()) {
logger.debug("Cannot find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute() + ". Trying inverted.");
}
key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, !inverted);
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
}
if(tmpSipSession == null) {
sipManager.dumpSipSessions();
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
} else {
if(logger.isDebugEnabled()) {
logger.debug("Inverted try worked. sip session found : " + tmpSipSession.getId());
}
}
final MobicentsSipSession sipSession = tmpSipSession;
sipServletRequest.setSipSession(sipSession);
// BEGIN validation delegated to the applicationas per JSIP patch for http://code.google.com/p/mobicents/issues/detail?id=766
if(request.getMethod().equalsIgnoreCase("ACK")) {
if(sipSession.isAckReceived()) {
// Filter out ACK retransmissions for JSIP patch for http://code.google.com/p/mobicents/issues/detail?id=766
logger.debug("ACK filtered out as a retransmission. This Sip Session already has been ACKed.");
return;
}
sipSession.setAckReceived(true);
}
- //CSeq validation should only be done for proxies
+ //CSeq validation should only be done for non proxy applications
if(sipSession.getProxy() == null) {
CSeqHeader cseq = (CSeqHeader) request.getHeader(CSeqHeader.NAME);
long localCseq = sipSession.getCseq();
long remoteCseq = cseq.getSeqNumber();
if(localCseq>remoteCseq) {
logger.error("CSeq out of order for the following request");
SipServletResponse response = sipServletRequest.createResponse(500, "CSeq out of order");
try {
response.send();
} catch (IOException e) {
logger.error("Can not send error response", e);
}
}
sipSession.setCseq(remoteCseq);
}
// END of validation for http://code.google.com/p/mobicents/issues/detail?id=766
DispatchTask dispatchTask = new DispatchTask(sipServletRequest, sipProvider) {
public void dispatch() throws DispatcherException {
sipContext.enterSipApp(sipServletRequest, null, sipManager, true, true);
final String requestMethod = sipServletRequest.getMethod();
final SubscriptionStateHeader subscriptionStateHeader = (SubscriptionStateHeader)
sipServletRequest.getMessage().getHeader(SubscriptionStateHeader.NAME);
try {
sipSession.setSessionCreatingTransaction(sipServletRequest.getTransaction());
// JSR 289 Section 6.2.1 :
// any state transition caused by the reception of a SIP message,
// the state change must be accomplished by the container before calling
// the service() method of any SipServlet to handle the incoming message.
sipSession.updateStateOnSubsequentRequest(sipServletRequest, true);
try {
// RFC 3265 : If a matching NOTIFY request contains a "Subscription-State" of "active" or "pending", it creates
// a new subscription and a new dialog (unless they have already been
// created by a matching response, as described above).
if(Request.NOTIFY.equals(requestMethod) &&
(subscriptionStateHeader != null &&
SubscriptionStateHeader.ACTIVE.equalsIgnoreCase(subscriptionStateHeader.getState()) ||
SubscriptionStateHeader.PENDING.equalsIgnoreCase(subscriptionStateHeader.getState()))) {
sipSession.addSubscription(sipServletRequest);
}
// See if the subsequent request should go directly to the proxy
final ProxyImpl proxy = sipSession.getProxy();
if(proxy != null) {
final ProxyBranchImpl finalBranch = proxy.getFinalBranchForSubsequentRequests();
if(finalBranch != null) {
proxy.setAckReceived(requestMethod.equalsIgnoreCase(Request.ACK));
proxy.setOriginalRequest(sipServletRequest);
callServlet(sipServletRequest);
finalBranch.proxySubsequentRequest(sipServletRequest);
} else if(requestMethod.equals(Request.PRACK)) {
callServlet(sipServletRequest);
List<ProxyBranch> branches = proxy.getProxyBranches();
for(ProxyBranch pb : branches) {
ProxyBranchImpl proxyBranch = (ProxyBranchImpl) pb;
if(proxyBranch.isWaitingForPrack()) {
proxyBranch.proxyDialogStateless(sipServletRequest);
proxyBranch.setWaitingForPrack(false);
}
}
}
}
// If it's not for a proxy then it's just an AR, so go to the next application
else {
callServlet(sipServletRequest);
}
} catch (ServletException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
} catch (SipException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
} catch (IOException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
}
} finally {
// A subscription is destroyed when a notifier sends a NOTIFY request
// with a "Subscription-State" of "terminated".
if(Request.NOTIFY.equals(requestMethod) &&
(subscriptionStateHeader != null &&
SubscriptionStateHeader.TERMINATED.equalsIgnoreCase(subscriptionStateHeader.getState()))) {
sipSession.removeSubscription(sipServletRequest);
}
sipContext.exitSipApp(sipServletRequest, null);
}
//nothing more needs to be done, either the app acted as UA, PROXY or B2BUA. in any case we stop routing
}
};
getConcurrencyModelExecutorService(sipContext, sipServletMessage).execute(dispatchTask);
}
}
| true | true | public void dispatchMessage(final SipProvider sipProvider, SipServletMessageImpl sipServletMessage) throws DispatcherException {
final SipFactoryImpl sipFactoryImpl = sipApplicationDispatcher.getSipFactory();
final SipServletRequestImpl sipServletRequest = (SipServletRequestImpl) sipServletMessage;
if(logger.isDebugEnabled()) {
logger.debug("Routing of Subsequent Request " + sipServletRequest);
}
final Request request = (Request) sipServletRequest.getMessage();
final Dialog dialog = sipServletRequest.getDialog();
final RouteHeader poppedRouteHeader = sipServletRequest.getPoppedRouteHeader();
String applicationName = null;
String applicationId = null;
if(poppedRouteHeader != null){
final Parameters poppedAddress = (Parameters)poppedRouteHeader.getAddress().getURI();
//Extract information from the Route Header
final String applicationNameHashed = poppedAddress.getParameter(RR_PARAM_APPLICATION_NAME);
if(applicationNameHashed != null && applicationNameHashed.length() > 0) {
applicationName = sipApplicationDispatcher.getApplicationNameFromHash(applicationNameHashed);
applicationId = poppedAddress.getParameter(APP_ID);
}
}
if(applicationId == null) {
final ToHeader toHeader = (ToHeader) request.getHeader(ToHeader.NAME);
final String arText = toHeader.getTag();
final String[] tuple = ApplicationRoutingHeaderComposer.getAppNameAndSessionId(sipApplicationDispatcher, arText);
applicationName = tuple[0];
applicationId = tuple[1];
if(Request.ACK.equals(request.getMethod()) && applicationId == null && applicationName == null) {
//Means that this is an ACK to a container generated error response, so we can drop it
if(logger.isDebugEnabled()) {
logger.debug("The popped Route, application Id and name are null for an ACK, so this is an ACK to a container generated error response, so it is dropped");
}
return ;
}
}
boolean inverted = false;
if(dialog != null && !dialog.isServer()) {
inverted = true;
}
final SipContext sipContext = sipApplicationDispatcher.findSipApplication(applicationName);
if(sipContext == null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request +
"in this popped routed header " + poppedRouteHeader);
}
final SipManager sipManager = (SipManager)sipContext.getManager();
SipApplicationSessionKey sipApplicationSessionKey = SessionManagerUtil.getSipApplicationSessionKey(
applicationName,
applicationId);
MobicentsSipSession tmpSipSession = null;
MobicentsSipApplicationSession sipApplicationSession = sipManager.getSipApplicationSession(sipApplicationSessionKey, false);
if(sipApplicationSession == null) {
if(logger.isDebugEnabled()) {
sipManager.dumpSipApplicationSessions();
}
//trying the join or replaces matching sip app sessions
final SipApplicationSessionKey joinSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, JoinHeader.NAME);
final SipApplicationSessionKey replacesSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, ReplacesHeader.NAME);
if(joinSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(joinSipApplicationSessionKey, false);
sipApplicationSessionKey = joinSipApplicationSessionKey;
} else if(replacesSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(replacesSipApplicationSessionKey, false);
sipApplicationSessionKey = replacesSipApplicationSessionKey;
}
if(sipApplicationSession == null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip application session to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
}
}
SipSessionKey key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, inverted);
if(logger.isDebugEnabled()) {
logger.debug("Trying to find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
}
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
// Added by Vladimir because the inversion detection on proxied requests doesn't work
if(tmpSipSession == null) {
if(logger.isDebugEnabled()) {
logger.debug("Cannot find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute() + ". Trying inverted.");
}
key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, !inverted);
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
}
if(tmpSipSession == null) {
sipManager.dumpSipSessions();
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
} else {
if(logger.isDebugEnabled()) {
logger.debug("Inverted try worked. sip session found : " + tmpSipSession.getId());
}
}
final MobicentsSipSession sipSession = tmpSipSession;
sipServletRequest.setSipSession(sipSession);
// BEGIN validation delegated to the applicationas per JSIP patch for http://code.google.com/p/mobicents/issues/detail?id=766
if(request.getMethod().equalsIgnoreCase("ACK")) {
if(sipSession.isAckReceived()) {
// Filter out ACK retransmissions for JSIP patch for http://code.google.com/p/mobicents/issues/detail?id=766
logger.debug("ACK filtered out as a retransmission. This Sip Session already has been ACKed.");
return;
}
sipSession.setAckReceived(true);
}
//CSeq validation should only be done for proxies
if(sipSession.getProxy() == null) {
CSeqHeader cseq = (CSeqHeader) request.getHeader(CSeqHeader.NAME);
long localCseq = sipSession.getCseq();
long remoteCseq = cseq.getSeqNumber();
if(localCseq>remoteCseq) {
logger.error("CSeq out of order for the following request");
SipServletResponse response = sipServletRequest.createResponse(500, "CSeq out of order");
try {
response.send();
} catch (IOException e) {
logger.error("Can not send error response", e);
}
}
sipSession.setCseq(remoteCseq);
}
// END of validation for http://code.google.com/p/mobicents/issues/detail?id=766
DispatchTask dispatchTask = new DispatchTask(sipServletRequest, sipProvider) {
public void dispatch() throws DispatcherException {
sipContext.enterSipApp(sipServletRequest, null, sipManager, true, true);
final String requestMethod = sipServletRequest.getMethod();
final SubscriptionStateHeader subscriptionStateHeader = (SubscriptionStateHeader)
sipServletRequest.getMessage().getHeader(SubscriptionStateHeader.NAME);
try {
sipSession.setSessionCreatingTransaction(sipServletRequest.getTransaction());
// JSR 289 Section 6.2.1 :
// any state transition caused by the reception of a SIP message,
// the state change must be accomplished by the container before calling
// the service() method of any SipServlet to handle the incoming message.
sipSession.updateStateOnSubsequentRequest(sipServletRequest, true);
try {
// RFC 3265 : If a matching NOTIFY request contains a "Subscription-State" of "active" or "pending", it creates
// a new subscription and a new dialog (unless they have already been
// created by a matching response, as described above).
if(Request.NOTIFY.equals(requestMethod) &&
(subscriptionStateHeader != null &&
SubscriptionStateHeader.ACTIVE.equalsIgnoreCase(subscriptionStateHeader.getState()) ||
SubscriptionStateHeader.PENDING.equalsIgnoreCase(subscriptionStateHeader.getState()))) {
sipSession.addSubscription(sipServletRequest);
}
// See if the subsequent request should go directly to the proxy
final ProxyImpl proxy = sipSession.getProxy();
if(proxy != null) {
final ProxyBranchImpl finalBranch = proxy.getFinalBranchForSubsequentRequests();
if(finalBranch != null) {
proxy.setAckReceived(requestMethod.equalsIgnoreCase(Request.ACK));
proxy.setOriginalRequest(sipServletRequest);
callServlet(sipServletRequest);
finalBranch.proxySubsequentRequest(sipServletRequest);
} else if(requestMethod.equals(Request.PRACK)) {
callServlet(sipServletRequest);
List<ProxyBranch> branches = proxy.getProxyBranches();
for(ProxyBranch pb : branches) {
ProxyBranchImpl proxyBranch = (ProxyBranchImpl) pb;
if(proxyBranch.isWaitingForPrack()) {
proxyBranch.proxyDialogStateless(sipServletRequest);
proxyBranch.setWaitingForPrack(false);
}
}
}
}
// If it's not for a proxy then it's just an AR, so go to the next application
else {
callServlet(sipServletRequest);
}
} catch (ServletException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
} catch (SipException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
} catch (IOException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
}
} finally {
// A subscription is destroyed when a notifier sends a NOTIFY request
// with a "Subscription-State" of "terminated".
if(Request.NOTIFY.equals(requestMethod) &&
(subscriptionStateHeader != null &&
SubscriptionStateHeader.TERMINATED.equalsIgnoreCase(subscriptionStateHeader.getState()))) {
sipSession.removeSubscription(sipServletRequest);
}
sipContext.exitSipApp(sipServletRequest, null);
}
//nothing more needs to be done, either the app acted as UA, PROXY or B2BUA. in any case we stop routing
}
};
getConcurrencyModelExecutorService(sipContext, sipServletMessage).execute(dispatchTask);
}
| public void dispatchMessage(final SipProvider sipProvider, SipServletMessageImpl sipServletMessage) throws DispatcherException {
final SipFactoryImpl sipFactoryImpl = sipApplicationDispatcher.getSipFactory();
final SipServletRequestImpl sipServletRequest = (SipServletRequestImpl) sipServletMessage;
if(logger.isDebugEnabled()) {
logger.debug("Routing of Subsequent Request " + sipServletRequest);
}
final Request request = (Request) sipServletRequest.getMessage();
final Dialog dialog = sipServletRequest.getDialog();
final RouteHeader poppedRouteHeader = sipServletRequest.getPoppedRouteHeader();
String applicationName = null;
String applicationId = null;
if(poppedRouteHeader != null){
final Parameters poppedAddress = (Parameters)poppedRouteHeader.getAddress().getURI();
//Extract information from the Route Header
final String applicationNameHashed = poppedAddress.getParameter(RR_PARAM_APPLICATION_NAME);
if(applicationNameHashed != null && applicationNameHashed.length() > 0) {
applicationName = sipApplicationDispatcher.getApplicationNameFromHash(applicationNameHashed);
applicationId = poppedAddress.getParameter(APP_ID);
}
}
if(applicationId == null) {
final ToHeader toHeader = (ToHeader) request.getHeader(ToHeader.NAME);
final String arText = toHeader.getTag();
final String[] tuple = ApplicationRoutingHeaderComposer.getAppNameAndSessionId(sipApplicationDispatcher, arText);
applicationName = tuple[0];
applicationId = tuple[1];
if(Request.ACK.equals(request.getMethod()) && applicationId == null && applicationName == null) {
//Means that this is an ACK to a container generated error response, so we can drop it
if(logger.isDebugEnabled()) {
logger.debug("The popped Route, application Id and name are null for an ACK, so this is an ACK to a container generated error response, so it is dropped");
}
return ;
}
}
boolean inverted = false;
if(dialog != null && !dialog.isServer()) {
inverted = true;
}
final SipContext sipContext = sipApplicationDispatcher.findSipApplication(applicationName);
if(sipContext == null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request +
"in this popped routed header " + poppedRouteHeader);
}
final SipManager sipManager = (SipManager)sipContext.getManager();
SipApplicationSessionKey sipApplicationSessionKey = SessionManagerUtil.getSipApplicationSessionKey(
applicationName,
applicationId);
MobicentsSipSession tmpSipSession = null;
MobicentsSipApplicationSession sipApplicationSession = sipManager.getSipApplicationSession(sipApplicationSessionKey, false);
if(sipApplicationSession == null) {
if(logger.isDebugEnabled()) {
sipManager.dumpSipApplicationSessions();
}
//trying the join or replaces matching sip app sessions
final SipApplicationSessionKey joinSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, JoinHeader.NAME);
final SipApplicationSessionKey replacesSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, ReplacesHeader.NAME);
if(joinSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(joinSipApplicationSessionKey, false);
sipApplicationSessionKey = joinSipApplicationSessionKey;
} else if(replacesSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(replacesSipApplicationSessionKey, false);
sipApplicationSessionKey = replacesSipApplicationSessionKey;
}
if(sipApplicationSession == null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip application session to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
}
}
SipSessionKey key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, inverted);
if(logger.isDebugEnabled()) {
logger.debug("Trying to find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
}
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
// Added by Vladimir because the inversion detection on proxied requests doesn't work
if(tmpSipSession == null) {
if(logger.isDebugEnabled()) {
logger.debug("Cannot find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute() + ". Trying inverted.");
}
key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, !inverted);
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
}
if(tmpSipSession == null) {
sipManager.dumpSipSessions();
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
} else {
if(logger.isDebugEnabled()) {
logger.debug("Inverted try worked. sip session found : " + tmpSipSession.getId());
}
}
final MobicentsSipSession sipSession = tmpSipSession;
sipServletRequest.setSipSession(sipSession);
// BEGIN validation delegated to the applicationas per JSIP patch for http://code.google.com/p/mobicents/issues/detail?id=766
if(request.getMethod().equalsIgnoreCase("ACK")) {
if(sipSession.isAckReceived()) {
// Filter out ACK retransmissions for JSIP patch for http://code.google.com/p/mobicents/issues/detail?id=766
logger.debug("ACK filtered out as a retransmission. This Sip Session already has been ACKed.");
return;
}
sipSession.setAckReceived(true);
}
//CSeq validation should only be done for non proxy applications
if(sipSession.getProxy() == null) {
CSeqHeader cseq = (CSeqHeader) request.getHeader(CSeqHeader.NAME);
long localCseq = sipSession.getCseq();
long remoteCseq = cseq.getSeqNumber();
if(localCseq>remoteCseq) {
logger.error("CSeq out of order for the following request");
SipServletResponse response = sipServletRequest.createResponse(500, "CSeq out of order");
try {
response.send();
} catch (IOException e) {
logger.error("Can not send error response", e);
}
}
sipSession.setCseq(remoteCseq);
}
// END of validation for http://code.google.com/p/mobicents/issues/detail?id=766
DispatchTask dispatchTask = new DispatchTask(sipServletRequest, sipProvider) {
public void dispatch() throws DispatcherException {
sipContext.enterSipApp(sipServletRequest, null, sipManager, true, true);
final String requestMethod = sipServletRequest.getMethod();
final SubscriptionStateHeader subscriptionStateHeader = (SubscriptionStateHeader)
sipServletRequest.getMessage().getHeader(SubscriptionStateHeader.NAME);
try {
sipSession.setSessionCreatingTransaction(sipServletRequest.getTransaction());
// JSR 289 Section 6.2.1 :
// any state transition caused by the reception of a SIP message,
// the state change must be accomplished by the container before calling
// the service() method of any SipServlet to handle the incoming message.
sipSession.updateStateOnSubsequentRequest(sipServletRequest, true);
try {
// RFC 3265 : If a matching NOTIFY request contains a "Subscription-State" of "active" or "pending", it creates
// a new subscription and a new dialog (unless they have already been
// created by a matching response, as described above).
if(Request.NOTIFY.equals(requestMethod) &&
(subscriptionStateHeader != null &&
SubscriptionStateHeader.ACTIVE.equalsIgnoreCase(subscriptionStateHeader.getState()) ||
SubscriptionStateHeader.PENDING.equalsIgnoreCase(subscriptionStateHeader.getState()))) {
sipSession.addSubscription(sipServletRequest);
}
// See if the subsequent request should go directly to the proxy
final ProxyImpl proxy = sipSession.getProxy();
if(proxy != null) {
final ProxyBranchImpl finalBranch = proxy.getFinalBranchForSubsequentRequests();
if(finalBranch != null) {
proxy.setAckReceived(requestMethod.equalsIgnoreCase(Request.ACK));
proxy.setOriginalRequest(sipServletRequest);
callServlet(sipServletRequest);
finalBranch.proxySubsequentRequest(sipServletRequest);
} else if(requestMethod.equals(Request.PRACK)) {
callServlet(sipServletRequest);
List<ProxyBranch> branches = proxy.getProxyBranches();
for(ProxyBranch pb : branches) {
ProxyBranchImpl proxyBranch = (ProxyBranchImpl) pb;
if(proxyBranch.isWaitingForPrack()) {
proxyBranch.proxyDialogStateless(sipServletRequest);
proxyBranch.setWaitingForPrack(false);
}
}
}
}
// If it's not for a proxy then it's just an AR, so go to the next application
else {
callServlet(sipServletRequest);
}
} catch (ServletException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
} catch (SipException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
} catch (IOException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
}
} finally {
// A subscription is destroyed when a notifier sends a NOTIFY request
// with a "Subscription-State" of "terminated".
if(Request.NOTIFY.equals(requestMethod) &&
(subscriptionStateHeader != null &&
SubscriptionStateHeader.TERMINATED.equalsIgnoreCase(subscriptionStateHeader.getState()))) {
sipSession.removeSubscription(sipServletRequest);
}
sipContext.exitSipApp(sipServletRequest, null);
}
//nothing more needs to be done, either the app acted as UA, PROXY or B2BUA. in any case we stop routing
}
};
getConcurrencyModelExecutorService(sipContext, sipServletMessage).execute(dispatchTask);
}
|
diff --git a/src/main/java/org/gwaspi/model/MatrixMetadata.java b/src/main/java/org/gwaspi/model/MatrixMetadata.java
index 71d854c5..6e9e7947 100644
--- a/src/main/java/org/gwaspi/model/MatrixMetadata.java
+++ b/src/main/java/org/gwaspi/model/MatrixMetadata.java
@@ -1,441 +1,443 @@
/*
* Copyright (C) 2013 Universitat Pompeu Fabra
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gwaspi.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import org.gwaspi.constants.cImport.ImportFormat;
import org.gwaspi.constants.cNetCDF.Defaults.GenotypeEncoding;
import org.gwaspi.constants.cNetCDF.Defaults.StrandType;
@Entity
@Table(name = "matrixMetadata")
@IdClass(MatrixKey.class)
@NamedQueries({
@NamedQuery(
name = "matrixMetadata_fetchById",
query = "SELECT mm FROM MatrixMetadata mm WHERE mm.matrixId = :id"),
@NamedQuery(
name = "matrixMetadata_fetchByNetCDFName",
query = "SELECT mm FROM MatrixMetadata mm WHERE mm.matrixNetCDFName = :netCDFName"),
@NamedQuery(
name = "matrixMetadata_listKeys",
query = "SELECT mm.studyId, mm.matrixId FROM MatrixMetadata mm"),
@NamedQuery(
name = "matrixMetadata_listIdsByStudyId",
query = "SELECT mm.matrixId FROM MatrixMetadata mm WHERE mm.studyId = :studyId"),
@NamedQuery(
name = "matrixMetadata_listIds",
query = "SELECT mm.matrixId FROM MatrixMetadata mm ORDER BY mm.matrixId"),
@NamedQuery(
name = "matrixMetadata_listByStudyId",
query = "SELECT mm FROM MatrixMetadata mm WHERE mm.studyId = :studyId"),
})
public class MatrixMetadata implements Serializable {
private int matrixId;
private String matrixFriendlyName;
private String matrixNetCDFName;
private String pathToMatrix;
private ImportFormat technology;
private String gwaspiDBVersion;
private String description;
private GenotypeEncoding gtEncoding;
private StrandType strand;
private boolean hasDictionray;
private int markerSetSize;
private int sampleSetSize;
private int studyId;
private String matrixType; // matrix_type VARCHAR(32) NOT NULL
private int parent1MatrixId;
private int parent2MatrixId;
private String inputLocation;
private Date creationDate;
protected MatrixMetadata() {
this.matrixId = Integer.MIN_VALUE;
this.matrixFriendlyName = "";
this.matrixNetCDFName = "";
this.pathToMatrix = "";
this.technology = ImportFormat.UNKNOWN;
this.gwaspiDBVersion = "";
this.description = "";
this.gtEncoding = null;
this.strand = null;
this.hasDictionray = false;
this.markerSetSize = Integer.MIN_VALUE;
this.sampleSetSize = Integer.MIN_VALUE;
this.studyId = Integer.MIN_VALUE;
this.matrixType = "";
this.parent1MatrixId = -1;
this.parent2MatrixId = -1;
this.inputLocation = "";
this.creationDate = new Date();
}
public MatrixMetadata(
String matrixFriendlyName,
String matrixNetCDFName,
String description,
GenotypeEncoding gtEncoding,
int studyId,
int parent1MatrixId,
int parent2MatrixId,
String inputLocation
)
{
this.matrixId = Integer.MIN_VALUE;
this.matrixFriendlyName = matrixFriendlyName;
this.matrixNetCDFName = matrixNetCDFName;
this.pathToMatrix = "";
this.technology = ImportFormat.UNKNOWN;
this.gwaspiDBVersion = "";
this.description = description;
this.gtEncoding = gtEncoding;
this.strand = null;
this.hasDictionray = false;
this.markerSetSize = Integer.MIN_VALUE;
this.sampleSetSize = Integer.MIN_VALUE;
this.studyId = studyId;
this.matrixType = "";
this.parent1MatrixId = parent1MatrixId;
this.parent2MatrixId = parent2MatrixId;
this.inputLocation = inputLocation;
this.creationDate = new Date();
}
public MatrixMetadata(
int matrixId,
String matrixFriendlyName,
String matrixNetCDFName,
String pathToMatrix,
ImportFormat technology,
String gwaspiDBVersion,
String description,
GenotypeEncoding gtEncoding,
StrandType strand,
boolean hasDictionray,
int markerSetSize,
int sampleSetSize,
int studyId,
String matrixType,
Date creationDate)
{
this.matrixId = matrixId;
this.matrixFriendlyName = matrixFriendlyName;
this.matrixNetCDFName = matrixNetCDFName;
this.pathToMatrix = pathToMatrix;
this.technology = technology;
this.gwaspiDBVersion = gwaspiDBVersion;
this.description = description;
this.gtEncoding = gtEncoding;
this.strand = strand;
this.hasDictionray = hasDictionray;
this.markerSetSize = markerSetSize;
this.sampleSetSize = sampleSetSize;
this.studyId = studyId;
this.matrixType = matrixType;
this.parent1MatrixId = -1;
this.parent2MatrixId = -1;
this.inputLocation = "";
- this.creationDate = (Date) creationDate.clone();
+ this.creationDate = (creationDate == null)
+ ? null
+ : (Date) creationDate.clone();
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MatrixMetadata other = (MatrixMetadata) obj;
if (this.getMatrixId() != other.getMatrixId()) {
return false;
}
if (this.getStudyId() != other.getStudyId()) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 3;
hash = 17 * hash + this.getMatrixId();
hash = 17 * hash + this.getStudyId();
return hash;
}
@Transient
public boolean getHasDictionray() {
return hasDictionray;
}
public void setHasDictionray(boolean hasDictionray) {
this.hasDictionray = hasDictionray;
}
@Id
@SequenceGenerator(name = "seqMatrixId")
@GeneratedValue(strategy = javax.persistence.GenerationType.TABLE, generator = "seqMatrixId")
@Column(
name = "matrixId",
unique = false,
nullable = false,
insertable = true,
updatable = false
)
public int getMatrixId() {
return matrixId;
}
protected void setMatrixId(int matrixId) {
this.matrixId = matrixId;
}
@Transient
public MatrixKey getKey() {
return new MatrixKey(getStudyId(), getMatrixId());
}
@Id
@Column(
name = "studyId",
unique = false,
nullable = false,
insertable = true,
updatable = false
)
public int getStudyId() {
return studyId;
}
protected void setStudyId(int studyId) {
this.studyId = studyId;
}
@Column(
name = "matrixFriendlyName",
length = 255,
unique = true,
nullable = false,
insertable = true,
updatable = false
)
public String getMatrixFriendlyName() {
return matrixFriendlyName;
}
protected void setMatrixFriendlyName(String matrixFriendlyName) {
this.matrixFriendlyName = matrixFriendlyName;
}
@Transient
public ImportFormat getTechnology() {
return technology;
}
public void setTechnology(ImportFormat technology) {
this.technology = technology;
}
@Transient
public String getGwaspiDBVersion() {
return gwaspiDBVersion;
}
public void setGwaspiDBVersion(String gwaspiDBVersion) {
this.gwaspiDBVersion = gwaspiDBVersion;
}
@Transient
public GenotypeEncoding getGenotypeEncoding() {
return gtEncoding;
}
public void setGenotypeEncoding(GenotypeEncoding gtEncoding) {
this.gtEncoding = gtEncoding;
}
@Transient
public int getMarkerSetSize() {
return markerSetSize;
}
public void setMarkerSetSize(int markerSetSize) {
this.markerSetSize = markerSetSize;
}
@Column(
name = "sampleSetSize",
unique = false,
nullable = false,
insertable = true,
updatable = false
)
@Transient
public int getSampleSetSize() {
return sampleSetSize;
}
public void setSampleSetSize(int sampleSetSize) {
this.sampleSetSize = sampleSetSize;
}
@Transient
public String getPathToMatrix() {
return pathToMatrix;
}
public void setPathToMatrix(String pathToMatrix) {
this.pathToMatrix = pathToMatrix;
}
@Transient
public StrandType getStrand() {
return strand;
}
public void setStrand(StrandType strand) {
this.strand = strand;
}
@Column(
name = "description",
length = 1023,
unique = false,
nullable = false,
insertable = true,
updatable = false
)
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Column(
name = "matrixNetCDFName",
length = 255,
unique = true,
nullable = false,
insertable = true,
updatable = false
)
public String getMatrixNetCDFName() {
return matrixNetCDFName;
}
protected void setMatrixNetCDFName(String matrixNetCDFName) {
this.matrixNetCDFName = matrixNetCDFName;
}
@Column(
name = "matrixType",
length = 31,
unique = false,
nullable = false,
insertable = true,
updatable = false
)
public String getMatrixType() {
return matrixType;
}
protected void setMatrixType(String matrixType) {
this.matrixType = matrixType;
}
@Column(
name = "parent1MatrixId",
unique = false,
nullable = false,
insertable = true,
updatable = false
)
public int getParent1MatrixId() {
return parent1MatrixId;
}
protected void setParent1MatrixId(int parent1MatrixId) {
this.parent1MatrixId = parent1MatrixId;
}
@Column(
name = "parent2MatrixId",
unique = false,
nullable = false,
insertable = true,
updatable = false
)
public int getParent2MatrixId() {
return parent2MatrixId;
}
protected void setParent2MatrixId(int parent2MatrixId) {
this.parent2MatrixId = parent2MatrixId;
}
@Column(
name = "inputLocation",
length = 1023,
unique = false,
nullable = false,
insertable = true,
updatable = false
)
public String getInputLocation() {
return inputLocation;
}
protected void setInputLocation(String inputLocation) {
this.inputLocation = inputLocation;
}
@Temporal(TemporalType.DATE)
@Column(
name = "creationDate",
unique = false,
nullable = false,
insertable = true,
updatable = false
)
public Date getCreationDate() {
return creationDate;
}
protected void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
}
| true | true | public MatrixMetadata(
int matrixId,
String matrixFriendlyName,
String matrixNetCDFName,
String pathToMatrix,
ImportFormat technology,
String gwaspiDBVersion,
String description,
GenotypeEncoding gtEncoding,
StrandType strand,
boolean hasDictionray,
int markerSetSize,
int sampleSetSize,
int studyId,
String matrixType,
Date creationDate)
{
this.matrixId = matrixId;
this.matrixFriendlyName = matrixFriendlyName;
this.matrixNetCDFName = matrixNetCDFName;
this.pathToMatrix = pathToMatrix;
this.technology = technology;
this.gwaspiDBVersion = gwaspiDBVersion;
this.description = description;
this.gtEncoding = gtEncoding;
this.strand = strand;
this.hasDictionray = hasDictionray;
this.markerSetSize = markerSetSize;
this.sampleSetSize = sampleSetSize;
this.studyId = studyId;
this.matrixType = matrixType;
this.parent1MatrixId = -1;
this.parent2MatrixId = -1;
this.inputLocation = "";
this.creationDate = (Date) creationDate.clone();
}
| public MatrixMetadata(
int matrixId,
String matrixFriendlyName,
String matrixNetCDFName,
String pathToMatrix,
ImportFormat technology,
String gwaspiDBVersion,
String description,
GenotypeEncoding gtEncoding,
StrandType strand,
boolean hasDictionray,
int markerSetSize,
int sampleSetSize,
int studyId,
String matrixType,
Date creationDate)
{
this.matrixId = matrixId;
this.matrixFriendlyName = matrixFriendlyName;
this.matrixNetCDFName = matrixNetCDFName;
this.pathToMatrix = pathToMatrix;
this.technology = technology;
this.gwaspiDBVersion = gwaspiDBVersion;
this.description = description;
this.gtEncoding = gtEncoding;
this.strand = strand;
this.hasDictionray = hasDictionray;
this.markerSetSize = markerSetSize;
this.sampleSetSize = sampleSetSize;
this.studyId = studyId;
this.matrixType = matrixType;
this.parent1MatrixId = -1;
this.parent2MatrixId = -1;
this.inputLocation = "";
this.creationDate = (creationDate == null)
? null
: (Date) creationDate.clone();
}
|
diff --git a/src/com/tactfactory/harmony/template/SQLiteAdapterGenerator.java b/src/com/tactfactory/harmony/template/SQLiteAdapterGenerator.java
index e16fc2e7..e68c976b 100644
--- a/src/com/tactfactory/harmony/template/SQLiteAdapterGenerator.java
+++ b/src/com/tactfactory/harmony/template/SQLiteAdapterGenerator.java
@@ -1,164 +1,164 @@
/**
* This file is part of the Harmony package.
*
* (c) Mickael Gaillard <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package com.tactfactory.harmony.template;
import com.tactfactory.harmony.meta.ClassMetadata;
import com.tactfactory.harmony.plateforme.BaseAdapter;
import com.tactfactory.harmony.utils.ConsoleUtils;
import com.tactfactory.harmony.utils.PackageUtils;
/**
* SQLite Adapters generator.
*/
public class SQLiteAdapterGenerator extends BaseGenerator {
/** The local name space. */
private String localNameSpace;
/**
* Constructor.
* @param adapter The adapter to use
* @throws Exception if adapter is null
*/
public SQLiteAdapterGenerator(final BaseAdapter adapter) throws Exception {
super(adapter);
this.setDatamodel(this.getAppMetas().toMap(this.getAdapter()));
}
/**
* Generate the adapters and the criterias.
*/
public final void generateAll() {
ConsoleUtils.display(">> Generate Adapter...");
for (final ClassMetadata classMeta
: this.getAppMetas().getEntities().values()) {
if (!classMeta.getFields().isEmpty()) {
this.localNameSpace = this.getAdapter().getNameSpace(
classMeta, this.getAdapter().getData());
this.getDatamodel().put(
TagConstant.CURRENT_ENTITY, classMeta.getName());
this.generate();
}
}
ConsoleUtils.display(">> Generate CriteriaBase...");
this.makeSourceCriteria(
"base/Criteria.java",
- "base/Criteria.java", false);
+ "base/Criteria.java", true);
this.makeSourceCriteria(
"base/CriteriasBase.java",
"base/CriteriasBase.java", true);
this.makeSourceCriteria(
"base/ICriteria.java",
- "base/ICriteria.java", false);
+ "base/ICriteria.java", true);
this.makeSourceCriteria(
"base/value/CriteriaValue.java",
- "base/value/CriteriaValue.java", false);
+ "base/value/CriteriaValue.java", true);
this.makeSourceCriteria(
"base/value/StringValue.java",
- "base/value/StringValue.java", false);
+ "base/value/StringValue.java", true);
this.makeSourceCriteria(
"base/value/ArrayValue.java",
- "base/value/ArrayValue.java", false);
+ "base/value/ArrayValue.java", true);
this.makeSourceCriteria(
"base/value/SelectValue.java",
- "base/value/SelectValue.java", false);
+ "base/value/SelectValue.java", true);
this.makeSourceCriteria(
"base/value/MethodValue.java",
- "base/value/MethodValue.java", false);
+ "base/value/MethodValue.java", true);
this.makeSourceCriteria(
"base/value/DateTimeValue.java",
- "base/value/DateTimeValue.java", false);
+ "base/value/DateTimeValue.java", true);
}
/**
* Generate the current entity's adapters and criteria.
*/
private void generate() {
// Info
ConsoleUtils.display(">>> Generate Adapter for "
+ this.getDatamodel().get(TagConstant.CURRENT_ENTITY));
try {
this.makeSourceControler(
"base/TemplateSQLiteAdapterBase.java",
"base/%sSQLiteAdapterBase.java", true);
this.makeSourceControler(
"TemplateSQLiteAdapter.java",
"%sSQLiteAdapter.java", false);
} catch (final Exception e) {
ConsoleUtils.displayError(e);
}
// Info
ConsoleUtils.display(">>> Generate Criterias for "
+ this.getDatamodel().get(TagConstant.CURRENT_ENTITY));
try {
this.makeSourceCriteria(
"TemplateCriterias.java",
"%sCriterias.java", false);
} catch (final Exception e) {
ConsoleUtils.displayError(e);
}
}
/**
* Make Java Source Code.
*
* @param template Template path file.
* For list activity is "TemplateListActivity.java"
* @param filename The destination file
* @param override True if must overwrite file.
*/
private void makeSourceControler(final String template,
final String filename,
final boolean override) {
final String fullFilePath = String.format("%s%s/%s",
this.getAdapter().getSourcePath(),
PackageUtils.extractPath(this.localNameSpace).toLowerCase(),
String.format(filename,
this.getDatamodel().get(TagConstant.CURRENT_ENTITY)));
final String fullTemplatePath =
this.getAdapter().getTemplateSourceProviderPath()
+ template;
super.makeSource(fullTemplatePath, fullFilePath, override);
}
/**
* Make Java Source Code.
*
* @param template Template path file.
* For list activity is "TemplateListActivity.java"
* @param filename Destination file name
* @param override True if must overwrite file.
*/
private void makeSourceCriteria(final String template,
final String filename,
final boolean override) {
final String fullFilePath = String.format("%s%s/%s/%s",
this.getAdapter().getSourcePath(),
this.getAppMetas().getProjectNameSpace(),
this.getAdapter().getCriterias(),
String.format(filename,
this.getDatamodel().get(TagConstant.CURRENT_ENTITY)));
final String fullTemplatePath =
this.getAdapter().getTemplateSourceCriteriasPath()
+ template;
super.makeSource(fullTemplatePath, fullFilePath, override);
}
}
| false | true | public final void generateAll() {
ConsoleUtils.display(">> Generate Adapter...");
for (final ClassMetadata classMeta
: this.getAppMetas().getEntities().values()) {
if (!classMeta.getFields().isEmpty()) {
this.localNameSpace = this.getAdapter().getNameSpace(
classMeta, this.getAdapter().getData());
this.getDatamodel().put(
TagConstant.CURRENT_ENTITY, classMeta.getName());
this.generate();
}
}
ConsoleUtils.display(">> Generate CriteriaBase...");
this.makeSourceCriteria(
"base/Criteria.java",
"base/Criteria.java", false);
this.makeSourceCriteria(
"base/CriteriasBase.java",
"base/CriteriasBase.java", true);
this.makeSourceCriteria(
"base/ICriteria.java",
"base/ICriteria.java", false);
this.makeSourceCriteria(
"base/value/CriteriaValue.java",
"base/value/CriteriaValue.java", false);
this.makeSourceCriteria(
"base/value/StringValue.java",
"base/value/StringValue.java", false);
this.makeSourceCriteria(
"base/value/ArrayValue.java",
"base/value/ArrayValue.java", false);
this.makeSourceCriteria(
"base/value/SelectValue.java",
"base/value/SelectValue.java", false);
this.makeSourceCriteria(
"base/value/MethodValue.java",
"base/value/MethodValue.java", false);
this.makeSourceCriteria(
"base/value/DateTimeValue.java",
"base/value/DateTimeValue.java", false);
}
| public final void generateAll() {
ConsoleUtils.display(">> Generate Adapter...");
for (final ClassMetadata classMeta
: this.getAppMetas().getEntities().values()) {
if (!classMeta.getFields().isEmpty()) {
this.localNameSpace = this.getAdapter().getNameSpace(
classMeta, this.getAdapter().getData());
this.getDatamodel().put(
TagConstant.CURRENT_ENTITY, classMeta.getName());
this.generate();
}
}
ConsoleUtils.display(">> Generate CriteriaBase...");
this.makeSourceCriteria(
"base/Criteria.java",
"base/Criteria.java", true);
this.makeSourceCriteria(
"base/CriteriasBase.java",
"base/CriteriasBase.java", true);
this.makeSourceCriteria(
"base/ICriteria.java",
"base/ICriteria.java", true);
this.makeSourceCriteria(
"base/value/CriteriaValue.java",
"base/value/CriteriaValue.java", true);
this.makeSourceCriteria(
"base/value/StringValue.java",
"base/value/StringValue.java", true);
this.makeSourceCriteria(
"base/value/ArrayValue.java",
"base/value/ArrayValue.java", true);
this.makeSourceCriteria(
"base/value/SelectValue.java",
"base/value/SelectValue.java", true);
this.makeSourceCriteria(
"base/value/MethodValue.java",
"base/value/MethodValue.java", true);
this.makeSourceCriteria(
"base/value/DateTimeValue.java",
"base/value/DateTimeValue.java", true);
}
|
diff --git a/src/main/java/org/apache/commons/digester3/annotations/handlers/FactoryCreateHandler.java b/src/main/java/org/apache/commons/digester3/annotations/handlers/FactoryCreateHandler.java
index 2c86eabf..60f82fa0 100644
--- a/src/main/java/org/apache/commons/digester3/annotations/handlers/FactoryCreateHandler.java
+++ b/src/main/java/org/apache/commons/digester3/annotations/handlers/FactoryCreateHandler.java
@@ -1,53 +1,53 @@
package org.apache.commons.digester3.annotations.handlers;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.commons.digester3.annotations.AnnotationHandler;
import org.apache.commons.digester3.annotations.rules.FactoryCreate;
import org.apache.commons.digester3.binder.FactoryCreateBuilder;
import org.apache.commons.digester3.binder.RulesBinder;
/**
* {@link FactoryCreate} handler.
*
* @since 3.0
*/
public final class FactoryCreateHandler
implements AnnotationHandler<FactoryCreate, Class<?>>
{
/**
* {@inheritDoc}
*/
public void handle( FactoryCreate annotation, Class<?> element, RulesBinder rulesBinder )
{
- FactoryCreateBuilder builder = rulesBinder.forPattern(annotation.pattern())
- .withNamespaceURI(annotation.namespaceURI())
+ FactoryCreateBuilder builder = rulesBinder.forPattern( annotation.pattern() )
+ .withNamespaceURI( annotation.namespaceURI() )
.factoryCreate()
- .overriddenByAttribute(annotation.attributeName().length() > 0 ? annotation.attributeName() : null)
- .ignoreCreateExceptions(annotation.ignoreCreateExceptions());
+ .overriddenByAttribute( annotation.attributeName().length() > 0 ? annotation.attributeName() : null )
+ .ignoreCreateExceptions( annotation.ignoreCreateExceptions() );
if ( FactoryCreate.DefaultObjectCreationFactory.class != annotation.factoryClass() )
{
builder.ofType( annotation.factoryClass() );
}
}
}
| false | true | public void handle( FactoryCreate annotation, Class<?> element, RulesBinder rulesBinder )
{
FactoryCreateBuilder builder = rulesBinder.forPattern(annotation.pattern())
.withNamespaceURI(annotation.namespaceURI())
.factoryCreate()
.overriddenByAttribute(annotation.attributeName().length() > 0 ? annotation.attributeName() : null)
.ignoreCreateExceptions(annotation.ignoreCreateExceptions());
if ( FactoryCreate.DefaultObjectCreationFactory.class != annotation.factoryClass() )
{
builder.ofType( annotation.factoryClass() );
}
}
| public void handle( FactoryCreate annotation, Class<?> element, RulesBinder rulesBinder )
{
FactoryCreateBuilder builder = rulesBinder.forPattern( annotation.pattern() )
.withNamespaceURI( annotation.namespaceURI() )
.factoryCreate()
.overriddenByAttribute( annotation.attributeName().length() > 0 ? annotation.attributeName() : null )
.ignoreCreateExceptions( annotation.ignoreCreateExceptions() );
if ( FactoryCreate.DefaultObjectCreationFactory.class != annotation.factoryClass() )
{
builder.ofType( annotation.factoryClass() );
}
}
|
diff --git a/src/com/android/settings/wifi/WifiConfigController.java b/src/com/android/settings/wifi/WifiConfigController.java
index 3efedf604..0d2429886 100644
--- a/src/com/android/settings/wifi/WifiConfigController.java
+++ b/src/com/android/settings/wifi/WifiConfigController.java
@@ -1,733 +1,732 @@
/*
* 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.settings.wifi;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.net.DhcpInfo;
import android.net.LinkAddress;
import android.net.LinkProperties;
import android.net.NetworkInfo.DetailedState;
import android.net.NetworkUtils;
import android.net.Proxy;
import android.net.ProxyProperties;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.IpAssignment;
import android.net.wifi.WifiConfiguration.AuthAlgorithm;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WpsConfiguration;
import android.net.wifi.WpsConfiguration.Setup;
import static android.net.wifi.WifiConfiguration.INVALID_NETWORK_ID;
import android.net.wifi.WifiConfiguration.ProxySettings;
import android.net.wifi.WifiInfo;
import android.security.Credentials;
import android.security.KeyStore;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.settings.ProxySelector;
import com.android.settings.R;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Iterator;
/**
* The class for allowing UIs like {@link WifiDialog} and {@link WifiConfigPreference} to
* share the logic for controlling buttons, text fields, etc.
*/
public class WifiConfigController implements TextWatcher,
View.OnClickListener, AdapterView.OnItemSelectedListener {
private static final String KEYSTORE_SPACE = "keystore://";
private final WifiConfigUiBase mConfigUi;
private final View mView;
private final AccessPoint mAccessPoint;
private boolean mEdit;
private TextView mSsidView;
// e.g. AccessPoint.SECURITY_NONE
private int mAccessPointSecurity;
private TextView mPasswordView;
private Spinner mSecuritySpinner;
private Spinner mEapMethodSpinner;
private Spinner mEapCaCertSpinner;
private Spinner mPhase2Spinner;
private Spinner mEapUserCertSpinner;
private TextView mEapIdentityView;
private TextView mEapAnonymousView;
/* This value comes from "wifi_ip_settings" resource array */
private static final int DHCP = 0;
private static final int STATIC_IP = 1;
/* These values come from "wifi_network_setup" resource array */
public static final int MANUAL = 0;
public static final int WPS_PBC = 1;
public static final int WPS_PIN_FROM_ACCESS_POINT = 2;
public static final int WPS_PIN_FROM_DEVICE = 3;
/* These values come from "wifi_proxy_settings" resource array */
public static final int PROXY_NONE = 0;
public static final int PROXY_STATIC = 1;
private static final String TAG = "WifiConfigController";
private Spinner mNetworkSetupSpinner;
private Spinner mIpSettingsSpinner;
private TextView mIpAddressView;
private TextView mGatewayView;
private TextView mNetworkPrefixLengthView;
private TextView mDns1View;
private TextView mDns2View;
private Spinner mProxySettingsSpinner;
private TextView mProxyHostView;
private TextView mProxyPortView;
private TextView mProxyExclusionListView;
private IpAssignment mIpAssignment;
private ProxySettings mProxySettings;
private LinkProperties mLinkProperties = new LinkProperties();
// True when this instance is used in SetupWizard XL context.
private final boolean mInXlSetupWizard;
static boolean requireKeyStore(WifiConfiguration config) {
if (config == null) {
return false;
}
String values[] = {config.ca_cert.value(), config.client_cert.value(),
config.private_key.value()};
for (String value : values) {
if (value != null && value.startsWith(KEYSTORE_SPACE)) {
return true;
}
}
return false;
}
public WifiConfigController(
WifiConfigUiBase parent, View view, AccessPoint accessPoint, boolean edit) {
mConfigUi = parent;
mInXlSetupWizard = (parent instanceof WifiConfigUiForSetupWizardXL);
mView = view;
mAccessPoint = accessPoint;
mAccessPointSecurity = (accessPoint == null) ? AccessPoint.SECURITY_NONE :
accessPoint.security;
mEdit = edit;
final Context context = mConfigUi.getContext();
final Resources resources = context.getResources();
if (mAccessPoint == null) { // new network
mConfigUi.setTitle(R.string.wifi_add_network);
mSsidView = (TextView) mView.findViewById(R.id.ssid);
mSsidView.addTextChangedListener(this);
mSecuritySpinner = ((Spinner) mView.findViewById(R.id.security));
mSecuritySpinner.setOnItemSelectedListener(this);
if (mInXlSetupWizard) {
mView.findViewById(R.id.type_ssid).setVisibility(View.VISIBLE);
mView.findViewById(R.id.type_security).setVisibility(View.VISIBLE);
// We want custom layout. The content must be same as the other cases.
mSecuritySpinner.setAdapter(
new ArrayAdapter<String>(context, R.layout.wifi_setup_custom_list_item_1,
android.R.id.text1,
context.getResources().getStringArray(R.array.wifi_security)));
} else {
mView.findViewById(R.id.type).setVisibility(View.VISIBLE);
}
mConfigUi.setSubmitButton(context.getString(R.string.wifi_save));
} else {
mConfigUi.setTitle(mAccessPoint.ssid);
mIpSettingsSpinner = (Spinner) mView.findViewById(R.id.ip_settings);
mIpSettingsSpinner.setOnItemSelectedListener(this);
mProxySettingsSpinner = (Spinner) mView.findViewById(R.id.proxy_settings);
mProxySettingsSpinner.setOnItemSelectedListener(this);
ViewGroup group = (ViewGroup) mView.findViewById(R.id.info);
DetailedState state = mAccessPoint.getState();
if (state != null) {
addRow(group, R.string.wifi_status, Summary.get(mConfigUi.getContext(), state));
}
String[] type = resources.getStringArray(R.array.wifi_security);
addRow(group, R.string.wifi_security, type[mAccessPoint.security]);
int level = mAccessPoint.getLevel();
if (level != -1) {
String[] signal = resources.getStringArray(R.array.wifi_signal);
addRow(group, R.string.wifi_signal, signal[level]);
}
WifiInfo info = mAccessPoint.getInfo();
if (info != null) {
addRow(group, R.string.wifi_speed, info.getLinkSpeed() + WifiInfo.LINK_SPEED_UNITS);
- // TODO: fix the ip address for IPv6.
- int address = info.getIpAddress();
- if (address != 0) {
- addRow(group, R.string.wifi_ip_address, Formatter.formatIpAddress(address));
- }
}
if (mAccessPoint.networkId != INVALID_NETWORK_ID) {
WifiConfiguration config = mAccessPoint.getConfig();
if (config.ipAssignment == IpAssignment.STATIC) {
mIpSettingsSpinner.setSelection(STATIC_IP);
} else {
mIpSettingsSpinner.setSelection(DHCP);
+ //Display IP addresses
+ for(InetAddress a : config.linkProperties.getAddresses()) {
+ addRow(group, R.string.wifi_ip_address, a.getHostAddress());
+ }
}
if (config.proxySettings == ProxySettings.STATIC) {
mProxySettingsSpinner.setSelection(PROXY_STATIC);
} else {
mProxySettingsSpinner.setSelection(PROXY_NONE);
}
}
/* Show network setup options only for a new network */
if (mAccessPoint.networkId == INVALID_NETWORK_ID && mAccessPoint.wpsAvailable) {
showNetworkSetupFields();
}
if (mAccessPoint.networkId == INVALID_NETWORK_ID || mEdit) {
showSecurityFields();
showIpConfigFields();
showProxyFields();
}
if (mEdit) {
mConfigUi.setSubmitButton(context.getString(R.string.wifi_save));
} else {
if (state == null && level != -1) {
mConfigUi.setSubmitButton(context.getString(R.string.wifi_connect));
} else {
mView.findViewById(R.id.ip_fields).setVisibility(View.GONE);
}
if (mAccessPoint.networkId != INVALID_NETWORK_ID) {
mConfigUi.setForgetButton(context.getString(R.string.wifi_forget));
}
}
}
mConfigUi.setCancelButton(context.getString(R.string.wifi_cancel));
if (mConfigUi.getSubmitButton() != null) {
enableSubmitIfAppropriate();
}
}
private void addRow(ViewGroup group, int name, String value) {
View row = mConfigUi.getLayoutInflater().inflate(R.layout.wifi_dialog_row, group, false);
((TextView) row.findViewById(R.id.name)).setText(name);
((TextView) row.findViewById(R.id.value)).setText(value);
group.addView(row);
}
/* show submit button if the password is valid */
private void enableSubmitIfAppropriate() {
if ((mSsidView != null && mSsidView.length() == 0) ||
((mAccessPoint == null || mAccessPoint.networkId == INVALID_NETWORK_ID) &&
((mAccessPointSecurity == AccessPoint.SECURITY_WEP && mPasswordView.length() == 0) ||
(mAccessPointSecurity == AccessPoint.SECURITY_PSK && mPasswordView.length() < 8)))) {
mConfigUi.getSubmitButton().setEnabled(false);
} else {
mConfigUi.getSubmitButton().setEnabled(true);
}
}
/* package */ WifiConfiguration getConfig() {
if (mAccessPoint != null && mAccessPoint.networkId != INVALID_NETWORK_ID && !mEdit) {
return null;
}
WifiConfiguration config = new WifiConfiguration();
if (mAccessPoint == null) {
config.SSID = AccessPoint.convertToQuotedString(
mSsidView.getText().toString());
// If the user adds a network manually, assume that it is hidden.
config.hiddenSSID = true;
} else if (mAccessPoint.networkId == INVALID_NETWORK_ID) {
config.SSID = AccessPoint.convertToQuotedString(
mAccessPoint.ssid);
} else {
config.networkId = mAccessPoint.networkId;
}
switch (mAccessPointSecurity) {
case AccessPoint.SECURITY_NONE:
config.allowedKeyManagement.set(KeyMgmt.NONE);
break;
case AccessPoint.SECURITY_WEP:
config.allowedKeyManagement.set(KeyMgmt.NONE);
config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
if (mPasswordView.length() != 0) {
int length = mPasswordView.length();
String password = mPasswordView.getText().toString();
// WEP-40, WEP-104, and 256-bit WEP (WEP-232?)
if ((length == 10 || length == 26 || length == 58) &&
password.matches("[0-9A-Fa-f]*")) {
config.wepKeys[0] = password;
} else {
config.wepKeys[0] = '"' + password + '"';
}
}
break;
case AccessPoint.SECURITY_PSK:
config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
if (mPasswordView.length() != 0) {
String password = mPasswordView.getText().toString();
if (password.matches("[0-9A-Fa-f]{64}")) {
config.preSharedKey = password;
} else {
config.preSharedKey = '"' + password + '"';
}
}
break;
case AccessPoint.SECURITY_EAP:
config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
config.eap.setValue((String) mEapMethodSpinner.getSelectedItem());
config.phase2.setValue((mPhase2Spinner.getSelectedItemPosition() == 0) ? "" :
"auth=" + mPhase2Spinner.getSelectedItem());
config.ca_cert.setValue((mEapCaCertSpinner.getSelectedItemPosition() == 0) ? "" :
KEYSTORE_SPACE + Credentials.CA_CERTIFICATE +
(String) mEapCaCertSpinner.getSelectedItem());
config.client_cert.setValue((mEapUserCertSpinner.getSelectedItemPosition() == 0) ?
"" : KEYSTORE_SPACE + Credentials.USER_CERTIFICATE +
(String) mEapUserCertSpinner.getSelectedItem());
config.private_key.setValue((mEapUserCertSpinner.getSelectedItemPosition() == 0) ?
"" : KEYSTORE_SPACE + Credentials.USER_PRIVATE_KEY +
(String) mEapUserCertSpinner.getSelectedItem());
config.identity.setValue((mEapIdentityView.length() == 0) ? "" :
mEapIdentityView.getText().toString());
config.anonymous_identity.setValue((mEapAnonymousView.length() == 0) ? "" :
mEapAnonymousView.getText().toString());
if (mPasswordView.length() != 0) {
config.password.setValue(mPasswordView.getText().toString());
}
break;
default:
return null;
}
validateAndFetchIpAndProxyFields();
config.proxySettings = mProxySettings;
config.ipAssignment = mIpAssignment;
config.linkProperties = new LinkProperties(mLinkProperties);
return config;
}
private void validateAndFetchIpAndProxyFields() {
mLinkProperties.clear();
mIpAssignment = (mIpSettingsSpinner != null &&
mIpSettingsSpinner.getSelectedItemPosition() == STATIC_IP) ?
IpAssignment.STATIC : IpAssignment.DHCP;
if (mIpAssignment == IpAssignment.STATIC) {
//TODO: A better way to do this is to not dismiss the
//dialog as long as one of the fields is invalid
int result = validateIpConfigFields(mLinkProperties);
if (result != 0) {
mLinkProperties.clear();
Toast.makeText(mConfigUi.getContext(), result, Toast.LENGTH_LONG).show();
mIpAssignment = IpAssignment.UNASSIGNED;
}
}
mProxySettings = (mProxySettingsSpinner != null &&
mProxySettingsSpinner.getSelectedItemPosition() == PROXY_STATIC) ?
ProxySettings.STATIC : ProxySettings.NONE;
if (mProxySettings == ProxySettings.STATIC) {
String host = mProxyHostView.getText().toString();
String portStr = mProxyPortView.getText().toString();
String exclusionList = mProxyExclusionListView.getText().toString();
int port = 0;
int result = 0;
try {
port = Integer.parseInt(portStr);
result = ProxySelector.validate(host, portStr, exclusionList);
} catch (NumberFormatException e) {
result = R.string.proxy_error_invalid_port;
}
if (result == 0) {
ProxyProperties proxyProperties= new ProxyProperties(host, port, exclusionList);
mLinkProperties.setHttpProxy(proxyProperties);
} else {
Toast.makeText(mConfigUi.getContext(), result, Toast.LENGTH_LONG).show();
mProxySettings = ProxySettings.UNASSIGNED;
}
}
}
private int validateIpConfigFields(LinkProperties linkProperties) {
String ipAddr = mIpAddressView.getText().toString();
InetAddress inetAddr = null;
try {
inetAddr = NetworkUtils.numericToInetAddress(ipAddr);
} catch (IllegalArgumentException e) {
return R.string.wifi_ip_settings_invalid_ip_address;
}
int networkPrefixLength = -1;
try {
networkPrefixLength = Integer.parseInt(mNetworkPrefixLengthView.getText().toString());
} catch (NumberFormatException e) { }
if (networkPrefixLength < 0 || networkPrefixLength > 32) {
return R.string.wifi_ip_settings_invalid_network_prefix_length;
}
linkProperties.addLinkAddress(new LinkAddress(inetAddr, networkPrefixLength));
String gateway = mGatewayView.getText().toString();
InetAddress gatewayAddr = null;
try {
gatewayAddr = NetworkUtils.numericToInetAddress(gateway);
} catch (IllegalArgumentException e) {
return R.string.wifi_ip_settings_invalid_gateway;
}
linkProperties.addGateway(gatewayAddr);
String dns = mDns1View.getText().toString();
InetAddress dnsAddr = null;
try {
dnsAddr = NetworkUtils.numericToInetAddress(dns);
} catch (IllegalArgumentException e) {
return R.string.wifi_ip_settings_invalid_dns;
}
linkProperties.addDns(dnsAddr);
if (mDns2View.length() > 0) {
dns = mDns2View.getText().toString();
try {
dnsAddr = NetworkUtils.numericToInetAddress(dns);
} catch (IllegalArgumentException e) {
return R.string.wifi_ip_settings_invalid_dns;
}
linkProperties.addDns(dnsAddr);
}
return 0;
}
int chosenNetworkSetupMethod() {
if (mNetworkSetupSpinner != null) {
return mNetworkSetupSpinner.getSelectedItemPosition();
}
return MANUAL;
}
WpsConfiguration getWpsConfig() {
WpsConfiguration config = new WpsConfiguration();
switch (mNetworkSetupSpinner.getSelectedItemPosition()) {
case WPS_PBC:
config.setup = Setup.PBC;
break;
case WPS_PIN_FROM_ACCESS_POINT:
config.setup = Setup.PIN_FROM_ACCESS_POINT;
break;
case WPS_PIN_FROM_DEVICE:
config.setup = Setup.PIN_FROM_DEVICE;
break;
default:
config.setup = Setup.INVALID;
Log.e(TAG, "WPS not selected type");
return config;
}
config.pin = ((TextView) mView.findViewById(R.id.wps_pin)).getText().toString();
config.BSSID = (mAccessPoint != null) ? mAccessPoint.bssid : null;
validateAndFetchIpAndProxyFields();
config.proxySettings = mProxySettings;
config.ipAssignment = mIpAssignment;
config.linkProperties = new LinkProperties(mLinkProperties);
return config;
}
private void showSecurityFields() {
if (mInXlSetupWizard) {
// Note: XL SetupWizard won't hide "EAP" settings here.
if (!((WifiSettingsForSetupWizardXL)mConfigUi.getContext()).initSecurityFields(mView,
mAccessPointSecurity)) {
return;
}
}
if (mAccessPointSecurity == AccessPoint.SECURITY_NONE) {
mView.findViewById(R.id.security_fields).setVisibility(View.GONE);
return;
}
mView.findViewById(R.id.security_fields).setVisibility(View.VISIBLE);
if (mPasswordView == null) {
mPasswordView = (TextView) mView.findViewById(R.id.password);
mPasswordView.addTextChangedListener(this);
((CheckBox) mView.findViewById(R.id.show_password)).setOnClickListener(this);
if (mAccessPoint != null && mAccessPoint.networkId != INVALID_NETWORK_ID) {
mPasswordView.setHint(R.string.wifi_unchanged);
}
}
if (mAccessPointSecurity != AccessPoint.SECURITY_EAP) {
mView.findViewById(R.id.eap).setVisibility(View.GONE);
return;
}
mView.findViewById(R.id.eap).setVisibility(View.VISIBLE);
if (mEapMethodSpinner == null) {
mEapMethodSpinner = (Spinner) mView.findViewById(R.id.method);
mPhase2Spinner = (Spinner) mView.findViewById(R.id.phase2);
mEapCaCertSpinner = (Spinner) mView.findViewById(R.id.ca_cert);
mEapUserCertSpinner = (Spinner) mView.findViewById(R.id.user_cert);
mEapIdentityView = (TextView) mView.findViewById(R.id.identity);
mEapAnonymousView = (TextView) mView.findViewById(R.id.anonymous);
loadCertificates(mEapCaCertSpinner, Credentials.CA_CERTIFICATE);
loadCertificates(mEapUserCertSpinner, Credentials.USER_PRIVATE_KEY);
if (mAccessPoint != null && mAccessPoint.networkId != INVALID_NETWORK_ID) {
WifiConfiguration config = mAccessPoint.getConfig();
setSelection(mEapMethodSpinner, config.eap.value());
setSelection(mPhase2Spinner, config.phase2.value());
setCertificate(mEapCaCertSpinner, Credentials.CA_CERTIFICATE,
config.ca_cert.value());
setCertificate(mEapUserCertSpinner, Credentials.USER_PRIVATE_KEY,
config.private_key.value());
mEapIdentityView.setText(config.identity.value());
mEapAnonymousView.setText(config.anonymous_identity.value());
}
}
}
private void showNetworkSetupFields() {
mView.findViewById(R.id.setup_fields).setVisibility(View.VISIBLE);
if (mNetworkSetupSpinner == null) {
mNetworkSetupSpinner = (Spinner) mView.findViewById(R.id.network_setup);
mNetworkSetupSpinner.setOnItemSelectedListener(this);
}
int pos = mNetworkSetupSpinner.getSelectedItemPosition();
/* Show pin text input if needed */
if (pos == WPS_PIN_FROM_ACCESS_POINT) {
mView.findViewById(R.id.wps_fields).setVisibility(View.VISIBLE);
} else {
mView.findViewById(R.id.wps_fields).setVisibility(View.GONE);
}
/* show/hide manual security fields appropriately */
if ((pos == WPS_PIN_FROM_ACCESS_POINT) || (pos == WPS_PIN_FROM_DEVICE)
|| (pos == WPS_PBC)) {
mView.findViewById(R.id.security_fields).setVisibility(View.GONE);
} else {
mView.findViewById(R.id.security_fields).setVisibility(View.VISIBLE);
}
}
private void showIpConfigFields() {
WifiConfiguration config = null;
mView.findViewById(R.id.ip_fields).setVisibility(View.VISIBLE);
if (mAccessPoint != null && mAccessPoint.networkId != INVALID_NETWORK_ID) {
config = mAccessPoint.getConfig();
}
if (mIpSettingsSpinner.getSelectedItemPosition() == STATIC_IP) {
mView.findViewById(R.id.staticip).setVisibility(View.VISIBLE);
if (mIpAddressView == null) {
mIpAddressView = (TextView) mView.findViewById(R.id.ipaddress);
mGatewayView = (TextView) mView.findViewById(R.id.gateway);
mNetworkPrefixLengthView = (TextView) mView.findViewById(
R.id.network_prefix_length);
mDns1View = (TextView) mView.findViewById(R.id.dns1);
mDns2View = (TextView) mView.findViewById(R.id.dns2);
}
if (config != null) {
LinkProperties linkProperties = config.linkProperties;
Iterator<LinkAddress> iterator = linkProperties.getLinkAddresses().iterator();
if (iterator.hasNext()) {
LinkAddress linkAddress = iterator.next();
mIpAddressView.setText(linkAddress.getAddress().getHostAddress());
mNetworkPrefixLengthView.setText(Integer.toString(linkAddress
.getNetworkPrefixLength()));
}
Iterator<InetAddress>gateways = linkProperties.getGateways().iterator();
if (gateways.hasNext()) {
mGatewayView.setText(gateways.next().getHostAddress());
}
Iterator<InetAddress> dnsIterator = linkProperties.getDnses().iterator();
if (dnsIterator.hasNext()) {
mDns1View.setText(dnsIterator.next().getHostAddress());
}
if (dnsIterator.hasNext()) {
mDns2View.setText(dnsIterator.next().getHostAddress());
}
}
} else {
mView.findViewById(R.id.staticip).setVisibility(View.GONE);
}
}
private void showProxyFields() {
WifiConfiguration config = null;
mView.findViewById(R.id.proxy_settings_fields).setVisibility(View.VISIBLE);
if (mAccessPoint != null && mAccessPoint.networkId != INVALID_NETWORK_ID) {
config = mAccessPoint.getConfig();
}
if (mProxySettingsSpinner.getSelectedItemPosition() == PROXY_STATIC) {
mView.findViewById(R.id.proxy_warning_limited_support).setVisibility(View.VISIBLE);
mView.findViewById(R.id.proxy_fields).setVisibility(View.VISIBLE);
if (mProxyHostView == null) {
mProxyHostView = (TextView) mView.findViewById(R.id.proxy_hostname);
mProxyPortView = (TextView) mView.findViewById(R.id.proxy_port);
mProxyExclusionListView = (TextView) mView.findViewById(R.id.proxy_exclusionlist);
}
if (config != null) {
ProxyProperties proxyProperties = config.linkProperties.getHttpProxy();
if (proxyProperties != null) {
mProxyHostView.setText(proxyProperties.getHost());
mProxyPortView.setText(Integer.toString(proxyProperties.getPort()));
mProxyExclusionListView.setText(proxyProperties.getExclusionList());
}
}
} else {
mView.findViewById(R.id.proxy_warning_limited_support).setVisibility(View.GONE);
mView.findViewById(R.id.proxy_fields).setVisibility(View.GONE);
}
}
private void loadCertificates(Spinner spinner, String prefix) {
final Context context = mConfigUi.getContext();
final String unspecified = context.getString(R.string.wifi_unspecified);
String[] certs = KeyStore.getInstance().saw(prefix);
if (certs == null || certs.length == 0) {
certs = new String[] {unspecified};
} else {
final String[] array = new String[certs.length + 1];
array[0] = unspecified;
System.arraycopy(certs, 0, array, 1, certs.length);
certs = array;
}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
context, android.R.layout.simple_spinner_item, certs);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
private void setCertificate(Spinner spinner, String prefix, String cert) {
prefix = KEYSTORE_SPACE + prefix;
if (cert != null && cert.startsWith(prefix)) {
setSelection(spinner, cert.substring(prefix.length()));
}
}
private void setSelection(Spinner spinner, String value) {
if (value != null) {
ArrayAdapter<String> adapter = (ArrayAdapter<String>) spinner.getAdapter();
for (int i = adapter.getCount() - 1; i >= 0; --i) {
if (value.equals(adapter.getItem(i))) {
spinner.setSelection(i);
break;
}
}
}
}
public boolean isEdit() {
return mEdit;
}
@Override
public void afterTextChanged(Editable s) {
enableSubmitIfAppropriate();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void onClick(View view) {
mPasswordView.setInputType(
InputType.TYPE_CLASS_TEXT | (((CheckBox) view).isChecked() ?
InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD :
InputType.TYPE_TEXT_VARIATION_PASSWORD));
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (parent == mSecuritySpinner) {
mAccessPointSecurity = position;
showSecurityFields();
enableSubmitIfAppropriate();
} else if (parent == mNetworkSetupSpinner) {
showNetworkSetupFields();
} else if (parent == mProxySettingsSpinner) {
showProxyFields();
} else {
showIpConfigFields();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
| false | true | public WifiConfigController(
WifiConfigUiBase parent, View view, AccessPoint accessPoint, boolean edit) {
mConfigUi = parent;
mInXlSetupWizard = (parent instanceof WifiConfigUiForSetupWizardXL);
mView = view;
mAccessPoint = accessPoint;
mAccessPointSecurity = (accessPoint == null) ? AccessPoint.SECURITY_NONE :
accessPoint.security;
mEdit = edit;
final Context context = mConfigUi.getContext();
final Resources resources = context.getResources();
if (mAccessPoint == null) { // new network
mConfigUi.setTitle(R.string.wifi_add_network);
mSsidView = (TextView) mView.findViewById(R.id.ssid);
mSsidView.addTextChangedListener(this);
mSecuritySpinner = ((Spinner) mView.findViewById(R.id.security));
mSecuritySpinner.setOnItemSelectedListener(this);
if (mInXlSetupWizard) {
mView.findViewById(R.id.type_ssid).setVisibility(View.VISIBLE);
mView.findViewById(R.id.type_security).setVisibility(View.VISIBLE);
// We want custom layout. The content must be same as the other cases.
mSecuritySpinner.setAdapter(
new ArrayAdapter<String>(context, R.layout.wifi_setup_custom_list_item_1,
android.R.id.text1,
context.getResources().getStringArray(R.array.wifi_security)));
} else {
mView.findViewById(R.id.type).setVisibility(View.VISIBLE);
}
mConfigUi.setSubmitButton(context.getString(R.string.wifi_save));
} else {
mConfigUi.setTitle(mAccessPoint.ssid);
mIpSettingsSpinner = (Spinner) mView.findViewById(R.id.ip_settings);
mIpSettingsSpinner.setOnItemSelectedListener(this);
mProxySettingsSpinner = (Spinner) mView.findViewById(R.id.proxy_settings);
mProxySettingsSpinner.setOnItemSelectedListener(this);
ViewGroup group = (ViewGroup) mView.findViewById(R.id.info);
DetailedState state = mAccessPoint.getState();
if (state != null) {
addRow(group, R.string.wifi_status, Summary.get(mConfigUi.getContext(), state));
}
String[] type = resources.getStringArray(R.array.wifi_security);
addRow(group, R.string.wifi_security, type[mAccessPoint.security]);
int level = mAccessPoint.getLevel();
if (level != -1) {
String[] signal = resources.getStringArray(R.array.wifi_signal);
addRow(group, R.string.wifi_signal, signal[level]);
}
WifiInfo info = mAccessPoint.getInfo();
if (info != null) {
addRow(group, R.string.wifi_speed, info.getLinkSpeed() + WifiInfo.LINK_SPEED_UNITS);
// TODO: fix the ip address for IPv6.
int address = info.getIpAddress();
if (address != 0) {
addRow(group, R.string.wifi_ip_address, Formatter.formatIpAddress(address));
}
}
if (mAccessPoint.networkId != INVALID_NETWORK_ID) {
WifiConfiguration config = mAccessPoint.getConfig();
if (config.ipAssignment == IpAssignment.STATIC) {
mIpSettingsSpinner.setSelection(STATIC_IP);
} else {
mIpSettingsSpinner.setSelection(DHCP);
}
if (config.proxySettings == ProxySettings.STATIC) {
mProxySettingsSpinner.setSelection(PROXY_STATIC);
} else {
mProxySettingsSpinner.setSelection(PROXY_NONE);
}
}
/* Show network setup options only for a new network */
if (mAccessPoint.networkId == INVALID_NETWORK_ID && mAccessPoint.wpsAvailable) {
showNetworkSetupFields();
}
if (mAccessPoint.networkId == INVALID_NETWORK_ID || mEdit) {
showSecurityFields();
showIpConfigFields();
showProxyFields();
}
if (mEdit) {
mConfigUi.setSubmitButton(context.getString(R.string.wifi_save));
} else {
if (state == null && level != -1) {
mConfigUi.setSubmitButton(context.getString(R.string.wifi_connect));
} else {
mView.findViewById(R.id.ip_fields).setVisibility(View.GONE);
}
if (mAccessPoint.networkId != INVALID_NETWORK_ID) {
mConfigUi.setForgetButton(context.getString(R.string.wifi_forget));
}
}
}
mConfigUi.setCancelButton(context.getString(R.string.wifi_cancel));
if (mConfigUi.getSubmitButton() != null) {
enableSubmitIfAppropriate();
}
}
| public WifiConfigController(
WifiConfigUiBase parent, View view, AccessPoint accessPoint, boolean edit) {
mConfigUi = parent;
mInXlSetupWizard = (parent instanceof WifiConfigUiForSetupWizardXL);
mView = view;
mAccessPoint = accessPoint;
mAccessPointSecurity = (accessPoint == null) ? AccessPoint.SECURITY_NONE :
accessPoint.security;
mEdit = edit;
final Context context = mConfigUi.getContext();
final Resources resources = context.getResources();
if (mAccessPoint == null) { // new network
mConfigUi.setTitle(R.string.wifi_add_network);
mSsidView = (TextView) mView.findViewById(R.id.ssid);
mSsidView.addTextChangedListener(this);
mSecuritySpinner = ((Spinner) mView.findViewById(R.id.security));
mSecuritySpinner.setOnItemSelectedListener(this);
if (mInXlSetupWizard) {
mView.findViewById(R.id.type_ssid).setVisibility(View.VISIBLE);
mView.findViewById(R.id.type_security).setVisibility(View.VISIBLE);
// We want custom layout. The content must be same as the other cases.
mSecuritySpinner.setAdapter(
new ArrayAdapter<String>(context, R.layout.wifi_setup_custom_list_item_1,
android.R.id.text1,
context.getResources().getStringArray(R.array.wifi_security)));
} else {
mView.findViewById(R.id.type).setVisibility(View.VISIBLE);
}
mConfigUi.setSubmitButton(context.getString(R.string.wifi_save));
} else {
mConfigUi.setTitle(mAccessPoint.ssid);
mIpSettingsSpinner = (Spinner) mView.findViewById(R.id.ip_settings);
mIpSettingsSpinner.setOnItemSelectedListener(this);
mProxySettingsSpinner = (Spinner) mView.findViewById(R.id.proxy_settings);
mProxySettingsSpinner.setOnItemSelectedListener(this);
ViewGroup group = (ViewGroup) mView.findViewById(R.id.info);
DetailedState state = mAccessPoint.getState();
if (state != null) {
addRow(group, R.string.wifi_status, Summary.get(mConfigUi.getContext(), state));
}
String[] type = resources.getStringArray(R.array.wifi_security);
addRow(group, R.string.wifi_security, type[mAccessPoint.security]);
int level = mAccessPoint.getLevel();
if (level != -1) {
String[] signal = resources.getStringArray(R.array.wifi_signal);
addRow(group, R.string.wifi_signal, signal[level]);
}
WifiInfo info = mAccessPoint.getInfo();
if (info != null) {
addRow(group, R.string.wifi_speed, info.getLinkSpeed() + WifiInfo.LINK_SPEED_UNITS);
}
if (mAccessPoint.networkId != INVALID_NETWORK_ID) {
WifiConfiguration config = mAccessPoint.getConfig();
if (config.ipAssignment == IpAssignment.STATIC) {
mIpSettingsSpinner.setSelection(STATIC_IP);
} else {
mIpSettingsSpinner.setSelection(DHCP);
//Display IP addresses
for(InetAddress a : config.linkProperties.getAddresses()) {
addRow(group, R.string.wifi_ip_address, a.getHostAddress());
}
}
if (config.proxySettings == ProxySettings.STATIC) {
mProxySettingsSpinner.setSelection(PROXY_STATIC);
} else {
mProxySettingsSpinner.setSelection(PROXY_NONE);
}
}
/* Show network setup options only for a new network */
if (mAccessPoint.networkId == INVALID_NETWORK_ID && mAccessPoint.wpsAvailable) {
showNetworkSetupFields();
}
if (mAccessPoint.networkId == INVALID_NETWORK_ID || mEdit) {
showSecurityFields();
showIpConfigFields();
showProxyFields();
}
if (mEdit) {
mConfigUi.setSubmitButton(context.getString(R.string.wifi_save));
} else {
if (state == null && level != -1) {
mConfigUi.setSubmitButton(context.getString(R.string.wifi_connect));
} else {
mView.findViewById(R.id.ip_fields).setVisibility(View.GONE);
}
if (mAccessPoint.networkId != INVALID_NETWORK_ID) {
mConfigUi.setForgetButton(context.getString(R.string.wifi_forget));
}
}
}
mConfigUi.setCancelButton(context.getString(R.string.wifi_cancel));
if (mConfigUi.getSubmitButton() != null) {
enableSubmitIfAppropriate();
}
}
|
diff --git a/opencv/modules/java/src/java/Converters.java b/opencv/modules/java/src/java/Converters.java
index 8efed8ce3..32edce866 100644
--- a/opencv/modules/java/src/java/Converters.java
+++ b/opencv/modules/java/src/java/Converters.java
@@ -1,514 +1,514 @@
package org.opencv;
import java.util.List;
import org.opencv.core.Mat;
import org.opencv.core.CvType;
import org.opencv.core.Point;
import org.opencv.core.Point3;
import org.opencv.core.Rect;
import org.opencv.features2d.DMatch;
import org.opencv.features2d.KeyPoint;
public class Converters {
public static Mat vector_Point_to_Mat(List<Point> pts) {
return vector_Point_to_Mat(pts, CvType.CV_32S);
}
public static Mat vector_Point2f_to_Mat(List<Point> pts) {
return vector_Point_to_Mat(pts, CvType.CV_32F);
}
public static Mat vector_Point2d_to_Mat(List<Point> pts) {
return vector_Point_to_Mat(pts, CvType.CV_64F);
}
public static Mat vector_Point_to_Mat(List<Point> pts, int typeDepth) {
Mat res;
int count = (pts!=null) ? pts.size() : 0;
if(count>0){
switch (typeDepth) {
case CvType.CV_32S:
{
res = new Mat(count, 1, CvType.CV_32SC2);
int[] buff = new int[count*2];
for(int i=0; i<count; i++) {
Point p = pts.get(i);
buff[i*2] = (int)p.x;
buff[i*2+1] = (int)p.y;
}
res.put(0, 0, buff);
}
break;
case CvType.CV_32F:
{
res = new Mat(count, 1, CvType.CV_32FC2);
float[] buff = new float[count*2];
for(int i=0; i<count; i++) {
Point p = pts.get(i);
buff[i*2] = (float)p.x;
buff[i*2+1] = (float)p.y;
}
res.put(0, 0, buff);
}
break;
case CvType.CV_64F:
{
res = new Mat(count, 1, CvType.CV_64FC2);
double[] buff = new double[count*2];
for(int i=0; i<count; i++) {
Point p = pts.get(i);
buff[i*2] = p.x;
buff[i*2+1] = p.y;
}
res.put(0, 0, buff);
}
break;
default:
throw new IllegalArgumentException("'typeDepth' can be CV_32S, CV_32F or CV_64F");
}
} else {
res = new Mat();
}
return res;
}
public static Mat vector_Point3i_to_Mat(List<Point3> pts) {
return vector_Point3_to_Mat(pts, CvType.CV_32S);
}
public static Mat vector_Point3f_to_Mat(List<Point3> pts) {
return vector_Point3_to_Mat(pts, CvType.CV_32F);
}
public static Mat vector_Point3d_to_Mat(List<Point3> pts) {
return vector_Point3_to_Mat(pts, CvType.CV_64F);
}
public static Mat vector_Point3_to_Mat(List<Point3> pts, int typeDepth) {
Mat res;
int count = (pts!=null) ? pts.size() : 0;
if(count>0){
switch (typeDepth){
case CvType.CV_32S:
{
res = new Mat(count, 1, CvType.CV_32SC3);
int[] buff = new int[count*3];
for(int i=0; i<count; i++) {
Point3 p = pts.get(i);
buff[i*3] = (int)p.x;
buff[i*3+1] = (int)p.y;
buff[i*3+2] = (int)p.z;
}
res.put(0, 0, buff);
}
break;
case CvType.CV_32F:
{
- res = new Mat(count, 1, CvType.CV_64FC3);
+ res = new Mat(count, 1, CvType.CV_32FC3);
float[] buff = new float[count*3];
for(int i=0; i<count; i++) {
Point3 p = pts.get(i);
buff[i*3] = (float)p.x;
buff[i*3+1] = (float)p.y;
buff[i*3+2] = (float)p.z;
}
res.put(0, 0, buff);
}
break;
case CvType.CV_64F:
{
res = new Mat(count, 1, CvType.CV_64FC3);
double[] buff = new double[count*3];
for(int i=0; i<count; i++) {
Point3 p = pts.get(i);
buff[i*3] = p.x;
buff[i*3+1] = p.y;
buff[i*3+2] = p.z;
}
res.put(0, 0, buff);
}
break;
default:
throw new IllegalArgumentException("'typeDepth' can be CV_32S, CV_32F or CV_64F");
}
} else {
res = new Mat();
}
return res;
}
public static void Mat_to_vector_Point2f(Mat m, List<Point> pts) {
Mat_to_vector_Point(m, pts);
}
public static void Mat_to_vector_Point2d(Mat m, List<Point> pts) {
Mat_to_vector_Point(m, pts);
}
public static void Mat_to_vector_Point(Mat m, List<Point> pts) {
if(pts == null)
throw new java.lang.IllegalArgumentException("Output List can't be null");
int count = m.rows();
int type = m.type();
if(m.cols() != 1)
throw new java.lang.IllegalArgumentException( "Input Mat should have one column\n" + m );
pts.clear();
if(type == CvType.CV_32SC2) {
int[] buff = new int[2*count];
m.get(0, 0, buff);
for(int i=0; i<count; i++) {
pts.add( new Point(buff[i*2], buff[i*2+1]) );
}
} else if(type == CvType.CV_32FC2){
float[] buff = new float[2*count];
m.get(0, 0, buff);
for(int i=0; i<count; i++) {
pts.add( new Point(buff[i*2], buff[i*2+1]) );
}
} else if(type == CvType.CV_64FC2){
double[] buff = new double[2*count];
m.get(0, 0, buff);
for(int i=0; i<count; i++) {
pts.add( new Point(buff[i*2], buff[i*2+1]) );
}
} else {
throw new java.lang.IllegalArgumentException(
"Input Mat should be of CV_32SC2, CV_32FC2 or CV_64FC2 type\n" + m );
}
}
public static void Mat_to_vector_Point3i(Mat m, List<Point3> pts) {
Mat_to_vector_Point3(m, pts);
}
public static void Mat_to_vector_Point3f(Mat m, List<Point3> pts) {
Mat_to_vector_Point3(m, pts);
}
public static void Mat_to_vector_Point3d(Mat m, List<Point3> pts) {
Mat_to_vector_Point3(m, pts);
}
public static void Mat_to_vector_Point3(Mat m, List<Point3> pts) {
if(pts == null)
throw new java.lang.IllegalArgumentException("Output List can't be null");
int count = m.rows();
int type = m.type();
if(m.cols() != 1)
throw new java.lang.IllegalArgumentException( "Input Mat should have one column\n" + m );
pts.clear();
if(type == CvType.CV_32SC3) {
int[] buff = new int[3*count];
m.get(0, 0, buff);
for(int i=0; i<count; i++) {
pts.add( new Point3(buff[i*3], buff[i*3+1], buff[i*3+2]) );
}
} else if(type == CvType.CV_32FC3){
float[] buff = new float[3*count];
m.get(0, 0, buff);
for(int i=0; i<count; i++) {
pts.add( new Point3(buff[i*3], buff[i*3+1], buff[i*3+2]) );
}
} else if(type == CvType.CV_64FC3){
double[] buff = new double[3*count];
m.get(0, 0, buff);
for(int i=0; i<count; i++) {
pts.add( new Point3(buff[i*3], buff[i*3+1], buff[i*3+2]) );
}
} else {
throw new java.lang.IllegalArgumentException(
"Input Mat should be of CV_32SC3, CV_32FC3 or CV_64FC3 type\n" + m );
}
}
public static Mat vector_Mat_to_Mat(List<Mat> mats) {
Mat res;
int count = (mats!=null) ? mats.size() : 0;
if(count>0){
res = new Mat(count, 1, CvType.CV_32SC2);
int[] buff = new int[count*2];
for(int i=0; i<count; i++) {
long addr = mats.get(i).nativeObj;
buff[i*2] = (int)(addr >> 32);
buff[i*2+1] = (int)(addr & 0xffffffff);
}
res.put(0, 0, buff);
} else {
res = new Mat();
}
return res;
}
public static void Mat_to_vector_Mat(Mat m, List<Mat> mats) {
if(mats == null)
throw new java.lang.IllegalArgumentException("mats == null");
int count = m.rows();
if( CvType.CV_32SC2 != m.type() || m.cols()!=1 )
throw new java.lang.IllegalArgumentException(
"CvType.CV_32SC2 != m.type() || m.cols()!=1\n" + m);
mats.clear();
int[] buff = new int[count*2];
m.get(0, 0, buff);
for(int i=0; i<count; i++) {
long addr = (((long)buff[i*2])<<32) | ((long)buff[i*2+1]);
mats.add( new Mat(addr) );
}
}
public static Mat vector_float_to_Mat(List<Float> fs) {
Mat res;
int count = (fs!=null) ? fs.size() : 0;
if(count>0){
res = new Mat(count, 1, CvType.CV_32FC1);
float[] buff = new float[count];
for(int i=0; i<count; i++) {
float f = fs.get(i);
buff[i] = f;
}
res.put(0, 0, buff);
} else {
res = new Mat();
}
return res;
}
public static void Mat_to_vector_float(Mat m, List<Float> fs) {
if(fs == null)
throw new java.lang.IllegalArgumentException("fs == null");
int count = m.rows();
if( CvType.CV_32FC1 != m.type() || m.cols()!=1 )
throw new java.lang.IllegalArgumentException(
"CvType.CV_32FC1 != m.type() || m.cols()!=1\n" + m);
fs.clear();
float[] buff = new float[count];
m.get(0, 0, buff);
for(int i=0; i<count; i++) {
fs.add( new Float(buff[i]) );
}
}
public static Mat vector_uchar_to_Mat(List<Byte> bs) {
Mat res;
int count = (bs!=null) ? bs.size() : 0;
if(count>0){
res = new Mat(count, 1, CvType.CV_8UC1);
byte[] buff = new byte[count];
for(int i=0; i<count; i++) {
byte b = bs.get(i);
buff[i] = b;
}
res.put(0, 0, buff);
} else {
res = new Mat();
}
return res;
}
public static Mat vector_char_to_Mat(List<Byte> bs) {
Mat res;
int count = (bs!=null) ? bs.size() : 0;
if(count>0){
res = new Mat(count, 1, CvType.CV_8SC1);
byte[] buff = new byte[count];
for(int i=0; i<count; i++) {
byte b = bs.get(i);
buff[i] = b;
}
res.put(0, 0, buff);
} else {
res = new Mat();
}
return res;
}
public static Mat vector_int_to_Mat(List<Integer> is) {
Mat res;
int count = (is!=null) ? is.size() : 0;
if(count>0){
res = new Mat(count, 1, CvType.CV_32SC1);
int[] buff = new int[count];
for(int i=0; i<count; i++) {
int v = is.get(i);
buff[i] = v;
}
res.put(0, 0, buff);
} else {
res = new Mat();
}
return res;
}
public static void Mat_to_vector_int(Mat m, List<Integer> is) {
if(is == null)
throw new java.lang.IllegalArgumentException("is == null");
int count = m.rows();
if( CvType.CV_32SC1 != m.type() || m.cols()!=1 )
throw new java.lang.IllegalArgumentException(
"CvType.CV_32SC1 != m.type() || m.cols()!=1\n" + m);
is.clear();
int[] buff = new int[count];
m.get(0, 0, buff);
for(int i=0; i<count; i++) {
is.add( new Integer(buff[i]) );
}
}
public static void Mat_to_vector_char(Mat m, List<Byte> bs) {
if(bs == null)
throw new java.lang.IllegalArgumentException("Output List can't be null");
int count = m.rows();
if( CvType.CV_8SC1 != m.type() || m.cols()!=1 )
throw new java.lang.IllegalArgumentException(
"CvType.CV_8SC1 != m.type() || m.cols()!=1\n" + m);
bs.clear();
byte[] buff = new byte[count];
m.get(0, 0, buff);
for(int i=0; i<count; i++) {
bs.add( new Byte(buff[i]) );
}
}
public static Mat vector_Rect_to_Mat(List<Rect> rs) {
Mat res;
int count = (rs!=null) ? rs.size() : 0;
if(count>0){
res = new Mat(count, 1, CvType.CV_32SC4);
int[] buff = new int[4*count];
for(int i=0; i<count; i++) {
Rect r = rs.get(i);
buff[4*i ] = r.x;
buff[4*i+1] = r.y;
buff[4*i+2] = r.width;
buff[4*i+3] = r.height;
}
res.put(0, 0, buff);
} else {
res = new Mat();
}
return res;
}
public static void Mat_to_vector_Rect(Mat m, List<Rect> rs) {
if(rs == null)
throw new java.lang.IllegalArgumentException("rs == null");
int count = m.rows();
if(CvType.CV_32SC4 != m.type() || m.cols()!=1 )
throw new java.lang.IllegalArgumentException(
"CvType.CV_32SC4 != m.type() || m.rows()!=1\n" + m);
rs.clear();
int[] buff = new int[4*count];
m.get(0, 0, buff);
for(int i=0; i<count; i++) {
rs.add( new Rect(buff[4*i], buff[4*i+1], buff[4*i+2], buff[4*i+3]) );
}
}
public static Mat vector_KeyPoint_to_Mat(List<KeyPoint> kps) {
Mat res;
int count = (kps!=null) ? kps.size() : 0;
if(count>0){
res = new Mat(count, 1, CvType.CV_64FC(7));
double[] buff = new double[count * 7];
for(int i=0; i<count; i++) {
KeyPoint kp = kps.get(i);
buff[7*i ] = kp.pt.x;
buff[7*i+1] = kp.pt.y;
buff[7*i+2] = kp.size;
buff[7*i+3] = kp.angle;
buff[7*i+4] = kp.response;
buff[7*i+5] = kp.octave;
buff[7*i+6] = kp.class_id;
}
res.put(0, 0, buff);
} else {
res = new Mat();
}
return res;
}
public static void Mat_to_vector_KeyPoint(Mat m, List<KeyPoint> kps) {
if(kps == null)
throw new java.lang.IllegalArgumentException("Output List can't be null");
int count = m.rows();
if( CvType.CV_64FC(7) != m.type() || m.cols()!=1 )
throw new java.lang.IllegalArgumentException(
"CvType.CV_64FC(7) != m.type() || m.cols()!=1\n" + m);
kps.clear();
double[] buff = new double[7*count];
m.get(0, 0, buff);
for(int i=0; i<count; i++) {
kps.add( new KeyPoint( (float)buff[7*i], (float)buff[7*i+1], (float)buff[7*i+2], (float)buff[7*i+3],
(float)buff[7*i+4], (int)buff[7*i+5], (int)buff[7*i+6] ) );
}
}
public static Mat vector_double_to_Mat(List<Double> ds) {
Mat res;
int count = (ds!=null) ? ds.size() : 0;
if(count>0){
res = new Mat(count, 1, CvType.CV_64FC1);
double[] buff = new double[count];
for(int i=0; i<count; i++) {
double v = ds.get(i);
buff[i] = v;
}
res.put(0, 0, buff);
} else {
res = new Mat();
}
return res;
}
public static Mat vector_DMatch_to_Mat(List<DMatch> matches) {
Mat res;
int count = (matches!=null) ? matches.size() : 0;
if(count>0){
res = new Mat(count, 1, CvType.CV_64FC4);
double[] buff = new double[count * 4];
for(int i=0; i<count; i++) {
DMatch m = matches.get(i);
buff[4*i ] = m.queryIdx;
buff[4*i+1] = m.trainIdx;
buff[4*i+2] = m.imgIdx;
buff[4*i+3] = m.distance;
}
res.put(0, 0, buff);
} else {
res = new Mat();
}
return res;
}
public static void Mat_to_vector_DMatch(Mat m, List<DMatch> matches) {
if(matches == null)
throw new java.lang.IllegalArgumentException("Output List can't be null");
int count = m.rows();
if( CvType.CV_64FC4 != m.type() || m.cols()!=1 )
throw new java.lang.IllegalArgumentException(
"CvType.CV_64FC4 != m.type() || m.cols()!=1\n" + m);
matches.clear();
double[] buff = new double[4*count];
m.get(0, 0, buff);
for(int i=0; i<count; i++) {
matches.add( new DMatch( (int)buff[4*i], (int)buff[4*i+1], (int)buff[4*i+2], (float)buff[4*i+3] ) );
}
}
}
| true | true | public static Mat vector_Point3_to_Mat(List<Point3> pts, int typeDepth) {
Mat res;
int count = (pts!=null) ? pts.size() : 0;
if(count>0){
switch (typeDepth){
case CvType.CV_32S:
{
res = new Mat(count, 1, CvType.CV_32SC3);
int[] buff = new int[count*3];
for(int i=0; i<count; i++) {
Point3 p = pts.get(i);
buff[i*3] = (int)p.x;
buff[i*3+1] = (int)p.y;
buff[i*3+2] = (int)p.z;
}
res.put(0, 0, buff);
}
break;
case CvType.CV_32F:
{
res = new Mat(count, 1, CvType.CV_64FC3);
float[] buff = new float[count*3];
for(int i=0; i<count; i++) {
Point3 p = pts.get(i);
buff[i*3] = (float)p.x;
buff[i*3+1] = (float)p.y;
buff[i*3+2] = (float)p.z;
}
res.put(0, 0, buff);
}
break;
case CvType.CV_64F:
{
res = new Mat(count, 1, CvType.CV_64FC3);
double[] buff = new double[count*3];
for(int i=0; i<count; i++) {
Point3 p = pts.get(i);
buff[i*3] = p.x;
buff[i*3+1] = p.y;
buff[i*3+2] = p.z;
}
res.put(0, 0, buff);
}
break;
default:
throw new IllegalArgumentException("'typeDepth' can be CV_32S, CV_32F or CV_64F");
}
} else {
res = new Mat();
}
return res;
}
| public static Mat vector_Point3_to_Mat(List<Point3> pts, int typeDepth) {
Mat res;
int count = (pts!=null) ? pts.size() : 0;
if(count>0){
switch (typeDepth){
case CvType.CV_32S:
{
res = new Mat(count, 1, CvType.CV_32SC3);
int[] buff = new int[count*3];
for(int i=0; i<count; i++) {
Point3 p = pts.get(i);
buff[i*3] = (int)p.x;
buff[i*3+1] = (int)p.y;
buff[i*3+2] = (int)p.z;
}
res.put(0, 0, buff);
}
break;
case CvType.CV_32F:
{
res = new Mat(count, 1, CvType.CV_32FC3);
float[] buff = new float[count*3];
for(int i=0; i<count; i++) {
Point3 p = pts.get(i);
buff[i*3] = (float)p.x;
buff[i*3+1] = (float)p.y;
buff[i*3+2] = (float)p.z;
}
res.put(0, 0, buff);
}
break;
case CvType.CV_64F:
{
res = new Mat(count, 1, CvType.CV_64FC3);
double[] buff = new double[count*3];
for(int i=0; i<count; i++) {
Point3 p = pts.get(i);
buff[i*3] = p.x;
buff[i*3+1] = p.y;
buff[i*3+2] = p.z;
}
res.put(0, 0, buff);
}
break;
default:
throw new IllegalArgumentException("'typeDepth' can be CV_32S, CV_32F or CV_64F");
}
} else {
res = new Mat();
}
return res;
}
|
diff --git a/org.dawnsci.plotting.draw2d/src/org/dawnsci/plotting/draw2d/swtxy/selection/RectangularHandle.java b/org.dawnsci.plotting.draw2d/src/org/dawnsci/plotting/draw2d/swtxy/selection/RectangularHandle.java
index 64ccccd02..2399a2ea6 100644
--- a/org.dawnsci.plotting.draw2d/src/org/dawnsci/plotting/draw2d/swtxy/selection/RectangularHandle.java
+++ b/org.dawnsci.plotting.draw2d/src/org/dawnsci/plotting/draw2d/swtxy/selection/RectangularHandle.java
@@ -1,37 +1,38 @@
package org.dawnsci.plotting.draw2d.swtxy.selection;
import org.dawnsci.plotting.api.axis.ICoordinateSystem;
import org.dawnsci.plotting.draw2d.swtxy.util.RotatablePolygonShape;
import org.dawnsci.plotting.draw2d.swtxy.util.RotatableRectangle;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.Shape;
import org.eclipse.draw2d.geometry.PrecisionPoint;
import org.eclipse.swt.graphics.Color;
public class RectangularHandle extends SelectionHandle {
/**
* @param xAxis
* @param yAxis
* @param colour
* @param parent
* @param side
* @param params (first corner's x and y, also centre of rotation)
*/
public RectangularHandle(ICoordinateSystem coords, Color colour, Figure parent, int side, double... params) {
super(coords, colour, parent, side, params);
}
@Override
public Shape createHandleShape(Figure parent, int side, double[] params) {
double angle;
if (parent instanceof RotatablePolygonShape) {
RotatablePolygonShape pg = (RotatablePolygonShape) parent;
angle = pg.getAngleDegrees();
} else {
angle = 0;
}
location = new PrecisionPoint(params[0], params[1]);
- return new RotatableRectangle(location.x(), location.y(), side, side, angle);
+ int[] pt = coords.getValuePosition(params);
+ return new RotatableRectangle(pt[0], pt[1], side, side, angle);
}
}
| true | true | public Shape createHandleShape(Figure parent, int side, double[] params) {
double angle;
if (parent instanceof RotatablePolygonShape) {
RotatablePolygonShape pg = (RotatablePolygonShape) parent;
angle = pg.getAngleDegrees();
} else {
angle = 0;
}
location = new PrecisionPoint(params[0], params[1]);
return new RotatableRectangle(location.x(), location.y(), side, side, angle);
}
| public Shape createHandleShape(Figure parent, int side, double[] params) {
double angle;
if (parent instanceof RotatablePolygonShape) {
RotatablePolygonShape pg = (RotatablePolygonShape) parent;
angle = pg.getAngleDegrees();
} else {
angle = 0;
}
location = new PrecisionPoint(params[0], params[1]);
int[] pt = coords.getValuePosition(params);
return new RotatableRectangle(pt[0], pt[1], side, side, angle);
}
|
diff --git a/src/com/dmdirc/logger/Logger.java b/src/com/dmdirc/logger/Logger.java
index 1ae831f92..ad7bda96e 100644
--- a/src/com/dmdirc/logger/Logger.java
+++ b/src/com/dmdirc/logger/Logger.java
@@ -1,229 +1,229 @@
/*
* Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.logger;
import com.dmdirc.Main;
import com.dmdirc.config.IdentityManager;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
/**
* Logger class for the application.
*/
public final class Logger {
/** ProgramError folder. */
private static File errorDir;
/** Prevent instantiation of a new instance of Logger. */
private Logger() {
//Ignore
}
/**
* Called when a user correctable error occurs.
*
* @param level Severity of the error
* @param message Brief error description
*/
public static void userError(final ErrorLevel level,
final String message) {
userError(level, message, "");
}
/**
* Called when a user correctable error occurs.
*
* @param level Severity of the error
* @param message Brief error description
* @param details Verbose description of the error
*/
public static void userError(final ErrorLevel level,
final String message, final String details) {
error(level, message, null, false);
}
/**
* Called when a user correctable error occurs.
*
* @param level Severity of the error
* @param message Brief error description
* @param exception Throwable cause for the error
*/
public static void userError(final ErrorLevel level,
final String message, final Throwable exception) {
error(level, message, null, false);
}
/**
* Called when a non user correctable error occurs, the error will be
* logged and optionally sent to the developers.
*
* @param level Severity of the error
* @param message Brief error description
* @param exception Cause of error
*/
public static void appError(final ErrorLevel level,
final String message, final Throwable exception) {
error(level, message, exception, true);
}
/**
* Handles an error in the program.
*
* @param level Severity of the error
* @param message Brief error description
* @param exception Cause of error
* @param sendable Whether the error is sendable
*/
private static void error(final ErrorLevel level,
final String message, final Throwable exception,
final boolean sendable) {
final ProgramError error = createError(level, message, exception);
final boolean report =
IdentityManager.getGlobalConfig().getOptionBool("general", "submitErrors", false)
& !IdentityManager.getGlobalConfig().getOptionBool("temp", "noerrorreporting", false);
if (!sendable) {
error.setReportStatus(ErrorReportStatus.NOT_APPLICABLE);
error.setFixedStatus(ErrorFixedStatus.UNREPORTED);
}
if (sendable && report) {
ErrorManager.getErrorManager().sendError(error);
}
if (level == ErrorLevel.FATAL && !report) {
error.setReportStatus(ErrorReportStatus.FINISHED);
}
ErrorManager.getErrorManager().addError(error);
}
/**
* Creates a new ProgramError from the supplied information, and writes
* the error to a file.
*
* @param level Error level
* @param message Error message
* @param exception Error cause
*
* @return ProgramError encapsulating the supplied information
*/
private static ProgramError createError(final ErrorLevel level,
final String message, final Throwable exception) {
final String[] trace;
final StackTraceElement[] traceElements;
if (exception == null) {
trace = new String[0];
} else {
traceElements = exception.getStackTrace();
trace = new String[traceElements.length + 1];
trace[0] = exception.toString();
for (int i = 0; i < traceElements.length; i++) {
trace[i + 1] = traceElements[i].toString();
}
}
final ProgramError error = new ProgramError(
ErrorManager.getErrorManager().getNextErrorID(), level, message,
trace, new Date(System.currentTimeMillis()));
writeError(error);
return error;
}
/**
* Writes the specified error to a file.
*
* @param error ProgramError to write to a file.
*/
private static void writeError(final ProgramError error) {
final PrintWriter out = new PrintWriter(createNewErrorFile(error), true);
out.println("Date:" + error.getDate());
out.println("Level: " + error.getLevel());
out.println("Description: " + error.getMessage());
out.println("Details:");
final String[] trace = error.getTrace();
for (String traceLine : trace) {
out.println('\t' + traceLine);
}
out.close();
}
/**
* Creates a new file for an error and returns the output stream.
*
* @param error Error to create file for
*
* @return BufferedOutputStream to write to the error file
*/
@SuppressWarnings("PMD.SystemPrintln")
private static synchronized OutputStream createNewErrorFile(final ProgramError error) {
- if (errorDir == null) {
+ if (errorDir == null || !errorDir.exists()) {
errorDir = new File(Main.getConfigDir() + "errors");
if (!errorDir.exists()) {
errorDir.mkdirs();
}
}
final String logName = error.getDate().getTime() + "-" + error.getLevel();
final File errorFile = new File(errorDir, logName + ".log");
if (errorFile.exists()) {
boolean rename = false;
int i = 0;
while (!rename) {
i++;
rename = errorFile.renameTo(new File(errorDir, logName + "-" + i + ".log"));
}
}
try {
errorFile.createNewFile();
} catch (IOException ex) {
System.err.println("Error creating new file: ");
ex.printStackTrace(System.err);
return new NullOutputStream();
}
try {
return new FileOutputStream(errorFile);
} catch (FileNotFoundException ex) {
System.err.println("Error creating new stream: ");
ex.printStackTrace(System.err);
return new NullOutputStream();
}
}
}
| true | true | private static synchronized OutputStream createNewErrorFile(final ProgramError error) {
if (errorDir == null) {
errorDir = new File(Main.getConfigDir() + "errors");
if (!errorDir.exists()) {
errorDir.mkdirs();
}
}
final String logName = error.getDate().getTime() + "-" + error.getLevel();
final File errorFile = new File(errorDir, logName + ".log");
if (errorFile.exists()) {
boolean rename = false;
int i = 0;
while (!rename) {
i++;
rename = errorFile.renameTo(new File(errorDir, logName + "-" + i + ".log"));
}
}
try {
errorFile.createNewFile();
} catch (IOException ex) {
System.err.println("Error creating new file: ");
ex.printStackTrace(System.err);
return new NullOutputStream();
}
try {
return new FileOutputStream(errorFile);
} catch (FileNotFoundException ex) {
System.err.println("Error creating new stream: ");
ex.printStackTrace(System.err);
return new NullOutputStream();
}
}
| private static synchronized OutputStream createNewErrorFile(final ProgramError error) {
if (errorDir == null || !errorDir.exists()) {
errorDir = new File(Main.getConfigDir() + "errors");
if (!errorDir.exists()) {
errorDir.mkdirs();
}
}
final String logName = error.getDate().getTime() + "-" + error.getLevel();
final File errorFile = new File(errorDir, logName + ".log");
if (errorFile.exists()) {
boolean rename = false;
int i = 0;
while (!rename) {
i++;
rename = errorFile.renameTo(new File(errorDir, logName + "-" + i + ".log"));
}
}
try {
errorFile.createNewFile();
} catch (IOException ex) {
System.err.println("Error creating new file: ");
ex.printStackTrace(System.err);
return new NullOutputStream();
}
try {
return new FileOutputStream(errorFile);
} catch (FileNotFoundException ex) {
System.err.println("Error creating new stream: ");
ex.printStackTrace(System.err);
return new NullOutputStream();
}
}
|
diff --git a/src/main/java/org/genedb/crawl/dao/proxy/Proxies.java b/src/main/java/org/genedb/crawl/dao/proxy/Proxies.java
index a0860d7..fb198b2 100644
--- a/src/main/java/org/genedb/crawl/dao/proxy/Proxies.java
+++ b/src/main/java/org/genedb/crawl/dao/proxy/Proxies.java
@@ -1,81 +1,81 @@
package org.genedb.crawl.dao.proxy;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.ArrayUtils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.type.JavaType;
import org.genedb.crawl.CrawlException;
import org.genedb.crawl.client.CrawlClient;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
public class Proxies {
static Logger logger = Logger.getLogger(Proxies.class);
private static String[] resources;
public String[] getResources() {
return resources;
}
public void setResources(String[] resources) {
logger.info("setting resources");
logger.info(resources);
Proxies.resources = resources;
}
public static <T extends Object> T proxyRequest(JavaType type) throws CrawlException {
RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
Assert.isInstanceOf(ServletRequestAttributes.class, attrs);
ServletRequestAttributes servletAttrs = (ServletRequestAttributes) attrs;
HttpServletRequest request = servletAttrs.getRequest();
@SuppressWarnings("unchecked")
Map<String, String[]> parameters = request.getParameterMap();
String[] uriSplit = request.getRequestURI().split("/");
ArrayUtils.reverse(uriSplit);
String method = uriSplit[0];
String resource = uriSplit[1];
String dot = ".";
int dotPos = method.indexOf(dot);
if (dotPos > 0)
method = method.substring(0, dotPos);
for (String url : resources) {
logger.info(url + " - " + resource + " - " + method);
CrawlClient client = new CrawlClient(url);
try {
- T result = client.request(type, resource, method, parameters);
+ T result = (T) client.request(type, resource, method, parameters);
if (result != null) {
logger.info(type + " -- " + result.getClass());
logger.info("found result, returning");
return result;
}
} catch (IOException e) {
throw new RuntimeException(e);
} catch (CrawlException e) {
throw (e);
}
}
return null;
}
}
| true | true | public static <T extends Object> T proxyRequest(JavaType type) throws CrawlException {
RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
Assert.isInstanceOf(ServletRequestAttributes.class, attrs);
ServletRequestAttributes servletAttrs = (ServletRequestAttributes) attrs;
HttpServletRequest request = servletAttrs.getRequest();
@SuppressWarnings("unchecked")
Map<String, String[]> parameters = request.getParameterMap();
String[] uriSplit = request.getRequestURI().split("/");
ArrayUtils.reverse(uriSplit);
String method = uriSplit[0];
String resource = uriSplit[1];
String dot = ".";
int dotPos = method.indexOf(dot);
if (dotPos > 0)
method = method.substring(0, dotPos);
for (String url : resources) {
logger.info(url + " - " + resource + " - " + method);
CrawlClient client = new CrawlClient(url);
try {
T result = client.request(type, resource, method, parameters);
if (result != null) {
logger.info(type + " -- " + result.getClass());
logger.info("found result, returning");
return result;
}
} catch (IOException e) {
throw new RuntimeException(e);
} catch (CrawlException e) {
throw (e);
}
}
return null;
}
| public static <T extends Object> T proxyRequest(JavaType type) throws CrawlException {
RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
Assert.isInstanceOf(ServletRequestAttributes.class, attrs);
ServletRequestAttributes servletAttrs = (ServletRequestAttributes) attrs;
HttpServletRequest request = servletAttrs.getRequest();
@SuppressWarnings("unchecked")
Map<String, String[]> parameters = request.getParameterMap();
String[] uriSplit = request.getRequestURI().split("/");
ArrayUtils.reverse(uriSplit);
String method = uriSplit[0];
String resource = uriSplit[1];
String dot = ".";
int dotPos = method.indexOf(dot);
if (dotPos > 0)
method = method.substring(0, dotPos);
for (String url : resources) {
logger.info(url + " - " + resource + " - " + method);
CrawlClient client = new CrawlClient(url);
try {
T result = (T) client.request(type, resource, method, parameters);
if (result != null) {
logger.info(type + " -- " + result.getClass());
logger.info("found result, returning");
return result;
}
} catch (IOException e) {
throw new RuntimeException(e);
} catch (CrawlException e) {
throw (e);
}
}
return null;
}
|
diff --git a/PrimeNumbers/src/PrimeNumbers.java b/PrimeNumbers/src/PrimeNumbers.java
index 8d00b3a..1e92beb 100644
--- a/PrimeNumbers/src/PrimeNumbers.java
+++ b/PrimeNumbers/src/PrimeNumbers.java
@@ -1,14 +1,14 @@
import java.util.ArrayList;
public class PrimeNumbers {
public static ArrayList<Integer> generatePrimes(int n){
ArrayList<Integer> ret = new ArrayList<Integer>();
if(n != 1){
- ret.add(2);
+ ret.add(n);
}
return ret;
}
}
| true | true | public static ArrayList<Integer> generatePrimes(int n){
ArrayList<Integer> ret = new ArrayList<Integer>();
if(n != 1){
ret.add(2);
}
return ret;
}
| public static ArrayList<Integer> generatePrimes(int n){
ArrayList<Integer> ret = new ArrayList<Integer>();
if(n != 1){
ret.add(n);
}
return ret;
}
|
diff --git a/src/Main.java b/src/Main.java
index 938615a..41640a3 100644
--- a/src/Main.java
+++ b/src/Main.java
@@ -1,45 +1,45 @@
import java.util.ResourceBundle;
public class Main {
public static void checkOver(String[] args) throws Exception {
if (args.length == 0) {
throw new Exception("No Files");
}
int i,j; //loops counters
for (i=0; i < args.length; i++){
for(j = i+1; j < args.length; j++){
if (args[i].equals(args[j])){
throw new Exception("2 queried files are the same file");
}
}
}
}
/**
* main method of the history system
* @param args command line arguments supplied by the user
*/
public static void main(String[] args){
long start = System.currentTimeMillis();
ResourceBundle bundle = ResourceBundle.getBundle("config");
try {
checkOver(args);
//information is parsed and printed here using a HistoryParser instance
HistoryParser history = new HistoryParser(args);
history.printHistoryInformation();
}
//catches any exception thrown
catch (Exception e) {
e.printStackTrace(); //prints out the issue caught
}
long end = System.currentTimeMillis();
- if (bundle.getString("time?").equals("YES")) {
+ if (bundle.getString("timeToggle").equals("true")) {
System.out.println("\n("+(end-start)/1000.00+" seconds for completion)");
}
}
}
| true | true | public static void main(String[] args){
long start = System.currentTimeMillis();
ResourceBundle bundle = ResourceBundle.getBundle("config");
try {
checkOver(args);
//information is parsed and printed here using a HistoryParser instance
HistoryParser history = new HistoryParser(args);
history.printHistoryInformation();
}
//catches any exception thrown
catch (Exception e) {
e.printStackTrace(); //prints out the issue caught
}
long end = System.currentTimeMillis();
if (bundle.getString("time?").equals("YES")) {
System.out.println("\n("+(end-start)/1000.00+" seconds for completion)");
}
}
| public static void main(String[] args){
long start = System.currentTimeMillis();
ResourceBundle bundle = ResourceBundle.getBundle("config");
try {
checkOver(args);
//information is parsed and printed here using a HistoryParser instance
HistoryParser history = new HistoryParser(args);
history.printHistoryInformation();
}
//catches any exception thrown
catch (Exception e) {
e.printStackTrace(); //prints out the issue caught
}
long end = System.currentTimeMillis();
if (bundle.getString("timeToggle").equals("true")) {
System.out.println("\n("+(end-start)/1000.00+" seconds for completion)");
}
}
|
diff --git a/kovu/teamstats/api/TeamStatsAPI.java b/kovu/teamstats/api/TeamStatsAPI.java
index fe79fd5..4c3aa5d 100644
--- a/kovu/teamstats/api/TeamStatsAPI.java
+++ b/kovu/teamstats/api/TeamStatsAPI.java
@@ -1,673 +1,681 @@
package kovu.teamstats.api;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import kovu.teamstats.api.exception.CreationNotCompleteException;
import kovu.teamstats.api.exception.ServerConnectionLostException;
import kovu.teamstats.api.exception.ServerOutdatedException;
import kovu.teamstats.api.exception.ServerRejectionException;
import kovu.teamstats.api.list.TSAList;
import net.ae97.teamstats.ClientRequest;
import net.ae97.teamstats.networking.Packet;
import net.ae97.teamstats.networking.PacketListener;
import net.ae97.teamstats.networking.PacketSender;
import net.minecraft.client.Minecraft;
/**
* The TeamStats API class. This handles all the server-related requests. This
* should be used to get info from the server.
*
* @author Lord_Ralex
* @version 0.3
* @since 0.1
*/
public final class TeamStatsAPI {
private static TeamStatsAPI api;
private static final String MAIN_SERVER_URL;
private static final int SERVER_PORT;
private final String name;
private String session;
private Socket connection;
private final PacketListener packetListener;
private final PacketSender packetSender;
private final List<String> friendList = new TSAList<String>();
private final Map<String, Map<String, Object>> friendStats = new ConcurrentHashMap<String, Map<String, Object>>();
private final List<String> friendRequests = new TSAList<String>();
private final UpdaterThread updaterThread = new UpdaterThread();
private final Map<String, Object> stats = new ConcurrentHashMap<String, Object>();
private final List<String> newFriends = new TSAList<String>();
private final List<String> newRequests = new TSAList<String>();
private final List<String> newlyRemovedFriends = new TSAList<String>();
private final List<String> onlineFriends = new TSAList<String>();
private final List<String> rejectedRequests = new TSAList<String>();
private final int UPDATE_TIMER = 60; //time this means is set when sent to executor service
private boolean online = false;
private static final short API_VERSION = 4;
private boolean was_set_up = false;
private final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
private final ScheduledFuture task;
static {
//enter the server url here where the main bouncer is
MAIN_SERVER_URL = "teamstats.ae97.net";
//enter the port the bouncer runs off of here
SERVER_PORT = 19325;
}
public TeamStatsAPI(String aName, String aSession) throws ServerRejectionException, IOException, ClassNotFoundException {
name = aName;
session = aSession;
connection = new Socket(MAIN_SERVER_URL, SERVER_PORT);
PacketSender tempSender = new PacketSender(connection.getOutputStream());
PacketListener tempListener = new PacketListener(connection.getInputStream());
tempListener.start();
Packet getServer = new Packet(ClientRequest.GETSERVER);
tempSender.sendPacket(getServer);
Packet p = tempListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
tempListener.interrupt();
String SERVER_URL = null;
Object o = p.getData("ip");
if (o instanceof String) {
SERVER_URL = (String) o;
}
connection.close();
if (SERVER_URL == null || SERVER_URL.equalsIgnoreCase("NONODE")) {
throw new ServerRejectionException("There is no node open");
}
String link = (String) p.getData("ip");
int port = (Integer) p.getData("port");
short server_version = (Short) p.getData("version");
if (server_version != API_VERSION) {
throw new ServerOutdatedException();
}
connection = new Socket(link, port);
packetListener = new PacketListener(connection.getInputStream());
packetSender = new PacketSender(connection.getOutputStream());
packetListener.start();
Packet pac = new Packet(ClientRequest.OPENCONNECTION);
pac.addData("name", name).addData("session", session);
packetSender.sendPacket(pac);
Packet response = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
boolean isAccepted = (Boolean) response.getData("reply");
if (!isAccepted) {
throw new ServerRejectionException();
}
task = service.scheduleAtFixedRate(updaterThread, UPDATE_TIMER, UPDATE_TIMER, TimeUnit.SECONDS);
online = true;
was_set_up = true;
}
/**
* Gets the stats for each friend that is registered by the server. This can
* throw an IOException if the server rejects the client communication or an
* issue occurs when reading the data.
*
* @return Mapping of friends and their stats
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public Map<String, Map<String, Object>> getFriendStats() throws IOException {
wasSetup();
return friendStats;
}
/**
* Returns the map's toString form of the friend's stats. THIS IS
* DEPRECATED, REFER TO NOTES FOR NEW METHOD
*
* @param friendName Name of friend
* @return String version of the stats
* @throws IOException
*/
public String getFriendState(String friendName) throws IOException {
wasSetup();
return friendStats.get(friendName).toString();
}
/**
* Gets the stats for a single friend. If the friend requested is not an
* actual friend, this will return null.
*
* @param friendName The friend to get the stats for
* @return The stats in a map
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public Map<String, Object> getFriendStat(String friendName) throws IOException {
wasSetup();
return friendStats.get(friendName);
}
/**
* Gets the specific value for a certain stat for a friend. The key is the
* stat name.
*
* @param friendName Name of friend
* @param key Key of stat
* @return Value of the friend's key, or null if not one
* @throws IOException
*/
public Object getFriendStat(String friendName, String key) throws IOException {
wasSetup();
key = key.toLowerCase();
Map<String, Object> stat = friendStats.get(friendName);
if (stat == null) {
return null;
} else {
return stat.get(key);
}
}
/**
* Gets all accepted friends.
*
* @return An array of all friends accepted
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public String[] getFriends() throws IOException {
wasSetup();
return friendList.toArray(new String[0]);
}
/**
* Sends the stats to the server. This will never return false. If the
* connection is rejected, this will throw an IOException.
*
* @param key Key to set
* @param value The value for this key
* @return True if connection was successful.
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public boolean updateStats(String key, Object value) throws IOException {
wasSetup();
stats.put(key.toLowerCase().trim(), value);
return true;
}
/**
* Sends the stats to the server. This will never return false. If the
* connection is rejected, this will throw an IOException.
*
* @param map Map of values to set
* @return True if connection was successful.
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public boolean updateStats(Map<String, Object> map) throws IOException {
for (String key : map.keySet()) {
updateStats(key, map.get(key));
}
return true;
}
/**
* Gets a list of friend requests the user has. This will return names of
* those that want to friend this user.
*
* @return Array of friend requests to the user
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public String[] getFriendRequests() throws IOException {
wasSetup();
return friendRequests.toArray(new String[0]);
}
/**
* Requests a friend addition. This will not add them, just request that the
* person add them. The return is just for the connection, not for the
* friend request.
*
* @param name Name of friend to add/request
* @return True if request was successful
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public boolean addFriend(String name) throws IOException {
wasSetup();
return friendList.add(name);
}
/**
* Removes a friend. This will take place once used and any friend list will
* be updated.
*
* @param name Name of friend to remove
* @return True if connection was successful
* @throws IOException Thrown when server fails to send data or if server
* rejects communication
*/
public boolean removeFriend(String name) throws IOException {
wasSetup();
return friendList.remove(name);
}
/**
* Gets the list of new requests to this user. This will also clear the list
* if true is passed.
*
* @param reset Whether to clear the list. True will remove the list after
* returning it.
* @return Names of new friend requests
*/
public String[] getNewFriendRequests(boolean reset) throws IOException {
wasSetup();
String[] newFriendsToReturn = newRequests.toArray(new String[0]);
if (reset) {
newRequests.clear();
}
return newFriendsToReturn;
}
/**
* Gets the list of new rejected names to this user. This will also clear
* the list if true is passed.
*
* @param reset Whether to clear the list. True will remove the list after
* returning it.
* @return Names of new rejected requests
*/
public String[] getNewRejectedRequests(boolean reset) throws IOException {
wasSetup();
String[] rejectedRequestsToReturn = rejectedRequests.toArray(new String[0]);
if (reset) {
rejectedRequests.clear();
}
return rejectedRequestsToReturn;
}
/**
* Gets the list of removed friends to this user. This will also clear the
* list if true is passed.
*
* @param reset Whether to clear the list. True will remove the list after
* returning it.
* @return Names of newly removed friends
*/
public String[] getRemovedFriends(boolean reset) throws IOException {
wasSetup();
String[] newFriendsToReturn = newlyRemovedFriends.toArray(new String[0]);
if (reset) {
newlyRemovedFriends.clear();
}
return newFriendsToReturn;
}
/**
* Gets the list of new friends to this user. This will also clear the list
* if true is passed.
*
* @param reset Whether to clear the list. True will remove the list after
* returning it.
* @return Names of new friends
*/
public String[] getNewFriends(boolean reset) throws IOException {
wasSetup();
String[] newFriendsToReturn = newFriends.toArray(new String[0]);
if (reset) {
newFriends.clear();
}
return newFriendsToReturn;
}
/**
* Gets the list of new requests to this user. This will also clear the
* list.
*
* @return Names of new friend requests
*/
public String[] getNewFriendRequests() throws IOException {
wasSetup();
return getNewFriendRequests(true);
}
/**
* Gets the list of removed friends to this user. This will also clear the
* list.
*
* @return Names of newly removed friends
*/
public String[] getRemovedFriends() throws IOException {
wasSetup();
return getRemovedFriends(true);
}
/**
* Gets the list of new friends to this user. This will also clear the list.
*
* @return Names of new friends
*/
public String[] getNewFriends() throws IOException {
wasSetup();
return getNewFriends(true);
}
/**
* Returns an array of friends that are online based on the cache.
*
* @return Array of friends who are online
*/
public String[] getOnlineFriends() throws IOException {
wasSetup();
return onlineFriends.toArray(new String[0]);
}
/**
* Checks to see if a particular friend is online.
*
* @param name Name of friend
* @return True if they are online, false otherwise
*/
public boolean isFriendOnline(String name) throws IOException {
wasSetup();
return onlineFriends.contains(name);
}
/**
* Forces the client to update the stats and such. This forces the update
* thread to run.
*
* @throws IOException
*/
public void forceUpdate() throws IOException {
wasSetup();
synchronized (task) {
if (!task.isDone()) {
task.notify();
} else {
throw new ServerConnectionLostException();
}
}
}
/**
* Checks to see if the client is still connected to the server and if the
* update thread is running.
*
* @return True if the update thread is alive, false otherwise.
* @throws IOException
*/
public boolean isChecking() throws IOException {
wasSetup();
boolean done;
synchronized (task) {
done = task.isDone();
}
return !done;
}
/**
* Changes the online status of the client. This is instant to the server
* and tells the server to turn the client offline.
*
* @param newStatus New online status
* @return The new online status
* @throws IOException
*/
public boolean changeOnlineStatus(boolean newStatus) throws IOException {
wasSetup();
online = newStatus;
Packet packet = new Packet(ClientRequest.CHANGEONLINE);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("online", online);
packetSender.sendPacket(packet);
Packet reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if ((Boolean) reply.getData("reply")) {
return online;
} else {
throw new ServerRejectionException();
}
}
/**
* Changes the online status of the client. This is instant to the server
* and tells the server to turn the client offline.
*
* @return The new online status
* @throws IOException
*/
public boolean changeOnlineStatus() throws IOException {
wasSetup();
return changeOnlineStatus(!online);
}
/**
* Returns a boolean where true means the API was completely setup and
* connections were successful, otherwise an exception is thrown. This only
* checks the initial connection, not the later connections. Use
* isChecking() for that.
*
* @return True if API was set up.
* @throws IOException If api was not created right, exception thrown
*/
public boolean wasSetup() throws IOException {
if (was_set_up) {
return true;
} else {
throw new CreationNotCompleteException();
}
}
public static void setAPI(TeamStatsAPI apiTemp) throws IllegalAccessException {
if (apiTemp == null) {
throw new IllegalAccessException("The API instance cannot be null");
}
if (api != null) {
if (api == apiTemp) {
return;
} else {
throw new IllegalAccessException("Cannot change the API once it is set");
}
}
api = apiTemp;
}
public static TeamStatsAPI getAPI() {
return api;
}
private class UpdaterThread implements Runnable {
@Override
public void run() {
if (online) {
try {
Packet packet = new Packet(ClientRequest.GETFRIENDS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packetSender.sendPacket(packet);
String[] friends;
Packet reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException((String) reply.getData("reason"));
}
String namesList = (String) packet.getData("names");
if (namesList != null) {
friends = namesList.split(" ");
} else {
friends = new String[0];
}
//check current friend list, removing and adding name differences
List<String> addFriend = new TSAList<String>();
addFriend.addAll(friendList);
for (String existing : friends) {
addFriend.remove(existing);
}
for (String name : addFriend) {
packet = new Packet(ClientRequest.ADDFRIEND);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("name", name);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
}
List<String> removeFriend = new ArrayList<String>();
removeFriend.addAll(Arrays.asList(friends));
for (String existing : friendList) {
removeFriend.remove(existing);
}
for (String name : removeFriend) {
packet = new Packet(ClientRequest.REMOVEFRIEND);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("name", name);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
}
packet = new Packet(ClientRequest.UPDATESTATS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("stats", stats);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
packet = new Packet(ClientRequest.REJECTREQUEST);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("names", null);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
packet = new Packet(ClientRequest.REJECTEDREQUESTS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String rejectedNames = (String) reply.getData("names");
if (rejectedNames != null) {
rejectedRequests.clear();
rejectedRequests.addAll(Arrays.asList(rejectedNames));
}
//check friend requests
packet = new Packet(ClientRequest.GETREQUESTS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String names = (String) reply.getData("names");
+ String[] old = friendRequests.toArray(new String[friendRequests.size()]);
friendRequests.clear();
if (names != null) {
friendRequests.addAll(Arrays.asList(names.split(" ")));
}
- String[] old = friendRequests.toArray(new String[0]);
- for (String name : old) {
- if (!newRequests.contains(name)) {
- newRequests.add(name);
+ for (String newName : friendRequests) {
+ boolean name_new = true;
+ for (String name : old) {
+ if (name.equalsIgnoreCase(newName)) {
+ name_new = false;
+ break;
+ }
+ }
+ if (name_new) {
+ newRequests.add(newName);
}
}
+ //newRequests
packet = new Packet(ClientRequest.GETFRIENDS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String aNameList = (String) reply.getData("names");
List<String> updateFriends = new ArrayList<String>();
if (aNameList != null) {
updateFriends = Arrays.asList(aNameList.split(" "));
if (updateFriends == null) {
updateFriends = new ArrayList<String>();
}
}
for (String name : updateFriends) {
if (friendList.contains(name)) {
continue;
}
newFriends.add(name);
}
for (String name : friendList) {
if (updateFriends.contains(name)) {
continue;
}
newlyRemovedFriends.add(name);
}
friendList.clear();
friendList.addAll(updateFriends);
//get stats for friends in list
friendStats.clear();
onlineFriends.clear();
for (String friendName : friendList) {
Packet send = new Packet(ClientRequest.GETSTATS);
send.addData("session", Minecraft.getMinecraft().session.sessionId);
send.addData("name", friendName);
packetSender.sendPacket(send);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String stat = (String) reply.getData("stats");
Map<String, Object> friendS = new HashMap<String, Object>();
String[] parts = stat.split(" ");
for (String string : parts) {
friendS.put(string.split(":")[0].toLowerCase().trim(), string.split(":")[1]);
}
friendStats.put(friendName, friendS);
Packet send2 = new Packet(ClientRequest.GETONLINESTATUS);
send2.addData("session", Minecraft.getMinecraft().session.sessionId);
send2.addData("name", friendName);
packetSender.sendPacket(send2);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
boolean isOnline = (Boolean) reply.getData("online");
if (isOnline) {
onlineFriends.add(friendName);
}
}
} catch (Exception ex) {
synchronized (System.out) {
System.out.println(ex.getMessage());
StackTraceElement[] el = ex.getStackTrace();
for (StackTraceElement e : el) {
System.out.println(e.toString());
}
online = false;
}
}
} else {
new ServerConnectionLostException().printStackTrace(System.out);
online = false;
}
}
}
}
| false | true | public void run() {
if (online) {
try {
Packet packet = new Packet(ClientRequest.GETFRIENDS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packetSender.sendPacket(packet);
String[] friends;
Packet reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException((String) reply.getData("reason"));
}
String namesList = (String) packet.getData("names");
if (namesList != null) {
friends = namesList.split(" ");
} else {
friends = new String[0];
}
//check current friend list, removing and adding name differences
List<String> addFriend = new TSAList<String>();
addFriend.addAll(friendList);
for (String existing : friends) {
addFriend.remove(existing);
}
for (String name : addFriend) {
packet = new Packet(ClientRequest.ADDFRIEND);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("name", name);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
}
List<String> removeFriend = new ArrayList<String>();
removeFriend.addAll(Arrays.asList(friends));
for (String existing : friendList) {
removeFriend.remove(existing);
}
for (String name : removeFriend) {
packet = new Packet(ClientRequest.REMOVEFRIEND);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("name", name);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
}
packet = new Packet(ClientRequest.UPDATESTATS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("stats", stats);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
packet = new Packet(ClientRequest.REJECTREQUEST);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("names", null);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
packet = new Packet(ClientRequest.REJECTEDREQUESTS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String rejectedNames = (String) reply.getData("names");
if (rejectedNames != null) {
rejectedRequests.clear();
rejectedRequests.addAll(Arrays.asList(rejectedNames));
}
//check friend requests
packet = new Packet(ClientRequest.GETREQUESTS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String names = (String) reply.getData("names");
friendRequests.clear();
if (names != null) {
friendRequests.addAll(Arrays.asList(names.split(" ")));
}
String[] old = friendRequests.toArray(new String[0]);
for (String name : old) {
if (!newRequests.contains(name)) {
newRequests.add(name);
}
}
packet = new Packet(ClientRequest.GETFRIENDS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String aNameList = (String) reply.getData("names");
List<String> updateFriends = new ArrayList<String>();
if (aNameList != null) {
updateFriends = Arrays.asList(aNameList.split(" "));
if (updateFriends == null) {
updateFriends = new ArrayList<String>();
}
}
for (String name : updateFriends) {
if (friendList.contains(name)) {
continue;
}
newFriends.add(name);
}
for (String name : friendList) {
if (updateFriends.contains(name)) {
continue;
}
newlyRemovedFriends.add(name);
}
friendList.clear();
friendList.addAll(updateFriends);
//get stats for friends in list
friendStats.clear();
onlineFriends.clear();
for (String friendName : friendList) {
Packet send = new Packet(ClientRequest.GETSTATS);
send.addData("session", Minecraft.getMinecraft().session.sessionId);
send.addData("name", friendName);
packetSender.sendPacket(send);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String stat = (String) reply.getData("stats");
Map<String, Object> friendS = new HashMap<String, Object>();
String[] parts = stat.split(" ");
for (String string : parts) {
friendS.put(string.split(":")[0].toLowerCase().trim(), string.split(":")[1]);
}
friendStats.put(friendName, friendS);
Packet send2 = new Packet(ClientRequest.GETONLINESTATUS);
send2.addData("session", Minecraft.getMinecraft().session.sessionId);
send2.addData("name", friendName);
packetSender.sendPacket(send2);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
boolean isOnline = (Boolean) reply.getData("online");
if (isOnline) {
onlineFriends.add(friendName);
}
}
} catch (Exception ex) {
synchronized (System.out) {
System.out.println(ex.getMessage());
StackTraceElement[] el = ex.getStackTrace();
for (StackTraceElement e : el) {
System.out.println(e.toString());
}
online = false;
}
}
} else {
new ServerConnectionLostException().printStackTrace(System.out);
online = false;
}
}
| public void run() {
if (online) {
try {
Packet packet = new Packet(ClientRequest.GETFRIENDS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packetSender.sendPacket(packet);
String[] friends;
Packet reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException((String) reply.getData("reason"));
}
String namesList = (String) packet.getData("names");
if (namesList != null) {
friends = namesList.split(" ");
} else {
friends = new String[0];
}
//check current friend list, removing and adding name differences
List<String> addFriend = new TSAList<String>();
addFriend.addAll(friendList);
for (String existing : friends) {
addFriend.remove(existing);
}
for (String name : addFriend) {
packet = new Packet(ClientRequest.ADDFRIEND);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("name", name);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
}
List<String> removeFriend = new ArrayList<String>();
removeFriend.addAll(Arrays.asList(friends));
for (String existing : friendList) {
removeFriend.remove(existing);
}
for (String name : removeFriend) {
packet = new Packet(ClientRequest.REMOVEFRIEND);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("name", name);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
}
packet = new Packet(ClientRequest.UPDATESTATS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("stats", stats);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
packet = new Packet(ClientRequest.REJECTREQUEST);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packet.addData("names", null);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
packet = new Packet(ClientRequest.REJECTEDREQUESTS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String rejectedNames = (String) reply.getData("names");
if (rejectedNames != null) {
rejectedRequests.clear();
rejectedRequests.addAll(Arrays.asList(rejectedNames));
}
//check friend requests
packet = new Packet(ClientRequest.GETREQUESTS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String names = (String) reply.getData("names");
String[] old = friendRequests.toArray(new String[friendRequests.size()]);
friendRequests.clear();
if (names != null) {
friendRequests.addAll(Arrays.asList(names.split(" ")));
}
for (String newName : friendRequests) {
boolean name_new = true;
for (String name : old) {
if (name.equalsIgnoreCase(newName)) {
name_new = false;
break;
}
}
if (name_new) {
newRequests.add(newName);
}
}
//newRequests
packet = new Packet(ClientRequest.GETFRIENDS);
packet.addData("session", Minecraft.getMinecraft().session.sessionId);
packetSender.sendPacket(packet);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String aNameList = (String) reply.getData("names");
List<String> updateFriends = new ArrayList<String>();
if (aNameList != null) {
updateFriends = Arrays.asList(aNameList.split(" "));
if (updateFriends == null) {
updateFriends = new ArrayList<String>();
}
}
for (String name : updateFriends) {
if (friendList.contains(name)) {
continue;
}
newFriends.add(name);
}
for (String name : friendList) {
if (updateFriends.contains(name)) {
continue;
}
newlyRemovedFriends.add(name);
}
friendList.clear();
friendList.addAll(updateFriends);
//get stats for friends in list
friendStats.clear();
onlineFriends.clear();
for (String friendName : friendList) {
Packet send = new Packet(ClientRequest.GETSTATS);
send.addData("session", Minecraft.getMinecraft().session.sessionId);
send.addData("name", friendName);
packetSender.sendPacket(send);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
String stat = (String) reply.getData("stats");
Map<String, Object> friendS = new HashMap<String, Object>();
String[] parts = stat.split(" ");
for (String string : parts) {
friendS.put(string.split(":")[0].toLowerCase().trim(), string.split(":")[1]);
}
friendStats.put(friendName, friendS);
Packet send2 = new Packet(ClientRequest.GETONLINESTATUS);
send2.addData("session", Minecraft.getMinecraft().session.sessionId);
send2.addData("name", friendName);
packetSender.sendPacket(send2);
reply = packetListener.getNextPacket(ClientRequest.SIMPLEREPLYPACKET);
if (!(Boolean) reply.getData("reply")) {
throw new ServerRejectionException();
}
boolean isOnline = (Boolean) reply.getData("online");
if (isOnline) {
onlineFriends.add(friendName);
}
}
} catch (Exception ex) {
synchronized (System.out) {
System.out.println(ex.getMessage());
StackTraceElement[] el = ex.getStackTrace();
for (StackTraceElement e : el) {
System.out.println(e.toString());
}
online = false;
}
}
} else {
new ServerConnectionLostException().printStackTrace(System.out);
online = false;
}
}
|
diff --git a/MyTracks/src/com/google/android/apps/mytracks/services/tasks/StatusAnnouncerTask.java b/MyTracks/src/com/google/android/apps/mytracks/services/tasks/StatusAnnouncerTask.java
index ee1c53cc..ed6472bd 100644
--- a/MyTracks/src/com/google/android/apps/mytracks/services/tasks/StatusAnnouncerTask.java
+++ b/MyTracks/src/com/google/android/apps/mytracks/services/tasks/StatusAnnouncerTask.java
@@ -1,298 +1,298 @@
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.tasks;
import com.google.android.apps.mytracks.services.TrackRecordingService;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.apps.mytracks.util.PreferencesUtils;
import com.google.android.apps.mytracks.util.StringUtils;
import com.google.android.apps.mytracks.util.UnitConversions;
import com.google.android.maps.mytracks.R;
import com.google.common.annotations.VisibleForTesting;
import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import java.util.Locale;
/**
* This class will periodically announce the user's trip statistics.
*
* @author Sandor Dornbush
*/
public class StatusAnnouncerTask implements PeriodicTask {
/**
* The rate at which announcements are spoken.
*/
@VisibleForTesting
static final float TTS_SPEECH_RATE = 0.9f;
private static final String TAG = StatusAnnouncerTask.class.getSimpleName();
private static final long HOUR_TO_MILLISECOND = 60 * 60 * 1000;
private final Context context;
protected TextToSpeech tts;
// Response from TTS after its initialization
private int initStatus = TextToSpeech.ERROR;
// True if TTS engine is ready
private boolean ready = false;
// True if speech is allowed
private boolean speechAllowed;
/**
* Listener which updates {@link #speechAllowed} when the phone state changes.
*/
private final PhoneStateListener phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
speechAllowed = state == TelephonyManager.CALL_STATE_IDLE;
if (!speechAllowed && tts != null && tts.isSpeaking()) {
// If we're already speaking, stop it.
tts.stop();
}
}
};
public StatusAnnouncerTask(Context context) {
this.context = context;
}
@Override
public void start() {
if (tts == null) {
tts = newTextToSpeech(context, new OnInitListener() {
@Override
public void onInit(int status) {
initStatus = status;
}
});
}
speechAllowed = true;
listenToPhoneState(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
@Override
public void run(TrackRecordingService trackRecordingService) {
if (trackRecordingService == null) {
Log.e(TAG, "TrackRecordingService is null.");
return;
}
announce(trackRecordingService.getTripStatistics());
}
/**
* Runs this task.
*
* @param tripStatistics the trip statistics
*/
@VisibleForTesting
void announce(TripStatistics tripStatistics) {
if (tripStatistics == null) {
Log.e(TAG, "TripStatistics is null.");
return;
}
synchronized (this) {
if (!ready) {
ready = initStatus == TextToSpeech.SUCCESS;
if (ready) {
onTtsReady();
}
}
if (!ready) {
Log.i(TAG, "TTS not ready.");
return;
}
}
if (!speechAllowed) {
Log.i(TAG, "Speech is not allowed at this time.");
return;
}
speakAnnouncement(getAnnouncement(tripStatistics));
}
@Override
public void shutdown() {
listenToPhoneState(phoneStateListener, PhoneStateListener.LISTEN_NONE);
if (tts != null) {
tts.shutdown();
tts = null;
}
}
/**
* Called when TTS is ready.
*/
protected void onTtsReady() {
Locale locale = Locale.getDefault();
int languageAvailability = tts.isLanguageAvailable(locale);
if (languageAvailability == TextToSpeech.LANG_MISSING_DATA
|| languageAvailability == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.w(TAG, "Default locale not available, use English.");
locale = Locale.ENGLISH;
/*
* TODO: instead of using english, load the language if missing and show a
* toast if not supported. Not able to change the resource strings to
* English.
*/
}
tts.setLanguage(locale);
// Slow down the speed just a bit as it is hard to hear when exercising.
tts.setSpeechRate(TTS_SPEECH_RATE);
}
/**
* Speaks the announcement.
*
* @param announcement the announcement
*/
protected void speakAnnouncement(String announcement) {
tts.speak(announcement, TextToSpeech.QUEUE_FLUSH, null);
}
/**
* Create a new {@link TextToSpeech}.
*
* @param aContext a context
* @param onInitListener an on init listener
*/
@VisibleForTesting
protected TextToSpeech newTextToSpeech(Context aContext, OnInitListener onInitListener) {
return new TextToSpeech(aContext, onInitListener);
}
/**
* Gets the announcement.
*
* @param tripStatistics the trip statistics
*/
@VisibleForTesting
protected String getAnnouncement(TripStatistics tripStatistics) {
boolean metricUnits = PreferencesUtils.getBoolean(
context, R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT);
boolean reportSpeed = PreferencesUtils.getBoolean(
context, R.string.report_speed_key, PreferencesUtils.REPORT_SPEED_DEFAULT);
double distance = tripStatistics.getTotalDistance() * UnitConversions.M_TO_KM;
double speed = tripStatistics.getAverageMovingSpeed() * UnitConversions.MS_TO_KMH;
if (distance == 0) {
return context.getString(R.string.voice_total_distance_zero);
}
if (!metricUnits) {
distance *= UnitConversions.KM_TO_MI;
speed *= UnitConversions.KM_TO_MI;
}
String rate;
if (reportSpeed) {
int speedId = metricUnits ? R.plurals.voiceSpeedKilometersPerHour
: R.plurals.voiceSpeedMilesPerHour;
rate = context.getResources().getQuantityString(speedId, getQuantityCount(speed), speed);
} else {
speed = speed == 0 ? 0.0 : 1 / speed;
int paceId = metricUnits ? R.string.voice_pace_per_kilometer : R.string.voice_pace_per_mile;
- rate = context.getString(paceId, getAnnounceTime((long) speed * HOUR_TO_MILLISECOND));
+ rate = context.getString(paceId, getAnnounceTime((long) (speed * HOUR_TO_MILLISECOND)));
}
int totalDistanceId = metricUnits ? R.plurals.voiceTotalDistanceKilometers
: R.plurals.voiceTotalDistanceMiles;
String totalDistance = context.getResources()
.getQuantityString(totalDistanceId, getQuantityCount(distance), distance);
return context.getString(R.string.voice_template, totalDistance, getAnnounceTime(
tripStatistics.getMovingTime()), rate);
}
/**
* Listens to phone state.
*
* @param listener the listener
* @param events the interested events
*/
@VisibleForTesting
protected void listenToPhoneState(PhoneStateListener listener, int events) {
TelephonyManager telephony = (TelephonyManager) context.getSystemService(
Context.TELEPHONY_SERVICE);
if (telephony != null) {
telephony.listen(listener, events);
}
}
/**
* Gets the announce time.
*
* @param time the time
*/
@VisibleForTesting
String getAnnounceTime(long time) {
int[] parts = StringUtils.getTimeParts(time);
String seconds = context.getResources()
.getQuantityString(R.plurals.voiceSeconds, parts[0], parts[0]);
String minutes = context.getResources()
.getQuantityString(R.plurals.voiceMinutes, parts[1], parts[1]);
String hours = context.getResources()
.getQuantityString(R.plurals.voiceHours, parts[2], parts[2]);
StringBuilder sb = new StringBuilder();
if (parts[2] != 0) {
sb.append(hours);
sb.append(" ");
sb.append(minutes);
} else {
sb.append(minutes);
sb.append(" ");
sb.append(seconds);
}
return sb.toString();
}
/**
* Gets the plural count to be used by getQuantityString. getQuantityString
* only supports integer quantities, not a double quantity like "2.2".
* <p>
* As a temporary workaround, we convert a double quantity to an integer
* quantity. If the double quantity is exactly 0, 1, or 2, then we can return
* these integer quantities. Otherwise, we cast the double quantity to an
* integer quantity. However, we need to make sure that if the casted value is
* 0, 1, or 2, we don't return those, instead, return the next biggest integer
* 3.
*
* @param d the double value
*/
private int getQuantityCount(double d) {
if (d == 0) {
return 0;
} else if (d == 1) {
return 1;
} else if (d == 2) {
return 2;
} else {
int count = (int) d;
return count < 3 ? 3 : count;
}
}
}
| true | true | protected String getAnnouncement(TripStatistics tripStatistics) {
boolean metricUnits = PreferencesUtils.getBoolean(
context, R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT);
boolean reportSpeed = PreferencesUtils.getBoolean(
context, R.string.report_speed_key, PreferencesUtils.REPORT_SPEED_DEFAULT);
double distance = tripStatistics.getTotalDistance() * UnitConversions.M_TO_KM;
double speed = tripStatistics.getAverageMovingSpeed() * UnitConversions.MS_TO_KMH;
if (distance == 0) {
return context.getString(R.string.voice_total_distance_zero);
}
if (!metricUnits) {
distance *= UnitConversions.KM_TO_MI;
speed *= UnitConversions.KM_TO_MI;
}
String rate;
if (reportSpeed) {
int speedId = metricUnits ? R.plurals.voiceSpeedKilometersPerHour
: R.plurals.voiceSpeedMilesPerHour;
rate = context.getResources().getQuantityString(speedId, getQuantityCount(speed), speed);
} else {
speed = speed == 0 ? 0.0 : 1 / speed;
int paceId = metricUnits ? R.string.voice_pace_per_kilometer : R.string.voice_pace_per_mile;
rate = context.getString(paceId, getAnnounceTime((long) speed * HOUR_TO_MILLISECOND));
}
int totalDistanceId = metricUnits ? R.plurals.voiceTotalDistanceKilometers
: R.plurals.voiceTotalDistanceMiles;
String totalDistance = context.getResources()
.getQuantityString(totalDistanceId, getQuantityCount(distance), distance);
return context.getString(R.string.voice_template, totalDistance, getAnnounceTime(
tripStatistics.getMovingTime()), rate);
}
| protected String getAnnouncement(TripStatistics tripStatistics) {
boolean metricUnits = PreferencesUtils.getBoolean(
context, R.string.metric_units_key, PreferencesUtils.METRIC_UNITS_DEFAULT);
boolean reportSpeed = PreferencesUtils.getBoolean(
context, R.string.report_speed_key, PreferencesUtils.REPORT_SPEED_DEFAULT);
double distance = tripStatistics.getTotalDistance() * UnitConversions.M_TO_KM;
double speed = tripStatistics.getAverageMovingSpeed() * UnitConversions.MS_TO_KMH;
if (distance == 0) {
return context.getString(R.string.voice_total_distance_zero);
}
if (!metricUnits) {
distance *= UnitConversions.KM_TO_MI;
speed *= UnitConversions.KM_TO_MI;
}
String rate;
if (reportSpeed) {
int speedId = metricUnits ? R.plurals.voiceSpeedKilometersPerHour
: R.plurals.voiceSpeedMilesPerHour;
rate = context.getResources().getQuantityString(speedId, getQuantityCount(speed), speed);
} else {
speed = speed == 0 ? 0.0 : 1 / speed;
int paceId = metricUnits ? R.string.voice_pace_per_kilometer : R.string.voice_pace_per_mile;
rate = context.getString(paceId, getAnnounceTime((long) (speed * HOUR_TO_MILLISECOND)));
}
int totalDistanceId = metricUnits ? R.plurals.voiceTotalDistanceKilometers
: R.plurals.voiceTotalDistanceMiles;
String totalDistance = context.getResources()
.getQuantityString(totalDistanceId, getQuantityCount(distance), distance);
return context.getString(R.string.voice_template, totalDistance, getAnnounceTime(
tripStatistics.getMovingTime()), rate);
}
|
diff --git a/grails/src/java/org/codehaus/groovy/grails/orm/hibernate/ConfigurableLocalSessionFactoryBean.java b/grails/src/java/org/codehaus/groovy/grails/orm/hibernate/ConfigurableLocalSessionFactoryBean.java
index 9d7b3ea7a..ca2404128 100644
--- a/grails/src/java/org/codehaus/groovy/grails/orm/hibernate/ConfigurableLocalSessionFactoryBean.java
+++ b/grails/src/java/org/codehaus/groovy/grails/orm/hibernate/ConfigurableLocalSessionFactoryBean.java
@@ -1,175 +1,176 @@
/* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.orm.hibernate;
import groovy.lang.GroovySystem;
import groovy.lang.MetaClassRegistry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsDomainConfiguration;
import org.codehaus.groovy.grails.orm.hibernate.cfg.DefaultGrailsDomainConfiguration;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cache.CacheException;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.metadata.ClassMetadata;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
/**
* A SessionFactory bean that allows the configuration class to be changed and customise for usage within Grails
*
* @author Graeme Rocher
* @since 07-Jul-2005
*/
public class ConfigurableLocalSessionFactoryBean extends
LocalSessionFactoryBean implements ApplicationContextAware {
private static final Log LOG = LogFactory.getLog(ConfigurableLocalSessionFactoryBean.class);
private ClassLoader classLoader = null;
private GrailsApplication grailsApplication;
private Class configClass;
private ApplicationContext applicationContext;
private Class currentSessionContextClass;
/**
* Sets class to be used for the Hibernate CurrentSessionContext
*
* @param currentSessionContextClass An implementation of the CurrentSessionContext interface
*/
public void setCurrentSessionContextClass(Class currentSessionContextClass) {
this.currentSessionContextClass = currentSessionContextClass;
}
/**
* Sets the class to be used for Hibernate Configuration
* @param configClass A subclass of the Hibernate Configuration class
*/
public void setConfigClass(Class configClass) {
this.configClass = configClass;
}
/**
*
*/
public ConfigurableLocalSessionFactoryBean() {
super();
}
/**
* @return Returns the grailsApplication.
*/
public GrailsApplication getGrailsApplication() {
return grailsApplication;
}
/**
* @param grailsApplication The grailsApplication to set.
*/
public void setGrailsApplication(GrailsApplication grailsApplication) {
this.grailsApplication = grailsApplication;
}
/**
* Overrides default behaviour to allow for a configurable configuration class
*/
protected Configuration newConfiguration() {
+ ClassLoader cl = this.classLoader != null ? this.classLoader : Thread.currentThread().getContextClassLoader();
if(configClass == null) {
try {
- configClass = this.classLoader.loadClass("org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration");
+ configClass = cl.loadClass("org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration");
}
catch (Throwable e) {
// probably not Java 5 or missing some annotation jars, use default
configClass = DefaultGrailsDomainConfiguration.class;
}
}
Object config = BeanUtils.instantiateClass(configClass);
if(config instanceof GrailsDomainConfiguration) {
GrailsDomainConfiguration grailsConfig = (GrailsDomainConfiguration) config;
grailsConfig.setGrailsApplication(grailsApplication);
}
if(currentSessionContextClass != null) {
((Configuration)config).setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, currentSessionContextClass.getName());
// don't allow Spring's LocaalSessionFactoryBean to override setting
setExposeTransactionAwareSessionFactory(false);
}
return (Configuration)config;
}
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
protected SessionFactory newSessionFactory(Configuration config) throws HibernateException {
try {
return super.newSessionFactory(config);
}
catch (HibernateException e) {
Throwable cause = e.getCause();
if(isCacheConfigurationError(cause)) {
LOG.fatal("There was an error configuring the Hibernate second level cache: " + getCauseMessage(e));
LOG.fatal("This is normally due to one of two reasons. Either you have incorrectly specified the cache provider class name in [DataSource.groovy] or you do not have the cache provider on your classpath (eg. runtime (\"net.sf.ehcache:ehcache:1.6.1\"))");
if(grails.util.Environment.getCurrent() == grails.util.Environment.DEVELOPMENT && !(getGrailsApplication().isWarDeployed()))
System.exit(1);
}
throw e;
}
}
private String getCauseMessage(HibernateException e) {
Throwable cause = e.getCause();
if(cause instanceof InvocationTargetException) {
cause = ((InvocationTargetException)cause).getTargetException();
}
return cause.getMessage();
}
private boolean isCacheConfigurationError(Throwable cause) {
if(cause instanceof InvocationTargetException) {
cause = ((InvocationTargetException)cause).getTargetException();
}
return cause != null && (cause instanceof CacheException);
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void destroy() throws HibernateException {
MetaClassRegistry registry = GroovySystem.getMetaClassRegistry();
Map classMetaData = getSessionFactory().getAllClassMetadata();
for (Object o : classMetaData.values()) {
ClassMetadata classMetadata = (ClassMetadata) o;
Class mappedClass = classMetadata.getMappedClass(EntityMode.POJO);
registry.removeMetaClass(mappedClass);
}
super.destroy();
}
}
| false | true | protected Configuration newConfiguration() {
if(configClass == null) {
try {
configClass = this.classLoader.loadClass("org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration");
}
catch (Throwable e) {
// probably not Java 5 or missing some annotation jars, use default
configClass = DefaultGrailsDomainConfiguration.class;
}
}
Object config = BeanUtils.instantiateClass(configClass);
if(config instanceof GrailsDomainConfiguration) {
GrailsDomainConfiguration grailsConfig = (GrailsDomainConfiguration) config;
grailsConfig.setGrailsApplication(grailsApplication);
}
if(currentSessionContextClass != null) {
((Configuration)config).setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, currentSessionContextClass.getName());
// don't allow Spring's LocaalSessionFactoryBean to override setting
setExposeTransactionAwareSessionFactory(false);
}
return (Configuration)config;
}
| protected Configuration newConfiguration() {
ClassLoader cl = this.classLoader != null ? this.classLoader : Thread.currentThread().getContextClassLoader();
if(configClass == null) {
try {
configClass = cl.loadClass("org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration");
}
catch (Throwable e) {
// probably not Java 5 or missing some annotation jars, use default
configClass = DefaultGrailsDomainConfiguration.class;
}
}
Object config = BeanUtils.instantiateClass(configClass);
if(config instanceof GrailsDomainConfiguration) {
GrailsDomainConfiguration grailsConfig = (GrailsDomainConfiguration) config;
grailsConfig.setGrailsApplication(grailsApplication);
}
if(currentSessionContextClass != null) {
((Configuration)config).setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, currentSessionContextClass.getName());
// don't allow Spring's LocaalSessionFactoryBean to override setting
setExposeTransactionAwareSessionFactory(false);
}
return (Configuration)config;
}
|
diff --git a/src/com/bignerdranch/android/geoquiz/QuizActivity.java b/src/com/bignerdranch/android/geoquiz/QuizActivity.java
index 07bcb9d..75e19e3 100644
--- a/src/com/bignerdranch/android/geoquiz/QuizActivity.java
+++ b/src/com/bignerdranch/android/geoquiz/QuizActivity.java
@@ -1,176 +1,178 @@
package com.bignerdranch.android.geoquiz;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class QuizActivity extends Activity {
private static final String TAG = "QuizActivity";
private static final String KEY_INDEX = "index";
private Button mTrueButton;
private Button mFalseButton;
private Button mNextButton;
private Button mPrevButton;
private Button mCheatButton;
private TextView mQuestionTextView;
private TrueFalse[] mQuestionBank = new TrueFalse[] {
new TrueFalse(R.string.question_oceans, true),
new TrueFalse(R.string.question_mideast, false),
new TrueFalse(R.string.question_africa, false),
new TrueFalse(R.string.question_americas, true),
new TrueFalse(R.string.question_asia, true),
};
private int mCurrentIndex = 0;
private static boolean mIsCheater;
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getQuestion();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
int messageResId = 0;
if (mIsCheater){
messageResId = R.string.judgment_toast;
}
else {
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
}
else {
messageResId = R.string.incorrect_toast;
}
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (data == null) {
return;
}
mIsCheater = data.getBooleanExtra(CheatActivity.EXTRA_ANSWER_SHOWN, false);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
mQuestionTextView = (TextView)findViewById(R.id.question_text_view);
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button)findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkAnswer(false);
}
});
mPrevButton = (Button)findViewById(R.id.prev_button);
mPrevButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
+ //Modulus trick to continuously loop forward through array
mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
mIsCheater = false;
updateQuestion();
}
});
mNextButton = (Button)findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
- mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
+ //Modulus trick to continuously loop backward through array
+ mCurrentIndex = (((mCurrentIndex + 1) % mQuestionBank.length) + mQuestionBank.length) % mQuestionBank.length;
mIsCheater = false;
updateQuestion();
}
});
mCheatButton = (Button)findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(QuizActivity.this, CheatActivity.class);
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
i.putExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, answerIsTrue);
startActivityForResult(i, 0);
}
});
if (savedInstanceState != null){
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
}
updateQuestion();
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.i(TAG, "onSaveInstanceState() called");
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
}
@Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
@Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
@Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop() called");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() called");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quiz, menu);
return true;
}
}
| false | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
mQuestionTextView = (TextView)findViewById(R.id.question_text_view);
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button)findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkAnswer(false);
}
});
mPrevButton = (Button)findViewById(R.id.prev_button);
mPrevButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
mIsCheater = false;
updateQuestion();
}
});
mNextButton = (Button)findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
mIsCheater = false;
updateQuestion();
}
});
mCheatButton = (Button)findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(QuizActivity.this, CheatActivity.class);
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
i.putExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, answerIsTrue);
startActivityForResult(i, 0);
}
});
if (savedInstanceState != null){
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
}
updateQuestion();
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
mQuestionTextView = (TextView)findViewById(R.id.question_text_view);
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button)findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkAnswer(false);
}
});
mPrevButton = (Button)findViewById(R.id.prev_button);
mPrevButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Modulus trick to continuously loop forward through array
mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
mIsCheater = false;
updateQuestion();
}
});
mNextButton = (Button)findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Modulus trick to continuously loop backward through array
mCurrentIndex = (((mCurrentIndex + 1) % mQuestionBank.length) + mQuestionBank.length) % mQuestionBank.length;
mIsCheater = false;
updateQuestion();
}
});
mCheatButton = (Button)findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(QuizActivity.this, CheatActivity.class);
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
i.putExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, answerIsTrue);
startActivityForResult(i, 0);
}
});
if (savedInstanceState != null){
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
}
updateQuestion();
}
|
diff --git a/src/AboutPanel.java b/src/AboutPanel.java
index cc3fe81..95603b1 100755
--- a/src/AboutPanel.java
+++ b/src/AboutPanel.java
@@ -1,241 +1,241 @@
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
public class AboutPanel extends JPanel {
private static final long serialVersionUID = 766490351950584347L;
ListenerHandler listener;
GridBagConstraints c = new GridBagConstraints();
Font textfont = new Font("Courier New", 1, 15);
Color yellowColor = new Color(0, 205, 106);
Font mono = new Font(Font.MONOSPACED,
Font.PLAIN, 12);
JLabel enlLogo, aboutUs, version, versionnumber,
weblink1, weblink2, weblink3, weblink4, weblink, contact,
contact_mail, contact_g_M0P, contact_g_Xeno;
JTextArea aboutUsText;
Cursor hand = new Cursor(Cursor.HAND_CURSOR);
public AboutPanel(ListenerHandler listenerHandler) {
super(new GridBagLayout());
this.listener = listenerHandler;
//
this.enlLogo = new JLabel(makeImageIcon("/images/enlightened_big.png"));
this.aboutUs = new JLabel("About us");
this.version = new JLabel("Version");
- this.versionnumber = new JLabel("0.8.17");
+ this.versionnumber = new JLabel("0.1.00");
this.weblink = new JLabel("Weblinks");
this.weblink1 = new JLabel("Our Website");
this.weblink2 = new JLabel("G+ Decode Community");
this.weblink3 = new JLabel("Niantic Investigation");
this.weblink4 = new JLabel("Intel Map");
this.contact = new JLabel("Contact us");
this.contact_mail = new JLabel("Write a mail");
this.contact_g_M0P = new JLabel("G+ MOP");
this.contact_g_Xeno = new JLabel("G+ Xenowarius");
this.aboutUsText = new JTextArea(
"This tool is developed by Xenowar and MOP.\n"
+ "We implemented several decoding methods which were frequently used by the Ingress team.");
// apply style to elements
this.aboutUs.setFont(this.textfont);
this.aboutUsText.setFont(this.textfont);
this.version.setFont(this.textfont);
this.versionnumber.setFont(this.textfont);
this.weblink.setFont(this.textfont);
this.weblink1.setFont(this.textfont);
this.weblink2.setFont(this.textfont);
this.weblink3.setFont(this.textfont);
this.weblink4.setFont(this.textfont);
this.contact.setFont(this.textfont);
this.contact_mail.setFont(this.textfont);
this.contact_g_M0P.setFont(this.textfont);
this.contact_g_Xeno.setFont(this.textfont);
this.aboutUs.setBackground(Color.black);
this.aboutUsText.setBackground(Color.black);
this.version.setBackground(Color.black);
this.versionnumber.setBackground(Color.black);
this.weblink.setBackground(Color.black);
this.weblink1.setBackground(Color.black);
this.weblink2.setBackground(Color.black);
this.weblink3.setBackground(Color.black);
this.weblink4.setBackground(Color.black);
this.contact.setBackground(Color.black);
this.contact_mail.setBackground(Color.black);
this.contact_g_M0P.setBackground(Color.black);
this.contact_g_Xeno.setBackground(Color.black);
this.aboutUs.setForeground(this.yellowColor);
this.aboutUsText.setForeground(this.yellowColor);
this.version.setForeground(this.yellowColor);
this.versionnumber.setForeground(this.yellowColor);
this.weblink.setForeground(this.yellowColor);
this.weblink1.setForeground(this.yellowColor);
this.weblink2.setForeground(this.yellowColor);
this.weblink3.setForeground(this.yellowColor);
this.weblink4.setForeground(this.yellowColor);
this.contact.setForeground(this.yellowColor);
this.contact_mail.setForeground(this.yellowColor);
this.contact_g_M0P.setForeground(this.yellowColor);
this.contact_g_Xeno.setForeground(this.yellowColor);
this.aboutUsText.setEditable(false);
this.aboutUsText.setBorder(new EmptyBorder(0, 0, 0, 0));
this.aboutUsText.setLineWrap(true);
this.aboutUsText.setWrapStyleWord(true);
// setting custom cursor
this.weblink1.setCursor(this.hand);
this.weblink2.setCursor(this.hand);
this.weblink3.setCursor(this.hand);
this.weblink4.setCursor(this.hand);
this.contact_mail.setCursor(this.hand);
this.contact_g_M0P.setCursor(this.hand);
this.contact_g_Xeno.setCursor(this.hand);
// adding listener for weblinks
this.weblink1.setName("link1");
this.weblink1.addMouseListener(this.listener);
this.weblink2.setName("link2");
this.weblink2.addMouseListener(this.listener);
this.weblink3.setName("link3");
this.weblink3.addMouseListener(this.listener);
this.weblink4.setName("link4");
this.weblink4.addMouseListener(this.listener);
this.contact_mail.setName("mail");
this.contact_mail.addMouseListener(this.listener);
this.contact_g_M0P.setName("MOP");
this.contact_g_M0P.addMouseListener(this.listener);
this.contact_g_Xeno.setName("Xeno");
this.contact_g_Xeno.addMouseListener(this.listener);
this.contact.setName("Ee");
this.contact.addMouseListener(this.listener);
// adding components to panel
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.1;
this.c.gridx = 2;
this.c.gridy = 0;
this.c.gridwidth = 2;
this.c.insets = new Insets(0, 0, 0, 0);
add(this.aboutUs, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 1;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.aboutUsText, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.1;
this.c.gridx = 2;
this.c.gridy = 2;
this.c.gridwidth = 2;
this.c.insets = new Insets(0, 0, 0, 0);
add(this.version, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 3;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.versionnumber, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.1;
this.c.gridx = 2;
this.c.gridy = 4;
this.c.gridwidth = 2;
this.c.insets = new Insets(0, 0, 0, 0);
add(this.weblink, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 5;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.weblink1, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 6;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.weblink2, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 7;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.weblink3, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 8;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.weblink4, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 9;
this.c.insets = new Insets(0, 0, 0, 0);
add(this.contact, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 10;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.contact_mail, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 11;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.contact_g_M0P, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 12;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.contact_g_Xeno, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.1;
this.c.gridx = 0;
this.c.gridy = 0;
this.c.anchor = GridBagConstraints.WEST;
this.c.gridheight = 20;
this.c.insets = new Insets(0, 0, 0, 0);
add(this.enlLogo, this.c);
setBackground(Color.black);
}
public ImageIcon makeImageIcon(String relative_path) {
URL imgURL = getClass().getResource(relative_path);
return new ImageIcon(imgURL);
}
}
| true | true | public AboutPanel(ListenerHandler listenerHandler) {
super(new GridBagLayout());
this.listener = listenerHandler;
//
this.enlLogo = new JLabel(makeImageIcon("/images/enlightened_big.png"));
this.aboutUs = new JLabel("About us");
this.version = new JLabel("Version");
this.versionnumber = new JLabel("0.8.17");
this.weblink = new JLabel("Weblinks");
this.weblink1 = new JLabel("Our Website");
this.weblink2 = new JLabel("G+ Decode Community");
this.weblink3 = new JLabel("Niantic Investigation");
this.weblink4 = new JLabel("Intel Map");
this.contact = new JLabel("Contact us");
this.contact_mail = new JLabel("Write a mail");
this.contact_g_M0P = new JLabel("G+ MOP");
this.contact_g_Xeno = new JLabel("G+ Xenowarius");
this.aboutUsText = new JTextArea(
"This tool is developed by Xenowar and MOP.\n"
+ "We implemented several decoding methods which were frequently used by the Ingress team.");
// apply style to elements
this.aboutUs.setFont(this.textfont);
this.aboutUsText.setFont(this.textfont);
this.version.setFont(this.textfont);
this.versionnumber.setFont(this.textfont);
this.weblink.setFont(this.textfont);
this.weblink1.setFont(this.textfont);
this.weblink2.setFont(this.textfont);
this.weblink3.setFont(this.textfont);
this.weblink4.setFont(this.textfont);
this.contact.setFont(this.textfont);
this.contact_mail.setFont(this.textfont);
this.contact_g_M0P.setFont(this.textfont);
this.contact_g_Xeno.setFont(this.textfont);
this.aboutUs.setBackground(Color.black);
this.aboutUsText.setBackground(Color.black);
this.version.setBackground(Color.black);
this.versionnumber.setBackground(Color.black);
this.weblink.setBackground(Color.black);
this.weblink1.setBackground(Color.black);
this.weblink2.setBackground(Color.black);
this.weblink3.setBackground(Color.black);
this.weblink4.setBackground(Color.black);
this.contact.setBackground(Color.black);
this.contact_mail.setBackground(Color.black);
this.contact_g_M0P.setBackground(Color.black);
this.contact_g_Xeno.setBackground(Color.black);
this.aboutUs.setForeground(this.yellowColor);
this.aboutUsText.setForeground(this.yellowColor);
this.version.setForeground(this.yellowColor);
this.versionnumber.setForeground(this.yellowColor);
this.weblink.setForeground(this.yellowColor);
this.weblink1.setForeground(this.yellowColor);
this.weblink2.setForeground(this.yellowColor);
this.weblink3.setForeground(this.yellowColor);
this.weblink4.setForeground(this.yellowColor);
this.contact.setForeground(this.yellowColor);
this.contact_mail.setForeground(this.yellowColor);
this.contact_g_M0P.setForeground(this.yellowColor);
this.contact_g_Xeno.setForeground(this.yellowColor);
this.aboutUsText.setEditable(false);
this.aboutUsText.setBorder(new EmptyBorder(0, 0, 0, 0));
this.aboutUsText.setLineWrap(true);
this.aboutUsText.setWrapStyleWord(true);
// setting custom cursor
this.weblink1.setCursor(this.hand);
this.weblink2.setCursor(this.hand);
this.weblink3.setCursor(this.hand);
this.weblink4.setCursor(this.hand);
this.contact_mail.setCursor(this.hand);
this.contact_g_M0P.setCursor(this.hand);
this.contact_g_Xeno.setCursor(this.hand);
// adding listener for weblinks
this.weblink1.setName("link1");
this.weblink1.addMouseListener(this.listener);
this.weblink2.setName("link2");
this.weblink2.addMouseListener(this.listener);
this.weblink3.setName("link3");
this.weblink3.addMouseListener(this.listener);
this.weblink4.setName("link4");
this.weblink4.addMouseListener(this.listener);
this.contact_mail.setName("mail");
this.contact_mail.addMouseListener(this.listener);
this.contact_g_M0P.setName("MOP");
this.contact_g_M0P.addMouseListener(this.listener);
this.contact_g_Xeno.setName("Xeno");
this.contact_g_Xeno.addMouseListener(this.listener);
this.contact.setName("Ee");
this.contact.addMouseListener(this.listener);
// adding components to panel
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.1;
this.c.gridx = 2;
this.c.gridy = 0;
this.c.gridwidth = 2;
this.c.insets = new Insets(0, 0, 0, 0);
add(this.aboutUs, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 1;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.aboutUsText, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.1;
this.c.gridx = 2;
this.c.gridy = 2;
this.c.gridwidth = 2;
this.c.insets = new Insets(0, 0, 0, 0);
add(this.version, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 3;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.versionnumber, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.1;
this.c.gridx = 2;
this.c.gridy = 4;
this.c.gridwidth = 2;
this.c.insets = new Insets(0, 0, 0, 0);
add(this.weblink, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 5;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.weblink1, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 6;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.weblink2, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 7;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.weblink3, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 8;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.weblink4, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 9;
this.c.insets = new Insets(0, 0, 0, 0);
add(this.contact, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 10;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.contact_mail, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 11;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.contact_g_M0P, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 12;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.contact_g_Xeno, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.1;
this.c.gridx = 0;
this.c.gridy = 0;
this.c.anchor = GridBagConstraints.WEST;
this.c.gridheight = 20;
this.c.insets = new Insets(0, 0, 0, 0);
add(this.enlLogo, this.c);
setBackground(Color.black);
}
| public AboutPanel(ListenerHandler listenerHandler) {
super(new GridBagLayout());
this.listener = listenerHandler;
//
this.enlLogo = new JLabel(makeImageIcon("/images/enlightened_big.png"));
this.aboutUs = new JLabel("About us");
this.version = new JLabel("Version");
this.versionnumber = new JLabel("0.1.00");
this.weblink = new JLabel("Weblinks");
this.weblink1 = new JLabel("Our Website");
this.weblink2 = new JLabel("G+ Decode Community");
this.weblink3 = new JLabel("Niantic Investigation");
this.weblink4 = new JLabel("Intel Map");
this.contact = new JLabel("Contact us");
this.contact_mail = new JLabel("Write a mail");
this.contact_g_M0P = new JLabel("G+ MOP");
this.contact_g_Xeno = new JLabel("G+ Xenowarius");
this.aboutUsText = new JTextArea(
"This tool is developed by Xenowar and MOP.\n"
+ "We implemented several decoding methods which were frequently used by the Ingress team.");
// apply style to elements
this.aboutUs.setFont(this.textfont);
this.aboutUsText.setFont(this.textfont);
this.version.setFont(this.textfont);
this.versionnumber.setFont(this.textfont);
this.weblink.setFont(this.textfont);
this.weblink1.setFont(this.textfont);
this.weblink2.setFont(this.textfont);
this.weblink3.setFont(this.textfont);
this.weblink4.setFont(this.textfont);
this.contact.setFont(this.textfont);
this.contact_mail.setFont(this.textfont);
this.contact_g_M0P.setFont(this.textfont);
this.contact_g_Xeno.setFont(this.textfont);
this.aboutUs.setBackground(Color.black);
this.aboutUsText.setBackground(Color.black);
this.version.setBackground(Color.black);
this.versionnumber.setBackground(Color.black);
this.weblink.setBackground(Color.black);
this.weblink1.setBackground(Color.black);
this.weblink2.setBackground(Color.black);
this.weblink3.setBackground(Color.black);
this.weblink4.setBackground(Color.black);
this.contact.setBackground(Color.black);
this.contact_mail.setBackground(Color.black);
this.contact_g_M0P.setBackground(Color.black);
this.contact_g_Xeno.setBackground(Color.black);
this.aboutUs.setForeground(this.yellowColor);
this.aboutUsText.setForeground(this.yellowColor);
this.version.setForeground(this.yellowColor);
this.versionnumber.setForeground(this.yellowColor);
this.weblink.setForeground(this.yellowColor);
this.weblink1.setForeground(this.yellowColor);
this.weblink2.setForeground(this.yellowColor);
this.weblink3.setForeground(this.yellowColor);
this.weblink4.setForeground(this.yellowColor);
this.contact.setForeground(this.yellowColor);
this.contact_mail.setForeground(this.yellowColor);
this.contact_g_M0P.setForeground(this.yellowColor);
this.contact_g_Xeno.setForeground(this.yellowColor);
this.aboutUsText.setEditable(false);
this.aboutUsText.setBorder(new EmptyBorder(0, 0, 0, 0));
this.aboutUsText.setLineWrap(true);
this.aboutUsText.setWrapStyleWord(true);
// setting custom cursor
this.weblink1.setCursor(this.hand);
this.weblink2.setCursor(this.hand);
this.weblink3.setCursor(this.hand);
this.weblink4.setCursor(this.hand);
this.contact_mail.setCursor(this.hand);
this.contact_g_M0P.setCursor(this.hand);
this.contact_g_Xeno.setCursor(this.hand);
// adding listener for weblinks
this.weblink1.setName("link1");
this.weblink1.addMouseListener(this.listener);
this.weblink2.setName("link2");
this.weblink2.addMouseListener(this.listener);
this.weblink3.setName("link3");
this.weblink3.addMouseListener(this.listener);
this.weblink4.setName("link4");
this.weblink4.addMouseListener(this.listener);
this.contact_mail.setName("mail");
this.contact_mail.addMouseListener(this.listener);
this.contact_g_M0P.setName("MOP");
this.contact_g_M0P.addMouseListener(this.listener);
this.contact_g_Xeno.setName("Xeno");
this.contact_g_Xeno.addMouseListener(this.listener);
this.contact.setName("Ee");
this.contact.addMouseListener(this.listener);
// adding components to panel
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.1;
this.c.gridx = 2;
this.c.gridy = 0;
this.c.gridwidth = 2;
this.c.insets = new Insets(0, 0, 0, 0);
add(this.aboutUs, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 1;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.aboutUsText, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.1;
this.c.gridx = 2;
this.c.gridy = 2;
this.c.gridwidth = 2;
this.c.insets = new Insets(0, 0, 0, 0);
add(this.version, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 3;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.versionnumber, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.1;
this.c.gridx = 2;
this.c.gridy = 4;
this.c.gridwidth = 2;
this.c.insets = new Insets(0, 0, 0, 0);
add(this.weblink, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 5;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.weblink1, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 6;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.weblink2, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 7;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.weblink3, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 8;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.weblink4, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 9;
this.c.insets = new Insets(0, 0, 0, 0);
add(this.contact, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 10;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.contact_mail, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 11;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.contact_g_M0P, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.8;
this.c.gridx = 3;
this.c.gridy = 12;
this.c.insets = new Insets(0, 30, 0, 0);
add(this.contact_g_Xeno, this.c);
this.c.fill = GridBagConstraints.BOTH;
this.c.weightx = 0.1;
this.c.gridx = 0;
this.c.gridy = 0;
this.c.anchor = GridBagConstraints.WEST;
this.c.gridheight = 20;
this.c.insets = new Insets(0, 0, 0, 0);
add(this.enlLogo, this.c);
setBackground(Color.black);
}
|
diff --git a/client/net/minecraftforge/client/ForgeHooksClient.java b/client/net/minecraftforge/client/ForgeHooksClient.java
index 412e1acdb..b47ae3b4f 100644
--- a/client/net/minecraftforge/client/ForgeHooksClient.java
+++ b/client/net/minecraftforge/client/ForgeHooksClient.java
@@ -1,308 +1,308 @@
package net.minecraftforge.client;
import java.util.HashMap;
import java.util.Random;
import java.util.TreeSet;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
import org.lwjgl.opengl.PixelFormat;
import cpw.mods.fml.client.FMLClientHandler;
import net.minecraft.client.Minecraft;
import net.minecraft.block.Block;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.client.texturepacks.ITexturePack;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.RenderEngine;
import net.minecraft.client.renderer.RenderGlobal;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraftforge.client.IItemRenderer.ItemRenderType;
import net.minecraftforge.client.event.DrawBlockHighlightEvent;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.client.event.TextureLoadEvent;
import net.minecraftforge.client.event.TextureStitchEvent;
import net.minecraftforge.common.IArmorTextureProvider;
import net.minecraftforge.common.MinecraftForge;
import static net.minecraftforge.client.IItemRenderer.ItemRenderType.*;
import static net.minecraftforge.client.IItemRenderer.ItemRendererHelper.*;
public class ForgeHooksClient
{
static RenderEngine engine()
{
return FMLClientHandler.instance().getClient().renderEngine;
}
@Deprecated //Deprecated in 1.5.1, move to the more detailed one below.
@SuppressWarnings("deprecation")
public static String getArmorTexture(ItemStack armor, String _default)
{
String result = null;
if (armor.getItem() instanceof IArmorTextureProvider)
{
result = ((IArmorTextureProvider)armor.getItem()).getArmorTextureFile(armor);
}
return result != null ? result : _default;
}
public static String getArmorTexture(Entity entity, ItemStack armor, String _default, int slot, int layer)
{
String result = armor.getItem().getArmorTexture(armor, entity, slot, layer);
return result != null ? result : _default;
}
public static boolean renderEntityItem(EntityItem entity, ItemStack item, float bobing, float rotation, Random random, RenderEngine engine, RenderBlocks renderBlocks)
{
IItemRenderer customRenderer = MinecraftForgeClient.getItemRenderer(item, ENTITY);
if (customRenderer == null)
{
return false;
}
if (customRenderer.shouldUseRenderHelper(ENTITY, item, ENTITY_ROTATION))
{
GL11.glRotatef(rotation, 0.0F, 1.0F, 0.0F);
}
if (!customRenderer.shouldUseRenderHelper(ENTITY, item, ENTITY_BOBBING))
{
GL11.glTranslatef(0.0F, -bobing, 0.0F);
}
boolean is3D = customRenderer.shouldUseRenderHelper(ENTITY, item, BLOCK_3D);
engine.bindTexture(item.getItemSpriteNumber() == 0 ? "/terrain.png" : "/gui/items.png");
Block block = (item.itemID < Block.blocksList.length ? Block.blocksList[item.itemID] : null);
if (is3D || (block != null && RenderBlocks.renderItemIn3d(block.getRenderType())))
{
int renderType = (block != null ? block.getRenderType() : 1);
float scale = (renderType == 1 || renderType == 19 || renderType == 12 || renderType == 2 ? 0.5F : 0.25F);
if (RenderItem.renderInFrame)
{
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);
}
GL11.glScalef(scale, scale, scale);
int size = item.stackSize;
- int count = (size > 20 ? 4 : (size > 5 ? 3 : (size > 1 ? 2 : 1)));
+ int count = (size > 40 ? 5 : (size > 20 ? 4 : (size > 5 ? 3 : (size > 1 ? 2 : 1))));
for(int j = 0; j < count; j++)
{
GL11.glPushMatrix();
if (j > 0)
{
GL11.glTranslatef(
- ((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / 0.5F,
- ((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / 0.5F,
- ((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / 0.5F);
+ ((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / scale,
+ ((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / scale,
+ ((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / scale);
}
customRenderer.renderItem(ENTITY, item, renderBlocks, entity);
GL11.glPopMatrix();
}
}
else
{
GL11.glScalef(0.5F, 0.5F, 0.5F);
customRenderer.renderItem(ENTITY, item, renderBlocks, entity);
}
return true;
}
public static boolean renderInventoryItem(RenderBlocks renderBlocks, RenderEngine engine, ItemStack item, boolean inColor, float zLevel, float x, float y)
{
IItemRenderer customRenderer = MinecraftForgeClient.getItemRenderer(item, INVENTORY);
if (customRenderer == null)
{
return false;
}
engine.bindTexture(item.getItemSpriteNumber() == 0 ? "/terrain.png" : "/gui/items.png");
if (customRenderer.shouldUseRenderHelper(INVENTORY, item, INVENTORY_BLOCK))
{
GL11.glPushMatrix();
GL11.glTranslatef(x - 2, y + 3, -3.0F + zLevel);
GL11.glScalef(10F, 10F, 10F);
GL11.glTranslatef(1.0F, 0.5F, 1.0F);
GL11.glScalef(1.0F, 1.0F, -1F);
GL11.glRotatef(210F, 1.0F, 0.0F, 0.0F);
GL11.glRotatef(45F, 0.0F, 1.0F, 0.0F);
if(inColor)
{
int color = Item.itemsList[item.itemID].getColorFromItemStack(item, 0);
float r = (float)(color >> 16 & 0xff) / 255F;
float g = (float)(color >> 8 & 0xff) / 255F;
float b = (float)(color & 0xff) / 255F;
GL11.glColor4f(r, g, b, 1.0F);
}
GL11.glRotatef(-90F, 0.0F, 1.0F, 0.0F);
renderBlocks.useInventoryTint = inColor;
customRenderer.renderItem(INVENTORY, item, renderBlocks);
renderBlocks.useInventoryTint = true;
GL11.glPopMatrix();
}
else
{
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glPushMatrix();
GL11.glTranslatef(x, y, -3.0F + zLevel);
if (inColor)
{
int color = Item.itemsList[item.itemID].getColorFromItemStack(item, 0);
float r = (float)(color >> 16 & 255) / 255.0F;
float g = (float)(color >> 8 & 255) / 255.0F;
float b = (float)(color & 255) / 255.0F;
GL11.glColor4f(r, g, b, 1.0F);
}
customRenderer.renderItem(INVENTORY, item, renderBlocks);
GL11.glPopMatrix();
GL11.glEnable(GL11.GL_LIGHTING);
}
return true;
}
@Deprecated
public static void renderEquippedItem(IItemRenderer customRenderer, RenderBlocks renderBlocks, EntityLiving entity, ItemStack item)
{
renderEquippedItem(ItemRenderType.EQUIPPED, customRenderer, renderBlocks, entity, item);
}
public static void renderEquippedItem(ItemRenderType type, IItemRenderer customRenderer, RenderBlocks renderBlocks, EntityLiving entity, ItemStack item)
{
if (customRenderer.shouldUseRenderHelper(type, item, EQUIPPED_BLOCK))
{
GL11.glPushMatrix();
GL11.glTranslatef(-0.5F, -0.5F, -0.5F);
customRenderer.renderItem(type, item, renderBlocks, entity);
GL11.glPopMatrix();
}
else
{
GL11.glPushMatrix();
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
GL11.glTranslatef(0.0F, -0.3F, 0.0F);
GL11.glScalef(1.5F, 1.5F, 1.5F);
GL11.glRotatef(50.0F, 0.0F, 1.0F, 0.0F);
GL11.glRotatef(335.0F, 0.0F, 0.0F, 1.0F);
GL11.glTranslatef(-0.9375F, -0.0625F, 0.0F);
customRenderer.renderItem(type, item, renderBlocks, entity);
GL11.glDisable(GL12.GL_RESCALE_NORMAL);
GL11.glPopMatrix();
}
}
//Optifine Helper Functions u.u, these are here specifically for Optifine
//Note: When using Optfine, these methods are invoked using reflection, which
//incurs a major performance penalty.
public static void orientBedCamera(Minecraft mc, EntityLiving entity)
{
int x = MathHelper.floor_double(entity.posX);
int y = MathHelper.floor_double(entity.posY);
int z = MathHelper.floor_double(entity.posZ);
Block block = Block.blocksList[mc.theWorld.getBlockId(x, y, z)];
if (block != null && block.isBed(mc.theWorld, x, y, z, entity))
{
int var12 = block.getBedDirection(mc.theWorld, x, y, z);
GL11.glRotatef((float)(var12 * 90), 0.0F, 1.0F, 0.0F);
}
}
public static boolean onDrawBlockHighlight(RenderGlobal context, EntityPlayer player, MovingObjectPosition target, int subID, ItemStack currentItem, float partialTicks)
{
return MinecraftForge.EVENT_BUS.post(new DrawBlockHighlightEvent(context, player, target, subID, currentItem, partialTicks));
}
public static void dispatchRenderLast(RenderGlobal context, float partialTicks)
{
MinecraftForge.EVENT_BUS.post(new RenderWorldLastEvent(context, partialTicks));
}
public static void onTextureLoad(String texture, ITexturePack pack)
{
MinecraftForge.EVENT_BUS.post(new TextureLoadEvent(texture, pack));
}
public static void onTextureStitchedPre(TextureMap map)
{
MinecraftForge.EVENT_BUS.post(new TextureStitchEvent.Pre(map));
}
public static void onTextureStitchedPost(TextureMap map)
{
MinecraftForge.EVENT_BUS.post(new TextureStitchEvent.Post(map));
}
/**
* This is added for Optifine's convenience. And to explode if a ModMaker is developing.
* @param texture
*/
public static void onTextureLoadPre(String texture)
{
if (Tessellator.renderingWorldRenderer)
{
String msg = String.format("Warning: Texture %s not preloaded, will cause render glitches!", texture);
System.out.println(msg);
if (Tessellator.class.getPackage() != null)
{
if (Tessellator.class.getPackage().getName().startsWith("net.minecraft."))
{
Minecraft mc = FMLClientHandler.instance().getClient();
if (mc.ingameGUI != null)
{
mc.ingameGUI.getChatGUI().printChatMessage(msg);
}
}
}
}
}
static int renderPass = -1;
public static void setRenderPass(int pass)
{
renderPass = pass;
}
public static ModelBiped getArmorModel(EntityLiving entityLiving, ItemStack itemStack, int slotID, ModelBiped _default)
{
ModelBiped modelbiped = itemStack.getItem().getArmorModel(entityLiving, itemStack, slotID);
return modelbiped == null ? _default : modelbiped;
}
static int stencilBits = 0;
public static void createDisplay() throws LWJGLException
{
PixelFormat format = new PixelFormat().withDepthBits(24);
try
{
//TODO: Figure out how to determine the max bits.
Display.create(format.withStencilBits(8));
stencilBits = 8;
}
catch(LWJGLException e)
{
Display.create(format);
stencilBits = 0;
}
}
}
| false | true | public static boolean renderEntityItem(EntityItem entity, ItemStack item, float bobing, float rotation, Random random, RenderEngine engine, RenderBlocks renderBlocks)
{
IItemRenderer customRenderer = MinecraftForgeClient.getItemRenderer(item, ENTITY);
if (customRenderer == null)
{
return false;
}
if (customRenderer.shouldUseRenderHelper(ENTITY, item, ENTITY_ROTATION))
{
GL11.glRotatef(rotation, 0.0F, 1.0F, 0.0F);
}
if (!customRenderer.shouldUseRenderHelper(ENTITY, item, ENTITY_BOBBING))
{
GL11.glTranslatef(0.0F, -bobing, 0.0F);
}
boolean is3D = customRenderer.shouldUseRenderHelper(ENTITY, item, BLOCK_3D);
engine.bindTexture(item.getItemSpriteNumber() == 0 ? "/terrain.png" : "/gui/items.png");
Block block = (item.itemID < Block.blocksList.length ? Block.blocksList[item.itemID] : null);
if (is3D || (block != null && RenderBlocks.renderItemIn3d(block.getRenderType())))
{
int renderType = (block != null ? block.getRenderType() : 1);
float scale = (renderType == 1 || renderType == 19 || renderType == 12 || renderType == 2 ? 0.5F : 0.25F);
if (RenderItem.renderInFrame)
{
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);
}
GL11.glScalef(scale, scale, scale);
int size = item.stackSize;
int count = (size > 20 ? 4 : (size > 5 ? 3 : (size > 1 ? 2 : 1)));
for(int j = 0; j < count; j++)
{
GL11.glPushMatrix();
if (j > 0)
{
GL11.glTranslatef(
((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / 0.5F,
((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / 0.5F,
((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / 0.5F);
}
customRenderer.renderItem(ENTITY, item, renderBlocks, entity);
GL11.glPopMatrix();
}
}
else
{
GL11.glScalef(0.5F, 0.5F, 0.5F);
customRenderer.renderItem(ENTITY, item, renderBlocks, entity);
}
return true;
}
| public static boolean renderEntityItem(EntityItem entity, ItemStack item, float bobing, float rotation, Random random, RenderEngine engine, RenderBlocks renderBlocks)
{
IItemRenderer customRenderer = MinecraftForgeClient.getItemRenderer(item, ENTITY);
if (customRenderer == null)
{
return false;
}
if (customRenderer.shouldUseRenderHelper(ENTITY, item, ENTITY_ROTATION))
{
GL11.glRotatef(rotation, 0.0F, 1.0F, 0.0F);
}
if (!customRenderer.shouldUseRenderHelper(ENTITY, item, ENTITY_BOBBING))
{
GL11.glTranslatef(0.0F, -bobing, 0.0F);
}
boolean is3D = customRenderer.shouldUseRenderHelper(ENTITY, item, BLOCK_3D);
engine.bindTexture(item.getItemSpriteNumber() == 0 ? "/terrain.png" : "/gui/items.png");
Block block = (item.itemID < Block.blocksList.length ? Block.blocksList[item.itemID] : null);
if (is3D || (block != null && RenderBlocks.renderItemIn3d(block.getRenderType())))
{
int renderType = (block != null ? block.getRenderType() : 1);
float scale = (renderType == 1 || renderType == 19 || renderType == 12 || renderType == 2 ? 0.5F : 0.25F);
if (RenderItem.renderInFrame)
{
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);
}
GL11.glScalef(scale, scale, scale);
int size = item.stackSize;
int count = (size > 40 ? 5 : (size > 20 ? 4 : (size > 5 ? 3 : (size > 1 ? 2 : 1))));
for(int j = 0; j < count; j++)
{
GL11.glPushMatrix();
if (j > 0)
{
GL11.glTranslatef(
((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / scale,
((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / scale,
((random.nextFloat() * 2.0F - 1.0F) * 0.2F) / scale);
}
customRenderer.renderItem(ENTITY, item, renderBlocks, entity);
GL11.glPopMatrix();
}
}
else
{
GL11.glScalef(0.5F, 0.5F, 0.5F);
customRenderer.renderItem(ENTITY, item, renderBlocks, entity);
}
return true;
}
|
diff --git a/src/dailymotion/cz/vity/freerapid/plugins/services/dailymotion/DailymotionRunner.java b/src/dailymotion/cz/vity/freerapid/plugins/services/dailymotion/DailymotionRunner.java
index 9bb86662..8e678406 100644
--- a/src/dailymotion/cz/vity/freerapid/plugins/services/dailymotion/DailymotionRunner.java
+++ b/src/dailymotion/cz/vity/freerapid/plugins/services/dailymotion/DailymotionRunner.java
@@ -1,91 +1,91 @@
package cz.vity.freerapid.plugins.services.dailymotion;
import cz.vity.freerapid.plugins.exceptions.ErrorDuringDownloadingException;
import cz.vity.freerapid.plugins.exceptions.PluginImplementationException;
import cz.vity.freerapid.plugins.exceptions.ServiceConnectionProblemException;
import cz.vity.freerapid.plugins.exceptions.URLNotAvailableAnymoreException;
import cz.vity.freerapid.plugins.webclient.AbstractRunner;
import cz.vity.freerapid.plugins.webclient.FileState;
import cz.vity.freerapid.plugins.webclient.utils.PlugUtils;
import cz.vity.freerapid.utilities.LogUtils;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpMethod;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.logging.Logger;
import java.util.regex.Matcher;
/**
* Class which contains main code
*
* @author Ramsestom, JPEXS, ntoskrnl
*/
class DailymotionRunner extends AbstractRunner {
private final static Logger logger = Logger.getLogger(DailymotionRunner.class.getName());
@Override
public void runCheck() throws Exception {
super.runCheck();
addCookie(new Cookie(".dailymotion.com", "family_filter", "off", "/", 86400, false));
final HttpMethod method = getGetMethod(fileURL);
if (makeRedirectedRequest(method)) {
checkProblems();
checkName();
} else {
checkProblems();
throw new ServiceConnectionProblemException();
}
}
private void checkName() throws ErrorDuringDownloadingException {
final Matcher matcher;
if (getContentAsString().contains("<h1 class=\"title\"")) {
matcher = getMatcherAgainstContent("<h1 class=\"title\"[^<>]*?>(.+?)</h1>");
} else {
matcher = getMatcherAgainstContent("<span class=\"title\"[^<>]*?>(.+?)</span>");
}
if (!matcher.find()) throw new PluginImplementationException("File name not found");
httpFile.setFileName(PlugUtils.unescapeHtml(matcher.group(1)) + ".mp4");
httpFile.setFileState(FileState.CHECKED_AND_EXISTING);
}
@Override
public void run() throws Exception {
super.run();
logger.info("Starting download in TASK " + fileURL);
addCookie(new Cookie(".dailymotion.com", "family_filter", "off", "/", 86400, false));
HttpMethod method = getGetMethod(fileURL);
if (makeRedirectedRequest(method)) {
checkProblems();
checkName();
- final String sequence = PlugUtils.getStringBetween(getContentAsString(), ".addVariable(\"sequence\", \"", "\"");
+ final String sequence = PlugUtils.getStringBetween(getContentAsString(), "\"sequence\":\"", "\"");
final String url = PlugUtils.getStringBetween(sequence, "%22sdURL%22%3A%22", "%22");
method = getGetMethod(urlDecode(url).replace("\\", ""));
if (!tryDownloadAndSaveFile(method)) {
checkProblems();
throw new ServiceConnectionProblemException("Error starting download");
}
} else {
checkProblems();
throw new ServiceConnectionProblemException();
}
}
private void checkProblems() throws ErrorDuringDownloadingException {
final String contentAsString = getContentAsString();
if (contentAsString.contains("We can't find the page you're looking for") || contentAsString.contains("video has been removed") || contentAsString.contains("Page Gone")) {
throw new URLNotAvailableAnymoreException("File not found");
}
}
private static String urlDecode(final String url) {
try {
return url == null ? "" : URLDecoder.decode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
LogUtils.processException(logger, e);
return "";
}
}
}
| true | true | public void run() throws Exception {
super.run();
logger.info("Starting download in TASK " + fileURL);
addCookie(new Cookie(".dailymotion.com", "family_filter", "off", "/", 86400, false));
HttpMethod method = getGetMethod(fileURL);
if (makeRedirectedRequest(method)) {
checkProblems();
checkName();
final String sequence = PlugUtils.getStringBetween(getContentAsString(), ".addVariable(\"sequence\", \"", "\"");
final String url = PlugUtils.getStringBetween(sequence, "%22sdURL%22%3A%22", "%22");
method = getGetMethod(urlDecode(url).replace("\\", ""));
if (!tryDownloadAndSaveFile(method)) {
checkProblems();
throw new ServiceConnectionProblemException("Error starting download");
}
} else {
checkProblems();
throw new ServiceConnectionProblemException();
}
}
| public void run() throws Exception {
super.run();
logger.info("Starting download in TASK " + fileURL);
addCookie(new Cookie(".dailymotion.com", "family_filter", "off", "/", 86400, false));
HttpMethod method = getGetMethod(fileURL);
if (makeRedirectedRequest(method)) {
checkProblems();
checkName();
final String sequence = PlugUtils.getStringBetween(getContentAsString(), "\"sequence\":\"", "\"");
final String url = PlugUtils.getStringBetween(sequence, "%22sdURL%22%3A%22", "%22");
method = getGetMethod(urlDecode(url).replace("\\", ""));
if (!tryDownloadAndSaveFile(method)) {
checkProblems();
throw new ServiceConnectionProblemException("Error starting download");
}
} else {
checkProblems();
throw new ServiceConnectionProblemException();
}
}
|
diff --git a/src/main/java/org/dita/dost/writer/KeyrefPaser.java b/src/main/java/org/dita/dost/writer/KeyrefPaser.java
index ec23e74ab..1e6314119 100644
--- a/src/main/java/org/dita/dost/writer/KeyrefPaser.java
+++ b/src/main/java/org/dita/dost/writer/KeyrefPaser.java
@@ -1,661 +1,661 @@
/*
* This file is part of the DITA Open Toolkit project.
* See the accompanying license.txt file for applicable licenses.
*/
/*
* (c) Copyright IBM Corp. 2010 All Rights Reserved.
*/
package org.dita.dost.writer;
import static javax.xml.XMLConstants.NULL_NS_URI;
import static org.dita.dost.util.Constants.*;
import static org.dita.dost.util.URLUtils.*;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import org.dita.dost.exception.DITAOTException;
import org.dita.dost.log.MessageUtils;
import org.dita.dost.util.DitaClass;
import org.dita.dost.util.MergeUtils;
import org.dita.dost.util.StringUtils;
import org.dita.dost.util.URLUtils;
import org.dita.dost.util.XMLUtils;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
/**
* Filter for processing key reference elements in DITA files.
* Instances are reusable but not thread-safe.
*/
public final class KeyrefPaser extends AbstractXMLFilter {
/**
* Set of attributes which should not be copied from
* key definition to key reference which is {@code <topicref>}.
*/
private static final Set<String> no_copy;
static {
final Set<String> nc = new HashSet<String>();
nc.add(ATTRIBUTE_NAME_ID);
nc.add(ATTRIBUTE_NAME_CLASS);
nc.add(ATTRIBUTE_NAME_XTRC);
nc.add(ATTRIBUTE_NAME_XTRF);
nc.add(ATTRIBUTE_NAME_HREF);
nc.add(ATTRIBUTE_NAME_KEYS);
nc.add(ATTRIBUTE_NAME_TOC);
nc.add(ATTRIBUTE_NAME_PROCESSING_ROLE);
no_copy = Collections.unmodifiableSet(nc);
}
/**
* Set of attributes which should not be copied from
* key definition to key reference which is not {@code <topicref>}.
*/
private static final Set<String> no_copy_topic;
static {
final Set<String> nct = new HashSet<String>();
nct.addAll(no_copy);
nct.add("query");
nct.add("search");
nct.add(ATTRIBUTE_NAME_TOC);
nct.add(ATTRIBUTE_NAME_PRINT);
nct.add(ATTRIBUTE_NAME_COPY_TO);
nct.add(ATTRIBUTE_NAME_CHUNK);
nct.add(ATTRIBUTE_NAME_NAVTITLE);
no_copy_topic = Collections.unmodifiableSet(nct);
}
/** List of key reference element definitions. */
private final static List<KeyrefInfo> keyrefInfos;
static {
final List<KeyrefInfo> ki = new ArrayList<KeyrefInfo>();
ki.add(new KeyrefInfo(TOPIC_AUTHOR, ATTRIBUTE_NAME_HREF, false));
ki.add(new KeyrefInfo(TOPIC_DATA, ATTRIBUTE_NAME_HREF, false));
ki.add(new KeyrefInfo(TOPIC_DATA_ABOUT, ATTRIBUTE_NAME_HREF, false));
ki.add(new KeyrefInfo(TOPIC_IMAGE, ATTRIBUTE_NAME_HREF, true));
ki.add(new KeyrefInfo(TOPIC_LINK, ATTRIBUTE_NAME_HREF, false));
ki.add(new KeyrefInfo(TOPIC_LQ, ATTRIBUTE_NAME_HREF, false));
ki.add(new KeyrefInfo(MAP_NAVREF, "mapref", true));
ki.add(new KeyrefInfo(TOPIC_PUBLISHER, ATTRIBUTE_NAME_HREF, false));
ki.add(new KeyrefInfo(TOPIC_SOURCE, ATTRIBUTE_NAME_HREF, false));
ki.add(new KeyrefInfo(MAP_TOPICREF, ATTRIBUTE_NAME_HREF, false));
ki.add(new KeyrefInfo(TOPIC_XREF, ATTRIBUTE_NAME_HREF, false));
ki.add(new KeyrefInfo(TOPIC_CITE, null, false));
ki.add(new KeyrefInfo(TOPIC_DT, null, false));
// links are processed for glossentry processing
ki.add(new KeyrefInfo(TOPIC_KEYWORD, ATTRIBUTE_NAME_HREF, false, false));
// links are processed for glossentry processing
ki.add(new KeyrefInfo(TOPIC_TERM, ATTRIBUTE_NAME_HREF, false, false));
ki.add(new KeyrefInfo(TOPIC_PH, null, false));
ki.add(new KeyrefInfo(TOPIC_INDEXTERM, null, false));
ki.add(new KeyrefInfo(TOPIC_INDEX_BASE, null, false));
ki.add(new KeyrefInfo(TOPIC_INDEXTERMREF, null, false));
keyrefInfos = Collections.unmodifiableList(ki);
}
private Map<String, Element> definitionMap;
private File tempDir;
/** File name with relative path to the temporary directory of input file. */
private File inputFile;
/**
* It is stack used to store the place of current element
* relative to the key reference element. Because keyref can be nested.
*/
private final Stack<Integer> keyrefLevalStack;
/**
* It is used to store the place of current element
* relative to the key reference element. If it is out of range of key
* reference element it is zero, otherwise it is positive number.
* It is also used to indicate whether current element is descendant of the
* key reference element.
*/
private int keyrefLeval;
/**
* It is used to store the target of the keys
* In the from the map <keys, target>.
*/
private Map<String, URI> keyMap;
/**
* It is used to indicate whether the keyref is valid.
* The descendant element should know whether keyref is valid because keyrefs can be nested.
*/
private final Stack<Boolean> validKeyref;
/**
* Flag indicating whether the key reference element is empty,
* if it is empty, it should pull matching content from the key definition.
*/
private boolean empty;
/** Stack of element names of the element containing keyref attribute. */
private final Stack<String> elemName;
/** Current element keyref info, {@code null} if not keyref type element. */
private KeyrefInfo currentElement;
private boolean hasChecked;
/** Flag stack to indicate whether key reference element has sub-elements. */
private final Stack<Boolean> hasSubElem;
/** Current key definition. */
private Element elem;
/** Set of link targets which are not resource-only */
private Set<String> normalProcessingRoleTargets;
/**
* Constructor.
*/
public KeyrefPaser() {
keyrefLeval = 0;
keyrefLevalStack = new Stack<Integer>();
validKeyref = new Stack<Boolean>();
empty = true;
keyMap = new HashMap<String, URI>();
elemName = new Stack<String>();
hasSubElem = new Stack<Boolean>();
}
public void setKeyDefinition(final Map<String, Element> definitionMap) {
this.definitionMap = definitionMap;
}
/**
* Set temp dir.
* @param tempDir temp dir
*/
public void setTempDir(final File tempDir) {
this.tempDir = tempDir;
}
/**
* Set current file.
*/
public void setCurrentFile(final File inputFile) {
this.inputFile = inputFile;
}
/**
* Set key map.
* @param map key map
*/
public void setKeyMap(final Map<String, URI> map) {
keyMap = map;
}
/**
* Get set of link targets which have normal processing role. Paths are relative to current file.
*/
public Set<String> getNormalProcessingRoleTargets() {
return Collections.unmodifiableSet(normalProcessingRoleTargets);
}
/**
* Process key references.
*
* @param filename file to process
* @throws DITAOTException if key reference resolution failed
*/
@Override
public void write(final File filename) throws DITAOTException {
super.write(new File(tempDir, inputFile.getPath()).getAbsoluteFile());
}
// XML filter methods ------------------------------------------------------
@Override
public void startDocument() throws SAXException {
normalProcessingRoleTargets = new HashSet<String>();
getContentHandler().startDocument();
}
@Override
public void characters(final char[] ch, final int start, final int length) throws SAXException {
if (keyrefLeval != 0 && new String(ch,start,length).trim().length() == 0) {
if (!hasChecked) {
empty = true;
}
} else {
hasChecked = true;
empty = false;
}
getContentHandler().characters(ch, start, length);
}
@Override
public void endElement(final String uri, final String localName, final String name) throws SAXException {
if (keyrefLeval != 0 && empty && !elemName.peek().equals(MAP_TOPICREF.localName)) {
// If current element is in the scope of key reference element
// and the element is empty
if (!validKeyref.isEmpty() && validKeyref.peek()) {
// Key reference is valid,
// need to pull matching content from the key definition
NodeList nodeList = null;
// If current element name doesn't equal the key reference element
// just grab the content from the matching element of key definition
if (!name.equals(elemName.peek())) {
nodeList = elem.getElementsByTagName(name);
if (nodeList.getLength() > 0) {
final Node node = nodeList.item(0);
final NodeList nList = node.getChildNodes();
int index = 0;
while (index < nList.getLength()) {
final Node n = nList.item(index++);
if (n.getNodeType() == Node.TEXT_NODE) {
final char[] ch = n.getNodeValue().toCharArray();
getContentHandler().characters(ch, 0, ch.length);
break;
}
}
}
} else {
// Current element name equals the key reference element
// grab keyword or term from key definition
nodeList = elem.getElementsByTagName(TOPIC_KEYWORD.localName);
if (nodeList.getLength() == 0 ) {
nodeList = elem.getElementsByTagName(TOPIC_TERM.localName);
}
if (!hasSubElem.peek()) {
if (nodeList.getLength() > 0) {
if (currentElement != null && !currentElement.isRefType) {
// only one keyword or term is used.
domToSax((Element) nodeList.item(0), false);
} else if (currentElement != null) {
// If the key reference element carries href attribute
// all keyword or term are used.
if (TOPIC_LINK.matches(currentElement.type)) {
final AttributesImpl atts = new AttributesImpl();
XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAME_CLASS, TOPIC_LINKTEXT.toString());
getContentHandler().startElement(NULL_NS_URI, TOPIC_LINKTEXT.localName, TOPIC_LINKTEXT.localName, atts);
}
if (!currentElement.isEmpty) {
for(int index = 0; index < nodeList.getLength(); index++) {
final Node node = nodeList.item(index);
if (node.getNodeType() == Node.ELEMENT_NODE) {
domToSax((Element) node, true);
}
}
}
if (TOPIC_LINK.matches(currentElement.type)) {
getContentHandler().endElement(NULL_NS_URI, TOPIC_LINKTEXT.localName, TOPIC_LINKTEXT.localName);
}
}
} else {
if (currentElement != null && TOPIC_LINK.matches(currentElement.type)) {
// If the key reference element is link or its specification,
// should pull in the linktext
final NodeList linktext = elem.getElementsByTagName(TOPIC_LINKTEXT.localName);
if (linktext.getLength() > 0) {
domToSax((Element) linktext.item(0), true);
} else if (!StringUtils.isEmptyString(elem.getAttribute(ATTRIBUTE_NAME_NAVTITLE))) {
final AttributesImpl atts = new AttributesImpl();
XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAME_CLASS, TOPIC_LINKTEXT.toString());
getContentHandler().startElement(NULL_NS_URI, TOPIC_LINKTEXT.localName, TOPIC_LINKTEXT.localName, atts);
if (elem.getAttribute(ATTRIBUTE_NAME_NAVTITLE) != null) {
final char[] ch = elem.getAttribute(ATTRIBUTE_NAME_NAVTITLE).toCharArray();
getContentHandler().characters(ch, 0, ch.length);
}
getContentHandler().endElement(NULL_NS_URI, TOPIC_LINKTEXT.localName, TOPIC_LINKTEXT.localName);
}
} else if (currentElement != null && currentElement.isRefType) {
final NodeList linktext = elem.getElementsByTagName(TOPIC_LINKTEXT.localName);
if (linktext.getLength() > 0) {
domToSax((Element) linktext.item(0), false);
} else {
if (elem.getAttribute(ATTRIBUTE_NAME_NAVTITLE) != null) {
final char[] ch = elem.getAttribute(ATTRIBUTE_NAME_NAVTITLE).toCharArray();
getContentHandler().characters(ch, 0, ch.length);
}
}
}
}
}
}
}
}
if (keyrefLeval != 0) {
keyrefLeval--;
empty = false;
}
if (keyrefLeval == 0 && !keyrefLevalStack.empty()) {
// To the end of key reference, pop the stacks.
keyrefLeval = keyrefLevalStack.pop();
validKeyref.pop();
elemName.pop();
hasSubElem.pop();
}
getContentHandler().endElement(uri, localName, name);
}
@Override
public void startElement(final String uri, final String localName, final String name,
final Attributes atts) throws SAXException {
currentElement = null;
final String cls = atts.getValue(ATTRIBUTE_NAME_CLASS);
for (final KeyrefInfo k: keyrefInfos) {
if (k.type.matches(cls)) {
currentElement = k;
}
}
final AttributesImpl resAtts = new AttributesImpl(atts);
hasChecked = false;
empty = true;
boolean valid = false;
if (atts.getIndex(ATTRIBUTE_NAME_KEYREF) == -1) {
// If the keyrefLeval doesn't equal 0, it means that current element is under the key reference element
if (keyrefLeval != 0) {
keyrefLeval++;
hasSubElem.pop();
hasSubElem.push(true);
}
} else {
// If there is @keyref, use the key definition to do
// combination.
// HashSet to store the attributes copied from key
// definition to key reference.
elemName.push(name);
//hasKeyref = true;
if (keyrefLeval != 0) {
keyrefLevalStack.push(keyrefLeval);
hasSubElem.pop();
hasSubElem.push(true);
}
hasSubElem.push(false);
keyrefLeval = 0;
keyrefLeval++;
//keyref.push(atts.getValue(ATTRIBUTE_NAME_KEYREF));
//the @keyref could be in the following forms:
// 1.keyName 2.keyName/elementId
/*String definition = ((Hashtable<String, String>) content
.getValue()).get(atts
.getValue(ATTRIBUTE_NAME_KEYREF));*/
final String keyrefValue = atts.getValue(ATTRIBUTE_NAME_KEYREF);
final int slashIndex = keyrefValue.indexOf(SLASH);
String keyName= keyrefValue;
String elementId= "";
if (slashIndex != -1) {
keyName = keyrefValue.substring(0, slashIndex);
elementId = keyrefValue.substring(slashIndex);
}
elem = definitionMap.get(keyName);
// If definition is not null
if (elem!=null) {
final NamedNodeMap namedNodeMap = elem.getAttributes();
// first resolve the keyref attribute
if (currentElement != null && currentElement.refAttr != null) {
final URI target = keyMap.get(keyName);
if (target != null && target.toString().length() != 0) {
URI target_output = target;
// if the scope equals local, the target should be verified that
// it exists.
final String scopeValue = elem.getAttribute(ATTRIBUTE_NAME_SCOPE);
final String formatValue = elem.getAttribute(ATTRIBUTE_NAME_FORMAT);
if (TOPIC_IMAGE.matches(currentElement.type)) {
valid = true;
target_output = normalizeHrefValue(URLUtils.getRelativePath(tempDir.toURI().resolve(inputFile.getPath()), tempDir.toURI().resolve(target)), elementId);
XMLUtils.addOrSetAttribute(resAtts, currentElement.refAttr, target_output.toString());
} else if (("".equals(scopeValue) || ATTR_SCOPE_VALUE_LOCAL.equals(scopeValue)) &&
("".equals(formatValue) || ATTR_FORMAT_VALUE_DITA.equals(formatValue) || ATTR_FORMAT_VALUE_DITAMAP.equals(formatValue))) {
final File topicFile = toFile(tempDir.toURI().resolve(stripFragment(target)));
if (topicFile.exists()) {
valid = true;
final String topicId = getFirstTopicId(topicFile);
- target_output = normalizeHrefValue(URLUtils.getRelativePath(tempDir.toURI().resolve(inputFile.getPath()), tempDir.toURI().resolve(target)), elementId, topicId);
+ target_output = normalizeHrefValue(URLUtils.getRelativePath(tempDir.toURI().resolve(toURI(inputFile)), tempDir.toURI().resolve(target)), elementId, topicId);
XMLUtils.addOrSetAttribute(resAtts, currentElement.refAttr, target_output.toString());
if (!ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equals(atts.getValue(ATTRIBUTE_NAME_PROCESSING_ROLE))) {
final URI f = toURI(inputFile).resolve(target_output);
normalProcessingRoleTargets.add(URLUtils.toFile(f).getPath());
}
} else {
// referenced file does not exist, emits a message.
// Should only emit this if in a debug mode; comment out for now
/*Properties prop = new Properties();
prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF));
javaLogger
.logInfo(MessageUtils.getInstance().getMessage("DOTJ047I", prop)
.toString());*/
}
}
// scope equals peer or external
else {
valid = true;
target_output = normalizeHrefValue(target_output, elementId);
XMLUtils.addOrSetAttribute(resAtts, currentElement.refAttr, target_output.toString());
}
} else if (target == null || target.toString().length() == 0) {
// Key definition does not carry an href or href equals "".
valid = true;
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE);
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF);
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE);
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT);
} else {
// key does not exist.
logger.info(MessageUtils.getInstance().getMessage("DOTJ047I", atts.getValue(ATTRIBUTE_NAME_KEYREF)).setLocation(atts).toString());
}
} else if (currentElement != null && !currentElement.isRefType) {
valid = true;
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE);
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF);
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE);
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT);
}
// copy attributes in key definition to key reference
// Set no_copy and no_copy_topic define some attributes should not be copied.
if (valid) {
if (currentElement != null && MAP_TOPICREF.matches(currentElement.type)) {
// @keyref in topicref
for (int index = 0; index < namedNodeMap.getLength(); index++) {
final Node node = namedNodeMap.item(index);
if (node.getNodeType() == Node.ATTRIBUTE_NODE
&& !no_copy.contains(node.getNodeName())) {
XMLUtils.removeAttribute(resAtts, node.getNodeName());
XMLUtils.addOrSetAttribute(resAtts, node);
}
}
} else {
// @keyref not in topicref
// different elements have different attributes
if (currentElement != null && currentElement.isRefType) {
// current element with href attribute
for (int index = 0; index < namedNodeMap.getLength(); index++) {
final Node node = namedNodeMap.item(index);
if (node.getNodeType() == Node.ATTRIBUTE_NODE
&& !no_copy_topic.contains(node.getNodeName())
&& (node.getNodeName().equals(currentElement.refAttr) || resAtts.getIndex(node.getNodeName()) == -1)) {
XMLUtils.removeAttribute(resAtts, node.getNodeName());
XMLUtils.addOrSetAttribute(resAtts, node);
}
}
} else if (currentElement != null && !currentElement.isRefType) {
// current element without href attribute
// so attributes about href should not be copied.
for (int index = 0; index < namedNodeMap.getLength(); index++) {
final Node node = namedNodeMap.item(index);
if (node.getNodeType() == Node.ATTRIBUTE_NODE
&& !no_copy_topic.contains(node.getNodeName())
&& !(node.getNodeName().equals(ATTRIBUTE_NAME_SCOPE)
|| node.getNodeName().equals(ATTRIBUTE_NAME_FORMAT)
|| node.getNodeName().equals(ATTRIBUTE_NAME_TYPE))) {
XMLUtils.removeAttribute(resAtts, node.getNodeName());
XMLUtils.addOrSetAttribute(resAtts, node);
}
}
}
}
} else {
// keyref is not valid, don't copy any attribute.
}
} else {
// key does not exist
logger.info(MessageUtils.getInstance().getMessage("DOTJ047I", atts.getValue(ATTRIBUTE_NAME_KEYREF)).setLocation(atts).toString());
}
validKeyref.push(valid);
}
getContentHandler().startElement(uri, localName, name, resAtts);
}
// Private methods ---------------------------------------------------------
/**
* Serialize DOM node into a SAX stream.
*
* @param elem element to serialize
* @param retainElements {@code true} to serialize elements, {@code false} to only serialize text nodes.
*/
private void domToSax(final Element elem, final boolean retainElements) throws SAXException{
// use retainElements to indicate that whether there is need to copy the element name
if (retainElements) {
final AttributesImpl atts = new AttributesImpl();
final NamedNodeMap namedNodeMap = elem.getAttributes();
for (int i = 0; i < namedNodeMap.getLength(); i++) {
final Attr a = (Attr) namedNodeMap.item(i);
if (a.getNodeName().equals(ATTRIBUTE_NAME_CLASS)) {
XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAME_CLASS, changeclassValue(a.getNodeValue()));
} else {
XMLUtils.addOrSetAttribute(atts, a);
}
}
getContentHandler().startElement(NULL_NS_URI, elem.getNodeName(), elem.getNodeName(), atts);
}
final NodeList nodeList = elem.getChildNodes();
for (int i = 0; i<nodeList.getLength(); i++) {
final Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
final Element e = (Element) node;
//special process for tm tag.
if (TOPIC_TM.matches(e)) {
domToSax(e, true);
} else {
// If the type of current node is ELEMENT_NODE, process current node.
domToSax(e, retainElements);
}
// If the type of current node is ELEMENT_NODE, process current node.
//stringBuffer.append(nodeToString((Element) node, retainElements));
} else if (node.getNodeType() == Node.TEXT_NODE) {
final char[] ch = node.getNodeValue().toCharArray();
getContentHandler().characters(ch, 0, ch.length);
}
}
if (retainElements) {
getContentHandler().endElement(NULL_NS_URI, elem.getNodeName(), elem.getNodeName());
}
}
/**
* Change map type to topic type.
*/
private String changeclassValue(final String classValue) {
final DitaClass cls = new DitaClass(classValue);
if (cls.equals(MAP_LINKTEXT)) {
return TOPIC_LINKTEXT.toString();
} else if (cls.equals(MAP_SEARCHTITLE)) {
return TOPIC_SEARCHTITLE.toString();
} else if (cls.equals(MAP_SHORTDESC)) {
return TOPIC_SHORTDESC.toString();
} else {
return cls.toString();
}
}
/**
* change elementId into topicId if there is no topicId in key definition.
*/
private static URI normalizeHrefValue(final URI keyName, final String tail) {
if (keyName.getFragment() == null) {
return toURI(keyName + tail.replaceAll(SLASH, SHARP));
}
return toURI(keyName + tail);
}
/**
* Get first topic id
*/
private String getFirstTopicId(final File topicFile) {
final File path = topicFile.getParentFile();
final String name = topicFile.getName();
return MergeUtils.getFirstTopicId(name, path, false);
}
/**
* Insert topic id into href
*/
private static URI normalizeHrefValue(final URI fileName, final String tail, final String topicId) {
//Insert first topic id only when topicid is not set in keydef
//and keyref has elementid
if (fileName.getFragment() == null && !"".equals(tail)) {
return setFragment(fileName, topicId + tail);
}
return toURI(fileName + tail);
}
// Inner classes -----------------------------------------------------------
private static final class KeyrefInfo {
/** DITA class. */
final DitaClass type;
/** Reference attribute name. */
final String refAttr;
/** Element is reference type. */
final boolean isRefType;
/** Element is empty. */
final boolean isEmpty;
/**
* Construct a new key reference info object.
*
* @param type element type
* @param refAttr hyperlink attribute name
* @param isEmpty flag if element is empty
* @param isRefType element is a reference type
*/
KeyrefInfo(final DitaClass type, final String refAttr, final boolean isEmpty, final boolean isRefType) {
this.type = type;
this.refAttr = refAttr;
this.isEmpty = isEmpty;
this.isRefType = isRefType;
}
/**
* Construct a new key reference info object.
*
* @param type element type
* @param refAttr hyperlink attribute name
* @param isEmpty flag if element is empty
*/
KeyrefInfo(final DitaClass type, final String refAttr, final boolean isEmpty) {
this(type, refAttr, isEmpty, refAttr != null);
}
}
}
| true | true | public void startElement(final String uri, final String localName, final String name,
final Attributes atts) throws SAXException {
currentElement = null;
final String cls = atts.getValue(ATTRIBUTE_NAME_CLASS);
for (final KeyrefInfo k: keyrefInfos) {
if (k.type.matches(cls)) {
currentElement = k;
}
}
final AttributesImpl resAtts = new AttributesImpl(atts);
hasChecked = false;
empty = true;
boolean valid = false;
if (atts.getIndex(ATTRIBUTE_NAME_KEYREF) == -1) {
// If the keyrefLeval doesn't equal 0, it means that current element is under the key reference element
if (keyrefLeval != 0) {
keyrefLeval++;
hasSubElem.pop();
hasSubElem.push(true);
}
} else {
// If there is @keyref, use the key definition to do
// combination.
// HashSet to store the attributes copied from key
// definition to key reference.
elemName.push(name);
//hasKeyref = true;
if (keyrefLeval != 0) {
keyrefLevalStack.push(keyrefLeval);
hasSubElem.pop();
hasSubElem.push(true);
}
hasSubElem.push(false);
keyrefLeval = 0;
keyrefLeval++;
//keyref.push(atts.getValue(ATTRIBUTE_NAME_KEYREF));
//the @keyref could be in the following forms:
// 1.keyName 2.keyName/elementId
/*String definition = ((Hashtable<String, String>) content
.getValue()).get(atts
.getValue(ATTRIBUTE_NAME_KEYREF));*/
final String keyrefValue = atts.getValue(ATTRIBUTE_NAME_KEYREF);
final int slashIndex = keyrefValue.indexOf(SLASH);
String keyName= keyrefValue;
String elementId= "";
if (slashIndex != -1) {
keyName = keyrefValue.substring(0, slashIndex);
elementId = keyrefValue.substring(slashIndex);
}
elem = definitionMap.get(keyName);
// If definition is not null
if (elem!=null) {
final NamedNodeMap namedNodeMap = elem.getAttributes();
// first resolve the keyref attribute
if (currentElement != null && currentElement.refAttr != null) {
final URI target = keyMap.get(keyName);
if (target != null && target.toString().length() != 0) {
URI target_output = target;
// if the scope equals local, the target should be verified that
// it exists.
final String scopeValue = elem.getAttribute(ATTRIBUTE_NAME_SCOPE);
final String formatValue = elem.getAttribute(ATTRIBUTE_NAME_FORMAT);
if (TOPIC_IMAGE.matches(currentElement.type)) {
valid = true;
target_output = normalizeHrefValue(URLUtils.getRelativePath(tempDir.toURI().resolve(inputFile.getPath()), tempDir.toURI().resolve(target)), elementId);
XMLUtils.addOrSetAttribute(resAtts, currentElement.refAttr, target_output.toString());
} else if (("".equals(scopeValue) || ATTR_SCOPE_VALUE_LOCAL.equals(scopeValue)) &&
("".equals(formatValue) || ATTR_FORMAT_VALUE_DITA.equals(formatValue) || ATTR_FORMAT_VALUE_DITAMAP.equals(formatValue))) {
final File topicFile = toFile(tempDir.toURI().resolve(stripFragment(target)));
if (topicFile.exists()) {
valid = true;
final String topicId = getFirstTopicId(topicFile);
target_output = normalizeHrefValue(URLUtils.getRelativePath(tempDir.toURI().resolve(inputFile.getPath()), tempDir.toURI().resolve(target)), elementId, topicId);
XMLUtils.addOrSetAttribute(resAtts, currentElement.refAttr, target_output.toString());
if (!ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equals(atts.getValue(ATTRIBUTE_NAME_PROCESSING_ROLE))) {
final URI f = toURI(inputFile).resolve(target_output);
normalProcessingRoleTargets.add(URLUtils.toFile(f).getPath());
}
} else {
// referenced file does not exist, emits a message.
// Should only emit this if in a debug mode; comment out for now
/*Properties prop = new Properties();
prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF));
javaLogger
.logInfo(MessageUtils.getInstance().getMessage("DOTJ047I", prop)
.toString());*/
}
}
// scope equals peer or external
else {
valid = true;
target_output = normalizeHrefValue(target_output, elementId);
XMLUtils.addOrSetAttribute(resAtts, currentElement.refAttr, target_output.toString());
}
} else if (target == null || target.toString().length() == 0) {
// Key definition does not carry an href or href equals "".
valid = true;
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE);
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF);
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE);
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT);
} else {
// key does not exist.
logger.info(MessageUtils.getInstance().getMessage("DOTJ047I", atts.getValue(ATTRIBUTE_NAME_KEYREF)).setLocation(atts).toString());
}
} else if (currentElement != null && !currentElement.isRefType) {
valid = true;
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE);
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF);
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE);
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT);
}
// copy attributes in key definition to key reference
// Set no_copy and no_copy_topic define some attributes should not be copied.
if (valid) {
if (currentElement != null && MAP_TOPICREF.matches(currentElement.type)) {
// @keyref in topicref
for (int index = 0; index < namedNodeMap.getLength(); index++) {
final Node node = namedNodeMap.item(index);
if (node.getNodeType() == Node.ATTRIBUTE_NODE
&& !no_copy.contains(node.getNodeName())) {
XMLUtils.removeAttribute(resAtts, node.getNodeName());
XMLUtils.addOrSetAttribute(resAtts, node);
}
}
} else {
// @keyref not in topicref
// different elements have different attributes
if (currentElement != null && currentElement.isRefType) {
// current element with href attribute
for (int index = 0; index < namedNodeMap.getLength(); index++) {
final Node node = namedNodeMap.item(index);
if (node.getNodeType() == Node.ATTRIBUTE_NODE
&& !no_copy_topic.contains(node.getNodeName())
&& (node.getNodeName().equals(currentElement.refAttr) || resAtts.getIndex(node.getNodeName()) == -1)) {
XMLUtils.removeAttribute(resAtts, node.getNodeName());
XMLUtils.addOrSetAttribute(resAtts, node);
}
}
} else if (currentElement != null && !currentElement.isRefType) {
// current element without href attribute
// so attributes about href should not be copied.
for (int index = 0; index < namedNodeMap.getLength(); index++) {
final Node node = namedNodeMap.item(index);
if (node.getNodeType() == Node.ATTRIBUTE_NODE
&& !no_copy_topic.contains(node.getNodeName())
&& !(node.getNodeName().equals(ATTRIBUTE_NAME_SCOPE)
|| node.getNodeName().equals(ATTRIBUTE_NAME_FORMAT)
|| node.getNodeName().equals(ATTRIBUTE_NAME_TYPE))) {
XMLUtils.removeAttribute(resAtts, node.getNodeName());
XMLUtils.addOrSetAttribute(resAtts, node);
}
}
}
}
} else {
// keyref is not valid, don't copy any attribute.
}
} else {
// key does not exist
logger.info(MessageUtils.getInstance().getMessage("DOTJ047I", atts.getValue(ATTRIBUTE_NAME_KEYREF)).setLocation(atts).toString());
}
validKeyref.push(valid);
}
getContentHandler().startElement(uri, localName, name, resAtts);
}
| public void startElement(final String uri, final String localName, final String name,
final Attributes atts) throws SAXException {
currentElement = null;
final String cls = atts.getValue(ATTRIBUTE_NAME_CLASS);
for (final KeyrefInfo k: keyrefInfos) {
if (k.type.matches(cls)) {
currentElement = k;
}
}
final AttributesImpl resAtts = new AttributesImpl(atts);
hasChecked = false;
empty = true;
boolean valid = false;
if (atts.getIndex(ATTRIBUTE_NAME_KEYREF) == -1) {
// If the keyrefLeval doesn't equal 0, it means that current element is under the key reference element
if (keyrefLeval != 0) {
keyrefLeval++;
hasSubElem.pop();
hasSubElem.push(true);
}
} else {
// If there is @keyref, use the key definition to do
// combination.
// HashSet to store the attributes copied from key
// definition to key reference.
elemName.push(name);
//hasKeyref = true;
if (keyrefLeval != 0) {
keyrefLevalStack.push(keyrefLeval);
hasSubElem.pop();
hasSubElem.push(true);
}
hasSubElem.push(false);
keyrefLeval = 0;
keyrefLeval++;
//keyref.push(atts.getValue(ATTRIBUTE_NAME_KEYREF));
//the @keyref could be in the following forms:
// 1.keyName 2.keyName/elementId
/*String definition = ((Hashtable<String, String>) content
.getValue()).get(atts
.getValue(ATTRIBUTE_NAME_KEYREF));*/
final String keyrefValue = atts.getValue(ATTRIBUTE_NAME_KEYREF);
final int slashIndex = keyrefValue.indexOf(SLASH);
String keyName= keyrefValue;
String elementId= "";
if (slashIndex != -1) {
keyName = keyrefValue.substring(0, slashIndex);
elementId = keyrefValue.substring(slashIndex);
}
elem = definitionMap.get(keyName);
// If definition is not null
if (elem!=null) {
final NamedNodeMap namedNodeMap = elem.getAttributes();
// first resolve the keyref attribute
if (currentElement != null && currentElement.refAttr != null) {
final URI target = keyMap.get(keyName);
if (target != null && target.toString().length() != 0) {
URI target_output = target;
// if the scope equals local, the target should be verified that
// it exists.
final String scopeValue = elem.getAttribute(ATTRIBUTE_NAME_SCOPE);
final String formatValue = elem.getAttribute(ATTRIBUTE_NAME_FORMAT);
if (TOPIC_IMAGE.matches(currentElement.type)) {
valid = true;
target_output = normalizeHrefValue(URLUtils.getRelativePath(tempDir.toURI().resolve(inputFile.getPath()), tempDir.toURI().resolve(target)), elementId);
XMLUtils.addOrSetAttribute(resAtts, currentElement.refAttr, target_output.toString());
} else if (("".equals(scopeValue) || ATTR_SCOPE_VALUE_LOCAL.equals(scopeValue)) &&
("".equals(formatValue) || ATTR_FORMAT_VALUE_DITA.equals(formatValue) || ATTR_FORMAT_VALUE_DITAMAP.equals(formatValue))) {
final File topicFile = toFile(tempDir.toURI().resolve(stripFragment(target)));
if (topicFile.exists()) {
valid = true;
final String topicId = getFirstTopicId(topicFile);
target_output = normalizeHrefValue(URLUtils.getRelativePath(tempDir.toURI().resolve(toURI(inputFile)), tempDir.toURI().resolve(target)), elementId, topicId);
XMLUtils.addOrSetAttribute(resAtts, currentElement.refAttr, target_output.toString());
if (!ATTR_PROCESSING_ROLE_VALUE_RESOURCE_ONLY.equals(atts.getValue(ATTRIBUTE_NAME_PROCESSING_ROLE))) {
final URI f = toURI(inputFile).resolve(target_output);
normalProcessingRoleTargets.add(URLUtils.toFile(f).getPath());
}
} else {
// referenced file does not exist, emits a message.
// Should only emit this if in a debug mode; comment out for now
/*Properties prop = new Properties();
prop.put("%1", atts.getValue(ATTRIBUTE_NAME_KEYREF));
javaLogger
.logInfo(MessageUtils.getInstance().getMessage("DOTJ047I", prop)
.toString());*/
}
}
// scope equals peer or external
else {
valid = true;
target_output = normalizeHrefValue(target_output, elementId);
XMLUtils.addOrSetAttribute(resAtts, currentElement.refAttr, target_output.toString());
}
} else if (target == null || target.toString().length() == 0) {
// Key definition does not carry an href or href equals "".
valid = true;
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE);
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF);
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE);
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT);
} else {
// key does not exist.
logger.info(MessageUtils.getInstance().getMessage("DOTJ047I", atts.getValue(ATTRIBUTE_NAME_KEYREF)).setLocation(atts).toString());
}
} else if (currentElement != null && !currentElement.isRefType) {
valid = true;
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_SCOPE);
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_HREF);
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_TYPE);
XMLUtils.removeAttribute(resAtts, ATTRIBUTE_NAME_FORMAT);
}
// copy attributes in key definition to key reference
// Set no_copy and no_copy_topic define some attributes should not be copied.
if (valid) {
if (currentElement != null && MAP_TOPICREF.matches(currentElement.type)) {
// @keyref in topicref
for (int index = 0; index < namedNodeMap.getLength(); index++) {
final Node node = namedNodeMap.item(index);
if (node.getNodeType() == Node.ATTRIBUTE_NODE
&& !no_copy.contains(node.getNodeName())) {
XMLUtils.removeAttribute(resAtts, node.getNodeName());
XMLUtils.addOrSetAttribute(resAtts, node);
}
}
} else {
// @keyref not in topicref
// different elements have different attributes
if (currentElement != null && currentElement.isRefType) {
// current element with href attribute
for (int index = 0; index < namedNodeMap.getLength(); index++) {
final Node node = namedNodeMap.item(index);
if (node.getNodeType() == Node.ATTRIBUTE_NODE
&& !no_copy_topic.contains(node.getNodeName())
&& (node.getNodeName().equals(currentElement.refAttr) || resAtts.getIndex(node.getNodeName()) == -1)) {
XMLUtils.removeAttribute(resAtts, node.getNodeName());
XMLUtils.addOrSetAttribute(resAtts, node);
}
}
} else if (currentElement != null && !currentElement.isRefType) {
// current element without href attribute
// so attributes about href should not be copied.
for (int index = 0; index < namedNodeMap.getLength(); index++) {
final Node node = namedNodeMap.item(index);
if (node.getNodeType() == Node.ATTRIBUTE_NODE
&& !no_copy_topic.contains(node.getNodeName())
&& !(node.getNodeName().equals(ATTRIBUTE_NAME_SCOPE)
|| node.getNodeName().equals(ATTRIBUTE_NAME_FORMAT)
|| node.getNodeName().equals(ATTRIBUTE_NAME_TYPE))) {
XMLUtils.removeAttribute(resAtts, node.getNodeName());
XMLUtils.addOrSetAttribute(resAtts, node);
}
}
}
}
} else {
// keyref is not valid, don't copy any attribute.
}
} else {
// key does not exist
logger.info(MessageUtils.getInstance().getMessage("DOTJ047I", atts.getValue(ATTRIBUTE_NAME_KEYREF)).setLocation(atts).toString());
}
validKeyref.push(valid);
}
getContentHandler().startElement(uri, localName, name, resAtts);
}
|
diff --git a/src/net/sf/freecol/client/control/PreGameController.java b/src/net/sf/freecol/client/control/PreGameController.java
index a7990a6aa..67295368d 100644
--- a/src/net/sf/freecol/client/control/PreGameController.java
+++ b/src/net/sf/freecol/client/control/PreGameController.java
@@ -1,261 +1,260 @@
/**
* Copyright (C) 2002-2007 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* FreeCol is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.client.control;
import java.awt.Color;
import java.util.logging.Logger;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.Canvas;
import net.sf.freecol.client.gui.CanvasKeyListener;
import net.sf.freecol.client.gui.CanvasMouseListener;
import net.sf.freecol.client.gui.CanvasMouseMotionListener;
import net.sf.freecol.client.gui.GUI;
import net.sf.freecol.client.gui.InGameMenuBar;
import net.sf.freecol.client.gui.i18n.Messages;
import net.sf.freecol.common.model.GameOptions;
import net.sf.freecol.common.model.ModelMessage;
import net.sf.freecol.common.model.Nation;
import net.sf.freecol.common.model.NationType;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.networking.Message;
import net.sf.freecol.server.generator.MapGeneratorOptions;
import org.w3c.dom.Element;
/**
* The controller that will be used before the game starts.
*/
public final class PreGameController {
@SuppressWarnings("unused")
private static final Logger logger = Logger.getLogger(PreGameController.class.getName());
private FreeColClient freeColClient;
private MapGeneratorOptions mapGeneratorOptions = null;
/**
* The constructor to use.
* @param freeColClient The main controller.
*/
public PreGameController(FreeColClient freeColClient) {
this.freeColClient = freeColClient;
}
/**
* Sets the <code>MapGeneratorOptions</code> used when creating
* a map.
*
* @param mapGeneratorOptions The <code>MapGeneratorOptions</code>.
*/
void setMapGeneratorOptions(MapGeneratorOptions mapGeneratorOptions) {
this.mapGeneratorOptions = mapGeneratorOptions;
}
/**
* Gets the <code>MapGeneratorOptions</code> used when creating
* a map.
*
* @return The <code>MapGeneratorOptions</code>.
*/
public MapGeneratorOptions getMapGeneratorOptions() {
return mapGeneratorOptions;
}
/**
* Sets this client to be (or not be) ready to start the game.
* @param ready Indicates wether or not this client is ready
* to start the game.
*/
public void setReady(boolean ready) {
// Make the change:
freeColClient.getMyPlayer().setReady(ready);
// Inform the server:
Element readyElement = Message.createNewRootElement("ready");
readyElement.setAttribute("value", Boolean.toString(ready));
freeColClient.getClient().send(readyElement);
}
/**
* Sets this client's player's nation.
* @param nation Which nation this player wishes to set.
*/
public void setNation(Nation nation) {
// Make the change:
freeColClient.getMyPlayer().setNation(nation);
// Inform the server:
Element nationElement = Message.createNewRootElement("setNation");
nationElement.setAttribute("value", nation.getId());
freeColClient.getClient().sendAndWait(nationElement);
}
/**
* Sets this client's player's nation type.
* @param nationType Which nation this player wishes to set.
*/
public void setNationType(NationType nationType) {
// Make the change:
freeColClient.getMyPlayer().setNationType(nationType);
// Inform the server:
Element nationTypeElement = Message.createNewRootElement("setNationType");
nationTypeElement.setAttribute("value", nationType.getId());
freeColClient.getClient().sendAndWait(nationTypeElement);
}
/**
* Sets this client's player's color.
* @param color Which color this player wishes to set.
*/
public void setColor(Color color) {
// Make the change:
freeColClient.getMyPlayer().setColor(color);
// Inform the server:
Element colorElement = Message.createNewRootElement("setColor");
// the substring hack is necessary to prevent an integer
// overflow, as the hex string will be unsigned, and
// Integer.decode() expects a signed int
colorElement.setAttribute("value", "#" + Integer.toHexString(color.getRGB()).substring(2));
freeColClient.getClient().sendAndWait(colorElement);
}
/**
* Requests the game to be started. This will only be successful
* if all players are ready to start the game.
*/
public void requestLaunch() {
Canvas canvas = freeColClient.getCanvas();
if (!freeColClient.getGame().isAllPlayersReadyToLaunch()) {
canvas.errorMessage("server.notAllReady");
return;
}
Element requestLaunchElement = Message.createNewRootElement("requestLaunch");
freeColClient.getClient().send(requestLaunchElement);
canvas.showStatusPanel( Messages.message("status.startingGame") );
}
/**
* Sends a chat message.
* @param message The message as plain text.
*/
public void chat(String message) {
Element chatElement = Message.createNewRootElement("chat");
chatElement.setAttribute("senderName", freeColClient.getMyPlayer().getName());
chatElement.setAttribute("message", message);
chatElement.setAttribute("privateChat", "false");
freeColClient.getClient().send(chatElement);
}
/**
* Sends the {@link GameOptions} to the server.
* This method should be called after updating that object.
*/
public void sendGameOptions() {
Element updateGameOptionsElement = Message.createNewRootElement("updateGameOptions");
updateGameOptionsElement.appendChild(freeColClient.getGame().getGameOptions().toXMLElement(updateGameOptionsElement.getOwnerDocument()));
freeColClient.getClient().send(updateGameOptionsElement);
}
/**
* Sends the {@link MapGeneratorOptions} to the server.
* This method should be called after updating that object.
*/
public void sendMapGeneratorOptions() {
if (mapGeneratorOptions != null) {
Element updateMapGeneratorOptionsElement = Message.createNewRootElement("updateMapGeneratorOptions");
updateMapGeneratorOptionsElement.appendChild(mapGeneratorOptions.toXMLElement(updateMapGeneratorOptionsElement.getOwnerDocument()));
freeColClient.getClient().send(updateMapGeneratorOptionsElement);
}
}
/**
* Starts the game.
*/
public void startGame() {
Canvas canvas = freeColClient.getCanvas();
GUI gui = freeColClient.getGUI();
canvas.closeMainPanel();
canvas.closeMenus();
InGameController inGameController = freeColClient.getInGameController();
InGameInputHandler inGameInputHandler = freeColClient.getInGameInputHandler();
freeColClient.getClient().setMessageHandler(inGameInputHandler);
gui.setInGame(true);
freeColClient.getCanvas().setJMenuBar(new InGameMenuBar(freeColClient));
if (freeColClient.getGame().getTurn().getNumber() == 1) {
Player player = freeColClient.getMyPlayer();
- player.addModelMessage(new ModelMessage(player, "tutorial.startGame", null,
- ModelMessage.MessageType.TUTORIAL, player));
+ player.addModelMessage(new ModelMessage(player, ModelMessage.MessageType.TUTORIAL, player, "tutorial.startGame"));
}
Unit activeUnit = freeColClient.getMyPlayer().getNextActiveUnit();
//freeColClient.getMyPlayer().updateCrossesRequired();
gui.setActiveUnit(activeUnit);
if (activeUnit != null) {
gui.setFocus(activeUnit.getTile().getPosition());
} else {
gui.setFocus(((Tile) freeColClient.getMyPlayer().getEntryLocation()).getPosition());
}
canvas.addKeyListener(new CanvasKeyListener(canvas, inGameController));
canvas.addMouseListener(new CanvasMouseListener(canvas, gui));
canvas.addMouseMotionListener(new CanvasMouseMotionListener(canvas, gui, freeColClient.getGame().getMap()));
if (freeColClient.getMyPlayer().equals(freeColClient.getGame().getCurrentPlayer())) {
canvas.requestFocus();
freeColClient.getInGameController().nextModelMessage();
} else {
//canvas.setEnabled(false);
}
}
}
| true | true | public void startGame() {
Canvas canvas = freeColClient.getCanvas();
GUI gui = freeColClient.getGUI();
canvas.closeMainPanel();
canvas.closeMenus();
InGameController inGameController = freeColClient.getInGameController();
InGameInputHandler inGameInputHandler = freeColClient.getInGameInputHandler();
freeColClient.getClient().setMessageHandler(inGameInputHandler);
gui.setInGame(true);
freeColClient.getCanvas().setJMenuBar(new InGameMenuBar(freeColClient));
if (freeColClient.getGame().getTurn().getNumber() == 1) {
Player player = freeColClient.getMyPlayer();
player.addModelMessage(new ModelMessage(player, "tutorial.startGame", null,
ModelMessage.MessageType.TUTORIAL, player));
}
Unit activeUnit = freeColClient.getMyPlayer().getNextActiveUnit();
//freeColClient.getMyPlayer().updateCrossesRequired();
gui.setActiveUnit(activeUnit);
if (activeUnit != null) {
gui.setFocus(activeUnit.getTile().getPosition());
} else {
gui.setFocus(((Tile) freeColClient.getMyPlayer().getEntryLocation()).getPosition());
}
canvas.addKeyListener(new CanvasKeyListener(canvas, inGameController));
canvas.addMouseListener(new CanvasMouseListener(canvas, gui));
canvas.addMouseMotionListener(new CanvasMouseMotionListener(canvas, gui, freeColClient.getGame().getMap()));
if (freeColClient.getMyPlayer().equals(freeColClient.getGame().getCurrentPlayer())) {
canvas.requestFocus();
freeColClient.getInGameController().nextModelMessage();
} else {
//canvas.setEnabled(false);
}
}
| public void startGame() {
Canvas canvas = freeColClient.getCanvas();
GUI gui = freeColClient.getGUI();
canvas.closeMainPanel();
canvas.closeMenus();
InGameController inGameController = freeColClient.getInGameController();
InGameInputHandler inGameInputHandler = freeColClient.getInGameInputHandler();
freeColClient.getClient().setMessageHandler(inGameInputHandler);
gui.setInGame(true);
freeColClient.getCanvas().setJMenuBar(new InGameMenuBar(freeColClient));
if (freeColClient.getGame().getTurn().getNumber() == 1) {
Player player = freeColClient.getMyPlayer();
player.addModelMessage(new ModelMessage(player, ModelMessage.MessageType.TUTORIAL, player, "tutorial.startGame"));
}
Unit activeUnit = freeColClient.getMyPlayer().getNextActiveUnit();
//freeColClient.getMyPlayer().updateCrossesRequired();
gui.setActiveUnit(activeUnit);
if (activeUnit != null) {
gui.setFocus(activeUnit.getTile().getPosition());
} else {
gui.setFocus(((Tile) freeColClient.getMyPlayer().getEntryLocation()).getPosition());
}
canvas.addKeyListener(new CanvasKeyListener(canvas, inGameController));
canvas.addMouseListener(new CanvasMouseListener(canvas, gui));
canvas.addMouseMotionListener(new CanvasMouseMotionListener(canvas, gui, freeColClient.getGame().getMap()));
if (freeColClient.getMyPlayer().equals(freeColClient.getGame().getCurrentPlayer())) {
canvas.requestFocus();
freeColClient.getInGameController().nextModelMessage();
} else {
//canvas.setEnabled(false);
}
}
|
diff --git a/src/main/java/org/offlike/server/LikeController.java b/src/main/java/org/offlike/server/LikeController.java
index 28e591e..9d01ae6 100644
--- a/src/main/java/org/offlike/server/LikeController.java
+++ b/src/main/java/org/offlike/server/LikeController.java
@@ -1,59 +1,59 @@
package org.offlike.server;
import org.offlike.server.data.Campaign;
import org.offlike.server.data.QrCode;
import org.offlike.server.service.MongoDbService;
import org.offlike.server.service.UrlBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.google.common.collect.ImmutableMap;
@Controller
public class LikeController {
// TODO count the number of requests,
private MongoDbService dbService;
@RequestMapping("/like/{id}")
public ModelAndView like(
@RequestParam(value = "campaign_name", required = false) String campaignName,
@RequestParam(value = "lat", required = false) Double lat,
- @RequestParam(value = "lng", required = false) Double lng,
+ @RequestParam(value = "lon", required = false) Double lng,
@RequestParam(value = "accuracy", required = false) Integer accuracy,
@PathVariable("id") String id) {
if (lat != null && lng != null && accuracy != null) {
getDbService().activateQrCode(id, lat, lng, accuracy);
}
QrCode qrCode = dbService.findQrCodeById(id);
if (qrCode == null) {
return errorPage("Unknown qr code!");
}
Campaign campaign = dbService.findCampaignById(qrCode.getCampaignId());
if (campaign==null){
return errorPage("Unknown campaign id!");
}
return new ModelAndView("like", ImmutableMap.<String, Object> of(
"campaign", campaign,
"url", UrlBuilder.createLikeURL(id)));
}
private ModelAndView errorPage(String error) {
return new ModelAndView("errorPage", ImmutableMap.of("error", error));
}
public MongoDbService getDbService() {
return dbService;
}
public void setDbService(MongoDbService dbService) {
this.dbService = dbService;
}
}
| true | true | public ModelAndView like(
@RequestParam(value = "campaign_name", required = false) String campaignName,
@RequestParam(value = "lat", required = false) Double lat,
@RequestParam(value = "lng", required = false) Double lng,
@RequestParam(value = "accuracy", required = false) Integer accuracy,
@PathVariable("id") String id) {
if (lat != null && lng != null && accuracy != null) {
getDbService().activateQrCode(id, lat, lng, accuracy);
}
QrCode qrCode = dbService.findQrCodeById(id);
if (qrCode == null) {
return errorPage("Unknown qr code!");
}
Campaign campaign = dbService.findCampaignById(qrCode.getCampaignId());
if (campaign==null){
return errorPage("Unknown campaign id!");
}
return new ModelAndView("like", ImmutableMap.<String, Object> of(
"campaign", campaign,
"url", UrlBuilder.createLikeURL(id)));
}
| public ModelAndView like(
@RequestParam(value = "campaign_name", required = false) String campaignName,
@RequestParam(value = "lat", required = false) Double lat,
@RequestParam(value = "lon", required = false) Double lng,
@RequestParam(value = "accuracy", required = false) Integer accuracy,
@PathVariable("id") String id) {
if (lat != null && lng != null && accuracy != null) {
getDbService().activateQrCode(id, lat, lng, accuracy);
}
QrCode qrCode = dbService.findQrCodeById(id);
if (qrCode == null) {
return errorPage("Unknown qr code!");
}
Campaign campaign = dbService.findCampaignById(qrCode.getCampaignId());
if (campaign==null){
return errorPage("Unknown campaign id!");
}
return new ModelAndView("like", ImmutableMap.<String, Object> of(
"campaign", campaign,
"url", UrlBuilder.createLikeURL(id)));
}
|
diff --git a/jruby-maven-plugin/src/main/java/de/saumya/mojo/jruby/IRBMojo.java b/jruby-maven-plugin/src/main/java/de/saumya/mojo/jruby/IRBMojo.java
index 95a4cd52..c15226d4 100644
--- a/jruby-maven-plugin/src/main/java/de/saumya/mojo/jruby/IRBMojo.java
+++ b/jruby-maven-plugin/src/main/java/de/saumya/mojo/jruby/IRBMojo.java
@@ -1,35 +1,36 @@
package de.saumya.mojo.jruby;
import org.apache.maven.plugin.MojoExecutionException;
/**
* maven wrpper around IRB.
*
* @goal irb
* @requiresDependencyResolution test
*/
public class IRBMojo extends AbstractJRubyMojo {
// override super mojo and make this readonly
/**
* @parameter expression="false"
* @readonly
*/
protected boolean fork;
/**
* arguments for the irb command.
*
* @parameter default-value="${jruby.irb.args}"
*/
protected String args = null;
public void execute() throws MojoExecutionException {
- super.fork = this.fork;
+ // make sure the whole things run in the same process
+ super.fork = false;
final StringBuilder args = new StringBuilder("-S irb");
if (this.args != null) {
args.append(" ").append(this.args);
}
execute(args.toString());
}
}
| true | true | public void execute() throws MojoExecutionException {
super.fork = this.fork;
final StringBuilder args = new StringBuilder("-S irb");
if (this.args != null) {
args.append(" ").append(this.args);
}
execute(args.toString());
}
| public void execute() throws MojoExecutionException {
// make sure the whole things run in the same process
super.fork = false;
final StringBuilder args = new StringBuilder("-S irb");
if (this.args != null) {
args.append(" ").append(this.args);
}
execute(args.toString());
}
|
diff --git a/de.tud.cs.st.vespucci.diagram/src/de/tud/cs/st/vespucci/diagram/converter/DiagramConverter.java b/de.tud.cs.st.vespucci.diagram/src/de/tud/cs/st/vespucci/diagram/converter/DiagramConverter.java
index ab9ad5f4..6bfd588f 100644
--- a/de.tud.cs.st.vespucci.diagram/src/de/tud/cs/st/vespucci/diagram/converter/DiagramConverter.java
+++ b/de.tud.cs.st.vespucci.diagram/src/de/tud/cs/st/vespucci/diagram/converter/DiagramConverter.java
@@ -1,597 +1,597 @@
/*
* License (BSD Style License):
* Copyright (c) 2010
* Author Patrick Jahnke
* Software Engineering
* Department of Computer Science
* Technische Universiti�t Darmstadt
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the Software Engineering Group or Technische
* Universit�t Darmstadt nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package de.tud.cs.st.vespucci.diagram.converter;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl;
import de.tud.cs.st.vespucci.vespucci_model.Connection;
import de.tud.cs.st.vespucci.vespucci_model.Dummy;
import de.tud.cs.st.vespucci.vespucci_model.Ensemble;
import de.tud.cs.st.vespucci.vespucci_model.Expected;
import de.tud.cs.st.vespucci.vespucci_model.InAndOut;
import de.tud.cs.st.vespucci.vespucci_model.Incoming;
import de.tud.cs.st.vespucci.vespucci_model.NotAllowed;
import de.tud.cs.st.vespucci.vespucci_model.Outgoing;
import de.tud.cs.st.vespucci.vespucci_model.Shape;
import de.tud.cs.st.vespucci.vespucci_model.ShapesDiagram;
/**
* DiagramConverter converts a *.sad into a *.pl File.
* @author PatrickJ
*/
public class DiagramConverter {
/**
* Regular expression to check parameter of Ensembles.
*/
private static Pattern mParameterVariable = Pattern.compile("\\p{Upper}.*");
/**
* Regular expression to split parameter names of Ensembles.
*/
private static Pattern mParameterNames = Pattern.compile("(.*?)=(.*)");
/**
* Regular expression to match a parameter.
*/
private static Pattern mParameterList = Pattern
.compile( "^.+?" + // match the descriptor
"\\(" + // match the first bracket
"(.*)" + // match anything in between as group
"\\)$"); // match the last parenthesis by asserting the string ends here
/**
* an internal member to increase the number of dependencies.
*/
private int mDependencyCounter;
/**
* an internal member to create an empty ensemble only once.
*/
private boolean mCreateEmptyEnsemble = false;
/**
* load a Diagram File
* @param fullPathFileName the full path filename.
* @return ShapesDiagramImpl Object
* @throws FileNotFoundException
* @throws IOException
* @author Patrick Jahnke
*/
public ShapesDiagram loadDiagramFile(String fullPathFileName) throws FileNotFoundException, IOException
{
XMIResourceImpl resource = new XMIResourceImpl();
File source = new File(fullPathFileName);
resource.load( new FileInputStream(source), new HashMap<Object,Object>());
EObject eObject = resource.getContents().get(0);
return (ShapesDiagram) eObject;
}
/**
* load a diagram file
* @param fullPathFileName the full path filename.
* @return ShapesDiagramImpl Object
* @throws FileNotFoundException
* @throws IOException
* @author Patrick Jahnke, MalteV
*/
public ShapesDiagram loadDiagramFile(File sadFile) throws FileNotFoundException, IOException
{
XMIResourceImpl resource = new XMIResourceImpl();
File source = sadFile;
resource.load( new FileInputStream(source), new HashMap<Object,Object>());
EObject eObject = resource.getContents().get(0);
return (ShapesDiagram) eObject;
}
/**
* read the given diagram and create a prolog file.
* @param fullPathFileName Name and path of the diagram
* @author Patrick Jahnke
* @throws Exception
*/
public void ConvertDiagramToProlog (String path, String fileName) throws Exception
{
String fullFileName = path + "/" + fileName;
ShapesDiagram diagram = loadDiagramFile(fullFileName);
// create a new Prolog File
File prologFile = new File(fullFileName + ".pl");
// the file will be overwritten
FileOutputStream fos;
fos = new FileOutputStream(prologFile);
BufferedOutputStream bos = new BufferedOutputStream(fos);
// write header string
bos.write(this.getFileHeaderString(fullFileName).getBytes());
// translate ensemble facts
bos.write(this.getFacts(diagram, fileName).getBytes());
bos.close();
fos.close();
return;
}
/**
* read the given diagram and create a prolog file.
* @param fullPathFileName Name and path of the diagram
* @author Patrick Jahnke, MalteV
* @throws Exception
*/
public void ConvertDiagramToProlog (File sadFile) throws Exception
{
this.ConvertDiagramToProlog(sadFile.getParent(), sadFile.getName());
}
/**
* Return true when the given file object is a diagram file.
* @author Patrick Jahnke
*/
public boolean isDiagramFile(File file){
String extension = file.getName().substring((file.getName().length()-3), file.getName().length());
return (extension.equals("sad"));
}
/**
* returns the separator %------
* @author Patrick Jahnke
*/
private String getStringSeperator() {
return "%------\n";
}
/**
* Build and returns a prolog file header.
* @author Patrick Jahnke
*/
private String getFileHeaderString(String fileName)
{
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(getStringSeperator());
// insert common information
strBuilder.append("% Prolog based representation of the Vespucci architecture diagram: ");
strBuilder.append(fileName+"\n");
strBuilder.append("% Created by Vespucci, Technische Universiti�t Darmstadt, Department of Computer Science\n");
strBuilder.append("% www.opal-project.de\n\n");
strBuilder.append(":- multifile ensemble/5.\n");
strBuilder.append(":- multifile abstract_ensemble/5.\n");
strBuilder.append(":- multifile outgoing/7.\n");
strBuilder.append(":- multifile incoming/7.\n");
strBuilder.append(":- multifile not_allowed/7.\n");
strBuilder.append(":- multifile expected/7.\n");
strBuilder.append(":- discontiguous ensemble/5.\n");
strBuilder.append(":- discontiguous abstract_ensemble/5.\n");
strBuilder.append(":- discontiguous outgoing/7.\n");
strBuilder.append(":- discontiguous incoming/7.\n");
strBuilder.append(":- discontiguous not_allowed/7.\n");
strBuilder.append(":- discontiguous expected/7.\n\n");
// insert Date
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
strBuilder.append("% Date <" + dateFormat.format(date) + ">.\n");
strBuilder.append(getStringSeperator());
strBuilder.append("\n");
return strBuilder.toString();
}
/**
* Read the diagram and create the prolog facts of ensembles and dependencies
* @param diagram the diagram model where are the ensembles and dependencies are defined.
* @param fileName the filename of the diagram model
* @return a string with the facts
* @author Patrick Jahnke
* @throws Exception
*/
private String getFacts(ShapesDiagram diagram, String fileName) throws Exception
{
StringBuilder strBuilder = new StringBuilder();
// insert ensemble Header
strBuilder.append(getEnsembleHeader());
// create ensembles and dependencies from diagram
StringBuilder ensembleFacts = new StringBuilder();
StringBuilder dependencyFacts = new StringBuilder();
// reset transaction counter
mDependencyCounter = 1;
mCreateEmptyEnsemble = false;
createFacts(diagram.getShapes(), fileName, ensembleFacts, dependencyFacts);
if (mCreateEmptyEnsemble)
ensembleFacts.append("ensemble('" + fileName + "',(empty),empty,[]).\n");
// insert ensembles
strBuilder.append(ensembleFacts);
// insert dependency header
strBuilder.append(getDependencyHeader());
// insert dependencies
strBuilder.append(dependencyFacts);
return strBuilder.toString();
}
/**
* Search the diagram recursive and create all facts.
* @author Patrick Jahnke
* @throws Exception
*/
private void createFacts(List<Shape> shapeList, String fileName, StringBuilder ensembleFacts, StringBuilder dependencyFacts) throws Exception
{
for (Shape shape : shapeList) {
// create Ensemble facts:
if (shape == null)
continue;
if (shape instanceof Dummy)
mCreateEmptyEnsemble = true;
else if (shape instanceof Ensemble)
{
Ensemble ensemble = (Ensemble) shape;
if (this.isAbstractEnsemble(ensemble))
ensembleFacts.append("abstract_ensemble");
else
ensembleFacts.append("ensemble");
// fix: inconsistent newline encodings
String query = ensemble.getQuery().replaceAll("\n", " ");
ensembleFacts.append("('" + fileName + "', " + this.getEnsembleDescriptor(ensemble) + ", "+ getEnsembleParameters (ensemble) +", (" + query + "), [" + listSubEnsembles(ensemble.getShapes()) + "]).\n");
// does children exist
if ((ensemble.getShapes() != null) && (ensemble.getShapes().size()>0))
createFacts(ensemble.getShapes(), fileName, ensembleFacts, dependencyFacts);
}
// create transaction facts:
for (Connection connection : shape.getTargetConnections())
dependencyFacts.append(createDependencyFact(connection, fileName));
}
}
/**
* Check if an ensemble an abstract one.
* @param ensemble
* @return
* @author Patrick Jahnke
*/
private boolean isAbstractEnsemble(Ensemble ensemble) {
String[] parameters = getEnsembleParameterDefinitions(ensemble);
for (int i = 0; i < parameters.length; i++) {
if (mParameterVariable.matcher(parameters[i]).matches())
return true;
}
return false;
}
/**
* @return a prolog list of the form ['ParamName'=ParamName, ...]
* @author Patrick Jahnke
*/
private String getEnsembleParameters(Ensemble ensemble) {
String[] parameters = this.getEnsembleParameterDefinitions(ensemble);
if (parameters.length == 0)
return "[]";
StringBuilder s = new StringBuilder("[");
s.append(getEncodedParameter(parameters[0]));
for (int i = 1; i < parameters.length; i++) {
s.append(", ");
s.append(getEncodedParameter(parameters[i]));
}
s.append("]");
return s.toString();
}
/**
* the name of the ensemble. (Without parameters)
* @param shape
* @return
* @author Patrick Jahnke
*/
private String getEnsembleDescriptor(Shape shape) {
String name = shape.getName().length()== 0 ? "non-editpart" : shape.getName();
StringBuilder s = new StringBuilder("'");
if (name.indexOf('(') > 0) {
s.append(name.subSequence(0, name.indexOf('(')));
} else {
s.append(name);
}
s.append("'");
return s.toString();
}
/**
* Encode and returns the pure parameter.
* @param name
* @return
* @author Patrick Jahnke
*/
private String getEncodedParameter(String name) {
StringBuilder s = new StringBuilder();
if (mParameterVariable.matcher(name).matches()) {
s.append("'");
s.append(name);
s.append("'");
s.append("=");
s.append(name);
return s.toString();
}
Matcher m = mParameterNames.matcher(name);
if (m.matches()) {
s.append("'");
s.append(m.group(1));
s.append("'");
s.append("=");
s.append(m.group(2));
return s.toString();
}
s.append("_");
s.append("=");
s.append(name);
return s.toString();
}
/**
* returns the parameter definitions of an ensemble
* @param ensemble
* @return
* @author Patrick Jahnke
*/
private String[] getEnsembleParameterDefinitions(Ensemble ensemble) {
// FIXME BenjaminL: schneller hack, dass keine nullpointerexception beim speichern eines diagramms mit einem ensemble mit leeren namen auftritt - sch�ner kettensatz, he?
if(ensemble.getName()==null){
ensemble.setName("");
}
String name = ensemble.getName().length()== 0 ? "non-editpart" : ensemble.getName();
Matcher m = mParameterList.matcher(name);
if (!m.matches())
return new String[0];
List<String> parameterDefinitions = new LinkedList<String>();
String parameters = m.group(1);
int start = 0;
int matchParenthesis = 0;
for (int i = 0; i < parameters.length(); i++) {
if(parameters.charAt(i) == '(')
matchParenthesis++;
if(matchParenthesis > 0 && parameters.charAt(i) == ')')
matchParenthesis--;
if(parameters.charAt(i) == ',' && matchParenthesis == 0) {
parameterDefinitions.add(parameters.substring(start, i).trim());
start = i + 1;
}
}
parameterDefinitions.add(parameters.substring(start, parameters.length()).trim());
String[] result = new String[parameterDefinitions.size()];
return parameterDefinitions.toArray(result);
}
/**
* returns a static string for the begin of the ensemble facts.
* @author Patrick Jahnke
*/
private String getEnsembleHeader()
{
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(getStringSeperator());
// insert common information
strBuilder.append("%ensemble(File, Name, Query, SubEnsembles) :- Definition of an ensemble.\n");
strBuilder.append("%\tFile - The simple file name in which the ensemble is defined. (e.g., 'Flashcards.sad')\n");
strBuilder.append("%\tName - Name of the ensemble\n");
strBuilder.append("%\tQuery - Query that determines which source elements belong to the ensemble\n");
strBuilder.append("%\tSubEnsembles - List of all sub ensembles of this ensemble.\n");
strBuilder.append(getStringSeperator());
return strBuilder.toString();
}
/**
* returns a static string for the begin of the dependency facts
* @return
*/
private String getDependencyHeader()
{
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("\n");
strBuilder.append(getStringSeperator());
// insert common information
strBuilder.append("%DEPENDENCY(File, ID, SourceE, TargetE, Type) :- Definition of a dependency between two ensembles.\n");
strBuilder.append("%\tDEPENDENCY - The type of the dependency. Possible values: outgoing, incoming, expected, not_allowed\n");
strBuilder.append("%\tFile - The simple file name in which the dependency is defined. (e.g., 'Flashcards.sad')\n");
strBuilder.append("%\tID - An ID identifying the dependency\n");
strBuilder.append("%\tSourceE - The source ensemble\n");
strBuilder.append("%\tTargetE - The target ensemble\n");
strBuilder.append("%\tRelation classifier - Kinds of uses-relation between source and target ensemble (all, field_access, method_call,...)\n");
strBuilder.append(getStringSeperator());
return strBuilder.toString();
}
/**
* create a dependency fact
* @param connection
* @param fileName
* @return
* @author Patrick Jahnke
* @throws Exception
*/
private String createDependencyFact(Connection connection, String fileName) throws Exception
{
Shape source = null;
Shape target = null;
// Get the original source (and not the red line source)
if ((connection.getOriginalSource()==null)
|| (connection.getOriginalSource().size()==0))
source = connection.getSource();
else if ((connection.getOriginalSource()!=null)
&& (connection.getOriginalSource().size()==1))
source = connection.getOriginalSource().get(0);
else
throw new Exception ("Too many original sources in connection available. Please check the the original sources of connection: \""+connection.getName()+"\"");
// Get the original target (and not the red line target)
if ((connection.getOriginalTarget()==null)
|| (connection.getOriginalTarget().size()==0))
- source = connection.getTarget();
+ target = connection.getTarget();
else if ((connection.getOriginalTarget()!=null)
&& (connection.getOriginalTarget().size()==1))
- source = connection.getOriginalTarget().get(0);
+ target = connection.getOriginalTarget().get(0);
else
throw new Exception ("Too many original tagets in connection available. Please check the the original targets of connection: \""+connection.getName()+"\"");
StringBuilder transactionSB = new StringBuilder();
//TODO: delete next 2 lines if saved sad file doesn't
//contains copy/paste artifact references. Problem: if one copy from one sad file
// an Ensemble with dependency in another sad file than the copy of
// the Ensemble will contains a reference to original Ensemble in first saf file.
// This reference has no influence on working process but it has problem here,
// by converting to prolog facts
if(connection.getSource().eIsProxy() || connection.getTarget().eIsProxy())
return "";
if (connection instanceof Outgoing)
transactionSB.append("outgoing"
+ "('" + fileName + "', " + mDependencyCounter + ", "
+ getDependencyEnsembleName(source) + ", [], "
+ getDependencyEnsembleName(target) + ", [], " + connection.getName() + ").\n");
else if (connection instanceof Incoming)
transactionSB.append("incoming"
+ "('" + fileName + "', " + mDependencyCounter + ", "
+ getDependencyEnsembleName(source) + ", [], "
+ getDependencyEnsembleName(target) + ", [], " + connection.getName() + ").\n");
else if (connection instanceof Expected)
transactionSB.append("expected"
+ "('" + fileName + "', " + mDependencyCounter + ", "
+ getDependencyEnsembleName(source) + ", [], "
+ getDependencyEnsembleName(target) + ", [], " + connection.getName() + ").\n");
else if (connection instanceof NotAllowed)
transactionSB.append("not_allowed"
+ "('" + fileName + "', " + mDependencyCounter + ", "
+ getDependencyEnsembleName(source) + ", [], "
+ getDependencyEnsembleName(target) + ", [], " + connection.getName() + ").\n");
else if (connection instanceof InAndOut)
{
transactionSB.append("incoming"
+ "('" + fileName + "', " + mDependencyCounter + ", "
+ getDependencyEnsembleName(source) + ", [], "
+ getDependencyEnsembleName(target) + ", [], " + connection.getName() + ").\n");
transactionSB.append("outgoing"
+ "('" + fileName + "', " + mDependencyCounter + ", "
+ getDependencyEnsembleName(source) + ", [], "
+ getDependencyEnsembleName(target) + ", [], " + connection.getName() + ").\n");
}
mDependencyCounter++;
return transactionSB.toString();
}
/**
* returns the right name of an ensemble (empty or x)
* @param Shape
* @return name of the ensemble
* @author Patrick Jahnke
*/
private String getDependencyEnsembleName(Shape shape)
{
if (shape instanceof Ensemble)
return this.getEnsembleDescriptor(shape);
else if (shape instanceof Dummy)
return "empty";
return "not_defined";
}
/**
* create a string with all subensembles of a parent.
* @param EList<Shape>
* @author Patrick Jahnke
*/
private String listSubEnsembles(EList<Shape> shapeList)
{
StringBuilder strBuilder = new StringBuilder();
if (shapeList == null)
return strBuilder.toString();
String komma = "";
for (Shape shape : shapeList)
{
if (shape instanceof Dummy)
strBuilder.append(komma + "'empty'");
else if (shape instanceof Ensemble)
strBuilder.append(komma + "'" + shape.getName() + "'");
komma = ", ";
}
return strBuilder.toString();
}
}
| false | true | private String createDependencyFact(Connection connection, String fileName) throws Exception
{
Shape source = null;
Shape target = null;
// Get the original source (and not the red line source)
if ((connection.getOriginalSource()==null)
|| (connection.getOriginalSource().size()==0))
source = connection.getSource();
else if ((connection.getOriginalSource()!=null)
&& (connection.getOriginalSource().size()==1))
source = connection.getOriginalSource().get(0);
else
throw new Exception ("Too many original sources in connection available. Please check the the original sources of connection: \""+connection.getName()+"\"");
// Get the original target (and not the red line target)
if ((connection.getOriginalTarget()==null)
|| (connection.getOriginalTarget().size()==0))
source = connection.getTarget();
else if ((connection.getOriginalTarget()!=null)
&& (connection.getOriginalTarget().size()==1))
source = connection.getOriginalTarget().get(0);
else
throw new Exception ("Too many original tagets in connection available. Please check the the original targets of connection: \""+connection.getName()+"\"");
StringBuilder transactionSB = new StringBuilder();
//TODO: delete next 2 lines if saved sad file doesn't
//contains copy/paste artifact references. Problem: if one copy from one sad file
// an Ensemble with dependency in another sad file than the copy of
// the Ensemble will contains a reference to original Ensemble in first saf file.
// This reference has no influence on working process but it has problem here,
// by converting to prolog facts
if(connection.getSource().eIsProxy() || connection.getTarget().eIsProxy())
return "";
if (connection instanceof Outgoing)
transactionSB.append("outgoing"
+ "('" + fileName + "', " + mDependencyCounter + ", "
+ getDependencyEnsembleName(source) + ", [], "
+ getDependencyEnsembleName(target) + ", [], " + connection.getName() + ").\n");
else if (connection instanceof Incoming)
transactionSB.append("incoming"
+ "('" + fileName + "', " + mDependencyCounter + ", "
+ getDependencyEnsembleName(source) + ", [], "
+ getDependencyEnsembleName(target) + ", [], " + connection.getName() + ").\n");
else if (connection instanceof Expected)
transactionSB.append("expected"
+ "('" + fileName + "', " + mDependencyCounter + ", "
+ getDependencyEnsembleName(source) + ", [], "
+ getDependencyEnsembleName(target) + ", [], " + connection.getName() + ").\n");
else if (connection instanceof NotAllowed)
transactionSB.append("not_allowed"
+ "('" + fileName + "', " + mDependencyCounter + ", "
+ getDependencyEnsembleName(source) + ", [], "
+ getDependencyEnsembleName(target) + ", [], " + connection.getName() + ").\n");
else if (connection instanceof InAndOut)
{
transactionSB.append("incoming"
+ "('" + fileName + "', " + mDependencyCounter + ", "
+ getDependencyEnsembleName(source) + ", [], "
+ getDependencyEnsembleName(target) + ", [], " + connection.getName() + ").\n");
transactionSB.append("outgoing"
+ "('" + fileName + "', " + mDependencyCounter + ", "
+ getDependencyEnsembleName(source) + ", [], "
+ getDependencyEnsembleName(target) + ", [], " + connection.getName() + ").\n");
}
mDependencyCounter++;
return transactionSB.toString();
}
| private String createDependencyFact(Connection connection, String fileName) throws Exception
{
Shape source = null;
Shape target = null;
// Get the original source (and not the red line source)
if ((connection.getOriginalSource()==null)
|| (connection.getOriginalSource().size()==0))
source = connection.getSource();
else if ((connection.getOriginalSource()!=null)
&& (connection.getOriginalSource().size()==1))
source = connection.getOriginalSource().get(0);
else
throw new Exception ("Too many original sources in connection available. Please check the the original sources of connection: \""+connection.getName()+"\"");
// Get the original target (and not the red line target)
if ((connection.getOriginalTarget()==null)
|| (connection.getOriginalTarget().size()==0))
target = connection.getTarget();
else if ((connection.getOriginalTarget()!=null)
&& (connection.getOriginalTarget().size()==1))
target = connection.getOriginalTarget().get(0);
else
throw new Exception ("Too many original tagets in connection available. Please check the the original targets of connection: \""+connection.getName()+"\"");
StringBuilder transactionSB = new StringBuilder();
//TODO: delete next 2 lines if saved sad file doesn't
//contains copy/paste artifact references. Problem: if one copy from one sad file
// an Ensemble with dependency in another sad file than the copy of
// the Ensemble will contains a reference to original Ensemble in first saf file.
// This reference has no influence on working process but it has problem here,
// by converting to prolog facts
if(connection.getSource().eIsProxy() || connection.getTarget().eIsProxy())
return "";
if (connection instanceof Outgoing)
transactionSB.append("outgoing"
+ "('" + fileName + "', " + mDependencyCounter + ", "
+ getDependencyEnsembleName(source) + ", [], "
+ getDependencyEnsembleName(target) + ", [], " + connection.getName() + ").\n");
else if (connection instanceof Incoming)
transactionSB.append("incoming"
+ "('" + fileName + "', " + mDependencyCounter + ", "
+ getDependencyEnsembleName(source) + ", [], "
+ getDependencyEnsembleName(target) + ", [], " + connection.getName() + ").\n");
else if (connection instanceof Expected)
transactionSB.append("expected"
+ "('" + fileName + "', " + mDependencyCounter + ", "
+ getDependencyEnsembleName(source) + ", [], "
+ getDependencyEnsembleName(target) + ", [], " + connection.getName() + ").\n");
else if (connection instanceof NotAllowed)
transactionSB.append("not_allowed"
+ "('" + fileName + "', " + mDependencyCounter + ", "
+ getDependencyEnsembleName(source) + ", [], "
+ getDependencyEnsembleName(target) + ", [], " + connection.getName() + ").\n");
else if (connection instanceof InAndOut)
{
transactionSB.append("incoming"
+ "('" + fileName + "', " + mDependencyCounter + ", "
+ getDependencyEnsembleName(source) + ", [], "
+ getDependencyEnsembleName(target) + ", [], " + connection.getName() + ").\n");
transactionSB.append("outgoing"
+ "('" + fileName + "', " + mDependencyCounter + ", "
+ getDependencyEnsembleName(source) + ", [], "
+ getDependencyEnsembleName(target) + ", [], " + connection.getName() + ").\n");
}
mDependencyCounter++;
return transactionSB.toString();
}
|
diff --git a/src/java/org/apache/fop/layoutmgr/FlowLayoutManager.java b/src/java/org/apache/fop/layoutmgr/FlowLayoutManager.java
index 597032848..9c05d2ee7 100644
--- a/src/java/org/apache/fop/layoutmgr/FlowLayoutManager.java
+++ b/src/java/org/apache/fop/layoutmgr/FlowLayoutManager.java
@@ -1,354 +1,357 @@
/*
* 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.
*/
/* $Id$ */
package org.apache.fop.layoutmgr;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.fop.area.Area;
import org.apache.fop.area.BlockParent;
import org.apache.fop.fo.pagination.Flow;
import org.apache.fop.layoutmgr.inline.InlineLevelLayoutManager;
import org.apache.fop.layoutmgr.inline.WrapperLayoutManager;
/**
* LayoutManager for an fo:flow object.
* Its parent LM is the PageSequenceLayoutManager.
* This LM is responsible for getting columns of the appropriate size
* and filling them with block-level areas generated by its children.
* @todo Reintroduce emergency counter (generate error to avoid endless loop)
*/
public class FlowLayoutManager extends BlockStackingLayoutManager
implements BlockLevelLayoutManager {
/**
* logging instance
*/
private static Log log = LogFactory.getLog(FlowLayoutManager.class);
/** Array of areas currently being filled stored by area class */
private BlockParent[] currentAreas = new BlockParent[Area.CLASS_MAX];
/**
* This is the top level layout manager.
* It is created by the PageSequence FO.
* @param pslm parent PageSequenceLayoutManager object
* @param node Flow object
*/
public FlowLayoutManager(PageSequenceLayoutManager pslm, Flow node) {
super(node);
setParent(pslm);
}
/** {@inheritDoc} */
public List getNextKnuthElements(LayoutContext context, int alignment) {
// set layout dimensions
int flowIPD = getCurrentPV().getCurrentSpan().getColumnWidth();
int flowBPD = getCurrentPV().getBodyRegion().getBPD();
// currently active LM
LayoutManager curLM;
List returnedList;
List returnList = new LinkedList();
while ((curLM = getChildLM()) != null) {
if (!(curLM instanceof WrapperLayoutManager)
&& curLM instanceof InlineLevelLayoutManager) {
log.error("inline area not allowed under flow - ignoring");
curLM.setFinished(true);
continue;
}
int span = EN_NONE;
int disableColumnBalancing = EN_FALSE;
if (curLM instanceof BlockLayoutManager) {
- span = ((BlockLayoutManager)curLM).getSpan();
- disableColumnBalancing = ((BlockLayoutManager) curLM).getDisableColumnBalancing();
+ span = ((BlockLayoutManager)curLM).getBlockFO().getSpan();
+ disableColumnBalancing = ((BlockLayoutManager) curLM).getBlockContainerFO()
+ .getDisableColumnBalancing();
} else if (curLM instanceof BlockContainerLayoutManager) {
- span = ((BlockContainerLayoutManager)curLM).getSpan();
- disableColumnBalancing = ((BlockContainerLayoutManager) curLM).getDisableColumnBalancing();
+ span = ((BlockContainerLayoutManager)curLM).getBlockFO()
+ .getSpan();
+ disableColumnBalancing = ((BlockContainerLayoutManager) curLM).getBlockContainerFO()
+ .getDisableColumnBalancing();
}
int currentSpan = context.getCurrentSpan();
if (currentSpan != span) {
if (span == EN_ALL) {
context.setDisableColumnBalancing(disableColumnBalancing);
}
log.debug("span change from " + currentSpan + " to " + span);
context.signalSpanChange(span);
SpaceResolver.resolveElementList(returnList);
return returnList;
}
// Set up a LayoutContext
//MinOptMax bpd = context.getStackLimit();
LayoutContext childLC = new LayoutContext(0);
childLC.setStackLimitBP(context.getStackLimitBP());
childLC.setRefIPD(context.getRefIPD());
childLC.setWritingMode(getCurrentPage().getSimplePageMaster().getWritingMode());
// get elements from curLM
returnedList = curLM.getNextKnuthElements(childLC, alignment);
//log.debug("FLM.getNextKnuthElements> returnedList.size() = " + returnedList.size());
if (returnList.size() == 0 && childLC.isKeepWithPreviousPending()) {
context.updateKeepWithPreviousPending(childLC.getKeepWithPreviousPending());
childLC.clearKeepWithPreviousPending();
}
// "wrap" the Position inside each element
List tempList = returnedList;
returnedList = new LinkedList();
wrapPositionElements(tempList, returnedList);
if (returnedList.size() == 1
&& ElementListUtils.endsWithForcedBreak(returnedList)) {
// a descendant of this flow has break-before
returnList.addAll(returnedList);
SpaceResolver.resolveElementList(returnList);
return returnList;
} else if (returnedList.size() > 0) {
if (returnList.size() > 0
&& !ElementListUtils.startsWithForcedBreak(returnedList)) {
addInBetweenBreak(returnList, context, childLC);
}
returnList.addAll(returnedList);
if (ElementListUtils.endsWithForcedBreak(returnList)) {
if (curLM.isFinished() && !hasNextChildLM()) {
//If the layout manager is finished at this point, the pending
//marks become irrelevant.
childLC.clearPendingMarks();
//setFinished(true);
break;
}
// a descendant of this flow has break-after
SpaceResolver.resolveElementList(returnList);
return returnList;
}
}
//Propagate and clear
context.updateKeepWithNextPending(childLC.getKeepWithNextPending());
childLC.clearKeepWithNextPending();
context.updateKeepWithNextPending(getKeepWithNextStrength());
}
SpaceResolver.resolveElementList(returnList);
setFinished(true);
if (returnList.size() > 0) {
return returnList;
} else {
return null;
}
}
/**
* {@inheritDoc}
*/
public int negotiateBPDAdjustment(int adj, KnuthElement lastElement) {
log.debug(" FLM.negotiateBPDAdjustment> " + adj);
if (lastElement.getPosition() instanceof NonLeafPosition) {
// this element was not created by this FlowLM
NonLeafPosition savedPos = (NonLeafPosition)lastElement.getPosition();
lastElement.setPosition(savedPos.getPosition());
int returnValue = ((BlockLevelLayoutManager)lastElement.getLayoutManager())
.negotiateBPDAdjustment(adj, lastElement);
lastElement.setPosition(savedPos);
log.debug(" FLM.negotiateBPDAdjustment> result " + returnValue);
return returnValue;
} else {
return 0;
}
}
/**
* {@inheritDoc}
*/
public void discardSpace(KnuthGlue spaceGlue) {
log.debug(" FLM.discardSpace> ");
if (spaceGlue.getPosition() instanceof NonLeafPosition) {
// this element was not created by this FlowLM
NonLeafPosition savedPos = (NonLeafPosition)spaceGlue.getPosition();
spaceGlue.setPosition(savedPos.getPosition());
((BlockLevelLayoutManager) spaceGlue.getLayoutManager()).discardSpace(spaceGlue);
spaceGlue.setPosition(savedPos);
}
}
/** {@inheritDoc} */
public int getKeepTogetherStrength() {
return KEEP_AUTO;
}
/** {@inheritDoc} */
public int getKeepWithNextStrength() {
return KEEP_AUTO;
}
/** {@inheritDoc} */
public int getKeepWithPreviousStrength() {
return KEEP_AUTO;
}
/** {@inheritDoc} */
public List getChangedKnuthElements(List oldList, /*int flaggedPenalty,*/ int alignment) {
ListIterator oldListIterator = oldList.listIterator();
KnuthElement returnedElement;
List returnedList = new LinkedList();
List returnList = new LinkedList();
KnuthElement prevElement = null;
KnuthElement currElement = null;
int fromIndex = 0;
// "unwrap" the Positions stored in the elements
KnuthElement oldElement;
while (oldListIterator.hasNext()) {
oldElement = (KnuthElement)oldListIterator.next();
if (oldElement.getPosition() instanceof NonLeafPosition) {
// oldElement was created by a descendant of this FlowLM
oldElement.setPosition((oldElement.getPosition()).getPosition());
} else {
// thisElement was created by this FlowLM, remove it
oldListIterator.remove();
}
}
// reset the iterator
oldListIterator = oldList.listIterator();
while (oldListIterator.hasNext()) {
currElement = (KnuthElement) oldListIterator.next();
if (prevElement != null
&& prevElement.getLayoutManager() != currElement.getLayoutManager()) {
// prevElement is the last element generated by the same LM
BlockLevelLayoutManager prevLM = (BlockLevelLayoutManager)
prevElement.getLayoutManager();
BlockLevelLayoutManager currLM = (BlockLevelLayoutManager)
currElement.getLayoutManager();
returnedList.addAll(prevLM.getChangedKnuthElements(
oldList.subList(fromIndex, oldListIterator.previousIndex()), alignment));
fromIndex = oldListIterator.previousIndex();
// there is another block after this one
if (prevLM.mustKeepWithNext()
|| currLM.mustKeepWithPrevious()) {
// add an infinite penalty to forbid a break between blocks
returnedList.add(new KnuthPenalty(0, KnuthElement.INFINITE, false,
new Position(this), false));
} else if (!((KnuthElement) returnedList.get(returnedList
.size() - 1)).isGlue()) {
// add a null penalty to allow a break between blocks
returnedList.add(new KnuthPenalty(0, 0, false, new Position(this), false));
}
}
prevElement = currElement;
}
if (currElement != null) {
BlockLevelLayoutManager currLM = (BlockLevelLayoutManager)
currElement.getLayoutManager();
returnedList.addAll(currLM.getChangedKnuthElements(
oldList.subList(fromIndex, oldList.size()), alignment));
}
// "wrap" the Position stored in each element of returnedList
// and add elements to returnList
ListIterator listIter = returnedList.listIterator();
while (listIter.hasNext()) {
returnedElement = (KnuthElement)listIter.next();
if (returnedElement.getLayoutManager() != this) {
returnedElement.setPosition(
new NonLeafPosition(this, returnedElement.getPosition()));
}
returnList.add(returnedElement);
}
return returnList;
}
/**
* {@inheritDoc}
*/
public void addAreas(PositionIterator parentIter, LayoutContext layoutContext) {
AreaAdditionUtil.addAreas(this, parentIter, layoutContext);
flush();
}
/**
* Add child area to a the correct container, depending on its
* area class. A Flow can fill at most one area container of any class
* at any one time. The actual work is done by BlockStackingLM.
*
* @param childArea the area to add
*/
public void addChildArea(Area childArea) {
getParentArea(childArea);
addChildToArea(childArea,
this.currentAreas[childArea.getAreaClass()]);
}
/**
* {@inheritDoc}
*/
public Area getParentArea(Area childArea) {
BlockParent parentArea = null;
int aclass = childArea.getAreaClass();
if (aclass == Area.CLASS_NORMAL) {
parentArea = getCurrentPV().getCurrentFlow();
} else if (aclass == Area.CLASS_BEFORE_FLOAT) {
parentArea = getCurrentPV().getBodyRegion().getBeforeFloat();
} else if (aclass == Area.CLASS_FOOTNOTE) {
parentArea = getCurrentPV().getBodyRegion().getFootnote();
} else {
throw new IllegalStateException("(internal error) Invalid "
+ "area class (" + aclass + ") requested.");
}
this.currentAreas[aclass] = parentArea;
setCurrentArea(parentArea);
return parentArea;
}
/**
* Returns the IPD of the content area
* @return the IPD of the content area
*/
public int getContentAreaIPD() {
return getCurrentPV().getCurrentSpan().getColumnWidth();
}
/**
* Returns the BPD of the content area
* @return the BPD of the content area
*/
public int getContentAreaBPD() {
return getCurrentPV().getBodyRegion().getBPD();
}
}
| false | true | public List getNextKnuthElements(LayoutContext context, int alignment) {
// set layout dimensions
int flowIPD = getCurrentPV().getCurrentSpan().getColumnWidth();
int flowBPD = getCurrentPV().getBodyRegion().getBPD();
// currently active LM
LayoutManager curLM;
List returnedList;
List returnList = new LinkedList();
while ((curLM = getChildLM()) != null) {
if (!(curLM instanceof WrapperLayoutManager)
&& curLM instanceof InlineLevelLayoutManager) {
log.error("inline area not allowed under flow - ignoring");
curLM.setFinished(true);
continue;
}
int span = EN_NONE;
int disableColumnBalancing = EN_FALSE;
if (curLM instanceof BlockLayoutManager) {
span = ((BlockLayoutManager)curLM).getSpan();
disableColumnBalancing = ((BlockLayoutManager) curLM).getDisableColumnBalancing();
} else if (curLM instanceof BlockContainerLayoutManager) {
span = ((BlockContainerLayoutManager)curLM).getSpan();
disableColumnBalancing = ((BlockContainerLayoutManager) curLM).getDisableColumnBalancing();
}
int currentSpan = context.getCurrentSpan();
if (currentSpan != span) {
if (span == EN_ALL) {
context.setDisableColumnBalancing(disableColumnBalancing);
}
log.debug("span change from " + currentSpan + " to " + span);
context.signalSpanChange(span);
SpaceResolver.resolveElementList(returnList);
return returnList;
}
// Set up a LayoutContext
//MinOptMax bpd = context.getStackLimit();
LayoutContext childLC = new LayoutContext(0);
childLC.setStackLimitBP(context.getStackLimitBP());
childLC.setRefIPD(context.getRefIPD());
childLC.setWritingMode(getCurrentPage().getSimplePageMaster().getWritingMode());
// get elements from curLM
returnedList = curLM.getNextKnuthElements(childLC, alignment);
//log.debug("FLM.getNextKnuthElements> returnedList.size() = " + returnedList.size());
if (returnList.size() == 0 && childLC.isKeepWithPreviousPending()) {
context.updateKeepWithPreviousPending(childLC.getKeepWithPreviousPending());
childLC.clearKeepWithPreviousPending();
}
// "wrap" the Position inside each element
List tempList = returnedList;
returnedList = new LinkedList();
wrapPositionElements(tempList, returnedList);
if (returnedList.size() == 1
&& ElementListUtils.endsWithForcedBreak(returnedList)) {
// a descendant of this flow has break-before
returnList.addAll(returnedList);
SpaceResolver.resolveElementList(returnList);
return returnList;
} else if (returnedList.size() > 0) {
if (returnList.size() > 0
&& !ElementListUtils.startsWithForcedBreak(returnedList)) {
addInBetweenBreak(returnList, context, childLC);
}
returnList.addAll(returnedList);
if (ElementListUtils.endsWithForcedBreak(returnList)) {
if (curLM.isFinished() && !hasNextChildLM()) {
//If the layout manager is finished at this point, the pending
//marks become irrelevant.
childLC.clearPendingMarks();
//setFinished(true);
break;
}
// a descendant of this flow has break-after
SpaceResolver.resolveElementList(returnList);
return returnList;
}
}
//Propagate and clear
context.updateKeepWithNextPending(childLC.getKeepWithNextPending());
childLC.clearKeepWithNextPending();
context.updateKeepWithNextPending(getKeepWithNextStrength());
}
SpaceResolver.resolveElementList(returnList);
setFinished(true);
if (returnList.size() > 0) {
return returnList;
} else {
return null;
}
}
| public List getNextKnuthElements(LayoutContext context, int alignment) {
// set layout dimensions
int flowIPD = getCurrentPV().getCurrentSpan().getColumnWidth();
int flowBPD = getCurrentPV().getBodyRegion().getBPD();
// currently active LM
LayoutManager curLM;
List returnedList;
List returnList = new LinkedList();
while ((curLM = getChildLM()) != null) {
if (!(curLM instanceof WrapperLayoutManager)
&& curLM instanceof InlineLevelLayoutManager) {
log.error("inline area not allowed under flow - ignoring");
curLM.setFinished(true);
continue;
}
int span = EN_NONE;
int disableColumnBalancing = EN_FALSE;
if (curLM instanceof BlockLayoutManager) {
span = ((BlockLayoutManager)curLM).getBlockFO().getSpan();
disableColumnBalancing = ((BlockLayoutManager) curLM).getBlockContainerFO()
.getDisableColumnBalancing();
} else if (curLM instanceof BlockContainerLayoutManager) {
span = ((BlockContainerLayoutManager)curLM).getBlockFO()
.getSpan();
disableColumnBalancing = ((BlockContainerLayoutManager) curLM).getBlockContainerFO()
.getDisableColumnBalancing();
}
int currentSpan = context.getCurrentSpan();
if (currentSpan != span) {
if (span == EN_ALL) {
context.setDisableColumnBalancing(disableColumnBalancing);
}
log.debug("span change from " + currentSpan + " to " + span);
context.signalSpanChange(span);
SpaceResolver.resolveElementList(returnList);
return returnList;
}
// Set up a LayoutContext
//MinOptMax bpd = context.getStackLimit();
LayoutContext childLC = new LayoutContext(0);
childLC.setStackLimitBP(context.getStackLimitBP());
childLC.setRefIPD(context.getRefIPD());
childLC.setWritingMode(getCurrentPage().getSimplePageMaster().getWritingMode());
// get elements from curLM
returnedList = curLM.getNextKnuthElements(childLC, alignment);
//log.debug("FLM.getNextKnuthElements> returnedList.size() = " + returnedList.size());
if (returnList.size() == 0 && childLC.isKeepWithPreviousPending()) {
context.updateKeepWithPreviousPending(childLC.getKeepWithPreviousPending());
childLC.clearKeepWithPreviousPending();
}
// "wrap" the Position inside each element
List tempList = returnedList;
returnedList = new LinkedList();
wrapPositionElements(tempList, returnedList);
if (returnedList.size() == 1
&& ElementListUtils.endsWithForcedBreak(returnedList)) {
// a descendant of this flow has break-before
returnList.addAll(returnedList);
SpaceResolver.resolveElementList(returnList);
return returnList;
} else if (returnedList.size() > 0) {
if (returnList.size() > 0
&& !ElementListUtils.startsWithForcedBreak(returnedList)) {
addInBetweenBreak(returnList, context, childLC);
}
returnList.addAll(returnedList);
if (ElementListUtils.endsWithForcedBreak(returnList)) {
if (curLM.isFinished() && !hasNextChildLM()) {
//If the layout manager is finished at this point, the pending
//marks become irrelevant.
childLC.clearPendingMarks();
//setFinished(true);
break;
}
// a descendant of this flow has break-after
SpaceResolver.resolveElementList(returnList);
return returnList;
}
}
//Propagate and clear
context.updateKeepWithNextPending(childLC.getKeepWithNextPending());
childLC.clearKeepWithNextPending();
context.updateKeepWithNextPending(getKeepWithNextStrength());
}
SpaceResolver.resolveElementList(returnList);
setFinished(true);
if (returnList.size() > 0) {
return returnList;
} else {
return null;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.