diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/spring-datastore-mongodb/src/main/java/org/springframework/datastore/document/mongodb/MongoDbUtils.java b/spring-datastore-mongodb/src/main/java/org/springframework/datastore/document/mongodb/MongoDbUtils.java
index 5d32f70a4..1d47cec20 100644
--- a/spring-datastore-mongodb/src/main/java/org/springframework/datastore/document/mongodb/MongoDbUtils.java
+++ b/spring-datastore-mongodb/src/main/java/org/springframework/datastore/document/mongodb/MongoDbUtils.java
@@ -1,168 +1,168 @@
/*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.datastore.document.mongodb;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.datastore.document.UncategorizedDocumentStoreException;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.Assert;
import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.MongoException.DuplicateKey;
import com.mongodb.MongoException.Network;
/**
* Helper class featuring helper methods for internal MongoDb classes.
*
* <p>Mainly intended for internal use within the framework.
*
* @author Thomas Risberg
* @author Graeme Rocher
*
* @since 1.0
*/
public class MongoDbUtils {
static final Log logger = LogFactory.getLog(MongoDbUtils.class);
/**
* Convert the given runtime exception to an appropriate exception from the
* <code>org.springframework.dao</code> hierarchy.
* Return null if no translation is appropriate: any other exception may
* have resulted from user code, and should not be translated.
* @param ex runtime exception that occurred
* @return the corresponding DataAccessException instance,
* or <code>null</code> if the exception should not be translated
*/
public static DataAccessException translateMongoExceptionIfPossible(RuntimeException ex) {
// Check for well-known MongoException subclasses.
// All other MongoExceptions
if(ex instanceof DuplicateKey) {
return new DataIntegrityViolationException(ex.getMessage(),ex);
}
if(ex instanceof Network) {
return new DataAccessResourceFailureException(ex.getMessage(), ex);
}
if (ex instanceof MongoException) {
return new UncategorizedDocumentStoreException(ex.getMessage(), ex);
}
// If we get here, we have an exception that resulted from user code,
// rather than the persistence provider, so we return null to indicate
// that translation should not occur.
return null;
}
public static DB getDB(Mongo mongo, String databaseName) {
return doGetDB(mongo, databaseName, true);
}
public static DB doGetDB(Mongo mongo, String databaseName, boolean allowCreate) {
Assert.notNull(mongo, "No Mongo instance specified");
DBHolder dbHolder = (DBHolder) TransactionSynchronizationManager.getResource(mongo);
if (dbHolder != null && !dbHolder.isEmpty()) {
// pre-bound Mongo DB
DB db = null;
if (TransactionSynchronizationManager.isSynchronizationActive() &&
dbHolder.doesNotHoldNonDefaultDB()) {
// Spring transaction management is active ->
db = dbHolder.getDB();
if (db != null && !dbHolder.isSynchronizedWithTransaction()) {
logger.debug("Registering Spring transaction synchronization for existing Mongo DB");
TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(dbHolder, mongo));
dbHolder.setSynchronizedWithTransaction(true);
}
}
if (db != null) {
return db;
}
}
logger.debug("Opening Mongo DB");
DB db = mongo.getDB(databaseName);
// Use same Session for further Mongo actions within the transaction.
// Thread object will get removed by synchronization at transaction completion.
if (TransactionSynchronizationManager.isSynchronizationActive()) {
// We're within a Spring-managed transaction, possibly from JtaTransactionManager.
logger.debug("Registering Spring transaction synchronization for new Hibernate Session");
DBHolder holderToUse = dbHolder;
if (holderToUse == null) {
holderToUse = new DBHolder(db);
}
else {
holderToUse.addDB(db);
}
- TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(dbHolder, mongo));
+ TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(holderToUse, mongo));
holderToUse.setSynchronizedWithTransaction(true);
if (holderToUse != dbHolder) {
TransactionSynchronizationManager.bindResource(mongo, holderToUse);
}
}
// Check whether we are allowed to return the DB.
if (!allowCreate && !isDBTransactional(db, mongo)) {
throw new IllegalStateException("No Mongo DB bound to thread, " +
"and configuration does not allow creation of non-transactional one here");
}
return db;
}
/**
* Return whether the given DB instance is transactional, that is,
* bound to the current thread by Spring's transaction facilities.
* @param db the DB to check
* @param mongo the Mongo instance that the DB was created with
* (may be <code>null</code>)
* @return whether the DB is transactional
*/
public static boolean isDBTransactional(DB db, Mongo mongo) {
if (mongo == null) {
return false;
}
DBHolder dbHolder =
(DBHolder) TransactionSynchronizationManager.getResource(mongo);
return (dbHolder != null && dbHolder.containsDB(db));
}
/**
* Perform actual closing of the Mongo DB object,
* catching and logging any cleanup exceptions thrown.
* @param db the DB to close (may be <code>null</code>)
*/
public static void closeDB(DB db) {
if (db != null) {
logger.debug("Closing Mongo DB object");
try {
db.requestDone();
}
catch (Throwable ex) {
logger.debug("Unexpected exception on closing Mongo DB object", ex);
}
}
}
}
| true | true | public static DB doGetDB(Mongo mongo, String databaseName, boolean allowCreate) {
Assert.notNull(mongo, "No Mongo instance specified");
DBHolder dbHolder = (DBHolder) TransactionSynchronizationManager.getResource(mongo);
if (dbHolder != null && !dbHolder.isEmpty()) {
// pre-bound Mongo DB
DB db = null;
if (TransactionSynchronizationManager.isSynchronizationActive() &&
dbHolder.doesNotHoldNonDefaultDB()) {
// Spring transaction management is active ->
db = dbHolder.getDB();
if (db != null && !dbHolder.isSynchronizedWithTransaction()) {
logger.debug("Registering Spring transaction synchronization for existing Mongo DB");
TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(dbHolder, mongo));
dbHolder.setSynchronizedWithTransaction(true);
}
}
if (db != null) {
return db;
}
}
logger.debug("Opening Mongo DB");
DB db = mongo.getDB(databaseName);
// Use same Session for further Mongo actions within the transaction.
// Thread object will get removed by synchronization at transaction completion.
if (TransactionSynchronizationManager.isSynchronizationActive()) {
// We're within a Spring-managed transaction, possibly from JtaTransactionManager.
logger.debug("Registering Spring transaction synchronization for new Hibernate Session");
DBHolder holderToUse = dbHolder;
if (holderToUse == null) {
holderToUse = new DBHolder(db);
}
else {
holderToUse.addDB(db);
}
TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(dbHolder, mongo));
holderToUse.setSynchronizedWithTransaction(true);
if (holderToUse != dbHolder) {
TransactionSynchronizationManager.bindResource(mongo, holderToUse);
}
}
// Check whether we are allowed to return the DB.
if (!allowCreate && !isDBTransactional(db, mongo)) {
throw new IllegalStateException("No Mongo DB bound to thread, " +
"and configuration does not allow creation of non-transactional one here");
}
return db;
}
| public static DB doGetDB(Mongo mongo, String databaseName, boolean allowCreate) {
Assert.notNull(mongo, "No Mongo instance specified");
DBHolder dbHolder = (DBHolder) TransactionSynchronizationManager.getResource(mongo);
if (dbHolder != null && !dbHolder.isEmpty()) {
// pre-bound Mongo DB
DB db = null;
if (TransactionSynchronizationManager.isSynchronizationActive() &&
dbHolder.doesNotHoldNonDefaultDB()) {
// Spring transaction management is active ->
db = dbHolder.getDB();
if (db != null && !dbHolder.isSynchronizedWithTransaction()) {
logger.debug("Registering Spring transaction synchronization for existing Mongo DB");
TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(dbHolder, mongo));
dbHolder.setSynchronizedWithTransaction(true);
}
}
if (db != null) {
return db;
}
}
logger.debug("Opening Mongo DB");
DB db = mongo.getDB(databaseName);
// Use same Session for further Mongo actions within the transaction.
// Thread object will get removed by synchronization at transaction completion.
if (TransactionSynchronizationManager.isSynchronizationActive()) {
// We're within a Spring-managed transaction, possibly from JtaTransactionManager.
logger.debug("Registering Spring transaction synchronization for new Hibernate Session");
DBHolder holderToUse = dbHolder;
if (holderToUse == null) {
holderToUse = new DBHolder(db);
}
else {
holderToUse.addDB(db);
}
TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(holderToUse, mongo));
holderToUse.setSynchronizedWithTransaction(true);
if (holderToUse != dbHolder) {
TransactionSynchronizationManager.bindResource(mongo, holderToUse);
}
}
// Check whether we are allowed to return the DB.
if (!allowCreate && !isDBTransactional(db, mongo)) {
throw new IllegalStateException("No Mongo DB bound to thread, " +
"and configuration does not allow creation of non-transactional one here");
}
return db;
}
|
diff --git a/core/src/org/icepdf/core/pobjects/Stream.java b/core/src/org/icepdf/core/pobjects/Stream.java
index b9fa67a8..c0c9fa97 100644
--- a/core/src/org/icepdf/core/pobjects/Stream.java
+++ b/core/src/org/icepdf/core/pobjects/Stream.java
@@ -1,3136 +1,3137 @@
/*
* Copyright 2006-2012 ICEsoft Technologies Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.icepdf.core.pobjects;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;
import org.icepdf.core.io.BitStream;
import org.icepdf.core.io.ConservativeSizingByteArrayOutputStream;
import org.icepdf.core.io.SeekableInputConstrainedWrapper;
import org.icepdf.core.pobjects.filters.*;
import org.icepdf.core.pobjects.functions.Function;
import org.icepdf.core.pobjects.graphics.*;
import org.icepdf.core.tag.Tagger;
import org.icepdf.core.util.Defs;
import org.icepdf.core.util.ImageCache;
import org.icepdf.core.util.Library;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.*;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.image.*;
import java.awt.image.renderable.ParameterBlock;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The Stream class is responsible for decoding stream contents and returning
* either an images object or a byte array depending on the content. The Stream
* object worker method is decode which is responsible for decoding the content
* stream, which is if the first step of the rendering process. Once a Stream
* is decoded it is either returned as an image object or a byte array that is
* then processed further by the ContentParser.
*
* @since 1.0
*/
public class Stream extends Dictionary {
private static final Logger logger =
Logger.getLogger(Stream.class.toString());
// original byte stream that has not been decoded
private SeekableInputConstrainedWrapper streamInput;
// Images object created from stream
private ImageCache image = null;
private final Object imageLock = new Object();
// reference of stream, needed for encryption support
private Reference pObjectReference = null;
// Inline image, from a content stream
private boolean inlineImage;
// minimum dimension which will enable image scaling
private static boolean scaleImages;
// paper size for rare corner case when ccittfax is missing a dimension.
private static double pageRatio;
// JDK 1.5 imaging order flag and b/r switch
private static int redIndex = 0;
private static int blueIndex = 2;
static {
// decide if large images will be scaled
scaleImages =
Defs.sysPropertyBoolean("org.icepdf.core.scaleImages",
true);
// sniff out jdk 1.5 version
String version = System.getProperty("java.version");
if (version.contains("1.5")){
redIndex = 2;
blueIndex = 0;
}
// define alternate page size ration w/h, default Legal.
pageRatio =
Defs.sysPropertyDouble("org.icepdf.core.pageRatio",
8.26/11.68);
}
private static final int[] GRAY_1_BIT_INDEX_TO_RGB_REVERSED = new int[]{
0xFFFFFFFF,
0xFF000000
};
private static final int[] GRAY_1_BIT_INDEX_TO_RGB = new int[]{
0xFF000000,
0xFFFFFFFF
};
private static final int[] GRAY_2_BIT_INDEX_TO_RGB = new int[]{
0xFF000000,
0xFF555555,
0xFFAAAAAA,
0xFFFFFFFF
}; // 0. 1 2 3 4 5. 6 7 8 9 A. B C D E F. 0/3, 1/3, 2/3, 3/3
private static final int[] GRAY_4_BIT_INDEX_TO_RGB = new int[]{
0xFF000000,
0xFF111111,
0xFF222222,
0xFF333333,
0xFF444444,
0xFF555555,
0xFF666666,
0xFF777777,
0xFF888888,
0xFF999999,
0xFFAAAAAA,
0xFFBBBBBB,
0xFFCCCCCC,
0xFFDDDDDD,
0xFFEEEEEE,
0xFFFFFFFF
};
private static final int JPEG_ENC_UNKNOWN_PROBABLY_YCbCr = 0;
private static final int JPEG_ENC_RGB = 1;
private static final int JPEG_ENC_CMYK = 2;
private static final int JPEG_ENC_YCbCr = 3;
private static final int JPEG_ENC_YCCK = 4;
private static final int JPEG_ENC_GRAY = 5;
private static String[] JPEG_ENC_NAMES = new String[]{
"JPEG_ENC_UNKNOWN_PROBABLY_YCbCr",
"JPEG_ENC_RGB",
"JPEG_ENC_CMYK",
"JPEG_ENC_YCbCr",
"JPEG_ENC_YCCK",
"JPEG_ENC_GRAY"
};
/**
* Create a new instance of a Stream.
*
* @param l library containing a hash of all document objects
* @param h hashtable of parameters specific to the Stream object.
* @param streamInputWrapper Accessor to stream byte data
*/
public Stream(Library l, Hashtable h, SeekableInputConstrainedWrapper streamInputWrapper) {
super(l, h);
streamInput = streamInputWrapper;
}
/**
* Sets the PObject referece for this stream. The reference number and
* generation is need by the encryption algorithm.
*/
public void setPObjectReference(Reference reference) {
pObjectReference = reference;
}
/**
* Gets the parent PObject reference for this stream.
*
* @return Reference number of parent PObject.
* @see #setPObjectReference(org.icepdf.core.pobjects.Reference)
*/
public Reference getPObjectReference() {
return pObjectReference;
}
/**
* Marks this stream as being constructed from an inline image
* definition in a content stream
*
* @param inlineImage true indicate inline image.
*/
public void setInlineImage(boolean inlineImage) {
this.inlineImage = inlineImage;
}
/**
* @return Whether this stream was constructed from an inline image
* definition in a content stream
*/
public boolean isInlineImage() {
return inlineImage;
}
boolean isImageSubtype() {
Object subtype = library.getObject(entries, "Subtype");
return subtype != null && subtype.equals("Image");
}
/**
* Utility Method to check if the <code>memoryNeeded</code> can be allocated,
* and if not, try and free up the needed amount of memory
*
* @param memoryNeeded amount of memory to check for availability.
* @return true if the request number of bytes are free.
*/
private boolean checkMemory(int memoryNeeded) {
return library.memoryManager.checkMemory(memoryNeeded);
}
/**
* Utility method for decoding the byte stream using the decode algorithem
* specified by the filter parameter
* <p/>
* The memory manger is called every time a stream is being decoded with an
* estimated size of the decoded stream. Because many of the Filter
* algorithms use compression, further research must be done to try and
* find the average amount of memory used by each of the algorithms.
*
* @return inputstream that has been decoded as defined by the streams filters.
*/
public InputStream getInputStreamForDecodedStreamBytes() {
// Make sure that the stream actually has data to decode, if it doesn't
// make it null and return.
if (streamInput == null || streamInput.getLength() < 1) {
return null;
}
long streamLength = streamInput.getLength();
int memoryNeeded = (int) streamLength;
checkMemory(memoryNeeded);
streamInput.prepareForCurrentUse();
InputStream input = streamInput;
int bufferSize = Math.min(Math.max((int) streamLength, 64), 16 * 1024);
input = new java.io.BufferedInputStream(input, bufferSize);
// Search for crypt dictionary entry and decode params so that
// named filters can be assigned correctly.
if (library.securityManager != null) {
// check see of there is a decodeParams for a crypt filter.
Hashtable decodeParams = library.getDictionary(entries,"DecodeParam");
input = library.getSecurityManager().getEncryptionInputStream(
getPObjectReference(), library.getSecurityManager().getDecryptionKey(),
decodeParams,
input, true);
}
// Get the filter name for the encoding type, which can be either
// a Name or Vector.
Vector filterNames = getFilterNames();
if (filterNames == null)
return input;
// Decode the stream data based on the filter names.
// Loop through the filterNames and apply the filters in the order
// in which they where found.
for (int i = 0; i < filterNames.size(); i++) {
// grab the name of the filter
String filterName = filterNames.elementAt(i).toString();
//System.out.println(" Decoding: " + filterName);
if (filterName.equals("FlateDecode")
|| filterName.equals("/Fl")
|| filterName.equals("Fl")) {
input = new FlateDecode(library, entries, input);
memoryNeeded *= 2;
} else if (
filterName.equals("LZWDecode")
|| filterName.equals("/LZW")
|| filterName.equals("LZW")) {
input = new LZWDecode(new BitStream(input), library, entries);
memoryNeeded *= 2;
} else if (
filterName.equals("ASCII85Decode")
|| filterName.equals("/A85")
|| filterName.equals("A85")) {
input = new ASCII85Decode(input);
memoryNeeded *= 2;
} else if (
filterName.equals("ASCIIHexDecode")
|| filterName.equals("/AHx")
|| filterName.equals("AHx")) {
input = new ASCIIHexDecode(input);
memoryNeeded /= 2;
} else if (
filterName.equals("RunLengthDecode")
|| filterName.equals("/RL")
|| filterName.equals("RL")) {
input = new RunLengthDecode(input);
memoryNeeded *= 2;
} else if (
filterName.equals("CCITTFaxDecode")
|| filterName.equals("/CCF")
|| filterName.equals("CCF")) {
// Leave empty so our else clause works
} else if (
filterName.equals("DCTDecode")
|| filterName.equals("/DCT")
|| filterName.equals("DCT")) {
// Leave empty so our else clause works
} else if ( // No short name, since no JBIG2 for inline images
filterName.equals("JBIG2Decode")) {
// Leave empty so our else clause works
} else if ( // No short name, since no JPX for inline images
filterName.equals("JPXDecode")) {
// Leave empty so our else clause works
} else {
if (logger.isLoggable(Level.FINE)) {
logger.fine("UNSUPPORTED:" + filterName + " " + entries);
}
}
}
checkMemory(memoryNeeded);
return input;
}
private byte[] getDecodedStreamBytes() {
InputStream input = getInputStreamForDecodedStreamBytes();
if (input == null)
return null;
try {
int outLength = Math.max(1024, (int) streamInput.getLength());
ConservativeSizingByteArrayOutputStream out = new
ConservativeSizingByteArrayOutputStream(outLength, library.memoryManager);
byte[] buffer = new byte[(outLength > 1024) ? 4096 : 1024];
while (true) {
int read = input.read(buffer);
if (read <= 0)
break;
out.write(buffer, 0, read);
}
out.flush();
out.close();
// removes this thread from current read, pottential entry for other thread
input.close();
byte[] ret = out.toByteArray();
return ret;
}
catch (IOException e) {
logger.log(Level.FINE, "Problem decoding stream bytes: ", e);
}
return null;
}
/**
* This is similar to getDecodedStreamBytes(), except that the returned byte[]
* is not necessarily exactly sized, and may be larger. Therefore the returned
* Integer gives the actual valid size
*
* @param presize potencial size to associate with byte array.
* @return Object[] { byte[] data, Integer sizeActualData }
*/
private Object[] getDecodedStreamBytesAndSize(int presize) {
InputStream input = getInputStreamForDecodedStreamBytes();
if (input == null)
return null;
try {
int outLength;
if (presize > 0)
outLength = presize;
else
outLength = Math.max(1024, (int) streamInput.getLength());
ConservativeSizingByteArrayOutputStream out = new
ConservativeSizingByteArrayOutputStream(outLength, library.memoryManager);
byte[] buffer = new byte[(outLength > 1024) ? 4096 : 1024];
while (true) {
int read = input.read(buffer);
if (read <= 0)
break;
out.write(buffer, 0, read);
}
out.flush();
out.close();
input.close();
int size = out.size();
boolean trimmed = out.trim();
byte[] data = out.relinquishByteArray();
Object[] ret = new Object[]{data, size};
return ret;
}
catch (IOException e) {
logger.log(Level.FINE, "Problem decoding stream bytes: ", e);
}
return null;
}
private void copyDecodedStreamBytesIntoRGB(int[] pixels) {
byte[] rgb = new byte[3];
try {
InputStream input = getInputStreamForDecodedStreamBytes();
for (int pixelIndex = 0; pixelIndex < pixels.length; pixelIndex++) {
int argb = 0xFF000000;
if (input != null) {
final int toRead = 3;
int haveRead = 0;
while (haveRead < toRead) {
int currRead = input.read(rgb, haveRead, toRead - haveRead);
if (currRead < 0)
break;
haveRead += currRead;
}
if (haveRead >= 1)
argb |= ((((int) rgb[0]) << 16) & 0x00FF0000);
if (haveRead >= 2)
argb |= ((((int) rgb[1]) << 8) & 0x0000FF00);
if (haveRead >= 3)
argb |= (((int) rgb[2]) & 0x000000FF);
}
pixels[pixelIndex] = argb;
}
if (input != null)
input.close();
}
catch (IOException e) {
logger.log(Level.FINE, "Problem copying decoding stream bytes: ", e);
}
}
private boolean shouldUseCCITTFaxDecode() {
return containsFilter(new String[]{"CCITTFaxDecode", "/CCF", "CCF"});
}
private boolean shouldUseDCTDecode() {
return containsFilter(new String[]{"DCTDecode", "/DCT", "DCT"});
}
private boolean shouldUseJBIG2Decode() {
return containsFilter(new String[]{"JBIG2Decode"});
}
private boolean shouldUseJPXDecode() {
return containsFilter(new String[]{"JPXDecode"});
}
private boolean containsFilter(String[] searchFilterNames) {
Vector filterNames = getFilterNames();
if (filterNames == null)
return false;
for (int i = 0; i < filterNames.size(); i++) {
String filterName = filterNames.elementAt(i).toString();
for (String search : searchFilterNames) {
if (search.equals(filterName)) {
return true;
}
}
}
return false;
}
private Vector getFilterNames() {
Vector filterNames = null;
Object o = library.getObject(entries, "Filter");
if (o instanceof Name) {
filterNames = new Vector(1);
filterNames.addElement(o);
} else if (o instanceof Vector) {
filterNames = (Vector) o;
}
return filterNames;
}
private Vector getNormalisedFilterNames() {
Vector filterNames = getFilterNames();
if (filterNames == null)
return null;
for (int i = 0; i < filterNames.size(); i++) {
String filterName = filterNames.elementAt(i).toString();
if (filterName.equals("FlateDecode")
|| filterName.equals("/Fl")
|| filterName.equals("Fl")) {
filterName = "FlateDecode";
} else if (
filterName.equals("LZWDecode")
|| filterName.equals("/LZW")
|| filterName.equals("LZW")) {
filterName = "LZWDecode";
} else if (
filterName.equals("ASCII85Decode")
|| filterName.equals("/A85")
|| filterName.equals("A85")) {
filterName = "ASCII85Decode";
} else if (
filterName.equals("ASCIIHexDecode")
|| filterName.equals("/AHx")
|| filterName.equals("AHx")) {
filterName = "ASCIIHexDecode";
} else if (
filterName.equals("RunLengthDecode")
|| filterName.equals("/RL")
|| filterName.equals("RL")) {
filterName = "RunLengthDecode";
} else if (
filterName.equals("CCITTFaxDecode")
|| filterName.equals("/CCF")
|| filterName.equals("CCF")) {
filterName = "CCITTFaxDecode";
} else if (
filterName.equals("DCTDecode")
|| filterName.equals("/DCT")
|| filterName.equals("DCT")) {
filterName = "DCTDecode";
}
// There aren't short names for JBIG2Decode or JPXDecode
filterNames.set(i, filterName);
}
return filterNames;
}
/**
* Despose of references to images and decoded byte streams.
* Memory optimization
*/
public void dispose(boolean cache) {
if (streamInput != null) {
if (!cache) {
try {
streamInput.dispose();
}
catch (IOException e) {
logger.log(Level.FINE, "Error disposing stream.", e);
}
streamInput = null;
}else{
library.removeObject(this.getPObjectReference());
}
}
synchronized (imageLock) {
if (image != null) {
image.dispose(cache, (streamInput != null));
if (!cache || !image.isCachedSomehow()) {
image = null;
}
}
}
}
/**
* The DCTDecode filter decodes grayscale or color image data that has been
* encoded in the JPEG baseline format. Because DCTDecode only deals
* with images, the instance of image is update instead of decoded
* stream.
*
* @return buffered images representation of the decoded JPEG data. Null
* if the image could not be properly decoded.
*/
private BufferedImage dctDecode(
int width, int height, PColorSpace colourSpace, int bitspercomponent,
BufferedImage smaskImage, BufferedImage maskImage,
int[] maskMinRGB, int[] maskMaxRGB, Vector<Integer> decode) {
// BIS's buffer size should be equal to mark() size, and greater than data size (below)
InputStream input = getInputStreamForDecodedStreamBytes();
// Used to just read 1000, but found a PDF that included thumbnails first
final int MAX_BYTES_TO_READ_FOR_ENCODING = 2048;
BufferedInputStream bufferedInput = new BufferedInputStream(
input, MAX_BYTES_TO_READ_FOR_ENCODING);
bufferedInput.mark(MAX_BYTES_TO_READ_FOR_ENCODING);
// We don't use the PColorSpace to determine how to decode the JPEG, because it tends to be wrong
// Some files say DeviceCMYK, or ICCBased, when neither would work, because it's really YCbCrA
// What does work though, is to look into the JPEG headers themself, via getJPEGEncoding()
int jpegEncoding = Stream.JPEG_ENC_UNKNOWN_PROBABLY_YCbCr;
try {
byte[] data = new byte[MAX_BYTES_TO_READ_FOR_ENCODING];
int dataRead = bufferedInput.read(data);
bufferedInput.reset();
if (dataRead > 0)
jpegEncoding = getJPEGEncoding(data, dataRead);
}
catch (IOException ioe) {
logger.log(Level.FINE, "Problem determining JPEG type: ", ioe);
}
if (Tagger.tagging)
Tagger.tagImage("DCTDecode_JpegEncoding=" + JPEG_ENC_NAMES[jpegEncoding]);
//System.out.println("Stream.dctDecode() objectNumber: " + getPObjectReference().getObjectNumber());
//System.out.println("Stream.dctDecode() jpegEncoding: " + JPEG_ENC_NAMES[jpegEncoding]);
//System.out.println("Stream.dctDecode() smask: " + smaskImage);
//System.out.println("Stream.dctDecode() mask: " + maskImage);
//System.out.println("Stream.dctDecode() maskMinRGB: " + maskMinRGB);
//System.out.println("Stream.dctDecode() maskMaxRGB: " + maskMaxRGB);
//long beginUsedMem = (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory());
//long beginTime = System.currentTimeMillis();
BufferedImage tmpImage = null;
if (tmpImage == null) {
try {
//System.out.println("Stream.dctDecode() JPEGImageDecoder");
JPEGImageDecoder imageDecoder = JPEGCodec.createJPEGDecoder(bufferedInput);
int bizarreFudge = 64 * 1024 + (int) streamInput.getLength();
checkMemory(width * height * 8 + bizarreFudge);
if (jpegEncoding == JPEG_ENC_RGB && bitspercomponent == 8) {
//System.out.println("Stream.dctDecode() JPEG_ENC_RGB");
Raster r = imageDecoder.decodeAsRaster();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
//System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID());
alterRasterRGB2PColorSpace(wr, colourSpace);
tmpImage = makeRGBBufferedImage(wr);
} else if (jpegEncoding == JPEG_ENC_CMYK && bitspercomponent == 8) {
//System.out.println("Stream.dctDecode() JPEG_ENC_CMYK");
Raster r = imageDecoder.decodeAsRaster();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
//System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID());
tmpImage = alterRasterCMYK2BGRA(wr, smaskImage, maskImage); //TODO Use maskMinRGB, maskMaxRGB or orig comp version here
} else if (jpegEncoding == JPEG_ENC_YCbCr && bitspercomponent == 8) {
//System.out.println("Stream.dctDecode() JPEG_ENC_YCbCr");
Raster r = imageDecoder.decodeAsRaster();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
//System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID());
tmpImage = alterRasterYCbCr2RGB(wr, smaskImage, maskImage, decode, bitspercomponent);
} else if (jpegEncoding == JPEG_ENC_YCCK && bitspercomponent == 8) {
//System.out.println("Stream.dctDecode() JPEG_ENC_YCCK");
Raster r = imageDecoder.decodeAsRaster();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
//System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID());
// YCCK to RGB works better if an CMYK intermediate is used, but slower.
alterRasterYCCK2CMYK(wr, decode,bitspercomponent);
tmpImage = alterRasterCMYK2BGRA(wr, smaskImage, maskImage);
} else if (jpegEncoding == JPEG_ENC_GRAY && bitspercomponent == 8) {
//System.out.println("Stream.dctDecode() JPEG_ENC_GRAY");
Raster r = imageDecoder.decodeAsRaster();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
//System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID());
// In DCTDecode with ColorSpace=DeviceGray, the samples are gray values (2000_SID_Service_Info.core)
// In DCTDecode with ColorSpace=Separation, the samples are Y values (45-14550BGermanForWeb.core AKA 4570.core)
- // Instead of assuming that Separation is special, I'll assume that DeviceGray is
+ // Avoid converting images that are already likely gray.
if (!(colourSpace instanceof DeviceGray) &&
- !(colourSpace instanceof ICCBased)) {
+ !(colourSpace instanceof ICCBased) &&
+ !(colourSpace instanceof Indexed)) {
if (Tagger.tagging)
Tagger.tagImage("DCTDecode_JpegSubEncoding=Y");
alterRasterY2Gray(wr, bitspercomponent, decode); //TODO Use smaskImage, maskImage, maskMinRGB, maskMaxRGB or orig comp version here
}
tmpImage = makeGrayBufferedImage(wr);
// apply mask value
if (maskImage != null){
tmpImage = applyExplicitMask(tmpImage, maskImage);
}
if (smaskImage != null){
tmpImage = applyExplicitSMask(tmpImage, smaskImage);
}
} else {
//System.out.println("Stream.dctDecode() Other");
//tmpImage = imageDecoder.decodeAsBufferedImage();
Raster r = imageDecoder.decodeAsRaster();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
//System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID());
if (imageDecoder.getJPEGDecodeParam().getEncodedColorID() ==
com.sun.image.codec.jpeg.JPEGDecodeParam.COLOR_ID_YCbCrA) {
if (Tagger.tagging)
Tagger.tagImage("DCTDecode_JpegSubEncoding=YCbCrA");
// YCbCrA, which is slightly different than YCCK
alterRasterYCbCrA2RGBA_new(wr, smaskImage, maskImage,
decode, bitspercomponent); //TODO Use maskMinRGB, maskMaxRGB or orig comp version here
tmpImage = makeRGBABufferedImage(wr);
} else {
if (Tagger.tagging)
Tagger.tagImage("DCTDecode_JpegSubEncoding=YCbCr");
alterRasterYCbCr2RGB(wr, smaskImage, maskImage, decode, bitspercomponent);
tmpImage = makeRGBBufferedImage(wr);
// special case to handle an smask on an RGB image. In
// such a case we need to copy the rgb and soft mask effect
// to th new ARGB image.
if (smaskImage != null) {
BufferedImage argbImage = new BufferedImage(width,
height, BufferedImage.TYPE_INT_ARGB);
int[] srcBand = new int[width];
int[] sMaskBand = new int[width];
// iterate over each band to apply the mask
for (int i = 0; i < height; i++) {
tmpImage.getRGB(0, i, width, 1, srcBand, 0, width);
smaskImage.getRGB(0, i, width, 1, sMaskBand, 0, width);
// apply the soft mask blending
for (int j = 0; j < width; j++) {
sMaskBand[j] = ((sMaskBand[j] & 0xff) << 24)
| (srcBand[j] & ~0xff000000);
}
argbImage.setRGB(0, i, width, 1, sMaskBand, 0, width);
}
tmpImage.flush();
tmpImage = argbImage;
}
}
}
}
catch (Exception e) {
logger.log(Level.FINE, "Problem loading JPEG image via JPEGImageDecoder: ", e);
}
if (tmpImage != null) {
if (Tagger.tagging)
Tagger.tagImage("HandledBy=DCTDecode_SunJPEGImageDecoder");
}
}
try {
bufferedInput.close();
}
catch (IOException e) {
logger.log(Level.FINE, "Error closing image stream.", e);
}
if (tmpImage == null) {
try {
//System.out.println("Stream.dctDecode() JAI");
Object javax_media_jai_RenderedOp_op = null;
try {
// Have to reget the data
input = getInputStreamForDecodedStreamBytes();
/*
com.sun.media.jai.codec.SeekableStream s = com.sun.media.jai.codec.SeekableStream.wrapInputStream( new ByteArrayInputStream(data), true );
ParameterBlock pb = new ParameterBlock();
pb.add( s );
javax.media.jai.RenderedOp op = javax.media.jai.JAI.create( "jpeg", pb );
*/
Class ssClass = Class.forName("com.sun.media.jai.codec.SeekableStream");
Method ssWrapInputStream = ssClass.getMethod("wrapInputStream", InputStream.class, Boolean.TYPE);
Object com_sun_media_jai_codec_SeekableStream_s =
ssWrapInputStream.invoke(null, input, Boolean.TRUE);
ParameterBlock pb = new ParameterBlock();
pb.add(com_sun_media_jai_codec_SeekableStream_s);
Class jaiClass = Class.forName("javax.media.jai.JAI");
Method jaiCreate = jaiClass.getMethod("create", String.class, ParameterBlock.class);
javax_media_jai_RenderedOp_op = jaiCreate.invoke(null, "jpeg", pb);
}
catch (Exception e) {
}
if (javax_media_jai_RenderedOp_op != null) {
if (jpegEncoding == JPEG_ENC_CMYK && bitspercomponent == 8) {
/*
* With or without alterRasterCMYK2BGRA(), give blank image
Raster r = op.copyData();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
alterRasterCMYK2BGRA( wr );
tmpImage = makeRGBABufferedImage( wr );
*/
/*
* With alterRasterCMYK2BGRA() colors gibbled, without is blank
* Slower, uses more memory, than JPEGImageDecoder
BufferedImage img = op.getAsBufferedImage();
WritableRaster wr = img.getRaster();
alterRasterCMYK2BGRA( wr );
tmpImage = img;
*/
} else if (jpegEncoding == JPEG_ENC_YCCK && bitspercomponent == 8) {
/*
* This way, with or without alterRasterYCbCrA2BGRA(), give blank image
Raster r = op.getData();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
alterRasterYCbCrA2BGRA( wr );
tmpImage = makeRGBABufferedImage( wr );
*/
/*
* With alterRasterYCbCrA2BGRA() colors gibbled, without is blank
* Slower, uses more memory, than JPEGImageDecoder
BufferedImage img = op.getAsBufferedImage();
WritableRaster wr = img.getRaster();
alterRasterYCbCrA2BGRA( wr );
tmpImage = img;
*/
} else {
//System.out.println("Stream.dctDecode() Other");
/* tmpImage = op.getAsBufferedImage(); */
Class roClass = Class.forName("javax.media.jai.RenderedOp");
Method roGetAsBufferedImage = roClass.getMethod("getAsBufferedImage");
tmpImage = (BufferedImage) roGetAsBufferedImage.invoke(javax_media_jai_RenderedOp_op);
if (tmpImage != null) {
if (Tagger.tagging)
Tagger.tagImage("HandledBy=DCTDecode_JAI");
}
}
}
}
catch (Exception e) {
logger.log(Level.FINE, "Problem loading JPEG image via JAI: ", e);
}
try {
input.close();
}
catch (IOException e) {
logger.log(Level.FINE, "Problem closing image stream. ", e);
}
}
if (tmpImage == null) {
try {
//System.out.println("Stream.dctDecode() Toolkit");
byte[] data = getDecodedStreamBytes();
if (data != null) {
Image img = Toolkit.getDefaultToolkit().createImage(data);
if (img != null) {
tmpImage = makeRGBABufferedImageFromImage(img);
if (Tagger.tagging)
Tagger.tagImage("HandledBy=DCTDecode_ToolkitCreateImage");
}
}
}
catch (Exception e) {
logger.log(Level.FINE, "Problem loading JPEG image via Toolkit: ", e);
}
}
//long endUsedMem = (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory());
//long endTime = System.currentTimeMillis();
//System.out.println("Mem used: " + (endUsedMem-beginUsedMem) + ",\ttime: " + (endTime-beginTime));
return tmpImage;
}
/**
* Utility method to decode JBig2 images.
*
* @param width width of image
* @param height height of image
* @param fill colour fill to be applied to a mask
* @param imageMask true to indicate image should be treated as a mask
* @return buffered image of decoded jbig2 image stream. Null if an error
* occured during decode.
*/
private BufferedImage jbig2Decode(int width, int height, Color fill, boolean imageMask) {
BufferedImage tmpImage = null;
try {
Class jbig2DecoderClass = Class.forName("org.jpedal.jbig2.JBIG2Decoder");
// create instance of decoder
Constructor jbig2DecoderClassConstructor =
jbig2DecoderClass.getDeclaredConstructor();
Object jbig2Decoder = jbig2DecoderClassConstructor.newInstance();
checkMemory(108 * 1024);
// get the decode params form the stream
Hashtable decodeParms = library.getDictionary(entries, "DecodeParms");
if (decodeParms != null) {
Stream globalsStream = null;
Object jbigGlobals = library.getObject(decodeParms, "JBIG2Globals");
if (jbigGlobals instanceof Stream){
globalsStream = (Stream) library.getObject(decodeParms, "JBIG2Globals");
}
if (globalsStream != null){
byte[] globals = globalsStream.getDecodedStreamBytes();
if (globals != null && globals.length > 0 ) {
// invoked ecoder.setGlobalData(globals);
Class partypes[] = new Class[1];
partypes[0] = byte[].class;
Object arglist[] = new Object[1];
arglist[0] = globals;
Method setGlobalData =
jbig2DecoderClass.getMethod("setGlobalData", partypes);
setGlobalData.invoke(jbig2Decoder, arglist);
globals = null;
}
}
}
// decode the data stream, decoder.decodeJBIG2(data);
byte[] data = getDecodedStreamBytes();
checkMemory((width + 8) * height * 22 / 10); // Between 0.5 and 2.2
Class argTypes[] = new Class[]{byte[].class};
Object arglist[] = new Object[]{data};
Method decodeJBIG2 = jbig2DecoderClass.getMethod("decodeJBIG2", argTypes);
decodeJBIG2.invoke(jbig2Decoder, arglist);
data = null;
// From decoding, memory usage increases more than (width*height/8),
// due to intermediate JBIG2Bitmap objects, used to build the final
// one, still hanging around. Cleanup intermediate data-structures.
// decoder.cleanupPostDecode();
Method cleanupPostDecode = jbig2DecoderClass.getMethod("cleanupPostDecode");
cleanupPostDecode.invoke(jbig2Decoder);
// final try an fetch the image. tmpImage = decoder.getPageAsBufferedImage(0);
checkMemory((width + 8) * height / 8);
argTypes = new Class[]{Integer.TYPE};
arglist = new Object[]{0};
Method getPageAsBufferedImage = jbig2DecoderClass.getMethod("getPageAsBufferedImage", argTypes);
tmpImage = (BufferedImage)getPageAsBufferedImage.invoke(jbig2Decoder, arglist);
}catch (ClassNotFoundException e) {
logger.warning("JBIG2 image library could not be found");
}
catch (Exception e) {
logger.log(Level.WARNING, "Problem loading JBIG2 image: ", e);
}
// apply the fill colour and alpha if masking is enabled.
if (imageMask){
tmpImage = applyExplicitMask(tmpImage, fill);
}
return tmpImage;
}
/**
* Creates a new instance of a Dictionary.
*
* @param library document library.
* @param entries dictionary entries.
*/
public Stream(Library library, Hashtable entries) {
super(library, entries); //To change body of overridden methods use File | Settings | File Templates.
}
/**
* Utility method to decode JPEG2000 images.
*
* @param width width of image.
* @param height height of image.
* @param colourSpace colour space to apply to image.
* @param bitsPerComponent bits used to represent a colour
* @param fill fill colour used in last draw operand.
* @param maskImage image mask if any, can be null.
* @param sMaskImage image smask if any, can be null.
* @param maskMinRGB mask minimum rgb value, optional.
* @param maskMaxRGB mask maximum rgb value, optional.
* @return buffered image of the jpeg2000 image stream. Null if a problem
* occurred during the decode.
*/
private BufferedImage jpxDecode(int width, int height, PColorSpace colourSpace,
int bitsPerComponent, Color fill,
BufferedImage sMaskImage, BufferedImage maskImage,
int[] maskMinRGB, int[] maskMaxRGB, Vector decode) {
BufferedImage tmpImage = null;
try {
// Verify that ImageIO can read JPEG2000
Iterator<ImageReader> iterator = ImageIO.getImageReadersByFormatName("JPEG2000");
if (!iterator.hasNext()) {
logger.info(
"ImageIO missing required plug-in to read JPEG 2000 images. " +
"You can download the JAI ImageIO Tools from: " +
"https://jai-imageio.dev.java.net/");
return null;
}
// decode the image.
byte[] data = getDecodedStreamBytes();
ImageInputStream imageInputStream = ImageIO.createImageInputStream(
new ByteArrayInputStream(data));
tmpImage = ImageIO.read(imageInputStream);
// check for an instance of ICCBased, we don't currently support
// this colour mode well so we'll used the alternative colour
if (colourSpace instanceof ICCBased) {
ICCBased iccBased = (ICCBased) colourSpace;
if (iccBased.getAlternate() != null) {
// set the alternate as the current
colourSpace = iccBased.getAlternate();
}
// try to process the ICC colour space
else {
ColorSpace cs = iccBased.getColorSpace();
ColorConvertOp cco = new ColorConvertOp(cs, null);
tmpImage = cco.filter(tmpImage, null);
}
}
// apply respective colour models to the JPEG2000 image.
if (colourSpace instanceof DeviceRGB && bitsPerComponent == 8) {
WritableRaster wr = tmpImage.getRaster();
alterRasterRGB2PColorSpace(wr, colourSpace);
tmpImage = makeRGBBufferedImage(wr);
} else if (colourSpace instanceof DeviceCMYK && bitsPerComponent == 8) {
WritableRaster wr = tmpImage.getRaster();
tmpImage = alterRasterCMYK2BGRA(wr, sMaskImage, maskImage);
} else if ((colourSpace instanceof DeviceGray ||
colourSpace instanceof Indexed)
&& bitsPerComponent == 8) {
WritableRaster wr = tmpImage.getRaster();
tmpImage = makeGrayBufferedImage(wr);
} else if (colourSpace instanceof Separation){
WritableRaster wr = tmpImage.getRaster();
alterRasterY2Gray(wr, bitsPerComponent, decode);
}
// check for a mask value
if (maskImage != null){
tmpImage = applyExplicitMask(tmpImage, maskImage);
}
if (sMaskImage != null){
tmpImage = applyExplicitSMask(tmpImage, sMaskImage);
}
}
catch (IOException e) {
logger.log(Level.FINE, "Problem loading JPEG2000 image: ", e);
}
return tmpImage;
}
private static BufferedImage alterRasterCMYK2BGRA(WritableRaster wr,
BufferedImage smaskImage,
BufferedImage maskImage) {
int width = wr.getWidth();
int height = wr.getHeight();
Raster smaskRaster = null;
int smaskWidth = 0;
int smaskHeight = 0;
if (smaskImage != null) {
smaskRaster = smaskImage.getRaster();
smaskWidth = smaskRaster.getWidth();
smaskHeight = smaskRaster.getHeight();
// If smask is larger then the image, and needs to be scaled to match the image.
if (width < smaskWidth || height < smaskHeight) {
// calculate scale factors.
double scaleX = width / (double) smaskWidth;
double scaleY = height / (double) smaskHeight;
// scale the mask to match the base image.
AffineTransform tx = new AffineTransform();
tx.scale(scaleX, scaleY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
BufferedImage sbim = op.filter(smaskImage, null);
smaskImage.flush();
smaskImage = sbim;
}
// update the new deminsions.
smaskRaster = smaskImage.getRaster();
smaskWidth = smaskRaster.getWidth();
smaskHeight = smaskRaster.getHeight();
}
Raster maskRaster = null;
int maskWidth = 0;
int maskHeight = 0;
if (maskImage != null) {
maskRaster = maskImage.getRaster();
maskWidth = maskRaster.getWidth();
maskHeight = maskRaster.getHeight();
}
// this convoluted cymk->rgba method is from DeviceCMYK class.
float inCyan, inMagenta, inYellow, inBlack;
float lastCyan = -1, lastMagenta = -1, lastYellow = -1, lastBlack = -1;
double c, m, y2, aw, ac, am, ay, ar, ag, ab;
float outRed, outGreen, outBlue;
int rValue = 0, gValue = 0, bValue = 0, alpha = 0;
int[] values = new int[4];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
wr.getPixel(x, y, values);
inCyan = values[0] / 255.0f;
inMagenta = values[1] / 255.0f;
inYellow = values[2] / 255.0f;
// lessen the amount of black, standard 255 fraction is too dark
// increasing the denominator has the same affect of lighting up
// the image.
inBlack = (values[3] / 768.0f);
if (!(inCyan == lastCyan && inMagenta == lastMagenta &&
inYellow == lastYellow && inBlack == lastBlack)){
c = clip(0, 1, inCyan + inBlack);
m = clip(0, 1, inMagenta + inBlack);
y2 = clip(0, 1, inYellow + inBlack);
aw = (1 - c) * (1 - m) * (1 - y2);
ac = c * (1 - m) * (1 - y2);
am = (1 - c) * m * (1 - y2);
ay = (1 - c) * (1 - m) * y2;
ar = (1 - c) * m * y2;
ag = c * (1 - m) * y2;
ab = c * m * (1 - y2);
outRed = (float)clip(0, 1, aw + 0.9137 * am + 0.9961 * ay + 0.9882 * ar);
outGreen = (float)clip(0, 1, aw + 0.6196 * ac + ay + 0.5176 * ag);
outBlue = (float)clip(0, 1, aw + 0.7804 * ac + 0.5412 * am + 0.0667 * ar + 0.2118 * ag + 0.4863 * ab);
rValue = (int) (outRed * 255);
gValue = (int) (outGreen * 255);
bValue = (int) (outBlue * 255);
alpha = 0xFF;
}
lastCyan = inCyan;
lastMagenta = inMagenta;
lastYellow = inYellow;
lastBlack = inBlack;
// this fits into the larger why are we doing this on a case by case basis.
if (y < smaskHeight && x < smaskWidth && smaskRaster != null){
alpha = (smaskRaster.getSample(x, y, 0) & 0xFF);
}else if (y < maskHeight && x < maskWidth && maskRaster != null) {
// When making an ImageMask, the alpha channel is setup so that
// it both works correctly for the ImageMask being painted,
// and also for when it's used here, to determine the alpha
// of an image that it's masking
alpha = (maskImage.getRGB(x, y) >>> 24) & 0xFF; // Extract Alpha from ARGB
}
values[redIndex] = rValue;
values[1] = gValue;
values[blueIndex] = bValue;
values[3] = alpha;
wr.setPixel(x, y, values);
}
}
// apply the soft mask, but first we need an rgba image,
// this is pretty expensive, would like to find quicker method.
BufferedImage tmpImage = makeRGBABufferedImage(wr);
if (smaskImage != null) {
BufferedImage argbImage = new BufferedImage(width,
height, BufferedImage.TYPE_INT_ARGB);
int[] srcBand = new int[width];
int[] sMaskBand = new int[width];
// iterate over each band to apply the mask
for (int i = 0; i < height; i++) {
tmpImage.getRGB(0, i, width, 1, srcBand, 0, width);
smaskImage.getRGB(0, i, width, 1, sMaskBand, 0, width);
// apply the soft mask blending
for (int j = 0; j < width; j++) {
sMaskBand[j] = ((sMaskBand[j] & 0xff) << 24)
| (srcBand[j] & ~0xff000000);
}
argbImage.setRGB(0, i, width, 1, sMaskBand, 0, width);
}
tmpImage.flush();
tmpImage = argbImage;
}
return tmpImage;
}
private static BufferedImage alterRasterYCbCr2RGB(WritableRaster wr,
BufferedImage smaskImage, BufferedImage maskImage,
Vector<Integer> decode, int bitsPerComponent) {
float[] values;
int width = wr.getWidth();
int height = wr.getHeight();
int maxValue = ((int) Math.pow(2, bitsPerComponent)) - 1;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
// apply decode param.
values = getNormalizedComponents(
(byte[])wr.getDataElements(x,y,null),
decode,
maxValue);
float Y = values[0] * 255;
float Cb = values[1] * 255;
float Cr = values[2] * 255;
float Cr_128 = Cr - 128;
float Cb_128 = Cb - 128;
float rVal = Y + (1370705 * Cr_128 / 1000000);
float gVal = Y - (337633 * Cb_128 / 1000000) - (698001 * Cr_128 / 1000000);
float bVal = Y + (1732446 * Cb_128 / 1000000);
byte rByte = (rVal < 0) ? (byte) 0 : (rVal > 255) ? (byte) 0xFF : (byte) rVal;
byte gByte = (gVal < 0) ? (byte) 0 : (gVal > 255) ? (byte) 0xFF : (byte) gVal;
byte bByte = (bVal < 0) ? (byte) 0 : (bVal > 255) ? (byte) 0xFF : (byte) bVal;
// apply mask and smask values.
values[0] = rByte;
values[1] = gByte;
values[2] = bByte;
wr.setPixel(x, y, values);
}
}
BufferedImage tmpImage = makeRGBBufferedImage(wr);
// special case to handle an smask on an RGB image. In
// such a case we need to copy the rgb and soft mask effect
// to th new ARGB image.
if (smaskImage != null) {
BufferedImage argbImage = new BufferedImage(width,
height, BufferedImage.TYPE_INT_ARGB);
int[] srcBand = new int[width];
int[] sMaskBand = new int[width];
// iterate over each band to apply the mask
for (int i = 0; i < height; i++) {
tmpImage.getRGB(0, i, width, 1, srcBand, 0, width);
smaskImage.getRGB(0, i, width, 1, sMaskBand, 0, width);
// apply the soft mask blending
for (int j = 0; j < width; j++) {
sMaskBand[j] = ((sMaskBand[j] & 0xff) << 24)
| (srcBand[j] & ~0xff000000);
}
argbImage.setRGB(0, i, width, 1, sMaskBand, 0, width);
}
tmpImage.flush();
tmpImage = argbImage;
}
return tmpImage;
}
/**
* The basic idea is that we do a fuzzy colour conversion from YCCK to
* BGRA. The conversion is not perfect giving a bit of a greenish hue to the
* image in question. I've tweaked the core Adobe algorithm ot give slightly
* "better" colour representation but it does seem to make red a little light.
* @param wr image stream to convert colour space.
* @param smaskImage smask used to apply alpha values.
* @param maskImage maks image for drop out.
*/
private static void alterRasterYCCK2BGRA(WritableRaster wr,
BufferedImage smaskImage,
BufferedImage maskImage,
Vector<Integer> decode,
int bitsPerComponent) {
Raster smaskRaster = null;
int smaskWidth = 0;
int smaskHeight = 0;
if (smaskImage != null) {
smaskRaster = smaskImage.getRaster();
smaskWidth = smaskRaster.getWidth();
smaskHeight = smaskRaster.getHeight();
}
Raster maskRaster = null;
int maskWidth = 0;
int maskHeight = 0;
if (maskImage != null) {
maskRaster = maskImage.getRaster();
maskWidth = maskRaster.getWidth();
maskHeight = maskRaster.getHeight();
}
float[] origValues;
double[] rgbaValues = new double[4];
int width = wr.getWidth();
int height = wr.getHeight();
int maxValue = ((int) Math.pow(2, bitsPerComponent)) - 1;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
// apply decode param.
origValues = getNormalizedComponents(
(byte[])wr.getDataElements(x,y,null),
decode,
maxValue);
float Y = origValues[0] * 255;
float Cb = origValues[1] * 255;
float Cr = origValues[2] * 255;
// float K = origValues[3] * 255;
// removing alteration for now as some samples are too dark.
// Y *= .95; // gives a darker image, as y approaches zero,
// the image becomes darke
float Cr_128 = Cr - 128;
float Cb_128 = Cb - 128;
// adobe conversion for CCIR Rec. 601-1 standard.
// http://partners.adobe.com/public/developer/en/ps/sdk/5116.DCT_Filter.pdf
// double rVal = Y + (1.4020 * Cr_128);
// double gVal = Y - (.3441363 * Cb_128) - (.71413636 * Cr_128);
// double bVal = Y + (1.772 * Cb_128);
// intel codecs, http://software.intel.com/sites/products/documentation/hpc/ipp/ippi/ippi_ch6/ch6_color_models.html
// Intel IPP conversion for JPEG codec.
// double rVal = Y + (1.402 * Cr) - 179.456;
// double gVal = Y - (0.34414 * Cb) - (.71413636 * Cr) + 135.45984;
// double bVal = Y + (1.772 * Cb) - 226.816;
// ICEsoft custom algorithm, results may vary, res are a little
// off but over all a better conversion/ then the stoke algorithms.
double rVal = Y + (1.4020 * Cr_128);
double gVal = Y + (.14414 * Cb_128) + (.11413636 * Cr_128);
double bVal = Y + (1.772 * Cb_128);
// Intel IPP conversion for ITU-R BT.601 for video
// default 16, higher more green and darker blacks, lower less
// green hue and lighter blacks.
// double kLight = (1.164 * (Y -16 ));
// double rVal = kLight + (1.596 * Cr_128);
// double gVal = kLight - (0.392 * Cb_128) - (0.813 * Cr_128);
// double bVal = kLight + (1.017 * Cb_128);
// intel PhotoYCC Color Model [0.1], not a likely candidate for jpegs.
// double y1 = Y/255.0;
// double c1 = Cb/255.0;
// double c2 = Cr/255.0;
// double rVal = ((0.981 * y1) + (1.315 * (c2 - 0.537))) *255.0;
// double gVal = ((0.981 * y1) - (0.311 * (c1 - 0.612))- (0.669 * (c2 - 0.537))) *255.0;
// double bVal = ((0.981 * y1) + (1.601 * (c1 - 0.612))) *255.0;
// check the range an convert as needed.
byte rByte = (rVal < 0) ? (byte) 0 : (rVal > 255) ? (byte) 0xFF : (byte) rVal;
byte gByte = (gVal < 0) ? (byte) 0 : (gVal > 255) ? (byte) 0xFF : (byte) gVal;
byte bByte = (bVal < 0) ? (byte) 0 : (bVal > 255) ? (byte) 0xFF : (byte) bVal;
int alpha = 0xFF;
if (y < smaskHeight && x < smaskWidth && smaskRaster != null){
alpha = (smaskRaster.getSample(x, y, 0) & 0xFF);
}else if (y < maskHeight && x < maskWidth && maskRaster != null) {
// When making an ImageMask, the alpha channel is setup so that
// it both works correctly for the ImageMask being painted,
// and also for when it's used here, to determine the alpha
// of an image that it's masking
alpha = (maskImage.getRGB(x, y) >>> 24) & 0xFF; // Extract Alpha from ARGB
}
rgbaValues[0] = bByte;
rgbaValues[1] = gByte;
rgbaValues[2] = rByte;
rgbaValues[3] = alpha;
wr.setPixel(x, y, rgbaValues);
}
}
}
/**
* The basic idea is that we do a fuzzy colour conversion from YCCK to
* CMYK. The conversion is not perfect but when converted again from
* CMYK to RGB the result is much better then going directly from YCCK to
* RGB.
* NOTE: no masking here, as it is done later in the call to
* {@see alterRasterCMYK2BGRA}
* @param wr writable raster to alter.
* @param decode decode vector.
* @param bitsPerComponent bits per component .
*/
private static void alterRasterYCCK2CMYK(WritableRaster wr,
Vector<Integer> decode,
int bitsPerComponent) {
float[] origValues;
double[] pixels = new double[4];
double Y,Cb,Cr,K;
double lastY = -1,lastCb = -1,lastCr = -1,lastK = -1;
double c = 0, m = 0, y2 = 0, k = 0;
int width = wr.getWidth();
int height = wr.getHeight();
int maxValue = ((int) Math.pow(2, bitsPerComponent)) - 1;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
// apply decode param.
origValues = getNormalizedComponents(
(byte[])wr.getDataElements(x,y,null),
decode,
maxValue);
Y = origValues[0] * 255;
Cb = origValues[1] * 255;
Cr = origValues[2]* 255;
K = origValues[3]* 255;
if (!(lastY == y && lastCb == Cb && lastCr == Cr && lastK == K )){
// intel codecs, http://software.intel.com/sites/products/documentation/hpc/ipp/ippi/ippi_ch6/ch6_color_models.html
// Intel IPP conversion for JPEG codec.
c = 255 - (Y + (1.402 * Cr) - 179.456 );
m = 255 - (Y - (0.34414 * Cb) - (0.71413636 * Cr) + 135.45984);
y2 = 255 - (Y + (1.7718 * Cb) - 226.816);
k = K;
c = clip(0,255,c);
m = clip(0,255,m);
y2 = clip(0,255,y2);
}
lastY = Y;
lastCb = Cb;
lastCr = Cr;
lastK = K;
pixels[0] = c;
pixels[1] = m;
pixels[2] = y2;
pixels[3] = k;
wr.setPixel(x, y, pixels);
}
}
}
/**
* Apply the Decode Array domain for each colour component.
* @param pixels colour to process by decode
* @param decode decode array for colour space
* @param xMax domain max for the second point on the interpolation line
* always (2<sup>bitsPerComponent</sup> - 1).
* @return
*/
private static float[] getNormalizedComponents(
byte[] pixels,
Vector decode, int xMax) {
float[] normComponents = new float[pixels.length];
int val;
float yMin;
float yMax;
// interpolate each colour component for the given decode domain.
for (int i = 0; i < pixels.length; i++) {
val = pixels[i] & 0xff;
yMin = ((Number)decode.get(i * 2)).floatValue();
yMax = ((Number)decode.get((i * 2) + 1)).floatValue();
normComponents[i] =
Function.interpolate(val, 0, xMax, yMin, yMax);
}
return normComponents;
}
private static void alterRasterYCbCrA2RGBA_new(WritableRaster wr,
BufferedImage smaskImage, BufferedImage maskImage,
Vector<Integer> decode, int bitsPerComponent) {
Raster smaskRaster = null;
int smaskWidth = 0;
int smaskHeight = 0;
if (smaskImage != null) {
smaskRaster = smaskImage.getRaster();
smaskWidth = smaskRaster.getWidth();
smaskHeight = smaskRaster.getHeight();
}
Raster maskRaster = null;
int maskWidth = 0;
int maskHeight = 0;
if (maskImage != null) {
maskRaster = maskImage.getRaster();
maskWidth = maskRaster.getWidth();
maskHeight = maskRaster.getHeight();
}
float[] origValues = new float[4];
int[] rgbaValues = new int[4];
int width = wr.getWidth();
int height = wr.getHeight();
int maxValue = ((int) Math.pow(2, bitsPerComponent)) - 1;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
wr.getPixel(x, y, origValues);
// apply decode param.
// couldn't quite get this one right, doesn't decode
// as I would have thought.
// origValues = getNormalizedComponents(
// (byte[])wr.getDataElements(x,y,null),
// decode,
// maxValue);
float Y = origValues[0];
float Cb = origValues[1];
float Cr = origValues[2];
float K = origValues[3];
Y = K - Y;
float Cr_128 = Cr - 128;
float Cb_128 = Cb - 128;
float rVal = Y + (1370705 * Cr_128 / 1000000);
float gVal = Y - (337633 * Cb_128 / 1000000) - (698001 * Cr_128 / 1000000);
float bVal = Y + (1732446 * Cb_128 / 1000000);
/*
// Formula used in JPEG standard. Gives pretty similar results
//int rVal = Y + (1402000 * Cr_128/ 1000000);
//int gVal = Y - (344140 * Cb_128 / 1000000) - (714140 * Cr_128 / 1000000);
//int bVal = Y + (1772000 * Cb_128 / 1000000);
*/
byte rByte = (rVal < 0) ? (byte) 0 : (rVal > 255) ? (byte) 0xFF : (byte) rVal;
byte gByte = (gVal < 0) ? (byte) 0 : (gVal > 255) ? (byte) 0xFF : (byte) gVal;
byte bByte = (bVal < 0) ? (byte) 0 : (bVal > 255) ? (byte) 0xFF : (byte) bVal;
float alpha = K;
if (y < smaskHeight && x < smaskWidth && smaskRaster != null)
alpha = (smaskRaster.getSample(x, y, 0) & 0xFF);
else if (y < maskHeight && x < maskWidth && maskRaster != null) {
// When making an ImageMask, the alpha channnel is setup so that
// it both works correctly for the ImageMask being painted,
// and also for when it's used here, to determine the alpha
// of an image that it's masking
alpha = (maskImage.getRGB(x, y) >>> 24) & 0xFF; // Extract Alpha from ARGB
}
rgbaValues[0] = rByte;
rgbaValues[1] = gByte;
rgbaValues[2] = bByte;
rgbaValues[3] = (int)alpha;
wr.setPixel(x, y, rgbaValues);
}
}
}
/**
* (see 8.9.6.3, "Explicit Masking")
* Explicit Masking algorithm, as of PDF 1.3. The entry in an image dictionary
* may be an image mask, as described under "Stencil Masking", which serves as
* an explicit mask for the primary or base image. The base image and the
* image mask need not have the same resolution (width, height), but since
* all images are defined on the unit square in user space, their boundaries on the
* page will conincide; that is, they will overlay each other.
* <p/>
* The image mask indicates indicates which places on the page are to be painted
* and which are to be masked out (left unchanged). Unmasked areas are painted
* with the corresponding portions of the base image; masked areas are not.
*
* @param baseImage base image in which the mask weill be applied to
* @param maskImage image mask to be applied to base image.
*/
private static BufferedImage applyExplicitMask(BufferedImage baseImage, BufferedImage maskImage) {
// check to see if we need to scale the mask to match the size of the
// base image.
int baseWidth = baseImage.getWidth();
int baseHeight = baseImage.getHeight();
final int maskWidth = maskImage.getWidth();
final int maskHeight = maskImage.getHeight();
// we're going for quality over memory foot print here, for most
// masks its better to scale the base image up to the mask size.
if (baseWidth != maskWidth || baseHeight != maskHeight) {
// calculate scale factors.
double scaleX = maskWidth / (double) baseWidth ;
double scaleY = maskHeight / (double) baseHeight;
// scale the mask to match the base image.
AffineTransform tx = new AffineTransform();
tx.scale(scaleX, scaleY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
BufferedImage sbim = op.filter(baseImage, null);
baseImage.flush();
baseImage = sbim;
}
// apply the mask by simply painting white to the base image where
// the mask specified no colour.
// todo: need to apply alpha instead of white, but requires a new CM.
for (int y = 0; y < maskHeight; y++) {
for (int x = 0; x < maskWidth; x++) {
// apply masking/smaksing logic.
int maskPixel = maskImage.getRGB(x, y);
if (maskPixel == -1 || maskPixel == 0xffffff || maskPixel == 0) {
baseImage.setRGB(x, y, Color.WHITE.getRGB());
}
}
}
return baseImage;
}
/**
* (see 11.6.5.3, "Soft-Mask Images")
* A subsidiary image XObject defining a soft-mask image that shall be used
* as a source of mask shape or mask opacity values in the transparent imaging
* model. The alpha source parameter in the graphics state determines whether
* the mask values shall be interpreted as shape or opacity.
*
* If present, this entry shall override the current soft mask in the graphics
* state, as well as the image’s Mask entry, if any. However, the other
* transparency-related graphics state parameters—blend mode and alpha
* constant—shall remain in effect. If SMask is absent, the image shall
* have no associated soft mask (although the current soft mask in the
* graphics state may still apply).
*
* @param baseImage base image in which the mask weill be applied to
*/
private static BufferedImage applyExplicitSMask(BufferedImage baseImage, BufferedImage sMaskImage) {
// check to see if we need to scale the mask to match the size of the
// base image.
int baseWidth = baseImage.getWidth();
int baseHeight = baseImage.getHeight();
final int maskWidth = sMaskImage.getWidth();
final int maskHeight = sMaskImage.getHeight();
// we're going for quality over memory foot print here, for most
// masks its better to scale the base image up to the mask size.
if (baseWidth != maskWidth || baseHeight != maskHeight) {
// calculate scale factors.
double scaleX = maskWidth / (double) baseWidth ;
double scaleY = maskHeight / (double) baseHeight;
// scale the mask to match the base image.
AffineTransform tx = new AffineTransform();
tx.scale(scaleX, scaleY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
BufferedImage sbim = op.filter(baseImage, null);
baseImage.flush();
baseImage = sbim;
}
// apply the mask by simply painting white to the base image where
// the mask specified no colour.
// todo: need to apply alpha instead of white, but requires a new CM.
int maskPixel;
for (int y = 0; y < maskHeight; y++) {
for (int x = 0; x < maskWidth; x++) {
maskPixel = sMaskImage.getRGB(x, y);
if (maskPixel != -1 || maskPixel != 0xffffff || maskPixel != 0) {
baseImage.setRGB(x, y, Color.WHITE.getRGB());
}
}
}
return baseImage;
}
/**
* Treats the base image as as mask data applying the specified fill colour
* to the flagged bytes and a transparency value otherwise. This method
* creates a new BufferedImage with a transparency model so it will cause
* a memory spike.
* @param baseImage masking image.
* @param fill fill value to apply to mask.
* @return masked image encoded with the fill colour and transparency.
*/
private static BufferedImage applyExplicitMask(BufferedImage baseImage, Color fill) {
// create an
int baseWidth = baseImage.getWidth();
int baseHeight = baseImage.getHeight();
BufferedImage imageMask = new BufferedImage(baseWidth, baseHeight,
BufferedImage.TYPE_INT_ARGB);
// apply the mask by simply painting white to the base image where
// the mask specified no colour.
for (int y = 0; y < baseHeight; y++) {
for (int x = 0; x < baseWidth; x++) {
int maskPixel = baseImage.getRGB(x, y);
if (!(maskPixel == -1 || maskPixel == 0xffffff)) {
imageMask.setRGB(x, y, fill.getRGB());
}
}
}
// clean up the old image.
baseImage.flush();
// return the mask.
return imageMask;
}
private static BufferedImage alterBufferedImage(BufferedImage bi, BufferedImage smaskImage, BufferedImage maskImage, int[] maskMinRGB, int[] maskMaxRGB) {
Raster smaskRaster = null;
int smaskWidth = 0;
int smaskHeight = 0;
int width = bi.getWidth();
int height = bi.getHeight();
if (smaskImage != null) {
smaskRaster = smaskImage.getRaster();
smaskWidth = smaskRaster.getWidth();
smaskHeight = smaskRaster.getHeight();
// scale the image to match the image mask.
if (width < smaskWidth || height < smaskHeight) {
// calculate scale factors.
double scaleX = smaskWidth / (double) width;
double scaleY = smaskHeight / (double) height;
// scale the mask to match the base image.
AffineTransform tx = new AffineTransform();
tx.scale(scaleX, scaleY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
BufferedImage bim = op.filter(bi, null);
bi.flush();
bi = bim;
}
width = bi.getWidth();
height = bi.getHeight();
}
Raster maskRaster = null;
int maskWidth = 0;
int maskHeight = 0;
if (maskImage != null) {
maskRaster = maskImage.getRaster();
maskWidth = maskRaster.getWidth();
maskHeight = maskRaster.getHeight();
}
int maskMinRed = 0xFF;
int maskMinGreen = 0xFF;
int maskMinBlue = 0xFF;
int maskMaxRed = 0x00;
int maskMaxGreen = 0x00;
int maskMaxBlue = 0x00;
if (maskMinRGB != null && maskMaxRGB != null) {
maskMinRed = maskMinRGB[0];
maskMinGreen = maskMinRGB[1];
maskMinBlue = maskMinRGB[2];
maskMaxRed = maskMaxRGB[0];
maskMaxGreen = maskMaxRGB[1];
maskMaxBlue = maskMaxRGB[2];
}
if (smaskRaster == null && maskRaster == null &&
(maskMinRGB == null || maskMaxRGB == null)){
return null;
}
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
boolean gotARBG = false;
int argb = 0;
int alpha = 0xFF;
if (y < smaskHeight && x < smaskWidth && smaskRaster != null) {
// Alpha equals greyscale value of smask
alpha = (smaskRaster.getSample(x, y, 0) & 0xFF);
} else if (y < maskHeight && x < maskWidth && maskRaster != null) {
// When making an ImageMask, the alpha channnel is setup so that
// it both works correctly for the ImageMask being painted,
// and also for when it's used here, to determine the alpha
// of an image that it's masking
alpha = (maskImage.getRGB(x, y) >>> 24) & 0xFF; // Extract Alpha from ARGB
} else {
gotARBG = true;
argb = bi.getRGB(x, y);
int red = ((argb >> 16) & 0xFF);
int green = ((argb >> 8) & 0xFF);
int blue = (argb & 0xFF);
if (blue >= maskMinBlue && blue <= maskMaxBlue &&
green >= maskMinGreen && green <= maskMaxGreen &&
red >= maskMinRed && red <= maskMaxRed) {
alpha = 0x00;
}
}
if (alpha != 0xFF) {
if (!gotARBG)
argb = bi.getRGB(x, y);
argb &= 0x00FFFFFF;
argb |= ((alpha << 24) & 0xFF000000);
bi.setRGB(x, y, argb);
}
}
}
// apply the soft mask.
BufferedImage tmpImage = bi;
if (smaskImage != null) {
BufferedImage argbImage = new BufferedImage(width,
height, BufferedImage.TYPE_INT_ARGB);
int[] srcBand = new int[width];
int[] sMaskBand = new int[width];
// iterate over each band to apply the mask
for (int i = 0; i < height; i++) {
tmpImage.getRGB(0, i, width, 1, srcBand, 0, width);
smaskImage.getRGB(0, i, width, 1, sMaskBand, 0, width);
// apply the soft mask blending
for (int j = 0; j < width; j++) {
sMaskBand[j] = ((sMaskBand[j] & 0xff) << 24)
| (srcBand[j] & ~0xff000000);
}
argbImage.setRGB(0, i, width, 1, sMaskBand, 0, width);
}
tmpImage.flush();
tmpImage = argbImage;
}
return tmpImage;
}
private static WritableRaster alterRasterRGBA(WritableRaster wr, BufferedImage smaskImage, BufferedImage maskImage, int[] maskMinRGB, int[] maskMaxRGB) {
Raster smaskRaster = null;
int smaskWidth = 0;
int smaskHeight = 0;
if (smaskImage != null) {
smaskRaster = smaskImage.getRaster();
smaskWidth = smaskRaster.getWidth();
smaskHeight = smaskRaster.getHeight();
}
Raster maskRaster = null;
int maskWidth = 0;
int maskHeight = 0;
if (maskImage != null) {
maskRaster = maskImage.getRaster();
maskWidth = maskRaster.getWidth();
maskHeight = maskRaster.getHeight();
}
int maskMinRed = 0xFF;
int maskMinGreen = 0xFF;
int maskMinBlue = 0xFF;
int maskMaxRed = 0x00;
int maskMaxGreen = 0x00;
int maskMaxBlue = 0x00;
if (maskMinRGB != null && maskMaxRGB != null) {
maskMinRed = maskMinRGB[0];
maskMinGreen = maskMinRGB[1];
maskMinBlue = maskMinRGB[2];
maskMaxRed = maskMaxRGB[0];
maskMaxGreen = maskMaxRGB[1];
maskMaxBlue = maskMaxRGB[2];
}
if (smaskRaster == null && maskRaster == null && (maskMinRGB == null || maskMaxRGB == null))
return null;
int[] rgbaValues = new int[4];
int width = wr.getWidth();
int height = wr.getHeight();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
wr.getPixel(x, y, rgbaValues);
int red = rgbaValues[0];
int green = rgbaValues[1];
int blue = rgbaValues[2];
int alpha = 0xFF;
if (y < smaskHeight && x < smaskWidth && smaskRaster != null) {
// Alpha equals greyscale value of smask
alpha = (smaskImage.getRGB(x, y)) & 0xFF;//(smaskRaster.getSample(x, y, 0) & 0xFF);
} else if (y < maskHeight && x < maskWidth && maskRaster != null) {
// When making an ImageMask, the alpha channnel is setup so that
// it both works correctly for the ImageMask being painted,
// and also for when it's used here, to determine the alpha
// of an image that it's masking
alpha = (maskImage.getRGB(x, y) >>> 24) & 0xFF; // Extract Alpha from ARGB
} else if (blue >= maskMinBlue && blue <= maskMaxBlue &&
green >= maskMinGreen && green <= maskMaxGreen &&
red >= maskMinRed && red <= maskMaxRed) {
alpha = 0x00;
}
if (alpha != 0xFF) {
rgbaValues[3] = alpha;
wr.setPixel(x, y, rgbaValues);
}
}
}
return wr;
}
private static void alterRasterRGB2PColorSpace(WritableRaster wr, PColorSpace colorSpace) {
//System.out.println("alterRasterRGB2PColorSpace() colorSpace: " + colorSpace);
if (colorSpace instanceof DeviceRGB)
return;
float[] values = new float[3];
int[] rgbValues = new int[3];
int width = wr.getWidth();
int height = wr.getHeight();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
wr.getPixel(x, y, rgbValues);
PColorSpace.reverseInPlace(rgbValues);
colorSpace.normaliseComponentsToFloats(rgbValues, values, 255.0f);
Color c = colorSpace.getColor(values);
rgbValues[0] = c.getRed();
rgbValues[1] = c.getGreen();
rgbValues[2] = c.getBlue();
wr.setPixel(x, y, rgbValues);
}
}
}
private static void alterRasterY2Gray(WritableRaster wr, int bitsPerComponent,
Vector decode) {
int[] values = new int[1];
int width = wr.getWidth();
int height = wr.getHeight();
boolean defaultDecode = (0.0f == ((Number) decode.elementAt(0)).floatValue());
int Y;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
wr.getPixel(x, y, values);
Y = values[0];
Y = defaultDecode?255 - Y:Y;
Y = (Y < 0) ? (byte) 0 : (Y > 255) ? (byte) 0xFF : (byte) Y;
values[0] = Y;
wr.setPixel(x, y, values);
}
}
}
private static int getJPEGEncoding(byte[] data, int dataLength) {
int jpegEncoding = JPEG_ENC_UNKNOWN_PROBABLY_YCbCr;
boolean foundAPP14 = false;
byte compsTypeFromAPP14 = 0;
boolean foundSOF = false;
int numCompsFromSOF = 0;
boolean foundSOS = false;
int numCompsFromSOS = 0;
int index = 0;
while (true) {
if (index >= dataLength)
break;
if (data[index] != ((byte) 0xFF))
break;
if (foundAPP14 && foundSOF)
break;
byte segmentType = data[index + 1];
index += 2;
if (segmentType == ((byte) 0xD8)) {
//System.out.println("Found SOI (0xD8)");
continue;
}
//System.out.println("Segment: " + Integer.toHexString( ((int)segmentType)&0xFF ));
int length = (((data[index] << 8)) & 0xFF00) + (((int) data[index + 1]) & 0xFF);
//System.out.println(" Length: " + length + " Index: " + index);
// APP14 (Might be Adobe file)
if (segmentType == ((byte) 0xEE)) {
//System.out.println("Found APP14 (0xEE)");
if (length >= 14) {
foundAPP14 = true;
compsTypeFromAPP14 = data[index + 13];
//System.out.println("APP14 format: " + compsTypeFromAPP14);
}
} else if (segmentType == ((byte) 0xC0)) {
foundSOF = true;
//System.out.println("Found SOF (0xC0) Start Of Frame");
//int bitsPerSample = ( ((int)data[index+2]) & 0xFF );
//int imageHeight = ( ((int)(data[index+3] << 8)) & 0xFF00 ) + ( ((int)data[index+4]) & 0xFF );
//int imageWidth = ( ((int)(data[index+5] << 8)) & 0xFF00 ) + ( ((int)data[index+6]) & 0xFF );
numCompsFromSOF = (((int) data[index + 7]) & 0xFF);
//System.out.println(" bitsPerSample: " + bitsPerSample + ", imageWidth: " + imageWidth + ", imageHeight: " + imageHeight + ", numComps: " + numCompsFromSOF);
//int[] compIds = new int[numCompsFromSOF];
//for(int i = 0; i < numCompsFromSOF; i++) {
// compIds[i] = ( ((int)data[index+8+(i*3)]) & 0xff );
// System.out.println(" compId: " + compIds[i]);
//}
} else if (segmentType == ((byte) 0xDA)) {
foundSOS = true;
//System.out.println("Found SOS (0xDA) Start Of Scan");
numCompsFromSOS = (((int) data[index + 2]) & 0xFF);
//int[] compIds = new int[numCompsFromSOS];
//for(int i = 0; i < numCompsFromSOS; i++) {
// compIds[i] = ( ((int)data[index+3+(i*2)]) & 0xff );
// System.out.println(" compId: " + compIds[i]);
//}
}
//System.out.println(" Data: " + org.icepdf.core.util.Utils.convertByteArrayToHexString( data, index+2, Math.min(length-2,dataLength-index-2), true, 20, '\n' ));
index += length;
}
if (foundAPP14 && foundSOF) {
if (compsTypeFromAPP14 == 0) { // 0 seems to indicate no conversion
if (numCompsFromSOF == 1)
jpegEncoding = JPEG_ENC_GRAY;
if (numCompsFromSOF == 3) // Most assume RGB. DesignJava_times_roman_substitution.PDF supports this.
jpegEncoding = JPEG_ENC_RGB;
else if (numCompsFromSOF == 4) // CMYK
jpegEncoding = JPEG_ENC_CMYK;
} else if (compsTypeFromAPP14 == 1) { // YCbCr
jpegEncoding = JPEG_ENC_YCbCr;
} else if (compsTypeFromAPP14 == 2) { // YCCK
jpegEncoding = JPEG_ENC_YCCK;
}
} else if (foundSOS) {
if (numCompsFromSOS == 1)
jpegEncoding = JPEG_ENC_GRAY; // Y
}
return jpegEncoding;
}
/**
* Utility to build an RGBA buffered image using the specified raster and
* a Transparency.OPAQUE transparency model.
*
* @param wr writable raster of image.
* @return constructed image.
*/
private static BufferedImage makeRGBABufferedImage(WritableRaster wr) {
return makeRGBABufferedImage(wr, Transparency.OPAQUE);
}
/**
* Utility to build an RGBA buffered image using the specified raster and
* transparency type.
*
* @param wr writable raster of image.
* @param transparency any valid Transparency interface type. Bitmask,
* opaque and translucent.
* @return constructed image.
*/
private static BufferedImage makeRGBABufferedImage(WritableRaster wr,
final int transparency) {
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
int[] bits = new int[4];
for (int i = 0; i < bits.length; i++)
bits[i] = 8;
ColorModel cm = new ComponentColorModel(
cs, bits, true, false,
transparency,
wr.getTransferType());
BufferedImage img = new BufferedImage(cm, wr, false, null);
return img;
}
private static BufferedImage makeRGBBufferedImage(WritableRaster wr) {
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
int[] bits = new int[3];
for (int i = 0; i < bits.length; i++)
bits[i] = 8;
ColorModel cm = new ComponentColorModel(
cs, bits, false, false,
ColorModel.OPAQUE,
wr.getTransferType());
BufferedImage img = new BufferedImage(cm, wr, false, null);
return img;
}
private static BufferedImage makeGrayBufferedImage(WritableRaster wr) {
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
int[] bits = new int[1];
for (int i = 0; i < bits.length; i++)
bits[i] = 8;
ColorModel cm = new ComponentColorModel(
cs, bits, false, false,
ColorModel.OPAQUE,
wr.getTransferType());
BufferedImage img = new BufferedImage(cm, wr, false, null);
return img;
}
// This method returns a buffered image with the contents of an image from
// java almanac
private BufferedImage makeRGBABufferedImageFromImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage) image;
}
// This code ensures that all the pixels in the image are loaded
image = new ImageIcon(image).getImage();
// Determine if the image has transparent pixels; for this method's
// implementation, see Determining If an Image Has Transparent Pixels
boolean hasAlpha = hasAlpha(image);
// Create a buffered image with a format that's compatible with the screen
BufferedImage bImage = null;
try {
// graphics environment calls can through headless exceptions so
// proceed with caution.
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
// Determine the type of transparency of the new buffered image
int transparency = Transparency.OPAQUE;
if (hasAlpha) {
transparency = Transparency.BITMASK;
}
// Create the buffered image
int width = image.getWidth(null);
int height = image.getHeight(null);
if (width == -1 || height == -1) {
return null;
}
bImage = gc.createCompatibleImage(
image.getWidth(null), image.getHeight(null), transparency);
} catch (HeadlessException e) {
// The system does not have a screen
}
if (bImage == null) {
// Create a buffered image using the default color model
int type = BufferedImage.TYPE_INT_RGB;
if (hasAlpha) {
type = BufferedImage.TYPE_INT_ARGB;
}
int width = image.getWidth(null);
int height = image.getHeight(null);
if (width == -1 || height == -1) {
return null;
}
bImage = new BufferedImage(width, height, type);
}
// Copy image to buffered image
Graphics g = bImage.createGraphics();
// Paint the image onto the buffered image
g.drawImage(image, 0, 0, null);
g.dispose();
image.flush();
return bImage;
}
// returns true if the specified image has transparent pixels, from
// java almanac
private static boolean hasAlpha(Image image) {
// If buffered image, the color model is readily available
if (image instanceof BufferedImage) {
BufferedImage bufferedImage = (BufferedImage) image;
return bufferedImage.getColorModel().hasAlpha();
}
// Use a pixel grabber to retrieve the image's color model;
// grabbing a single pixel is usually sufficient
PixelGrabber pixelGrabber = new PixelGrabber(image, 0, 0, 1, 1, false);
try {
pixelGrabber.grabPixels();
} catch (InterruptedException e) {
// fail quietly
}
// Get the image's color model
ColorModel cm = pixelGrabber.getColorModel();
return cm == null || cm.hasAlpha();
}
/**
* CCITT fax decode algorithm, decodes the stream into a valid image
* stream that can be used to create a BufferedImage.
*
* @param width of image
* @param height height of image.
* @return decoded stream bytes.
*/
private byte[] ccittFaxDecode(int width, int height) {
byte[] streamData = getDecodedStreamBytes();
Hashtable decodeParms = library.getDictionary(entries, "DecodeParms");
float k = library.getFloat(decodeParms, "K");
// default value is always false
boolean blackIs1 = getBlackIs1(library, decodeParms);
// get value of key if it is available.
boolean encodedByteAlign = false;
Object encodedByteAlignObject = library.getObject(decodeParms, "EncodedByteAlign");
if (encodedByteAlignObject instanceof Boolean) {
encodedByteAlign = (Boolean) encodedByteAlignObject;
}
int columns = library.getInt(decodeParms, "Columns");
int rows = library.getInt(decodeParms, "Rows");
if (columns == 0) {
columns = width;
}
if (rows == 0) {
rows = height;
}
int size = rows * ((columns + 7) >> 3);
byte[] decodedStreamData = new byte[size];
CCITTFaxDecoder decoder = new CCITTFaxDecoder(1, columns, rows);
decoder.setAlign(encodedByteAlign);
// pick three three possible fax encoding.
try {
if (k == 0) {
decoder.decodeT41D(decodedStreamData, streamData, 0, rows);
} else if (k > 0) {
decoder.decodeT42D(decodedStreamData, streamData, 0, rows);
} else if (k < 0) {
decoder.decodeT6(decodedStreamData, streamData, 0, rows);
}
} catch (Exception e) {
logger.warning("Error decoding CCITTFax image k: " + k );
// IText 5.03 doesn't correctly assign a k value for the deocde,
// as result we can try one more time using the T6.
decoder.decodeT6(decodedStreamData, streamData, 0, rows);
}
// check the black is value flag, no one likes inverted colours.
if (!blackIs1) {
// toggle the byte data invert colour, not bit operand.
for (int i = 0; i < decodedStreamData.length; i++) {
decodedStreamData[i] = (byte) ~decodedStreamData[i];
}
}
return decodedStreamData;
}
/**
* Gets the decoded Byte stream of the Stream object.
*
* @return decoded Byte stream
*/
public byte[] getBytes() {
byte[] data = getDecodedStreamBytes();
if (data == null)
data = new byte[0];
return data;
}
/**
* Gets the image object for the given resource. This method can optionally
* scale an image to reduce the total memory foot print or to increase the
* perceived render quality on screen at low zoom levels.
*
* @param fill color value of image
* @param resources resouces containing image reference
* @param allowScaling true indicates that the image will be scaled, fals
* no scaling.
* @return new image object
*/
// was synchronized, not think it is needed?
public BufferedImage getImage(Color fill, Resources resources, boolean allowScaling) {
if (Tagger.tagging)
Tagger.beginImage(pObjectReference, inlineImage);
//String debugFill = (fill == null) ? "null" : Integer.toHexString(fill.getRGB());
//System.out.println("Stream.getImage() for: " + pObjectReference + " fill: " + debugFill + "\n stream: " + this);
if (Tagger.tagging)
Tagger.tagImage("Filter=" + getNormalisedFilterNames());
// parse colour space
PColorSpace colourSpace = null;
Object o = library.getObject(entries, "ColorSpace");
if (resources != null) {
colourSpace = resources.getColorSpace(o);
}
//colorSpace = PColorSpace.getColorSpace(library, o);
// assume b&w image is no colour space
if (colourSpace == null) {
colourSpace = new DeviceGray(library, null);
if (Tagger.tagging)
Tagger.tagImage("ColorSpace_Implicit_DeviceGray");
}
if (Tagger.tagging)
Tagger.tagImage("ColorSpace=" + colourSpace.getDescription());
boolean imageMask = isImageMask();
if (Tagger.tagging)
Tagger.tagImage("ImageMask=" + imageMask);
if (imageMask)
allowScaling = false;
// find out the number of bits in the image
int bitspercomponent = library.getInt(entries, "BitsPerComponent");
if (imageMask && bitspercomponent == 0) {
bitspercomponent = 1;
if (Tagger.tagging)
Tagger.tagImage("BitsPerComponent_Implicit_1");
}
if (Tagger.tagging)
Tagger.tagImage("BitsPerComponent=" + bitspercomponent);
// get dimension of image stream
int width = library.getInt(entries, "Width");
int height = library.getInt(entries, "Height");
// PDF-458 corner case/one off for trying to guess the width or height
// of an CCITTfax image that is basically the same use as the page, we
// use the page dimensions to try and determine the page size.
// This will fail miserably if the image isn't full page.
if (height == 0){
height = (int)((1/pageRatio)*width);
}else if (width == 0){
width = (int)(pageRatio*height);
}
// check for available memory, get colour space and bit count
// to better estimate size of image in memory
int colorSpaceCompCount = colourSpace.getNumComponents();
// parse decode information
Vector<Integer> decode = (Vector) library.getObject(entries, "Decode");
if (decode == null) {
int depth = colourSpace.getNumComponents();
decode = new Vector<Integer>(depth);
// add a decode param for each colour channel.
for (int i= 0; i < depth; i++){
decode.addElement(0);
decode.addElement(1);
}
if (Tagger.tagging)
Tagger.tagImage("Decode_Implicit_01");
}
if (Tagger.tagging)
Tagger.tagImage("Decode=" + decode);
BufferedImage smaskImage = null;
BufferedImage maskImage = null;
int[] maskMinRGB = null;
int[] maskMaxRGB = null;
int maskMinIndex = -1;
int maskMaxIndex = -1;
Object smaskObj = library.getObject(entries, "SMask");
Object maskObj = library.getObject(entries, "Mask");
if (smaskObj instanceof Stream) {
if (Tagger.tagging)
Tagger.tagImage("SMaskStream");
Stream smaskStream = (Stream) smaskObj;
if (smaskStream.isImageSubtype())
smaskImage = smaskStream.getImage(fill, resources, false);
}
if (smaskImage != null) {
if (Tagger.tagging)
Tagger.tagImage("SMaskImage");
allowScaling = false;
}
if (maskObj != null && smaskImage == null) {
if (maskObj instanceof Stream) {
if (Tagger.tagging)
Tagger.tagImage("MaskStream");
Stream maskStream = (Stream) maskObj;
if (maskStream.isImageSubtype()) {
maskImage = maskStream.getImage(fill, resources, false);
if (maskImage != null) {
if (Tagger.tagging)
Tagger.tagImage("MaskImage");
}
}
} else if (maskObj instanceof Vector) {
if (Tagger.tagging)
Tagger.tagImage("MaskVector");
Vector maskVector = (Vector) maskObj;
int[] maskMinOrigCompsInt = new int[colorSpaceCompCount];
int[] maskMaxOrigCompsInt = new int[colorSpaceCompCount];
for (int i = 0; i < colorSpaceCompCount; i++) {
if ((i * 2) < maskVector.size())
maskMinOrigCompsInt[i] = ((Number) maskVector.get(i * 2)).intValue();
if ((i * 2 + 1) < maskVector.size())
maskMaxOrigCompsInt[i] = ((Number) maskVector.get(i * 2 + 1)).intValue();
}
if (colourSpace instanceof Indexed) {
Indexed icolourSpace = (Indexed) colourSpace;
Color[] colors = icolourSpace.accessColorTable();
if (colors != null &&
maskMinOrigCompsInt.length >= 1 &&
maskMaxOrigCompsInt.length >= 1) {
maskMinIndex = maskMinOrigCompsInt[0];
maskMaxIndex = maskMaxOrigCompsInt[0];
if (maskMinIndex >= 0 && maskMinIndex < colors.length &&
maskMaxIndex >= 0 && maskMaxIndex < colors.length) {
Color minColor = colors[maskMinOrigCompsInt[0]];
Color maxColor = colors[maskMaxOrigCompsInt[0]];
maskMinRGB = new int[]{minColor.getRed(), minColor.getGreen(), minColor.getBlue()};
maskMaxRGB = new int[]{maxColor.getRed(), maxColor.getGreen(), maxColor.getBlue()};
}
}
} else {
PColorSpace.reverseInPlace(maskMinOrigCompsInt);
PColorSpace.reverseInPlace(maskMaxOrigCompsInt);
float[] maskMinOrigComps = new float[colorSpaceCompCount];
float[] maskMaxOrigComps = new float[colorSpaceCompCount];
colourSpace.normaliseComponentsToFloats(maskMinOrigCompsInt, maskMinOrigComps, (1 << bitspercomponent) - 1);
colourSpace.normaliseComponentsToFloats(maskMaxOrigCompsInt, maskMaxOrigComps, (1 << bitspercomponent) - 1);
Color minColor = colourSpace.getColor(maskMinOrigComps);
Color maxColor = colourSpace.getColor(maskMaxOrigComps);
PColorSpace.reverseInPlace(maskMinOrigComps);
PColorSpace.reverseInPlace(maskMaxOrigComps);
maskMinRGB = new int[]{minColor.getRed(), minColor.getGreen(), minColor.getBlue()};
maskMaxRGB = new int[]{maxColor.getRed(), maxColor.getGreen(), maxColor.getBlue()};
}
}
}
BufferedImage img = getImage(
colourSpace, fill,
width, height,
colorSpaceCompCount,
bitspercomponent,
imageMask,
decode,
smaskImage,
maskImage,
maskMinRGB, maskMaxRGB,
maskMinIndex, maskMaxIndex);
if (img != null) {
img = putIntoImageCache(img, width, height, allowScaling);
}
//String title = "Image: " + getPObjectReference();
//CCITTFax.showRenderedImage(img, title);
if (Tagger.tagging)
Tagger.endImage(pObjectReference);
return img;
}
/**
* Utility to to the image work, the public version pretty much just
* parses out image dictionary parameters. This method start the actual
* image decoding.
*
* @param colourSpace colour space of image.
* @param fill fill color to aply to image from current graphics context.
* @param width width of image.
* @param height heigth of image
* @param colorSpaceCompCount colour space component count, 1, 3, 4 etc.
* @param bitsPerComponent number of bits that represent one component.
* @param imageMask boolean flag to use image mask or not.
* @param decode decode array, 1,0 or 0,1 can effect colour interpretation.
* @param smaskImage smaask image value, optional.
* @param maskImage buffered image image mask to apply to decoded image, optional.
* @param maskMinRGB max rgb values for the mask
* @param maskMaxRGB min rgb values for the mask.
* @param maskMinIndex max indexed colour values for the mask.
* @param maskMaxIndex min indexed colour values for the mask.
* @return buffered image of decoded image stream, null if an error occured.
*/
private BufferedImage getImage(
PColorSpace colourSpace, Color fill,
int width, int height,
int colorSpaceCompCount,
int bitsPerComponent,
boolean imageMask,
Vector decode,
BufferedImage smaskImage,
BufferedImage maskImage,
int[] maskMinRGB, int[] maskMaxRGB,
int maskMinIndex, int maskMaxIndex) {
// return cached image if we have already.
if (image != null) {
// If Stream.dispose(true) was called since last call to Stream.getPageImage(),
// then might have to read from file
checkMemory(width * height * Math.max(colorSpaceCompCount, 4));
//TODO There's a race-ish condition here
// checkMemory() could have called Page.reduceMemory(), which
// could have called Stream.dispose(), which could have nulled
// out our "image" field
BufferedImage img = null;
synchronized (imageLock) {
if (image != null) {
img = image.readImage();
}
}
if (img != null) {
return img;
}
}
// No image cash yet, so we decode known image types.
if (image == null) {
BufferedImage decodedImage = null;
// JPEG writes out image if successful
if (shouldUseDCTDecode()) {
if (Tagger.tagging)
Tagger.tagImage("DCTDecode");
decodedImage = dctDecode(width, height, colourSpace, bitsPerComponent,
smaskImage, maskImage, maskMinRGB, maskMaxRGB, decode);
}
// JBIG2 writes out image if successful
else if (shouldUseJBIG2Decode()) {
if (Tagger.tagging)
Tagger.tagImage("JBIG2Decode");
decodedImage = jbig2Decode(width, height, fill, imageMask);
}
// JPEG2000 writes out image if successful
else if (shouldUseJPXDecode()) {
if (Tagger.tagging)
Tagger.tagImage("JPXDecode");
decodedImage = jpxDecode(width, height, colourSpace, bitsPerComponent, fill,
smaskImage, maskImage, maskMinRGB, maskMaxRGB, decode);
}
// finally if we have something then we return it.
if (decodedImage != null) {
// write tmpImage to the cache
return decodedImage;
}
}
byte[] data = null;
int dataLength = 0;
// CCITTfax data is raw byte decode.
if (shouldUseCCITTFaxDecode()) {
// try default ccittfax decode.
if (Tagger.tagging)
Tagger.tagImage("CCITTFaxDecode");
try{
data = ccittFaxDecode(width, height);
dataLength = data.length;
}catch(Throwable e){
// on a failure then fall back to JAI for a try. likely
// will not happen.
if (Tagger.tagging) {
Tagger.tagImage("CCITTFaxDecode JAI");
}
BufferedImage decodedImage = CCITTFax.attemptDeriveBufferedImageFromBytes(
this, library, entries, fill);
if (decodedImage != null){
return decodedImage;
}
}
}
// no further processing needed we can just get the stream bytes using
// normal filter decompression.
else {
Object[] dataAndSize = getDecodedStreamBytesAndSize(
width * height
* colourSpace.getNumComponents()
* bitsPerComponent / 8);
data = (byte[]) dataAndSize[0];
dataLength = (Integer) dataAndSize[1];
}
// finally push the bytes though the common image processor
if (data != null) {
try {
BufferedImage decodedImage = makeImageWithRasterFromBytes(
colourSpace, fill,
width, height,
colorSpaceCompCount,
bitsPerComponent,
imageMask,
decode,
smaskImage,
maskImage,
maskMinRGB, maskMaxRGB,
maskMinIndex, maskMaxIndex,
data, dataLength);
// if we have something then we can decode it.
if (decodedImage != null) {
return decodedImage;
}
}
catch (Exception e) {
logger.log(Level.FINE, "Error building image raster.", e);
}
}
// decodes the image stream and returns an image object. Legacy fallback
// code, should never get here, put there are always corner cases. .
BufferedImage decodedImage = parseImage(
width,
height,
colourSpace,
imageMask,
fill,
bitsPerComponent,
decode,
data,
smaskImage,
maskImage,
maskMinRGB, maskMaxRGB);
return decodedImage;
}
private BufferedImage makeImageWithRasterFromBytes(
PColorSpace colourSpace,
Color fill,
int width, int height,
int colorSpaceCompCount,
int bitspercomponent,
boolean imageMask,
Vector decode,
BufferedImage smaskImage,
BufferedImage maskImage,
int[] maskMinRGB, int[] maskMaxRGB,
int maskMinIndex, int maskMaxIndex, byte[] data, int dataLength) {
BufferedImage img = null;
// check if the ICCBased colour has an alternative that
// we might support for decoding with a colorModel.
if (colourSpace instanceof ICCBased) {
ICCBased iccBased = (ICCBased) colourSpace;
if (iccBased.getAlternate() != null) {
// set the alternate as the current
colourSpace = iccBased.getAlternate();
}
}
if (colourSpace instanceof DeviceGray) {
//System.out.println("Stream.makeImageWithRasterFromBytes() DeviceGray");
if (imageMask && bitspercomponent == 1) {
if (Tagger.tagging)
Tagger.tagImage("HandledBy=RasterFromBytes_DeviceGray_1_ImageMask");
//byte[] data = getDecodedStreamBytes();
//int data_length = data.length;
DataBuffer db = new DataBufferByte(data, dataLength);
WritableRaster wr = Raster.createPackedRaster(db, width, height,
bitspercomponent, new Point(0, 0));
// From PDF 1.6 spec, concerning ImageMask and Decode array:
// todo we nee dot apply the decode method generically as we do
// it in different places different ways.
// [0 1] (the default for an image mask), a sample value of 0 marks
// the page with the current color, and a 1 leaves the previous
// contents unchanged.
// [1 0] Is the reverse
// In case alpha transparency doesn't work, it'll paint white opaquely
boolean defaultDecode = (0.0f == ((Number) decode.elementAt(0)).floatValue());
//int a = Color.white.getRGB();
int a = 0x00FFFFFF; // Clear if alpha supported, else white
int[] cmap = new int[]{
(defaultDecode ? fill.getRGB() : a),
(defaultDecode ? a : fill.getRGB())
};
int transparentIndex = (defaultDecode ? 1 : 0);
IndexColorModel icm = new IndexColorModel(
bitspercomponent, // the number of bits each pixel occupies
cmap.length, // the size of the color component arrays
cmap, // the array of color components
0, // the starting offset of the first color component
true, // indicates whether alpha values are contained in the cmap array
transparentIndex, // the index of the fully transparent pixel
db.getDataType()); // the data type of the array used to represent pixel values. The data type must be either DataBuffer.TYPE_BYTE or DataBuffer.TYPE_USHORT
img = new BufferedImage(icm, wr, false, null);
} else if (bitspercomponent == 1 || bitspercomponent == 2 || bitspercomponent == 4) {
if (Tagger.tagging)
Tagger.tagImage("HandledBy=RasterFromBytes_DeviceGray_124");
//byte[] data = getDecodedStreamBytes();
//int data_length = data.length;
DataBuffer db = new DataBufferByte(data, dataLength);
WritableRaster wr = Raster.createPackedRaster(db, width, height, bitspercomponent, new Point(0, 0));
int[] cmap = null;
if (bitspercomponent == 1) {
boolean defaultDecode = (0.0f == ((Number) decode.elementAt(0)).floatValue());
cmap = defaultDecode ? GRAY_1_BIT_INDEX_TO_RGB : GRAY_1_BIT_INDEX_TO_RGB_REVERSED;
} else if (bitspercomponent == 2)
cmap = GRAY_2_BIT_INDEX_TO_RGB;
else if (bitspercomponent == 4)
cmap = GRAY_4_BIT_INDEX_TO_RGB;
ColorModel cm = new IndexColorModel(bitspercomponent, cmap.length, cmap, 0, false, -1, db.getDataType());
img = new BufferedImage(cm, wr, false, null);
} else if (bitspercomponent == 8) {
if (Tagger.tagging)
Tagger.tagImage("HandledBy=RasterFromBytes_DeviceGray_8");
//byte[] data = getDecodedStreamBytes();
//int data_length = data.length;
DataBuffer db = new DataBufferByte(data, dataLength);
SampleModel sm = new PixelInterleavedSampleModel(db.getDataType(),
width, height, 1, width, new int[]{0});
WritableRaster wr = Raster.createWritableRaster(sm, db, new Point(0, 0));
// apply decode array manually
float[] origValues = new float[3];
int maxValue = ((int) Math.pow(2, bitspercomponent)) - 1;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
wr.getPixel(x, y, origValues);
origValues = getNormalizedComponents(
(byte[])wr.getDataElements(x,y,null), decode, maxValue);
float gray = origValues[0] *255;
byte rByte = (gray < 0) ? (byte) 0 : (gray > 255) ? (byte) 0xFF : (byte) gray;
origValues[0] = rByte;
wr.setPixel(x, y, origValues);
}
}
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorModel cm = new ComponentColorModel(cs, new int[]{bitspercomponent},
false, false, ColorModel.OPAQUE, db.getDataType());
img = new BufferedImage(cm, wr, false, null);
}
// apply explicit mask
if (maskImage != null){
img = applyExplicitMask(img, maskImage);
}
// apply soft mask
if (smaskImage != null){
img = alterBufferedImage(img, smaskImage, maskImage, maskMinRGB, maskMaxRGB);
}
} else if (colourSpace instanceof DeviceRGB) {
if (bitspercomponent == 8) {
if (Tagger.tagging)
Tagger.tagImage("HandledBy=RasterFromBytes_DeviceRGB_8");
checkMemory(width * height * 4);
boolean usingAlpha = smaskImage != null || maskImage != null || ((maskMinRGB != null) && (maskMaxRGB != null));
if (Tagger.tagging)
Tagger.tagImage("RasterFromBytes_DeviceRGB_8_alpha=" + usingAlpha);
int type = usingAlpha ? BufferedImage.TYPE_INT_ARGB :
BufferedImage.TYPE_INT_RGB;
img = new BufferedImage(width, height, type);
int[] dataToRGB = ((DataBufferInt) img.getRaster().getDataBuffer()).getData();
copyDecodedStreamBytesIntoRGB(dataToRGB);
if (usingAlpha)
alterBufferedImage(img, smaskImage, maskImage, maskMinRGB, maskMaxRGB);
}
} else if (colourSpace instanceof DeviceCMYK) {
// TODO Look at doing CMYK properly, fallback code is very slow.
if (false && bitspercomponent == 8) {
if (Tagger.tagging)
Tagger.tagImage("HandledBy=RasterFromBytes_DeviceCMYK_8");
DataBuffer db = new DataBufferByte(data, dataLength);
int[] bandOffsets = new int[colorSpaceCompCount];
for (int i = 0; i < colorSpaceCompCount; i++)
bandOffsets[i] = i;
SampleModel sm = new PixelInterleavedSampleModel(db.getDataType(), width, height, colorSpaceCompCount, colorSpaceCompCount * width, bandOffsets);
WritableRaster wr = Raster.createWritableRaster(sm, db, new Point(0, 0));
//WritableRaster wr = Raster.createInterleavedRaster( db, width, height, colorSpaceCompCount*width, colorSpaceCompCount, bandOffsets, new Point(0,0) );
ColorSpace cs = null;
// try {
//cs = new ColorSpaceCMYK(); //ColorSpace.getInstance( ColorSpace.CS_PYCC );//ColorSpace.TYPE_CMYK );
///cs = ColorSpaceWrapper.getICCColorSpaceInstance("C:\\Documents and Settings\\Mark Collette\\IdeaProjects\\TestJAI\\CMYK.pf");
// }
// catch (Exception csex) {
// if (logger.isLoggable(Level.FINE)) {
// logger.fine("Problem loading CMYK ColorSpace");
// }
// }
int[] bits = new int[colorSpaceCompCount];
for (int i = 0; i < colorSpaceCompCount; i++)
bits[i] = bitspercomponent;
ColorModel cm = new ComponentColorModel(cs, bits, false, false, ColorModel.OPAQUE, db.getDataType());
img = new BufferedImage(cm, wr, false, null);
}
} else if (colourSpace instanceof Indexed) {
if (bitspercomponent == 1 || bitspercomponent == 2 || bitspercomponent == 4) {
if (Tagger.tagging)
Tagger.tagImage("HandledBy=RasterFromBytes_Indexed_124");
colourSpace.init();
Color[] colors = ((Indexed) colourSpace).accessColorTable();
int[] cmap = new int[(colors == null) ? 0 : colors.length];
for (int i = 0; i < cmap.length; i++) {
cmap[i] = colors[i].getRGB();
}
int cmapMaxLength = 1 << bitspercomponent;
if (cmap.length > cmapMaxLength) {
int[] cmapTruncated = new int[cmapMaxLength];
System.arraycopy(cmap, 0, cmapTruncated, 0, cmapMaxLength);
cmap = cmapTruncated;
}
boolean usingIndexedAlpha = maskMinIndex >= 0 && maskMaxIndex >= 0;
boolean usingAlpha = smaskImage != null || maskImage != null ||
((maskMinRGB != null) && (maskMaxRGB != null));
if (Tagger.tagging)
Tagger.tagImage("RasterFromBytes_Indexed_124_alpha=" +
(usingIndexedAlpha ? "indexed" : (usingAlpha ? "alpha" : "false")));
if (usingAlpha) {
DataBuffer db = new DataBufferByte(data, dataLength);
WritableRaster wr = Raster.createPackedRaster(db, width, height, bitspercomponent, new Point(0, 0));
ColorModel cm = new IndexColorModel(bitspercomponent, cmap.length, cmap, 0, false, -1, db.getDataType());
img = new BufferedImage(cm, wr, false, null);
img = alterBufferedImage(img, smaskImage, maskImage, maskMinRGB, maskMaxRGB);
}
else{
DataBuffer db = new DataBufferByte(data, dataLength);
WritableRaster wr = Raster.createPackedRaster(db, width, height, bitspercomponent, new Point(0, 0));
ColorModel cm = new IndexColorModel(bitspercomponent, cmap.length, cmap, 0, false, -1, db.getDataType());
img = new BufferedImage(cm, wr, false, null);
}
} else if (bitspercomponent == 8) {
if (Tagger.tagging)
Tagger.tagImage("HandledBy=RasterFromBytes_Indexed_8");
//byte[] data = getDecodedStreamBytes();
//int data_length = data.length;
colourSpace.init();
Color[] colors = ((Indexed) colourSpace).accessColorTable();
int colorsLength = (colors == null) ? 0 : colors.length;
int[] cmap = new int[256];
for (int i = 0; i < colorsLength; i++) {
cmap[i] = colors[i].getRGB();
}
for (int i = colorsLength; i < cmap.length; i++){
cmap[i] = 0xFF000000;
}
boolean usingIndexedAlpha = maskMinIndex >= 0 && maskMaxIndex >= 0;
boolean usingAlpha = smaskImage != null || maskImage != null || ((maskMinRGB != null) && (maskMaxRGB != null));
if (Tagger.tagging)
Tagger.tagImage("RasterFromBytes_Indexed_8_alpha=" + (usingIndexedAlpha ? "indexed" : (usingAlpha ? "alpha" : "false")));
if (usingIndexedAlpha) {
for (int i = maskMinIndex; i <= maskMaxIndex; i++)
cmap[i] = 0x00000000;
DataBuffer db = new DataBufferByte(data, dataLength);
SampleModel sm = new PixelInterleavedSampleModel(db.getDataType(), width, height, 1, width, new int[]{0});
WritableRaster wr = Raster.createWritableRaster(sm, db, new Point(0, 0));
ColorModel cm = new IndexColorModel(bitspercomponent, cmap.length, cmap, 0, true, -1, db.getDataType());
img = new BufferedImage(cm, wr, false, null);
}else if (usingAlpha) {
checkMemory(width * height * 4);
int[] rgbaData = new int[width * height];
for (int index = 0; index < dataLength; index++) {
int cmapIndex = (data[index] & 0xFF);
rgbaData[index] = cmap[cmapIndex];
}
DataBuffer db = new DataBufferInt(rgbaData, rgbaData.length);
int[] masks = new int[]{0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000};
//SampleModel sm = new SinglePixelPackedSampleModel(
// db.getDataType(), width, height, masks );
WritableRaster wr = Raster.createPackedRaster(db, width, height, width, masks, new Point(0, 0));
alterRasterRGBA(wr, smaskImage, maskImage, maskMinRGB, maskMaxRGB);
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
ColorModel cm = new DirectColorModel(cs, 32, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000, false, db.getDataType());
img = new BufferedImage(cm, wr, false, null);
}else {
DataBuffer db = new DataBufferByte(data, dataLength);
SampleModel sm = new PixelInterleavedSampleModel(db.getDataType(), width, height, 1, width, new int[]{0});
WritableRaster wr = Raster.createWritableRaster(sm, db, new Point(0, 0));
ColorModel cm = new IndexColorModel(bitspercomponent, cmap.length, cmap, 0, false, -1, db.getDataType());
img = new BufferedImage(cm, wr, false, null);
}
}
}
return img;
}
/**
* Parses the image stream and creates a Java Images object based on the
* the given stream and the supporting paramaters.
*
* @param width dimension of new image
* @param height dimension of new image
* @param colorSpace colour space of image
* @param imageMask true if the image has a imageMask, false otherwise
* @param fill colour pased in via graphic state, used to fill in background
* @param bitsPerColour number of bits used in a colour
* @param decode Decode attribute values from PObject
* @return valid java image from the PDF stream
*/
private BufferedImage parseImage(
int width,
int height,
PColorSpace colorSpace,
boolean imageMask,
Color fill,
int bitsPerColour,
Vector decode,
byte[] baCCITTFaxData,
BufferedImage smaskImage,
BufferedImage maskImage,
int[] maskMinRGB, int[] maskMaxRGB) {
if (Tagger.tagging)
Tagger.tagImage("HandledBy=ParseImage");
// store for manipulating bits in image
int[] imageBits = new int[width];
// RGB value for colour used as fill for image
int fillRGB = fill.getRGB();
// Number of colour components in image, should be 3 for RGB or 4
// for ARGB.
int colorSpaceCompCount = colorSpace.getNumComponents();
boolean isDeviceRGB = colorSpace instanceof DeviceRGB;
boolean isDeviceGray = colorSpace instanceof DeviceGray;
// Max value used to represent a colour, usually 255, min is 0
int maxColourValue = ((1 << bitsPerColour) - 1);
int f[] = new int[colorSpaceCompCount];
float ff[] = new float[colorSpaceCompCount];
// image mask from
int imageMaskValue = ((Number) decode.elementAt(0)).intValue();
// decode decode.
float[] decodeArray = null;
if (decode != null) {
decodeArray = new float[decode.size()];
for (int i = 0; i < decodeArray.length; i++) {
decodeArray[i] = ((Number) decode.elementAt(i)).floatValue();
}
}
// System.out.println("image size " + width + "x" + height +
// "\n\tBitsPerComponent " + bitsPerColour +
// "\n\tColorSpace " + colorSpaceCompCount +
// "\n\tFill " + fillRGB +
// "\n\tDecode " + decode +
// "\n\tImageMask " + imageMask +
// "\n\tMaxColorValue " + maxColourValue +
// "\n\tColourSpace " + colorSpace.toString() +
// "\n\tLength " + streamInput.getLength());
// Do a rough check for memory need for this image, we want to over
// estimate the memory needed so that we minimize the change of
// a out of memory error. Because of image caching, there is no
// significant performance hit, as loading the image from file is much
// faster then parsing it from the decoded byte stream.
int memoryNeeded = (width * height * 4); // ARGB
checkMemory(memoryNeeded);
// Create the memory hole where where the buffered image will be writen
// too, bit by painfull bit.
BufferedImage bim = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
// create the buffer and get the first series of bytes from the cached
// stream
BitStream in;
if (baCCITTFaxData != null) {
in = new BitStream(new ByteArrayInputStream(baCCITTFaxData));
} else {
InputStream dataInput = getInputStreamForDecodedStreamBytes();
if (dataInput == null)
return null;
in = new BitStream(dataInput);
}
try {
// Start encoding bit stream into an image, we work one pixel at
// a time, and grap the need bit information for the images
// colour space and bits per colour
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
// if image has mask apply it
if (imageMask) {
int bit = in.getBits(bitsPerColour);
bit = (bit == imageMaskValue) ? fillRGB : 0x00000000;
imageBits[x] = bit;
}
// other wise start colour bit parsing
else {
// set some default values
int red = 255;
int blue = 255;
int green = 255;
int alpha = 255;
// indexed colour
if (colorSpaceCompCount == 1) {
// get value used for this bit
int bit = in.getBits(bitsPerColour);
// check decode array if a colour inversion is needed
if (decodeArray != null) {
// if index 0 > index 1 then we have a need for ainversion
if (decodeArray[0] > decodeArray[1]) {
bit = (bit == maxColourValue) ? 0x00000000 : maxColourValue;
}
}
if (isDeviceGray) {
if (bitsPerColour == 1)
bit = GRAY_1_BIT_INDEX_TO_RGB[bit];
else if (bitsPerColour == 2)
bit = GRAY_2_BIT_INDEX_TO_RGB[bit];
else if (bitsPerColour == 4)
bit = GRAY_4_BIT_INDEX_TO_RGB[bit];
else if (bitsPerColour == 8) {
bit = ((bit << 24) |
(bit << 16) |
(bit << 8) |
bit);
}
imageBits[x] = bit;
} else {
f[0] = bit;
colorSpace.normaliseComponentsToFloats(f, ff, maxColourValue);
Color color = colorSpace.getColor(ff);
imageBits[x] = color.getRGB();
}
}
// normal RGB colour
else if (colorSpaceCompCount == 3) {
// We can have an ICCBased color space that has 3 components,
// but where we can't assume it's RGB.
// But, when it is DeviceRGB, we don't want the performance hit
// of converting the pixels via the PColorSpace, so we'll
// break this into the two cases
if (isDeviceRGB) {
red = in.getBits(bitsPerColour);
green = in.getBits(bitsPerColour);
blue = in.getBits(bitsPerColour);
// combine the colour together
imageBits[x] = (alpha << 24) | (red << 16) |
(green << 8) | blue;
} else {
for (int i = 0; i < colorSpaceCompCount; i++) {
f[i] = in.getBits(bitsPerColour);
}
PColorSpace.reverseInPlace(f);
colorSpace.normaliseComponentsToFloats(f, ff, maxColourValue);
Color color = colorSpace.getColor(ff);
imageBits[x] = color.getRGB();
}
}
// normal aRGB colour, this could use some more
// work for optimizing.
else if (colorSpaceCompCount == 4) {
for (int i = 0; i < colorSpaceCompCount; i++) {
f[i] = in.getBits(bitsPerColour);
}
PColorSpace.reverseInPlace(f);
colorSpace.normaliseComponentsToFloats(f, ff, maxColourValue);
Color color = colorSpace.getColor(ff);
imageBits[x] = color.getRGB();
}
// else just set pixel with the default values
else {
// compine the colour together
imageBits[x] = (alpha << 24) | (red << 16) |
(green << 8) | blue;
}
}
}
// Assign the new bits for this pixel
bim.setRGB(0, y, width, 1, imageBits, 0, 1);
}
// final clean up.
in.close();
in = null;
if (smaskImage != null || maskImage != null || maskMinRGB != null || maskMaxRGB != null) {
WritableRaster wr = bim.getRaster();
alterRasterRGBA(wr, smaskImage, maskImage, maskMinRGB, maskMaxRGB);
}
}
catch (IOException e) {
logger.log(Level.FINE, "Error parsing image.", e);
}
return bim;
}
private BufferedImage putIntoImageCache(BufferedImage bim, int width, int height, boolean allowScaling) {
// create new Image cache if needed.
if (image == null) {
image = new ImageCache(library);
}
boolean setIsScaledOnImageCache = false;
if (allowScaling && scaleImages && !image.isScaled()) {
boolean canScale = checkMemory(
Math.max(width, bim.getWidth()) *
Math.max(height, bim.getHeight()) *
Math.max(4, bim.getColorModel().getPixelSize()));
if (canScale) {
// To limit the number of image file cache writes this scaling
// algorithem works with the buffered image in memory
bim = ImageCache.scaleBufferedImage(bim, width, height);
setIsScaledOnImageCache = true;
}
}
// The checkMemory call above can make us lose our ImageCache
synchronized (imageLock) {
if (image == null) {
image = new ImageCache(library);
}
// cache the new image
if (setIsScaledOnImageCache)
image.setIsScaled(true);
image.setImage(bim);
// read the image from the cache and return to caller
bim = image.readImage();
}
return bim;
}
/**
* Does the image have an ImageMask.
*/
public boolean isImageMask() {
Object o = library.getObject(entries, "ImageMask");
return (o != null)
? (o.toString().equals("true") ? true : false)
: false;
}
public boolean getBlackIs1(Library library, Hashtable decodeParmsDictionary) {
Boolean blackIs1 = getBlackIs1OrNull(library, decodeParmsDictionary);
if (blackIs1 != null)
return blackIs1.booleanValue();
return false;
}
/**
* If BlackIs1 was not specified, then return null, instead of the
* default value of false, so we can tell if it was given or not
*/
public Boolean getBlackIs1OrNull(Library library, Hashtable decodeParmsDictionary) {
Object blackIs1Obj = library.getObject(decodeParmsDictionary, "BlackIs1");
if (blackIs1Obj != null) {
if (blackIs1Obj instanceof Boolean) {
return (Boolean) blackIs1Obj;
} else if (blackIs1Obj instanceof String) {
String blackIs1String = (String) blackIs1Obj;
if (blackIs1String.equalsIgnoreCase("true"))
return Boolean.TRUE;
else if (blackIs1String.equalsIgnoreCase("t"))
return Boolean.TRUE;
else if (blackIs1String.equals("1"))
return Boolean.TRUE;
else if (blackIs1String.equalsIgnoreCase("false"))
return Boolean.FALSE;
else if (blackIs1String.equalsIgnoreCase("f"))
return Boolean.FALSE;
else if (blackIs1String.equals("0"))
return Boolean.FALSE;
}
}
return null;
}
/**
* Allow access to seakable intput so that pattern object can
* be corrrectly created.
*
* @return stream istnaces SeekableInputConstrainedWrapper
*/
public SeekableInputConstrainedWrapper getStreamInput() {
return streamInput;
}
/**
* Return a string description of the object. Primarly used for debugging.
*/
public String toString() {
StringBuilder sb = new StringBuilder(64);
sb.append("STREAM= ");
sb.append(entries);
if (getPObjectReference() != null) {
sb.append(" ");
sb.append(getPObjectReference());
}
return sb.toString();
}
/**
* Clips the value according to the specified floor and ceiling.
* @param floor floor value of clip
* @param ceiling ceiling value of clip
* @param value value to clip.
* @return clipped value.
*/
private static double clip(double floor, double ceiling, double value) {
if (value < floor){
value = floor;
}
if (value > ceiling){
value = ceiling;
}
return value;
}
private static void displayImage(BufferedImage bufferedImage){
int width2 = bufferedImage.getWidth();
int height2 = bufferedImage.getHeight();
final BufferedImage bi = bufferedImage;
// final BufferedImage bi = new BufferedImage(width2,height2, BufferedImage.TYPE_INT_RGB);
// for (int y = 0; y < height2; y++) {
// for (int x = 0; x < width2; x++) {
// if (bufferedImage.getRGB(x,y) != -1){
// bi.setRGB(x, y, Color.red.getRGB());
// }
// else{
// bi.setRGB(x, y, Color.green.getRGB());
// }
// }
// }
final JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
JComponent image = new JComponent() {
@Override
public void paint(Graphics g_) {
super.paint(g_);
g_.drawImage(bi, 0, 0, f);
}
};
image.setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight()));
image.setSize(new Dimension(bi.getWidth(), bi.getHeight()));
JPanel test = new JPanel();
test.setPreferredSize(new Dimension(1200,1200));
JScrollPane tmp = new JScrollPane(image);
tmp.revalidate();
f.setSize(new Dimension(800, 800));
f.getContentPane().add(tmp);
f.validate();
f.setVisible(true);
}
}
| false | true | private BufferedImage dctDecode(
int width, int height, PColorSpace colourSpace, int bitspercomponent,
BufferedImage smaskImage, BufferedImage maskImage,
int[] maskMinRGB, int[] maskMaxRGB, Vector<Integer> decode) {
// BIS's buffer size should be equal to mark() size, and greater than data size (below)
InputStream input = getInputStreamForDecodedStreamBytes();
// Used to just read 1000, but found a PDF that included thumbnails first
final int MAX_BYTES_TO_READ_FOR_ENCODING = 2048;
BufferedInputStream bufferedInput = new BufferedInputStream(
input, MAX_BYTES_TO_READ_FOR_ENCODING);
bufferedInput.mark(MAX_BYTES_TO_READ_FOR_ENCODING);
// We don't use the PColorSpace to determine how to decode the JPEG, because it tends to be wrong
// Some files say DeviceCMYK, or ICCBased, when neither would work, because it's really YCbCrA
// What does work though, is to look into the JPEG headers themself, via getJPEGEncoding()
int jpegEncoding = Stream.JPEG_ENC_UNKNOWN_PROBABLY_YCbCr;
try {
byte[] data = new byte[MAX_BYTES_TO_READ_FOR_ENCODING];
int dataRead = bufferedInput.read(data);
bufferedInput.reset();
if (dataRead > 0)
jpegEncoding = getJPEGEncoding(data, dataRead);
}
catch (IOException ioe) {
logger.log(Level.FINE, "Problem determining JPEG type: ", ioe);
}
if (Tagger.tagging)
Tagger.tagImage("DCTDecode_JpegEncoding=" + JPEG_ENC_NAMES[jpegEncoding]);
//System.out.println("Stream.dctDecode() objectNumber: " + getPObjectReference().getObjectNumber());
//System.out.println("Stream.dctDecode() jpegEncoding: " + JPEG_ENC_NAMES[jpegEncoding]);
//System.out.println("Stream.dctDecode() smask: " + smaskImage);
//System.out.println("Stream.dctDecode() mask: " + maskImage);
//System.out.println("Stream.dctDecode() maskMinRGB: " + maskMinRGB);
//System.out.println("Stream.dctDecode() maskMaxRGB: " + maskMaxRGB);
//long beginUsedMem = (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory());
//long beginTime = System.currentTimeMillis();
BufferedImage tmpImage = null;
if (tmpImage == null) {
try {
//System.out.println("Stream.dctDecode() JPEGImageDecoder");
JPEGImageDecoder imageDecoder = JPEGCodec.createJPEGDecoder(bufferedInput);
int bizarreFudge = 64 * 1024 + (int) streamInput.getLength();
checkMemory(width * height * 8 + bizarreFudge);
if (jpegEncoding == JPEG_ENC_RGB && bitspercomponent == 8) {
//System.out.println("Stream.dctDecode() JPEG_ENC_RGB");
Raster r = imageDecoder.decodeAsRaster();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
//System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID());
alterRasterRGB2PColorSpace(wr, colourSpace);
tmpImage = makeRGBBufferedImage(wr);
} else if (jpegEncoding == JPEG_ENC_CMYK && bitspercomponent == 8) {
//System.out.println("Stream.dctDecode() JPEG_ENC_CMYK");
Raster r = imageDecoder.decodeAsRaster();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
//System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID());
tmpImage = alterRasterCMYK2BGRA(wr, smaskImage, maskImage); //TODO Use maskMinRGB, maskMaxRGB or orig comp version here
} else if (jpegEncoding == JPEG_ENC_YCbCr && bitspercomponent == 8) {
//System.out.println("Stream.dctDecode() JPEG_ENC_YCbCr");
Raster r = imageDecoder.decodeAsRaster();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
//System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID());
tmpImage = alterRasterYCbCr2RGB(wr, smaskImage, maskImage, decode, bitspercomponent);
} else if (jpegEncoding == JPEG_ENC_YCCK && bitspercomponent == 8) {
//System.out.println("Stream.dctDecode() JPEG_ENC_YCCK");
Raster r = imageDecoder.decodeAsRaster();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
//System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID());
// YCCK to RGB works better if an CMYK intermediate is used, but slower.
alterRasterYCCK2CMYK(wr, decode,bitspercomponent);
tmpImage = alterRasterCMYK2BGRA(wr, smaskImage, maskImage);
} else if (jpegEncoding == JPEG_ENC_GRAY && bitspercomponent == 8) {
//System.out.println("Stream.dctDecode() JPEG_ENC_GRAY");
Raster r = imageDecoder.decodeAsRaster();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
//System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID());
// In DCTDecode with ColorSpace=DeviceGray, the samples are gray values (2000_SID_Service_Info.core)
// In DCTDecode with ColorSpace=Separation, the samples are Y values (45-14550BGermanForWeb.core AKA 4570.core)
// Instead of assuming that Separation is special, I'll assume that DeviceGray is
if (!(colourSpace instanceof DeviceGray) &&
!(colourSpace instanceof ICCBased)) {
if (Tagger.tagging)
Tagger.tagImage("DCTDecode_JpegSubEncoding=Y");
alterRasterY2Gray(wr, bitspercomponent, decode); //TODO Use smaskImage, maskImage, maskMinRGB, maskMaxRGB or orig comp version here
}
tmpImage = makeGrayBufferedImage(wr);
// apply mask value
if (maskImage != null){
tmpImage = applyExplicitMask(tmpImage, maskImage);
}
if (smaskImage != null){
tmpImage = applyExplicitSMask(tmpImage, smaskImage);
}
} else {
//System.out.println("Stream.dctDecode() Other");
//tmpImage = imageDecoder.decodeAsBufferedImage();
Raster r = imageDecoder.decodeAsRaster();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
//System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID());
if (imageDecoder.getJPEGDecodeParam().getEncodedColorID() ==
com.sun.image.codec.jpeg.JPEGDecodeParam.COLOR_ID_YCbCrA) {
if (Tagger.tagging)
Tagger.tagImage("DCTDecode_JpegSubEncoding=YCbCrA");
// YCbCrA, which is slightly different than YCCK
alterRasterYCbCrA2RGBA_new(wr, smaskImage, maskImage,
decode, bitspercomponent); //TODO Use maskMinRGB, maskMaxRGB or orig comp version here
tmpImage = makeRGBABufferedImage(wr);
} else {
if (Tagger.tagging)
Tagger.tagImage("DCTDecode_JpegSubEncoding=YCbCr");
alterRasterYCbCr2RGB(wr, smaskImage, maskImage, decode, bitspercomponent);
tmpImage = makeRGBBufferedImage(wr);
// special case to handle an smask on an RGB image. In
// such a case we need to copy the rgb and soft mask effect
// to th new ARGB image.
if (smaskImage != null) {
BufferedImage argbImage = new BufferedImage(width,
height, BufferedImage.TYPE_INT_ARGB);
int[] srcBand = new int[width];
int[] sMaskBand = new int[width];
// iterate over each band to apply the mask
for (int i = 0; i < height; i++) {
tmpImage.getRGB(0, i, width, 1, srcBand, 0, width);
smaskImage.getRGB(0, i, width, 1, sMaskBand, 0, width);
// apply the soft mask blending
for (int j = 0; j < width; j++) {
sMaskBand[j] = ((sMaskBand[j] & 0xff) << 24)
| (srcBand[j] & ~0xff000000);
}
argbImage.setRGB(0, i, width, 1, sMaskBand, 0, width);
}
tmpImage.flush();
tmpImage = argbImage;
}
}
}
}
catch (Exception e) {
logger.log(Level.FINE, "Problem loading JPEG image via JPEGImageDecoder: ", e);
}
if (tmpImage != null) {
if (Tagger.tagging)
Tagger.tagImage("HandledBy=DCTDecode_SunJPEGImageDecoder");
}
}
try {
bufferedInput.close();
}
catch (IOException e) {
logger.log(Level.FINE, "Error closing image stream.", e);
}
if (tmpImage == null) {
try {
//System.out.println("Stream.dctDecode() JAI");
Object javax_media_jai_RenderedOp_op = null;
try {
// Have to reget the data
input = getInputStreamForDecodedStreamBytes();
/*
com.sun.media.jai.codec.SeekableStream s = com.sun.media.jai.codec.SeekableStream.wrapInputStream( new ByteArrayInputStream(data), true );
ParameterBlock pb = new ParameterBlock();
pb.add( s );
javax.media.jai.RenderedOp op = javax.media.jai.JAI.create( "jpeg", pb );
*/
Class ssClass = Class.forName("com.sun.media.jai.codec.SeekableStream");
Method ssWrapInputStream = ssClass.getMethod("wrapInputStream", InputStream.class, Boolean.TYPE);
Object com_sun_media_jai_codec_SeekableStream_s =
ssWrapInputStream.invoke(null, input, Boolean.TRUE);
ParameterBlock pb = new ParameterBlock();
pb.add(com_sun_media_jai_codec_SeekableStream_s);
Class jaiClass = Class.forName("javax.media.jai.JAI");
Method jaiCreate = jaiClass.getMethod("create", String.class, ParameterBlock.class);
javax_media_jai_RenderedOp_op = jaiCreate.invoke(null, "jpeg", pb);
}
catch (Exception e) {
}
if (javax_media_jai_RenderedOp_op != null) {
if (jpegEncoding == JPEG_ENC_CMYK && bitspercomponent == 8) {
/*
* With or without alterRasterCMYK2BGRA(), give blank image
Raster r = op.copyData();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
alterRasterCMYK2BGRA( wr );
tmpImage = makeRGBABufferedImage( wr );
*/
/*
* With alterRasterCMYK2BGRA() colors gibbled, without is blank
* Slower, uses more memory, than JPEGImageDecoder
BufferedImage img = op.getAsBufferedImage();
WritableRaster wr = img.getRaster();
alterRasterCMYK2BGRA( wr );
tmpImage = img;
*/
} else if (jpegEncoding == JPEG_ENC_YCCK && bitspercomponent == 8) {
/*
* This way, with or without alterRasterYCbCrA2BGRA(), give blank image
Raster r = op.getData();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
alterRasterYCbCrA2BGRA( wr );
tmpImage = makeRGBABufferedImage( wr );
*/
/*
* With alterRasterYCbCrA2BGRA() colors gibbled, without is blank
* Slower, uses more memory, than JPEGImageDecoder
BufferedImage img = op.getAsBufferedImage();
WritableRaster wr = img.getRaster();
alterRasterYCbCrA2BGRA( wr );
tmpImage = img;
*/
} else {
//System.out.println("Stream.dctDecode() Other");
/* tmpImage = op.getAsBufferedImage(); */
Class roClass = Class.forName("javax.media.jai.RenderedOp");
Method roGetAsBufferedImage = roClass.getMethod("getAsBufferedImage");
tmpImage = (BufferedImage) roGetAsBufferedImage.invoke(javax_media_jai_RenderedOp_op);
if (tmpImage != null) {
if (Tagger.tagging)
Tagger.tagImage("HandledBy=DCTDecode_JAI");
}
}
}
}
catch (Exception e) {
logger.log(Level.FINE, "Problem loading JPEG image via JAI: ", e);
}
try {
input.close();
}
catch (IOException e) {
logger.log(Level.FINE, "Problem closing image stream. ", e);
}
}
if (tmpImage == null) {
try {
//System.out.println("Stream.dctDecode() Toolkit");
byte[] data = getDecodedStreamBytes();
if (data != null) {
Image img = Toolkit.getDefaultToolkit().createImage(data);
if (img != null) {
tmpImage = makeRGBABufferedImageFromImage(img);
if (Tagger.tagging)
Tagger.tagImage("HandledBy=DCTDecode_ToolkitCreateImage");
}
}
}
catch (Exception e) {
logger.log(Level.FINE, "Problem loading JPEG image via Toolkit: ", e);
}
}
//long endUsedMem = (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory());
//long endTime = System.currentTimeMillis();
//System.out.println("Mem used: " + (endUsedMem-beginUsedMem) + ",\ttime: " + (endTime-beginTime));
return tmpImage;
}
| private BufferedImage dctDecode(
int width, int height, PColorSpace colourSpace, int bitspercomponent,
BufferedImage smaskImage, BufferedImage maskImage,
int[] maskMinRGB, int[] maskMaxRGB, Vector<Integer> decode) {
// BIS's buffer size should be equal to mark() size, and greater than data size (below)
InputStream input = getInputStreamForDecodedStreamBytes();
// Used to just read 1000, but found a PDF that included thumbnails first
final int MAX_BYTES_TO_READ_FOR_ENCODING = 2048;
BufferedInputStream bufferedInput = new BufferedInputStream(
input, MAX_BYTES_TO_READ_FOR_ENCODING);
bufferedInput.mark(MAX_BYTES_TO_READ_FOR_ENCODING);
// We don't use the PColorSpace to determine how to decode the JPEG, because it tends to be wrong
// Some files say DeviceCMYK, or ICCBased, when neither would work, because it's really YCbCrA
// What does work though, is to look into the JPEG headers themself, via getJPEGEncoding()
int jpegEncoding = Stream.JPEG_ENC_UNKNOWN_PROBABLY_YCbCr;
try {
byte[] data = new byte[MAX_BYTES_TO_READ_FOR_ENCODING];
int dataRead = bufferedInput.read(data);
bufferedInput.reset();
if (dataRead > 0)
jpegEncoding = getJPEGEncoding(data, dataRead);
}
catch (IOException ioe) {
logger.log(Level.FINE, "Problem determining JPEG type: ", ioe);
}
if (Tagger.tagging)
Tagger.tagImage("DCTDecode_JpegEncoding=" + JPEG_ENC_NAMES[jpegEncoding]);
//System.out.println("Stream.dctDecode() objectNumber: " + getPObjectReference().getObjectNumber());
//System.out.println("Stream.dctDecode() jpegEncoding: " + JPEG_ENC_NAMES[jpegEncoding]);
//System.out.println("Stream.dctDecode() smask: " + smaskImage);
//System.out.println("Stream.dctDecode() mask: " + maskImage);
//System.out.println("Stream.dctDecode() maskMinRGB: " + maskMinRGB);
//System.out.println("Stream.dctDecode() maskMaxRGB: " + maskMaxRGB);
//long beginUsedMem = (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory());
//long beginTime = System.currentTimeMillis();
BufferedImage tmpImage = null;
if (tmpImage == null) {
try {
//System.out.println("Stream.dctDecode() JPEGImageDecoder");
JPEGImageDecoder imageDecoder = JPEGCodec.createJPEGDecoder(bufferedInput);
int bizarreFudge = 64 * 1024 + (int) streamInput.getLength();
checkMemory(width * height * 8 + bizarreFudge);
if (jpegEncoding == JPEG_ENC_RGB && bitspercomponent == 8) {
//System.out.println("Stream.dctDecode() JPEG_ENC_RGB");
Raster r = imageDecoder.decodeAsRaster();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
//System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID());
alterRasterRGB2PColorSpace(wr, colourSpace);
tmpImage = makeRGBBufferedImage(wr);
} else if (jpegEncoding == JPEG_ENC_CMYK && bitspercomponent == 8) {
//System.out.println("Stream.dctDecode() JPEG_ENC_CMYK");
Raster r = imageDecoder.decodeAsRaster();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
//System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID());
tmpImage = alterRasterCMYK2BGRA(wr, smaskImage, maskImage); //TODO Use maskMinRGB, maskMaxRGB or orig comp version here
} else if (jpegEncoding == JPEG_ENC_YCbCr && bitspercomponent == 8) {
//System.out.println("Stream.dctDecode() JPEG_ENC_YCbCr");
Raster r = imageDecoder.decodeAsRaster();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
//System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID());
tmpImage = alterRasterYCbCr2RGB(wr, smaskImage, maskImage, decode, bitspercomponent);
} else if (jpegEncoding == JPEG_ENC_YCCK && bitspercomponent == 8) {
//System.out.println("Stream.dctDecode() JPEG_ENC_YCCK");
Raster r = imageDecoder.decodeAsRaster();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
//System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID());
// YCCK to RGB works better if an CMYK intermediate is used, but slower.
alterRasterYCCK2CMYK(wr, decode,bitspercomponent);
tmpImage = alterRasterCMYK2BGRA(wr, smaskImage, maskImage);
} else if (jpegEncoding == JPEG_ENC_GRAY && bitspercomponent == 8) {
//System.out.println("Stream.dctDecode() JPEG_ENC_GRAY");
Raster r = imageDecoder.decodeAsRaster();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
//System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID());
// In DCTDecode with ColorSpace=DeviceGray, the samples are gray values (2000_SID_Service_Info.core)
// In DCTDecode with ColorSpace=Separation, the samples are Y values (45-14550BGermanForWeb.core AKA 4570.core)
// Avoid converting images that are already likely gray.
if (!(colourSpace instanceof DeviceGray) &&
!(colourSpace instanceof ICCBased) &&
!(colourSpace instanceof Indexed)) {
if (Tagger.tagging)
Tagger.tagImage("DCTDecode_JpegSubEncoding=Y");
alterRasterY2Gray(wr, bitspercomponent, decode); //TODO Use smaskImage, maskImage, maskMinRGB, maskMaxRGB or orig comp version here
}
tmpImage = makeGrayBufferedImage(wr);
// apply mask value
if (maskImage != null){
tmpImage = applyExplicitMask(tmpImage, maskImage);
}
if (smaskImage != null){
tmpImage = applyExplicitSMask(tmpImage, smaskImage);
}
} else {
//System.out.println("Stream.dctDecode() Other");
//tmpImage = imageDecoder.decodeAsBufferedImage();
Raster r = imageDecoder.decodeAsRaster();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
//System.out.println("Stream.dctDecode() EncodedColorID: " + imageDecoder.getJPEGDecodeParam().getEncodedColorID());
if (imageDecoder.getJPEGDecodeParam().getEncodedColorID() ==
com.sun.image.codec.jpeg.JPEGDecodeParam.COLOR_ID_YCbCrA) {
if (Tagger.tagging)
Tagger.tagImage("DCTDecode_JpegSubEncoding=YCbCrA");
// YCbCrA, which is slightly different than YCCK
alterRasterYCbCrA2RGBA_new(wr, smaskImage, maskImage,
decode, bitspercomponent); //TODO Use maskMinRGB, maskMaxRGB or orig comp version here
tmpImage = makeRGBABufferedImage(wr);
} else {
if (Tagger.tagging)
Tagger.tagImage("DCTDecode_JpegSubEncoding=YCbCr");
alterRasterYCbCr2RGB(wr, smaskImage, maskImage, decode, bitspercomponent);
tmpImage = makeRGBBufferedImage(wr);
// special case to handle an smask on an RGB image. In
// such a case we need to copy the rgb and soft mask effect
// to th new ARGB image.
if (smaskImage != null) {
BufferedImage argbImage = new BufferedImage(width,
height, BufferedImage.TYPE_INT_ARGB);
int[] srcBand = new int[width];
int[] sMaskBand = new int[width];
// iterate over each band to apply the mask
for (int i = 0; i < height; i++) {
tmpImage.getRGB(0, i, width, 1, srcBand, 0, width);
smaskImage.getRGB(0, i, width, 1, sMaskBand, 0, width);
// apply the soft mask blending
for (int j = 0; j < width; j++) {
sMaskBand[j] = ((sMaskBand[j] & 0xff) << 24)
| (srcBand[j] & ~0xff000000);
}
argbImage.setRGB(0, i, width, 1, sMaskBand, 0, width);
}
tmpImage.flush();
tmpImage = argbImage;
}
}
}
}
catch (Exception e) {
logger.log(Level.FINE, "Problem loading JPEG image via JPEGImageDecoder: ", e);
}
if (tmpImage != null) {
if (Tagger.tagging)
Tagger.tagImage("HandledBy=DCTDecode_SunJPEGImageDecoder");
}
}
try {
bufferedInput.close();
}
catch (IOException e) {
logger.log(Level.FINE, "Error closing image stream.", e);
}
if (tmpImage == null) {
try {
//System.out.println("Stream.dctDecode() JAI");
Object javax_media_jai_RenderedOp_op = null;
try {
// Have to reget the data
input = getInputStreamForDecodedStreamBytes();
/*
com.sun.media.jai.codec.SeekableStream s = com.sun.media.jai.codec.SeekableStream.wrapInputStream( new ByteArrayInputStream(data), true );
ParameterBlock pb = new ParameterBlock();
pb.add( s );
javax.media.jai.RenderedOp op = javax.media.jai.JAI.create( "jpeg", pb );
*/
Class ssClass = Class.forName("com.sun.media.jai.codec.SeekableStream");
Method ssWrapInputStream = ssClass.getMethod("wrapInputStream", InputStream.class, Boolean.TYPE);
Object com_sun_media_jai_codec_SeekableStream_s =
ssWrapInputStream.invoke(null, input, Boolean.TRUE);
ParameterBlock pb = new ParameterBlock();
pb.add(com_sun_media_jai_codec_SeekableStream_s);
Class jaiClass = Class.forName("javax.media.jai.JAI");
Method jaiCreate = jaiClass.getMethod("create", String.class, ParameterBlock.class);
javax_media_jai_RenderedOp_op = jaiCreate.invoke(null, "jpeg", pb);
}
catch (Exception e) {
}
if (javax_media_jai_RenderedOp_op != null) {
if (jpegEncoding == JPEG_ENC_CMYK && bitspercomponent == 8) {
/*
* With or without alterRasterCMYK2BGRA(), give blank image
Raster r = op.copyData();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
alterRasterCMYK2BGRA( wr );
tmpImage = makeRGBABufferedImage( wr );
*/
/*
* With alterRasterCMYK2BGRA() colors gibbled, without is blank
* Slower, uses more memory, than JPEGImageDecoder
BufferedImage img = op.getAsBufferedImage();
WritableRaster wr = img.getRaster();
alterRasterCMYK2BGRA( wr );
tmpImage = img;
*/
} else if (jpegEncoding == JPEG_ENC_YCCK && bitspercomponent == 8) {
/*
* This way, with or without alterRasterYCbCrA2BGRA(), give blank image
Raster r = op.getData();
WritableRaster wr = (r instanceof WritableRaster)
? (WritableRaster) r : r.createCompatibleWritableRaster();
alterRasterYCbCrA2BGRA( wr );
tmpImage = makeRGBABufferedImage( wr );
*/
/*
* With alterRasterYCbCrA2BGRA() colors gibbled, without is blank
* Slower, uses more memory, than JPEGImageDecoder
BufferedImage img = op.getAsBufferedImage();
WritableRaster wr = img.getRaster();
alterRasterYCbCrA2BGRA( wr );
tmpImage = img;
*/
} else {
//System.out.println("Stream.dctDecode() Other");
/* tmpImage = op.getAsBufferedImage(); */
Class roClass = Class.forName("javax.media.jai.RenderedOp");
Method roGetAsBufferedImage = roClass.getMethod("getAsBufferedImage");
tmpImage = (BufferedImage) roGetAsBufferedImage.invoke(javax_media_jai_RenderedOp_op);
if (tmpImage != null) {
if (Tagger.tagging)
Tagger.tagImage("HandledBy=DCTDecode_JAI");
}
}
}
}
catch (Exception e) {
logger.log(Level.FINE, "Problem loading JPEG image via JAI: ", e);
}
try {
input.close();
}
catch (IOException e) {
logger.log(Level.FINE, "Problem closing image stream. ", e);
}
}
if (tmpImage == null) {
try {
//System.out.println("Stream.dctDecode() Toolkit");
byte[] data = getDecodedStreamBytes();
if (data != null) {
Image img = Toolkit.getDefaultToolkit().createImage(data);
if (img != null) {
tmpImage = makeRGBABufferedImageFromImage(img);
if (Tagger.tagging)
Tagger.tagImage("HandledBy=DCTDecode_ToolkitCreateImage");
}
}
}
catch (Exception e) {
logger.log(Level.FINE, "Problem loading JPEG image via Toolkit: ", e);
}
}
//long endUsedMem = (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory());
//long endTime = System.currentTimeMillis();
//System.out.println("Mem used: " + (endUsedMem-beginUsedMem) + ",\ttime: " + (endTime-beginTime));
return tmpImage;
}
|
diff --git a/kornell-gwt/src/main/java/kornell/gui/client/presentation/vitrine/generic/GenericVitrineView.java b/kornell-gwt/src/main/java/kornell/gui/client/presentation/vitrine/generic/GenericVitrineView.java
index 757af6c2..d88087fa 100644
--- a/kornell-gwt/src/main/java/kornell/gui/client/presentation/vitrine/generic/GenericVitrineView.java
+++ b/kornell-gwt/src/main/java/kornell/gui/client/presentation/vitrine/generic/GenericVitrineView.java
@@ -1,154 +1,155 @@
package kornell.gui.client.presentation.vitrine.generic;
import kornell.api.client.Callback;
import kornell.api.client.KornellClient;
import kornell.core.shared.to.UserInfoTO;
import kornell.gui.client.presentation.profile.ProfilePlace;
import kornell.gui.client.presentation.terms.TermsPlace;
import kornell.gui.client.presentation.vitrine.VitrinePlace;
import kornell.gui.client.presentation.vitrine.VitrineView;
import kornell.gui.client.util.ClientProperties;
import com.github.gwtbootstrap.client.ui.Alert;
import com.github.gwtbootstrap.client.ui.Form;
import com.github.gwtbootstrap.client.ui.Image;
import com.github.gwtbootstrap.client.ui.PasswordTextBox;
import com.github.gwtbootstrap.client.ui.TextBox;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.place.shared.PlaceHistoryMapper;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Widget;
//HTTP
public class GenericVitrineView extends Composite implements VitrineView {
interface MyUiBinder extends UiBinder<Widget, GenericVitrineView> {
}
private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);
private PlaceController placeCtrl;
@UiField
TextBox txtUsername;
@UiField
PasswordTextBox pwdPassword;
@UiField
Form frmLogin;
@UiField
Button btnLogin;
@UiField
Button btnRegister;
@UiField
Alert altUnauthorized;
@UiField
Image imgLogo;
@UiField
FlowPanel contentPanel;
private KornellClient client;
private Place defaultPlace;
private PlaceHistoryMapper mapper;
//TODO i18n xml
public GenericVitrineView(
PlaceHistoryMapper mapper,
PlaceController placeCtrl,
Place defaultPlace,
KornellClient client) {
this.placeCtrl = placeCtrl;
this.client = client;
this.defaultPlace = defaultPlace;
this.mapper = mapper;
initWidget(uiBinder.createAndBindUi(this));
pwdPassword.addKeyPressHandler(new KeyPressHandler() {
@Override
public void onKeyPress(KeyPressEvent event) {
if(KeyCodes.KEY_ENTER == event.getCharCode())
doLogin();
}
});
txtUsername.getElement().setAttribute("autocorrect", "off");
txtUsername.getElement().setAttribute("autocapitalize", "off");
btnLogin.removeStyleName("btn");
String imgLogoURL = ClientProperties.getDecoded("institutionAssetsURL");
if(imgLogoURL != null){
imgLogo.setUrl(imgLogoURL + "logo300x80.png");
} else {
imgLogo.setUrl("/skins/first/icons/logo.png");
}
}
@Override
public void setPresenter(Presenter presenter) {
}
@UiHandler("btnLogin")
void doLogin(ClickEvent e) {
altUnauthorized.setVisible(true);
doLogin();
}
@UiHandler("btnRegister")
void register(ClickEvent e) {
placeCtrl.goTo(new ProfilePlace(""));
}
private void doLogin() {
altUnauthorized.setVisible(false);
Callback<UserInfoTO> callback = new Callback<UserInfoTO>() {
@Override
protected void ok(UserInfoTO user) {
if("".equals(user.getPerson().getConfirmation())){
if(user.isSigningNeeded()){
placeCtrl.goTo(new TermsPlace());
} else {
String token = user.getLastPlaceVisited();
Place place;
if(token == null || token.contains("vitrine")){
place = defaultPlace;
}else {
place = mapper.getPlace(token);
}
placeCtrl.goTo(place);
}
} else {
altUnauthorized.setText("Usuário não verificado. Confira seu email.");
altUnauthorized.setVisible(true);
+ ClientProperties.remove("Authorization");
}
}
@Override
protected void unauthorized() {
altUnauthorized.setText("Usuário ou senha incorretos, por favor tente novamente.");
altUnauthorized.setVisible(true);
}
};
String confirmation = ((VitrinePlace)placeCtrl.getWhere()).getConfirmation();
GWT.log("Confirmation: " + confirmation);
// TODO: Should be client.auth().checkPassword()?
// TODO: Should the api accept HasValue<String> too?
client.login(txtUsername.getValue(),
pwdPassword.getValue(),
confirmation,
callback);
}
}
| true | true | private void doLogin() {
altUnauthorized.setVisible(false);
Callback<UserInfoTO> callback = new Callback<UserInfoTO>() {
@Override
protected void ok(UserInfoTO user) {
if("".equals(user.getPerson().getConfirmation())){
if(user.isSigningNeeded()){
placeCtrl.goTo(new TermsPlace());
} else {
String token = user.getLastPlaceVisited();
Place place;
if(token == null || token.contains("vitrine")){
place = defaultPlace;
}else {
place = mapper.getPlace(token);
}
placeCtrl.goTo(place);
}
} else {
altUnauthorized.setText("Usuário não verificado. Confira seu email.");
altUnauthorized.setVisible(true);
}
}
@Override
protected void unauthorized() {
altUnauthorized.setText("Usuário ou senha incorretos, por favor tente novamente.");
altUnauthorized.setVisible(true);
}
};
String confirmation = ((VitrinePlace)placeCtrl.getWhere()).getConfirmation();
GWT.log("Confirmation: " + confirmation);
// TODO: Should be client.auth().checkPassword()?
// TODO: Should the api accept HasValue<String> too?
client.login(txtUsername.getValue(),
pwdPassword.getValue(),
confirmation,
callback);
}
| private void doLogin() {
altUnauthorized.setVisible(false);
Callback<UserInfoTO> callback = new Callback<UserInfoTO>() {
@Override
protected void ok(UserInfoTO user) {
if("".equals(user.getPerson().getConfirmation())){
if(user.isSigningNeeded()){
placeCtrl.goTo(new TermsPlace());
} else {
String token = user.getLastPlaceVisited();
Place place;
if(token == null || token.contains("vitrine")){
place = defaultPlace;
}else {
place = mapper.getPlace(token);
}
placeCtrl.goTo(place);
}
} else {
altUnauthorized.setText("Usuário não verificado. Confira seu email.");
altUnauthorized.setVisible(true);
ClientProperties.remove("Authorization");
}
}
@Override
protected void unauthorized() {
altUnauthorized.setText("Usuário ou senha incorretos, por favor tente novamente.");
altUnauthorized.setVisible(true);
}
};
String confirmation = ((VitrinePlace)placeCtrl.getWhere()).getConfirmation();
GWT.log("Confirmation: " + confirmation);
// TODO: Should be client.auth().checkPassword()?
// TODO: Should the api accept HasValue<String> too?
client.login(txtUsername.getValue(),
pwdPassword.getValue(),
confirmation,
callback);
}
|
diff --git a/VisualizationModule/src/org/gephi/visualization/opengl/text/TextManager.java b/VisualizationModule/src/org/gephi/visualization/opengl/text/TextManager.java
index 3361f6025..52f985666 100644
--- a/VisualizationModule/src/org/gephi/visualization/opengl/text/TextManager.java
+++ b/VisualizationModule/src/org/gephi/visualization/opengl/text/TextManager.java
@@ -1,392 +1,392 @@
/*
Copyright 2008 WebAtlas
Authors : Mathieu Bastian, Mathieu Jacomy, Julian Bilcke
Website : http://www.gephi.org
This file is part of Gephi.
Gephi 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.
Gephi 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 Gephi. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gephi.visualization.opengl.text;
import com.sun.opengl.util.j2d.TextRenderer;
import java.awt.Font;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.gephi.data.attributes.api.AttributeColumn;
import org.gephi.data.attributes.api.AttributeController;
import org.gephi.data.attributes.api.AttributeModel;
import org.gephi.data.properties.PropertiesColumn;
import org.gephi.graph.api.EdgeData;
import org.gephi.graph.api.NodeData;
import org.gephi.graph.api.Renderable;
import org.gephi.graph.spi.TextDataFactory;
import org.gephi.visualization.VizArchitecture;
import org.gephi.visualization.VizController;
import org.gephi.visualization.api.GraphDrawable;
import org.gephi.visualization.api.ModelImpl;
import org.gephi.visualization.api.VizConfig;
import org.openide.util.Lookup;
/**
*
* @author Mathieu Bastian
*/
public class TextManager implements VizArchitecture {
//Architecture
private VizConfig vizConfig;
private GraphDrawable drawable;
//Configuration
private SizeMode[] sizeModes;
private ColorMode[] colorModes;
//Processing
private TextUtils textUtils;
private Renderer nodeRenderer;
private Renderer edgeRenderer;
private TextDataBuilderImpl builder;
//Variables
private TextModel model;
private boolean nodeRefresh = true;
private boolean edgeRefresh = true;
//Preferences
private boolean renderer3d;
private boolean mipmap;
private boolean fractionalMetrics;
private boolean antialised;
public TextManager() {
textUtils = new TextUtils(this);
builder = (TextDataBuilderImpl) Lookup.getDefault().lookup(TextDataFactory.class);
//SizeMode init
sizeModes = new SizeMode[3];
sizeModes[0] = new FixedSizeMode();
sizeModes[1] = new ScaledSizeMode();
sizeModes[2] = new ProportionalSizeMode();
//ColorMode init
colorModes = new ColorMode[2];
colorModes[0] = new UniqueColorMode();
colorModes[1] = new ObjectColorMode();
}
public void initArchitecture() {
model = VizController.getInstance().getVizModel().getTextModel();
vizConfig = VizController.getInstance().getVizConfig();
drawable = VizController.getInstance().getDrawable();
initRenderer();
//Init sizemodes
for (SizeMode s : sizeModes) {
s.init();
}
//Model listening
model.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (!nodeRenderer.getFont().equals(model.getNodeFont())) {
nodeRenderer.setFont(model.getNodeFont());
}
if (!edgeRenderer.getFont().equals(model.getEdgeFont())) {
edgeRenderer.setFont(model.getEdgeFont());
}
nodeRefresh = true;
edgeRefresh = true;
}
});
//Model change
VizController.getInstance().getVizModel().addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("init")) {
TextManager.this.model = VizController.getInstance().getVizModel().getTextModel();
//Initialize columns if needed
- if (model.getNodeTextColumns() == null) {
+ if (model.getNodeTextColumns() == null || model.getNodeTextColumns().length == 0) {
AttributeController attributeController = Lookup.getDefault().lookup(AttributeController.class);
if (attributeController != null && attributeController.getModel() != null) {
AttributeModel attributeModel = attributeController.getModel();
AttributeColumn[] nodeCols = new AttributeColumn[]{attributeModel.getNodeTable().getColumn(PropertiesColumn.NODE_LABEL.getIndex())};
AttributeColumn[] edgeCols = new AttributeColumn[]{attributeModel.getEdgeTable().getColumn(PropertiesColumn.EDGE_LABEL.getIndex())};
model.setTextColumns(nodeCols, edgeCols);
}
}
}
}
});
//Settings
antialised = vizConfig.isLabelAntialiased();
mipmap = vizConfig.isLabelMipMap();
fractionalMetrics = vizConfig.isLabelFractionalMetrics();
renderer3d = false;
}
private void initRenderer() {
if (renderer3d) {
nodeRenderer = new Renderer3D();
edgeRenderer = new Renderer3D();
} else {
nodeRenderer = new Renderer2D();
edgeRenderer = new Renderer2D();
}
nodeRenderer.initRenderer(model.getNodeFont());
edgeRenderer.initRenderer(model.getEdgeFont());
}
public void defaultNodeColor() {
model.colorMode.defaultNodeColor(nodeRenderer);
}
public void defaultEdgeColor() {
model.colorMode.defaultEdgeColor(edgeRenderer);
}
public boolean isSelectedOnly() {
return model.selectedOnly;
}
public TextModel getModel() {
return model;
}
public void setModel(TextModel model) {
this.model = model;
}
public SizeMode[] getSizeModes() {
return sizeModes;
}
public ColorMode[] getColorModes() {
return colorModes;
}
public Renderer getNodeRenderer() {
return nodeRenderer;
}
public Renderer getEdgeRenderer() {
return edgeRenderer;
}
public void setRenderer3d(boolean renderer3d) {
this.renderer3d = renderer3d;
initRenderer();
}
//-------------------------------------------------------------------------------------------------
public static interface Renderer {
public void initRenderer(Font font);
public void reinitRenderer();
public void disposeRenderer();
public void beginRendering();
public void endRendering();
public void drawTextNode(ModelImpl model);
public void drawTextEdge(ModelImpl model);
public Font getFont();
public void setFont(Font font);
public void setColor(float r, float g, float b, float a);
public TextRenderer getJOGLRenderer();
}
private class Renderer3D implements Renderer {
private TextRenderer renderer;
public void initRenderer(Font font) {
renderer = new TextRenderer(font, antialised, fractionalMetrics, null, mipmap);
}
public void reinitRenderer() {
renderer = new TextRenderer(renderer.getFont(), antialised, fractionalMetrics, null, mipmap);
}
public void disposeRenderer() {
renderer.flush();
renderer.dispose();
}
public Font getFont() {
return renderer.getFont();
}
public void setFont(Font font) {
initRenderer(font);
}
public void beginRendering() {
renderer.begin3DRendering();
}
public void endRendering() {
renderer.end3DRendering();
}
public void drawTextNode(ModelImpl objectModel) {
Renderable renderable = objectModel.getObj();
TextDataImpl textData = (TextDataImpl) renderable.getTextData();
if (textData != null) {
model.colorMode.textColor(this, textData, objectModel);
model.sizeMode.setSizeFactor3d(model.nodeSizeFactor, textData, objectModel);
if (nodeRefresh) {
builder.buildNodeText((NodeData) renderable, textData, model);
}
String txt = textData.line.text;
Rectangle2D r = renderer.getBounds(txt);
textData.line.setBounds(r);
float posX = renderable.x() + (float) r.getWidth() / -2 * textData.sizeFactor;
float posY = renderable.y() + (float) r.getHeight() / -2 * textData.sizeFactor;
float posZ = renderable.getRadius();
renderer.draw3D(txt, posX, posY, posZ, textData.sizeFactor);
}
}
public void drawTextEdge(ModelImpl objectModel) {
Renderable renderable = objectModel.getObj();
TextDataImpl textData = (TextDataImpl) renderable.getTextData();
if (textData != null) {
model.colorMode.textColor(this, textData, objectModel);
model.sizeMode.setSizeFactor2d(model.edgeSizeFactor, textData, objectModel);
if (edgeRefresh) {
builder.buildNodeText((NodeData) renderable, textData, model);
}
String txt = textData.line.text;
Rectangle2D r = renderer.getBounds(txt);
textData.line.setBounds(r);
float posX = renderable.x() + (float) r.getWidth() / -2 * textData.sizeFactor;
float posY = renderable.y() + (float) r.getHeight() / -2 * textData.sizeFactor;
float posZ = renderable.getRadius();
renderer.draw3D(txt, posX, posY, posZ, textData.sizeFactor);
}
}
public void setColor(float r, float g, float b, float a) {
renderer.setColor(r, g, b, a);
}
public TextRenderer getJOGLRenderer() {
return renderer;
}
}
private class Renderer2D implements Renderer {
private TextRenderer renderer;
private static final float PIXEL_LIMIT = 3.5f;
public void initRenderer(Font font) {
renderer = new TextRenderer(font, antialised, fractionalMetrics, null, mipmap);
}
public void reinitRenderer() {
renderer = new TextRenderer(renderer.getFont(), antialised, fractionalMetrics, null, mipmap);
}
public void disposeRenderer() {
renderer.flush();
renderer.dispose();
}
public Font getFont() {
return renderer.getFont();
}
public void setFont(Font font) {
initRenderer(font);
}
public void beginRendering() {
renderer.beginRendering(drawable.getViewportWidth(), drawable.getViewportHeight());
}
public void endRendering() {
renderer.endRendering();
}
public void drawTextNode(ModelImpl objectModel) {
Renderable renderable = objectModel.getObj();
TextDataImpl textData = (TextDataImpl) renderable.getTextData();
if (textData != null) {
model.colorMode.textColor(this, textData, objectModel);
model.sizeMode.setSizeFactor2d(model.nodeSizeFactor, textData, objectModel);
if (nodeRefresh) {
builder.buildNodeText((NodeData) renderable, textData, model);
}
if (textData.sizeFactor * renderer.getCharWidth('a') < PIXEL_LIMIT) {
return;
}
String txt = textData.line.text;
Rectangle2D r = renderer.getBounds(txt);
float posX = renderable.getModel().getViewportX() + (float) r.getWidth() / -2 * textData.sizeFactor;
float posY = renderable.getModel().getViewportY() + (float) r.getHeight() / -2 * textData.sizeFactor;
r.setRect(0, 0, r.getWidth() / Math.abs(drawable.getDraggingMarkerX()), r.getHeight() / Math.abs(drawable.getDraggingMarkerY()));
textData.line.setBounds(r);
renderer.draw3D(txt, posX, posY, 0, textData.sizeFactor);
}
}
public void drawTextEdge(ModelImpl objectModel) {
Renderable renderable = objectModel.getObj();
TextDataImpl textData = (TextDataImpl) renderable.getTextData();
if (textData != null) {
model.colorMode.textColor(this, textData, objectModel);
model.sizeMode.setSizeFactor2d(model.edgeSizeFactor, textData, objectModel);
if (edgeRefresh) {
builder.buildEdgeText((EdgeData) renderable, textData, model);
}
if (textData.sizeFactor * renderer.getCharWidth('a') < PIXEL_LIMIT) {
return;
}
String txt = textData.line.text;
Rectangle2D r = renderer.getBounds(txt);
float posX = renderable.getModel().getViewportX() + (float) r.getWidth() / -2 * textData.sizeFactor;
float posY = renderable.getModel().getViewportY() + (float) r.getHeight() / -2 * textData.sizeFactor;
r.setRect(0, 0, r.getWidth() / drawable.getDraggingMarkerX(), r.getHeight() / drawable.getDraggingMarkerY());
textData.line.setBounds(r);
renderer.draw3D(txt, posX, posY, 0, textData.sizeFactor);
}
}
public void setColor(float r, float g, float b, float a) {
renderer.setColor(r, g, b, a);
}
public TextRenderer getJOGLRenderer() {
return renderer;
}
}
}
| true | true | public void initArchitecture() {
model = VizController.getInstance().getVizModel().getTextModel();
vizConfig = VizController.getInstance().getVizConfig();
drawable = VizController.getInstance().getDrawable();
initRenderer();
//Init sizemodes
for (SizeMode s : sizeModes) {
s.init();
}
//Model listening
model.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (!nodeRenderer.getFont().equals(model.getNodeFont())) {
nodeRenderer.setFont(model.getNodeFont());
}
if (!edgeRenderer.getFont().equals(model.getEdgeFont())) {
edgeRenderer.setFont(model.getEdgeFont());
}
nodeRefresh = true;
edgeRefresh = true;
}
});
//Model change
VizController.getInstance().getVizModel().addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("init")) {
TextManager.this.model = VizController.getInstance().getVizModel().getTextModel();
//Initialize columns if needed
if (model.getNodeTextColumns() == null) {
AttributeController attributeController = Lookup.getDefault().lookup(AttributeController.class);
if (attributeController != null && attributeController.getModel() != null) {
AttributeModel attributeModel = attributeController.getModel();
AttributeColumn[] nodeCols = new AttributeColumn[]{attributeModel.getNodeTable().getColumn(PropertiesColumn.NODE_LABEL.getIndex())};
AttributeColumn[] edgeCols = new AttributeColumn[]{attributeModel.getEdgeTable().getColumn(PropertiesColumn.EDGE_LABEL.getIndex())};
model.setTextColumns(nodeCols, edgeCols);
}
}
}
}
});
//Settings
antialised = vizConfig.isLabelAntialiased();
mipmap = vizConfig.isLabelMipMap();
fractionalMetrics = vizConfig.isLabelFractionalMetrics();
renderer3d = false;
}
| public void initArchitecture() {
model = VizController.getInstance().getVizModel().getTextModel();
vizConfig = VizController.getInstance().getVizConfig();
drawable = VizController.getInstance().getDrawable();
initRenderer();
//Init sizemodes
for (SizeMode s : sizeModes) {
s.init();
}
//Model listening
model.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (!nodeRenderer.getFont().equals(model.getNodeFont())) {
nodeRenderer.setFont(model.getNodeFont());
}
if (!edgeRenderer.getFont().equals(model.getEdgeFont())) {
edgeRenderer.setFont(model.getEdgeFont());
}
nodeRefresh = true;
edgeRefresh = true;
}
});
//Model change
VizController.getInstance().getVizModel().addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("init")) {
TextManager.this.model = VizController.getInstance().getVizModel().getTextModel();
//Initialize columns if needed
if (model.getNodeTextColumns() == null || model.getNodeTextColumns().length == 0) {
AttributeController attributeController = Lookup.getDefault().lookup(AttributeController.class);
if (attributeController != null && attributeController.getModel() != null) {
AttributeModel attributeModel = attributeController.getModel();
AttributeColumn[] nodeCols = new AttributeColumn[]{attributeModel.getNodeTable().getColumn(PropertiesColumn.NODE_LABEL.getIndex())};
AttributeColumn[] edgeCols = new AttributeColumn[]{attributeModel.getEdgeTable().getColumn(PropertiesColumn.EDGE_LABEL.getIndex())};
model.setTextColumns(nodeCols, edgeCols);
}
}
}
}
});
//Settings
antialised = vizConfig.isLabelAntialiased();
mipmap = vizConfig.isLabelMipMap();
fractionalMetrics = vizConfig.isLabelFractionalMetrics();
renderer3d = false;
}
|
diff --git a/src/DVN-web/src/edu/harvard/iq/dvn/core/web/site/AddSitePage.java b/src/DVN-web/src/edu/harvard/iq/dvn/core/web/site/AddSitePage.java
index a63ec4bb..db384bae 100644
--- a/src/DVN-web/src/edu/harvard/iq/dvn/core/web/site/AddSitePage.java
+++ b/src/DVN-web/src/edu/harvard/iq/dvn/core/web/site/AddSitePage.java
@@ -1,716 +1,716 @@
/*
* Dataverse Network - A web application to distribute, share and analyze quantitative data.
* Copyright (C) 2007
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses
* or write to the Free Software Foundation,Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* AddSitePage.java
*
* Created on September 19, 2006, 9:57 AM
*/
package edu.harvard.iq.dvn.core.web.site;
import edu.harvard.iq.dvn.core.admin.RoleServiceLocal;
import edu.harvard.iq.dvn.core.admin.UserServiceLocal;
import edu.harvard.iq.dvn.core.mail.MailServiceLocal;
import edu.harvard.iq.dvn.core.study.StudyFieldServiceLocal;
import edu.harvard.iq.dvn.core.vdc.VDC;
import edu.harvard.iq.dvn.core.vdc.VDCCollectionServiceLocal;
import edu.harvard.iq.dvn.core.vdc.VDCGroupServiceLocal;
import edu.harvard.iq.dvn.core.vdc.VDCNetworkServiceLocal;
import edu.harvard.iq.dvn.core.vdc.VDCServiceLocal;
import edu.harvard.iq.dvn.core.web.common.StatusMessage;
import edu.harvard.iq.dvn.core.web.common.VDCBaseBean;
import java.util.Map;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import com.icesoft.faces.component.ext.HtmlOutputText;
import com.icesoft.faces.component.ext.HtmlOutputLabel;
import com.icesoft.faces.component.ext.HtmlInputText;
import com.icesoft.faces.component.ext.HtmlCommandButton;
import com.icesoft.faces.component.ext.HtmlInputTextarea;
import edu.harvard.iq.dvn.core.admin.VDCUser;
import edu.harvard.iq.dvn.core.web.util.CharacterValidator;
import edu.harvard.iq.dvn.core.util.PropertyUtil;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
/**
* <p>Page bean that corresponds to a similarly named JSP page. This
* class contains component definitions (and initialization code) for
* all components that you have defined on this page, as well as
* lifecycle methods and event handlers where you may add behavior
* to respond to incoming events.</p>
*/
@Named("AddSitePage")
@ViewScoped
public class AddSitePage extends VDCBaseBean implements java.io.Serializable {
// </editor-fold>
private static final Logger logger = Logger.getLogger("edu.harvard.iq.dvn.core.web.site.AddSitePage");
/**
* <p>Construct a new Page bean instance.</p>
*/
public AddSitePage() {
}
@EJB
VDCServiceLocal vdcService;
@EJB
VDCGroupServiceLocal vdcGroupService;
@EJB
VDCCollectionServiceLocal vdcCollectionService;
@EJB
VDCNetworkServiceLocal vdcNetworkService;
@EJB
StudyFieldServiceLocal studyFieldService;
@EJB
UserServiceLocal userService;
@EJB
RoleServiceLocal roleService;
@EJB
MailServiceLocal mailService;
StatusMessage msg;
//private BundleReader messagebundle = new BundleReader("Bundle");
private ResourceBundle messagebundle = ResourceBundle.getBundle("Bundle");
public StatusMessage getMsg() {
return msg;
}
public void setMsg(StatusMessage msg) {
this.msg = msg;
}
// <editor-fold defaultstate="collapsed" desc="Creator-managed Component Definition">
private int __placeholder;
/**
* <p>Automatically managed component initialization. <strong>WARNING:</strong>
* This method is automatically generated, so any user-specified code inserted
* here is subject to being replaced.</p>
*/
public void init() {
super.init();
//check to see if a dataverse type is in request
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
Iterator iterator = request.getParameterMap().keySet().iterator();
while (iterator.hasNext()) {
Object key = (Object) iterator.next();
if (key instanceof String && ((String) key).indexOf("dataverseType") != -1 && !request.getParameter((String) key).equals("")) {
this.setDataverseType(request.getParameter((String) key));
}
}
}
//copied from manageclassificationsPage.java
private boolean result;
//fields from dvrecordsmanager
private ArrayList itemBeans = new ArrayList();
private static String GROUP_INDENT_STYLE_CLASS = "GROUP_INDENT_STYLE_CLASS";
private static String GROUP_ROW_STYLE_CLASS = "groupRow";
private static String CHILD_INDENT_STYLE_CLASS = "CHILD_INDENT_STYLE_CLASS";
private String CHILD_ROW_STYLE_CLASS;
private static String CONTRACT_IMAGE = "tree_nav_top_close_no_siblings.gif";
private static String EXPAND_IMAGE = "tree_nav_top_open_no_siblings.gif";
//these static variables have a dependency on the Network Stats Server e.g.
// they should be held as constants in a constants file ... TODO
private static Long SCHOLAR_ID = new Long("-1");
private static String SCHOLAR_SHORT_DESCRIPTION = new String("A short description for the research scholar group");
private static Long OTHER_ID = new Long("-2");
private static String OTHER_SHORT_DESCRIPTION = new String("A short description for the unclassified dataverses group (other).");
//Manage classification
public boolean getResult() {
return result;
}
//setters
public void setResult(boolean result) {
this.result = result;
}
public ArrayList getItemBeans() {
return itemBeans;
}
/**
* <p>Callback method that is called after the component tree has been
* restored, but before any event processing takes place. This method
* will <strong>only</strong> be called on a postback request that
* is processing a form submit. Customize this method to allocate
* resources that will be required in your event handlers.</p>
*/
public void preprocess() {
}
/**
* <p>Callback method that is called just before rendering takes place.
* This method will <strong>only</strong> be called for the page that
* will actually be rendered (and not, for example, on a page that
* handled a postback and then navigated to a different page). Customize
* this method to allocate resources that will be required for rendering
* this page.</p>
*/
public void prerender() {
}
/**
* <p>Callback method that is called after rendering is completed for
* this request, if <code>init()</code> was called (regardless of whether
* or not this was the page that was actually rendered). Customize this
* method to release resources acquired in the <code>init()</code>,
* <code>preprocess()</code>, or <code>prerender()</code> methods (or
* acquired during execution of an event handler).</p>
*/
public void destroy() {
}
private HtmlOutputLabel componentLabel1 = new HtmlOutputLabel();
public HtmlOutputLabel getComponentLabel1() {
return componentLabel1;
}
public void setComponentLabel1(HtmlOutputLabel hol) {
this.componentLabel1 = hol;
}
private HtmlOutputText componentLabel1Text = new HtmlOutputText();
public HtmlOutputText getComponentLabel1Text() {
return componentLabel1Text;
}
public void setComponentLabel1Text(HtmlOutputText hot) {
this.componentLabel1Text = hot;
}
private HtmlInputText dataverseName = new HtmlInputText();
public HtmlInputText getDataverseName() {
return dataverseName;
}
public void setDataverseName(HtmlInputText hit) {
this.dataverseName = hit;
}
private HtmlOutputLabel componentLabel2 = new HtmlOutputLabel();
public HtmlOutputLabel getComponentLabel2() {
return componentLabel2;
}
public void setComponentLabel2(HtmlOutputLabel hol) {
this.componentLabel2 = hol;
}
private HtmlOutputText componentLabel2Text = new HtmlOutputText();
public HtmlOutputText getComponentLabel2Text() {
return componentLabel2Text;
}
public void setComponentLabel2Text(HtmlOutputText hot) {
this.componentLabel2Text = hot;
}
private HtmlInputText dataverseAlias = new HtmlInputText();
public HtmlInputText getDataverseAlias() {
return dataverseAlias;
}
public void setDataverseAlias(HtmlInputText hit) {
this.dataverseAlias = hit;
}
private HtmlCommandButton button1 = new HtmlCommandButton();
public HtmlCommandButton getButton1() {
return button1;
}
public void setButton1(HtmlCommandButton hcb) {
this.button1 = hcb;
}
private HtmlCommandButton button2 = new HtmlCommandButton();
public HtmlCommandButton getButton2() {
return button2;
}
public void setButton2(HtmlCommandButton hcb) {
this.button2 = hcb;
}
// I'm initializing classificationList below in order to get the page
// to work; otherwise (if it's set to null), the page dies quietly in
// classificationList.getClassificationUIs() (in saveClassifications),
// after creating the new DV.
// I'm still not quite sure how/where this list was initialized before?
ClassificationList classificationList = new ClassificationList();//null;
public ClassificationList getClassificationList() {
return classificationList;
}
public void setClassificationList(ClassificationList classificationList) {
this.classificationList = classificationList;
}
public String create() {
// Long selectedgroup = this.getSelectedGroup();
String dtype = dataverseType;
String name = (String) dataverseName.getValue();
String alias = (String) dataverseAlias.getValue();
String strAffiliation = (String) affiliation.getValue();
String strShortDescription = (String) shortDescription.getValue();
Long userId = getVDCSessionBean().getLoginBean().getUser().getId();
boolean success = true;
if (validateClassificationCheckBoxes()) {
vdcService.create(userId, name, alias, dtype);
VDC createdVDC = vdcService.findByAlias(alias);
saveClassifications(createdVDC);
createdVDC.setDtype(dataverseType);
createdVDC.setDisplayNetworkAnnouncements(getVDCRequestBean().getVdcNetwork().isDisplayAnnouncements());
createdVDC.setDisplayAnnouncements(getVDCRequestBean().getVdcNetwork().isDisplayVDCAnnouncements());
createdVDC.setAnnouncements(getVDCRequestBean().getVdcNetwork().getDefaultVDCAnnouncements());
createdVDC.setDisplayNewStudies(getVDCRequestBean().getVdcNetwork().isDisplayVDCRecentStudies());
createdVDC.setAboutThisDataverse(getVDCRequestBean().getVdcNetwork().getDefaultVDCAboutText());
createdVDC.setContactEmail(getVDCSessionBean().getLoginBean().getUser().getEmail());
createdVDC.setAffiliation(strAffiliation);
createdVDC.setDvnDescription(strShortDescription);
vdcService.edit(createdVDC);
StatusMessage msg = new StatusMessage();
String hostUrl = PropertyUtil.getHostUrl();
- msg.setMessageText("Your new dataverse <a href='http://" + hostUrl + "/dvn" + getVDCRequestBean().getCurrentVDCURL()+ "'>http://" + hostUrl + "/dvn" + getVDCRequestBean().getCurrentVDCURL()+ "</a> has been successfully created!");
+ msg.setMessageText("Your new dataverse <a href='http://" + hostUrl + "/dvn/dv/" + createdVDC.getAlias() + "'>http://" + hostUrl + "/dvn/dv/" + createdVDC.getAlias() + "</a> has been successfully created!");
msg.setStyleClass("successMessage");
Map m = getRequestMap();
m.put("statusMessage", msg);
VDCUser creator = userService.findByUserName(getVDCSessionBean().getLoginBean().getUser().getUserName());
String toMailAddress = getVDCSessionBean().getLoginBean().getUser().getEmail();
String siteAddress = "unknown";
siteAddress = hostUrl + "/dvn" + getVDCRequestBean().getCurrentVDCURL();
logger.fine("created dataverse; site address: "+siteAddress);
mailService.sendAddSiteNotification(toMailAddress, name, siteAddress);
// Refresh User object in LoginBean so it contains the user's new role of VDC administrator.
getVDCSessionBean().getLoginBean().setUser(creator);
- return "/site/AddSiteSuccess?faces-redirect=true&vdcId=" + createdVDC.getId();
+ return "/site/AddSiteSuccessPage?faces-redirect=true&vdcId=" + createdVDC.getId();
}
else {
success = false;
return null;
}
}
private void saveClassifications(VDC createdVDC) {
for (ClassificationUI classUI: classificationList.getClassificationUIs()) {
if (classUI.isSelected()) {
createdVDC.getVdcGroups().add(classUI.getVdcGroup());
}
}
}
public String createScholarDataverse() {
String dataversetype = dataverseType;
String name = (String) dataverseName.getValue();
String alias = (String) dataverseAlias.getValue();
String strAffiliation = (String) affiliation.getValue();
String strShortDescription = (String) shortDescription.getValue();
Long userId = getVDCSessionBean().getLoginBean().getUser().getId();
if (validateClassificationCheckBoxes()) {
vdcService.createScholarDataverse(userId, firstName, lastName, name, strAffiliation, alias, dataversetype);
VDC createdScholarDataverse = vdcService.findScholarDataverseByAlias(alias);
saveClassifications(createdScholarDataverse);
// add default values to the VDC table and commit/set the vdc bean props
createdScholarDataverse.setDisplayNetworkAnnouncements(getVDCRequestBean().getVdcNetwork().isDisplayAnnouncements());
createdScholarDataverse.setDisplayAnnouncements(getVDCRequestBean().getVdcNetwork().isDisplayVDCAnnouncements());
createdScholarDataverse.setAnnouncements(getVDCRequestBean().getVdcNetwork().getDefaultVDCAnnouncements());
createdScholarDataverse.setDisplayNewStudies(getVDCRequestBean().getVdcNetwork().isDisplayVDCRecentStudies());
createdScholarDataverse.setAboutThisDataverse(getVDCRequestBean().getVdcNetwork().getDefaultVDCAboutText());
createdScholarDataverse.setContactEmail(getVDCSessionBean().getLoginBean().getUser().getEmail());
createdScholarDataverse.setDvnDescription(strShortDescription);
vdcService.edit(createdScholarDataverse);
getVDCRequestBean().setCurrentVDC(createdScholarDataverse);
// Refresh User object in LoginBean so it contains the user's new role of VDC administrator.
StatusMessage msg = new StatusMessage();
String hostUrl = PropertyUtil.getHostUrl();
msg.setMessageText("Your new scholar dataverse <a href='http://" + hostUrl + "/dvn" + getVDCRequestBean().getCurrentVDCURL()+ "'>http://" + hostUrl + "/dvn" + getVDCRequestBean().getCurrentVDCURL()+ "</a> has been successfully created!");
msg.setStyleClass("successMessage");
Map m = getRequestMap();
m.put("statusMessage", msg);
VDCUser creator = userService.findByUserName(getVDCSessionBean().getLoginBean().getUser().getUserName());
String toMailAddress = getVDCSessionBean().getLoginBean().getUser().getEmail();
String siteAddress = "unknown";
siteAddress = hostUrl + "/dvn" + getVDCRequestBean().getCurrentVDCURL();
mailService.sendAddSiteNotification(toMailAddress, name, siteAddress);
getVDCSessionBean().getLoginBean().setUser(creator);
return "addSiteSuccess";
}
else {
return null;
}
}
public String cancel() {
return "cancel";
}
public boolean validateClassificationCheckBoxes() {
if (!getVDCRequestBean().getVdcNetwork().isRequireDVclassification()){
return true;
}
else {
for (ClassificationUI classUI: classificationList.getClassificationUIs()) {
if (classUI.isSelected()) {
return true;
}
}
FacesMessage message = new FacesMessage("You must select at least one classification for your dataverse.");
FacesContext.getCurrentInstance().addMessage("addsiteform", message);
return false;
}
}
public void validateShortDescription(FacesContext context,
UIComponent toValidate,
Object value) {
String newValue = (String)value;
if (newValue != null && newValue.trim().length() > 0) {
if (newValue.length() > 255) {
((UIInput)toValidate).setValid(false);
FacesMessage message = new FacesMessage("The field cannot be more than 255 characters in length.");
context.addMessage(toValidate.getClientId(context), message);
}
}
if ((newValue == null || newValue.trim().length() == 0) && getVDCRequestBean().getVdcNetwork().isRequireDVdescription()) {
FacesMessage message = new FacesMessage("The field must have a value.");
context.addMessage(toValidate.getClientId(context), message);
((UIInput) toValidate).setValid(false);
context.renderResponse();
}
}
public void validateName(FacesContext context,
UIComponent toValidate,
Object value) {
String name = (String) value;
if (name != null && name.trim().length() == 0) {
FacesMessage message = new FacesMessage("The dataverse name field must have a value.");
context.addMessage(toValidate.getClientId(context), message);
context.renderResponse();
}
boolean nameFound = false;
VDC vdc = vdcService.findByName(name);
if (vdc != null) {
nameFound = true;
}
if (nameFound) {
((UIInput) toValidate).setValid(false);
FacesMessage message = new FacesMessage("This name is already taken.");
context.addMessage(toValidate.getClientId(context), message);
}
resetScholarProperties();
}
public void validateAlias(FacesContext context,
UIComponent toValidate,
Object value) {
CharacterValidator charactervalidator = new CharacterValidator();
charactervalidator.validate(context, toValidate, value);
String alias = (String) value;
boolean isValid = false;
VDC vdc = vdcService.findByAlias(alias);
if (alias.equals("") || vdc != null) {
isValid = true;
}
if (isValid) {
((UIInput) toValidate).setValid(false);
FacesMessage message = new FacesMessage("This alias is already taken.");
context.addMessage(toValidate.getClientId(context), message);
}
resetScholarProperties();
}
private void resetScholarProperties() {
if (dataverseType != null) {
this.setDataverseType(dataverseType);
}
}
/**
* Changes for build 16
* to support scholar
* dataverses and display
*
* @author wbossons
*/
/**
* Used to set the discriminator value
* in the entity
*
*/
private String dataverseType = null;
public String getDataverseType() {
if (dataverseType == null) {
setDataverseType("Basic");
}
return dataverseType;
}
public void setDataverseType(String dataverseType) {
this.dataverseType = dataverseType;
}
/**
* Used to set the discriminator value
* in the entity
*
*/
private String selected = null;
public String getSelected() {
return selected;
}
public void setSelected(String selected) {
this.selected = selected;
}
/**
* set the possible options
*
*
*/
private List<SelectItem> dataverseOptions = null;
public List getDataverseOptions() {
if (this.dataverseOptions == null) {
dataverseOptions = new ArrayList();
/**
* Choose Scholar if this dataverse will have your
* own name and will contain your own research,
* and Basic for any other dataverse.
*
*
Select the group that will most likely fit your
* dataverse, be it a university department, a journal,
* a research center, etc. If you create a Scholar dataverse,
* it will be automatically entered under the Scholar group.
*
*/
try {
String scholarOption = messagebundle.getString("scholarOption");
String basicOption = messagebundle.getString("basicOption");
String scholarLabel = messagebundle.getString("scholarOptionDetail");
String basicLabel = messagebundle.getString("basicOptionDetail");
dataverseOptions.add(new SelectItem(basicOption, basicLabel));
dataverseOptions.add(new SelectItem(scholarOption, scholarLabel));
} catch (Exception uee) {
System.out.println("Exception: " + uee.toString());
}
}
return dataverseOptions;
}
/**
* Holds value of property firstName.
*/
private String firstName = new String("");
/**
* Getter for property firstName.
* @return Value of property firstName.
*/
public String getFirstName() {
return this.firstName;
}
/**
* Setter for property firstName.
* @param firstName New value of property firstName.
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* Holds value of property lastName.
*/
private String lastName;
/**
* Getter for property lastName.
* @return Value of property lastName.
*/
public String getLastName() {
return this.lastName;
}
/**
* Setter for property lastName.
* @param lastName New value of property lastName.
*/
public void setLastName(String lastname) {
this.lastName = lastname;
}
/**
* Holds value of property affiliation.
*/
private HtmlInputText affiliation;
/**
* Getter for property affiliation.
* @return Value of property affiliation.
*/
public HtmlInputText getAffiliation() {
return this.affiliation;
}
public HtmlInputTextarea getShortDescription() {
return shortDescription;
}
public void setShortDescription(HtmlInputTextarea shortDescription) {
this.shortDescription = shortDescription;
}
/**
* Setter for property affiliation.
* @param affiliation New value of property affiliation.
*/
public void setAffiliation(HtmlInputText affiliation) {
this.affiliation = affiliation;
}
HtmlInputTextarea shortDescription;
//END Group Select widgets
/**
* value change listeners and validators
*
*
*/
public void changeDataverseOption(ValueChangeEvent event) {
String newValue = (String) event.getNewValue();
this.setDataverseType(newValue);
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
request.setAttribute("dataverseType", newValue);
FacesContext.getCurrentInstance().renderResponse();
}
public void changeFirstName(ValueChangeEvent event) {
String newValue = (String) event.getNewValue();
this.setFirstName(newValue);
}
public void changeLastName(ValueChangeEvent event) {
String newValue = (String) event.getNewValue();
this.setLastName(newValue);
}
public void validateIsEmpty(FacesContext context,
UIComponent toValidate,
Object value) {
String newValue = (String) value;
if (newValue == null || newValue.trim().length() == 0) {
((UIInput) toValidate).setValid(false);
FacesMessage message = new FacesMessage("The field must have a value.");
context.addMessage(toValidate.getClientId(context), message);
context.renderResponse();
}
}
public void validateIsEmptyRequiredAffiliation(FacesContext context,
UIComponent toValidate,
Object value) {
String newValue = (String) value;
if ((newValue == null || newValue.trim().length() == 0) && getVDCRequestBean().getVdcNetwork().isRequireDVaffiliation()) {
FacesMessage message = new FacesMessage("The field must have a value.");
context.addMessage(toValidate.getClientId(context), message);
context.renderResponse();
((UIInput) toValidate).setValid(false);
}
}
}
| false | true | public String create() {
// Long selectedgroup = this.getSelectedGroup();
String dtype = dataverseType;
String name = (String) dataverseName.getValue();
String alias = (String) dataverseAlias.getValue();
String strAffiliation = (String) affiliation.getValue();
String strShortDescription = (String) shortDescription.getValue();
Long userId = getVDCSessionBean().getLoginBean().getUser().getId();
boolean success = true;
if (validateClassificationCheckBoxes()) {
vdcService.create(userId, name, alias, dtype);
VDC createdVDC = vdcService.findByAlias(alias);
saveClassifications(createdVDC);
createdVDC.setDtype(dataverseType);
createdVDC.setDisplayNetworkAnnouncements(getVDCRequestBean().getVdcNetwork().isDisplayAnnouncements());
createdVDC.setDisplayAnnouncements(getVDCRequestBean().getVdcNetwork().isDisplayVDCAnnouncements());
createdVDC.setAnnouncements(getVDCRequestBean().getVdcNetwork().getDefaultVDCAnnouncements());
createdVDC.setDisplayNewStudies(getVDCRequestBean().getVdcNetwork().isDisplayVDCRecentStudies());
createdVDC.setAboutThisDataverse(getVDCRequestBean().getVdcNetwork().getDefaultVDCAboutText());
createdVDC.setContactEmail(getVDCSessionBean().getLoginBean().getUser().getEmail());
createdVDC.setAffiliation(strAffiliation);
createdVDC.setDvnDescription(strShortDescription);
vdcService.edit(createdVDC);
StatusMessage msg = new StatusMessage();
String hostUrl = PropertyUtil.getHostUrl();
msg.setMessageText("Your new dataverse <a href='http://" + hostUrl + "/dvn" + getVDCRequestBean().getCurrentVDCURL()+ "'>http://" + hostUrl + "/dvn" + getVDCRequestBean().getCurrentVDCURL()+ "</a> has been successfully created!");
msg.setStyleClass("successMessage");
Map m = getRequestMap();
m.put("statusMessage", msg);
VDCUser creator = userService.findByUserName(getVDCSessionBean().getLoginBean().getUser().getUserName());
String toMailAddress = getVDCSessionBean().getLoginBean().getUser().getEmail();
String siteAddress = "unknown";
siteAddress = hostUrl + "/dvn" + getVDCRequestBean().getCurrentVDCURL();
logger.fine("created dataverse; site address: "+siteAddress);
mailService.sendAddSiteNotification(toMailAddress, name, siteAddress);
// Refresh User object in LoginBean so it contains the user's new role of VDC administrator.
getVDCSessionBean().getLoginBean().setUser(creator);
return "/site/AddSiteSuccess?faces-redirect=true&vdcId=" + createdVDC.getId();
}
else {
success = false;
return null;
}
}
| public String create() {
// Long selectedgroup = this.getSelectedGroup();
String dtype = dataverseType;
String name = (String) dataverseName.getValue();
String alias = (String) dataverseAlias.getValue();
String strAffiliation = (String) affiliation.getValue();
String strShortDescription = (String) shortDescription.getValue();
Long userId = getVDCSessionBean().getLoginBean().getUser().getId();
boolean success = true;
if (validateClassificationCheckBoxes()) {
vdcService.create(userId, name, alias, dtype);
VDC createdVDC = vdcService.findByAlias(alias);
saveClassifications(createdVDC);
createdVDC.setDtype(dataverseType);
createdVDC.setDisplayNetworkAnnouncements(getVDCRequestBean().getVdcNetwork().isDisplayAnnouncements());
createdVDC.setDisplayAnnouncements(getVDCRequestBean().getVdcNetwork().isDisplayVDCAnnouncements());
createdVDC.setAnnouncements(getVDCRequestBean().getVdcNetwork().getDefaultVDCAnnouncements());
createdVDC.setDisplayNewStudies(getVDCRequestBean().getVdcNetwork().isDisplayVDCRecentStudies());
createdVDC.setAboutThisDataverse(getVDCRequestBean().getVdcNetwork().getDefaultVDCAboutText());
createdVDC.setContactEmail(getVDCSessionBean().getLoginBean().getUser().getEmail());
createdVDC.setAffiliation(strAffiliation);
createdVDC.setDvnDescription(strShortDescription);
vdcService.edit(createdVDC);
StatusMessage msg = new StatusMessage();
String hostUrl = PropertyUtil.getHostUrl();
msg.setMessageText("Your new dataverse <a href='http://" + hostUrl + "/dvn/dv/" + createdVDC.getAlias() + "'>http://" + hostUrl + "/dvn/dv/" + createdVDC.getAlias() + "</a> has been successfully created!");
msg.setStyleClass("successMessage");
Map m = getRequestMap();
m.put("statusMessage", msg);
VDCUser creator = userService.findByUserName(getVDCSessionBean().getLoginBean().getUser().getUserName());
String toMailAddress = getVDCSessionBean().getLoginBean().getUser().getEmail();
String siteAddress = "unknown";
siteAddress = hostUrl + "/dvn" + getVDCRequestBean().getCurrentVDCURL();
logger.fine("created dataverse; site address: "+siteAddress);
mailService.sendAddSiteNotification(toMailAddress, name, siteAddress);
// Refresh User object in LoginBean so it contains the user's new role of VDC administrator.
getVDCSessionBean().getLoginBean().setUser(creator);
return "/site/AddSiteSuccessPage?faces-redirect=true&vdcId=" + createdVDC.getId();
}
else {
success = false;
return null;
}
}
|
diff --git a/microemulator/src/com/barteo/emulator/device/applet/AppletDevice.java b/microemulator/src/com/barteo/emulator/device/applet/AppletDevice.java
index b2227508..b50a0e2d 100644
--- a/microemulator/src/com/barteo/emulator/device/applet/AppletDevice.java
+++ b/microemulator/src/com/barteo/emulator/device/applet/AppletDevice.java
@@ -1,493 +1,493 @@
/*
* MicroEmulator
* Copyright (C) 2002 Bartek Teodorczyk <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.barteo.emulator.device.applet;
import java.awt.Color;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.lcdui.Canvas;
import com.barteo.emulator.EmulatorContext;
import com.barteo.emulator.device.Device;
import com.barteo.emulator.device.DeviceDisplay;
import com.barteo.emulator.device.FontManager;
import com.barteo.emulator.device.InputMethod;
import com.sixlegs.image.png.PngImage;
import nanoxml.XMLElement;
import nanoxml.XMLParseException;
public class AppletDevice implements Device
{
AppletDeviceDisplay deviceDisplay;
FontManager fontManager = null;
InputMethod inputMethod = null;
Vector buttons;
Vector softButtons;
Image normalImage;
Image overImage;
Image pressedImage;
public AppletDevice()
{
}
public void init(EmulatorContext context)
{
// Here should be device.xml but Netscape security manager doesn't accept this extension
init(context, "/com/barteo/emulator/device/device.txt");
}
public void init(EmulatorContext context, String config)
{
deviceDisplay = new AppletDeviceDisplay(context);
buttons = new Vector();
softButtons = new Vector();
loadConfig(config);
}
public javax.microedition.lcdui.Image createImage(int width, int height)
{
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException();
}
return new MutableImage(width, height);
}
public javax.microedition.lcdui.Image createImage(String name)
throws IOException
{
return new ImmutableImage(getImage(name));
}
public javax.microedition.lcdui.Image createImage(byte[] imageData, int imageOffset, int imageLength)
{
ByteArrayInputStream is = new ByteArrayInputStream(imageData, imageOffset, imageLength);
return new ImmutableImage(getImage(is));
}
public DeviceDisplay getDeviceDisplay()
{
return deviceDisplay;
}
public FontManager getFontManager()
{
if (fontManager == null) {
fontManager = new AppletFontManager();
}
return fontManager;
}
public InputMethod getInputMethod()
{
if (inputMethod == null) {
inputMethod = new AppletInputMethod();
}
return inputMethod;
}
public int getGameAction(int keyCode)
{
switch (keyCode) {
case KeyEvent.VK_UP:
return Canvas.UP;
case KeyEvent.VK_DOWN:
return Canvas.DOWN;
case KeyEvent.VK_LEFT:
return Canvas.LEFT;
case KeyEvent.VK_RIGHT:
return Canvas.RIGHT;
case KeyEvent.VK_ENTER:
return Canvas.FIRE;
case KeyEvent.VK_A:
return Canvas.GAME_A;
case KeyEvent.VK_B:
return Canvas.GAME_B;
case KeyEvent.VK_C:
return Canvas.GAME_C;
case KeyEvent.VK_D:
return Canvas.GAME_D;
case KeyEvent.VK_0:
case KeyEvent.VK_1:
case KeyEvent.VK_2:
case KeyEvent.VK_3:
case KeyEvent.VK_4:
case KeyEvent.VK_5:
case KeyEvent.VK_6:
case KeyEvent.VK_7:
case KeyEvent.VK_8:
case KeyEvent.VK_9:
int rval = Canvas.KEY_NUM0 + (keyCode-KeyEvent.VK_0);
return rval;
case KeyEvent.VK_MULTIPLY:
return Canvas.KEY_STAR;
case KeyEvent.VK_NUMBER_SIGN:
return Canvas.KEY_POUND;
default:
return 0;
}
}
public int getKeyCode(int gameAction)
{
switch (gameAction) {
case Canvas.UP:
return KeyEvent.VK_UP;
case Canvas.DOWN:
return KeyEvent.VK_DOWN;
case Canvas.LEFT:
return KeyEvent.VK_LEFT;
case Canvas.RIGHT:
return KeyEvent.VK_RIGHT;
case Canvas.FIRE:
return KeyEvent.VK_ENTER;
case Canvas.GAME_A:
return KeyEvent.VK_A;
case Canvas.GAME_B:
return KeyEvent.VK_B;
case Canvas.GAME_C:
return KeyEvent.VK_C;
case Canvas.GAME_D:
return KeyEvent.VK_D;
case Canvas.KEY_NUM0:
case Canvas.KEY_NUM1:
case Canvas.KEY_NUM2:
case Canvas.KEY_NUM3:
case Canvas.KEY_NUM4:
case Canvas.KEY_NUM5:
case Canvas.KEY_NUM6:
case Canvas.KEY_NUM7:
case Canvas.KEY_NUM8:
case Canvas.KEY_NUM9:
int rval = KeyEvent.VK_0 + (gameAction-Canvas.KEY_NUM0);
return rval;
case Canvas.KEY_POUND:
return KeyEvent.VK_NUMBER_SIGN;
case Canvas.KEY_STAR:
return KeyEvent.VK_MULTIPLY;
default:
return 0;
}
}
public Vector getSoftButtons()
{
return softButtons;
}
public Image getNormalImage()
{
return normalImage;
}
public Image getOverImage()
{
return overImage;
}
public Image getPressedImage()
{
return pressedImage;
}
public boolean hasPointerMotionEvents()
{
return false;
}
public boolean hasPointerEvents()
{
return false;
}
public boolean hasRepeatEvents()
{
return false;
}
public Vector getButtons()
{
return buttons;
}
public void loadConfig(String config)
{
String xml = "";
InputStream dis = new BufferedInputStream(getClass().getResourceAsStream(config));
try {
while (dis.available() > 0) {
byte[] b = new byte[dis.available()];
dis.read(b);
xml += new String(b);
}
} catch (Exception ex) {
- System.out.println("Cannot find com.barteo.emulator.device.device.txt definition file");
+ System.out.println("Cannot load " + config + " definition file");
return;
}
XMLElement doc = new XMLElement();
try {
doc.parseString(xml);
} catch (XMLParseException ex) {
System.err.println(ex);
return;
}
for (Enumeration e = doc.enumerateChildren(); e.hasMoreElements(); ) {
XMLElement tmp = (XMLElement) e.nextElement();
if (tmp.getName().equals("img")) {
try {
if (tmp.getStringAttribute("name").equals("normal")) {
normalImage = getSystemImage(tmp.getStringAttribute("src"));
} else if (tmp.getStringAttribute("name").equals("over")) {
overImage = getSystemImage(tmp.getStringAttribute("src"));
} else if (tmp.getStringAttribute("name").equals("pressed")) {
pressedImage = getSystemImage(tmp.getStringAttribute("src"));
}
} catch (IOException ex) {
System.out.println("Cannot load " + tmp.getStringAttribute("src"));
return;
}
} else if (tmp.getName().equals("display")) {
for (Enumeration e_display = tmp.enumerateChildren(); e_display.hasMoreElements(); ) {
XMLElement tmp_display = (XMLElement) e_display.nextElement();
if (tmp_display.getName().equals("numcolors")) {
deviceDisplay.numColors = Integer.parseInt(tmp_display.getContent());
} else if (tmp_display.getName().equals("iscolor")) {
deviceDisplay.isColor = parseBoolean(tmp_display.getContent());
} else if (tmp_display.getName().equals("background")) {
deviceDisplay.backgroundColor = new Color(Integer.parseInt(tmp_display.getContent(), 16));
} else if (tmp_display.getName().equals("foreground")) {
deviceDisplay.foregroundColor = new Color(Integer.parseInt(tmp_display.getContent(), 16));
} else if (tmp_display.getName().equals("rectangle")) {
deviceDisplay.displayRectangle = getRectangle(tmp_display);
} else if (tmp_display.getName().equals("paintable")) {
deviceDisplay.displayPaintable = getRectangle(tmp_display);
} else if (tmp_display.getName().equals("img")) {
if (tmp_display.getStringAttribute("name").equals("up")) {
deviceDisplay.upImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("name").equals("down")) {
deviceDisplay.downImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("name").equals("mode")) {
if (tmp_display.getStringAttribute("type").equals("123")) {
deviceDisplay.mode123Image = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("type").equals("abc")) {
deviceDisplay.modeAbcLowerImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("type").equals("ABC")) {
deviceDisplay.modeAbcUpperImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
}
}
}
}
} else if (tmp.getName().equals("keyboard")) {
for (Enumeration e_keyboard = tmp.enumerateChildren(); e_keyboard.hasMoreElements(); ) {
XMLElement tmp_keyboard = (XMLElement) e_keyboard.nextElement();
if (tmp_keyboard.getName().equals("button")) {
Rectangle rectangle = null;
Vector stringArray = new Vector();
for (Enumeration e_button = tmp_keyboard.enumerateChildren(); e_button.hasMoreElements(); ) {
XMLElement tmp_button = (XMLElement) e_button.nextElement();
if (tmp_button.getName().equals("chars")) {
for (Enumeration e_chars = tmp_button.enumerateChildren(); e_chars.hasMoreElements(); ) {
XMLElement tmp_chars = (XMLElement) e_chars.nextElement();
if (tmp_chars.getName().equals("char")) {
stringArray.addElement(tmp_chars.getContent());
}
}
} else if (tmp_button.getName().equals("rectangle")) {
rectangle = getRectangle(tmp_button);
}
}
char[] charArray = new char[stringArray.size()];
for (int i = 0; i < stringArray.size(); i++) {
String str = (String) stringArray.elementAt(i);
if (str.length() > 0) {
charArray[i] = str.charAt(0);
} else {
charArray[i] = ' ';
}
}
buttons.addElement(new AppletButton(tmp_keyboard.getStringAttribute("name"),
rectangle, tmp_keyboard.getStringAttribute("key"), charArray));
} else if (tmp_keyboard.getName().equals("softbutton")) {
Vector commands = new Vector();
Rectangle rectangle = null, paintable = null;
for (Enumeration e_button = tmp_keyboard.enumerateChildren(); e_button.hasMoreElements(); ) {
XMLElement tmp_button = (XMLElement) e_button.nextElement();
if (tmp_button.getName().equals("rectangle")) {
rectangle = getRectangle(tmp_button);
} else if (tmp_button.getName().equals("paintable")) {
paintable = getRectangle(tmp_button);
} else if (tmp_button.getName().equals("command")) {
commands.addElement(tmp_button.getContent());
}
}
String tmp_str = tmp_keyboard.getStringAttribute("menuactivate");
boolean menuactivate = false;
if (tmp_str != null && tmp_str.equals("true")) {
menuactivate = true;
}
AppletSoftButton button = new AppletSoftButton(tmp_keyboard.getStringAttribute("name"),
rectangle, tmp_keyboard.getStringAttribute("key"), paintable,
tmp_keyboard.getStringAttribute("alignment"), commands, menuactivate);
buttons.addElement(button);
softButtons.addElement(button);
}
}
}
}
}
private XMLElement getElement(XMLElement source, String name)
{
for (Enumeration e_content = source.enumerateChildren(); e_content.hasMoreElements(); ) {
XMLElement tmp_content = (XMLElement) e_content.nextElement();
if (tmp_content.getName().equals(name)) {
return tmp_content;
}
}
return null;
}
private Rectangle getRectangle(XMLElement source)
{
Rectangle rect = new Rectangle();
for (Enumeration e_rectangle = source.enumerateChildren(); e_rectangle.hasMoreElements(); ) {
XMLElement tmp_rectangle = (XMLElement) e_rectangle.nextElement();
if (tmp_rectangle.getName().equals("x")) {
rect.x = Integer.parseInt(tmp_rectangle.getContent());
} else if (tmp_rectangle.getName().equals("y")) {
rect.y = Integer.parseInt(tmp_rectangle.getContent());
} else if (tmp_rectangle.getName().equals("width")) {
rect.width = Integer.parseInt(tmp_rectangle.getContent());
} else if (tmp_rectangle.getName().equals("height")) {
rect.height = Integer.parseInt(tmp_rectangle.getContent());
}
}
return rect;
}
private boolean parseBoolean(String value)
{
if (value.toLowerCase().equals(new String("true").toLowerCase())) {
return true;
} else {
return false;
}
}
private Image getSystemImage(String str)
throws IOException
{
InputStream is;
is = EmulatorContext.class.getResourceAsStream(str);
if (is == null) {
throw new IOException();
}
PngImage png = new PngImage(is);
return Toolkit.getDefaultToolkit().createImage(png);
}
private Image getImage(String str)
{
InputStream is = EmulatorContext.class.getResourceAsStream(str);
return getImage(is);
}
private Image getImage(InputStream is)
{
ImageFilter filter = null;
PngImage png = new PngImage(is);
if (getDeviceDisplay().isColor()) {
filter = new RGBImageFilter();
} else {
if (getDeviceDisplay().numColors() == 2) {
filter = new BWImageFilter();
} else {
filter = new GrayImageFilter();
}
}
FilteredImageSource imageSource = new FilteredImageSource(png, filter);
return Toolkit.getDefaultToolkit().createImage(imageSource);
}
}
| true | true | public void loadConfig(String config)
{
String xml = "";
InputStream dis = new BufferedInputStream(getClass().getResourceAsStream(config));
try {
while (dis.available() > 0) {
byte[] b = new byte[dis.available()];
dis.read(b);
xml += new String(b);
}
} catch (Exception ex) {
System.out.println("Cannot find com.barteo.emulator.device.device.txt definition file");
return;
}
XMLElement doc = new XMLElement();
try {
doc.parseString(xml);
} catch (XMLParseException ex) {
System.err.println(ex);
return;
}
for (Enumeration e = doc.enumerateChildren(); e.hasMoreElements(); ) {
XMLElement tmp = (XMLElement) e.nextElement();
if (tmp.getName().equals("img")) {
try {
if (tmp.getStringAttribute("name").equals("normal")) {
normalImage = getSystemImage(tmp.getStringAttribute("src"));
} else if (tmp.getStringAttribute("name").equals("over")) {
overImage = getSystemImage(tmp.getStringAttribute("src"));
} else if (tmp.getStringAttribute("name").equals("pressed")) {
pressedImage = getSystemImage(tmp.getStringAttribute("src"));
}
} catch (IOException ex) {
System.out.println("Cannot load " + tmp.getStringAttribute("src"));
return;
}
} else if (tmp.getName().equals("display")) {
for (Enumeration e_display = tmp.enumerateChildren(); e_display.hasMoreElements(); ) {
XMLElement tmp_display = (XMLElement) e_display.nextElement();
if (tmp_display.getName().equals("numcolors")) {
deviceDisplay.numColors = Integer.parseInt(tmp_display.getContent());
} else if (tmp_display.getName().equals("iscolor")) {
deviceDisplay.isColor = parseBoolean(tmp_display.getContent());
} else if (tmp_display.getName().equals("background")) {
deviceDisplay.backgroundColor = new Color(Integer.parseInt(tmp_display.getContent(), 16));
} else if (tmp_display.getName().equals("foreground")) {
deviceDisplay.foregroundColor = new Color(Integer.parseInt(tmp_display.getContent(), 16));
} else if (tmp_display.getName().equals("rectangle")) {
deviceDisplay.displayRectangle = getRectangle(tmp_display);
} else if (tmp_display.getName().equals("paintable")) {
deviceDisplay.displayPaintable = getRectangle(tmp_display);
} else if (tmp_display.getName().equals("img")) {
if (tmp_display.getStringAttribute("name").equals("up")) {
deviceDisplay.upImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("name").equals("down")) {
deviceDisplay.downImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("name").equals("mode")) {
if (tmp_display.getStringAttribute("type").equals("123")) {
deviceDisplay.mode123Image = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("type").equals("abc")) {
deviceDisplay.modeAbcLowerImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("type").equals("ABC")) {
deviceDisplay.modeAbcUpperImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
}
}
}
}
} else if (tmp.getName().equals("keyboard")) {
for (Enumeration e_keyboard = tmp.enumerateChildren(); e_keyboard.hasMoreElements(); ) {
XMLElement tmp_keyboard = (XMLElement) e_keyboard.nextElement();
if (tmp_keyboard.getName().equals("button")) {
Rectangle rectangle = null;
Vector stringArray = new Vector();
for (Enumeration e_button = tmp_keyboard.enumerateChildren(); e_button.hasMoreElements(); ) {
XMLElement tmp_button = (XMLElement) e_button.nextElement();
if (tmp_button.getName().equals("chars")) {
for (Enumeration e_chars = tmp_button.enumerateChildren(); e_chars.hasMoreElements(); ) {
XMLElement tmp_chars = (XMLElement) e_chars.nextElement();
if (tmp_chars.getName().equals("char")) {
stringArray.addElement(tmp_chars.getContent());
}
}
} else if (tmp_button.getName().equals("rectangle")) {
rectangle = getRectangle(tmp_button);
}
}
char[] charArray = new char[stringArray.size()];
for (int i = 0; i < stringArray.size(); i++) {
String str = (String) stringArray.elementAt(i);
if (str.length() > 0) {
charArray[i] = str.charAt(0);
} else {
charArray[i] = ' ';
}
}
buttons.addElement(new AppletButton(tmp_keyboard.getStringAttribute("name"),
rectangle, tmp_keyboard.getStringAttribute("key"), charArray));
} else if (tmp_keyboard.getName().equals("softbutton")) {
Vector commands = new Vector();
Rectangle rectangle = null, paintable = null;
for (Enumeration e_button = tmp_keyboard.enumerateChildren(); e_button.hasMoreElements(); ) {
XMLElement tmp_button = (XMLElement) e_button.nextElement();
if (tmp_button.getName().equals("rectangle")) {
rectangle = getRectangle(tmp_button);
} else if (tmp_button.getName().equals("paintable")) {
paintable = getRectangle(tmp_button);
} else if (tmp_button.getName().equals("command")) {
commands.addElement(tmp_button.getContent());
}
}
String tmp_str = tmp_keyboard.getStringAttribute("menuactivate");
boolean menuactivate = false;
if (tmp_str != null && tmp_str.equals("true")) {
menuactivate = true;
}
AppletSoftButton button = new AppletSoftButton(tmp_keyboard.getStringAttribute("name"),
rectangle, tmp_keyboard.getStringAttribute("key"), paintable,
tmp_keyboard.getStringAttribute("alignment"), commands, menuactivate);
buttons.addElement(button);
softButtons.addElement(button);
}
}
}
}
}
| public void loadConfig(String config)
{
String xml = "";
InputStream dis = new BufferedInputStream(getClass().getResourceAsStream(config));
try {
while (dis.available() > 0) {
byte[] b = new byte[dis.available()];
dis.read(b);
xml += new String(b);
}
} catch (Exception ex) {
System.out.println("Cannot load " + config + " definition file");
return;
}
XMLElement doc = new XMLElement();
try {
doc.parseString(xml);
} catch (XMLParseException ex) {
System.err.println(ex);
return;
}
for (Enumeration e = doc.enumerateChildren(); e.hasMoreElements(); ) {
XMLElement tmp = (XMLElement) e.nextElement();
if (tmp.getName().equals("img")) {
try {
if (tmp.getStringAttribute("name").equals("normal")) {
normalImage = getSystemImage(tmp.getStringAttribute("src"));
} else if (tmp.getStringAttribute("name").equals("over")) {
overImage = getSystemImage(tmp.getStringAttribute("src"));
} else if (tmp.getStringAttribute("name").equals("pressed")) {
pressedImage = getSystemImage(tmp.getStringAttribute("src"));
}
} catch (IOException ex) {
System.out.println("Cannot load " + tmp.getStringAttribute("src"));
return;
}
} else if (tmp.getName().equals("display")) {
for (Enumeration e_display = tmp.enumerateChildren(); e_display.hasMoreElements(); ) {
XMLElement tmp_display = (XMLElement) e_display.nextElement();
if (tmp_display.getName().equals("numcolors")) {
deviceDisplay.numColors = Integer.parseInt(tmp_display.getContent());
} else if (tmp_display.getName().equals("iscolor")) {
deviceDisplay.isColor = parseBoolean(tmp_display.getContent());
} else if (tmp_display.getName().equals("background")) {
deviceDisplay.backgroundColor = new Color(Integer.parseInt(tmp_display.getContent(), 16));
} else if (tmp_display.getName().equals("foreground")) {
deviceDisplay.foregroundColor = new Color(Integer.parseInt(tmp_display.getContent(), 16));
} else if (tmp_display.getName().equals("rectangle")) {
deviceDisplay.displayRectangle = getRectangle(tmp_display);
} else if (tmp_display.getName().equals("paintable")) {
deviceDisplay.displayPaintable = getRectangle(tmp_display);
} else if (tmp_display.getName().equals("img")) {
if (tmp_display.getStringAttribute("name").equals("up")) {
deviceDisplay.upImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("name").equals("down")) {
deviceDisplay.downImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("name").equals("mode")) {
if (tmp_display.getStringAttribute("type").equals("123")) {
deviceDisplay.mode123Image = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("type").equals("abc")) {
deviceDisplay.modeAbcLowerImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
} else if (tmp_display.getStringAttribute("type").equals("ABC")) {
deviceDisplay.modeAbcUpperImage = new PositionedImage(
getImage(tmp_display.getStringAttribute("src")),
getRectangle(getElement(tmp_display, "paintable")));
}
}
}
}
} else if (tmp.getName().equals("keyboard")) {
for (Enumeration e_keyboard = tmp.enumerateChildren(); e_keyboard.hasMoreElements(); ) {
XMLElement tmp_keyboard = (XMLElement) e_keyboard.nextElement();
if (tmp_keyboard.getName().equals("button")) {
Rectangle rectangle = null;
Vector stringArray = new Vector();
for (Enumeration e_button = tmp_keyboard.enumerateChildren(); e_button.hasMoreElements(); ) {
XMLElement tmp_button = (XMLElement) e_button.nextElement();
if (tmp_button.getName().equals("chars")) {
for (Enumeration e_chars = tmp_button.enumerateChildren(); e_chars.hasMoreElements(); ) {
XMLElement tmp_chars = (XMLElement) e_chars.nextElement();
if (tmp_chars.getName().equals("char")) {
stringArray.addElement(tmp_chars.getContent());
}
}
} else if (tmp_button.getName().equals("rectangle")) {
rectangle = getRectangle(tmp_button);
}
}
char[] charArray = new char[stringArray.size()];
for (int i = 0; i < stringArray.size(); i++) {
String str = (String) stringArray.elementAt(i);
if (str.length() > 0) {
charArray[i] = str.charAt(0);
} else {
charArray[i] = ' ';
}
}
buttons.addElement(new AppletButton(tmp_keyboard.getStringAttribute("name"),
rectangle, tmp_keyboard.getStringAttribute("key"), charArray));
} else if (tmp_keyboard.getName().equals("softbutton")) {
Vector commands = new Vector();
Rectangle rectangle = null, paintable = null;
for (Enumeration e_button = tmp_keyboard.enumerateChildren(); e_button.hasMoreElements(); ) {
XMLElement tmp_button = (XMLElement) e_button.nextElement();
if (tmp_button.getName().equals("rectangle")) {
rectangle = getRectangle(tmp_button);
} else if (tmp_button.getName().equals("paintable")) {
paintable = getRectangle(tmp_button);
} else if (tmp_button.getName().equals("command")) {
commands.addElement(tmp_button.getContent());
}
}
String tmp_str = tmp_keyboard.getStringAttribute("menuactivate");
boolean menuactivate = false;
if (tmp_str != null && tmp_str.equals("true")) {
menuactivate = true;
}
AppletSoftButton button = new AppletSoftButton(tmp_keyboard.getStringAttribute("name"),
rectangle, tmp_keyboard.getStringAttribute("key"), paintable,
tmp_keyboard.getStringAttribute("alignment"), commands, menuactivate);
buttons.addElement(button);
softButtons.addElement(button);
}
}
}
}
}
|
diff --git a/src/org/mozilla/javascript/Interpreter.java b/src/org/mozilla/javascript/Interpreter.java
index 0673433c..189d6193 100644
--- a/src/org/mozilla/javascript/Interpreter.java
+++ b/src/org/mozilla/javascript/Interpreter.java
@@ -1,3042 +1,3041 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape 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/NPL/
*
* 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 Netscape are
* Copyright (C) 1997-2000 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
* Patrick Beard
* Norris Boyd
* Igor Bukanov
* Roger Lawrence
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (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 NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript;
import java.io.*;
import org.mozilla.javascript.debug.*;
public class Interpreter
{
// Additional interpreter-specific codes
private static final int BASE_ICODE = Token.LAST_BYTECODE_TOKEN;
private static final int
Icode_DUP = BASE_ICODE + 1,
// various types of ++/--
Icode_NAMEINC = BASE_ICODE + 2,
Icode_PROPINC = BASE_ICODE + 3,
Icode_ELEMINC = BASE_ICODE + 4,
Icode_VARINC = BASE_ICODE + 5,
Icode_NAMEDEC = BASE_ICODE + 6,
Icode_PROPDEC = BASE_ICODE + 7,
Icode_ELEMDEC = BASE_ICODE + 8,
Icode_VARDEC = BASE_ICODE + 9,
// helper codes to deal with activation
Icode_SCOPE = BASE_ICODE + 10,
Icode_TYPEOFNAME = BASE_ICODE + 11,
// Access to parent scope and prototype
Icode_GETPROTO = BASE_ICODE + 12,
Icode_GETPARENT = BASE_ICODE + 13,
Icode_GETSCOPEPARENT = BASE_ICODE + 14,
Icode_SETPROTO = BASE_ICODE + 15,
Icode_SETPARENT = BASE_ICODE + 16,
// Create closure object for nested functions
Icode_CLOSURE = BASE_ICODE + 17,
// Special calls
Icode_CALLSPECIAL = BASE_ICODE + 18,
// To return undefined value
Icode_RETUNDEF = BASE_ICODE + 19,
// Exception handling implementation
Icode_CATCH = BASE_ICODE + 20,
Icode_GOSUB = BASE_ICODE + 21,
Icode_RETSUB = BASE_ICODE + 22,
// To indicating a line number change in icodes.
Icode_LINE = BASE_ICODE + 23,
// To store shorts and ints inline
Icode_SHORTNUMBER = BASE_ICODE + 24,
Icode_INTNUMBER = BASE_ICODE + 25,
// Last icode
Icode_END = BASE_ICODE + 26;
public IRFactory createIRFactory(Context cx, TokenStream ts)
{
return new IRFactory(this, ts);
}
public FunctionNode createFunctionNode(IRFactory irFactory, String name)
{
return new FunctionNode(name);
}
public ScriptOrFnNode transform(Context cx, IRFactory irFactory,
ScriptOrFnNode tree)
{
(new NodeTransformer(irFactory)).transform(tree);
return tree;
}
public Object compile(Context cx, Scriptable scope, ScriptOrFnNode tree,
SecurityController securityController,
Object securityDomain, String encodedSource)
{
scriptOrFn = tree;
itsData = new InterpreterData(securityDomain, cx.getLanguageVersion());
itsData.itsSourceFile = scriptOrFn.getSourceName();
itsData.encodedSource = encodedSource;
if (tree instanceof FunctionNode) {
generateFunctionICode(cx, scope);
return createFunction(cx, scope, itsData, false);
} else {
generateICodeFromTree(cx, scope, scriptOrFn);
return new InterpretedScript(itsData);
}
}
public void notifyDebuggerCompilationDone(Context cx,
Object scriptOrFunction,
String debugSource)
{
InterpreterData idata;
if (scriptOrFunction instanceof InterpretedScript) {
idata = ((InterpretedScript)scriptOrFunction).itsData;
} else {
idata = ((InterpretedFunction)scriptOrFunction).itsData;
}
notifyDebugger_r(cx, idata, debugSource);
}
private static void notifyDebugger_r(Context cx, InterpreterData idata,
String debugSource)
{
if (idata.itsNestedFunctions != null) {
for (int i = 0; i != idata.itsNestedFunctions.length; ++i) {
notifyDebugger_r(cx, idata.itsNestedFunctions[i], debugSource);
}
}
cx.debugger.handleCompilationDone(cx, idata, debugSource);
}
private void generateFunctionICode(Context cx, Scriptable scope)
{
FunctionNode theFunction = (FunctionNode)scriptOrFn;
itsData.itsFunctionType = theFunction.getFunctionType();
itsData.itsNeedsActivation = theFunction.requiresActivation();
itsData.itsName = theFunction.getFunctionName();
generateICodeFromTree(cx, scope, theFunction.getLastChild());
}
private void generateICodeFromTree(Context cx, Scriptable scope, Node tree)
{
generateNestedFunctions(cx, scope);
generateRegExpLiterals(cx, scope);
int theICodeTop = 0;
theICodeTop = generateICode(tree, theICodeTop);
itsLabels.fixLabelGotos(itsData.itsICode);
// add Icode_END only to scripts as function always ends with RETURN
if (itsData.itsFunctionType == 0) {
theICodeTop = addIcode(Icode_END, theICodeTop);
}
// Add special CATCH to simplify Interpreter.interpret logic
// and workaround lack of goto in Java
theICodeTop = addIcode(Icode_CATCH, theICodeTop);
itsData.itsICodeTop = theICodeTop;
if (itsData.itsICode.length != theICodeTop) {
// Make itsData.itsICode length exactly theICodeTop to save memory
// and catch bugs with jumps beyound icode as early as possible
byte[] tmp = new byte[theICodeTop];
System.arraycopy(itsData.itsICode, 0, tmp, 0, theICodeTop);
itsData.itsICode = tmp;
}
if (itsStrings.size() == 0) {
itsData.itsStringTable = null;
} else {
itsData.itsStringTable = new String[itsStrings.size()];
ObjToIntMap.Iterator iter = itsStrings.newIterator();
for (iter.start(); !iter.done(); iter.next()) {
String str = (String)iter.getKey();
int index = iter.getValue();
if (itsData.itsStringTable[index] != null) Context.codeBug();
itsData.itsStringTable[index] = str;
}
}
if (itsDoubleTableTop == 0) {
itsData.itsDoubleTable = null;
} else if (itsData.itsDoubleTable.length != itsDoubleTableTop) {
double[] tmp = new double[itsDoubleTableTop];
System.arraycopy(itsData.itsDoubleTable, 0, tmp, 0,
itsDoubleTableTop);
itsData.itsDoubleTable = tmp;
}
if (itsExceptionTableTop != 0
&& itsData.itsExceptionTable.length != itsExceptionTableTop)
{
int[] tmp = new int[itsExceptionTableTop];
System.arraycopy(itsData.itsExceptionTable, 0, tmp, 0,
itsExceptionTableTop);
itsData.itsExceptionTable = tmp;
}
itsData.itsMaxVars = scriptOrFn.getParamAndVarCount();
// itsMaxFrameArray: interpret method needs this amount for its
// stack and sDbl arrays
itsData.itsMaxFrameArray = itsData.itsMaxVars
+ itsData.itsMaxLocals
+ itsData.itsMaxStack;
itsData.argNames = scriptOrFn.getParamAndVarNames();
itsData.argCount = scriptOrFn.getParamCount();
itsData.encodedSourceStart = scriptOrFn.getEncodedSourceStart();
itsData.encodedSourceEnd = scriptOrFn.getEncodedSourceEnd();
if (Token.printICode) dumpICode(itsData);
}
private void generateNestedFunctions(Context cx, Scriptable scope)
{
int functionCount = scriptOrFn.getFunctionCount();
if (functionCount == 0) return;
InterpreterData[] array = new InterpreterData[functionCount];
for (int i = 0; i != functionCount; i++) {
FunctionNode def = scriptOrFn.getFunctionNode(i);
Interpreter jsi = new Interpreter();
jsi.scriptOrFn = def;
jsi.itsData = new InterpreterData(itsData.securityDomain,
itsData.languageVersion);
jsi.itsData.itsSourceFile = itsData.itsSourceFile;
jsi.itsData.encodedSource = itsData.encodedSource;
jsi.itsData.itsCheckThis = def.getCheckThis();
jsi.itsInFunctionFlag = true;
jsi.generateFunctionICode(cx, scope);
array[i] = jsi.itsData;
}
itsData.itsNestedFunctions = array;
}
private void generateRegExpLiterals(Context cx, Scriptable scope)
{
int N = scriptOrFn.getRegexpCount();
if (N == 0) return;
RegExpProxy rep = cx.getRegExpProxy();
if (rep == null) {
throw cx.reportRuntimeError0("msg.no.regexp");
}
Object[] array = new Object[N];
for (int i = 0; i != N; i++) {
String string = scriptOrFn.getRegexpString(i);
String flags = scriptOrFn.getRegexpFlags(i);
array[i] = rep.newRegExp(cx, scope, string, flags, false);
}
itsData.itsRegExpLiterals = array;
}
private int updateLineNumber(Node node, int iCodeTop)
{
int lineno = node.getLineno();
if (lineno != itsLineNumber && lineno >= 0) {
itsLineNumber = lineno;
iCodeTop = addIcode(Icode_LINE, iCodeTop);
iCodeTop = addShort(lineno, iCodeTop);
}
return iCodeTop;
}
private void badTree(Node node)
{
throw new RuntimeException("Un-handled node: "+node.toString());
}
private int generateICode(Node node, int iCodeTop)
{
int type = node.getType();
Node child = node.getFirstChild();
Node firstChild = child;
switch (type) {
case Token.FUNCTION : {
int fnIndex = node.getExistingIntProp(Node.FUNCTION_PROP);
FunctionNode fn = scriptOrFn.getFunctionNode(fnIndex);
if (fn.itsFunctionType != FunctionNode.FUNCTION_STATEMENT) {
// Only function expressions or function expression
// statements needs closure code creating new function
// object on stack as function statements are initialized
// at script/function start
iCodeTop = addIcode(Icode_CLOSURE, iCodeTop);
iCodeTop = addIndex(fnIndex, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
break;
}
case Token.SCRIPT :
iCodeTop = updateLineNumber(node, iCodeTop);
while (child != null) {
if (child.getType() != Token.FUNCTION)
iCodeTop = generateICode(child, iCodeTop);
child = child.getNext();
}
break;
case Token.CASE :
iCodeTop = updateLineNumber(node, iCodeTop);
child = child.getNext();
while (child != null) {
iCodeTop = generateICode(child, iCodeTop);
child = child.getNext();
}
break;
case Token.LABEL :
case Token.LOOP :
case Token.DEFAULT :
case Token.BLOCK :
case Token.EMPTY :
case Token.NOP :
iCodeTop = updateLineNumber(node, iCodeTop);
while (child != null) {
iCodeTop = generateICode(child, iCodeTop);
child = child.getNext();
}
break;
case Token.WITH :
++itsWithDepth;
iCodeTop = updateLineNumber(node, iCodeTop);
while (child != null) {
iCodeTop = generateICode(child, iCodeTop);
child = child.getNext();
}
--itsWithDepth;
break;
case Token.COMMA :
iCodeTop = generateICode(child, iCodeTop);
while (null != (child = child.getNext())) {
iCodeTop = addToken(Token.POP, iCodeTop);
itsStackDepth--;
iCodeTop = generateICode(child, iCodeTop);
}
break;
case Token.SWITCH : {
iCodeTop = updateLineNumber(node, iCodeTop);
iCodeTop = generateICode(child, iCodeTop);
int theLocalSlot = itsData.itsMaxLocals++;
iCodeTop = addToken(Token.NEWTEMP, iCodeTop);
iCodeTop = addByte(theLocalSlot, iCodeTop);
iCodeTop = addToken(Token.POP, iCodeTop);
itsStackDepth--;
ObjArray cases = (ObjArray) node.getProp(Node.CASES_PROP);
for (int i = 0; i < cases.size(); i++) {
Node thisCase = (Node)cases.get(i);
Node first = thisCase.getFirstChild();
// the case expression is the firstmost child
// the rest will be generated when the case
// statements are encountered as siblings of
// the switch statement.
iCodeTop = generateICode(first, iCodeTop);
iCodeTop = addToken(Token.USETEMP, iCodeTop);
iCodeTop = addByte(theLocalSlot, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
iCodeTop = addToken(Token.SHEQ, iCodeTop);
itsStackDepth--;
Node target = new Node(Token.TARGET);
thisCase.addChildAfter(target, first);
iCodeTop = addGoto(target, Token.IFEQ, iCodeTop);
}
Node defaultNode = (Node) node.getProp(Node.DEFAULT_PROP);
if (defaultNode != null) {
Node defaultTarget = new Node(Token.TARGET);
defaultNode.getFirstChild().
addChildToFront(defaultTarget);
iCodeTop = addGoto(defaultTarget, Token.GOTO,
iCodeTop);
}
Node breakTarget = (Node) node.getProp(Node.BREAK_PROP);
iCodeTop = addGoto(breakTarget, Token.GOTO,
iCodeTop);
break;
}
case Token.TARGET :
markTargetLabel(node, iCodeTop);
break;
case Token.NEW :
case Token.CALL : {
int childCount = 0;
String functionName = null;
while (child != null) {
iCodeTop = generateICode(child, iCodeTop);
if (functionName == null) {
int childType = child.getType();
if (childType == Token.NAME
|| childType == Token.GETPROP)
{
functionName = lastAddString;
}
}
child = child.getNext();
childCount++;
}
int callType = node.getIntProp(Node.SPECIALCALL_PROP,
Node.NON_SPECIALCALL);
if (callType != Node.NON_SPECIALCALL) {
// embed line number and source filename
iCodeTop = addIcode(Icode_CALLSPECIAL, iCodeTop);
iCodeTop = addByte(callType, iCodeTop);
iCodeTop = addByte(type == Token.NEW ? 1 : 0, iCodeTop);
iCodeTop = addShort(itsLineNumber, iCodeTop);
} else {
iCodeTop = addToken(type, iCodeTop);
iCodeTop = addString(functionName, iCodeTop);
}
itsStackDepth -= (childCount - 1); // always a result value
// subtract from child count to account for [thisObj &] fun
if (type == Token.NEW) {
childCount -= 1;
} else {
childCount -= 2;
}
iCodeTop = addIndex(childCount, iCodeTop);
if (childCount > itsData.itsMaxCalleeArgs)
itsData.itsMaxCalleeArgs = childCount;
break;
}
case Token.NEWLOCAL :
case Token.NEWTEMP : {
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(Token.NEWTEMP, iCodeTop);
iCodeTop = addLocalRef(node, iCodeTop);
break;
}
case Token.USELOCAL : {
if (node.getProp(Node.TARGET_PROP) != null) {
iCodeTop = addIcode(Icode_RETSUB, iCodeTop);
} else {
iCodeTop = addToken(Token.USETEMP, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
Node temp = (Node) node.getProp(Node.LOCAL_PROP);
iCodeTop = addLocalRef(temp, iCodeTop);
break;
}
case Token.USETEMP : {
iCodeTop = addToken(Token.USETEMP, iCodeTop);
Node temp = (Node) node.getProp(Node.TEMP_PROP);
iCodeTop = addLocalRef(temp, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
}
case Token.IFEQ :
case Token.IFNE :
iCodeTop = generateICode(child, iCodeTop);
itsStackDepth--; // after the conditional GOTO, really
// fall thru...
case Token.GOTO : {
Node target = (Node)(node.getProp(Node.TARGET_PROP));
iCodeTop = addGoto(target, (byte) type, iCodeTop);
break;
}
case Token.JSR : {
Node target = (Node)(node.getProp(Node.TARGET_PROP));
iCodeTop = addGoto(target, Icode_GOSUB, iCodeTop);
break;
}
case Token.AND : {
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addIcode(Icode_DUP, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
int falseJumpStart = iCodeTop;
iCodeTop = addForwardGoto(Token.IFNE, iCodeTop);
iCodeTop = addToken(Token.POP, iCodeTop);
itsStackDepth--;
child = child.getNext();
iCodeTop = generateICode(child, iCodeTop);
resolveForwardGoto(falseJumpStart, iCodeTop);
break;
}
case Token.OR : {
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addIcode(Icode_DUP, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
int trueJumpStart = iCodeTop;
iCodeTop = addForwardGoto(Token.IFEQ, iCodeTop);
iCodeTop = addToken(Token.POP, iCodeTop);
itsStackDepth--;
child = child.getNext();
iCodeTop = generateICode(child, iCodeTop);
resolveForwardGoto(trueJumpStart, iCodeTop);
break;
}
case Token.GETPROP : {
iCodeTop = generateICode(child, iCodeTop);
String s = (String) node.getProp(Node.SPECIAL_PROP_PROP);
if (s != null) {
if (s.equals("__proto__")) {
iCodeTop = addIcode(Icode_GETPROTO, iCodeTop);
} else if (s.equals("__parent__")) {
iCodeTop = addIcode(Icode_GETSCOPEPARENT, iCodeTop);
} else {
badTree(node);
}
} else {
child = child.getNext();
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(Token.GETPROP, iCodeTop);
itsStackDepth--;
}
break;
}
case Token.DELPROP :
case Token.BITAND :
case Token.BITOR :
case Token.BITXOR :
case Token.LSH :
case Token.RSH :
case Token.URSH :
case Token.ADD :
case Token.SUB :
case Token.MOD :
case Token.DIV :
case Token.MUL :
case Token.GETELEM :
case Token.EQ:
case Token.NE:
case Token.SHEQ:
case Token.SHNE:
case Token.IN :
case Token.INSTANCEOF :
case Token.LE :
case Token.LT :
case Token.GE :
case Token.GT :
iCodeTop = generateICode(child, iCodeTop);
child = child.getNext();
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(type, iCodeTop);
itsStackDepth--;
break;
case Token.POS :
case Token.NEG :
case Token.NOT :
case Token.BITNOT :
case Token.TYPEOF :
case Token.VOID :
iCodeTop = generateICode(child, iCodeTop);
if (type == Token.VOID) {
iCodeTop = addToken(Token.POP, iCodeTop);
iCodeTop = addToken(Token.UNDEFINED, iCodeTop);
} else {
iCodeTop = addToken(type, iCodeTop);
}
break;
case Token.SETPROP : {
iCodeTop = generateICode(child, iCodeTop);
child = child.getNext();
iCodeTop = generateICode(child, iCodeTop);
String s = (String) node.getProp(Node.SPECIAL_PROP_PROP);
if (s != null) {
if (s.equals("__proto__")) {
iCodeTop = addIcode(Icode_SETPROTO, iCodeTop);
} else if (s.equals("__parent__")) {
iCodeTop = addIcode(Icode_SETPARENT, iCodeTop);
} else {
badTree(node);
}
} else {
child = child.getNext();
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(Token.SETPROP, iCodeTop);
itsStackDepth -= 2;
}
break;
}
case Token.SETELEM :
iCodeTop = generateICode(child, iCodeTop);
child = child.getNext();
iCodeTop = generateICode(child, iCodeTop);
child = child.getNext();
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(Token.SETELEM, iCodeTop);
itsStackDepth -= 2;
break;
case Token.SETNAME :
iCodeTop = generateICode(child, iCodeTop);
child = child.getNext();
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(Token.SETNAME, iCodeTop);
iCodeTop = addString(firstChild.getString(), iCodeTop);
itsStackDepth--;
break;
case Token.TYPEOFNAME : {
String name = node.getString();
int index = -1;
// use typeofname if an activation frame exists
// since the vars all exist there instead of in jregs
if (itsInFunctionFlag && !itsData.itsNeedsActivation)
index = scriptOrFn.getParamOrVarIndex(name);
if (index == -1) {
iCodeTop = addIcode(Icode_TYPEOFNAME, iCodeTop);
iCodeTop = addString(name, iCodeTop);
} else {
iCodeTop = addToken(Token.GETVAR, iCodeTop);
iCodeTop = addByte(index, iCodeTop);
iCodeTop = addToken(Token.TYPEOF, iCodeTop);
}
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
}
case Token.PARENT :
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addIcode(Icode_GETPARENT, iCodeTop);
break;
case Token.GETBASE :
case Token.BINDNAME :
case Token.NAME :
case Token.STRING :
iCodeTop = addToken(type, iCodeTop);
iCodeTop = addString(node.getString(), iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
case Token.INC :
case Token.DEC : {
int childType = child.getType();
switch (childType) {
case Token.GETVAR : {
String name = child.getString();
if (itsData.itsNeedsActivation) {
iCodeTop = addIcode(Icode_SCOPE, iCodeTop);
iCodeTop = addToken(Token.STRING, iCodeTop);
iCodeTop = addString(name, iCodeTop);
itsStackDepth += 2;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
iCodeTop = addIcode(type == Token.INC
? Icode_PROPINC
: Icode_PROPDEC,
iCodeTop);
itsStackDepth--;
} else {
int i = scriptOrFn.getParamOrVarIndex(name);
iCodeTop = addIcode(type == Token.INC
? Icode_VARINC
: Icode_VARDEC,
iCodeTop);
iCodeTop = addByte(i, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
break;
}
case Token.GETPROP :
case Token.GETELEM : {
Node getPropChild = child.getFirstChild();
iCodeTop = generateICode(getPropChild, iCodeTop);
getPropChild = getPropChild.getNext();
iCodeTop = generateICode(getPropChild, iCodeTop);
int icode;
if (childType == Token.GETPROP) {
icode = (type == Token.INC)
? Icode_PROPINC : Icode_PROPDEC;
} else {
icode = (type == Token.INC)
? Icode_ELEMINC : Icode_ELEMDEC;
}
iCodeTop = addIcode(icode, iCodeTop);
itsStackDepth--;
break;
}
default : {
iCodeTop = addIcode(type == Token.INC
? Icode_NAMEINC
: Icode_NAMEDEC,
iCodeTop);
iCodeTop = addString(child.getString(), iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
}
}
break;
}
case Token.NUMBER : {
double num = node.getDouble();
int inum = (int)num;
if (inum == num) {
if (inum == 0) {
iCodeTop = addToken(Token.ZERO, iCodeTop);
} else if (inum == 1) {
iCodeTop = addToken(Token.ONE, iCodeTop);
} else if ((short)inum == inum) {
iCodeTop = addIcode(Icode_SHORTNUMBER, iCodeTop);
iCodeTop = addShort(inum, iCodeTop);
} else {
iCodeTop = addIcode(Icode_INTNUMBER, iCodeTop);
iCodeTop = addInt(inum, iCodeTop);
}
} else {
iCodeTop = addToken(Token.NUMBER, iCodeTop);
iCodeTop = addDouble(num, iCodeTop);
}
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
}
case Token.POP :
case Token.POPV :
iCodeTop = updateLineNumber(node, iCodeTop);
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(type, iCodeTop);
itsStackDepth--;
break;
case Token.ENTERWITH :
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(Token.ENTERWITH, iCodeTop);
itsStackDepth--;
break;
case Token.GETTHIS :
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(Token.GETTHIS, iCodeTop);
break;
case Token.NEWSCOPE :
iCodeTop = addToken(Token.NEWSCOPE, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
case Token.LEAVEWITH :
iCodeTop = addToken(Token.LEAVEWITH, iCodeTop);
break;
case Token.TRY : {
Node catchTarget = (Node)node.getProp(Node.TARGET_PROP);
Node finallyTarget = (Node)node.getProp(Node.FINALLY_PROP);
int tryStart = iCodeTop;
int tryEnd = -1;
int catchStart = -1;
int finallyStart = -1;
while (child != null) {
boolean generated = false;
if (child == catchTarget) {
if (child.getType() != Token.TARGET)
Context.codeBug();
if (tryEnd >= 0) Context.codeBug();
tryEnd = iCodeTop;
catchStart = iCodeTop;
markTargetLabel(child, iCodeTop);
generated = true;
// Catch code has exception object on the stack
itsStackDepth = 1;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
} else if (child == finallyTarget) {
if (child.getType() != Token.TARGET)
Context.codeBug();
if (tryEnd < 0) {
tryEnd = iCodeTop;
}
finallyStart = iCodeTop;
markTargetLabel(child, iCodeTop);
generated = true;
// Adjust stack for finally code: on the top of the
// stack it has either a PC value when called from
// GOSUB or exception object to rethrow when called
// from exception handler
itsStackDepth = 1;
if (itsStackDepth > itsData.itsMaxStack) {
itsData.itsMaxStack = itsStackDepth;
}
}
if (!generated) {
iCodeTop = generateICode(child, iCodeTop);
}
child = child.getNext();
}
itsStackDepth = 0;
// [tryStart, tryEnd) contains GOSUB to call finally when it
// presents at the end of try code and before return, break
// continue that transfer control outside try.
// After finally is executed the control will be
// transfered back into [tryStart, tryEnd) and exception
// handling assumes that the only code executed after
// finally returns will be a jump outside try which could not
// trigger exceptions.
// It does not hold if instruction observer throws during
// goto. Currently it may lead to double execution of finally.
addExceptionHandler(tryStart, tryEnd, catchStart, finallyStart,
itsWithDepth);
break;
}
case Token.THROW :
iCodeTop = updateLineNumber(node, iCodeTop);
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(Token.THROW, iCodeTop);
iCodeTop = addShort(itsLineNumber, iCodeTop);
itsStackDepth--;
break;
case Token.RETURN :
iCodeTop = updateLineNumber(node, iCodeTop);
if (child != null) {
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(Token.RETURN, iCodeTop);
itsStackDepth--;
} else {
iCodeTop = addIcode(Icode_RETUNDEF, iCodeTop);
}
break;
case Token.GETVAR : {
String name = node.getString();
if (itsData.itsNeedsActivation) {
// SETVAR handled this by turning into a SETPROP, but
// we can't do that to a GETVAR without manufacturing
// bogus children. Instead we use a special op to
// push the current scope.
iCodeTop = addIcode(Icode_SCOPE, iCodeTop);
iCodeTop = addToken(Token.STRING, iCodeTop);
iCodeTop = addString(name, iCodeTop);
itsStackDepth += 2;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
iCodeTop = addToken(Token.GETPROP, iCodeTop);
itsStackDepth--;
} else {
int index = scriptOrFn.getParamOrVarIndex(name);
iCodeTop = addToken(Token.GETVAR, iCodeTop);
iCodeTop = addByte(index, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
}
break;
}
case Token.SETVAR : {
if (itsData.itsNeedsActivation) {
child.setType(Token.BINDNAME);
node.setType(Token.SETNAME);
iCodeTop = generateICode(node, iCodeTop);
} else {
String name = child.getString();
child = child.getNext();
iCodeTop = generateICode(child, iCodeTop);
int index = scriptOrFn.getParamOrVarIndex(name);
iCodeTop = addToken(Token.SETVAR, iCodeTop);
iCodeTop = addByte(index, iCodeTop);
}
break;
}
case Token.NULL:
case Token.THIS:
case Token.THISFN:
case Token.FALSE:
case Token.TRUE:
case Token.UNDEFINED:
iCodeTop = addToken(type, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
case Token.ENUMINIT :
iCodeTop = generateICode(child, iCodeTop);
iCodeTop = addToken(Token.ENUMINIT, iCodeTop);
iCodeTop = addLocalRef(node, iCodeTop);
itsStackDepth--;
break;
case Token.ENUMNEXT : {
iCodeTop = addToken(Token.ENUMNEXT, iCodeTop);
Node init = (Node)node.getProp(Node.ENUM_PROP);
iCodeTop = addLocalRef(init, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
}
case Token.ENUMDONE :
// could release the local here??
break;
case Token.REGEXP : {
int index = node.getExistingIntProp(Node.REGEXP_PROP);
iCodeTop = addToken(Token.REGEXP, iCodeTop);
iCodeTop = addIndex(index, iCodeTop);
itsStackDepth++;
if (itsStackDepth > itsData.itsMaxStack)
itsData.itsMaxStack = itsStackDepth;
break;
}
default :
badTree(node);
break;
}
return iCodeTop;
}
private int addLocalRef(Node node, int iCodeTop)
{
int theLocalSlot = node.getIntProp(Node.LOCAL_PROP, -1);
if (theLocalSlot == -1) {
theLocalSlot = itsData.itsMaxLocals++;
node.putIntProp(Node.LOCAL_PROP, theLocalSlot);
}
iCodeTop = addByte(theLocalSlot, iCodeTop);
if (theLocalSlot >= itsData.itsMaxLocals)
itsData.itsMaxLocals = theLocalSlot + 1;
return iCodeTop;
}
private int getTargetLabel(Node target) {
int targetLabel = target.getIntProp(Node.LABEL_PROP, -1);
if (targetLabel == -1) {
targetLabel = itsLabels.acquireLabel();
target.putIntProp(Node.LABEL_PROP, targetLabel);
}
return targetLabel;
}
private void markTargetLabel(Node target, int iCodeTop)
{
int label = getTargetLabel(target);
itsLabels.markLabel(label, iCodeTop);
}
private int addGoto(Node target, int gotoOp, int iCodeTop)
{
int targetLabel = getTargetLabel(target);
int gotoPC = iCodeTop;
if (gotoOp > BASE_ICODE) {
iCodeTop = addIcode(gotoOp, iCodeTop);
} else {
iCodeTop = addToken(gotoOp, iCodeTop);
}
iCodeTop = addShort(0, iCodeTop);
int targetPC = itsLabels.getLabelPC(targetLabel);
if (targetPC != -1) {
recordJumpOffset(gotoPC + 1, targetPC - gotoPC);
} else {
itsLabels.addLabelFixup(targetLabel, gotoPC + 1);
}
return iCodeTop;
}
private int addForwardGoto(int gotoOp, int iCodeTop)
{
iCodeTop = addToken(gotoOp, iCodeTop);
iCodeTop = addShort(0, iCodeTop);
return iCodeTop;
}
private void resolveForwardGoto(int jumpStart, int iCodeTop)
{
if (jumpStart + 3 > iCodeTop) Context.codeBug();
int offset = iCodeTop - jumpStart;
// +1 to write after jump icode
recordJumpOffset(jumpStart + 1, offset);
}
private void recordJumpOffset(int pos, int offset)
{
if (offset != (short)offset) {
throw Context.reportRuntimeError0("msg.too.big.jump");
}
itsData.itsICode[pos] = (byte)(offset >> 8);
itsData.itsICode[pos + 1] = (byte)offset;
}
private int addByte(int b, int iCodeTop)
{
byte[] array = itsData.itsICode;
if (iCodeTop == array.length) {
array = increaseICodeCapasity(iCodeTop, 1);
}
array[iCodeTop++] = (byte)b;
return iCodeTop;
}
private int addToken(int token, int iCodeTop)
{
if (!(Token.FIRST_BYTECODE_TOKEN <= token
&& token <= Token.LAST_BYTECODE_TOKEN))
{
Context.codeBug();
}
return addByte(token, iCodeTop);
}
private int addIcode(int icode, int iCodeTop)
{
if (!(BASE_ICODE < icode && icode <= Icode_END)) Context.codeBug();
return addByte(icode, iCodeTop);
}
private int addShort(int s, int iCodeTop)
{
byte[] array = itsData.itsICode;
if (iCodeTop + 2 > array.length) {
array = increaseICodeCapasity(iCodeTop, 2);
}
array[iCodeTop] = (byte)(s >>> 8);
array[iCodeTop + 1] = (byte)s;
return iCodeTop + 2;
}
private int addIndex(int index, int iCodeTop)
{
if (index < 0) Context.codeBug();
if (index > 0xFFFF) {
throw Context.reportRuntimeError0("msg.too.big.index");
}
byte[] array = itsData.itsICode;
if (iCodeTop + 2 > array.length) {
array = increaseICodeCapasity(iCodeTop, 2);
}
array[iCodeTop] = (byte)(index >>> 8);
array[iCodeTop + 1] = (byte)index;
return iCodeTop + 2;
}
private int addInt(int i, int iCodeTop)
{
byte[] array = itsData.itsICode;
if (iCodeTop + 4 > array.length) {
array = increaseICodeCapasity(iCodeTop, 4);
}
array[iCodeTop] = (byte)(i >>> 24);
array[iCodeTop + 1] = (byte)(i >>> 16);
array[iCodeTop + 2] = (byte)(i >>> 8);
array[iCodeTop + 3] = (byte)i;
return iCodeTop + 4;
}
private int addDouble(double num, int iCodeTop)
{
int index = itsDoubleTableTop;
if (index == 0) {
itsData.itsDoubleTable = new double[64];
} else if (itsData.itsDoubleTable.length == index) {
double[] na = new double[index * 2];
System.arraycopy(itsData.itsDoubleTable, 0, na, 0, index);
itsData.itsDoubleTable = na;
}
itsData.itsDoubleTable[index] = num;
itsDoubleTableTop = index + 1;
iCodeTop = addIndex(index, iCodeTop);
return iCodeTop;
}
private int addString(String str, int iCodeTop)
{
int index = itsStrings.get(str, -1);
if (index == -1) {
index = itsStrings.size();
itsStrings.put(str, index);
}
iCodeTop = addIndex(index, iCodeTop);
lastAddString = str;
return iCodeTop;
}
private void addExceptionHandler(int icodeStart, int icodeEnd,
int catchStart, int finallyStart,
int withDepth)
{
int top = itsExceptionTableTop;
int[] table = itsData.itsExceptionTable;
if (table == null) {
if (top != 0) Context.codeBug();
table = new int[EXCEPTION_SLOT_SIZE * 2];
itsData.itsExceptionTable = table;
} else if (table.length == top) {
table = new int[table.length * 2];
System.arraycopy(itsData.itsExceptionTable, 0, table, 0, top);
itsData.itsExceptionTable = table;
}
table[top + EXCEPTION_TRY_START_SLOT] = icodeStart;
table[top + EXCEPTION_TRY_END_SLOT] = icodeEnd;
table[top + EXCEPTION_CATCH_SLOT] = catchStart;
table[top + EXCEPTION_FINALLY_SLOT] = finallyStart;
table[top + EXCEPTION_WITH_DEPTH_SLOT] = withDepth;
itsExceptionTableTop = top + EXCEPTION_SLOT_SIZE;
}
private byte[] increaseICodeCapasity(int iCodeTop, int extraSize) {
int capacity = itsData.itsICode.length;
if (iCodeTop + extraSize <= capacity) Context.codeBug();
capacity *= 2;
if (iCodeTop + extraSize > capacity) {
capacity = iCodeTop + extraSize;
}
byte[] array = new byte[capacity];
System.arraycopy(itsData.itsICode, 0, array, 0, iCodeTop);
itsData.itsICode = array;
return array;
}
private static int getShort(byte[] iCode, int pc) {
return (iCode[pc] << 8) | (iCode[pc + 1] & 0xFF);
}
private static int getIndex(byte[] iCode, int pc) {
return ((iCode[pc] & 0xFF) << 8) | (iCode[pc + 1] & 0xFF);
}
private static int getInt(byte[] iCode, int pc) {
return (iCode[pc] << 24) | ((iCode[pc + 1] & 0xFF) << 16)
| ((iCode[pc + 2] & 0xFF) << 8) | (iCode[pc + 3] & 0xFF);
}
private static int getTarget(byte[] iCode, int pc) {
int displacement = getShort(iCode, pc);
return pc - 1 + displacement;
}
private static int getExceptionHandler(int[] exceptionTable, int pc)
{
// OPT: use binary search
if (exceptionTable == null) { return -1; }
int best = -1, bestStart = 0, bestEnd = 0;
for (int i = 0; i != exceptionTable.length; i += EXCEPTION_SLOT_SIZE) {
int start = exceptionTable[i + EXCEPTION_TRY_START_SLOT];
int end = exceptionTable[i + EXCEPTION_TRY_END_SLOT];
if (start <= pc && pc < end) {
if (best < 0 || bestStart <= start) {
// Check handlers are nested
if (best >= 0 && bestEnd < end) Context.codeBug();
best = i;
bestStart = start;
bestEnd = end;
}
}
}
return best;
}
private static String icodeToName(int icode)
{
if (Token.printICode) {
if (icode <= Token.LAST_BYTECODE_TOKEN) {
return Token.name(icode);
} else {
switch (icode) {
case Icode_DUP: return "dup";
case Icode_NAMEINC: return "nameinc";
case Icode_PROPINC: return "propinc";
case Icode_ELEMINC: return "eleminc";
case Icode_VARINC: return "varinc";
case Icode_NAMEDEC: return "namedec";
case Icode_PROPDEC: return "propdec";
case Icode_ELEMDEC: return "elemdec";
case Icode_VARDEC: return "vardec";
case Icode_SCOPE: return "scope";
case Icode_TYPEOFNAME: return "typeofname";
case Icode_GETPROTO: return "getproto";
case Icode_GETPARENT: return "getparent";
case Icode_GETSCOPEPARENT: return "getscopeparent";
case Icode_SETPROTO: return "setproto";
case Icode_SETPARENT: return "setparent";
case Icode_CLOSURE: return "closure";
case Icode_CALLSPECIAL: return "callspecial";
case Icode_RETUNDEF: return "retundef";
case Icode_CATCH: return "catch";
case Icode_GOSUB: return "gosub";
case Icode_RETSUB: return "retsub";
case Icode_LINE: return "line";
case Icode_SHORTNUMBER: return "shortnumber";
case Icode_INTNUMBER: return "intnumber";
case Icode_END: return "end";
}
}
return "<UNKNOWN ICODE: "+icode+">";
}
return "";
}
private static void dumpICode(InterpreterData idata)
{
if (Token.printICode) {
int iCodeLength = idata.itsICodeTop;
byte iCode[] = idata.itsICode;
String[] strings = idata.itsStringTable;
PrintStream out = System.out;
out.println("ICode dump, for " + idata.itsName
+ ", length = " + iCodeLength);
out.println("MaxStack = " + idata.itsMaxStack);
for (int pc = 0; pc < iCodeLength; ) {
out.flush();
out.print(" [" + pc + "] ");
int token = iCode[pc] & 0xff;
String tname = icodeToName(token);
int old_pc = pc;
++pc;
int icodeLength = icodeTokenLength(token);
switch (token) {
default:
if (icodeLength != 1) Context.codeBug();
out.println(tname);
break;
case Icode_GOSUB :
case Token.GOTO :
case Token.IFEQ :
case Token.IFNE : {
int newPC = getTarget(iCode, pc);
out.println(tname + " " + newPC);
pc += 2;
break;
}
case Icode_RETSUB :
case Token.ENUMINIT :
case Token.ENUMNEXT :
case Icode_VARINC :
case Icode_VARDEC :
case Token.GETVAR :
case Token.SETVAR :
case Token.NEWTEMP :
case Token.USETEMP : {
int slot = (iCode[pc] & 0xFF);
out.println(tname + " " + slot);
pc++;
break;
}
case Icode_CALLSPECIAL : {
int callType = iCode[pc] & 0xFF;
boolean isNew = (iCode[pc + 1] != 0);
int line = getShort(iCode, pc+2);
int count = getIndex(iCode, pc + 4);
out.println(tname+" "+callType+" "+isNew
+" "+count+" "+line);
pc += 8;
break;
}
case Token.REGEXP : {
int i = getIndex(iCode, pc);
Object regexp = idata.itsRegExpLiterals[i];
out.println(tname + " " + regexp);
pc += 2;
break;
}
case Icode_CLOSURE : {
int i = getIndex(iCode, pc);
InterpreterData data2 = idata.itsNestedFunctions[i];
out.println(tname + " " + data2);
pc += 2;
break;
}
case Token.NEW :
case Token.CALL : {
int count = getIndex(iCode, pc + 2);
String name = strings[getIndex(iCode, pc)];
out.println(tname+' '+count+" \""+name+'"');
pc += 4;
break;
}
case Icode_SHORTNUMBER : {
int value = getShort(iCode, pc);
out.println(tname + " " + value);
pc += 2;
break;
}
case Icode_INTNUMBER : {
int value = getInt(iCode, pc);
out.println(tname + " " + value);
pc += 4;
break;
}
case Token.NUMBER : {
int index = getIndex(iCode, pc);
double value = idata.itsDoubleTable[index];
out.println(tname + " " + value);
pc += 2;
break;
}
case Icode_TYPEOFNAME :
case Token.GETBASE :
case Token.BINDNAME :
case Token.SETNAME :
case Token.NAME :
case Icode_NAMEINC :
case Icode_NAMEDEC :
case Token.STRING : {
String str = strings[getIndex(iCode, pc)];
out.println(tname + " \"" + str + '"');
pc += 2;
break;
}
case Icode_LINE : {
int line = getShort(iCode, pc);
out.println(tname + " : " + line);
pc += 2;
break;
}
}
if (old_pc + icodeLength != pc) Context.codeBug();
}
int[] table = idata.itsExceptionTable;
if (table != null) {
out.println("Exception handlers: "
+table.length / EXCEPTION_SLOT_SIZE);
for (int i = 0; i != table.length;
i += EXCEPTION_SLOT_SIZE)
{
int tryStart = table[i + EXCEPTION_TRY_START_SLOT];
int tryEnd = table[i + EXCEPTION_TRY_END_SLOT];
int catchStart = table[i + EXCEPTION_CATCH_SLOT];
int finallyStart = table[i + EXCEPTION_FINALLY_SLOT];
int withDepth = table[i + EXCEPTION_WITH_DEPTH_SLOT];
out.println(" "+tryStart+"\t "+tryEnd+"\t "
+catchStart+"\t "+finallyStart
+"\t "+withDepth);
}
}
out.flush();
}
}
private static int icodeTokenLength(int icodeToken) {
switch (icodeToken) {
case Icode_SCOPE :
case Icode_GETPROTO :
case Icode_GETPARENT :
case Icode_GETSCOPEPARENT :
case Icode_SETPROTO :
case Icode_SETPARENT :
case Token.DELPROP :
case Token.TYPEOF :
case Token.NEWSCOPE :
case Token.ENTERWITH :
case Token.LEAVEWITH :
case Token.RETURN :
case Token.GETTHIS :
case Token.SETELEM :
case Token.GETELEM :
case Token.SETPROP :
case Token.GETPROP :
case Icode_PROPINC :
case Icode_PROPDEC :
case Icode_ELEMINC :
case Icode_ELEMDEC :
case Token.BITNOT :
case Token.BITAND :
case Token.BITOR :
case Token.BITXOR :
case Token.LSH :
case Token.RSH :
case Token.URSH :
case Token.NOT :
case Token.POS :
case Token.NEG :
case Token.SUB :
case Token.MUL :
case Token.DIV :
case Token.MOD :
case Token.ADD :
case Token.POPV :
case Token.POP :
case Icode_DUP :
case Token.LT :
case Token.GT :
case Token.LE :
case Token.GE :
case Token.IN :
case Token.INSTANCEOF :
case Token.EQ :
case Token.NE :
case Token.SHEQ :
case Token.SHNE :
case Token.ZERO :
case Token.ONE :
case Token.NULL :
case Token.THIS :
case Token.THISFN :
case Token.FALSE :
case Token.TRUE :
case Token.UNDEFINED :
case Icode_CATCH:
case Icode_RETUNDEF:
case Icode_END:
return 1;
case Token.THROW :
// source line
return 1 + 2;
case Icode_GOSUB :
case Token.GOTO :
case Token.IFEQ :
case Token.IFNE :
// target pc offset
return 1 + 2;
case Icode_RETSUB :
case Token.ENUMINIT :
case Token.ENUMNEXT :
case Icode_VARINC :
case Icode_VARDEC :
case Token.GETVAR :
case Token.SETVAR :
case Token.NEWTEMP :
case Token.USETEMP :
// slot index
return 1 + 1;
case Icode_CALLSPECIAL :
// call type
// is new
// line number
// arg count
return 1 + 1 + 1 + 2 + 2;
case Token.REGEXP :
// regexp index
return 1 + 2;
case Icode_CLOSURE :
// index of closure master copy
return 1 + 2;
case Token.NEW :
case Token.CALL :
// name string index
// arg count
return 1 + 2 + 2;
case Icode_SHORTNUMBER :
// short number
return 1 + 2;
case Icode_INTNUMBER :
// int number
return 1 + 4;
case Token.NUMBER :
// index of double number
return 1 + 2;
case Icode_TYPEOFNAME :
case Token.GETBASE :
case Token.BINDNAME :
case Token.SETNAME :
case Token.NAME :
case Icode_NAMEINC :
case Icode_NAMEDEC :
case Token.STRING :
// string index
return 1 + 2;
case Icode_LINE :
// line number
return 1 + 2;
default:
Context.codeBug(); // Bad icodeToken
return 0;
}
}
static int[] getLineNumbers(InterpreterData data) {
UintMap presentLines = new UintMap();
int iCodeLength = data.itsICodeTop;
byte[] iCode = data.itsICode;
for (int pc = 0; pc != iCodeLength;) {
int icodeToken = iCode[pc] & 0xff;
int icodeLength = icodeTokenLength(icodeToken);
if (icodeToken == Icode_LINE) {
if (icodeLength != 3) Context.codeBug();
int line = getShort(iCode, pc + 1);
presentLines.put(line, 0);
}
pc += icodeLength;
}
return presentLines.getKeys();
}
static Object getEncodedSource(InterpreterData idata)
{
if (idata.encodedSource == null) {
return null;
}
return idata.encodedSource.substring(idata.encodedSourceStart,
idata.encodedSourceEnd);
}
private static InterpretedFunction createFunction(Context cx,
Scriptable scope,
InterpreterData idata,
boolean fromEvalCode)
{
InterpretedFunction fn = new InterpretedFunction(idata);
if (cx.hasCompileFunctionsWithDynamicScope()) {
// Nested functions are not affected by the dynamic scope flag
// as dynamic scope is already a parent of their scope
// Functions defined under the with statement also immune to
// this setup, in which case dynamic scope is ignored in favor
// of with object.
if (!(scope instanceof NativeCall
|| scope instanceof NativeWith))
{
fn.itsUseDynamicScope = true;
}
}
ScriptRuntime.initFunction(cx, scope, fn, idata.itsFunctionType,
fromEvalCode);
return fn;
}
static Object interpret(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args, double[] argsDbl,
int argShift, int argCount,
NativeFunction fnOrScript,
InterpreterData idata)
throws JavaScriptException
{
if (cx.interpreterSecurityDomain != idata.securityDomain) {
return execWithNewDomain(cx, scope, thisObj,
args, argsDbl, argShift, argCount,
fnOrScript, idata);
}
final Object DBL_MRK = Interpreter.DBL_MRK;
final Scriptable undefined = Undefined.instance;
final int VAR_SHFT = 0;
final int maxVars = idata.itsMaxVars;
final int LOCAL_SHFT = VAR_SHFT + maxVars;
final int STACK_SHFT = LOCAL_SHFT + idata.itsMaxLocals;
// stack[VAR_SHFT <= i < LOCAL_SHFT]: variables
// stack[LOCAL_SHFT <= i < TRY_STACK_SHFT]: used for newtemp/usetemp
// stack[STACK_SHFT <= i < STACK_SHFT + idata.itsMaxStack]: stack data
// sDbl[i]: if stack[i] is DBL_MRK, sDbl[i] holds the number value
int maxFrameArray = idata.itsMaxFrameArray;
if (maxFrameArray != STACK_SHFT + idata.itsMaxStack)
Context.codeBug();
Object[] stack = new Object[maxFrameArray];
double[] sDbl = new double[maxFrameArray];
int stackTop = STACK_SHFT - 1;
int withDepth = 0;
int definedArgs = fnOrScript.argCount;
if (definedArgs > argCount) { definedArgs = argCount; }
for (int i = 0; i != definedArgs; ++i) {
Object arg = args[argShift + i];
stack[VAR_SHFT + i] = arg;
if (arg == DBL_MRK) {
sDbl[VAR_SHFT + i] = argsDbl[argShift + i];
}
}
for (int i = definedArgs; i != maxVars; ++i) {
stack[VAR_SHFT + i] = undefined;
}
DebugFrame debuggerFrame = null;
if (cx.debugger != null) {
debuggerFrame = cx.debugger.getFrame(cx, idata);
}
if (idata.itsFunctionType != 0) {
InterpretedFunction f = (InterpretedFunction)fnOrScript;
if (!f.itsUseDynamicScope) {
scope = fnOrScript.getParentScope();
}
if (idata.itsCheckThis) {
thisObj = ScriptRuntime.getThis(thisObj);
}
if (idata.itsNeedsActivation) {
if (argsDbl != null) {
args = getArgsArray(args, argsDbl, argShift, argCount);
argShift = 0;
argsDbl = null;
}
scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript,
thisObj, args);
}
} else {
scope = ScriptRuntime.initScript(cx, scope, fnOrScript, thisObj,
idata.itsFromEvalCode);
}
if (idata.itsNestedFunctions != null) {
if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation)
Context.codeBug();
for (int i = 0; i < idata.itsNestedFunctions.length; i++) {
InterpreterData fdata = idata.itsNestedFunctions[i];
if (fdata.itsFunctionType == FunctionNode.FUNCTION_STATEMENT) {
createFunction(cx, scope, fdata, idata.itsFromEvalCode);
}
}
}
boolean useActivationVars = false;
if (debuggerFrame != null) {
if (argsDbl != null) {
args = getArgsArray(args, argsDbl, argShift, argCount);
argShift = 0;
argsDbl = null;
}
if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation) {
useActivationVars = true;
scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript,
thisObj, args);
}
debuggerFrame.onEnter(cx, scope, thisObj, args);
}
String savedSourceFile = cx.interpreterSourceFile;
cx.interpreterSourceFile = idata.itsSourceFile;
Object result = undefined;
// If javaException != null on exit, it will be throw instead of
// normal return
Throwable javaException = null;
int exceptionPC = -1;
byte[] iCode = idata.itsICode;
String[] strings = idata.itsStringTable;
int pc = 0;
int pcPrevBranch = pc;
final int instructionThreshold = cx.instructionThreshold;
// During function call this will be set to -1 so catch can properly
// adjust it
int instructionCount = cx.instructionCount;
// arbitrary number to add to instructionCount when calling
// other functions
final int INVOCATION_COST = 100;
Loop: for (;;) {
try {
switch (iCode[pc] & 0xff) {
// Back indent to ease imlementation reading
case Icode_CATCH: {
// The following code should be executed inside try/catch inside main
// loop, not in the loop catch block itself to deal withnexceptions
// from observeInstructionCount. A special bytecode is used only to
// simplify logic.
if (javaException == null) Context.codeBug();
int pcNew = -1;
boolean doCatch = false;
int handlerOffset = getExceptionHandler(idata.itsExceptionTable,
exceptionPC);
if (handlerOffset >= 0) {
final int SCRIPT_CAN_CATCH = 0, ONLY_FINALLY = 1, OTHER = 2;
int exType;
if (javaException instanceof JavaScriptException) {
exType = SCRIPT_CAN_CATCH;
} else if (javaException instanceof EcmaError) {
// an offical ECMA error object,
exType = SCRIPT_CAN_CATCH;
} else if (javaException instanceof WrappedException) {
exType = SCRIPT_CAN_CATCH;
} else if (javaException instanceof RuntimeException) {
exType = ONLY_FINALLY;
} else {
// Error instance
exType = OTHER;
}
if (exType != OTHER) {
// Do not allow for JS to interfere with Error instances
// (exType == OTHER), as they can be used to terminate
// long running script
if (exType == SCRIPT_CAN_CATCH) {
// Allow JS to catch only JavaScriptException and
// EcmaError
pcNew = idata.itsExceptionTable[handlerOffset
+ EXCEPTION_CATCH_SLOT];
if (pcNew >= 0) {
// Has catch block
doCatch = true;
}
}
if (pcNew < 0) {
pcNew = idata.itsExceptionTable[handlerOffset
+ EXCEPTION_FINALLY_SLOT];
}
}
}
if (debuggerFrame != null && !(javaException instanceof Error)) {
debuggerFrame.onExceptionThrown(cx, javaException);
}
if (pcNew < 0) {
break Loop;
}
// We caught an exception
// restore scope at try point
int tryWithDepth = idata.itsExceptionTable[
handlerOffset + EXCEPTION_WITH_DEPTH_SLOT];
while (tryWithDepth != withDepth) {
if (scope == null) Context.codeBug();
scope = ScriptRuntime.leaveWith(scope);
--withDepth;
}
// make stack to contain single exception object
stackTop = STACK_SHFT;
if (doCatch) {
stack[stackTop] = ScriptRuntime.getCatchObject(cx, scope,
javaException);
} else {
// Call finally handler with javaException on stack top to
// distinguish from normal invocation through GOSUB
// which would contain DBL_MRK on the stack
stack[stackTop] = javaException;
}
// clear exception
javaException = null;
// Notify instruction observer if necessary
// and point pc and pcPrevBranch to start of catch/finally block
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
// Note: this can throw Error
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = pcNew;
continue Loop;
}
case Token.THROW: {
Object value = stack[stackTop];
if (value == DBL_MRK) value = doubleWrap(sDbl[stackTop]);
--stackTop;
int sourceLine = getShort(iCode, pc + 1);
javaException = new JavaScriptException(value, idata.itsSourceFile,
sourceLine);
exceptionPC = pc;
if (instructionThreshold != 0) {
instructionCount += pc + 1 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getJavaCatchPC(iCode);
continue Loop;
}
case Token.GE : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && rDbl <= lDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LE(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.LE : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && lDbl <= rDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LE(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.GT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && rDbl < lDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LT(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.LT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && lDbl < rDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LT(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.IN : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
boolean valBln = ScriptRuntime.in(lhs, rhs, scope);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.INSTANCEOF : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
boolean valBln = ScriptRuntime.instanceOf(lhs, rhs, scope);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.EQ : {
--stackTop;
boolean valBln = do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.NE : {
--stackTop;
boolean valBln = !do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.SHEQ : {
--stackTop;
boolean valBln = do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.SHNE : {
--stackTop;
boolean valBln = !do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.IFNE : {
boolean valBln = stack_boolean(stack, sDbl, stackTop);
--stackTop;
if (!valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue Loop;
}
pc += 2;
break;
}
case Token.IFEQ : {
boolean valBln = stack_boolean(stack, sDbl, stackTop);
--stackTop;
if (valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue Loop;
}
pc += 2;
break;
}
case Token.GOTO :
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue Loop;
case Icode_GOSUB :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = pc + 3;
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1); continue Loop;
case Icode_RETSUB : {
int slot = (iCode[pc + 1] & 0xFF);
if (instructionThreshold != 0) {
instructionCount += pc + 2 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
int newPC;
Object value = stack[LOCAL_SHFT + slot];
if (value != DBL_MRK) {
// Invocation from exception handler, restore object to rethrow
javaException = (Throwable)value;
exceptionPC = pc;
newPC = getJavaCatchPC(iCode);
} else {
// Normal return from GOSUB
newPC = (int)sDbl[LOCAL_SHFT + slot];
}
pcPrevBranch = pc = newPC;
continue Loop;
}
case Token.POP :
stack[stackTop] = null;
stackTop--;
break;
case Icode_DUP :
stack[stackTop + 1] = stack[stackTop];
sDbl[stackTop + 1] = sDbl[stackTop];
stackTop++;
break;
case Token.POPV :
result = stack[stackTop];
if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]);
stack[stackTop] = null;
--stackTop;
break;
case Token.RETURN :
result = stack[stackTop];
if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]);
--stackTop;
break Loop;
case Icode_RETUNDEF :
result = undefined;
break Loop;
case Icode_END:
break Loop;
case Token.BITNOT : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ~rIntValue;
break;
}
case Token.BITAND : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue & rIntValue;
break;
}
case Token.BITOR : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue | rIntValue;
break;
}
case Token.BITXOR : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue ^ rIntValue;
break;
}
case Token.LSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue << rIntValue;
break;
}
case Token.RSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue >> rIntValue;
break;
}
case Token.URSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop) & 0x1F;
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue;
break;
}
case Token.ADD :
--stackTop;
do_add(stack, sDbl, stackTop);
break;
case Token.SUB : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl - rDbl;
break;
}
case Token.NEG : {
double rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = -rDbl;
break;
}
case Token.POS : {
double rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = rDbl;
break;
}
case Token.MUL : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl * rDbl;
break;
}
case Token.DIV : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
// Detect the divide by zero or let Java do it ?
sDbl[stackTop] = lDbl / rDbl;
break;
}
case Token.MOD : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl % rDbl;
break;
}
case Token.NOT : {
stack[stackTop] = stack_boolean(stack, sDbl, stackTop)
? Boolean.FALSE : Boolean.TRUE;
break;
}
case Token.BINDNAME : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.bind(scope, name);
pc += 2;
break;
}
case Token.GETBASE : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.getBase(scope, name);
pc += 2;
break;
}
case Token.SETNAME : {
String name = strings[getIndex(iCode, pc + 1)];
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
// what about class cast exception here for lhs?
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.setName(lhs, rhs, scope, name);
pc += 2;
break;
}
case Token.DELPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.delete(cx, scope, lhs, rhs);
break;
}
case Token.GETPROP : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getProp(lhs, name, scope);
break;
}
case Token.SETPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setProp(lhs, name, rhs, scope);
break;
}
case Token.GETELEM :
do_getElem(cx, stack, sDbl, stackTop, scope);
--stackTop;
break;
case Token.SETELEM :
do_setElem(cx, stack, sDbl, stackTop, scope);
stackTop -= 2;
break;
case Icode_PROPINC : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postIncrement(lhs, name, scope);
break;
}
case Icode_PROPDEC : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postDecrement(lhs, name, scope);
break;
}
case Icode_ELEMINC : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postIncrementElem(lhs, rhs, scope);
break;
}
case Icode_ELEMDEC : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postDecrementElem(lhs, rhs, scope);
break;
}
case Token.GETTHIS : {
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.getThis(lhs);
break;
}
case Token.NEWTEMP : {
int slot = (iCode[++pc] & 0xFF);
stack[LOCAL_SHFT + slot] = stack[stackTop];
sDbl[LOCAL_SHFT + slot] = sDbl[stackTop];
break;
}
case Token.USETEMP : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
stack[stackTop] = stack[LOCAL_SHFT + slot];
sDbl[stackTop] = sDbl[LOCAL_SHFT + slot];
break;
}
case Icode_CALLSPECIAL : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int callType = iCode[pc + 1] & 0xFF;
boolean isNew = (iCode[pc + 2] != 0);
int sourceLine = getShort(iCode, pc + 3);
int count = getIndex(iCode, pc + 5);
stackTop -= count;
Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 1, count);
Object functionThis;
if (isNew) {
functionThis = null;
} else {
functionThis = stack[stackTop];
if (functionThis == DBL_MRK) {
functionThis = doubleWrap(sDbl[stackTop]);
}
--stackTop;
}
Object function = stack[stackTop];
if (function == DBL_MRK) function = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.callSpecial(
cx, function, isNew, functionThis, outArgs,
scope, thisObj, callType,
idata.itsSourceFile, sourceLine);
pc += 6;
instructionCount = cx.instructionCount;
break;
}
case Token.CALL : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
- cx.instructionCount = instructionCount;
int count = getIndex(iCode, pc + 3);
stackTop -= count;
int calleeArgShft = stackTop + 1;
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
Scriptable calleeScope = scope;
if (idata.itsNeedsActivation) {
calleeScope = ScriptableObject.getTopLevelScope(scope);
}
Scriptable calleeThis;
if (rhs instanceof Scriptable || rhs == null) {
calleeThis = (Scriptable)rhs;
} else {
calleeThis = ScriptRuntime.toObject(cx, calleeScope, rhs);
}
if (lhs instanceof InterpretedFunction) {
// Inlining of InterpretedFunction.call not to create
// argument array
InterpretedFunction f = (InterpretedFunction)lhs;
stack[stackTop] = interpret(cx, calleeScope, calleeThis,
stack, sDbl, calleeArgShft, count,
f, f.itsData);
} else if (lhs instanceof Function) {
Function f = (Function)lhs;
Object[] outArgs = getArgsArray(stack, sDbl, calleeArgShft, count);
stack[stackTop] = f.call(cx, calleeScope, calleeThis, outArgs);
} else {
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
else if (lhs == undefined) {
// special code for better error message for call
// to undefined
lhs = strings[getIndex(iCode, pc + 1)];
if (lhs == null) lhs = undefined;
}
throw NativeGlobal.typeError1
("msg.isnt.function", ScriptRuntime.toString(lhs), calleeScope);
}
pc += 4;
instructionCount = cx.instructionCount;
break;
}
case Token.NEW : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int count = getIndex(iCode, pc + 3);
stackTop -= count;
int calleeArgShft = stackTop + 1;
Object lhs = stack[stackTop];
if (lhs instanceof InterpretedFunction) {
// Inlining of InterpretedFunction.construct not to create
// argument array
InterpretedFunction f = (InterpretedFunction)lhs;
Scriptable newInstance = f.createObject(cx, scope);
Object callResult = interpret(cx, scope, newInstance,
stack, sDbl, calleeArgShft, count,
f, f.itsData);
if (callResult instanceof Scriptable && callResult != undefined) {
stack[stackTop] = callResult;
} else {
stack[stackTop] = newInstance;
}
} else if (lhs instanceof Function) {
Function f = (Function)lhs;
Object[] outArgs = getArgsArray(stack, sDbl, calleeArgShft, count);
stack[stackTop] = f.construct(cx, scope, outArgs);
} else {
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
else if (lhs == undefined) {
// special code for better error message for call
// to undefined
lhs = strings[getIndex(iCode, pc + 1)];
if (lhs == null) lhs = undefined;
}
throw NativeGlobal.typeError1
("msg.isnt.function", ScriptRuntime.toString(lhs), scope);
}
pc += 4; instructionCount = cx.instructionCount;
break;
}
case Token.TYPEOF : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.typeof(lhs);
break;
}
case Icode_TYPEOFNAME : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.typeofName(scope, name);
pc += 2;
break;
}
case Token.STRING :
stack[++stackTop] = strings[getIndex(iCode, pc + 1)];
pc += 2;
break;
case Icode_SHORTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getShort(iCode, pc + 1);
pc += 2;
break;
case Icode_INTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getInt(iCode, pc + 1);
pc += 4;
break;
case Token.NUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = idata.itsDoubleTable[getIndex(iCode, pc + 1)];
pc += 2;
break;
case Token.NAME : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.name(scope, name);
pc += 2;
break;
}
case Icode_NAMEINC : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.postIncrement(scope, name);
pc += 2;
break;
}
case Icode_NAMEDEC : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.postDecrement(scope, name);
pc += 2;
break;
}
case Token.SETVAR : {
int slot = (iCode[++pc] & 0xFF);
if (!useActivationVars) {
stack[VAR_SHFT + slot] = stack[stackTop];
sDbl[VAR_SHFT + slot] = sDbl[stackTop];
} else {
Object val = stack[stackTop];
if (val == DBL_MRK) val = doubleWrap(sDbl[stackTop]);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case Token.GETVAR : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
} else {
stack[stackTop] = activationGet(fnOrScript, scope, slot);
}
break;
}
case Icode_VARINC : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) + 1.0;
} else {
Object val = activationGet(fnOrScript, scope, slot);
stack[stackTop] = val;
val = doubleWrap(ScriptRuntime.toNumber(val) + 1.0);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case Icode_VARDEC : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) - 1.0;
} else {
Object val = activationGet(fnOrScript, scope, slot);
stack[stackTop] = val;
val = doubleWrap(ScriptRuntime.toNumber(val) - 1.0);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case Token.ZERO :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 0;
break;
case Token.ONE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 1;
break;
case Token.NULL :
stack[++stackTop] = null;
break;
case Token.THIS :
stack[++stackTop] = thisObj;
break;
case Token.THISFN :
stack[++stackTop] = fnOrScript;
break;
case Token.FALSE :
stack[++stackTop] = Boolean.FALSE;
break;
case Token.TRUE :
stack[++stackTop] = Boolean.TRUE;
break;
case Token.UNDEFINED :
stack[++stackTop] = Undefined.instance;
break;
case Token.ENTERWITH : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
scope = ScriptRuntime.enterWith(lhs, scope);
++withDepth;
break;
}
case Token.LEAVEWITH :
scope = ScriptRuntime.leaveWith(scope);
--withDepth;
break;
case Token.NEWSCOPE :
stack[++stackTop] = ScriptRuntime.newScope();
break;
case Token.ENUMINIT : {
int slot = (iCode[++pc] & 0xFF);
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
stack[LOCAL_SHFT + slot] = ScriptRuntime.initEnum(lhs, scope);
break;
}
case Token.ENUMNEXT : {
int slot = (iCode[++pc] & 0xFF);
Object val = stack[LOCAL_SHFT + slot];
++stackTop;
stack[stackTop] = ScriptRuntime.nextEnum(val);
break;
}
case Icode_GETPROTO : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getProto(lhs, scope);
break;
}
case Icode_GETPARENT : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs);
break;
}
case Icode_GETSCOPEPARENT : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs, scope);
break;
}
case Icode_SETPROTO : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setProto(lhs, rhs, scope);
break;
}
case Icode_SETPARENT : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setParent(lhs, rhs, scope);
break;
}
case Icode_SCOPE :
stack[++stackTop] = scope;
break;
case Icode_CLOSURE : {
int i = getIndex(iCode, pc + 1);
InterpreterData closureData = idata.itsNestedFunctions[i];
stack[++stackTop] = createFunction(cx, scope, closureData,
idata.itsFromEvalCode);
pc += 2;
break;
}
case Token.REGEXP : {
int i = getIndex(iCode, pc + 1);
stack[++stackTop] = idata.itsRegExpLiterals[i];
pc += 2;
break;
}
case Icode_LINE : {
int line = getShort(iCode, pc + 1);
cx.interpreterLine = line;
if (debuggerFrame != null) {
debuggerFrame.onLineChange(cx, line);
}
pc += 2;
break;
}
default : {
dumpICode(idata);
throw new RuntimeException
("Unknown icode : "+(iCode[pc] & 0xff)+" @ pc : "+pc);
}
// end of interpreter switch
}
pc++;
}
catch (Throwable ex) {
if (instructionThreshold != 0) {
if (instructionCount < 0) {
// throw during function call
instructionCount = cx.instructionCount;
} else {
// throw during any other operation
instructionCount += pc - pcPrevBranch;
cx.instructionCount = instructionCount;
}
}
javaException = ex;
exceptionPC = pc;
pc = getJavaCatchPC(iCode);
continue Loop;
}
}
cx.interpreterSourceFile = savedSourceFile;
if (debuggerFrame != null) {
if (javaException != null) {
debuggerFrame.onExit(cx, true, javaException);
} else {
debuggerFrame.onExit(cx, false, result);
}
}
if (idata.itsNeedsActivation) {
ScriptRuntime.popActivation(cx);
}
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
cx.instructionCount = instructionCount;
}
if (javaException != null) {
if (javaException instanceof JavaScriptException) {
throw (JavaScriptException)javaException;
} else if (javaException instanceof RuntimeException) {
throw (RuntimeException)javaException;
} else {
// Must be instance of Error or code bug
throw (Error)javaException;
}
}
return result;
}
private static Object doubleWrap(double x)
{
return new Double(x);
}
private static int stack_int32(Object[] stack, double[] stackDbl, int i) {
Object x = stack[i];
return (x != DBL_MRK)
? ScriptRuntime.toInt32(x)
: ScriptRuntime.toInt32(stackDbl[i]);
}
private static double stack_double(Object[] stack, double[] stackDbl,
int i)
{
Object x = stack[i];
return (x != DBL_MRK) ? ScriptRuntime.toNumber(x) : stackDbl[i];
}
private static boolean stack_boolean(Object[] stack, double[] stackDbl,
int i)
{
Object x = stack[i];
if (x == DBL_MRK) {
double d = stackDbl[i];
return d == d && d != 0.0;
} else if (x instanceof Boolean) {
return ((Boolean)x).booleanValue();
} else if (x == null || x == Undefined.instance) {
return false;
} else if (x instanceof Number) {
double d = ((Number)x).doubleValue();
return (d == d && d != 0.0);
} else {
return ScriptRuntime.toBoolean(x);
}
}
private static void do_add(Object[] stack, double[] stackDbl, int stackTop)
{
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
if (rhs == DBL_MRK) {
double rDbl = stackDbl[stackTop + 1];
if (lhs == DBL_MRK) {
stackDbl[stackTop] += rDbl;
} else {
do_add(lhs, rDbl, stack, stackDbl, stackTop, true);
}
} else if (lhs == DBL_MRK) {
do_add(rhs, stackDbl[stackTop], stack, stackDbl, stackTop, false);
} else {
if (lhs instanceof Scriptable)
lhs = ((Scriptable) lhs).getDefaultValue(null);
if (rhs instanceof Scriptable)
rhs = ((Scriptable) rhs).getDefaultValue(null);
if (lhs instanceof String) {
String lstr = (String)lhs;
String rstr = ScriptRuntime.toString(rhs);
stack[stackTop] = lstr.concat(rstr);
} else if (rhs instanceof String) {
String lstr = ScriptRuntime.toString(lhs);
String rstr = (String)rhs;
stack[stackTop] = lstr.concat(rstr);
} else {
double lDbl = (lhs instanceof Number)
? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs);
double rDbl = (rhs instanceof Number)
? ((Number)rhs).doubleValue() : ScriptRuntime.toNumber(rhs);
stack[stackTop] = DBL_MRK;
stackDbl[stackTop] = lDbl + rDbl;
}
}
}
// x + y when x is Number
private static void do_add
(Object lhs, double rDbl,
Object[] stack, double[] stackDbl, int stackTop,
boolean left_right_order)
{
if (lhs instanceof Scriptable) {
if (lhs == Undefined.instance) {
lhs = ScriptRuntime.NaNobj;
} else {
lhs = ((Scriptable)lhs).getDefaultValue(null);
}
}
if (lhs instanceof String) {
String lstr = (String)lhs;
String rstr = ScriptRuntime.toString(rDbl);
if (left_right_order) {
stack[stackTop] = lstr.concat(rstr);
} else {
stack[stackTop] = rstr.concat(lstr);
}
} else {
double lDbl = (lhs instanceof Number)
? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs);
stack[stackTop] = DBL_MRK;
stackDbl[stackTop] = lDbl + rDbl;
}
}
private static boolean do_eq(Object[] stack, double[] stackDbl,
int stackTop)
{
boolean result;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
if (rhs == DBL_MRK) {
if (lhs == DBL_MRK) {
result = (stackDbl[stackTop] == stackDbl[stackTop + 1]);
} else {
result = do_eq(stackDbl[stackTop + 1], lhs);
}
} else {
if (lhs == DBL_MRK) {
result = do_eq(stackDbl[stackTop], rhs);
} else {
result = ScriptRuntime.eq(lhs, rhs);
}
}
return result;
}
// Optimized version of ScriptRuntime.eq if x is a Number
private static boolean do_eq(double x, Object y)
{
for (;;) {
if (y instanceof Number) {
return x == ((Number) y).doubleValue();
}
if (y instanceof String) {
return x == ScriptRuntime.toNumber((String)y);
}
if (y instanceof Boolean) {
return x == (((Boolean)y).booleanValue() ? 1 : 0);
}
if (y instanceof Scriptable) {
if (y == Undefined.instance) { return false; }
y = ScriptRuntime.toPrimitive(y);
continue;
}
return false;
}
}
private static boolean do_sheq(Object[] stack, double[] stackDbl,
int stackTop)
{
boolean result;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
if (rhs == DBL_MRK) {
double rDbl = stackDbl[stackTop + 1];
if (lhs == DBL_MRK) {
result = (stackDbl[stackTop] == rDbl);
} else {
result = (lhs instanceof Number);
if (result) {
result = (((Number)lhs).doubleValue() == rDbl);
}
}
} else if (rhs instanceof Number) {
double rDbl = ((Number)rhs).doubleValue();
if (lhs == DBL_MRK) {
result = (stackDbl[stackTop] == rDbl);
} else {
result = (lhs instanceof Number);
if (result) {
result = (((Number)lhs).doubleValue() == rDbl);
}
}
} else {
result = ScriptRuntime.shallowEq(lhs, rhs);
}
return result;
}
private static void do_getElem(Context cx,
Object[] stack, double[] stackDbl,
int stackTop, Scriptable scope)
{
Object lhs = stack[stackTop - 1];
if (lhs == DBL_MRK) lhs = doubleWrap(stackDbl[stackTop - 1]);
Object result;
Object id = stack[stackTop];
if (id != DBL_MRK) {
result = ScriptRuntime.getElem(lhs, id, scope);
} else {
double val = stackDbl[stackTop];
if (lhs == null || lhs == Undefined.instance) {
throw NativeGlobal.undefReadError(
lhs, ScriptRuntime.toString(val), scope);
}
Scriptable obj = (lhs instanceof Scriptable)
? (Scriptable)lhs
: ScriptRuntime.toObject(cx, scope, lhs);
int index = (int)val;
if (index == val) {
result = ScriptRuntime.getElem(obj, index);
} else {
String s = ScriptRuntime.toString(val);
result = ScriptRuntime.getStrIdElem(obj, s);
}
}
stack[stackTop - 1] = result;
}
private static void do_setElem(Context cx,
Object[] stack, double[] stackDbl,
int stackTop, Scriptable scope)
{
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(stackDbl[stackTop]);
Object lhs = stack[stackTop - 2];
if (lhs == DBL_MRK) lhs = doubleWrap(stackDbl[stackTop - 2]);
Object result;
Object id = stack[stackTop - 1];
if (id != DBL_MRK) {
result = ScriptRuntime.setElem(lhs, id, rhs, scope);
} else {
double val = stackDbl[stackTop - 1];
if (lhs == null || lhs == Undefined.instance) {
throw NativeGlobal.undefWriteError(
lhs, ScriptRuntime.toString(val), rhs, scope);
}
Scriptable obj = (lhs instanceof Scriptable)
? (Scriptable)lhs
: ScriptRuntime.toObject(cx, scope, lhs);
int index = (int)val;
if (index == val) {
result = ScriptRuntime.setElem(obj, index, rhs);
} else {
String s = ScriptRuntime.toString(val);
result = ScriptRuntime.setStrIdElem(obj, s, rhs, scope);
}
}
stack[stackTop - 2] = result;
}
private static Object[] getArgsArray(Object[] stack, double[] sDbl,
int shift, int count)
{
if (count == 0) {
return ScriptRuntime.emptyArgs;
}
Object[] args = new Object[count];
for (int i = 0; i != count; ++i, ++shift) {
Object val = stack[shift];
if (val == DBL_MRK) val = doubleWrap(sDbl[shift]);
args[i] = val;
}
return args;
}
private static Object activationGet(NativeFunction f,
Scriptable activation, int slot)
{
String name = f.argNames[slot];
Object val = activation.get(name, activation);
// Activation parameter or var is permanent
if (val == Scriptable.NOT_FOUND) Context.codeBug();
return val;
}
private static void activationPut(NativeFunction f,
Scriptable activation, int slot,
Object value)
{
String name = f.argNames[slot];
activation.put(name, activation, value);
}
private static Object execWithNewDomain(Context cx, Scriptable scope,
final Scriptable thisObj,
final Object[] args,
final double[] argsDbl,
final int argShift,
final int argCount,
final NativeFunction fnOrScript,
final InterpreterData idata)
throws JavaScriptException
{
if (cx.interpreterSecurityDomain == idata.securityDomain)
Context.codeBug();
Script code = new Script() {
public Object exec(Context cx, Scriptable scope)
throws JavaScriptException
{
return interpret(cx, scope, thisObj,
args, argsDbl, argShift, argCount,
fnOrScript, idata);
}
};
Object savedDomain = cx.interpreterSecurityDomain;
cx.interpreterSecurityDomain = idata.securityDomain;
try {
return cx.getSecurityController().
execWithDomain(cx, scope, code, idata.securityDomain);
} finally {
cx.interpreterSecurityDomain = savedDomain;
}
}
private static int getJavaCatchPC(byte[] iCode)
{
int pc = iCode.length - 1;
if ((iCode[pc] & 0xFF) != Icode_CATCH) Context.codeBug();
return pc;
}
private boolean itsInFunctionFlag;
private InterpreterData itsData;
private ScriptOrFnNode scriptOrFn;
private int itsStackDepth = 0;
private int itsWithDepth = 0;
private int itsLineNumber = 0;
private LabelTable itsLabels = new LabelTable();
private int itsDoubleTableTop;
private ObjToIntMap itsStrings = new ObjToIntMap(20);
private String lastAddString;
private int itsExceptionTableTop = 0;
// 5 = space for try start/end, catch begin, finally begin and with depth
private static final int EXCEPTION_SLOT_SIZE = 5;
private static final int EXCEPTION_TRY_START_SLOT = 0;
private static final int EXCEPTION_TRY_END_SLOT = 1;
private static final int EXCEPTION_CATCH_SLOT = 2;
private static final int EXCEPTION_FINALLY_SLOT = 3;
private static final int EXCEPTION_WITH_DEPTH_SLOT = 4;
private static final Object DBL_MRK = new Object();
}
| true | true | static Object interpret(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args, double[] argsDbl,
int argShift, int argCount,
NativeFunction fnOrScript,
InterpreterData idata)
throws JavaScriptException
{
if (cx.interpreterSecurityDomain != idata.securityDomain) {
return execWithNewDomain(cx, scope, thisObj,
args, argsDbl, argShift, argCount,
fnOrScript, idata);
}
final Object DBL_MRK = Interpreter.DBL_MRK;
final Scriptable undefined = Undefined.instance;
final int VAR_SHFT = 0;
final int maxVars = idata.itsMaxVars;
final int LOCAL_SHFT = VAR_SHFT + maxVars;
final int STACK_SHFT = LOCAL_SHFT + idata.itsMaxLocals;
// stack[VAR_SHFT <= i < LOCAL_SHFT]: variables
// stack[LOCAL_SHFT <= i < TRY_STACK_SHFT]: used for newtemp/usetemp
// stack[STACK_SHFT <= i < STACK_SHFT + idata.itsMaxStack]: stack data
// sDbl[i]: if stack[i] is DBL_MRK, sDbl[i] holds the number value
int maxFrameArray = idata.itsMaxFrameArray;
if (maxFrameArray != STACK_SHFT + idata.itsMaxStack)
Context.codeBug();
Object[] stack = new Object[maxFrameArray];
double[] sDbl = new double[maxFrameArray];
int stackTop = STACK_SHFT - 1;
int withDepth = 0;
int definedArgs = fnOrScript.argCount;
if (definedArgs > argCount) { definedArgs = argCount; }
for (int i = 0; i != definedArgs; ++i) {
Object arg = args[argShift + i];
stack[VAR_SHFT + i] = arg;
if (arg == DBL_MRK) {
sDbl[VAR_SHFT + i] = argsDbl[argShift + i];
}
}
for (int i = definedArgs; i != maxVars; ++i) {
stack[VAR_SHFT + i] = undefined;
}
DebugFrame debuggerFrame = null;
if (cx.debugger != null) {
debuggerFrame = cx.debugger.getFrame(cx, idata);
}
if (idata.itsFunctionType != 0) {
InterpretedFunction f = (InterpretedFunction)fnOrScript;
if (!f.itsUseDynamicScope) {
scope = fnOrScript.getParentScope();
}
if (idata.itsCheckThis) {
thisObj = ScriptRuntime.getThis(thisObj);
}
if (idata.itsNeedsActivation) {
if (argsDbl != null) {
args = getArgsArray(args, argsDbl, argShift, argCount);
argShift = 0;
argsDbl = null;
}
scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript,
thisObj, args);
}
} else {
scope = ScriptRuntime.initScript(cx, scope, fnOrScript, thisObj,
idata.itsFromEvalCode);
}
if (idata.itsNestedFunctions != null) {
if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation)
Context.codeBug();
for (int i = 0; i < idata.itsNestedFunctions.length; i++) {
InterpreterData fdata = idata.itsNestedFunctions[i];
if (fdata.itsFunctionType == FunctionNode.FUNCTION_STATEMENT) {
createFunction(cx, scope, fdata, idata.itsFromEvalCode);
}
}
}
boolean useActivationVars = false;
if (debuggerFrame != null) {
if (argsDbl != null) {
args = getArgsArray(args, argsDbl, argShift, argCount);
argShift = 0;
argsDbl = null;
}
if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation) {
useActivationVars = true;
scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript,
thisObj, args);
}
debuggerFrame.onEnter(cx, scope, thisObj, args);
}
String savedSourceFile = cx.interpreterSourceFile;
cx.interpreterSourceFile = idata.itsSourceFile;
Object result = undefined;
// If javaException != null on exit, it will be throw instead of
// normal return
Throwable javaException = null;
int exceptionPC = -1;
byte[] iCode = idata.itsICode;
String[] strings = idata.itsStringTable;
int pc = 0;
int pcPrevBranch = pc;
final int instructionThreshold = cx.instructionThreshold;
// During function call this will be set to -1 so catch can properly
// adjust it
int instructionCount = cx.instructionCount;
// arbitrary number to add to instructionCount when calling
// other functions
final int INVOCATION_COST = 100;
Loop: for (;;) {
try {
switch (iCode[pc] & 0xff) {
// Back indent to ease imlementation reading
case Icode_CATCH: {
// The following code should be executed inside try/catch inside main
// loop, not in the loop catch block itself to deal withnexceptions
// from observeInstructionCount. A special bytecode is used only to
// simplify logic.
if (javaException == null) Context.codeBug();
int pcNew = -1;
boolean doCatch = false;
int handlerOffset = getExceptionHandler(idata.itsExceptionTable,
exceptionPC);
if (handlerOffset >= 0) {
final int SCRIPT_CAN_CATCH = 0, ONLY_FINALLY = 1, OTHER = 2;
int exType;
if (javaException instanceof JavaScriptException) {
exType = SCRIPT_CAN_CATCH;
} else if (javaException instanceof EcmaError) {
// an offical ECMA error object,
exType = SCRIPT_CAN_CATCH;
} else if (javaException instanceof WrappedException) {
exType = SCRIPT_CAN_CATCH;
} else if (javaException instanceof RuntimeException) {
exType = ONLY_FINALLY;
} else {
// Error instance
exType = OTHER;
}
if (exType != OTHER) {
// Do not allow for JS to interfere with Error instances
// (exType == OTHER), as they can be used to terminate
// long running script
if (exType == SCRIPT_CAN_CATCH) {
// Allow JS to catch only JavaScriptException and
// EcmaError
pcNew = idata.itsExceptionTable[handlerOffset
+ EXCEPTION_CATCH_SLOT];
if (pcNew >= 0) {
// Has catch block
doCatch = true;
}
}
if (pcNew < 0) {
pcNew = idata.itsExceptionTable[handlerOffset
+ EXCEPTION_FINALLY_SLOT];
}
}
}
if (debuggerFrame != null && !(javaException instanceof Error)) {
debuggerFrame.onExceptionThrown(cx, javaException);
}
if (pcNew < 0) {
break Loop;
}
// We caught an exception
// restore scope at try point
int tryWithDepth = idata.itsExceptionTable[
handlerOffset + EXCEPTION_WITH_DEPTH_SLOT];
while (tryWithDepth != withDepth) {
if (scope == null) Context.codeBug();
scope = ScriptRuntime.leaveWith(scope);
--withDepth;
}
// make stack to contain single exception object
stackTop = STACK_SHFT;
if (doCatch) {
stack[stackTop] = ScriptRuntime.getCatchObject(cx, scope,
javaException);
} else {
// Call finally handler with javaException on stack top to
// distinguish from normal invocation through GOSUB
// which would contain DBL_MRK on the stack
stack[stackTop] = javaException;
}
// clear exception
javaException = null;
// Notify instruction observer if necessary
// and point pc and pcPrevBranch to start of catch/finally block
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
// Note: this can throw Error
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = pcNew;
continue Loop;
}
case Token.THROW: {
Object value = stack[stackTop];
if (value == DBL_MRK) value = doubleWrap(sDbl[stackTop]);
--stackTop;
int sourceLine = getShort(iCode, pc + 1);
javaException = new JavaScriptException(value, idata.itsSourceFile,
sourceLine);
exceptionPC = pc;
if (instructionThreshold != 0) {
instructionCount += pc + 1 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getJavaCatchPC(iCode);
continue Loop;
}
case Token.GE : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && rDbl <= lDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LE(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.LE : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && lDbl <= rDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LE(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.GT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && rDbl < lDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LT(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.LT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && lDbl < rDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LT(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.IN : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
boolean valBln = ScriptRuntime.in(lhs, rhs, scope);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.INSTANCEOF : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
boolean valBln = ScriptRuntime.instanceOf(lhs, rhs, scope);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.EQ : {
--stackTop;
boolean valBln = do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.NE : {
--stackTop;
boolean valBln = !do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.SHEQ : {
--stackTop;
boolean valBln = do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.SHNE : {
--stackTop;
boolean valBln = !do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.IFNE : {
boolean valBln = stack_boolean(stack, sDbl, stackTop);
--stackTop;
if (!valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue Loop;
}
pc += 2;
break;
}
case Token.IFEQ : {
boolean valBln = stack_boolean(stack, sDbl, stackTop);
--stackTop;
if (valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue Loop;
}
pc += 2;
break;
}
case Token.GOTO :
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue Loop;
case Icode_GOSUB :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = pc + 3;
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1); continue Loop;
case Icode_RETSUB : {
int slot = (iCode[pc + 1] & 0xFF);
if (instructionThreshold != 0) {
instructionCount += pc + 2 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
int newPC;
Object value = stack[LOCAL_SHFT + slot];
if (value != DBL_MRK) {
// Invocation from exception handler, restore object to rethrow
javaException = (Throwable)value;
exceptionPC = pc;
newPC = getJavaCatchPC(iCode);
} else {
// Normal return from GOSUB
newPC = (int)sDbl[LOCAL_SHFT + slot];
}
pcPrevBranch = pc = newPC;
continue Loop;
}
case Token.POP :
stack[stackTop] = null;
stackTop--;
break;
case Icode_DUP :
stack[stackTop + 1] = stack[stackTop];
sDbl[stackTop + 1] = sDbl[stackTop];
stackTop++;
break;
case Token.POPV :
result = stack[stackTop];
if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]);
stack[stackTop] = null;
--stackTop;
break;
case Token.RETURN :
result = stack[stackTop];
if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]);
--stackTop;
break Loop;
case Icode_RETUNDEF :
result = undefined;
break Loop;
case Icode_END:
break Loop;
case Token.BITNOT : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ~rIntValue;
break;
}
case Token.BITAND : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue & rIntValue;
break;
}
case Token.BITOR : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue | rIntValue;
break;
}
case Token.BITXOR : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue ^ rIntValue;
break;
}
case Token.LSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue << rIntValue;
break;
}
case Token.RSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue >> rIntValue;
break;
}
case Token.URSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop) & 0x1F;
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue;
break;
}
case Token.ADD :
--stackTop;
do_add(stack, sDbl, stackTop);
break;
case Token.SUB : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl - rDbl;
break;
}
case Token.NEG : {
double rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = -rDbl;
break;
}
case Token.POS : {
double rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = rDbl;
break;
}
case Token.MUL : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl * rDbl;
break;
}
case Token.DIV : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
// Detect the divide by zero or let Java do it ?
sDbl[stackTop] = lDbl / rDbl;
break;
}
case Token.MOD : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl % rDbl;
break;
}
case Token.NOT : {
stack[stackTop] = stack_boolean(stack, sDbl, stackTop)
? Boolean.FALSE : Boolean.TRUE;
break;
}
case Token.BINDNAME : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.bind(scope, name);
pc += 2;
break;
}
case Token.GETBASE : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.getBase(scope, name);
pc += 2;
break;
}
case Token.SETNAME : {
String name = strings[getIndex(iCode, pc + 1)];
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
// what about class cast exception here for lhs?
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.setName(lhs, rhs, scope, name);
pc += 2;
break;
}
case Token.DELPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.delete(cx, scope, lhs, rhs);
break;
}
case Token.GETPROP : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getProp(lhs, name, scope);
break;
}
case Token.SETPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setProp(lhs, name, rhs, scope);
break;
}
case Token.GETELEM :
do_getElem(cx, stack, sDbl, stackTop, scope);
--stackTop;
break;
case Token.SETELEM :
do_setElem(cx, stack, sDbl, stackTop, scope);
stackTop -= 2;
break;
case Icode_PROPINC : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postIncrement(lhs, name, scope);
break;
}
case Icode_PROPDEC : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postDecrement(lhs, name, scope);
break;
}
case Icode_ELEMINC : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postIncrementElem(lhs, rhs, scope);
break;
}
case Icode_ELEMDEC : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postDecrementElem(lhs, rhs, scope);
break;
}
case Token.GETTHIS : {
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.getThis(lhs);
break;
}
case Token.NEWTEMP : {
int slot = (iCode[++pc] & 0xFF);
stack[LOCAL_SHFT + slot] = stack[stackTop];
sDbl[LOCAL_SHFT + slot] = sDbl[stackTop];
break;
}
case Token.USETEMP : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
stack[stackTop] = stack[LOCAL_SHFT + slot];
sDbl[stackTop] = sDbl[LOCAL_SHFT + slot];
break;
}
case Icode_CALLSPECIAL : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int callType = iCode[pc + 1] & 0xFF;
boolean isNew = (iCode[pc + 2] != 0);
int sourceLine = getShort(iCode, pc + 3);
int count = getIndex(iCode, pc + 5);
stackTop -= count;
Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 1, count);
Object functionThis;
if (isNew) {
functionThis = null;
} else {
functionThis = stack[stackTop];
if (functionThis == DBL_MRK) {
functionThis = doubleWrap(sDbl[stackTop]);
}
--stackTop;
}
Object function = stack[stackTop];
if (function == DBL_MRK) function = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.callSpecial(
cx, function, isNew, functionThis, outArgs,
scope, thisObj, callType,
idata.itsSourceFile, sourceLine);
pc += 6;
instructionCount = cx.instructionCount;
break;
}
case Token.CALL : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
cx.instructionCount = instructionCount;
int count = getIndex(iCode, pc + 3);
stackTop -= count;
int calleeArgShft = stackTop + 1;
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
Scriptable calleeScope = scope;
if (idata.itsNeedsActivation) {
calleeScope = ScriptableObject.getTopLevelScope(scope);
}
Scriptable calleeThis;
if (rhs instanceof Scriptable || rhs == null) {
calleeThis = (Scriptable)rhs;
} else {
calleeThis = ScriptRuntime.toObject(cx, calleeScope, rhs);
}
if (lhs instanceof InterpretedFunction) {
// Inlining of InterpretedFunction.call not to create
// argument array
InterpretedFunction f = (InterpretedFunction)lhs;
stack[stackTop] = interpret(cx, calleeScope, calleeThis,
stack, sDbl, calleeArgShft, count,
f, f.itsData);
} else if (lhs instanceof Function) {
Function f = (Function)lhs;
Object[] outArgs = getArgsArray(stack, sDbl, calleeArgShft, count);
stack[stackTop] = f.call(cx, calleeScope, calleeThis, outArgs);
} else {
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
else if (lhs == undefined) {
// special code for better error message for call
// to undefined
lhs = strings[getIndex(iCode, pc + 1)];
if (lhs == null) lhs = undefined;
}
throw NativeGlobal.typeError1
("msg.isnt.function", ScriptRuntime.toString(lhs), calleeScope);
}
pc += 4;
instructionCount = cx.instructionCount;
break;
}
case Token.NEW : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int count = getIndex(iCode, pc + 3);
stackTop -= count;
int calleeArgShft = stackTop + 1;
Object lhs = stack[stackTop];
if (lhs instanceof InterpretedFunction) {
// Inlining of InterpretedFunction.construct not to create
// argument array
InterpretedFunction f = (InterpretedFunction)lhs;
Scriptable newInstance = f.createObject(cx, scope);
Object callResult = interpret(cx, scope, newInstance,
stack, sDbl, calleeArgShft, count,
f, f.itsData);
if (callResult instanceof Scriptable && callResult != undefined) {
stack[stackTop] = callResult;
} else {
stack[stackTop] = newInstance;
}
} else if (lhs instanceof Function) {
Function f = (Function)lhs;
Object[] outArgs = getArgsArray(stack, sDbl, calleeArgShft, count);
stack[stackTop] = f.construct(cx, scope, outArgs);
} else {
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
else if (lhs == undefined) {
// special code for better error message for call
// to undefined
lhs = strings[getIndex(iCode, pc + 1)];
if (lhs == null) lhs = undefined;
}
throw NativeGlobal.typeError1
("msg.isnt.function", ScriptRuntime.toString(lhs), scope);
}
pc += 4; instructionCount = cx.instructionCount;
break;
}
case Token.TYPEOF : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.typeof(lhs);
break;
}
case Icode_TYPEOFNAME : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.typeofName(scope, name);
pc += 2;
break;
}
case Token.STRING :
stack[++stackTop] = strings[getIndex(iCode, pc + 1)];
pc += 2;
break;
case Icode_SHORTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getShort(iCode, pc + 1);
pc += 2;
break;
case Icode_INTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getInt(iCode, pc + 1);
pc += 4;
break;
case Token.NUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = idata.itsDoubleTable[getIndex(iCode, pc + 1)];
pc += 2;
break;
case Token.NAME : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.name(scope, name);
pc += 2;
break;
}
case Icode_NAMEINC : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.postIncrement(scope, name);
pc += 2;
break;
}
case Icode_NAMEDEC : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.postDecrement(scope, name);
pc += 2;
break;
}
case Token.SETVAR : {
int slot = (iCode[++pc] & 0xFF);
if (!useActivationVars) {
stack[VAR_SHFT + slot] = stack[stackTop];
sDbl[VAR_SHFT + slot] = sDbl[stackTop];
} else {
Object val = stack[stackTop];
if (val == DBL_MRK) val = doubleWrap(sDbl[stackTop]);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case Token.GETVAR : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
} else {
stack[stackTop] = activationGet(fnOrScript, scope, slot);
}
break;
}
case Icode_VARINC : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) + 1.0;
} else {
Object val = activationGet(fnOrScript, scope, slot);
stack[stackTop] = val;
val = doubleWrap(ScriptRuntime.toNumber(val) + 1.0);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case Icode_VARDEC : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) - 1.0;
} else {
Object val = activationGet(fnOrScript, scope, slot);
stack[stackTop] = val;
val = doubleWrap(ScriptRuntime.toNumber(val) - 1.0);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case Token.ZERO :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 0;
break;
case Token.ONE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 1;
break;
case Token.NULL :
stack[++stackTop] = null;
break;
case Token.THIS :
stack[++stackTop] = thisObj;
break;
case Token.THISFN :
stack[++stackTop] = fnOrScript;
break;
case Token.FALSE :
stack[++stackTop] = Boolean.FALSE;
break;
case Token.TRUE :
stack[++stackTop] = Boolean.TRUE;
break;
case Token.UNDEFINED :
stack[++stackTop] = Undefined.instance;
break;
case Token.ENTERWITH : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
scope = ScriptRuntime.enterWith(lhs, scope);
++withDepth;
break;
}
case Token.LEAVEWITH :
scope = ScriptRuntime.leaveWith(scope);
--withDepth;
break;
case Token.NEWSCOPE :
stack[++stackTop] = ScriptRuntime.newScope();
break;
case Token.ENUMINIT : {
int slot = (iCode[++pc] & 0xFF);
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
stack[LOCAL_SHFT + slot] = ScriptRuntime.initEnum(lhs, scope);
break;
}
case Token.ENUMNEXT : {
int slot = (iCode[++pc] & 0xFF);
Object val = stack[LOCAL_SHFT + slot];
++stackTop;
stack[stackTop] = ScriptRuntime.nextEnum(val);
break;
}
case Icode_GETPROTO : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getProto(lhs, scope);
break;
}
case Icode_GETPARENT : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs);
break;
}
case Icode_GETSCOPEPARENT : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs, scope);
break;
}
case Icode_SETPROTO : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setProto(lhs, rhs, scope);
break;
}
case Icode_SETPARENT : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setParent(lhs, rhs, scope);
break;
}
case Icode_SCOPE :
stack[++stackTop] = scope;
break;
case Icode_CLOSURE : {
int i = getIndex(iCode, pc + 1);
InterpreterData closureData = idata.itsNestedFunctions[i];
stack[++stackTop] = createFunction(cx, scope, closureData,
idata.itsFromEvalCode);
pc += 2;
break;
}
case Token.REGEXP : {
int i = getIndex(iCode, pc + 1);
stack[++stackTop] = idata.itsRegExpLiterals[i];
pc += 2;
break;
}
case Icode_LINE : {
int line = getShort(iCode, pc + 1);
cx.interpreterLine = line;
if (debuggerFrame != null) {
debuggerFrame.onLineChange(cx, line);
}
pc += 2;
break;
}
default : {
dumpICode(idata);
throw new RuntimeException
("Unknown icode : "+(iCode[pc] & 0xff)+" @ pc : "+pc);
}
// end of interpreter switch
}
pc++;
}
catch (Throwable ex) {
if (instructionThreshold != 0) {
if (instructionCount < 0) {
// throw during function call
instructionCount = cx.instructionCount;
} else {
// throw during any other operation
instructionCount += pc - pcPrevBranch;
cx.instructionCount = instructionCount;
}
}
javaException = ex;
exceptionPC = pc;
pc = getJavaCatchPC(iCode);
continue Loop;
}
}
cx.interpreterSourceFile = savedSourceFile;
if (debuggerFrame != null) {
if (javaException != null) {
debuggerFrame.onExit(cx, true, javaException);
} else {
debuggerFrame.onExit(cx, false, result);
}
}
if (idata.itsNeedsActivation) {
ScriptRuntime.popActivation(cx);
}
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
cx.instructionCount = instructionCount;
}
if (javaException != null) {
if (javaException instanceof JavaScriptException) {
throw (JavaScriptException)javaException;
} else if (javaException instanceof RuntimeException) {
throw (RuntimeException)javaException;
} else {
// Must be instance of Error or code bug
throw (Error)javaException;
}
}
return result;
}
| static Object interpret(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args, double[] argsDbl,
int argShift, int argCount,
NativeFunction fnOrScript,
InterpreterData idata)
throws JavaScriptException
{
if (cx.interpreterSecurityDomain != idata.securityDomain) {
return execWithNewDomain(cx, scope, thisObj,
args, argsDbl, argShift, argCount,
fnOrScript, idata);
}
final Object DBL_MRK = Interpreter.DBL_MRK;
final Scriptable undefined = Undefined.instance;
final int VAR_SHFT = 0;
final int maxVars = idata.itsMaxVars;
final int LOCAL_SHFT = VAR_SHFT + maxVars;
final int STACK_SHFT = LOCAL_SHFT + idata.itsMaxLocals;
// stack[VAR_SHFT <= i < LOCAL_SHFT]: variables
// stack[LOCAL_SHFT <= i < TRY_STACK_SHFT]: used for newtemp/usetemp
// stack[STACK_SHFT <= i < STACK_SHFT + idata.itsMaxStack]: stack data
// sDbl[i]: if stack[i] is DBL_MRK, sDbl[i] holds the number value
int maxFrameArray = idata.itsMaxFrameArray;
if (maxFrameArray != STACK_SHFT + idata.itsMaxStack)
Context.codeBug();
Object[] stack = new Object[maxFrameArray];
double[] sDbl = new double[maxFrameArray];
int stackTop = STACK_SHFT - 1;
int withDepth = 0;
int definedArgs = fnOrScript.argCount;
if (definedArgs > argCount) { definedArgs = argCount; }
for (int i = 0; i != definedArgs; ++i) {
Object arg = args[argShift + i];
stack[VAR_SHFT + i] = arg;
if (arg == DBL_MRK) {
sDbl[VAR_SHFT + i] = argsDbl[argShift + i];
}
}
for (int i = definedArgs; i != maxVars; ++i) {
stack[VAR_SHFT + i] = undefined;
}
DebugFrame debuggerFrame = null;
if (cx.debugger != null) {
debuggerFrame = cx.debugger.getFrame(cx, idata);
}
if (idata.itsFunctionType != 0) {
InterpretedFunction f = (InterpretedFunction)fnOrScript;
if (!f.itsUseDynamicScope) {
scope = fnOrScript.getParentScope();
}
if (idata.itsCheckThis) {
thisObj = ScriptRuntime.getThis(thisObj);
}
if (idata.itsNeedsActivation) {
if (argsDbl != null) {
args = getArgsArray(args, argsDbl, argShift, argCount);
argShift = 0;
argsDbl = null;
}
scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript,
thisObj, args);
}
} else {
scope = ScriptRuntime.initScript(cx, scope, fnOrScript, thisObj,
idata.itsFromEvalCode);
}
if (idata.itsNestedFunctions != null) {
if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation)
Context.codeBug();
for (int i = 0; i < idata.itsNestedFunctions.length; i++) {
InterpreterData fdata = idata.itsNestedFunctions[i];
if (fdata.itsFunctionType == FunctionNode.FUNCTION_STATEMENT) {
createFunction(cx, scope, fdata, idata.itsFromEvalCode);
}
}
}
boolean useActivationVars = false;
if (debuggerFrame != null) {
if (argsDbl != null) {
args = getArgsArray(args, argsDbl, argShift, argCount);
argShift = 0;
argsDbl = null;
}
if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation) {
useActivationVars = true;
scope = ScriptRuntime.initVarObj(cx, scope, fnOrScript,
thisObj, args);
}
debuggerFrame.onEnter(cx, scope, thisObj, args);
}
String savedSourceFile = cx.interpreterSourceFile;
cx.interpreterSourceFile = idata.itsSourceFile;
Object result = undefined;
// If javaException != null on exit, it will be throw instead of
// normal return
Throwable javaException = null;
int exceptionPC = -1;
byte[] iCode = idata.itsICode;
String[] strings = idata.itsStringTable;
int pc = 0;
int pcPrevBranch = pc;
final int instructionThreshold = cx.instructionThreshold;
// During function call this will be set to -1 so catch can properly
// adjust it
int instructionCount = cx.instructionCount;
// arbitrary number to add to instructionCount when calling
// other functions
final int INVOCATION_COST = 100;
Loop: for (;;) {
try {
switch (iCode[pc] & 0xff) {
// Back indent to ease imlementation reading
case Icode_CATCH: {
// The following code should be executed inside try/catch inside main
// loop, not in the loop catch block itself to deal withnexceptions
// from observeInstructionCount. A special bytecode is used only to
// simplify logic.
if (javaException == null) Context.codeBug();
int pcNew = -1;
boolean doCatch = false;
int handlerOffset = getExceptionHandler(idata.itsExceptionTable,
exceptionPC);
if (handlerOffset >= 0) {
final int SCRIPT_CAN_CATCH = 0, ONLY_FINALLY = 1, OTHER = 2;
int exType;
if (javaException instanceof JavaScriptException) {
exType = SCRIPT_CAN_CATCH;
} else if (javaException instanceof EcmaError) {
// an offical ECMA error object,
exType = SCRIPT_CAN_CATCH;
} else if (javaException instanceof WrappedException) {
exType = SCRIPT_CAN_CATCH;
} else if (javaException instanceof RuntimeException) {
exType = ONLY_FINALLY;
} else {
// Error instance
exType = OTHER;
}
if (exType != OTHER) {
// Do not allow for JS to interfere with Error instances
// (exType == OTHER), as they can be used to terminate
// long running script
if (exType == SCRIPT_CAN_CATCH) {
// Allow JS to catch only JavaScriptException and
// EcmaError
pcNew = idata.itsExceptionTable[handlerOffset
+ EXCEPTION_CATCH_SLOT];
if (pcNew >= 0) {
// Has catch block
doCatch = true;
}
}
if (pcNew < 0) {
pcNew = idata.itsExceptionTable[handlerOffset
+ EXCEPTION_FINALLY_SLOT];
}
}
}
if (debuggerFrame != null && !(javaException instanceof Error)) {
debuggerFrame.onExceptionThrown(cx, javaException);
}
if (pcNew < 0) {
break Loop;
}
// We caught an exception
// restore scope at try point
int tryWithDepth = idata.itsExceptionTable[
handlerOffset + EXCEPTION_WITH_DEPTH_SLOT];
while (tryWithDepth != withDepth) {
if (scope == null) Context.codeBug();
scope = ScriptRuntime.leaveWith(scope);
--withDepth;
}
// make stack to contain single exception object
stackTop = STACK_SHFT;
if (doCatch) {
stack[stackTop] = ScriptRuntime.getCatchObject(cx, scope,
javaException);
} else {
// Call finally handler with javaException on stack top to
// distinguish from normal invocation through GOSUB
// which would contain DBL_MRK on the stack
stack[stackTop] = javaException;
}
// clear exception
javaException = null;
// Notify instruction observer if necessary
// and point pc and pcPrevBranch to start of catch/finally block
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
// Note: this can throw Error
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = pcNew;
continue Loop;
}
case Token.THROW: {
Object value = stack[stackTop];
if (value == DBL_MRK) value = doubleWrap(sDbl[stackTop]);
--stackTop;
int sourceLine = getShort(iCode, pc + 1);
javaException = new JavaScriptException(value, idata.itsSourceFile,
sourceLine);
exceptionPC = pc;
if (instructionThreshold != 0) {
instructionCount += pc + 1 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getJavaCatchPC(iCode);
continue Loop;
}
case Token.GE : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && rDbl <= lDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LE(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.LE : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && lDbl <= rDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LE(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.GT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && rDbl < lDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LT(rhs, lhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.LT : {
--stackTop;
Object rhs = stack[stackTop + 1];
Object lhs = stack[stackTop];
boolean valBln;
if (rhs == DBL_MRK || lhs == DBL_MRK) {
double rDbl = stack_double(stack, sDbl, stackTop + 1);
double lDbl = stack_double(stack, sDbl, stackTop);
valBln = (rDbl == rDbl && lDbl == lDbl && lDbl < rDbl);
} else {
valBln = (1 == ScriptRuntime.cmp_LT(lhs, rhs));
}
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.IN : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
boolean valBln = ScriptRuntime.in(lhs, rhs, scope);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.INSTANCEOF : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
boolean valBln = ScriptRuntime.instanceOf(lhs, rhs, scope);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.EQ : {
--stackTop;
boolean valBln = do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.NE : {
--stackTop;
boolean valBln = !do_eq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.SHEQ : {
--stackTop;
boolean valBln = do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.SHNE : {
--stackTop;
boolean valBln = !do_sheq(stack, sDbl, stackTop);
stack[stackTop] = valBln ? Boolean.TRUE : Boolean.FALSE;
break;
}
case Token.IFNE : {
boolean valBln = stack_boolean(stack, sDbl, stackTop);
--stackTop;
if (!valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue Loop;
}
pc += 2;
break;
}
case Token.IFEQ : {
boolean valBln = stack_boolean(stack, sDbl, stackTop);
--stackTop;
if (valBln) {
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue Loop;
}
pc += 2;
break;
}
case Token.GOTO :
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1);
continue Loop;
case Icode_GOSUB :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = pc + 3;
if (instructionThreshold != 0) {
instructionCount += pc + 3 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
pcPrevBranch = pc = getTarget(iCode, pc + 1); continue Loop;
case Icode_RETSUB : {
int slot = (iCode[pc + 1] & 0xFF);
if (instructionThreshold != 0) {
instructionCount += pc + 2 - pcPrevBranch;
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
}
int newPC;
Object value = stack[LOCAL_SHFT + slot];
if (value != DBL_MRK) {
// Invocation from exception handler, restore object to rethrow
javaException = (Throwable)value;
exceptionPC = pc;
newPC = getJavaCatchPC(iCode);
} else {
// Normal return from GOSUB
newPC = (int)sDbl[LOCAL_SHFT + slot];
}
pcPrevBranch = pc = newPC;
continue Loop;
}
case Token.POP :
stack[stackTop] = null;
stackTop--;
break;
case Icode_DUP :
stack[stackTop + 1] = stack[stackTop];
sDbl[stackTop + 1] = sDbl[stackTop];
stackTop++;
break;
case Token.POPV :
result = stack[stackTop];
if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]);
stack[stackTop] = null;
--stackTop;
break;
case Token.RETURN :
result = stack[stackTop];
if (result == DBL_MRK) result = doubleWrap(sDbl[stackTop]);
--stackTop;
break Loop;
case Icode_RETUNDEF :
result = undefined;
break Loop;
case Icode_END:
break Loop;
case Token.BITNOT : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ~rIntValue;
break;
}
case Token.BITAND : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue & rIntValue;
break;
}
case Token.BITOR : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue | rIntValue;
break;
}
case Token.BITXOR : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue ^ rIntValue;
break;
}
case Token.LSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue << rIntValue;
break;
}
case Token.RSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop);
--stackTop;
int lIntValue = stack_int32(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lIntValue >> rIntValue;
break;
}
case Token.URSH : {
int rIntValue = stack_int32(stack, sDbl, stackTop) & 0x1F;
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue;
break;
}
case Token.ADD :
--stackTop;
do_add(stack, sDbl, stackTop);
break;
case Token.SUB : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl - rDbl;
break;
}
case Token.NEG : {
double rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = -rDbl;
break;
}
case Token.POS : {
double rDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = rDbl;
break;
}
case Token.MUL : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl * rDbl;
break;
}
case Token.DIV : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
// Detect the divide by zero or let Java do it ?
sDbl[stackTop] = lDbl / rDbl;
break;
}
case Token.MOD : {
double rDbl = stack_double(stack, sDbl, stackTop);
--stackTop;
double lDbl = stack_double(stack, sDbl, stackTop);
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = lDbl % rDbl;
break;
}
case Token.NOT : {
stack[stackTop] = stack_boolean(stack, sDbl, stackTop)
? Boolean.FALSE : Boolean.TRUE;
break;
}
case Token.BINDNAME : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.bind(scope, name);
pc += 2;
break;
}
case Token.GETBASE : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.getBase(scope, name);
pc += 2;
break;
}
case Token.SETNAME : {
String name = strings[getIndex(iCode, pc + 1)];
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
// what about class cast exception here for lhs?
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.setName(lhs, rhs, scope, name);
pc += 2;
break;
}
case Token.DELPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.delete(cx, scope, lhs, rhs);
break;
}
case Token.GETPROP : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getProp(lhs, name, scope);
break;
}
case Token.SETPROP : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setProp(lhs, name, rhs, scope);
break;
}
case Token.GETELEM :
do_getElem(cx, stack, sDbl, stackTop, scope);
--stackTop;
break;
case Token.SETELEM :
do_setElem(cx, stack, sDbl, stackTop, scope);
stackTop -= 2;
break;
case Icode_PROPINC : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postIncrement(lhs, name, scope);
break;
}
case Icode_PROPDEC : {
String name = (String)stack[stackTop];
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postDecrement(lhs, name, scope);
break;
}
case Icode_ELEMINC : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postIncrementElem(lhs, rhs, scope);
break;
}
case Icode_ELEMDEC : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.postDecrementElem(lhs, rhs, scope);
break;
}
case Token.GETTHIS : {
Scriptable lhs = (Scriptable)stack[stackTop];
stack[stackTop] = ScriptRuntime.getThis(lhs);
break;
}
case Token.NEWTEMP : {
int slot = (iCode[++pc] & 0xFF);
stack[LOCAL_SHFT + slot] = stack[stackTop];
sDbl[LOCAL_SHFT + slot] = sDbl[stackTop];
break;
}
case Token.USETEMP : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
stack[stackTop] = stack[LOCAL_SHFT + slot];
sDbl[stackTop] = sDbl[LOCAL_SHFT + slot];
break;
}
case Icode_CALLSPECIAL : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int callType = iCode[pc + 1] & 0xFF;
boolean isNew = (iCode[pc + 2] != 0);
int sourceLine = getShort(iCode, pc + 3);
int count = getIndex(iCode, pc + 5);
stackTop -= count;
Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 1, count);
Object functionThis;
if (isNew) {
functionThis = null;
} else {
functionThis = stack[stackTop];
if (functionThis == DBL_MRK) {
functionThis = doubleWrap(sDbl[stackTop]);
}
--stackTop;
}
Object function = stack[stackTop];
if (function == DBL_MRK) function = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.callSpecial(
cx, function, isNew, functionThis, outArgs,
scope, thisObj, callType,
idata.itsSourceFile, sourceLine);
pc += 6;
instructionCount = cx.instructionCount;
break;
}
case Token.CALL : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int count = getIndex(iCode, pc + 3);
stackTop -= count;
int calleeArgShft = stackTop + 1;
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
Scriptable calleeScope = scope;
if (idata.itsNeedsActivation) {
calleeScope = ScriptableObject.getTopLevelScope(scope);
}
Scriptable calleeThis;
if (rhs instanceof Scriptable || rhs == null) {
calleeThis = (Scriptable)rhs;
} else {
calleeThis = ScriptRuntime.toObject(cx, calleeScope, rhs);
}
if (lhs instanceof InterpretedFunction) {
// Inlining of InterpretedFunction.call not to create
// argument array
InterpretedFunction f = (InterpretedFunction)lhs;
stack[stackTop] = interpret(cx, calleeScope, calleeThis,
stack, sDbl, calleeArgShft, count,
f, f.itsData);
} else if (lhs instanceof Function) {
Function f = (Function)lhs;
Object[] outArgs = getArgsArray(stack, sDbl, calleeArgShft, count);
stack[stackTop] = f.call(cx, calleeScope, calleeThis, outArgs);
} else {
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
else if (lhs == undefined) {
// special code for better error message for call
// to undefined
lhs = strings[getIndex(iCode, pc + 1)];
if (lhs == null) lhs = undefined;
}
throw NativeGlobal.typeError1
("msg.isnt.function", ScriptRuntime.toString(lhs), calleeScope);
}
pc += 4;
instructionCount = cx.instructionCount;
break;
}
case Token.NEW : {
if (instructionThreshold != 0) {
instructionCount += INVOCATION_COST;
cx.instructionCount = instructionCount;
instructionCount = -1;
}
int count = getIndex(iCode, pc + 3);
stackTop -= count;
int calleeArgShft = stackTop + 1;
Object lhs = stack[stackTop];
if (lhs instanceof InterpretedFunction) {
// Inlining of InterpretedFunction.construct not to create
// argument array
InterpretedFunction f = (InterpretedFunction)lhs;
Scriptable newInstance = f.createObject(cx, scope);
Object callResult = interpret(cx, scope, newInstance,
stack, sDbl, calleeArgShft, count,
f, f.itsData);
if (callResult instanceof Scriptable && callResult != undefined) {
stack[stackTop] = callResult;
} else {
stack[stackTop] = newInstance;
}
} else if (lhs instanceof Function) {
Function f = (Function)lhs;
Object[] outArgs = getArgsArray(stack, sDbl, calleeArgShft, count);
stack[stackTop] = f.construct(cx, scope, outArgs);
} else {
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
else if (lhs == undefined) {
// special code for better error message for call
// to undefined
lhs = strings[getIndex(iCode, pc + 1)];
if (lhs == null) lhs = undefined;
}
throw NativeGlobal.typeError1
("msg.isnt.function", ScriptRuntime.toString(lhs), scope);
}
pc += 4; instructionCount = cx.instructionCount;
break;
}
case Token.TYPEOF : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.typeof(lhs);
break;
}
case Icode_TYPEOFNAME : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.typeofName(scope, name);
pc += 2;
break;
}
case Token.STRING :
stack[++stackTop] = strings[getIndex(iCode, pc + 1)];
pc += 2;
break;
case Icode_SHORTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getShort(iCode, pc + 1);
pc += 2;
break;
case Icode_INTNUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = getInt(iCode, pc + 1);
pc += 4;
break;
case Token.NUMBER :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = idata.itsDoubleTable[getIndex(iCode, pc + 1)];
pc += 2;
break;
case Token.NAME : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.name(scope, name);
pc += 2;
break;
}
case Icode_NAMEINC : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.postIncrement(scope, name);
pc += 2;
break;
}
case Icode_NAMEDEC : {
String name = strings[getIndex(iCode, pc + 1)];
stack[++stackTop] = ScriptRuntime.postDecrement(scope, name);
pc += 2;
break;
}
case Token.SETVAR : {
int slot = (iCode[++pc] & 0xFF);
if (!useActivationVars) {
stack[VAR_SHFT + slot] = stack[stackTop];
sDbl[VAR_SHFT + slot] = sDbl[stackTop];
} else {
Object val = stack[stackTop];
if (val == DBL_MRK) val = doubleWrap(sDbl[stackTop]);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case Token.GETVAR : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
} else {
stack[stackTop] = activationGet(fnOrScript, scope, slot);
}
break;
}
case Icode_VARINC : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) + 1.0;
} else {
Object val = activationGet(fnOrScript, scope, slot);
stack[stackTop] = val;
val = doubleWrap(ScriptRuntime.toNumber(val) + 1.0);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case Icode_VARDEC : {
int slot = (iCode[++pc] & 0xFF);
++stackTop;
if (!useActivationVars) {
stack[stackTop] = stack[VAR_SHFT + slot];
sDbl[stackTop] = sDbl[VAR_SHFT + slot];
stack[VAR_SHFT + slot] = DBL_MRK;
sDbl[VAR_SHFT + slot] = stack_double(stack, sDbl, stackTop) - 1.0;
} else {
Object val = activationGet(fnOrScript, scope, slot);
stack[stackTop] = val;
val = doubleWrap(ScriptRuntime.toNumber(val) - 1.0);
activationPut(fnOrScript, scope, slot, val);
}
break;
}
case Token.ZERO :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 0;
break;
case Token.ONE :
++stackTop;
stack[stackTop] = DBL_MRK;
sDbl[stackTop] = 1;
break;
case Token.NULL :
stack[++stackTop] = null;
break;
case Token.THIS :
stack[++stackTop] = thisObj;
break;
case Token.THISFN :
stack[++stackTop] = fnOrScript;
break;
case Token.FALSE :
stack[++stackTop] = Boolean.FALSE;
break;
case Token.TRUE :
stack[++stackTop] = Boolean.TRUE;
break;
case Token.UNDEFINED :
stack[++stackTop] = Undefined.instance;
break;
case Token.ENTERWITH : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
scope = ScriptRuntime.enterWith(lhs, scope);
++withDepth;
break;
}
case Token.LEAVEWITH :
scope = ScriptRuntime.leaveWith(scope);
--withDepth;
break;
case Token.NEWSCOPE :
stack[++stackTop] = ScriptRuntime.newScope();
break;
case Token.ENUMINIT : {
int slot = (iCode[++pc] & 0xFF);
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
--stackTop;
stack[LOCAL_SHFT + slot] = ScriptRuntime.initEnum(lhs, scope);
break;
}
case Token.ENUMNEXT : {
int slot = (iCode[++pc] & 0xFF);
Object val = stack[LOCAL_SHFT + slot];
++stackTop;
stack[stackTop] = ScriptRuntime.nextEnum(val);
break;
}
case Icode_GETPROTO : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getProto(lhs, scope);
break;
}
case Icode_GETPARENT : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs);
break;
}
case Icode_GETSCOPEPARENT : {
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.getParent(lhs, scope);
break;
}
case Icode_SETPROTO : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setProto(lhs, rhs, scope);
break;
}
case Icode_SETPARENT : {
Object rhs = stack[stackTop];
if (rhs == DBL_MRK) rhs = doubleWrap(sDbl[stackTop]);
--stackTop;
Object lhs = stack[stackTop];
if (lhs == DBL_MRK) lhs = doubleWrap(sDbl[stackTop]);
stack[stackTop] = ScriptRuntime.setParent(lhs, rhs, scope);
break;
}
case Icode_SCOPE :
stack[++stackTop] = scope;
break;
case Icode_CLOSURE : {
int i = getIndex(iCode, pc + 1);
InterpreterData closureData = idata.itsNestedFunctions[i];
stack[++stackTop] = createFunction(cx, scope, closureData,
idata.itsFromEvalCode);
pc += 2;
break;
}
case Token.REGEXP : {
int i = getIndex(iCode, pc + 1);
stack[++stackTop] = idata.itsRegExpLiterals[i];
pc += 2;
break;
}
case Icode_LINE : {
int line = getShort(iCode, pc + 1);
cx.interpreterLine = line;
if (debuggerFrame != null) {
debuggerFrame.onLineChange(cx, line);
}
pc += 2;
break;
}
default : {
dumpICode(idata);
throw new RuntimeException
("Unknown icode : "+(iCode[pc] & 0xff)+" @ pc : "+pc);
}
// end of interpreter switch
}
pc++;
}
catch (Throwable ex) {
if (instructionThreshold != 0) {
if (instructionCount < 0) {
// throw during function call
instructionCount = cx.instructionCount;
} else {
// throw during any other operation
instructionCount += pc - pcPrevBranch;
cx.instructionCount = instructionCount;
}
}
javaException = ex;
exceptionPC = pc;
pc = getJavaCatchPC(iCode);
continue Loop;
}
}
cx.interpreterSourceFile = savedSourceFile;
if (debuggerFrame != null) {
if (javaException != null) {
debuggerFrame.onExit(cx, true, javaException);
} else {
debuggerFrame.onExit(cx, false, result);
}
}
if (idata.itsNeedsActivation) {
ScriptRuntime.popActivation(cx);
}
if (instructionThreshold != 0) {
if (instructionCount > instructionThreshold) {
cx.observeInstructionCount(instructionCount);
instructionCount = 0;
}
cx.instructionCount = instructionCount;
}
if (javaException != null) {
if (javaException instanceof JavaScriptException) {
throw (JavaScriptException)javaException;
} else if (javaException instanceof RuntimeException) {
throw (RuntimeException)javaException;
} else {
// Must be instance of Error or code bug
throw (Error)javaException;
}
}
return result;
}
|
diff --git a/wicket-contrib-tinymce/src/test/wicket/contrib/tinymce/TinyMCEPanelTest.java b/wicket-contrib-tinymce/src/test/wicket/contrib/tinymce/TinyMCEPanelTest.java
index e199b1fe2..aa9ea75e5 100644
--- a/wicket-contrib-tinymce/src/test/wicket/contrib/tinymce/TinyMCEPanelTest.java
+++ b/wicket-contrib-tinymce/src/test/wicket/contrib/tinymce/TinyMCEPanelTest.java
@@ -1,167 +1,167 @@
/*
* Copyright (C) 2005 Iulian-Corneliu Costan
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package wicket.contrib.tinymce;
import junit.framework.TestCase;
import wicket.contrib.tinymce.TinyMCEPanel;
import wicket.contrib.tinymce.settings.NoneditablePlugin;
import wicket.contrib.tinymce.settings.Plugin;
import wicket.contrib.tinymce.settings.TinyMCESettings;
import wicket.markup.html.WebComponent;
import wicket.markup.html.panel.Panel;
import wicket.markup.html.resources.JavaScriptReference;
import wicket.util.tester.TestPanelSource;
import wicket.util.tester.WicketTester;
/**
* Tests of the TinyMCE panel.
*
* @author Frank Bille Jensen ([email protected])
*/
public class TinyMCEPanelTest extends TestCase
{
WicketTester application;
/**
* For each test case we provide a new WicketTester.
* @see junit.framework.TestCase#setUp()
*/
public void setUp()
{
application = new WicketTester();
}
/**
* Test if basic rendering of this panel works.
*/
public void testRender()
{
application.startPanel(new TestPanelSource()
{
public Panel getTestPanel(String panelId)
{
TinyMCESettings settings = new TinyMCESettings();
return new TinyMCEPanel("panel", settings);
}
});
assertCommonComponents();
application.assertContains("mode : \"textareas\"");
application.assertContains("theme : \"simple\"");
}
/**
* Test that the correct output is rendered when using the advanced theme.
*/
public void testRenderAdvanced()
{
application.startPanel(new TestPanelSource()
{
public Panel getTestPanel(String panelId)
{
TinyMCESettings settings = new TinyMCESettings(TinyMCESettings.Theme.advanced);
settings.register(new NoneditablePlugin());
return new TinyMCEPanel("panel", settings);
}
});
assertCommonComponents();
application.assertContains("mode : \"textareas\"");
application.assertContains("theme : \"advanced\"");
application.assertContains("plugins : \"noneditable\"");
}
/**
* Ensure that the correct javascript is written, to load the plugins
* needed.
*/
public void testRenderWithExternalPlugins()
{
// Define a mock plugin
final Plugin mockPlugin = new Plugin("mockplugin", "the/path/to/the/plugin")
{
private static final long serialVersionUID = 1L;
};
// Add the panel.
application.startPanel(new TestPanelSource()
{
public Panel getTestPanel(String panelId)
{
TinyMCESettings settings = new TinyMCESettings(TinyMCESettings.Theme.advanced);
settings.register(mockPlugin);
return new TinyMCEPanel("panel", settings);
}
});
assertCommonComponents();
application.assertContains("plugins : \"mockplugin\"");
application.assertContains("tinyMCE\\.loadPlugin\\('" + mockPlugin.getName() + "','"
+ mockPlugin.getPluginPath() + "'\\);");
}
/**
* Ensure that the plugins additional javascript is actually rendered.
*
*/
public void testAdditionalPluginJavaScript()
{
// Define a mock plugin
final Plugin mockPlugin = new Plugin("mockplugin")
{
private static final long serialVersionUID = 1L;
- protected void additionalJavaScript(StringBuffer buffer)
+ protected void definePluginExtensions(StringBuffer buffer)
{
buffer.append("alert('Hello Mock World');");
}
};
// Add the panel.
application.startPanel(new TestPanelSource()
{
public Panel getTestPanel(String panelId)
{
TinyMCESettings settings = new TinyMCESettings();
settings.register(mockPlugin);
return new TinyMCEPanel("panel", settings);
}
});
assertCommonComponents();
application.assertContains("tinyMCE.init\\(\\{[^\\}]+\\}\\);\nalert\\('Hello Mock World'\\);");
}
private void assertCommonComponents()
{
application.assertComponent("panel", TinyMCEPanel.class);
application.assertComponent("panel:tinymce", JavaScriptReference.class);
application.assertComponent("panel:initScript", WebComponent.class);
application.assertContains("tinyMCE\\.init\\(\\{");
application.assertContains("\\}\\);");
}
}
| true | true | public void testAdditionalPluginJavaScript()
{
// Define a mock plugin
final Plugin mockPlugin = new Plugin("mockplugin")
{
private static final long serialVersionUID = 1L;
protected void additionalJavaScript(StringBuffer buffer)
{
buffer.append("alert('Hello Mock World');");
}
};
// Add the panel.
application.startPanel(new TestPanelSource()
{
public Panel getTestPanel(String panelId)
{
TinyMCESettings settings = new TinyMCESettings();
settings.register(mockPlugin);
return new TinyMCEPanel("panel", settings);
}
});
assertCommonComponents();
application.assertContains("tinyMCE.init\\(\\{[^\\}]+\\}\\);\nalert\\('Hello Mock World'\\);");
}
| public void testAdditionalPluginJavaScript()
{
// Define a mock plugin
final Plugin mockPlugin = new Plugin("mockplugin")
{
private static final long serialVersionUID = 1L;
protected void definePluginExtensions(StringBuffer buffer)
{
buffer.append("alert('Hello Mock World');");
}
};
// Add the panel.
application.startPanel(new TestPanelSource()
{
public Panel getTestPanel(String panelId)
{
TinyMCESettings settings = new TinyMCESettings();
settings.register(mockPlugin);
return new TinyMCEPanel("panel", settings);
}
});
assertCommonComponents();
application.assertContains("tinyMCE.init\\(\\{[^\\}]+\\}\\);\nalert\\('Hello Mock World'\\);");
}
|
diff --git a/resources/diameter-cx-dx/ra/src/main/java/org/mobicents/slee/resource/diameter/cxdx/CxDxMessageFactoryImpl.java b/resources/diameter-cx-dx/ra/src/main/java/org/mobicents/slee/resource/diameter/cxdx/CxDxMessageFactoryImpl.java
index 4ec3ec91f..db0ad105a 100644
--- a/resources/diameter-cx-dx/ra/src/main/java/org/mobicents/slee/resource/diameter/cxdx/CxDxMessageFactoryImpl.java
+++ b/resources/diameter-cx-dx/ra/src/main/java/org/mobicents/slee/resource/diameter/cxdx/CxDxMessageFactoryImpl.java
@@ -1,331 +1,332 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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.slee.resource.diameter.cxdx;
import net.java.slee.resource.diameter.base.DiameterAvpFactory;
import net.java.slee.resource.diameter.base.DiameterMessageFactory;
import net.java.slee.resource.diameter.base.NoSuchAvpException;
import net.java.slee.resource.diameter.base.events.DiameterHeader;
import net.java.slee.resource.diameter.base.events.DiameterMessage;
import net.java.slee.resource.diameter.base.events.avp.DiameterAvp;
import net.java.slee.resource.diameter.base.events.avp.DiameterIdentity;
import net.java.slee.resource.diameter.cxdx.CxDxMessageFactory;
import net.java.slee.resource.diameter.cxdx.events.LocationInfoRequest;
import net.java.slee.resource.diameter.cxdx.events.MultimediaAuthenticationRequest;
import net.java.slee.resource.diameter.cxdx.events.PushProfileRequest;
import net.java.slee.resource.diameter.cxdx.events.RegistrationTerminationRequest;
import net.java.slee.resource.diameter.cxdx.events.ServerAssignmentRequest;
import net.java.slee.resource.diameter.cxdx.events.UserAuthorizationRequest;
import net.java.slee.resource.diameter.cxdx.events.avp.DiameterCxDxAvpCodes;
import org.apache.log4j.Logger;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Avp;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Message;
import org.jdiameter.api.Session;
import org.jdiameter.api.Stack;
import org.mobicents.slee.resource.diameter.base.DiameterAvpFactoryImpl;
import org.mobicents.slee.resource.diameter.base.DiameterMessageFactoryImpl;
import org.mobicents.slee.resource.diameter.base.events.ExtensionDiameterMessageImpl;
import org.mobicents.slee.resource.diameter.cxdx.events.LocationInfoAnswerImpl;
import org.mobicents.slee.resource.diameter.cxdx.events.LocationInfoRequestImpl;
import org.mobicents.slee.resource.diameter.cxdx.events.MultimediaAuthenticationAnswerImpl;
import org.mobicents.slee.resource.diameter.cxdx.events.MultimediaAuthenticationRequestImpl;
import org.mobicents.slee.resource.diameter.cxdx.events.PushProfileAnswerImpl;
import org.mobicents.slee.resource.diameter.cxdx.events.PushProfileRequestImpl;
import org.mobicents.slee.resource.diameter.cxdx.events.RegistrationTerminationAnswerImpl;
import org.mobicents.slee.resource.diameter.cxdx.events.RegistrationTerminationRequestImpl;
import org.mobicents.slee.resource.diameter.cxdx.events.ServerAssignmentAnswerImpl;
import org.mobicents.slee.resource.diameter.cxdx.events.ServerAssignmentRequestImpl;
import org.mobicents.slee.resource.diameter.cxdx.events.UserAuthorizationAnswerImpl;
import org.mobicents.slee.resource.diameter.cxdx.events.UserAuthorizationRequestImpl;
/**
*
* CxDxMessageFactoryImpl.java
*
* @author <a href="mailto:[email protected]"> Alexandre Mendonca </a>
* @author <a href="mailto:[email protected]"> Bartosz Baranowski </a>
*/
public class CxDxMessageFactoryImpl extends DiameterMessageFactoryImpl implements CxDxMessageFactory {
private static Logger logger = Logger.getLogger(CxDxMessageFactoryImpl.class);
public static final ApplicationId cxdxAppId = ApplicationId.createByAuthAppId(DiameterCxDxAvpCodes.CXDX_VENDOR_ID, DiameterCxDxAvpCodes.CXDX_AUTH_APP_ID);
private DiameterAvpFactory baseAvpFactory = null;
protected DiameterMessageFactory baseFactory = null;
private DiameterAvp[] EMPTY_AVP_ARRAY = new DiameterAvp[]{};
/**
* @param session
* @param stack
* @param avps
*/
public CxDxMessageFactoryImpl(DiameterMessageFactory baseFactory,Session session, Stack stack, DiameterIdentity... avps) {
super(session, stack, avps);
this.baseAvpFactory = new DiameterAvpFactoryImpl();
this.baseFactory = baseFactory;
}
/**
* @param stack
*/
public CxDxMessageFactoryImpl(DiameterMessageFactory baseFactory,Stack stack) {
super(stack);
this.baseAvpFactory = new DiameterAvpFactoryImpl();
this.baseFactory = baseFactory;
}
/* (non-Javadoc)
* @see net.java.slee.resource.diameter.cxdx.CxDxMessageFactory#createLocationInfoRequest()
*/
public LocationInfoRequest createLocationInfoRequest() {
try {
return (LocationInfoRequest) createCxDxMessage(null, EMPTY_AVP_ARRAY, LocationInfoRequest.COMMAND_CODE, cxdxAppId);
}
catch (InternalException e) {
logger.error("Failed to create Location-Info-Request", e);
}
return null;
}
/* (non-Javadoc)
* @see net.java.slee.resource.diameter.cxdx.CxDxMessageFactory#createLocationInfoRequest(java.lang.String)
*/
public LocationInfoRequest createLocationInfoRequest(String sessionId) throws IllegalArgumentException {
LocationInfoRequest lir = createLocationInfoRequest();
lir.setSessionId(sessionId);
return lir;
}
/* (non-Javadoc)
* @see net.java.slee.resource.diameter.cxdx.CxDxMessageFactory#createMultimediaAuthenticationRequest()
*/
public MultimediaAuthenticationRequest createMultimediaAuthenticationRequest() {
try {
return (MultimediaAuthenticationRequest) createCxDxMessage(null, EMPTY_AVP_ARRAY, MultimediaAuthenticationRequest.COMMAND_CODE, cxdxAppId);
}
catch (InternalException e) {
logger.error("Failed to create Multimedia-Authentication-Request", e);
}
return null;
}
/* (non-Javadoc)
* @see net.java.slee.resource.diameter.cxdx.CxDxMessageFactory#createMultimediaAuthenticationRequest(java.lang.String)
*/
public MultimediaAuthenticationRequest createMultimediaAuthenticationRequest(String sessionId) throws IllegalArgumentException {
MultimediaAuthenticationRequest mar = createMultimediaAuthenticationRequest();
mar.setSessionId(sessionId);
return mar;
}
/* (non-Javadoc)
* @see net.java.slee.resource.diameter.cxdx.CxDxMessageFactory#createPushProfileRequest()
*/
public PushProfileRequest createPushProfileRequest() {
try {
return (PushProfileRequest) createCxDxMessage(null, EMPTY_AVP_ARRAY, PushProfileRequest.COMMAND_CODE, cxdxAppId);
}
catch (InternalException e) {
logger.error("Failed to create Push-Profile-Request", e);
}
return null;
}
/* (non-Javadoc)
* @see net.java.slee.resource.diameter.cxdx.CxDxMessageFactory#createPushProfileRequest(java.lang.String)
*/
public PushProfileRequest createPushProfileRequest(String sessionId) throws IllegalArgumentException {
PushProfileRequest ppr = createPushProfileRequest();
ppr.setSessionId(sessionId);
return ppr;
}
/* (non-Javadoc)
* @see net.java.slee.resource.diameter.cxdx.CxDxMessageFactory#createRegistrationTerminationRequest()
*/
public RegistrationTerminationRequest createRegistrationTerminationRequest() {
try {
return (RegistrationTerminationRequest) createCxDxMessage(null, EMPTY_AVP_ARRAY, RegistrationTerminationRequest.COMMAND_CODE, cxdxAppId);
}
catch (InternalException e) {
logger.error("Failed to create Registration-Termination-Request", e);
}
return null;
}
/* (non-Javadoc)
* @see net.java.slee.resource.diameter.cxdx.CxDxMessageFactory#createRegistrationTerminationRequest(java.lang.String)
*/
public RegistrationTerminationRequest createRegistrationTerminationRequest(String sessionId) throws IllegalArgumentException {
RegistrationTerminationRequest rtr = createRegistrationTerminationRequest();
rtr.setSessionId(sessionId);
return rtr;
}
/* (non-Javadoc)
* @see net.java.slee.resource.diameter.cxdx.CxDxMessageFactory#createServerAssignmentRequest()
*/
public ServerAssignmentRequest createServerAssignmentRequest() {
try {
return (ServerAssignmentRequest) createCxDxMessage(null, EMPTY_AVP_ARRAY, ServerAssignmentRequest.COMMAND_CODE, cxdxAppId);
}
catch (InternalException e) {
logger.error("Failed to create Server-Assignment-Request", e);
}
return null;
}
/* (non-Javadoc)
* @see net.java.slee.resource.diameter.cxdx.CxDxMessageFactory#createServerAssignmentRequest(java.lang.String)
*/
public ServerAssignmentRequest createServerAssignmentRequest(String sessionId) throws IllegalArgumentException {
ServerAssignmentRequest sar = createServerAssignmentRequest();
sar.setSessionId(sessionId);
return sar;
}
/* (non-Javadoc)
* @see net.java.slee.resource.diameter.cxdx.CxDxMessageFactory#createUserAuthorizationRequest()
*/
public UserAuthorizationRequest createUserAuthorizationRequest() {
try {
return (UserAuthorizationRequest) createCxDxMessage(null, EMPTY_AVP_ARRAY, UserAuthorizationRequest.COMMAND_CODE, cxdxAppId);
}
catch (InternalException e) {
logger.error("Failed to create User-Authorization-Request", e);
}
return null;
}
/* (non-Javadoc)
* @see net.java.slee.resource.diameter.cxdx.CxDxMessageFactory#createUserAuthorizationRequest(java.lang.String)
*/
public UserAuthorizationRequest createUserAuthorizationRequest(String sessionId) throws IllegalArgumentException {
UserAuthorizationRequest uar = createUserAuthorizationRequest();
uar.setSessionId(sessionId);
return uar;
}
@Override
public DiameterMessageFactory getBaseMessageFactory()
{
return baseFactory;
}
/**
* Creates a CxDx Message with specified command-code and avps filled. If a header is present an answer will be created, if not
* it will generate a request.
*
* @param diameterHeader
* @param avps
* @param _commandCode
* @param appId
* @return
* @throws InternalException
*/
DiameterMessage createCxDxMessage(DiameterHeader diameterHeader, DiameterAvp[] avps, int _commandCode, ApplicationId appId) throws InternalException {
boolean creatingRequest = diameterHeader == null;
Message msg = null;
if (!creatingRequest) {
Message raw = createMessage(diameterHeader, avps, 0, appId);
raw.setProxiable(diameterHeader.isProxiable());
raw.setRequest(false);
+ raw.setReTransmitted(false); // just in case. answers never have T flag set
msg = raw;
}
else {
Message raw = createMessage(diameterHeader, avps, _commandCode, appId);
raw.setProxiable(true);
raw.setRequest(true);
msg = raw;
}
if (msg.getAvps().getAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID) == null) {
try {
DiameterAvp avpVendorId = this.baseAvpFactory.createAvp(Avp.VENDOR_ID, DiameterCxDxAvpCodes.CXDX_VENDOR_ID);
DiameterAvp avpAcctApplicationId = this.baseAvpFactory.createAvp(Avp.AUTH_APPLICATION_ID, DiameterCxDxAvpCodes.CXDX_AUTH_APP_ID);
DiameterAvp vendorSpecific = this.baseAvpFactory.createAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, new DiameterAvp[] { avpVendorId, avpAcctApplicationId });
msg.getAvps().addAvp(vendorSpecific.getCode(), vendorSpecific.byteArrayValue());
}
catch(NoSuchAvpException nsae) {
logger.error("Failed to create AVPs", nsae);
}
}
int commandCode = creatingRequest ? _commandCode : diameterHeader.getCommandCode();
DiameterMessage diamMessage = null;
switch (commandCode) {
case LocationInfoRequest.COMMAND_CODE:
diamMessage = creatingRequest ? new LocationInfoRequestImpl(msg) : new LocationInfoAnswerImpl(msg);
break;
case MultimediaAuthenticationRequest.COMMAND_CODE:
diamMessage = creatingRequest ? new MultimediaAuthenticationRequestImpl(msg) : new MultimediaAuthenticationAnswerImpl(msg);
break;
case PushProfileRequest.COMMAND_CODE:
diamMessage = creatingRequest ? new PushProfileRequestImpl(msg) : new PushProfileAnswerImpl(msg);
break;
case RegistrationTerminationRequest.COMMAND_CODE:
diamMessage = creatingRequest ? new RegistrationTerminationRequestImpl(msg) : new RegistrationTerminationAnswerImpl(msg);
break;
case ServerAssignmentRequest.COMMAND_CODE:
diamMessage = creatingRequest ? new ServerAssignmentRequestImpl(msg) : new ServerAssignmentAnswerImpl(msg);
break;
case UserAuthorizationRequest.COMMAND_CODE:
diamMessage = creatingRequest ? new UserAuthorizationRequestImpl(msg) : new UserAuthorizationAnswerImpl(msg);
break;
default:
diamMessage = new ExtensionDiameterMessageImpl(msg);
}
// Finally, add Origin-Host and Origin-Realm, if not present.
// FIXME: Alex: needed? addOriginHostAndRealm(diamMessage);
if (!diamMessage.hasSessionId() && session != null) {
diamMessage.setSessionId(session.getSessionId());
}
return diamMessage;
}
}
| true | true | DiameterMessage createCxDxMessage(DiameterHeader diameterHeader, DiameterAvp[] avps, int _commandCode, ApplicationId appId) throws InternalException {
boolean creatingRequest = diameterHeader == null;
Message msg = null;
if (!creatingRequest) {
Message raw = createMessage(diameterHeader, avps, 0, appId);
raw.setProxiable(diameterHeader.isProxiable());
raw.setRequest(false);
msg = raw;
}
else {
Message raw = createMessage(diameterHeader, avps, _commandCode, appId);
raw.setProxiable(true);
raw.setRequest(true);
msg = raw;
}
if (msg.getAvps().getAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID) == null) {
try {
DiameterAvp avpVendorId = this.baseAvpFactory.createAvp(Avp.VENDOR_ID, DiameterCxDxAvpCodes.CXDX_VENDOR_ID);
DiameterAvp avpAcctApplicationId = this.baseAvpFactory.createAvp(Avp.AUTH_APPLICATION_ID, DiameterCxDxAvpCodes.CXDX_AUTH_APP_ID);
DiameterAvp vendorSpecific = this.baseAvpFactory.createAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, new DiameterAvp[] { avpVendorId, avpAcctApplicationId });
msg.getAvps().addAvp(vendorSpecific.getCode(), vendorSpecific.byteArrayValue());
}
catch(NoSuchAvpException nsae) {
logger.error("Failed to create AVPs", nsae);
}
}
int commandCode = creatingRequest ? _commandCode : diameterHeader.getCommandCode();
DiameterMessage diamMessage = null;
switch (commandCode) {
case LocationInfoRequest.COMMAND_CODE:
diamMessage = creatingRequest ? new LocationInfoRequestImpl(msg) : new LocationInfoAnswerImpl(msg);
break;
case MultimediaAuthenticationRequest.COMMAND_CODE:
diamMessage = creatingRequest ? new MultimediaAuthenticationRequestImpl(msg) : new MultimediaAuthenticationAnswerImpl(msg);
break;
case PushProfileRequest.COMMAND_CODE:
diamMessage = creatingRequest ? new PushProfileRequestImpl(msg) : new PushProfileAnswerImpl(msg);
break;
case RegistrationTerminationRequest.COMMAND_CODE:
diamMessage = creatingRequest ? new RegistrationTerminationRequestImpl(msg) : new RegistrationTerminationAnswerImpl(msg);
break;
case ServerAssignmentRequest.COMMAND_CODE:
diamMessage = creatingRequest ? new ServerAssignmentRequestImpl(msg) : new ServerAssignmentAnswerImpl(msg);
break;
case UserAuthorizationRequest.COMMAND_CODE:
diamMessage = creatingRequest ? new UserAuthorizationRequestImpl(msg) : new UserAuthorizationAnswerImpl(msg);
break;
default:
diamMessage = new ExtensionDiameterMessageImpl(msg);
}
// Finally, add Origin-Host and Origin-Realm, if not present.
// FIXME: Alex: needed? addOriginHostAndRealm(diamMessage);
if (!diamMessage.hasSessionId() && session != null) {
diamMessage.setSessionId(session.getSessionId());
}
return diamMessage;
}
| DiameterMessage createCxDxMessage(DiameterHeader diameterHeader, DiameterAvp[] avps, int _commandCode, ApplicationId appId) throws InternalException {
boolean creatingRequest = diameterHeader == null;
Message msg = null;
if (!creatingRequest) {
Message raw = createMessage(diameterHeader, avps, 0, appId);
raw.setProxiable(diameterHeader.isProxiable());
raw.setRequest(false);
raw.setReTransmitted(false); // just in case. answers never have T flag set
msg = raw;
}
else {
Message raw = createMessage(diameterHeader, avps, _commandCode, appId);
raw.setProxiable(true);
raw.setRequest(true);
msg = raw;
}
if (msg.getAvps().getAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID) == null) {
try {
DiameterAvp avpVendorId = this.baseAvpFactory.createAvp(Avp.VENDOR_ID, DiameterCxDxAvpCodes.CXDX_VENDOR_ID);
DiameterAvp avpAcctApplicationId = this.baseAvpFactory.createAvp(Avp.AUTH_APPLICATION_ID, DiameterCxDxAvpCodes.CXDX_AUTH_APP_ID);
DiameterAvp vendorSpecific = this.baseAvpFactory.createAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, new DiameterAvp[] { avpVendorId, avpAcctApplicationId });
msg.getAvps().addAvp(vendorSpecific.getCode(), vendorSpecific.byteArrayValue());
}
catch(NoSuchAvpException nsae) {
logger.error("Failed to create AVPs", nsae);
}
}
int commandCode = creatingRequest ? _commandCode : diameterHeader.getCommandCode();
DiameterMessage diamMessage = null;
switch (commandCode) {
case LocationInfoRequest.COMMAND_CODE:
diamMessage = creatingRequest ? new LocationInfoRequestImpl(msg) : new LocationInfoAnswerImpl(msg);
break;
case MultimediaAuthenticationRequest.COMMAND_CODE:
diamMessage = creatingRequest ? new MultimediaAuthenticationRequestImpl(msg) : new MultimediaAuthenticationAnswerImpl(msg);
break;
case PushProfileRequest.COMMAND_CODE:
diamMessage = creatingRequest ? new PushProfileRequestImpl(msg) : new PushProfileAnswerImpl(msg);
break;
case RegistrationTerminationRequest.COMMAND_CODE:
diamMessage = creatingRequest ? new RegistrationTerminationRequestImpl(msg) : new RegistrationTerminationAnswerImpl(msg);
break;
case ServerAssignmentRequest.COMMAND_CODE:
diamMessage = creatingRequest ? new ServerAssignmentRequestImpl(msg) : new ServerAssignmentAnswerImpl(msg);
break;
case UserAuthorizationRequest.COMMAND_CODE:
diamMessage = creatingRequest ? new UserAuthorizationRequestImpl(msg) : new UserAuthorizationAnswerImpl(msg);
break;
default:
diamMessage = new ExtensionDiameterMessageImpl(msg);
}
// Finally, add Origin-Host and Origin-Realm, if not present.
// FIXME: Alex: needed? addOriginHostAndRealm(diamMessage);
if (!diamMessage.hasSessionId() && session != null) {
diamMessage.setSessionId(session.getSessionId());
}
return diamMessage;
}
|
diff --git a/nuxeo-social-workspace/nuxeo-social-workspace-gadgets/src/test/java/org/nuxeo/ecm/social/workspace/gadgets/TestSocialWorkspaceMembersOperation.java b/nuxeo-social-workspace/nuxeo-social-workspace-gadgets/src/test/java/org/nuxeo/ecm/social/workspace/gadgets/TestSocialWorkspaceMembersOperation.java
index fdd12d5f..9e2ebc5a 100644
--- a/nuxeo-social-workspace/nuxeo-social-workspace-gadgets/src/test/java/org/nuxeo/ecm/social/workspace/gadgets/TestSocialWorkspaceMembersOperation.java
+++ b/nuxeo-social-workspace/nuxeo-social-workspace-gadgets/src/test/java/org/nuxeo/ecm/social/workspace/gadgets/TestSocialWorkspaceMembersOperation.java
@@ -1,169 +1,169 @@
/*
* (C) Copyright 2011 Nuxeo SA (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* eugen
*/
package org.nuxeo.ecm.social.workspace.gadgets;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.nuxeo.ecm.social.workspace.SocialConstants.SOCIAL_WORKSPACE_TYPE;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.nuxeo.ecm.automation.AutomationService;
import org.nuxeo.ecm.automation.OperationChain;
import org.nuxeo.ecm.automation.OperationContext;
import org.nuxeo.ecm.automation.OperationParameters;
import org.nuxeo.ecm.core.api.Blob;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.event.EventServiceAdmin;
import org.nuxeo.ecm.core.test.CoreFeature;
import org.nuxeo.ecm.core.test.DefaultRepositoryInit;
import org.nuxeo.ecm.core.test.annotations.BackendType;
import org.nuxeo.ecm.core.test.annotations.Granularity;
import org.nuxeo.ecm.core.test.annotations.RepositoryConfig;
import org.nuxeo.ecm.platform.usermanager.UserManager;
import org.nuxeo.ecm.social.workspace.adapters.SocialWorkspace;
import org.nuxeo.runtime.test.runner.Deploy;
import org.nuxeo.runtime.test.runner.Features;
import org.nuxeo.runtime.test.runner.FeaturesRunner;
import org.nuxeo.runtime.test.runner.LocalDeploy;
import com.google.inject.Inject;
/**
* @author <a href="mailto:[email protected]">Eugen Ionica</a>
*
*/
@RunWith(FeaturesRunner.class)
@Features(CoreFeature.class)
@RepositoryConfig(type = BackendType.H2, init = DefaultRepositoryInit.class, user = "Administrator", cleanup = Granularity.METHOD)
@Deploy({
"org.nuxeo.ecm.platform.api",
"org.nuxeo.ecm.platform.dublincore",
"org.nuxeo.ecm.directory",
"org.nuxeo.ecm.directory.sql",
"org.nuxeo.ecm.directory.types.contrib",
"org.nuxeo.ecm.platform.usermanager.api",
"org.nuxeo.ecm.platform.usermanager",
"org.nuxeo.ecm.platform.content.template",
"org.nuxeo.ecm.opensocial.spaces",
"org.nuxeo.ecm.platform.types.api",
"org.nuxeo.ecm.platform.types.core",
"org.nuxeo.ecm.automation.core",
"org.nuxeo.ecm.core.persistence",
"org.nuxeo.ecm.platform.url.api",
"org.nuxeo.ecm.platform.url.core",
"org.nuxeo.ecm.platform.ui:OSGI-INF/urlservice-framework.xml",
"org.nuxeo.ecm.user.center:OSGI-INF/urlservice-contrib.xml",
"org.nuxeo.ecm.platform.userworkspace.types",
"org.nuxeo.ecm.platform.userworkspace.api",
"org.nuxeo.ecm.platform.userworkspace.core",
"org.nuxeo.ecm.user.center.profile",
"org.nuxeo.ecm.activity",
"org.nuxeo.ecm.automation.features",
"org.nuxeo.ecm.platform.query.api",
"org.nuxeo.ecm.social.workspace.core",
"org.nuxeo.ecm.platform.content.template",
"org.nuxeo.ecm.user.relationships",
"org.nuxeo.ecm.social.workspace.gadgets",
"org.nuxeo.ecm.platform.test:test-usermanagerimpl/directory-config.xml",
"org.nuxeo.ecm.platform.picture.core:OSGI-INF/picturebook-schemas-contrib.xml" })
@LocalDeploy({
"org.nuxeo.ecm.user.relationships:test-user-relationship-directories-contrib.xml",
"org.nuxeo.ecm.social.workspace.core:social-workspace-test.xml" })
public class TestSocialWorkspaceMembersOperation {
@Inject
protected CoreSession session;
@Inject
protected UserManager userManager;
@Inject
protected EventServiceAdmin eventServiceAdmin;
@Inject
AutomationService automationService;
DocumentModel socialWorkspaceDocument;
SocialWorkspace socialWorkspace;
@Before
public void disableActivityStreamListener() {
eventServiceAdmin.setListenerEnabledFlag("activityStreamListener",
false);
}
@Before
public void setup() throws Exception {
// create social workspace
socialWorkspaceDocument = session.createDocumentModel("/",
"testSocialWorkspace", SOCIAL_WORKSPACE_TYPE);
socialWorkspaceDocument = session.createDocument(socialWorkspaceDocument);
socialWorkspace = socialWorkspaceDocument.getAdapter(SocialWorkspace.class);
assertNotNull(socialWorkspace);
// create a user
DocumentModel testUser = userManager.getBareUserModel();
String schemaName = userManager.getUserSchemaName();
testUser.setPropertyValue(schemaName + ":username", "testUser");
testUser.setPropertyValue(schemaName + ":firstName",
"testUser_firstName");
testUser.setPropertyValue(schemaName + ":lastName", "testUser_lastName");
userManager.createUser(testUser);
assertNotNull(userManager.getPrincipal("testUser"));
// make the user member of SocialWorkspace
socialWorkspace.addMember(userManager.getPrincipal("testUser"));
session.save();
}
@Test
public void testOperation() throws Exception {
List<String> list = socialWorkspace.searchMembers("t%");
assertEquals(1, list.size());
OperationContext ctx = new OperationContext(session);
assertNotNull(ctx);
OperationChain chain = new OperationChain("fakeChain");
OperationParameters oParams = new OperationParameters(
GetSocialWorkspaceMembers.ID);
oParams.set("pattern", "testU%");
oParams.set("page", 0);
- oParams.set("limit", 5);
+ oParams.set("pageSize", 5);
oParams.set("contextPath", "/testSocialWorkspace");
chain.add(oParams);
Blob result = (Blob) automationService.run(ctx, chain);
JSONObject o = JSONObject.fromObject(result.getString());
JSONArray array = (JSONArray) o.get("users");
assertEquals(1, array.size());
assertEquals("testUser_firstName",
((JSONObject) array.get(0)).get("firstName"));
assertEquals("testUser_lastName",
((JSONObject) array.get(0)).get("lastName"));
}
}
| true | true | public void testOperation() throws Exception {
List<String> list = socialWorkspace.searchMembers("t%");
assertEquals(1, list.size());
OperationContext ctx = new OperationContext(session);
assertNotNull(ctx);
OperationChain chain = new OperationChain("fakeChain");
OperationParameters oParams = new OperationParameters(
GetSocialWorkspaceMembers.ID);
oParams.set("pattern", "testU%");
oParams.set("page", 0);
oParams.set("limit", 5);
oParams.set("contextPath", "/testSocialWorkspace");
chain.add(oParams);
Blob result = (Blob) automationService.run(ctx, chain);
JSONObject o = JSONObject.fromObject(result.getString());
JSONArray array = (JSONArray) o.get("users");
assertEquals(1, array.size());
assertEquals("testUser_firstName",
((JSONObject) array.get(0)).get("firstName"));
assertEquals("testUser_lastName",
((JSONObject) array.get(0)).get("lastName"));
}
| public void testOperation() throws Exception {
List<String> list = socialWorkspace.searchMembers("t%");
assertEquals(1, list.size());
OperationContext ctx = new OperationContext(session);
assertNotNull(ctx);
OperationChain chain = new OperationChain("fakeChain");
OperationParameters oParams = new OperationParameters(
GetSocialWorkspaceMembers.ID);
oParams.set("pattern", "testU%");
oParams.set("page", 0);
oParams.set("pageSize", 5);
oParams.set("contextPath", "/testSocialWorkspace");
chain.add(oParams);
Blob result = (Blob) automationService.run(ctx, chain);
JSONObject o = JSONObject.fromObject(result.getString());
JSONArray array = (JSONArray) o.get("users");
assertEquals(1, array.size());
assertEquals("testUser_firstName",
((JSONObject) array.get(0)).get("firstName"));
assertEquals("testUser_lastName",
((JSONObject) array.get(0)).get("lastName"));
}
|
diff --git a/src/org/zwobble/shed/parser/parsing/Parser.java b/src/org/zwobble/shed/parser/parsing/Parser.java
index e772adb..bc33ef6 100644
--- a/src/org/zwobble/shed/parser/parsing/Parser.java
+++ b/src/org/zwobble/shed/parser/parsing/Parser.java
@@ -1,131 +1,131 @@
package org.zwobble.shed.parser.parsing;
import java.util.List;
import org.zwobble.shed.parser.parsing.nodes.ExpressionNode;
import org.zwobble.shed.parser.parsing.nodes.ImmutableVariableNode;
import org.zwobble.shed.parser.parsing.nodes.ImportNode;
import org.zwobble.shed.parser.parsing.nodes.MutableVariableNode;
import org.zwobble.shed.parser.parsing.nodes.PackageDeclarationNode;
import org.zwobble.shed.parser.parsing.nodes.SourceNode;
import org.zwobble.shed.parser.tokeniser.Keyword;
import static org.zwobble.shed.parser.parsing.Expressions.expression;
import static org.zwobble.shed.parser.parsing.Result.success;
import static org.zwobble.shed.parser.parsing.Rules.guard;
import static org.zwobble.shed.parser.parsing.Rules.keyword;
import static org.zwobble.shed.parser.parsing.Rules.last;
import static org.zwobble.shed.parser.parsing.Rules.oneOrMoreWithSeparator;
import static org.zwobble.shed.parser.parsing.Rules.optional;
import static org.zwobble.shed.parser.parsing.Rules.sequence;
import static org.zwobble.shed.parser.parsing.Rules.symbol;
import static org.zwobble.shed.parser.parsing.Rules.then;
import static org.zwobble.shed.parser.parsing.Rules.tokenOfType;
import static org.zwobble.shed.parser.parsing.Rules.whitespace;
import static org.zwobble.shed.parser.parsing.Rules.zeroOrMoreWithSeparator;
import static org.zwobble.shed.parser.tokeniser.Keyword.IMPORT;
import static org.zwobble.shed.parser.tokeniser.Keyword.PACKAGE;
import static org.zwobble.shed.parser.tokeniser.TokenType.IDENTIFIER;
public class Parser {
public Rule<SourceNode> source() {
final Rule<PackageDeclarationNode> packageDeclaration;
final Rule<List<ImportNode>> imports;
return then(
sequence(OnError.CONTINUE,
packageDeclaration = packageDeclaration(),
optional(whitespace()),
imports = zeroOrMoreWithSeparator(importNode(), whitespace())
),
new ParseAction<RuleValues, SourceNode>() {
@Override
public Result<SourceNode> apply(RuleValues result) {
return success(new SourceNode(result.get(packageDeclaration), result.get(imports)));
}
}
);
}
public Rule<PackageDeclarationNode> packageDeclaration() {
final Rule<List<String>> names;
return then(
sequence(OnError.FINISH,
keyword(PACKAGE),
whitespace(),
names = dotSeparatedIdentifiers(),
last(symbol(";"))
),
new ParseAction<RuleValues, PackageDeclarationNode>() {
@Override
public Result<PackageDeclarationNode> apply(RuleValues result) {
return success(new PackageDeclarationNode(result.get(names)));
}
}
);
}
public Rule<ImportNode> importNode() {
final Rule<List<String>> names;
return then(
sequence(OnError.FINISH,
guard(keyword(IMPORT)),
whitespace(),
(names = dotSeparatedIdentifiers()),
last(symbol(";"))
),
new ParseAction<RuleValues, ImportNode>() {
@Override
public Result<ImportNode> apply(RuleValues result) {
return success(new ImportNode(result.get(names)));
}
}
);
}
public Rule<ImmutableVariableNode> immutableVariable() {
return variable(Keyword.VAL, new VariableNodeConstructor<ImmutableVariableNode>() {
@Override
public ImmutableVariableNode apply(String identifier, ExpressionNode expression) {
return new ImmutableVariableNode(identifier, expression);
}
});
}
public Rule<MutableVariableNode> mutableVariable() {
return variable(Keyword.VAR, new VariableNodeConstructor<MutableVariableNode>() {
@Override
public MutableVariableNode apply(String identifier, ExpressionNode expression) {
return new MutableVariableNode(identifier, expression);
}
});
}
private <T> Rule<T> variable(Keyword keyword, final VariableNodeConstructor<T> constructor) {
final Rule<String> identifier = tokenOfType(IDENTIFIER);
final Rule<? extends ExpressionNode> expression = expression();
return then(
- sequence(OnError.CONTINUE,
+ sequence(OnError.FINISH,
guard(keyword(keyword)), whitespace(),
identifier, optional(whitespace()),
symbol("="), optional(whitespace()),
expression, optional(whitespace()),
- symbol(";")
+ last(symbol(";"))
),
new ParseAction<RuleValues, T>() {
@Override
public Result<T> apply(RuleValues result) {
return success(constructor.apply(result.get(identifier), result.get(expression)));
}
}
);
}
private Rule<List<String>> dotSeparatedIdentifiers() {
return oneOrMoreWithSeparator(tokenOfType(IDENTIFIER), symbol("."));
}
private interface VariableNodeConstructor<T> {
T apply(String identifier, ExpressionNode expression);
}
}
| false | true | private <T> Rule<T> variable(Keyword keyword, final VariableNodeConstructor<T> constructor) {
final Rule<String> identifier = tokenOfType(IDENTIFIER);
final Rule<? extends ExpressionNode> expression = expression();
return then(
sequence(OnError.CONTINUE,
guard(keyword(keyword)), whitespace(),
identifier, optional(whitespace()),
symbol("="), optional(whitespace()),
expression, optional(whitespace()),
symbol(";")
),
new ParseAction<RuleValues, T>() {
@Override
public Result<T> apply(RuleValues result) {
return success(constructor.apply(result.get(identifier), result.get(expression)));
}
}
);
}
| private <T> Rule<T> variable(Keyword keyword, final VariableNodeConstructor<T> constructor) {
final Rule<String> identifier = tokenOfType(IDENTIFIER);
final Rule<? extends ExpressionNode> expression = expression();
return then(
sequence(OnError.FINISH,
guard(keyword(keyword)), whitespace(),
identifier, optional(whitespace()),
symbol("="), optional(whitespace()),
expression, optional(whitespace()),
last(symbol(";"))
),
new ParseAction<RuleValues, T>() {
@Override
public Result<T> apply(RuleValues result) {
return success(constructor.apply(result.get(identifier), result.get(expression)));
}
}
);
}
|
diff --git a/CornerstoneCommon/src/main/java/com/paxxis/cornerstone/common/CornerstoneConfigurable.java b/CornerstoneCommon/src/main/java/com/paxxis/cornerstone/common/CornerstoneConfigurable.java
index 094cc14..efec9fa 100644
--- a/CornerstoneCommon/src/main/java/com/paxxis/cornerstone/common/CornerstoneConfigurable.java
+++ b/CornerstoneCommon/src/main/java/com/paxxis/cornerstone/common/CornerstoneConfigurable.java
@@ -1,484 +1,484 @@
/*
* Copyright 2010 the original author or authors.
* Copyright 2009 Paxxis Technology LLC
*
* 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.paxxis.cornerstone.common;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.log4j.Logger;
/**
*
* @author Robert Englander
*/
public abstract class CornerstoneConfigurable implements IManagedBean {
public interface ChangeListener {
public void onChange(String propName, Object value);
}
private static final Logger logger = Logger.getLogger(CornerstoneConfigurable.class);
private ArrayList<ChangeListener> listeners = new ArrayList<ChangeListener>();
/** the configuration object to use to populate property values */
private CornerstoneConfiguration _configuration = null;
/** contains a mapping of property names to configuration values */
private HashMap<String, Object> _propertyMap = new HashMap<String, Object>();
/** flag indicating if this instance should register for changes */
private boolean registerForChanges = true;
//this is for dynamically finding config properties for objects based on a configured prefix
//for example a bean could have two prefixes defined - global, myBeanName - in that order
//in the db one can add values like global.propName=defaultGlobalValue and
//myBeanName.propName=specificValue and the bean will be configured with myBeanName.propName
//as that was the last defined prefix...
private Collection<String> configPropertyPrefixes = new ArrayList<String>();
/** a prefix found in system variables to prepend onto any supplied prefixes */
private String configSystemPrefix = null;
/** get properties directly from system variables based on prefixes */
private boolean useSystemProperties = false;
public CornerstoneConfigurable() {
}
public void addConfigurableListener(ChangeListener listener) {
synchronized (listeners) {
if (!listeners.contains(listener)) {
listeners.add(listener);
}
}
}
public void removeConfigurableListener(ChangeListener listener) {
synchronized (listeners) {
listeners.remove(listener);
}
}
public void setConfigurationPropertyMap(Map<String, ?> localMap) {
_propertyMap.putAll(localMap);
}
/**
* Get the config items WITHOUT any prefixes which results in
* a single view of the config - later defined items override earlier defined ones
* so if a Configurable has defined two prefixes, global and myBeanName, in that order
* a config item of global.propName will be overriden by myBeanName.propName
*
* @return
*/
public Map<String, Object> getPrefixedConfigurationValues() {
Collection<Map<String, Object>> allConfigItems = getAllPrefixedConfigurationValues();
if (allConfigItems.isEmpty()) {
return Collections.<String, Object>emptyMap();
}
Iterator<String> prefixes = configPropertyPrefixes.iterator();
Iterator<Map<String, Object>> items = allConfigItems.iterator();
Map<String, Object> configItems = new HashMap<String, Object>();
while (prefixes.hasNext()) {
String prefix = prefixes.next();
for (Map.Entry<String, Object> item : items.next().entrySet()) {
//all config items are put into map WITHOUT the prefix + '.' resulting in
//a single view of the config - later defined items override earlier defined ones
//so if a Configurable has defined two prefixes, global and myBeanName, in that order
//a config item of global.propName will be overriden by myBeanName.propName
Object prev = configItems.put(item.getKey().substring(prefix.length()+1), item.getValue());
if (prev != null && logger.isDebugEnabled()) {
logger.debug(
"Config item " +
item.getKey() +
" with value " +
item.getValue() +
" has overriden previous value " +
prev);
}
}
}
return configItems;
}
protected Collection<Map<String, Object>> getAllPrefixedConfigurationValues() {
CornerstoneConfiguration config = getCornerstoneConfiguration();
if (config == null || configPropertyPrefixes.isEmpty()) {
return Collections.<Map<String, Object>>emptyList();
}
Collection<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
for (String prefix : configPropertyPrefixes) {
Map<String, Object> configItems = new HashMap<String, Object>();
configItems.putAll(config.findParameters(prefix + "."));
results.add(configItems);
}
return results;
}
@SuppressWarnings("unchecked")
private <T> T getConfigurationValue(String propName, T defaultValue, Collection<String> prefixes) {
CornerstoneConfiguration config = getCornerstoneConfiguration();
if (config == null || prefixes.isEmpty()) {
return defaultValue;
}
String configPropName = null;
Object value = null;
for (String prefix : prefixes) {
configPropName = prefix + "." + propName;
//the last prefix defined always overrides previous config items...
Object temp = config.getObjectValue(configPropName);
if (temp != null) {
if (value != null && logger.isDebugEnabled()) {
logger.debug(
"Config item " +
configPropName +
" with value " +
temp +
" has overriden previous value " +
value);
}
value = temp;
}
}
if (value == null) {
return defaultValue;
}
if (defaultValue != null) {
value = convert(defaultValue.getClass(), value);
}
if (registerForChanges) {
//only bother putting a dynamically found property in the map if we are registered
//for changes AND we have a config property for it in the database - never seen
//before config properties added to the database will still be picked up in the onChange
_propertyMap.put(propName, configPropName);
}
return (T) value;
}
public void onChange(String configPropName) {
// the actual property name we want is the key mapped to this configPropName.
// we don't support this for non string mappings (yet).
Collection<String> props = new ArrayList<String>();
for (String key : _propertyMap.keySet()) {
Object obj = _propertyMap.get(key);
if (obj instanceof String) {
String value = (String)obj;
if (value.equals(configPropName)) {
props.add(key);
}
}
}
for (String prefix : configPropertyPrefixes) {
//lets see if the propName starts with any of our defined prefixes..
if (configPropName.startsWith(prefix) && configPropName.charAt(prefix.length()) == '.') {
//it does so lets add it to the list to be configured and also add it to our
//property map so loadConfigurationPropertyValues will find it...
//NOTE: this logic will only happen if a property was ADDED to the database
//post startup - if the item was in the db on startup it will already be in propertyMap
//due to being found via reflectConfigurationPropertyValues which ran in initialization
String property = configPropName.substring(prefix.length());
props.add(property);
_propertyMap.put(property, configPropName);
}
}
props.add(configPropName); //why do we do this?
loadConfigurationPropertyValues(props, true);
}
protected void reflectConfigurationPropertyValues() {
CornerstoneConfiguration config = getCornerstoneConfiguration();
Collection<String> prefixes = getConfigPropertyPrefixes();
if (config == null || prefixes == null || prefixes.isEmpty()) {
return;
}
// add any prefixes from the system prefix to the end of the list
if (configSystemPrefix != null) {
String prefix = System.getProperty(configSystemPrefix);
List<String> list = new ArrayList<String>();
if (prefix != null) {
for (String pref : prefixes) {
list.add(prefix + "." + pref);
}
}
prefixes.addAll(list);
}
Map<String, String> systemProps = new HashMap<String, String>();
if (useSystemProperties) {
- for (String prefix : this.configPropertyPrefixes) {
+ for (String prefix : prefixes) {
Properties properties = System.getProperties();
Set<Object> propNames = properties.keySet();
for (Object obj : propNames) {
String pName = obj.toString();
if (pName.startsWith(prefix + ".")) {
String value = System.getProperty(pName);
String shortName = pName.substring(prefix.length() + 1);
systemProps.put(shortName, value);
}
}
}
}
Method[] methods = this.getClass().getMethods();
for (Method method : methods) {
String methodName = method.getName();
if (!methodName.startsWith("set") || methodName.length() < 5) {
//not a set method or not a property that is at least 2 letters long
//(ie. methods with names like setZ will not be looked at)
continue;
}
Class<?>[] params = method.getParameterTypes();
if (params.length != 1) {
continue;
}
//looks like we found a setter method, lets look for a value now...
String propName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4);
// if there is a system variable with this name, we use that value instead of what's in the config
Object value = systemProps.get(propName);
if (value == null) {
value = getConfigurationValue(propName, null, prefixes);
}
if (value == null) {
continue;
}
try {
method.invoke(this, convert(params[0], value));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
/**
* Load property values from the configuration.
*/
private void loadConfigurationPropertyValues(Collection<String> props, boolean changes) {
CornerstoneConfiguration config = getCornerstoneConfiguration();
if (config == null) {
return;
}
Method[] methods = this.getClass().getMethods();
for (String propName : props) {
Object configObject = _propertyMap.get(propName);
if (configObject == null) {
continue;
}
Object value = null;
if (configObject instanceof List<?>) {
List<String> valueList = new ArrayList<String>();
List<?> configList = (List<?>)configObject;
for (Object o : configList) {
String v = config.getStringValue(o.toString(), "");
valueList.add(v);
}
value = valueList;
} else {
value = config.getObjectValue(configObject.toString());
}
if (value == null) {
continue;
}
if (changes) {
// inform the registered listeners
List<ChangeListener> list = new ArrayList<ChangeListener>();
synchronized (listeners) {
list.addAll(listeners);
}
for (ChangeListener listener : list) {
listener.onChange(propName, value);
}
}
// get the setter
String firstLetter = propName.substring(0, 1).toUpperCase();
String setterName = "set" + firstLetter + propName.substring(1);
for (Method method : methods) {
if (!method.getName().equals(setterName)) {
continue;
}
Class<?>[] paramClasses = method.getParameterTypes();
if (paramClasses.length == 1) {
// this is the one we want, so convert the value to this type
Object objValue = convert(paramClasses[0], value);
try {
method.invoke(this, objValue);
} catch (Exception e) {
throw new RuntimeException(e);
}
break;
}
} //for (Method method : methods)
} //for (String propName : props)
}
@SuppressWarnings("rawtypes")
private Object convert(Class cls, Object value) {
Object objValue = null;
if (cls.getName().equals("java.lang.String")) {
objValue = String.valueOf(value);
} else if (cls.getName().equals("int")) {
objValue = Integer.valueOf(value.toString());
} else if (cls.getName().equals("long")) {
objValue = Long.valueOf(value.toString());
} else if (cls.getName().equals("float")) {
objValue = Float.valueOf(value.toString());
} else if (cls.getName().equals("double")) {
objValue = Double.valueOf(value.toString());
} else if (cls.getName().equals("boolean")) {
objValue = Boolean.valueOf(value.toString());
} else if (cls.getName().equals("java.util.List")) {
objValue = value;
} else {
//this covers any class (Enums most importantly) that has
//a static valueOf(java.lang.String) method
try {
@SuppressWarnings("unchecked")
Method valueOf = cls.getMethod(
"valueOf",
String.class);
objValue = valueOf.invoke(null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return objValue;
}
/**
* Set the cornerstoneConfiguration property. Setting this property
* causes the initialization process to use the configuration object
* to retrieve property values immediately.
*
*/
public void setCornerstoneConfiguration(CornerstoneConfiguration configuration) {
_configuration = configuration;
Set<String> props = _propertyMap.keySet();
loadConfigurationPropertyValues(props, false);
}
/**
* Get the Configuration object
*
*/
public CornerstoneConfiguration getCornerstoneConfiguration() {
return _configuration;
}
public void setRegisterForChanges(boolean register) {
this.registerForChanges = register;
}
/**
* Initialize the object
*/
public void initialize() {
reflectConfigurationPropertyValues();
if (registerForChanges && _configuration != null) {
_configuration.registerConfigurable(this);
}
}
/**
* Tear down the object
*/
public void destroy() {
}
public void addConfigPropertyPrefix(String configPrefix) {
if (configPropertyPrefixes == null) {
configPropertyPrefixes = new ArrayList<String>();
}
if (!configPropertyPrefixes.contains(configPrefix)) {
configPropertyPrefixes.add(configPrefix);
}
}
public Collection<String> getConfigPropertyPrefixes() {
List<String> list = new ArrayList<String>();
list.addAll(configPropertyPrefixes);
return list;
}
public void setConfigPropertyPrefixes(Collection<String> configPropertyPrefixes) {
this.configPropertyPrefixes = configPropertyPrefixes;
}
public void setUseSystemProperties(boolean val) {
this.useSystemProperties = val;
}
public boolean isUseSystemProperties() {
return this.useSystemProperties;
}
public void setConfigSystemPrefix(String prefix) {
this.configSystemPrefix = prefix;
}
public String getConfigSystemPrefix() {
return this.configSystemPrefix;
}
}
| true | true | protected void reflectConfigurationPropertyValues() {
CornerstoneConfiguration config = getCornerstoneConfiguration();
Collection<String> prefixes = getConfigPropertyPrefixes();
if (config == null || prefixes == null || prefixes.isEmpty()) {
return;
}
// add any prefixes from the system prefix to the end of the list
if (configSystemPrefix != null) {
String prefix = System.getProperty(configSystemPrefix);
List<String> list = new ArrayList<String>();
if (prefix != null) {
for (String pref : prefixes) {
list.add(prefix + "." + pref);
}
}
prefixes.addAll(list);
}
Map<String, String> systemProps = new HashMap<String, String>();
if (useSystemProperties) {
for (String prefix : this.configPropertyPrefixes) {
Properties properties = System.getProperties();
Set<Object> propNames = properties.keySet();
for (Object obj : propNames) {
String pName = obj.toString();
if (pName.startsWith(prefix + ".")) {
String value = System.getProperty(pName);
String shortName = pName.substring(prefix.length() + 1);
systemProps.put(shortName, value);
}
}
}
}
Method[] methods = this.getClass().getMethods();
for (Method method : methods) {
String methodName = method.getName();
if (!methodName.startsWith("set") || methodName.length() < 5) {
//not a set method or not a property that is at least 2 letters long
//(ie. methods with names like setZ will not be looked at)
continue;
}
Class<?>[] params = method.getParameterTypes();
if (params.length != 1) {
continue;
}
//looks like we found a setter method, lets look for a value now...
String propName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4);
// if there is a system variable with this name, we use that value instead of what's in the config
Object value = systemProps.get(propName);
if (value == null) {
value = getConfigurationValue(propName, null, prefixes);
}
if (value == null) {
continue;
}
try {
method.invoke(this, convert(params[0], value));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| protected void reflectConfigurationPropertyValues() {
CornerstoneConfiguration config = getCornerstoneConfiguration();
Collection<String> prefixes = getConfigPropertyPrefixes();
if (config == null || prefixes == null || prefixes.isEmpty()) {
return;
}
// add any prefixes from the system prefix to the end of the list
if (configSystemPrefix != null) {
String prefix = System.getProperty(configSystemPrefix);
List<String> list = new ArrayList<String>();
if (prefix != null) {
for (String pref : prefixes) {
list.add(prefix + "." + pref);
}
}
prefixes.addAll(list);
}
Map<String, String> systemProps = new HashMap<String, String>();
if (useSystemProperties) {
for (String prefix : prefixes) {
Properties properties = System.getProperties();
Set<Object> propNames = properties.keySet();
for (Object obj : propNames) {
String pName = obj.toString();
if (pName.startsWith(prefix + ".")) {
String value = System.getProperty(pName);
String shortName = pName.substring(prefix.length() + 1);
systemProps.put(shortName, value);
}
}
}
}
Method[] methods = this.getClass().getMethods();
for (Method method : methods) {
String methodName = method.getName();
if (!methodName.startsWith("set") || methodName.length() < 5) {
//not a set method or not a property that is at least 2 letters long
//(ie. methods with names like setZ will not be looked at)
continue;
}
Class<?>[] params = method.getParameterTypes();
if (params.length != 1) {
continue;
}
//looks like we found a setter method, lets look for a value now...
String propName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4);
// if there is a system variable with this name, we use that value instead of what's in the config
Object value = systemProps.get(propName);
if (value == null) {
value = getConfigurationValue(propName, null, prefixes);
}
if (value == null) {
continue;
}
try {
method.invoke(this, convert(params[0], value));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
diff --git a/src/music/midi/SequencePlayer.java b/src/music/midi/SequencePlayer.java
index 76afff5..31f4461 100644
--- a/src/music/midi/SequencePlayer.java
+++ b/src/music/midi/SequencePlayer.java
@@ -1,245 +1,245 @@
package music.midi;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import javax.sound.midi.*;
import music.Instrument;
import music.Pitch;
/**
* Schedules and plays a sequence of notes at given time steps (or "ticks")
*/
public class SequencePlayer {
private final Synthesizer synthesizer;
// active MIDI channels, assigned to instruments
private final Map<music.Instrument, Integer> channels = new HashMap<music.Instrument,Integer>();
// next available channel number (unassigned to an instrument yet)
private int nextChannel = 0;
private final Sequencer sequencer;
private final Track track;
private final int beatsPerMinute;
private static int DEFAULT_VELOCITY = 100; // the volume
private void checkRep() {
assert sequencer != null : "sequencer should be non-null";
assert track != null : "track should be non-null";
assert beatsPerMinute >= 0 : "should be positive number of beats per minute";
}
/**
* @param beatsPerMinute
* : the number of beats per minute, where each beat is equal to
* a quarter note in duration
* @param ticksPerQuarterNote
* : the number of ticks per quarter note
* @throws MidiUnavailableException
* @throws InvalidMidiDataException
*/
public SequencePlayer(int beatsPerMinute, int ticksPerQuarterNote)
throws MidiUnavailableException, InvalidMidiDataException {
synthesizer = MidiSystem.getSynthesizer();
synthesizer.open();
synthesizer.loadAllInstruments(synthesizer.getDefaultSoundbank());
this.sequencer = MidiSystem.getSequencer();
// Create a sequence object with with tempo-based timing, where
// the resolution of the time step is based on ticks per quarter note
Sequence sequence = new Sequence(Sequence.PPQ, ticksPerQuarterNote);
this.beatsPerMinute = beatsPerMinute;
// Create an empty track. Notes will be added to this track.
this.track = sequence.createTrack();
sequencer.setSequence(sequence);
checkRep();
}
/**
* @param eventType
* @param note
* @param tick
* @pre eventType is a valid MidiMessage type in ShortMessage && note is a
* valid pitch value && tick => 0
*/
private void addMidiEvent(int eventType, int channel, int note, int tick) throws InvalidMidiDataException {
ShortMessage msg = new ShortMessage();
msg.setMessage(eventType, channel, note, DEFAULT_VELOCITY);
MidiEvent event = new MidiEvent(msg, tick);
this.track.add(event);
}
/**
* @param note
* : the pitch value for the note to be played
* @param startTick
* : the starting tick
* @param numTicks
* : the number of ticks for which this note should be played
* @pre note is a valid pitch value && startTick >= 0 && numTicks >= 0
* @post schedule the note to be played starting at startTick for the
* duration of numTicks
*/
public void addNote(music.Instrument instr, int note, int startTick, int numTicks) {
int channel = getChannel(instr);
try {
// schedule two events in the track, one for starting a note and
// the other for ending the note.
addMidiEvent(ShortMessage.NOTE_ON, channel, note, startTick);
addMidiEvent(ShortMessage.NOTE_OFF, channel, note, startTick + numTicks);
} catch (InvalidMidiDataException e) {
String msg = MessageFormat.format("Cannot add note with the pitch {0} at tick {1} " +
"for duration of {2}", note, startTick, numTicks);
throw new RuntimeException(msg, e);
}
}
/**
* @post the sequencer is opened to begin playing its track
*/
public void play() throws MidiUnavailableException {
sequencer.open();
sequencer.setTempoInBPM(this.beatsPerMinute);
// start playing!
sequencer.start();
// busy-wait until the sequencer stops playing or the user presses Enter
while (sequencer.isRunning()) {
try {
if (System.in.available() > 0) {
break;
}
} catch (IOException e) {
}
Thread.yield();
}
// stop & close the sequencer
sequencer.stop();
sequencer.close();
}
private int getChannel(music.Instrument instr) {
// check whether this instrument already has a channel
if (channels.containsKey(instr)) {
return channels.get(instr);
}
int channel = allocateChannel();
patchInstrumentIntoChannel(channel, instr);
channels.put(instr, channel);
checkRep();
return channel;
}
private int allocateChannel() {
MidiChannel[] channels = synthesizer.getChannels();
if (nextChannel >= channels.length) throw new RuntimeException("tried to use too many instruments: limited to " + channels.length);
return nextChannel++;
}
private void patchInstrumentIntoChannel(int channel, music.Instrument instr) {
try {
addMidiEvent(ShortMessage.PROGRAM_CHANGE, channel, instr.ordinal(), 0);
} catch (InvalidMidiDataException e) {
throw new RuntimeException("Cannot set instrument", e);
}
}
/**
* @post returns a string that displays the entire track information as a
* sequence of MIDI events, where each event is either turning on or
* off a note at a certain tick
*/
@Override
public String toString() {
String trackInfo = "";
for (int i = 0; i < track.size(); i++) {
MidiEvent e = track.get(i);
MidiMessage msg = e.getMessage();
String msgString = "";
if (msg instanceof javax.sound.midi.ShortMessage) {
ShortMessage smg = ((ShortMessage) msg);
int command = smg.getCommand();
String commandType = "UnknownCommand";
// determine the type of the command in this message
if (command == ShortMessage.NOTE_OFF) {
commandType = "NOTE_OFF";
} else if (command == ShortMessage.NOTE_ON) {
commandType = "NOTE_ON ";
}
msgString = "Event: " + commandType + " Pitch: " + smg.getData1() + " ";
} else {
msgString = "***** End of track ***** ";
}
trackInfo = trackInfo + msgString + " Tick: " + e.getTick() + "\n";
}
return trackInfo;
}
/**
* Play an octave up and back down starting from middle C.
*/
public static void main(String[] args) {
SequencePlayer player;
// create a new player, with 120 beats (i.e. quarter note) per
// minute, with 2 tick per quarter note
player = new SequencePlayer(120, 2);
final Pitch C = new Pitch('C');
int start = 1;
for (Pitch p : new Pitch[] {
new Pitch('C'),
new Pitch('D'),
new Pitch('E'),
new Pitch('F'),
new Pitch('G'),
new Pitch('A'),
new Pitch('B'),
new Pitch('C').transpose(Pitch.OCTAVE),
new Pitch('B'),
new Pitch('A'),
new Pitch('G'),
new Pitch('F'),
new Pitch('E'),
new Pitch('D'),
- new Pitch('A'),
+ new Pitch('C'),
}) {
player.addNote(Instrument.PIANO, p.difference(C) + 60, start++, 1);
}
System.out.println(player);
// play!
player.play();
/*
* Note: A possible weird behavior of the Java sequencer: Even if the
* sequencer has finished playing all of the scheduled notes and is
* manually closed, the program may not terminate. This is likely
* due to daemon threads that are spawned when the sequencer is
* opened but keep on running even after the sequencer is killed. In
* this case, you need to explicitly exit the program with
* System.exit(0).
*/
// System.exit(0);
}
}
| true | true | public static void main(String[] args) {
SequencePlayer player;
// create a new player, with 120 beats (i.e. quarter note) per
// minute, with 2 tick per quarter note
player = new SequencePlayer(120, 2);
final Pitch C = new Pitch('C');
int start = 1;
for (Pitch p : new Pitch[] {
new Pitch('C'),
new Pitch('D'),
new Pitch('E'),
new Pitch('F'),
new Pitch('G'),
new Pitch('A'),
new Pitch('B'),
new Pitch('C').transpose(Pitch.OCTAVE),
new Pitch('B'),
new Pitch('A'),
new Pitch('G'),
new Pitch('F'),
new Pitch('E'),
new Pitch('D'),
new Pitch('A'),
}) {
player.addNote(Instrument.PIANO, p.difference(C) + 60, start++, 1);
}
System.out.println(player);
// play!
player.play();
/*
* Note: A possible weird behavior of the Java sequencer: Even if the
* sequencer has finished playing all of the scheduled notes and is
* manually closed, the program may not terminate. This is likely
* due to daemon threads that are spawned when the sequencer is
* opened but keep on running even after the sequencer is killed. In
* this case, you need to explicitly exit the program with
* System.exit(0).
*/
// System.exit(0);
}
| public static void main(String[] args) {
SequencePlayer player;
// create a new player, with 120 beats (i.e. quarter note) per
// minute, with 2 tick per quarter note
player = new SequencePlayer(120, 2);
final Pitch C = new Pitch('C');
int start = 1;
for (Pitch p : new Pitch[] {
new Pitch('C'),
new Pitch('D'),
new Pitch('E'),
new Pitch('F'),
new Pitch('G'),
new Pitch('A'),
new Pitch('B'),
new Pitch('C').transpose(Pitch.OCTAVE),
new Pitch('B'),
new Pitch('A'),
new Pitch('G'),
new Pitch('F'),
new Pitch('E'),
new Pitch('D'),
new Pitch('C'),
}) {
player.addNote(Instrument.PIANO, p.difference(C) + 60, start++, 1);
}
System.out.println(player);
// play!
player.play();
/*
* Note: A possible weird behavior of the Java sequencer: Even if the
* sequencer has finished playing all of the scheduled notes and is
* manually closed, the program may not terminate. This is likely
* due to daemon threads that are spawned when the sequencer is
* opened but keep on running even after the sequencer is killed. In
* this case, you need to explicitly exit the program with
* System.exit(0).
*/
// System.exit(0);
}
|
diff --git a/alpha-conferences/src/uk/co/brightec/alphaconferences/more/DonateActivity.java b/alpha-conferences/src/uk/co/brightec/alphaconferences/more/DonateActivity.java
index b74463b..8abe84d 100644
--- a/alpha-conferences/src/uk/co/brightec/alphaconferences/more/DonateActivity.java
+++ b/alpha-conferences/src/uk/co/brightec/alphaconferences/more/DonateActivity.java
@@ -1,98 +1,98 @@
package uk.co.brightec.alphaconferences.more;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import uk.co.brightec.alphaconferences.AlphaAdapter;
import uk.co.brightec.alphaconferences.Constants;
import uk.co.brightec.alphaconferences.Row;
import uk.co.brightec.alphaconferences.data.Conference;
import uk.co.brightec.alphaconferences.data.DataStore;
import uk.co.brightec.alphaconferences.rows.ButtonBarRow;
import uk.co.brightec.alphaconferences.rows.HTMLRow;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.MenuItem;
public class DonateActivity extends SherlockListActivity {
private ActionBar mActionBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActionBar = getSupportActionBar();
mActionBar.setTitle("Donate");
mActionBar.setDisplayHomeAsUpEnabled(true);
AlphaAdapter adapter = new AlphaAdapter();
setListAdapter(adapter);
}
@Override
protected void onResume() {
super.onResume();
populate();
}
private void populate() {
- final Conference conference = DataStore.conference(this);
+ final Conference conference = DataStore.conference(this, Constants.CONFERENCE_ID);
List<Row> rows = new ArrayList<Row>();
rows.add(new HTMLRow(conference.donationDescription, this));
View.OnClickListener donateBySmsHandler = null;
if (StringUtils.isNotBlank(conference.donationTelephoneNumber)) {
donateBySmsHandler = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("sms:"+conference.donationTelephoneNumber));
//intent.putExtra("sms_body", "HLCG12 £");
startActivity(intent);
}
};
}
View.OnClickListener donateOnlineHandler = null;
if (StringUtils.isNotBlank(conference.donationUrl)) {
donateOnlineHandler = new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(conference.donationUrl)));
}
};
}
ButtonBarRow buttons = new ButtonBarRow(this);
buttons.setButton1("Donate by SMS", donateBySmsHandler);
buttons.setButton2("Donate online", donateOnlineHandler);
rows.add(buttons);
((AlphaAdapter) getListAdapter()).setRows(rows, this);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
| true | true | private void populate() {
final Conference conference = DataStore.conference(this);
List<Row> rows = new ArrayList<Row>();
rows.add(new HTMLRow(conference.donationDescription, this));
View.OnClickListener donateBySmsHandler = null;
if (StringUtils.isNotBlank(conference.donationTelephoneNumber)) {
donateBySmsHandler = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("sms:"+conference.donationTelephoneNumber));
//intent.putExtra("sms_body", "HLCG12 £");
startActivity(intent);
}
};
}
View.OnClickListener donateOnlineHandler = null;
if (StringUtils.isNotBlank(conference.donationUrl)) {
donateOnlineHandler = new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(conference.donationUrl)));
}
};
}
ButtonBarRow buttons = new ButtonBarRow(this);
buttons.setButton1("Donate by SMS", donateBySmsHandler);
buttons.setButton2("Donate online", donateOnlineHandler);
rows.add(buttons);
((AlphaAdapter) getListAdapter()).setRows(rows, this);
}
| private void populate() {
final Conference conference = DataStore.conference(this, Constants.CONFERENCE_ID);
List<Row> rows = new ArrayList<Row>();
rows.add(new HTMLRow(conference.donationDescription, this));
View.OnClickListener donateBySmsHandler = null;
if (StringUtils.isNotBlank(conference.donationTelephoneNumber)) {
donateBySmsHandler = new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("sms:"+conference.donationTelephoneNumber));
//intent.putExtra("sms_body", "HLCG12 £");
startActivity(intent);
}
};
}
View.OnClickListener donateOnlineHandler = null;
if (StringUtils.isNotBlank(conference.donationUrl)) {
donateOnlineHandler = new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(conference.donationUrl)));
}
};
}
ButtonBarRow buttons = new ButtonBarRow(this);
buttons.setButton1("Donate by SMS", donateBySmsHandler);
buttons.setButton2("Donate online", donateOnlineHandler);
rows.add(buttons);
((AlphaAdapter) getListAdapter()).setRows(rows, this);
}
|
diff --git a/netlogo/RunHeadless.java b/netlogo/RunHeadless.java
index 01b017b..531eaaa 100644
--- a/netlogo/RunHeadless.java
+++ b/netlogo/RunHeadless.java
@@ -1,92 +1,92 @@
import java.io.*;
import org.nlogo.headless.HeadlessWorkspace;
public class RunHeadless {
private static String usage = "Usage: java [java args] -classpath [classpath] RunHeadless.java filename \n" +
" filename: Name of the HubNet activity to launch.\n" +
"Launches a HubNet activity headlessly and keeps it running by repeatedly issuing the 'go' command.\n" +
"NetLogo's dependencies must be on the classpath.";
public static void main(String[] args) {
if (args.length != 1)
error(ErrorCode.Usage, usage);
String filename = args[0];
try {
HeadlessWorkspace workspace = HeadlessWorkspace.newInstance();
workspace.open(filename);
workspace.command("startup");
// The HubNet webapp looks for this line in the output to determine
// the port that the activity is running on.
System.out.println("Running on port: " + workspace.hubnetManager().getPort());
workspace.command("setup");
// The HubNet webapp looks for this line in the output to determine
// that launching the activity was successful, and that startup/setup
// got called without problems.
- // See: app/controllers/Activities.scala
+ // See: app/util/ActivityLauncher.scala
System.out.println("The model is running...");
while(true) {
workspace.command("go");
}
}
catch (FileNotFoundException e) {
error(ErrorCode.InvalidFile, "** Error: File not found: " + filename);
}
catch (org.nlogo.api.CompilerException e) {
error(ErrorCode.ModelError, "** Error:" +
"There were errors in the model file (CompilerException):\n" +
getStackTrace(e) + "\n\n");
}
catch (org.nlogo.nvm.EngineException e) {
error(ErrorCode.ModelError, "** Error:" +
"There were errors in the model file (EngineException):\n" +
e.context.buildRuntimeErrorMessage(e.instruction, e) + "\n" +
getStackTrace(e) + "\n\n");
}
catch (NoClassDefFoundError e) {
error(ErrorCode.Usage, e + "\n" + classpathErrorMessage);
}
catch (Exception e) {
error(ErrorCode.UnknownError, "An error occurred while opening the model:\n" +
e.getMessage() + "\n" + getStackTrace(e) + "\n\n");
}
}
private static void error(ErrorCode error, String message) {
System.err.println(message);
System.exit(error.code());
}
private enum ErrorCode {
UnknownError(1), Usage(101), InvalidFile(102), ModelError(103);
private final int _code;
public int code() { return _code; }
ErrorCode(int code) {
_code = code;
}
}
private static String classpathErrorMessage = "The following must be on the classpath in order to run this file: \n" +
" * The directory containing the compiled RunHeadless.class file\n" +
" * NetLogo.jar\n" +
" * scala-library.jar (version 2.9.0-1)\n" +
" * NetLogo's dependencies:\n" +
" asm-3.3.1.jar asm-tree-3.3.1.jar jhotdraw-6.0b1.jar log4j-1.2.16.jar parboiled-java-0.11.0.jar quaqua-7.3.4.jar\n" +
" asm-all-3.3.1.jar asm-util-3.3.1.jar jmf-2.1.1e.jar mrjadapter-1.2.jar pegdown-0.9.1.jar swing-layout-7.3.4.jar\n" +
" asm-analysis-3.3.1.jar gluegen-rt-1.1.1.jar jogl-1.1.1.jar parboiled-core-0.11.0.jar picocontainer-2.11.1.jar\n";
public static String getStackTrace(Throwable aThrowable) {
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
aThrowable.printStackTrace(printWriter);
return result.toString();
}
}
| true | true | public static void main(String[] args) {
if (args.length != 1)
error(ErrorCode.Usage, usage);
String filename = args[0];
try {
HeadlessWorkspace workspace = HeadlessWorkspace.newInstance();
workspace.open(filename);
workspace.command("startup");
// The HubNet webapp looks for this line in the output to determine
// the port that the activity is running on.
System.out.println("Running on port: " + workspace.hubnetManager().getPort());
workspace.command("setup");
// The HubNet webapp looks for this line in the output to determine
// that launching the activity was successful, and that startup/setup
// got called without problems.
// See: app/controllers/Activities.scala
System.out.println("The model is running...");
while(true) {
workspace.command("go");
}
}
catch (FileNotFoundException e) {
error(ErrorCode.InvalidFile, "** Error: File not found: " + filename);
}
catch (org.nlogo.api.CompilerException e) {
error(ErrorCode.ModelError, "** Error:" +
"There were errors in the model file (CompilerException):\n" +
getStackTrace(e) + "\n\n");
}
catch (org.nlogo.nvm.EngineException e) {
error(ErrorCode.ModelError, "** Error:" +
"There were errors in the model file (EngineException):\n" +
e.context.buildRuntimeErrorMessage(e.instruction, e) + "\n" +
getStackTrace(e) + "\n\n");
}
catch (NoClassDefFoundError e) {
error(ErrorCode.Usage, e + "\n" + classpathErrorMessage);
}
catch (Exception e) {
error(ErrorCode.UnknownError, "An error occurred while opening the model:\n" +
e.getMessage() + "\n" + getStackTrace(e) + "\n\n");
}
}
| public static void main(String[] args) {
if (args.length != 1)
error(ErrorCode.Usage, usage);
String filename = args[0];
try {
HeadlessWorkspace workspace = HeadlessWorkspace.newInstance();
workspace.open(filename);
workspace.command("startup");
// The HubNet webapp looks for this line in the output to determine
// the port that the activity is running on.
System.out.println("Running on port: " + workspace.hubnetManager().getPort());
workspace.command("setup");
// The HubNet webapp looks for this line in the output to determine
// that launching the activity was successful, and that startup/setup
// got called without problems.
// See: app/util/ActivityLauncher.scala
System.out.println("The model is running...");
while(true) {
workspace.command("go");
}
}
catch (FileNotFoundException e) {
error(ErrorCode.InvalidFile, "** Error: File not found: " + filename);
}
catch (org.nlogo.api.CompilerException e) {
error(ErrorCode.ModelError, "** Error:" +
"There were errors in the model file (CompilerException):\n" +
getStackTrace(e) + "\n\n");
}
catch (org.nlogo.nvm.EngineException e) {
error(ErrorCode.ModelError, "** Error:" +
"There were errors in the model file (EngineException):\n" +
e.context.buildRuntimeErrorMessage(e.instruction, e) + "\n" +
getStackTrace(e) + "\n\n");
}
catch (NoClassDefFoundError e) {
error(ErrorCode.Usage, e + "\n" + classpathErrorMessage);
}
catch (Exception e) {
error(ErrorCode.UnknownError, "An error occurred while opening the model:\n" +
e.getMessage() + "\n" + getStackTrace(e) + "\n\n");
}
}
|
diff --git a/esup-opi-web-jsf-servlet/src/main/java/org/esupportail/opi/web/controllers/formation/ParamClefFormationController.java b/esup-opi-web-jsf-servlet/src/main/java/org/esupportail/opi/web/controllers/formation/ParamClefFormationController.java
index c40fadfe..805d34e9 100644
--- a/esup-opi-web-jsf-servlet/src/main/java/org/esupportail/opi/web/controllers/formation/ParamClefFormationController.java
+++ b/esup-opi-web-jsf-servlet/src/main/java/org/esupportail/opi/web/controllers/formation/ParamClefFormationController.java
@@ -1,887 +1,887 @@
/**
*
*/
package org.esupportail.opi.web.controllers.formation;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.comparators.NullComparator;
import org.esupportail.commons.services.logging.Logger;
import org.esupportail.commons.services.logging.LoggerImpl;
import org.esupportail.opi.domain.beans.formation.*;
import org.esupportail.opi.services.remote.client.IApogee;
import org.esupportail.opi.web.beans.beanEnum.ActionEnum;
import org.esupportail.opi.web.beans.pojo.ClesAnnuFormPojo;
import org.esupportail.opi.web.beans.pojo.DomaineAnnuFormPojo;
import org.esupportail.opi.web.beans.utils.NavigationRulesConst;
import org.esupportail.opi.web.controllers.AbstractAccessController;
import org.esupportail.opi.web.controllers.PreferencesController;
import org.esupportail.wssi.services.remote.Diplome;
import javax.faces.model.SelectItem;
import java.util.*;
/**
* @author gomez
*/
public class ParamClefFormationController extends AbstractAccessController {
/*
* ******************* PROPERTIES STATIC ******************* */
/**
* attribute serialVersionUID
*/
private static final long serialVersionUID = 4756615930472850162L;
/**
*
*/
protected static final String[] DEFAULT_TEMOIN_VALUES = {"O", "N"};
/**
*
*/
private static final String FORMULAIRE_CLEF = "formAddClef";
/*
* ******************* PROPERTIES ******************* */
/**
* A logger.
*/
private final Logger log = new LoggerImpl(getClass());
/**
*
*/
private PreferencesController preferencesController;
/**
*
*/
private List<DomaineAnnuFormPojo> listDomain;
/**
* The actionEnum.
*/
private ActionEnum actionEnum;
/**
* The actionLang.
*/
private ActionEnum actionLang;
/**
* The actionLang.
*/
private ActionEnum actionDom;
/**
* clef de formation selectionnee.
*/
private ClesAnnuFormPojo cles;
/**
* liste des domaines.
*/
private List<ClesAnnuFormPojo> listCles;
/**
* langue selectionnee.
*/
private String langueSelected;
/**
* libele saisie.
*/
private String libSaisi;
/**
* map du libele en fonction du code de diplemes.
*/
private Map<String, String> mapCodeDipLib;
/**
* temEnSveItems.
*/
private List<SelectItem> temEnSveItems;
/**
* temEnSveItems.
*/
private List<SelectItem> itemDomaine;
/**
* liste des langues.
*/
private List<SelectItem> allLangue;
/**
* dipsItems.
*/
private List<SelectItem> dipsItems;
/**
* allDipsItems.
*/
private List<SelectItem> allDipsItems;
/**
* selectDipsDI.
*/
private List<String> selectDipsDI;
/**
* selectDipsADI.
*/
private List<String> selectDipsADI;
/**
* selectDoms.
*/
private String selectDoms;
private IApogee iApogee;
/*
* ******************* CONSTRUCTOR ************************* */
/**
* Constructors.
*/
public ParamClefFormationController() {
super();
temEnSveItems = new ArrayList<SelectItem>();
itemDomaine = new ArrayList<SelectItem>();
selectDipsDI = new ArrayList<String>();
selectDipsADI = new ArrayList<String>();
allLangue = new ArrayList<SelectItem>();
mapCodeDipLib = new HashMap<String, String>();
}
/*
* ******************* RESET ************************* */
/**
* @see org.esupportail.opi.web.controllers.AbstractDomainAwareBean#reset()
*/
@Override
public void reset() {
super.reset();
actionEnum = null;
actionLang = null;
actionDom = null;
cles = null;
listCles = null;
langueSelected = null;
libSaisi = null;
dipsItems = null;
allDipsItems = null;
allLangue.clear();
}
/*
* ******************* CALLBACK ************************* */
/**
* Callback to domain list.
*
* @return String
*/
public String goSeeAllKeys() {
reset();
return NavigationRulesConst.DISPLAY_KEYWORDS;
}
/**
* Callback to add domain.
*
* @return String
*/
public String goAddKeys() {
reset();
getActionEnum().setWhatAction(ActionEnum.ADD_ACTION);
return null;
}
/*
* ******************* ADD ET UPDATE ************************* */
/**
* Add a Domain to the dataBase.
*/
@SuppressWarnings("unchecked")
public void add() {
if (testErreurSave()) {
return;
}
if (log.isDebugEnabled()) {
log.debug("enterind add with domain = " + getCles().getClesAnnuForm().getCodCles());
}
//save ClesAnnuForm
iApogee.save(getCles().getClesAnnuForm());
for (Cles2AnnuForm langLib : getCles().getCles2AnnuForm()) {
langLib.getId().setCodCles(getCles().getClesAnnuForm().getCodCles());
langLib.setClesAnnuForm(getCles().getClesAnnuForm());
//save Cles2AnnuForm
iApogee.save(langLib);
}
for (SelectItem dipItem : dipsItems) {
ClesDiplomeAnnuForm cleDip = new ClesDiplomeAnnuForm();
cleDip.setCodCles(getCles().getClesAnnuForm().getCodCles());
cleDip.setCodDip((String) dipItem.getValue());
getCles().getClesDiplomeAnnuForm().add(cleDip);
//save Cles2AnnuForm
iApogee.save(cleDip);
}
getListCles().add(getCles());
Collections.sort(getListCles(), new BeanComparator("ClesAnnuForm",
new BeanComparator("codCles", new NullComparator())));
reset();
addInfoMessage(null, "INFO.ENTER.SUCCESS");
if (log.isDebugEnabled()) {
log.debug("leaving add");
}
}
/**
* Update a fonction to the dataBase.
*/
public void update() {
if (testErreurUpdate()) {
return;
}
if (log.isDebugEnabled()) {
log.debug("enterind update with domain = " + getCles().getClesAnnuForm().getCodCles());
}
for (Cles2AnnuForm langLib : getCles().getCles2AnnuForm()) {
langLib.getId().setCodCles(getCles().getClesAnnuForm().getCodCles());
langLib.setClesAnnuForm(getCles().getClesAnnuForm());
- if (langLib.getLibCles().length()>=50){
+ if (langLib.getLibCles().length()>50){
addErrorMessage(FORMULAIRE_CLEF, "ERROR.FIELD.TOO_LONG","Libelle",50);
return;
}
//save or update Cles2AnnuForm
iApogee.saveOrUpdate(langLib);
}
int index;
List<ClesDiplomeAnnuForm> listDip = new ArrayList<ClesDiplomeAnnuForm>();
for (ClesDiplomeAnnuForm dip : getCles().getClesDiplomeAnnuForm()) {
index = getExistDipsItems(dip.getCodDip());
if (index == -1) {
listDip.add(dip);
} else {
dipsItems.remove(index);
}
}
for (ClesDiplomeAnnuForm dip : listDip) {
getCles().getClesDiplomeAnnuForm().remove(dip);
//delete Cles2AnnuForm
iApogee.delete(dip);
}
for (SelectItem dipItem : dipsItems) {
ClesDiplomeAnnuForm cleDip = new ClesDiplomeAnnuForm();
cleDip.setCodCles(getCles().getClesAnnuForm().getCodCles());
cleDip.setCodDip((String) dipItem.getValue());
getCles().getClesDiplomeAnnuForm().add(cleDip);
//save Cles2AnnuForm
iApogee.save(cleDip);
}
//update ClesAnnuForm
iApogee.update(getCles().getClesAnnuForm());
reset();
if (log.isDebugEnabled()) {
log.debug("leaving update");
}
}
/**
* Delete a fonction to the dataBase.
*/
public void delete() {
if (log.isDebugEnabled()) {
log.debug("enterind delete with domain = " + getCles().getClesAnnuForm().getCodCles());
}
for (Cles2AnnuForm langLib : getCles().getCles2AnnuForm()) {
//delete Cles2AnnuForm
iApogee.delete(langLib);
}
for (ClesDiplomeAnnuForm cleDip : getCles().getClesDiplomeAnnuForm()) {
//delete ClesDiplomeAnnuForm
iApogee.delete(cleDip);
}
getListCles().remove(cles);
//delete ClesAnnuForm
iApogee.delete(getCles().getClesAnnuForm());
reset();
if (log.isDebugEnabled()) {
log.debug("leaving delete");
}
}
/*
* ******************* TEST ************************* */
/**
* @return boolean
*/
private boolean testErreurSave() {
if (getCles().getClesAnnuForm().getCodCles() == null || getCles().getClesAnnuForm().getCodCles().equals("")) {
addErrorMessage(FORMULAIRE_CLEF, "ERROR.FIELD.EMPTY", "Code");
return true;
}
if (testCles()) {
addErrorMessage(FORMULAIRE_CLEF, "ERROR.FIELD.EXISTE", "Cle", "Code");
return true;
}
return testErreurUpdate();
}
/**
* @return boolean
*/
private boolean testErreurUpdate() {
if (getCles().getDomaineAnnuFormPojo() == null) {
addErrorMessage(FORMULAIRE_CLEF, "ERROR.FIELD.EMPTY", "Domaine");
return true;
}
if (getCles().getCles2AnnuForm().isEmpty()) {
addErrorMessage(FORMULAIRE_CLEF, "ERROR.LIST.EMPTY", "Libele en fonction de la langue");
return true;
}
if (dipsItems.isEmpty()) {
addErrorMessage(FORMULAIRE_CLEF, "ERROR.LIST.EMPTY", "Dipleme");
return true;
}
return false;
}
/**
* @param langue
* @return boolean
*/
public boolean isNotExistLangueInDom(final String langue) {
for (Cles2AnnuForm langLib : getCles().getCles2AnnuForm()) {
if (langLib.getId().getCodLang().equalsIgnoreCase(langue)) {
return false;
}
}
return true;
}
/**
* @return boolean
*/
private boolean testCles() {
String code = getCles().getClesAnnuForm().getCodCles();
for (ClesAnnuFormPojo c : getListCles()) {
if (code.equals(c.getClesAnnuForm().getCodCles())) {
return true;
}
}
return false;
}
/*
* ******************* GESTION DES LIBELES ET DES LANGUES ************************* */
/**
*
*/
public void addLangLib() {
getActionLang().setWhatAction(ActionEnum.ADD_ACTION);
}
/**
*
*/
public void updateLangLib() {
getActionLang().setWhatAction(ActionEnum.UPDATE_ACTION);
}
/**
*
*/
public void suppLangLib() {
Cles2AnnuForm langLibDelete = recupLangLib();
if (langLibDelete != null) {
getCles().getCles2AnnuForm().remove(langLibDelete);
}
}
/**
*
*/
public void validModLangLib() {
if (libSaisi == null || libSaisi.equals("")) {
addErrorMessage(FORMULAIRE_CLEF, "ERROR.FIELD.EMPTY", "Libele");
return;
}
recupLangLib().setLibCles(libSaisi);
getActionLang().setWhatAction(ActionEnum.EMPTY_ACTION);
libSaisi = null;
}
/**
*
*/
public void validAddLangLib() {
if (libSaisi == null || libSaisi.equals("")) {
addErrorMessage(FORMULAIRE_CLEF, "ERROR.FIELD.EMPTY", "Libele");
return;
}
Cles2AnnuForm langLib = new Cles2AnnuForm();
Cles2AnnuFormId cles2Id = new Cles2AnnuFormId();
cles2Id.setCodLang(langueSelected.toUpperCase());
langLib.setId(cles2Id);
langLib.setLibCles(libSaisi);
getCles().getCles2AnnuForm().add(langLib);
getActionLang().setWhatAction(ActionEnum.EMPTY_ACTION);
libSaisi = null;
}
/**
*
*/
public void annulLangLib() {
getActionLang().setWhatAction(ActionEnum.EMPTY_ACTION);
libSaisi = null;
}
/*
* ******************* GESTION DU DOMAINES ************************* */
/**
*
*/
public void updateDomaines() {
getActionDom().setWhatAction(ActionEnum.UPDATE_ACTION);
}
/**
*
*/
public void validDomaines() {
if (selectDoms == null || selectDoms.equals("")) {
addErrorMessage(FORMULAIRE_CLEF, "ERROR.FIELD.EMPTY", "Domaine");
return;
}
getCles().getClesAnnuForm().setCodDom(selectDoms);
getCles().setDomaineAnnuFormPojo(getDomaine(selectDoms));
getActionDom().setWhatAction(ActionEnum.EMPTY_ACTION);
}
/**
*
*/
public void annulDomaines() {
getActionDom().setWhatAction(ActionEnum.EMPTY_ACTION);
}
/*
* ******************* GETTERS ITEMS ************************* */
/**
* @return the list of temoins
*/
public List<SelectItem> getTemEnSveItems() {
if (temEnSveItems.isEmpty()) {
for (String pageSizeValue : DEFAULT_TEMOIN_VALUES) {
temEnSveItems.add(new SelectItem(pageSizeValue));
}
}
return temEnSveItems;
}
/**
* @return the list of temoins
*/
@SuppressWarnings("unchecked")
public List<SelectItem> getItemDomaine() {
if (itemDomaine.isEmpty()) {
for (DomaineAnnuFormPojo dom : getListDomain()) {
itemDomaine.add(new SelectItem(dom.getDomaineAnnuForm().getCodDom()));
}
Collections.sort(itemDomaine, new BeanComparator("value", new NullComparator()));
}
return itemDomaine;
}
/**
* @return the list of diplemes
*/
@SuppressWarnings("unchecked")
public List<SelectItem> getDipsItems() {
if (dipsItems == null) {
dipsItems = new ArrayList<SelectItem>();
List<ClesDiplomeAnnuForm> listDiplomes = getCles().getClesDiplomeAnnuForm();
if (listDiplomes != null) {
for (ClesDiplomeAnnuForm dip : listDiplomes) {
dipsItems.add(new SelectItem(dip.getCodDip(), dip.getCodDip() + " (" + getMapCodeDipLib().get(dip.getCodDip()) + ")"));
}
}
Collections.sort(dipsItems, new BeanComparator("value", new NullComparator()));
}
return dipsItems;
}
/**
* @return the list of diplemes
*/
@SuppressWarnings("unchecked")
public List<SelectItem> getAllDipsItems() {
if (allDipsItems == null) {
allDipsItems = new ArrayList<SelectItem>();
List<Diplome> allDiplomes = getAllDiplome();
if (allDiplomes != null) {
for (Diplome dip : allDiplomes) {
if (getExistDipsItems(dip.getCodDip()) == -1) {
allDipsItems.add(new SelectItem(dip.getCodDip(), dip.getCodDip() + " (" + dip.getLibDip() + ")"));
}
}
}
Collections.sort(allDipsItems, new BeanComparator("value", new NullComparator()));
}
return allDipsItems;
}
/**
* Ajoute la selection dans DipsItems.
*/
@SuppressWarnings("unchecked")
public void ajouDipsItems() {
int index = -1;
for (String c : selectDipsADI) {
for (int i = 0; i < allDipsItems.size() && index == -1; i++) {
if (allDipsItems.get(i).getValue().equals(c)) {
index = i;
}
}
if (index >= 0) {
dipsItems.add(allDipsItems.get(index));
allDipsItems.remove(index);
}
index = -1;
}
Collections.sort(dipsItems, new BeanComparator("value", new NullComparator()));
Collections.sort(allDipsItems, new BeanComparator("value", new NullComparator()));
selectDipsADI.clear();
}
/**
* Supprime la selection dans DipsItems.
*/
@SuppressWarnings("unchecked")
public void suppDipsItems() {
int index = -1;
for (String c : selectDipsDI) {
for (int i = 0; i < dipsItems.size() && index == -1; i++) {
if (dipsItems.get(i).getValue().equals(c)) {
index = i;
}
}
if (index >= 0) {
allDipsItems.add(dipsItems.get(index));
dipsItems.remove(index);
}
index = -1;
}
Collections.sort(dipsItems, new BeanComparator("value", new NullComparator()));
Collections.sort(allDipsItems, new BeanComparator("value", new NullComparator()));
selectDipsDI.clear();
}
/*
* ******************* OTHERS GETTERS ************************* */
/**
* @param codDip
* @return integer
*/
@SuppressWarnings("cast")
private int getExistDipsItems(final String codDip) {
for (int i = 0; i < getDipsItems().size(); i++) {
if (codDip.equals((String) getDipsItems().get(i).getValue())) {
return i;
}
}
return -1;
}
/**
* @return List(TypDiplome)
*/
public List<Diplome> getAllDiplome() {
return getDomainApoService().getAllDiplomes();
}
/**
* @return liste de Items
*/
@SuppressWarnings("unchecked")
public List<SelectItem> getAllLangue() {
allLangue.clear();
String langue;
for (SelectItem item : preferencesController.getLocaleItems()) {
langue = ((Locale) item.getValue()).getLanguage();
if (isNotExistLangueInDom(langue)) {
allLangue.add(new SelectItem(langue));
}
}
Collections.sort(allLangue, new BeanComparator("value", new NullComparator()));
return allLangue;
}
/**
* @return Domaine2AnnuForm
*/
public Cles2AnnuForm recupLangLib() {
for (Cles2AnnuForm langLib : getCles().getCles2AnnuForm()) {
if (langLib.getId().getCodLang().equalsIgnoreCase(langueSelected)) {
return langLib;
}
}
return null;
}
/**
* @param codDom
* @return the list of temoins
*/
public DomaineAnnuFormPojo getDomaine(String codDom) {
for (DomaineAnnuFormPojo dom : getListDomain()) {
if (dom.getDomaineAnnuForm().getCodDom().equals(codDom)) {
return dom;
}
}
return null;
}
/*
* ******************* OTHERS GETTERS ************************* */
/**
* @return List(GrpTypDip)
*/
@SuppressWarnings("unchecked")
public List<ClesAnnuFormPojo> getListCles() {
if (listCles == null) {
listCles = new ArrayList<ClesAnnuFormPojo>();
for (ClesAnnuForm cle : iApogee.getClesAnnuForm()) {
ClesAnnuFormPojo clePojo = new ClesAnnuFormPojo(cle, "fr");
clePojo.setCles2AnnuForm(iApogee.getCles2AnnuForm(cle.getCodCles()));
clePojo.setClesDiplomeAnnuForm(iApogee.getClesDiplomeAnnuForm(cle.getCodCles()));
clePojo.setDomaineAnnuFormPojo(getDomaineAnnuFormPojo(cle.getCodDom()));
listCles.add(clePojo);
}
Collections.sort(getListCles(), new BeanComparator("clesAnnuForm",
new BeanComparator("codCles", new NullComparator())));
}
return listCles;
}
public DomaineAnnuFormPojo getDomaineAnnuFormPojo(final String codDom) {
DomaineAnnuFormPojo domPojo = new DomaineAnnuFormPojo(iApogee.getDomaineAnnuForm(codDom), "fr");
domPojo.setDomaine2AnnuForm(iApogee.getDomaine2AnnuForm(domPojo.getDomaineAnnuForm().getCodDom()));
return domPojo;
}
/*
* ******************* GETTERS ************************* */
/**
* @return List(GrpTypDip)
*/
@SuppressWarnings("unchecked")
public List<DomaineAnnuFormPojo> getListDomain() {
if (listDomain == null || listDomain.isEmpty()) {
listDomain = new ArrayList<DomaineAnnuFormPojo>();
for (DomaineAnnuForm dom : iApogee.getDomaineAnnuForm()) {
DomaineAnnuFormPojo domPojo = new DomaineAnnuFormPojo(dom, "fr");
domPojo.setDomaine2AnnuForm(iApogee.getDomaine2AnnuForm(dom.getCodDom()));
listDomain.add(domPojo);
}
Collections.sort(listDomain, new BeanComparator("DomaineAnnuForm",
new BeanComparator("codDom", new NullComparator())));
}
return listDomain;
}
/**
* @return the actionEnum
*/
public ActionEnum getActionEnum() {
if (actionEnum == null) {
actionEnum = new ActionEnum();
}
return actionEnum;
}
/**
* @return mapCodeDipLib
*/
public Map<String, String> getMapCodeDipLib() {
if (mapCodeDipLib.isEmpty()) {
for (Diplome dip : getAllDiplome()) {
mapCodeDipLib.put(dip.getCodDip(), dip.getLibDip());
}
}
return mapCodeDipLib;
}
/**
* @return ActionEnum
*/
public ActionEnum getActionLang() {
if (actionLang == null) {
actionLang = new ActionEnum();
}
return actionLang;
}
/**
* @return ActionEnum
*/
public ActionEnum getActionDom() {
if (actionDom == null) {
actionDom = new ActionEnum();
}
return actionDom;
}
/**
* @return selectDoms
*/
public String getSelectDoms() {
return selectDoms;
}
/**
* @return la clef de formation selectionnee
*/
public ClesAnnuFormPojo getCles() {
if (cles == null) {
cles = new ClesAnnuFormPojo();
cles.setClesAnnuForm(new ClesAnnuForm());
cles.setCles2AnnuForm(new ArrayList<Cles2AnnuForm>());
cles.setClesDiplomeAnnuForm(new ArrayList<ClesDiplomeAnnuForm>());
}
return cles;
}
/**
* @return preferencesController
*/
public PreferencesController getPreferencesController() {
return preferencesController;
}
/**
* @return langueSelected
*/
public String getLangueSelected() {
return langueSelected;
}
/**
* @return libSaisi
*/
public String getLibSaisi() {
return libSaisi;
}
/**
* @return selectDipsDI
*/
public List<String> getSelectDipsDI() {
return selectDipsDI;
}
/**
* @return selectDipsADI
*/
public List<String> getSelectDipsADI() {
return selectDipsADI;
}
/*
* ******************* SETTERS ************************* */
/**
* @param actionEnum the actionEnum to set
*/
public void setActionEnum(final ActionEnum actionEnum) {
this.actionEnum = actionEnum;
}
/**
* @param actionLang
*/
public void setActionLang(ActionEnum actionLang) {
this.actionLang = actionLang;
}
/**
* @param actionDom
*/
public void setActionDom(ActionEnum actionDom) {
this.actionDom = actionDom;
}
/**
* @param cles
*/
public void setCles(final ClesAnnuFormPojo cles) {
this.cles = cles;
}
/**
* @param preferencesController
*/
public void setPreferencesController(PreferencesController preferencesController) {
this.preferencesController = preferencesController;
}
/**
* @param langueSelected
*/
public void setLangueSelected(String langueSelected) {
this.langueSelected = langueSelected;
}
/**
* @param libSaisi
*/
public void setLibSaisi(String libSaisi) {
this.libSaisi = libSaisi;
}
/**
* @param selectDipsDI
*/
public void setSelectDipsDI(List<String> selectDipsDI) {
this.selectDipsDI = selectDipsDI;
}
/**
* @param selectDipsADI
*/
public void setSelectDipsADI(List<String> selectDipsADI) {
this.selectDipsADI = selectDipsADI;
}
/**
* @param selectDoms
*/
public void setSelectDoms(String selectDoms) {
this.selectDoms = selectDoms;
}
/**
* @param iApogee the iApogee to set
*/
public void setIApogee(final IApogee iApogee) {
this.iApogee = iApogee;
}
}
| true | true | public void update() {
if (testErreurUpdate()) {
return;
}
if (log.isDebugEnabled()) {
log.debug("enterind update with domain = " + getCles().getClesAnnuForm().getCodCles());
}
for (Cles2AnnuForm langLib : getCles().getCles2AnnuForm()) {
langLib.getId().setCodCles(getCles().getClesAnnuForm().getCodCles());
langLib.setClesAnnuForm(getCles().getClesAnnuForm());
if (langLib.getLibCles().length()>=50){
addErrorMessage(FORMULAIRE_CLEF, "ERROR.FIELD.TOO_LONG","Libelle",50);
return;
}
//save or update Cles2AnnuForm
iApogee.saveOrUpdate(langLib);
}
int index;
List<ClesDiplomeAnnuForm> listDip = new ArrayList<ClesDiplomeAnnuForm>();
for (ClesDiplomeAnnuForm dip : getCles().getClesDiplomeAnnuForm()) {
index = getExistDipsItems(dip.getCodDip());
if (index == -1) {
listDip.add(dip);
} else {
dipsItems.remove(index);
}
}
for (ClesDiplomeAnnuForm dip : listDip) {
getCles().getClesDiplomeAnnuForm().remove(dip);
//delete Cles2AnnuForm
iApogee.delete(dip);
}
for (SelectItem dipItem : dipsItems) {
ClesDiplomeAnnuForm cleDip = new ClesDiplomeAnnuForm();
cleDip.setCodCles(getCles().getClesAnnuForm().getCodCles());
cleDip.setCodDip((String) dipItem.getValue());
getCles().getClesDiplomeAnnuForm().add(cleDip);
//save Cles2AnnuForm
iApogee.save(cleDip);
}
//update ClesAnnuForm
iApogee.update(getCles().getClesAnnuForm());
reset();
if (log.isDebugEnabled()) {
log.debug("leaving update");
}
}
| public void update() {
if (testErreurUpdate()) {
return;
}
if (log.isDebugEnabled()) {
log.debug("enterind update with domain = " + getCles().getClesAnnuForm().getCodCles());
}
for (Cles2AnnuForm langLib : getCles().getCles2AnnuForm()) {
langLib.getId().setCodCles(getCles().getClesAnnuForm().getCodCles());
langLib.setClesAnnuForm(getCles().getClesAnnuForm());
if (langLib.getLibCles().length()>50){
addErrorMessage(FORMULAIRE_CLEF, "ERROR.FIELD.TOO_LONG","Libelle",50);
return;
}
//save or update Cles2AnnuForm
iApogee.saveOrUpdate(langLib);
}
int index;
List<ClesDiplomeAnnuForm> listDip = new ArrayList<ClesDiplomeAnnuForm>();
for (ClesDiplomeAnnuForm dip : getCles().getClesDiplomeAnnuForm()) {
index = getExistDipsItems(dip.getCodDip());
if (index == -1) {
listDip.add(dip);
} else {
dipsItems.remove(index);
}
}
for (ClesDiplomeAnnuForm dip : listDip) {
getCles().getClesDiplomeAnnuForm().remove(dip);
//delete Cles2AnnuForm
iApogee.delete(dip);
}
for (SelectItem dipItem : dipsItems) {
ClesDiplomeAnnuForm cleDip = new ClesDiplomeAnnuForm();
cleDip.setCodCles(getCles().getClesAnnuForm().getCodCles());
cleDip.setCodDip((String) dipItem.getValue());
getCles().getClesDiplomeAnnuForm().add(cleDip);
//save Cles2AnnuForm
iApogee.save(cleDip);
}
//update ClesAnnuForm
iApogee.update(getCles().getClesAnnuForm());
reset();
if (log.isDebugEnabled()) {
log.debug("leaving update");
}
}
|
diff --git a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/CVSMergeSubscriberTest.java b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/CVSMergeSubscriberTest.java
index d6e2c19f9..850ee7e2b 100644
--- a/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/CVSMergeSubscriberTest.java
+++ b/tests/org.eclipse.team.tests.cvs.core/src/org/eclipse/team/tests/ccvs/core/subscriber/CVSMergeSubscriberTest.java
@@ -1,616 +1,616 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.team.tests.ccvs.core.subscriber;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.core.resources.*;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.team.core.RepositoryProvider;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.core.synchronize.SyncInfo;
import org.eclipse.team.internal.ccvs.core.*;
import org.eclipse.team.tests.ccvs.core.CVSTestSetup;
/**
* Tests the CVSMergeSubscriber
*/
public class CVSMergeSubscriberTest extends CVSSyncSubscriberTest {
public static Test suite() {
String testName = System.getProperty("eclipse.cvs.testName");
if (testName == null) {
TestSuite suite = new TestSuite(CVSMergeSubscriberTest.class);
return new CVSTestSetup(suite);
} else {
return new CVSTestSetup(new CVSMergeSubscriberTest(testName));
}
}
public CVSMergeSubscriberTest() {
super();
}
public CVSMergeSubscriberTest(String name) {
super(name);
}
private IProject branchProject(IProject project, CVSTag root, CVSTag branch) throws TeamException {
IProject copy = checkoutCopy(project, "-copy");
tagProject(project, root, false);
tagProject(project, branch, false);
updateProject(copy, branch, false);
return copy;
}
private void mergeResources(CVSMergeSubscriber subscriber, IProject project, String[] resourcePaths, boolean allowOverwrite) throws CoreException, TeamException, InvocationTargetException, InterruptedException {
IResource[] resources = getResources(project, resourcePaths);
getSyncInfoSource().mergeResources(subscriber, resources, allowOverwrite);
}
/**
* Test the basic incoming changes cases
* - incoming addition
* - incoming deletion
* - incoming change
* - incoming addition of a folder containing files
*/
public void testIncomingChanges() throws InvocationTargetException, InterruptedException, CVSException, CoreException, IOException {
// Create a test project
IProject project = createProject("testIncomingChanges", new String[] { "file1.txt", "file2.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"});
// Checkout and branch a copy
CVSTag root = new CVSTag("root_branch1", CVSTag.VERSION);
CVSTag branch = new CVSTag("branch1", CVSTag.BRANCH);
IProject copy = branchProject(project, root, branch);
// Modify the branch
addResources(copy, new String[] {"addition.txt", "folderAddition/", "folderAddition/new.txt"}, true);
deleteResources(copy, new String[] {"folder1/a.txt"}, true);
// modify file1 - make two revisions
appendText(copy.getFile("file1.txt"), "Appended text 1", false);
commitProject(copy);
appendText(copy.getFile("file1.txt"), "Appended text 2", false);
commitProject(copy);
// modify file2 in both branch and head and ensure it's merged properly
appendText(copy.getFile("file2.txt"), "appended text", false);
commitProject(copy);
appendText(project.getFile("file2.txt"), "prefixed text", true);
commitProject(project);
// create a merge subscriber
CVSMergeSubscriber subscriber = getSyncInfoSource().createMergeSubscriber(project, root, branch);
// check the sync states
assertSyncEquals("testIncomingChanges", subscriber, project,
new String[]{"file1.txt", "file2.txt", "folder1/", "folder1/a.txt", "addition.txt", "folderAddition/", "folderAddition/new.txt"},
true,
new int[]{
SyncInfo.INCOMING | SyncInfo.CHANGE,
SyncInfo.CONFLICTING | SyncInfo.CHANGE,
SyncInfo.IN_SYNC,
SyncInfo.INCOMING | SyncInfo.DELETION,
SyncInfo.INCOMING | SyncInfo.ADDITION,
SyncInfo.INCOMING | SyncInfo.ADDITION,
SyncInfo.INCOMING | SyncInfo.ADDITION});
// Perform a merge
mergeResources(subscriber, project, new String[]{"file1.txt", "file2.txt", "folder1/a.txt", "addition.txt", "folderAddition/", "folderAddition/new.txt"}, true);
// check the sync states for the workspace subscriber
assertSyncEquals("testIncomingChanges", getWorkspaceSubscriber(), project,
new String[] { "file1.txt", "file2.txt", "folder1/", "folder1/a.txt", "addition.txt", "folderAddition/", "folderAddition/new.txt"},
true, new int[] {
SyncInfo.OUTGOING | SyncInfo.CHANGE,
SyncInfo.OUTGOING | SyncInfo.CHANGE,
SyncInfo.IN_SYNC,
SyncInfo.OUTGOING | SyncInfo.DELETION,
SyncInfo.OUTGOING | SyncInfo.ADDITION,
SyncInfo.IN_SYNC,
SyncInfo.OUTGOING | SyncInfo.ADDITION});
assertEndsWith(project.getFile("file1.txt"), "Appended text 1" + eol + "Appended text 2");
assertStartsWith(project.getFile("file2.txt"), "prefixed text");
assertEndsWith(project.getFile("file2.txt"), "appended text");
}
/**
* This tests tests that the cvs update command is sent properly with the two -j options to merge
* contents between two revisions into the workspaoce.
*/
public void test46007() throws InvocationTargetException, InterruptedException, CVSException, CoreException, IOException {
// Create a test project
IProject project = createProject("test46007", new String[] { "file1.txt" });
appendText(project.getFile("file1.txt"), "dummy", true);
commitProject(project);
// Checkout and branch a copy
CVSTag root = new CVSTag("root_branch1", CVSTag.VERSION);
CVSTag branch = new CVSTag("branch1", CVSTag.BRANCH);
IProject copy = branchProject(project, root, branch);
// modify file1
appendText(copy.getFile("file1.txt"), "Appended text 1", true);
commitProject(copy);
CVSTag root2 = new CVSTag("v1", CVSTag.VERSION);
tagProject(copy, root2, true);
appendText(copy.getFile("file1.txt"), "Appended text 2", false);
commitProject(copy);
CVSTag root3 = new CVSTag("v2", CVSTag.VERSION);
tagProject(copy, root3, true);
CVSMergeSubscriber subscriber = getSyncInfoSource().createMergeSubscriber(project, root2, root3);
assertSyncEquals("test46007", subscriber, project,
new String[]{"file1.txt"},
true,
new int[]{SyncInfo.CONFLICTING | SyncInfo.CHANGE});
mergeResources(subscriber, project, new String[]{"file1.txt"}, true);
assertSyncEquals("test46007", getWorkspaceSubscriber(), project,
new String[] { "file1.txt"},
true, new int[] {SyncInfo.OUTGOING | SyncInfo.CHANGE});
// the change made before v1 in the branch should not of been merged into the
// workspace since the start/end points do not include those changed. Hence,
// the two -j options sent to the cvs server.
assertEndsWith(project.getFile("file1.txt"), "Appended text 2");
assertStartsWith(project.getFile("file1.txt"), "dummy");
}
public void testMergableConflicts() throws IOException, TeamException, CoreException, InvocationTargetException, InterruptedException {
// Create a test project
IProject project = createProject("testMergableConflicts", new String[] { "file1.txt", "file2.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"});
setContentsAndEnsureModified(project.getFile("file1.txt"), "some text\nwith several lines\n");
setContentsAndEnsureModified(project.getFile("file2.txt"), "some text\nwith several lines\n");
commitProject(project);
// Checkout and branch a copy
CVSTag root = new CVSTag("root_branch1", CVSTag.VERSION);
CVSTag branch = new CVSTag("branch1", CVSTag.BRANCH);
IProject branchedProject = branchProject(project, root, branch);
// modify the branch
appendText(branchedProject.getFile("file1.txt"), "first line\n", true);
appendText(branchedProject.getFile("file2.txt"), "last line\n", false);
commitProject(branchedProject);
// modify HEAD
appendText(project.getFile("file1.txt"), "last line\n", false);
commitProject(project);
// have one local change
appendText(project.getFile("file2.txt"), "first line\n", true);
// create a merge subscriber
CVSMergeSubscriber subscriber = getSyncInfoSource().createMergeSubscriber(project, root, branch);
// check the sync states
assertSyncEquals("testMergableConflicts", subscriber, project,
new String[] { "file1.txt", "file2.txt"},
true, new int[] {
SyncInfo.CONFLICTING | SyncInfo.CHANGE,
SyncInfo.CONFLICTING | SyncInfo.CHANGE});
// Perform a merge
mergeResources(subscriber, project, new String[] {
"file1.txt",
"file2.txt"},
false /* allow overwrite */);
// check the sync states for the workspace subscriber
assertSyncEquals("testMergableConflicts", getWorkspaceSubscriber(), project,
new String[] { "file1.txt", "file2.txt"},
true, new int[] {
SyncInfo.OUTGOING | SyncInfo.CHANGE,
SyncInfo.OUTGOING | SyncInfo.CHANGE});
//TODO: How do we know if the right thing happened to the file contents?
}
public void testUnmergableConflicts() throws IOException, TeamException, CoreException, InvocationTargetException, InterruptedException {
// Create a test project
IProject project = createProject("testUnmergableConflicts", new String[] { "delete.txt", "file1.txt", "file2.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"});
setContentsAndEnsureModified(project.getFile("file1.txt"), "some text\nwith several lines\n");
setContentsAndEnsureModified(project.getFile("file2.txt"), "some text\nwith several lines\n");
commitProject(project);
// Checkout and branch a copy
CVSTag root = new CVSTag("root_branch1", CVSTag.VERSION);
CVSTag branch = new CVSTag("branch1", CVSTag.BRANCH);
IProject branchedProject = branchProject(project, root, branch);
// modify the branch
appendText(branchedProject.getFile("file1.txt"), "first line\n", true);
appendText(branchedProject.getFile("file2.txt"), "last line\n", false);
addResources(branchedProject, new String[] {"addition.txt"}, false);
deleteResources(branchedProject, new String[] {"delete.txt", "folder1/a.txt"}, false);
setContentsAndEnsureModified(branchedProject.getFile("folder1/b.txt"));
commitProject(branchedProject);
// modify local workspace
appendText(project.getFile("file1.txt"), "conflict line\n", true);
setContentsAndEnsureModified(project.getFile("folder1/a.txt"));
deleteResources(project, new String[] {"delete.txt", "folder1/b.txt"}, false);
addResources(project, new String[] {"addition.txt"}, false);
appendText(project.getFile("file2.txt"), "conflict line\n", false);
// create a merge subscriber
CVSMergeSubscriber subscriber = getSyncInfoSource().createMergeSubscriber(project, root, branch);
// check the sync states
assertSyncEquals("testUnmergableConflicts", subscriber, project,
new String[] { "delete.txt", "file1.txt", "file2.txt", "addition.txt", "folder1/a.txt", "folder1/b.txt"},
true, new int[] {
SyncInfo.IN_SYNC, /* TODO: is this OK */
SyncInfo.CONFLICTING | SyncInfo.CHANGE,
SyncInfo.CONFLICTING | SyncInfo.CHANGE,
SyncInfo.CONFLICTING | SyncInfo.ADDITION,
SyncInfo.CONFLICTING | SyncInfo.CHANGE,
SyncInfo.CONFLICTING | SyncInfo.CHANGE});
// TODO: Should actually perform the merge and check the results
// However, this would require the changes to be redone
// commit to modify HEAD
commitProject(project);
// check the sync states
assertSyncEquals("testUnmergableConflicts", subscriber, project,
new String[] { "delete.txt", "file1.txt", "file2.txt", "addition.txt", "folder1/a.txt", "folder1/b.txt"},
true, new int[] {
SyncInfo.IN_SYNC, /* TODO: is this OK */
SyncInfo.CONFLICTING | SyncInfo.CHANGE,
SyncInfo.CONFLICTING | SyncInfo.CHANGE,
SyncInfo.CONFLICTING | SyncInfo.ADDITION,
SyncInfo.CONFLICTING | SyncInfo.CHANGE,
SyncInfo.CONFLICTING | SyncInfo.CHANGE});
// Perform a merge
mergeResources(subscriber, project, new String[] { "delete.txt", "file1.txt", "file2.txt", "addition.txt", "folder1/a.txt", "folder1/b.txt"}, true /* allow overwrite */);
// check the sync states for the workspace subscriber
assertSyncEquals("testUnmergableConflicts", getWorkspaceSubscriber(), project,
new String[] { "file1.txt", "file2.txt", "addition.txt", "folder1/a.txt", "folder1/b.txt"},
true, new int[] {
SyncInfo.OUTGOING | SyncInfo.CHANGE,
SyncInfo.OUTGOING | SyncInfo.CHANGE,
SyncInfo.OUTGOING | SyncInfo.CHANGE,
SyncInfo.OUTGOING | SyncInfo.DELETION,
SyncInfo.OUTGOING | SyncInfo.ADDITION});
assertDeleted("testUnmergableConflicts", project, new String[] { "delete.txt" });
//TODO: How do we know if the right thing happend to the file contents?
}
public void testLocalScrub() throws IOException, TeamException, CoreException, InvocationTargetException, InterruptedException {
// Create a test project
IProject project = createProject("testLocalScrub", new String[] { "delete.txt", "file1.txt", "file2.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"});
setContentsAndEnsureModified(project.getFile("file1.txt"), "some text\nwith several lines\n");
setContentsAndEnsureModified(project.getFile("file2.txt"), "some text\nwith several lines\n");
commitProject(project);
// Checkout and branch a copy
CVSTag root = new CVSTag("root_branch1", CVSTag.VERSION);
CVSTag branch = new CVSTag("branch1", CVSTag.BRANCH);
IProject branchedProject = branchProject(project, root, branch);
// modify the branch
appendText(branchedProject.getFile("file1.txt"), "first line\n", true);
appendText(branchedProject.getFile("file2.txt"), "last line\n", false);
addResources(branchedProject, new String[] {"addition.txt"}, false);
deleteResources(branchedProject, new String[] {"delete.txt", "folder1/a.txt"}, false);
setContentsAndEnsureModified(branchedProject.getFile("folder1/b.txt"));
commitProject(branchedProject);
// create a merge subscriber
CVSMergeSubscriber subscriber = getSyncInfoSource().createMergeSubscriber(project, root, branch);
// check the sync states
assertSyncEquals("testLocalScrub", subscriber, project,
new String[] { "delete.txt", "file1.txt", "file2.txt", "addition.txt", "folder1/a.txt", "folder1/b.txt"},
true, new int[] {
SyncInfo.INCOMING | SyncInfo.DELETION,
SyncInfo.INCOMING | SyncInfo.CHANGE,
SyncInfo.INCOMING | SyncInfo.CHANGE,
SyncInfo.INCOMING | SyncInfo.ADDITION,
SyncInfo.INCOMING | SyncInfo.DELETION,
SyncInfo.INCOMING | SyncInfo.CHANGE});
// scrub the project contents
IResource[] members = project.members();
for (int i = 0; i < members.length; i++) {
IResource resource = members[i];
if (resource.getName().equals(".project")) continue;
resource.delete(false, DEFAULT_MONITOR);
}
// update
mergeResources(subscriber, project,
new String[] {
"delete.txt",
"file1.txt",
"file2.txt",
"addition.txt",
"folder1/a.txt",
"folder1/b.txt"},
true /* allow overwrite */);
// commit
commitProject(project);
}
public void testBug37546MergeWantsToDeleteNewDirectories() throws CVSException, CoreException {
IProject project = createProject("testBug37546", new String[]{"file1.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"});
setContentsAndEnsureModified(project.getFile("file1.txt"), "some text\nwith several lines\n");
commitProject(project);
// Checkout and branch a copy
CVSTag root = new CVSTag("root_branch1", CVSTag.VERSION);
CVSTag branch = new CVSTag("branch1", CVSTag.BRANCH);
IProject branchedProject = branchProject(project, root, branch);
// modify the branch
addResources(branchedProject, new String[] {"folder2/", "folder2/c.txt"}, true);
// modify HEAD and add the same folder
addResources(project, new String[] {"folder2/"}, true);
addResources(project, new String[] {"folder3/"}, true);
addResources(project, new String[] {"folder4/", "folder4/d.txt"}, false);
// create a merge subscriber
CVSMergeSubscriber subscriber = getSyncInfoSource().createMergeSubscriber(project, root, branch);
assertSyncEquals("testBug37546", subscriber, project,
new String[]{"folder2/", "folder2/c.txt", "folder3/", "folder4/", "folder4/d.txt"}, true,
new int[]{
SyncInfo.IN_SYNC,
SyncInfo.INCOMING | SyncInfo.ADDITION,
SyncInfo.IN_SYNC, SyncInfo.IN_SYNC, SyncInfo.IN_SYNC});
}
/*Bug 53129
Outgoing deletions in deleted folders are lost.
*/
public void testOutgoingDeletionAfterMergeBug53129() throws TeamException, CoreException, InvocationTargetException, InterruptedException {
IProject project = createProject("testBug53129", new String[]{"file1.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"});
setContentsAndEnsureModified(project.getFile("file1.txt"), "some text\nwith several lines\n");
commitProject(project);
// Checkout and branch a copy
CVSTag root = new CVSTag("root_branch1", CVSTag.VERSION);
CVSTag branch = new CVSTag("branch1", CVSTag.BRANCH);
IProject branchedProject = branchProject(project, root, branch);
// modify the branch
deleteResources(branchedProject, new String[] {"folder1/a.txt", "folder1/b.txt"}, true);
// create a merge subscriber
CVSMergeSubscriber subscriber = getSyncInfoSource().createMergeSubscriber(project, root, branch);
assertSyncEquals("testBug53129 - 1", subscriber, project,
new String[]{"file1.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"}, true,
new int[]{
SyncInfo.IN_SYNC, SyncInfo.IN_SYNC,
SyncInfo.INCOMING | SyncInfo.DELETION,
SyncInfo.INCOMING | SyncInfo.DELETION});
mergeResources(subscriber, project, new String[]{"folder1/a.txt", "folder1/b.txt"}, true);
assertSyncEquals("testBug53129 - 2", getWorkspaceSubscriber(), project,
new String[]{"file1.txt", "folder1", "folder1/a.txt", "folder1/b.txt"}, true,
new int[]{
SyncInfo.IN_SYNC, SyncInfo.IN_SYNC,
SyncInfo.OUTGOING | SyncInfo.DELETION,
SyncInfo.OUTGOING | SyncInfo.DELETION});
IFolder f = project.getFolder("folder1");
f.delete(true, null);
assertSyncEquals("testBug53129 - 3", getWorkspaceSubscriber(), project,
new String[]{"file1.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"}, true,
new int[]{
SyncInfo.IN_SYNC,
SyncInfo.IN_SYNC,
SyncInfo.OUTGOING | SyncInfo.DELETION,
SyncInfo.OUTGOING | SyncInfo.DELETION});
}
public void testDisconnectingProject() throws CoreException, IOException, TeamException, InterruptedException {
// Create a test project (which commits it as well)
// Create a test project
IProject project = createProject("testDisconnect", new String[] { "file1.txt", "file2.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"});
setContentsAndEnsureModified(project.getFile("file1.txt"), "some text\nwith several lines\n");
setContentsAndEnsureModified(project.getFile("file2.txt"), "some text\nwith several lines\n");
commitProject(project);
// Checkout and branch a copy
CVSTag root = new CVSTag("root_branch1", CVSTag.VERSION);
CVSTag branch = new CVSTag("branch1", CVSTag.BRANCH);
IProject branchedProject = branchProject(project, root, branch);
// modify the branch
appendText(branchedProject.getFile("file1.txt"), "first line\n", true);
appendText(branchedProject.getFile("file2.txt"), "last line\n", false);
commitProject(branchedProject);
// create a merge subscriber
CVSMergeSubscriber subscriber = getSyncInfoSource().createMergeSubscriber(project, root, branch);
RepositoryProvider.unmap(project);
assertProjectRemoved(subscriber, project);
}
public void testMarkAsMerged() throws IOException, TeamException, CoreException, InvocationTargetException, InterruptedException {
// Create a test project
IProject project = createProject("testMarkAsMerged", new String[] { "delete.txt", "file1.txt", "file2.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"});
setContentsAndEnsureModified(project.getFile("file1.txt"), "some text\nwith several lines\n");
setContentsAndEnsureModified(project.getFile("file2.txt"), "some text\nwith several lines\n");
commitProject(project);
// Checkout and branch a copy
CVSTag root = new CVSTag("root_branch1", CVSTag.VERSION);
CVSTag branch = new CVSTag("branch1", CVSTag.BRANCH);
IProject branchedProject = branchProject(project, root, branch);
// modify the branch
appendText(branchedProject.getFile("file1.txt"), "first line\n", true);
appendText(branchedProject.getFile("file2.txt"), "last line\n", false);
addResources(branchedProject, new String[] {"addition.txt"}, false);
deleteResources(branchedProject, new String[] {"delete.txt", "folder1/a.txt"}, false);
setContentsAndEnsureModified(branchedProject.getFile("folder1/b.txt"));
commitProject(branchedProject);
// modify local workspace
appendText(project.getFile("file1.txt"), "conflict line\n", true);
setContentsAndEnsureModified(project.getFile("folder1/a.txt"));
setContentsAndEnsureModified(project.getFile("delete.txt"));
addResources(project, new String[] {"addition.txt"}, false);
appendText(project.getFile("file2.txt"), "conflict line\n", false);
// create a merge subscriber
CVSMergeSubscriber subscriber = getSyncInfoSource().createMergeSubscriber(project, root, branch);
// check the sync states
assertSyncEquals("testMarkAsMergedConflicts", subscriber, project,
new String[] { "delete.txt", "file1.txt", "file2.txt", "addition.txt", "folder1/a.txt"},
true, new int[] {
SyncInfo.CONFLICTING | SyncInfo.CHANGE,
SyncInfo.CONFLICTING | SyncInfo.CHANGE,
SyncInfo.CONFLICTING | SyncInfo.CHANGE,
SyncInfo.CONFLICTING | SyncInfo.ADDITION,
SyncInfo.CONFLICTING | SyncInfo.CHANGE});
markAsMerged(subscriber, project, new String[] { "delete.txt", "file1.txt", "file2.txt", "addition.txt", "folder1/a.txt"});
// check the sync states
assertSyncEquals("testMarkAsMerged", subscriber, project,
new String[] { "delete.txt", "file1.txt", "file2.txt", "addition.txt", "folder1/a.txt"},
true, new int[] {
SyncInfo.IN_SYNC,
SyncInfo.IN_SYNC,
SyncInfo.IN_SYNC,
SyncInfo.IN_SYNC,
SyncInfo.IN_SYNC});
}
/* (non-Javadoc)
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception {
getSyncInfoSource().tearDown();
super.tearDown();
}
public void testDeletedAddition() throws TeamException, CoreException, InvocationTargetException, InterruptedException {
IProject project = createProject("testDeletedAddition", new String[]{"file1.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"});
// Checkout and branch a copy
CVSTag root = new CVSTag("root_branch1", CVSTag.VERSION);
CVSTag branch = new CVSTag("branch1", CVSTag.BRANCH);
IProject branchedProject = branchProject(project, root, branch);
// add a file to the branch
addResources(branchedProject, new String[] {"folder2/", "folder2/added.txt"}, true);
// Setup a merge by creating a merge subscriber
CVSMergeSubscriber subscriber = getSyncInfoSource().createMergeSubscriber(project, root, branch);
assertSyncEquals("testDeletedAddition", subscriber, project,
new String[]{"folder2/", "folder2/added.txt"}, true,
new int[]{
SyncInfo.INCOMING | SyncInfo.ADDITION,
SyncInfo.INCOMING | SyncInfo.ADDITION
});
// Merge the change with HEAD
mergeResources(subscriber, project, new String[]{"folder2/", "folder2/added.txt"}, true);
assertSyncEquals("testDeletedAddition", subscriber, project,
new String[]{"folder2/", "folder2/added.txt"}, true,
new int[]{
SyncInfo.IN_SYNC,
SyncInfo.IN_SYNC
});
// Delete the file from the branch
deleteResources(branchedProject, new String[] {"folder2/added.txt"}, true);
assertSyncEquals("testDeletedAddition", subscriber, project,
new String[]{"folder2/", "folder2/added.txt"}, true,
new int[]{
SyncInfo.IN_SYNC,
SyncInfo.CONFLICTING | SyncInfo.CHANGE
});
}
public void testFileAddedToBranch() throws InvocationTargetException, InterruptedException, CoreException, IOException {
// Create a project
IProject project = createProject(new String[] { "delete.txt", "file1.txt", "file2.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"});
// Checkout and branch a copy
CVSTag root = new CVSTag("root_branch1", CVSTag.VERSION);
CVSTag branch = new CVSTag("branch1", CVSTag.BRANCH);
IProject branchedProject = branchProject(project, root, branch);
// Add a file to the branch
addResources(branchedProject, new String[] {"folder2/", "folder2/added.txt"}, true);
// Merge the file with HEAD but do not commit
CVSMergeSubscriber subscriber = getSyncInfoSource().createMergeSubscriber(project, root, branch);
assertSyncEquals("testFileAddedToBranch", subscriber, project,
new String[]{"folder2/", "folder2/added.txt"}, true,
new int[]{
SyncInfo.INCOMING | SyncInfo.ADDITION,
SyncInfo.INCOMING | SyncInfo.ADDITION
});
mergeResources(subscriber, project, new String[]{"folder2/", "folder2/added.txt"}, true /* allow overwrite */);
// Ensure HEAD matches branch
assertContentsEqual(project, branchedProject);
// Modify the file on the branch
- setContentsAndEnsureModified(branchedProject.getFile("folder2/added.txt"));
+ setContentsAndEnsureModified(branchedProject.getFile("folder2/added.txt"), "Unmergable contents");
commitProject(branchedProject);
// Merge with HEAD again and commit afterwards
assertSyncEquals("testFileAddedToBranch", subscriber, project,
new String[]{"folder2/added.txt"}, true,
new int[]{
SyncInfo.CONFLICTING | SyncInfo.CHANGE
});
mergeResources(subscriber, project, new String[]{"folder2/added.txt"}, true /* allow overwrite */);
commitProject(project);
// Ensure HEAD matches branch
assertContentsEqual(project, branchedProject);
// Modify the file on the branch again
- setContentsAndEnsureModified(branchedProject.getFile("folder2/added.txt"));
+ setContentsAndEnsureModified(branchedProject.getFile("folder2/added.txt"), "More unmergable");
commitProject(branchedProject);
// Merge with HEAD one last time
assertSyncEquals("testFileAddedToBranch", subscriber, project,
new String[]{"folder2/added.txt"}, true,
new int[]{
SyncInfo.CONFLICTING | SyncInfo.CHANGE
});
mergeResources(subscriber, project, new String[]{"folder2/added.txt"}, true /* allow overwrite */);
// Ensure HEAD matches branch
assertContentsEqual(project, branchedProject);
}
}
| false | true | public void testFileAddedToBranch() throws InvocationTargetException, InterruptedException, CoreException, IOException {
// Create a project
IProject project = createProject(new String[] { "delete.txt", "file1.txt", "file2.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"});
// Checkout and branch a copy
CVSTag root = new CVSTag("root_branch1", CVSTag.VERSION);
CVSTag branch = new CVSTag("branch1", CVSTag.BRANCH);
IProject branchedProject = branchProject(project, root, branch);
// Add a file to the branch
addResources(branchedProject, new String[] {"folder2/", "folder2/added.txt"}, true);
// Merge the file with HEAD but do not commit
CVSMergeSubscriber subscriber = getSyncInfoSource().createMergeSubscriber(project, root, branch);
assertSyncEquals("testFileAddedToBranch", subscriber, project,
new String[]{"folder2/", "folder2/added.txt"}, true,
new int[]{
SyncInfo.INCOMING | SyncInfo.ADDITION,
SyncInfo.INCOMING | SyncInfo.ADDITION
});
mergeResources(subscriber, project, new String[]{"folder2/", "folder2/added.txt"}, true /* allow overwrite */);
// Ensure HEAD matches branch
assertContentsEqual(project, branchedProject);
// Modify the file on the branch
setContentsAndEnsureModified(branchedProject.getFile("folder2/added.txt"));
commitProject(branchedProject);
// Merge with HEAD again and commit afterwards
assertSyncEquals("testFileAddedToBranch", subscriber, project,
new String[]{"folder2/added.txt"}, true,
new int[]{
SyncInfo.CONFLICTING | SyncInfo.CHANGE
});
mergeResources(subscriber, project, new String[]{"folder2/added.txt"}, true /* allow overwrite */);
commitProject(project);
// Ensure HEAD matches branch
assertContentsEqual(project, branchedProject);
// Modify the file on the branch again
setContentsAndEnsureModified(branchedProject.getFile("folder2/added.txt"));
commitProject(branchedProject);
// Merge with HEAD one last time
assertSyncEquals("testFileAddedToBranch", subscriber, project,
new String[]{"folder2/added.txt"}, true,
new int[]{
SyncInfo.CONFLICTING | SyncInfo.CHANGE
});
mergeResources(subscriber, project, new String[]{"folder2/added.txt"}, true /* allow overwrite */);
// Ensure HEAD matches branch
assertContentsEqual(project, branchedProject);
}
| public void testFileAddedToBranch() throws InvocationTargetException, InterruptedException, CoreException, IOException {
// Create a project
IProject project = createProject(new String[] { "delete.txt", "file1.txt", "file2.txt", "folder1/", "folder1/a.txt", "folder1/b.txt"});
// Checkout and branch a copy
CVSTag root = new CVSTag("root_branch1", CVSTag.VERSION);
CVSTag branch = new CVSTag("branch1", CVSTag.BRANCH);
IProject branchedProject = branchProject(project, root, branch);
// Add a file to the branch
addResources(branchedProject, new String[] {"folder2/", "folder2/added.txt"}, true);
// Merge the file with HEAD but do not commit
CVSMergeSubscriber subscriber = getSyncInfoSource().createMergeSubscriber(project, root, branch);
assertSyncEquals("testFileAddedToBranch", subscriber, project,
new String[]{"folder2/", "folder2/added.txt"}, true,
new int[]{
SyncInfo.INCOMING | SyncInfo.ADDITION,
SyncInfo.INCOMING | SyncInfo.ADDITION
});
mergeResources(subscriber, project, new String[]{"folder2/", "folder2/added.txt"}, true /* allow overwrite */);
// Ensure HEAD matches branch
assertContentsEqual(project, branchedProject);
// Modify the file on the branch
setContentsAndEnsureModified(branchedProject.getFile("folder2/added.txt"), "Unmergable contents");
commitProject(branchedProject);
// Merge with HEAD again and commit afterwards
assertSyncEquals("testFileAddedToBranch", subscriber, project,
new String[]{"folder2/added.txt"}, true,
new int[]{
SyncInfo.CONFLICTING | SyncInfo.CHANGE
});
mergeResources(subscriber, project, new String[]{"folder2/added.txt"}, true /* allow overwrite */);
commitProject(project);
// Ensure HEAD matches branch
assertContentsEqual(project, branchedProject);
// Modify the file on the branch again
setContentsAndEnsureModified(branchedProject.getFile("folder2/added.txt"), "More unmergable");
commitProject(branchedProject);
// Merge with HEAD one last time
assertSyncEquals("testFileAddedToBranch", subscriber, project,
new String[]{"folder2/added.txt"}, true,
new int[]{
SyncInfo.CONFLICTING | SyncInfo.CHANGE
});
mergeResources(subscriber, project, new String[]{"folder2/added.txt"}, true /* allow overwrite */);
// Ensure HEAD matches branch
assertContentsEqual(project, branchedProject);
}
|
diff --git a/libraries/lib-segmentation-ui/src/main/java/net/sf/okapi/lib/ui/segmentation/SRXEditor.java b/libraries/lib-segmentation-ui/src/main/java/net/sf/okapi/lib/ui/segmentation/SRXEditor.java
index 6cb177185..b76ab028f 100644
--- a/libraries/lib-segmentation-ui/src/main/java/net/sf/okapi/lib/ui/segmentation/SRXEditor.java
+++ b/libraries/lib-segmentation-ui/src/main/java/net/sf/okapi/lib/ui/segmentation/SRXEditor.java
@@ -1,1062 +1,1063 @@
/*===========================================================================
Copyright (C) 2008-2009 by the Okapi Framework contributors
-----------------------------------------------------------------------------
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html
===========================================================================*/
package net.sf.okapi.lib.ui.segmentation;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import net.sf.okapi.common.IHelp;
import net.sf.okapi.common.LocaleId;
import net.sf.okapi.common.Util;
import net.sf.okapi.common.filterwriter.GenericContent;
import net.sf.okapi.common.resource.TextContainer;
import net.sf.okapi.common.ui.AboutDialog;
import net.sf.okapi.common.ui.CharacterInfoDialog;
import net.sf.okapi.common.ui.Dialogs;
import net.sf.okapi.common.ui.InputDialog;
import net.sf.okapi.common.ui.ResourceManager;
import net.sf.okapi.common.ui.UIUtil;
import net.sf.okapi.common.ui.UserConfiguration;
import net.sf.okapi.lib.segmentation.ISegmenter;
import net.sf.okapi.lib.segmentation.LanguageMap;
import net.sf.okapi.lib.segmentation.Rule;
import net.sf.okapi.lib.segmentation.SRXDocument;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.dnd.TransferData;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.events.ShellListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
public class SRXEditor {
private static final String APPNAME = "Ratel"; //$NON-NLS-1$
private Shell shell;
private Text edSampleText;
private Text edResults;
private Table tblRules;
private RulesTableModel rulesTableMod;
private Combo cbGroup;
private SRXDocument srxDoc;
private ISegmenter segmenter;
private String srxPath;
private TextContainer sampleText;
private Button btAddRule;
private Button btEditRule;
private Button btRemoveRule;
private Button btMoveUpRule;
private Button btMoveDownRule;
private Button rdTestOnLanguage;
private Button rdTestOnSelectedGroup;
private Text edSampleLanguage;
private GenericContent sampleOutput;
private Font sampleFont;
private ResourceManager rm;
private FileProcessor fileProc;
private String testInputPath;
private String testOutputPath;
private boolean htmlOutput;
private UserConfiguration config;
private IHelp help;
@Override
protected void finalize () {
dispose();
}
/**
* Creates a new SRXEditor dialog.
* @param parent the parent shell.
* @param asDialog true if used from another program.
* @param helpParam the help engine to use.
*/
public SRXEditor (Shell parent,
boolean asDialog,
IHelp helpParam)
{
config = new UserConfiguration();
config.load(APPNAME);
testInputPath = config.getProperty("testInputPath"); //$NON-NLS-1$
testOutputPath = config.getProperty("testOutputPath"); //$NON-NLS-1$
htmlOutput = config.getBoolean("htmlOutput"); //$NON-NLS-1$
help = helpParam;
srxDoc = new SRXDocument();
srxPath = null;
sampleText = new TextContainer(null);
sampleOutput = new GenericContent();
fileProc = new FileProcessor();
if ( asDialog ) {
shell = new Shell(parent, SWT.CLOSE | SWT.TITLE | SWT.RESIZE | SWT.MAX | SWT.MIN | SWT.APPLICATION_MODAL);
}
else {
shell = parent;
}
rm = new ResourceManager(SRXEditor.class, shell.getDisplay());
rm.loadCommands("net.sf.okapi.lib.ui.segmentation.Commands"); //$NON-NLS-1$
rm.addImages("ratel", "ratel16", "ratel32"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
shell.setImages(rm.getImages("ratel")); //$NON-NLS-1$
GridLayout layout = new GridLayout();
shell.setLayout(layout);
createMenus();
SashForm sashForm = new SashForm(shell, SWT.VERTICAL);
sashForm.setLayoutData(new GridData(GridData.FILL_BOTH));
sashForm.setSashWidth(3);
sashForm.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW));
Composite cmpTmp = new Composite(sashForm, SWT.BORDER);
cmpTmp.setLayoutData(new GridData(GridData.FILL_BOTH));
GridLayout layTmp = new GridLayout(6, false);
cmpTmp.setLayout(layTmp);
Label label = new Label(cmpTmp, SWT.NONE);
label.setText(Res.getString("edit.currentLangRules")); //$NON-NLS-1$
GridData gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.horizontalSpan = 4;
label.setLayoutData(gdTmp);
cbGroup = new Combo(cmpTmp, SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.horizontalSpan = 5;
cbGroup.setLayoutData(gdTmp);
cbGroup.setVisibleItemCount(15);
cbGroup.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updateRules(0, false);
};
});
int topButtonsWidth = 180;
Button btTmp = new Button(cmpTmp, SWT.PUSH);
btTmp.setText(Res.getString("edit.groupAndOptions")); //$NON-NLS-1$
gdTmp = new GridData();
btTmp.setLayoutData(gdTmp);
UIUtil.ensureWidth(btTmp, topButtonsWidth);
btTmp.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editGroupsAndOptions();
}
});
tblRules = new Table(cmpTmp, SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION | SWT.CHECK);
tblRules.setHeaderVisible(true);
tblRules.setLinesVisible(true);
gdTmp = new GridData(GridData.FILL_BOTH);
gdTmp.horizontalSpan = 6;
gdTmp.minimumHeight = 130;
tblRules.setLayoutData(gdTmp);
tblRules.addControlListener(new ControlAdapter() {
public void controlResized(ControlEvent e) {
Rectangle rect = tblRules.getClientArea();
//TODO: Check behavior when manual resize a column width out of client area
int typeColWidth = 75;
int nHalf = (int)((rect.width-typeColWidth) / 2);
tblRules.getColumn(0).setWidth(typeColWidth);
tblRules.getColumn(1).setWidth(nHalf);
tblRules.getColumn(2).setWidth(nHalf);
}
});
tblRules.addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent e) {
editRule(false);
}
public void mouseDown(MouseEvent e) {}
public void mouseUp(MouseEvent e) {}
});
tblRules.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
- if (e.detail == SWT.CHECK) {
+ if ( e.detail == SWT.CHECK ) {
+ tblRules.setSelection((TableItem)e.item); // Force selection to move if needed
int n = tblRules.getSelectionIndex();
if ( n < 0 ) return;
String ruleName = cbGroup.getItem(cbGroup.getSelectionIndex());
srxDoc.getLanguageRules(ruleName).get(n).setActive(((TableItem)e.item).getChecked());
srxDoc.setModified(true);
updateResults(true);
}
updateRulesButtons();
};
});
rulesTableMod = new RulesTableModel();
rulesTableMod.linkTable(tblRules);
Composite cmpGroup = new Composite(cmpTmp, SWT.NONE);
layTmp = new GridLayout(7, true);
layTmp.marginHeight = 0;
layTmp.marginWidth = 0;
cmpGroup.setLayout(layTmp);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.horizontalSpan = 6;
cmpGroup.setLayoutData(gdTmp);
btAddRule = new Button(cmpGroup, SWT.PUSH);
btAddRule.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btAddRule.setText(Res.getString("edit.btAddRule")); //$NON-NLS-1$
btAddRule.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editRule(true);
}
});
btEditRule = new Button(cmpGroup, SWT.PUSH);
btEditRule.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btEditRule.setText(Res.getString("edit.btEditRule")); //$NON-NLS-1$
btEditRule.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editRule(false);
}
});
btRemoveRule = new Button(cmpGroup, SWT.PUSH);
btRemoveRule.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btRemoveRule.setText(Res.getString("edit.btRemoveRule")); //$NON-NLS-1$
btRemoveRule.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
removeRule();
}
});
btMoveUpRule = new Button(cmpGroup, SWT.PUSH);
btMoveUpRule.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btMoveUpRule.setText(Res.getString("edit.moveUp")); //$NON-NLS-1$
btMoveUpRule.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
moveUpRule();
}
});
btMoveDownRule = new Button(cmpGroup, SWT.PUSH);
btMoveDownRule.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btMoveDownRule.setText(Res.getString("edit.moveDown")); //$NON-NLS-1$
btMoveDownRule.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
moveDownRule();
}
});
Button btMaskRule = new Button(cmpGroup, SWT.PUSH);
btMaskRule.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btMaskRule.setText(Res.getString("edit.maskRule")); //$NON-NLS-1$
btMaskRule.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editMaskRule();
}
});
Button btCharInfo = new Button(cmpGroup, SWT.PUSH);
btCharInfo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btCharInfo.setText(Res.getString("edit.charInfo")); //$NON-NLS-1$
btCharInfo.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
showCharInfo();
}
});
//--- Sample block
Composite cmpSample = new Composite(sashForm, SWT.BORDER);
cmpSample.setLayoutData(new GridData(GridData.FILL_BOTH));
cmpSample.setLayout(new GridLayout(3, false));
label = new Label(cmpSample, SWT.None);
label.setText(Res.getString("edit.sampleNote")); //$NON-NLS-1$
gdTmp = new GridData();
gdTmp.horizontalSpan = 3;
label.setLayoutData(gdTmp);
int sampleMinHeight = 40;
edSampleText = new Text(cmpSample, SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
gdTmp = new GridData(GridData.FILL_BOTH);
gdTmp.minimumHeight = sampleMinHeight;
gdTmp.horizontalSpan = 3;
edSampleText.setLayoutData(gdTmp);
Font font = edSampleText.getFont();
FontData[] fontData = font.getFontData();
fontData[0].setHeight(fontData[0].getHeight()+2);
sampleFont = new Font(font.getDevice(), fontData[0]);
edSampleText.setFont(sampleFont);
rdTestOnSelectedGroup = new Button(cmpSample, SWT.RADIO);
rdTestOnSelectedGroup.setText(Res.getString("edit.testOnlyGroup")); //$NON-NLS-1$
rdTestOnSelectedGroup.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
edSampleLanguage.setEnabled(rdTestOnLanguage.getSelection());
updateRules(tblRules.getSelectionIndex(), true);
};
});
rdTestOnLanguage = new Button(cmpSample, SWT.RADIO);
rdTestOnLanguage.setText(Res.getString("edit.testLanguage")); //$NON-NLS-1$
rdTestOnLanguage.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
edSampleLanguage.setEnabled(rdTestOnLanguage.getSelection());
updateRules(tblRules.getSelectionIndex(), true);
};
});
edSampleLanguage = new Text(cmpSample, SWT.BORDER | SWT.SINGLE);
gdTmp = new GridData();
edSampleLanguage.setLayoutData(gdTmp);
edSampleLanguage.addModifyListener(new ModifyListener () {
public void modifyText(ModifyEvent e) {
updateResults(false);
}
});
edResults = new Text(cmpSample, SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
gdTmp = new GridData(GridData.FILL_BOTH);
edResults.setLayoutData(gdTmp);
gdTmp.minimumHeight = sampleMinHeight;
gdTmp.horizontalSpan = 3;
edResults.setEditable(false);
edResults.setFont(sampleFont);
edSampleText.addModifyListener(new ModifyListener () {
public void modifyText(ModifyEvent e) {
updateResults(false);
}
});
// Handling of the closing event
shell.addShellListener(new ShellListener() {
public void shellActivated(ShellEvent event) {}
public void shellClosed(ShellEvent event) {
if ( !checkIfRulesNeedSaving() ) event.doit = false;
}
public void shellDeactivated(ShellEvent event) {}
public void shellDeiconified(ShellEvent event) {}
public void shellIconified(ShellEvent event) {}
});
// Drop target for opening project
DropTarget dropTarget = new DropTarget(shell, DND.DROP_DEFAULT | DND.DROP_COPY | DND.DROP_MOVE);
dropTarget.setTransfer(new FileTransfer[]{FileTransfer.getInstance()});
dropTarget.addDropListener(new DropTargetAdapter() {
public void drop (DropTargetEvent e) {
FileTransfer FT = FileTransfer.getInstance();
if ( FT.isSupportedType(e.currentDataType) ) {
String[] paths = (String[])e.data;
if ( paths != null ) {
loadSRXDocument(paths[0]);
}
}
}
});
// Size
shell.pack();
shell.setMinimumSize(shell.getSize());
Point startSize = shell.getMinimumSize();
if ( startSize.x < 700 ) startSize.x = 700;
if ( startSize.y < 600 ) startSize.y = 600;
shell.setSize(startSize);
if ( asDialog ) {
Dialogs.centerWindow(shell, parent);
}
updateCaption();
updateAll();
}
private void createMenus () {
// Menus
Menu menuBar = new Menu(shell, SWT.BAR);
shell.setMenuBar(menuBar);
//=== File menu
MenuItem topItem = new MenuItem(menuBar, SWT.CASCADE);
topItem.setText(rm.getCommandLabel("file")); //$NON-NLS-1$
Menu dropMenu = new Menu(shell, SWT.DROP_DOWN);
topItem.setMenu(dropMenu);
MenuItem menuItem = new MenuItem(dropMenu, SWT.PUSH);
rm.setCommand(menuItem, "file.new"); //$NON-NLS-1$
menuItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
newSRXDocument(false);
}
});
menuItem = new MenuItem(dropMenu, SWT.PUSH);
rm.setCommand(menuItem, "file.newWithSample"); //$NON-NLS-1$
menuItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
newSRXDocument(true);
}
});
new MenuItem(dropMenu, SWT.SEPARATOR);
menuItem = new MenuItem(dropMenu, SWT.PUSH);
rm.setCommand(menuItem, "file.open"); //$NON-NLS-1$
menuItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
loadSRXDocument(null);
}
});
menuItem = new MenuItem(dropMenu, SWT.PUSH);
rm.setCommand(menuItem, "file.loadFromClipboard"); //$NON-NLS-1$
menuItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
loadSRXDocumentfromClipboard();
}
});
new MenuItem(dropMenu, SWT.SEPARATOR);
menuItem = new MenuItem(dropMenu, SWT.PUSH);
rm.setCommand(menuItem, "file.save"); //$NON-NLS-1$
menuItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
saveSRXDocument(srxPath);
}
});
menuItem = new MenuItem(dropMenu, SWT.PUSH);
rm.setCommand(menuItem, "file.saveas"); //$NON-NLS-1$
menuItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
saveSRXDocument(null);
}
});
menuItem = new MenuItem(dropMenu, SWT.PUSH);
rm.setCommand(menuItem, "file.copyToClipboard"); //$NON-NLS-1$
menuItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
copySRXDocumentToClipboard();
}
});
new MenuItem(dropMenu, SWT.SEPARATOR);
menuItem = new MenuItem(dropMenu, SWT.PUSH);
rm.setCommand(menuItem, "file.exit"); //$NON-NLS-1$
menuItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
shell.close();
}
});
//=== Tools menu
topItem = new MenuItem(menuBar, SWT.CASCADE);
topItem.setText(rm.getCommandLabel("tools")); //$NON-NLS-1$
dropMenu = new Menu(shell, SWT.DROP_DOWN);
topItem.setMenu(dropMenu);
menuItem = new MenuItem(dropMenu, SWT.PUSH);
rm.setCommand(menuItem, "tools.segfile"); //$NON-NLS-1$
menuItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
segmentTextFile();
}
});
//=== Help menu
topItem = new MenuItem(menuBar, SWT.CASCADE);
topItem.setText(rm.getCommandLabel("help")); //$NON-NLS-1$
dropMenu = new Menu(shell, SWT.DROP_DOWN);
topItem.setMenu(dropMenu);
menuItem = new MenuItem(dropMenu, SWT.PUSH);
rm.setCommand(menuItem, "help.topics"); //$NON-NLS-1$
menuItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
if ( help != null ) help.showTopic(this, "index"); //$NON-NLS-1$
}
});
menuItem = new MenuItem(dropMenu, SWT.PUSH);
rm.setCommand(menuItem, "help.howtouse"); //$NON-NLS-1$
menuItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
if ( help != null ) help.showTopic(this, "index", "howTo.html"); //$NON-NLS-1$ //$NON-NLS-2$
}
});
new MenuItem(dropMenu, SWT.SEPARATOR);
menuItem = new MenuItem(dropMenu, SWT.PUSH);
rm.setCommand(menuItem, "help.update"); //$NON-NLS-1$
menuItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
UIUtil.start("http://okapi.opentag.com/updates?" //$NON-NLS-1$
+ getClass().getPackage().getImplementationTitle()
+ "=" //$NON-NLS-1$
+ getClass().getPackage().getImplementationVersion());
}
});
menuItem = new MenuItem(dropMenu, SWT.PUSH);
rm.setCommand(menuItem, "help.feedback"); //$NON-NLS-1$
menuItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
UIUtil.start("mailto:[email protected]&subject=Feedback (Ratel: SRX Editor)"); //$NON-NLS-1$
}
});
menuItem = new MenuItem(dropMenu, SWT.PUSH);
rm.setCommand(menuItem, "help.bugreport"); //$NON-NLS-1$
menuItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
UIUtil.start("http://code.google.com/p/okapi/issues/list"); //$NON-NLS-1$
}
});
menuItem = new MenuItem(dropMenu, SWT.PUSH);
rm.setCommand(menuItem, "help.featurerequest"); //$NON-NLS-1$
menuItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
UIUtil.start("http://code.google.com/p/okapi/issues/list"); //$NON-NLS-1$
}
});
menuItem = new MenuItem(dropMenu, SWT.PUSH);
rm.setCommand(menuItem, "help.users"); //$NON-NLS-1$
menuItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
UIUtil.start("http://groups.yahoo.com/group/okapitools/"); //$NON-NLS-1$
}
});
menuItem = new MenuItem(dropMenu, SWT.SEPARATOR);
menuItem = new MenuItem(dropMenu, SWT.PUSH);
rm.setCommand(menuItem, "help.srx20"); //$NON-NLS-1$
menuItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
UIUtil.start("http://www.lisa.org/fileadmin/standards/srx20.html"); //$NON-NLS-1$
}
});
menuItem = new MenuItem(dropMenu, SWT.SEPARATOR);
menuItem = new MenuItem(dropMenu, SWT.PUSH);
rm.setCommand(menuItem, "help.about"); //$NON-NLS-1$
menuItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
AboutDialog dlg = new AboutDialog(shell,
Res.getString("SRXEditor.aboutCaption"), //$NON-NLS-1$
Res.getString("SRXEditor.aboutDescription"), //$NON-NLS-1$
getClass().getPackage().getImplementationVersion());
dlg.showDialog();
}
});
}
public void dispose () {
if ( sampleFont != null ) {
sampleFont.dispose();
sampleFont = null;
}
if ( rm != null ) {
rm.dispose();
}
}
private void showCharInfo () {
try {
CharacterInfoDialog charInfoDlg = new CharacterInfoDialog(shell,
Res.getString("edit.charInfoCaption"), help); //$NON-NLS-1$
int codePoint = 225;
String tmp = edSampleText.getSelectionText();
if ( tmp.length() > 0 ) {
codePoint = tmp.codePointAt(0);
}
charInfoDlg.showDialog(codePoint);
}
catch ( Throwable e ) {
Dialogs.showError(shell, e.getMessage(), null);
}
}
/**
* Opens the dialog box, loads an SRX document if one is specified.
* @param path Optional SRX document to load. Use null to load nothing.
*/
public void showDialog (String path) {
shell.open();
if ( path != null ) loadSRXDocument(path);
while ( !shell.isDisposed() ) {
if ( !shell.getDisplay().readAndDispatch() )
shell.getDisplay().sleep();
}
}
/**
* Gets the full path of the last SRX document loaded.
* @return The full path of the last SRX document loaded, or null
* if not has been loaded.
*/
public String getPath () {
return srxPath;
}
private void updateResults (boolean forceReset) {
try {
// Check if we need to re-build the list of applicable rules
if ( cbGroup.getSelectionIndex() != -1 ) {
// Both methods applies new rules only if the
// parameter passed is different from the current identifier
// or if forceReset is true.
if ( rdTestOnSelectedGroup.getSelection() ) {
segmenter = srxDoc.compileSingleLanguageRule(cbGroup.getText(),
(forceReset ? null : segmenter));
}
else { // Applies all the matching rules
// Make sure we have a language code
if ( edSampleLanguage.getText().length() == 0 ) {
edSampleLanguage.setText("en"); //$NON-NLS-1$
}
segmenter = srxDoc.compileLanguageRules(
LocaleId.fromString(edSampleLanguage.getText()),
(forceReset ? null : segmenter));
}
}
else { // No selection
segmenter = null;
}
if (( segmenter != null ) && ( segmenter.getLanguage() != null )) {
// Converts the <x>/</x>/etc. into real inline codes
fileProc.populateTextContainer(
edSampleText.getText().replace("\r", ""), sampleText); //$NON-NLS-1$ //$NON-NLS-2$
// Segment
segmenter.computeSegments(sampleText);
sampleText.createSegments(segmenter.getRanges());
// Create the output in generic format
edResults.setText(sampleOutput.printSegmentedContent(sampleText, true, true));
}
else {
edResults.setText(""); //$NON-NLS-1$
}
}
catch ( Throwable e ) {
edResults.setText(Res.getString("edit.error")+ e.getMessage()); //$NON-NLS-1$
}
}
private void updateLanguageRuleList () {
cbGroup.removeAll();
LinkedHashMap<String, ArrayList<Rule>> langRules = srxDoc.getAllLanguageRules();
for ( String ruleName : langRules.keySet() ) {
cbGroup.add(ruleName);
}
if ( cbGroup.getItemCount() > 0 ) {
cbGroup.select(0);
}
updateRules(0, true);
}
private void updateRules (int selection,
boolean forceReset)
{
rulesTableMod.setLanguageRules(srxDoc.getLanguageRules(cbGroup.getText()));
rulesTableMod.updateTable(selection);
updateResults(forceReset);
updateRulesButtons();
}
private void updateRulesButtons () {
int n = tblRules.getSelectionIndex();
btAddRule.setEnabled(cbGroup.getSelectionIndex()>-1);
btEditRule.setEnabled(n != -1);
btRemoveRule.setEnabled(n != -1);
btMoveUpRule.setEnabled(n > 0);
btMoveDownRule.setEnabled(n < tblRules.getItemCount()-1);
}
private void editGroupsAndOptions () {
try {
getSurfaceData();
GroupsAndOptionsDialog dlg = new GroupsAndOptionsDialog(shell, srxDoc, help);
dlg.showDialog();
}
catch ( Exception e ) {
Dialogs.showError(shell, e.getLocalizedMessage(), null);
}
finally {
updateAll();
}
}
private void setSurfaceData () {
edSampleText.setText(srxDoc.getSampleText());
edSampleLanguage.setText(srxDoc.getSampleLanguage());
rdTestOnSelectedGroup.setSelection(srxDoc.testOnSelectedGroup());
rdTestOnLanguage.setSelection(!srxDoc.testOnSelectedGroup());
edSampleLanguage.setEnabled(rdTestOnLanguage.getSelection());
}
private void getSurfaceData () {
srxDoc.setSampleText(edSampleText.getText().replace("\r", "")); //$NON-NLS-1$ //$NON-NLS-2$
srxDoc.setSampleLanguage(edSampleLanguage.getText());
srxDoc.setTestOnSelectedGroup(rdTestOnSelectedGroup.getSelection());
}
private void updateCaption () {
String filename;
if ( srxPath != null ) filename = Util.getFilename(srxPath, true);
else filename = Res.getString("SRXEditor.untitled"); //$NON-NLS-1$
String text = Res.getString("edit.captionApp"); //$NON-NLS-1$
shell.setText(filename + " - " + text); //$NON-NLS-1$
}
private void updateAll () {
cbGroup.removeAll();
setSurfaceData();
updateLanguageRuleList();
}
private boolean newSRXDocument (boolean withSimpleDefault) {
if ( !checkIfRulesNeedSaving() ) return false;
srxDoc = new SRXDocument();
srxPath = null;
updateCaption();
if ( withSimpleDefault ) {
ArrayList<Rule> list = new ArrayList<Rule>();
list.add(new Rule("([A-Z]\\.){2,}", "\\s", false)); //$NON-NLS-1$ //$NON-NLS-2$
list.add(new Rule("\\.", "\\s", true)); //$NON-NLS-1$ //$NON-NLS-2$
srxDoc.addLanguageRule(Res.getString("SRXEditor.defaultSetName"), list); //$NON-NLS-1$
srxDoc.addLanguageMap(new LanguageMap(".*", Res.getString("SRXEditor.defaultSetName"))); //$NON-NLS-1$ //$NON-NLS-2$
}
updateAll();
return true;
}
private void loadSRXDocumentfromClipboard () {
try {
if ( !checkIfRulesNeedSaving() ) return;
getSurfaceData(); // To get back the original data in case of escape:
// Get the data types available in the Clipboard
Clipboard clipboard = new Clipboard(shell.getDisplay());
TransferData[] transferDatas = clipboard.getAvailableTypes();
boolean found = false;
for(int i=0; i<transferDatas.length; i++) {
if ( TextTransfer.getInstance().isSupportedType(transferDatas[i]) ) {
found = true;
break;
}
}
// Do nothing if there is no simple text available
if ( !found ) return;
// Load the file from the text in the Clipboard
srxDoc.loadRules((CharSequence)clipboard.getContents(TextTransfer.getInstance()));
if ( srxDoc.hasWarning() ) {
MessageBox dlg = new MessageBox(shell, SWT.ICON_WARNING | SWT.YES | SWT.CANCEL);
dlg.setText(shell.getText());
dlg.setMessage(srxDoc.getWarning());
dlg.open();
}
srxPath = null; // No path
}
catch ( Throwable e ) {
Dialogs.showError(shell, e.getLocalizedMessage(), null);
}
finally {
updateCaption();
updateAll();
}
}
private void loadSRXDocument (String path) {
try {
if ( !checkIfRulesNeedSaving() ) return;
getSurfaceData(); // To get back the original data in case of escape:
if ( path == null ) {
String[] paths = Dialogs.browseFilenames(shell,
Res.getString("edit.loadDocCaption"), //$NON-NLS-1$
false, null, Res.getString("edit.loadDocFileTypes"), //$NON-NLS-1$
Res.getString("edit.loadDocFilters")); //$NON-NLS-1$
if ( paths == null ) return; // Cancel
else path = paths[0];
}
srxPath = null; // In case an error occurs
srxDoc.loadRules(path);
if ( srxDoc.hasWarning() ) {
MessageBox dlg = new MessageBox(shell, SWT.ICON_WARNING | SWT.YES | SWT.CANCEL);
dlg.setText(shell.getText());
dlg.setMessage(srxDoc.getWarning());
dlg.open();
}
srxPath = path; // Set the path only after the load is fine
}
catch ( Throwable e ) {
Dialogs.showError(shell, e.getLocalizedMessage(), null);
}
finally {
updateCaption();
updateAll();
}
}
private void copySRXDocumentToClipboard () {
if ( !srxDoc.getVersion().equals("2.0") ) { //$NON-NLS-1$
MessageBox dlg = new MessageBox(shell, SWT.ICON_QUESTION | SWT.YES | SWT.NO | SWT.CANCEL);
dlg.setText(shell.getText());
dlg.setMessage(Res.getString("edit.saveDocVersionWarning")); //$NON-NLS-1$
if ( dlg.open() != SWT.YES ) return;
}
getSurfaceData();
Clipboard clipboard = null;
try {
clipboard = new Clipboard(shell.getDisplay());
TextTransfer textTransfer = TextTransfer.getInstance();
// Save, but not the rules extra info: active/non-active (not standard)
clipboard.setContents(new String[]{srxDoc.saveRulesToString(false, false)},
new Transfer[]{textTransfer});
}
finally {
if ( clipboard != null ) clipboard.dispose();
}
}
private boolean saveSRXDocument (String path) {
try {
if ( !srxDoc.getVersion().equals("2.0") ) { //$NON-NLS-1$
MessageBox dlg = new MessageBox(shell, SWT.ICON_QUESTION | SWT.YES | SWT.NO | SWT.CANCEL);
dlg.setText(shell.getText());
dlg.setMessage(Res.getString("edit.saveDocVersionWarning")); //$NON-NLS-1$
if ( dlg.open() != SWT.YES ) return false;
}
if ( path == null ) {
path = Dialogs.browseFilenamesForSave(shell, Res.getString("edit.saveDocCaption"), null, //$NON-NLS-1$
Res.getString("edit.saveDocFileTypes"), //$NON-NLS-1$
Res.getString("edit.saveDocFilters")); //$NON-NLS-1$
if ( path == null ) return false;
}
getSurfaceData();
// Save, but not the rules extra info: active/non-active (not standard)
srxDoc.saveRules(path, true, false);
srxPath = path;
updateCaption();
}
catch ( Exception e ) {
Dialogs.showError(shell, e.getLocalizedMessage(), null);
}
return true;
}
private void editRule (boolean createNewRule) {
if ( cbGroup.getSelectionIndex() < 0 ) return;
Rule rule;
String ruleName = cbGroup.getItem(cbGroup.getSelectionIndex());
int n = -1;
if ( createNewRule ) {
rule = new Rule("", "", true); //$NON-NLS-1$ //$NON-NLS-2$
}
else {
n = tblRules.getSelectionIndex();
if ( n == -1 ) return;
rule = srxDoc.getLanguageRules(ruleName).get(n);
}
RuleDialog dlg = new RuleDialog(shell, rule, help);
if ( (rule = dlg.showDialog()) == null ) return; // Cancel
if ( createNewRule ) {
srxDoc.getLanguageRules(ruleName).add(rule);
n = srxDoc.getLanguageRules(ruleName).size()-1;
}
else {
srxDoc.getLanguageRules(ruleName).set(n, rule);
}
srxDoc.setModified(true);
updateRules(n, true);
}
private void removeRule () {
int n = tblRules.getSelectionIndex();
if ( n == -1 ) return;
String ruleName = cbGroup.getItem(cbGroup.getSelectionIndex());
srxDoc.getLanguageRules(ruleName).remove(n);
srxDoc.setModified(true);
tblRules.remove(n);
if ( n > tblRules.getItemCount()-1 )
n = tblRules.getItemCount()-1;
if ( tblRules.getItemCount() > 0 )
tblRules.select(n);
updateRulesButtons();
updateResults(true);
}
private void moveUpRule () {
int n = tblRules.getSelectionIndex();
if ( n < 1 ) return;
// Move in the segmenter
String ruleName = cbGroup.getItem(cbGroup.getSelectionIndex());
Rule tmp = srxDoc.getLanguageRules(ruleName).get(n-1);
srxDoc.getLanguageRules(ruleName).set(n-1,
srxDoc.getLanguageRules(ruleName).get(n));
srxDoc.getLanguageRules(ruleName).set(n, tmp);
srxDoc.setModified(true);
// Update
updateRules(n-1, true);
}
private void moveDownRule () {
int n = tblRules.getSelectionIndex();
if ( n > tblRules.getItemCount()-2 ) return;
// Move in the segmenter
String ruleName = cbGroup.getItem(cbGroup.getSelectionIndex());
Rule tmp = srxDoc.getLanguageRules(ruleName).get(n+1);
srxDoc.getLanguageRules(ruleName).set(n+1,
srxDoc.getLanguageRules(ruleName).get(n));
srxDoc.getLanguageRules(ruleName).set(n, tmp);
srxDoc.setModified(true);
// Update
updateRules(n+1, true);
}
/**
* Edits the range rule of the document.
*/
private void editMaskRule () {
try {
String pattern = srxDoc.getMaskRule();
while ( true ) {
InputDialog dlg = new InputDialog(shell, Res.getString("edit.maskRuleCaption"), //$NON-NLS-1$
Res.getString("edit.maskRuleDesc"), "", null, 0, -1, -1); //$NON-NLS-1$ //$NON-NLS-2$
dlg.setInputValue(pattern);
dlg.setAllowEmptyValue(true);
pattern = dlg.showDialog();
if ( pattern == null ) return; // Canceled
// Check the syntax
try {
Pattern.compile(pattern.replace(SRXDocument.ANYCODE,
SRXDocument.INLINECODE_PATTERN));
}
catch ( PatternSyntaxException e ) {
Dialogs.showError(shell, e.getLocalizedMessage(), null);
continue;
}
break;
}
// Else: Set the new expression
srxDoc.setMaskRule(pattern);
updateResults(true);
}
catch ( Throwable e ) {
Dialogs.showError(shell, e.getLocalizedMessage(), null);
}
}
/**
* Checks if the rules need saving, and save them after prompting
* the user if needed.
* @return False if the user cancel, true if a decision is made.
*/
private boolean checkIfRulesNeedSaving () {
config.setProperty("testInputPath", testInputPath); //$NON-NLS-1$
config.setProperty("testOutputPath", testOutputPath); //$NON-NLS-1$
config.setProperty("htmlOutput", htmlOutput); //$NON-NLS-1$
config.save(APPNAME, "N/A"); //$NON-NLS-1$
getSurfaceData();
if ( srxDoc.isModified() ) {
MessageBox dlg = new MessageBox(shell, SWT.ICON_QUESTION | SWT.YES | SWT.NO | SWT.CANCEL);
dlg.setText(shell.getText());
dlg.setMessage(Res.getString("edit.confirmSave")); //$NON-NLS-1$
switch ( dlg.open() ) {
case SWT.CANCEL:
return false;
case SWT.YES:
return saveSRXDocument(srxPath);
}
}
return true;
}
private void segmentTextFile () {
try {
// Get the input file
FileProcessingDialog dlg = new FileProcessingDialog(shell, help);
String[] result = dlg.showDialog(testInputPath, testOutputPath, htmlOutput);
if ( result == null ) return; // Canceled
testInputPath = result[0];
testOutputPath = result[1];
htmlOutput = (result[2]!=null);
// Process
fileProc.process(testInputPath, testOutputPath, htmlOutput, segmenter);
// Show the result
UIUtil.start(testOutputPath);
}
catch ( Throwable e ) {
Dialogs.showError(shell, e.getLocalizedMessage(), null);
}
}
}
| true | true | public SRXEditor (Shell parent,
boolean asDialog,
IHelp helpParam)
{
config = new UserConfiguration();
config.load(APPNAME);
testInputPath = config.getProperty("testInputPath"); //$NON-NLS-1$
testOutputPath = config.getProperty("testOutputPath"); //$NON-NLS-1$
htmlOutput = config.getBoolean("htmlOutput"); //$NON-NLS-1$
help = helpParam;
srxDoc = new SRXDocument();
srxPath = null;
sampleText = new TextContainer(null);
sampleOutput = new GenericContent();
fileProc = new FileProcessor();
if ( asDialog ) {
shell = new Shell(parent, SWT.CLOSE | SWT.TITLE | SWT.RESIZE | SWT.MAX | SWT.MIN | SWT.APPLICATION_MODAL);
}
else {
shell = parent;
}
rm = new ResourceManager(SRXEditor.class, shell.getDisplay());
rm.loadCommands("net.sf.okapi.lib.ui.segmentation.Commands"); //$NON-NLS-1$
rm.addImages("ratel", "ratel16", "ratel32"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
shell.setImages(rm.getImages("ratel")); //$NON-NLS-1$
GridLayout layout = new GridLayout();
shell.setLayout(layout);
createMenus();
SashForm sashForm = new SashForm(shell, SWT.VERTICAL);
sashForm.setLayoutData(new GridData(GridData.FILL_BOTH));
sashForm.setSashWidth(3);
sashForm.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW));
Composite cmpTmp = new Composite(sashForm, SWT.BORDER);
cmpTmp.setLayoutData(new GridData(GridData.FILL_BOTH));
GridLayout layTmp = new GridLayout(6, false);
cmpTmp.setLayout(layTmp);
Label label = new Label(cmpTmp, SWT.NONE);
label.setText(Res.getString("edit.currentLangRules")); //$NON-NLS-1$
GridData gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.horizontalSpan = 4;
label.setLayoutData(gdTmp);
cbGroup = new Combo(cmpTmp, SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.horizontalSpan = 5;
cbGroup.setLayoutData(gdTmp);
cbGroup.setVisibleItemCount(15);
cbGroup.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updateRules(0, false);
};
});
int topButtonsWidth = 180;
Button btTmp = new Button(cmpTmp, SWT.PUSH);
btTmp.setText(Res.getString("edit.groupAndOptions")); //$NON-NLS-1$
gdTmp = new GridData();
btTmp.setLayoutData(gdTmp);
UIUtil.ensureWidth(btTmp, topButtonsWidth);
btTmp.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editGroupsAndOptions();
}
});
tblRules = new Table(cmpTmp, SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION | SWT.CHECK);
tblRules.setHeaderVisible(true);
tblRules.setLinesVisible(true);
gdTmp = new GridData(GridData.FILL_BOTH);
gdTmp.horizontalSpan = 6;
gdTmp.minimumHeight = 130;
tblRules.setLayoutData(gdTmp);
tblRules.addControlListener(new ControlAdapter() {
public void controlResized(ControlEvent e) {
Rectangle rect = tblRules.getClientArea();
//TODO: Check behavior when manual resize a column width out of client area
int typeColWidth = 75;
int nHalf = (int)((rect.width-typeColWidth) / 2);
tblRules.getColumn(0).setWidth(typeColWidth);
tblRules.getColumn(1).setWidth(nHalf);
tblRules.getColumn(2).setWidth(nHalf);
}
});
tblRules.addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent e) {
editRule(false);
}
public void mouseDown(MouseEvent e) {}
public void mouseUp(MouseEvent e) {}
});
tblRules.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (e.detail == SWT.CHECK) {
int n = tblRules.getSelectionIndex();
if ( n < 0 ) return;
String ruleName = cbGroup.getItem(cbGroup.getSelectionIndex());
srxDoc.getLanguageRules(ruleName).get(n).setActive(((TableItem)e.item).getChecked());
srxDoc.setModified(true);
updateResults(true);
}
updateRulesButtons();
};
});
rulesTableMod = new RulesTableModel();
rulesTableMod.linkTable(tblRules);
Composite cmpGroup = new Composite(cmpTmp, SWT.NONE);
layTmp = new GridLayout(7, true);
layTmp.marginHeight = 0;
layTmp.marginWidth = 0;
cmpGroup.setLayout(layTmp);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.horizontalSpan = 6;
cmpGroup.setLayoutData(gdTmp);
btAddRule = new Button(cmpGroup, SWT.PUSH);
btAddRule.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btAddRule.setText(Res.getString("edit.btAddRule")); //$NON-NLS-1$
btAddRule.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editRule(true);
}
});
btEditRule = new Button(cmpGroup, SWT.PUSH);
btEditRule.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btEditRule.setText(Res.getString("edit.btEditRule")); //$NON-NLS-1$
btEditRule.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editRule(false);
}
});
btRemoveRule = new Button(cmpGroup, SWT.PUSH);
btRemoveRule.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btRemoveRule.setText(Res.getString("edit.btRemoveRule")); //$NON-NLS-1$
btRemoveRule.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
removeRule();
}
});
btMoveUpRule = new Button(cmpGroup, SWT.PUSH);
btMoveUpRule.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btMoveUpRule.setText(Res.getString("edit.moveUp")); //$NON-NLS-1$
btMoveUpRule.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
moveUpRule();
}
});
btMoveDownRule = new Button(cmpGroup, SWT.PUSH);
btMoveDownRule.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btMoveDownRule.setText(Res.getString("edit.moveDown")); //$NON-NLS-1$
btMoveDownRule.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
moveDownRule();
}
});
Button btMaskRule = new Button(cmpGroup, SWT.PUSH);
btMaskRule.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btMaskRule.setText(Res.getString("edit.maskRule")); //$NON-NLS-1$
btMaskRule.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editMaskRule();
}
});
Button btCharInfo = new Button(cmpGroup, SWT.PUSH);
btCharInfo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btCharInfo.setText(Res.getString("edit.charInfo")); //$NON-NLS-1$
btCharInfo.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
showCharInfo();
}
});
//--- Sample block
Composite cmpSample = new Composite(sashForm, SWT.BORDER);
cmpSample.setLayoutData(new GridData(GridData.FILL_BOTH));
cmpSample.setLayout(new GridLayout(3, false));
label = new Label(cmpSample, SWT.None);
label.setText(Res.getString("edit.sampleNote")); //$NON-NLS-1$
gdTmp = new GridData();
gdTmp.horizontalSpan = 3;
label.setLayoutData(gdTmp);
int sampleMinHeight = 40;
edSampleText = new Text(cmpSample, SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
gdTmp = new GridData(GridData.FILL_BOTH);
gdTmp.minimumHeight = sampleMinHeight;
gdTmp.horizontalSpan = 3;
edSampleText.setLayoutData(gdTmp);
Font font = edSampleText.getFont();
FontData[] fontData = font.getFontData();
fontData[0].setHeight(fontData[0].getHeight()+2);
sampleFont = new Font(font.getDevice(), fontData[0]);
edSampleText.setFont(sampleFont);
rdTestOnSelectedGroup = new Button(cmpSample, SWT.RADIO);
rdTestOnSelectedGroup.setText(Res.getString("edit.testOnlyGroup")); //$NON-NLS-1$
rdTestOnSelectedGroup.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
edSampleLanguage.setEnabled(rdTestOnLanguage.getSelection());
updateRules(tblRules.getSelectionIndex(), true);
};
});
rdTestOnLanguage = new Button(cmpSample, SWT.RADIO);
rdTestOnLanguage.setText(Res.getString("edit.testLanguage")); //$NON-NLS-1$
rdTestOnLanguage.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
edSampleLanguage.setEnabled(rdTestOnLanguage.getSelection());
updateRules(tblRules.getSelectionIndex(), true);
};
});
edSampleLanguage = new Text(cmpSample, SWT.BORDER | SWT.SINGLE);
gdTmp = new GridData();
edSampleLanguage.setLayoutData(gdTmp);
edSampleLanguage.addModifyListener(new ModifyListener () {
public void modifyText(ModifyEvent e) {
updateResults(false);
}
});
edResults = new Text(cmpSample, SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
gdTmp = new GridData(GridData.FILL_BOTH);
edResults.setLayoutData(gdTmp);
gdTmp.minimumHeight = sampleMinHeight;
gdTmp.horizontalSpan = 3;
edResults.setEditable(false);
edResults.setFont(sampleFont);
edSampleText.addModifyListener(new ModifyListener () {
public void modifyText(ModifyEvent e) {
updateResults(false);
}
});
// Handling of the closing event
shell.addShellListener(new ShellListener() {
public void shellActivated(ShellEvent event) {}
public void shellClosed(ShellEvent event) {
if ( !checkIfRulesNeedSaving() ) event.doit = false;
}
public void shellDeactivated(ShellEvent event) {}
public void shellDeiconified(ShellEvent event) {}
public void shellIconified(ShellEvent event) {}
});
// Drop target for opening project
DropTarget dropTarget = new DropTarget(shell, DND.DROP_DEFAULT | DND.DROP_COPY | DND.DROP_MOVE);
dropTarget.setTransfer(new FileTransfer[]{FileTransfer.getInstance()});
dropTarget.addDropListener(new DropTargetAdapter() {
public void drop (DropTargetEvent e) {
FileTransfer FT = FileTransfer.getInstance();
if ( FT.isSupportedType(e.currentDataType) ) {
String[] paths = (String[])e.data;
if ( paths != null ) {
loadSRXDocument(paths[0]);
}
}
}
});
// Size
shell.pack();
shell.setMinimumSize(shell.getSize());
Point startSize = shell.getMinimumSize();
if ( startSize.x < 700 ) startSize.x = 700;
if ( startSize.y < 600 ) startSize.y = 600;
shell.setSize(startSize);
if ( asDialog ) {
Dialogs.centerWindow(shell, parent);
}
updateCaption();
updateAll();
}
| public SRXEditor (Shell parent,
boolean asDialog,
IHelp helpParam)
{
config = new UserConfiguration();
config.load(APPNAME);
testInputPath = config.getProperty("testInputPath"); //$NON-NLS-1$
testOutputPath = config.getProperty("testOutputPath"); //$NON-NLS-1$
htmlOutput = config.getBoolean("htmlOutput"); //$NON-NLS-1$
help = helpParam;
srxDoc = new SRXDocument();
srxPath = null;
sampleText = new TextContainer(null);
sampleOutput = new GenericContent();
fileProc = new FileProcessor();
if ( asDialog ) {
shell = new Shell(parent, SWT.CLOSE | SWT.TITLE | SWT.RESIZE | SWT.MAX | SWT.MIN | SWT.APPLICATION_MODAL);
}
else {
shell = parent;
}
rm = new ResourceManager(SRXEditor.class, shell.getDisplay());
rm.loadCommands("net.sf.okapi.lib.ui.segmentation.Commands"); //$NON-NLS-1$
rm.addImages("ratel", "ratel16", "ratel32"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
shell.setImages(rm.getImages("ratel")); //$NON-NLS-1$
GridLayout layout = new GridLayout();
shell.setLayout(layout);
createMenus();
SashForm sashForm = new SashForm(shell, SWT.VERTICAL);
sashForm.setLayoutData(new GridData(GridData.FILL_BOTH));
sashForm.setSashWidth(3);
sashForm.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW));
Composite cmpTmp = new Composite(sashForm, SWT.BORDER);
cmpTmp.setLayoutData(new GridData(GridData.FILL_BOTH));
GridLayout layTmp = new GridLayout(6, false);
cmpTmp.setLayout(layTmp);
Label label = new Label(cmpTmp, SWT.NONE);
label.setText(Res.getString("edit.currentLangRules")); //$NON-NLS-1$
GridData gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.horizontalSpan = 4;
label.setLayoutData(gdTmp);
cbGroup = new Combo(cmpTmp, SWT.BORDER | SWT.DROP_DOWN | SWT.READ_ONLY);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.horizontalSpan = 5;
cbGroup.setLayoutData(gdTmp);
cbGroup.setVisibleItemCount(15);
cbGroup.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updateRules(0, false);
};
});
int topButtonsWidth = 180;
Button btTmp = new Button(cmpTmp, SWT.PUSH);
btTmp.setText(Res.getString("edit.groupAndOptions")); //$NON-NLS-1$
gdTmp = new GridData();
btTmp.setLayoutData(gdTmp);
UIUtil.ensureWidth(btTmp, topButtonsWidth);
btTmp.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editGroupsAndOptions();
}
});
tblRules = new Table(cmpTmp, SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION | SWT.CHECK);
tblRules.setHeaderVisible(true);
tblRules.setLinesVisible(true);
gdTmp = new GridData(GridData.FILL_BOTH);
gdTmp.horizontalSpan = 6;
gdTmp.minimumHeight = 130;
tblRules.setLayoutData(gdTmp);
tblRules.addControlListener(new ControlAdapter() {
public void controlResized(ControlEvent e) {
Rectangle rect = tblRules.getClientArea();
//TODO: Check behavior when manual resize a column width out of client area
int typeColWidth = 75;
int nHalf = (int)((rect.width-typeColWidth) / 2);
tblRules.getColumn(0).setWidth(typeColWidth);
tblRules.getColumn(1).setWidth(nHalf);
tblRules.getColumn(2).setWidth(nHalf);
}
});
tblRules.addMouseListener(new MouseListener() {
public void mouseDoubleClick(MouseEvent e) {
editRule(false);
}
public void mouseDown(MouseEvent e) {}
public void mouseUp(MouseEvent e) {}
});
tblRules.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if ( e.detail == SWT.CHECK ) {
tblRules.setSelection((TableItem)e.item); // Force selection to move if needed
int n = tblRules.getSelectionIndex();
if ( n < 0 ) return;
String ruleName = cbGroup.getItem(cbGroup.getSelectionIndex());
srxDoc.getLanguageRules(ruleName).get(n).setActive(((TableItem)e.item).getChecked());
srxDoc.setModified(true);
updateResults(true);
}
updateRulesButtons();
};
});
rulesTableMod = new RulesTableModel();
rulesTableMod.linkTable(tblRules);
Composite cmpGroup = new Composite(cmpTmp, SWT.NONE);
layTmp = new GridLayout(7, true);
layTmp.marginHeight = 0;
layTmp.marginWidth = 0;
cmpGroup.setLayout(layTmp);
gdTmp = new GridData(GridData.FILL_HORIZONTAL);
gdTmp.horizontalSpan = 6;
cmpGroup.setLayoutData(gdTmp);
btAddRule = new Button(cmpGroup, SWT.PUSH);
btAddRule.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btAddRule.setText(Res.getString("edit.btAddRule")); //$NON-NLS-1$
btAddRule.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editRule(true);
}
});
btEditRule = new Button(cmpGroup, SWT.PUSH);
btEditRule.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btEditRule.setText(Res.getString("edit.btEditRule")); //$NON-NLS-1$
btEditRule.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editRule(false);
}
});
btRemoveRule = new Button(cmpGroup, SWT.PUSH);
btRemoveRule.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btRemoveRule.setText(Res.getString("edit.btRemoveRule")); //$NON-NLS-1$
btRemoveRule.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
removeRule();
}
});
btMoveUpRule = new Button(cmpGroup, SWT.PUSH);
btMoveUpRule.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btMoveUpRule.setText(Res.getString("edit.moveUp")); //$NON-NLS-1$
btMoveUpRule.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
moveUpRule();
}
});
btMoveDownRule = new Button(cmpGroup, SWT.PUSH);
btMoveDownRule.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btMoveDownRule.setText(Res.getString("edit.moveDown")); //$NON-NLS-1$
btMoveDownRule.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
moveDownRule();
}
});
Button btMaskRule = new Button(cmpGroup, SWT.PUSH);
btMaskRule.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btMaskRule.setText(Res.getString("edit.maskRule")); //$NON-NLS-1$
btMaskRule.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
editMaskRule();
}
});
Button btCharInfo = new Button(cmpGroup, SWT.PUSH);
btCharInfo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btCharInfo.setText(Res.getString("edit.charInfo")); //$NON-NLS-1$
btCharInfo.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
showCharInfo();
}
});
//--- Sample block
Composite cmpSample = new Composite(sashForm, SWT.BORDER);
cmpSample.setLayoutData(new GridData(GridData.FILL_BOTH));
cmpSample.setLayout(new GridLayout(3, false));
label = new Label(cmpSample, SWT.None);
label.setText(Res.getString("edit.sampleNote")); //$NON-NLS-1$
gdTmp = new GridData();
gdTmp.horizontalSpan = 3;
label.setLayoutData(gdTmp);
int sampleMinHeight = 40;
edSampleText = new Text(cmpSample, SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
gdTmp = new GridData(GridData.FILL_BOTH);
gdTmp.minimumHeight = sampleMinHeight;
gdTmp.horizontalSpan = 3;
edSampleText.setLayoutData(gdTmp);
Font font = edSampleText.getFont();
FontData[] fontData = font.getFontData();
fontData[0].setHeight(fontData[0].getHeight()+2);
sampleFont = new Font(font.getDevice(), fontData[0]);
edSampleText.setFont(sampleFont);
rdTestOnSelectedGroup = new Button(cmpSample, SWT.RADIO);
rdTestOnSelectedGroup.setText(Res.getString("edit.testOnlyGroup")); //$NON-NLS-1$
rdTestOnSelectedGroup.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
edSampleLanguage.setEnabled(rdTestOnLanguage.getSelection());
updateRules(tblRules.getSelectionIndex(), true);
};
});
rdTestOnLanguage = new Button(cmpSample, SWT.RADIO);
rdTestOnLanguage.setText(Res.getString("edit.testLanguage")); //$NON-NLS-1$
rdTestOnLanguage.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
edSampleLanguage.setEnabled(rdTestOnLanguage.getSelection());
updateRules(tblRules.getSelectionIndex(), true);
};
});
edSampleLanguage = new Text(cmpSample, SWT.BORDER | SWT.SINGLE);
gdTmp = new GridData();
edSampleLanguage.setLayoutData(gdTmp);
edSampleLanguage.addModifyListener(new ModifyListener () {
public void modifyText(ModifyEvent e) {
updateResults(false);
}
});
edResults = new Text(cmpSample, SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
gdTmp = new GridData(GridData.FILL_BOTH);
edResults.setLayoutData(gdTmp);
gdTmp.minimumHeight = sampleMinHeight;
gdTmp.horizontalSpan = 3;
edResults.setEditable(false);
edResults.setFont(sampleFont);
edSampleText.addModifyListener(new ModifyListener () {
public void modifyText(ModifyEvent e) {
updateResults(false);
}
});
// Handling of the closing event
shell.addShellListener(new ShellListener() {
public void shellActivated(ShellEvent event) {}
public void shellClosed(ShellEvent event) {
if ( !checkIfRulesNeedSaving() ) event.doit = false;
}
public void shellDeactivated(ShellEvent event) {}
public void shellDeiconified(ShellEvent event) {}
public void shellIconified(ShellEvent event) {}
});
// Drop target for opening project
DropTarget dropTarget = new DropTarget(shell, DND.DROP_DEFAULT | DND.DROP_COPY | DND.DROP_MOVE);
dropTarget.setTransfer(new FileTransfer[]{FileTransfer.getInstance()});
dropTarget.addDropListener(new DropTargetAdapter() {
public void drop (DropTargetEvent e) {
FileTransfer FT = FileTransfer.getInstance();
if ( FT.isSupportedType(e.currentDataType) ) {
String[] paths = (String[])e.data;
if ( paths != null ) {
loadSRXDocument(paths[0]);
}
}
}
});
// Size
shell.pack();
shell.setMinimumSize(shell.getSize());
Point startSize = shell.getMinimumSize();
if ( startSize.x < 700 ) startSize.x = 700;
if ( startSize.y < 600 ) startSize.y = 600;
shell.setSize(startSize);
if ( asDialog ) {
Dialogs.centerWindow(shell, parent);
}
updateCaption();
updateAll();
}
|
diff --git a/eclipse_project/src/com/ptzlabs/wc/servlet/ReadingServlet.java b/eclipse_project/src/com/ptzlabs/wc/servlet/ReadingServlet.java
index 7d12d81..174e87f 100644
--- a/eclipse_project/src/com/ptzlabs/wc/servlet/ReadingServlet.java
+++ b/eclipse_project/src/com/ptzlabs/wc/servlet/ReadingServlet.java
@@ -1,188 +1,187 @@
package com.ptzlabs.wc.servlet;
import static com.googlecode.objectify.ObjectifyService.ofy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileReadChannel;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.googlecode.objectify.Key;
import com.ptzlabs.wc.Chunk;
import com.ptzlabs.wc.Reading;
import com.ptzlabs.wc.User;
public class ReadingServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
if (req.getParameter("mode").equals("new")
&& req.getParameter("name") != null
&& req.getParameter("location") != null
&& req.getParameter("fbid") != null
&& req.getParameter("type") != null) {
Reading reading;
if (req.getParameter("dueDate") != null) {
reading = new Reading(req.getParameter("name"), new Date(
Long.parseLong(req.getParameter("dueDate"))),
Long.parseLong(req.getParameter("fbid")));
} else {
reading = new Reading(req.getParameter("name"),
Long.parseLong(req.getParameter("fbid")));
}
ofy().save().entity(reading).now();
Key<Reading> readingKey = Key.create(Reading.class, reading.id);
if (req.getParameter("type").equals("application/pdf")) {
PDDocument document = PDDocument.load(req
.getParameter("location"));
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(document);
int fromIndex = 0;
int endSentence = text.indexOf(". ", fromIndex);
int sentence = 0;
- int fromIndex = 0;
String data = "";
int chunkCounter = 1;
while (endSentence != -1) {
- data += text.subString(fromIndex, endSentence);
+ data += text.substring(fromIndex, endSentence);
sentence++;
if (sentence == 2) {
Chunk chunk = new Chunk(chunkCounter, readingKey, data);
ofy().save().entity(chunk).now();
chunkCounter++;
sentence = 0;
data = "";
}
fromIndex = endSentence + 2;
endSentence = text.indexOf(". ", fromIndex);
}
if (sentence != 0) {
Chunk chunk = new Chunk(chunkCounter, readingKey, data);
ofy().save().entity(chunk).now();
}
//total chunks = chunkCounter
Reading r = ofy().load().key(readingKey).get();
r.setTotalChunks(chunkCounter);
ofy().save().entity(r).now();
} else {
AppEngineFile file = readFileAndStore(req
.getParameter("location"));
FileService fileService = FileServiceFactory.getFileService();
// Later, read from the file using the file API
FileReadChannel readChannel = fileService.openReadChannel(file,
false);
// Again, different standard Java ways of reading from the
// channel.
BufferedReader reader = new BufferedReader(Channels.newReader(
readChannel, "UTF8"));
String line = reader.readLine();
String data = "";
int sentence = 0;
int chunkCounter = 1;
int fromIndex = 0;
while (line != null) {
int i = 0;
int endSentence = line.indexOf(". ", fromIndex);
while (endSentence != -1) {
data += line.substring(fromIndex, endSentence);
sentence++;
if (sentence == 2) {
Chunk chunk = new Chunk(chunkCounter, readingKey, data);
ofy().save().entity(chunk).now();
sentence = 0;
data = "";
chunkCounter++;
}
fromIndex = endSentence + 2;
endSentence = line.indexOf(". ", fromIndex);
}
data += line.substring(fromIndex, endSentence);
line = reader.readLine();
}
if (sentence != 0) {
Chunk chunk = new Chunk(chunkCounter, readingKey, data);
ofy().save().entity(chunk).now();
}
//total chunks = chunkCounter
Reading r = ofy().load().key(readingKey).get();
r.setTotalChunks(chunkCounter);
ofy().save().entity(r).now();
readChannel.close();
// remove blob from blobstore
BlobKey blobKey = fileService.getBlobKey(file);
BlobstoreService blobStoreService = BlobstoreServiceFactory
.getBlobstoreService();
blobStoreService.delete(blobKey);
}
resp.setContentType("text/plain");
resp.getWriter().println("OK");
}
}
private static AppEngineFile readFileAndStore(String location) throws IOException {
BufferedReader reader;
FileService fileService = FileServiceFactory.getFileService();
AppEngineFile file = fileService.createNewBlobFile("text/plain");
FileWriteChannel writeChannel = fileService.openWriteChannel(file, true);
reader = new BufferedReader(new InputStreamReader(
new URL(location).openStream()));
String line;
while ((line = reader.readLine()) != null) {
writeChannel.write(ByteBuffer.wrap(line.getBytes()));
}
reader.close();
writeChannel.closeFinally();
return file;
}
public static List<Reading> getReadings(long fbid) {
User user = User.getUser(fbid);
return ofy().load().type(Reading.class).filter("user", user.id).list();
}
public static Reading get(long id) {
return ofy().load().type(Reading.class).id(id).get();
}
}
| false | true | public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
if (req.getParameter("mode").equals("new")
&& req.getParameter("name") != null
&& req.getParameter("location") != null
&& req.getParameter("fbid") != null
&& req.getParameter("type") != null) {
Reading reading;
if (req.getParameter("dueDate") != null) {
reading = new Reading(req.getParameter("name"), new Date(
Long.parseLong(req.getParameter("dueDate"))),
Long.parseLong(req.getParameter("fbid")));
} else {
reading = new Reading(req.getParameter("name"),
Long.parseLong(req.getParameter("fbid")));
}
ofy().save().entity(reading).now();
Key<Reading> readingKey = Key.create(Reading.class, reading.id);
if (req.getParameter("type").equals("application/pdf")) {
PDDocument document = PDDocument.load(req
.getParameter("location"));
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(document);
int fromIndex = 0;
int endSentence = text.indexOf(". ", fromIndex);
int sentence = 0;
int fromIndex = 0;
String data = "";
int chunkCounter = 1;
while (endSentence != -1) {
data += text.subString(fromIndex, endSentence);
sentence++;
if (sentence == 2) {
Chunk chunk = new Chunk(chunkCounter, readingKey, data);
ofy().save().entity(chunk).now();
chunkCounter++;
sentence = 0;
data = "";
}
fromIndex = endSentence + 2;
endSentence = text.indexOf(". ", fromIndex);
}
if (sentence != 0) {
Chunk chunk = new Chunk(chunkCounter, readingKey, data);
ofy().save().entity(chunk).now();
}
//total chunks = chunkCounter
Reading r = ofy().load().key(readingKey).get();
r.setTotalChunks(chunkCounter);
ofy().save().entity(r).now();
} else {
AppEngineFile file = readFileAndStore(req
.getParameter("location"));
FileService fileService = FileServiceFactory.getFileService();
// Later, read from the file using the file API
FileReadChannel readChannel = fileService.openReadChannel(file,
false);
// Again, different standard Java ways of reading from the
// channel.
BufferedReader reader = new BufferedReader(Channels.newReader(
readChannel, "UTF8"));
String line = reader.readLine();
String data = "";
int sentence = 0;
int chunkCounter = 1;
int fromIndex = 0;
while (line != null) {
int i = 0;
int endSentence = line.indexOf(". ", fromIndex);
while (endSentence != -1) {
data += line.substring(fromIndex, endSentence);
sentence++;
if (sentence == 2) {
Chunk chunk = new Chunk(chunkCounter, readingKey, data);
ofy().save().entity(chunk).now();
sentence = 0;
data = "";
chunkCounter++;
}
fromIndex = endSentence + 2;
endSentence = line.indexOf(". ", fromIndex);
}
data += line.substring(fromIndex, endSentence);
line = reader.readLine();
}
if (sentence != 0) {
Chunk chunk = new Chunk(chunkCounter, readingKey, data);
ofy().save().entity(chunk).now();
}
//total chunks = chunkCounter
Reading r = ofy().load().key(readingKey).get();
r.setTotalChunks(chunkCounter);
ofy().save().entity(r).now();
readChannel.close();
// remove blob from blobstore
BlobKey blobKey = fileService.getBlobKey(file);
BlobstoreService blobStoreService = BlobstoreServiceFactory
.getBlobstoreService();
blobStoreService.delete(blobKey);
}
resp.setContentType("text/plain");
resp.getWriter().println("OK");
}
}
| public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
if (req.getParameter("mode").equals("new")
&& req.getParameter("name") != null
&& req.getParameter("location") != null
&& req.getParameter("fbid") != null
&& req.getParameter("type") != null) {
Reading reading;
if (req.getParameter("dueDate") != null) {
reading = new Reading(req.getParameter("name"), new Date(
Long.parseLong(req.getParameter("dueDate"))),
Long.parseLong(req.getParameter("fbid")));
} else {
reading = new Reading(req.getParameter("name"),
Long.parseLong(req.getParameter("fbid")));
}
ofy().save().entity(reading).now();
Key<Reading> readingKey = Key.create(Reading.class, reading.id);
if (req.getParameter("type").equals("application/pdf")) {
PDDocument document = PDDocument.load(req
.getParameter("location"));
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(document);
int fromIndex = 0;
int endSentence = text.indexOf(". ", fromIndex);
int sentence = 0;
String data = "";
int chunkCounter = 1;
while (endSentence != -1) {
data += text.substring(fromIndex, endSentence);
sentence++;
if (sentence == 2) {
Chunk chunk = new Chunk(chunkCounter, readingKey, data);
ofy().save().entity(chunk).now();
chunkCounter++;
sentence = 0;
data = "";
}
fromIndex = endSentence + 2;
endSentence = text.indexOf(". ", fromIndex);
}
if (sentence != 0) {
Chunk chunk = new Chunk(chunkCounter, readingKey, data);
ofy().save().entity(chunk).now();
}
//total chunks = chunkCounter
Reading r = ofy().load().key(readingKey).get();
r.setTotalChunks(chunkCounter);
ofy().save().entity(r).now();
} else {
AppEngineFile file = readFileAndStore(req
.getParameter("location"));
FileService fileService = FileServiceFactory.getFileService();
// Later, read from the file using the file API
FileReadChannel readChannel = fileService.openReadChannel(file,
false);
// Again, different standard Java ways of reading from the
// channel.
BufferedReader reader = new BufferedReader(Channels.newReader(
readChannel, "UTF8"));
String line = reader.readLine();
String data = "";
int sentence = 0;
int chunkCounter = 1;
int fromIndex = 0;
while (line != null) {
int i = 0;
int endSentence = line.indexOf(". ", fromIndex);
while (endSentence != -1) {
data += line.substring(fromIndex, endSentence);
sentence++;
if (sentence == 2) {
Chunk chunk = new Chunk(chunkCounter, readingKey, data);
ofy().save().entity(chunk).now();
sentence = 0;
data = "";
chunkCounter++;
}
fromIndex = endSentence + 2;
endSentence = line.indexOf(". ", fromIndex);
}
data += line.substring(fromIndex, endSentence);
line = reader.readLine();
}
if (sentence != 0) {
Chunk chunk = new Chunk(chunkCounter, readingKey, data);
ofy().save().entity(chunk).now();
}
//total chunks = chunkCounter
Reading r = ofy().load().key(readingKey).get();
r.setTotalChunks(chunkCounter);
ofy().save().entity(r).now();
readChannel.close();
// remove blob from blobstore
BlobKey blobKey = fileService.getBlobKey(file);
BlobstoreService blobStoreService = BlobstoreServiceFactory
.getBlobstoreService();
blobStoreService.delete(blobKey);
}
resp.setContentType("text/plain");
resp.getWriter().println("OK");
}
}
|
diff --git a/codemonkey-core/src/main/java/com/codemonkey/service/GenericServiceImpl.java b/codemonkey-core/src/main/java/com/codemonkey/service/GenericServiceImpl.java
index bd93ec4..6750032 100644
--- a/codemonkey-core/src/main/java/com/codemonkey/service/GenericServiceImpl.java
+++ b/codemonkey-core/src/main/java/com/codemonkey/service/GenericServiceImpl.java
@@ -1,327 +1,329 @@
package com.codemonkey.service;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.StopWatch;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.codemonkey.dao.GenericDao;
import com.codemonkey.domain.IEntity;
import com.codemonkey.error.BadObjVersionError;
import com.codemonkey.error.FieldValidation;
import com.codemonkey.error.FormFieldValidation;
import com.codemonkey.error.ValidationError;
import com.codemonkey.utils.ClassHelper;
import com.codemonkey.utils.ExtConstant;
import com.codemonkey.web.converter.CustomConversionService;
@Transactional
public abstract class GenericServiceImpl<T extends IEntity> extends AbsService implements GenericService<T> {
private GenericDao<T> dao;
private Class<?> type;
public GenericServiceImpl(){
this.type = ClassHelper.getSuperClassGenricType(getClass());
}
@Override
public abstract T createEntity();
@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
dao = new GenericDao<T>(sessionFactory , type);
}
protected GenericDao<T> getDao() {
return dao;
}
public T get(Long id) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
T t = getDao().get(id);
stopWatch.stop();
getLog().info(stopWatch);
return t;
}
public void save(T entity) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
if(entity.isOptimisticLockingFailure()){
- throw new BadObjVersionError(get(entity.getId()).detailJson());
+ T t = get(entity.getId());
+ t.setOriginVersion(null);
+ throw new BadObjVersionError(t.detailJson());
}
entity.setOriginVersion(null);
Set<FieldValidation> set = validate(entity);
if(CollectionUtils.isNotEmpty(set)){
throw new ValidationError(set);
}
getDao().save(entity);
stopWatch.stop();
getLog().info(stopWatch);
}
//implements by subclass if needed
//if validation failed , throw ValidationError exception
protected Set<FieldValidation> validate(T entity) {
Set<FieldValidation> errorSet = new HashSet<FieldValidation>();
if(entity == null){
return errorSet;
}
if(StringUtils.isNotBlank(entity.getCode())){
long count = getDao().countBy("code" , entity.getCode());
if(count > 1){
errorSet.add(new FormFieldValidation("code" , "code must be unique"));
}
}
return errorSet;
}
public void delete(Long id) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
getDao().delete(id);
stopWatch.stop();
getLog().info(stopWatch);
}
public List<T> findAll() {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
List<T> list = getDao().findAll();
stopWatch.stop();
getLog().info(stopWatch);
return list;
}
public List<T> findAll(int start , int limit){
StopWatch stopWatch = new StopWatch();
stopWatch.start();
List<T> list = getDao().findAll(start , limit);
stopWatch.stop();
getLog().info(stopWatch);
return list;
}
public List<T> find(Criterion... criterions){
StopWatch stopWatch = new StopWatch();
stopWatch.start();
List<T> list = getDao().findByCriteria(criterions);
stopWatch.stop();
getLog().info(stopWatch);
return list;
}
public List<T> find(int start, int limit, Criterion... criterions) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
List<T> list = getDao().findByCriteria(start , limit , criterions);
stopWatch.stop();
getLog().info(stopWatch);
return list;
}
public T findBy(String query , Object... params){
StopWatch stopWatch = new StopWatch();
stopWatch.start();
T t = getDao().findBy(query , params);
stopWatch.stop();
getLog().info(stopWatch);
return t;
}
public T findBy(String query , String[] joins , Object... params){
StopWatch stopWatch = new StopWatch();
stopWatch.start();
T t = getDao().findBy(query , joins , params);
stopWatch.stop();
getLog().info(stopWatch);
return t;
}
@Override
public long countBy(String query, Object... params) {
return countBy(query , null , params);
}
@Override
public long countBy(String query, String[] joins, Object... params) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
long count = getDao().countBy(query, joins , params);
stopWatch.stop();
getLog().info(stopWatch);
return count;
}
public List<T> findAllBy(String query , Object... params){
StopWatch stopWatch = new StopWatch();
stopWatch.start();
List<T> list = getDao().findAllBy(query , params);
stopWatch.stop();
getLog().info(stopWatch);
return list;
}
@Override
public List<T> findAllBy(String query, String[] joins, Object... params) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
List<T> list = getDao().findAllBy(query , joins , params);
stopWatch.stop();
getLog().info(stopWatch);
return list;
}
public long count(Criterion... criterions){
StopWatch stopWatch = new StopWatch();
stopWatch.start();
long count = getDao().count(criterions);
stopWatch.stop();
getLog().info(stopWatch);
return count;
}
public T convert(String source) {
if(StringUtils.isEmpty(source)){
return null;
}
return getDao().get(Long.valueOf(source));
}
public List<T> findByQueryInfo(JSONObject queryInfo, Integer start, Integer limit) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
List<T> list = getDao().findByQueryInfo(queryInfo , start , limit);
stopWatch.stop();
getLog().info(stopWatch);
return list;
}
public List<T> findByQueryInfo(JSONObject queryInfo) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
List<T> list = getDao().findByQueryInfo(queryInfo);
stopWatch.stop();
getLog().info(stopWatch);
return list;
}
public long countByQueryInfo(JSONObject queryInfo) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
long count = getDao().countByQueryInfo(queryInfo);
stopWatch.stop();
getLog().info(stopWatch);
return count;
}
public T doSave(JSONObject body , CustomConversionService ccService){
T t = buildEntity(body , ccService);
save(t);
return t;
}
public T buildEntity(JSONObject params , CustomConversionService ccService){
T t = null;
Long id = extractId(params);
if(id == null){
t = createEntity();
ClassHelper.build(params, t , ccService);
}else{
t = get(id);
if(t != null){
ClassHelper.build(params, t , ccService);
}
}
return t;
}
private Long extractId(JSONObject params) {
Long id = null;
if(params.has(ExtConstant.ID) && StringUtils.isNotBlank(params.getString(ExtConstant.ID)) && !"null".equals(params.getString(ExtConstant.ID))){
id = params.getLong(ExtConstant.ID);
}
return id;
}
}
| true | true | public void save(T entity) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
if(entity.isOptimisticLockingFailure()){
throw new BadObjVersionError(get(entity.getId()).detailJson());
}
entity.setOriginVersion(null);
Set<FieldValidation> set = validate(entity);
if(CollectionUtils.isNotEmpty(set)){
throw new ValidationError(set);
}
getDao().save(entity);
stopWatch.stop();
getLog().info(stopWatch);
}
| public void save(T entity) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
if(entity.isOptimisticLockingFailure()){
T t = get(entity.getId());
t.setOriginVersion(null);
throw new BadObjVersionError(t.detailJson());
}
entity.setOriginVersion(null);
Set<FieldValidation> set = validate(entity);
if(CollectionUtils.isNotEmpty(set)){
throw new ValidationError(set);
}
getDao().save(entity);
stopWatch.stop();
getLog().info(stopWatch);
}
|
diff --git a/bundles/jcr/contentloader/src/main/java/org/apache/sling/jcr/contentloader/internal/readers/XmlReader.java b/bundles/jcr/contentloader/src/main/java/org/apache/sling/jcr/contentloader/internal/readers/XmlReader.java
index 3c28ef38bf..7047685043 100644
--- a/bundles/jcr/contentloader/src/main/java/org/apache/sling/jcr/contentloader/internal/readers/XmlReader.java
+++ b/bundles/jcr/contentloader/src/main/java/org/apache/sling/jcr/contentloader/internal/readers/XmlReader.java
@@ -1,602 +1,604 @@
/*
* 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.jcr.contentloader.internal.readers;
import java.io.BufferedInputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.File;
import java.net.URL;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.sling.jcr.contentloader.internal.ContentCreator;
import org.apache.sling.jcr.contentloader.internal.ContentReader;
import org.apache.sling.jcr.contentloader.internal.ImportProvider;
import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
/**
* This reader reads an xml file defining the content. The xml format should have this
* format:
*
* <pre>
* <node>
* <name>the name of the node</name>
* <primaryNodeType>type</primaryNodeType>
* <mixinNodeTypes>
* <mixinNodeType>mixtype1</mixinNodeType>
* <mixinNodeType>mixtype2</mixinNodeType>
* </mixingNodeTypes>
* <properties>
* <property>
* <name>propName</name>
* <value>propValue</value>
* or
* <values>
* <value/> for multi value properties
* </values>
* <type>propType</type>
* </property>
* <!-- more properties -->
* </properties>
* <nodes>
* <!-- child nodes -->
* <node>
* ..
* </node>
* </nodes>
* </node>
* </pre>
*
* If you want to include a binary file in your loaded content, you may specify it using a
* {@link org.apache.sling.jcr.contentloader.internal.readers.XmlReader.FileDescription <code><nt:file></code>} element.
*/
public class XmlReader implements ContentReader {
/*
* <node> <primaryNodeType>type</primaryNodeType> <mixinNodeTypes>
* <mixinNodeType>mixtype1</mixinNodeType> <mixinNodeType>mixtype2</mixinNodeType>
* </mixinNodeTypes> <properties> <property> <name>propName</name>
* <value>propValue</value> <type>propType</type> </property> <!-- more
* --> </properties> </node>
*/
/** default log */
private static final String ELEM_NODE = "node";
private static final String ELEM_PRIMARY_NODE_TYPE = "primaryNodeType";
private static final String ELEM_MIXIN_NODE_TYPE = "mixinNodeType";
private static final String ELEM_PROPERTY = "property";
private static final String ELEM_NAME = "name";
private static final String ELEM_VALUE = "value";
private static final String ELEM_VALUES = "values";
private static final String ELEM_TYPE = "type";
private static final String XML_STYLESHEET_PROCESSING_INSTRUCTION = "xml-stylesheet";
private static final String HREF_ATTRIBUTE = "href";
private static final String ELEM_FILE_NAMESPACE = "http://www.jcp.org/jcr/nt/1.0";
private static final String ELEM_FILE_NAME = "file";
public static final ImportProvider PROVIDER = new ImportProvider() {
private XmlReader xmlReader;
public ContentReader getReader() throws IOException {
if (xmlReader == null) {
try {
xmlReader = new XmlReader();
} catch (Throwable t) {
throw (IOException) new IOException(t.getMessage()).initCause(t);
}
}
return xmlReader;
}
};
private KXmlParser xmlParser;
XmlReader() {
this.xmlParser = new KXmlParser();
try {
// Make namespace-aware
this.xmlParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
} catch (XmlPullParserException e) {
throw new RuntimeException(e);
}
}
// ---------- XML content access -------------------------------------------
/**
* @see org.apache.sling.jcr.contentloader.internal.ContentReader#parse(java.net.URL, org.apache.sling.jcr.contentloader.internal.ContentCreator)
*/
public synchronized void parse(java.net.URL url, ContentCreator creator)
throws IOException, RepositoryException {
BufferedInputStream bufferedInput = null;
try {
// We need to buffer input, so that we can reset the stream if we encounter an XSL stylesheet reference
bufferedInput = new BufferedInputStream(url.openStream());
parseInternal(bufferedInput, creator, url);
} catch (XmlPullParserException xppe) {
throw (IOException) new IOException(xppe.getMessage()).initCause(xppe);
} finally {
closeStream(bufferedInput);
}
}
private void parseInternal(InputStream bufferedInput, ContentCreator creator, java.net.URL xmlLocation) throws XmlPullParserException, IOException, RepositoryException {
final StringBuffer contentBuffer = new StringBuffer();
// Mark the beginning of the stream. We assume that if there's an XSL processing instruction,
// it will occur in the first gulp - which makes sense, as processing instructions must be
// specified before the root elemeent of an XML file.
bufferedInput.mark(bufferedInput.available());
// set the parser input, use null encoding to force detection with
// <?xml?>
this.xmlParser.setInput(bufferedInput, null);
NodeDescription.SHARED.clear();
PropertyDescription.SHARED.clear();
FileDescription.SHARED.clear();
NodeDescription currentNode = null;
PropertyDescription currentProperty = null;
String currentElement;
int eventType = this.xmlParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.PROCESSING_INSTRUCTION) {
ProcessingInstruction pi = new ProcessingInstruction(this.xmlParser.getText());
// Look for a reference to an XSL stylesheet
if (pi.getName().equals(XML_STYLESHEET_PROCESSING_INSTRUCTION)) {
// Rewind the input stream to the beginning, so that it can be transformed with XSL
bufferedInput.reset();
// Pipe the XML input through the XSL transformer
XslTransformerStream transformerStream = new XslTransformerStream(bufferedInput, pi.getAttribute(HREF_ATTRIBUTE), xmlLocation);
// Start the transformer thread
transformerStream.startTransform();
// Re-run the XML parser, now with the transformed XML
parseInternal(transformerStream, creator, xmlLocation);
transformerStream.close();
return;
}
}
if (eventType == XmlPullParser.START_TAG) {
currentElement = this.xmlParser.getName();
if (ELEM_PROPERTY.equals(currentElement)) {
currentNode = NodeDescription.create(currentNode, creator);
currentProperty = PropertyDescription.SHARED;
} else if (ELEM_NODE.equals(currentElement)) {
currentNode = NodeDescription.create(currentNode, creator);
currentNode = NodeDescription.SHARED;
} else if (ELEM_FILE_NAME.equals(currentElement) && ELEM_FILE_NAMESPACE.equals(this.xmlParser.getNamespace())) {
int attributeCount = this.xmlParser.getAttributeCount();
if (attributeCount < 2 || attributeCount > 3) {
throw new IOException("File element must have these attributes: url, mimeType and lastModified");
}
try {
AttributeMap attributes = AttributeMap.getInstance();
attributes.setValues(xmlParser);
FileDescription.SHARED.setBaseLocation(xmlLocation);
FileDescription.SHARED.setValues(attributes);
attributes.clear();
} catch (ParseException e) {
- throw new IOException("Error parsing file description", e);
+ IOException ioe = new IOException("Error parsing file description");
+ ioe.initCause(e);
+ throw ioe;
}
FileDescription.SHARED.create(creator);
FileDescription.SHARED.clear();
}
} else if (eventType == XmlPullParser.END_TAG) {
String qName = this.xmlParser.getName();
String content = contentBuffer.toString().trim();
contentBuffer.delete(0, contentBuffer.length());
if (ELEM_PROPERTY.equals(qName)) {
currentProperty = PropertyDescription.create(currentProperty, creator);
} else if (ELEM_NAME.equals(qName)) {
if (currentProperty != null) {
currentProperty.name = content;
} else if (currentNode != null) {
currentNode.name = content;
}
} else if (ELEM_VALUE.equals(qName)) {
currentProperty.addValue(content);
} else if (ELEM_VALUES.equals(qName)) {
currentProperty.isMultiValue = true;
} else if (ELEM_TYPE.equals(qName)) {
currentProperty.type = content;
} else if (ELEM_NODE.equals(qName)) {
currentNode = NodeDescription.create(currentNode, creator);
creator.finishNode();
} else if (ELEM_PRIMARY_NODE_TYPE.equals(qName)) {
if ( currentNode == null ) {
throw new IOException("Element is not allowed at this location: " + qName);
}
currentNode.primaryNodeType = content;
} else if (ELEM_MIXIN_NODE_TYPE.equals(qName)) {
if ( currentNode == null ) {
throw new IOException("Element is not allowed at this location: " + qName);
}
currentNode.addMixinType(content);
}
} else if (eventType == XmlPullParser.TEXT || eventType == XmlPullParser.CDSECT) {
contentBuffer.append(this.xmlParser.getText());
}
eventType = this.xmlParser.nextToken();
}
}
/**
* Takes an XML input stream and pipes it through an XSL transformer.
* Callers should call {@link #startTransform} before trying to use the stream, or the caller will wait indefinately for input.
*/
private static class XslTransformerStream extends PipedInputStream {
private InputStream inputXml;
private String xslHref;
private Thread transformerThread;
private PipedOutputStream pipedOut;
private URL xmlLocation;
/**
* Instantiate the XslTransformerStream.
* @param inputXml XML to be transformed.
* @param xslHref Path to an XSL stylesheet
* @param xmlLocation
* @throws IOException
*/
public XslTransformerStream(InputStream inputXml, String xslHref, URL xmlLocation) throws IOException {
super();
this.inputXml = inputXml;
this.xslHref = xslHref;
this.transformerThread = null;
this.pipedOut = new PipedOutputStream(this);
this.xmlLocation = xmlLocation;
}
/**
* Starts the XSL transformer in a new thread, so that it can pipe its output to our <code>PipedInputStream</code>.
* @throws IOException
*/
public void startTransform() throws IOException {
final URL xslResource = new java.net.URL(xmlLocation, this.xslHref);
/*
if (xslResource == null) {
throw new IOException("Could not find " + xslHref);
}
*/
transformerThread = new Thread(
new Runnable() {
public void run() {
try {
Source xml = new StreamSource(inputXml);
Source xsl = new StreamSource(xslResource.toExternalForm());
final StreamResult streamResult;
final Templates templates = TransformerFactory.newInstance().newTemplates(xsl);
streamResult = new StreamResult(pipedOut);
templates.newTransformer().transform(xml, streamResult);
} catch (TransformerConfigurationException e) {
throw new RuntimeException("Error initializing XSL transformer", e);
} catch (TransformerException e) {
throw new RuntimeException("Error transforming", e);
} finally {
closeStream(pipedOut);
}
}
}
, "XslTransformerThread");
transformerThread.start();
}
}
/**
* Utility function to close a stream if it is still open.
* @param closeable Stream to close
*/
private static void closeStream(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException ignore) {
}
}
}
protected static final class NodeDescription {
public static NodeDescription SHARED = new NodeDescription();
public String name;
public String primaryNodeType;
public List<String> mixinTypes;
public static NodeDescription create(NodeDescription desc, ContentCreator creator)
throws RepositoryException {
if ( desc != null ) {
creator.createNode(desc.name, desc.primaryNodeType, desc.getMixinTypes());
desc.clear();
}
return null;
}
public void addMixinType(String v) {
if ( this.mixinTypes == null ) {
this.mixinTypes = new ArrayList<String>();
}
this.mixinTypes.add(v);
}
private String[] getMixinTypes() {
if ( this.mixinTypes == null || this.mixinTypes.size() == 0) {
return null;
}
return mixinTypes.toArray(new String[this.mixinTypes.size()]);
}
private void clear() {
this.name = null;
this.primaryNodeType = null;
if ( this.mixinTypes != null ) {
this.mixinTypes.clear();
}
}
}
protected static final class PropertyDescription {
public static PropertyDescription SHARED = new PropertyDescription();
public static PropertyDescription create(PropertyDescription desc, ContentCreator creator)
throws RepositoryException {
int type = (desc.type == null ? PropertyType.STRING : PropertyType.valueFromName(desc.type));
if ( desc.isMultiValue ) {
creator.createProperty(desc.name, type, desc.getPropertyValues());
} else {
String value = null;
if ( desc.values != null && desc.values.size() == 1 ) {
value = desc.values.get(0);
}
creator.createProperty(desc.name, type, value);
}
desc.clear();
return null;
}
public String name;
public String type;
public List<String> values;
public boolean isMultiValue;
public void addValue(String v) {
if ( this.values == null ) {
this.values = new ArrayList<String>();
}
this.values.add(v);
}
private String[] getPropertyValues() {
if ( this.values == null || this.values.size() == 0) {
return null;
}
return values.toArray(new String[this.values.size()]);
}
private void clear() {
this.name = null;
this.type = null;
if ( this.values != null ) {
this.values.clear();
}
this.isMultiValue = false;
}
}
/**
* Represents an XML processing instruction.<br />
* A processing instruction like <code><?xml-stylesheet href="stylesheet.xsl" type="text/css"?></code>
* will have <code>name</code> == <code>"xml-stylesheet"</code> and two attributes: <code>href</code> and <code>type</code>.
*/
private static class ProcessingInstruction {
private Map<String, String> attributes = new HashMap<String, String>();
private static final Pattern ATTRIBUTE_PATTERN = Pattern.compile("\\s(.[^=\\s]*)\\s?=\\s?\"(.[^\"]*)\"");
private static final Pattern NAME_PATTERN = Pattern.compile("^(.[^\\s\\?>]*)");
private String name;
public ProcessingInstruction(String text) throws IOException {
final Matcher nameMatcher = NAME_PATTERN.matcher(text);
if (!nameMatcher.find()) {
throw new IOException("Malformed processing instruction: " + text);
}
this.name = nameMatcher.group(1);
final Matcher attributeMatcher = ATTRIBUTE_PATTERN.matcher(text);
while (attributeMatcher.find()) {
attributes.put(attributeMatcher.group(1), attributeMatcher.group(2));
}
}
public String getName() {
return name;
}
public String getAttribute(String key) {
return this.attributes.get(key);
}
}
/**
* Represents a reference to a file that is to be loaded into the repository. The file is referenced by an
* XML element named <code><nt:file></code>, with the attributes <code>src</code>,
* <code>mimeType</code> and <code>lastModified</code>. <br/><br/>Example:
* <pre>
* <nt:file src="../../image.png" mimeType="image/png" lastModified="1977-06-01T07:00:00+0100" />
* </pre>
* The date format for <code>lastModified</code> is <code>yyyy-MM-dd'T'HH:mm:ssZ</code>.
* The <code>lastModified</code> attribute is optional. If missing, the last modified date reported by the
* filesystem will be used.
*/
protected static final class FileDescription {
private URL url;
private String mimeType;
private URL baseLocation;
private Long lastModified;
public static FileDescription SHARED = new FileDescription();
private static final String SRC_ATTRIBUTE = "src";
private static final String MIME_TYPE_ATTRIBUTE = "mimeType";
private static final String LAST_MODIFIED_ATTRIBUTE = "lastModified";
public static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
static {
DATE_FORMAT.setLenient(true);
}
public void setValues(AttributeMap attributes) throws MalformedURLException, ParseException {
Set<String> attributeNames = attributes.keySet();
for (String name : attributeNames) {
String value = attributes.get(name);
if (name.equals(SRC_ATTRIBUTE)) {
url = new URL(baseLocation, value);
} else if (name.equals(MIME_TYPE_ATTRIBUTE)) {
mimeType = value;
} else if (name.equals(LAST_MODIFIED_ATTRIBUTE)) {
lastModified = DATE_FORMAT.parse(value).getTime();
}
}
}
public void create(ContentCreator creator) throws RepositoryException, IOException {
String[] parts = url.getPath().split("/");
String name = parts[parts.length - 1];
InputStream stream = url.openStream();
if (lastModified == null) {
try {
lastModified = new File(url.toURI()).lastModified();
} catch (Throwable ignore) {
// Could not get lastModified from file system, so we'll use current date
lastModified = Calendar.getInstance().getTimeInMillis();
}
}
creator.createFileAndResourceNode(name, stream, mimeType, lastModified);
closeStream(stream);
creator.finishNode();
creator.finishNode();
this.clear();
}
public URL getUrl() {
return url;
}
public String getMimeType() {
return mimeType;
}
public Long getLastModified() {
return lastModified;
}
public void clear() {
this.url = null;
this.mimeType = null;
this.lastModified = null;
}
public void setBaseLocation(URL xmlLocation) {
this.baseLocation = xmlLocation;
}
}
/**
* Utility class for dealing with attributes from KXmlParser.
*/
protected static class AttributeMap extends HashMap<String, String> {
private static final AttributeMap instance = new AttributeMap();
public static AttributeMap getInstance() {
return instance;
}
/**
* Puts values in an <code>AttributeMap</code> by extracting attributes from the <code>xmlParser</code>.
* @param xmlParser <code>xmlParser</code> to extract attributes from. The parser must be
* in {@link org.xmlpull.v1.XmlPullParser#START_TAG} state.
*/
public void setValues(KXmlParser xmlParser) {
final int count = xmlParser.getAttributeCount();
for (int i = 0; i < count; i++) {
this.put(xmlParser.getAttributeName(i), xmlParser.getAttributeValue(i));
}
}
}
}
| true | true | private void parseInternal(InputStream bufferedInput, ContentCreator creator, java.net.URL xmlLocation) throws XmlPullParserException, IOException, RepositoryException {
final StringBuffer contentBuffer = new StringBuffer();
// Mark the beginning of the stream. We assume that if there's an XSL processing instruction,
// it will occur in the first gulp - which makes sense, as processing instructions must be
// specified before the root elemeent of an XML file.
bufferedInput.mark(bufferedInput.available());
// set the parser input, use null encoding to force detection with
// <?xml?>
this.xmlParser.setInput(bufferedInput, null);
NodeDescription.SHARED.clear();
PropertyDescription.SHARED.clear();
FileDescription.SHARED.clear();
NodeDescription currentNode = null;
PropertyDescription currentProperty = null;
String currentElement;
int eventType = this.xmlParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.PROCESSING_INSTRUCTION) {
ProcessingInstruction pi = new ProcessingInstruction(this.xmlParser.getText());
// Look for a reference to an XSL stylesheet
if (pi.getName().equals(XML_STYLESHEET_PROCESSING_INSTRUCTION)) {
// Rewind the input stream to the beginning, so that it can be transformed with XSL
bufferedInput.reset();
// Pipe the XML input through the XSL transformer
XslTransformerStream transformerStream = new XslTransformerStream(bufferedInput, pi.getAttribute(HREF_ATTRIBUTE), xmlLocation);
// Start the transformer thread
transformerStream.startTransform();
// Re-run the XML parser, now with the transformed XML
parseInternal(transformerStream, creator, xmlLocation);
transformerStream.close();
return;
}
}
if (eventType == XmlPullParser.START_TAG) {
currentElement = this.xmlParser.getName();
if (ELEM_PROPERTY.equals(currentElement)) {
currentNode = NodeDescription.create(currentNode, creator);
currentProperty = PropertyDescription.SHARED;
} else if (ELEM_NODE.equals(currentElement)) {
currentNode = NodeDescription.create(currentNode, creator);
currentNode = NodeDescription.SHARED;
} else if (ELEM_FILE_NAME.equals(currentElement) && ELEM_FILE_NAMESPACE.equals(this.xmlParser.getNamespace())) {
int attributeCount = this.xmlParser.getAttributeCount();
if (attributeCount < 2 || attributeCount > 3) {
throw new IOException("File element must have these attributes: url, mimeType and lastModified");
}
try {
AttributeMap attributes = AttributeMap.getInstance();
attributes.setValues(xmlParser);
FileDescription.SHARED.setBaseLocation(xmlLocation);
FileDescription.SHARED.setValues(attributes);
attributes.clear();
} catch (ParseException e) {
throw new IOException("Error parsing file description", e);
}
FileDescription.SHARED.create(creator);
FileDescription.SHARED.clear();
}
} else if (eventType == XmlPullParser.END_TAG) {
String qName = this.xmlParser.getName();
String content = contentBuffer.toString().trim();
contentBuffer.delete(0, contentBuffer.length());
if (ELEM_PROPERTY.equals(qName)) {
currentProperty = PropertyDescription.create(currentProperty, creator);
} else if (ELEM_NAME.equals(qName)) {
if (currentProperty != null) {
currentProperty.name = content;
} else if (currentNode != null) {
currentNode.name = content;
}
} else if (ELEM_VALUE.equals(qName)) {
currentProperty.addValue(content);
} else if (ELEM_VALUES.equals(qName)) {
currentProperty.isMultiValue = true;
} else if (ELEM_TYPE.equals(qName)) {
currentProperty.type = content;
} else if (ELEM_NODE.equals(qName)) {
currentNode = NodeDescription.create(currentNode, creator);
creator.finishNode();
} else if (ELEM_PRIMARY_NODE_TYPE.equals(qName)) {
if ( currentNode == null ) {
throw new IOException("Element is not allowed at this location: " + qName);
}
currentNode.primaryNodeType = content;
} else if (ELEM_MIXIN_NODE_TYPE.equals(qName)) {
if ( currentNode == null ) {
throw new IOException("Element is not allowed at this location: " + qName);
}
currentNode.addMixinType(content);
}
} else if (eventType == XmlPullParser.TEXT || eventType == XmlPullParser.CDSECT) {
contentBuffer.append(this.xmlParser.getText());
}
eventType = this.xmlParser.nextToken();
}
}
| private void parseInternal(InputStream bufferedInput, ContentCreator creator, java.net.URL xmlLocation) throws XmlPullParserException, IOException, RepositoryException {
final StringBuffer contentBuffer = new StringBuffer();
// Mark the beginning of the stream. We assume that if there's an XSL processing instruction,
// it will occur in the first gulp - which makes sense, as processing instructions must be
// specified before the root elemeent of an XML file.
bufferedInput.mark(bufferedInput.available());
// set the parser input, use null encoding to force detection with
// <?xml?>
this.xmlParser.setInput(bufferedInput, null);
NodeDescription.SHARED.clear();
PropertyDescription.SHARED.clear();
FileDescription.SHARED.clear();
NodeDescription currentNode = null;
PropertyDescription currentProperty = null;
String currentElement;
int eventType = this.xmlParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.PROCESSING_INSTRUCTION) {
ProcessingInstruction pi = new ProcessingInstruction(this.xmlParser.getText());
// Look for a reference to an XSL stylesheet
if (pi.getName().equals(XML_STYLESHEET_PROCESSING_INSTRUCTION)) {
// Rewind the input stream to the beginning, so that it can be transformed with XSL
bufferedInput.reset();
// Pipe the XML input through the XSL transformer
XslTransformerStream transformerStream = new XslTransformerStream(bufferedInput, pi.getAttribute(HREF_ATTRIBUTE), xmlLocation);
// Start the transformer thread
transformerStream.startTransform();
// Re-run the XML parser, now with the transformed XML
parseInternal(transformerStream, creator, xmlLocation);
transformerStream.close();
return;
}
}
if (eventType == XmlPullParser.START_TAG) {
currentElement = this.xmlParser.getName();
if (ELEM_PROPERTY.equals(currentElement)) {
currentNode = NodeDescription.create(currentNode, creator);
currentProperty = PropertyDescription.SHARED;
} else if (ELEM_NODE.equals(currentElement)) {
currentNode = NodeDescription.create(currentNode, creator);
currentNode = NodeDescription.SHARED;
} else if (ELEM_FILE_NAME.equals(currentElement) && ELEM_FILE_NAMESPACE.equals(this.xmlParser.getNamespace())) {
int attributeCount = this.xmlParser.getAttributeCount();
if (attributeCount < 2 || attributeCount > 3) {
throw new IOException("File element must have these attributes: url, mimeType and lastModified");
}
try {
AttributeMap attributes = AttributeMap.getInstance();
attributes.setValues(xmlParser);
FileDescription.SHARED.setBaseLocation(xmlLocation);
FileDescription.SHARED.setValues(attributes);
attributes.clear();
} catch (ParseException e) {
IOException ioe = new IOException("Error parsing file description");
ioe.initCause(e);
throw ioe;
}
FileDescription.SHARED.create(creator);
FileDescription.SHARED.clear();
}
} else if (eventType == XmlPullParser.END_TAG) {
String qName = this.xmlParser.getName();
String content = contentBuffer.toString().trim();
contentBuffer.delete(0, contentBuffer.length());
if (ELEM_PROPERTY.equals(qName)) {
currentProperty = PropertyDescription.create(currentProperty, creator);
} else if (ELEM_NAME.equals(qName)) {
if (currentProperty != null) {
currentProperty.name = content;
} else if (currentNode != null) {
currentNode.name = content;
}
} else if (ELEM_VALUE.equals(qName)) {
currentProperty.addValue(content);
} else if (ELEM_VALUES.equals(qName)) {
currentProperty.isMultiValue = true;
} else if (ELEM_TYPE.equals(qName)) {
currentProperty.type = content;
} else if (ELEM_NODE.equals(qName)) {
currentNode = NodeDescription.create(currentNode, creator);
creator.finishNode();
} else if (ELEM_PRIMARY_NODE_TYPE.equals(qName)) {
if ( currentNode == null ) {
throw new IOException("Element is not allowed at this location: " + qName);
}
currentNode.primaryNodeType = content;
} else if (ELEM_MIXIN_NODE_TYPE.equals(qName)) {
if ( currentNode == null ) {
throw new IOException("Element is not allowed at this location: " + qName);
}
currentNode.addMixinType(content);
}
} else if (eventType == XmlPullParser.TEXT || eventType == XmlPullParser.CDSECT) {
contentBuffer.append(this.xmlParser.getText());
}
eventType = this.xmlParser.nextToken();
}
}
|
diff --git a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/callgraph/launch/SystemTapLaunchConfigurationDelegate.java b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/callgraph/launch/SystemTapLaunchConfigurationDelegate.java
index 565da0d1a..664caf210 100644
--- a/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/callgraph/launch/SystemTapLaunchConfigurationDelegate.java
+++ b/systemtap/org.eclipse.linuxtools.callgraph.launch/src/org/eclipse/linuxtools/callgraph/launch/SystemTapLaunchConfigurationDelegate.java
@@ -1,509 +1,509 @@
/*******************************************************************************
* Copyright (c) 2009 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat - initial API and implementation
*******************************************************************************/
package org.eclipse.linuxtools.callgraph.launch;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import org.eclipse.cdt.launch.AbstractCLaunchDelegate;
import org.eclipse.cdt.utils.pty.PTY;
import org.eclipse.cdt.utils.spawner.ProcessFactory;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.IStreamListener;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.debug.core.model.IStreamMonitor;
import org.eclipse.jface.text.IDocument;
import org.eclipse.linuxtools.callgraph.core.DocWriter;
import org.eclipse.linuxtools.callgraph.core.Helper;
import org.eclipse.linuxtools.callgraph.core.LaunchConfigurationConstants;
import org.eclipse.linuxtools.callgraph.core.PluginConstants;
import org.eclipse.linuxtools.callgraph.core.SystemTapCommandGenerator;
import org.eclipse.linuxtools.callgraph.core.SystemTapErrorHandler;
import org.eclipse.linuxtools.callgraph.core.SystemTapParser;
import org.eclipse.linuxtools.callgraph.core.SystemTapUIErrorMessages;
import org.eclipse.ui.console.TextConsole;
/**
* Delegate for Stap scripts. The Delegate generates part of the command string
* and schedules a job to finish generation of the command and execute.
*
*/
public class SystemTapLaunchConfigurationDelegate extends
AbstractCLaunchDelegate {
private static final String TEMP_ERROR_OUTPUT =
PluginConstants.getDefaultOutput() + "stapTempError.error"; //$NON-NLS-1$
private String cmd;
private File temporaryScript = null;
private String arguments = ""; //$NON-NLS-1$
private String scriptPath = ""; //$NON-NLS-1$
private String binaryPath = ""; //$NON-NLS-1$
private String outputPath = ""; //$NON-NLS-1$
private boolean needsBinary = false; // Set to false if we want to use SystemTap
private boolean needsArguments = false;
@SuppressWarnings("unused")
private boolean useColour = false;
private String binaryArguments = ""; //$NON-NLS-1$
@Override
protected String getPluginID() {
return null;
}
/**
* Sets strings to blank, booleans to false and everything else to null
*/
private void initialize() {
temporaryScript = null;
arguments = ""; //$NON-NLS-1$
scriptPath = ""; //$NON-NLS-1$
binaryPath = ""; //$NON-NLS-1$
outputPath = ""; //$NON-NLS-1$
needsBinary = false; // Set to false if we want to use SystemTap
needsArguments = false;
useColour = false;
binaryArguments = ""; //$NON-NLS-1$
}
@Override
public void launch(ILaunchConfiguration config, String mode,
ILaunch launch, IProgressMonitor m) throws CoreException {
if (m == null) {
m = new NullProgressMonitor();
}
SubMonitor monitor = SubMonitor.convert(m,
"SystemTap runtime monitor", 5); //$NON-NLS-1$
initialize();
// check for cancellation
if (monitor.isCanceled()) {
return;
}
/*
* Set variables
*/
if (config.getAttribute(LaunchConfigurationConstants.USE_COLOUR,
LaunchConfigurationConstants.DEFAULT_USE_COLOUR))
useColour = true;
if (!config.getAttribute(LaunchConfigurationConstants.ARGUMENTS,
LaunchConfigurationConstants.DEFAULT_ARGUMENTS).equals(
LaunchConfigurationConstants.DEFAULT_ARGUMENTS)) {
arguments = config.getAttribute(
LaunchConfigurationConstants.ARGUMENTS,
LaunchConfigurationConstants.DEFAULT_ARGUMENTS);
needsArguments = true;
}
if (!config.getAttribute(LaunchConfigurationConstants.BINARY_PATH,
LaunchConfigurationConstants.DEFAULT_BINARY_PATH).equals(
LaunchConfigurationConstants.DEFAULT_BINARY_PATH)) {
binaryPath = config.getAttribute(
LaunchConfigurationConstants.BINARY_PATH,
LaunchConfigurationConstants.DEFAULT_BINARY_PATH);
needsBinary = true;
}
if (!config.getAttribute(LaunchConfigurationConstants.BINARY_ARGUMENTS,
LaunchConfigurationConstants.DEFAULT_BINARY_ARGUMENTS).equals(
LaunchConfigurationConstants.DEFAULT_BINARY_ARGUMENTS)) {
binaryArguments = config.getAttribute(
LaunchConfigurationConstants.BINARY_ARGUMENTS,
LaunchConfigurationConstants.DEFAULT_BINARY_ARGUMENTS);
}
if (!config.getAttribute(LaunchConfigurationConstants.SCRIPT_PATH,
LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH).equals(
LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH)) {
scriptPath = config.getAttribute(
LaunchConfigurationConstants.SCRIPT_PATH,
LaunchConfigurationConstants.DEFAULT_SCRIPT_PATH);
}
// Generate script if needed
if (config.getAttribute(LaunchConfigurationConstants.NEED_TO_GENERATE,
LaunchConfigurationConstants.DEFAULT_NEED_TO_GENERATE)) {
temporaryScript = new File(scriptPath);
temporaryScript.delete();
try {
temporaryScript.createNewFile();
FileWriter fstream = new FileWriter(temporaryScript);
BufferedWriter out = new BufferedWriter(fstream);
out.write(config.getAttribute(
LaunchConfigurationConstants.GENERATED_SCRIPT,
LaunchConfigurationConstants.DEFAULT_GENERATED_SCRIPT));
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
/**
* Generate partial command
*/
String partialCommand = ConfigurationOptionsSetter.setOptions(config);
outputPath = config.getAttribute(
LaunchConfigurationConstants.OUTPUT_PATH,
PluginConstants.getDefaultOutput());
partialCommand += "-o " + outputPath; //$NON-NLS-1$
try {
//Make sure the output file exists
File tempFile = new File(outputPath);
tempFile.delete();
tempFile.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
// check for cancellation
if (monitor.isCanceled()) {
return;
}
finishLaunch(launch, config, partialCommand, m, true);
}
/**
* Returns the current SystemTap command, or returns an error message.
* @return
*/
public String getCommand() {
if (cmd.length() > 0)
return cmd;
else
return Messages.getString("SystemTapLaunchConfigurationDelegate.0"); //$NON-NLS-1$
}
/**
* Executes a command array using pty
*
* @param commandArray -- Split a command string on the ' ' character
* @param env -- Use <code>getEnvironment(ILaunchConfiguration)</code> in the AbstractCLaunchDelegate.
* @param wd -- Working directory
* @param usePty -- A value of 'true' usually suffices
* @return A properly formed process, or null
* @throws IOException -- If the process cannot be created
*/
public Process execute(String[] commandArray, String[] env, File wd,
boolean usePty) throws IOException {
Process process = null;
try {
if (wd == null) {
process = ProcessFactory.getFactory().exec(commandArray, env);
} else {
if (PTY.isSupported() && usePty) {
process = ProcessFactory.getFactory().exec(commandArray,
env, wd, new PTY());
} else {
process = ProcessFactory.getFactory().exec(commandArray,
env, wd);
}
}
} catch (IOException e) {
if (process != null) {
process.destroy();
}
return null;
}
return process;
}
/**
* Spawn a new IProcess using the Debug Plugin.
*
* @param launch
* @param systemProcess
* @param programName
* @return
*/
protected IProcess createNewProcess(ILaunch launch, Process systemProcess,
String programName) {
return DebugPlugin.newProcess(launch, systemProcess,
renderProcessLabel(programName));
}
private void finishLaunch(ILaunch launch, ILaunchConfiguration config, String command,
IProgressMonitor monitor, boolean retry) {
String errorMessage = ""; //$NON-NLS-1$
try {
File workDir = getWorkingDirectory(config);
if (workDir == null) {
workDir = new File(System.getProperty("user.home", ".")); //$NON-NLS-1$ //$NON-NLS-2$
}
// Generate the command
SystemTapCommandGenerator cmdGenerator = new SystemTapCommandGenerator();
cmd = cmdGenerator.generateCommand(scriptPath, binaryPath,
command, needsBinary, needsArguments, arguments, binaryArguments);
// Prepare cmd for execution - we need a command array of strings,
// no string can contain a space character. (One of the process'
// requirements)
String tmp[] = cmd.split(" "); //$NON-NLS-1$
ArrayList<String> cmdLine = new ArrayList<String>();
for (String str : tmp) {
cmdLine.add(str);
}
String[] commandArray = (String[]) cmdLine.toArray(new String[cmdLine.size()]);
// Check for cancellation
if (monitor.isCanceled()) {
return;
}
monitor.worked(1);
if (launch == null) {
return;
}
// Not sure if this line is necessary
// set the default source locator if required
setDefaultSourceLocator(launch, config);
String parserClass = config.getAttribute(LaunchConfigurationConstants.PARSER_CLASS,
LaunchConfigurationConstants.DEFAULT_PARSER_CLASS);
IExtensionRegistry reg = Platform.getExtensionRegistry();
IConfigurationElement[] extensions = reg
.getConfigurationElementsFor(PluginConstants.PARSER_RESOURCE,
PluginConstants.PARSER_NAME,
parserClass);
if (extensions == null || extensions.length < 1) {
SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser1"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser2"), //$NON-NLS-1$ //$NON-NLS-2$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser3") + //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser4") + parserClass); //$NON-NLS-1$
mess.schedule();
return;
}
IConfigurationElement element = extensions[0];
SystemTapParser parser =
(SystemTapParser) element.createExecutableExtension(PluginConstants.ATTR_CLASS);
parser.setViewID(config.getAttribute(LaunchConfigurationConstants.VIEW_CLASS,
LaunchConfigurationConstants.VIEW_CLASS));
parser.setSourcePath(outputPath);
parser.setMonitor(SubMonitor.convert(monitor));
parser.setDone(false);
parser.setKillButtonEnabled(true);
if (element.getAttribute(PluginConstants.ATTR_REALTIME).equals(PluginConstants.VAL_TRUE)) {
parser.setRealTime(true);
parser.schedule();
}
monitor.worked(1);
Process subProcess = execute(commandArray, getEnvironment(config),
workDir, true);
System.out.println(cmd);
if (subProcess == null){
SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.NullProcessErrorName"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.NullProcessErrorTitle"), //$NON-NLS-1$ //$NON-NLS-2$
Messages.getString("SystemTapLaunchConfigurationDelegate.NullProcessErrorMessage1")); //$NON-NLS-1$
mess.schedule();
return;
}
IProcess process = createNewProcess(launch, subProcess,commandArray[0]);
// set the command line used
process.setAttribute(IProcess.ATTR_CMDLINE,cmd);
monitor.worked(1);
StreamListener s = new StreamListener();
process.getStreamsProxy().getErrorStreamMonitor().addListener(s);
while (!process.isTerminated()) {
Thread.sleep(100);
if ((monitor != null && monitor.isCanceled()) || parser.isJobCancelled()) {
parser.cancelJob();
process.terminate();
return;
}
}
Thread.sleep(100);
s.close();
parser.setKillButtonEnabled(false);
if (process.getExitValue() != 0) {
parser.cancelJob();
//SystemTap terminated with errors, parse console to figure out which error
IDocument doc = Helper.getConsoleDocumentByName(config.getName());
//Sometimes the console has not been printed to yet, wait for a little while longer
if (doc.get().length() < 1)
Thread.sleep(300);
SystemTapErrorHandler errorHandler = new SystemTapErrorHandler();
//Prepare stap information
errorHandler.appendToLog(config.getName() + Messages.getString("SystemTapLaunchConfigurationDelegate.stap_command") + cmd+ PluginConstants.NEW_LINE + PluginConstants.NEW_LINE);//$NON-NLS-1$
//Handle error from TEMP_ERROR_OUTPUT
errorMessage = errorHandler.handle(monitor, new FileReader(TEMP_ERROR_OUTPUT)); //$NON-NLS-1$
if ((monitor != null && monitor.isCanceled()))
return;
//If we are meant to retry, and the conditions for retry are met
//Currently conditions only met if there are mismatched probe points present
if (errorHandler.hasMismatchedProbePoints() && retry) {
SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch1"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch2"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch3")); //$NON-NLS-1$
mess.schedule();
//If finishHandling determines that errors are not fixable, return
- if (!errorHandler.finishHandling(monitor, s.getNumberOfErrors(), scriptPath))
+ if (!errorHandler.finishHandling(monitor, scriptPath))
return;
//Abort job
if ((monitor != null && monitor.isCanceled()) || parser.isJobCancelled()) {
monitor.setCanceled(true);
parser.cancelJob();
return;
}
finishLaunch(launch, config, command, monitor, false);
return;
}
- errorHandler.finishHandling(monitor, s.getNumberOfErrors(), scriptPath);
+ errorHandler.finishHandling(monitor, scriptPath);
return;
}
if (! element.getAttribute(PluginConstants.ATTR_REALTIME).equals(PluginConstants.VAL_TRUE)) { //$NON-NLS-1$ //$NON-NLS-2$
parser.schedule();
} else {
//Parser already scheduled, but double-check
if (parser != null)
parser.cancelJob();
}
monitor.worked(1);
errorMessage = generateErrorMessage(config.getName(), command) + errorMessage;
DocWriter dw = new DocWriter(Messages.getString("SystemTapLaunchConfigurationDelegate.DocWriterName"), //$NON-NLS-1$
((TextConsole)Helper.getConsoleByName(config.getName())), errorMessage);
dw.schedule();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (CoreException e) {
e.printStackTrace();
} finally {
monitor.done();
}
}
private String generateErrorMessage(String configName, String binaryCommand) {
String output = ""; //$NON-NLS-1$
if (binaryCommand == null || binaryCommand.length() < 0) {
output = PluginConstants.NEW_LINE +
PluginConstants.NEW_LINE + "-------------" + //$NON-NLS-1$
PluginConstants.NEW_LINE +
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch10") //$NON-NLS-1$
+ configName + PluginConstants.NEW_LINE +
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch8") + //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch9") + //$NON-NLS-1$
"configuration in Profile As --> Profile Configurations." + //$NON-NLS-1$
PluginConstants.NEW_LINE + PluginConstants.NEW_LINE;
}
else {
output = PluginConstants.NEW_LINE
+ PluginConstants.NEW_LINE +"-------------" //$NON-NLS-1$
+ PluginConstants.NEW_LINE
+ Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage1") //$NON-NLS-1$
+ configName + PluginConstants.NEW_LINE +
Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage2") //$NON-NLS-1$
+ binaryCommand + PluginConstants.NEW_LINE +
Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage3") + //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage4") + //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.EndMessage5") + //$NON-NLS-1$
PluginConstants.NEW_LINE + PluginConstants.NEW_LINE;
}
return output;
}
private class StreamListener implements IStreamListener{
private Helper h;
private int counter;
public StreamListener() throws IOException {
File file = new File(TEMP_ERROR_OUTPUT);
file.delete();
file.createNewFile();
h = new Helper();
h.setBufferedWriter(TEMP_ERROR_OUTPUT); //$NON-NLS-1$
counter = 0;
}
@Override
public void streamAppended(String text, IStreamMonitor monitor) {
try {
if (text.length() < 1) return;
counter++;
if (counter < PluginConstants.MAX_ERRORS)
h.appendToExistingFile(text);
} catch (IOException e) {
e.printStackTrace();
}
}
public void close() throws IOException {
h.closeBufferedWriter();
}
public int getNumberOfErrors() {
return counter;
}
}
}
| false | true | private void finishLaunch(ILaunch launch, ILaunchConfiguration config, String command,
IProgressMonitor monitor, boolean retry) {
String errorMessage = ""; //$NON-NLS-1$
try {
File workDir = getWorkingDirectory(config);
if (workDir == null) {
workDir = new File(System.getProperty("user.home", ".")); //$NON-NLS-1$ //$NON-NLS-2$
}
// Generate the command
SystemTapCommandGenerator cmdGenerator = new SystemTapCommandGenerator();
cmd = cmdGenerator.generateCommand(scriptPath, binaryPath,
command, needsBinary, needsArguments, arguments, binaryArguments);
// Prepare cmd for execution - we need a command array of strings,
// no string can contain a space character. (One of the process'
// requirements)
String tmp[] = cmd.split(" "); //$NON-NLS-1$
ArrayList<String> cmdLine = new ArrayList<String>();
for (String str : tmp) {
cmdLine.add(str);
}
String[] commandArray = (String[]) cmdLine.toArray(new String[cmdLine.size()]);
// Check for cancellation
if (monitor.isCanceled()) {
return;
}
monitor.worked(1);
if (launch == null) {
return;
}
// Not sure if this line is necessary
// set the default source locator if required
setDefaultSourceLocator(launch, config);
String parserClass = config.getAttribute(LaunchConfigurationConstants.PARSER_CLASS,
LaunchConfigurationConstants.DEFAULT_PARSER_CLASS);
IExtensionRegistry reg = Platform.getExtensionRegistry();
IConfigurationElement[] extensions = reg
.getConfigurationElementsFor(PluginConstants.PARSER_RESOURCE,
PluginConstants.PARSER_NAME,
parserClass);
if (extensions == null || extensions.length < 1) {
SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser1"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser2"), //$NON-NLS-1$ //$NON-NLS-2$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser3") + //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser4") + parserClass); //$NON-NLS-1$
mess.schedule();
return;
}
IConfigurationElement element = extensions[0];
SystemTapParser parser =
(SystemTapParser) element.createExecutableExtension(PluginConstants.ATTR_CLASS);
parser.setViewID(config.getAttribute(LaunchConfigurationConstants.VIEW_CLASS,
LaunchConfigurationConstants.VIEW_CLASS));
parser.setSourcePath(outputPath);
parser.setMonitor(SubMonitor.convert(monitor));
parser.setDone(false);
parser.setKillButtonEnabled(true);
if (element.getAttribute(PluginConstants.ATTR_REALTIME).equals(PluginConstants.VAL_TRUE)) {
parser.setRealTime(true);
parser.schedule();
}
monitor.worked(1);
Process subProcess = execute(commandArray, getEnvironment(config),
workDir, true);
System.out.println(cmd);
if (subProcess == null){
SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.NullProcessErrorName"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.NullProcessErrorTitle"), //$NON-NLS-1$ //$NON-NLS-2$
Messages.getString("SystemTapLaunchConfigurationDelegate.NullProcessErrorMessage1")); //$NON-NLS-1$
mess.schedule();
return;
}
IProcess process = createNewProcess(launch, subProcess,commandArray[0]);
// set the command line used
process.setAttribute(IProcess.ATTR_CMDLINE,cmd);
monitor.worked(1);
StreamListener s = new StreamListener();
process.getStreamsProxy().getErrorStreamMonitor().addListener(s);
while (!process.isTerminated()) {
Thread.sleep(100);
if ((monitor != null && monitor.isCanceled()) || parser.isJobCancelled()) {
parser.cancelJob();
process.terminate();
return;
}
}
Thread.sleep(100);
s.close();
parser.setKillButtonEnabled(false);
if (process.getExitValue() != 0) {
parser.cancelJob();
//SystemTap terminated with errors, parse console to figure out which error
IDocument doc = Helper.getConsoleDocumentByName(config.getName());
//Sometimes the console has not been printed to yet, wait for a little while longer
if (doc.get().length() < 1)
Thread.sleep(300);
SystemTapErrorHandler errorHandler = new SystemTapErrorHandler();
//Prepare stap information
errorHandler.appendToLog(config.getName() + Messages.getString("SystemTapLaunchConfigurationDelegate.stap_command") + cmd+ PluginConstants.NEW_LINE + PluginConstants.NEW_LINE);//$NON-NLS-1$
//Handle error from TEMP_ERROR_OUTPUT
errorMessage = errorHandler.handle(monitor, new FileReader(TEMP_ERROR_OUTPUT)); //$NON-NLS-1$
if ((monitor != null && monitor.isCanceled()))
return;
//If we are meant to retry, and the conditions for retry are met
//Currently conditions only met if there are mismatched probe points present
if (errorHandler.hasMismatchedProbePoints() && retry) {
SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch1"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch2"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch3")); //$NON-NLS-1$
mess.schedule();
//If finishHandling determines that errors are not fixable, return
if (!errorHandler.finishHandling(monitor, s.getNumberOfErrors(), scriptPath))
return;
//Abort job
if ((monitor != null && monitor.isCanceled()) || parser.isJobCancelled()) {
monitor.setCanceled(true);
parser.cancelJob();
return;
}
finishLaunch(launch, config, command, monitor, false);
return;
}
errorHandler.finishHandling(monitor, s.getNumberOfErrors(), scriptPath);
return;
}
if (! element.getAttribute(PluginConstants.ATTR_REALTIME).equals(PluginConstants.VAL_TRUE)) { //$NON-NLS-1$ //$NON-NLS-2$
parser.schedule();
} else {
//Parser already scheduled, but double-check
if (parser != null)
parser.cancelJob();
}
monitor.worked(1);
errorMessage = generateErrorMessage(config.getName(), command) + errorMessage;
DocWriter dw = new DocWriter(Messages.getString("SystemTapLaunchConfigurationDelegate.DocWriterName"), //$NON-NLS-1$
((TextConsole)Helper.getConsoleByName(config.getName())), errorMessage);
dw.schedule();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (CoreException e) {
e.printStackTrace();
} finally {
monitor.done();
}
}
| private void finishLaunch(ILaunch launch, ILaunchConfiguration config, String command,
IProgressMonitor monitor, boolean retry) {
String errorMessage = ""; //$NON-NLS-1$
try {
File workDir = getWorkingDirectory(config);
if (workDir == null) {
workDir = new File(System.getProperty("user.home", ".")); //$NON-NLS-1$ //$NON-NLS-2$
}
// Generate the command
SystemTapCommandGenerator cmdGenerator = new SystemTapCommandGenerator();
cmd = cmdGenerator.generateCommand(scriptPath, binaryPath,
command, needsBinary, needsArguments, arguments, binaryArguments);
// Prepare cmd for execution - we need a command array of strings,
// no string can contain a space character. (One of the process'
// requirements)
String tmp[] = cmd.split(" "); //$NON-NLS-1$
ArrayList<String> cmdLine = new ArrayList<String>();
for (String str : tmp) {
cmdLine.add(str);
}
String[] commandArray = (String[]) cmdLine.toArray(new String[cmdLine.size()]);
// Check for cancellation
if (monitor.isCanceled()) {
return;
}
monitor.worked(1);
if (launch == null) {
return;
}
// Not sure if this line is necessary
// set the default source locator if required
setDefaultSourceLocator(launch, config);
String parserClass = config.getAttribute(LaunchConfigurationConstants.PARSER_CLASS,
LaunchConfigurationConstants.DEFAULT_PARSER_CLASS);
IExtensionRegistry reg = Platform.getExtensionRegistry();
IConfigurationElement[] extensions = reg
.getConfigurationElementsFor(PluginConstants.PARSER_RESOURCE,
PluginConstants.PARSER_NAME,
parserClass);
if (extensions == null || extensions.length < 1) {
SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser1"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser2"), //$NON-NLS-1$ //$NON-NLS-2$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser3") + //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.InvalidParser4") + parserClass); //$NON-NLS-1$
mess.schedule();
return;
}
IConfigurationElement element = extensions[0];
SystemTapParser parser =
(SystemTapParser) element.createExecutableExtension(PluginConstants.ATTR_CLASS);
parser.setViewID(config.getAttribute(LaunchConfigurationConstants.VIEW_CLASS,
LaunchConfigurationConstants.VIEW_CLASS));
parser.setSourcePath(outputPath);
parser.setMonitor(SubMonitor.convert(monitor));
parser.setDone(false);
parser.setKillButtonEnabled(true);
if (element.getAttribute(PluginConstants.ATTR_REALTIME).equals(PluginConstants.VAL_TRUE)) {
parser.setRealTime(true);
parser.schedule();
}
monitor.worked(1);
Process subProcess = execute(commandArray, getEnvironment(config),
workDir, true);
System.out.println(cmd);
if (subProcess == null){
SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.NullProcessErrorName"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.NullProcessErrorTitle"), //$NON-NLS-1$ //$NON-NLS-2$
Messages.getString("SystemTapLaunchConfigurationDelegate.NullProcessErrorMessage1")); //$NON-NLS-1$
mess.schedule();
return;
}
IProcess process = createNewProcess(launch, subProcess,commandArray[0]);
// set the command line used
process.setAttribute(IProcess.ATTR_CMDLINE,cmd);
monitor.worked(1);
StreamListener s = new StreamListener();
process.getStreamsProxy().getErrorStreamMonitor().addListener(s);
while (!process.isTerminated()) {
Thread.sleep(100);
if ((monitor != null && monitor.isCanceled()) || parser.isJobCancelled()) {
parser.cancelJob();
process.terminate();
return;
}
}
Thread.sleep(100);
s.close();
parser.setKillButtonEnabled(false);
if (process.getExitValue() != 0) {
parser.cancelJob();
//SystemTap terminated with errors, parse console to figure out which error
IDocument doc = Helper.getConsoleDocumentByName(config.getName());
//Sometimes the console has not been printed to yet, wait for a little while longer
if (doc.get().length() < 1)
Thread.sleep(300);
SystemTapErrorHandler errorHandler = new SystemTapErrorHandler();
//Prepare stap information
errorHandler.appendToLog(config.getName() + Messages.getString("SystemTapLaunchConfigurationDelegate.stap_command") + cmd+ PluginConstants.NEW_LINE + PluginConstants.NEW_LINE);//$NON-NLS-1$
//Handle error from TEMP_ERROR_OUTPUT
errorMessage = errorHandler.handle(monitor, new FileReader(TEMP_ERROR_OUTPUT)); //$NON-NLS-1$
if ((monitor != null && monitor.isCanceled()))
return;
//If we are meant to retry, and the conditions for retry are met
//Currently conditions only met if there are mismatched probe points present
if (errorHandler.hasMismatchedProbePoints() && retry) {
SystemTapUIErrorMessages mess = new SystemTapUIErrorMessages(Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch1"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch2"), //$NON-NLS-1$
Messages.getString("SystemTapLaunchConfigurationDelegate.Relaunch3")); //$NON-NLS-1$
mess.schedule();
//If finishHandling determines that errors are not fixable, return
if (!errorHandler.finishHandling(monitor, scriptPath))
return;
//Abort job
if ((monitor != null && monitor.isCanceled()) || parser.isJobCancelled()) {
monitor.setCanceled(true);
parser.cancelJob();
return;
}
finishLaunch(launch, config, command, monitor, false);
return;
}
errorHandler.finishHandling(monitor, scriptPath);
return;
}
if (! element.getAttribute(PluginConstants.ATTR_REALTIME).equals(PluginConstants.VAL_TRUE)) { //$NON-NLS-1$ //$NON-NLS-2$
parser.schedule();
} else {
//Parser already scheduled, but double-check
if (parser != null)
parser.cancelJob();
}
monitor.worked(1);
errorMessage = generateErrorMessage(config.getName(), command) + errorMessage;
DocWriter dw = new DocWriter(Messages.getString("SystemTapLaunchConfigurationDelegate.DocWriterName"), //$NON-NLS-1$
((TextConsole)Helper.getConsoleByName(config.getName())), errorMessage);
dw.schedule();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (CoreException e) {
e.printStackTrace();
} finally {
monitor.done();
}
}
|
diff --git a/src/com/matejdro/bukkit/monsterhunt/InputOutput.java b/src/com/matejdro/bukkit/monsterhunt/InputOutput.java
index 3f1cf43..620ecd4 100644
--- a/src/com/matejdro/bukkit/monsterhunt/InputOutput.java
+++ b/src/com/matejdro/bukkit/monsterhunt/InputOutput.java
@@ -1,346 +1,346 @@
package com.matejdro.bukkit.monsterhunt;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.logging.Level;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.util.config.Configuration;
public class InputOutput {
private static Connection connection;
public static synchronized Connection getConnection() {
try {
if (connection == null || connection.isClosed()) {
connection = createConnection();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
private static Connection createConnection() {
try {
if (Settings.globals.getBoolean("Database.UseMySQL", false)) {
Class.forName("com.mysql.jdbc.Driver");
Connection ret = DriverManager.getConnection(Settings.globals.getString("Database.MySQLConn", ""), Settings.globals.getString("Database.MySQLUsername", ""), Settings.globals.getString("Database.MySQLPassword", ""));
ret.setAutoCommit(false);
return ret;
} else {
Class.forName("org.sqlite.JDBC");
Connection ret = DriverManager.getConnection("jdbc:sqlite:plugins" + File.separator + "MonsterHunt" + File.separator + "MonsterHunt.sqlite");
ret.setAutoCommit(false);
return ret;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public static Integer getHighScore(String player)
{
Connection conn = getConnection();
PreparedStatement ps = null;
ResultSet set = null;
Integer score = null;
try {
ps = conn.prepareStatement("SELECT * FROM monsterhunt_highscores WHERE name = ? LIMIT 1");
ps.setString(1, player);
set = ps.executeQuery();
if (set.next())
score = set.getInt("highscore");
set.close();
ps.close();
conn.close();
} catch (SQLException e) {
MonsterHunt.log.log(Level.SEVERE,"[MonsterHunt] Error while retreiving high scores! - " + e.getMessage() );
// TODO Auto-generated catch block
e.printStackTrace();
}
return score;
}
public static Integer getHighScoreRank(String player)
{
Connection conn = getConnection();
PreparedStatement ps = null;
ResultSet set = null;
Boolean exist = false;
Integer counter = 0;
try {
ps = conn.prepareStatement("SELECT * FROM monsterhunt_highscores ORDER BY highscore DESC");
set = ps.executeQuery();
while (set.next())
{
counter++;
String name = set.getString("name");
if (name.equals(player))
{
exist = true;
break;
}
}
set.close();
ps.close();
conn.close();
} catch (SQLException e) {
MonsterHunt.log.log(Level.SEVERE,"[MonsterHunt] Error while retreiving high scores! - " + e.getMessage() );
// TODO Auto-generated catch block
e.printStackTrace();
}
if (exist)
return counter;
else
return null;
}
public static LinkedHashMap<String, Integer> getTopScores(int number)
{
Connection conn = getConnection();
PreparedStatement ps = null;
ResultSet set = null;
LinkedHashMap<String, Integer> map = new LinkedHashMap<String, Integer>();
try {
ps = conn.prepareStatement("SELECT * FROM monsterhunt_highscores ORDER BY highscore DESC LIMIT ?");
ps.setInt(1, number);
set = ps.executeQuery();
while (set.next())
{
String name = set.getString("name");
Integer score = set.getInt("highscore");
map.put(name, score);
}
set.close();
ps.close();
conn.close();
} catch (SQLException e) {
MonsterHunt.log.log(Level.SEVERE,"[MonsterHunt] Error while retreiving high scores! - " + e.getMessage() );
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}
public static void UpdateHighScore(String playername, int score)
{
try {
Connection conn = InputOutput.getConnection();
PreparedStatement ps = conn.prepareStatement("REPLACE INTO monsterhunt_highscores VALUES (?,?)");
ps.setString(1, playername);
ps.setInt(2, score);
ps.executeUpdate();
conn.commit();
ps.close();
conn.close();
} catch (SQLException e) {
MonsterHunt.log.log(Level.SEVERE,"[MonsterHunt] Error while inserting new high score into DB! - " + e.getMessage() );
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void LoadSettings()
{
if (!new File("plugins" + File.separator + "MonsterHunt").exists()) {
try {
(new File("plugins" + File.separator + "MonsterHunt")).mkdir();
} catch (Exception e) {
MonsterHunt.log.log(Level.SEVERE, "[MonsterHunt]: Unable to create plugins/MontsterHunt/ directory");
}
}
Settings.globals = new Configuration(new File("plugins" + File.separator + "MonsterHunt" + File.separator, "global.txt"));
LoadDefaults();
if (!new File("plugins" + File.separator + "MonsterHunt" + File.separator, "global.txt").exists())
{
for (Entry<String, Object> e : Settings.defaults.entrySet())
{
Settings.globals.setProperty(e.getKey(), e.getValue());
}
Settings.globals.save();
}
Settings.globals.load();
for (String n : Settings.globals.getString("EnabledWorlds").split(","))
{
MonsterHuntWorld mw = new MonsterHuntWorld(n);
Configuration config = new Configuration(new File("plugins" + File.separator + "MonsterHunt" + File.separator,n + ".yml"));
Settings settings = new Settings(config);
mw.settings = settings;
HuntWorldManager.worlds.put(n, mw);
}
String[] temp = Settings.globals.getString("HuntZone.FirstCorner", "0,0,0").split(",");
HuntZone.corner1 = new Location(null, Double.parseDouble(temp[0]), Double.parseDouble(temp[1]), Double.parseDouble(temp[2]));
temp = Settings.globals.getString("HuntZone.SecondCorner", "0,0,0").split(",");
HuntZone.corner2 = new Location(null, Double.parseDouble(temp[0]), Double.parseDouble(temp[1]), Double.parseDouble(temp[2]));
temp = Settings.globals.getString("HuntZone.TeleportLocation", "0,0,0").split(",");
World world = MonsterHunt.instance.getServer().getWorld(Settings.globals.getString("HuntZone.World", MonsterHunt.instance.getServer().getWorlds().get(0).getName()));
HuntZone.teleport = new Location(world, Double.parseDouble(temp[0]), Double.parseDouble(temp[1]), Double.parseDouble(temp[2]));
//Create zone world
MonsterHuntWorld mw = new MonsterHuntWorld(world.getName());
Configuration config = new Configuration(new File("plugins" + File.separator + "MonsterHunt" + File.separator + "zone.yml"));
Settings settings = new Settings(config);
mw.settings = settings;
HuntWorldManager.HuntZoneWorld = mw;
}
public static void LoadDefaults()
{
Settings.defaults.put("StartTime", 13000);
Settings.defaults.put("EndTime", 23600);
Settings.defaults.put("DeathPenalty", 30);
Settings.defaults.put("TellTime", true);
Settings.defaults.put("CountBows", true);
Settings.defaults.put("EnableSignup", true);
Settings.defaults.put("EnableHighScores", true);
Settings.defaults.put("MinimumPointsPlace1", 1);
Settings.defaults.put("MinimumPointsPlace2", 1);
Settings.defaults.put("MinimumPointsPlace3", 1);
Settings.defaults.put("MinimumPlayers", 2);
Settings.defaults.put("StartChance", 100);
Settings.defaults.put("SkipDays", 0);
Settings.defaults.put("SignUpPeriodTime", 5);
Settings.defaults.put("AllowSignUpAfterHuntStart", false);
Settings.defaults.put("EnabledWorlds", MonsterHunt.instance.getServer().getWorlds().get(0).getName());
Settings.defaults.put("OnlyCountMobsSpawnedOutside", false);
Settings.defaults.put("OnlyCountMobsSpawnedOutsideHeightLimit", 0);
Settings.defaults.put("SkipToIfFailsToStart", -1);
Settings.defaults.put("AnnounceLead", true);
Settings.defaults.put("SelectionTool", 268);
Settings.defaults.put("HuntZoneMode", false);
Settings.defaults.put("Rewards.EnableReward", false);
Settings.defaults.put("Rewards.EnableRewardEveryonePermission", false);
Settings.defaults.put("Rewards.RewardEveryone", false);
Settings.defaults.put("Rewards.NumberOfWinners", 3);
Settings.defaults.put("Rewards.RewardParametersPlace1", "3 3");
Settings.defaults.put("Rewards.RewardParametersPlace2", "3 2");
Settings.defaults.put("Rewards.RewardParametersPlace3", "3 1");
Settings.defaults.put("Rewards.RewardParametersEveryone", "3 1-1");
for (String i : new String[]{"Zombie", "Skeleton", "Creeper", "Spider", "Ghast", "Slime", "ZombiePigman", "Giant", "TamedWolf", "WildWolf", "ElectrifiedCreeper", "Player"})
{
Settings.defaults.put("Value." + i + ".General", 10);
Settings.defaults.put("Value." + i + ".Wolf", 7);
Settings.defaults.put("Value." + i + ".Arrow", 4);
Settings.defaults.put("Value." + i + ".283", 20);
}
Settings.defaults.put("Database.UseMySQL", false);
Settings.defaults.put("Database.MySQLConn", "jdbc:mysql://localhost:3306/minecraft");
Settings.defaults.put("Database.MySQLUsername", "root");
Settings.defaults.put("Database.MySQLPassword", "password");
Settings.defaults.put("Debug", false);
Settings.defaults.put("Messages.StartMessage", "&2Monster Hunt have started in world <World>! Go kill those damn mobs!");
Settings.defaults.put("Messages.FinishMessageWinners", "Sun is rising, so monster Hunt is finished in world <World>! Winners of the today's match are: [NEWLINE] 1st place: <NamesPlace1> (<PointsPlace1> points) [NEWLINE] 2nd place: <NamesPlace2> (<PointsPlace2> points) [NEWLINE] 3rd place: <NamesPlace3> (<PointsPlace3> points)" );
Settings.defaults.put("Messages.KillMessageGeneral", "You have got <MobValue> points from killing that <MobName>. You have <Points> points so far. Keep it up!");
Settings.defaults.put("Messages.KillMessageWolf", "You have got <MobValue> points because your wolf killed <MobName>. You have <Points> points so far. Keep it up!");
Settings.defaults.put("Messages.KillMessageArrow", "You have got only <MobValue> points because you used bow when killing <MobName>. You have <Points> points so far. Keep it up!");
Settings.defaults.put("Messages.RewardMessage", "Congratulations! You have received <Items>");
Settings.defaults.put("Messages.DeathMessage","You have died, so your Monster Hunt score is reduced by 30%. Be more careful next time!");
Settings.defaults.put("Messages.NoBowMessage", "Your kill is not counted. Stop camping with your bow and get into the fight!");
Settings.defaults.put("Messages.SignupBeforeHuntMessage", "You have signed up for the next hunt in world <World>!");
Settings.defaults.put("Messages.SignupAtHuntMessage", "You have signed up for the hunt in in world <World>. Now hurry and kill some monsters!");
Settings.defaults.put("Messages.HighScoreMessage","You have reached a new high score: <Points> points!");
Settings.defaults.put("Messages.FinishMessageNotEnoughPoints", "Sun is rising, so monster Hunt is finished in world <World>! Unfortunately nobody killed enough monsters, so there is no winner.");
Settings.defaults.put("Messages.FinishMessageNotEnoughPlayers", "Sun is rising, so monster Hunt is finished in world <World>! Unfortunately there were not enough players participating, so there is no winner.");
Settings.defaults.put("Messages.MessageSignUpPeriod", "Sharpen your swords, strengthen your armor and type /hunt, because Monster Hunt will begin in several mintues in world <World>!");
Settings.defaults.put("Messages.MessageTooLateSignUp", "Sorry, you are too late to sign up. More luck next time!");
Settings.defaults.put("Messages.MessageAlreadySignedUp", "You are already signed up!");
Settings.defaults.put("Messages.MessageStartNotEnoughPlayers", "Monster Hunt was about to start, but unfortunately there were not enough players signed up. ");
Settings.defaults.put("Messages.KillMobSpawnedInsideMessage", "Your kill was not counted. Stop grinding in caves and go outside!");
Settings.defaults.put("Messages.MessageHuntStatusNotActive", "Hunt is currently not active anywhere");
Settings.defaults.put("Messages.MessageHuntStatusHuntActive", "Hunt is active in <Worlds>");
Settings.defaults.put("Messages.MessageHuntStatusLastScore", "Your last score in this world was <Points> points");
Settings.defaults.put("Messages.MessageHuntStatusNotInvolvedLastHunt", "You were not involved in last hunt in this world");
Settings.defaults.put("Messages.MessageHuntStatusNoKills", "You haven't killed any mob in this world's hunt yet. Hurry up!");
Settings.defaults.put("Messages.MessageHuntStatusCurrentScore", "Your current score in this world's hunt is <Points> points! Keep it up!");
Settings.defaults.put("Messages.MessageHuntStatusTimeReamining", "Keep up the killing! You have only <Timeleft>% of the night left in this world!");
Settings.defaults.put("Messages.MessageLead", "<Player> has just taken over lead with <Points> points!");
Settings.defaults.put("Messages.MessageHuntTeleNoHunt", "You cannot teleport to hunt zone when there is no hunt!");
Settings.defaults.put("Messages.MessageHuntTeleNotSignedUp", "You cannot teleport to hunt zone if you are not signed up to the hunt!");
Settings.defaults.put("HuntZone.FirstCorner", "0,0,0");
Settings.defaults.put("HuntZone.SecondCorner", "0,0,0");
Settings.defaults.put("HuntZone.TeleportLocation", "0,0,0");
- Settings.defaults.put("HuntZone.World", "world");
+ Settings.defaults.put("HuntZone.World", MonsterHunt.instance.getServer().getWorlds().get(0).getName());
}
public static void saveZone()
{
Settings.globals.setProperty("HuntZone.FirstCorner", String.valueOf(HuntZone.corner1.getBlockX()) + "," + String.valueOf(HuntZone.corner1.getBlockY()) + "," + String.valueOf(HuntZone.corner1.getBlockZ()));
Settings.globals.setProperty("HuntZone.SecondCorner", String.valueOf(HuntZone.corner2.getBlockX()) + "," + String.valueOf(HuntZone.corner2.getBlockY()) + "," + String.valueOf(HuntZone.corner2.getBlockZ()));
Settings.globals.setProperty("HuntZone.TeleportLocation", String.valueOf(HuntZone.teleport.getX()) + "," + String.valueOf(HuntZone.teleport.getY()) + "," + String.valueOf(HuntZone.teleport.getZ()));
Settings.globals.setProperty("HuntZone.World", HuntZone.teleport.getWorld().getName());
Settings.globals.save();
}
public static void PrepareDB()
{
Connection conn = null;
Statement st = null;
try {
conn = InputOutput.getConnection();
st = conn.createStatement();
if (Settings.globals.getBoolean("UseMySql", false))
{
st.executeUpdate("CREATE TABLE IF NOT EXISTS `monsterhunt_highscores` ( `name` varchar(250) NOT NULL DEFAULT '', `highscore` integer DEFAULT NULL, PRIMARY KEY (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
}
else
{
st.executeUpdate("CREATE TABLE IF NOT EXISTS \"monsterhunt_highscores\" (\"name\" VARCHAR PRIMARY KEY NOT NULL , \"highscore\" INTEGER)");
}
conn.commit();
} catch (SQLException e) {
MonsterHunt.log.log(Level.SEVERE, "[MonsterHunt]: Error while creating tables! - " + e.getMessage());
}
}
}
| true | true | public static void LoadDefaults()
{
Settings.defaults.put("StartTime", 13000);
Settings.defaults.put("EndTime", 23600);
Settings.defaults.put("DeathPenalty", 30);
Settings.defaults.put("TellTime", true);
Settings.defaults.put("CountBows", true);
Settings.defaults.put("EnableSignup", true);
Settings.defaults.put("EnableHighScores", true);
Settings.defaults.put("MinimumPointsPlace1", 1);
Settings.defaults.put("MinimumPointsPlace2", 1);
Settings.defaults.put("MinimumPointsPlace3", 1);
Settings.defaults.put("MinimumPlayers", 2);
Settings.defaults.put("StartChance", 100);
Settings.defaults.put("SkipDays", 0);
Settings.defaults.put("SignUpPeriodTime", 5);
Settings.defaults.put("AllowSignUpAfterHuntStart", false);
Settings.defaults.put("EnabledWorlds", MonsterHunt.instance.getServer().getWorlds().get(0).getName());
Settings.defaults.put("OnlyCountMobsSpawnedOutside", false);
Settings.defaults.put("OnlyCountMobsSpawnedOutsideHeightLimit", 0);
Settings.defaults.put("SkipToIfFailsToStart", -1);
Settings.defaults.put("AnnounceLead", true);
Settings.defaults.put("SelectionTool", 268);
Settings.defaults.put("HuntZoneMode", false);
Settings.defaults.put("Rewards.EnableReward", false);
Settings.defaults.put("Rewards.EnableRewardEveryonePermission", false);
Settings.defaults.put("Rewards.RewardEveryone", false);
Settings.defaults.put("Rewards.NumberOfWinners", 3);
Settings.defaults.put("Rewards.RewardParametersPlace1", "3 3");
Settings.defaults.put("Rewards.RewardParametersPlace2", "3 2");
Settings.defaults.put("Rewards.RewardParametersPlace3", "3 1");
Settings.defaults.put("Rewards.RewardParametersEveryone", "3 1-1");
for (String i : new String[]{"Zombie", "Skeleton", "Creeper", "Spider", "Ghast", "Slime", "ZombiePigman", "Giant", "TamedWolf", "WildWolf", "ElectrifiedCreeper", "Player"})
{
Settings.defaults.put("Value." + i + ".General", 10);
Settings.defaults.put("Value." + i + ".Wolf", 7);
Settings.defaults.put("Value." + i + ".Arrow", 4);
Settings.defaults.put("Value." + i + ".283", 20);
}
Settings.defaults.put("Database.UseMySQL", false);
Settings.defaults.put("Database.MySQLConn", "jdbc:mysql://localhost:3306/minecraft");
Settings.defaults.put("Database.MySQLUsername", "root");
Settings.defaults.put("Database.MySQLPassword", "password");
Settings.defaults.put("Debug", false);
Settings.defaults.put("Messages.StartMessage", "&2Monster Hunt have started in world <World>! Go kill those damn mobs!");
Settings.defaults.put("Messages.FinishMessageWinners", "Sun is rising, so monster Hunt is finished in world <World>! Winners of the today's match are: [NEWLINE] 1st place: <NamesPlace1> (<PointsPlace1> points) [NEWLINE] 2nd place: <NamesPlace2> (<PointsPlace2> points) [NEWLINE] 3rd place: <NamesPlace3> (<PointsPlace3> points)" );
Settings.defaults.put("Messages.KillMessageGeneral", "You have got <MobValue> points from killing that <MobName>. You have <Points> points so far. Keep it up!");
Settings.defaults.put("Messages.KillMessageWolf", "You have got <MobValue> points because your wolf killed <MobName>. You have <Points> points so far. Keep it up!");
Settings.defaults.put("Messages.KillMessageArrow", "You have got only <MobValue> points because you used bow when killing <MobName>. You have <Points> points so far. Keep it up!");
Settings.defaults.put("Messages.RewardMessage", "Congratulations! You have received <Items>");
Settings.defaults.put("Messages.DeathMessage","You have died, so your Monster Hunt score is reduced by 30%. Be more careful next time!");
Settings.defaults.put("Messages.NoBowMessage", "Your kill is not counted. Stop camping with your bow and get into the fight!");
Settings.defaults.put("Messages.SignupBeforeHuntMessage", "You have signed up for the next hunt in world <World>!");
Settings.defaults.put("Messages.SignupAtHuntMessage", "You have signed up for the hunt in in world <World>. Now hurry and kill some monsters!");
Settings.defaults.put("Messages.HighScoreMessage","You have reached a new high score: <Points> points!");
Settings.defaults.put("Messages.FinishMessageNotEnoughPoints", "Sun is rising, so monster Hunt is finished in world <World>! Unfortunately nobody killed enough monsters, so there is no winner.");
Settings.defaults.put("Messages.FinishMessageNotEnoughPlayers", "Sun is rising, so monster Hunt is finished in world <World>! Unfortunately there were not enough players participating, so there is no winner.");
Settings.defaults.put("Messages.MessageSignUpPeriod", "Sharpen your swords, strengthen your armor and type /hunt, because Monster Hunt will begin in several mintues in world <World>!");
Settings.defaults.put("Messages.MessageTooLateSignUp", "Sorry, you are too late to sign up. More luck next time!");
Settings.defaults.put("Messages.MessageAlreadySignedUp", "You are already signed up!");
Settings.defaults.put("Messages.MessageStartNotEnoughPlayers", "Monster Hunt was about to start, but unfortunately there were not enough players signed up. ");
Settings.defaults.put("Messages.KillMobSpawnedInsideMessage", "Your kill was not counted. Stop grinding in caves and go outside!");
Settings.defaults.put("Messages.MessageHuntStatusNotActive", "Hunt is currently not active anywhere");
Settings.defaults.put("Messages.MessageHuntStatusHuntActive", "Hunt is active in <Worlds>");
Settings.defaults.put("Messages.MessageHuntStatusLastScore", "Your last score in this world was <Points> points");
Settings.defaults.put("Messages.MessageHuntStatusNotInvolvedLastHunt", "You were not involved in last hunt in this world");
Settings.defaults.put("Messages.MessageHuntStatusNoKills", "You haven't killed any mob in this world's hunt yet. Hurry up!");
Settings.defaults.put("Messages.MessageHuntStatusCurrentScore", "Your current score in this world's hunt is <Points> points! Keep it up!");
Settings.defaults.put("Messages.MessageHuntStatusTimeReamining", "Keep up the killing! You have only <Timeleft>% of the night left in this world!");
Settings.defaults.put("Messages.MessageLead", "<Player> has just taken over lead with <Points> points!");
Settings.defaults.put("Messages.MessageHuntTeleNoHunt", "You cannot teleport to hunt zone when there is no hunt!");
Settings.defaults.put("Messages.MessageHuntTeleNotSignedUp", "You cannot teleport to hunt zone if you are not signed up to the hunt!");
Settings.defaults.put("HuntZone.FirstCorner", "0,0,0");
Settings.defaults.put("HuntZone.SecondCorner", "0,0,0");
Settings.defaults.put("HuntZone.TeleportLocation", "0,0,0");
Settings.defaults.put("HuntZone.World", "world");
}
| public static void LoadDefaults()
{
Settings.defaults.put("StartTime", 13000);
Settings.defaults.put("EndTime", 23600);
Settings.defaults.put("DeathPenalty", 30);
Settings.defaults.put("TellTime", true);
Settings.defaults.put("CountBows", true);
Settings.defaults.put("EnableSignup", true);
Settings.defaults.put("EnableHighScores", true);
Settings.defaults.put("MinimumPointsPlace1", 1);
Settings.defaults.put("MinimumPointsPlace2", 1);
Settings.defaults.put("MinimumPointsPlace3", 1);
Settings.defaults.put("MinimumPlayers", 2);
Settings.defaults.put("StartChance", 100);
Settings.defaults.put("SkipDays", 0);
Settings.defaults.put("SignUpPeriodTime", 5);
Settings.defaults.put("AllowSignUpAfterHuntStart", false);
Settings.defaults.put("EnabledWorlds", MonsterHunt.instance.getServer().getWorlds().get(0).getName());
Settings.defaults.put("OnlyCountMobsSpawnedOutside", false);
Settings.defaults.put("OnlyCountMobsSpawnedOutsideHeightLimit", 0);
Settings.defaults.put("SkipToIfFailsToStart", -1);
Settings.defaults.put("AnnounceLead", true);
Settings.defaults.put("SelectionTool", 268);
Settings.defaults.put("HuntZoneMode", false);
Settings.defaults.put("Rewards.EnableReward", false);
Settings.defaults.put("Rewards.EnableRewardEveryonePermission", false);
Settings.defaults.put("Rewards.RewardEveryone", false);
Settings.defaults.put("Rewards.NumberOfWinners", 3);
Settings.defaults.put("Rewards.RewardParametersPlace1", "3 3");
Settings.defaults.put("Rewards.RewardParametersPlace2", "3 2");
Settings.defaults.put("Rewards.RewardParametersPlace3", "3 1");
Settings.defaults.put("Rewards.RewardParametersEveryone", "3 1-1");
for (String i : new String[]{"Zombie", "Skeleton", "Creeper", "Spider", "Ghast", "Slime", "ZombiePigman", "Giant", "TamedWolf", "WildWolf", "ElectrifiedCreeper", "Player"})
{
Settings.defaults.put("Value." + i + ".General", 10);
Settings.defaults.put("Value." + i + ".Wolf", 7);
Settings.defaults.put("Value." + i + ".Arrow", 4);
Settings.defaults.put("Value." + i + ".283", 20);
}
Settings.defaults.put("Database.UseMySQL", false);
Settings.defaults.put("Database.MySQLConn", "jdbc:mysql://localhost:3306/minecraft");
Settings.defaults.put("Database.MySQLUsername", "root");
Settings.defaults.put("Database.MySQLPassword", "password");
Settings.defaults.put("Debug", false);
Settings.defaults.put("Messages.StartMessage", "&2Monster Hunt have started in world <World>! Go kill those damn mobs!");
Settings.defaults.put("Messages.FinishMessageWinners", "Sun is rising, so monster Hunt is finished in world <World>! Winners of the today's match are: [NEWLINE] 1st place: <NamesPlace1> (<PointsPlace1> points) [NEWLINE] 2nd place: <NamesPlace2> (<PointsPlace2> points) [NEWLINE] 3rd place: <NamesPlace3> (<PointsPlace3> points)" );
Settings.defaults.put("Messages.KillMessageGeneral", "You have got <MobValue> points from killing that <MobName>. You have <Points> points so far. Keep it up!");
Settings.defaults.put("Messages.KillMessageWolf", "You have got <MobValue> points because your wolf killed <MobName>. You have <Points> points so far. Keep it up!");
Settings.defaults.put("Messages.KillMessageArrow", "You have got only <MobValue> points because you used bow when killing <MobName>. You have <Points> points so far. Keep it up!");
Settings.defaults.put("Messages.RewardMessage", "Congratulations! You have received <Items>");
Settings.defaults.put("Messages.DeathMessage","You have died, so your Monster Hunt score is reduced by 30%. Be more careful next time!");
Settings.defaults.put("Messages.NoBowMessage", "Your kill is not counted. Stop camping with your bow and get into the fight!");
Settings.defaults.put("Messages.SignupBeforeHuntMessage", "You have signed up for the next hunt in world <World>!");
Settings.defaults.put("Messages.SignupAtHuntMessage", "You have signed up for the hunt in in world <World>. Now hurry and kill some monsters!");
Settings.defaults.put("Messages.HighScoreMessage","You have reached a new high score: <Points> points!");
Settings.defaults.put("Messages.FinishMessageNotEnoughPoints", "Sun is rising, so monster Hunt is finished in world <World>! Unfortunately nobody killed enough monsters, so there is no winner.");
Settings.defaults.put("Messages.FinishMessageNotEnoughPlayers", "Sun is rising, so monster Hunt is finished in world <World>! Unfortunately there were not enough players participating, so there is no winner.");
Settings.defaults.put("Messages.MessageSignUpPeriod", "Sharpen your swords, strengthen your armor and type /hunt, because Monster Hunt will begin in several mintues in world <World>!");
Settings.defaults.put("Messages.MessageTooLateSignUp", "Sorry, you are too late to sign up. More luck next time!");
Settings.defaults.put("Messages.MessageAlreadySignedUp", "You are already signed up!");
Settings.defaults.put("Messages.MessageStartNotEnoughPlayers", "Monster Hunt was about to start, but unfortunately there were not enough players signed up. ");
Settings.defaults.put("Messages.KillMobSpawnedInsideMessage", "Your kill was not counted. Stop grinding in caves and go outside!");
Settings.defaults.put("Messages.MessageHuntStatusNotActive", "Hunt is currently not active anywhere");
Settings.defaults.put("Messages.MessageHuntStatusHuntActive", "Hunt is active in <Worlds>");
Settings.defaults.put("Messages.MessageHuntStatusLastScore", "Your last score in this world was <Points> points");
Settings.defaults.put("Messages.MessageHuntStatusNotInvolvedLastHunt", "You were not involved in last hunt in this world");
Settings.defaults.put("Messages.MessageHuntStatusNoKills", "You haven't killed any mob in this world's hunt yet. Hurry up!");
Settings.defaults.put("Messages.MessageHuntStatusCurrentScore", "Your current score in this world's hunt is <Points> points! Keep it up!");
Settings.defaults.put("Messages.MessageHuntStatusTimeReamining", "Keep up the killing! You have only <Timeleft>% of the night left in this world!");
Settings.defaults.put("Messages.MessageLead", "<Player> has just taken over lead with <Points> points!");
Settings.defaults.put("Messages.MessageHuntTeleNoHunt", "You cannot teleport to hunt zone when there is no hunt!");
Settings.defaults.put("Messages.MessageHuntTeleNotSignedUp", "You cannot teleport to hunt zone if you are not signed up to the hunt!");
Settings.defaults.put("HuntZone.FirstCorner", "0,0,0");
Settings.defaults.put("HuntZone.SecondCorner", "0,0,0");
Settings.defaults.put("HuntZone.TeleportLocation", "0,0,0");
Settings.defaults.put("HuntZone.World", MonsterHunt.instance.getServer().getWorlds().get(0).getName());
}
|
diff --git a/src/main/java/org/apache/ibatis/executor/CachingExecutor.java b/src/main/java/org/apache/ibatis/executor/CachingExecutor.java
index 9c01562338..76df861387 100644
--- a/src/main/java/org/apache/ibatis/executor/CachingExecutor.java
+++ b/src/main/java/org/apache/ibatis/executor/CachingExecutor.java
@@ -1,166 +1,165 @@
/*
* Copyright 2009-2012 The MyBatis Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.executor;
import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.cache.TransactionalCacheManager;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.mapping.StatementType;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.transaction.Transaction;
import java.sql.SQLException;
import java.util.List;
public class CachingExecutor implements Executor {
private Executor delegate;
private boolean autoCommit; // issue #573. No need to call commit() on autoCommit sessions
private TransactionalCacheManager tcm = new TransactionalCacheManager();
private boolean dirty;
public CachingExecutor(Executor delegate) {
this(delegate, false);
}
public CachingExecutor(Executor delegate, boolean autoCommit) {
this.delegate = delegate;
this.autoCommit = autoCommit;
}
public Transaction getTransaction() {
return delegate.getTransaction();
}
public void close(boolean forceRollback) {
try {
//issue #499. Unresolved session handling
//issue #573. Autocommit sessions should commit
if (dirty && !autoCommit) {
tcm.rollback();
} else {
tcm.commit();
}
} finally {
delegate.close(forceRollback);
}
}
public boolean isClosed() {
return delegate.isClosed();
}
public int update(MappedStatement ms, Object parameterObject) throws SQLException {
flushCacheIfRequired(ms);
return delegate.update(ms, parameterObject);
}
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
BoundSql boundSql = ms.getBoundSql(parameterObject);
CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
Cache cache = ms.getCache();
if (cache != null) {
flushCacheIfRequired(ms);
if (ms.isUseCache() && resultHandler == null) {
ensureNoOutParams(ms, key, parameterObject, boundSql);
- cache.getReadWriteLock().readLock().lock();
- try {
- @SuppressWarnings("unchecked")
- List<E> cachedList = dirty ? null : (List<E>) cache.getObject(key);
- if (cachedList != null) {
- return cachedList;
- } else {
- List<E> list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
- tcm.putObject(cache, key, list);
- return list;
+ if (!dirty) {
+ cache.getReadWriteLock().readLock().lock();
+ try {
+ @SuppressWarnings("unchecked")
+ List<E> cachedList = (List<E>) cache.getObject(key);
+ if (cachedList != null) return cachedList;
+ } finally {
+ cache.getReadWriteLock().readLock().unlock();
}
- } finally {
- cache.getReadWriteLock().readLock().unlock();
}
+ List<E> list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
+ tcm.putObject(cache, key, list); // issue #578. Query must be not synchronized to prevent deadlocks
+ return list;
}
}
return delegate.<E>query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
public List<BatchResult> flushStatements() throws SQLException {
return delegate.flushStatements();
}
public void commit(boolean required) throws SQLException {
delegate.commit(required);
tcm.commit();
dirty = false;
}
public void rollback(boolean required) throws SQLException {
try {
delegate.rollback(required);
dirty = false;
} finally {
if (required) {
tcm.rollback();
}
}
}
private void ensureNoOutParams(MappedStatement ms, CacheKey key, Object parameter, BoundSql boundSql) {
if (ms.getStatementType() == StatementType.CALLABLE) {
for (ParameterMapping parameterMapping : ms.getBoundSql(parameter).getParameterMappings()) {
if (parameterMapping.getMode() != ParameterMode.IN) {
throw new ExecutorException("Caching stored procedures with OUT params is not supported. Please configure useCache=false in " + ms.getId() + " statement.");
}
}
}
}
public CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql) {
return delegate.createCacheKey(ms, parameterObject, rowBounds, boundSql);
}
public boolean isCached(MappedStatement ms, CacheKey key) {
throw new UnsupportedOperationException("The CachingExecutor should not be used by result loaders and thus isCached() should never be called.");
}
public void deferLoad(MappedStatement ms, MetaObject resultObject, String property, CacheKey key) {
throw new UnsupportedOperationException("The CachingExecutor should not be used by result loaders and thus deferLoad() should never be called.");
}
public void clearLocalCache() {
delegate.clearLocalCache();
}
private void flushCacheIfRequired(MappedStatement ms) {
Cache cache = ms.getCache();
if (cache != null) {
if (ms.isFlushCacheRequired()) {
dirty = true; // issue #524. Disable using cached data for this session
tcm.clear(cache);
}
}
}
}
| false | true | public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
Cache cache = ms.getCache();
if (cache != null) {
flushCacheIfRequired(ms);
if (ms.isUseCache() && resultHandler == null) {
ensureNoOutParams(ms, key, parameterObject, boundSql);
cache.getReadWriteLock().readLock().lock();
try {
@SuppressWarnings("unchecked")
List<E> cachedList = dirty ? null : (List<E>) cache.getObject(key);
if (cachedList != null) {
return cachedList;
} else {
List<E> list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
tcm.putObject(cache, key, list);
return list;
}
} finally {
cache.getReadWriteLock().readLock().unlock();
}
}
}
return delegate.<E>query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
| public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
Cache cache = ms.getCache();
if (cache != null) {
flushCacheIfRequired(ms);
if (ms.isUseCache() && resultHandler == null) {
ensureNoOutParams(ms, key, parameterObject, boundSql);
if (!dirty) {
cache.getReadWriteLock().readLock().lock();
try {
@SuppressWarnings("unchecked")
List<E> cachedList = (List<E>) cache.getObject(key);
if (cachedList != null) return cachedList;
} finally {
cache.getReadWriteLock().readLock().unlock();
}
}
List<E> list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
tcm.putObject(cache, key, list); // issue #578. Query must be not synchronized to prevent deadlocks
return list;
}
}
return delegate.<E>query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
|
diff --git a/java/tools/parser/src/tools/parser/Var.java b/java/tools/parser/src/tools/parser/Var.java
index 6118165e..91f1ce10 100644
--- a/java/tools/parser/src/tools/parser/Var.java
+++ b/java/tools/parser/src/tools/parser/Var.java
@@ -1,92 +1,92 @@
package tools.parser;
/*
* This source code is freely distributable under the GNU public licence. I
* would be delighted to hear if have made use of this code. If you make money
* with this code, please give me some! If you find this code useful, or have
* any queries, please feel free to contact me: [email protected] /
* [email protected] Paul "Joey" Clark, hacking for humanity, Feb 99
* www.cs.bris.ac.uk/~pclark / www.changetheworld.org.uk
*/
import java.lang.*;
import java.util.*;
import java.awt.TextArea; // debug
import java.awt.Frame; // debug
import java.awt.FlowLayout; // debug
import java.awt.event.ActionListener; // debug
import java.awt.event.ActionEvent; // debug
import java.awt.Button; // debug
import org.neuralyte.Logger;
import jlib.Files;
import jlib.JString;
import jlib.strings.*;
import tools.parser.*;
public class Var implements Type {
String name;
String deny; // characters which are not allowed
String accept;
Var(String n) {
name = n;
deny = "";
}
Var(String n, String d) {
name = n;
deny = d;
}
Var(String n, String _, String a) {
name = n;
accept = a;
}
public Match match(SomeString s) {
int most = s.length();
if (accept != null) {
for (int i=0;i<s.length();i++) {
int found = accept.indexOf(s.charAt(i));
if (found == -1) {
most = i;
break;
}
}
}
else if (deny != null) {
for (int i = 0; i < deny.length(); i++) {
int j = s.indexOf(deny.charAt(i));
// System.out.println("Found '"+Atom.strip(""+deny.charAt(i))+"' at "+j+" of "+Atom.strip(""+s));
if (j >= 0 && j < most) most = j;
}
}
if (most == 0) {
// Failure!
if (Parser.Debugging) {
// Logger.log("Failed to match var "+name+" with accept="+accept+" and deny="+deny);
- // if (accept != null && deny == null) {
- return null;
- // }
+ }
+ if (accept != null && deny == null) {
+ return null;
}
}
return new Match(this, s.subString(0, most), s.subString(most));
}
public String toString() {
return "<" + name + ">";
}
public boolean replacementfor(Type o) {
if (o instanceof Var) {
Var v = (Var) o;
if (name.equals(v.name)) return true;
}
return false;
}
}
| true | true | public Match match(SomeString s) {
int most = s.length();
if (accept != null) {
for (int i=0;i<s.length();i++) {
int found = accept.indexOf(s.charAt(i));
if (found == -1) {
most = i;
break;
}
}
}
else if (deny != null) {
for (int i = 0; i < deny.length(); i++) {
int j = s.indexOf(deny.charAt(i));
// System.out.println("Found '"+Atom.strip(""+deny.charAt(i))+"' at "+j+" of "+Atom.strip(""+s));
if (j >= 0 && j < most) most = j;
}
}
if (most == 0) {
// Failure!
if (Parser.Debugging) {
// Logger.log("Failed to match var "+name+" with accept="+accept+" and deny="+deny);
// if (accept != null && deny == null) {
return null;
// }
}
}
return new Match(this, s.subString(0, most), s.subString(most));
}
| public Match match(SomeString s) {
int most = s.length();
if (accept != null) {
for (int i=0;i<s.length();i++) {
int found = accept.indexOf(s.charAt(i));
if (found == -1) {
most = i;
break;
}
}
}
else if (deny != null) {
for (int i = 0; i < deny.length(); i++) {
int j = s.indexOf(deny.charAt(i));
// System.out.println("Found '"+Atom.strip(""+deny.charAt(i))+"' at "+j+" of "+Atom.strip(""+s));
if (j >= 0 && j < most) most = j;
}
}
if (most == 0) {
// Failure!
if (Parser.Debugging) {
// Logger.log("Failed to match var "+name+" with accept="+accept+" and deny="+deny);
}
if (accept != null && deny == null) {
return null;
}
}
return new Match(this, s.subString(0, most), s.subString(most));
}
|
diff --git a/java/JavaExample.java b/java/JavaExample.java
index 2b377f6..5bd3b66 100644
--- a/java/JavaExample.java
+++ b/java/JavaExample.java
@@ -1,39 +1,40 @@
import java.io.*;
import java.net.*;
public class JavaExample {
public static void main(String[] args) throws Exception{
String document = "<html><body>This is a DocRaptor Example</body></html>";
String apikey = "YOUR_API_KEY_HERE";
- String data = "doc[document_content]=" + document;
+ String encoded_document = URLEncoder.encode(document, "UTF8");
+ String data = "doc[document_content]=" +encoded_document;
data += "&doc[name]=java_sample.pdf";
data += "&doc[document_type]=pdf";
data += "&doc[test]=true";
byte[] encodedData = data.getBytes("UTF8");
String url = "https://docraptor.com/docs?user_credentials=" + apikey;
String agent = "Mozilla/4.0";
String type = "application/x-www-form-urlencoded";
HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
conn.setDoOutput(true); // send as a POST
conn.setRequestProperty("User-Agent", agent);
conn.setRequestProperty("Content-Type", type);
conn.setRequestProperty("Content-Length", Integer.toString(encodedData.length));
OutputStream os = conn.getOutputStream();
os.write(encodedData);
os.flush();
InputStream responseStream = conn.getInputStream();
OutputStream outputStream = new FileOutputStream(new File("java_sample.pdf"));
byte[] buffer = new byte[1024];
int len;
while((len = responseStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
responseStream.close();
outputStream.close();
}
}
| true | true | public static void main(String[] args) throws Exception{
String document = "<html><body>This is a DocRaptor Example</body></html>";
String apikey = "YOUR_API_KEY_HERE";
String data = "doc[document_content]=" + document;
data += "&doc[name]=java_sample.pdf";
data += "&doc[document_type]=pdf";
data += "&doc[test]=true";
byte[] encodedData = data.getBytes("UTF8");
String url = "https://docraptor.com/docs?user_credentials=" + apikey;
String agent = "Mozilla/4.0";
String type = "application/x-www-form-urlencoded";
HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
conn.setDoOutput(true); // send as a POST
conn.setRequestProperty("User-Agent", agent);
conn.setRequestProperty("Content-Type", type);
conn.setRequestProperty("Content-Length", Integer.toString(encodedData.length));
OutputStream os = conn.getOutputStream();
os.write(encodedData);
os.flush();
InputStream responseStream = conn.getInputStream();
OutputStream outputStream = new FileOutputStream(new File("java_sample.pdf"));
byte[] buffer = new byte[1024];
int len;
while((len = responseStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
responseStream.close();
outputStream.close();
}
| public static void main(String[] args) throws Exception{
String document = "<html><body>This is a DocRaptor Example</body></html>";
String apikey = "YOUR_API_KEY_HERE";
String encoded_document = URLEncoder.encode(document, "UTF8");
String data = "doc[document_content]=" +encoded_document;
data += "&doc[name]=java_sample.pdf";
data += "&doc[document_type]=pdf";
data += "&doc[test]=true";
byte[] encodedData = data.getBytes("UTF8");
String url = "https://docraptor.com/docs?user_credentials=" + apikey;
String agent = "Mozilla/4.0";
String type = "application/x-www-form-urlencoded";
HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
conn.setDoOutput(true); // send as a POST
conn.setRequestProperty("User-Agent", agent);
conn.setRequestProperty("Content-Type", type);
conn.setRequestProperty("Content-Length", Integer.toString(encodedData.length));
OutputStream os = conn.getOutputStream();
os.write(encodedData);
os.flush();
InputStream responseStream = conn.getInputStream();
OutputStream outputStream = new FileOutputStream(new File("java_sample.pdf"));
byte[] buffer = new byte[1024];
int len;
while((len = responseStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
responseStream.close();
outputStream.close();
}
|
diff --git a/PVUgame/src/no/hist/gruppe5/pvu/book/BookScreen.java b/PVUgame/src/no/hist/gruppe5/pvu/book/BookScreen.java
index b74dd4b..15ff77a 100644
--- a/PVUgame/src/no/hist/gruppe5/pvu/book/BookScreen.java
+++ b/PVUgame/src/no/hist/gruppe5/pvu/book/BookScreen.java
@@ -1,98 +1,96 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package no.hist.gruppe5.pvu.book;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import no.hist.gruppe5.pvu.Assets;
import no.hist.gruppe5.pvu.GameScreen;
import no.hist.gruppe5.pvu.PVU;
import no.hist.gruppe5.pvu.XmlReader;
/**
*
* @author linnk
*/
public class BookScreen extends GameScreen {
public static Texture testTexture;
private Label leftPage;
private Label rightPage;
private Stage stage;
private int pageNumber;
private final String FILE_NAME = "data/test.xml";
public BookScreen(PVU game) {
super(game);
pageNumber = 1;
initScreen();
}
@Override
protected void draw(float delta) {
clearCamera(1, 1, 1, 1);
batch.begin();
//DRAW BOOK
batch.end();
leftPage.setText(getPageContent(0));
rightPage.setText(getPageContent(1));
stage.draw();
}
@Override
protected void update(float delta) {
if (Gdx.input.isKeyPressed(Input.Keys.ESCAPE)) {
game.setScreen(PVU.MAIN_SCREEN);
}if(Gdx.input.isKeyPressed(Input.Keys.SPACE)){
getNextPage();
}
}
@Override
protected void cleanUp() {
}
private String getPageContent(int rightPage) {
String name = "section"+(pageNumber+rightPage);
String content = XmlReader.loadText(name, FILE_NAME);
return content;
}
private void initScreen() {
testTexture = new Texture(Gdx.files.internal("data/book.png"));
testTexture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
- stage = new Stage(PVU.GAME_WIDTH, PVU.GAME_HEIGHT, true, batch);
+ stage = new Stage(PVU.GAME_WIDTH*2.5f, PVU.GAME_HEIGHT*2.5f, true);
Label.LabelStyle labelStyle = new Label.LabelStyle(Assets.primaryFont10px, Color.BLACK);
leftPage = new Label(getPageContent(0), labelStyle);
- leftPage.setFontScale(0.35f);
leftPage.setWidth(PVU.GAME_WIDTH);
- leftPage.setPosition(20, PVU.GAME_HEIGHT / 2);
+ leftPage.setPosition(35, stage.getHeight() / 2);
leftPage.setWrap(true);
rightPage = new Label(getPageContent(1), labelStyle);
rightPage.setPosition(110, 0);
- rightPage.setFontScale(0.35f);
rightPage.setWidth(PVU.GAME_WIDTH);
- rightPage.setPosition(PVU.GAME_WIDTH * 0.65f - 20, PVU.GAME_HEIGHT / 2);
+ rightPage.setPosition(stage.getWidth()/2+5, stage.getHeight() / 2);
rightPage.setWrap(true);
stage.addActor(leftPage);
stage.addActor(rightPage);
}
public void getNextPage(){
pageNumber+=2;
}
public void getPreviousPage(){
pageNumber-=2;
}
}
| false | true | private void initScreen() {
testTexture = new Texture(Gdx.files.internal("data/book.png"));
testTexture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
stage = new Stage(PVU.GAME_WIDTH, PVU.GAME_HEIGHT, true, batch);
Label.LabelStyle labelStyle = new Label.LabelStyle(Assets.primaryFont10px, Color.BLACK);
leftPage = new Label(getPageContent(0), labelStyle);
leftPage.setFontScale(0.35f);
leftPage.setWidth(PVU.GAME_WIDTH);
leftPage.setPosition(20, PVU.GAME_HEIGHT / 2);
leftPage.setWrap(true);
rightPage = new Label(getPageContent(1), labelStyle);
rightPage.setPosition(110, 0);
rightPage.setFontScale(0.35f);
rightPage.setWidth(PVU.GAME_WIDTH);
rightPage.setPosition(PVU.GAME_WIDTH * 0.65f - 20, PVU.GAME_HEIGHT / 2);
rightPage.setWrap(true);
stage.addActor(leftPage);
stage.addActor(rightPage);
}
| private void initScreen() {
testTexture = new Texture(Gdx.files.internal("data/book.png"));
testTexture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
stage = new Stage(PVU.GAME_WIDTH*2.5f, PVU.GAME_HEIGHT*2.5f, true);
Label.LabelStyle labelStyle = new Label.LabelStyle(Assets.primaryFont10px, Color.BLACK);
leftPage = new Label(getPageContent(0), labelStyle);
leftPage.setWidth(PVU.GAME_WIDTH);
leftPage.setPosition(35, stage.getHeight() / 2);
leftPage.setWrap(true);
rightPage = new Label(getPageContent(1), labelStyle);
rightPage.setPosition(110, 0);
rightPage.setWidth(PVU.GAME_WIDTH);
rightPage.setPosition(stage.getWidth()/2+5, stage.getHeight() / 2);
rightPage.setWrap(true);
stage.addActor(leftPage);
stage.addActor(rightPage);
}
|
diff --git a/api/src/main/java/org/openmrs/module/mirebalaisreports/cohort/definition/evaluator/LastDispositionBeforeExitCohortDefinitionEvaluator.java b/api/src/main/java/org/openmrs/module/mirebalaisreports/cohort/definition/evaluator/LastDispositionBeforeExitCohortDefinitionEvaluator.java
index a6b28f9..d2cbf51 100644
--- a/api/src/main/java/org/openmrs/module/mirebalaisreports/cohort/definition/evaluator/LastDispositionBeforeExitCohortDefinitionEvaluator.java
+++ b/api/src/main/java/org/openmrs/module/mirebalaisreports/cohort/definition/evaluator/LastDispositionBeforeExitCohortDefinitionEvaluator.java
@@ -1,123 +1,123 @@
/*
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.module.mirebalaisreports.cohort.definition.evaluator;
import org.hibernate.SQLQuery;
import org.hibernate.SessionFactory;
import org.openmrs.Cohort;
import org.openmrs.Concept;
import org.openmrs.Location;
import org.openmrs.OpenmrsObject;
import org.openmrs.annotation.Handler;
import org.openmrs.module.emrapi.EmrApiProperties;
import org.openmrs.module.emrapi.disposition.DispositionService;
import org.openmrs.module.mirebalaisreports.cohort.definition.LastDispositionBeforeExitCohortDefinition;
import org.openmrs.module.reporting.cohort.EvaluatedCohort;
import org.openmrs.module.reporting.cohort.definition.CohortDefinition;
import org.openmrs.module.reporting.cohort.definition.evaluator.CohortDefinitionEvaluator;
import org.openmrs.module.reporting.evaluation.EvaluationContext;
import org.openmrs.module.reporting.evaluation.EvaluationException;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
/**
*
*/
@Handler(supports = LastDispositionBeforeExitCohortDefinition.class)
public class LastDispositionBeforeExitCohortDefinitionEvaluator implements CohortDefinitionEvaluator {
@Autowired
SessionFactory sessionFactory;
@Autowired
private EmrApiProperties emrApiProperties;
@Autowired
private DispositionService dispositionService;
@Override
public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context) throws EvaluationException {
LastDispositionBeforeExitCohortDefinition cd = (LastDispositionBeforeExitCohortDefinition) cohortDefinition;
Location exitFromWard = cd.getExitFromWard();
List<Concept> dispositions = cd.getDispositions();
List<Concept> dispositionsToConsider = cd.getDispositionsToConsider();
String sql = "select distinct v.patient_id " +
"from visit v " +
"inner join encounter exit_encounter " +
" on exit_encounter.visit_id = v.visit_id " +
" and exit_encounter.voided = false " +
" and exit_encounter.encounter_type = :exitEncounterType " +
" and exit_encounter.encounter_datetime between :exitOnOrAfter and :exitOnOrBefore ";
if (exitFromWard != null) {
sql += " and exit_encounter.location_id = :exitFromWard ";
}
sql += "inner join encounter obs_encounter " +
" on obs_encounter.visit_id = v.visit_id " +
- " and obs_encounter.encounter_datetime = (" +
+ " and obs_encounter.encounter_id = (" +
" select find_obs_encounter.encounter_id " +
" from encounter find_obs_encounter " +
" inner join obs has_obs " +
" on has_obs.encounter_id = find_obs_encounter.encounter_id " +
" and has_obs.voided = false " +
" and has_obs.concept_id = :dispositionConcept ";
if (dispositionsToConsider != null) {
sql += " and has_obs.value_coded in (:dispositionsToConsider) ";
}
sql += " where find_obs_encounter.visit_id = v.visit_id " +
" and find_obs_encounter.voided = false " +
" order by find_obs_encounter.encounter_datetime desc, find_obs_encounter.date_created desc limit 1 " +
// if we wanted to require disposition at the same location as exit
// " and find_obs_encounter.location_id = :exitFromWard " +
" )" +
"inner join obs o " +
" on o.voided = false " +
" and o.concept_id = :dispositionConcept " +
" and o.encounter_id = obs_encounter.encounter_id " +
"where v.voided = false " +
" and o.value_coded in (:dispositions) ";
SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(sql);
query.setInteger("dispositionConcept", dispositionService.getDispositionDescriptor().getDispositionConcept().getId());
query.setParameterList("dispositions", idList(dispositions));
query.setInteger("exitEncounterType", emrApiProperties.getExitFromInpatientEncounterType().getId());
query.setTimestamp("exitOnOrAfter", cd.getExitOnOrAfter());
query.setTimestamp("exitOnOrBefore", cd.getExitOnOrBefore());
if (exitFromWard != null) {
query.setInteger("exitFromWard", exitFromWard.getId());
}
if (dispositionsToConsider != null) {
query.setParameterList("dispositionsToConsider", idList(dispositionsToConsider));
}
Cohort c = new Cohort();
for (Integer i : (List<Integer>) query.list()){
c.addMember(i);
}
return new EvaluatedCohort(c, cohortDefinition, context);
}
private List<Integer> idList(List<? extends OpenmrsObject> list) {
List<Integer> asIds = new ArrayList<Integer>();
for (OpenmrsObject o : list) {
asIds.add(o.getId());
}
return asIds;
}
}
| true | true | public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context) throws EvaluationException {
LastDispositionBeforeExitCohortDefinition cd = (LastDispositionBeforeExitCohortDefinition) cohortDefinition;
Location exitFromWard = cd.getExitFromWard();
List<Concept> dispositions = cd.getDispositions();
List<Concept> dispositionsToConsider = cd.getDispositionsToConsider();
String sql = "select distinct v.patient_id " +
"from visit v " +
"inner join encounter exit_encounter " +
" on exit_encounter.visit_id = v.visit_id " +
" and exit_encounter.voided = false " +
" and exit_encounter.encounter_type = :exitEncounterType " +
" and exit_encounter.encounter_datetime between :exitOnOrAfter and :exitOnOrBefore ";
if (exitFromWard != null) {
sql += " and exit_encounter.location_id = :exitFromWard ";
}
sql += "inner join encounter obs_encounter " +
" on obs_encounter.visit_id = v.visit_id " +
" and obs_encounter.encounter_datetime = (" +
" select find_obs_encounter.encounter_id " +
" from encounter find_obs_encounter " +
" inner join obs has_obs " +
" on has_obs.encounter_id = find_obs_encounter.encounter_id " +
" and has_obs.voided = false " +
" and has_obs.concept_id = :dispositionConcept ";
if (dispositionsToConsider != null) {
sql += " and has_obs.value_coded in (:dispositionsToConsider) ";
}
sql += " where find_obs_encounter.visit_id = v.visit_id " +
" and find_obs_encounter.voided = false " +
" order by find_obs_encounter.encounter_datetime desc, find_obs_encounter.date_created desc limit 1 " +
// if we wanted to require disposition at the same location as exit
// " and find_obs_encounter.location_id = :exitFromWard " +
" )" +
"inner join obs o " +
" on o.voided = false " +
" and o.concept_id = :dispositionConcept " +
" and o.encounter_id = obs_encounter.encounter_id " +
"where v.voided = false " +
" and o.value_coded in (:dispositions) ";
SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(sql);
query.setInteger("dispositionConcept", dispositionService.getDispositionDescriptor().getDispositionConcept().getId());
query.setParameterList("dispositions", idList(dispositions));
query.setInteger("exitEncounterType", emrApiProperties.getExitFromInpatientEncounterType().getId());
query.setTimestamp("exitOnOrAfter", cd.getExitOnOrAfter());
query.setTimestamp("exitOnOrBefore", cd.getExitOnOrBefore());
if (exitFromWard != null) {
query.setInteger("exitFromWard", exitFromWard.getId());
}
if (dispositionsToConsider != null) {
query.setParameterList("dispositionsToConsider", idList(dispositionsToConsider));
}
Cohort c = new Cohort();
for (Integer i : (List<Integer>) query.list()){
c.addMember(i);
}
return new EvaluatedCohort(c, cohortDefinition, context);
}
| public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context) throws EvaluationException {
LastDispositionBeforeExitCohortDefinition cd = (LastDispositionBeforeExitCohortDefinition) cohortDefinition;
Location exitFromWard = cd.getExitFromWard();
List<Concept> dispositions = cd.getDispositions();
List<Concept> dispositionsToConsider = cd.getDispositionsToConsider();
String sql = "select distinct v.patient_id " +
"from visit v " +
"inner join encounter exit_encounter " +
" on exit_encounter.visit_id = v.visit_id " +
" and exit_encounter.voided = false " +
" and exit_encounter.encounter_type = :exitEncounterType " +
" and exit_encounter.encounter_datetime between :exitOnOrAfter and :exitOnOrBefore ";
if (exitFromWard != null) {
sql += " and exit_encounter.location_id = :exitFromWard ";
}
sql += "inner join encounter obs_encounter " +
" on obs_encounter.visit_id = v.visit_id " +
" and obs_encounter.encounter_id = (" +
" select find_obs_encounter.encounter_id " +
" from encounter find_obs_encounter " +
" inner join obs has_obs " +
" on has_obs.encounter_id = find_obs_encounter.encounter_id " +
" and has_obs.voided = false " +
" and has_obs.concept_id = :dispositionConcept ";
if (dispositionsToConsider != null) {
sql += " and has_obs.value_coded in (:dispositionsToConsider) ";
}
sql += " where find_obs_encounter.visit_id = v.visit_id " +
" and find_obs_encounter.voided = false " +
" order by find_obs_encounter.encounter_datetime desc, find_obs_encounter.date_created desc limit 1 " +
// if we wanted to require disposition at the same location as exit
// " and find_obs_encounter.location_id = :exitFromWard " +
" )" +
"inner join obs o " +
" on o.voided = false " +
" and o.concept_id = :dispositionConcept " +
" and o.encounter_id = obs_encounter.encounter_id " +
"where v.voided = false " +
" and o.value_coded in (:dispositions) ";
SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(sql);
query.setInteger("dispositionConcept", dispositionService.getDispositionDescriptor().getDispositionConcept().getId());
query.setParameterList("dispositions", idList(dispositions));
query.setInteger("exitEncounterType", emrApiProperties.getExitFromInpatientEncounterType().getId());
query.setTimestamp("exitOnOrAfter", cd.getExitOnOrAfter());
query.setTimestamp("exitOnOrBefore", cd.getExitOnOrBefore());
if (exitFromWard != null) {
query.setInteger("exitFromWard", exitFromWard.getId());
}
if (dispositionsToConsider != null) {
query.setParameterList("dispositionsToConsider", idList(dispositionsToConsider));
}
Cohort c = new Cohort();
for (Integer i : (List<Integer>) query.list()){
c.addMember(i);
}
return new EvaluatedCohort(c, cohortDefinition, context);
}
|
diff --git a/bundles/org.eclipse.core.filesystem/src/org/eclipse/core/internal/filesystem/local/LocalFileSystem.java b/bundles/org.eclipse.core.filesystem/src/org/eclipse/core/internal/filesystem/local/LocalFileSystem.java
index 18573207a..64f4468a5 100644
--- a/bundles/org.eclipse.core.filesystem/src/org/eclipse/core/internal/filesystem/local/LocalFileSystem.java
+++ b/bundles/org.eclipse.core.filesystem/src/org/eclipse/core/internal/filesystem/local/LocalFileSystem.java
@@ -1,155 +1,155 @@
/*******************************************************************************
* Copyright (c) 2005, 2009 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Martin Oberhuber (Wind River) - [170317] add symbolic link support to API
* Martin Oberhuber (Wind River) - [183137] liblocalfile for solaris-sparc
* Martin Oberhuber (Wind River) - [184433] liblocalfile for Linux x86_64
* Martin Oberhuber (Wind River) - [184534] get attributes from native lib
*******************************************************************************/
package org.eclipse.core.internal.filesystem.local;
import java.io.File;
import java.net.URI;
import org.eclipse.core.filesystem.*;
import org.eclipse.core.filesystem.provider.FileSystem;
import org.eclipse.core.runtime.IPath;
import org.eclipse.osgi.service.environment.Constants;
/**
* File system provider for the "file" scheme. This file system provides access to
* the local file system that is available via java.io.File.
*/
public class LocalFileSystem extends FileSystem {
/**
* Cached constant indicating if the current OS is Mac OSX
*/
static final boolean MACOSX = LocalFileSystem.getOS().equals(Constants.OS_MACOSX);
/**
* Whether the current file system is case sensitive
*/
private static final boolean caseSensitive = MACOSX ? false : new java.io.File("a").compareTo(new java.io.File("A")) != 0; //$NON-NLS-1$ //$NON-NLS-2$
/**
* The attributes of this file system. The initial value of -1 is used
* to indicate that the attributes have not yet been computed.
*/
private int attributes = -1;
/**
* The singleton instance of this file system.
*/
private static IFileSystem instance;
/**
* Returns the instance of this file system
*
* @return The instance of this file system.
*/
public static IFileSystem getInstance() {
return instance;
}
/**
* Returns the current OS. This is equivalent to Platform.getOS(), but
* is tolerant of the platform runtime not being present.
*/
static String getOS() {
return System.getProperty("osgi.os", ""); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Creates a new local file system.
*/
public LocalFileSystem() {
super();
instance = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.core.filesystem.IFileSystem#attributes()
*/
public int attributes() {
if (attributes != -1)
return attributes;
attributes = 0;
if (!LocalFileNatives.usingNatives())
return attributes;
//try to query supported attributes from native lib impl
int nativeAttributes = LocalFileNatives.attributes();
if (nativeAttributes >= 0) {
attributes = nativeAttributes;
return attributes;
}
//fallback for older lib: compute attributes as known before
//all known platforms with native implementation support the read only flag
attributes |= EFS.ATTRIBUTE_READ_ONLY;
//this must be kept in sync with the actual native implementations.
String os = getOS();
String arch = System.getProperty("osgi.arch", ""); //$NON-NLS-1$ //$NON-NLS-2$
if (os.equals(Constants.OS_WIN32))
attributes |= EFS.ATTRIBUTE_ARCHIVE | EFS.ATTRIBUTE_HIDDEN;
- else if (os.equals(Constants.OS_LINUX) || (os.equals(Constants.OS_SOLARIS) && arch.equals(Constants.ARCH_SPARC)))
- attributes |= EFS.ATTRIBUTE_EXECUTABLE | EFS.ATTRIBUTE_SYMLINK | EFS.ATTRIBUTE_LINK_TARGET;
- else if (os.equals(Constants.OS_MACOSX) || os.equals(Constants.OS_HPUX) || os.equals(Constants.OS_QNX))
+ else if (os.equals(Constants.OS_LINUX) || (os.equals(Constants.OS_SOLARIS) && arch.equals(Constants.ARCH_SPARC)) || os.equals(Constants.OS_MACOSX))
attributes |= EFS.ATTRIBUTE_EXECUTABLE | EFS.ATTRIBUTE_SYMLINK | EFS.ATTRIBUTE_LINK_TARGET;
+ else if (os.equals(Constants.OS_HPUX) || os.equals(Constants.OS_QNX))
+ attributes |= EFS.ATTRIBUTE_EXECUTABLE;
return attributes;
}
/*
* (non-Javadoc)
* @see org.eclipse.core.filesystem.IFileSystem#canDelete()
*/
public boolean canDelete() {
return true;
}
/*
* (non-Javadoc)
* @see org.eclipse.core.filesystem.IFileSystem#canWrite()
*/
public boolean canWrite() {
return true;
}
/*
* (non-Javadoc)
* @see org.eclipse.core.filesystem.IFileSystem#fromLocalFile(java.io.File)
*/
public IFileStore fromLocalFile(File file) {
return new LocalFile(file);
}
/*
* (non-Javadoc)
* @see org.eclipse.core.filesystem.IFileSystem#getStore(org.eclipse.core.runtime.IPath)
*/
public IFileStore getStore(IPath path) {
return new LocalFile(path.toFile());
}
/*
* (non-Javadoc)
* @see org.eclipse.core.filesystem.IFileSystem#getStore(java.net.URI)
*/
public IFileStore getStore(URI uri) {
return new LocalFile(new File(uri.getSchemeSpecificPart()));
}
/*
* (non-Javadoc)
* @see org.eclipse.core.filesystem.IFileSystem#isCaseSensitive()
*/
public boolean isCaseSensitive() {
return caseSensitive;
}
}
| false | true | public int attributes() {
if (attributes != -1)
return attributes;
attributes = 0;
if (!LocalFileNatives.usingNatives())
return attributes;
//try to query supported attributes from native lib impl
int nativeAttributes = LocalFileNatives.attributes();
if (nativeAttributes >= 0) {
attributes = nativeAttributes;
return attributes;
}
//fallback for older lib: compute attributes as known before
//all known platforms with native implementation support the read only flag
attributes |= EFS.ATTRIBUTE_READ_ONLY;
//this must be kept in sync with the actual native implementations.
String os = getOS();
String arch = System.getProperty("osgi.arch", ""); //$NON-NLS-1$ //$NON-NLS-2$
if (os.equals(Constants.OS_WIN32))
attributes |= EFS.ATTRIBUTE_ARCHIVE | EFS.ATTRIBUTE_HIDDEN;
else if (os.equals(Constants.OS_LINUX) || (os.equals(Constants.OS_SOLARIS) && arch.equals(Constants.ARCH_SPARC)))
attributes |= EFS.ATTRIBUTE_EXECUTABLE | EFS.ATTRIBUTE_SYMLINK | EFS.ATTRIBUTE_LINK_TARGET;
else if (os.equals(Constants.OS_MACOSX) || os.equals(Constants.OS_HPUX) || os.equals(Constants.OS_QNX))
attributes |= EFS.ATTRIBUTE_EXECUTABLE | EFS.ATTRIBUTE_SYMLINK | EFS.ATTRIBUTE_LINK_TARGET;
return attributes;
}
| public int attributes() {
if (attributes != -1)
return attributes;
attributes = 0;
if (!LocalFileNatives.usingNatives())
return attributes;
//try to query supported attributes from native lib impl
int nativeAttributes = LocalFileNatives.attributes();
if (nativeAttributes >= 0) {
attributes = nativeAttributes;
return attributes;
}
//fallback for older lib: compute attributes as known before
//all known platforms with native implementation support the read only flag
attributes |= EFS.ATTRIBUTE_READ_ONLY;
//this must be kept in sync with the actual native implementations.
String os = getOS();
String arch = System.getProperty("osgi.arch", ""); //$NON-NLS-1$ //$NON-NLS-2$
if (os.equals(Constants.OS_WIN32))
attributes |= EFS.ATTRIBUTE_ARCHIVE | EFS.ATTRIBUTE_HIDDEN;
else if (os.equals(Constants.OS_LINUX) || (os.equals(Constants.OS_SOLARIS) && arch.equals(Constants.ARCH_SPARC)) || os.equals(Constants.OS_MACOSX))
attributes |= EFS.ATTRIBUTE_EXECUTABLE | EFS.ATTRIBUTE_SYMLINK | EFS.ATTRIBUTE_LINK_TARGET;
else if (os.equals(Constants.OS_HPUX) || os.equals(Constants.OS_QNX))
attributes |= EFS.ATTRIBUTE_EXECUTABLE;
return attributes;
}
|
diff --git a/src/com/VolunteerCoordinatorApp/VolunteerCoordinatorServlet.java b/src/com/VolunteerCoordinatorApp/VolunteerCoordinatorServlet.java
index fdebb4a..4f6a19f 100644
--- a/src/com/VolunteerCoordinatorApp/VolunteerCoordinatorServlet.java
+++ b/src/com/VolunteerCoordinatorApp/VolunteerCoordinatorServlet.java
@@ -1,112 +1,117 @@
package com.VolunteerCoordinatorApp;
import java.util.*;
import java.io.*;
import javax.servlet.http.*;
import java.text.SimpleDateFormat;
import javax.jdo.Query;
import javax.jdo.PersistenceManager;
import com.google.gdata.client.*;
import com.google.gdata.client.calendar.*;
import com.google.gdata.data.*;
import com.google.gdata.data.acl.*;
import com.google.gdata.data.calendar.*;
import com.google.gdata.data.extensions.*;
import com.google.gdata.util.*;
import com.google.common.collect.Maps;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import java.net.URL;
@SuppressWarnings("serial")
public class VolunteerCoordinatorServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
Object taskObj = req.getAttribute("task");
Object nameObj = req.getAttribute("name");
String task;
String name;
if (taskObj == null) {
name = req.getParameter("name");
task = req.getParameter("task");
}
else {
name = nameObj.toString();
task = taskObj.toString();
}
- if(!userExists(name)) {
+ if( name.equals( "" ) )
+ {
+ String redirect = "/index.jsp?name=none";
+ resp.sendRedirect( redirect );
+ }
+ else if(!userExists(name)) {
String splitName[] = name.split(" ");
String redirect = "/newUser.jsp?name=";
for( int i = 0; i < splitName.length; i++ )
{
if( i > 0 )
redirect += "+";
redirect += splitName[i];
}
redirect += "&task=" + task;
resp.sendRedirect( redirect );
}
else if(task.equals("volunteer")) {
resp.sendRedirect("/volunteer.jsp?pageNumber=1&resultIndex=1");
} else if(task.equals("initiate")) {
resp.sendRedirect("/add.jsp");
} else if(task.equals("manage")) {
resp.sendRedirect("/manProj.jsp?pageNumber=1&resultIndex=1");
} else if(task.equals("dashboard")) {
resp.sendRedirect("/underConstruction.jsp");
} else if(task.equals("preferences")) {
resp.sendRedirect("/prefs.jsp?name="
+ name.substring(0, name.indexOf(" ")) + "+"
+ name.substring(name.indexOf(" "), name.length()).trim()
+ "&email=" + getEmail(name)
+ "&phone=" + getPhone(name)
+ "&reminder=" + getReminder(name));
}
}
private boolean userExists(String name) {
PersistenceManager pm = PMF.get().getPersistenceManager();
Query query = pm.newQuery(Volunteer.class);
query.setFilter("name == nameParam");
query.declareParameters("String nameParam");
List<Volunteer> results = (List<Volunteer>)query.execute(name);
if(results.isEmpty()) {
return false;
} else {
return true;
}
}
private String getEmail(String name) {
PersistenceManager pm = PMF.get().getPersistenceManager();
Key k = KeyFactory.createKey(Volunteer.class.getSimpleName(), name);
Volunteer v = pm.getObjectById(Volunteer.class, k);
return v.getEmail();
}
private String getPhone(String name) {
PersistenceManager pm = PMF.get().getPersistenceManager();
Key k = KeyFactory.createKey(Volunteer.class.getSimpleName(), name);
Volunteer v = pm.getObjectById(Volunteer.class, k);
return v.getPhone();
}
private String getReminder(String name) {
PersistenceManager pm = PMF.get().getPersistenceManager();
Key k = KeyFactory.createKey(Volunteer.class.getSimpleName(), name);
Volunteer v = pm.getObjectById(Volunteer.class, k);
return v.getReminder();
}
}
| true | true | public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
Object taskObj = req.getAttribute("task");
Object nameObj = req.getAttribute("name");
String task;
String name;
if (taskObj == null) {
name = req.getParameter("name");
task = req.getParameter("task");
}
else {
name = nameObj.toString();
task = taskObj.toString();
}
if(!userExists(name)) {
String splitName[] = name.split(" ");
String redirect = "/newUser.jsp?name=";
for( int i = 0; i < splitName.length; i++ )
{
if( i > 0 )
redirect += "+";
redirect += splitName[i];
}
redirect += "&task=" + task;
resp.sendRedirect( redirect );
}
else if(task.equals("volunteer")) {
resp.sendRedirect("/volunteer.jsp?pageNumber=1&resultIndex=1");
} else if(task.equals("initiate")) {
resp.sendRedirect("/add.jsp");
} else if(task.equals("manage")) {
resp.sendRedirect("/manProj.jsp?pageNumber=1&resultIndex=1");
} else if(task.equals("dashboard")) {
resp.sendRedirect("/underConstruction.jsp");
} else if(task.equals("preferences")) {
resp.sendRedirect("/prefs.jsp?name="
+ name.substring(0, name.indexOf(" ")) + "+"
+ name.substring(name.indexOf(" "), name.length()).trim()
+ "&email=" + getEmail(name)
+ "&phone=" + getPhone(name)
+ "&reminder=" + getReminder(name));
}
}
| public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
Object taskObj = req.getAttribute("task");
Object nameObj = req.getAttribute("name");
String task;
String name;
if (taskObj == null) {
name = req.getParameter("name");
task = req.getParameter("task");
}
else {
name = nameObj.toString();
task = taskObj.toString();
}
if( name.equals( "" ) )
{
String redirect = "/index.jsp?name=none";
resp.sendRedirect( redirect );
}
else if(!userExists(name)) {
String splitName[] = name.split(" ");
String redirect = "/newUser.jsp?name=";
for( int i = 0; i < splitName.length; i++ )
{
if( i > 0 )
redirect += "+";
redirect += splitName[i];
}
redirect += "&task=" + task;
resp.sendRedirect( redirect );
}
else if(task.equals("volunteer")) {
resp.sendRedirect("/volunteer.jsp?pageNumber=1&resultIndex=1");
} else if(task.equals("initiate")) {
resp.sendRedirect("/add.jsp");
} else if(task.equals("manage")) {
resp.sendRedirect("/manProj.jsp?pageNumber=1&resultIndex=1");
} else if(task.equals("dashboard")) {
resp.sendRedirect("/underConstruction.jsp");
} else if(task.equals("preferences")) {
resp.sendRedirect("/prefs.jsp?name="
+ name.substring(0, name.indexOf(" ")) + "+"
+ name.substring(name.indexOf(" "), name.length()).trim()
+ "&email=" + getEmail(name)
+ "&phone=" + getPhone(name)
+ "&reminder=" + getReminder(name));
}
}
|
diff --git a/src/com/dmdirc/config/prefs/PreferencesManager.java b/src/com/dmdirc/config/prefs/PreferencesManager.java
index 1936a257b..6c0cb3c42 100644
--- a/src/com/dmdirc/config/prefs/PreferencesManager.java
+++ b/src/com/dmdirc/config/prefs/PreferencesManager.java
@@ -1,606 +1,604 @@
/*
* 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.config.prefs;
import com.dmdirc.Main;
import com.dmdirc.actions.ActionManager;
import com.dmdirc.actions.CoreActionType;
import com.dmdirc.config.prefs.validator.NumericalValidator;
import com.dmdirc.plugins.PluginManager;
import com.dmdirc.plugins.Service;
import com.dmdirc.util.ListenerList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
/**
* Manages categories that should appear in the preferences dialog.
*
* @author chris
*/
public class PreferencesManager {
/** A list of categories. */
private final List<PreferencesCategory> categories
= new ArrayList<PreferencesCategory>();
/** A list of listeners. */
private final ListenerList listeners = new ListenerList();
/**
* Creates a new instance of PreferencesManager.
*/
public PreferencesManager() {
addDefaultCategories();
ActionManager.processEvent(CoreActionType.CLIENT_PREFS_OPENED, null, this);
}
/**
* Adds the specified category to the preferences manager.
*
* @param category The category to be added
*/
public void addCategory(final PreferencesCategory category) {
categories.add(category);
}
/**
* Retrieves a list of categories registered with the preferences manager.
*
* @return An ordered list of categories
*/
public List<PreferencesCategory> getCategories() {
return categories;
}
/**
* Finds and retrieves the category with the specified name.
*
* @param name The name (title) of the category to find.
* @return The appropriate category, or null if none was found
*/
public PreferencesCategory getCategory(final String name) {
for (PreferencesCategory category : categories) {
if (category.getTitle().equals(name)) {
return category;
}
}
return null;
}
/**
* Saves all the settings in this manager.
*
* @return Is a restart needed after saving?
*/
public boolean save() {
fireSaveListeners();
boolean restart = false;
for (PreferencesCategory category : categories) {
if (category.save()) {
restart = true;
}
}
return restart;
}
/**
* Dismisses all the settings in this manager.
*/
public void dismiss() {
for (PreferencesCategory category : categories) {
category.dismiss();
}
}
/**
* Adds the default categories to this preferences manager.
*/
private void addDefaultCategories() {
addGeneralCategory();
addConnectionCategory();
addMessagesCategory();
addGuiCategory();
addPluginsCategory();
addUrlHandlerCategory();
addUpdatesCategory();
addAdvancedCategory();
}
/**
* Creates and adds the "General" category.
*/
private void addGeneralCategory() {
final PreferencesCategory category = new PreferencesCategory("General", "");
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"ui", "confirmQuit", "Confirm quit",
"Do you want to confirm closing the client?"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"channel", "splitusermodes", "Split user modes",
"Show individual mode lines for each mode change that affects" +
" a user (e.g. op, devoice)"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"channel", "sendwho", "Send channel WHOs",
"Request information (away state, hostname, etc) on channel " +
"users automatically"));
category.addSetting(new PreferencesSetting(PreferencesType.DURATION,
"general", "whotime", "Who request interval",
"How often to send WHO requests for a channel"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"channel", "showmodeprefix", "Show mode prefix",
"Prefix users' names with their mode in channels"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"server", "friendlymodes", "Friendly modes",
"Show friendly mode names"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"general", "hidequeries", "Hide queries",
"Initially hide queries so that they don't steal focus"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"ui", "awayindicator", "Away indicator",
"Shows an indicator in windows when you are marked as away"));
category.addSetting(new PreferencesSetting(PreferencesType.INTEGER,
new NumericalValidator(0, 100), "ui", "pasteProtectionLimit",
"Paste protection trigger", "Confirm pasting of text that " +
"contains more than this many lines."));
final Map<String, String> taboptions = new HashMap<String, String>();
for (Service service : PluginManager.getPluginManager().getServicesByType("tabcompletion")) {
taboptions.put(service.getName(), service.getName());
}
category.addSetting(new PreferencesSetting("tabcompletion", "style",
"Tab completion style", "Determines the behaviour of " +
"the tab completer when there are multiple matches.", taboptions));
addCategory(category);
}
/**
* Creates and adds the "Connection" category.
*/
private void addConnectionCategory() {
final PreferencesCategory category = new PreferencesCategory("Connection",
"", "category-connection");
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"general", "closechannelsonquit", "Close channels on quit",
"Close channel windows when you quit the server?"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"general", "closechannelsondisconnect",
"Close channels on disconnect", "Close channel windows when " +
"the server is disconnected?"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"general", "closequeriesonquit", "Close queries on quit",
"Close query windows when you quit the server?"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"general", "closequeriesondisconnect",
"Close queries on disconnect", "Close query windows when " +
"the server is disconnected?"));
category.addSetting(new PreferencesSetting(PreferencesType.DURATION,
"server", "pingtimer", "Ping warning time",
"How long to wait after a ping reply is sent before showing " +
"a warning message"));
category.addSetting(new PreferencesSetting(PreferencesType.DURATION,
"server", "pingtimeout", "Ping timeout",
"How long to wait for a server to reply to a PING request " +
"before assume it has died and disconnecting"));
category.addSetting(new PreferencesSetting(PreferencesType.DURATION,
"server", "pingfrequency", "Ping frequency",
"How often a PING request should be sent to the server (to " +
"check that it is still alive)"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"general", "reconnectonconnectfailure", "Reconnect on failure",
"Attempt to reconnect if there is an error when connecting?"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"general", "reconnectondisconnect", "Reconnect on disconnect",
"Attempt to reconnect if the server is disconnected?"));
category.addSetting(new PreferencesSetting(PreferencesType.DURATION,
"general", "reconnectdelay", "Reconnect delay",
"How long to wait before attempting to reconnect to a server"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"general", "rejoinchannels", "Rejoin open channels",
"Rejoin open channels when reconnecting to a server?"));
addCategory(category);
}
/**
* Creates and adds the "Messages" category.
*/
private void addMessagesCategory() {
final PreferencesCategory category = new PreferencesCategory("Messages",
"", "category-messages");
category.addSetting(new PreferencesSetting(PreferencesType.TEXT,
"general", "closemessage",
"Close message", "Default quit message to use when closing DMDirc"));
category.addSetting(new PreferencesSetting(PreferencesType.TEXT,
"general", "partmessage",
"Part message", "Default part message to use when leaving channels"));
category.addSetting(new PreferencesSetting(PreferencesType.TEXT,
"general", "quitmessage",
"Quit message", "Default quit message to use when disconnecting"));
category.addSetting(new PreferencesSetting(PreferencesType.TEXT,
"general", "cyclemessage",
"Cycle message", "Default part message to use when cycling channels"));
category.addSetting(new PreferencesSetting(PreferencesType.TEXT,
"general", "kickmessage",
"Kick message", "Default message to use when kicking people"));
category.addSetting(new PreferencesSetting(PreferencesType.TEXT,
"general", "reconnectmessage",
"Reconnect message", "Default quit message to use when reconnecting"));
addNotificationsCategory(category);
addCategory(category);
}
/**
* Creates and adds the "Notifications" category.
*
* @param parent The parent category.
*/
private void addNotificationsCategory(final PreferencesCategory parent) {
final PreferencesCategory category = new PreferencesCategory("Notifications", "");
final Map<String, String> options = new HashMap<String, String>();
final Map<String, String> whoisOptions = new HashMap<String, String>();
final Map<String, String> ctcprOptions = new HashMap<String, String>();
final Map<String, String> mapOptions = new HashMap<String, String>();
options.put("all", "All windows");
options.put("active", "Active window");
options.put("server", "Server window");
options.put("none", "Nowhere");
whoisOptions.putAll(options);
whoisOptions.put("lastcommand:(raw )?whois %4$s( %4$s)?", "Source of whois command");
ctcprOptions.putAll(options);
ctcprOptions.put("lastcommand:ctcp %1$s %4$S", "Source of ctcp command");
mapOptions.putAll(options);
mapOptions.put("window:Network Map", "Map window");
category.addSetting(new PreferencesSetting("notifications", "socketClosed",
"Socket closed", "Where to display socket closed notifications",
options));
category.addSetting(new PreferencesSetting("notifications", "privateNotice",
"Private notice", "Where to display private notices",
options));
category.addSetting(new PreferencesSetting("notifications", "privateCTCP",
"CTCP request", "Where to display CTCP request notifications",
options));
category.addSetting(new PreferencesSetting("notifications", "privateCTCPreply",
"CTCP reply", "Where to display CTCP replies",
ctcprOptions));
category.addSetting(new PreferencesSetting("notifications", "connectError",
"Connect error", "Where to display connect error notifications",
options));
category.addSetting(new PreferencesSetting("notifications", "connectRetry",
"Connect retry", "Where to display connect retry notifications",
options));
category.addSetting(new PreferencesSetting("notifications", "stonedServer",
"Stoned server", "Where to display stoned server notifications",
options));
category.addSetting(new PreferencesSetting("notifications", "whois",
"Whois output", "Where to display /whois output",
whoisOptions));
category.addSetting(new PreferencesSetting("notifications", "lusers",
"Lusers output", "Where to display /lusers output",
options));
category.addSetting(new PreferencesSetting("notifications", "map",
"Map output", "Where to display /map output",
mapOptions));
category.addSetting(new PreferencesSetting("notifications", "away",
"Away notification", "Where to display /away output",
options));
category.addSetting(new PreferencesSetting("notifications", "back",
"Back notification", "Where to display /away output",
options));
parent.addSubCategory(category);
}
/**
* Creates and adds the "Advanced" category.
*/
private void addAdvancedCategory() {
final PreferencesCategory category = new PreferencesCategory("Advanced",
"", "category-advanced");
final Map<String, String> options = new HashMap<String, String>();
options.put("alwaysShow", "Always show");
options.put("neverShow", "Never show");
options.put("showWhenMaximised", "Show only when windows maximised");
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"browser", "uselaunchdelay", "Use browser launch delay",
"Enable delay between browser launches (to prevent mistakenly" +
" double clicking)?"));
category.addSetting(new PreferencesSetting(PreferencesType.DURATION,
"browser", "launchdelay", "Browser launch delay",
"Minimum time between opening of URLs"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"general", "submitErrors", "Automatically submit errors",
"Automatically submit client errors to the developers?"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"general", "logerrors", "Log errors to disk",
"Save copies of all errors to disk?"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"tabcompletion", "casesensitive", "Case-sensitive tab completion",
"Respect case when tab completing?"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"ui", "quickCopy", "Quick copy", "Automatically copy" +
" text that's selected when the mouse button is released?"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"ui", "showversion", "Show version",
"Show DMDirc version in the titlebar?"));
category.addSetting(new PreferencesSetting(PreferencesType.INTEGER,
new NumericalValidator(10, -1), "ui", "frameBufferSize",
"Window buffer size", "The maximum number of lines in a window" +
" buffer"));
category.addSetting(new PreferencesSetting("ui", "mdiBarVisibility",
"MDI Bar Visibility", "Controls the visibility of the MDI bar", options));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN, "ui",
"useOneTouchExpandable", "Use one touch expandable split panes?",
"Use one touch expandable arrows for collapsing/expanding the split panes"));
addCategory(category);
}
/**
* Creates and adds the "GUI" category.
*/
private void addGuiCategory() {
final Map<String, String> lafs = new HashMap<String, String>();
final Map<String, String> framemanagers = new HashMap<String, String>();
final Map<String, String> fmpositions = new HashMap<String, String>();
final PreferencesCategory category = new PreferencesCategory("GUI", "",
"category-gui");
framemanagers.put("com.dmdirc.ui.swing.framemanager.tree.TreeFrameManager", "Treeview");
framemanagers.put("com.dmdirc.ui.swing.framemanager.buttonbar.ButtonBar", "Button bar");
fmpositions.put("top", "Top");
fmpositions.put("bottom", "Bottom");
fmpositions.put("left", "Left");
fmpositions.put("right", "Right");
final LookAndFeelInfo[] plaf = UIManager.getInstalledLookAndFeels();
final String sysLafClass = UIManager.getSystemLookAndFeelClassName();
lafs.put("Native", "Native");
for (LookAndFeelInfo laf : plaf) {
lafs.put(laf.getName(), laf.getName());
}
category.addSetting(new PreferencesSetting(PreferencesType.COLOUR,
"ui", "backgroundcolour", "Background colour", "Default " +
"background colour to use"));
category.addSetting(new PreferencesSetting(PreferencesType.COLOUR,
"ui", "foregroundcolour", "Foreground colour", "Default " +
"foreground colour to use"));
category.addSetting(new PreferencesSetting(PreferencesType.OPTIONALCOLOUR,
"ui", "inputbackgroundcolour", "Input background colour",
"Default background colour to use for input fields"));
category.addSetting(new PreferencesSetting(PreferencesType.OPTIONALCOLOUR,
"ui", "inputforegroundcolour", "Input foreground colour",
"Default foreground colour to use for input fields"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"general", "showcolourdialog", "Show colour dialog",
"Show colour picker dialog when using colour control codes?"));
category.addSetting(new PreferencesSetting("ui", "lookandfeel",
"Look and feel", "The Java look and feel to use",
lafs));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"ui", "antialias", "System anti-alias",
"Anti-alias all fonts?").setRestartNeeded());
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"ui", "maximisewindows", "Auto-maximise windows",
"Automatically maximise newly opened windows?"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"ui", "shownickcoloursintext", "Show nick colours in text area",
"Show nickname colours in text areas?"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"ui", "shownickcoloursinnicklist", "Show nick colours in nicklists",
"Show nickname colours in channel nicklists?"));
category.addSetting(new PreferencesSetting("ui", "framemanager",
"Window manager", "Which window manager should be used?",
framemanagers).setRestartNeeded());
category.addSetting(new PreferencesSetting("ui", "framemanagerPosition",
"Window manager position", "Where should the window " +
"manager be positioned?", fmpositions).setRestartNeeded());
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"ui", "stylelinks", "Style links", "Style links in text areas"));
- category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
- "ui", "stylelinks", "Style links", "Style links in text areas"));
addThemesCategory(category);
addNicklistCategory(category);
addTreeviewCategory(category);
addCategory(category);
}
/**
* Creates and adds the "Themes" category.
*
* @param parent The parent category
*/
private void addThemesCategory(final PreferencesCategory parent) {
// TODO: Abstract the panel
parent.addSubCategory(new PreferencesCategory("Themes", "",
"category-addons", Main.getUI().getThemesPrefsPanel()));
}
/**
* Creates and adds the "Nicklist" category.
*
* @param parent The parent category
*/
private void addNicklistCategory(final PreferencesCategory parent) {
final PreferencesCategory category = new PreferencesCategory("Nicklist", "");
category.addSetting(new PreferencesSetting(PreferencesType.OPTIONALCOLOUR,
"ui", "nicklistbackgroundcolour", "Nicklist background colour",
"Background colour to use for the nicklist"));
category.addSetting(new PreferencesSetting(PreferencesType.OPTIONALCOLOUR,
"ui", "nicklistforegroundcolour", "Nicklist foreground colour",
"Foreground colour to use for the nicklist"));
category.addSetting(new PreferencesSetting(PreferencesType.OPTIONALCOLOUR,
"ui", "nickListAltBackgroundColour", "Alternate background colour",
"Background colour to use for every other nicklist entry"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"nicklist", "sortByMode", "Sort nicklist by user mode",
"Sort nicknames by the modes that they have?"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"nicklist", "sortByCase", "Sort nicklist by case",
"Sort nicknames in a case-sensitive manner?"));
parent.addSubCategory(category);
}
/**
* Creates and adds the "Treeview" category.
*
* @param parent The parent category
*/
private void addTreeviewCategory(final PreferencesCategory parent) {
final PreferencesCategory category = new PreferencesCategory("Treeview", "");
category.addSetting(new PreferencesSetting(PreferencesType.OPTIONALCOLOUR,
"treeview", "backgroundcolour", "Treeview background colour",
"Background colour to use for the treeview"));
category.addSetting(new PreferencesSetting(PreferencesType.OPTIONALCOLOUR,
"treeview", "foregroundcolour", "Treeview foreground colour",
"Foreground colour to use for the treeview"));
category.addSetting(new PreferencesSetting(PreferencesType.OPTIONALCOLOUR,
"ui", "treeviewRolloverColour", "Treeview rollover colour",
"Background colour to use when the mouse cursor is over a node"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"treeview", "sortwindows", "Sort windows",
"Sort windows belonging to servers in the treeview?"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"treeview", "sortservers", "Sort servers",
"Sort servers in the treeview?"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"ui", "treeviewActiveBold", "Active node bold",
"Make the active node bold?"));
category.addSetting(new PreferencesSetting(PreferencesType.OPTIONALCOLOUR,
"ui", "treeviewActiveBackground", "Active node background",
"Background colour to use for active treeview node"));
category.addSetting(new PreferencesSetting(PreferencesType.OPTIONALCOLOUR,
"ui", "treeviewActiveForeground", "Active node foreground",
"Foreground colour to use for active treeview node"));
parent.addSubCategory(category);
}
/**
* Creates and adds the "Plugins" category.
*/
private void addPluginsCategory() {
// TODO: Abstract the panel
addCategory(new PreferencesCategory("Plugins", "", "category-addons",
Main.getUI().getPluginPrefsPanel()));
}
/**
* Creates and adds the "Updates" category.
*/
private void addUpdatesCategory() {
// TODO: Abstract the panel
addCategory(new PreferencesCategory("Updates", "", "category-updates",
Main.getUI().getUpdatesPrefsPanel()));
}
/**
* Creates and adds the "URL Handlers" category.
*/
private void addUrlHandlerCategory() {
// TODO: Abstract the panel
addCategory(new PreferencesCategory("URL Handlers",
"Configure how DMDirc handles different types of URLs",
"category-urlhandlers", Main.getUI().getUrlHandlersPrefsPanel()));
}
/**
* Registers the specified save listener with this manager.
*
* @param listener The listener to be registered
*/
public void registerSaveListener(final PreferencesInterface listener) {
listeners.add(PreferencesInterface.class, listener);
}
/**
* Fires the "save" methods of all registered listeners.
*/
public void fireSaveListeners() {
for (PreferencesInterface iface : listeners.get(PreferencesInterface.class)) {
iface.save();
}
for (PreferencesCategory category : categories) {
fireSaveListener(category);
}
}
/**
* Fires the save listener for any objects within the specified category.
*
* @param category The category to check
*/
private void fireSaveListener(final PreferencesCategory category) {
if (category.hasObject()) {
category.getObject().save();
}
for (PreferencesCategory subcategory : category.getSubcats()) {
fireSaveListener(subcategory);
}
}
/**
* Fires the CLIENT_PREFS_CLOSED action
*
* @since 0.6
*/
public void close() {
ActionManager.processEvent(CoreActionType.CLIENT_PREFS_CLOSED, null);
}
}
| true | true | private void addGuiCategory() {
final Map<String, String> lafs = new HashMap<String, String>();
final Map<String, String> framemanagers = new HashMap<String, String>();
final Map<String, String> fmpositions = new HashMap<String, String>();
final PreferencesCategory category = new PreferencesCategory("GUI", "",
"category-gui");
framemanagers.put("com.dmdirc.ui.swing.framemanager.tree.TreeFrameManager", "Treeview");
framemanagers.put("com.dmdirc.ui.swing.framemanager.buttonbar.ButtonBar", "Button bar");
fmpositions.put("top", "Top");
fmpositions.put("bottom", "Bottom");
fmpositions.put("left", "Left");
fmpositions.put("right", "Right");
final LookAndFeelInfo[] plaf = UIManager.getInstalledLookAndFeels();
final String sysLafClass = UIManager.getSystemLookAndFeelClassName();
lafs.put("Native", "Native");
for (LookAndFeelInfo laf : plaf) {
lafs.put(laf.getName(), laf.getName());
}
category.addSetting(new PreferencesSetting(PreferencesType.COLOUR,
"ui", "backgroundcolour", "Background colour", "Default " +
"background colour to use"));
category.addSetting(new PreferencesSetting(PreferencesType.COLOUR,
"ui", "foregroundcolour", "Foreground colour", "Default " +
"foreground colour to use"));
category.addSetting(new PreferencesSetting(PreferencesType.OPTIONALCOLOUR,
"ui", "inputbackgroundcolour", "Input background colour",
"Default background colour to use for input fields"));
category.addSetting(new PreferencesSetting(PreferencesType.OPTIONALCOLOUR,
"ui", "inputforegroundcolour", "Input foreground colour",
"Default foreground colour to use for input fields"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"general", "showcolourdialog", "Show colour dialog",
"Show colour picker dialog when using colour control codes?"));
category.addSetting(new PreferencesSetting("ui", "lookandfeel",
"Look and feel", "The Java look and feel to use",
lafs));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"ui", "antialias", "System anti-alias",
"Anti-alias all fonts?").setRestartNeeded());
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"ui", "maximisewindows", "Auto-maximise windows",
"Automatically maximise newly opened windows?"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"ui", "shownickcoloursintext", "Show nick colours in text area",
"Show nickname colours in text areas?"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"ui", "shownickcoloursinnicklist", "Show nick colours in nicklists",
"Show nickname colours in channel nicklists?"));
category.addSetting(new PreferencesSetting("ui", "framemanager",
"Window manager", "Which window manager should be used?",
framemanagers).setRestartNeeded());
category.addSetting(new PreferencesSetting("ui", "framemanagerPosition",
"Window manager position", "Where should the window " +
"manager be positioned?", fmpositions).setRestartNeeded());
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"ui", "stylelinks", "Style links", "Style links in text areas"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"ui", "stylelinks", "Style links", "Style links in text areas"));
addThemesCategory(category);
addNicklistCategory(category);
addTreeviewCategory(category);
addCategory(category);
}
| private void addGuiCategory() {
final Map<String, String> lafs = new HashMap<String, String>();
final Map<String, String> framemanagers = new HashMap<String, String>();
final Map<String, String> fmpositions = new HashMap<String, String>();
final PreferencesCategory category = new PreferencesCategory("GUI", "",
"category-gui");
framemanagers.put("com.dmdirc.ui.swing.framemanager.tree.TreeFrameManager", "Treeview");
framemanagers.put("com.dmdirc.ui.swing.framemanager.buttonbar.ButtonBar", "Button bar");
fmpositions.put("top", "Top");
fmpositions.put("bottom", "Bottom");
fmpositions.put("left", "Left");
fmpositions.put("right", "Right");
final LookAndFeelInfo[] plaf = UIManager.getInstalledLookAndFeels();
final String sysLafClass = UIManager.getSystemLookAndFeelClassName();
lafs.put("Native", "Native");
for (LookAndFeelInfo laf : plaf) {
lafs.put(laf.getName(), laf.getName());
}
category.addSetting(new PreferencesSetting(PreferencesType.COLOUR,
"ui", "backgroundcolour", "Background colour", "Default " +
"background colour to use"));
category.addSetting(new PreferencesSetting(PreferencesType.COLOUR,
"ui", "foregroundcolour", "Foreground colour", "Default " +
"foreground colour to use"));
category.addSetting(new PreferencesSetting(PreferencesType.OPTIONALCOLOUR,
"ui", "inputbackgroundcolour", "Input background colour",
"Default background colour to use for input fields"));
category.addSetting(new PreferencesSetting(PreferencesType.OPTIONALCOLOUR,
"ui", "inputforegroundcolour", "Input foreground colour",
"Default foreground colour to use for input fields"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"general", "showcolourdialog", "Show colour dialog",
"Show colour picker dialog when using colour control codes?"));
category.addSetting(new PreferencesSetting("ui", "lookandfeel",
"Look and feel", "The Java look and feel to use",
lafs));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"ui", "antialias", "System anti-alias",
"Anti-alias all fonts?").setRestartNeeded());
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"ui", "maximisewindows", "Auto-maximise windows",
"Automatically maximise newly opened windows?"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"ui", "shownickcoloursintext", "Show nick colours in text area",
"Show nickname colours in text areas?"));
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"ui", "shownickcoloursinnicklist", "Show nick colours in nicklists",
"Show nickname colours in channel nicklists?"));
category.addSetting(new PreferencesSetting("ui", "framemanager",
"Window manager", "Which window manager should be used?",
framemanagers).setRestartNeeded());
category.addSetting(new PreferencesSetting("ui", "framemanagerPosition",
"Window manager position", "Where should the window " +
"manager be positioned?", fmpositions).setRestartNeeded());
category.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
"ui", "stylelinks", "Style links", "Style links in text areas"));
addThemesCategory(category);
addNicklistCategory(category);
addTreeviewCategory(category);
addCategory(category);
}
|
diff --git a/src/main/com/deftlabs/lock/mongo/impl/LockState.java b/src/main/com/deftlabs/lock/mongo/impl/LockState.java
index 423d148..7d29047 100644
--- a/src/main/com/deftlabs/lock/mongo/impl/LockState.java
+++ b/src/main/com/deftlabs/lock/mongo/impl/LockState.java
@@ -1,41 +1,41 @@
/**
* Copyright 2011, Deft Labs.
*
* 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.deftlabs.lock.mongo.impl;
/**
* The lock states.
*/
enum LockState {
LOCKED("locked"),
UNLOCKED("unlocked");
private LockState(final String pCode) { _code = pCode; }
private final String _code;
public String code() { return _code; }
public boolean isLocked() { return this == LOCKED; }
public boolean isUnlocked() { return this == UNLOCKED; }
public static LockState findByCode(final String pCode) {
if (pCode == null) throw new IllegalArgumentException("Invalid lock state code: " + pCode);
- for (final LockState s : values()) if (s.equals(pCode)) return s;
+ for (final LockState s : values()) if (s._code.equals(pCode)) return s;
throw new IllegalArgumentException("Invalid lock state code: " + pCode);
}
}
| true | true | public static LockState findByCode(final String pCode) {
if (pCode == null) throw new IllegalArgumentException("Invalid lock state code: " + pCode);
for (final LockState s : values()) if (s.equals(pCode)) return s;
throw new IllegalArgumentException("Invalid lock state code: " + pCode);
}
| public static LockState findByCode(final String pCode) {
if (pCode == null) throw new IllegalArgumentException("Invalid lock state code: " + pCode);
for (final LockState s : values()) if (s._code.equals(pCode)) return s;
throw new IllegalArgumentException("Invalid lock state code: " + pCode);
}
|
diff --git a/test/com/pacman/entity/maze/BlockFactoryTest.java b/test/com/pacman/entity/maze/BlockFactoryTest.java
index 443e2f1..1011a65 100644
--- a/test/com/pacman/entity/maze/BlockFactoryTest.java
+++ b/test/com/pacman/entity/maze/BlockFactoryTest.java
@@ -1,33 +1,38 @@
package com.pacman.entity.maze;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.util.List;
import org.junit.Test;
import org.newdawn.slick.tiled.TiledMap;
public class BlockFactoryTest {
@Test
public void shouldCreateBlocksFromTiledMap() throws Exception {
BlockFactory factory = new BlockFactory();
TiledMap map = mock(TiledMap.class);
+ Integer firstTileId = 1;
+ Integer secondTileId = 2;
when(map.getTileWidth()).thenReturn(10);
when(map.getWidth()).thenReturn(1);
- when(map.getHeight()).thenReturn(1);
- when(map.getTileId(0, 0, 0)).thenReturn(1);
+ when(map.getHeight()).thenReturn(secondTileId);
+ when(map.getTileId(0, 0, 0)).thenReturn(firstTileId);
+ when(map.getTileId(0, 1, 0)).thenReturn(secondTileId);
+ when(map.getTileProperty(firstTileId, "collidable", "false")).thenReturn("true");
+ when(map.getTileProperty(secondTileId, "collidable", "false")).thenReturn("false");
List<Block> blocks = factory.from(map);
verify(map).getTileWidth();
verify(map).getWidth();
verify(map).getHeight();
verify(map, never()).getTileHeight();
assertEquals(1, blocks.size());
}
}
| false | true | public void shouldCreateBlocksFromTiledMap() throws Exception {
BlockFactory factory = new BlockFactory();
TiledMap map = mock(TiledMap.class);
when(map.getTileWidth()).thenReturn(10);
when(map.getWidth()).thenReturn(1);
when(map.getHeight()).thenReturn(1);
when(map.getTileId(0, 0, 0)).thenReturn(1);
List<Block> blocks = factory.from(map);
verify(map).getTileWidth();
verify(map).getWidth();
verify(map).getHeight();
verify(map, never()).getTileHeight();
assertEquals(1, blocks.size());
}
| public void shouldCreateBlocksFromTiledMap() throws Exception {
BlockFactory factory = new BlockFactory();
TiledMap map = mock(TiledMap.class);
Integer firstTileId = 1;
Integer secondTileId = 2;
when(map.getTileWidth()).thenReturn(10);
when(map.getWidth()).thenReturn(1);
when(map.getHeight()).thenReturn(secondTileId);
when(map.getTileId(0, 0, 0)).thenReturn(firstTileId);
when(map.getTileId(0, 1, 0)).thenReturn(secondTileId);
when(map.getTileProperty(firstTileId, "collidable", "false")).thenReturn("true");
when(map.getTileProperty(secondTileId, "collidable", "false")).thenReturn("false");
List<Block> blocks = factory.from(map);
verify(map).getTileWidth();
verify(map).getWidth();
verify(map).getHeight();
verify(map, never()).getTileHeight();
assertEquals(1, blocks.size());
}
|
diff --git a/shoppinglist/ShoppingList/src/org/openintents/shopping/ui/ShoppingActivity.java b/shoppinglist/ShoppingList/src/org/openintents/shopping/ui/ShoppingActivity.java
index 30ab8a33..5886f19a 100644
--- a/shoppinglist/ShoppingList/src/org/openintents/shopping/ui/ShoppingActivity.java
+++ b/shoppinglist/ShoppingList/src/org/openintents/shopping/ui/ShoppingActivity.java
@@ -1,2726 +1,2726 @@
/*
* Copyright (C) 2007-2010 OpenIntents.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openintents.shopping.ui;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import org.openintents.OpenIntents;
import org.openintents.distribution.DistributionLibraryFragmentActivity;
import org.openintents.intents.GeneralIntents;
import org.openintents.intents.ShoppingListIntents;
import org.openintents.provider.Alert;
import org.openintents.provider.Location.Locations;
import org.openintents.shopping.LogConstants;
import org.openintents.shopping.R;
import org.openintents.shopping.library.provider.ShoppingContract;
import org.openintents.shopping.library.provider.ShoppingContract.Contains;
import org.openintents.shopping.library.provider.ShoppingContract.ContainsFull;
import org.openintents.shopping.library.provider.ShoppingContract.Items;
import org.openintents.shopping.library.provider.ShoppingContract.Lists;
import org.openintents.shopping.library.provider.ShoppingContract.Status;
import org.openintents.shopping.library.util.PriceConverter;
import org.openintents.shopping.library.util.ShoppingUtils;
import org.openintents.shopping.ui.dialog.DialogActionListener;
import org.openintents.shopping.ui.dialog.EditItemDialog;
import org.openintents.shopping.ui.dialog.NewListDialog;
import org.openintents.shopping.ui.dialog.RenameListDialog;
import org.openintents.shopping.ui.dialog.ThemeDialog;
import org.openintents.shopping.ui.dialog.ThemeDialog.ThemeDialogListener;
import org.openintents.shopping.ui.tablet.ShoppingListFilterFragment;
import org.openintents.shopping.ui.widget.ShoppingItemsView;
import org.openintents.shopping.ui.widget.ShoppingItemsView.ActionBarListener;
import org.openintents.shopping.ui.widget.ShoppingItemsView.DragListener;
import org.openintents.shopping.ui.widget.ShoppingItemsView.DropListener;
import org.openintents.shopping.ui.widget.ShoppingItemsView.OnCustomClickListener;
import org.openintents.util.MenuIntentOptionsWithIcons;
import org.openintents.util.ShakeSensorListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.ContentObserver;
import android.database.Cursor;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v2.os.Build;
import android.support.v2.view.MenuCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.FilterQueryProvider;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
/**
*
* Displays a shopping list.
*
*/
public class ShoppingActivity extends DistributionLibraryFragmentActivity implements
ThemeDialogListener, OnCustomClickListener,
ActionBarListener { // implements
// AdapterView.OnItemClickListener
// {
/**
* TAG for logging.
*/
private static final String TAG = "ShoppingActivity";
private static final boolean debug = false || LogConstants.debug;
public class MyGestureDetector extends SimpleOnGestureListener {
private static final float DISTANCE_DIP = 16.0f;
private static final float PATH_DIP = 40.0f;
// convert dip measurements to pixels
final float scale = getResources().getDisplayMetrics().density;
int scaledDistance = (int) (DISTANCE_DIP * scale + 0.5f);
int scaledPath = (int) (PATH_DIP * scale + 0.5f);
// For more information about touch gestures and screens support, see:
// http://developer.android.com/resources/articles/gestures.html
// http://developer.android.com/reference/android/gesture/package-summary.html
// http://developer.android.com/guide/practices/screens_support.html try {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (e1 == null || e2 == null) return false;
try {
DisplayMetrics dm = getResources().getDisplayMetrics();
int REL_SWIPE_MIN_DISTANCE = (int)(SWIPE_MIN_DISTANCE * dm.densityDpi / 160.0f);
int REL_SWIPE_MAX_OFF_PATH = (int)(SWIPE_MAX_OFF_PATH * dm.densityDpi / 160.0f);
int REL_SWIPE_THRESHOLD_VELOCITY = (int)(SWIPE_THRESHOLD_VELOCITY * dm.densityDpi / 160.0f);
if (Math.abs(e1.getY() - e2.getY()) > REL_SWIPE_MAX_OFF_PATH)
return false;
// right to left swipe
if(e1.getX() - e2.getX() > REL_SWIPE_MIN_DISTANCE && Math.abs(velocityX) > REL_SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(ShoppingActivity.this, "Left Swipe", Toast.LENGTH_SHORT).show();
changeList(-1);
} else if (e2.getX() - e1.getX() > REL_SWIPE_MIN_DISTANCE && Math.abs(velocityX) > REL_SWIPE_THRESHOLD_VELOCITY) {
Toast.makeText(ShoppingActivity.this, "Right Swipe", Toast.LENGTH_SHORT).show();
changeList(1);
}
} catch (Exception e) {
// nothing
}
return false;
}
}
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private static final int MENU_NEW_LIST = Menu.FIRST;
private static final int MENU_CLEAN_UP_LIST = Menu.FIRST + 1;
private static final int MENU_DELETE_LIST = Menu.FIRST + 2;
private static final int MENU_SHARE = Menu.FIRST + 3;
private static final int MENU_THEME = Menu.FIRST + 4;
private static final int MENU_ADD_LOCATION_ALERT = Menu.FIRST + 5;
private static final int MENU_RENAME_LIST = Menu.FIRST + 6;
private static final int MENU_MARK_ITEM = Menu.FIRST + 7;
private static final int MENU_EDIT_ITEM = Menu.FIRST + 8; // includes rename
private static final int MENU_DELETE_ITEM = Menu.FIRST + 9;
private static final int MENU_INSERT_FROM_EXTRAS = Menu.FIRST + 10; // insert
// from
// string
// array
// in
// intent
// extras
// TODO: Implement the following menu items
// private static final int MENU_EDIT_LIST = Menu.FIRST + 12; // includes
// rename
// private static final int MENU_SORT = Menu.FIRST + 13; // sort
// alphabetically
// or modified
private static final int MENU_PICK_ITEMS = Menu.FIRST + 14; // pick from
// previously
// used items
// TODO: Implement "select list" action
// that can be called by other programs.
// private static final int MENU_SELECT_LIST = Menu.FIRST + 15; // select a
// shopping list
private static final int MENU_PREFERENCES = Menu.FIRST + 17;
private static final int MENU_SEND = Menu.FIRST + 18;
private static final int MENU_REMOVE_ITEM_FROM_LIST = Menu.FIRST + 19;
private static final int MENU_MOVE_ITEM = Menu.FIRST + 20;
private static final int MENU_MARK_ALL_ITEMS = Menu.FIRST + 21;
private static final int MENU_ITEM_STORES = Menu.FIRST + 22;
private static final int MENU_DISTRIBUTION_START = Menu.FIRST + 100; // MUST
// BE
// LAST
private static final int DIALOG_ABOUT = 1;
// private static final int DIALOG_TEXT_ENTRY = 2;
private static final int DIALOG_NEW_LIST = 2;
private static final int DIALOG_RENAME_LIST = 3;
private static final int DIALOG_EDIT_ITEM = 4;
private static final int DIALOG_DELETE_ITEM = 5;
private static final int DIALOG_THEME = 6;
private static final int DIALOG_DISTRIBUTION_START = 100; // MUST BE LAST
private static final int REQUEST_CODE_CATEGORY_ALTERNATIVE = 1;
private static final int REQUEST_PICK_LIST = 2;
/**
* The main activity.
*
* Displays the shopping list that was used last time.
*/
private static final int STATE_MAIN = 0;
/**
* VIEW action on a item/list URI.
*/
private static final int STATE_VIEW_LIST = 1;
/**
* PICK action on an dir/item URI.
*/
private static final int STATE_PICK_ITEM = 2;
/**
* GET_CONTENT action on an item/item URI.
*/
private static final int STATE_GET_CONTENT_ITEM = 3;
/**
* Current state
*/
private int mState;
/*
* Value of PreferenceActivity.updateCount last time we
* called fillItems().
*/
private int lastAppliedPrefChange = -1;
/**
* mode: separate dialog to add items from existing list
*/
public static final int MODE_PICK_ITEMS_DLG = 3;
/**
* mode: add items from existing list
*/
public static final int MODE_ADD_ITEMS = 2;
/**
* mode: I am in the shop
*/
public static final int MODE_IN_SHOP = 1;
/**
* URI of current list
*/
private Uri mListUri;
/**
* URI of selected item
*/
private Uri mItemUri;
/**
* Definition of the requestCode for the subactivity.
*/
static final private int SUBACTIVITY_LIST_SHARE_SETTINGS = 0;
/**
* Definition for message handler:
*/
static final private int MESSAGE_UPDATE_CURSORS = 1;
/**
* Update interval for automatic requires.
*
* (Workaround since ContentObserver does not work.)
*/
private int mUpdateInterval;
private boolean mUpdating;
/**
* The items to add to the shopping list.
*
* Received as a string array list in the intent extras.
*/
private List<String> mExtraItems;
/**
* The quantities for items to add to the shopping list.
*
* Received as a string array list in the intent extras.
*/
private List<String> mExtraQuantities;
/**
* The prices for items to add to the shopping list.
*
* Received as a string array list in the intent extras.
*/
private List<String> mExtraPrices;
/**
* The barcodes for items to add to the shopping list.
*
* Received as a string array list in the intent extras.
*/
private List<String> mExtraBarcodes;
/**
* The list URI received together with intent extras.
*/
private Uri mExtraListUri;
/**
* Private members connected to list of shopping lists
*/
// Temp - making it generic for tablet compatibility
private AdapterView mShoppingListsView;
private Cursor mCursorShoppingLists;
private static final String[] mStringListFilter = new String[] { Lists._ID,
Lists.NAME, Lists.IMAGE, Lists.SHARE_NAME, Lists.SHARE_CONTACTS,
Lists.SKIN_BACKGROUND };
private static final int mStringListFilterID = 0;
private static final int mStringListFilterNAME = 1;
private static final int mStringListFilterIMAGE = 2;
private static final int mStringListFilterSHARENAME = 3;
private static final int mStringListFilterSHARECONTACTS = 4;
private static final int mStringListFilterSKINBACKGROUND = 5;
private ShoppingItemsView mItemsView;
// private Cursor mCursorItems;
public static final String[] mStringItems = new String[] { ContainsFull._ID,
ContainsFull.ITEM_NAME, ContainsFull.ITEM_IMAGE,
ContainsFull.ITEM_TAGS, ContainsFull.ITEM_PRICE,
ContainsFull.QUANTITY, ContainsFull.STATUS, ContainsFull.ITEM_ID,
ContainsFull.SHARE_CREATED_BY, ContainsFull.SHARE_MODIFIED_BY,
ContainsFull.PRIORITY, ContainsFull.ITEM_HAS_NOTE,
ContainsFull.ITEM_UNITS };
static final int mStringItemsCONTAINSID = 0;
public static final int mStringItemsITEMNAME = 1;
static final int mStringItemsITEMIMAGE = 2;
public static final int mStringItemsITEMTAGS = 3;
public static final int mStringItemsITEMPRICE = 4;
public static final int mStringItemsQUANTITY = 5;
public static final int mStringItemsSTATUS = 6;
public static final int mStringItemsITEMID = 7;
private static final int mStringItemsSHARECREATEDBY = 8;
private static final int mStringItemsSHAREMODIFIEDBY = 9;
public static final int mStringItemsPRIORITY = 10;
public static final int mStringItemsITEMHASNOTE = 11;
public static final int mStringItemsITEMUNITS = 12;
private LinearLayout.LayoutParams mLayoutParamsItems;
private int mAllowedListHeight; // Height for the list allowed in this view.
private AutoCompleteTextView mEditText;
private Button mButton;
protected Context mDialogContext;
// TODO: Set up state information for onFreeze(), ...
// State data to be stored when freezing:
private final String ORIGINAL_ITEM = "original item";
// private static final String BUNDLE_TEXT_ENTRY_MENU = "text entry menu";
// private static final String BUNDLE_CURSOR_ITEMS_POSITION =
// "cursor items position";
private static final String BUNDLE_ITEM_URI = "item uri";
private static final String BUNDLE_RELATION_URI = "relation_uri";
private static final String BUNDLE_MODE = "mode";
// Skins --------------------------
// private int mTextEntryMenu;
/*
* NOTE: mItemsCursor is used for autocomplete Textview, mCursorItems is for
* items in list
*/
private Cursor mItemsCursor;
private static boolean usingListSpinner() {
// TODO switch layout on screen size, not sdk versions
return (Build.VERSION.SDK_INT<Build.VERSION_CODES.HONEYCOMB);
}
/**
* Remember position for screen orientation change.
*/
// int mEditItemPosition = -1;
// public int mPriceVisibility;
// private int mTagsVisibility;
private SensorManager mSensorManager;
private SensorListener mMySensorListener = new ShakeSensorListener() {
@Override
public void onShake() {
// Provide some visual feedback.
Animation shake = AnimationUtils.loadAnimation(
ShoppingActivity.this, R.anim.shake);
findViewById(R.id.background).startAnimation(shake);
cleanupList();
}
};
/**
* isActive is true only after onResume() and before onPause().
*/
private boolean mIsActive = false;
/**
* Whether to use the sensor for shake.
*/
private boolean mUseSensor = false;
private Uri mRelationUri;
private int mMoveItemPosition;
private EditItemDialog.FieldType mEditItemFocusField = EditItemDialog.FieldType.ITEMNAME;
private GestureDetector mGestureDetector;
private View.OnTouchListener mGestureListener;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
if (debug)
Log.d(TAG, "Shopping list onCreate()");
mDistribution.setFirst(MENU_DISTRIBUTION_START,
DIALOG_DISTRIBUTION_START);
// Check whether EULA has been accepted
// or information about new version can be presented.
if (mDistribution.showEulaOrNewVersion()) {
return;
}
setContentView(R.layout.activity_shopping);
// mEditItemPosition = -1;
// Automatic requeries (once a second)
mUpdateInterval = 2000;
mUpdating = false;
// General Uris:
mListUri = ShoppingContract.Lists.CONTENT_URI;
mItemUri = ShoppingContract.Items.CONTENT_URI;
int defaultShoppingList = initFromPreferences();
// Handle the calling intent
final Intent intent = getIntent();
final String type = intent.resolveType(this);
final String action = intent.getAction();
if (action == null) {
// Main action
mState = STATE_MAIN;
mListUri = Uri.withAppendedPath(ShoppingContract.Lists.CONTENT_URI, ""
+ defaultShoppingList);
intent.setData(mListUri);
} else if (Intent.ACTION_MAIN.equals(action)) {
// Main action
mState = STATE_MAIN;
mListUri = Uri.withAppendedPath(ShoppingContract.Lists.CONTENT_URI, ""
+ defaultShoppingList);
intent.setData(mListUri);
} else if (Intent.ACTION_VIEW.equals(action)) {
mState = STATE_VIEW_LIST;
if (ShoppingContract.ITEM_TYPE.equals(type)) {
mListUri = ShoppingUtils.getListForItem(this, intent.getData()
.getLastPathSegment());
} else if (intent.getData() != null) {
mListUri = intent.getData();
}
} else if (Intent.ACTION_INSERT.equals(action)) {
// TODO: insert items from extras ????
mState = STATE_VIEW_LIST;
if (ShoppingContract.ITEM_TYPE.equals(type)) {
mListUri = ShoppingUtils.getListForItem(
getApplicationContext(), intent.getData()
.getLastPathSegment());
} else if (intent.getData() != null) {
mListUri = intent.getData();
}
} else if (Intent.ACTION_PICK.equals(action)) {
mState = STATE_PICK_ITEM;
mListUri = Uri.withAppendedPath(ShoppingContract.Lists.CONTENT_URI, ""
+ defaultShoppingList);
} else if (Intent.ACTION_GET_CONTENT.equals(action)) {
mState = STATE_GET_CONTENT_ITEM;
mListUri = Uri.withAppendedPath(ShoppingContract.Lists.CONTENT_URI, ""
+ defaultShoppingList);
} else if (GeneralIntents.ACTION_INSERT_FROM_EXTRAS.equals(action)) {
if (ShoppingListIntents.TYPE_STRING_ARRAYLIST_SHOPPING.equals(type)) {
/*
* Need to insert new items from a string array in the intent
* extras Use main action but add an item to the options menu
* for adding extra items
*/
getShoppingExtras(intent);
mState = STATE_MAIN;
mListUri = Uri.withAppendedPath(ShoppingContract.Lists.CONTENT_URI, ""
+ defaultShoppingList);
intent.setData(mListUri);
} else if (intent.getDataString().startsWith(
ShoppingContract.Lists.CONTENT_URI.toString())) {
// Somewhat quick fix to pass data from ShoppingListsActivity to
// this activity.
// We received a valid shopping list URI:
mListUri = intent.getData();
getShoppingExtras(intent);
mState = STATE_MAIN;
intent.setData(mListUri);
}
} else {
// Unknown action.
Log.e(TAG, "Shopping: Unknown action, exiting");
finish();
return;
}
// hook up all buttons, lists, edit text:
createView();
// populate the lists
fillListFilter();
// Get last part of URI:
int selectList;
try {
selectList = Integer.parseInt(mListUri.getLastPathSegment());
} catch (NumberFormatException e) {
selectList = defaultShoppingList;
}
// select the default shopping list at the beginning:
setSelectedListId(selectList);
if (icicle != null) {
String prevText = icicle.getString(ORIGINAL_ITEM);
if (prevText != null) {
mEditText.setTextKeepState(prevText);
}
// mTextEntryMenu = icicle.getInt(BUNDLE_TEXT_ENTRY_MENU);
// mEditItemPosition = icicle.getInt(BUNDLE_CURSOR_ITEMS_POSITION);
mItemUri = Uri.parse(icicle.getString(BUNDLE_ITEM_URI));
if (icicle.containsKey(BUNDLE_RELATION_URI)) {
mRelationUri = Uri.parse(icicle.getString(BUNDLE_RELATION_URI));
}
mItemsView.mMode = icicle.getInt(BUNDLE_MODE);
}
// set focus to the edit line:
mEditText.requestFocus();
// TODO remove initFromPreferences from onCreate
// we need it in resume to update after settings have changed
initFromPreferences();
// now update title and fill all items
onModeChanged();
mItemsView.setActionBarListener(this);
}
private int initFromPreferences() {
boolean loadLastUsed = true;
SharedPreferences sp = getSharedPreferences(
"org.openintents.shopping_preferences", MODE_PRIVATE);
// Always load last list used. This setting got abandoned.
if (false) {
// if set to "last used", override the default list.
loadLastUsed = sp.getBoolean(
PreferenceActivity.PREFS_LOADLASTUSED,
PreferenceActivity.PREFS_LOADLASTUSED_DEFAULT);
if (debug) Log.d(TAG, "load last used ?" + loadLastUsed);
}
int defaultShoppingList = 1;
if (loadLastUsed) {
defaultShoppingList = sp.getInt(PreferenceActivity.PREFS_LASTUSED,
1);
if (mItemsView != null) {
// UGLY WORKAROUND:
// On screen orientation changes, fillItems() is called twice.
// That is why we have to set the list position twice.
mItemsView.mUpdateLastListPosition = 2;
mItemsView.mLastListPosition = sp.getInt(PreferenceActivity.PREFS_LASTLIST_POSITION, 0);
mItemsView.mLastListTop = sp.getInt(PreferenceActivity.PREFS_LASTLIST_TOP, 0);
if (debug) Log.d(TAG, "Load list position: pos: " + mItemsView.mLastListPosition
+ ", top: " + mItemsView.mLastListTop);
}
} else {
defaultShoppingList = (int) ShoppingUtils.getDefaultList(this);
}
if (mItemsView != null) {
if (sp.getBoolean(PreferenceActivity.PREFS_SHOW_PRICE,
PreferenceActivity.PREFS_SHOW_PRICE_DEFAULT)) {
mItemsView.mPriceVisibility = View.VISIBLE;
} else {
mItemsView.mPriceVisibility = View.GONE;
}
if (sp.getBoolean(PreferenceActivity.PREFS_SHOW_TAGS,
PreferenceActivity.PREFS_SHOW_TAGS_DEFAULT)) {
mItemsView.mTagsVisibility = View.VISIBLE;
} else {
mItemsView.mTagsVisibility = View.GONE;
}
if (sp.getBoolean(PreferenceActivity.PREFS_SHOW_QUANTITY,
PreferenceActivity.PREFS_SHOW_QUANTITY_DEFAULT)) {
mItemsView.mQuantityVisibility = View.VISIBLE;
} else {
mItemsView.mQuantityVisibility = View.GONE;
}
if (sp.getBoolean(PreferenceActivity.PREFS_SHOW_UNITS,
PreferenceActivity.PREFS_SHOW_UNITS_DEFAULT)) {
mItemsView.mUnitsVisibility = View.VISIBLE;
} else {
mItemsView.mUnitsVisibility = View.GONE;
}
if (sp.getBoolean(PreferenceActivity.PREFS_SHOW_PRIORITY,
PreferenceActivity.PREFS_SHOW_PRIORITY_DEFAULT)) {
mItemsView.mPriorityVisibility = View.VISIBLE;
} else {
mItemsView.mPriorityVisibility = View.GONE;
}
}
mUseSensor = sp.getBoolean(PreferenceActivity.PREFS_SHAKE,
PreferenceActivity.PREFS_SHAKE_DEFAULT);
return defaultShoppingList;
}
private void registerSensor() {
if (!mUseSensor) {
// Don't use sensors
return;
}
if (mItemsView.mMode == MODE_IN_SHOP) {
if (mSensorManager == null) {
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
}
mSensorManager.registerListener(mMySensorListener,
SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_UI);
}
}
private void unregisterSensor() {
if (mSensorManager != null) {
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mSensorManager.unregisterListener(mMySensorListener);
}
}
@Override
protected void onResume() {
if (debug)
Log.i(TAG, "Shopping list onResume() 1");
super.onResume();
if (debug)
Log.i(TAG, "Shopping list onResume() 2");
// Reload preferences, in case something changed
initFromPreferences();
mIsActive = true;
getSelectedListId();
setListTheme(loadListTheme());
applyListTheme();
mItemsView.onResume();
updateTitle();
// TODO fling disabled for release 1.3.0
// mGestureDetector = new GestureDetector(new MyGestureDetector());
// mGestureListener = new OnTouchListener() {
// public boolean onTouch(View view, MotionEvent e) {
// if (mGestureDetector.onTouchEvent(e)) {
// return true;
// }
// return false;
// }
// };
// mListItemsView.setOnTouchListener(mGestureListener);
mEditText
.setKeyListener(PreferenceActivity
.getCapitalizationKeyListenerFromPrefs(getApplicationContext()));
if (!mUpdating) {
mUpdating = true;
// mHandler.sendMessageDelayed(mHandler.obtainMessage(
// MESSAGE_UPDATE_CURSORS), mUpdateInterval);
}
// OnResume can be called when exiting PreferenceActivity, in
// which case we might need to refresh the list depending on
// which settings were changed. We could be smarter about this,
// but for now refresh if /any/ pref has changed.
//
// In phone mode list id is generally not set by now, and there will
// soon be a fillItems call triggered by updating the list selector.
// However when the embedded list selector is not being used, now might
// be a good time to update for pending
// preference changes.
if (!usingListSpinner()) {
fillItems(true);
}
// TODO ???
/*
* // Register intent receiver for refresh intents: IntentFilter
* intentfilter = new IntentFilter(OpenIntents.REFRESH_ACTION);
* registerReceiver(mIntentReceiver, intentfilter);
*/
// Items received through intents are added in
// fillItems().
registerSensor();
if (debug)
Log.i(TAG, "Shopping list onResume() finished");
}
private void updateTitle() {
// Modify our overall title depending on the mode we are running in.
if (mState == STATE_MAIN || mState == STATE_VIEW_LIST) {
if (PreferenceActivity.getPickItemsInListFromPrefs(getApplicationContext())) {
// 2 different modes
if (mItemsView.mMode == MODE_IN_SHOP) {
setTitle(getString(R.string.shopping_title,
getCurrentListName()));
registerSensor();
} else {
setTitle(getString(R.string.pick_items_titel,
getCurrentListName()));
unregisterSensor();
}
} else {
// Only one mode: "Pick items using dialog"
// App name is default
setTitle(getText(R.string.app_name));
}
} else if ((mState == STATE_PICK_ITEM)
|| (mState == STATE_GET_CONTENT_ITEM)) {
setTitle(getText(R.string.pick_item));
setTitleColor(0xFFAAAAFF);
}
// also update the button label
updateButton();
}
private void updateButton() {
if (mItemsView.mMode == MODE_ADD_ITEMS) {
String newItem = mEditText.getText().toString();
if (TextUtils.isEmpty(newItem)) {
// If in "add items" mode and the text field is empty,
// set the button text to "Shopping"
mButton.setText(R.string.menu_start_shopping);
} else {
mButton.setText(R.string.add);
}
} else {
mButton.setText(R.string.add);
}
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (debug)
Log.i(TAG, "Shopping list onPause()");
if (debug)
Log.i(TAG, "Spinner: onPause: " + mIsActive);
mIsActive = false;
if (debug)
Log.i(TAG, "Spinner: onPause: " + mIsActive);
unregisterSensor();
// Save position and pixel position of first visible item
// of current shopping list
int listposition = mItemsView.getFirstVisiblePosition();
View v = mItemsView.getChildAt(0);
int listtop = (v == null) ? 0 : v.getTop();
if (debug) Log.d(TAG, "Save list position: pos: " + listposition
+ ", top: " + listtop);
SharedPreferences sp = getSharedPreferences(
"org.openintents.shopping_preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt(PreferenceActivity.PREFS_LASTUSED, new Long(
getSelectedListId()).intValue());
editor.putInt(PreferenceActivity.PREFS_LASTLIST_POSITION, listposition);
editor.putInt(PreferenceActivity.PREFS_LASTLIST_TOP, listtop);
editor.commit();
// TODO ???
/*
* // Unregister refresh intent receiver
* unregisterReceiver(mIntentReceiver);
*
*/
mItemsView.onPause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (debug)
Log.i(TAG, "Shopping list onSaveInstanceState()");
// Save original text from edit box
String s = mEditText.getText().toString();
outState.putString(ORIGINAL_ITEM, s);
outState.putString(BUNDLE_ITEM_URI, mItemUri.toString());
if (mRelationUri != null) {
outState.putString(BUNDLE_RELATION_URI, mRelationUri.toString());
}
outState.putInt(BUNDLE_MODE, mItemsView.mMode);
mUpdating = false;
// after items have been added through an "insert from extras" the
// action name should be different to avoid duplicate inserts e.g. on
// rotation.
if (mExtraItems == null
&& GeneralIntents.ACTION_INSERT_FROM_EXTRAS.equals(getIntent()
.getAction())) {
setIntent(getIntent().setAction(Intent.ACTION_VIEW));
}
}
/**
* Hook up buttons, lists, and edittext with functionality.
*/
private void createView() {
//Temp-create either Spinner or List based upon the Display
createList();
mEditText = (AutoCompleteTextView) findViewById(R.id.autocomplete_add_item);
if (mItemsCursor != null) {
if (debug)
Log.d(TAG, "mItemsCursor managedQuery 1");
stopManagingCursor(mItemsCursor);
mItemsCursor.close();
mItemsCursor = null;
}
mItemsCursor = managedQuery(Items.CONTENT_URI, new String[] {
Items._ID, Items.NAME }, null, null, "name desc");
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_dropdown_item_1line, mItemsCursor,
new String[] { Items.NAME }, new int[] { android.R.id.text1 });
adapter.setStringConversionColumn(1);
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
if (mItemsCursor != null) {
if (debug)
Log.d(TAG, "mItemsCursor managedQuery 2");
stopManagingCursor(mItemsCursor);
// For some reason, closing the cursor seems to post
// an invalidation on the background thread and a crash...
// so we keep it open.
// mItemsCursor.close();
// mItemsCursor = null;
}
mItemsCursor = managedQuery(Items.CONTENT_URI, new String[] {
- Items._ID, Items.NAME }, "upper(name) like ?",
+ Items._ID, Items.NAME }, "upper(name) like upper(?)",
new String[] { "%"
+ (constraint == null ? "" : constraint
- .toString().toUpperCase()) + "%" },
+ .toString()) + "%" },
"name desc");
return mItemsCursor;
}
});
mEditText.setAdapter(adapter);
mEditText.setOnKeyListener(new OnKeyListener() {
private int mLastKeyAction = KeyEvent.ACTION_UP;
public boolean onKey(View v, int keyCode, KeyEvent key) {
// Log.i(TAG, "KeyCode: " + keyCode
// + " =?= "
// +Integer.parseInt(getString(R.string.key_return)) );
// Shortcut: Instead of pressing the button,
// one can also press the "Enter" key.
if (debug)
Log.i(TAG, "Key action: " + key.getAction());
if (debug)
Log.i(TAG, "Key code: " + keyCode);
if (keyCode == KeyEvent.KEYCODE_ENTER) {
if (mEditText.isPopupShowing()) {
mEditText.performCompletion();
}
// long key press might cause call of duplicate onKey events
// with ACTION_DOWN
// this would result in inserting an item and showing the
// pick list
if (key.getAction() == KeyEvent.ACTION_DOWN
&& mLastKeyAction == KeyEvent.ACTION_UP) {
insertNewItem();
}
mLastKeyAction = key.getAction();
return true;
};
return false;
}
});
mEditText.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
if (mItemsView.mMode == MODE_ADD_ITEMS) {
// small optimization: Only care about updating
// the button label on each key pressed if we
// are in "add items" mode.
updateButton();
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
mButton = (Button) findViewById(R.id.button_add_item);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
insertNewItem();
}
});
mButton.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent();
intent.setData(mListUri);
intent.setClassName("org.openintents.barcodescanner", "org.openintents.barcodescanner.BarcodeScanner");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.v(TAG, "barcode scanner not found");
return false;
}
return true;
}
});
mLayoutParamsItems = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
mItemsView = (ShoppingItemsView) findViewById(R.id.list_items);
mItemsView.setThemedBackground(findViewById(R.id.background));
mItemsView.setCustomClickListener(this);
mItemsView.setItemsCanFocus(true);
mItemsView.setDragListener(new DragListener() {
@Override
public void drag(int from, int to) {
if (debug) Log.v("DRAG", "" + from + "/" + to);
}
});
mItemsView.setDropListener(new DropListener() {
@Override
public void drop(int from, int to) {
if (debug) Log.v("DRAG", "" + from + "/" + to);
}
});
TextView tv = (TextView) findViewById(R.id.total_1);
mItemsView.setTotalCheckedTextView(tv);
tv = (TextView) findViewById(R.id.total_2);
mItemsView.setTotalTextView(tv);
tv = (TextView) findViewById(R.id.total_3);
mItemsView.setPrioritySubtotalTextView(tv);
tv = (TextView) findViewById(R.id.count);
mItemsView.setCountTextView(tv);
mItemsView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int pos, long id) {
Cursor c = (Cursor) parent.getItemAtPosition(pos);
onCustomClick(c, pos, EditItemDialog.FieldType.ITEMNAME);
// DO NOT CLOSE THIS CURSOR - IT IS A MANAGED ONE.
// ---- c.close();
}
});
mItemsView
.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu contextmenu,
View view, ContextMenuInfo info) {
contextmenu.add(0, MENU_EDIT_ITEM, 0,
R.string.menu_edit_item).setShortcut('1', 'e');
contextmenu.add(0, MENU_MARK_ITEM, 0,
R.string.menu_mark_item).setShortcut('2', 'm');
contextmenu.add(0, MENU_ITEM_STORES, 0,
R.string.menu_item_stores).setShortcut('3', 's');
contextmenu.add(0, MENU_REMOVE_ITEM_FROM_LIST, 0,
R.string.menu_remove_item)
.setShortcut('3', 'r');
contextmenu.add(0, MENU_DELETE_ITEM, 0,
R.string.menu_delete_item)
.setShortcut('4', 'd');
contextmenu.add(0, MENU_MOVE_ITEM, 0,
R.string.menu_move_item).setShortcut('5', 'l');
}
});
}
private void createList() {
// TODO switch layout on screen size, not sdk versions
if(!usingListSpinner()){
mShoppingListsView = (ListView) findViewById(android.R.id.list);
((ListView)mShoppingListsView)
.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView parent, View v,
int position, long id) {
if (debug)
Log.d(TAG, "ListView: onItemSelected");
// Update list cursor:
getSelectedListId();
// Set the theme based on the selected list:
setListTheme(loadListTheme());
// If it's the same list we had before, requery only
// if a preference has changed since then.
fillItems(id == mItemsView.getListId());
// Apply the theme after the list has been filled:
applyListTheme();
updateTitle();
((ListView) mShoppingListsView).setItemChecked(position,true);
}
public void onNothingSelected(AdapterView arg0) {
if (debug)
Log.d(TAG, "Listview: onNothingSelected: "
+ mIsActive);
if (mIsActive) {
fillItems(false);
}
}
});
}else{
mShoppingListsView = (Spinner) findViewById(R.id.spinner_listfilter);
((Spinner)mShoppingListsView)
.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView parent, View v,
int position, long id) {
if (debug)
Log.d(TAG, "Spinner: onItemSelected");
// Update list cursor:
getSelectedListId();
// Set the theme based on the selected list:
setListTheme(loadListTheme());
// If it's the same list we had before, requery only
// if a preference has changed since then.
fillItems(id == mItemsView.getListId());
updateTitle();
// Apply the theme after the list has been filled:
applyListTheme();
}
public void onNothingSelected(AdapterView arg0) {
if (debug)
Log.d(TAG, "Spinner: onNothingSelected: "
+ mIsActive);
if (mIsActive) {
fillItems(false);
}
}
});
}
}
public void onCustomClick(Cursor c, int pos, EditItemDialog.FieldType field) {
if (mState == STATE_PICK_ITEM) {
pickItem(c);
} else {
if (mItemsView.mShowCheckBox) {
// In default theme, there is an extra check box,
// so clicking on anywhere else means to edit the
// item.
if (field == EditItemDialog.FieldType.PRICE &&
PreferenceActivity.getUsingPerStorePricesFromPrefs(this))
// should really be a per-list preference
{
editItemStores(pos);
}
else
editItem(pos, field);
} else {
// For themes without a checkbox, clicking anywhere means
// to toggle the item.
mItemsView.toggleItemBought(pos);
}
}
}
/**
* Inserts new item from edit box into currently selected shopping list.
*/
private void insertNewItem() {
String newItem = mEditText.getText().toString();
// Only add if there is something to add:
if (newItem.compareTo("") != 0) {
long listId = getSelectedListId();
if (listId < 0) {
// No valid list - probably view is not active
// and no item is selected.
return;
}
mItemsView.insertNewItem(this, newItem, null, null, null, null);
mEditText.setText("");
} else {
// Open list to select item from
pickItems();
}
}
/**
* Obtain items from extras.
*/
private void getShoppingExtras(final Intent intent) {
mExtraItems = intent.getExtras().getStringArrayList(
ShoppingListIntents.EXTRA_STRING_ARRAYLIST_SHOPPING);
mExtraQuantities = intent.getExtras().getStringArrayList(
ShoppingListIntents.EXTRA_STRING_ARRAYLIST_QUANTITY);
mExtraPrices = intent.getExtras().getStringArrayList(
ShoppingListIntents.EXTRA_STRING_ARRAYLIST_PRICE);
mExtraBarcodes = intent.getExtras().getStringArrayList(
ShoppingListIntents.EXTRA_STRING_ARRAYLIST_BARCODE);
mExtraListUri = null;
if ((intent.getDataString() != null)
&& (intent.getDataString()
.startsWith(ShoppingContract.Lists.CONTENT_URI.toString()))) {
// We received a valid shopping list URI.
// Set current list to received list:
mExtraListUri = intent.getData();
if (debug)
Log.d(TAG, "Received extras for " + mExtraListUri.toString());
}
}
/**
* Inserts new item from string array received in intent extras.
*/
private void insertItemsFromExtras() {
if (mExtraItems != null) {
// Make sure we are in the correct list:
if (mExtraListUri != null) {
long listId = Long
.parseLong(mExtraListUri.getLastPathSegment());
if (debug)
Log.d(TAG, "insert items into list " + listId);
if (listId != getSelectedListId()) {
if (debug)
Log.d(TAG, "set new list: " + listId);
setSelectedListId((int) listId);
mItemsView.fillItems(this, listId);
}
}
int max = mExtraItems.size();
int maxQuantity = (mExtraQuantities != null) ? mExtraQuantities
.size() : -1;
int maxPrice = (mExtraPrices != null) ? mExtraPrices.size() : -1;
int maxBarcode = (mExtraBarcodes != null) ? mExtraBarcodes.size()
: -1;
for (int i = 0; i < max; i++) {
String item = mExtraItems.get(i);
String quantity = (i < maxQuantity) ? mExtraQuantities.get(i)
: null;
String price = (i < maxPrice) ? mExtraPrices.get(i) : null;
String barcode = (i < maxBarcode) ? mExtraBarcodes.get(i)
: null;
if (debug)
Log.d(TAG, "Add item: " + item + ", quantity: " + quantity
+ ", price: " + price + ", barcode: " + barcode);
mItemsView.insertNewItem(this, item, quantity, null, price,
barcode);
}
// delete the string array list of extra items so it can't be
// inserted twice
mExtraItems = null;
mExtraQuantities = null;
mExtraPrices = null;
mExtraBarcodes = null;
mExtraListUri = null;
} else {
Toast.makeText(this, R.string.no_items_available,
Toast.LENGTH_SHORT).show();
}
}
/**
* Picks an item and returns to calling activity.
*/
private void pickItem(Cursor c) {
long itemId = c.getLong(mStringItemsITEMID);
Uri url = ContentUris
.withAppendedId(ShoppingContract.Items.CONTENT_URI, itemId);
Intent intent = new Intent();
intent.setData(url);
setResult(RESULT_OK, intent);
finish();
}
// Menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
int MENU_ACTION_WITH_TEXT=0;
//Temp- for backward compatibility with OS 3 features
if(!usingListSpinner()){
try{
//setting the value equivalent to desired expression
//MenuItem.SHOW_AS_ACTION_IF_ROOM|MenuItem.SHOW_AS_ACTION_WITH_TEXT
java.lang.reflect.Field field=MenuItem.class.getDeclaredField("SHOW_AS_ACTION_IF_ROOM");
MENU_ACTION_WITH_TEXT=field.getInt(MenuItem.class);
field=MenuItem.class.getDeclaredField("SHOW_AS_ACTION_WITH_TEXT");
MENU_ACTION_WITH_TEXT|=field.getInt(MenuItem.class);
}catch(Exception e){
//reset value irrespective of cause
MENU_ACTION_WITH_TEXT=0;
}
}
// Add menu option for auto adding items from string array in intent
// extra if they exist
if (mExtraItems != null) {
menu.add(0, MENU_INSERT_FROM_EXTRAS, 0, R.string.menu_auto_add)
.setIcon(android.R.drawable.ic_menu_upload);
}
//Temp - Temporary item holder for compatibility framework
MenuItem item=null;
// Standard menu
item=menu.add(0, MENU_NEW_LIST, 0, R.string.new_list)
.setIcon(R.drawable.ic_menu_add_list).setShortcut('0', 'n');
MenuCompat.setShowAsAction(item, MENU_ACTION_WITH_TEXT);
item=menu.add(0, MENU_CLEAN_UP_LIST, 0, R.string.clean_up_list)
.setIcon(R.drawable.ic_menu_clean_up).setShortcut('1', 'c');
MenuCompat.setShowAsAction(item, MENU_ACTION_WITH_TEXT);
menu.add(0, MENU_PICK_ITEMS, 0, R.string.menu_pick_items)
.setIcon(android.R.drawable.ic_menu_add).setShortcut('2', 'p');
/*
* menu.add(0, MENU_SHARE, 0, R.string.share)
* .setIcon(R.drawable.contact_share001a) .setShortcut('4', 's');
*/
menu.add(0, MENU_THEME, 0, R.string.theme)
.setIcon(android.R.drawable.ic_menu_manage)
.setShortcut('3', 't');
item=menu.add(0, MENU_PREFERENCES, 0, R.string.preferences)
.setIcon(android.R.drawable.ic_menu_preferences)
.setShortcut('4', 'p');
MenuCompat.setShowAsAction(item, MENU_ACTION_WITH_TEXT);
item=menu.add(0, MENU_RENAME_LIST, 0, R.string.rename_list)
.setIcon(android.R.drawable.ic_menu_edit).setShortcut('5', 'r');
MenuCompat.setShowAsAction(item, MENU_ACTION_WITH_TEXT);
menu.add(0, MENU_DELETE_LIST, 0, R.string.delete_list)
.setIcon(android.R.drawable.ic_menu_delete)
.setShortcut('6', 'd');
MenuCompat.setShowAsAction(item, MENU_ACTION_WITH_TEXT);
menu.add(0, MENU_SEND, 0, R.string.send)
.setIcon(android.R.drawable.ic_menu_send).setShortcut('7', 's');
if (addLocationAlertPossible()) {
menu.add(0, MENU_ADD_LOCATION_ALERT, 0, R.string.shopping_add_alert)
.setIcon(android.R.drawable.ic_menu_mylocation)
.setShortcut('8', 'l');
}
menu.add(0, MENU_MARK_ALL_ITEMS, 0, R.string.mark_all_items)
.setIcon(android.R.drawable.ic_menu_agenda)
.setShortcut('9', 'm');
MenuCompat.setShowAsAction(item, MENU_ACTION_WITH_TEXT);
// Add distribution menu items last.
mDistribution.onCreateOptionsMenu(menu);
// NOTE:
// Dynamically added menu items are included in onPrepareOptionsMenu()
// instead of here!
// (Explanation see there.)
return true;
}
/**
* Check whether an application exists that handles the pick activity.
*
* @return
*/
private boolean addLocationAlertPossible() {
// Test whether intent exists for picking a location:
PackageManager pm = getPackageManager();
Intent intent = new Intent(Intent.ACTION_PICK, Locations.CONTENT_URI);
List<ResolveInfo> resolve_pick_location = pm.queryIntentActivities(
intent, PackageManager.MATCH_DEFAULT_ONLY);
/*
* for (int i = 0; i < resolve_pick_location.size(); i++) { Log.d(TAG,
* "Activity name: " + resolve_pick_location.get(i).activityInfo.name);
* }
*/
// Check whether adding alerts is possible.
intent = new Intent(Intent.ACTION_VIEW, Alert.Generic.CONTENT_URI);
List<ResolveInfo> resolve_view_alerts = pm.queryIntentActivities(
intent, PackageManager.MATCH_DEFAULT_ONLY);
boolean pick_location_possible = (resolve_pick_location.size() > 0);
boolean view_alerts_possible = (resolve_view_alerts.size() > 0);
if (debug)
Log.d(TAG, "Pick location possible: " + pick_location_possible);
if (debug)
Log.d(TAG, "View alerts possible: " + view_alerts_possible);
if (pick_location_possible && view_alerts_possible) {
return true;
}
return false;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
// TODO: Add item-specific menu items (see NotesList.java example)
// like edit, strike-through, delete.
// Add menu option for auto adding items from string array in intent
// extra if they exist
if (mExtraItems == null) {
menu.removeItem(MENU_INSERT_FROM_EXTRAS);
}
// Selected list:
long listId = getSelectedListId();
// set menu title for change mode
MenuItem menuItem = menu.findItem(MENU_PICK_ITEMS);
if (mItemsView.mMode == MODE_ADD_ITEMS) {
menuItem.setTitle(R.string.menu_start_shopping);
menuItem.setIcon(android.R.drawable.ic_menu_myplaces);
} else {
menu.findItem(MENU_PICK_ITEMS).setTitle(R.string.menu_pick_items);
menuItem.setIcon(android.R.drawable.ic_menu_add);
}
menuItem = menu.findItem(MENU_CLEAN_UP_LIST).setEnabled(
mItemsView.mNumChecked > 0);
// Delete list is possible, if we have more than one list:
// AND
// the current list is not the default list (listId == 0) - issue #105
// TODO: Later, the default list should be user-selectable,
// and not deletable.
// TODO ???
/*
* menu.setItemShown(MENU_DELETE_LIST, mCursorListFilter.count() > 1 &&
* listId != 1); // 1 is hardcoded number of default first list.
*/
// The following code is put from onCreateOptionsMenu to
// onPrepareOptionsMenu,
// because the URI of the shopping list can change if the user switches
// to another list.
// Generate any additional actions that can be performed on the
// overall list. This allows other applications to extend
// our menu with their own actions.
Intent intent = new Intent(null, getIntent().getData());
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
// menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0,
// new ComponentName(this, NoteEditor.class), null, intent, 0, null);
// Workaround to add icons:
MenuIntentOptionsWithIcons menu2 = new MenuIntentOptionsWithIcons(this,
menu);
menu2.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0,
new ComponentName(this, ShoppingActivity.class), null, intent,
0, null);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (debug)
Log.d(TAG, "onOptionsItemSelected getItemId: " + item.getItemId());
Intent intent;
switch (item.getItemId()) {
case MENU_NEW_LIST:
showDialog(DIALOG_NEW_LIST);
return true;
case MENU_CLEAN_UP_LIST:
cleanupList();
return true;
case MENU_RENAME_LIST:
showDialog(DIALOG_RENAME_LIST);
return true;
case MENU_DELETE_LIST:
deleteListConfirm();
return true;
case MENU_PICK_ITEMS:
pickItems();
return true;
case MENU_SHARE:
setShareSettings();
return true;
case MENU_THEME:
setThemeSettings();
return true;
case MENU_ADD_LOCATION_ALERT:
addLocationAlert();
return true;
case MENU_PREFERENCES:
intent = new Intent(this, PreferenceActivity.class);
startActivity(intent);
return true;
case MENU_SEND:
sendList();
return true;
case MENU_INSERT_FROM_EXTRAS:
insertItemsFromExtras();
return true;
case MENU_MARK_ALL_ITEMS:
mItemsView.toggleOnAllItems();
return true;
}
if (debug)
Log.d(TAG, "Start intent group id : " + item.getGroupId());
if (Menu.CATEGORY_ALTERNATIVE == item.getGroupId()) {
// Start alternative cateogory intents with option to return a
// result.
if (debug)
Log.d(TAG, "Start alternative intent for : "
+ item.getIntent().getDataString());
startActivityForResult(item.getIntent(),
REQUEST_CODE_CATEGORY_ALTERNATIVE);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
*
*/
private void pickItems() {
if (PreferenceActivity.getPickItemsInListFromPrefs(getApplicationContext())) {
if (mItemsView.mMode == MODE_IN_SHOP) {
mItemsView.mMode = MODE_ADD_ITEMS;
} else {
mItemsView.mMode = MODE_IN_SHOP;
}
onModeChanged();
} else {
pickItemsUsingDialog();
}
}
private void pickItemsUsingDialog() {
Intent intent;
intent = new Intent(this, PickItemsActivity.class);
intent.setData(mListUri);
startActivity(intent);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
super.onContextItemSelected(item);
AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item
.getMenuInfo();
switch (item.getItemId()) {
case MENU_MARK_ITEM:
markItem(menuInfo.position);
break;
case MENU_EDIT_ITEM:
editItem(menuInfo.position, EditItemDialog.FieldType.ITEMNAME);
break;
case MENU_REMOVE_ITEM_FROM_LIST:
removeItemFromList(menuInfo.position);
break;
case MENU_DELETE_ITEM:
deleteItemDialog(menuInfo.position);
break;
case MENU_MOVE_ITEM:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setData(ShoppingContract.Lists.CONTENT_URI);
startActivityForResult(intent, REQUEST_PICK_LIST);
mMoveItemPosition = menuInfo.position;
break;
case MENU_ITEM_STORES:
editItemStores(menuInfo.position);
break;
}
return true;
}
// /////////////////////////////////////////////////////
//
// Menu functions
//
/**
* Creates a new list from dialog.
*
* @return true if new list was created. False if new list was not created,
* because user has not given any name.
*/
private boolean createNewList(String name) {
if (name.equals("")) {
// User has not provided any name
Toast.makeText(this, getString(R.string.please_enter_name),
Toast.LENGTH_SHORT).show();
return false;
}
String previousTheme = loadListTheme();
int newId = (int) ShoppingUtils.getList(this, name);
fillListFilter();
setSelectedListId(newId);
// Now set the theme based on the selected list:
saveListTheme(previousTheme);
setListTheme(previousTheme);
applyListTheme();
return true;
}
private void setListTheme(String theme) {
mItemsView.setListTheme(theme);
if (!usingListSpinner()) {
// In Holo themes, apply the theme text color also to the
// input box and the button, because the background is semi-transparent.
mEditText.setTextColor(mItemsView.mTextColor);
mButton.setTextColor(mItemsView.mTextColor);
}
}
private void applyListTheme() {
mItemsView.applyListTheme();
}
/**
* Rename list from dialog.
*
* @return true if new list was renamed. False if new list was not renamed,
* because user has not given any name.
*/
private boolean renameList(String newName) {
if (newName.equals("")) {
// User has not provided any name
Toast.makeText(this, getString(R.string.please_enter_name),
Toast.LENGTH_SHORT).show();
return false;
}
// Rename currently selected list:
ContentValues values = new ContentValues();
values.put(Lists.NAME, "" + newName);
getContentResolver().update(
Uri.withAppendedPath(Lists.CONTENT_URI,
mCursorShoppingLists.getString(0)), values, null, null);
mCursorShoppingLists.requery();
updateTitle();
return true;
}
private void sendList() {
if (mItemsView.getAdapter() instanceof CursorAdapter) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < mItemsView.getAdapter().getCount(); i++) {
Cursor item = (Cursor) mItemsView.getAdapter().getItem(i);
if (item.getLong(mStringItemsSTATUS) == ShoppingContract.Status.BOUGHT) {
sb.append("[X] ");
} else {
sb.append("[ ] ");
}
String quantity = item.getString(mStringItemsQUANTITY);
long pricecent = item.getLong(mStringItemsITEMPRICE);
String price = PriceConverter.getStringFromCentPrice(pricecent);
String tags = item.getString(mStringItemsITEMTAGS);
if (!TextUtils.isEmpty(quantity)) {
sb.append(quantity);
sb.append(" ");
}
String units = item.getString(mStringItemsITEMUNITS);
if (!TextUtils.isEmpty(units)) {
sb.append(units);
sb.append(" ");
}
sb.append(item.getString(mStringItemsITEMNAME));
// Put additional info (price, tags) in brackets
boolean p = !TextUtils.isEmpty(price);
boolean t = !TextUtils.isEmpty(tags);
if (p || t) {
sb.append(" (");
if (p) {
sb.append(price);
}
if (p && t) {
sb.append(", ");
}
if (t) {
sb.append(tags);
}
sb.append(")");
}
sb.append("\n");
}
Intent i = new Intent();
i.setAction(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, getCurrentListName());
i.putExtra(Intent.EXTRA_TEXT, sb.toString());
try {
startActivity(Intent.createChooser(i, getString(R.string.send)));
} catch (ActivityNotFoundException e) {
Toast.makeText(this, R.string.email_not_available,
Toast.LENGTH_SHORT).show();
Log.e(TAG, "Email client not installed");
}
} else {
Toast.makeText(this, R.string.empty_list_not_sent,
Toast.LENGTH_SHORT);
}
}
/**
* Clean up the currently visible shopping list by removing items from list
* that are marked BOUGHT.
*/
private void cleanupList() {
// Remove all items from current list
// which have STATUS = Status.BOUGHT
if (!mItemsView.cleanupList()) {
// Show toast
Toast.makeText(this, R.string.no_items_marked, Toast.LENGTH_SHORT)
.show();
}
}
// TODO: Convert into proper dialog that remains across screen orientation changes.
/**
* Confirm 'delete list' command by AlertDialog.
*/
private void deleteListConfirm() {
new AlertDialog.Builder(this)
// .setIcon(R.drawable.alert_dialog_icon)
.setTitle(R.string.confirm_delete_list)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// click Ok
deleteList();
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// click Cancel
}
})
// .create()
.show();
}
/**
* Deletes currently selected shopping list.
*/
private void deleteList() {
String listId = mCursorShoppingLists.getString(0);
ShoppingUtils.deleteList(this, listId);
// Update view
fillListFilter();
getSelectedListId();
// Set the theme based on the selected list:
setListTheme(loadListTheme());
fillItems(false);
applyListTheme();
}
/** Mark item */
void markItem(int position) {
mItemsView.toggleItemBought(position);
}
/**
* Edit item
*
* @param field
*/
void editItem(int position, EditItemDialog.FieldType field) {
if (debug)
Log.d(TAG, "EditItems: Position: " + position);
mItemsView.mCursorItems.moveToPosition(position);
// mEditItemPosition = position;
long itemId = mItemsView.mCursorItems.getLong(mStringItemsITEMID);
long containsId = mItemsView.mCursorItems
.getLong(mStringItemsCONTAINSID);
mItemUri = Uri
.withAppendedPath(ShoppingContract.Items.CONTENT_URI, "" + itemId);
mRelationUri = Uri.withAppendedPath(ShoppingContract.Contains.CONTENT_URI, ""
+ containsId);
mEditItemFocusField = field;
showDialog(DIALOG_EDIT_ITEM);
}
void editItemStores(int position) {
if (debug)
Log.d(TAG, "EditItemStores: Position: " + position);
mItemsView.mCursorItems.moveToPosition(position);
// mEditItemPosition = position;
long itemId = mItemsView.mCursorItems.getLong(mStringItemsITEMID);
Intent intent;
intent = new Intent(this, ItemStoresActivity.class);
intent.setData(mListUri.buildUpon().appendPath(String.valueOf(itemId)).build());
startActivity(intent);
}
int mDeleteItemPosition;
/** delete item */
void deleteItemDialog(int position) {
if (debug)
Log.d(TAG, "EditItems: Position: " + position);
mItemsView.mCursorItems.moveToPosition(position);
mDeleteItemPosition = position;
showDialog(DIALOG_DELETE_ITEM);
}
/** delete item */
void deleteItem(int position) {
Cursor c = mItemsView.mCursorItems;
c.moveToPosition(position);
String listId = mListUri.getLastPathSegment();
String itemId = c.getString(mStringItemsITEMID);
ShoppingUtils.deleteItem(this, itemId, listId);
// c.requery();
mItemsView.requery();
}
/** move item */
void moveItem(int position, int targetListId) {
Cursor c = mItemsView.mCursorItems;
mItemsView.mCursorItems.requery();
c.moveToPosition(position);
long listId = getSelectedListId();
if (false && listId < 0) {
// No valid list - probably view is not active
// and no item is selected.
return;
}
listId = Integer.parseInt(mListUri.getLastPathSegment());
int itemId = c.getInt(mStringItemsITEMID);
// add item to new list
ShoppingUtils.addItemToList(this, itemId,
targetListId, Status.WANT_TO_BUY,
c.getString(mStringItemsPRIORITY),
c.getString(mStringItemsQUANTITY), false);
ShoppingUtils.deleteItemFromList(this, "" + itemId, "" + listId);
mItemsView.requery();
}
/** removeItemFromList */
void removeItemFromList(int position) {
Cursor c = mItemsView.mCursorItems;
c.moveToPosition(position);
// Remember old values before delete (for share below)
String itemName = c.getString(mStringItemsITEMNAME);
long oldstatus = c.getLong(mStringItemsSTATUS);
// Delete item by changing its state
ContentValues values = new ContentValues();
values.put(Contains.STATUS, Status.REMOVED_FROM_LIST);
getContentResolver().update(Contains.CONTENT_URI, values, "_id = ?",
new String[] { c.getString(mStringItemsCONTAINSID) });
// c.requery();
mItemsView.requery();
// If we share items, mark item on other lists:
// TODO ???
/*
* String recipients =
* mCursorListFilter.getString(mStringListFilterSHARECONTACTS); if (!
* recipients.equals("")) { String shareName =
* mCursorListFilter.getString(mStringListFilterSHARENAME); long
* newstatus = Shopping.Status.BOUGHT;
*
* Log.i(TAG, "Update shared item. " + " recipients: " + recipients +
* ", shareName: " + shareName + ", status: " + newstatus);
* mGTalkSender.sendItemUpdate(recipients, shareName, itemName,
* itemName, oldstatus, newstatus); }
*/
}
/**
* Calls the share settings with the currently selected list.
*/
void setShareSettings() {
// Obtain URI of current list
// Call share settings as subactivity
Intent intent = new Intent(OpenIntents.SET_SHARE_SETTINGS_ACTION,
mListUri);
startActivityForResult(intent, SUBACTIVITY_LIST_SHARE_SETTINGS);
}
void setThemeSettings() {
showDialog(DIALOG_THEME);
}
@Override
public String onLoadTheme() {
return loadListTheme();
}
@Override
public void onSaveTheme(String theme) {
saveListTheme(theme);
}
@Override
public void onSetTheme(String theme) {
setListTheme(theme);
applyListTheme();
}
@Override
public void onSetThemeForAll(String theme) {
setThemeForAll(this, theme);
}
/**
* Set theme for all lists.
*
* @param context
* @param theme
*/
public static void setThemeForAll(Context context, String theme) {
ContentValues values = new ContentValues();
values.put(Lists.SKIN_BACKGROUND, theme);
context.getContentResolver().update(Lists.CONTENT_URI, values, null,
null);
}
/**
* Loads the theme settings for the currently selected theme.
*
* Up to version 1.2.1, only one of 3 hardcoded themes are available. These
* are stored in 'skin_background' as '1', '2', or '3'.
*
* Starting in 1.2.2, also themes of other packages are allowed.
*
* @return
*/
public String loadListTheme() {
/*
* long listId = getSelectedListId(); if (listId < 0) { // No valid list
* - probably view is not active // and no item is selected. return 1;
* // return default theme }
*/
// Return default theme if something unexpected happens:
if (mCursorShoppingLists == null)
return "1";
if (mCursorShoppingLists.getPosition() < 0)
return "1";
// mCursorListFilter has been set to correct position
// by calling getSelectedListId(),
// so we can read out further elements:
String skinBackground = mCursorShoppingLists
.getString(mStringListFilterSKINBACKGROUND);
return skinBackground;
}
public void saveListTheme(String theme) {
long listId = getSelectedListId();
if (listId < 0) {
// No valid list - probably view is not active
// and no item is selected.
return; // return default theme
}
ContentValues values = new ContentValues();
values.put(Lists.SKIN_BACKGROUND, theme);
getContentResolver().update(
Uri.withAppendedPath(Lists.CONTENT_URI,
mCursorShoppingLists.getString(0)), values, null, null);
mCursorShoppingLists.requery();
}
/**
* Calls a dialog for setting the locations alert.
*/
void addLocationAlert() {
// Call dialog as activity
Intent intent = new Intent(OpenIntents.ADD_LOCATION_ALERT_ACTION,
mListUri);
// startSubActivity(intent, SUBACTIVITY_ADD_LOCATION_ALERT);
startActivity(intent);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_NEW_LIST:
return new NewListDialog(this, new DialogActionListener() {
public void onAction(String name) {
createNewList(name);
}
});
case DIALOG_RENAME_LIST:
return new RenameListDialog(this, getCurrentListName(),
new DialogActionListener() {
public void onAction(String name) {
renameList(name);
}
});
case DIALOG_EDIT_ITEM:
return new EditItemDialog(this, mItemUri, mRelationUri);
case DIALOG_DELETE_ITEM:
return new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.menu_delete_item)
.setMessage(R.string.delete_item_confirm)
.setPositiveButton(R.string.delete,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
deleteItem(mDeleteItemPosition);
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// Don't do anything
}
}).create();
case DIALOG_THEME:
return new ThemeDialog(this, this);
}
return super.onCreateDialog(id);
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
switch (id) {
case DIALOG_RENAME_LIST:
((RenameListDialog) dialog).setName(getCurrentListName());
break;
case DIALOG_EDIT_ITEM:
EditItemDialog d = (EditItemDialog) dialog;
d.setItemUri(mItemUri);
d.setRelationUri(mRelationUri);
d.setFocusField(mEditItemFocusField);
String[] taglist = getTaglist();
d.setTagList(taglist);
d.setRequeryCursor(mItemsView.mCursorItems);
break;
case DIALOG_THEME:
((ThemeDialog) dialog).prepareDialog();
break;
}
}
// /////////////////////////////////////////////////////
//
// Helper functions
//
/**
* Returns the ID of the selected shopping list.
*
* As a side effect, the item URI is updated. Returns -1 if nothing is
* selected.
*
* @return ID of selected shopping list.
*/
private long getSelectedListId() {
int pos = mShoppingListsView.getSelectedItemPosition();
//Temp- Due to architecture requirements of OS 3, the value can not be passed directly
if(pos==-1 && !usingListSpinner()){
try {
pos=(Integer)mShoppingListsView.getTag();
pos=mCursorShoppingLists.getCount()<=pos?-1:pos;
} catch (Exception e) {
// e.printStackTrace();
}
}
if (pos < 0) {
// nothing selected - probably view is out of focus:
// Do nothing.
return -1;
}
// Obtain Id of currently selected shopping list:
mCursorShoppingLists.moveToPosition(pos);
long listId = mCursorShoppingLists.getLong(mStringListFilterID);
mListUri = Uri
.withAppendedPath(ShoppingContract.Lists.CONTENT_URI, "" + listId);
getIntent().setData(mListUri);
return listId;
};
/**
* sets the selected list to a specific list Id
*/
private void setSelectedListId(int id) {
// Is there a nicer way to accomplish the following?
// (we look through all elements to look for the
// one entry that has the same ID as returned by
// getDefaultList()).
//
// unfortunately, a SQL query won't work, as it would
// return 1 row, but I still would not know which
// row in the mCursorListFilter corresponds to that id.
//
// one could use: findViewById() but how will this
// translate to the position in the list?
mCursorShoppingLists.moveToPosition(-1);
while (mCursorShoppingLists.moveToNext()) {
int posId = mCursorShoppingLists.getInt(mStringListFilterID);
if (posId == id) {
int row = mCursorShoppingLists.getPosition();
// if we found the Id, then select this in
// the Spinner:
setSelectedListPos(row);
break;
}
}
}
private void setSelectedListPos(int pos){
mShoppingListsView.setTag(pos);
mShoppingListsView.setSelection(pos);
long id = getSelectedListId();
// Set the theme based on the selected list:
setListTheme(loadListTheme());
if (id != mItemsView.getListId()) {
fillItems(false);
}
applyListTheme();
if (mShoppingListsView instanceof ListView){
((ListView) mShoppingListsView).setItemChecked(pos,true);
}
}
/**
*
*/
private void fillListFilter() {
// Get a cursor with all lists
mCursorShoppingLists = getContentResolver().query(Lists.CONTENT_URI,
mStringListFilter, null, null, Lists.DEFAULT_SORT_ORDER);
startManagingCursor(mCursorShoppingLists);
if (mCursorShoppingLists == null) {
Log.e(TAG, "missing shopping provider");
ArrayAdapter adapter=new ArrayAdapter(this,
android.R.layout.simple_spinner_item,
new String[] { getString(R.string.no_shopping_provider) });
setSpinnerListAdapter(adapter);
return;
}
if (mCursorShoppingLists.getCount() < 1) {
// We have to create default shopping list:
long listId = ShoppingUtils.getList(this,
getText(R.string.my_shopping_list).toString());
// Check if insertion really worked. Otherwise
// we may end up in infinite recursion.
if (listId < 0) {
// for some reason insertion did not work.
return;
}
// The insertion should have worked, so let us call ourselves
// to try filling the list again:
fillListFilter();
return;
}
class mListContentObserver extends ContentObserver {
public mListContentObserver(Handler handler) {
super(handler);
if (debug)
Log.i(TAG, "mListContentObserver: Constructor");
}
/*
* (non-Javadoc)
*
* @see android.database.ContentObserver#deliverSelfNotifications()
*/
@Override
public boolean deliverSelfNotifications() {
// TODO Auto-generated method stub
if (debug)
Log.i(TAG, "mListContentObserver: deliverSelfNotifications");
return super.deliverSelfNotifications();
}
/*
* (non-Javadoc)
*
* @see android.database.ContentObserver#onChange(boolean)
*/
@Override
public void onChange(boolean arg0) {
// TODO Auto-generated method stub
if (debug)
Log.i(TAG, "mListContentObserver: onChange");
mCursorShoppingLists.requery();
super.onChange(arg0);
}
}
;
mListContentObserver observer = new mListContentObserver(new Handler());
mCursorShoppingLists.registerContentObserver(observer);
// Register a ContentObserver, so that a new list can be
// automatically detected.
// mCursor
/*
* ArrayList<String> list = new ArrayList<String>(); // TODO Create
* summary of all lists // list.add(ALL); while
* (mCursorListFilter.next()) {
* list.add(mCursorListFilter.getString(mStringListFilterNAME)); }
* ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
* android.R.layout.simple_spinner_item, list);
* adapter.setDropDownViewResource(
* android.R.layout.simple_spinner_dropdown_item);
* mSpinnerListFilter.setAdapter(adapter);
*/
SimpleCursorAdapter adapter;
if (mShoppingListsView instanceof Spinner){
adapter = new SimpleCursorAdapter(this,
// Use a template that displays a text view
android.R.layout.simple_spinner_item,
// Give the cursor to the list adapter
mCursorShoppingLists, new String[] { Lists.NAME },
new int[] { android.R.id.text1 });
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
} else {
// mShoppingListView is a ListView
adapter = new SimpleCursorAdapter(this,
// Use a template that displays a text view
R.layout.list_item_shopping_list,
// Give the cursor to the list adapter
mCursorShoppingLists, new String[] { Lists.NAME },
new int[] { R.id.text1 });
}
// mSpinnerListFilter.setAdapter(adapter);//Temp- redirected through method
setSpinnerListAdapter(adapter);
}
private void onModeChanged() {
if (debug)
Log.d(TAG, "onModeChanged()");
fillItems(false);
compat_invalidateOptionsMenu();
updateTitle();
}
java.lang.reflect.Method mMethodInvalidateOptionsMenu = null;
/**
* Update the ActionBar (Honeycomb or higher)
*/
private void compat_invalidateOptionsMenu() {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB){
//invalidateOptionsMenu();
try {
if (mMethodInvalidateOptionsMenu == null) {
mMethodInvalidateOptionsMenu = Activity.class.getMethod("invalidateOptionsMenu");
}
mMethodInvalidateOptionsMenu.invoke(this);
} catch(Exception e) {
mMethodInvalidateOptionsMenu = null;
}
}
}
@Override
public void updateActionBar() {
compat_invalidateOptionsMenu();
}
private String getCurrentListName() {
long listId = getSelectedListId();
// calling getSelectedListId also updates mCursorShoppingLists:
if (listId >= 0) {
return mCursorShoppingLists.getString(mStringListFilterNAME);
} else {
return "";
}
}
private void fillItems(boolean onlyIfPrefsChanged) {
if (debug)
Log.d(TAG, "fillItems()");
if (onlyIfPrefsChanged &&
(lastAppliedPrefChange == PreferenceActivity.updateCount)) {
return;
}
long listId = getSelectedListId();
if (listId < 0) {
// No valid list - probably view is not active
// and no item is selected.
return;
}
if (debug)
Log.d(TAG, "fillItems() for list " + listId);
lastAppliedPrefChange = PreferenceActivity.updateCount;
mItemsView.fillItems(this, listId);
// Insert any pending items received either through intents
// or in onActivityResult:
if (mExtraItems != null) {
insertItemsFromExtras();
}
}
/**
* Create list of tags.
*
* Tags for notes can be comma-separated. Here we create a list of the
* unique tags.
*
* @param c
* @return
*/
String[] getTaglist() {
Cursor c = getContentResolver().query(ShoppingContract.Items.CONTENT_URI,
new String[] { ShoppingContract.Items.TAGS }, null, null,
ShoppingContract.Items.DEFAULT_SORT_ORDER);
// Create a set of all tags (every tag should only appear once).
HashSet<String> tagset = new HashSet<String>();
c.moveToPosition(-1);
while (c.moveToNext()) {
String tags = c.getString(0);
if (tags != null) {
// Split several tags in a line, separated by comma
String[] smalltaglist = tags.split(",");
for (String tag : smalltaglist) {
if (!tag.equals("")) {
tagset.add(tag.trim());
}
}
}
}
c.close();
// Sort the list
// 1. Convert HashSet to String list.
ArrayList<String> list = new ArrayList<String>();
list.addAll(tagset);
// 2. Sort the String list
Collections.sort(list);
// 3. Convert it to String array
return list.toArray(new String[0]);
}
/**
* Tests whether the current list is shared via GTalk. (not local sharing!)
*
* @return true if SHARE_CONTACTS contains the '@' character.
*/
boolean isCurrentListShared() {
long listId = getSelectedListId();
if (listId < 0) {
// No valid list - probably view is not active
// and no item is selected.
return false;
}
// mCursorListFilter has been set to correct position
// by calling getSelectedListId(),
// so we can read out further elements:
// String shareName =
// mCursorListFilter.getString(mStringListFilterSHARENAME);
String recipients = mCursorShoppingLists
.getString(mStringListFilterSHARECONTACTS);
// If recipients contains the '@' symbol, it is shared.
return recipients.contains("@");
}
// Handle the process of automatically updating enabled sensors:
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == MESSAGE_UPDATE_CURSORS) {
mCursorShoppingLists.requery();
if (mUpdating) {
sendMessageDelayed(obtainMessage(MESSAGE_UPDATE_CURSORS),
mUpdateInterval);
}
}
}
};
/**
* Listens for intents for updates in the database.
*
* @param context
* @param intent
*/
// TODO ???
/*
* public class ListIntentReceiver extends IntentReceiver {
*
* public void onReceiveIntent(Context context, Intent intent) { String
* action = intent.getAction(); Log.i(TAG, "ShoppingList received intent " +
* action);
*
* if (action.equals(OpenIntents.REFRESH_ACTION)) {
* mCursorListFilter.requery();
*
* } } }
*/
/*
* ListIntentReceiver mIntentReceiver;
*/
/**
* This method is called when the sending activity has finished, with the
* result it supplied.
*
* @param requestCode
* The original request code as given to startActivity().
* @param resultCode
* From sending activity as per setResult().
* @param data
* From sending activity as per setResult().
* @param extras
* From sending activity as per setResult().
*
* @see android.app.Activity#onActivityResult(int, int, java.lang.String,
* android.os.Bundle)
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (debug)
Log.i(TAG, "ShoppingView: onActivityResult. ");
if (requestCode == SUBACTIVITY_LIST_SHARE_SETTINGS) {
if (debug)
Log.i(TAG, "SUBACTIVITY_LIST_SHARE_SETTINGS");
if (resultCode == RESULT_CANCELED) {
// Don't do anything.
if (debug)
Log.i(TAG, "RESULT_CANCELED");
} else {
// Broadcast the intent
if (debug)
Log.i(TAG, "Broadcast intent.");
// TODO ???
/*
* Uri uri = Uri.parse(data);
*/
Uri uri = Uri.parse(data.getDataString());
if (!mListUri.equals(uri)) {
Log.e(TAG, "Unexpected uri returned: Should be " + mListUri
+ " but was " + uri);
return;
}
// TODO ???
Bundle extras = data.getExtras();
String sharename = extras.getString(ShoppingContract.Lists.SHARE_NAME);
String contacts = extras
.getString(ShoppingContract.Lists.SHARE_CONTACTS);
if (debug)
Log.i(TAG, "Received bundle: sharename: " + sharename
+ ", contacts: " + contacts);
// Here we also send the current content of the list
// to all recipients.
// This could probably be optimized - by sending
// content only to the new recipients, as the
// old ones should be in sync already.
// First delete all items in list
/*
* mCursorItems.moveToPosition(-1); while
* (mCursorItems.moveToNext()) { String itemName = mCursorItems
* .getString(mStringItemsITEMNAME); Long status =
* mCursorItems.getLong(mStringItemsSTATUS); Log.i(TAG,
* "Update shared item. " + " recipients: " + contacts +
* ", shareName: " + sharename + ", item: " + itemName); // TODO
* ??? /* mGTalkSender.sendItemUpdate(contacts, sharename,
* itemName, itemName, status, status); / }
*/
}
} else if (REQUEST_CODE_CATEGORY_ALTERNATIVE == requestCode) {
if (debug)
Log.d(TAG, "result received");
if (RESULT_OK == resultCode) {
if (debug)
Log.d(TAG, "result OK");
// Check if any results have been returned:
/*
* if ((data.getDataString() != null) &&
* (data.getDataString().startsWith
* (Shopping.Lists.CONTENT_URI.toString()))) { // We received a
* valid shopping list URI.
*
* // Set current list to received list: mListUri =
* data.getData(); intent.setData(mListUri); }
*/
if (data.getExtras() != null) {
if (debug)
Log.d(TAG, "extras received");
getShoppingExtras(data);
}
}
} else if (REQUEST_PICK_LIST == requestCode) {
if (debug)
Log.d(TAG, "result received");
if (RESULT_OK == resultCode) {
int position = mMoveItemPosition;
if (mMoveItemPosition >= 0) {
moveItem(position, Integer.parseInt(data.getData()
.getLastPathSegment()));
}
}
mMoveItemPosition = -1;
}
}
public void changeList(int value) {
int pos = mShoppingListsView.getSelectedItemPosition();
//Temp- Due to architecture requirements of OS 3, the value can not be passed directly
if(pos==-1 && !usingListSpinner()){
try {
pos=(Integer)mShoppingListsView.getTag();
pos=mCursorShoppingLists.getCount()<=pos?-1:pos;
} catch (Exception e) {
e.printStackTrace();
}
}
int newPos;
if (pos < 0) {
// nothing selected - probably view is out of focus:
// Do nothing.
newPos = -1;
} else if (pos == 0) {
newPos = mShoppingListsView.getCount() - 1;
} else if (pos == mShoppingListsView.getCount()) {
newPos = 0;
} else {
newPos = pos + value;
}
setSelectedListPos(newPos);
}
/**
* With the requirement of OS3, making an intermediary decision depending upon the widget
* @param adapter
*/
private void setSpinnerListAdapter(ListAdapter adapter){
if(usingListSpinner()){//Temp - restricted for OS3
mShoppingListsView.setAdapter(adapter);
}else{
ShoppingListFilterFragment os3=(ShoppingListFilterFragment)getSupportFragmentManager().findFragmentById(R.id.sidelist);
os3.setAdapter(adapter);
}
}
}
| false | true | private void createView() {
//Temp-create either Spinner or List based upon the Display
createList();
mEditText = (AutoCompleteTextView) findViewById(R.id.autocomplete_add_item);
if (mItemsCursor != null) {
if (debug)
Log.d(TAG, "mItemsCursor managedQuery 1");
stopManagingCursor(mItemsCursor);
mItemsCursor.close();
mItemsCursor = null;
}
mItemsCursor = managedQuery(Items.CONTENT_URI, new String[] {
Items._ID, Items.NAME }, null, null, "name desc");
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_dropdown_item_1line, mItemsCursor,
new String[] { Items.NAME }, new int[] { android.R.id.text1 });
adapter.setStringConversionColumn(1);
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
if (mItemsCursor != null) {
if (debug)
Log.d(TAG, "mItemsCursor managedQuery 2");
stopManagingCursor(mItemsCursor);
// For some reason, closing the cursor seems to post
// an invalidation on the background thread and a crash...
// so we keep it open.
// mItemsCursor.close();
// mItemsCursor = null;
}
mItemsCursor = managedQuery(Items.CONTENT_URI, new String[] {
Items._ID, Items.NAME }, "upper(name) like ?",
new String[] { "%"
+ (constraint == null ? "" : constraint
.toString().toUpperCase()) + "%" },
"name desc");
return mItemsCursor;
}
});
mEditText.setAdapter(adapter);
mEditText.setOnKeyListener(new OnKeyListener() {
private int mLastKeyAction = KeyEvent.ACTION_UP;
public boolean onKey(View v, int keyCode, KeyEvent key) {
// Log.i(TAG, "KeyCode: " + keyCode
// + " =?= "
// +Integer.parseInt(getString(R.string.key_return)) );
// Shortcut: Instead of pressing the button,
// one can also press the "Enter" key.
if (debug)
Log.i(TAG, "Key action: " + key.getAction());
if (debug)
Log.i(TAG, "Key code: " + keyCode);
if (keyCode == KeyEvent.KEYCODE_ENTER) {
if (mEditText.isPopupShowing()) {
mEditText.performCompletion();
}
// long key press might cause call of duplicate onKey events
// with ACTION_DOWN
// this would result in inserting an item and showing the
// pick list
if (key.getAction() == KeyEvent.ACTION_DOWN
&& mLastKeyAction == KeyEvent.ACTION_UP) {
insertNewItem();
}
mLastKeyAction = key.getAction();
return true;
};
return false;
}
});
mEditText.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
if (mItemsView.mMode == MODE_ADD_ITEMS) {
// small optimization: Only care about updating
// the button label on each key pressed if we
// are in "add items" mode.
updateButton();
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
mButton = (Button) findViewById(R.id.button_add_item);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
insertNewItem();
}
});
mButton.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent();
intent.setData(mListUri);
intent.setClassName("org.openintents.barcodescanner", "org.openintents.barcodescanner.BarcodeScanner");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.v(TAG, "barcode scanner not found");
return false;
}
return true;
}
});
mLayoutParamsItems = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
mItemsView = (ShoppingItemsView) findViewById(R.id.list_items);
mItemsView.setThemedBackground(findViewById(R.id.background));
mItemsView.setCustomClickListener(this);
mItemsView.setItemsCanFocus(true);
mItemsView.setDragListener(new DragListener() {
@Override
public void drag(int from, int to) {
if (debug) Log.v("DRAG", "" + from + "/" + to);
}
});
mItemsView.setDropListener(new DropListener() {
@Override
public void drop(int from, int to) {
if (debug) Log.v("DRAG", "" + from + "/" + to);
}
});
TextView tv = (TextView) findViewById(R.id.total_1);
mItemsView.setTotalCheckedTextView(tv);
tv = (TextView) findViewById(R.id.total_2);
mItemsView.setTotalTextView(tv);
tv = (TextView) findViewById(R.id.total_3);
mItemsView.setPrioritySubtotalTextView(tv);
tv = (TextView) findViewById(R.id.count);
mItemsView.setCountTextView(tv);
mItemsView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int pos, long id) {
Cursor c = (Cursor) parent.getItemAtPosition(pos);
onCustomClick(c, pos, EditItemDialog.FieldType.ITEMNAME);
// DO NOT CLOSE THIS CURSOR - IT IS A MANAGED ONE.
// ---- c.close();
}
});
mItemsView
.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu contextmenu,
View view, ContextMenuInfo info) {
contextmenu.add(0, MENU_EDIT_ITEM, 0,
R.string.menu_edit_item).setShortcut('1', 'e');
contextmenu.add(0, MENU_MARK_ITEM, 0,
R.string.menu_mark_item).setShortcut('2', 'm');
contextmenu.add(0, MENU_ITEM_STORES, 0,
R.string.menu_item_stores).setShortcut('3', 's');
contextmenu.add(0, MENU_REMOVE_ITEM_FROM_LIST, 0,
R.string.menu_remove_item)
.setShortcut('3', 'r');
contextmenu.add(0, MENU_DELETE_ITEM, 0,
R.string.menu_delete_item)
.setShortcut('4', 'd');
contextmenu.add(0, MENU_MOVE_ITEM, 0,
R.string.menu_move_item).setShortcut('5', 'l');
}
});
}
| private void createView() {
//Temp-create either Spinner or List based upon the Display
createList();
mEditText = (AutoCompleteTextView) findViewById(R.id.autocomplete_add_item);
if (mItemsCursor != null) {
if (debug)
Log.d(TAG, "mItemsCursor managedQuery 1");
stopManagingCursor(mItemsCursor);
mItemsCursor.close();
mItemsCursor = null;
}
mItemsCursor = managedQuery(Items.CONTENT_URI, new String[] {
Items._ID, Items.NAME }, null, null, "name desc");
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_dropdown_item_1line, mItemsCursor,
new String[] { Items.NAME }, new int[] { android.R.id.text1 });
adapter.setStringConversionColumn(1);
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
if (mItemsCursor != null) {
if (debug)
Log.d(TAG, "mItemsCursor managedQuery 2");
stopManagingCursor(mItemsCursor);
// For some reason, closing the cursor seems to post
// an invalidation on the background thread and a crash...
// so we keep it open.
// mItemsCursor.close();
// mItemsCursor = null;
}
mItemsCursor = managedQuery(Items.CONTENT_URI, new String[] {
Items._ID, Items.NAME }, "upper(name) like upper(?)",
new String[] { "%"
+ (constraint == null ? "" : constraint
.toString()) + "%" },
"name desc");
return mItemsCursor;
}
});
mEditText.setAdapter(adapter);
mEditText.setOnKeyListener(new OnKeyListener() {
private int mLastKeyAction = KeyEvent.ACTION_UP;
public boolean onKey(View v, int keyCode, KeyEvent key) {
// Log.i(TAG, "KeyCode: " + keyCode
// + " =?= "
// +Integer.parseInt(getString(R.string.key_return)) );
// Shortcut: Instead of pressing the button,
// one can also press the "Enter" key.
if (debug)
Log.i(TAG, "Key action: " + key.getAction());
if (debug)
Log.i(TAG, "Key code: " + keyCode);
if (keyCode == KeyEvent.KEYCODE_ENTER) {
if (mEditText.isPopupShowing()) {
mEditText.performCompletion();
}
// long key press might cause call of duplicate onKey events
// with ACTION_DOWN
// this would result in inserting an item and showing the
// pick list
if (key.getAction() == KeyEvent.ACTION_DOWN
&& mLastKeyAction == KeyEvent.ACTION_UP) {
insertNewItem();
}
mLastKeyAction = key.getAction();
return true;
};
return false;
}
});
mEditText.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
if (mItemsView.mMode == MODE_ADD_ITEMS) {
// small optimization: Only care about updating
// the button label on each key pressed if we
// are in "add items" mode.
updateButton();
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
mButton = (Button) findViewById(R.id.button_add_item);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
insertNewItem();
}
});
mButton.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent();
intent.setData(mListUri);
intent.setClassName("org.openintents.barcodescanner", "org.openintents.barcodescanner.BarcodeScanner");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.v(TAG, "barcode scanner not found");
return false;
}
return true;
}
});
mLayoutParamsItems = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
mItemsView = (ShoppingItemsView) findViewById(R.id.list_items);
mItemsView.setThemedBackground(findViewById(R.id.background));
mItemsView.setCustomClickListener(this);
mItemsView.setItemsCanFocus(true);
mItemsView.setDragListener(new DragListener() {
@Override
public void drag(int from, int to) {
if (debug) Log.v("DRAG", "" + from + "/" + to);
}
});
mItemsView.setDropListener(new DropListener() {
@Override
public void drop(int from, int to) {
if (debug) Log.v("DRAG", "" + from + "/" + to);
}
});
TextView tv = (TextView) findViewById(R.id.total_1);
mItemsView.setTotalCheckedTextView(tv);
tv = (TextView) findViewById(R.id.total_2);
mItemsView.setTotalTextView(tv);
tv = (TextView) findViewById(R.id.total_3);
mItemsView.setPrioritySubtotalTextView(tv);
tv = (TextView) findViewById(R.id.count);
mItemsView.setCountTextView(tv);
mItemsView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int pos, long id) {
Cursor c = (Cursor) parent.getItemAtPosition(pos);
onCustomClick(c, pos, EditItemDialog.FieldType.ITEMNAME);
// DO NOT CLOSE THIS CURSOR - IT IS A MANAGED ONE.
// ---- c.close();
}
});
mItemsView
.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu contextmenu,
View view, ContextMenuInfo info) {
contextmenu.add(0, MENU_EDIT_ITEM, 0,
R.string.menu_edit_item).setShortcut('1', 'e');
contextmenu.add(0, MENU_MARK_ITEM, 0,
R.string.menu_mark_item).setShortcut('2', 'm');
contextmenu.add(0, MENU_ITEM_STORES, 0,
R.string.menu_item_stores).setShortcut('3', 's');
contextmenu.add(0, MENU_REMOVE_ITEM_FROM_LIST, 0,
R.string.menu_remove_item)
.setShortcut('3', 'r');
contextmenu.add(0, MENU_DELETE_ITEM, 0,
R.string.menu_delete_item)
.setShortcut('4', 'd');
contextmenu.add(0, MENU_MOVE_ITEM, 0,
R.string.menu_move_item).setShortcut('5', 'l');
}
});
}
|
diff --git a/src/main/java/config/PlanningServerModule.java b/src/main/java/config/PlanningServerModule.java
index 659dfe4..dc13f51 100644
--- a/src/main/java/config/PlanningServerModule.java
+++ b/src/main/java/config/PlanningServerModule.java
@@ -1,38 +1,38 @@
package config;
import auth.Authenticator;
import auth.TwitterAuthenticator;
import com.google.common.base.Strings;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.name.Named;
import twitter4j.TwitterFactory;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import static com.google.inject.name.Names.named;
public class PlanningServerModule extends AbstractModule {
@Override
protected void configure() {
bindConstant().annotatedWith(named("oAuth.callback")).to(env("OAUTH_CALLBACK"));
- bindConstant().annotatedWith(named("oAuth.key")).to(env("OAUTH_CONSUMER-KEY"));
- bindConstant().annotatedWith(named("oAuth.secret")).to(env("OAUTH_CONSUMER-SECRET"));
+ bindConstant().annotatedWith(named("oAuth.key")).to(env("OAUTH_CONSUMER_KEY"));
+ bindConstant().annotatedWith(named("oAuth.secret")).to(env("OAUTH_CONSUMER_SECRET"));
bind(Authenticator.class).to(TwitterAuthenticator.class);
}
@Provides
private Configuration createConfiguration(@Named("oAuth.key") String key, @Named("oAuth.secret") String secret) {
return new ConfigurationBuilder().setOAuthConsumerKey(key).setOAuthConsumerSecret(secret).build();
}
@Provides
private TwitterFactory createTwitterFactory(Configuration config) {
return new TwitterFactory(config);
}
private static String env(String name) {
return Strings.nullToEmpty(System.getenv(name));
}
}
| true | true | protected void configure() {
bindConstant().annotatedWith(named("oAuth.callback")).to(env("OAUTH_CALLBACK"));
bindConstant().annotatedWith(named("oAuth.key")).to(env("OAUTH_CONSUMER-KEY"));
bindConstant().annotatedWith(named("oAuth.secret")).to(env("OAUTH_CONSUMER-SECRET"));
bind(Authenticator.class).to(TwitterAuthenticator.class);
}
| protected void configure() {
bindConstant().annotatedWith(named("oAuth.callback")).to(env("OAUTH_CALLBACK"));
bindConstant().annotatedWith(named("oAuth.key")).to(env("OAUTH_CONSUMER_KEY"));
bindConstant().annotatedWith(named("oAuth.secret")).to(env("OAUTH_CONSUMER_SECRET"));
bind(Authenticator.class).to(TwitterAuthenticator.class);
}
|
diff --git a/src/org/Barteks2x/b173gen/generator/ChunkProviderGenerate.java b/src/org/Barteks2x/b173gen/generator/ChunkProviderGenerate.java
index 0a36e85..22f6804 100644
--- a/src/org/Barteks2x/b173gen/generator/ChunkProviderGenerate.java
+++ b/src/org/Barteks2x/b173gen/generator/ChunkProviderGenerate.java
@@ -1,806 +1,806 @@
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode
package org.Barteks2x.b173gen.generator;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import net.minecraft.server.v1_4_6.BiomeBase;
import net.minecraft.server.v1_4_6.Block;
import net.minecraft.server.v1_4_6.BlockSand;
import net.minecraft.server.v1_4_6.Chunk;
import net.minecraft.server.v1_4_6.ChunkPosition;
import net.minecraft.server.v1_4_6.EnumCreatureType;
import net.minecraft.server.v1_4_6.IChunkProvider;
import net.minecraft.server.v1_4_6.IProgressUpdate;
import net.minecraft.server.v1_4_6.Material;
import net.minecraft.server.v1_4_6.WorldGenStronghold;
import net.minecraft.server.v1_4_6.WorldGenerator;
import org.Barteks2x.b173gen.generator.beta173.BiomeGenBase;
import org.Barteks2x.b173gen.generator.beta173.MapGenBase;
import org.Barteks2x.b173gen.generator.beta173.MapGenCaves;
import org.Barteks2x.b173gen.generator.beta173.NoiseGeneratorOctaves;
import org.Barteks2x.b173gen.generator.beta173.Wcm;
import org.Barteks2x.b173gen.generator.beta173.WorldGenCactus;
import org.Barteks2x.b173gen.generator.beta173.WorldGenClay;
import org.Barteks2x.b173gen.generator.beta173.WorldGenDeadBush;
import org.Barteks2x.b173gen.generator.beta173.WorldGenDungeons;
import org.Barteks2x.b173gen.generator.beta173.WorldGenFlowers;
import org.Barteks2x.b173gen.generator.beta173.WorldGenLakes;
import org.Barteks2x.b173gen.generator.beta173.WorldGenLiquids;
import org.Barteks2x.b173gen.generator.beta173.WorldGenMinable;
import org.Barteks2x.b173gen.generator.beta173.WorldGenPumpkin;
import org.Barteks2x.b173gen.generator.beta173.WorldGenReed;
import org.Barteks2x.b173gen.generator.beta173.WorldGenTallGrass;
import org.Barteks2x.b173gen.plugin.Generator;
import org.Barteks2x.b173gen.plugin.WorldConfig;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_4_6.CraftWorld;
import org.bukkit.generator.ChunkGenerator;
// Referenced classes of package net.minecraft.src:
// IChunkProvider, MapGenCaves, NoiseGeneratorOctaves, Block,
// BiomeGenBase, Chunk, World, WorldChunkManager,
// MapGenBase, BlockSand, WorldGenLakes, WorldGenDungeons,
// WorldGenClay, WorldGenMinable, WorldGenerator, WorldGenFlowers,
// BlockFlower, WorldGenTallGrass, BlockTallGrass, WorldGenDeadBush,
// BlockDeadBush, WorldGenReed, WorldGenPumpkin, WorldGenCactus,
// WorldGenLiquids, Material, IProgressUpdate
public class ChunkProviderGenerate extends ChunkGenerator implements
IChunkProvider {
private Random rand;
private NoiseGeneratorOctaves noiseOctaves1;
private NoiseGeneratorOctaves noiseOctaves2;
private NoiseGeneratorOctaves noiseOctaves3;
private NoiseGeneratorOctaves noiseOctaves4;
private NoiseGeneratorOctaves noiseOctaves5;
public NoiseGeneratorOctaves noiseOctaves6;
public NoiseGeneratorOctaves noiseOctaves7;
public NoiseGeneratorOctaves mobSpawnerNoise;
private net.minecraft.server.v1_4_6.World worldObj;
private double noiseArray[];
private double sandNoise[] = new double[256];
private double gravelNoise[] = new double[256];
private double stoneNoise[] = new double[256];
private MapGenBase caves = new MapGenCaves();
private BiomeBase[] biomesForGeneration;
double field_4185_d[];
double field_4184_e[];
double field_4183_f[];
double field_4182_g[];
double field_4181_h[];
int field_914_i[][] = new int[32][32];
private float[] generatedTemperatures;
private Wcm wcm;
private List<org.bukkit.generator.BlockPopulator> populatorList;
private WorldConfig worldSettings;
private Generator plugin;
@Override
public List<org.bukkit.generator.BlockPopulator> getDefaultPopulators(
World world) {
return populatorList;
}
public void init(net.minecraft.server.v1_4_6.World workWorld, Wcm wcm1,
long seed) {
worldObj = workWorld;
this.wcm = wcm1;
rand = new Random(seed);
noiseOctaves1 = new NoiseGeneratorOctaves(rand, 16);
noiseOctaves2 = new NoiseGeneratorOctaves(rand, 16);
noiseOctaves3 = new NoiseGeneratorOctaves(rand, 8);
noiseOctaves4 = new NoiseGeneratorOctaves(rand, 4);
noiseOctaves5 = new NoiseGeneratorOctaves(rand, 4);
noiseOctaves6 = new NoiseGeneratorOctaves(rand, 10);
noiseOctaves7 = new NoiseGeneratorOctaves(rand, 16);
mobSpawnerNoise = new NoiseGeneratorOctaves(rand, 8);
caves = new MapGenCaves();
field_914_i = new int[32][32];
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public ChunkProviderGenerate(WorldConfig worldSettings, Generator plugin) {
this.plugin = plugin;
this.worldSettings = worldSettings;
this.worldSettings.chunkProvider = this;
this.populatorList = new ArrayList();
this.populatorList.add(new BlockPopulator(this));
}
public void generateTerrain(int i, int j, byte terrainBlockArray[],
double ad[]) {
byte byte0 = 4;
byte byte1 = 64;
int k = byte0 + 1;
byte byte2 = 17;
int l = byte0 + 1;
noiseArray = initializeNoiseField(noiseArray, i * byte0, 0, j * byte0,
k, byte2, l);
for (int i1 = 0; i1 < byte0; i1++) {
for (int j1 = 0; j1 < byte0; j1++) {
for (int k1 = 0; k1 < 16; k1++) {
double d = 0.125D;
double d1 = noiseArray[((i1 + 0) * l + (j1 + 0)) * byte2
+ (k1 + 0)];
double d2 = noiseArray[((i1 + 0) * l + (j1 + 1)) * byte2
+ (k1 + 0)];
double d3 = noiseArray[((i1 + 1) * l + (j1 + 0)) * byte2
+ (k1 + 0)];
double d4 = noiseArray[((i1 + 1) * l + (j1 + 1)) * byte2
+ (k1 + 0)];
double d5 = (noiseArray[((i1 + 0) * l + (j1 + 0)) * byte2
+ (k1 + 1)] - d1)
* d;
double d6 = (noiseArray[((i1 + 0) * l + (j1 + 1)) * byte2
+ (k1 + 1)] - d2)
* d;
double d7 = (noiseArray[((i1 + 1) * l + (j1 + 0)) * byte2
+ (k1 + 1)] - d3)
* d;
double d8 = (noiseArray[((i1 + 1) * l + (j1 + 1)) * byte2
+ (k1 + 1)] - d4)
* d;
for (int l1 = 0; l1 < 8; l1++) {
double d9 = 0.25D;
double d10 = d1;
double d11 = d2;
double d12 = (d3 - d1) * d9;
double d13 = (d4 - d2) * d9;
for (int i2 = 0; i2 < 4; i2++) {
int blockInArray = i2 + i1 * 4 << 11
| 0 + j1 * 4 << 7 | k1 * 8 + l1;
char c = '\200';
double d14 = 0.25D;
double d15 = d10;
double d16 = (d11 - d10) * d14;
for (int k2 = 0; k2 < 4; k2++) {
double d17 = ad[(i1 * 4 + i2) * 16
+ (j1 * 4 + k2)];
int block = 0;
if (k1 * 8 + l1 < byte1) {
if (d17 < 0.5D && k1 * 8 + l1 >= byte1 - 1) {
block = Block.ICE.id;
} else {
block = Block.STATIONARY_WATER.id;
}
}
if (d15 > 0.0D) {
block = Block.STONE.id;
}
terrainBlockArray[blockInArray] = (byte) block;
blockInArray += c;
d15 += d16;
}
d10 += d12;
d11 += d13;
}
d1 += d5;
d2 += d6;
d3 += d7;
d4 += d8;
}
}
}
}
}
public byte[] generate(int x, int z) {
this.rand.setSeed(x * 341873128712L + z * 132897987541L);
byte abyte[] = new byte[32768];
Chunk chunk = new Chunk(worldObj, abyte, x, z);
biomesForGeneration = wcm.getBiomeBlock(biomesForGeneration, x * 16,
z * 16, 16, 16);
double ad[] = this.wcm.temperature;
generateTerrain(x, z, abyte, ad);
replaceBlocksForBiome(x, z, abyte, biomesForGeneration);
caves.func_867_a(this, worldObj, x, z, abyte);// caves
chunk.initLighting();
return abyte;
}
@Override
public byte[][] generateBlockSections(World world, Random random, int x,
int z, BiomeGrid biomes) {
byte[] blockArray = generate(x, z);
// //System.out.println("genBlockSection");
byte[][] sectionBlocks = new byte[16][];
// TODO Too slow, for fix need change generator output.
int blockInArray = 0;
for (int blockInSectionX = 0; blockInSectionX < 16; blockInSectionX++) {
for (int blockInSectionZ = 0; blockInSectionZ < 16; blockInSectionZ++) {
for (int section = 0; section < 8; section++) {
for (int blockInSectionY = 0; blockInSectionY < 16; blockInSectionY++) {
sectionBlocks[section][blockInSectionX
| (blockInSectionZ << 4)
| (blockInSectionY << 8)] = blockArray[blockInArray++];
}
}
}
}
return sectionBlocks;
}
@Override
public short[][] generateExtBlockSections(World world, Random random,
int x, int z, BiomeGrid biomes) {
byte[] blockArray;
try {
blockArray = generate(x, z);
} catch (java.lang.NullPointerException e) {
net.minecraft.server.v1_4_6.World workWorld = ((CraftWorld) world)
.getHandle();
Wcm wcm1 = new Wcm(workWorld.getSeed());
workWorld.worldProvider.d = wcm1;
this.init(workWorld, wcm1, workWorld.getSeed());
blockArray = generate(x, z);
}
short[][] sectionBlocks = new short[16][4096];
int blockInArray = 0;
for (int blockInSectionX = 0; blockInSectionX < 16; blockInSectionX++) {
for (int blockInSectionZ = 0; blockInSectionZ < 16; blockInSectionZ++) {
for (int section = 0; section < 8; section++) {
for (int blockInSectionY = 0; blockInSectionY < 16; blockInSectionY++) {
sectionBlocks[section][blockInSectionX
| (blockInSectionZ << 4)
| (blockInSectionY << 8)] = blockArray[blockInArray++];
}
}
}
}
return sectionBlocks;
}
public void replaceBlocksForBiome(int i, int j, byte terrainBlockArray[],
BiomeBase abiomebase[]) {
byte byte0 = 64;
double d = 0.03125D;
sandNoise = noiseOctaves4.generateNoiseOctaves(sandNoise, i * 16,
j * 16, 0.0D, 16, 16, 1, d, d, 1.0D);
gravelNoise = noiseOctaves4.generateNoiseOctaves(gravelNoise, i * 16,
109.0134D, j * 16, 16, 1, 16, d, 1.0D, d);
stoneNoise = noiseOctaves5.generateNoiseOctaves(stoneNoise, i * 16,
j * 16, 0.0D, 16, 16, 1, d * 2D, d * 2D, d * 2D);
for (int k = 0; k < 16; k++) {
for (int l = 0; l < 16; l++) {
BiomeBase biomegenbase = abiomebase[k + l * 16];
boolean randomSand = sandNoise[k + l * 16] + rand.nextDouble()
* 0.20000000000000001D > 0.0D;
boolean randomGravel = gravelNoise[k + l * 16]
+ rand.nextDouble() * 0.20000000000000001D > 3D;
int i1 = (int) (stoneNoise[k + l * 16] / 3D + 3D + rand
.nextDouble() * 0.25D);
int j1 = -1;
byte topBlock = biomegenbase.A;
byte fillerBlock = biomegenbase.B;
for (int k1 = 127; k1 >= 0; k1--) {
int currentBlockInArrayNum = (l * 16 + k) * 128 + k1;
if (k1 <= 0 + rand.nextInt(5)) {
terrainBlockArray[currentBlockInArrayNum] = (byte) Block.BEDROCK.id;
continue;
}
byte currentBlock = terrainBlockArray[currentBlockInArrayNum];
if (currentBlock == 0) {
j1 = -1;
continue;
}
if (currentBlock != Block.STONE.id) {
continue;
}
if (j1 == -1) {
if (i1 <= 0) {
topBlock = 0;
fillerBlock = (byte) Block.STONE.id;
} else if (k1 >= byte0 - 4 && k1 <= byte0 + 1) {
topBlock = biomegenbase.A;
fillerBlock = biomegenbase.B;
if (randomGravel) {
topBlock = 0;
}
if (randomGravel) {
fillerBlock = (byte) Block.GRAVEL.id;
}
if (randomSand) {
topBlock = (byte) Block.SAND.id;
}
if (randomSand) {
fillerBlock = (byte) Block.SAND.id;
}
}
if (k1 < byte0 && topBlock == 0) {
topBlock = (byte) Block.STATIONARY_WATER.id;
}
j1 = i1;
if (k1 >= byte0 - 1) {
terrainBlockArray[currentBlockInArrayNum] = topBlock;
} else {
terrainBlockArray[currentBlockInArrayNum] = fillerBlock;
}
continue;
}
if (j1 <= 0) {
continue;
}
j1--;
terrainBlockArray[currentBlockInArrayNum] = fillerBlock;
if (j1 == 0 && fillerBlock == Block.SAND.id) {
j1 = rand.nextInt(4);
fillerBlock = (byte) Block.SANDSTONE.id;
}
}
}
}
}
public Chunk getChunkAt(int i, int j) {
return getOrCreateChunk(i, j);
}
@SuppressWarnings("cast")
public Chunk getOrCreateChunk(int i, int j) {
rand.setSeed((long) i * 0x4f9939f508L + (long) j * 0x1ef1565bd5L);
byte abyte0[] = new byte[32768];
Chunk chunk = new Chunk(worldObj, abyte0, i, j);
biomesForGeneration = this.wcm.getBiomeBlock(biomesForGeneration,
i * 16, j * 16, 16, 16);
double ad[] = this.wcm.temperature;
generateTerrain(i, j, abyte0, ad);
replaceBlocksForBiome(i, j, abyte0, biomesForGeneration);
caves.func_867_a(this, worldObj, i, j, abyte0);
chunk.initLighting();
return chunk;
}
@SuppressWarnings("cast")
private double[] initializeNoiseField(double ad[], int i, int j, int k,
int l, int i1, int j1) {
if (ad == null) {
ad = new double[l * i1 * j1];
}
double d = 684.41200000000003D;
double d1 = 684.41200000000003D;
double ad1[] = this.wcm.temperature;
double ad2[] = this.wcm.rain;
field_4182_g = noiseOctaves6.func_4109_a(field_4182_g, i, k, l, j1,
1.121D, 1.121D, 0.5D);
field_4181_h = noiseOctaves7.func_4109_a(field_4181_h, i, k, l, j1,
200D, 200D, 0.5D);
field_4185_d = noiseOctaves3.generateNoiseOctaves(field_4185_d, i, j,
k, l, i1, j1, d / 80D, d1 / 160D, d / 80D);
field_4184_e = noiseOctaves1.generateNoiseOctaves(field_4184_e, i, j,
k, l, i1, j1, d, d1, d);
field_4183_f = noiseOctaves2.generateNoiseOctaves(field_4183_f, i, j,
k, l, i1, j1, d, d1, d);
int k1 = 0;
int l1 = 0;
int i2 = 16 / l;
for (int j2 = 0; j2 < l; j2++) {
int k2 = j2 * i2 + i2 / 2;
for (int l2 = 0; l2 < j1; l2++) {
int i3 = l2 * i2 + i2 / 2;
double d2 = ad1[k2 * 16 + i3];
double d3 = ad2[k2 * 16 + i3] * d2;
double d4 = 1.0D - d3;
d4 *= d4;
d4 *= d4;
d4 = 1.0D - d4;
double d5 = (field_4182_g[l1] + 256D) / 512D;
d5 *= d4;
if (d5 > 1.0D) {
d5 = 1.0D;
}
double d6 = field_4181_h[l1] / 8000D;
if (d6 < 0.0D) {
d6 = -d6 * 0.29999999999999999D;
}
d6 = d6 * 3D - 2D;
if (d6 < 0.0D) {
d6 /= 2D;
if (d6 < -1D) {
d6 = -1D;
}
d6 /= 1.3999999999999999D;
d6 /= 2D;
d5 = 0.0D;
} else {
if (d6 > 1.0D) {
d6 = 1.0D;
}
d6 /= 8D;
}
if (d5 < 0.0D) {
d5 = 0.0D;
}
d5 += 0.5D;
d6 = (d6 * (double) i1) / 16D;
double d7 = (double) i1 / 2D + d6 * 4D;
l1++;
for (int j3 = 0; j3 < i1; j3++) {
double d8 = 0.0D;
double d9 = (((double) j3 - d7) * 12D) / d5;
if (d9 < 0.0D) {
d9 *= 4D;
}
double d10 = field_4184_e[k1] / 512D;
double d11 = field_4183_f[k1] / 512D;
double d12 = (field_4185_d[k1] / 10D + 1.0D) / 2D;
if (d12 < 0.0D) {
d8 = d10;
} else if (d12 > 1.0D) {
d8 = d11;
} else {
d8 = d10 + (d11 - d10) * d12;
}
d8 -= d9;
if (j3 > i1 - 4) {
double d13 = (float) (j3 - (i1 - 4)) / 3F;
d8 = d8 * (1.0D - d13) + -10D * d13;
}
ad[k1] = d8;
k1++;
}
}
}
// //System.out.println("selectBiome end");
return ad;
}
@SuppressWarnings("cast")
public void getChunkAt(IChunkProvider ichunkprovider, int i, int j) {
BlockSand.instaFall = true;
int k = i * 16;
int l = j * 16;
BiomeGenBase biomegenbase = this.wcm.getBiome(k + 16, l + 16);
rand.setSeed(worldObj.getSeed());
long l1 = (rand.nextLong() / 2L) * 2L + 1L;
long l2 = (rand.nextLong() / 2L) * 2L + 1L;
rand.setSeed((long) i * l1 + (long) j * l2 ^ worldObj.getSeed());
double d = 0.25D;
if (rand.nextInt(4) == 0) {
int i1 = k + rand.nextInt(16) + 8;
int l4 = rand.nextInt(128);
int i8 = l + rand.nextInt(16) + 8;
(new WorldGenLakes(Block.WATER.id)).a(worldObj, rand, i1, l4, i8);
}
if (rand.nextInt(8) == 0) {
int j1 = k + rand.nextInt(16) + 8;
int i5 = rand.nextInt(rand.nextInt(120) + 8);
int j8 = l + rand.nextInt(16) + 8;
if (i5 < 64 || rand.nextInt(10) == 0) {
(new WorldGenLakes(Block.LAVA.id))
.a(worldObj, rand, j1, i5, j8);
}
}
for (int k1 = 0; k1 < 8; k1++) {
int j5 = k + rand.nextInt(16) + 8;
int k8 = rand.nextInt(128);
int j11 = l + rand.nextInt(16) + 8;
(new WorldGenDungeons()).a(worldObj, rand, j5, k8, j11);
}
for (int i2 = 0; i2 < 10; i2++) {
int k5 = k + rand.nextInt(16);
int l8 = rand.nextInt(128);
int k11 = l + rand.nextInt(16);
(new WorldGenClay(32)).a(worldObj, rand, k5, l8, k11);
}
for (int j2 = 0; j2 < 20; j2++) {
int l5 = k + rand.nextInt(16);
int i9 = rand.nextInt(128);
int l11 = l + rand.nextInt(16);
(new WorldGenMinable(Block.DIRT.id, 32)).a(worldObj, rand, l5, i9,
l11);
}
for (int k2 = 0; k2 < 10; k2++) {
int i6 = k + rand.nextInt(16);
int j9 = rand.nextInt(128);
int i12 = l + rand.nextInt(16);
(new WorldGenMinable(Block.GRAVEL.id, 32)).a(worldObj, rand, i6,
j9, i12);
}
for (int i3 = 0; i3 < 20; i3++) {
int j6 = k + rand.nextInt(16);
int k9 = rand.nextInt(128);
int j12 = l + rand.nextInt(16);
(new WorldGenMinable(Block.COAL_ORE.id, 16)).a(worldObj, rand, j6,
k9, j12);
}
for (int j3 = 0; j3 < 20; j3++) {
int k6 = k + rand.nextInt(16);
int l9 = rand.nextInt(64);
int k12 = l + rand.nextInt(16);
(new WorldGenMinable(Block.IRON_ORE.id, 8)).a(worldObj, rand, k6,
l9, k12);
}
for (int k3 = 0; k3 < 2; k3++) {
int l6 = k + rand.nextInt(16);
int i10 = rand.nextInt(32);
int l12 = l + rand.nextInt(16);
(new WorldGenMinable(Block.GOLD_ORE.id, 8)).a(worldObj, rand, l6,
i10, l12);
}
for (int l3 = 0; l3 < 8; l3++) {
int i7 = k + rand.nextInt(16);
int j10 = rand.nextInt(16);
int i13 = l + rand.nextInt(16);
(new WorldGenMinable(Block.REDSTONE_ORE.id, 7)).a(worldObj, rand,
i7, j10, i13);
}
for (int i4 = 0; i4 < 1; i4++) {
int j7 = k + rand.nextInt(16);
int k10 = rand.nextInt(16);
int j13 = l + rand.nextInt(16);
(new WorldGenMinable(Block.DIAMOND_ORE.id, 7)).a(worldObj, rand,
j7, k10, j13);
}
for (int j4 = 0; j4 < 1; j4++) {
int k7 = k + rand.nextInt(16);
int l10 = rand.nextInt(16) + rand.nextInt(16);
int k13 = l + rand.nextInt(16);
(new WorldGenMinable(Block.LAPIS_ORE.id, 6)).a(worldObj, rand, k7,
l10, k13);
}
d = 0.5D;
int k4 = (int) ((mobSpawnerNoise.func_806_a((double) k * d, (double) l
* d)
/ 8D + rand.nextDouble() * 4D + 4D) / 3D);
int l7 = 0;
if (rand.nextInt(10) == 0) {
l7++;
}
if (biomegenbase == BiomeGenBase.forest) {
l7 += k4 + 5;
}
if (biomegenbase == BiomeGenBase.rainforest) {
l7 += k4 + 5;
}
if (biomegenbase == BiomeGenBase.seasonalForest) {
l7 += k4 + 2;
}
if (biomegenbase == BiomeGenBase.taiga) {
l7 += k4 + 5;
}
if (biomegenbase == BiomeGenBase.desert) {
l7 -= 20;
}
if (biomegenbase == BiomeGenBase.tundra) {
l7 -= 20;
}
if (biomegenbase == BiomeGenBase.plains) {
l7 -= 20;
}
for (int i11 = 0; i11 < l7; i11++) {
int l13 = k + rand.nextInt(16) + 8;
int j14 = l + rand.nextInt(16) + 8;
WorldGenerator worldgenerator = biomegenbase.a(rand);
worldgenerator.a(1.0D, 1.0D, 1.0D);
worldgenerator.a(worldObj, rand, l13,
worldObj.getHighestBlockYAt(l13, j14), j14);
}
byte byte0 = 0;
if (biomegenbase == BiomeGenBase.forest) {
byte0 = 2;
}
if (biomegenbase == BiomeGenBase.seasonalForest) {
byte0 = 4;
}
if (biomegenbase == BiomeGenBase.taiga) {
byte0 = 2;
}
if (biomegenbase == BiomeGenBase.plains) {
byte0 = 3;
}
for (int i14 = 0; i14 < byte0; i14++) {
int k14 = k + rand.nextInt(16) + 8;
int l16 = rand.nextInt(128);
int k19 = l + rand.nextInt(16) + 8;
(new WorldGenFlowers(Block.YELLOW_FLOWER.id)).a(worldObj, rand,
k14, l16, k19);
}
byte byte1 = 0;
if (biomegenbase == BiomeGenBase.forest) {
byte1 = 2;
}
if (biomegenbase == BiomeGenBase.rainforest) {
byte1 = 10;
}
if (biomegenbase == BiomeGenBase.seasonalForest) {
byte1 = 2;
}
if (biomegenbase == BiomeGenBase.taiga) {
byte1 = 1;
}
if (biomegenbase == BiomeGenBase.plains) {
byte1 = 10;
}
for (int l14 = 0; l14 < byte1; l14++) {
byte byte2 = 1;
if (biomegenbase == BiomeGenBase.rainforest && rand.nextInt(3) != 0) {
byte2 = 2;
}
int l19 = k + rand.nextInt(16) + 8;
int k22 = rand.nextInt(128);
int j24 = l + rand.nextInt(16) + 8;
(new WorldGenTallGrass(Block.LONG_GRASS.id, byte2)).a(worldObj,
rand, l19, k22, j24);
}
byte1 = 0;
if (biomegenbase == BiomeGenBase.desert) {
byte1 = 2;
}
for (int i15 = 0; i15 < byte1; i15++) {
int i17 = k + rand.nextInt(16) + 8;
int i20 = rand.nextInt(128);
int l22 = l + rand.nextInt(16) + 8;
(new WorldGenDeadBush(Block.DEAD_BUSH.id)).a(worldObj, rand, i17,
i20, l22);
}
if (rand.nextInt(2) == 0) {
int j15 = k + rand.nextInt(16) + 8;
int j17 = rand.nextInt(128);
int j20 = l + rand.nextInt(16) + 8;
(new WorldGenFlowers(Block.RED_ROSE.id)).a(worldObj, rand, j15,
j17, j20);
}
if (rand.nextInt(4) == 0) {
int k15 = k + rand.nextInt(16) + 8;
int k17 = rand.nextInt(128);
int k20 = l + rand.nextInt(16) + 8;
(new WorldGenFlowers(Block.BROWN_MUSHROOM.id)).a(worldObj, rand,
k15, k17, k20);
}
if (rand.nextInt(8) == 0) {
int l15 = k + rand.nextInt(16) + 8;
int l17 = rand.nextInt(128);
int l20 = l + rand.nextInt(16) + 8;
(new WorldGenFlowers(Block.RED_MUSHROOM.id)).a(worldObj, rand, l15,
l17, l20);
}
for (int i16 = 0; i16 < 10; i16++) {
int i18 = k + rand.nextInt(16) + 8;
int i21 = rand.nextInt(128);
int i23 = l + rand.nextInt(16) + 8;
(new WorldGenReed()).a(worldObj, rand, i18, i21, i23);
}
if (rand.nextInt(32) == 0) {
int j16 = k + rand.nextInt(16) + 8;
int j18 = rand.nextInt(128);
int j21 = l + rand.nextInt(16) + 8;
(new WorldGenPumpkin()).a(worldObj, rand, j16, j18, j21);
}
int k16 = 0;
if (biomegenbase == BiomeGenBase.desert) {
k16 += 10;
}
for (int k18 = 0; k18 < k16; k18++) {
int k21 = k + rand.nextInt(16) + 8;
int j23 = rand.nextInt(128);
int k24 = l + rand.nextInt(16) + 8;
(new WorldGenCactus()).a(worldObj, rand, k21, j23, k24);
}
for (int l18 = 0; l18 < 50; l18++) {
int l21 = k + rand.nextInt(16) + 8;
int k23 = rand.nextInt(rand.nextInt(120) + 8);
int l24 = l + rand.nextInt(16) + 8;
(new WorldGenLiquids(Block.WATER.id)).a(worldObj, rand, l21, k23,
l24);
}
for (int i19 = 0; i19 < 20; i19++) {
int i22 = k + rand.nextInt(16) + 8;
int l23 = rand.nextInt(rand.nextInt(rand.nextInt(112) + 8) + 8);
int i25 = l + rand.nextInt(16) + 8;
(new WorldGenLiquids(Block.LAVA.id)).a(worldObj, rand, i22, l23,
i25);
}
generatedTemperatures = this.wcm.getTemperatures(generatedTemperatures,
k + 8, l + 8, 16, 16);
for (int j19 = k + 8; j19 < k + 8 + 16; j19++) {
for (int j22 = l + 8; j22 < l + 8 + 16; j22++) {
int i24 = j19 - (k + 8);
int j25 = j22 - (l + 8);
- int k25 = worldObj.g(j19, j22);
+ int k25 = worldObj.getHighestBlockYAt(j19, j22);
double d1 = generatedTemperatures[i24 * 16 + j25]
- ((double) (k25 - 64) / 64D) * 0.29999999999999999D;
if (d1 < 0.5D
&& k25 > 0
&& k25 < 128
&& worldObj.isEmpty(j19, k25, j22)
&& worldObj.getMaterial(j19, k25 - 1, j22).isSolid()
&& worldObj.getMaterial(j19, k25 - 1, j22) != Material.ICE) {
worldObj.setTypeId(j19, k25, j22, Block.SNOW.id);
}
}
}
BlockSand.instaFall = false;
}
public boolean saveChunks(boolean flag, IProgressUpdate iprogressupdate) {
return true;
}
public boolean canSave() {
return true;
}
public String makeString() {
return "RandomLevelSource";
}
@SuppressWarnings("rawtypes")
public List getMobsFor(EnumCreatureType type, int x, int y, int z) {
BiomeBase biome = this.wcm.getBiome(x, z);
return biome.getMobs(type);
}
public boolean unloadChunks() {
return false;
}
public boolean isChunkLoaded(int x, int z) {
return true;
}
private final WorldGenStronghold strongholdGen = new WorldGenStronghold();
public ChunkPosition findNearestMapFeature(
net.minecraft.server.v1_4_6.World world, String type, int x, int y,
int z) {
return ((("Stronghold".equals(type)) && (this.strongholdGen != null)) ? this.strongholdGen
.getNearestGeneratedFeature(world, x, y, z) : null);
}
public int getLoadedChunks() {
// TODO Auto-generated method stub
return 0;
}
public String getName() {
return plugin.getDescription().getName();
}
public void recreateStructures(int arg0, int arg1) {
// TODO Auto-generated method stub
}
}
| true | true | public void getChunkAt(IChunkProvider ichunkprovider, int i, int j) {
BlockSand.instaFall = true;
int k = i * 16;
int l = j * 16;
BiomeGenBase biomegenbase = this.wcm.getBiome(k + 16, l + 16);
rand.setSeed(worldObj.getSeed());
long l1 = (rand.nextLong() / 2L) * 2L + 1L;
long l2 = (rand.nextLong() / 2L) * 2L + 1L;
rand.setSeed((long) i * l1 + (long) j * l2 ^ worldObj.getSeed());
double d = 0.25D;
if (rand.nextInt(4) == 0) {
int i1 = k + rand.nextInt(16) + 8;
int l4 = rand.nextInt(128);
int i8 = l + rand.nextInt(16) + 8;
(new WorldGenLakes(Block.WATER.id)).a(worldObj, rand, i1, l4, i8);
}
if (rand.nextInt(8) == 0) {
int j1 = k + rand.nextInt(16) + 8;
int i5 = rand.nextInt(rand.nextInt(120) + 8);
int j8 = l + rand.nextInt(16) + 8;
if (i5 < 64 || rand.nextInt(10) == 0) {
(new WorldGenLakes(Block.LAVA.id))
.a(worldObj, rand, j1, i5, j8);
}
}
for (int k1 = 0; k1 < 8; k1++) {
int j5 = k + rand.nextInt(16) + 8;
int k8 = rand.nextInt(128);
int j11 = l + rand.nextInt(16) + 8;
(new WorldGenDungeons()).a(worldObj, rand, j5, k8, j11);
}
for (int i2 = 0; i2 < 10; i2++) {
int k5 = k + rand.nextInt(16);
int l8 = rand.nextInt(128);
int k11 = l + rand.nextInt(16);
(new WorldGenClay(32)).a(worldObj, rand, k5, l8, k11);
}
for (int j2 = 0; j2 < 20; j2++) {
int l5 = k + rand.nextInt(16);
int i9 = rand.nextInt(128);
int l11 = l + rand.nextInt(16);
(new WorldGenMinable(Block.DIRT.id, 32)).a(worldObj, rand, l5, i9,
l11);
}
for (int k2 = 0; k2 < 10; k2++) {
int i6 = k + rand.nextInt(16);
int j9 = rand.nextInt(128);
int i12 = l + rand.nextInt(16);
(new WorldGenMinable(Block.GRAVEL.id, 32)).a(worldObj, rand, i6,
j9, i12);
}
for (int i3 = 0; i3 < 20; i3++) {
int j6 = k + rand.nextInt(16);
int k9 = rand.nextInt(128);
int j12 = l + rand.nextInt(16);
(new WorldGenMinable(Block.COAL_ORE.id, 16)).a(worldObj, rand, j6,
k9, j12);
}
for (int j3 = 0; j3 < 20; j3++) {
int k6 = k + rand.nextInt(16);
int l9 = rand.nextInt(64);
int k12 = l + rand.nextInt(16);
(new WorldGenMinable(Block.IRON_ORE.id, 8)).a(worldObj, rand, k6,
l9, k12);
}
for (int k3 = 0; k3 < 2; k3++) {
int l6 = k + rand.nextInt(16);
int i10 = rand.nextInt(32);
int l12 = l + rand.nextInt(16);
(new WorldGenMinable(Block.GOLD_ORE.id, 8)).a(worldObj, rand, l6,
i10, l12);
}
for (int l3 = 0; l3 < 8; l3++) {
int i7 = k + rand.nextInt(16);
int j10 = rand.nextInt(16);
int i13 = l + rand.nextInt(16);
(new WorldGenMinable(Block.REDSTONE_ORE.id, 7)).a(worldObj, rand,
i7, j10, i13);
}
for (int i4 = 0; i4 < 1; i4++) {
int j7 = k + rand.nextInt(16);
int k10 = rand.nextInt(16);
int j13 = l + rand.nextInt(16);
(new WorldGenMinable(Block.DIAMOND_ORE.id, 7)).a(worldObj, rand,
j7, k10, j13);
}
for (int j4 = 0; j4 < 1; j4++) {
int k7 = k + rand.nextInt(16);
int l10 = rand.nextInt(16) + rand.nextInt(16);
int k13 = l + rand.nextInt(16);
(new WorldGenMinable(Block.LAPIS_ORE.id, 6)).a(worldObj, rand, k7,
l10, k13);
}
d = 0.5D;
int k4 = (int) ((mobSpawnerNoise.func_806_a((double) k * d, (double) l
* d)
/ 8D + rand.nextDouble() * 4D + 4D) / 3D);
int l7 = 0;
if (rand.nextInt(10) == 0) {
l7++;
}
if (biomegenbase == BiomeGenBase.forest) {
l7 += k4 + 5;
}
if (biomegenbase == BiomeGenBase.rainforest) {
l7 += k4 + 5;
}
if (biomegenbase == BiomeGenBase.seasonalForest) {
l7 += k4 + 2;
}
if (biomegenbase == BiomeGenBase.taiga) {
l7 += k4 + 5;
}
if (biomegenbase == BiomeGenBase.desert) {
l7 -= 20;
}
if (biomegenbase == BiomeGenBase.tundra) {
l7 -= 20;
}
if (biomegenbase == BiomeGenBase.plains) {
l7 -= 20;
}
for (int i11 = 0; i11 < l7; i11++) {
int l13 = k + rand.nextInt(16) + 8;
int j14 = l + rand.nextInt(16) + 8;
WorldGenerator worldgenerator = biomegenbase.a(rand);
worldgenerator.a(1.0D, 1.0D, 1.0D);
worldgenerator.a(worldObj, rand, l13,
worldObj.getHighestBlockYAt(l13, j14), j14);
}
byte byte0 = 0;
if (biomegenbase == BiomeGenBase.forest) {
byte0 = 2;
}
if (biomegenbase == BiomeGenBase.seasonalForest) {
byte0 = 4;
}
if (biomegenbase == BiomeGenBase.taiga) {
byte0 = 2;
}
if (biomegenbase == BiomeGenBase.plains) {
byte0 = 3;
}
for (int i14 = 0; i14 < byte0; i14++) {
int k14 = k + rand.nextInt(16) + 8;
int l16 = rand.nextInt(128);
int k19 = l + rand.nextInt(16) + 8;
(new WorldGenFlowers(Block.YELLOW_FLOWER.id)).a(worldObj, rand,
k14, l16, k19);
}
byte byte1 = 0;
if (biomegenbase == BiomeGenBase.forest) {
byte1 = 2;
}
if (biomegenbase == BiomeGenBase.rainforest) {
byte1 = 10;
}
if (biomegenbase == BiomeGenBase.seasonalForest) {
byte1 = 2;
}
if (biomegenbase == BiomeGenBase.taiga) {
byte1 = 1;
}
if (biomegenbase == BiomeGenBase.plains) {
byte1 = 10;
}
for (int l14 = 0; l14 < byte1; l14++) {
byte byte2 = 1;
if (biomegenbase == BiomeGenBase.rainforest && rand.nextInt(3) != 0) {
byte2 = 2;
}
int l19 = k + rand.nextInt(16) + 8;
int k22 = rand.nextInt(128);
int j24 = l + rand.nextInt(16) + 8;
(new WorldGenTallGrass(Block.LONG_GRASS.id, byte2)).a(worldObj,
rand, l19, k22, j24);
}
byte1 = 0;
if (biomegenbase == BiomeGenBase.desert) {
byte1 = 2;
}
for (int i15 = 0; i15 < byte1; i15++) {
int i17 = k + rand.nextInt(16) + 8;
int i20 = rand.nextInt(128);
int l22 = l + rand.nextInt(16) + 8;
(new WorldGenDeadBush(Block.DEAD_BUSH.id)).a(worldObj, rand, i17,
i20, l22);
}
if (rand.nextInt(2) == 0) {
int j15 = k + rand.nextInt(16) + 8;
int j17 = rand.nextInt(128);
int j20 = l + rand.nextInt(16) + 8;
(new WorldGenFlowers(Block.RED_ROSE.id)).a(worldObj, rand, j15,
j17, j20);
}
if (rand.nextInt(4) == 0) {
int k15 = k + rand.nextInt(16) + 8;
int k17 = rand.nextInt(128);
int k20 = l + rand.nextInt(16) + 8;
(new WorldGenFlowers(Block.BROWN_MUSHROOM.id)).a(worldObj, rand,
k15, k17, k20);
}
if (rand.nextInt(8) == 0) {
int l15 = k + rand.nextInt(16) + 8;
int l17 = rand.nextInt(128);
int l20 = l + rand.nextInt(16) + 8;
(new WorldGenFlowers(Block.RED_MUSHROOM.id)).a(worldObj, rand, l15,
l17, l20);
}
for (int i16 = 0; i16 < 10; i16++) {
int i18 = k + rand.nextInt(16) + 8;
int i21 = rand.nextInt(128);
int i23 = l + rand.nextInt(16) + 8;
(new WorldGenReed()).a(worldObj, rand, i18, i21, i23);
}
if (rand.nextInt(32) == 0) {
int j16 = k + rand.nextInt(16) + 8;
int j18 = rand.nextInt(128);
int j21 = l + rand.nextInt(16) + 8;
(new WorldGenPumpkin()).a(worldObj, rand, j16, j18, j21);
}
int k16 = 0;
if (biomegenbase == BiomeGenBase.desert) {
k16 += 10;
}
for (int k18 = 0; k18 < k16; k18++) {
int k21 = k + rand.nextInt(16) + 8;
int j23 = rand.nextInt(128);
int k24 = l + rand.nextInt(16) + 8;
(new WorldGenCactus()).a(worldObj, rand, k21, j23, k24);
}
for (int l18 = 0; l18 < 50; l18++) {
int l21 = k + rand.nextInt(16) + 8;
int k23 = rand.nextInt(rand.nextInt(120) + 8);
int l24 = l + rand.nextInt(16) + 8;
(new WorldGenLiquids(Block.WATER.id)).a(worldObj, rand, l21, k23,
l24);
}
for (int i19 = 0; i19 < 20; i19++) {
int i22 = k + rand.nextInt(16) + 8;
int l23 = rand.nextInt(rand.nextInt(rand.nextInt(112) + 8) + 8);
int i25 = l + rand.nextInt(16) + 8;
(new WorldGenLiquids(Block.LAVA.id)).a(worldObj, rand, i22, l23,
i25);
}
generatedTemperatures = this.wcm.getTemperatures(generatedTemperatures,
k + 8, l + 8, 16, 16);
for (int j19 = k + 8; j19 < k + 8 + 16; j19++) {
for (int j22 = l + 8; j22 < l + 8 + 16; j22++) {
int i24 = j19 - (k + 8);
int j25 = j22 - (l + 8);
int k25 = worldObj.g(j19, j22);
double d1 = generatedTemperatures[i24 * 16 + j25]
- ((double) (k25 - 64) / 64D) * 0.29999999999999999D;
if (d1 < 0.5D
&& k25 > 0
&& k25 < 128
&& worldObj.isEmpty(j19, k25, j22)
&& worldObj.getMaterial(j19, k25 - 1, j22).isSolid()
&& worldObj.getMaterial(j19, k25 - 1, j22) != Material.ICE) {
worldObj.setTypeId(j19, k25, j22, Block.SNOW.id);
}
}
}
BlockSand.instaFall = false;
}
| public void getChunkAt(IChunkProvider ichunkprovider, int i, int j) {
BlockSand.instaFall = true;
int k = i * 16;
int l = j * 16;
BiomeGenBase biomegenbase = this.wcm.getBiome(k + 16, l + 16);
rand.setSeed(worldObj.getSeed());
long l1 = (rand.nextLong() / 2L) * 2L + 1L;
long l2 = (rand.nextLong() / 2L) * 2L + 1L;
rand.setSeed((long) i * l1 + (long) j * l2 ^ worldObj.getSeed());
double d = 0.25D;
if (rand.nextInt(4) == 0) {
int i1 = k + rand.nextInt(16) + 8;
int l4 = rand.nextInt(128);
int i8 = l + rand.nextInt(16) + 8;
(new WorldGenLakes(Block.WATER.id)).a(worldObj, rand, i1, l4, i8);
}
if (rand.nextInt(8) == 0) {
int j1 = k + rand.nextInt(16) + 8;
int i5 = rand.nextInt(rand.nextInt(120) + 8);
int j8 = l + rand.nextInt(16) + 8;
if (i5 < 64 || rand.nextInt(10) == 0) {
(new WorldGenLakes(Block.LAVA.id))
.a(worldObj, rand, j1, i5, j8);
}
}
for (int k1 = 0; k1 < 8; k1++) {
int j5 = k + rand.nextInt(16) + 8;
int k8 = rand.nextInt(128);
int j11 = l + rand.nextInt(16) + 8;
(new WorldGenDungeons()).a(worldObj, rand, j5, k8, j11);
}
for (int i2 = 0; i2 < 10; i2++) {
int k5 = k + rand.nextInt(16);
int l8 = rand.nextInt(128);
int k11 = l + rand.nextInt(16);
(new WorldGenClay(32)).a(worldObj, rand, k5, l8, k11);
}
for (int j2 = 0; j2 < 20; j2++) {
int l5 = k + rand.nextInt(16);
int i9 = rand.nextInt(128);
int l11 = l + rand.nextInt(16);
(new WorldGenMinable(Block.DIRT.id, 32)).a(worldObj, rand, l5, i9,
l11);
}
for (int k2 = 0; k2 < 10; k2++) {
int i6 = k + rand.nextInt(16);
int j9 = rand.nextInt(128);
int i12 = l + rand.nextInt(16);
(new WorldGenMinable(Block.GRAVEL.id, 32)).a(worldObj, rand, i6,
j9, i12);
}
for (int i3 = 0; i3 < 20; i3++) {
int j6 = k + rand.nextInt(16);
int k9 = rand.nextInt(128);
int j12 = l + rand.nextInt(16);
(new WorldGenMinable(Block.COAL_ORE.id, 16)).a(worldObj, rand, j6,
k9, j12);
}
for (int j3 = 0; j3 < 20; j3++) {
int k6 = k + rand.nextInt(16);
int l9 = rand.nextInt(64);
int k12 = l + rand.nextInt(16);
(new WorldGenMinable(Block.IRON_ORE.id, 8)).a(worldObj, rand, k6,
l9, k12);
}
for (int k3 = 0; k3 < 2; k3++) {
int l6 = k + rand.nextInt(16);
int i10 = rand.nextInt(32);
int l12 = l + rand.nextInt(16);
(new WorldGenMinable(Block.GOLD_ORE.id, 8)).a(worldObj, rand, l6,
i10, l12);
}
for (int l3 = 0; l3 < 8; l3++) {
int i7 = k + rand.nextInt(16);
int j10 = rand.nextInt(16);
int i13 = l + rand.nextInt(16);
(new WorldGenMinable(Block.REDSTONE_ORE.id, 7)).a(worldObj, rand,
i7, j10, i13);
}
for (int i4 = 0; i4 < 1; i4++) {
int j7 = k + rand.nextInt(16);
int k10 = rand.nextInt(16);
int j13 = l + rand.nextInt(16);
(new WorldGenMinable(Block.DIAMOND_ORE.id, 7)).a(worldObj, rand,
j7, k10, j13);
}
for (int j4 = 0; j4 < 1; j4++) {
int k7 = k + rand.nextInt(16);
int l10 = rand.nextInt(16) + rand.nextInt(16);
int k13 = l + rand.nextInt(16);
(new WorldGenMinable(Block.LAPIS_ORE.id, 6)).a(worldObj, rand, k7,
l10, k13);
}
d = 0.5D;
int k4 = (int) ((mobSpawnerNoise.func_806_a((double) k * d, (double) l
* d)
/ 8D + rand.nextDouble() * 4D + 4D) / 3D);
int l7 = 0;
if (rand.nextInt(10) == 0) {
l7++;
}
if (biomegenbase == BiomeGenBase.forest) {
l7 += k4 + 5;
}
if (biomegenbase == BiomeGenBase.rainforest) {
l7 += k4 + 5;
}
if (biomegenbase == BiomeGenBase.seasonalForest) {
l7 += k4 + 2;
}
if (biomegenbase == BiomeGenBase.taiga) {
l7 += k4 + 5;
}
if (biomegenbase == BiomeGenBase.desert) {
l7 -= 20;
}
if (biomegenbase == BiomeGenBase.tundra) {
l7 -= 20;
}
if (biomegenbase == BiomeGenBase.plains) {
l7 -= 20;
}
for (int i11 = 0; i11 < l7; i11++) {
int l13 = k + rand.nextInt(16) + 8;
int j14 = l + rand.nextInt(16) + 8;
WorldGenerator worldgenerator = biomegenbase.a(rand);
worldgenerator.a(1.0D, 1.0D, 1.0D);
worldgenerator.a(worldObj, rand, l13,
worldObj.getHighestBlockYAt(l13, j14), j14);
}
byte byte0 = 0;
if (biomegenbase == BiomeGenBase.forest) {
byte0 = 2;
}
if (biomegenbase == BiomeGenBase.seasonalForest) {
byte0 = 4;
}
if (biomegenbase == BiomeGenBase.taiga) {
byte0 = 2;
}
if (biomegenbase == BiomeGenBase.plains) {
byte0 = 3;
}
for (int i14 = 0; i14 < byte0; i14++) {
int k14 = k + rand.nextInt(16) + 8;
int l16 = rand.nextInt(128);
int k19 = l + rand.nextInt(16) + 8;
(new WorldGenFlowers(Block.YELLOW_FLOWER.id)).a(worldObj, rand,
k14, l16, k19);
}
byte byte1 = 0;
if (biomegenbase == BiomeGenBase.forest) {
byte1 = 2;
}
if (biomegenbase == BiomeGenBase.rainforest) {
byte1 = 10;
}
if (biomegenbase == BiomeGenBase.seasonalForest) {
byte1 = 2;
}
if (biomegenbase == BiomeGenBase.taiga) {
byte1 = 1;
}
if (biomegenbase == BiomeGenBase.plains) {
byte1 = 10;
}
for (int l14 = 0; l14 < byte1; l14++) {
byte byte2 = 1;
if (biomegenbase == BiomeGenBase.rainforest && rand.nextInt(3) != 0) {
byte2 = 2;
}
int l19 = k + rand.nextInt(16) + 8;
int k22 = rand.nextInt(128);
int j24 = l + rand.nextInt(16) + 8;
(new WorldGenTallGrass(Block.LONG_GRASS.id, byte2)).a(worldObj,
rand, l19, k22, j24);
}
byte1 = 0;
if (biomegenbase == BiomeGenBase.desert) {
byte1 = 2;
}
for (int i15 = 0; i15 < byte1; i15++) {
int i17 = k + rand.nextInt(16) + 8;
int i20 = rand.nextInt(128);
int l22 = l + rand.nextInt(16) + 8;
(new WorldGenDeadBush(Block.DEAD_BUSH.id)).a(worldObj, rand, i17,
i20, l22);
}
if (rand.nextInt(2) == 0) {
int j15 = k + rand.nextInt(16) + 8;
int j17 = rand.nextInt(128);
int j20 = l + rand.nextInt(16) + 8;
(new WorldGenFlowers(Block.RED_ROSE.id)).a(worldObj, rand, j15,
j17, j20);
}
if (rand.nextInt(4) == 0) {
int k15 = k + rand.nextInt(16) + 8;
int k17 = rand.nextInt(128);
int k20 = l + rand.nextInt(16) + 8;
(new WorldGenFlowers(Block.BROWN_MUSHROOM.id)).a(worldObj, rand,
k15, k17, k20);
}
if (rand.nextInt(8) == 0) {
int l15 = k + rand.nextInt(16) + 8;
int l17 = rand.nextInt(128);
int l20 = l + rand.nextInt(16) + 8;
(new WorldGenFlowers(Block.RED_MUSHROOM.id)).a(worldObj, rand, l15,
l17, l20);
}
for (int i16 = 0; i16 < 10; i16++) {
int i18 = k + rand.nextInt(16) + 8;
int i21 = rand.nextInt(128);
int i23 = l + rand.nextInt(16) + 8;
(new WorldGenReed()).a(worldObj, rand, i18, i21, i23);
}
if (rand.nextInt(32) == 0) {
int j16 = k + rand.nextInt(16) + 8;
int j18 = rand.nextInt(128);
int j21 = l + rand.nextInt(16) + 8;
(new WorldGenPumpkin()).a(worldObj, rand, j16, j18, j21);
}
int k16 = 0;
if (biomegenbase == BiomeGenBase.desert) {
k16 += 10;
}
for (int k18 = 0; k18 < k16; k18++) {
int k21 = k + rand.nextInt(16) + 8;
int j23 = rand.nextInt(128);
int k24 = l + rand.nextInt(16) + 8;
(new WorldGenCactus()).a(worldObj, rand, k21, j23, k24);
}
for (int l18 = 0; l18 < 50; l18++) {
int l21 = k + rand.nextInt(16) + 8;
int k23 = rand.nextInt(rand.nextInt(120) + 8);
int l24 = l + rand.nextInt(16) + 8;
(new WorldGenLiquids(Block.WATER.id)).a(worldObj, rand, l21, k23,
l24);
}
for (int i19 = 0; i19 < 20; i19++) {
int i22 = k + rand.nextInt(16) + 8;
int l23 = rand.nextInt(rand.nextInt(rand.nextInt(112) + 8) + 8);
int i25 = l + rand.nextInt(16) + 8;
(new WorldGenLiquids(Block.LAVA.id)).a(worldObj, rand, i22, l23,
i25);
}
generatedTemperatures = this.wcm.getTemperatures(generatedTemperatures,
k + 8, l + 8, 16, 16);
for (int j19 = k + 8; j19 < k + 8 + 16; j19++) {
for (int j22 = l + 8; j22 < l + 8 + 16; j22++) {
int i24 = j19 - (k + 8);
int j25 = j22 - (l + 8);
int k25 = worldObj.getHighestBlockYAt(j19, j22);
double d1 = generatedTemperatures[i24 * 16 + j25]
- ((double) (k25 - 64) / 64D) * 0.29999999999999999D;
if (d1 < 0.5D
&& k25 > 0
&& k25 < 128
&& worldObj.isEmpty(j19, k25, j22)
&& worldObj.getMaterial(j19, k25 - 1, j22).isSolid()
&& worldObj.getMaterial(j19, k25 - 1, j22) != Material.ICE) {
worldObj.setTypeId(j19, k25, j22, Block.SNOW.id);
}
}
}
BlockSand.instaFall = false;
}
|
diff --git a/httpcore-ab/src/main/java/org/apache/http/benchmark/BenchmarkWorker.java b/httpcore-ab/src/main/java/org/apache/http/benchmark/BenchmarkWorker.java
index 0105efe9a..45f4ac600 100644
--- a/httpcore-ab/src/main/java/org/apache/http/benchmark/BenchmarkWorker.java
+++ b/httpcore-ab/src/main/java/org/apache/http/benchmark/BenchmarkWorker.java
@@ -1,280 +1,280 @@
/*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.benchmark;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.charset.Charset;
import javax.net.SocketFactory;
import org.apache.http.ConnectionReuseStrategy;
import org.apache.http.Header;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.Config;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.ImmutableHttpProcessor;
import org.apache.http.protocol.RequestConnControl;
import org.apache.http.protocol.RequestContent;
import org.apache.http.protocol.RequestExpectContinue;
import org.apache.http.protocol.RequestTargetHost;
import org.apache.http.protocol.RequestUserAgent;
/**
* Worker thread for the {@link HttpBenchmark HttpBenchmark}.
*
*
* @since 4.0
*/
class BenchmarkWorker implements Runnable {
private final byte[] buffer = new byte[4096];
private final int verbosity;
private final HttpContext context;
private final HttpProcessor httpProcessor;
private final HttpRequestExecutor httpexecutor;
private final ConnectionReuseStrategy connstrategy;
private final HttpRequest request;
private final HttpHost targetHost;
private final int count;
private final boolean keepalive;
private final SocketFactory socketFactory;
private final Stats stats = new Stats();
public BenchmarkWorker(
final HttpRequest request,
final HttpHost targetHost,
int count,
boolean keepalive,
int verbosity,
final SocketFactory socketFactory) {
super();
this.context = new BasicHttpContext(null);
this.request = request;
this.targetHost = targetHost;
this.count = count;
this.keepalive = keepalive;
this.httpProcessor = new ImmutableHttpProcessor(
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue());
this.httpexecutor = new HttpRequestExecutor();
this.connstrategy = DefaultConnectionReuseStrategy.INSTANCE;
this.verbosity = verbosity;
this.socketFactory = socketFactory;
}
public void run() {
HttpResponse response = null;
BenchmarkConnection conn = new BenchmarkConnection(stats, request.getParams());
String scheme = targetHost.getSchemeName();
String hostname = targetHost.getHostName();
int port = targetHost.getPort();
if (port == -1) {
if (scheme.equalsIgnoreCase("https")) {
port = 443;
} else {
port = 80;
}
}
// Populate the execution context
this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
this.context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.targetHost);
this.context.setAttribute(ExecutionContext.HTTP_REQUEST, this.request);
stats.start();
for (int i = 0; i < count; i++) {
try {
resetHeader(request);
if (!conn.isOpen()) {
Socket socket;
if (socketFactory != null) {
socket = socketFactory.createSocket();
} else {
socket = new Socket();
}
HttpParams params = request.getParams();
int connTimeout = Config.getInt(params, CoreConnectionPNames.CONNECTION_TIMEOUT, 0);
int soTimeout = Config.getInt(params, CoreConnectionPNames.SO_TIMEOUT, 0);
socket.setSoTimeout(soTimeout);
socket.connect(new InetSocketAddress(hostname, port), connTimeout);
conn.bind(socket);
}
try {
// Prepare request
this.httpexecutor.preProcess(this.request, this.httpProcessor, this.context);
// Execute request and get a response
response = this.httpexecutor.execute(this.request, conn, this.context);
// Finalize response
this.httpexecutor.postProcess(response, this.httpProcessor, this.context);
} catch (HttpException e) {
stats.incWriteErrors();
if (this.verbosity >= 2) {
System.err.println("Failed HTTP request : " + e.getMessage());
}
continue;
}
verboseOutput(response);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
stats.incSuccessCount();
} else {
stats.incFailureCount();
continue;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
- ContentType ct = ContentType.get(entity);
+ ContentType ct = ContentType.getOrDefault(entity);
Charset charset = ct.getCharset();
if (charset == null) {
charset = HTTP.DEF_CONTENT_CHARSET;
}
long contentlen = 0;
InputStream instream = entity.getContent();
int l = 0;
while ((l = instream.read(this.buffer)) != -1) {
contentlen += l;
if (this.verbosity >= 4) {
String s = new String(this.buffer, 0, l, charset.name());
System.out.print(s);
}
}
instream.close();
stats.setContentLength(contentlen);
}
if (this.verbosity >= 4) {
System.out.println();
System.out.println();
}
if (!keepalive || !this.connstrategy.keepAlive(response, this.context)) {
conn.close();
} else {
stats.incKeepAliveCount();
}
} catch (IOException ex) {
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("I/O error: " + ex.getMessage());
}
} catch (Exception ex) {
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("Generic error: " + ex.getMessage());
}
}
}
stats.finish();
if (response != null) {
Header header = response.getFirstHeader("Server");
if (header != null) {
stats.setServerName(header.getValue());
}
}
try {
conn.close();
} catch (IOException ex) {
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("I/O error: " + ex.getMessage());
}
}
}
private void verboseOutput(HttpResponse response) {
if (this.verbosity >= 3) {
System.out.println(">> " + request.getRequestLine().toString());
Header[] headers = request.getAllHeaders();
for (int h = 0; h < headers.length; h++) {
System.out.println(">> " + headers[h].toString());
}
System.out.println();
}
if (this.verbosity >= 2) {
System.out.println(response.getStatusLine().getStatusCode());
}
if (this.verbosity >= 3) {
System.out.println("<< " + response.getStatusLine().toString());
Header[] headers = response.getAllHeaders();
for (int h = 0; h < headers.length; h++) {
System.out.println("<< " + headers[h].toString());
}
System.out.println();
}
}
private static void resetHeader(final HttpRequest request) {
for (HeaderIterator it = request.headerIterator(); it.hasNext();) {
Header header = it.nextHeader();
if (!(header instanceof DefaultHeader)) {
it.remove();
}
}
}
public Stats getStats() {
return stats;
}
}
| true | true | public void run() {
HttpResponse response = null;
BenchmarkConnection conn = new BenchmarkConnection(stats, request.getParams());
String scheme = targetHost.getSchemeName();
String hostname = targetHost.getHostName();
int port = targetHost.getPort();
if (port == -1) {
if (scheme.equalsIgnoreCase("https")) {
port = 443;
} else {
port = 80;
}
}
// Populate the execution context
this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
this.context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.targetHost);
this.context.setAttribute(ExecutionContext.HTTP_REQUEST, this.request);
stats.start();
for (int i = 0; i < count; i++) {
try {
resetHeader(request);
if (!conn.isOpen()) {
Socket socket;
if (socketFactory != null) {
socket = socketFactory.createSocket();
} else {
socket = new Socket();
}
HttpParams params = request.getParams();
int connTimeout = Config.getInt(params, CoreConnectionPNames.CONNECTION_TIMEOUT, 0);
int soTimeout = Config.getInt(params, CoreConnectionPNames.SO_TIMEOUT, 0);
socket.setSoTimeout(soTimeout);
socket.connect(new InetSocketAddress(hostname, port), connTimeout);
conn.bind(socket);
}
try {
// Prepare request
this.httpexecutor.preProcess(this.request, this.httpProcessor, this.context);
// Execute request and get a response
response = this.httpexecutor.execute(this.request, conn, this.context);
// Finalize response
this.httpexecutor.postProcess(response, this.httpProcessor, this.context);
} catch (HttpException e) {
stats.incWriteErrors();
if (this.verbosity >= 2) {
System.err.println("Failed HTTP request : " + e.getMessage());
}
continue;
}
verboseOutput(response);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
stats.incSuccessCount();
} else {
stats.incFailureCount();
continue;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
ContentType ct = ContentType.get(entity);
Charset charset = ct.getCharset();
if (charset == null) {
charset = HTTP.DEF_CONTENT_CHARSET;
}
long contentlen = 0;
InputStream instream = entity.getContent();
int l = 0;
while ((l = instream.read(this.buffer)) != -1) {
contentlen += l;
if (this.verbosity >= 4) {
String s = new String(this.buffer, 0, l, charset.name());
System.out.print(s);
}
}
instream.close();
stats.setContentLength(contentlen);
}
if (this.verbosity >= 4) {
System.out.println();
System.out.println();
}
if (!keepalive || !this.connstrategy.keepAlive(response, this.context)) {
conn.close();
} else {
stats.incKeepAliveCount();
}
} catch (IOException ex) {
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("I/O error: " + ex.getMessage());
}
} catch (Exception ex) {
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("Generic error: " + ex.getMessage());
}
}
}
stats.finish();
if (response != null) {
Header header = response.getFirstHeader("Server");
if (header != null) {
stats.setServerName(header.getValue());
}
}
try {
conn.close();
} catch (IOException ex) {
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("I/O error: " + ex.getMessage());
}
}
}
| public void run() {
HttpResponse response = null;
BenchmarkConnection conn = new BenchmarkConnection(stats, request.getParams());
String scheme = targetHost.getSchemeName();
String hostname = targetHost.getHostName();
int port = targetHost.getPort();
if (port == -1) {
if (scheme.equalsIgnoreCase("https")) {
port = 443;
} else {
port = 80;
}
}
// Populate the execution context
this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
this.context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.targetHost);
this.context.setAttribute(ExecutionContext.HTTP_REQUEST, this.request);
stats.start();
for (int i = 0; i < count; i++) {
try {
resetHeader(request);
if (!conn.isOpen()) {
Socket socket;
if (socketFactory != null) {
socket = socketFactory.createSocket();
} else {
socket = new Socket();
}
HttpParams params = request.getParams();
int connTimeout = Config.getInt(params, CoreConnectionPNames.CONNECTION_TIMEOUT, 0);
int soTimeout = Config.getInt(params, CoreConnectionPNames.SO_TIMEOUT, 0);
socket.setSoTimeout(soTimeout);
socket.connect(new InetSocketAddress(hostname, port), connTimeout);
conn.bind(socket);
}
try {
// Prepare request
this.httpexecutor.preProcess(this.request, this.httpProcessor, this.context);
// Execute request and get a response
response = this.httpexecutor.execute(this.request, conn, this.context);
// Finalize response
this.httpexecutor.postProcess(response, this.httpProcessor, this.context);
} catch (HttpException e) {
stats.incWriteErrors();
if (this.verbosity >= 2) {
System.err.println("Failed HTTP request : " + e.getMessage());
}
continue;
}
verboseOutput(response);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
stats.incSuccessCount();
} else {
stats.incFailureCount();
continue;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
ContentType ct = ContentType.getOrDefault(entity);
Charset charset = ct.getCharset();
if (charset == null) {
charset = HTTP.DEF_CONTENT_CHARSET;
}
long contentlen = 0;
InputStream instream = entity.getContent();
int l = 0;
while ((l = instream.read(this.buffer)) != -1) {
contentlen += l;
if (this.verbosity >= 4) {
String s = new String(this.buffer, 0, l, charset.name());
System.out.print(s);
}
}
instream.close();
stats.setContentLength(contentlen);
}
if (this.verbosity >= 4) {
System.out.println();
System.out.println();
}
if (!keepalive || !this.connstrategy.keepAlive(response, this.context)) {
conn.close();
} else {
stats.incKeepAliveCount();
}
} catch (IOException ex) {
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("I/O error: " + ex.getMessage());
}
} catch (Exception ex) {
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("Generic error: " + ex.getMessage());
}
}
}
stats.finish();
if (response != null) {
Header header = response.getFirstHeader("Server");
if (header != null) {
stats.setServerName(header.getValue());
}
}
try {
conn.close();
} catch (IOException ex) {
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("I/O error: " + ex.getMessage());
}
}
}
|
diff --git a/src/main/ed/net/lb/LB.java b/src/main/ed/net/lb/LB.java
index bec7488f8..8f6104253 100644
--- a/src/main/ed/net/lb/LB.java
+++ b/src/main/ed/net/lb/LB.java
@@ -1,503 +1,503 @@
// LB.java
/**
* Copyright (C) 2008 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ed.net.lb;
import java.io.*;
import java.net.*;
import java.nio.*;
import java.util.*;
import java.util.concurrent.*;
import org.apache.commons.cli.*;
import ed.io.*;
import ed.js.*;
import ed.log.*;
import ed.net.*;
import ed.cloud.*;
import ed.net.httpserver.*;
public class LB extends NIOClient {
static final long WAIT_FOR_POOL_TIMEOUT = 10000;
static final String LBIDENT = DNSUtil.getLocalHost().getHostName() + " : v0" ;
enum State { WAITING , IN_HEADER , READY_TO_STREAM , STREAMING , ERROR , DONE };
public LB( int port , MappingFactory mappingFactory , int verbose )
throws IOException {
super( "LB" , 15 , verbose );
_port = port;
_handler = new LBHandler();
_logger = Logger.getLogger( "LB" );
_logger.setLevel( Level.forDebugId( verbose ) );
_server = new HttpServer( port );
_server.addGlobalHandler( _handler ) ;
_router = new Router( mappingFactory );
_loadMonitor = new LoadMonitor( _router );
_addMonitors();
setDaemon( true );
}
public void start(){
_server.start();
super.start();
}
public void run(){
_logger.debug( "Started" );
super.run();
}
protected void shutdown(){
_logger.error( "SHUTDOWN starting" );
_server.stopServer();
super.shutdown();
Thread t = new Thread(){
public void run(){
try {
Thread.sleep( 1000 * 60 );
}
catch ( Exception e ){}
System.exit(0);
}
};
t.start();
}
protected void serverError( InetSocketAddress addr , ServerErrorType type , Exception why ){
// TODO: uh oh
_logger.debug( 1 , "serverError" , addr + ":" + type );
}
class RR extends Call {
RR( HttpRequest req , HttpResponse res ){
_request = req;
_response = res;
reset();
_lastCalls[_lastCallsPos] = this;
_lastCallsPos++;
if ( _lastCallsPos >= _lastCalls.length )
_lastCallsPos = 0;
}
void reset(){
_response.clearHeaders();
_response.setHeader( "X-lb" , LBIDENT );
_state = State.WAITING;
_line = null;
}
void success(){
done();
_router.success( _request , _response , _lastWent );
_loadMonitor.hit( _request , _response );
}
protected InetSocketAddress where(){
_lastWent = _router.chooseAddress( _request , _request.elapsed() > WAIT_FOR_POOL_TIMEOUT );
return _lastWent;
}
protected InetSocketAddress lastWent(){
return _lastWent;
}
protected void error( ServerErrorType type , Exception e ){
_logger.debug( 1 , "backend error" , e );
_router.error( _request , _response , _lastWent , type , e );
if ( type != ServerErrorType.WEIRD &&
( _state == State.WAITING || _state == State.IN_HEADER ) &&
++_numFails <= 3 ){
reset();
_logger.debug( 1 , "retrying" );
add( this );
return;
}
try {
_response.setResponseCode( 500 );
_response.getJxpWriter().print( "backend error : " + e + "\n\n" );
_response.done();
_state = State.ERROR;
done();
_loadMonitor.hit( _request , _response );
}
catch ( IOException ioe2 ){
ioe2.printStackTrace();
}
}
void backendError( ServerErrorType type , String msg ){
backendError( type , new IOException( msg ) );
}
void backendError( ServerErrorType type , IOException ioe ){
_logger.debug( 1 , "backend error" , ioe );
error( type , ioe );
}
protected WhatToDo handleRead( ByteBuffer buf , Connection conn ){
if ( _state == State.WAITING || _state == State.IN_HEADER ){
// TODO: should i read this all in at once
if ( _line == null )
_line = new StringBuilder();
while ( buf.hasRemaining() ){
char c = (char)buf.get();
if ( c == '\r' )
continue;
if ( c == '\n' ){
if ( _line.length() == 0 ){
_logger.debug( 3 , "end of header" );
_state = State.READY_TO_STREAM;
break;
}
String line = _line.toString();
if ( _state == State.WAITING ){
int idx = line.indexOf( " " );
if ( idx < 0 ){
backendError( ServerErrorType.INVALID , "invalid first line [" + line + "]" );
return WhatToDo.ERROR;
}
line = line.substring( idx + 1 ).trim();
idx = line.indexOf( " " );
if ( idx < 0 )
_response.setResponseCode( Integer.parseInt( line ) );
else
_response.setStatus( Integer.parseInt( line.substring( 0 , idx ) ) , line.substring( idx + 1 ).trim() );
_logger.debug( 3 , "got first line " , line );
_state = State.IN_HEADER;
}
else {
int idx = line.indexOf( ":" );
if ( idx < 0 ){
backendError( ServerErrorType.INVALID , "invalid line [ " + line + "]" );
return WhatToDo.ERROR;
}
String name = line.substring( 0 , idx );
String value = line.substring( idx + 1 ).trim();
_logger.debug( 3 , "got header line " , line );
if ( name.equalsIgnoreCase( "Connection" ) ){
_keepalive = ! value.toLowerCase().contains( "close" );
}
else {
- _response.setHeader( name , value );
+ _response.addHeader( name , value );
}
}
_line.setLength( 0 );
continue;
}
_line.append( c );
}
if ( _state != State.READY_TO_STREAM )
return WhatToDo.CONTINUE;
_logger.debug( 3 , "starting to stream data" );
}
if ( _state == State.READY_TO_STREAM ){
MyChunk chunk = new MyChunk( this , conn , _response.getContentLength() , buf );
_response.sendFile( new MySender( chunk ) );
_state = State.STREAMING;
}
try {
_response.done();
}
catch ( IOException ioe ){
_logger.debug( 2 , "client error" , ioe );
return WhatToDo.ERROR;
}
return WhatToDo.PAUSE;
}
protected ByteStream fillInRequest( ByteBuffer buf ){
buf.put( generateRequestHeader().getBytes() );
if ( _request.getPostData() != null )
return _request.getPostData().getByteStream();
return null;
}
String generateRequestHeader(){
StringBuilder buf = new StringBuilder( _request.getRawHeader().length() + 200 );
buf.append( _request.getMethod().toUpperCase() ).append( " " ).append( _request.getURL() ).append( " HTTP/1.0\r\n" );
buf.append( "Connection: keep-alive\r\n" );
buf.append( HttpRequest.REAL_IP_HEADER ).append( ": " ).append( _request.getRemoteIP() ).append( "\r\n" );
for ( String n : _request.getHeaderNameKeySet() ){
if ( n.equalsIgnoreCase( "Connection" ) ||
n.equalsIgnoreCase( HttpRequest.REAL_IP_HEADER ) )
continue;
String v = _request.getHeader( n );
buf.append( n ).append( ": " ).append( v ).append( "\r\n" );
}
buf.append( "\r\n" );
_logger.debug( 3 , "request\n" , buf );
return buf.toString();
}
public String toString(){
return _request.getFullURL();
}
final HttpRequest _request;
final HttpResponse _response;
int _numFails = 0;
private InetSocketAddress _lastWent;
private boolean _keepalive;
private State _state;
private StringBuilder _line;
}
class MySender extends JSFile.Sender {
MySender( MyChunk chunk ){
super( chunk , chunk._length );
}
}
class MyChunk extends JSFileChunk {
MyChunk( RR rr , Connection conn , long length , ByteBuffer buf ){
_rr = rr;
_conn = conn;
_length = length;
_buf = buf;
_data = new MyBinaryData( _buf );
_sent += _data.length();
}
public JSBinaryData getData(){
return _data;
}
public MyChunk getNext(){
_logger.debug( 4, "want next chunk of data" );
if ( _sent == _length ){
_logger.debug( 4 , "no more data" );
_conn.done( ! _rr._keepalive );
_rr._state = State.DONE;
_rr.success();
return null;
}
_conn.doRead( _length > 0 );
_sent += _data.length();
_last = _data.length();
_logger.debug( _last == 0 ? 4 : 3 , "sent " + _sent + "/" + _length );
return this;
}
long _sent = 0;
long _last = -1;
final RR _rr;
final Connection _conn;
final long _length;
final ByteBuffer _buf;
final MyBinaryData _data;
}
class MyBinaryData extends JSBinaryData {
MyBinaryData( ByteBuffer buf ){
_buf = buf;
}
public int length(){
return _buf.remaining();
}
public void put( ByteBuffer buf ){
throw new RuntimeException( "not allowed" );
}
public void write( OutputStream out ){
throw new RuntimeException( "not allowed" );
}
public ByteBuffer asByteBuffer(){
return _buf;
}
final ByteBuffer _buf;
}
class LBHandler implements HttpHandler {
public boolean handles( HttpRequest request , Info info ){
info.admin = false;
info.fork = false;
info.doneAfterHandles = false;
return true;
}
public void handle( HttpRequest request , HttpResponse response ){
if ( add( new RR( request , response ) ) )
return;
JxpWriter out = response.getJxpWriter();
out.print( "new request queue full (lb 1)" );
try {
response.done();
}
catch ( IOException ioe ){
ioe.printStackTrace();
}
}
public double priority(){
return Double.MAX_VALUE;
}
}
void _addMonitors(){
HttpServer.addGlobalHandler( new WebViews.LBOverview( this ) );
HttpServer.addGlobalHandler( new WebViews.LBLast( this ) );
HttpServer.addGlobalHandler( new WebViews.LoadMonitorWebView( this._loadMonitor ) );
HttpServer.addGlobalHandler( new WebViews.RouterPools( this._router ) );
HttpServer.addGlobalHandler( new HttpHandler(){
public boolean handles( HttpRequest request , Info info ){
if ( ! "/~kill".equals( request.getURI() ) )
return false;
if ( ! "127.0.0.1".equals( request.getPhysicalRemoteAddr() ) )
return false;
info.fork = false;
info.admin = true;
return true;
}
public void handle( HttpRequest request , HttpResponse response ){
JxpWriter out = response.getJxpWriter();
if ( isShutDown() ){
out.print( "alredy shutdown" );
return;
}
LB.this.shutdown();
out.print( "done" );
}
public double priority(){
return Double.MIN_VALUE;
}
}
);
}
final int _port;
final LBHandler _handler;
final HttpServer _server;
final Router _router;
final LoadMonitor _loadMonitor;
final Logger _logger;
final RR[] _lastCalls = new RR[1000];
int _lastCallsPos = 0;
public static void main( String args[] )
throws Exception {
int verbose = 0;
for ( int i=0; i<args.length; i++ ){
if ( args[i].matches( "\\-v+" ) ){
verbose = args[i].length() - 1;
args[i] = "";
}
}
Options o = new Options();
o.addOption( "p" , "port" , true , "Port to Listen On" );
o.addOption( "v" , "verbose" , false , "Verbose" );
o.addOption( "mapfile" , "m" , true , "file from which to load mappings" );
CommandLine cl = ( new BasicParser() ).parse( o , args );
final int port = Integer.parseInt( cl.getOptionValue( "p" , "8080" ) );
MappingFactory mf = null;
if ( cl.hasOption( "m" ) )
mf = new TextMapping.Factory( cl.getOptionValue( "m" , null ) );
else
mf = new GridMapping.Factory();
System.out.println( "10gen load balancer" );
System.out.println( "\t port \t " + port );
System.out.println( "\t verbose \t " + verbose );
int retriesLeft = 2;
LB lb = null;
while ( retriesLeft-- > 0 ){
try {
lb = new LB( port , mf , verbose );
break;
}
catch ( BindException be ){
be.printStackTrace();
System.out.println( "can't bind to port. going to try to kill old one" );
HttpDownload.downloadToJS( new URL( "http://127.0.0.1:" + port + "/~kill" ) );
Thread.sleep( 100 );
}
}
if ( lb == null ){
System.err.println( "couldn't ever bind" );
System.exit(-1);
return;
}
lb.start();
lb.join();
System.exit(0);
}
}
| true | true | protected WhatToDo handleRead( ByteBuffer buf , Connection conn ){
if ( _state == State.WAITING || _state == State.IN_HEADER ){
// TODO: should i read this all in at once
if ( _line == null )
_line = new StringBuilder();
while ( buf.hasRemaining() ){
char c = (char)buf.get();
if ( c == '\r' )
continue;
if ( c == '\n' ){
if ( _line.length() == 0 ){
_logger.debug( 3 , "end of header" );
_state = State.READY_TO_STREAM;
break;
}
String line = _line.toString();
if ( _state == State.WAITING ){
int idx = line.indexOf( " " );
if ( idx < 0 ){
backendError( ServerErrorType.INVALID , "invalid first line [" + line + "]" );
return WhatToDo.ERROR;
}
line = line.substring( idx + 1 ).trim();
idx = line.indexOf( " " );
if ( idx < 0 )
_response.setResponseCode( Integer.parseInt( line ) );
else
_response.setStatus( Integer.parseInt( line.substring( 0 , idx ) ) , line.substring( idx + 1 ).trim() );
_logger.debug( 3 , "got first line " , line );
_state = State.IN_HEADER;
}
else {
int idx = line.indexOf( ":" );
if ( idx < 0 ){
backendError( ServerErrorType.INVALID , "invalid line [ " + line + "]" );
return WhatToDo.ERROR;
}
String name = line.substring( 0 , idx );
String value = line.substring( idx + 1 ).trim();
_logger.debug( 3 , "got header line " , line );
if ( name.equalsIgnoreCase( "Connection" ) ){
_keepalive = ! value.toLowerCase().contains( "close" );
}
else {
_response.setHeader( name , value );
}
}
_line.setLength( 0 );
continue;
}
_line.append( c );
}
if ( _state != State.READY_TO_STREAM )
return WhatToDo.CONTINUE;
_logger.debug( 3 , "starting to stream data" );
}
if ( _state == State.READY_TO_STREAM ){
MyChunk chunk = new MyChunk( this , conn , _response.getContentLength() , buf );
_response.sendFile( new MySender( chunk ) );
_state = State.STREAMING;
}
try {
_response.done();
}
catch ( IOException ioe ){
_logger.debug( 2 , "client error" , ioe );
return WhatToDo.ERROR;
}
return WhatToDo.PAUSE;
}
| protected WhatToDo handleRead( ByteBuffer buf , Connection conn ){
if ( _state == State.WAITING || _state == State.IN_HEADER ){
// TODO: should i read this all in at once
if ( _line == null )
_line = new StringBuilder();
while ( buf.hasRemaining() ){
char c = (char)buf.get();
if ( c == '\r' )
continue;
if ( c == '\n' ){
if ( _line.length() == 0 ){
_logger.debug( 3 , "end of header" );
_state = State.READY_TO_STREAM;
break;
}
String line = _line.toString();
if ( _state == State.WAITING ){
int idx = line.indexOf( " " );
if ( idx < 0 ){
backendError( ServerErrorType.INVALID , "invalid first line [" + line + "]" );
return WhatToDo.ERROR;
}
line = line.substring( idx + 1 ).trim();
idx = line.indexOf( " " );
if ( idx < 0 )
_response.setResponseCode( Integer.parseInt( line ) );
else
_response.setStatus( Integer.parseInt( line.substring( 0 , idx ) ) , line.substring( idx + 1 ).trim() );
_logger.debug( 3 , "got first line " , line );
_state = State.IN_HEADER;
}
else {
int idx = line.indexOf( ":" );
if ( idx < 0 ){
backendError( ServerErrorType.INVALID , "invalid line [ " + line + "]" );
return WhatToDo.ERROR;
}
String name = line.substring( 0 , idx );
String value = line.substring( idx + 1 ).trim();
_logger.debug( 3 , "got header line " , line );
if ( name.equalsIgnoreCase( "Connection" ) ){
_keepalive = ! value.toLowerCase().contains( "close" );
}
else {
_response.addHeader( name , value );
}
}
_line.setLength( 0 );
continue;
}
_line.append( c );
}
if ( _state != State.READY_TO_STREAM )
return WhatToDo.CONTINUE;
_logger.debug( 3 , "starting to stream data" );
}
if ( _state == State.READY_TO_STREAM ){
MyChunk chunk = new MyChunk( this , conn , _response.getContentLength() , buf );
_response.sendFile( new MySender( chunk ) );
_state = State.STREAMING;
}
try {
_response.done();
}
catch ( IOException ioe ){
_logger.debug( 2 , "client error" , ioe );
return WhatToDo.ERROR;
}
return WhatToDo.PAUSE;
}
|
diff --git a/src/ca/cumulonimbus/barometer/DatabaseHelper.java b/src/ca/cumulonimbus/barometer/DatabaseHelper.java
index a1b2196..ffe1c37 100644
--- a/src/ca/cumulonimbus/barometer/DatabaseHelper.java
+++ b/src/ca/cumulonimbus/barometer/DatabaseHelper.java
@@ -1,855 +1,855 @@
package ca.cumulonimbus.barometer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.Random;
import java.util.logging.Logger;
public class DatabaseHelper {
// Database objects
Connection db;
PreparedStatement pstmt;
boolean connected = false;
private static final int MAX = 100;
private static String logName = "ca.cumulonimbus.barometer.DatabaseHelper";
private static Logger log = Logger.getLogger(logName);
private static double TENDENCY_HOURS = 12;
private static double TENDENCY_DELTA = 0.5;
/**
* Add a barometer reading to the database. Before inserting a new row, check to see if
* this user has submitted an entry before. If so, update the row.
* @param reading
* @return
*/
public boolean addReadingToDatabase(BarometerReading reading) {
if(!connected) {
connectToDatabase();
}
try {
// Check for existing ID in database
ArrayList<BarometerReading> readings = new ArrayList<BarometerReading>();
pstmt = db.prepareStatement("SELECT * FROM Readings WHERE text='" + reading.getAndroidId() + "'");
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
readings.add(resultSetToBarometerReading(rs));
}
log.info("adding a reading. existing entries for id: " + readings.size());
if(readings.size() > 0) {
// Exists. Update.
pstmt = db.prepareStatement("UPDATE Readings SET latitude=?, longitude=?, daterecorded=?, reading=?, tzoffset=?, privacy=?, client_key=?, location_accuracy=?, reading_accuracy=? WHERE text=?");
pstmt.setDouble(1, reading.getLatitude());
pstmt.setDouble(2, reading.getLongitude());
pstmt.setDouble(3, reading.getTime());
pstmt.setDouble(4, reading.getReading());
pstmt.setInt(5, reading.getTimeZoneOffset());
pstmt.setString(6, reading.getSharingPrivacy());
pstmt.setString(7, reading.getClientKey());
pstmt.setFloat(8, reading.getLocationAccuracy());
pstmt.setFloat(9, reading.getReadingAccuracy());
pstmt.setString(10, reading.getAndroidId());
pstmt.execute();
//log.info("updating " + reading.getAndroidId() + " to " + reading.getReading());
} else {
// Doesn't exist. Insert a new row.
pstmt = db.prepareStatement("INSERT INTO Readings (latitude, longitude, daterecorded, reading, tzoffset, text, privacy, client_key, location_accuracy, reading_accuracy) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
pstmt.setDouble(1, reading.getLatitude());
pstmt.setDouble(2, reading.getLongitude());
pstmt.setDouble(3, reading.getTime());
pstmt.setDouble(4, reading.getReading());
pstmt.setInt(5, reading.getTimeZoneOffset());
pstmt.setString(6, reading.getAndroidId());
pstmt.setString(7, reading.getSharingPrivacy());
pstmt.setString(8, reading.getClientKey());
pstmt.setFloat(9, reading.getLocationAccuracy());
pstmt.setFloat(10, reading.getReadingAccuracy());
pstmt.execute();
//log.info("inserting new " + reading.getAndroidId());
}
// Either way, add it to the archive.
pstmt = db.prepareStatement("INSERT INTO archive (latitude, longitude, daterecorded, reading, tzoffset, text, privacy, client_key, location_accuracy, reading_accuracy) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
pstmt.setDouble(1, reading.getLatitude());
pstmt.setDouble(2, reading.getLongitude());
pstmt.setDouble(3, reading.getTime());
pstmt.setDouble(4, reading.getReading());
pstmt.setInt(5, reading.getTimeZoneOffset());
pstmt.setString(6, reading.getAndroidId());
pstmt.setString(7, reading.getSharingPrivacy());
pstmt.setString(8, reading.getClientKey());
pstmt.setFloat(9, reading.getLocationAccuracy());
pstmt.setFloat(10, reading.getReadingAccuracy());
pstmt.execute();
//log.info("archiving " + reading.getAndroidId());
return true;
} catch(SQLException sqle) {
log.info(sqle.getMessage());
return false;
}
}
public class UserCollection {
private ArrayList<BarometerReading> allReadings = new ArrayList<BarometerReading>();
private String id;
public UserCollection(BarometerReading firstReading, String id) {
allReadings.add(firstReading);
this.id = id;
}
public UserCollection(String id) {
this.id = id;
}
public ArrayList<BarometerReading> getAllReadings() {
return allReadings;
}
public void setAllReadings(ArrayList<BarometerReading> allReadings) {
this.allReadings = allReadings;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void addReading(BarometerReading newReading) {
allReadings.add(newReading);
}
}
// Loop through the archive, and split out useful data into User Collections
public ArrayList<UserCollection> getUCFromArchive(ArrayList<BarometerReading> archive) {
ArrayList<UserCollection> users = new ArrayList<UserCollection>();
// Loop through the archive, and split out useful data.
for(BarometerReading single : archive) {
String id = single.getAndroidId();
boolean exists = false;
for(UserCollection user : users) {
if(user.getId().equals(id)) {
// User exists in collection. Add the entry there.
user.addReading(single);
exists = true;
}
}
if(!exists) {
// User not in the collection. Add.
users.add(new UserCollection(single, id));
}
}
return users;
}
public boolean deleteUserData(String userID) {
if(!connected) {
connectToDatabase();
}
try {
pstmt = db.prepareStatement("delete from readings where text=?");
pstmt.setString(1, userID);
boolean deletedFromReadings = pstmt.execute();
pstmt = db.prepareStatement("delete from archive where text=?");
pstmt.setString(1, userID);
boolean deletedFromArchive = pstmt.execute();
if(deletedFromReadings && deletedFromArchive) {
return true;
}
} catch(SQLException e) {
log.info(e.getMessage());
}
return false;
}
// use Google Charts
public String getChartFromSingleUser(String userId, long sinceWhen, String units) {
String html = "";
ArrayList<UserCollection> ucs = getReadingsByUserAndTime(userId, sinceWhen, "mbar");
if(ucs.size()==1) {
UserCollection uc = ucs.get(0);
ChartData cd = new ChartData("Pressure over Time");
for(BarometerReading br : uc.getAllReadings()) {
cd.addRow(br.getReading(), (long)br.getTime());
}
html = cd.getChartWebPage();
} else {
return "Error. Invalid data returned from server. Size is " + ucs.size() + " for user " + userId + " since " + sinceWhen;
}
return html;
}
// Get all a user's info and return it in CSV
public String getUserCSV(String userId) {
if(!connected) {
connectToDatabase();
}
try {
pstmt = db.prepareStatement("select * from archive where text=? order by daterecorded");
pstmt.setString(1, userId);
ResultSet rs = pstmt.executeQuery();
String csv = "";
while(rs.next()) {
BarometerReading current = resultSetToBarometerReading(rs, "mbar");
Date d = new Date((long)current.getTime());
csv += d.toLocaleString() + "," + current.getLatitude() + "," + current.getLongitude() + "," + current.getReading() + "\n";
}
return csv;
} catch(SQLException sqle) {
log.info(sqle.getMessage());
return "no data";
}
}
// Return a set of useful information from a single user
// All users, all time = (null,0L). Return the data chronologically
public ArrayList<UserCollection> getReadingsByUserAndTime(String userId, long sinceWhen, String units) {
ArrayList<UserCollection> uc = new ArrayList<UserCollection>();
if(!connected) {
connectToDatabase();
}
try {
if(userId != null) {
// Single user
pstmt = db.prepareStatement("select * from archive where text=? and daterecorded >? order by daterecorded");
} else {
// All users
pstmt = db.prepareStatement("select * from archive where daterecorded > ? order by daterecorded");
}
pstmt.setString(1, userId);
pstmt.setLong(2, sinceWhen);
ResultSet rs = pstmt.executeQuery();
ArrayList<BarometerReading> readings = new ArrayList<BarometerReading>();
while(rs.next()) {
readings.add(resultSetToBarometerReading(rs, units));
}
uc = getUCFromArchive(readings);
} catch(SQLException sqle) {
log.info(sqle.getMessage());
return null;
}
return uc;
}
// Return a set of useful information from a single user
public String generateStatisticsByUserAndTime(String userId, long sinceWhen) {
String stats = "";
if(!connected) {
connectToDatabase();
}
try {
pstmt = db.prepareStatement("select * from archive where text=? and daterecorded > ?");
pstmt.setString(1, userId);
pstmt.setLong(2, sinceWhen);
ResultSet rs = pstmt.executeQuery();
ArrayList<BarometerReading> readings = new ArrayList<BarometerReading>();
while(rs.next()) {
readings.add(resultSetToBarometerReading(rs));
}
if(sinceWhen==0) {
//stats = "Your total readings: " + readings.size();
} else {
// TODO: HACK! Fix this to give the correct time. Right now we only
// call this function with sinceWhen = an hour, but that will change.
stats = "Readings in the last day: " + readings.size();
}
return stats;
} catch(SQLException sqle) {
log.info(sqle.getMessage());
return "error";
}
}
// Return a set of useful information from only recent data in the archive
public String generateRecentStatisticsFromArchive(String days) {
if(!connected) {
connectToDatabase();
}
try {
pstmt = db.prepareStatement("select * from archive");
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
}
} catch(SQLException sqle) {
}
return "Service not yet implemented.";
}
// Return a set of useful information from all the data in the archive
public ArrayList<BarometerReading> getRecentArchive() {
ArrayList<BarometerReading> archive = new ArrayList<BarometerReading>();
if(!connected) {
connectToDatabase();
}
try {
pstmt = db.prepareStatement("select * from archive order by daterecorded limit 1000");
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
archive.add(resultSetToBarometerReading(rs));
}
} catch(SQLException sqle) {
log.info(sqle.getMessage());
}
return archive;
}
// Return a set of useful information from all the data in the archive
public ArrayList<BarometerReading> getFullArchive() {
ArrayList<BarometerReading> archive = new ArrayList<BarometerReading>();
if(!connected) {
connectToDatabase();
}
try {
pstmt = db.prepareStatement("select * from archive");
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
archive.add(resultSetToBarometerReading(rs));
}
} catch(SQLException sqle) {
log.info(sqle.getMessage());
}
return archive;
}
// table is usually "readings" for only-single-datapoints, "archive" for historical user values
public int getReadingCountWithinRegion(double[] region, long sinceWhen, String table ) {
if(!connected) {
connectToDatabase();
}
double lat1 = region[0];
double lat2 = region[1];
double lon1 = region[2];
double lon2 = region[3];
String sql = "SELECT count(*) FROM " + table + " WHERE latitude>? AND latitude<? AND longitude>? AND longitude<? and daterecorded>?";
try {
pstmt = db.prepareStatement(sql);
pstmt.setDouble(1, lat1);
pstmt.setDouble(2, lat2);
pstmt.setDouble(3, lon1);
pstmt.setDouble(4, lon2);
pstmt.setLong(5, sinceWhen);
ResultSet rs = pstmt.executeQuery();
rs.next();
int count = rs.getInt(1);
return count;
} catch(SQLException sqle) {
log.info(sqle.getMessage());
return -1;
}
}
/*
* Current conditions
*/
public CurrentCondition resultSetToCurrentCondition(ResultSet rs) {
if(!connected) {
connectToDatabase();
}
try {
CurrentCondition cc = new CurrentCondition();
cc.setGeneral_condition(rs.getString("general_condition"));
cc.setLatitude(rs.getDouble("latitude"));
cc.setLongitude(rs.getDouble("longitude"));
cc.setUser_id(rs.getString("user_id"));
cc.setTime(rs.getDouble("time"));
cc.setTzoffset(rs.getInt("tzoffset"));
cc.setWindy(rs.getString("windy"));
cc.setPrecipitation_type(rs.getString("precipitation_type"));
cc.setPrecipitation_amount(rs.getDouble("precipitation_amount"));
cc.setThunderstorm_intensity(rs.getString("thunderstorm_intensity"));
cc.setCloud_type(rs.getString("cloud_type"));
return cc;
} catch (SQLException sqle) {
log.info(sqle.getMessage());
return null;
}
}
public ArrayList<CurrentCondition> getConditionsWithinRegion(ArrayList<Double> region, long sinceWhen ) {
if(!connected) {
connectToDatabase();
}
ArrayList<CurrentCondition> conditionsList = new ArrayList<CurrentCondition>();
double lat1 = region.get(0);
double lat2 = region.get(1);
double lon1 = region.get(2);
double lon2 = region.get(3);
//log.info("lat1: " + lat1 + ", lat2: " + lat2 + ", lon1: " + lon1 + ", lon2: " + lon2);
//log.info(sinceWhen + " - " + Calendar.getInstance().getTimeInMillis());
String sql = "SELECT * FROM CurrentCondition WHERE latitude>? AND latitude<? AND longitude>? AND longitude<? and time>?";
try {
pstmt = db.prepareStatement(sql);
pstmt.setDouble(1, lat1);
pstmt.setDouble(2, lat2);
pstmt.setDouble(3, lon1);
pstmt.setDouble(4, lon2);
pstmt.setLong(5, sinceWhen);
ResultSet rs = pstmt.executeQuery();
int i = 0;
while(rs.next()) {
i++;
conditionsList.add(resultSetToCurrentCondition(rs));
if(i>MAX) {
break;
}
}
return fudgeGPSConditionsData(conditionsList);
} catch(SQLException sqle) {
log.info(sqle.getMessage());
return null;
}
}
private double thunderstormStringToDouble(String intensity) {
if (intensity.contains("Low")) {
return 0.0;
} else if (intensity.contains("Moderate")) {
return 1.0;
} else if (intensity.contains("Heavy")) {
return 2.0;
} else {
return -1.0;
}
}
public boolean addCurrentConditionToDatabase(CurrentCondition condition) {
if(!connected) {
connectToDatabase();
}
try {
// Check for existing ID in database
ArrayList<CurrentCondition> conditions = new ArrayList<CurrentCondition>();
pstmt = db.prepareStatement("SELECT * FROM CurrentCondition WHERE user_id='" + condition.getUser_id() + "'");
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
conditions.add(resultSetToCurrentCondition(rs));
}
log.info("adding a condition. existing entries for id: " + conditions.size());
if(conditions.size() > 0) {
// Exists. Update.
pstmt = db.prepareStatement("UPDATE CurrentCondition SET latitude=?, longitude=?, location_type=?, location_accuracy=?, time=?, tzoffset=?, general_condition=?, windy=?, foggy=?, cloud_type=?, precipitation_type=?, precipitation_amount=?, precipitation_unit=?, thunderstorm_intensity=?, user_comment=?, sharing_policy=? WHERE user_id=?");
pstmt.setDouble(1, condition.getLatitude());
pstmt.setDouble(2, condition.getLongitude());
pstmt.setString(3, condition.getLocation_type());
pstmt.setDouble(4, condition.getLocation_accuracy());
pstmt.setDouble(5, condition.getTime());
pstmt.setInt(6, condition.getTzoffset());
pstmt.setString(7, condition.getGeneral_condition());
pstmt.setString(8, condition.getWindy());
pstmt.setString(9, condition.getFog_thickness());
pstmt.setString(10, condition.getCloud_type());
pstmt.setString(11, condition.getPrecipitation_type());
pstmt.setDouble(12, condition.getPrecipitation_amount());
pstmt.setString(13, condition.getPrecipitation_unit());
pstmt.setDouble(14, thunderstormStringToDouble(condition.getThunderstorm_intensity()));
pstmt.setString(15, condition.getUser_comment());
pstmt.setString(16, condition.getSharing_policy());
pstmt.setString(17, condition.getUser_id());
pstmt.execute();
} else {
// Doesn't exist. Insert a new row.
pstmt = db.prepareStatement("INSERT INTO CurrentCondition (latitude, longitude, location_type, location_accuracy, time, tzoffset, general_condition, windy, foggy, cloud_type, precipitation_type, precipitation_amount, precipitation_unit, thunderstorm_intensity, user_comment, sharing_policy, user_id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,?)");
pstmt.setDouble(1, condition.getLatitude());
- pstmt.setDouble(2, condition.getLatitude());
+ pstmt.setDouble(2, condition.getLongitude());
pstmt.setString(3, condition.getLocation_type());
pstmt.setDouble(4, condition.getLocation_accuracy());
pstmt.setDouble(5, condition.getTime());
pstmt.setInt(6, condition.getTzoffset());
pstmt.setString(7, condition.getGeneral_condition());
pstmt.setString(8, condition.getWindy());
pstmt.setString(9, condition.getFog_thickness());
pstmt.setString(10, condition.getCloud_type());
pstmt.setString(11, condition.getPrecipitation_type());
pstmt.setDouble(12, condition.getPrecipitation_amount());
pstmt.setString(13, condition.getPrecipitation_unit());
pstmt.setDouble(14, thunderstormStringToDouble(condition.getThunderstorm_intensity()));
pstmt.setString(15, condition.getUser_comment());
pstmt.setString(16, condition.getSharing_policy());
pstmt.setString(17, condition.getUser_id());
pstmt.execute();
//log.info("inserting new " + reading.getAndroidId());
}
// Either way, add it to the archive.
log.info("archiving condition.");
pstmt = db.prepareStatement("INSERT INTO CurrentConditionArchive (latitude, longitude, location_type, location_accuracy, time, tzoffset, general_condition, windy, foggy, cloud_type, precipitation_type, precipitation_amount, precipitation_unit, thunderstorm_intensity, user_comment, sharing_policy, user_id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,?)");
pstmt.setDouble(1, condition.getLatitude());
- pstmt.setDouble(2, condition.getLatitude());
+ pstmt.setDouble(2, condition.getLongitude());
pstmt.setString(3, condition.getLocation_type());
pstmt.setDouble(4, condition.getLocation_accuracy());
pstmt.setDouble(5, condition.getTime());
pstmt.setInt(6, condition.getTzoffset());
pstmt.setString(7, condition.getGeneral_condition());
pstmt.setString(8, condition.getWindy());
pstmt.setString(9, condition.getFog_thickness());
pstmt.setString(10, condition.getCloud_type());
pstmt.setString(11, condition.getPrecipitation_type());
pstmt.setDouble(12, condition.getPrecipitation_amount());
pstmt.setString(13, condition.getPrecipitation_unit());
pstmt.setDouble(14, thunderstormStringToDouble(condition.getThunderstorm_intensity()));
pstmt.setString(15, condition.getUser_comment());
pstmt.setString(16, condition.getSharing_policy());
pstmt.setString(17, condition.getUser_id());
pstmt.execute();
return true;
} catch(SQLException sqle) {
log.info(sqle.getMessage());
return false;
}
}
// table is "readings" for only-single-datapoints, "archive" for historical user values
public ArrayList<BarometerReading> getReadingsWithinRegion(double[] region, long sinceWhen, String table ) {
if(!connected) {
connectToDatabase();
}
ArrayList<BarometerReading> readingsList = new ArrayList<BarometerReading>();
double lat1 = region[0];
double lat2 = region[1];
double lon1 = region[2];
double lon2 = region[3];
//log.info("lat1: " + lat1 + ", lat2: " + lat2 + ", lon1: " + lon1 + ", lon2: " + lon2);
//log.info(sinceWhen + " - " + Calendar.getInstance().getTimeInMillis());
String sql = "SELECT * FROM " + table + " WHERE latitude>? AND latitude<? AND longitude>? AND longitude<? and daterecorded>?";
try {
pstmt = db.prepareStatement(sql);
pstmt.setDouble(1, lat1);
pstmt.setDouble(2, lat2);
pstmt.setDouble(3, lon1);
pstmt.setDouble(4, lon2);
pstmt.setLong(5, sinceWhen);
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
readingsList.add(resultSetToBarometerReading(rs));
}
return fudgeGPSData(readingsList);
//return readingsList;
} catch(SQLException sqle) {
log.info(sqle.getMessage());
return null;
}
}
// Reading is stored in millibars. Convert to user-preferred unit.
public double convertFromMbarsToCustomUnits(double reading, String units) {
Unit u = new Unit(units);
u.setValue(reading);
return u.convertToPreferredUnit();
}
public BarometerReading resultSetToBarometerReading(ResultSet rs, String units) {
if(!connected) {
connectToDatabase();
}
try {
BarometerReading br = new BarometerReading();
br.setLatitude(rs.getDouble("latitude"));
br.setLongitude(rs.getDouble("longitude"));
br.setReading(convertFromMbarsToCustomUnits(rs.getDouble("reading"), units));
br.setTime(rs.getDouble("daterecorded"));
br.setTimeZoneOffset(rs.getInt("tzoffset"));
br.setAndroidId(rs.getString("text"));
br.setSharingPrivacy(rs.getString("privacy"));
br.setClientKey(rs.getString("client_key"));
br.setLocationAccuracy(rs.getFloat("location_accuracy"));
br.setReadingAccuracy(rs.getFloat("reading_accuracy"));
return br;
} catch (SQLException sqle) {
log.info(sqle.getMessage());
return null;
}
}
public BarometerReading resultSetToBarometerReading(ResultSet rs) {
if(!connected) {
connectToDatabase();
}
try {
BarometerReading br = new BarometerReading();
br.setLatitude(rs.getDouble("latitude"));
br.setLongitude(rs.getDouble("longitude"));
br.setReading(rs.getDouble("reading"));
br.setTime(rs.getDouble("daterecorded"));
br.setTimeZoneOffset(rs.getInt("tzoffset"));
br.setAndroidId(rs.getString("text"));
br.setSharingPrivacy(rs.getString("privacy"));
br.setClientKey(rs.getString("client_key"));
br.setLocationAccuracy(rs.getFloat("location_accuracy"));
br.setReadingAccuracy(rs.getFloat("reading_accuracy"));
return br;
} catch (SQLException sqle) {
log.info(sqle.getMessage());
return null;
}
}
private double daysToMs(int days) {
return 1000 * 60 * 60 * 24 * days;
}
private ArrayList<CurrentCondition> fudgeGPSConditionsData(ArrayList<CurrentCondition> conditions) {
ArrayList<CurrentCondition> fudgedConditions = new ArrayList<CurrentCondition>();
for(CurrentCondition cc : conditions) {
double longitude = cc.getLongitude();
double latitude = cc.getLatitude();
double range = .01;
Random lat = new Random(Long.parseLong(cc.getUser_id().substring(0, 4),16));
Random lon = new Random(Long.parseLong(cc.getUser_id().substring(0, 4),16));
latitude = (latitude - range) + (int)(lat.nextDouble()) * ((2 * range) + 1);
longitude = (longitude - range) + (int)(lon.nextDouble() * ((2 * range) + 1));
cc.setLatitude(latitude);
cc.setLongitude(longitude);
fudgedConditions.add(cc);
}
return fudgedConditions;
}
private ArrayList<BarometerReading> fudgeGPSData(ArrayList<BarometerReading> readings) {
ArrayList<BarometerReading> fudgedReadings = new ArrayList<BarometerReading>();
for(BarometerReading br : readings) {
double longitude = br.getLongitude();
double latitude = br.getLatitude();
double range = .01;
Random lat = new Random(Long.parseLong(br.getAndroidId().substring(0, 4),16));
Random lon = new Random(Long.parseLong(br.getAndroidId().substring(0, 4),16));
latitude = (latitude - range) + (int)(lat.nextDouble() * ((2 * range) + 1));
longitude = (longitude - range) + (int)(lon.nextDouble() * ((2 * range) + 1));
br.setLatitude(latitude);
br.setLongitude(longitude);
fudgedReadings.add(br);
}
return fudgedReadings;
}
public ArrayList<BarometerReading> getRecentReadings(int days) {
if(!connected) {
connectToDatabase();
}
if(connected) {
ArrayList<BarometerReading> readings = new ArrayList<BarometerReading>();
try {
double dateCutoff = Calendar.getInstance().getTimeInMillis() - daysToMs(days); // Now - days in millis
log.info("date cutoff: " + dateCutoff + " dayscuttingoffinms: " + daysToMs(days));
pstmt = db.prepareStatement("SELECT * FROM Readings WHERE daterecorded > " + dateCutoff);
ResultSet rs = pstmt.executeQuery();
int i = 0;
while(rs.next()) {
i++;
readings.add(resultSetToBarometerReading(rs));
if(i>MAX) {
break;
}
}
return fudgeGPSData(readings);
} catch(SQLException e) {
log.info(e.getMessage());
return null;
}
}
return null;
}
public ArrayList<BarometerReading> getAllReadings() {
if(!connected) {
connectToDatabase();
}
if(connected) {
ArrayList<BarometerReading> readings = new ArrayList<BarometerReading>();
try {
pstmt = db.prepareStatement("SELECT * FROM Readings");
ResultSet rs = pstmt.executeQuery();
int i = 0;
while(rs.next()) {
i++;
readings.add(resultSetToBarometerReading(rs));
if(i>MAX) {
break;
}
}
return fudgeGPSData(readings);
} catch(SQLException sqle) {
log.info(sqle.getMessage());
return null;
}
}
return null;
}
public ArrayList<BarometerReading> getReadingsWithinRegion(ArrayList<Double> region, long sinceWhen ) {
if(!connected) {
connectToDatabase();
}
ArrayList<BarometerReading> readingsList = new ArrayList<BarometerReading>();
double lat1 = region.get(0);
double lat2 = region.get(1);
double lon1 = region.get(2);
double lon2 = region.get(3);
//log.info("lat1: " + lat1 + ", lat2: " + lat2 + ", lon1: " + lon1 + ", lon2: " + lon2);
//log.info(sinceWhen + " - " + Calendar.getInstance().getTimeInMillis());
String sql = "SELECT * FROM Readings WHERE latitude>? AND latitude<? AND longitude>? AND longitude<? and daterecorded>?";
try {
pstmt = db.prepareStatement(sql);
pstmt.setDouble(1, lat1);
pstmt.setDouble(2, lat2);
pstmt.setDouble(3, lon1);
pstmt.setDouble(4, lon2);
pstmt.setLong(5, sinceWhen);
ResultSet rs = pstmt.executeQuery();
int i = 0;
while(rs.next()) {
i++;
readingsList.add(resultSetToBarometerReading(rs));
if(i>MAX) {
break;
}
}
return fudgeGPSData(readingsList);
} catch(SQLException sqle) {
log.info(sqle.getMessage());
return null;
}
}
public BarometerReading getReadingById(int id) {
if(!connected) {
connectToDatabase();
}
try {
pstmt = db.prepareStatement("SELECT * FROM Readings WHERE id=" + id);
ResultSet rs = pstmt.executeQuery();
if(rs.next()) {
BarometerReading br = resultSetToBarometerReading(rs);
return br;
} else {
return null;
}
} catch(SQLException sqle) {
log.info(sqle.getMessage());
return null;
}
}
public void create() {
if(!connected) {
connectToDatabase();
}
try {
pstmt = db.prepareStatement("DROP TABLE Archive;");
pstmt = db.prepareStatement("DROP TABLE Readings;");
pstmt = db.prepareStatement("DROP TABLE CurrentCondition;");
pstmt = db.prepareStatement("DROP TABLE CurrentConditionArchive;");
pstmt.execute();
pstmt = db.prepareStatement("CREATE TABLE Archive (id serial, latitude numeric, longitude numeric, daterecorded numeric, reading numeric, tzoffset int, text varchar(200), privacy varchar(100), client_key varchar(100), location_accuracy numeric, reading_accuracy numeric)");
pstmt = db.prepareStatement("CREATE TABLE CurrentCondition (id serial, latitude numeric, longitude numeric, location_type varchar(20), location_accuracy numeric, time numeric, tzoffset int, general_condition varchar(200), windy varchar(20), foggy varchar(200), cloud_type varchar(200), precipitation_type varchar(20), precipitation_amount numeric, precipitation_unit varchar(20), thunderstorm_intensity numeric, user_comment varchar(200), sharing_policy varchar(100), user_id varchar(200))");
pstmt = db.prepareStatement("CREATE TABLE CurrentConditionArchive (id serial, latitude numeric, longitude numeric, location_type varchar(20), location_accuracy numeric, time numeric, tzoffset int, general_condition varchar(200), windy varchar(20), foggy varchar(200), cloud_type varchar(200), precipitation_type varchar(20), precipitation_amount numeric, precipitation_unit varchar(20), thunderstorm_intensity numeric, user_comment varchar(200), sharing_policy varchar(100), user_id varchar(200))");
pstmt = db.prepareStatement("CREATE TABLE Readings (id serial, latitude numeric, longitude numeric, daterecorded numeric, reading numeric, tzoffset int, text varchar(200), client_key varchar(100), location_accuracy numeric, reading_accuracy numeric)");
pstmt.execute();
} catch(SQLException e) {
log.info(e.getMessage());
}
}
public void cleanDatabase() {
if(!connected) {
connectToDatabase();
}
try {
pstmt = db.prepareStatement("DELETE FROM Readings");
pstmt = db.prepareStatement("DELETE FROM Archive");
pstmt = db.prepareStatement("DELETE FROM CurrentCondition");
pstmt = db.prepareStatement("DELETE FROM CurrentConditionArchive");
pstmt.execute();
} catch(SQLException sqle) {
log.info(sqle.getMessage());
}
}
public void connectToDatabase() {
try {
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://localhost"; // LIVE: breadings // DEV: dev_archive
Properties props = new Properties();
props.setProperty("user","USER");
props.setProperty("password","PASS");
db = DriverManager.getConnection(url, props);
connected = true;
return;
}
catch(SQLException e) {
log.info("sqle " + e.getMessage());
connected = false;
}
catch(ClassNotFoundException cnfe) {
log.info("class nfe " + cnfe.getMessage());
connected = false;
}
}
public DatabaseHelper () {
connectToDatabase();
if(!connected) {
System.out.println("unable to connect to the database");
}
}
}
| false | true | public boolean addCurrentConditionToDatabase(CurrentCondition condition) {
if(!connected) {
connectToDatabase();
}
try {
// Check for existing ID in database
ArrayList<CurrentCondition> conditions = new ArrayList<CurrentCondition>();
pstmt = db.prepareStatement("SELECT * FROM CurrentCondition WHERE user_id='" + condition.getUser_id() + "'");
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
conditions.add(resultSetToCurrentCondition(rs));
}
log.info("adding a condition. existing entries for id: " + conditions.size());
if(conditions.size() > 0) {
// Exists. Update.
pstmt = db.prepareStatement("UPDATE CurrentCondition SET latitude=?, longitude=?, location_type=?, location_accuracy=?, time=?, tzoffset=?, general_condition=?, windy=?, foggy=?, cloud_type=?, precipitation_type=?, precipitation_amount=?, precipitation_unit=?, thunderstorm_intensity=?, user_comment=?, sharing_policy=? WHERE user_id=?");
pstmt.setDouble(1, condition.getLatitude());
pstmt.setDouble(2, condition.getLongitude());
pstmt.setString(3, condition.getLocation_type());
pstmt.setDouble(4, condition.getLocation_accuracy());
pstmt.setDouble(5, condition.getTime());
pstmt.setInt(6, condition.getTzoffset());
pstmt.setString(7, condition.getGeneral_condition());
pstmt.setString(8, condition.getWindy());
pstmt.setString(9, condition.getFog_thickness());
pstmt.setString(10, condition.getCloud_type());
pstmt.setString(11, condition.getPrecipitation_type());
pstmt.setDouble(12, condition.getPrecipitation_amount());
pstmt.setString(13, condition.getPrecipitation_unit());
pstmt.setDouble(14, thunderstormStringToDouble(condition.getThunderstorm_intensity()));
pstmt.setString(15, condition.getUser_comment());
pstmt.setString(16, condition.getSharing_policy());
pstmt.setString(17, condition.getUser_id());
pstmt.execute();
} else {
// Doesn't exist. Insert a new row.
pstmt = db.prepareStatement("INSERT INTO CurrentCondition (latitude, longitude, location_type, location_accuracy, time, tzoffset, general_condition, windy, foggy, cloud_type, precipitation_type, precipitation_amount, precipitation_unit, thunderstorm_intensity, user_comment, sharing_policy, user_id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,?)");
pstmt.setDouble(1, condition.getLatitude());
pstmt.setDouble(2, condition.getLatitude());
pstmt.setString(3, condition.getLocation_type());
pstmt.setDouble(4, condition.getLocation_accuracy());
pstmt.setDouble(5, condition.getTime());
pstmt.setInt(6, condition.getTzoffset());
pstmt.setString(7, condition.getGeneral_condition());
pstmt.setString(8, condition.getWindy());
pstmt.setString(9, condition.getFog_thickness());
pstmt.setString(10, condition.getCloud_type());
pstmt.setString(11, condition.getPrecipitation_type());
pstmt.setDouble(12, condition.getPrecipitation_amount());
pstmt.setString(13, condition.getPrecipitation_unit());
pstmt.setDouble(14, thunderstormStringToDouble(condition.getThunderstorm_intensity()));
pstmt.setString(15, condition.getUser_comment());
pstmt.setString(16, condition.getSharing_policy());
pstmt.setString(17, condition.getUser_id());
pstmt.execute();
//log.info("inserting new " + reading.getAndroidId());
}
// Either way, add it to the archive.
log.info("archiving condition.");
pstmt = db.prepareStatement("INSERT INTO CurrentConditionArchive (latitude, longitude, location_type, location_accuracy, time, tzoffset, general_condition, windy, foggy, cloud_type, precipitation_type, precipitation_amount, precipitation_unit, thunderstorm_intensity, user_comment, sharing_policy, user_id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,?)");
pstmt.setDouble(1, condition.getLatitude());
pstmt.setDouble(2, condition.getLatitude());
pstmt.setString(3, condition.getLocation_type());
pstmt.setDouble(4, condition.getLocation_accuracy());
pstmt.setDouble(5, condition.getTime());
pstmt.setInt(6, condition.getTzoffset());
pstmt.setString(7, condition.getGeneral_condition());
pstmt.setString(8, condition.getWindy());
pstmt.setString(9, condition.getFog_thickness());
pstmt.setString(10, condition.getCloud_type());
pstmt.setString(11, condition.getPrecipitation_type());
pstmt.setDouble(12, condition.getPrecipitation_amount());
pstmt.setString(13, condition.getPrecipitation_unit());
pstmt.setDouble(14, thunderstormStringToDouble(condition.getThunderstorm_intensity()));
pstmt.setString(15, condition.getUser_comment());
pstmt.setString(16, condition.getSharing_policy());
pstmt.setString(17, condition.getUser_id());
pstmt.execute();
return true;
} catch(SQLException sqle) {
log.info(sqle.getMessage());
return false;
}
}
| public boolean addCurrentConditionToDatabase(CurrentCondition condition) {
if(!connected) {
connectToDatabase();
}
try {
// Check for existing ID in database
ArrayList<CurrentCondition> conditions = new ArrayList<CurrentCondition>();
pstmt = db.prepareStatement("SELECT * FROM CurrentCondition WHERE user_id='" + condition.getUser_id() + "'");
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
conditions.add(resultSetToCurrentCondition(rs));
}
log.info("adding a condition. existing entries for id: " + conditions.size());
if(conditions.size() > 0) {
// Exists. Update.
pstmt = db.prepareStatement("UPDATE CurrentCondition SET latitude=?, longitude=?, location_type=?, location_accuracy=?, time=?, tzoffset=?, general_condition=?, windy=?, foggy=?, cloud_type=?, precipitation_type=?, precipitation_amount=?, precipitation_unit=?, thunderstorm_intensity=?, user_comment=?, sharing_policy=? WHERE user_id=?");
pstmt.setDouble(1, condition.getLatitude());
pstmt.setDouble(2, condition.getLongitude());
pstmt.setString(3, condition.getLocation_type());
pstmt.setDouble(4, condition.getLocation_accuracy());
pstmt.setDouble(5, condition.getTime());
pstmt.setInt(6, condition.getTzoffset());
pstmt.setString(7, condition.getGeneral_condition());
pstmt.setString(8, condition.getWindy());
pstmt.setString(9, condition.getFog_thickness());
pstmt.setString(10, condition.getCloud_type());
pstmt.setString(11, condition.getPrecipitation_type());
pstmt.setDouble(12, condition.getPrecipitation_amount());
pstmt.setString(13, condition.getPrecipitation_unit());
pstmt.setDouble(14, thunderstormStringToDouble(condition.getThunderstorm_intensity()));
pstmt.setString(15, condition.getUser_comment());
pstmt.setString(16, condition.getSharing_policy());
pstmt.setString(17, condition.getUser_id());
pstmt.execute();
} else {
// Doesn't exist. Insert a new row.
pstmt = db.prepareStatement("INSERT INTO CurrentCondition (latitude, longitude, location_type, location_accuracy, time, tzoffset, general_condition, windy, foggy, cloud_type, precipitation_type, precipitation_amount, precipitation_unit, thunderstorm_intensity, user_comment, sharing_policy, user_id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,?)");
pstmt.setDouble(1, condition.getLatitude());
pstmt.setDouble(2, condition.getLongitude());
pstmt.setString(3, condition.getLocation_type());
pstmt.setDouble(4, condition.getLocation_accuracy());
pstmt.setDouble(5, condition.getTime());
pstmt.setInt(6, condition.getTzoffset());
pstmt.setString(7, condition.getGeneral_condition());
pstmt.setString(8, condition.getWindy());
pstmt.setString(9, condition.getFog_thickness());
pstmt.setString(10, condition.getCloud_type());
pstmt.setString(11, condition.getPrecipitation_type());
pstmt.setDouble(12, condition.getPrecipitation_amount());
pstmt.setString(13, condition.getPrecipitation_unit());
pstmt.setDouble(14, thunderstormStringToDouble(condition.getThunderstorm_intensity()));
pstmt.setString(15, condition.getUser_comment());
pstmt.setString(16, condition.getSharing_policy());
pstmt.setString(17, condition.getUser_id());
pstmt.execute();
//log.info("inserting new " + reading.getAndroidId());
}
// Either way, add it to the archive.
log.info("archiving condition.");
pstmt = db.prepareStatement("INSERT INTO CurrentConditionArchive (latitude, longitude, location_type, location_accuracy, time, tzoffset, general_condition, windy, foggy, cloud_type, precipitation_type, precipitation_amount, precipitation_unit, thunderstorm_intensity, user_comment, sharing_policy, user_id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,?)");
pstmt.setDouble(1, condition.getLatitude());
pstmt.setDouble(2, condition.getLongitude());
pstmt.setString(3, condition.getLocation_type());
pstmt.setDouble(4, condition.getLocation_accuracy());
pstmt.setDouble(5, condition.getTime());
pstmt.setInt(6, condition.getTzoffset());
pstmt.setString(7, condition.getGeneral_condition());
pstmt.setString(8, condition.getWindy());
pstmt.setString(9, condition.getFog_thickness());
pstmt.setString(10, condition.getCloud_type());
pstmt.setString(11, condition.getPrecipitation_type());
pstmt.setDouble(12, condition.getPrecipitation_amount());
pstmt.setString(13, condition.getPrecipitation_unit());
pstmt.setDouble(14, thunderstormStringToDouble(condition.getThunderstorm_intensity()));
pstmt.setString(15, condition.getUser_comment());
pstmt.setString(16, condition.getSharing_policy());
pstmt.setString(17, condition.getUser_id());
pstmt.execute();
return true;
} catch(SQLException sqle) {
log.info(sqle.getMessage());
return false;
}
}
|
diff --git a/SpeechVersion/src/com/luugiathuy/apps/remotebluetooth/InputAndOutput.java b/SpeechVersion/src/com/luugiathuy/apps/remotebluetooth/InputAndOutput.java
index 1cc5f86..ba88022 100644
--- a/SpeechVersion/src/com/luugiathuy/apps/remotebluetooth/InputAndOutput.java
+++ b/SpeechVersion/src/com/luugiathuy/apps/remotebluetooth/InputAndOutput.java
@@ -1,127 +1,127 @@
package com.luugiathuy.apps.remotebluetooth;
import java.io.Serializable;
public class InputAndOutput implements Serializable
{
double[] _InputPoint;
double[] _AlgorithmLabel;
double[] _Size;
double[] _Refer= new double [8];
public InputAndOutput(double[] inputpoint, double[] algorithm_labels)
{
_InputPoint = inputpoint;
_AlgorithmLabel = algorithm_labels;
}
public InputAndOutput(double[] inputpoint, double[] algorithm_labels, double [] _Size)
{
_InputPoint = inputpoint;
_AlgorithmLabel = algorithm_labels;
_Size=_Size;
Calculate_Refer(inputpoint, _Size);
}
public double[] getinputpoint()
{
return _InputPoint;
}
public double[] getalgorithmlabels ()
{
return _AlgorithmLabel;
}
//get_index of the
public int getindex(){
int len=_AlgorithmLabel.length;
for (int i=0;i<len;i++){
if (_AlgorithmLabel[i]==1)
return i;
}
return -1;
}
/**
* Calculate refer so we can check if another input suit for this one or not.
* (used when we do prediction.)
* qiao 26, August,2012
* @param inputpoint
* @param time
*/
public void Calculate_Refer(double [] inputpoint, double[] size)
{
//first I will get the direction vector.
//accelerometer
_Refer[0]=inputpoint[28];
_Refer[1]=inputpoint[29];
_Refer[2]=inputpoint[30];
//gyro
_Refer[5]=inputpoint[31];
_Refer[6]=inputpoint[32];
_Refer[7]=inputpoint[33];
//time
_Refer[3]=size[0];
//accelerate
_Refer[4]=size[1];
}
/**
* compare time and direction (gyroscope..)
*
* @param newinput
* @return
*/
public boolean Compare( double [] newinput ){
//time
if( newinput[3]>2*_Refer[3] || newinput[3]<_Refer[3]/1.5){
System.out.println("Time erro...newinput: "+newinput[3]+"\nTime erro...refer: "+_Refer[3]);
return false;
}
System.out.println("Time newinput: "+newinput[3]+"\nTime refer: "+_Refer[3]);
System.out.println("Acc newinput: "+newinput[4]+"\nAcc refer: "+_Refer[4]);
//angle
double result = GetAngle(newinput,_Refer,5);
double accresult=GetAngle(newinput,_Refer,0);
System.out.println("Acc angle-- "+accresult);
//first check angle of gyro
if (result < 0.85 ){
- //second check acc angle and have to have gyro base 0.2
- if (accresult <0.9 || result <0.2)
+ //second check acc angle and have to have gyro base 0.3
+ if (accresult <0.9 || result <0.3)
{
System.out.println("Angle erro... gyro_angle "+result+" acc_angle "+accresult);
for (int i=5;i<8;i++){
System.out.println("new gyro"+newinput[i]+ " refer gyro "+_Refer[i]);
}
for (int i=0;i<3;i++){
System.out.println("new acc "+newinput[i]+ " refer acc "+_Refer[i]);
}
return false;
}
}
System.out.println("Angle...�� "+result);
System.out.println("gyro_angle "+result+" acc_angle "+accresult);
System.out.println("Angle of acc ");
for (int i=0;i<3;i++){
System.out.println("new acc "+newinput[i]+ " refer acc "+_Refer[i]);
}
return true;
}
public double GetAngle(double[] _new, double[] _refer, int index){
double gyro_new_pow = Math.sqrt(Math.pow(_new[index], 2) + Math.pow(_new[index+1], 2) + Math.pow(_new[index+2], 2));
double gyro__refer_pow = Math.sqrt(Math.pow(_refer[index], 2) + Math.pow(_refer[index+1], 2) + Math.pow(_refer[index+2], 2));
//calculate the direction angle of movement here. cos ?= a.b/|a||b|
double result= (_new[index]*_refer[index]+_new[index+1]*_refer[index+1]+_new[index+2]*_refer[index+2]) /(gyro_new_pow*gyro__refer_pow );
return result;
}
}
| true | true | public boolean Compare( double [] newinput ){
//time
if( newinput[3]>2*_Refer[3] || newinput[3]<_Refer[3]/1.5){
System.out.println("Time erro...newinput: "+newinput[3]+"\nTime erro...refer: "+_Refer[3]);
return false;
}
System.out.println("Time newinput: "+newinput[3]+"\nTime refer: "+_Refer[3]);
System.out.println("Acc newinput: "+newinput[4]+"\nAcc refer: "+_Refer[4]);
//angle
double result = GetAngle(newinput,_Refer,5);
double accresult=GetAngle(newinput,_Refer,0);
System.out.println("Acc angle-- "+accresult);
//first check angle of gyro
if (result < 0.85 ){
//second check acc angle and have to have gyro base 0.2
if (accresult <0.9 || result <0.2)
{
System.out.println("Angle erro... gyro_angle "+result+" acc_angle "+accresult);
for (int i=5;i<8;i++){
System.out.println("new gyro"+newinput[i]+ " refer gyro "+_Refer[i]);
}
for (int i=0;i<3;i++){
System.out.println("new acc "+newinput[i]+ " refer acc "+_Refer[i]);
}
return false;
}
}
System.out.println("Angle...�� "+result);
System.out.println("gyro_angle "+result+" acc_angle "+accresult);
System.out.println("Angle of acc ");
for (int i=0;i<3;i++){
System.out.println("new acc "+newinput[i]+ " refer acc "+_Refer[i]);
}
return true;
}
| public boolean Compare( double [] newinput ){
//time
if( newinput[3]>2*_Refer[3] || newinput[3]<_Refer[3]/1.5){
System.out.println("Time erro...newinput: "+newinput[3]+"\nTime erro...refer: "+_Refer[3]);
return false;
}
System.out.println("Time newinput: "+newinput[3]+"\nTime refer: "+_Refer[3]);
System.out.println("Acc newinput: "+newinput[4]+"\nAcc refer: "+_Refer[4]);
//angle
double result = GetAngle(newinput,_Refer,5);
double accresult=GetAngle(newinput,_Refer,0);
System.out.println("Acc angle-- "+accresult);
//first check angle of gyro
if (result < 0.85 ){
//second check acc angle and have to have gyro base 0.3
if (accresult <0.9 || result <0.3)
{
System.out.println("Angle erro... gyro_angle "+result+" acc_angle "+accresult);
for (int i=5;i<8;i++){
System.out.println("new gyro"+newinput[i]+ " refer gyro "+_Refer[i]);
}
for (int i=0;i<3;i++){
System.out.println("new acc "+newinput[i]+ " refer acc "+_Refer[i]);
}
return false;
}
}
System.out.println("Angle...�� "+result);
System.out.println("gyro_angle "+result+" acc_angle "+accresult);
System.out.println("Angle of acc ");
for (int i=0;i<3;i++){
System.out.println("new acc "+newinput[i]+ " refer acc "+_Refer[i]);
}
return true;
}
|
diff --git a/nuxeo-platform-webapp-core/src/main/java/org/nuxeo/ecm/webapp/shield/SeamExceptionHandlingListener.java b/nuxeo-platform-webapp-core/src/main/java/org/nuxeo/ecm/webapp/shield/SeamExceptionHandlingListener.java
index 319a96eb..b2ff6c94 100644
--- a/nuxeo-platform-webapp-core/src/main/java/org/nuxeo/ecm/webapp/shield/SeamExceptionHandlingListener.java
+++ b/nuxeo-platform-webapp-core/src/main/java/org/nuxeo/ecm/webapp/shield/SeamExceptionHandlingListener.java
@@ -1,198 +1,201 @@
/*
* (C) Copyright 2006-2008 Nuxeo SAS (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* arussel
*/
package org.nuxeo.ecm.webapp.shield;
import java.io.IOException;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.contexts.FacesLifecycle;
import org.jboss.seam.contexts.Lifecycle;
import org.jboss.seam.mock.MockApplication;
import org.jboss.seam.mock.MockExternalContext;
import org.jboss.seam.mock.MockFacesContext;
import org.nuxeo.ecm.platform.web.common.exceptionhandling.service.NullExceptionHandlingListener;
import org.nuxeo.runtime.transaction.TransactionHelper;
/**
* Plays with conversations, trying to rollback transaction.
*
* @author arussel
*/
public class SeamExceptionHandlingListener extends
NullExceptionHandlingListener {
private static final Log log = LogFactory.getLog(SeamExceptionHandlingListener.class);
/**
* Initiates a mock faces context when needed and tries to restore current
* conversation
*/
@Override
public void beforeSetErrorPageAttribute(Throwable t,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// cut/paste from seam Exception filter.
// we recreate the seam context to be able to use the messages.
// patch following https://jira.jboss.org/browse/JBPAPP-1427
// Ensure that the call in which the exception occurred was cleaned up
// - it might not be, and there is no harm in trying
// we keep around the synchronization component because
// SeSynchronizations expects it to be unchanged when called by
// the finally block of UTTransaction.rollback
String SEAM_TX_SYNCS = "org.jboss.seam.transaction.synchronizations";
- Object syncs = Contexts.getEventContext().get(SEAM_TX_SYNCS);
+ Object syncs = null;
+ if (Contexts.isEventContextActive()) {
+ syncs = Contexts.getEventContext().get(SEAM_TX_SYNCS);
+ }
Lifecycle.endRequest();
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext == null) {
// the FacesContext is gone - create a fake one for Redirect and
// HttpError to call
MockFacesContext mockContext = createFacesContext(request, response);
mockContext.setCurrent();
facesContext = mockContext;
log.debug("Created mock faces context for exception handling");
} else {
// do not use a mock faces context when a real one still exists:
// when released, the mock faces context is nullified, and this
// leads to errors like in the following stack trace:
/**
* java.lang.NullPointerException: FacesContext is null at
* org.ajax4jsf
* .context.AjaxContext.getCurrentInstance(AjaxContext.java:159) at
* org.ajax4jsf.context.AjaxContext.getCurrentInstance(AjaxContext.
* java:144) at
* org.ajax4jsf.component.AjaxViewRoot.getViewId(AjaxViewRoot
* .java:580) at
* com.sun.faces.lifecycle.Phase.doPhase(Phase.java:104)
*/
log.debug("Using existing faces context for exception handling");
}
// NXP-5998: conversation initialization seems to be already handled by
// SeamPhaseListener => do not handle conversation as otherwise it'll
// stay unlocked.
// if the event context was cleaned up, fish the conversation id
// directly out of the ServletRequest attributes, else get it from
// the event context
// Manager manager = Contexts.isEventContextActive() ? (Manager)
// Contexts.getEventContext().get(
// Manager.class)
// : (Manager)
// request.getAttribute(Seam.getComponentName(Manager.class));
// String conversationId = manager == null ? null
// : manager.getCurrentConversationId();
FacesLifecycle.beginExceptionRecovery(facesContext.getExternalContext());
// restore syncs
if (syncs != null) {
Contexts.getEventContext().set(SEAM_TX_SYNCS, syncs);
}
// If there is an existing long-running conversation on
// the failed request, propagate it
// if (conversationId == null) {
// Manager.instance().initializeTemporaryConversation();
// } else {
// ConversationPropagation.instance().setConversationId(conversationId);
// Manager.instance().restoreConversation();
// }
}
/**
* Rollbacks transaction if necessary
*/
@Override
public void startHandling(Throwable t, HttpServletRequest request,
HttpServletResponse response) throws ServletException {
if (TransactionHelper.isTransactionActive()) {
TransactionHelper.setTransactionRollbackOnly();
}
}
/**
* Cleans up context created in
* {@link #beforeSetErrorPageAttribute(Throwable, HttpServletRequest, HttpServletResponse)}
* when needed.
*/
@Override
public void afterDispatch(Throwable t, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
FacesContext context = FacesContext.getCurrentInstance();
// XXX: it's not clear what should be done here: current tests
// depending on the faces context just allow to avoid errors after
if (context instanceof MockFacesContext) {
// do not end the request if it's a real faces context, otherwise
// we'll get the following stack trace:
/**
* java.lang.IllegalStateException: No active application scope at
* org.jboss.seam.core.Init.instance(Init.java:76) at
* org.jboss.seam.
* jsf.SeamPhaseListener.handleTransactionsAfterPhase(
* SeamPhaseListener.java:330) at
* org.jboss.seam.jsf.SeamPhaseListener
* .afterServletPhase(SeamPhaseListener.java:241) at
* org.jboss.seam.jsf
* .SeamPhaseListener.afterPhase(SeamPhaseListener.java:192) at
* com.sun.faces.lifecycle.Phase.handleAfterPhase(Phase.java:175)
* at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:114) at
* com.sun.faces
* .lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
*/
FacesLifecycle.endRequest(context.getExternalContext());
// do not release an actual FacesContext that we did not create,
// otherwise we get the following stack trace:
/**
* java.lang.IllegalStateException at
* com.sun.faces.context.FacesContextImpl
* .assertNotReleased(FacesContextImpl.java:395) at
* com.sun.faces.context
* .FacesContextImpl.getExternalContext(FacesContextImpl.java:147)
* at com.sun.faces.util.RequestStateManager.getStateMap(
* RequestStateManager.java:276) at
* com.sun.faces.util.RequestStateManager
* .remove(RequestStateManager.java:243) at
* com.sun.faces.context.FacesContextImpl
* .release(FacesContextImpl.java:345)
*/
context.release();
}
}
protected MockFacesContext createFacesContext(HttpServletRequest request,
HttpServletResponse response) {
MockFacesContext mockFacesContext = new MockFacesContext(
new MockExternalContext(
request.getSession().getServletContext(), request,
response), new MockApplication());
mockFacesContext.setViewRoot(new UIViewRoot());
return mockFacesContext;
}
}
| true | true | public void beforeSetErrorPageAttribute(Throwable t,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// cut/paste from seam Exception filter.
// we recreate the seam context to be able to use the messages.
// patch following https://jira.jboss.org/browse/JBPAPP-1427
// Ensure that the call in which the exception occurred was cleaned up
// - it might not be, and there is no harm in trying
// we keep around the synchronization component because
// SeSynchronizations expects it to be unchanged when called by
// the finally block of UTTransaction.rollback
String SEAM_TX_SYNCS = "org.jboss.seam.transaction.synchronizations";
Object syncs = Contexts.getEventContext().get(SEAM_TX_SYNCS);
Lifecycle.endRequest();
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext == null) {
// the FacesContext is gone - create a fake one for Redirect and
// HttpError to call
MockFacesContext mockContext = createFacesContext(request, response);
mockContext.setCurrent();
facesContext = mockContext;
log.debug("Created mock faces context for exception handling");
} else {
// do not use a mock faces context when a real one still exists:
// when released, the mock faces context is nullified, and this
// leads to errors like in the following stack trace:
/**
* java.lang.NullPointerException: FacesContext is null at
* org.ajax4jsf
* .context.AjaxContext.getCurrentInstance(AjaxContext.java:159) at
* org.ajax4jsf.context.AjaxContext.getCurrentInstance(AjaxContext.
* java:144) at
* org.ajax4jsf.component.AjaxViewRoot.getViewId(AjaxViewRoot
* .java:580) at
* com.sun.faces.lifecycle.Phase.doPhase(Phase.java:104)
*/
log.debug("Using existing faces context for exception handling");
}
// NXP-5998: conversation initialization seems to be already handled by
// SeamPhaseListener => do not handle conversation as otherwise it'll
// stay unlocked.
// if the event context was cleaned up, fish the conversation id
// directly out of the ServletRequest attributes, else get it from
// the event context
// Manager manager = Contexts.isEventContextActive() ? (Manager)
// Contexts.getEventContext().get(
// Manager.class)
// : (Manager)
// request.getAttribute(Seam.getComponentName(Manager.class));
// String conversationId = manager == null ? null
// : manager.getCurrentConversationId();
FacesLifecycle.beginExceptionRecovery(facesContext.getExternalContext());
// restore syncs
if (syncs != null) {
Contexts.getEventContext().set(SEAM_TX_SYNCS, syncs);
}
// If there is an existing long-running conversation on
// the failed request, propagate it
// if (conversationId == null) {
// Manager.instance().initializeTemporaryConversation();
// } else {
// ConversationPropagation.instance().setConversationId(conversationId);
// Manager.instance().restoreConversation();
// }
}
| public void beforeSetErrorPageAttribute(Throwable t,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// cut/paste from seam Exception filter.
// we recreate the seam context to be able to use the messages.
// patch following https://jira.jboss.org/browse/JBPAPP-1427
// Ensure that the call in which the exception occurred was cleaned up
// - it might not be, and there is no harm in trying
// we keep around the synchronization component because
// SeSynchronizations expects it to be unchanged when called by
// the finally block of UTTransaction.rollback
String SEAM_TX_SYNCS = "org.jboss.seam.transaction.synchronizations";
Object syncs = null;
if (Contexts.isEventContextActive()) {
syncs = Contexts.getEventContext().get(SEAM_TX_SYNCS);
}
Lifecycle.endRequest();
FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext == null) {
// the FacesContext is gone - create a fake one for Redirect and
// HttpError to call
MockFacesContext mockContext = createFacesContext(request, response);
mockContext.setCurrent();
facesContext = mockContext;
log.debug("Created mock faces context for exception handling");
} else {
// do not use a mock faces context when a real one still exists:
// when released, the mock faces context is nullified, and this
// leads to errors like in the following stack trace:
/**
* java.lang.NullPointerException: FacesContext is null at
* org.ajax4jsf
* .context.AjaxContext.getCurrentInstance(AjaxContext.java:159) at
* org.ajax4jsf.context.AjaxContext.getCurrentInstance(AjaxContext.
* java:144) at
* org.ajax4jsf.component.AjaxViewRoot.getViewId(AjaxViewRoot
* .java:580) at
* com.sun.faces.lifecycle.Phase.doPhase(Phase.java:104)
*/
log.debug("Using existing faces context for exception handling");
}
// NXP-5998: conversation initialization seems to be already handled by
// SeamPhaseListener => do not handle conversation as otherwise it'll
// stay unlocked.
// if the event context was cleaned up, fish the conversation id
// directly out of the ServletRequest attributes, else get it from
// the event context
// Manager manager = Contexts.isEventContextActive() ? (Manager)
// Contexts.getEventContext().get(
// Manager.class)
// : (Manager)
// request.getAttribute(Seam.getComponentName(Manager.class));
// String conversationId = manager == null ? null
// : manager.getCurrentConversationId();
FacesLifecycle.beginExceptionRecovery(facesContext.getExternalContext());
// restore syncs
if (syncs != null) {
Contexts.getEventContext().set(SEAM_TX_SYNCS, syncs);
}
// If there is an existing long-running conversation on
// the failed request, propagate it
// if (conversationId == null) {
// Manager.instance().initializeTemporaryConversation();
// } else {
// ConversationPropagation.instance().setConversationId(conversationId);
// Manager.instance().restoreConversation();
// }
}
|
diff --git a/src/keepcalm/mods/bukkit/ForgeEventHelper.java b/src/keepcalm/mods/bukkit/ForgeEventHelper.java
index 1bd0b58..b9149b2 100644
--- a/src/keepcalm/mods/bukkit/ForgeEventHelper.java
+++ b/src/keepcalm/mods/bukkit/ForgeEventHelper.java
@@ -1,134 +1,134 @@
package keepcalm.mods.bukkit;
import keepcalm.mods.bukkit.bukkitAPI.BukkitChunk;
import keepcalm.mods.bukkit.bukkitAPI.block.BukkitBlock;
import keepcalm.mods.bukkit.bukkitAPI.scheduler.BukkitDummyPlugin;
import keepcalm.mods.bukkit.events.BlockDestroyEvent;
import keepcalm.mods.bukkit.events.DispenseItemEvent;
import keepcalm.mods.bukkit.events.PlayerDamageBlockEvent;
import keepcalm.mods.bukkit.events.PlayerUseItemEvent;
import keepcalm.mods.bukkit.forgeHandler.ForgeEventHandler;
import net.minecraft.entity.passive.EntitySheep;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemInWorldManager;
import net.minecraft.item.ItemStack;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.common.MinecraftForge;
import org.bukkit.Bukkit;
import cpw.mods.fml.relauncher.Side;
public class ForgeEventHelper {
public static void onItemUse(ItemStack stack, EntityPlayer who, World world, int x, int y, int z, int blockFace) {
if (Side.CLIENT.isClient())
// not on client
return;
PlayerUseItemEvent ev = new PlayerUseItemEvent(stack, who, world, x, y, z, ForgeDirection.getOrientation(blockFace));
MinecraftForge.EVENT_BUS.post(ev);
}
public static boolean onBlockDamage(ItemInWorldManager man) {
// mcp has ridiculously long names
PlayerDamageBlockEvent ev = new PlayerDamageBlockEvent(man.thisPlayerMP, man.partiallyDestroyedBlockX,
man.partiallyDestroyedBlockY, man.partiallyDestroyedBlockZ,
man.theWorld, man.curblockDamage, man.durabilityRemainingOnBlock);
MinecraftForge.EVENT_BUS.post(ev);
if (ev.isCanceled()) {
return true;
}
return false;
}
/**
*
* @param block
* @param itemToDispense
* @param x
* @param y
* @param z
* @return whether to cancel or not (true == cancelled)
*/
public static boolean onDispenseItem(World world, int x, int y, int z, ItemStack itemToDispense) {
DispenseItemEvent ev = new DispenseItemEvent(x, y, z, world, itemToDispense);
MinecraftForge.EVENT_BUS.post(ev);
if (ev.isCanceled()) {
return true;
}
return false;
}
public static boolean onSheepDye(EntitySheep sheep, int newColor, byte oldColor) {
return false;
}
public static void onBlockBreak(final World world, final int x, final int y, final int z, final int id, final int data) {
if (!ForgeEventHandler.ready)
return;
try {
throw new RuntimeException("nobody saw this");
}
catch (RuntimeException ex) {
boolean foundIIWM = false;
int a = 0;
//System.out.println("StackTrace count: " + ex.getStackTrace().length);
for (StackTraceElement i : ex.getStackTrace()) {
if (a == 1) {
a++;
continue;
}
//System.out.println("Class found: " + i.getClassName());
if (i.getClassName().toLowerCase().contains("iteminworldmanager") || i.getClassName().toLowerCase().equals("ir")) {
foundIIWM = true;
break;
}
if (i.getMethodName().toLowerCase().contains("updateflow")) {
foundIIWM = true;
break;
}
if (i.getMethodName().toLowerCase().contains("l") && i.getClassName().toLowerCase().equals("aky")) {
foundIIWM = true;
break;
}
// it was us cancelling - or us doing something else
if (i.getClassName().contains("keepcalm.mods.bukkit")) {
foundIIWM = true;
break;
}
a++;
}
- if (foundIIWM) {// block break got this
- System.out.println("Cancelled.");
+ if (foundIIWM) {// block break got this, or it's something else
+ //System.out.println("Cancelled.");
return;
}
if (id == 0) // no point - air got broken
return;
- System.out.println("This is a break!");
+ //System.out.println("This is a break!");
Bukkit.getScheduler().runTaskLater(BukkitDummyPlugin.INSTANCE, new Runnable() {
@Override
public void run() {
BlockDestroyEvent ev = new BlockDestroyEvent(world, x, y, z, id, data);
MinecraftForge.EVENT_BUS.post(ev);
if (ev.isCanceled()) {
world.setBlockAndMetadata(x, y, z, id, data);
}
}
}, 10);
}
}
}
| false | true | public static void onBlockBreak(final World world, final int x, final int y, final int z, final int id, final int data) {
if (!ForgeEventHandler.ready)
return;
try {
throw new RuntimeException("nobody saw this");
}
catch (RuntimeException ex) {
boolean foundIIWM = false;
int a = 0;
//System.out.println("StackTrace count: " + ex.getStackTrace().length);
for (StackTraceElement i : ex.getStackTrace()) {
if (a == 1) {
a++;
continue;
}
//System.out.println("Class found: " + i.getClassName());
if (i.getClassName().toLowerCase().contains("iteminworldmanager") || i.getClassName().toLowerCase().equals("ir")) {
foundIIWM = true;
break;
}
if (i.getMethodName().toLowerCase().contains("updateflow")) {
foundIIWM = true;
break;
}
if (i.getMethodName().toLowerCase().contains("l") && i.getClassName().toLowerCase().equals("aky")) {
foundIIWM = true;
break;
}
// it was us cancelling - or us doing something else
if (i.getClassName().contains("keepcalm.mods.bukkit")) {
foundIIWM = true;
break;
}
a++;
}
if (foundIIWM) {// block break got this
System.out.println("Cancelled.");
return;
}
if (id == 0) // no point - air got broken
return;
System.out.println("This is a break!");
Bukkit.getScheduler().runTaskLater(BukkitDummyPlugin.INSTANCE, new Runnable() {
@Override
public void run() {
BlockDestroyEvent ev = new BlockDestroyEvent(world, x, y, z, id, data);
MinecraftForge.EVENT_BUS.post(ev);
if (ev.isCanceled()) {
world.setBlockAndMetadata(x, y, z, id, data);
}
}
}, 10);
}
}
| public static void onBlockBreak(final World world, final int x, final int y, final int z, final int id, final int data) {
if (!ForgeEventHandler.ready)
return;
try {
throw new RuntimeException("nobody saw this");
}
catch (RuntimeException ex) {
boolean foundIIWM = false;
int a = 0;
//System.out.println("StackTrace count: " + ex.getStackTrace().length);
for (StackTraceElement i : ex.getStackTrace()) {
if (a == 1) {
a++;
continue;
}
//System.out.println("Class found: " + i.getClassName());
if (i.getClassName().toLowerCase().contains("iteminworldmanager") || i.getClassName().toLowerCase().equals("ir")) {
foundIIWM = true;
break;
}
if (i.getMethodName().toLowerCase().contains("updateflow")) {
foundIIWM = true;
break;
}
if (i.getMethodName().toLowerCase().contains("l") && i.getClassName().toLowerCase().equals("aky")) {
foundIIWM = true;
break;
}
// it was us cancelling - or us doing something else
if (i.getClassName().contains("keepcalm.mods.bukkit")) {
foundIIWM = true;
break;
}
a++;
}
if (foundIIWM) {// block break got this, or it's something else
//System.out.println("Cancelled.");
return;
}
if (id == 0) // no point - air got broken
return;
//System.out.println("This is a break!");
Bukkit.getScheduler().runTaskLater(BukkitDummyPlugin.INSTANCE, new Runnable() {
@Override
public void run() {
BlockDestroyEvent ev = new BlockDestroyEvent(world, x, y, z, id, data);
MinecraftForge.EVENT_BUS.post(ev);
if (ev.isCanceled()) {
world.setBlockAndMetadata(x, y, z, id, data);
}
}
}, 10);
}
}
|
diff --git a/src/main/java/com/forum/web/controller/QuestionController.java b/src/main/java/com/forum/web/controller/QuestionController.java
index 1bd9f24..c5f7cf0 100644
--- a/src/main/java/com/forum/web/controller/QuestionController.java
+++ b/src/main/java/com/forum/web/controller/QuestionController.java
@@ -1,58 +1,58 @@
package com.forum.web.controller;
import com.forum.domain.Question;
import com.forum.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import java.text.SimpleDateFormat;
import java.util.Map;
@Controller
public class QuestionController {
private QuestionService questionService;
@Autowired
public QuestionController(QuestionService questionService) {
this.questionService = questionService;
}
@RequestMapping(value = "/postQuestion", method = RequestMethod.GET)
public ModelAndView postQuestion() {
return new ModelAndView("postQuestion");
}
@RequestMapping(value = "/showPostedQuestion", method = RequestMethod.POST)
public ModelAndView showPostedQuestion(@RequestParam Map<String, String> params){
questionService.createQuestion(params);
ModelAndView modelAndView = new ModelAndView("showPostedQuestion");
modelAndView.addObject("questionTitle",params.get("questionTitle"));
modelAndView.addObject("questionDescription",params.get("editor"));
return modelAndView;
}
@RequestMapping(value = "/question/view/{questionId}", method = RequestMethod.GET)
public ModelAndView viewQuestionDetail(@PathVariable Integer questionId) {
Question question = questionService.getById(questionId);
- ModelAndView modelAndView = new ModelAndView("questiondetail");
+ ModelAndView modelAndView = new ModelAndView("questionDetail");
modelAndView.addObject("questionTitle", question.getTitle());
modelAndView.addObject("questionDescription", question.getDescription());
modelAndView.addObject("username", question.getUser().getName());
modelAndView.addObject("dateCreatedAt", new SimpleDateFormat("dd/MM/yyyy").format(question.getCreatedAt()));
modelAndView.addObject("timeCreatedAt", new SimpleDateFormat("kk:mm:ss").format(question.getCreatedAt()));
modelAndView.addObject("likes", question.getLikes());
modelAndView.addObject("dislikes", question.getDislikes());
modelAndView.addObject("views", question.getViews());
modelAndView.addObject("flags", question.getFlags());
return modelAndView;
}
}
| true | true | public ModelAndView viewQuestionDetail(@PathVariable Integer questionId) {
Question question = questionService.getById(questionId);
ModelAndView modelAndView = new ModelAndView("questiondetail");
modelAndView.addObject("questionTitle", question.getTitle());
modelAndView.addObject("questionDescription", question.getDescription());
modelAndView.addObject("username", question.getUser().getName());
modelAndView.addObject("dateCreatedAt", new SimpleDateFormat("dd/MM/yyyy").format(question.getCreatedAt()));
modelAndView.addObject("timeCreatedAt", new SimpleDateFormat("kk:mm:ss").format(question.getCreatedAt()));
modelAndView.addObject("likes", question.getLikes());
modelAndView.addObject("dislikes", question.getDislikes());
modelAndView.addObject("views", question.getViews());
modelAndView.addObject("flags", question.getFlags());
return modelAndView;
}
| public ModelAndView viewQuestionDetail(@PathVariable Integer questionId) {
Question question = questionService.getById(questionId);
ModelAndView modelAndView = new ModelAndView("questionDetail");
modelAndView.addObject("questionTitle", question.getTitle());
modelAndView.addObject("questionDescription", question.getDescription());
modelAndView.addObject("username", question.getUser().getName());
modelAndView.addObject("dateCreatedAt", new SimpleDateFormat("dd/MM/yyyy").format(question.getCreatedAt()));
modelAndView.addObject("timeCreatedAt", new SimpleDateFormat("kk:mm:ss").format(question.getCreatedAt()));
modelAndView.addObject("likes", question.getLikes());
modelAndView.addObject("dislikes", question.getDislikes());
modelAndView.addObject("views", question.getViews());
modelAndView.addObject("flags", question.getFlags());
return modelAndView;
}
|
diff --git a/pentaho-aggdesigner-ui/test-src/org/pentaho/aggdes/ui/MainControllerTest.java b/pentaho-aggdesigner-ui/test-src/org/pentaho/aggdes/ui/MainControllerTest.java
index cdb4de6..4746e02 100644
--- a/pentaho-aggdesigner-ui/test-src/org/pentaho/aggdes/ui/MainControllerTest.java
+++ b/pentaho-aggdesigner-ui/test-src/org/pentaho/aggdes/ui/MainControllerTest.java
@@ -1,435 +1,435 @@
/*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License, version 2 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/gpl-2.0.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
*
* Copyright 2008 Pentaho Corporation. All rights reserved.
*/
package org.pentaho.aggdes.ui;
import static org.pentaho.aggdes.test.util.TestUtils.getTestProperty;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import junit.framework.TestCase;
import org.pentaho.aggdes.test.algorithm.impl.SchemaStub;
import org.pentaho.aggdes.ui.ext.SchemaProviderUiExtension;
import org.pentaho.aggdes.ui.ext.impl.MondrianFileSchemaModel;
import org.pentaho.aggdes.ui.ext.impl.MondrianFileSchemaProvider;
import org.pentaho.aggdes.ui.form.controller.ConnectionController;
import org.pentaho.aggdes.ui.form.controller.MainController;
import org.pentaho.aggdes.ui.form.model.ConnectionModelImpl;
import org.pentaho.aggdes.ui.model.AggList;
import org.pentaho.aggdes.ui.util.SerializationService;
import org.pentaho.aggdes.ui.xulstubs.XulDomContainerStub;
import org.pentaho.aggdes.ui.xulstubs.XulFileDialogStub;
import org.pentaho.aggdes.ui.xulstubs.XulMessageBoxStub;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulDomException;
import org.pentaho.ui.xul.XulEventSource;
import org.pentaho.ui.xul.XulException;
import org.pentaho.ui.xul.XulLoader;
import org.pentaho.ui.xul.binding.Binding;
import org.pentaho.ui.xul.components.XulFileDialog;
import org.pentaho.ui.xul.components.XulMessageBox;
import org.pentaho.ui.xul.components.XulFileDialog.RETURN_CODE;
import org.pentaho.ui.xul.dom.Attribute;
import org.pentaho.ui.xul.dom.Document;
import org.pentaho.ui.xul.dom.Element;
import org.pentaho.ui.xul.dom.Namespace;
import org.pentaho.ui.xul.impl.XulEventHandler;
public class MainControllerTest extends TestCase {
public void testSaveWorkspace() throws Exception {
// INITIAL STUB WIRING
Workspace workspace = new Workspace();
SchemaStub schemaStub = new SchemaStub();
ConnectionModelImpl connectionModel = new ConnectionModelImpl();
connectionModel.setDatabaseMeta(new DatabaseMeta());
MondrianFileSchemaModel schemaModel = new MondrianFileSchemaModel();
schemaModel.setMondrianSchemaFilename(getTestProperty("test.mondrian.foodmart.connectString.catalog"));
connectionModel.setSelectedSchemaModel(schemaModel);
connectionModel.setCubeName("Sales");
AggList aggList = SerializationServiceTest.getAggList(schemaStub);
SerializationService serializationService = new SerializationService();
serializationService.setConnectionModel(connectionModel);
serializationService.setAggList(aggList);
workspace.setSchema(schemaStub);
XulDomContainer xulDomContainer = new XulDomContainerStub();
MainController controller = new MainController();
controller.setXulDomContainer(xulDomContainer);
controller.setWorkspace(workspace);
controller.setConnectionModel(connectionModel);
controller.setSerializationService(serializationService);
// TEST 1 - App Locked
workspace.setWorkspaceUpToDate(false);
workspace.setApplicationUnlocked(false);
controller.saveWorkspace(false);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 1);
assertTrue(XulMessageBoxStub.openedMessageBoxes.get(0).getMessage().indexOf("Cannot save") >= 0);
// makes sure we didn't make it past where we were
assertFalse(workspace.getWorkspaceUpToDate());
// TEST 2 - User Cancels In File Dialog
XulMessageBoxStub.openedMessageBoxes.clear();
XulFileDialogStub.openedFileDialogs.clear();
XulFileDialogStub.returnCode = RETURN_CODE.CANCEL;
workspace.setApplicationUnlocked(true);
controller.saveWorkspace(false);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 0);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 1);
assertFalse(workspace.getWorkspaceUpToDate());
// TEST 3 - Save Design
XulMessageBoxStub.openedMessageBoxes.clear();
XulFileDialogStub.openedFileDialogs.clear();
XulFileDialogStub.returnCode = RETURN_CODE.OK;
XulFileDialogStub.returnFile = new File("temp_design_output.xml");
if (XulFileDialogStub.returnFile.exists()) {
XulFileDialogStub.returnFile.delete();
}
controller.saveWorkspace(false);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 0);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 1);
assertEquals(workspace.getWorkspaceLocation(), XulFileDialogStub.returnFile);
assertTrue(workspace.getWorkspaceUpToDate());
assertTrue(XulFileDialogStub.returnFile.exists());
// TEST 4 - Save without File Dialog, already has save location
XulMessageBoxStub.openedMessageBoxes.clear();
XulFileDialogStub.openedFileDialogs.clear();
if (XulFileDialogStub.returnFile.exists()) {
XulFileDialogStub.returnFile.delete();
}
controller.saveWorkspace(false);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 0);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 0);
assertEquals(workspace.getWorkspaceLocation(), XulFileDialogStub.returnFile);
assertTrue(workspace.getWorkspaceUpToDate());
assertTrue(XulFileDialogStub.returnFile.exists());
// TEST 5 - Save As
XulMessageBoxStub.openedMessageBoxes.clear();
XulFileDialogStub.openedFileDialogs.clear();
XulFileDialogStub.returnCode = RETURN_CODE.OK;
XulFileDialogStub.returnFile = new File("temp_design_output.xml");
if (XulFileDialogStub.returnFile.exists()) {
XulFileDialogStub.returnFile.delete();
}
controller.saveWorkspace(true);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 0);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 1);
assertEquals(workspace.getWorkspaceLocation(), XulFileDialogStub.returnFile);
assertTrue(workspace.getWorkspaceUpToDate());
assertTrue(XulFileDialogStub.returnFile.exists());
// TEST 6 - Save to Directory
workspace.setWorkspaceLocation(null);
workspace.setWorkspaceUpToDate(false);
XulMessageBoxStub.openedMessageBoxes.clear();
XulFileDialogStub.openedFileDialogs.clear();
XulFileDialogStub.returnCode = RETURN_CODE.OK;
- XulFileDialogStub.returnFile = new File(".");
+ XulFileDialogStub.returnFile = new File("dummyWorkspaceFile");
controller.saveWorkspace(false);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 1);
assertTrue(XulMessageBoxStub.openedMessageBoxes.get(0).getMessage().indexOf("Failed") >= 0);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 1);
assertNull(workspace.getWorkspaceLocation());
assertFalse(workspace.getWorkspaceUpToDate());
}
public void testPromptIfSaveRequired() throws XulException {
// INITIAL STUB WIRING
Workspace workspace = new Workspace();
SchemaStub schemaStub = new SchemaStub();
ConnectionModelImpl connectionModel = new ConnectionModelImpl();
connectionModel.setDatabaseMeta(new DatabaseMeta());
MondrianFileSchemaModel schemaModel = new MondrianFileSchemaModel();
schemaModel.setMondrianSchemaFilename(getTestProperty("test.mondrian.foodmart.connectString.catalog"));
connectionModel.setSelectedSchemaModel(schemaModel);
connectionModel.setCubeName("Sales");
AggList aggList = SerializationServiceTest.getAggList(schemaStub);
SerializationService serializationService = new SerializationService();
serializationService.setConnectionModel(connectionModel);
serializationService.setAggList(aggList);
workspace.setSchema(schemaStub);
XulDomContainer xulDomContainer = new XulDomContainerStub();
MainController controller = new MainController();
controller.setXulDomContainer(xulDomContainer);
controller.setWorkspace(workspace);
controller.setConnectionModel(connectionModel);
controller.setSerializationService(serializationService);
// Test 1 - No Prompt Necessary
XulMessageBoxStub.openedMessageBoxes.clear();
XulFileDialogStub.openedFileDialogs.clear();
workspace.setApplicationUnlocked(false);
workspace.setWorkspaceUpToDate(false);
boolean rtnValue = controller.promptIfSaveRequired();
assertEquals(rtnValue, true);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 0);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 0);
// Test 2 - Still No Prompt Necessary
workspace.setApplicationUnlocked(false);
workspace.setWorkspaceUpToDate(true);
rtnValue = controller.promptIfSaveRequired();
assertEquals(rtnValue, true);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 0);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 0);
// Test 3 - Still No Prompt Necessary
workspace.setApplicationUnlocked(true);
workspace.setWorkspaceUpToDate(true);
rtnValue = controller.promptIfSaveRequired();
assertEquals(rtnValue, true);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 0);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 0);
// Test 4 - Prompt Necessary, Cancel
workspace.setApplicationUnlocked(true);
workspace.setWorkspaceUpToDate(false);
XulMessageBoxStub.returnCode = 2;
rtnValue = controller.promptIfSaveRequired();
assertEquals(rtnValue, false);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 1);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 0);
// Test 4 - Prompt Necessary, Don't Save
XulMessageBoxStub.openedMessageBoxes.clear();
workspace.setApplicationUnlocked(true);
workspace.setWorkspaceUpToDate(false);
XulMessageBoxStub.returnCode = 1;
rtnValue = controller.promptIfSaveRequired();
assertEquals(rtnValue, true);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 1);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 0);
// Test 5 - Prompt Necessary, Save (Cancel)
XulMessageBoxStub.openedMessageBoxes.clear();
workspace.setApplicationUnlocked(true);
workspace.setWorkspaceUpToDate(false);
XulMessageBoxStub.returnCode = 0;
XulFileDialogStub.returnCode = RETURN_CODE.OK;
rtnValue = controller.promptIfSaveRequired();
assertEquals(rtnValue, false);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 2);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 1);
}
public void testOpenWorkspace() throws XulException {
// INITIAL STUB WIRING
Workspace workspace = new Workspace();
final SchemaStub schemaStub = new SchemaStub();
final ConnectionModelImpl connectionModel = new ConnectionModelImpl();
connectionModel.setDatabaseMeta(new DatabaseMeta());
MondrianFileSchemaModel schemaModel = new MondrianFileSchemaModel();
schemaModel.setMondrianSchemaFilename(getTestProperty("test.mondrian.foodmart.connectString.catalog"));
connectionModel.setSelectedSchemaModel(schemaModel);
connectionModel.setCubeName("Sales");
AggList aggList = SerializationServiceTest.getAggList(schemaStub);
SerializationService serializationService = new SerializationService();
serializationService.setConnectionModel(connectionModel);
serializationService.setAggList(aggList);
workspace.setSchema(schemaStub);
XulDomContainer xulDomContainer = new XulDomContainerStub();
MainController controller = new MainController();
controller.setXulDomContainer(xulDomContainer);
controller.setWorkspace(workspace);
controller.setConnectionModel(connectionModel);
controller.setSerializationService(serializationService);
final List<Integer> connected = new ArrayList<Integer>();
final List<Integer> applied = new ArrayList<Integer>();
ConnectionController connectionController = new ConnectionController() {
public void connect() {
connected.add(1);
connectionModel.setSchema(schemaStub);
}
public void apply() {
applied.add(1);
}
};
connectionController.setConnectionModel(connectionModel);
controller.setConnectionController(connectionController);
// Save temporary design
XulMessageBoxStub.openedMessageBoxes.clear();
XulFileDialogStub.openedFileDialogs.clear();
workspace.setApplicationUnlocked(true);
workspace.setWorkspaceUpToDate(true);
XulFileDialogStub.returnCode = RETURN_CODE.OK;
XulFileDialogStub.returnFile = new File("temp_design_output.xml");
if (XulFileDialogStub.returnFile.exists()) {
XulFileDialogStub.returnFile.delete();
}
controller.saveWorkspace(false);
assertTrue(XulFileDialogStub.returnFile.exists());
// Test 1 - Cancel Opening
XulMessageBoxStub.openedMessageBoxes.clear();
XulFileDialogStub.openedFileDialogs.clear();
XulFileDialogStub.returnCode = RETURN_CODE.CANCEL;
controller.openWorkspace();
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 0);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 1);
// Test 2 - Happy Path
XulMessageBoxStub.openedMessageBoxes.clear();
XulFileDialogStub.openedFileDialogs.clear();
XulFileDialogStub.returnCode = RETURN_CODE.OK;
aggList.clearAggs();
controller.openWorkspace();
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 0);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 1);
assertEquals(connected.size(), 1);
assertEquals(applied.size(), 1);
assertEquals(aggList.getSize(), 4);
assertEquals(workspace.isApplicationUnlocked(), true);
assertEquals(workspace.getWorkspaceUpToDate(), true);
}
public void testNewWorkspace() throws Exception {
Workspace workspace = new Workspace();
SchemaStub schemaStub = new SchemaStub();
ConnectionModelImpl connectionModel = new ConnectionModelImpl();
// ConnectionController connectionController = new ConnectionController();
// connectionController.setConnectionModel(connectionModel);
// List<SchemaProviderUiExtension> providerList = new ArrayList<SchemaProviderUiExtension>();
// MondrianFileSchemaProvider mondrianProvider = new MondrianFileSchemaProvider();
// providerList.add(mondrianProvider);
connectionModel.setDatabaseMeta(new DatabaseMeta());
MondrianFileSchemaModel schemaModel = new MondrianFileSchemaModel();
schemaModel.setMondrianSchemaFilename(getTestProperty("test.mondrian.foodmart.connectString.catalog"));
connectionModel.setSelectedSchemaModel(schemaModel);
connectionModel.setCubeName("Sales");
AggList aggList = SerializationServiceTest.getAggList(schemaStub);
SerializationService serializationService = new SerializationService();
serializationService.setConnectionModel(connectionModel);
serializationService.setAggList(aggList);
workspace.setSchema(schemaStub);
XulDomContainer xulDomContainer = new XulDomContainerStub();
MainController controller = new MainController();
final List<Integer> showDialog = new ArrayList<Integer>();
ConnectionController connectionController = new ConnectionController() {
public void showConnectionDialog(){
showDialog.add(1);
}
};
connectionController.setConnectionModel(connectionModel);
controller.setConnectionController(connectionController);
controller.setAggList(aggList);
controller.setXulDomContainer(xulDomContainer);
controller.setWorkspace(workspace);
controller.setConnectionModel(connectionModel);
controller.setConnectionController(connectionController);
controller.setSerializationService(serializationService);
controller.newWorkspace();
assertEquals(aggList.getSize(), 0);
assertEquals(showDialog.size(), 1);
}
}
| true | true | public void testSaveWorkspace() throws Exception {
// INITIAL STUB WIRING
Workspace workspace = new Workspace();
SchemaStub schemaStub = new SchemaStub();
ConnectionModelImpl connectionModel = new ConnectionModelImpl();
connectionModel.setDatabaseMeta(new DatabaseMeta());
MondrianFileSchemaModel schemaModel = new MondrianFileSchemaModel();
schemaModel.setMondrianSchemaFilename(getTestProperty("test.mondrian.foodmart.connectString.catalog"));
connectionModel.setSelectedSchemaModel(schemaModel);
connectionModel.setCubeName("Sales");
AggList aggList = SerializationServiceTest.getAggList(schemaStub);
SerializationService serializationService = new SerializationService();
serializationService.setConnectionModel(connectionModel);
serializationService.setAggList(aggList);
workspace.setSchema(schemaStub);
XulDomContainer xulDomContainer = new XulDomContainerStub();
MainController controller = new MainController();
controller.setXulDomContainer(xulDomContainer);
controller.setWorkspace(workspace);
controller.setConnectionModel(connectionModel);
controller.setSerializationService(serializationService);
// TEST 1 - App Locked
workspace.setWorkspaceUpToDate(false);
workspace.setApplicationUnlocked(false);
controller.saveWorkspace(false);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 1);
assertTrue(XulMessageBoxStub.openedMessageBoxes.get(0).getMessage().indexOf("Cannot save") >= 0);
// makes sure we didn't make it past where we were
assertFalse(workspace.getWorkspaceUpToDate());
// TEST 2 - User Cancels In File Dialog
XulMessageBoxStub.openedMessageBoxes.clear();
XulFileDialogStub.openedFileDialogs.clear();
XulFileDialogStub.returnCode = RETURN_CODE.CANCEL;
workspace.setApplicationUnlocked(true);
controller.saveWorkspace(false);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 0);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 1);
assertFalse(workspace.getWorkspaceUpToDate());
// TEST 3 - Save Design
XulMessageBoxStub.openedMessageBoxes.clear();
XulFileDialogStub.openedFileDialogs.clear();
XulFileDialogStub.returnCode = RETURN_CODE.OK;
XulFileDialogStub.returnFile = new File("temp_design_output.xml");
if (XulFileDialogStub.returnFile.exists()) {
XulFileDialogStub.returnFile.delete();
}
controller.saveWorkspace(false);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 0);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 1);
assertEquals(workspace.getWorkspaceLocation(), XulFileDialogStub.returnFile);
assertTrue(workspace.getWorkspaceUpToDate());
assertTrue(XulFileDialogStub.returnFile.exists());
// TEST 4 - Save without File Dialog, already has save location
XulMessageBoxStub.openedMessageBoxes.clear();
XulFileDialogStub.openedFileDialogs.clear();
if (XulFileDialogStub.returnFile.exists()) {
XulFileDialogStub.returnFile.delete();
}
controller.saveWorkspace(false);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 0);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 0);
assertEquals(workspace.getWorkspaceLocation(), XulFileDialogStub.returnFile);
assertTrue(workspace.getWorkspaceUpToDate());
assertTrue(XulFileDialogStub.returnFile.exists());
// TEST 5 - Save As
XulMessageBoxStub.openedMessageBoxes.clear();
XulFileDialogStub.openedFileDialogs.clear();
XulFileDialogStub.returnCode = RETURN_CODE.OK;
XulFileDialogStub.returnFile = new File("temp_design_output.xml");
if (XulFileDialogStub.returnFile.exists()) {
XulFileDialogStub.returnFile.delete();
}
controller.saveWorkspace(true);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 0);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 1);
assertEquals(workspace.getWorkspaceLocation(), XulFileDialogStub.returnFile);
assertTrue(workspace.getWorkspaceUpToDate());
assertTrue(XulFileDialogStub.returnFile.exists());
// TEST 6 - Save to Directory
workspace.setWorkspaceLocation(null);
workspace.setWorkspaceUpToDate(false);
XulMessageBoxStub.openedMessageBoxes.clear();
XulFileDialogStub.openedFileDialogs.clear();
XulFileDialogStub.returnCode = RETURN_CODE.OK;
XulFileDialogStub.returnFile = new File(".");
controller.saveWorkspace(false);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 1);
assertTrue(XulMessageBoxStub.openedMessageBoxes.get(0).getMessage().indexOf("Failed") >= 0);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 1);
assertNull(workspace.getWorkspaceLocation());
assertFalse(workspace.getWorkspaceUpToDate());
}
| public void testSaveWorkspace() throws Exception {
// INITIAL STUB WIRING
Workspace workspace = new Workspace();
SchemaStub schemaStub = new SchemaStub();
ConnectionModelImpl connectionModel = new ConnectionModelImpl();
connectionModel.setDatabaseMeta(new DatabaseMeta());
MondrianFileSchemaModel schemaModel = new MondrianFileSchemaModel();
schemaModel.setMondrianSchemaFilename(getTestProperty("test.mondrian.foodmart.connectString.catalog"));
connectionModel.setSelectedSchemaModel(schemaModel);
connectionModel.setCubeName("Sales");
AggList aggList = SerializationServiceTest.getAggList(schemaStub);
SerializationService serializationService = new SerializationService();
serializationService.setConnectionModel(connectionModel);
serializationService.setAggList(aggList);
workspace.setSchema(schemaStub);
XulDomContainer xulDomContainer = new XulDomContainerStub();
MainController controller = new MainController();
controller.setXulDomContainer(xulDomContainer);
controller.setWorkspace(workspace);
controller.setConnectionModel(connectionModel);
controller.setSerializationService(serializationService);
// TEST 1 - App Locked
workspace.setWorkspaceUpToDate(false);
workspace.setApplicationUnlocked(false);
controller.saveWorkspace(false);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 1);
assertTrue(XulMessageBoxStub.openedMessageBoxes.get(0).getMessage().indexOf("Cannot save") >= 0);
// makes sure we didn't make it past where we were
assertFalse(workspace.getWorkspaceUpToDate());
// TEST 2 - User Cancels In File Dialog
XulMessageBoxStub.openedMessageBoxes.clear();
XulFileDialogStub.openedFileDialogs.clear();
XulFileDialogStub.returnCode = RETURN_CODE.CANCEL;
workspace.setApplicationUnlocked(true);
controller.saveWorkspace(false);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 0);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 1);
assertFalse(workspace.getWorkspaceUpToDate());
// TEST 3 - Save Design
XulMessageBoxStub.openedMessageBoxes.clear();
XulFileDialogStub.openedFileDialogs.clear();
XulFileDialogStub.returnCode = RETURN_CODE.OK;
XulFileDialogStub.returnFile = new File("temp_design_output.xml");
if (XulFileDialogStub.returnFile.exists()) {
XulFileDialogStub.returnFile.delete();
}
controller.saveWorkspace(false);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 0);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 1);
assertEquals(workspace.getWorkspaceLocation(), XulFileDialogStub.returnFile);
assertTrue(workspace.getWorkspaceUpToDate());
assertTrue(XulFileDialogStub.returnFile.exists());
// TEST 4 - Save without File Dialog, already has save location
XulMessageBoxStub.openedMessageBoxes.clear();
XulFileDialogStub.openedFileDialogs.clear();
if (XulFileDialogStub.returnFile.exists()) {
XulFileDialogStub.returnFile.delete();
}
controller.saveWorkspace(false);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 0);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 0);
assertEquals(workspace.getWorkspaceLocation(), XulFileDialogStub.returnFile);
assertTrue(workspace.getWorkspaceUpToDate());
assertTrue(XulFileDialogStub.returnFile.exists());
// TEST 5 - Save As
XulMessageBoxStub.openedMessageBoxes.clear();
XulFileDialogStub.openedFileDialogs.clear();
XulFileDialogStub.returnCode = RETURN_CODE.OK;
XulFileDialogStub.returnFile = new File("temp_design_output.xml");
if (XulFileDialogStub.returnFile.exists()) {
XulFileDialogStub.returnFile.delete();
}
controller.saveWorkspace(true);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 0);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 1);
assertEquals(workspace.getWorkspaceLocation(), XulFileDialogStub.returnFile);
assertTrue(workspace.getWorkspaceUpToDate());
assertTrue(XulFileDialogStub.returnFile.exists());
// TEST 6 - Save to Directory
workspace.setWorkspaceLocation(null);
workspace.setWorkspaceUpToDate(false);
XulMessageBoxStub.openedMessageBoxes.clear();
XulFileDialogStub.openedFileDialogs.clear();
XulFileDialogStub.returnCode = RETURN_CODE.OK;
XulFileDialogStub.returnFile = new File("dummyWorkspaceFile");
controller.saveWorkspace(false);
assertEquals(XulMessageBoxStub.openedMessageBoxes.size(), 1);
assertTrue(XulMessageBoxStub.openedMessageBoxes.get(0).getMessage().indexOf("Failed") >= 0);
assertEquals(XulFileDialogStub.openedFileDialogs.size(), 1);
assertNull(workspace.getWorkspaceLocation());
assertFalse(workspace.getWorkspaceUpToDate());
}
|
diff --git a/src/main/java/org/osiam/resources/helper/ExtensionSerializer.java b/src/main/java/org/osiam/resources/helper/ExtensionSerializer.java
index e1d582c..3297f91 100644
--- a/src/main/java/org/osiam/resources/helper/ExtensionSerializer.java
+++ b/src/main/java/org/osiam/resources/helper/ExtensionSerializer.java
@@ -1,73 +1,72 @@
/*
* Copyright (C) 2013 tarent AG
*
* 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.osiam.resources.helper;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Map;
import java.util.Map.Entry;
import org.osiam.resources.scim.Extension;
import org.osiam.resources.scim.Extension.Field;
import org.osiam.resources.scim.ExtensionFieldType;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class ExtensionSerializer extends JsonSerializer<Extension> {
@Override
- public void serialize(Extension value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
- JsonProcessingException {
+ public void serialize(Extension value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeStartObject();
Map<String, Field> fields = value.getAllFields();
for (Entry<String, Field> entry : fields.entrySet()) {
String fieldName = entry.getKey();
ExtensionFieldType<?> fieldType = entry.getValue().getType();
String rawFieldValue = entry.getValue().getValue();
jgen.writeFieldName(fieldName);
if (fieldType == ExtensionFieldType.INTEGER) {
BigInteger valueAsBigInteger = ExtensionFieldType.INTEGER.fromString(rawFieldValue);
jgen.writeNumber(valueAsBigInteger);
} else if (fieldType == ExtensionFieldType.DECIMAL) {
BigDecimal valueAsBigDecimal = ExtensionFieldType.DECIMAL.fromString(rawFieldValue);
jgen.writeNumber(valueAsBigDecimal);
} else if (fieldType == ExtensionFieldType.BOOLEAN) {
Boolean valueAsBoolean = ExtensionFieldType.BOOLEAN.fromString(rawFieldValue);
jgen.writeBoolean(valueAsBoolean);
} else {
jgen.writeString(rawFieldValue);
}
}
jgen.writeEndObject();
}
}
| true | true | public void serialize(Extension value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeStartObject();
Map<String, Field> fields = value.getAllFields();
for (Entry<String, Field> entry : fields.entrySet()) {
String fieldName = entry.getKey();
ExtensionFieldType<?> fieldType = entry.getValue().getType();
String rawFieldValue = entry.getValue().getValue();
jgen.writeFieldName(fieldName);
if (fieldType == ExtensionFieldType.INTEGER) {
BigInteger valueAsBigInteger = ExtensionFieldType.INTEGER.fromString(rawFieldValue);
jgen.writeNumber(valueAsBigInteger);
} else if (fieldType == ExtensionFieldType.DECIMAL) {
BigDecimal valueAsBigDecimal = ExtensionFieldType.DECIMAL.fromString(rawFieldValue);
jgen.writeNumber(valueAsBigDecimal);
} else if (fieldType == ExtensionFieldType.BOOLEAN) {
Boolean valueAsBoolean = ExtensionFieldType.BOOLEAN.fromString(rawFieldValue);
jgen.writeBoolean(valueAsBoolean);
} else {
jgen.writeString(rawFieldValue);
}
}
jgen.writeEndObject();
}
| public void serialize(Extension value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeStartObject();
Map<String, Field> fields = value.getAllFields();
for (Entry<String, Field> entry : fields.entrySet()) {
String fieldName = entry.getKey();
ExtensionFieldType<?> fieldType = entry.getValue().getType();
String rawFieldValue = entry.getValue().getValue();
jgen.writeFieldName(fieldName);
if (fieldType == ExtensionFieldType.INTEGER) {
BigInteger valueAsBigInteger = ExtensionFieldType.INTEGER.fromString(rawFieldValue);
jgen.writeNumber(valueAsBigInteger);
} else if (fieldType == ExtensionFieldType.DECIMAL) {
BigDecimal valueAsBigDecimal = ExtensionFieldType.DECIMAL.fromString(rawFieldValue);
jgen.writeNumber(valueAsBigDecimal);
} else if (fieldType == ExtensionFieldType.BOOLEAN) {
Boolean valueAsBoolean = ExtensionFieldType.BOOLEAN.fromString(rawFieldValue);
jgen.writeBoolean(valueAsBoolean);
} else {
jgen.writeString(rawFieldValue);
}
}
jgen.writeEndObject();
}
|
diff --git a/odata4j-fit/src/test/java/org/odata4j/test/core/OEntityKeyTest.java b/odata4j-fit/src/test/java/org/odata4j/test/core/OEntityKeyTest.java
index 2b396d18..7416933a 100644
--- a/odata4j-fit/src/test/java/org/odata4j/test/core/OEntityKeyTest.java
+++ b/odata4j-fit/src/test/java/org/odata4j/test/core/OEntityKeyTest.java
@@ -1,104 +1,104 @@
package org.odata4j.test.core;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import junit.framework.Assert;
import org.junit.Test;
import org.odata4j.core.NamedValue;
import org.odata4j.core.OEntityKey;
import org.odata4j.core.OEntityKey.KeyType;
import org.odata4j.core.OProperties;
public class OEntityKeyTest {
@Test
public void parseTests() {
Assert.assertEquals(k(1), OEntityKey.parse("(1)"));
Assert.assertEquals(k(1), OEntityKey.parse("1"));
Assert.assertEquals(k(1L), OEntityKey.parse("(1L)"));
Assert.assertEquals(k("a"), OEntityKey.parse("('a')"));
Assert.assertEquals(k("a"), OEntityKey.parse("(s='a')"));
Assert.assertEquals(k("PartitionKey", "", "RowKey", "1"), OEntityKey.parse("(PartitionKey='',RowKey='1')"));
Assert.assertEquals(k(new BigDecimal("43.9000")), OEntityKey.parse("(43.9000M)"));
}
@Test
public void createTests() {
sk("1", 1);
sk("1L", 1L);
sk("1", (short) 1);
- sk("01", (byte) 1);
+ sk("-5", (byte) -5);
sk("true", true);
sk("'1'", "1");
sk("'1'", '1');
sk("'quo''te'", "quo'te");
sk("1", OProperties.int32("n", 1), 1);
Assert.assertEquals(k(1).hashCode(), k(1).hashCode());
Assert.assertEquals(k(1), k(1));
ck("a=1,b=2", OProperties.int32("a", 1), OProperties.int32("b", 2));
ck("a=1,b=2", k("a", 1, "b", 2));
i((Object[]) null);
i();
i(1, 1);
i(OProperties.int32("a", 1), 1);
i(OProperties.int32("a", 1), null);
i(OProperties.int32("a", 1), OProperties.string("b", null));
i(OProperties.int32("a", 1), OProperties.int32(null, 2));
i(OProperties.int32("a", 1), OProperties.int32("", 2));
i(new StringBuilder());
}
private static void i(Object... values) {
try {
OEntityKey.create(values);
} catch (IllegalArgumentException e) {
// expected
return;
}
Assert.fail("Did not throw expected IllegalArgumentException");
}
private static OEntityKey k(Object value) {
return OEntityKey.create(value);
}
private static OEntityKey k(Object... nameValues) {
Map<String, Object> rt = new HashMap<String, Object>();
for (int i = 0; i < nameValues.length; i += 2) {
String name = (String) nameValues[i];
Object value = nameValues[i + 1];
rt.put(name, value);
}
return OEntityKey.create(rt);
}
private static void ck(String keyString, NamedValue<?>... nvs) {
OEntityKey k = OEntityKey.create((Object[]) nvs);
ck(keyString, k);
}
private static void ck(String keyString, OEntityKey k) {
Assert.assertNotNull(k);
Assert.assertTrue(k.getKeyType() == KeyType.COMPLEX);
Assert.assertEquals("(" + keyString + ")", k.toKeyString());
}
private static void sk(String keyString, Object singleValue) {
sk(keyString, singleValue, singleValue);
}
private static void sk(String keyString, Object singleValueInput, Object singleValue) {
OEntityKey k = k(singleValueInput);
Assert.assertNotNull(k);
Assert.assertTrue(k.getKeyType() == KeyType.SINGLE);
Assert.assertEquals(singleValue, k.asSingleValue());
Assert.assertEquals("(" + keyString + ")", k.toKeyString());
}
}
| true | true | public void createTests() {
sk("1", 1);
sk("1L", 1L);
sk("1", (short) 1);
sk("01", (byte) 1);
sk("true", true);
sk("'1'", "1");
sk("'1'", '1');
sk("'quo''te'", "quo'te");
sk("1", OProperties.int32("n", 1), 1);
Assert.assertEquals(k(1).hashCode(), k(1).hashCode());
Assert.assertEquals(k(1), k(1));
ck("a=1,b=2", OProperties.int32("a", 1), OProperties.int32("b", 2));
ck("a=1,b=2", k("a", 1, "b", 2));
i((Object[]) null);
i();
i(1, 1);
i(OProperties.int32("a", 1), 1);
i(OProperties.int32("a", 1), null);
i(OProperties.int32("a", 1), OProperties.string("b", null));
i(OProperties.int32("a", 1), OProperties.int32(null, 2));
i(OProperties.int32("a", 1), OProperties.int32("", 2));
i(new StringBuilder());
}
| public void createTests() {
sk("1", 1);
sk("1L", 1L);
sk("1", (short) 1);
sk("-5", (byte) -5);
sk("true", true);
sk("'1'", "1");
sk("'1'", '1');
sk("'quo''te'", "quo'te");
sk("1", OProperties.int32("n", 1), 1);
Assert.assertEquals(k(1).hashCode(), k(1).hashCode());
Assert.assertEquals(k(1), k(1));
ck("a=1,b=2", OProperties.int32("a", 1), OProperties.int32("b", 2));
ck("a=1,b=2", k("a", 1, "b", 2));
i((Object[]) null);
i();
i(1, 1);
i(OProperties.int32("a", 1), 1);
i(OProperties.int32("a", 1), null);
i(OProperties.int32("a", 1), OProperties.string("b", null));
i(OProperties.int32("a", 1), OProperties.int32(null, 2));
i(OProperties.int32("a", 1), OProperties.int32("", 2));
i(new StringBuilder());
}
|
diff --git a/plugins/org.eclipse.m2m.atl.engine.vm/src/org/eclipse/m2m/atl/engine/vm/nativelib/ASMTransientLinkSet.java b/plugins/org.eclipse.m2m.atl.engine.vm/src/org/eclipse/m2m/atl/engine/vm/nativelib/ASMTransientLinkSet.java
index ba9fc728..8d65e979 100644
--- a/plugins/org.eclipse.m2m.atl.engine.vm/src/org/eclipse/m2m/atl/engine/vm/nativelib/ASMTransientLinkSet.java
+++ b/plugins/org.eclipse.m2m.atl.engine.vm/src/org/eclipse/m2m/atl/engine/vm/nativelib/ASMTransientLinkSet.java
@@ -1,158 +1,158 @@
/*******************************************************************************
* Copyright (c) 2004 INRIA.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Frederic Jouault (INRIA) - initial API and implementation
*******************************************************************************/
package org.eclipse.m2m.atl.engine.vm.nativelib;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.m2m.atl.engine.vm.StackFrame;
/**
* ASMTransientLinkSet represents a set of traceability links.
*
* @author <a href="mailto:[email protected]">Frederic Jouault</a>
*/
public class ASMTransientLinkSet extends ASMOclAny {
public static ASMOclType myType = new ASMOclSimpleType("TransientLinkSet", getOclAnyType());
public ASMTransientLinkSet() {
super(myType);
}
public String toString() {
StringBuffer ret = new StringBuffer("TransientLinkSet {");
for (Iterator i = linksBySourceElement.values().iterator(); i.hasNext();) {
ret.append(i.next());
if (i.hasNext()) {
ret.append(", ");
}
}
ret.append("}");
return ret.toString();
}
// Native Operations below
public static void addLink(StackFrame frame, ASMTransientLinkSet self, ASMTransientLink link) {
addLink2(frame, self, link, new ASMBoolean(true));
}
public static void addLink2(StackFrame frame, ASMTransientLinkSet self, ASMTransientLink link,
ASMBoolean isDefault) {
ASMOclAny rule = ASMTransientLink.getRule(frame, link);
ASMSequence s = (ASMSequence)self.linksByRule.get(rule);
if (s == null) {
s = new ASMSequence();
self.linksByRule.put(rule, s);
}
s.add(link);
Map linksBySourceElements2 = (Map)self.linksBySourceElementByRule.get(rule);
if (linksBySourceElements2 == null) {
linksBySourceElements2 = new HashMap();
self.linksBySourceElementByRule.put(rule, linksBySourceElements2);
}
for (Iterator i = link.getSourceElements().iterator(); i.hasNext();) {
Object e = i.next();
linksBySourceElements2.put(e, link);
}
if (isDefault.getSymbol()) {
Object se;
if (link.getSourceElements().size() == 1) {
se = link.getSourceElements().iterator().next();
} else {
se = new ASMTuple();
for (Iterator i = link.getSourceMap().keySet().iterator(); i.hasNext();) {
String k = (String)i.next();
((ASMTuple)se).set(frame, k, (ASMOclAny)link.getSourceMap().get(k));
}
}
ASMTransientLink other = (ASMTransientLink)self.linksBySourceElement.get(se);
if (other != null) {
- frame.printStackTrace("trying to register several rules as default for element " + se + ": "
+ frame.printStackTrace("Trying to register several rules as default for element " + se + ": "
+ ASMTransientLink.getRule(frame, other) + " and " + rule);
}
self.linksBySourceElement.put(se, link);
}
for (Iterator i = link.getTargetElements().iterator(); i.hasNext();) {
Object o = i.next();
if (o instanceof ASMCollection) {
for (Iterator j = ((ASMCollection)o).iterator(); j.hasNext();) {
self.linksByTargetElement.put(j.next(), link);
}
} else {
self.linksByTargetElement.put(o, link);
}
}
}
public static ASMSequence getLinksByRule(StackFrame frame, ASMTransientLinkSet self, ASMOclAny rule) {
ASMSequence ret = (ASMSequence)self.linksByRule.get(rule);
if (ret == null) {
ret = new ASMSequence();
}
return ret;
}
public static ASMOclAny getLinkBySourceElement(StackFrame frame, ASMTransientLinkSet self,
ASMOclAny sourceElement) {
ASMOclAny ret = (ASMOclAny)self.linksBySourceElement.get(sourceElement);
if (ret == null) {
ret = new ASMOclUndefined();
}
return ret;
}
public static ASMOclAny getLinkByRuleAndSourceElement(StackFrame frame, ASMTransientLinkSet self,
ASMOclAny rule, ASMOclAny sourceElement) {
Map map = (Map)self.linksBySourceElementByRule.get(rule);
ASMOclAny ret = null;
if (map != null) {
ret = (ASMOclAny)map.get(sourceElement);
}
if (ret == null) {
ret = new ASMOclUndefined();
}
return ret;
}
public static ASMOclAny getLinkByTargetElement(StackFrame frame, ASMTransientLinkSet self,
ASMOclAny targetElement) {
ASMOclAny ret = (ASMOclAny)self.linksByTargetElement.get(targetElement);
if (ret == null) {
ret = new ASMOclUndefined();
}
return ret;
}
private Map linksByRule = new HashMap();
private Map linksBySourceElementByRule = new HashMap();
private Map linksBySourceElement = new HashMap();
private Map linksByTargetElement = new HashMap();
}
| true | true | public static void addLink2(StackFrame frame, ASMTransientLinkSet self, ASMTransientLink link,
ASMBoolean isDefault) {
ASMOclAny rule = ASMTransientLink.getRule(frame, link);
ASMSequence s = (ASMSequence)self.linksByRule.get(rule);
if (s == null) {
s = new ASMSequence();
self.linksByRule.put(rule, s);
}
s.add(link);
Map linksBySourceElements2 = (Map)self.linksBySourceElementByRule.get(rule);
if (linksBySourceElements2 == null) {
linksBySourceElements2 = new HashMap();
self.linksBySourceElementByRule.put(rule, linksBySourceElements2);
}
for (Iterator i = link.getSourceElements().iterator(); i.hasNext();) {
Object e = i.next();
linksBySourceElements2.put(e, link);
}
if (isDefault.getSymbol()) {
Object se;
if (link.getSourceElements().size() == 1) {
se = link.getSourceElements().iterator().next();
} else {
se = new ASMTuple();
for (Iterator i = link.getSourceMap().keySet().iterator(); i.hasNext();) {
String k = (String)i.next();
((ASMTuple)se).set(frame, k, (ASMOclAny)link.getSourceMap().get(k));
}
}
ASMTransientLink other = (ASMTransientLink)self.linksBySourceElement.get(se);
if (other != null) {
frame.printStackTrace("trying to register several rules as default for element " + se + ": "
+ ASMTransientLink.getRule(frame, other) + " and " + rule);
}
self.linksBySourceElement.put(se, link);
}
for (Iterator i = link.getTargetElements().iterator(); i.hasNext();) {
Object o = i.next();
if (o instanceof ASMCollection) {
for (Iterator j = ((ASMCollection)o).iterator(); j.hasNext();) {
self.linksByTargetElement.put(j.next(), link);
}
} else {
self.linksByTargetElement.put(o, link);
}
}
}
| public static void addLink2(StackFrame frame, ASMTransientLinkSet self, ASMTransientLink link,
ASMBoolean isDefault) {
ASMOclAny rule = ASMTransientLink.getRule(frame, link);
ASMSequence s = (ASMSequence)self.linksByRule.get(rule);
if (s == null) {
s = new ASMSequence();
self.linksByRule.put(rule, s);
}
s.add(link);
Map linksBySourceElements2 = (Map)self.linksBySourceElementByRule.get(rule);
if (linksBySourceElements2 == null) {
linksBySourceElements2 = new HashMap();
self.linksBySourceElementByRule.put(rule, linksBySourceElements2);
}
for (Iterator i = link.getSourceElements().iterator(); i.hasNext();) {
Object e = i.next();
linksBySourceElements2.put(e, link);
}
if (isDefault.getSymbol()) {
Object se;
if (link.getSourceElements().size() == 1) {
se = link.getSourceElements().iterator().next();
} else {
se = new ASMTuple();
for (Iterator i = link.getSourceMap().keySet().iterator(); i.hasNext();) {
String k = (String)i.next();
((ASMTuple)se).set(frame, k, (ASMOclAny)link.getSourceMap().get(k));
}
}
ASMTransientLink other = (ASMTransientLink)self.linksBySourceElement.get(se);
if (other != null) {
frame.printStackTrace("Trying to register several rules as default for element " + se + ": "
+ ASMTransientLink.getRule(frame, other) + " and " + rule);
}
self.linksBySourceElement.put(se, link);
}
for (Iterator i = link.getTargetElements().iterator(); i.hasNext();) {
Object o = i.next();
if (o instanceof ASMCollection) {
for (Iterator j = ((ASMCollection)o).iterator(); j.hasNext();) {
self.linksByTargetElement.put(j.next(), link);
}
} else {
self.linksByTargetElement.put(o, link);
}
}
}
|
diff --git a/src/main/java/com/norcode/bukkit/livestocklock/EntityListener.java b/src/main/java/com/norcode/bukkit/livestocklock/EntityListener.java
index ac8c2bb..36599d3 100644
--- a/src/main/java/com/norcode/bukkit/livestocklock/EntityListener.java
+++ b/src/main/java/com/norcode/bukkit/livestocklock/EntityListener.java
@@ -1,176 +1,182 @@
package com.norcode.bukkit.livestocklock;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.*;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityTameEvent;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import java.util.List;
import java.util.UUID;
public class EntityListener implements Listener {
LivestockLock plugin;
public EntityListener(LivestockLock plugin) {
this.plugin = plugin;
}
public void checkExpiry(Entity e) {
OwnedAnimal oa = plugin.getOwnedAnimal(e.getUniqueId());
if (oa == null) return;
if (plugin.getExpiryTime() > 0 && System.currentTimeMillis() - oa.getOwnerActivityTime() > plugin.getExpiryTime()) {
plugin.removeOwnedAnimal(oa);
if (plugin.isDespawnExpiredClaims()) {
e.remove();
}
}
}
@EventHandler
public void onEntityTarget(EntityTargetEvent event) {
checkExpiry(event.getEntity());
}
@EventHandler(ignoreCancelled=true)
public void onEntityDeath(EntityDeathEvent event) {
OwnedAnimal oa = plugin.getOwnedAnimal(event.getEntity().getUniqueId());
if (oa != null) {
plugin.removeOwnedAnimal(oa);
}
}
@EventHandler(ignoreCancelled=true)
public void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
checkExpiry(event.getEntity());
OwnedAnimal oa = plugin.getOwnedAnimal(event.getEntity().getUniqueId());
if (oa == null) return;
Player damager = null;
if (event.getDamager().getType() == EntityType.PLAYER) {
damager = (Player) event.getDamager();
} else if (event.getEntity() instanceof Projectile) {
Projectile p = (Projectile) event.getDamager();
if (p.getShooter() instanceof Player) {
damager = (Player) p.getShooter();
}
}
if (damager != null && !oa.allowAccess(damager.getName())) {
event.setCancelled(true);
damager.sendMessage("That animal belongs to " + oa.getOwnerName());
return;
}
}
@EventHandler(ignoreCancelled=true)
public void onEntityTamed(EntityTameEvent event) {
if (!plugin.getOwnedAnimals().containsKey(event.getEntity().getUniqueId())) {
if (plugin.getClaimableAnimals().containsKey(event.getEntityType().getTypeId())) {
if (plugin.getConfig().getBoolean("auto-claim-on-tame", true)) {
Player owner = plugin.getServer().getPlayerExact(event.getOwner().getName());
List<UUID> alreadyOwned = plugin.getOwnedAnimalIDs(owner.getName());
if (alreadyOwned.size() >= plugin.getPlayerClaimLimit(owner)) {
owner.sendMessage("You aren't allowed to own any more animals.");
return;
}
ClaimableAnimal ca = plugin.getClaimableAnimals().get(event.getEntity().getType().getTypeId());
event.setCancelled(true);
if (ca.takeCost(owner)) {
OwnedAnimal oa = new OwnedAnimal(plugin, event.getEntity().getUniqueId(), owner.getName());
oa.setEntityType(event.getEntity().getType());
plugin.saveOwnedAnimal(oa);
owner.sendMessage("This " + oa.getEntityType().name() + " now belongs to you.");
} else {
owner.sendMessage("Sorry, you don't have " + ca.getCostDescription());
}
}
}
}
}
@EventHandler(ignoreCancelled=true)
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
+ plugin.debug("Interact Event!");
checkExpiry(event.getRightClicked());
Player player = event.getPlayer();
Entity animal = event.getRightClicked();
if (plugin.getOwnedAnimals().containsKey(animal.getUniqueId())) {
+ plugin.debug("Clicked animal is already owned?");
// This animal is owned, check for permission.
OwnedAnimal oa = plugin.getOwnedAnimal(animal.getUniqueId());
if (player.hasMetadata("livestocklock-abandon-pending")) {
player.removeMetadata("livestocklock-abandon-pending", plugin);
if (oa.getOwnerName().equals(player.getName()) || player.hasPermission("livestocklock.claimforothers")) {
player.sendMessage("This animal has been abandoned.");
plugin.removeOwnedAnimal(oa);
return;
} else {
player.sendMessage("This animal doesn't belong to you!");
return;
}
} else if (!oa.allowAccess(player.getName())) {
player.sendMessage("Sorry, that animal belongs to " + oa.getOwnerName());
Player owner = plugin.getServer().getPlayerExact(oa.getOwnerName());
if (owner != null && owner.isOnline()) {
owner.sendMessage(player.getName() + " is trying to use your animal at " + formatLoc(player.getLocation()));
}
event.setCancelled(true);
return;
}
oa.setOwnerActivityTime(System.currentTimeMillis());
plugin.saveOwnedAnimal(oa);
} else if (player.hasMetadata("livestocklock-claim-pending") ||
- (plugin.getConfig().getBoolean("auto-claim-on-lead", true) && event.getPlayer().getItemInHand().equals(Material.LEASH))) {
+ (plugin.getConfig().getBoolean("auto-claim-on-lead", true) &&
+ event.getPlayer().getItemInHand().getType().equals(Material.LEASH))) {
+ plugin.debug("Potential Claim Attempt.");
String ownerName = player.getName();
if (player.hasMetadata("livestocklock-claim-pending")) {
ownerName = player.getMetadata("livestocklock-claim-pending").get(0).asString();
player.removeMetadata("livestocklock-claim-pending", plugin);
}
if (plugin.getClaimableAnimals().containsKey(animal.getType().getTypeId())) {
if (player.hasPermission("livestocklock.claim." + animal.getType().getTypeId())) {
if (animal instanceof Tameable && !((Tameable) animal).isTamed()) {
if (plugin.getConfig().getBoolean("require-taming", true)) {
player.sendMessage("You can't claim a wild animal.");
event.setCancelled(true);
return;
}
} else if ((animal instanceof Ageable) && !((Ageable) animal).isAdult()) {
if (plugin.getConfig().getBoolean("require-adulthood", true)) {
player.sendMessage("You can't claim a baby animal.");
event.setCancelled(true);
return;
}
}
ClaimableAnimal ca = plugin.getClaimableAnimals().get(animal.getType().getTypeId());
if (event.getPlayer().getItemInHand().getType() == Material.LEASH && plugin.getConfig().getBoolean("auto-claim-on-lead", true)) {
// We dont cancel the lead event.\
} else {
event.setCancelled(true);
}
if (ca.takeCost(player)) {
OwnedAnimal oa = new OwnedAnimal(plugin, animal.getUniqueId(), ownerName);
oa.setEntityType(animal.getType());
plugin.saveOwnedAnimal(oa);
player.sendMessage("This " + oa.getEntityType().name() + " now belongs to you.");
} else {
player.sendMessage("Sorry, you don't have " + ca.getCostDescription());
}
}
}
+ } else {
+ plugin.debug(event.getPlayer().getItemInHand() + " in hand, cfg: " + plugin.getConfig().getBoolean("auto-claim-on-lead", true));
}
}
public static String formatLoc(Location l) {
return l.getWorld().getName() + ": " + l.getBlockX() + ", " + l.getBlockY() + ", " + l.getBlockZ();
}
}
| false | true | public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
checkExpiry(event.getRightClicked());
Player player = event.getPlayer();
Entity animal = event.getRightClicked();
if (plugin.getOwnedAnimals().containsKey(animal.getUniqueId())) {
// This animal is owned, check for permission.
OwnedAnimal oa = plugin.getOwnedAnimal(animal.getUniqueId());
if (player.hasMetadata("livestocklock-abandon-pending")) {
player.removeMetadata("livestocklock-abandon-pending", plugin);
if (oa.getOwnerName().equals(player.getName()) || player.hasPermission("livestocklock.claimforothers")) {
player.sendMessage("This animal has been abandoned.");
plugin.removeOwnedAnimal(oa);
return;
} else {
player.sendMessage("This animal doesn't belong to you!");
return;
}
} else if (!oa.allowAccess(player.getName())) {
player.sendMessage("Sorry, that animal belongs to " + oa.getOwnerName());
Player owner = plugin.getServer().getPlayerExact(oa.getOwnerName());
if (owner != null && owner.isOnline()) {
owner.sendMessage(player.getName() + " is trying to use your animal at " + formatLoc(player.getLocation()));
}
event.setCancelled(true);
return;
}
oa.setOwnerActivityTime(System.currentTimeMillis());
plugin.saveOwnedAnimal(oa);
} else if (player.hasMetadata("livestocklock-claim-pending") ||
(plugin.getConfig().getBoolean("auto-claim-on-lead", true) && event.getPlayer().getItemInHand().equals(Material.LEASH))) {
String ownerName = player.getName();
if (player.hasMetadata("livestocklock-claim-pending")) {
ownerName = player.getMetadata("livestocklock-claim-pending").get(0).asString();
player.removeMetadata("livestocklock-claim-pending", plugin);
}
if (plugin.getClaimableAnimals().containsKey(animal.getType().getTypeId())) {
if (player.hasPermission("livestocklock.claim." + animal.getType().getTypeId())) {
if (animal instanceof Tameable && !((Tameable) animal).isTamed()) {
if (plugin.getConfig().getBoolean("require-taming", true)) {
player.sendMessage("You can't claim a wild animal.");
event.setCancelled(true);
return;
}
} else if ((animal instanceof Ageable) && !((Ageable) animal).isAdult()) {
if (plugin.getConfig().getBoolean("require-adulthood", true)) {
player.sendMessage("You can't claim a baby animal.");
event.setCancelled(true);
return;
}
}
ClaimableAnimal ca = plugin.getClaimableAnimals().get(animal.getType().getTypeId());
if (event.getPlayer().getItemInHand().getType() == Material.LEASH && plugin.getConfig().getBoolean("auto-claim-on-lead", true)) {
// We dont cancel the lead event.\
} else {
event.setCancelled(true);
}
if (ca.takeCost(player)) {
OwnedAnimal oa = new OwnedAnimal(plugin, animal.getUniqueId(), ownerName);
oa.setEntityType(animal.getType());
plugin.saveOwnedAnimal(oa);
player.sendMessage("This " + oa.getEntityType().name() + " now belongs to you.");
} else {
player.sendMessage("Sorry, you don't have " + ca.getCostDescription());
}
}
}
}
}
| public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
plugin.debug("Interact Event!");
checkExpiry(event.getRightClicked());
Player player = event.getPlayer();
Entity animal = event.getRightClicked();
if (plugin.getOwnedAnimals().containsKey(animal.getUniqueId())) {
plugin.debug("Clicked animal is already owned?");
// This animal is owned, check for permission.
OwnedAnimal oa = plugin.getOwnedAnimal(animal.getUniqueId());
if (player.hasMetadata("livestocklock-abandon-pending")) {
player.removeMetadata("livestocklock-abandon-pending", plugin);
if (oa.getOwnerName().equals(player.getName()) || player.hasPermission("livestocklock.claimforothers")) {
player.sendMessage("This animal has been abandoned.");
plugin.removeOwnedAnimal(oa);
return;
} else {
player.sendMessage("This animal doesn't belong to you!");
return;
}
} else if (!oa.allowAccess(player.getName())) {
player.sendMessage("Sorry, that animal belongs to " + oa.getOwnerName());
Player owner = plugin.getServer().getPlayerExact(oa.getOwnerName());
if (owner != null && owner.isOnline()) {
owner.sendMessage(player.getName() + " is trying to use your animal at " + formatLoc(player.getLocation()));
}
event.setCancelled(true);
return;
}
oa.setOwnerActivityTime(System.currentTimeMillis());
plugin.saveOwnedAnimal(oa);
} else if (player.hasMetadata("livestocklock-claim-pending") ||
(plugin.getConfig().getBoolean("auto-claim-on-lead", true) &&
event.getPlayer().getItemInHand().getType().equals(Material.LEASH))) {
plugin.debug("Potential Claim Attempt.");
String ownerName = player.getName();
if (player.hasMetadata("livestocklock-claim-pending")) {
ownerName = player.getMetadata("livestocklock-claim-pending").get(0).asString();
player.removeMetadata("livestocklock-claim-pending", plugin);
}
if (plugin.getClaimableAnimals().containsKey(animal.getType().getTypeId())) {
if (player.hasPermission("livestocklock.claim." + animal.getType().getTypeId())) {
if (animal instanceof Tameable && !((Tameable) animal).isTamed()) {
if (plugin.getConfig().getBoolean("require-taming", true)) {
player.sendMessage("You can't claim a wild animal.");
event.setCancelled(true);
return;
}
} else if ((animal instanceof Ageable) && !((Ageable) animal).isAdult()) {
if (plugin.getConfig().getBoolean("require-adulthood", true)) {
player.sendMessage("You can't claim a baby animal.");
event.setCancelled(true);
return;
}
}
ClaimableAnimal ca = plugin.getClaimableAnimals().get(animal.getType().getTypeId());
if (event.getPlayer().getItemInHand().getType() == Material.LEASH && plugin.getConfig().getBoolean("auto-claim-on-lead", true)) {
// We dont cancel the lead event.\
} else {
event.setCancelled(true);
}
if (ca.takeCost(player)) {
OwnedAnimal oa = new OwnedAnimal(plugin, animal.getUniqueId(), ownerName);
oa.setEntityType(animal.getType());
plugin.saveOwnedAnimal(oa);
player.sendMessage("This " + oa.getEntityType().name() + " now belongs to you.");
} else {
player.sendMessage("Sorry, you don't have " + ca.getCostDescription());
}
}
}
} else {
plugin.debug(event.getPlayer().getItemInHand() + " in hand, cfg: " + plugin.getConfig().getBoolean("auto-claim-on-lead", true));
}
}
|
diff --git a/src/Lihad/Conflict/Util/BeyondUtil.java b/src/Lihad/Conflict/Util/BeyondUtil.java
index 237ee18..461da35 100644
--- a/src/Lihad/Conflict/Util/BeyondUtil.java
+++ b/src/Lihad/Conflict/Util/BeyondUtil.java
@@ -1,427 +1,430 @@
package Lihad.Conflict.Util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Chest;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.Inventory;
import org.bukkit.potion.Potion.Tier;
import org.bukkit.potion.PotionType;
import Lihad.Conflict.Conflict;
/**
*
* Utility class, holds static convenience methods
*
* @author Lihad
* @author Joren
*
*/
public class BeyondUtil {
/**
* Compares two locations to see if they share the same block.
*
* @param a - Location to be compared with b
* @param b - Location to be compared with a
* @return true if they share the same block, false if not, false if either Location is null
*/
public static boolean isSameBlock(Location a, Location b)
{
return (a!=null && b!=null && a.getBlock().equals(b.getBlock()));
}
/**
*
* @param chest
* @param material
* @return Returns amount of specified material in specified chest
*/
public static int getChestAmount(Chest chest, Material material){
int amount = 0;
for(int i=0; i<chest.getInventory().getSize(); i++){
if(chest.getInventory().getItem(i) == null) continue;
if(chest.getInventory().getItem(i).getType() == material){
amount = amount+chest.getInventory().getItem(i).getAmount();
}
}
return amount;
}
/**
*
* Checks to see if a location is next to another block. z,x ONLY
*/
public static boolean isNextTo(Location reference, Location variable){
variable.setX(variable.getBlockX()+1);
if(reference.equals(variable)){
return true;
}
variable.setX(variable.getBlockX()-2);
if(reference.equals(variable)){
return true;
}
variable.setX(variable.getBlockX()+1);
variable.setZ(variable.getBlockZ()+1);
if(reference.equals(variable)){
return true;
}
variable.setZ(variable.getBlockZ()-2);
if(reference.equals(variable)){
return true;
}
return false;
}
public static int rarity(ItemStack stack){
int levelvalue = 0;
int itemvalue = 0;
if(stack.getEnchantments().keySet() != null){
for(int i=0;i<stack.getEnchantments().keySet().size();i++){
levelvalue = levelvalue + stack.getEnchantmentLevel((Enchantment)stack.getEnchantments().keySet().toArray()[i]);
}
}
if(stack.getType() == Material.LEATHER_BOOTS
|| stack.getType() == Material.LEATHER_CHESTPLATE
|| stack.getType() == Material.LEATHER_HELMET
|| stack.getType() == Material.LEATHER_LEGGINGS
|| stack.getType() == Material.WOOD_AXE
|| stack.getType() == Material.WOOD_SPADE
|| stack.getType() == Material.WOOD_PICKAXE
|| stack.getType() == Material.WOOD_SWORD)
itemvalue = 60;
else if(stack.getType() == Material.STONE_PICKAXE
|| stack.getType() == Material.STONE_SPADE
|| stack.getType() == Material.STONE_AXE
|| stack.getType() == Material.STONE_SWORD)
itemvalue = 80;
else if(stack.getType() == Material.GOLD_BOOTS
|| stack.getType() == Material.GOLD_CHESTPLATE
|| stack.getType() == Material.GOLD_HELMET
|| stack.getType() == Material.GOLD_LEGGINGS
|| stack.getType() == Material.GOLD_AXE
|| stack.getType() == Material.GOLD_SPADE
|| stack.getType() == Material.GOLD_PICKAXE
|| stack.getType() == Material.GOLD_SWORD)
itemvalue = 100;
else if(stack.getType() == Material.IRON_BOOTS
|| stack.getType() == Material.IRON_CHESTPLATE
|| stack.getType() == Material.IRON_HELMET
|| stack.getType() == Material.IRON_LEGGINGS
|| stack.getType() == Material.IRON_AXE
|| stack.getType() == Material.IRON_SPADE
|| stack.getType() == Material.IRON_PICKAXE
|| stack.getType() == Material.IRON_SWORD)
itemvalue = 120;
else if(stack.getType() == Material.DIAMOND_BOOTS
|| stack.getType() == Material.BOW
|| stack.getType() == Material.DIAMOND_CHESTPLATE
|| stack.getType() == Material.DIAMOND_HELMET
|| stack.getType() == Material.DIAMOND_LEGGINGS
|| stack.getType() == Material.DIAMOND_AXE
|| stack.getType() == Material.DIAMOND_SPADE
|| stack.getType() == Material.DIAMOND_PICKAXE
|| stack.getType() == Material.DIAMOND_SWORD)
itemvalue = 140;
return (levelvalue+itemvalue);
}
public static String getColorOfRarity(double index){
if(index >= 180)return ChatColor.DARK_RED.toString();
else if(index >= 160)return ChatColor.RED.toString();
else if(index >= 140)return ChatColor.LIGHT_PURPLE.toString();
else if(index >= 120)return ChatColor.BLUE.toString();
else if(index >= 100)return ChatColor.GREEN.toString();
else if(index >= 80)return ChatColor.YELLOW.toString();
else return ChatColor.GRAY.toString();
}
public static String getColorOfTotalRarity(int index){
if(index >= 1000)return ChatColor.DARK_RED.toString();
else if(index >= 800)return ChatColor.RED.toString();
else if(index >= 700)return ChatColor.LIGHT_PURPLE.toString();
else if(index >= 600)return ChatColor.BLUE.toString();
else if(index >= 500)return ChatColor.GREEN.toString();
else if(index >= 400)return ChatColor.YELLOW.toString();
else return ChatColor.GRAY.toString();
}
public static String getColorOfLevel(int index){
if(index >= 12)return ChatColor.DARK_RED.toString();
else if(index >= 10)return ChatColor.RED.toString();
else if(index >= 8)return ChatColor.LIGHT_PURPLE.toString();
else if(index >= 6)return ChatColor.BLUE.toString();
else if(index >= 4)return ChatColor.GREEN.toString();
else if(index >= 2)return ChatColor.YELLOW.toString();
else return ChatColor.GRAY.toString();
}
//
//
// Helper Functions
//
//
public static boolean isDiamondItem(ItemStack item) {
switch(item.getType()) {
case DIAMOND_SWORD:
case DIAMOND_HELMET:
case DIAMOND_CHESTPLATE:
case DIAMOND_LEGGINGS:
case DIAMOND_BOOTS:
case DIAMOND_AXE:
case DIAMOND_PICKAXE:
case DIAMOND_SPADE:
case DIAMOND_HOE:
return true;
default:
return false;
}
}
static int enchantLevelRandomizer(Enchantment e) {
double p = Conflict.random.nextDouble();
// square power distribution - Bunches up probabilities toward the bottom
p = p * p;
int level = (int)(((double)maxEnchantLevel(e)) * p) + 1;
return level;
}
public static int maxEnchantLevel(Enchantment e) {
if (e.equals(Enchantment.DURABILITY)) { return 10; }
if (e.equals(Enchantment.DIG_SPEED)) { return 10; }
return e.getMaxLevel();
}
public static ItemStack addRandomEnchant(ItemStack item) {
if (item.getAmount() != 1) {
// Can't operate on stacks
return null;
}
Enchantment e = null;
e = enchantRandomizer(item);
int level = enchantLevelRandomizer(e);
item.addUnsafeEnchantment(e, level);
return item;
}
public static int calculator(Player player){
int next = Conflict.random.nextInt(1000);
int playerlevel = player.getLevel()/10;
if(playerlevel > 10)playerlevel = 10;
return (next - (playerlevel*3));
}
public static PotionType potionTypeRandomizer(){
int next = Conflict.random.nextInt(9);
switch(next){
case 0: return PotionType.SPEED;
case 1: return PotionType.SLOWNESS;
case 2: return PotionType.FIRE_RESISTANCE;
case 3: return PotionType.REGEN;
case 4: return PotionType.INSTANT_DAMAGE;
case 5: return PotionType.INSTANT_HEAL;
case 6: return PotionType.POISON;
case 7: return PotionType.WEAKNESS;
case 8: return PotionType.STRENGTH;
}
return PotionType.SPEED;
}
public static Tier potionTierRandomizer(){
int next = Conflict.random.nextInt(3);
if(next < 2){
return Tier.ONE;
}else return Tier.TWO;
}
public static boolean potionSplashRandomizer(){
int next = Conflict.random.nextInt(2);
if(next == 0)return true;
else return false;
}
public static Material weaponTypeRandomizer(){
int next = Conflict.random.nextInt(100);
if(next<10)return Material.DIAMOND_SWORD;
else if(next<25)return Material.IRON_SWORD;
else if(next<40)return Material.GOLD_SWORD;
else if(next<60)return Material.STONE_SWORD;
else return Material.WOOD_SWORD;
}
public static Material armorTypeRandomizer(){
int next = Conflict.random.nextInt(100);
if(next<2)return Material.DIAMOND_CHESTPLATE;
else if(next<5)return Material.DIAMOND_BOOTS;
else if(next<7)return Material.DIAMOND_HELMET;
else if(next<10)return Material.DIAMOND_LEGGINGS;
else if(next<13)return Material.IRON_CHESTPLATE;
else if(next<17)return Material.IRON_BOOTS;
else if(next<21)return Material.IRON_HELMET;
else if(next<25)return Material.IRON_LEGGINGS;
else if(next<29)return Material.GOLD_CHESTPLATE;
else if(next<36)return Material.GOLD_BOOTS;
else if(next<43)return Material.GOLD_HELMET;
else if(next<50)return Material.GOLD_LEGGINGS;
else if(next<60)return Material.LEATHER_CHESTPLATE;
else if(next<73)return Material.LEATHER_BOOTS;
else if(next<86)return Material.LEATHER_HELMET;
else return Material.LEATHER_LEGGINGS;
}
public static Material toolTypeRandomizer(){
int next = Conflict.random.nextInt(100);
if(next<4)return Material.DIAMOND_AXE;
else if(next<7)return Material.DIAMOND_PICKAXE;
else if(next<10)return Material.DIAMOND_SPADE;
else if(next<15)return Material.IRON_AXE;
else if(next<20)return Material.IRON_PICKAXE;
else if(next<25)return Material.IRON_SPADE;
else if(next<29)return Material.GOLD_AXE;
else if(next<33)return Material.GOLD_PICKAXE;
else if(next<37)return Material.GOLD_SPADE;
else if(next<41)return Material.STONE_AXE;
else if(next<45)return Material.STONE_PICKAXE;
else if(next<50)return Material.STONE_SPADE;
else if(next<60)return Material.WOOD_PICKAXE;
else if(next<85)return Material.WOOD_AXE;
else return Material.WOOD_SPADE;
}
public static Enchantment enchantRandomizer(ItemStack item){
final Enchantment[] weaponEnchants = new Enchantment[] {
Enchantment.LOOT_BONUS_MOBS,
Enchantment.KNOCKBACK,
Enchantment.FIRE_ASPECT,
Enchantment.DAMAGE_UNDEAD,
Enchantment.DAMAGE_ARTHROPODS,
Enchantment.DAMAGE_ALL
};
final Enchantment[] armorEnchants = new Enchantment[] {
Enchantment.PROTECTION_FIRE,
Enchantment.PROTECTION_PROJECTILE,
Enchantment.PROTECTION_ENVIRONMENTAL,
Enchantment.PROTECTION_EXPLOSIONS
};
final Enchantment[] bowEnchants = new Enchantment[] {
Enchantment.ARROW_DAMAGE,
Enchantment.ARROW_FIRE,
Enchantment.ARROW_INFINITE,
Enchantment.ARROW_KNOCKBACK,
Enchantment.LOOT_BONUS_MOBS
};
final Enchantment[] toolEnchants = new Enchantment[] {
Enchantment.DURABILITY,
Enchantment.LOOT_BONUS_BLOCKS,
Enchantment.DIG_SPEED
};
ArrayList<Enchantment> possible = new ArrayList<Enchantment>();
switch(item.getType()) {
case DIAMOND_SWORD:
case IRON_SWORD:
case STONE_SWORD:
case WOOD_SWORD:
possible.addAll(Arrays.asList(weaponEnchants));
+ break;
case DIAMOND_HELMET:
case DIAMOND_CHESTPLATE:
case DIAMOND_LEGGINGS:
case DIAMOND_BOOTS:
case GOLD_HELMET:
case GOLD_CHESTPLATE:
case GOLD_LEGGINGS:
case GOLD_BOOTS:
case IRON_HELMET:
case IRON_CHESTPLATE:
case IRON_LEGGINGS:
case IRON_BOOTS:
case LEATHER_HELMET:
case LEATHER_CHESTPLATE:
case LEATHER_LEGGINGS:
case LEATHER_BOOTS:
possible.addAll(Arrays.asList(armorEnchants));
+ break;
+ case DIAMOND_AXE:
+ case GOLD_AXE:
+ case IRON_AXE:
+ case WOOD_AXE:
+ // Axes are usually tools, but might be weapons.
+ possible.addAll(Arrays.asList(toolEnchants));
+ possible.addAll(Arrays.asList(toolEnchants));
+ possible.addAll(Arrays.asList(toolEnchants));
+ possible.addAll(Arrays.asList(weaponEnchants));
case DIAMOND_PICKAXE:
case DIAMOND_SPADE:
case DIAMOND_HOE:
case GOLD_PICKAXE:
case GOLD_SPADE:
case GOLD_HOE:
case IRON_PICKAXE:
case IRON_SPADE:
case IRON_HOE:
case WOOD_PICKAXE:
case WOOD_SPADE:
case WOOD_HOE:
possible.addAll(Arrays.asList(toolEnchants));
- case DIAMOND_AXE:
- case GOLD_AXE:
- case IRON_AXE:
- case WOOD_AXE:
- // Axes are usually tools, but might be weapons.
- possible.addAll(Arrays.asList(toolEnchants));
- possible.addAll(Arrays.asList(toolEnchants));
- possible.addAll(Arrays.asList(toolEnchants));
- possible.addAll(Arrays.asList(toolEnchants));
- possible.addAll(Arrays.asList(weaponEnchants));
+ break;
case BOW:
possible.addAll(Arrays.asList(bowEnchants));
+ break;
default:
// Shouldn't get here. Throw sharpness on it.
possible.add(Enchantment.DAMAGE_ALL);
}
int chosen = Conflict.random.nextInt(possible.size());
return possible.get(chosen);
}
public static void nerfOverenchantedPlayerInventory(Player player) {
for (ItemStack i : player.getInventory().getContents()) {
if (i != null) nerfOverenchantedItem(i);
}
for (ItemStack i : player.getInventory().getArmorContents()) {
if (i != null) nerfOverenchantedItem(i);
}
}
public static void nerfOverenchantedInventory(Inventory inv) {
for (ItemStack i : inv.getContents()) {
if (i != null) nerfOverenchantedItem(i);
}
}
public static void nerfOverenchantedItem(ItemStack i) {
if (i != null) {
Map<Enchantment, Integer> enchantments = i.getEnchantments();
if (enchantments != null) {
for (Map.Entry entry : enchantments.entrySet()) {
Enchantment e = (Enchantment)entry.getKey();
int level = (Integer)entry.getValue();
int max = BeyondUtil.maxEnchantLevel(e);
if (level > max) {
i.addUnsafeEnchantment(e, max);
}
}
}
}
}
}
| false | true | public static Enchantment enchantRandomizer(ItemStack item){
final Enchantment[] weaponEnchants = new Enchantment[] {
Enchantment.LOOT_BONUS_MOBS,
Enchantment.KNOCKBACK,
Enchantment.FIRE_ASPECT,
Enchantment.DAMAGE_UNDEAD,
Enchantment.DAMAGE_ARTHROPODS,
Enchantment.DAMAGE_ALL
};
final Enchantment[] armorEnchants = new Enchantment[] {
Enchantment.PROTECTION_FIRE,
Enchantment.PROTECTION_PROJECTILE,
Enchantment.PROTECTION_ENVIRONMENTAL,
Enchantment.PROTECTION_EXPLOSIONS
};
final Enchantment[] bowEnchants = new Enchantment[] {
Enchantment.ARROW_DAMAGE,
Enchantment.ARROW_FIRE,
Enchantment.ARROW_INFINITE,
Enchantment.ARROW_KNOCKBACK,
Enchantment.LOOT_BONUS_MOBS
};
final Enchantment[] toolEnchants = new Enchantment[] {
Enchantment.DURABILITY,
Enchantment.LOOT_BONUS_BLOCKS,
Enchantment.DIG_SPEED
};
ArrayList<Enchantment> possible = new ArrayList<Enchantment>();
switch(item.getType()) {
case DIAMOND_SWORD:
case IRON_SWORD:
case STONE_SWORD:
case WOOD_SWORD:
possible.addAll(Arrays.asList(weaponEnchants));
case DIAMOND_HELMET:
case DIAMOND_CHESTPLATE:
case DIAMOND_LEGGINGS:
case DIAMOND_BOOTS:
case GOLD_HELMET:
case GOLD_CHESTPLATE:
case GOLD_LEGGINGS:
case GOLD_BOOTS:
case IRON_HELMET:
case IRON_CHESTPLATE:
case IRON_LEGGINGS:
case IRON_BOOTS:
case LEATHER_HELMET:
case LEATHER_CHESTPLATE:
case LEATHER_LEGGINGS:
case LEATHER_BOOTS:
possible.addAll(Arrays.asList(armorEnchants));
case DIAMOND_PICKAXE:
case DIAMOND_SPADE:
case DIAMOND_HOE:
case GOLD_PICKAXE:
case GOLD_SPADE:
case GOLD_HOE:
case IRON_PICKAXE:
case IRON_SPADE:
case IRON_HOE:
case WOOD_PICKAXE:
case WOOD_SPADE:
case WOOD_HOE:
possible.addAll(Arrays.asList(toolEnchants));
case DIAMOND_AXE:
case GOLD_AXE:
case IRON_AXE:
case WOOD_AXE:
// Axes are usually tools, but might be weapons.
possible.addAll(Arrays.asList(toolEnchants));
possible.addAll(Arrays.asList(toolEnchants));
possible.addAll(Arrays.asList(toolEnchants));
possible.addAll(Arrays.asList(toolEnchants));
possible.addAll(Arrays.asList(weaponEnchants));
case BOW:
possible.addAll(Arrays.asList(bowEnchants));
default:
// Shouldn't get here. Throw sharpness on it.
possible.add(Enchantment.DAMAGE_ALL);
}
int chosen = Conflict.random.nextInt(possible.size());
return possible.get(chosen);
}
| public static Enchantment enchantRandomizer(ItemStack item){
final Enchantment[] weaponEnchants = new Enchantment[] {
Enchantment.LOOT_BONUS_MOBS,
Enchantment.KNOCKBACK,
Enchantment.FIRE_ASPECT,
Enchantment.DAMAGE_UNDEAD,
Enchantment.DAMAGE_ARTHROPODS,
Enchantment.DAMAGE_ALL
};
final Enchantment[] armorEnchants = new Enchantment[] {
Enchantment.PROTECTION_FIRE,
Enchantment.PROTECTION_PROJECTILE,
Enchantment.PROTECTION_ENVIRONMENTAL,
Enchantment.PROTECTION_EXPLOSIONS
};
final Enchantment[] bowEnchants = new Enchantment[] {
Enchantment.ARROW_DAMAGE,
Enchantment.ARROW_FIRE,
Enchantment.ARROW_INFINITE,
Enchantment.ARROW_KNOCKBACK,
Enchantment.LOOT_BONUS_MOBS
};
final Enchantment[] toolEnchants = new Enchantment[] {
Enchantment.DURABILITY,
Enchantment.LOOT_BONUS_BLOCKS,
Enchantment.DIG_SPEED
};
ArrayList<Enchantment> possible = new ArrayList<Enchantment>();
switch(item.getType()) {
case DIAMOND_SWORD:
case IRON_SWORD:
case STONE_SWORD:
case WOOD_SWORD:
possible.addAll(Arrays.asList(weaponEnchants));
break;
case DIAMOND_HELMET:
case DIAMOND_CHESTPLATE:
case DIAMOND_LEGGINGS:
case DIAMOND_BOOTS:
case GOLD_HELMET:
case GOLD_CHESTPLATE:
case GOLD_LEGGINGS:
case GOLD_BOOTS:
case IRON_HELMET:
case IRON_CHESTPLATE:
case IRON_LEGGINGS:
case IRON_BOOTS:
case LEATHER_HELMET:
case LEATHER_CHESTPLATE:
case LEATHER_LEGGINGS:
case LEATHER_BOOTS:
possible.addAll(Arrays.asList(armorEnchants));
break;
case DIAMOND_AXE:
case GOLD_AXE:
case IRON_AXE:
case WOOD_AXE:
// Axes are usually tools, but might be weapons.
possible.addAll(Arrays.asList(toolEnchants));
possible.addAll(Arrays.asList(toolEnchants));
possible.addAll(Arrays.asList(toolEnchants));
possible.addAll(Arrays.asList(weaponEnchants));
case DIAMOND_PICKAXE:
case DIAMOND_SPADE:
case DIAMOND_HOE:
case GOLD_PICKAXE:
case GOLD_SPADE:
case GOLD_HOE:
case IRON_PICKAXE:
case IRON_SPADE:
case IRON_HOE:
case WOOD_PICKAXE:
case WOOD_SPADE:
case WOOD_HOE:
possible.addAll(Arrays.asList(toolEnchants));
break;
case BOW:
possible.addAll(Arrays.asList(bowEnchants));
break;
default:
// Shouldn't get here. Throw sharpness on it.
possible.add(Enchantment.DAMAGE_ALL);
}
int chosen = Conflict.random.nextInt(possible.size());
return possible.get(chosen);
}
|
diff --git a/sonar-batch/src/main/java/org/sonar/batch/local/DryRunDatabase.java b/sonar-batch/src/main/java/org/sonar/batch/local/DryRunDatabase.java
index 8a5bf92857..c2f69706d5 100644
--- a/sonar-batch/src/main/java/org/sonar/batch/local/DryRunDatabase.java
+++ b/sonar-batch/src/main/java/org/sonar/batch/local/DryRunDatabase.java
@@ -1,108 +1,108 @@
/*
* Sonar, open source software quality management tool.
* Copyright (C) 2008-2012 SonarSource
* mailto:contact AT sonarsource DOT com
*
* Sonar is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.batch.local;
import com.google.common.base.Throwables;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.BatchComponent;
import org.sonar.api.batch.bootstrap.ProjectReactor;
import org.sonar.api.config.Settings;
import org.sonar.api.database.DatabaseProperties;
import org.sonar.api.utils.SonarException;
import org.sonar.batch.bootstrap.DryRun;
import org.sonar.batch.bootstrap.ProjectReactorReady;
import org.sonar.batch.bootstrap.ServerClient;
import org.sonar.batch.bootstrap.TempDirectories;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* @since 3.4
*/
public class DryRunDatabase implements BatchComponent {
private static final Logger LOG = LoggerFactory.getLogger(DryRunDatabase.class);
private static final String API_SYNCHRO = "/api/synchro";
private static final String DIALECT = "h2";
private static final String DRIVER = "org.h2.Driver";
private static final String URL = "jdbc:h2:";
private static final String USER = "sonar";
private static final String PASSWORD = "sonar";
private final DryRun dryRun;
private final Settings settings;
private final ServerClient server;
private final TempDirectories tempDirectories;
private final ProjectReactor reactor;
public DryRunDatabase(DryRun dryRun, Settings settings, ServerClient server, TempDirectories tempDirectories, ProjectReactor reactor,
// project reactor must be completely built
ProjectReactorReady reactorReady) {
this.dryRun = dryRun;
this.settings = settings;
this.server = server;
this.tempDirectories = tempDirectories;
this.reactor = reactor;
}
public void start() {
if (!dryRun.isEnabled()) {
return;
}
File databaseFile = tempDirectories.getFile("dry_run", "db.h2.db");
downloadDatabase(reactor.getRoot().getKey(), databaseFile);
String databasePath = StringUtils.removeEnd(databaseFile.getAbsolutePath(), ".h2.db");
replaceSettings(databasePath);
}
private void downloadDatabase(String projectKey, File toFile) {
LOG.info("Downloading DryRun database for project [{}]", projectKey);
try {
server.download(API_SYNCHRO + "?resource=" + projectKey, toFile);
} catch (SonarException e) {
Throwable rootCause = Throwables.getRootCause(e);
if (rootCause instanceof FileNotFoundException) {
- throw new SonarException(String.format("Project [%s] doesn't exist on server", projectKey));
+ throw new SonarException(String.format("Project [%s] doesn't exist on server", projectKey), e);
} else if ((rootCause instanceof IOException) && (StringUtils.contains(rootCause.getMessage(), "401"))) {
- throw new SonarException(String.format("You don't have access rights to project [%s]", projectKey));
+ throw new SonarException(String.format("You don't have access rights to project [%s]", projectKey), e);
}
throw e;
}
}
private void replaceSettings(String databasePath) {
LOG.info("Overriding database settings");
settings
.setProperty("sonar.jdbc.schema", "")
.setProperty(DatabaseProperties.PROP_DIALECT, DIALECT)
.setProperty(DatabaseProperties.PROP_DRIVER, DRIVER)
.setProperty(DatabaseProperties.PROP_USER, USER)
.setProperty(DatabaseProperties.PROP_PASSWORD, PASSWORD)
.setProperty(DatabaseProperties.PROP_URL, URL + databasePath);
}
}
| false | true | private void downloadDatabase(String projectKey, File toFile) {
LOG.info("Downloading DryRun database for project [{}]", projectKey);
try {
server.download(API_SYNCHRO + "?resource=" + projectKey, toFile);
} catch (SonarException e) {
Throwable rootCause = Throwables.getRootCause(e);
if (rootCause instanceof FileNotFoundException) {
throw new SonarException(String.format("Project [%s] doesn't exist on server", projectKey));
} else if ((rootCause instanceof IOException) && (StringUtils.contains(rootCause.getMessage(), "401"))) {
throw new SonarException(String.format("You don't have access rights to project [%s]", projectKey));
}
throw e;
}
}
| private void downloadDatabase(String projectKey, File toFile) {
LOG.info("Downloading DryRun database for project [{}]", projectKey);
try {
server.download(API_SYNCHRO + "?resource=" + projectKey, toFile);
} catch (SonarException e) {
Throwable rootCause = Throwables.getRootCause(e);
if (rootCause instanceof FileNotFoundException) {
throw new SonarException(String.format("Project [%s] doesn't exist on server", projectKey), e);
} else if ((rootCause instanceof IOException) && (StringUtils.contains(rootCause.getMessage(), "401"))) {
throw new SonarException(String.format("You don't have access rights to project [%s]", projectKey), e);
}
throw e;
}
}
|
diff --git a/as/plugins/org.jboss.tools.openshift.express.ui/src/org/jboss/tools/openshift/express/internal/ui/wizard/ApplicationWizardPage.java b/as/plugins/org.jboss.tools.openshift.express.ui/src/org/jboss/tools/openshift/express/internal/ui/wizard/ApplicationWizardPage.java
index a9f4214e0..f30950a51 100644
--- a/as/plugins/org.jboss.tools.openshift.express.ui/src/org/jboss/tools/openshift/express/internal/ui/wizard/ApplicationWizardPage.java
+++ b/as/plugins/org.jboss.tools.openshift.express.ui/src/org/jboss/tools/openshift/express/internal/ui/wizard/ApplicationWizardPage.java
@@ -1,294 +1,294 @@
/*******************************************************************************
* Copyright (c) 2011 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.openshift.express.internal.ui.wizard;
import java.util.Collection;
import org.eclipse.core.databinding.Binding;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.UpdateValueStrategy;
import org.eclipse.core.databinding.beans.BeanProperties;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.databinding.viewers.ViewerProperties;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CellLabelProvider;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.jface.wizard.IWizard;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.ui.PlatformUI;
import org.jboss.tools.common.ui.BrowserUtil;
import org.jboss.tools.common.ui.WizardUtils;
import org.jboss.tools.common.ui.databinding.DataBindingUtils;
import org.jboss.tools.openshift.express.client.IApplication;
import org.jboss.tools.openshift.express.client.OpenshiftException;
import org.jboss.tools.openshift.express.internal.ui.OpenshiftUIActivator;
/**
* @author André Dietisheim
*/
public class ApplicationWizardPage extends AbstractOpenshiftWizardPage {
private TableViewer viewer;
private ApplicationWizardPageModel model;
protected ApplicationWizardPage(IWizard wizard, ServerAdapterWizardModel wizardModel) {
super("Application selection", "Please select an Openshift Express application",
"Application selection", wizard);
this.model = new ApplicationWizardPageModel(wizardModel);
}
@Override
protected void doCreateControls(Composite container, DataBindingContext dbc) {
GridLayoutFactory.fillDefaults().numColumns(3).applyTo(container);
Group group = new Group(container, SWT.BORDER);
group.setText("Available Applications");
GridDataFactory.fillDefaults().grab(true, true).align(SWT.FILL, SWT.FILL).hint(400, 160).span(3, 1)
.applyTo(group);
FillLayout fillLayout = new FillLayout(SWT.VERTICAL);
fillLayout.marginHeight = 6;
fillLayout.marginWidth = 6;
group.setLayout(fillLayout);
Composite tableContainer = new Composite(group, SWT.NONE);
this.viewer = createTable(tableContainer);
viewer.addDoubleClickListener(onApplicationDoubleClick());
Binding selectedApplicationBinding = dbc.bindValue(
ViewerProperties.singleSelection().observe(viewer),
BeanProperties.value(ApplicationWizardPageModel.PROPERTY_SELECTED_APPLICATION).observe(model),
new UpdateValueStrategy().setAfterGetValidator(new IValidator() {
@Override
public IStatus validate(Object value) {
if (value != null) {
return ValidationStatus.ok();
}
else {
return ValidationStatus.info("You have to select an application...");
}
}
}),
null);
Button newButton = new Button(container, SWT.PUSH);
newButton.setText("Ne&w");
GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).hint(80, 30).applyTo(newButton);
newButton.addSelectionListener(onNew(dbc));
Button deleteButton = new Button(container, SWT.PUSH);
deleteButton.setText("&Delete");
GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).hint(80, 30).applyTo(deleteButton);
- DataBindingUtils.bindEnablementToValidationStatus(deleteButton, dbc, selectedApplicationBinding);
+ DataBindingUtils.bindEnablementToValidationStatus(deleteButton, IStatus.INFO, dbc, selectedApplicationBinding);
deleteButton.addSelectionListener(onDelete(dbc));
Button detailsButton = new Button(container, SWT.PUSH);
detailsButton.setText("De&tails");
GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).hint(80, 30).applyTo(detailsButton);
- DataBindingUtils.bindEnablementToValidationStatus(detailsButton, dbc, IStatus.INFO, selectedApplicationBinding);
+ DataBindingUtils.bindEnablementToValidationStatus(detailsButton, IStatus.INFO, dbc , selectedApplicationBinding);
detailsButton.addSelectionListener(onDetails(dbc));
}
private IDoubleClickListener onApplicationDoubleClick() {
return new IDoubleClickListener() {
@Override
public void doubleClick(DoubleClickEvent event) {
try {
ISelection selection = event.getSelection();
if (selection instanceof StructuredSelection) {
Object firstElement = ((IStructuredSelection) selection).getFirstElement();
if (firstElement instanceof IApplication) {
String url = ((IApplication) firstElement).getApplicationUrl();
BrowserUtil.checkedCreateExternalBrowser(url, OpenshiftUIActivator.PLUGIN_ID,
OpenshiftUIActivator.getDefault().getLog());
}
}
} catch (OpenshiftException e) {
IStatus status = new Status(IStatus.ERROR, OpenshiftUIActivator.PLUGIN_ID,
"Could not open Openshift Express application in browser", e);
OpenshiftUIActivator.getDefault().getLog().log(status);
}
}
};
}
protected TableViewer createTable(Composite tableContainer) {
Table table = new Table(tableContainer, SWT.BORDER | SWT.FULL_SELECTION | SWT.V_SCROLL | SWT.H_SCROLL);
GridDataFactory.fillDefaults().grab(true, true).applyTo(table);
table.setLinesVisible(true);
table.setHeaderVisible(true);
TableColumnLayout tableLayout = new TableColumnLayout();
tableContainer.setLayout(tableLayout);
TableViewer viewer = new TableViewer(table);
viewer.setContentProvider(new ArrayContentProvider());
createTableColumn("Name", 1, new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
IApplication application = (IApplication) cell.getElement();
cell.setText(application.getName());
}
}, viewer, tableLayout);
createTableColumn("Type", 1, new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
IApplication application = (IApplication) cell.getElement();
cell.setText(application.getCartridge().getName());
}
}, viewer, tableLayout);
createTableColumn("URL", 3, new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
try {
IApplication application = (IApplication) cell.getElement();
cell.setText(application.getApplicationUrl());
} catch (OpenshiftException e) {
// ignore
}
}
}, viewer, tableLayout);
return viewer;
}
private void createTableColumn(String name, int weight, CellLabelProvider cellLabelProvider, TableViewer viewer,
TableColumnLayout layout) {
TableViewerColumn column = new TableViewerColumn(viewer, SWT.LEFT);
column.getColumn().setText(name);
column.setLabelProvider(cellLabelProvider);
layout.setColumnData(column.getColumn(), new ColumnWeightData(weight, true));
}
private SelectionAdapter onDelete(final DataBindingContext dbc) {
return new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
try {
WizardUtils.runInWizard(new DeleteApplicationJob(), getWizard().getContainer(), dbc);
} catch (Exception ex) {
// ignore
}
}
};
}
private SelectionAdapter onNew(DataBindingContext dbc) {
return new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Shell shell = getContainer().getShell();
if (WizardUtils.openWizardDialog(new NewApplicationDialog(model.getUser()), shell)
== Dialog.OK) {
viewer.refresh();
}
}
};
}
private SelectionAdapter onDetails(DataBindingContext dbc) {
return new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Shell shell = getContainer().getShell();
new ApplicationDetailsDialog(model.getSelectedApplication(), shell).open();
}
};
}
@Override
protected void onPageActivated(DataBindingContext dbc) {
try {
WizardUtils.runInWizard(new LoadApplicationsJob(), getWizard().getContainer(), dbc);
} catch (Exception ex) {
// ignore
}
}
private class LoadApplicationsJob extends Job {
private LoadApplicationsJob() {
super("Loading applications");
}
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
final Collection<IApplication> applications = model.getApplications();
Display display = PlatformUI.getWorkbench().getDisplay();
display.syncExec(new Runnable() {
@Override
public void run() {
viewer.setInput(applications);
}
});
return Status.OK_STATUS;
} catch (OpenshiftException e) {
return new Status(IStatus.ERROR, OpenshiftUIActivator.PLUGIN_ID,
"Could not load applications from Openshift Express");
}
}
}
private class DeleteApplicationJob extends Job {
public DeleteApplicationJob() {
super("Deleteing application");
}
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
model.destroyCurrentApplication();
return Status.OK_STATUS;
} catch (OpenshiftException e) {
return new Status(IStatus.ERROR, OpenshiftUIActivator.PLUGIN_ID, NLS.bind(
"Could not delete application \"{0}\"",
model.getSelectedApplication().getName()));
}
}
}
}
| false | true | protected void doCreateControls(Composite container, DataBindingContext dbc) {
GridLayoutFactory.fillDefaults().numColumns(3).applyTo(container);
Group group = new Group(container, SWT.BORDER);
group.setText("Available Applications");
GridDataFactory.fillDefaults().grab(true, true).align(SWT.FILL, SWT.FILL).hint(400, 160).span(3, 1)
.applyTo(group);
FillLayout fillLayout = new FillLayout(SWT.VERTICAL);
fillLayout.marginHeight = 6;
fillLayout.marginWidth = 6;
group.setLayout(fillLayout);
Composite tableContainer = new Composite(group, SWT.NONE);
this.viewer = createTable(tableContainer);
viewer.addDoubleClickListener(onApplicationDoubleClick());
Binding selectedApplicationBinding = dbc.bindValue(
ViewerProperties.singleSelection().observe(viewer),
BeanProperties.value(ApplicationWizardPageModel.PROPERTY_SELECTED_APPLICATION).observe(model),
new UpdateValueStrategy().setAfterGetValidator(new IValidator() {
@Override
public IStatus validate(Object value) {
if (value != null) {
return ValidationStatus.ok();
}
else {
return ValidationStatus.info("You have to select an application...");
}
}
}),
null);
Button newButton = new Button(container, SWT.PUSH);
newButton.setText("Ne&w");
GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).hint(80, 30).applyTo(newButton);
newButton.addSelectionListener(onNew(dbc));
Button deleteButton = new Button(container, SWT.PUSH);
deleteButton.setText("&Delete");
GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).hint(80, 30).applyTo(deleteButton);
DataBindingUtils.bindEnablementToValidationStatus(deleteButton, dbc, selectedApplicationBinding);
deleteButton.addSelectionListener(onDelete(dbc));
Button detailsButton = new Button(container, SWT.PUSH);
detailsButton.setText("De&tails");
GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).hint(80, 30).applyTo(detailsButton);
DataBindingUtils.bindEnablementToValidationStatus(detailsButton, dbc, IStatus.INFO, selectedApplicationBinding);
detailsButton.addSelectionListener(onDetails(dbc));
}
| protected void doCreateControls(Composite container, DataBindingContext dbc) {
GridLayoutFactory.fillDefaults().numColumns(3).applyTo(container);
Group group = new Group(container, SWT.BORDER);
group.setText("Available Applications");
GridDataFactory.fillDefaults().grab(true, true).align(SWT.FILL, SWT.FILL).hint(400, 160).span(3, 1)
.applyTo(group);
FillLayout fillLayout = new FillLayout(SWT.VERTICAL);
fillLayout.marginHeight = 6;
fillLayout.marginWidth = 6;
group.setLayout(fillLayout);
Composite tableContainer = new Composite(group, SWT.NONE);
this.viewer = createTable(tableContainer);
viewer.addDoubleClickListener(onApplicationDoubleClick());
Binding selectedApplicationBinding = dbc.bindValue(
ViewerProperties.singleSelection().observe(viewer),
BeanProperties.value(ApplicationWizardPageModel.PROPERTY_SELECTED_APPLICATION).observe(model),
new UpdateValueStrategy().setAfterGetValidator(new IValidator() {
@Override
public IStatus validate(Object value) {
if (value != null) {
return ValidationStatus.ok();
}
else {
return ValidationStatus.info("You have to select an application...");
}
}
}),
null);
Button newButton = new Button(container, SWT.PUSH);
newButton.setText("Ne&w");
GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).hint(80, 30).applyTo(newButton);
newButton.addSelectionListener(onNew(dbc));
Button deleteButton = new Button(container, SWT.PUSH);
deleteButton.setText("&Delete");
GridDataFactory.fillDefaults().align(SWT.LEFT, SWT.CENTER).hint(80, 30).applyTo(deleteButton);
DataBindingUtils.bindEnablementToValidationStatus(deleteButton, IStatus.INFO, dbc, selectedApplicationBinding);
deleteButton.addSelectionListener(onDelete(dbc));
Button detailsButton = new Button(container, SWT.PUSH);
detailsButton.setText("De&tails");
GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).hint(80, 30).applyTo(detailsButton);
DataBindingUtils.bindEnablementToValidationStatus(detailsButton, IStatus.INFO, dbc , selectedApplicationBinding);
detailsButton.addSelectionListener(onDetails(dbc));
}
|
diff --git a/src/test/java/org/diveintojee/poc/stories/ContinuityStory.java b/src/test/java/org/diveintojee/poc/stories/ContinuityStory.java
index c033b0c..aa726b5 100644
--- a/src/test/java/org/diveintojee/poc/stories/ContinuityStory.java
+++ b/src/test/java/org/diveintojee/poc/stories/ContinuityStory.java
@@ -1,35 +1,34 @@
/**
*
*/
package org.diveintojee.poc.stories;
import org.diveintojee.poc.steps.ContinuitySteps;
import org.diveintojee.poc.steps.Exchange;
import org.diveintojee.poc.web.SearchClassifiedsResource;
import org.jbehave.core.io.CodeLocations;
import org.jbehave.core.io.StoryFinder;
import org.jbehave.core.steps.InjectableStepsFactory;
import org.jbehave.core.steps.InstanceStepsFactory;
import java.util.Arrays;
import java.util.List;
/**
* @author [email protected]
*/
public class ContinuityStory extends AbstractJUnitStories {
@Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(configuration(), new ContinuitySteps(new Exchange()));
}
@Override
protected List<String> storyPaths() {
- List<String> paths = new StoryFinder().findPaths(CodeLocations.codeLocationFromClass(
- SearchClassifiedsResource.class).getFile(),
+ List<String> paths = new StoryFinder().findPaths(CodeLocations.codeLocationFromClass(getClass()).getFile(),
Arrays.asList("**/continuity.story"), null);
//System.out.println("paths = " + paths);
return paths;
}
}
| true | true | protected List<String> storyPaths() {
List<String> paths = new StoryFinder().findPaths(CodeLocations.codeLocationFromClass(
SearchClassifiedsResource.class).getFile(),
Arrays.asList("**/continuity.story"), null);
//System.out.println("paths = " + paths);
return paths;
}
| protected List<String> storyPaths() {
List<String> paths = new StoryFinder().findPaths(CodeLocations.codeLocationFromClass(getClass()).getFile(),
Arrays.asList("**/continuity.story"), null);
//System.out.println("paths = " + paths);
return paths;
}
|
diff --git a/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindS3ObjectToPayload.java b/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindS3ObjectToPayload.java
index a1d17f281..851c103ef 100755
--- a/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindS3ObjectToPayload.java
+++ b/aws/core/src/main/java/org/jclouds/aws/s3/binders/BindS3ObjectToPayload.java
@@ -1,67 +1,67 @@
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <[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 org.jclouds.aws.s3.binders;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.inject.Inject;
import javax.ws.rs.core.HttpHeaders;
import org.jclouds.aws.s3.blobstore.functions.ObjectToBlob;
import org.jclouds.aws.s3.domain.S3Object;
import org.jclouds.blobstore.binders.BindBlobToPayloadAndUserMetadataToHeadersWithPrefix;
import org.jclouds.http.HttpRequest;
import org.jclouds.rest.Binder;
public class BindS3ObjectToPayload implements Binder {
private final BindBlobToPayloadAndUserMetadataToHeadersWithPrefix blobBinder;
private final ObjectToBlob object2Blob;
@Inject
public BindS3ObjectToPayload(ObjectToBlob object2Blob,
BindBlobToPayloadAndUserMetadataToHeadersWithPrefix blobBinder) {
this.blobBinder = blobBinder;
this.object2Blob = object2Blob;
}
public void bindToRequest(HttpRequest request, Object payload) {
S3Object s3Object = (S3Object) payload;
checkNotNull(s3Object.getContentLength(), "contentLength");
- checkArgument(s3Object.getContentLength() <= 5 * 1024 * 1024 * 1024,
+ checkArgument(s3Object.getContentLength() <= 5l * 1024 * 1024 * 1024,
"maximum size for put object is 5GB");
blobBinder.bindToRequest(request, object2Blob.apply(s3Object));
if (s3Object.getMetadata().getCacheControl() != null) {
request.getHeaders().put(HttpHeaders.CACHE_CONTROL,
s3Object.getMetadata().getCacheControl());
}
if (s3Object.getMetadata().getContentDisposition() != null) {
request.getHeaders().put("Content-Disposition",
s3Object.getMetadata().getContentDisposition());
}
if (s3Object.getMetadata().getContentEncoding() != null) {
request.getHeaders().put(HttpHeaders.CONTENT_ENCODING,
s3Object.getMetadata().getContentEncoding());
}
}
}
| true | true | public void bindToRequest(HttpRequest request, Object payload) {
S3Object s3Object = (S3Object) payload;
checkNotNull(s3Object.getContentLength(), "contentLength");
checkArgument(s3Object.getContentLength() <= 5 * 1024 * 1024 * 1024,
"maximum size for put object is 5GB");
blobBinder.bindToRequest(request, object2Blob.apply(s3Object));
if (s3Object.getMetadata().getCacheControl() != null) {
request.getHeaders().put(HttpHeaders.CACHE_CONTROL,
s3Object.getMetadata().getCacheControl());
}
if (s3Object.getMetadata().getContentDisposition() != null) {
request.getHeaders().put("Content-Disposition",
s3Object.getMetadata().getContentDisposition());
}
if (s3Object.getMetadata().getContentEncoding() != null) {
request.getHeaders().put(HttpHeaders.CONTENT_ENCODING,
s3Object.getMetadata().getContentEncoding());
}
}
| public void bindToRequest(HttpRequest request, Object payload) {
S3Object s3Object = (S3Object) payload;
checkNotNull(s3Object.getContentLength(), "contentLength");
checkArgument(s3Object.getContentLength() <= 5l * 1024 * 1024 * 1024,
"maximum size for put object is 5GB");
blobBinder.bindToRequest(request, object2Blob.apply(s3Object));
if (s3Object.getMetadata().getCacheControl() != null) {
request.getHeaders().put(HttpHeaders.CACHE_CONTROL,
s3Object.getMetadata().getCacheControl());
}
if (s3Object.getMetadata().getContentDisposition() != null) {
request.getHeaders().put("Content-Disposition",
s3Object.getMetadata().getContentDisposition());
}
if (s3Object.getMetadata().getContentEncoding() != null) {
request.getHeaders().put(HttpHeaders.CONTENT_ENCODING,
s3Object.getMetadata().getContentEncoding());
}
}
|
diff --git a/acs/tabbychat/TabbyChat.java b/acs/tabbychat/TabbyChat.java
index 2df4ec5..785043c 100644
--- a/acs/tabbychat/TabbyChat.java
+++ b/acs/tabbychat/TabbyChat.java
@@ -1,721 +1,721 @@
package acs.tabbychat;
/****************************************************
* This document is Copyright ©(2012) and is the intellectual property of the author.
* It may be not be reproduced under any circumstances except for personal, private
* use as long as it remains in its unaltered, unedited form. It may not be placed on
* any web site or otherwise distributed publicly without advance written permission.
* Use of this mod on any other website or as a part of any public display is strictly
* prohibited, and a violation of copyright.
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import org.lwjgl.input.Keyboard;
import net.minecraft.client.Minecraft;
import net.minecraft.src.Gui;
import net.minecraft.src.MathHelper;
import net.minecraft.src.ScaledResolution;
import net.minecraft.src.StringUtils;
public class TabbyChat {
protected static Minecraft mc;
private volatile Pattern chatChannelPatternClean = Pattern.compile("^\\[([A-Za-z0-9_]{1,10})\\]");
private volatile Pattern chatChannelPatternDirty = Pattern.compile("^\\[([A-Za-z0-9_]{1,10})\\]");
private volatile Pattern chatPMfromMePattern = null;
private volatile Pattern chatPMtoMePattern = null;
public static String version = TabbyChatUtils.version;
protected Calendar cal = Calendar.getInstance();
private volatile List<TCChatLine> lastChat = new ArrayList();
public LinkedHashMap<String, ChatChannel> channelMap = new LinkedHashMap();
public int nextID = 3600;
public static TCSettingsGeneral generalSettings;
public static TCSettingsServer serverSettings;
public static TCSettingsFilters filterSettings;
public static TCSettingsAdvanced advancedSettings;
private Semaphore serverDataLock = new Semaphore(0, true);
private final ReentrantReadWriteLock lastChatLock = new ReentrantReadWriteLock(true);
private final Lock lastChatReadLock = lastChatLock.readLock();
private final Lock lastChatWriteLock = lastChatLock.writeLock();
public static final GuiNewChatTC gnc = GuiNewChatTC.me;
public static final TabbyChat instance = new TabbyChat();
private TabbyChat() {
mc = Minecraft.getMinecraft();
generalSettings = new TCSettingsGeneral(this);
serverSettings = new TCSettingsServer(this);
filterSettings = new TCSettingsFilters(this);
advancedSettings = new TCSettingsAdvanced(this);
generalSettings.loadSettingsFile();
advancedSettings.loadSettingsFile();
if (!this.enabled()) this.disable();
else {
this.enable();
}
}
protected int addToChannel(String name, TCChatLine thisChat) {
int ret = 0;
TCChatLine newChat = this.withTimeStamp(thisChat);
ChatChannel theChan = this.channelMap.get(name);
theChan.chatLog.add(0, newChat);
theChan.trimLog();
if (theChan.active || this.channelMap.get("*").active)
ret = 1;
return ret;
}
protected int addToChannel(String _name, List<TCChatLine> thisChat) {
ChatChannel theChan = this.channelMap.get(_name);
for (String ichan : Pattern.compile("[ ]?,[ ]?").split(serverSettings.ignoredChannels.getValue())) {
if (ichan.length() > 0 && _name.equals(ichan)) {
return 0;
}
}
if (theChan != null) {
int ret = 0;
if (generalSettings.groupSpam.getValue()) {
this.spamCheck(_name, thisChat);
if (!theChan.hasSpam) {
for (TCChatLine cl : thisChat) {
ret += this.addToChannel(_name, cl);
}
}
} else {
for (TCChatLine cl : thisChat) {
ret += this.addToChannel(_name, cl);
}
}
return ret;
}
if (this.channelMap.size() >= 20) return 0; // Too many tabs
if (serverSettings.autoChannelSearch.getValue()) {
this.channelMap.put(_name, new ChatChannel(_name));
int ret = 0;
for (TCChatLine cl : thisChat) {
ret += this.addToChannel(_name, cl);
}
return ret;
}
return 0;
}
protected void addLastChatToChannel(ChatChannel _chan) {
this.lastChatReadLock.lock();
try {
for(int i=this.lastChat.size()-1;i>=0;i--)
_chan.chatLog.add(0, this.lastChat.get(i));
} finally {
this.lastChatReadLock.unlock();
}
}
private void spamCheck(String _chan, List<TCChatLine> lastChat) {
ChatChannel theChan = this.channelMap.get(_chan);
String oldChat = "";
String oldChat2 = "";
String newChat = "";
if (theChan.chatLog.size() < lastChat.size()) {
theChan.hasSpam = false;
theChan.spamCount = 1;
return;
}
int _size = lastChat.size();
for (int i=0; i<_size; i++) {
if(lastChat.get(i).getChatLineString() == null || theChan.chatLog.get(i).getChatLineString() == null) continue;
newChat = newChat + lastChat.get(i).getChatLineString();
if (generalSettings.timeStampEnable.getValue()) {
oldChat = theChan.chatLog.get(i).getChatLineString().replaceAll("^"+((TimeStampEnum)generalSettings.timeStampStyle.getValue()).regEx, "") + oldChat;
} else {
oldChat = theChan.chatLog.get(i).getChatLineString() + oldChat;
}
}
if (theChan.hasSpam) {
oldChat2 = oldChat.substring(0, oldChat.length() - 4 - Integer.toString(theChan.spamCount).length());
oldChat = oldChat2;
}
if (oldChat.equals(newChat)) {
theChan.hasSpam = true;
theChan.spamCount++;
for (int i=1; i<_size; i++)
theChan.chatLog.set(i, this.withTimeStamp(lastChat.get(lastChat.size()-i-1)));
theChan.chatLog.set(0, new TCChatLine(lastChat.get(lastChat.size()-1).getUpdatedCounter(), this.withTimeStamp(lastChat.get(lastChat.size()-1).getChatLineString()) + " [" + theChan.spamCount + "x]", lastChat.get(lastChat.size()-1).getChatLineID()));
} else {
theChan.hasSpam = false;
theChan.spamCount = 1;
}
}
private List<TCChatLine> withTimeStamp(List<TCChatLine> _orig) {
List<TCChatLine> stamped = new ArrayList();
for (TCChatLine cl : _orig)
stamped.add(0, this.withTimeStamp(cl));
return stamped;
}
private TCChatLine withTimeStamp(TCChatLine _orig) {
TCChatLine stamped = _orig;
if (generalSettings.timeStampEnable.getValue()) {
this.cal = Calendar.getInstance();
stamped = new TCChatLine(_orig.getUpdatedCounter(), generalSettings.timeStamp.format(this.cal.getTime())+_orig.getChatLineString(), _orig.getChatLineID());
}
return stamped;
}
private String withTimeStamp(String _orig) {
String stamped = _orig;
if (generalSettings.timeStampEnable.getValue()) {
this.cal = Calendar.getInstance();
stamped = generalSettings.timeStamp.format(this.cal.getTime()) + _orig;
}
return stamped;
}
protected static String getNewestVersion() {
try {
HttpURLConnection conn = (HttpURLConnection) new URL("http://goo.gl/LkiHT").openConnection();
BufferedReader buffer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String newestVersion = buffer.readLine();
buffer.close();
return newestVersion;
} catch (Throwable e) {
printErr("Unable to check for TabbyChat update.");
}
return TabbyChat.version;
}
protected void disable() {
this.channelMap.clear();
this.channelMap.put("*", new ChatChannel("*"));
}
protected void enable() {
if (!this.channelMap.containsKey("*")) {
this.channelMap.put("*", new ChatChannel("*"));
this.channelMap.get("*").active = true;
}
synchronized(TabbyChat.class) {
this.serverDataLock.tryAcquire();
serverSettings.updateForServer();
this.reloadServerData();
this.loadPatterns();
this.updateDefaults();
this.updateFilters();
if(serverSettings.server != null) this.loadPMPatterns();
this.serverDataLock.release();
}
if (generalSettings.saveChatLog.getValue() && serverSettings.server != null) {
TabbyChatUtils.logChat("\nBEGIN CHAT LOGGING FOR "+serverSettings.serverName+"("+serverSettings.serverIP+") -- "+(new SimpleDateFormat()).format(Calendar.getInstance().getTime()));
}
}
private void reloadServerData() {
serverSettings.loadSettingsFile();
filterSettings.loadSettingsFile();
this.loadChannelData();
}
protected void loadPatterns() {
ChannelDelimEnum delims = (ChannelDelimEnum)serverSettings.delimiterChars.getValue();
String colCode = "";
String fmtCode = "";
if (serverSettings.delimColorBool.getValue())
colCode = ((ColorCodeEnum)serverSettings.delimColorCode.getValue()).toCode();
if (serverSettings.delimFormatBool.getValue())
fmtCode = ((FormatCodeEnum)serverSettings.delimFormatCode.getValue()).toCode();
String frmt = colCode + fmtCode;
if (((ColorCodeEnum)serverSettings.delimColorCode.getValue()).toString().equals("White")) {
frmt = "(" + colCode + ")?" + fmtCode;
} else if (frmt.length() > 7)
frmt = "[" + frmt + "]{2}";
if (frmt.length() > 0)
frmt = "(?i:"+frmt+")";
if (frmt.length() == 0)
frmt = "(?i:\u00A7[0-9A-FK-OR])*";
this.chatChannelPatternDirty = Pattern.compile("^(\u00A7r)?"+frmt+"\\"+delims.open()+"([A-Za-z0-9_\u00A7]+)\\"+delims.close());
this.chatChannelPatternClean = Pattern.compile("^"+"\\"+delims.open()+"([A-Za-z0-9_]{1,"+this.advancedSettings.maxLengthChannelName.getValue()+"})\\"+delims.close());
}
protected void loadPMPatterns() {
StringBuilder toMePM = new StringBuilder();
StringBuilder fromMePM = new StringBuilder();
// Matches '[Player -> me]' and '[me -> Player]'
toMePM.append("^\\[(\\w{3,16})[ ]?\\-\\>[ ]?me\\]");
fromMePM.append("^\\[me[ ]?\\-\\>[ ]?(\\w{3,16})\\]");
// Matches 'From Player' and 'From Player'
toMePM.append("|^From (\\w{3,16})[ ]?:");
fromMePM.append("|^To (\\w{3,16})[ ]?:");
// Matches 'Player whispers to you' and 'You whisper to Player'
toMePM.append("|^(\\w{3,16}) whispers to you");
fromMePM.append("|^You whisper to (\\w{3,16})");
if(mc.thePlayer != null && mc.thePlayer.username != null) {
String me = mc.thePlayer.username;
// Matches '[Player->Player1]' and '[Player1->Player]'
toMePM.append("|^\\[(\\w{3,16})[ ]?\\-\\>[ ]?").append(me).append("\\]");
fromMePM.append("|^\\[").append(me).append("[ ]?\\-\\>[ ]?(\\w{3,16})\\]");
}
this.chatPMtoMePattern = Pattern.compile(toMePM.toString());
this.chatPMfromMePattern = Pattern.compile(fromMePM.toString());
}
protected void updateFilters() {
if (!generalSettings.tabbyChatEnable.getValue()) return;
if (filterSettings.numFilters == 0) return;
String newName;
for (int i=0; i<filterSettings.numFilters; i++) {
newName = filterSettings.sendToTabName(i);
if (filterSettings.sendToTabBool(i) &&
!filterSettings.sendToAllTabs(i) &&
!this.channelMap.containsKey(newName)) {
this.channelMap.put(newName, new ChatChannel(newName));
}
}
}
protected void updateDefaults() {
if (!this.generalSettings.tabbyChatEnable.getValue()) return;
List<String> dList = new ArrayList(Arrays.asList(Pattern.compile("[ ]?,[ ]?").split(serverSettings.defaultChannels.getValue())));
int ind;
for (ChatChannel chan : this.channelMap.values()) {
ind = dList.indexOf(chan.title);
if (ind >= 0) dList.remove(ind);
}
for (String defChan : dList) {
if (defChan.length() > 0) this.channelMap.put(defChan, new ChatChannel(defChan));
}
}
protected void loadChannelData() {
LinkedHashMap<String, ChatChannel> importData = null;
File chanDataFile;
String ip = TabbyChat.serverSettings.serverIP;
if (ip == null || ip.length() == 0) return;
if (ip.contains(":")) {
ip = ip.replaceAll(":", "(") + ")";
}
String pName = "";
if(mc.thePlayer != null && mc.thePlayer.username != null) pName = mc.thePlayer.username;
File settingsDir = new File(TCSettingsGUI.tabbyChatDir, ip);
chanDataFile = new File(settingsDir, pName+"_chanData.ser");
if(!chanDataFile.exists()) return;
FileInputStream cFileStream = null;
BufferedInputStream cBuffStream = null;
ObjectInputStream cObjStream = null;
try {
cFileStream = new FileInputStream(chanDataFile);
cBuffStream = new BufferedInputStream(cFileStream);
cObjStream = new ObjectInputStream(cBuffStream);
importData = (LinkedHashMap<String, ChatChannel>)cObjStream.readObject();
cObjStream.close();
cBuffStream.close();
} catch (Exception e) {
printErr("Unable to read channel data file : '" + e.getLocalizedMessage() + "' : " + e.toString());
return;
}
if(importData == null) return;
int oldIDs = 0;
for(Map.Entry<String, ChatChannel> chan : importData.entrySet()) {
ChatChannel _new = null;
if(!this.channelMap.containsKey(chan.getKey())) {
_new = new ChatChannel(chan.getKey());
_new.chanID = chan.getValue().chanID;
this.channelMap.put(_new.title, _new);
} else {
_new = this.channelMap.get(chan.getKey());
}
_new.alias = chan.getValue().alias;
_new.active = chan.getValue().active;
_new.notificationsOn = chan.getValue().notificationsOn;
_new.cmdPrefix = chan.getValue().cmdPrefix;
this.addToChannel(chan.getKey(), new TCChatLine(-1, "-- chat history from "+(new SimpleDateFormat()).format(chanDataFile.lastModified()), 0, true));
_new.importOldChat(chan.getValue().chatLog);
oldIDs++;
}
ChatChannel.nextID = 3600 + oldIDs;
this.resetDisplayedChat();
}
protected void storeChannelData() {
LinkedHashMap<String, ChatChannel> chanData = TabbyChat.instance.channelMap;
File chanDataFile;
String ip = TabbyChat.serverSettings.serverIP;
if (ip == null || ip.length() == 0) return;
if (ip.contains(":")) {
ip = ip.replaceAll(":", "(") + ")";
}
String pName = "";
if(mc.thePlayer != null && mc.thePlayer.username != null) pName = mc.thePlayer.username;
File settingsDir = new File(TCSettingsGUI.tabbyChatDir, ip);
if (!settingsDir.exists())
settingsDir.mkdirs();
chanDataFile = new File(settingsDir, pName+"_chanData.ser");
FileOutputStream cFileStream = null;
BufferedOutputStream cBuffStream = null;
ObjectOutputStream cObjStream = null;
try {
cFileStream = new FileOutputStream(chanDataFile);
cBuffStream = new BufferedOutputStream(cFileStream);
cObjStream = new ObjectOutputStream(cBuffStream);
cObjStream.writeObject(chanData);
cObjStream.flush();
cObjStream.close();
cBuffStream.close();
} catch (Exception e) {
printErr("Unable to write channel data to file : '" + e.getLocalizedMessage() + "' : " + e.toString());
}
}
protected void finalize() {
this.storeChannelData();
}
public void checkServer() {
if (mc.getServerData() == null) return;
if(serverSettings.server == null) {
BackgroundUpdateCheck buc = new BackgroundUpdateCheck();
buc.start();
}
if (!mc.getServerData().serverIP.equalsIgnoreCase(serverSettings.serverIP)) {
this.storeChannelData();
this.channelMap.clear();
if (this.enabled()) {
this.enable();
this.resetDisplayedChat();
} else this.disable();
}
return;
}
public void copyTab(String toName, String fromName) {
this.channelMap.put(toName, this.channelMap.get(fromName));
}
public boolean enabled() {
if (mc.isSingleplayer()) {
return false;
} else
return generalSettings.tabbyChatEnable.getValue();
}
public List<String> getActive() {
int n = this.channelMap.size();
List<String> actives = new ArrayList<String>(n);
for (ChatChannel chan : this.channelMap.values()) {
if (chan.active)
actives.add(chan.title);
}
return actives;
}
public void pollForUnread(Gui _gui, int _y, int _tick) {
int _opacity = 0;
int tickdiff = 50;
this.lastChatReadLock.lock();
try {
if(this.lastChat != null && this.lastChat.size() > 0) tickdiff = _tick - this.lastChat.get(0).getUpdatedCounter();
} finally {
this.lastChatReadLock.unlock();
}
if (tickdiff < 50) {
float var6 = this.mc.gameSettings.chatOpacity * 0.9F + 0.1F;
double var10 = (double)tickdiff / 50.0D;
var10 = 1.0D - var10;
var10 *= 10.0D;
if (var10 < 0.0D) var10 = 0.0D;
if (var10 > 1.0D) var10 = 1.0D;
var10 *= var10;
_opacity = (int)(255.0D * var10);
_opacity = (int)((float)_opacity * var6);
if (_opacity <= 3) return;
this.updateButtonLocations();
for (ChatChannel chan : this.channelMap.values()) {
if (chan.unread && chan.notificationsOn)
chan.unreadNotify(_gui, _y, _opacity);
}
}
}
public static void printErr(String err) {
System.err.println(err);
mc.getLogAgent().logWarning(err);
}
public int processChat(List<TCChatLine> theChat) {
if(this.serverDataLock.availablePermits() == 0) {
this.serverDataLock.acquireUninterruptibly();
this.serverDataLock.release();
}
ArrayList<TCChatLine> filteredChatLine = new ArrayList<TCChatLine>(theChat.size());
List<String> toTabs = new ArrayList<String>();
toTabs.add("*");
int _ind;
int ret = 0;
boolean skip = !serverSettings.autoChannelSearch.getValue();
int n = theChat.size();
StringBuilder filteredChat = new StringBuilder(theChat.get(0).getChatLineString().length() * n);
for (int z=0; z<n; z++)
filteredChat.append(theChat.get(z).getChatLineString());
for (int i = 0; i < filterSettings.numFilters; i++) {
if (!filterSettings.applyFilterToDirtyChat(i, filteredChat.toString())) continue;
if (filterSettings.removeMatches(i)) {
toTabs.clear();
toTabs.add("*");
skip = true;
break;
}
filteredChat = new StringBuilder(filterSettings.getLastMatchPretty());
if (filterSettings.sendToTabBool(i)) {
if (filterSettings.sendToAllTabs(i)) {
toTabs.clear();
for (ChatChannel chan : this.channelMap.values())
toTabs.add(chan.title);
skip = true;
continue;
} else {
String destTab = filterSettings.sendToTabName(i);
if (!this.channelMap.containsKey(destTab)) {
this.channelMap.put(destTab, new ChatChannel(destTab));
}
if (!toTabs.contains(destTab))
toTabs.add(destTab);
}
}
if (filterSettings.audioNotificationBool(i))
filterSettings.audioNotification(i);
}
Iterator splitChat = mc.fontRenderer.listFormattedStringToWidth(filteredChat.toString(), gnc.chatWidth).iterator();
boolean firstline = true;
while (splitChat.hasNext()) {
String _line = (String)splitChat.next();
if (!firstline)
_line = " " + _line;
filteredChatLine.add(new TCChatLine(theChat.get(0).getUpdatedCounter(), _line, theChat.get(0).getChatLineID(), theChat.get(0).statusMsg));
firstline = false;
}
for (String c : toTabs) {
this.addToChannel(c, filteredChatLine);
}
for (String _act : this.getActive()) {
if (toTabs.contains(_act))
ret++;
}
String coloredChat = "";
for (TCChatLine cl : theChat)
coloredChat = coloredChat + cl.getChatLineString();
String cleanedChat = StringUtils.stripControlCodes(coloredChat);
if (generalSettings.saveChatLog.getValue()) TabbyChatUtils.logChat(this.withTimeStamp(cleanedChat));
if (!skip) {
Matcher findChannelClean = this.chatChannelPatternClean.matcher(cleanedChat);
Matcher findChannelDirty = this.chatChannelPatternDirty.matcher(coloredChat);
String cName = null;
boolean dirtyValid = (!serverSettings.delimColorBool.getValue() && !serverSettings.delimFormatBool.getValue()) ? true : findChannelDirty.find();
if (findChannelClean.find() && dirtyValid) {
cName = findChannelClean.group(1);
ret += this.addToChannel(cName, filteredChatLine);
toTabs.add(cName);
} else if(this.chatPMtoMePattern != null){
Matcher findPMtoMe = this.chatPMtoMePattern.matcher(cleanedChat);
if (findPMtoMe.find()) {
for(int i=1;i<=findPMtoMe.groupCount();i++) {
if(findPMtoMe.group(i) != null) {
cName = findPMtoMe.group(i);
if(!this.channelMap.containsKey(cName)) {
ChatChannel newPM = new ChatChannel(cName);
newPM.cmdPrefix = "/msg "+cName;
this.channelMap.put(cName, newPM);
}
ret += this.addToChannel(cName, filteredChatLine);
toTabs.add(cName);
break;
}
}
} else if(this.chatPMfromMePattern != null) {
Matcher findPMfromMe = this.chatPMfromMePattern.matcher(cleanedChat);
if (findPMfromMe.find()) {
for(int i=1;i<=findPMfromMe.groupCount();i++) {
if(findPMfromMe.group(i) != null) {
cName = findPMfromMe.group(i);
if(!this.channelMap.containsKey(cName)) {
ChatChannel newPM = new ChatChannel(cName);
newPM.cmdPrefix = "/msg "+cName;
this.channelMap.put(cName, newPM);
}
ret += this.addToChannel(cName, filteredChatLine);
toTabs.add(cName);
break;
}
}
}
}
}
}
if (ret == 0) {
for (String c : toTabs) {
if (c != "*" && this.channelMap.containsKey(c)) {
this.channelMap.get(c).unread = true;
}
}
}
List<String> activeTabs = this.getActive();
this.lastChatWriteLock.lock();
try {
if (generalSettings.groupSpam.getValue() && activeTabs.size() > 0) {
if (toTabs.contains(activeTabs.get(0)))
- this.lastChat = this.channelMap.get(activeTabs.get(0)).chatLog.subList(0, filteredChatLine.size());
+ this.lastChat = new ArrayList(this.channelMap.get(activeTabs.get(0)).chatLog.subList(0, filteredChatLine.size()));
else
this.lastChat = this.withTimeStamp(filteredChatLine);
} else
this.lastChat = this.withTimeStamp(filteredChatLine);
} finally {
this.lastChatWriteLock.unlock();
}
this.lastChatReadLock.lock();
try {
if (ret > 0) {
if (generalSettings.groupSpam.getValue() && this.channelMap.get(activeTabs.get(0)).hasSpam) {
gnc.setChatLines(0, new ArrayList<TCChatLine>(this.lastChat));
} else {
gnc.addChatLines(0, new ArrayList<TCChatLine>(this.lastChat));
}
}
} finally {
this.lastChatReadLock.unlock();
}
return ret;
}
public void removeTab(String _name) {
this.channelMap.remove(_name);
}
public void resetDisplayedChat() {
gnc.clearChatLines();
List<String> actives = this.getActive();
if (actives.size() < 1) return;
gnc.addChatLines(this.channelMap.get(actives.get(0)).chatLog);
int n = actives.size();
for (int i = 1; i < n; i++) {
gnc.mergeChatLines(this.channelMap.get(actives.get(i)).chatLog);
}
}
public void updateButtonLocations() {
int xOff = 0;
int yOff = 0;
ScaledResolution sr = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight);
int maxlines = gnc.getHeightSetting() / 9;
int clines = (gnc.GetChatHeight() < maxlines) ? gnc.GetChatHeight() : maxlines;
int vert = sr.getScaledHeight() - gnc.chatHeight - 51;;
int horiz = 5;
int n = this.channelMap.size();
/* try {
if (TabbyChatUtils.is(mc.ingameGUI.getChatGUI(), "GuiNewChatWrapper")) {
Class aHudCls = Class.forName("advancedhud.ahuditem.DefaultHudItems");
Field aHudFld = aHudCls.getField("chat");
Object aHudObj = aHudFld.get(null);
aHudCls = Class.forName("advancedhud.ahuditem.HudItem");
int dVert = mc.currentScreen.height - 22 - 6 * 18;
xOff = aHudCls.getField("posX").getInt(aHudObj) - 3;
yOff = aHudCls.getField("posY").getInt(aHudObj) - dVert;
horiz += xOff;
vert -= yOff;
if (gnc.getChatOpen()) ((GuiChatTC)mc.currentScreen).scrollBar.setOffset(xOff, yOff);
}
} catch (Throwable e) {}*/
int i = 0;
for (ChatChannel chan : this.channelMap.values()) {
chan.tab.width(mc.fontRenderer.getStringWidth(chan.getDisplayTitle()) + 8);
if (horiz + chan.tab.width() > gnc.chatWidth - 5) {
vert = vert - chan.tab.height();
horiz = 5;
}
chan.setButtonLoc(horiz, vert);
if (chan.tab == null) {
chan.setButtonObj(new ChatButton(chan.getID(), horiz, vert, chan.tab.width(), chan.tab.height(), chan.getDisplayTitle()));
} else {
chan.tab.id = chan.getID();
chan.tab.xPosition = horiz;
chan.tab.yPosition = vert;
chan.tab.displayString = chan.getDisplayTitle();
}
horiz = chan.getButtonEnd() + 1;
}
}
}
| true | true | public int processChat(List<TCChatLine> theChat) {
if(this.serverDataLock.availablePermits() == 0) {
this.serverDataLock.acquireUninterruptibly();
this.serverDataLock.release();
}
ArrayList<TCChatLine> filteredChatLine = new ArrayList<TCChatLine>(theChat.size());
List<String> toTabs = new ArrayList<String>();
toTabs.add("*");
int _ind;
int ret = 0;
boolean skip = !serverSettings.autoChannelSearch.getValue();
int n = theChat.size();
StringBuilder filteredChat = new StringBuilder(theChat.get(0).getChatLineString().length() * n);
for (int z=0; z<n; z++)
filteredChat.append(theChat.get(z).getChatLineString());
for (int i = 0; i < filterSettings.numFilters; i++) {
if (!filterSettings.applyFilterToDirtyChat(i, filteredChat.toString())) continue;
if (filterSettings.removeMatches(i)) {
toTabs.clear();
toTabs.add("*");
skip = true;
break;
}
filteredChat = new StringBuilder(filterSettings.getLastMatchPretty());
if (filterSettings.sendToTabBool(i)) {
if (filterSettings.sendToAllTabs(i)) {
toTabs.clear();
for (ChatChannel chan : this.channelMap.values())
toTabs.add(chan.title);
skip = true;
continue;
} else {
String destTab = filterSettings.sendToTabName(i);
if (!this.channelMap.containsKey(destTab)) {
this.channelMap.put(destTab, new ChatChannel(destTab));
}
if (!toTabs.contains(destTab))
toTabs.add(destTab);
}
}
if (filterSettings.audioNotificationBool(i))
filterSettings.audioNotification(i);
}
Iterator splitChat = mc.fontRenderer.listFormattedStringToWidth(filteredChat.toString(), gnc.chatWidth).iterator();
boolean firstline = true;
while (splitChat.hasNext()) {
String _line = (String)splitChat.next();
if (!firstline)
_line = " " + _line;
filteredChatLine.add(new TCChatLine(theChat.get(0).getUpdatedCounter(), _line, theChat.get(0).getChatLineID(), theChat.get(0).statusMsg));
firstline = false;
}
for (String c : toTabs) {
this.addToChannel(c, filteredChatLine);
}
for (String _act : this.getActive()) {
if (toTabs.contains(_act))
ret++;
}
String coloredChat = "";
for (TCChatLine cl : theChat)
coloredChat = coloredChat + cl.getChatLineString();
String cleanedChat = StringUtils.stripControlCodes(coloredChat);
if (generalSettings.saveChatLog.getValue()) TabbyChatUtils.logChat(this.withTimeStamp(cleanedChat));
if (!skip) {
Matcher findChannelClean = this.chatChannelPatternClean.matcher(cleanedChat);
Matcher findChannelDirty = this.chatChannelPatternDirty.matcher(coloredChat);
String cName = null;
boolean dirtyValid = (!serverSettings.delimColorBool.getValue() && !serverSettings.delimFormatBool.getValue()) ? true : findChannelDirty.find();
if (findChannelClean.find() && dirtyValid) {
cName = findChannelClean.group(1);
ret += this.addToChannel(cName, filteredChatLine);
toTabs.add(cName);
} else if(this.chatPMtoMePattern != null){
Matcher findPMtoMe = this.chatPMtoMePattern.matcher(cleanedChat);
if (findPMtoMe.find()) {
for(int i=1;i<=findPMtoMe.groupCount();i++) {
if(findPMtoMe.group(i) != null) {
cName = findPMtoMe.group(i);
if(!this.channelMap.containsKey(cName)) {
ChatChannel newPM = new ChatChannel(cName);
newPM.cmdPrefix = "/msg "+cName;
this.channelMap.put(cName, newPM);
}
ret += this.addToChannel(cName, filteredChatLine);
toTabs.add(cName);
break;
}
}
} else if(this.chatPMfromMePattern != null) {
Matcher findPMfromMe = this.chatPMfromMePattern.matcher(cleanedChat);
if (findPMfromMe.find()) {
for(int i=1;i<=findPMfromMe.groupCount();i++) {
if(findPMfromMe.group(i) != null) {
cName = findPMfromMe.group(i);
if(!this.channelMap.containsKey(cName)) {
ChatChannel newPM = new ChatChannel(cName);
newPM.cmdPrefix = "/msg "+cName;
this.channelMap.put(cName, newPM);
}
ret += this.addToChannel(cName, filteredChatLine);
toTabs.add(cName);
break;
}
}
}
}
}
}
if (ret == 0) {
for (String c : toTabs) {
if (c != "*" && this.channelMap.containsKey(c)) {
this.channelMap.get(c).unread = true;
}
}
}
List<String> activeTabs = this.getActive();
this.lastChatWriteLock.lock();
try {
if (generalSettings.groupSpam.getValue() && activeTabs.size() > 0) {
if (toTabs.contains(activeTabs.get(0)))
this.lastChat = this.channelMap.get(activeTabs.get(0)).chatLog.subList(0, filteredChatLine.size());
else
this.lastChat = this.withTimeStamp(filteredChatLine);
} else
this.lastChat = this.withTimeStamp(filteredChatLine);
} finally {
this.lastChatWriteLock.unlock();
}
this.lastChatReadLock.lock();
try {
if (ret > 0) {
if (generalSettings.groupSpam.getValue() && this.channelMap.get(activeTabs.get(0)).hasSpam) {
gnc.setChatLines(0, new ArrayList<TCChatLine>(this.lastChat));
} else {
gnc.addChatLines(0, new ArrayList<TCChatLine>(this.lastChat));
}
}
} finally {
this.lastChatReadLock.unlock();
}
return ret;
}
| public int processChat(List<TCChatLine> theChat) {
if(this.serverDataLock.availablePermits() == 0) {
this.serverDataLock.acquireUninterruptibly();
this.serverDataLock.release();
}
ArrayList<TCChatLine> filteredChatLine = new ArrayList<TCChatLine>(theChat.size());
List<String> toTabs = new ArrayList<String>();
toTabs.add("*");
int _ind;
int ret = 0;
boolean skip = !serverSettings.autoChannelSearch.getValue();
int n = theChat.size();
StringBuilder filteredChat = new StringBuilder(theChat.get(0).getChatLineString().length() * n);
for (int z=0; z<n; z++)
filteredChat.append(theChat.get(z).getChatLineString());
for (int i = 0; i < filterSettings.numFilters; i++) {
if (!filterSettings.applyFilterToDirtyChat(i, filteredChat.toString())) continue;
if (filterSettings.removeMatches(i)) {
toTabs.clear();
toTabs.add("*");
skip = true;
break;
}
filteredChat = new StringBuilder(filterSettings.getLastMatchPretty());
if (filterSettings.sendToTabBool(i)) {
if (filterSettings.sendToAllTabs(i)) {
toTabs.clear();
for (ChatChannel chan : this.channelMap.values())
toTabs.add(chan.title);
skip = true;
continue;
} else {
String destTab = filterSettings.sendToTabName(i);
if (!this.channelMap.containsKey(destTab)) {
this.channelMap.put(destTab, new ChatChannel(destTab));
}
if (!toTabs.contains(destTab))
toTabs.add(destTab);
}
}
if (filterSettings.audioNotificationBool(i))
filterSettings.audioNotification(i);
}
Iterator splitChat = mc.fontRenderer.listFormattedStringToWidth(filteredChat.toString(), gnc.chatWidth).iterator();
boolean firstline = true;
while (splitChat.hasNext()) {
String _line = (String)splitChat.next();
if (!firstline)
_line = " " + _line;
filteredChatLine.add(new TCChatLine(theChat.get(0).getUpdatedCounter(), _line, theChat.get(0).getChatLineID(), theChat.get(0).statusMsg));
firstline = false;
}
for (String c : toTabs) {
this.addToChannel(c, filteredChatLine);
}
for (String _act : this.getActive()) {
if (toTabs.contains(_act))
ret++;
}
String coloredChat = "";
for (TCChatLine cl : theChat)
coloredChat = coloredChat + cl.getChatLineString();
String cleanedChat = StringUtils.stripControlCodes(coloredChat);
if (generalSettings.saveChatLog.getValue()) TabbyChatUtils.logChat(this.withTimeStamp(cleanedChat));
if (!skip) {
Matcher findChannelClean = this.chatChannelPatternClean.matcher(cleanedChat);
Matcher findChannelDirty = this.chatChannelPatternDirty.matcher(coloredChat);
String cName = null;
boolean dirtyValid = (!serverSettings.delimColorBool.getValue() && !serverSettings.delimFormatBool.getValue()) ? true : findChannelDirty.find();
if (findChannelClean.find() && dirtyValid) {
cName = findChannelClean.group(1);
ret += this.addToChannel(cName, filteredChatLine);
toTabs.add(cName);
} else if(this.chatPMtoMePattern != null){
Matcher findPMtoMe = this.chatPMtoMePattern.matcher(cleanedChat);
if (findPMtoMe.find()) {
for(int i=1;i<=findPMtoMe.groupCount();i++) {
if(findPMtoMe.group(i) != null) {
cName = findPMtoMe.group(i);
if(!this.channelMap.containsKey(cName)) {
ChatChannel newPM = new ChatChannel(cName);
newPM.cmdPrefix = "/msg "+cName;
this.channelMap.put(cName, newPM);
}
ret += this.addToChannel(cName, filteredChatLine);
toTabs.add(cName);
break;
}
}
} else if(this.chatPMfromMePattern != null) {
Matcher findPMfromMe = this.chatPMfromMePattern.matcher(cleanedChat);
if (findPMfromMe.find()) {
for(int i=1;i<=findPMfromMe.groupCount();i++) {
if(findPMfromMe.group(i) != null) {
cName = findPMfromMe.group(i);
if(!this.channelMap.containsKey(cName)) {
ChatChannel newPM = new ChatChannel(cName);
newPM.cmdPrefix = "/msg "+cName;
this.channelMap.put(cName, newPM);
}
ret += this.addToChannel(cName, filteredChatLine);
toTabs.add(cName);
break;
}
}
}
}
}
}
if (ret == 0) {
for (String c : toTabs) {
if (c != "*" && this.channelMap.containsKey(c)) {
this.channelMap.get(c).unread = true;
}
}
}
List<String> activeTabs = this.getActive();
this.lastChatWriteLock.lock();
try {
if (generalSettings.groupSpam.getValue() && activeTabs.size() > 0) {
if (toTabs.contains(activeTabs.get(0)))
this.lastChat = new ArrayList(this.channelMap.get(activeTabs.get(0)).chatLog.subList(0, filteredChatLine.size()));
else
this.lastChat = this.withTimeStamp(filteredChatLine);
} else
this.lastChat = this.withTimeStamp(filteredChatLine);
} finally {
this.lastChatWriteLock.unlock();
}
this.lastChatReadLock.lock();
try {
if (ret > 0) {
if (generalSettings.groupSpam.getValue() && this.channelMap.get(activeTabs.get(0)).hasSpam) {
gnc.setChatLines(0, new ArrayList<TCChatLine>(this.lastChat));
} else {
gnc.addChatLines(0, new ArrayList<TCChatLine>(this.lastChat));
}
}
} finally {
this.lastChatReadLock.unlock();
}
return ret;
}
|
diff --git a/src/depositfiles/cz/vity/freerapid/plugins/services/depositfiles/DepositFilesRunner.java b/src/depositfiles/cz/vity/freerapid/plugins/services/depositfiles/DepositFilesRunner.java
index ec3d7574..369e4f29 100644
--- a/src/depositfiles/cz/vity/freerapid/plugins/services/depositfiles/DepositFilesRunner.java
+++ b/src/depositfiles/cz/vity/freerapid/plugins/services/depositfiles/DepositFilesRunner.java
@@ -1,215 +1,213 @@
package cz.vity.freerapid.plugins.services.depositfiles;
import cz.vity.freerapid.plugins.exceptions.*;
import cz.vity.freerapid.plugins.webclient.AbstractRunner;
import cz.vity.freerapid.plugins.webclient.FileState;
import cz.vity.freerapid.plugins.webclient.utils.PlugUtils;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import java.net.URI;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Ladislav Vitasek, Ludek Zika, RubinX
*/
class DepositFilesRunner extends AbstractRunner {
private final static Logger logger = Logger.getLogger(DepositFilesRunner.class.getName());
private void setLanguageEN() {
addCookie(new Cookie(".depositfiles.com", "lang_current", "en", "/", 86400, false));
fileURL = fileURL.replaceFirst("/[^/]{2}/(files|folders)/", "/$1/"); // remove language id from URL
}
@Override
public void runCheck() throws Exception {
super.runCheck();
setLanguageEN();
if (!checkIsFolder()) {
final HttpMethod method = getGetMethod(fileURL);
if (makeRedirectedRequest(method)) {
checkNameAndSize(getContentAsString());
} else {
throw new ServiceConnectionProblemException();
}
}
}
@Override
public void run() throws Exception {
super.run();
setLanguageEN();
if (checkIsFolder()) {
runFolder();
return;
}
HttpMethod method = getGetMethod(fileURL);
if (makeRedirectedRequest(method)) {
checkNameAndSize(getContentAsString());
checkProblems();
- if (getContentAsString().contains("FREE downloading")) {
- method = getMethodBuilder().setReferer(fileURL).setAction(fileURL).setParameter("free_btn", "FREE downloading").toPostMethod();
- if (!makeRedirectedRequest(method)) {
- throw new ServiceConnectionProblemException();
- }
+ method = getMethodBuilder().setReferer(fileURL).setAction(fileURL).setParameter("free_btn", "Regular downloading").toPostMethod();
+ if (!makeRedirectedRequest(method)) {
+ throw new ServiceConnectionProblemException();
}
Matcher matcher = getMatcherAgainstContent("setTimeout\\s*\\(\\s*'load_form\\s*\\(\\s*fid\\s*,\\s*msg\\s*\\)\\s*'\\s*,\\s*(\\d+)\\s*\\)");
if (!matcher.find()) {
checkProblems();
throw new ServiceConnectionProblemException("Cannot find wait time");
}
int seconds = Integer.parseInt(matcher.group(1)) / 1000;
logger.info("wait - " + seconds);
matcher = getMatcherAgainstContent("<a href=\"(/get_file\\.php\\?fid=([^&]+)).*?\"[^>]*>");
if (!matcher.find()) {
throw new PluginImplementationException();
}
final String getFileUrl = matcher.group(1);
final String fid = matcher.group(2);
- downloadTask.sleep(seconds + 5);
+ downloadTask.sleep(seconds + 1);
String reCaptchaUrl = "";
matcher = getMatcherAgainstContent("Recaptcha\\.create\\s*\\(\\s*'([^']+)'");
if (matcher.find())
reCaptchaUrl = "http://www.google.com/recaptcha/api/challenge?k=" + matcher.group(1) + "&ajax=1&cachestop=0." + System.currentTimeMillis();
method = getMethodBuilder().setReferer(fileURL).setAction(getFileUrl).toGetMethod();
if (!makeRedirectedRequest(method)) {
throw new ServiceConnectionProblemException();
}
while (PlugUtils.find("(?s)check_recaptcha\\s*\\(\\s*'" + fid + "'", getContentAsString())) {
logger.info("Captcha URL: " + reCaptchaUrl);
method = getGetMethod(reCaptchaUrl);
if (!makeRedirectedRequest(method))
throw new ServiceConnectionProblemException();
matcher = getMatcherAgainstContent("(?s)challenge\\s*:\\s*'([\\w-]+)'.*?server\\s*:\\s*'([^']+)'");
if (!matcher.find())
throw new PluginImplementationException("Error parsing ReCaptcha response");
String reCaptcha_challenge = matcher.group(1);
String captchaImg = matcher.group(2) + "image?c=" + reCaptcha_challenge;
logger.info("Captcha URL: " + captchaImg);
String reCaptcha_response = getCaptchaSupport().getCaptcha(captchaImg);
if (reCaptcha_response == null)
throw new CaptchaEntryInputMismatchException();
method = getMethodBuilder()
.setAction("/get_file.php")
.setReferer(fileURL)
.setEncodePathAndQuery(true)
.setParameter("fid", fid)
.setParameter("challenge", reCaptcha_challenge)
.setParameter("response", reCaptcha_response)
.toGetMethod();
if (!makeRedirectedRequest(method))
throw new ServiceConnectionProblemException();
}
matcher = getMatcherAgainstContent("<form[^>]+action=\"([^\"]+)\"");
if (!matcher.find()) {
throw new PluginImplementationException("Cannot find download URL");
}
String finalDownloadUrl = matcher.group(1);
logger.info("Download URL: " + finalDownloadUrl);
method = getMethodBuilder().setReferer(getFileUrl).setAction(finalDownloadUrl).toGetMethod();
if (!tryDownloadAndSaveFile(method)) {
checkProblems();
throw new ServiceConnectionProblemException("Error starting download");
}
} else {
throw new ServiceConnectionProblemException();
}
}
private void checkNameAndSize(String content) throws Exception {
if (content.contains("file does not exist"))
throw new URLNotAvailableAnymoreException("Such file does not exist or it has been removed for infringement of copyrights");
Matcher matcher = getMatcherAgainstContent("File name: <b[^<>]*?>(.+?)</b>");
if (!matcher.find()) {
throw new PluginImplementationException("File name not found");
}
httpFile.setFileName(matcher.group(1));
matcher = getMatcherAgainstContent("File size: <b[^<>]*?>(.+?)</b>");
if (!matcher.find()) {
throw new PluginImplementationException("File size not found");
}
httpFile.setFileSize(PlugUtils.getFileSizeFromString(matcher.group(1)));
httpFile.setFileState(FileState.CHECKED_AND_EXISTING);
}
private void checkProblems() throws ErrorDuringDownloadingException {
Matcher matcher;
String content = getContentAsString();
if (content.contains("already downloading"))
throw new ServiceConnectionProblemException("Your IP is already downloading a file from our system. You cannot download more than one file in parallel.");
matcher = Pattern.compile("Try in\\s*([0-9]+) minute", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE).matcher(content);
if (matcher.find())
throw new YouHaveToWaitException("You used up your limit for file downloading!", Integer.parseInt(matcher.group(1)) * 60 + 20);
matcher = Pattern.compile("Try in\\s*([0-9]+) hour", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE).matcher(content);
if (matcher.find())
throw new YouHaveToWaitException("You used up your limit for file downloading!", Integer.parseInt(matcher.group(1)) * 60 * 60 + 20);
matcher = Pattern.compile("Please try in\\s*([0-9]+) minute", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE).matcher(content);
if (matcher.find())
throw new YouHaveToWaitException("You used up your limit for file downloading!", Integer.parseInt(matcher.group(1)) * 60 + 20);
matcher = Pattern.compile("Please try in\\s*([0-9]+) hour", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE).matcher(content);
if (matcher.find())
throw new YouHaveToWaitException("You used up your limit for file downloading!", Integer.parseInt(matcher.group(1)) * 60 * 60 + 20);
matcher = Pattern.compile("Please try in\\s*([0-9]+):([0-9]+) hour", Pattern.MULTILINE | Pattern.CASE_INSENSITIVE).matcher(content);
if (matcher.find())
throw new YouHaveToWaitException("You used up your limit for file downloading!", Integer.parseInt(matcher.group(1)) * 60 * 60 + Integer.parseInt(matcher.group(2)) * 60 + 20);
matcher = PlugUtils.matcher("slots[^<]*busy", content);
if (matcher.find())
throw new YouHaveToWaitException("All downloading slots for your country are busy", 60);
if (content.contains("file does not exist"))
throw new URLNotAvailableAnymoreException("Such file does not exist or it has been removed for infringement of copyrights");
}
private boolean checkIsFolder() {
return fileURL.contains("/folders/");
}
private void runFolder() throws Exception {
List<URI> queue = new LinkedList<URI>();
final GetMethod getMethod = getGetMethod(fileURL);
if (makeRedirectedRequest(getMethod)) {
Matcher matcher = getMatcherAgainstContent("<a[^>]+href=\"/folders/[^\\?]+\\?page=(\\d+)\"[^>]*>\\d+</a>\\s*<a[^>]+href=\"[^\\?]+\\?page=(\\d+)\">>>></a>");
int maxPageNumber = 1;
if (matcher.find())
maxPageNumber = Integer.parseInt(matcher.group(1));
for (int i = 1; i <= maxPageNumber; i++) {
if (i > 1) { // 1st page is already loaded - skip
GetMethod getPageMethod = getGetMethod(fileURL + "?page=" + i);
if (!makeRedirectedRequest(getPageMethod))
throw new ServiceConnectionProblemException();
}
matcher = getMatcherAgainstContent("<a\\s+href=\"(http://(www\\.)?depositfiles\\.com/([^/]{2}/)?files/[^\"]+)\"");
while (matcher.find())
queue.add(new URI(matcher.group(1)));
}
} else
throw new ServiceConnectionProblemException();
getPluginService().getPluginContext().getQueueSupport().addLinksToQueue(httpFile, queue);
httpFile.getProperties().put("removeCompleted", true);
}
}
| false | true | public void run() throws Exception {
super.run();
setLanguageEN();
if (checkIsFolder()) {
runFolder();
return;
}
HttpMethod method = getGetMethod(fileURL);
if (makeRedirectedRequest(method)) {
checkNameAndSize(getContentAsString());
checkProblems();
if (getContentAsString().contains("FREE downloading")) {
method = getMethodBuilder().setReferer(fileURL).setAction(fileURL).setParameter("free_btn", "FREE downloading").toPostMethod();
if (!makeRedirectedRequest(method)) {
throw new ServiceConnectionProblemException();
}
}
Matcher matcher = getMatcherAgainstContent("setTimeout\\s*\\(\\s*'load_form\\s*\\(\\s*fid\\s*,\\s*msg\\s*\\)\\s*'\\s*,\\s*(\\d+)\\s*\\)");
if (!matcher.find()) {
checkProblems();
throw new ServiceConnectionProblemException("Cannot find wait time");
}
int seconds = Integer.parseInt(matcher.group(1)) / 1000;
logger.info("wait - " + seconds);
matcher = getMatcherAgainstContent("<a href=\"(/get_file\\.php\\?fid=([^&]+)).*?\"[^>]*>");
if (!matcher.find()) {
throw new PluginImplementationException();
}
final String getFileUrl = matcher.group(1);
final String fid = matcher.group(2);
downloadTask.sleep(seconds + 5);
String reCaptchaUrl = "";
matcher = getMatcherAgainstContent("Recaptcha\\.create\\s*\\(\\s*'([^']+)'");
if (matcher.find())
reCaptchaUrl = "http://www.google.com/recaptcha/api/challenge?k=" + matcher.group(1) + "&ajax=1&cachestop=0." + System.currentTimeMillis();
method = getMethodBuilder().setReferer(fileURL).setAction(getFileUrl).toGetMethod();
if (!makeRedirectedRequest(method)) {
throw new ServiceConnectionProblemException();
}
while (PlugUtils.find("(?s)check_recaptcha\\s*\\(\\s*'" + fid + "'", getContentAsString())) {
logger.info("Captcha URL: " + reCaptchaUrl);
method = getGetMethod(reCaptchaUrl);
if (!makeRedirectedRequest(method))
throw new ServiceConnectionProblemException();
matcher = getMatcherAgainstContent("(?s)challenge\\s*:\\s*'([\\w-]+)'.*?server\\s*:\\s*'([^']+)'");
if (!matcher.find())
throw new PluginImplementationException("Error parsing ReCaptcha response");
String reCaptcha_challenge = matcher.group(1);
String captchaImg = matcher.group(2) + "image?c=" + reCaptcha_challenge;
logger.info("Captcha URL: " + captchaImg);
String reCaptcha_response = getCaptchaSupport().getCaptcha(captchaImg);
if (reCaptcha_response == null)
throw new CaptchaEntryInputMismatchException();
method = getMethodBuilder()
.setAction("/get_file.php")
.setReferer(fileURL)
.setEncodePathAndQuery(true)
.setParameter("fid", fid)
.setParameter("challenge", reCaptcha_challenge)
.setParameter("response", reCaptcha_response)
.toGetMethod();
if (!makeRedirectedRequest(method))
throw new ServiceConnectionProblemException();
}
matcher = getMatcherAgainstContent("<form[^>]+action=\"([^\"]+)\"");
if (!matcher.find()) {
throw new PluginImplementationException("Cannot find download URL");
}
String finalDownloadUrl = matcher.group(1);
logger.info("Download URL: " + finalDownloadUrl);
method = getMethodBuilder().setReferer(getFileUrl).setAction(finalDownloadUrl).toGetMethod();
if (!tryDownloadAndSaveFile(method)) {
checkProblems();
throw new ServiceConnectionProblemException("Error starting download");
}
} else {
throw new ServiceConnectionProblemException();
}
}
| public void run() throws Exception {
super.run();
setLanguageEN();
if (checkIsFolder()) {
runFolder();
return;
}
HttpMethod method = getGetMethod(fileURL);
if (makeRedirectedRequest(method)) {
checkNameAndSize(getContentAsString());
checkProblems();
method = getMethodBuilder().setReferer(fileURL).setAction(fileURL).setParameter("free_btn", "Regular downloading").toPostMethod();
if (!makeRedirectedRequest(method)) {
throw new ServiceConnectionProblemException();
}
Matcher matcher = getMatcherAgainstContent("setTimeout\\s*\\(\\s*'load_form\\s*\\(\\s*fid\\s*,\\s*msg\\s*\\)\\s*'\\s*,\\s*(\\d+)\\s*\\)");
if (!matcher.find()) {
checkProblems();
throw new ServiceConnectionProblemException("Cannot find wait time");
}
int seconds = Integer.parseInt(matcher.group(1)) / 1000;
logger.info("wait - " + seconds);
matcher = getMatcherAgainstContent("<a href=\"(/get_file\\.php\\?fid=([^&]+)).*?\"[^>]*>");
if (!matcher.find()) {
throw new PluginImplementationException();
}
final String getFileUrl = matcher.group(1);
final String fid = matcher.group(2);
downloadTask.sleep(seconds + 1);
String reCaptchaUrl = "";
matcher = getMatcherAgainstContent("Recaptcha\\.create\\s*\\(\\s*'([^']+)'");
if (matcher.find())
reCaptchaUrl = "http://www.google.com/recaptcha/api/challenge?k=" + matcher.group(1) + "&ajax=1&cachestop=0." + System.currentTimeMillis();
method = getMethodBuilder().setReferer(fileURL).setAction(getFileUrl).toGetMethod();
if (!makeRedirectedRequest(method)) {
throw new ServiceConnectionProblemException();
}
while (PlugUtils.find("(?s)check_recaptcha\\s*\\(\\s*'" + fid + "'", getContentAsString())) {
logger.info("Captcha URL: " + reCaptchaUrl);
method = getGetMethod(reCaptchaUrl);
if (!makeRedirectedRequest(method))
throw new ServiceConnectionProblemException();
matcher = getMatcherAgainstContent("(?s)challenge\\s*:\\s*'([\\w-]+)'.*?server\\s*:\\s*'([^']+)'");
if (!matcher.find())
throw new PluginImplementationException("Error parsing ReCaptcha response");
String reCaptcha_challenge = matcher.group(1);
String captchaImg = matcher.group(2) + "image?c=" + reCaptcha_challenge;
logger.info("Captcha URL: " + captchaImg);
String reCaptcha_response = getCaptchaSupport().getCaptcha(captchaImg);
if (reCaptcha_response == null)
throw new CaptchaEntryInputMismatchException();
method = getMethodBuilder()
.setAction("/get_file.php")
.setReferer(fileURL)
.setEncodePathAndQuery(true)
.setParameter("fid", fid)
.setParameter("challenge", reCaptcha_challenge)
.setParameter("response", reCaptcha_response)
.toGetMethod();
if (!makeRedirectedRequest(method))
throw new ServiceConnectionProblemException();
}
matcher = getMatcherAgainstContent("<form[^>]+action=\"([^\"]+)\"");
if (!matcher.find()) {
throw new PluginImplementationException("Cannot find download URL");
}
String finalDownloadUrl = matcher.group(1);
logger.info("Download URL: " + finalDownloadUrl);
method = getMethodBuilder().setReferer(getFileUrl).setAction(finalDownloadUrl).toGetMethod();
if (!tryDownloadAndSaveFile(method)) {
checkProblems();
throw new ServiceConnectionProblemException("Error starting download");
}
} else {
throw new ServiceConnectionProblemException();
}
}
|
diff --git a/src/main/java/org/riderzen/flume/sink/MongoSink.java b/src/main/java/org/riderzen/flume/sink/MongoSink.java
index 8b822f6..76f2c5e 100644
--- a/src/main/java/org/riderzen/flume/sink/MongoSink.java
+++ b/src/main/java/org/riderzen/flume/sink/MongoSink.java
@@ -1,219 +1,219 @@
package org.riderzen.flume.sink;
import com.mongodb.*;
import com.mongodb.util.JSON;
import org.apache.flume.*;
import org.apache.flume.conf.Configurable;
import org.apache.flume.sink.AbstractSink;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
/**
* User: guoqiang.li
* Date: 12-9-12
* Time: 下午3:31
*/
public class MongoSink extends AbstractSink implements Configurable {
private static Logger logger = LoggerFactory.getLogger(MongoSink.class);
public static final String HOST = "host";
public static final String PORT = "port";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static final String MODEL = "model";
public static final String DB_NAME = "db";
public static final String COLLECTION = "collection";
public static final String NAME_PREFIX = "MongSink_";
public static final String BATCH_SIZE = "batch";
public static final String AUTO_WRAP = "autoWrap";
private static final String WRAP_FIELD = "wrapField";
public static final String DEFAULT_HOST = "localhost";
public static final int DEFAULT_PORT = 27017;
public static final String DEFAULT_DB = "events";
public static final String DEFAULT_COLLECTION = "events";
public static final int DEFAULT_BATCH = 100;
private static final Boolean DEFAULT_AUTO_WRAP = false;
public static final String DEFAULT_WRAP_FIELD = "log";
private static AtomicInteger counter = new AtomicInteger();
private Mongo mongo;
private DB db;
private String host;
private int port;
private String username;
private String password;
private CollectionModel model;
private String dbName;
private String collectionName;
private int batchSize;
private boolean autoWrap;
private String wrapField;
@Override
public void configure(Context context) {
setName(NAME_PREFIX + counter.getAndIncrement());
host = context.getString(HOST, DEFAULT_HOST);
port = context.getInteger(PORT, DEFAULT_PORT);
username = context.getString(USERNAME);
password = context.getString(PASSWORD);
model = CollectionModel.valueOf(context.getString(MODEL, CollectionModel.single.name()));
dbName = context.getString(DB_NAME, DEFAULT_DB);
collectionName = context.getString(COLLECTION, DEFAULT_COLLECTION);
batchSize = context.getInteger(BATCH_SIZE, DEFAULT_BATCH);
autoWrap = context.getBoolean(AUTO_WRAP, DEFAULT_AUTO_WRAP);
wrapField = context.getString(WRAP_FIELD, DEFAULT_WRAP_FIELD);
logger.info("MongoSink {} context { host:{}, port:{}, username:{}, password:{}, model:{}, dbName:{}, collectionName:{}, batch: {} }",
new Object[]{getName(), host, port, username, password, model, dbName, collectionName, batchSize});
}
@Override
public synchronized void start() {
logger.info("Starting {}...", getName());
try {
mongo = new Mongo(host, port);
db = mongo.getDB(dbName);
} catch (UnknownHostException e) {
logger.error("Can't connect to mongoDB", e);
}
super.start();
logger.info("Started {}.", getName());
}
@Override
public Status process() throws EventDeliveryException {
logger.debug("{} start to process event", getName());
Status status = Status.READY;
try {
status = parseEvents();
} catch (Exception e) {
logger.error("can't process events", e);
}
logger.debug("{} processed event", getName());
return status;
}
private void saveEvents(Map<String, List<DBObject>> eventMap) {
if (eventMap.isEmpty()) {
logger.debug("eventMap is empty");
return;
}
for (String collectionName : eventMap.keySet()) {
List<DBObject> docs = eventMap.get(collectionName);
if (logger.isDebugEnabled()) {
logger.debug("collection: {}, length: {}", collectionName, docs.size());
}
//Warning: please change the WriteConcern level if you need high datum consistence.
CommandResult result = db.getCollection(collectionName).insert(docs, WriteConcern.NORMAL).getLastError();
if (result.ok()) {
String errorMessage = result.getErrorMessage();
if (errorMessage != null) {
logger.error("can't insert documents with error: {} ", errorMessage);
logger.error("with exception", result.getException());
throw new MongoException(errorMessage);
}
} else {
logger.error("can't get last error");
}
}
}
private Status parseEvents() throws EventDeliveryException {
Status status = Status.READY;
Channel channel = getChannel();
Transaction tx = null;
Map<String, List<DBObject>> eventMap = new HashMap<String, List<DBObject>>();
try {
tx = channel.getTransaction();
tx.begin();
for (int i = 0; i < batchSize; i++) {
Event event = channel.take();
if (event == null) {
status = Status.BACKOFF;
break;
} else {
switch (model) {
case single:
if (!eventMap.containsKey(collectionName)) {
eventMap.put(collectionName, new ArrayList<DBObject>());
}
List<DBObject> docs = eventMap.get(collectionName);
addEventToList(docs, event);
break;
case dynamic:
Map<String, String> headers = event.getHeaders();
String dynamicCollection = headers.get(COLLECTION);
if (!eventMap.containsKey(dynamicCollection)) {
eventMap.put(dynamicCollection, new ArrayList<DBObject>());
}
List<DBObject> documents = eventMap.get(dynamicCollection);
addEventToList(documents, event);
break;
default:
logger.error("can't support model: {}, please check configuration.", model);
}
}
}
if (!eventMap.isEmpty()) {
saveEvents(eventMap);
}
tx.commit();
} catch (Exception e) {
- logger.error("can't process events", e);
+ logger.error("can't process events, drop it!", e);
if (tx != null) {
- tx.rollback();
+ tx.commit();// commit to drop bad event, otherwise it will enter dead loop.
}
throw new EventDeliveryException(e);
} finally {
if (tx != null) {
tx.close();
}
}
return status;
}
private List<DBObject> addEventToList(List<DBObject> documents, Event event) {
if (documents == null) {
documents = new ArrayList<DBObject>(batchSize);
}
DBObject eventJson;
if (autoWrap) {
eventJson = new BasicDBObject(wrapField, new String(event.getBody()));
} else {
eventJson = (DBObject) JSON.parse(new String(event.getBody()));
}
documents.add(eventJson);
return documents;
}
public static enum CollectionModel {
dynamic, single
}
}
| false | true | private Status parseEvents() throws EventDeliveryException {
Status status = Status.READY;
Channel channel = getChannel();
Transaction tx = null;
Map<String, List<DBObject>> eventMap = new HashMap<String, List<DBObject>>();
try {
tx = channel.getTransaction();
tx.begin();
for (int i = 0; i < batchSize; i++) {
Event event = channel.take();
if (event == null) {
status = Status.BACKOFF;
break;
} else {
switch (model) {
case single:
if (!eventMap.containsKey(collectionName)) {
eventMap.put(collectionName, new ArrayList<DBObject>());
}
List<DBObject> docs = eventMap.get(collectionName);
addEventToList(docs, event);
break;
case dynamic:
Map<String, String> headers = event.getHeaders();
String dynamicCollection = headers.get(COLLECTION);
if (!eventMap.containsKey(dynamicCollection)) {
eventMap.put(dynamicCollection, new ArrayList<DBObject>());
}
List<DBObject> documents = eventMap.get(dynamicCollection);
addEventToList(documents, event);
break;
default:
logger.error("can't support model: {}, please check configuration.", model);
}
}
}
if (!eventMap.isEmpty()) {
saveEvents(eventMap);
}
tx.commit();
} catch (Exception e) {
logger.error("can't process events", e);
if (tx != null) {
tx.rollback();
}
throw new EventDeliveryException(e);
} finally {
if (tx != null) {
tx.close();
}
}
return status;
}
| private Status parseEvents() throws EventDeliveryException {
Status status = Status.READY;
Channel channel = getChannel();
Transaction tx = null;
Map<String, List<DBObject>> eventMap = new HashMap<String, List<DBObject>>();
try {
tx = channel.getTransaction();
tx.begin();
for (int i = 0; i < batchSize; i++) {
Event event = channel.take();
if (event == null) {
status = Status.BACKOFF;
break;
} else {
switch (model) {
case single:
if (!eventMap.containsKey(collectionName)) {
eventMap.put(collectionName, new ArrayList<DBObject>());
}
List<DBObject> docs = eventMap.get(collectionName);
addEventToList(docs, event);
break;
case dynamic:
Map<String, String> headers = event.getHeaders();
String dynamicCollection = headers.get(COLLECTION);
if (!eventMap.containsKey(dynamicCollection)) {
eventMap.put(dynamicCollection, new ArrayList<DBObject>());
}
List<DBObject> documents = eventMap.get(dynamicCollection);
addEventToList(documents, event);
break;
default:
logger.error("can't support model: {}, please check configuration.", model);
}
}
}
if (!eventMap.isEmpty()) {
saveEvents(eventMap);
}
tx.commit();
} catch (Exception e) {
logger.error("can't process events, drop it!", e);
if (tx != null) {
tx.commit();// commit to drop bad event, otherwise it will enter dead loop.
}
throw new EventDeliveryException(e);
} finally {
if (tx != null) {
tx.close();
}
}
return status;
}
|
diff --git a/src/groupone/SelectCoupon.java b/src/groupone/SelectCoupon.java
index 4bfee55..ac8770b 100644
--- a/src/groupone/SelectCoupon.java
+++ b/src/groupone/SelectCoupon.java
@@ -1,60 +1,63 @@
package groupone;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class CouponSelect
*/
@WebServlet("/SelectCoupon")
public class SelectCoupon extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SelectCoupon() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String[] couponIds = request.getParameterValues("checkBox");
String gift = request.getParameter("gift");
if(couponIds != null) {
ArrayList<Coupon> coupons = DBOperation.searchCoupon(couponIds);
String objectId = UUID.randomUUID().toString();
String objectId2 = UUID.randomUUID().toString();
request.getSession().setAttribute(objectId, couponIds);
request.getSession().setAttribute(objectId2, coupons);
request.setAttribute("objectId", objectId);
request.setAttribute("objectId2", objectId2);
request.setAttribute("coupons", coupons);
request.setAttribute("gift", gift);
request.getRequestDispatcher("/page_checkOut.jsp").forward(request, response);
}
+ else {
+ request.getRequestDispatcher("/page_browse.jsp").forward(request, response);
+ }
}
}
| true | true | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String[] couponIds = request.getParameterValues("checkBox");
String gift = request.getParameter("gift");
if(couponIds != null) {
ArrayList<Coupon> coupons = DBOperation.searchCoupon(couponIds);
String objectId = UUID.randomUUID().toString();
String objectId2 = UUID.randomUUID().toString();
request.getSession().setAttribute(objectId, couponIds);
request.getSession().setAttribute(objectId2, coupons);
request.setAttribute("objectId", objectId);
request.setAttribute("objectId2", objectId2);
request.setAttribute("coupons", coupons);
request.setAttribute("gift", gift);
request.getRequestDispatcher("/page_checkOut.jsp").forward(request, response);
}
}
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String[] couponIds = request.getParameterValues("checkBox");
String gift = request.getParameter("gift");
if(couponIds != null) {
ArrayList<Coupon> coupons = DBOperation.searchCoupon(couponIds);
String objectId = UUID.randomUUID().toString();
String objectId2 = UUID.randomUUID().toString();
request.getSession().setAttribute(objectId, couponIds);
request.getSession().setAttribute(objectId2, coupons);
request.setAttribute("objectId", objectId);
request.setAttribute("objectId2", objectId2);
request.setAttribute("coupons", coupons);
request.setAttribute("gift", gift);
request.getRequestDispatcher("/page_checkOut.jsp").forward(request, response);
}
else {
request.getRequestDispatcher("/page_browse.jsp").forward(request, response);
}
}
|
diff --git a/ngrinder-controller/src/main/java/org/ngrinder/security/NgrinderUsernamePasswordAuthenticationFilter.java b/ngrinder-controller/src/main/java/org/ngrinder/security/NgrinderUsernamePasswordAuthenticationFilter.java
index 2f62277c..c06b402f 100644
--- a/ngrinder-controller/src/main/java/org/ngrinder/security/NgrinderUsernamePasswordAuthenticationFilter.java
+++ b/ngrinder-controller/src/main/java/org/ngrinder/security/NgrinderUsernamePasswordAuthenticationFilter.java
@@ -1,64 +1,64 @@
/*
* Copyright (C) 2012 - 2012 NHN Corporation
* All rights reserved.
*
* This file is part of The nGrinder software distribution. Refer to
* the file LICENSE which is part of The nGrinder distribution for
* licensing details. The nGrinder distribution is available on the
* Internet at http://nhnopensource.org/ngrinder
*
* 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 HOLDERS 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 org.ngrinder.security;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
public class NgrinderUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
public NgrinderUsernamePasswordAuthenticationFilter() {
super();
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
Authentication auth = super.attemptAuthentication(request, response);
String timezone = (String) request.getParameter("user_locale");
String language = (String) request.getParameter("native_language");
SecuredUser user = (SecuredUser) auth.getPrincipal();
- user.setTimezone(timezone);
+ user.getUser().setTimeZone(timezone);
user.getUser().setUserLanguage(language);
return auth;
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
javax.servlet.FilterChain chain, Authentication authResult) throws IOException, ServletException {
super.successfulAuthentication(request, response, chain, authResult);
};
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) throws IOException, ServletException {
super.unsuccessfulAuthentication(request, response, failed);
}
}
| true | true | public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
Authentication auth = super.attemptAuthentication(request, response);
String timezone = (String) request.getParameter("user_locale");
String language = (String) request.getParameter("native_language");
SecuredUser user = (SecuredUser) auth.getPrincipal();
user.setTimezone(timezone);
user.getUser().setUserLanguage(language);
return auth;
}
| public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
Authentication auth = super.attemptAuthentication(request, response);
String timezone = (String) request.getParameter("user_locale");
String language = (String) request.getParameter("native_language");
SecuredUser user = (SecuredUser) auth.getPrincipal();
user.getUser().setTimeZone(timezone);
user.getUser().setUserLanguage(language);
return auth;
}
|
diff --git a/Harvester/branches/Development/src/main/java/org/vivoweb/harvester/update/ChangeNamespace.java b/Harvester/branches/Development/src/main/java/org/vivoweb/harvester/update/ChangeNamespace.java
index 3fc72542..83a969ea 100644
--- a/Harvester/branches/Development/src/main/java/org/vivoweb/harvester/update/ChangeNamespace.java
+++ b/Harvester/branches/Development/src/main/java/org/vivoweb/harvester/update/ChangeNamespace.java
@@ -1,298 +1,298 @@
/*******************************************************************************
* Copyright (c) 2010 Christopher Haines, Dale Scheppler, Nicholas Skaggs, Stephen V. Williams, James Pence. 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, James Pence - initial API and implementation
******************************************************************************/
package org.vivoweb.harvester.update;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.xml.parsers.ParserConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vivoweb.harvester.util.InitLog;
import org.vivoweb.harvester.util.IterableAdaptor;
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.repo.JenaConnect;
import org.xml.sax.SAXException;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.rdf.model.Property;
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.sparql.util.StringUtils;
import com.hp.hpl.jena.util.ResourceUtils;
/**
* Changes the namespace for all matching uris
* @author Christopher Haines ([email protected])
*/
public class ChangeNamespace {
/**
* SLF4J Logger
*/
private static Logger log = LoggerFactory.getLogger(ChangeNamespace.class);
/**
* The model to change uris in
*/
private JenaConnect model;
/**
* The old namespace
*/
private String oldNamespace;
/**
* The new namespace
*/
private String newNamespace;
/**
* the propeties to match on
*/
private List<Property> properties;
/**
* The search model
*/
private JenaConnect vivo;
/**
* Constructor
* @param argList parsed argument list
* @throws IOException error reading config
* @throws SAXException error parsing config
* @throws ParserConfigurationException error parsing config
*/
public ChangeNamespace(ArgList argList) throws ParserConfigurationException, SAXException, IOException {
this.model = JenaConnect.parseConfig(argList.get("i"), argList.getProperties("I"));
this.vivo = JenaConnect.parseConfig(argList.get("v"), argList.getProperties("V"));
this.oldNamespace = argList.get("o");
this.newNamespace = argList.get("n");
List<String> predicates = argList.getAll("p");
this.properties = new ArrayList<Property>(predicates.size());
for(String pred : predicates) {
this.properties.add(ResourceFactory.createProperty(pred));
}
}
/**
* Get either a matching uri from the given model or an unused uri
* @param current the current resource
* @param namespace the namespace to match in
* @param properties the propeties to match on
* @param vivo the model to match in
* @param model models to check for duplicates
* @return the uri of the first matched resource or an unused uri if none found
*/
public static String getURI(Resource current, String namespace, List<Property> properties, JenaConnect vivo, JenaConnect model) {
String uri = null;
String matchURI = null;
if (properties != null && !properties.isEmpty()) {
matchURI = getMatchingURI(current, namespace, properties, vivo);
}
if (matchURI != null) {
uri = matchURI;
} else {
uri = getUnusedURI(namespace, vivo, model);
}
log.debug("Using URI: <"+uri+">");
return uri;
}
/**
* Gets an unused URI in the the given namespace for the given models
* @param namespace the namespace
* @param vivo primary model to check in
* @param models additional models to check in
* @return the uri
* @throws IllegalArgumentException empty namespace
*/
public static String getUnusedURI(String namespace, JenaConnect vivo, JenaConnect... models) throws IllegalArgumentException {
if(namespace == null || namespace.equals("")) {
throw new IllegalArgumentException("namespace cannot be empty");
}
String uri = null;
Random random = new Random();
while(uri == null) {
uri = namespace + "n" + random.nextInt(Integer.MAX_VALUE);
if(vivo.containsURI(uri)) {
uri = null;
}
for(JenaConnect model : models) {
if(model.containsURI(uri)) {
uri = null;
}
}
}
log.debug("Using new URI: <"+uri+">");
return uri;
}
/**
* Matches the current resource to a resource in the given namespace in the given model based on the given properties
* @param current the current resource
* @param namespace the namespace to match in
* @param properties the propeties to match on
* @param vivo the model to match in
* @return the uri of the first matched resource or null if none found
*/
public static String getMatchingURI(Resource current, String namespace, List<Property> properties, JenaConnect vivo) {
List<String> uris = getMatchingURIs(current, namespace, properties, vivo);
String uri = uris.isEmpty()?null:uris.get(0);
log.debug("Matched URI: <"+uri+">");
return uri;
}
/**
* Matches the current resource to resources in the given namespace in the given model based on the given properties
* @param current the current resource
* @param namespace the namespace to match in
* @param properties the propeties to match on
* @param vivo the model to match in
* @return the uris of the matched resources (empty set if none found)
*/
public static List<String> getMatchingURIs(Resource current, String namespace, List<Property> properties, JenaConnect vivo) {
StringBuilder sbQuery = new StringBuilder();
ArrayList<String> filters = new ArrayList<String>();
int valueCount = 0;
sbQuery.append("SELECT ?uri\nWHERE\n{");
for(Property p : properties) {
for(Statement s : IterableAdaptor.adapt(current.listProperties(p))) {
sbQuery.append("\t?uri <");
sbQuery.append(p.getURI());
sbQuery.append("> ");
if(s.getObject().isResource()) {
sbQuery.append("<");
sbQuery.append(s.getObject().asResource().getURI());
sbQuery.append(">");
} else {
filters.add("( str(?value"+valueCount+") = \""+s.getObject().asLiteral().getValue().toString()+"\" )");
sbQuery.append("?value");
sbQuery.append(valueCount);
valueCount++;
}
sbQuery.append(" .\n");
}
}
- sbQuery.append("\tFILTER (");
// sbQuery.append("regex( ?uri , \"");
// sbQuery.append(namespace);
// sbQuery.append("\" )");
if(!filters.isEmpty()) {
+ sbQuery.append("\tFILTER (");
// sbQuery.append(" && ");
sbQuery.append(StringUtils.join(" && ", filters));
}
sbQuery.append(")\n}");
ArrayList<String> retVal = new ArrayList<String>();
int count = 0;
log.debug("Query:\n"+sbQuery.toString());
log.debug("namespace: "+namespace);
for(QuerySolution qs : IterableAdaptor.adapt(vivo.executeQuery(sbQuery.toString()))) {
Resource res = qs.getResource("uri");
if(res.getNameSpace().equals(namespace)) {
String uri = res.getURI();
retVal.add(uri);
log.debug("Matched URI["+count+"]: <"+uri+">");
count++;
}
}
return retVal;
}
/**
* Changes the namespace for all matching uris
* @param model the model to change namespaces for
* @param vivo the model to search for uris in
* @param oldNamespace the old namespace
* @param newNamespace the new namespace
* @param properties the propeties to match on
* @throws IllegalArgumentException empty namespace
*/
public static void changeNS(JenaConnect model, JenaConnect vivo, String oldNamespace, String newNamespace, List<Property> properties) throws IllegalArgumentException {
if(oldNamespace == null || oldNamespace.equals("")) {
throw new IllegalArgumentException("old namespace cannot be empty");
}
if(newNamespace == null || newNamespace.equals("")) {
throw new IllegalArgumentException("new namespace cannot be empty");
}
if(oldNamespace.equals(newNamespace)) {
return;
}
ArrayList<String> uriCheck = new ArrayList<String>();
int count = 0;
for(Resource res : IterableAdaptor.adapt(model.getJenaModel().listSubjects())) {
if(oldNamespace.equals(res.getNameSpace())) {
log.debug("Finding match for <"+res.getURI()+">");
String uri = null;
boolean uriFound = false;
//find valid URI
while (!uriFound) {
uri = getURI(res, newNamespace, properties, vivo, model);
log.trace("urlCheck: "+uriCheck.contains(uri));
//if matched in VIVO or not previously used
if (vivo.containsURI(uri) || !uriCheck.contains(uri)) {
//note URI as being used
uriCheck.add(uri);
//use this URI
uriFound = true;
}
}
ResourceUtils.renameResource(res, uri);
count++;
}
}
log.info("Changed namespace for "+count+" rdf nodes");
}
/**
* Change namespace
*/
private void execute() {
changeNS(this.model, this.vivo, this.oldNamespace, this.newNamespace, this.properties);
}
/**
* Get the ArgParser for this task
* @return the ArgParser
*/
private static ArgParser getParser() {
ArgParser parser = new ArgParser("ChangeNamespace");
// Inputs
parser.addArgument(new ArgDef().setShortOption('i').setLongOpt("inputModel").withParameter(true, "CONFIG_FILE").setDescription("config file for input jena model").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('I').setLongOpt("inputModelOverride").withParameterProperties("JENA_PARAM", "VALUE").setDescription("override the JENA_PARAM of input jena model config using VALUE").setRequired(false));
parser.addArgument(new ArgDef().setShortOption('v').setLongOpt("vivoModel").withParameter(true, "CONFIG_FILE").setDescription("config file for vivo jena model").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('V').setLongOpt("vivoModelOverride").withParameterProperties("JENA_PARAM", "VALUE").setDescription("override the JENA_PARAM of vivo jena model config using VALUE").setRequired(false));
// Params
parser.addArgument(new ArgDef().setShortOption('o').setLongOpt("oldNamespace").withParameter(true, "OLD_NAMESPACE").setDescription("The old namespace").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('n').setLongOpt("newNamespace").withParameter(true, "NEW_NAMESPACE").setDescription("The new namespace").setRequired(true));
parser.addArgument(new ArgDef().setShortOption('p').setLongOpt("predicate").withParameters(true, "MATCH_PREDICATE").setDescription("Predicate to match on").setRequired(true));
return parser;
}
/**
* Main method
* @param args commandline arguments
*/
public static void main(String... args) {
InitLog.initLogger(ChangeNamespace.class);
log.info(getParser().getAppName()+": Start");
try {
new ChangeNamespace(new ArgList(getParser(), args)).execute();
} catch(IllegalArgumentException e) {
log.error(e.getMessage());
System.out.println(getParser().getUsage());
} catch(IOException e) {
log.error(e.getMessage(), e);
// System.out.println(getParser().getUsage());
} catch(Exception e) {
log.error(e.getMessage(), e);
}
log.info(getParser().getAppName()+": End");
}
}
| false | true | public static List<String> getMatchingURIs(Resource current, String namespace, List<Property> properties, JenaConnect vivo) {
StringBuilder sbQuery = new StringBuilder();
ArrayList<String> filters = new ArrayList<String>();
int valueCount = 0;
sbQuery.append("SELECT ?uri\nWHERE\n{");
for(Property p : properties) {
for(Statement s : IterableAdaptor.adapt(current.listProperties(p))) {
sbQuery.append("\t?uri <");
sbQuery.append(p.getURI());
sbQuery.append("> ");
if(s.getObject().isResource()) {
sbQuery.append("<");
sbQuery.append(s.getObject().asResource().getURI());
sbQuery.append(">");
} else {
filters.add("( str(?value"+valueCount+") = \""+s.getObject().asLiteral().getValue().toString()+"\" )");
sbQuery.append("?value");
sbQuery.append(valueCount);
valueCount++;
}
sbQuery.append(" .\n");
}
}
sbQuery.append("\tFILTER (");
// sbQuery.append("regex( ?uri , \"");
// sbQuery.append(namespace);
// sbQuery.append("\" )");
if(!filters.isEmpty()) {
// sbQuery.append(" && ");
sbQuery.append(StringUtils.join(" && ", filters));
}
sbQuery.append(")\n}");
ArrayList<String> retVal = new ArrayList<String>();
int count = 0;
log.debug("Query:\n"+sbQuery.toString());
log.debug("namespace: "+namespace);
for(QuerySolution qs : IterableAdaptor.adapt(vivo.executeQuery(sbQuery.toString()))) {
Resource res = qs.getResource("uri");
if(res.getNameSpace().equals(namespace)) {
String uri = res.getURI();
retVal.add(uri);
log.debug("Matched URI["+count+"]: <"+uri+">");
count++;
}
}
return retVal;
}
| public static List<String> getMatchingURIs(Resource current, String namespace, List<Property> properties, JenaConnect vivo) {
StringBuilder sbQuery = new StringBuilder();
ArrayList<String> filters = new ArrayList<String>();
int valueCount = 0;
sbQuery.append("SELECT ?uri\nWHERE\n{");
for(Property p : properties) {
for(Statement s : IterableAdaptor.adapt(current.listProperties(p))) {
sbQuery.append("\t?uri <");
sbQuery.append(p.getURI());
sbQuery.append("> ");
if(s.getObject().isResource()) {
sbQuery.append("<");
sbQuery.append(s.getObject().asResource().getURI());
sbQuery.append(">");
} else {
filters.add("( str(?value"+valueCount+") = \""+s.getObject().asLiteral().getValue().toString()+"\" )");
sbQuery.append("?value");
sbQuery.append(valueCount);
valueCount++;
}
sbQuery.append(" .\n");
}
}
// sbQuery.append("regex( ?uri , \"");
// sbQuery.append(namespace);
// sbQuery.append("\" )");
if(!filters.isEmpty()) {
sbQuery.append("\tFILTER (");
// sbQuery.append(" && ");
sbQuery.append(StringUtils.join(" && ", filters));
}
sbQuery.append(")\n}");
ArrayList<String> retVal = new ArrayList<String>();
int count = 0;
log.debug("Query:\n"+sbQuery.toString());
log.debug("namespace: "+namespace);
for(QuerySolution qs : IterableAdaptor.adapt(vivo.executeQuery(sbQuery.toString()))) {
Resource res = qs.getResource("uri");
if(res.getNameSpace().equals(namespace)) {
String uri = res.getURI();
retVal.add(uri);
log.debug("Matched URI["+count+"]: <"+uri+">");
count++;
}
}
return retVal;
}
|
diff --git a/workspace/Angr/src/fi/hbp/angr/screens/GameScreen.java b/workspace/Angr/src/fi/hbp/angr/screens/GameScreen.java
index 82df2e6..e23a760 100644
--- a/workspace/Angr/src/fi/hbp/angr/screens/GameScreen.java
+++ b/workspace/Angr/src/fi/hbp/angr/screens/GameScreen.java
@@ -1,107 +1,109 @@
package fi.hbp.angr.screens;
import java.util.Iterator;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import fi.hbp.angr.G;
import fi.hbp.angr.GameStage;
import fi.hbp.angr.Preloadable;
import fi.hbp.angr.models.BodyFactory;
import fi.hbp.angr.models.Grenade;
import fi.hbp.angr.models.Level;
public class GameScreen implements Screen, Preloadable {
private World world;
private Stage stage;
private String levelName;
private BodyFactory bdf;
public GameScreen(String levelName) {
this.levelName = levelName;
}
@Override
public void preload() {
G.preloadTextures.add("data/" + levelName + ".png");
BodyFactory.preload();
Iterator<String> it = G.preloadTextures.iterator();
while (it.hasNext()) {
G.getAssetManager().load(it.next(), Texture.class);
}
}
@Override
public void unload() {
// TODO Iterate and remove from list
G.getAssetManager().unload("data/" + levelName + ".png");
}
@Override
public void render(float delta) {
world.step(Gdx.app.getGraphics().getDeltaTime(), 10, 10);
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
stage.act(delta);
stage.draw();
}
@Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void show() {
world = new World(new Vector2(0, -8), true);
- stage = new GameStage(2500, 2500, false, world);
+ int xsize = Gdx.graphics.getWidth() * 4;
+ int ysize = Gdx.graphics.getHeight() * 4;
+ stage = new GameStage(xsize, ysize, false, world);
Gdx.input.setInputProcessor(stage);
// Add map/level actor
Level level = new Level(levelName, world);
stage.addActor(level);
// Add player
bdf = new BodyFactory();
Actor grenade = bdf.createGrenade(world, 1000, 1500, 0);
stage.addActor(grenade);
Actor grenade2 = bdf.createGrenade(world, 1000, 1000, 90);
((Grenade)grenade2).body.setLinearVelocity(new Vector2(0, 100));
stage.addActor(grenade2);
}
@Override
public void hide() {
// TODO Auto-generated method stub
}
@Override
public void pause() {
// TODO Auto-generated method stub
}
@Override
public void resume() {
// TODO Auto-generated method stub
}
@Override
public void dispose() {
stage.dispose();
this.unload();
}
}
| true | true | public void show() {
world = new World(new Vector2(0, -8), true);
stage = new GameStage(2500, 2500, false, world);
Gdx.input.setInputProcessor(stage);
// Add map/level actor
Level level = new Level(levelName, world);
stage.addActor(level);
// Add player
bdf = new BodyFactory();
Actor grenade = bdf.createGrenade(world, 1000, 1500, 0);
stage.addActor(grenade);
Actor grenade2 = bdf.createGrenade(world, 1000, 1000, 90);
((Grenade)grenade2).body.setLinearVelocity(new Vector2(0, 100));
stage.addActor(grenade2);
}
| public void show() {
world = new World(new Vector2(0, -8), true);
int xsize = Gdx.graphics.getWidth() * 4;
int ysize = Gdx.graphics.getHeight() * 4;
stage = new GameStage(xsize, ysize, false, world);
Gdx.input.setInputProcessor(stage);
// Add map/level actor
Level level = new Level(levelName, world);
stage.addActor(level);
// Add player
bdf = new BodyFactory();
Actor grenade = bdf.createGrenade(world, 1000, 1500, 0);
stage.addActor(grenade);
Actor grenade2 = bdf.createGrenade(world, 1000, 1000, 90);
((Grenade)grenade2).body.setLinearVelocity(new Vector2(0, 100));
stage.addActor(grenade2);
}
|
diff --git a/enunciate/amf/src/main/java/org/codehaus/enunciate/modules/amf/AccessorOverridesAnotherMethod.java b/enunciate/amf/src/main/java/org/codehaus/enunciate/modules/amf/AccessorOverridesAnotherMethod.java
index dc20f003..a50af989 100644
--- a/enunciate/amf/src/main/java/org/codehaus/enunciate/modules/amf/AccessorOverridesAnotherMethod.java
+++ b/enunciate/amf/src/main/java/org/codehaus/enunciate/modules/amf/AccessorOverridesAnotherMethod.java
@@ -1,73 +1,74 @@
/*
* Copyright 2006-2008 Web Cohesion
*
* 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.enunciate.modules.amf;
import com.sun.mirror.declaration.ClassDeclaration;
import com.sun.mirror.declaration.TypeDeclaration;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import net.sf.jelly.apt.freemarker.FreemarkerModel;
import org.codehaus.enunciate.apt.EnunciateFreemarkerModel;
import org.codehaus.enunciate.contract.jaxb.Accessor;
import org.codehaus.enunciate.contract.jaxb.TypeDefinition;
import java.util.ArrayList;
import java.util.List;
/**
* @author Ryan Heaton
*/
public class AccessorOverridesAnotherMethod implements TemplateMethodModelEx {
public Object exec(List list) throws TemplateModelException {
if (list.size() < 1) {
throw new TemplateModelException("The accessorOverridesAnother method must have the accessor as a parameter.");
}
TemplateModel from = (TemplateModel) list.get(0);
Object unwrapped = BeansWrapper.getDefaultInstance().unwrap(from);
if (!(unwrapped instanceof Accessor)) {
throw new TemplateModelException("The accessorOverridesAnother method must have the accessor as a parameter.");
}
String name = ((Accessor) unwrapped).getSimpleName();
EnunciateFreemarkerModel model = (EnunciateFreemarkerModel) FreemarkerModel.get();
TypeDeclaration declaringType = ((Accessor) unwrapped).getDeclaringType();
if (declaringType instanceof ClassDeclaration) {
declaringType = ((ClassDeclaration) declaringType).getSuperclass().getDeclaration();
while (declaringType instanceof ClassDeclaration && !Object.class.getName().equals(declaringType.getQualifiedName())) {
TypeDefinition typeDef = model.findTypeDefinition((ClassDeclaration) declaringType);
if (typeDef != null) {
ArrayList<Accessor> accessors = new ArrayList<Accessor>();
accessors.addAll(typeDef.getAttributes());
accessors.add(typeDef.getValue());
accessors.addAll(typeDef.getElements());
for (Accessor accessor : accessors) {
if (accessor != null && name.equals(accessor.getName())) {
return Boolean.TRUE;
}
}
}
+ declaringType = ((ClassDeclaration) declaringType).getSuperclass().getDeclaration();
}
}
return Boolean.FALSE;
}
}
| true | true | public Object exec(List list) throws TemplateModelException {
if (list.size() < 1) {
throw new TemplateModelException("The accessorOverridesAnother method must have the accessor as a parameter.");
}
TemplateModel from = (TemplateModel) list.get(0);
Object unwrapped = BeansWrapper.getDefaultInstance().unwrap(from);
if (!(unwrapped instanceof Accessor)) {
throw new TemplateModelException("The accessorOverridesAnother method must have the accessor as a parameter.");
}
String name = ((Accessor) unwrapped).getSimpleName();
EnunciateFreemarkerModel model = (EnunciateFreemarkerModel) FreemarkerModel.get();
TypeDeclaration declaringType = ((Accessor) unwrapped).getDeclaringType();
if (declaringType instanceof ClassDeclaration) {
declaringType = ((ClassDeclaration) declaringType).getSuperclass().getDeclaration();
while (declaringType instanceof ClassDeclaration && !Object.class.getName().equals(declaringType.getQualifiedName())) {
TypeDefinition typeDef = model.findTypeDefinition((ClassDeclaration) declaringType);
if (typeDef != null) {
ArrayList<Accessor> accessors = new ArrayList<Accessor>();
accessors.addAll(typeDef.getAttributes());
accessors.add(typeDef.getValue());
accessors.addAll(typeDef.getElements());
for (Accessor accessor : accessors) {
if (accessor != null && name.equals(accessor.getName())) {
return Boolean.TRUE;
}
}
}
}
}
return Boolean.FALSE;
}
| public Object exec(List list) throws TemplateModelException {
if (list.size() < 1) {
throw new TemplateModelException("The accessorOverridesAnother method must have the accessor as a parameter.");
}
TemplateModel from = (TemplateModel) list.get(0);
Object unwrapped = BeansWrapper.getDefaultInstance().unwrap(from);
if (!(unwrapped instanceof Accessor)) {
throw new TemplateModelException("The accessorOverridesAnother method must have the accessor as a parameter.");
}
String name = ((Accessor) unwrapped).getSimpleName();
EnunciateFreemarkerModel model = (EnunciateFreemarkerModel) FreemarkerModel.get();
TypeDeclaration declaringType = ((Accessor) unwrapped).getDeclaringType();
if (declaringType instanceof ClassDeclaration) {
declaringType = ((ClassDeclaration) declaringType).getSuperclass().getDeclaration();
while (declaringType instanceof ClassDeclaration && !Object.class.getName().equals(declaringType.getQualifiedName())) {
TypeDefinition typeDef = model.findTypeDefinition((ClassDeclaration) declaringType);
if (typeDef != null) {
ArrayList<Accessor> accessors = new ArrayList<Accessor>();
accessors.addAll(typeDef.getAttributes());
accessors.add(typeDef.getValue());
accessors.addAll(typeDef.getElements());
for (Accessor accessor : accessors) {
if (accessor != null && name.equals(accessor.getName())) {
return Boolean.TRUE;
}
}
}
declaringType = ((ClassDeclaration) declaringType).getSuperclass().getDeclaration();
}
}
return Boolean.FALSE;
}
|
diff --git a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ConfigureProjectWizard.java b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ConfigureProjectWizard.java
index 6a7e7e521..b1414ebe8 100644
--- a/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ConfigureProjectWizard.java
+++ b/bundles/org.eclipse.team.ui/src/org/eclipse/team/internal/ui/wizards/ConfigureProjectWizard.java
@@ -1,255 +1,255 @@
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.team.internal.ui.wizards;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.*;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.team.internal.ui.*;
import org.eclipse.team.ui.IConfigurationWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.activities.IActivityManager;
import org.eclipse.ui.activities.IIdentifier;
import org.eclipse.ui.model.AdaptableList;
/**
* The wizard for associating projects with team providers
*/
public class ConfigureProjectWizard extends Wizard implements IConfigurationWizard {
protected IWorkbench workbench;
protected IProject project;
protected IConfigurationWizard wizard;
protected ConfigureProjectWizardMainPage mainPage;
private String pluginId = TeamUIPlugin.PLUGIN_ID;
protected final static String PT_CONFIGURATION ="configurationWizards"; //$NON-NLS-1$
protected final static String TAG_WIZARD = "wizard"; //$NON-NLS-1$
protected final static String TAG_DESCRIPTION = "description"; //$NON-NLS-1$
protected final static String ATT_NAME = "name"; //$NON-NLS-1$
protected final static String ATT_CLASS = "class"; //$NON-NLS-1$
protected final static String ATT_ICON = "icon"; //$NON-NLS-1$
protected final static String ATT_ID = "id"; //$NON-NLS-1$
public ConfigureProjectWizard() {
setNeedsProgressMonitor(true);
setWindowTitle(getWizardWindowTitle()); //$NON-NLS-1$
}
protected String getExtensionPoint() {
return PT_CONFIGURATION;
}
protected String getWizardWindowTitle() {
return Policy.bind("ConfigureProjectWizard.title"); //$NON-NLS-1$
}
protected String getWizardLabel() {
return Policy.bind("ConfigureProjectWizard.configureProject"); //$NON-NLS-1$
}
protected String getWizardDescription() {
return Policy.bind("ConfigureProjectWizard.description"); //$NON-NLS-1$
}
/*
* @see Wizard#addPages
*/
public void addPages() {
AdaptableList disabledWizards = new AdaptableList();
AdaptableList wizards = getAvailableWizards(disabledWizards);
- if (wizards.size() == 1) {
+ if (wizards.size() == 1 && disabledWizards.size() == 0) {
// If there is only one wizard, skip the first page.
// Only skip the first page if the one wizard has at least one page.
ConfigurationWizardElement element = (ConfigurationWizardElement)wizards.getChildren()[0];
try {
this.wizard = (IConfigurationWizard)element.createExecutableExtension();
wizard.init(workbench, project);
wizard.addPages();
if (wizard.getPageCount() > 0) {
wizard.setContainer(getContainer());
IWizardPage[] pages = wizard.getPages();
for (int i = 0; i < pages.length; i++) {
addPage(pages[i]);
}
return;
}
} catch (CoreException e) {
TeamUIPlugin.log(e);
return;
}
}
mainPage = new ConfigureProjectWizardMainPage("configurePage1", getWizardLabel(), TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_WIZBAN_SHARE), wizards, disabledWizards); //$NON-NLS-1$
mainPage.setDescription(getWizardDescription());
mainPage.setProject(project);
mainPage.setWorkbench(workbench);
addPage(mainPage);
}
public IWizardPage getNextPage(IWizardPage page) {
if (wizard != null) {
return wizard.getNextPage(page);
}
return super.getNextPage(page);
}
public boolean canFinish() {
// If we are on the first page, never allow finish unless the selected wizard has no pages.
if (getContainer().getCurrentPage() == mainPage) {
if (mainPage.getSelectedWizard() != null && mainPage.getNextPage() == null) {
return true;
}
return false;
}
if (wizard != null) {
return wizard.canFinish();
}
return super.canFinish();
}
/*
* @see Wizard#performFinish
*/
public boolean performFinish() {
// There is only one wizard with at least one page
if (wizard != null) {
return wizard.performFinish();
}
// If we are on the first page and the selected wizard has no pages then
// allow it to finish.
if (getContainer().getCurrentPage() == mainPage) {
IConfigurationWizard noPageWizard = mainPage.getSelectedWizard();
if (noPageWizard != null) {
if (noPageWizard.canFinish())
{
return noPageWizard.performFinish();
}
}
}
// If the wizard has pages and there are several
// wizards registered then the registered wizard
// will call it's own performFinish().
return true;
}
/* (non-Javadoc)
* @see org.eclipse.jface.wizard.IWizard#performCancel()
*/
public boolean performCancel() {
if (wizard != null) {
return wizard.performCancel();
}
return super.performCancel();
}
/**
* Returns the configuration wizards that are available for invocation.
*
* @return the available wizards
*/
protected AdaptableList getAvailableWizards(AdaptableList disabledWizards) {
AdaptableList result = new AdaptableList();
IPluginRegistry registry = Platform.getPluginRegistry();
IExtensionPoint point = registry.getExtensionPoint(pluginId, getExtensionPoint());
if (point != null) {
IExtension[] extensions = point.getExtensions();
for (int i = 0; i < extensions.length; i++) {
IConfigurationElement[] elements = extensions[i].getConfigurationElements();
for (int j = 0; j < elements.length; j++) {
IConfigurationElement element = elements[j];
if (element.getName().equals(TAG_WIZARD)) {
ConfigurationWizardElement wizard = createWizardElement(element);
if (wizard != null && filterItem(element)) {
disabledWizards.add(wizard);
} else if (wizard != null) {
result.add(wizard);
}
}
}
}
}
return result;
}
private boolean filterItem(IConfigurationElement element) {
String extensionId = element.getAttribute(ATT_ID);
String extensionPluginId = element.getDeclaringExtension().getDeclaringPluginDescriptor().getUniqueIdentifier();
IActivityManager activityMgr = PlatformUI.getWorkbench().getActivitySupport().getActivityManager();
IIdentifier id = activityMgr.getIdentifier(extensionPluginId + "/" + extensionId); //$NON-NLS-1$
return (!id.isEnabled());
}
/**
* Returns a new ConfigurationWizardElement configured according to the parameters
* contained in the passed Registry.
*
* May answer null if there was not enough information in the Extension to create
* an adequate wizard
*
* @param element the element for which to create a wizard element
* @return the wizard element for the given element
*/
protected ConfigurationWizardElement createWizardElement(IConfigurationElement element) {
// WizardElements must have a name attribute
String nameString = element.getAttribute(ATT_NAME);
if (nameString == null) {
// Missing attribute
return null;
}
ConfigurationWizardElement result = new ConfigurationWizardElement(nameString);
if (initializeWizard(result, element)) {
// initialization was successful
return result;
}
return null;
}
/**
* Initialize the passed element's properties based on the contents of
* the passed registry. Answer a boolean indicating whether the element
* was able to be adequately initialized.
*
* @param element the element to initialize the properties for
* @param extension the registry to get properties from
* @return whether initialization was successful
*/
protected boolean initializeWizard(ConfigurationWizardElement element, IConfigurationElement config) {
element.setID(config.getAttribute(ATT_ID));
String description = ""; //$NON-NLS-1$
IConfigurationElement [] children = config.getChildren(TAG_DESCRIPTION);
if (children.length >= 1) {
description = children[0].getValue();
}
element.setDescription(description);
// apply CLASS and ICON properties
element.setConfigurationElement(config);
String iconName = config.getAttribute(ATT_ICON);
if (iconName != null) {
IExtension extension = config.getDeclaringExtension();
element.setImageDescriptor(TeamUIPlugin.getImageDescriptorFromExtension(extension, iconName));
}
// ensure that a class was specified
if (element.getConfigurationElement() == null) {
// Missing attribute
return false;
}
setForcePreviousAndNextButtons(true);
return true;
}
/*
* Method declared on IConfigurationWizard
*/
public void init(IWorkbench workbench, IProject project) {
this.workbench = workbench;
this.project = project;
}
}
| true | true | public void addPages() {
AdaptableList disabledWizards = new AdaptableList();
AdaptableList wizards = getAvailableWizards(disabledWizards);
if (wizards.size() == 1) {
// If there is only one wizard, skip the first page.
// Only skip the first page if the one wizard has at least one page.
ConfigurationWizardElement element = (ConfigurationWizardElement)wizards.getChildren()[0];
try {
this.wizard = (IConfigurationWizard)element.createExecutableExtension();
wizard.init(workbench, project);
wizard.addPages();
if (wizard.getPageCount() > 0) {
wizard.setContainer(getContainer());
IWizardPage[] pages = wizard.getPages();
for (int i = 0; i < pages.length; i++) {
addPage(pages[i]);
}
return;
}
} catch (CoreException e) {
TeamUIPlugin.log(e);
return;
}
}
mainPage = new ConfigureProjectWizardMainPage("configurePage1", getWizardLabel(), TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_WIZBAN_SHARE), wizards, disabledWizards); //$NON-NLS-1$
mainPage.setDescription(getWizardDescription());
mainPage.setProject(project);
mainPage.setWorkbench(workbench);
addPage(mainPage);
}
| public void addPages() {
AdaptableList disabledWizards = new AdaptableList();
AdaptableList wizards = getAvailableWizards(disabledWizards);
if (wizards.size() == 1 && disabledWizards.size() == 0) {
// If there is only one wizard, skip the first page.
// Only skip the first page if the one wizard has at least one page.
ConfigurationWizardElement element = (ConfigurationWizardElement)wizards.getChildren()[0];
try {
this.wizard = (IConfigurationWizard)element.createExecutableExtension();
wizard.init(workbench, project);
wizard.addPages();
if (wizard.getPageCount() > 0) {
wizard.setContainer(getContainer());
IWizardPage[] pages = wizard.getPages();
for (int i = 0; i < pages.length; i++) {
addPage(pages[i]);
}
return;
}
} catch (CoreException e) {
TeamUIPlugin.log(e);
return;
}
}
mainPage = new ConfigureProjectWizardMainPage("configurePage1", getWizardLabel(), TeamUIPlugin.getImageDescriptor(ITeamUIImages.IMG_WIZBAN_SHARE), wizards, disabledWizards); //$NON-NLS-1$
mainPage.setDescription(getWizardDescription());
mainPage.setProject(project);
mainPage.setWorkbench(workbench);
addPage(mainPage);
}
|
diff --git a/spring-integration-groovy/src/test/java/org/springframework/integration/groovy/GroovyControlBusIntegrationTests.java b/spring-integration-groovy/src/test/java/org/springframework/integration/groovy/GroovyControlBusIntegrationTests.java
index cb1b6b466a..4363f349a4 100644
--- a/spring-integration-groovy/src/test/java/org/springframework/integration/groovy/GroovyControlBusIntegrationTests.java
+++ b/spring-integration-groovy/src/test/java/org/springframework/integration/groovy/GroovyControlBusIntegrationTests.java
@@ -1,77 +1,78 @@
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.springframework.integration.groovy;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.io.IOException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.integration.Message;
import org.springframework.integration.MessageChannel;
import org.springframework.integration.core.PollableChannel;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scripting.ScriptSource;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @author Artem Bilan
* @since 2.2
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class GroovyControlBusIntegrationTests {
@Autowired
private MessageChannel controlBus;
@Autowired
private PollableChannel controlBusOutput;
@Autowired
private PollableChannel output;
@Autowired
private MessageChannel delayerInput;
@Autowired
ThreadPoolTaskScheduler scheduler;
@Test
public void testDelayerManagement() throws IOException {
Message<String> testMessage = MessageBuilder.withPayload("test").build();
this.delayerInput.send(testMessage);
this.delayerInput.send(testMessage);
this.scheduler.destroy();
- assertNull(this.output.receive(100));
+ // ensure the delayer did not release any messages
+ assertNull(this.output.receive(500));
this.scheduler.afterPropertiesSet();
Resource scriptResource = new ClassPathResource("GroovyControlBusDelayerManagementTest.groovy", this.getClass());
ScriptSource scriptSource = new ResourceScriptSource(scriptResource);
Message<?> message = MessageBuilder.withPayload(scriptSource.getScriptAsString()).build();
this.controlBus.send(message);
- assertNotNull(this.output.receive(100));
- assertNotNull(this.output.receive(100));
+ assertNotNull(this.output.receive(1000));
+ assertNotNull(this.output.receive(1000));
}
}
| false | true | public void testDelayerManagement() throws IOException {
Message<String> testMessage = MessageBuilder.withPayload("test").build();
this.delayerInput.send(testMessage);
this.delayerInput.send(testMessage);
this.scheduler.destroy();
assertNull(this.output.receive(100));
this.scheduler.afterPropertiesSet();
Resource scriptResource = new ClassPathResource("GroovyControlBusDelayerManagementTest.groovy", this.getClass());
ScriptSource scriptSource = new ResourceScriptSource(scriptResource);
Message<?> message = MessageBuilder.withPayload(scriptSource.getScriptAsString()).build();
this.controlBus.send(message);
assertNotNull(this.output.receive(100));
assertNotNull(this.output.receive(100));
}
| public void testDelayerManagement() throws IOException {
Message<String> testMessage = MessageBuilder.withPayload("test").build();
this.delayerInput.send(testMessage);
this.delayerInput.send(testMessage);
this.scheduler.destroy();
// ensure the delayer did not release any messages
assertNull(this.output.receive(500));
this.scheduler.afterPropertiesSet();
Resource scriptResource = new ClassPathResource("GroovyControlBusDelayerManagementTest.groovy", this.getClass());
ScriptSource scriptSource = new ResourceScriptSource(scriptResource);
Message<?> message = MessageBuilder.withPayload(scriptSource.getScriptAsString()).build();
this.controlBus.send(message);
assertNotNull(this.output.receive(1000));
assertNotNull(this.output.receive(1000));
}
|
diff --git a/modules/server/jetty-util/src/test/java/org/mortbay/thread/TimeoutTest.java b/modules/server/jetty-util/src/test/java/org/mortbay/thread/TimeoutTest.java
index bae09149e..ab7d1c4fd 100644
--- a/modules/server/jetty-util/src/test/java/org/mortbay/thread/TimeoutTest.java
+++ b/modules/server/jetty-util/src/test/java/org/mortbay/thread/TimeoutTest.java
@@ -1,256 +1,257 @@
//========================================================================
//$Id: TimeoutTest.java,v 1.1 2005/10/05 14:09:42 janb Exp $
//Copyright 2004-2005 Mort Bay Consulting Pty. Ltd.
//------------------------------------------------------------------------
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//========================================================================
package org.mortbay.thread;
import junit.framework.TestCase;
public class TimeoutTest extends TestCase
{
Object lock = new Object();
Timeout timeout = new Timeout(null);
Timeout.Task[] tasks;
/* ------------------------------------------------------------ */
/*
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception
{
super.setUp();
timeout=new Timeout(lock);
tasks= new Timeout.Task[10];
for (int i=0;i<tasks.length;i++)
{
tasks[i]=new Timeout.Task();
timeout.setNow(1000+i*100);
timeout.schedule(tasks[i]);
}
timeout.setNow(100);
}
/* ------------------------------------------------------------ */
/*
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception
{
super.tearDown();
}
/* ------------------------------------------------------------ */
public void testExpiry()
{
timeout.setDuration(200);
timeout.setNow(1500);
timeout.tick();
for (int i=0;i<tasks.length;i++)
{
assertEquals("isExpired "+i,i<4, tasks[i].isExpired());
}
}
/* ------------------------------------------------------------ */
public void testCancel()
{
timeout.setDuration(200);
timeout.setNow(1700);
for (int i=0;i<tasks.length;i++)
if (i%2==1)
tasks[i].cancel();
timeout.tick();
for (int i=0;i<tasks.length;i++)
{
assertEquals("isExpired "+i,i%2==0 && i<6, tasks[i].isExpired());
}
}
/* ------------------------------------------------------------ */
public void testTouch()
{
timeout.setDuration(200);
timeout.setNow(1350);
timeout.schedule(tasks[2]);
timeout.setNow(1500);
timeout.tick();
for (int i=0;i<tasks.length;i++)
{
assertEquals("isExpired "+i,i!=2 && i<4, tasks[i].isExpired());
}
timeout.setNow(1550);
timeout.tick();
for (int i=0;i<tasks.length;i++)
{
assertEquals("isExpired "+i, i<4, tasks[i].isExpired());
}
}
/* ------------------------------------------------------------ */
public void testDelay()
{
Timeout.Task task = new Timeout.Task();
timeout.setNow(1100);
timeout.schedule(task, 300);
timeout.setDuration(200);
timeout.setNow(1300);
timeout.tick();
assertEquals("delay", false, task.isExpired());
timeout.setNow(1500);
timeout.tick();
assertEquals("delay", false, task.isExpired());
timeout.setNow(1700);
timeout.tick();
assertEquals("delay", true, task.isExpired());
}
/* ------------------------------------------------------------ */
public void testStress() throws Exception
{
final int LOOP=500;
final boolean[] running = {true};
final int[] count = {0,0,0};
+ timeout.setNow(System.currentTimeMillis());
timeout.setDuration(100);
// Start a ticker thread that will tick over the timer frequently.
Thread ticker = new Thread()
{
public void run()
{
while (running[0])
{
try
{
// use lock.wait so we have a memory barrier and
// have no funny optimisation issues.
synchronized (lock)
{
lock.wait(40);
}
timeout.tick(System.currentTimeMillis());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
};
ticker.start();
// start lots of test threads
for (int i=0;i<LOOP;i++)
{
final int l =i;
//
Thread th = new Thread()
{
public void run()
{
// count how many threads were started (should == LOOP)
synchronized(count)
{
count[0]++;
}
// create a task for this thread
Timeout.Task task = new Timeout.Task()
{
public void expired()
{
// count the number of expires
synchronized(count)
{
count[2]++;
}
}
};
// this thread will loop and each loop with schedule a
- // task with a delay between 0 and 100ms on top of the timeouts 100ms duration
+ // task with a delay between 200 and 300ms on top of the timeouts 100ms duration
// mostly this thread will then wait 50ms and cancel the task
- // But once it will wait 500ms and the task will expire
- long delay = this.hashCode() % 100;
+ // But once it will wait 1000ms and the task will expire
+ long delay = 200+this.hashCode() % 100;
int once = (int)( 10+(System.currentTimeMillis() % 50));
System.err.println(l+" "+delay+" "+once);
// do the looping until we are stopped
int loop=0;
while (running[0])
{
try
{
timeout.schedule(task,delay);
long wait=50;
if (loop++==once)
{
- // THIS loop is the one time we wait 500ms
+ // THIS loop is the one time we wait 1000ms
synchronized(count)
{
count[1]++;
}
- wait=500;
+ wait=1000;
}
// do the wait
synchronized (lock)
{
lock.wait(wait);
}
// cancel task (which may have expired)
task.cancel();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
};
th.start();
}
// run test for 5s
Thread.sleep(5000);
synchronized (lock)
{
running[0]=false;
}
// give some time for test to stop
Thread.sleep(1000);
timeout.tick(System.currentTimeMillis());
// check the counts
assertEquals("count threads", LOOP,count[0]);
assertEquals("count once waits",LOOP,count[1]);
assertEquals("count expires",LOOP,count[2]);
}
}
| false | true | public void testStress() throws Exception
{
final int LOOP=500;
final boolean[] running = {true};
final int[] count = {0,0,0};
timeout.setDuration(100);
// Start a ticker thread that will tick over the timer frequently.
Thread ticker = new Thread()
{
public void run()
{
while (running[0])
{
try
{
// use lock.wait so we have a memory barrier and
// have no funny optimisation issues.
synchronized (lock)
{
lock.wait(40);
}
timeout.tick(System.currentTimeMillis());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
};
ticker.start();
// start lots of test threads
for (int i=0;i<LOOP;i++)
{
final int l =i;
//
Thread th = new Thread()
{
public void run()
{
// count how many threads were started (should == LOOP)
synchronized(count)
{
count[0]++;
}
// create a task for this thread
Timeout.Task task = new Timeout.Task()
{
public void expired()
{
// count the number of expires
synchronized(count)
{
count[2]++;
}
}
};
// this thread will loop and each loop with schedule a
// task with a delay between 0 and 100ms on top of the timeouts 100ms duration
// mostly this thread will then wait 50ms and cancel the task
// But once it will wait 500ms and the task will expire
long delay = this.hashCode() % 100;
int once = (int)( 10+(System.currentTimeMillis() % 50));
System.err.println(l+" "+delay+" "+once);
// do the looping until we are stopped
int loop=0;
while (running[0])
{
try
{
timeout.schedule(task,delay);
long wait=50;
if (loop++==once)
{
// THIS loop is the one time we wait 500ms
synchronized(count)
{
count[1]++;
}
wait=500;
}
// do the wait
synchronized (lock)
{
lock.wait(wait);
}
// cancel task (which may have expired)
task.cancel();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
};
th.start();
}
// run test for 5s
Thread.sleep(5000);
synchronized (lock)
{
running[0]=false;
}
// give some time for test to stop
Thread.sleep(1000);
timeout.tick(System.currentTimeMillis());
// check the counts
assertEquals("count threads", LOOP,count[0]);
assertEquals("count once waits",LOOP,count[1]);
assertEquals("count expires",LOOP,count[2]);
}
| public void testStress() throws Exception
{
final int LOOP=500;
final boolean[] running = {true};
final int[] count = {0,0,0};
timeout.setNow(System.currentTimeMillis());
timeout.setDuration(100);
// Start a ticker thread that will tick over the timer frequently.
Thread ticker = new Thread()
{
public void run()
{
while (running[0])
{
try
{
// use lock.wait so we have a memory barrier and
// have no funny optimisation issues.
synchronized (lock)
{
lock.wait(40);
}
timeout.tick(System.currentTimeMillis());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
};
ticker.start();
// start lots of test threads
for (int i=0;i<LOOP;i++)
{
final int l =i;
//
Thread th = new Thread()
{
public void run()
{
// count how many threads were started (should == LOOP)
synchronized(count)
{
count[0]++;
}
// create a task for this thread
Timeout.Task task = new Timeout.Task()
{
public void expired()
{
// count the number of expires
synchronized(count)
{
count[2]++;
}
}
};
// this thread will loop and each loop with schedule a
// task with a delay between 200 and 300ms on top of the timeouts 100ms duration
// mostly this thread will then wait 50ms and cancel the task
// But once it will wait 1000ms and the task will expire
long delay = 200+this.hashCode() % 100;
int once = (int)( 10+(System.currentTimeMillis() % 50));
System.err.println(l+" "+delay+" "+once);
// do the looping until we are stopped
int loop=0;
while (running[0])
{
try
{
timeout.schedule(task,delay);
long wait=50;
if (loop++==once)
{
// THIS loop is the one time we wait 1000ms
synchronized(count)
{
count[1]++;
}
wait=1000;
}
// do the wait
synchronized (lock)
{
lock.wait(wait);
}
// cancel task (which may have expired)
task.cancel();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
};
th.start();
}
// run test for 5s
Thread.sleep(5000);
synchronized (lock)
{
running[0]=false;
}
// give some time for test to stop
Thread.sleep(1000);
timeout.tick(System.currentTimeMillis());
// check the counts
assertEquals("count threads", LOOP,count[0]);
assertEquals("count once waits",LOOP,count[1]);
assertEquals("count expires",LOOP,count[2]);
}
|
diff --git a/src/java/org/apache/log4j/chainsaw/ApplicationPreferenceModelPanel.java b/src/java/org/apache/log4j/chainsaw/ApplicationPreferenceModelPanel.java
index 5521f75..a58f2ab 100644
--- a/src/java/org/apache/log4j/chainsaw/ApplicationPreferenceModelPanel.java
+++ b/src/java/org/apache/log4j/chainsaw/ApplicationPreferenceModelPanel.java
@@ -1,528 +1,528 @@
/*
* ============================================================================
* The Apache Software License, Version 1.1
* ============================================================================
*
* Copyright (C) 1999 The Apache Software Foundation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modifica-
* tion, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The end-user documentation included with the redistribution, if any, must
* include the following acknowledgment: "This product includes software
* developed by the Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself, if
* and wherever such third-party acknowledgments normally appear.
*
* 4. The names "log4j" and "Apache Software Foundation" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* [email protected].
*
* 5. Products derived from this software may not be called "Apache", nor may
* "Apache" appear in their name, without prior written permission of the
* Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
* DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* on behalf of the Apache Software Foundation. For more information on the
* Apache Software Foundation, please see <http://www.apache.org/>.
*
*/
package org.apache.log4j.chainsaw;
import org.apache.log4j.helpers.LogLog;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
/**
* A panel used by the user to modify any application-wide preferences.
*
* @author Paul Smith <[email protected]>
*
*/
public class ApplicationPreferenceModelPanel extends AbstractPreferencePanel {
private ApplicationPreferenceModel committedPreferenceModel;
private ApplicationPreferenceModel uncommittedPreferenceModel =
new ApplicationPreferenceModel();
JTextField identifierExpression;
ApplicationPreferenceModelPanel(ApplicationPreferenceModel model) {
this.committedPreferenceModel = model;
initComponents();
getOkButton().addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
uncommittedPreferenceModel.setIdentifierExpression(
identifierExpression.getText());
committedPreferenceModel.apply(uncommittedPreferenceModel);
hidePanel();
}
});
getCancelButton().addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
hidePanel();
}
});
}
public static void main(String[] args) {
JFrame f = new JFrame("App Preferences Panel Test Bed");
ApplicationPreferenceModel model = new ApplicationPreferenceModel();
ApplicationPreferenceModelPanel panel =
new ApplicationPreferenceModelPanel(model);
f.getContentPane().add(panel);
model.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
LogLog.warn(evt.toString());
}
});
panel.setOkCancelActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(1);
}
});
f.setSize(640, 480);
f.show();
}
/**
* Ensures this panels DISPLAYED model is in sync with
* the model initially passed to the constructor.
*
*/
public void updateModel() {
this.uncommittedPreferenceModel.apply(committedPreferenceModel);
}
/* (non-Javadoc)
* @see org.apache.log4j.chainsaw.AbstractPreferencePanel#createTreeModel()
*/
protected TreeModel createTreeModel() {
final DefaultMutableTreeNode rootNode =
new DefaultMutableTreeNode("Preferences");
DefaultTreeModel model = new DefaultTreeModel(rootNode);
DefaultMutableTreeNode general =
new DefaultMutableTreeNode(new GeneralAllPrefPanel());
DefaultMutableTreeNode visuals =
new DefaultMutableTreeNode(new VisualsPrefPanel());
rootNode.add(general);
rootNode.add(visuals);
return model;
}
public class VisualsPrefPanel extends BasicPrefPanel {
private final JRadioButton topPlacement = new JRadioButton("Top");
private final JRadioButton bottomPlacement = new JRadioButton("Bottom");
private final JCheckBox statusBar = new JCheckBox("Show Status bar");
private final JCheckBox toolBar = new JCheckBox("Show Toolbar");
private final JCheckBox receivers = new JCheckBox("Show Receivers");
private UIManager.LookAndFeelInfo[] lookAndFeels =
UIManager.getInstalledLookAndFeels();
private final ButtonGroup lookAndFeelGroup = new ButtonGroup();
private VisualsPrefPanel() {
super("Visuals");
setupComponents();
setupListeners();
}
/**
*
*/
private void setupListeners() {
topPlacement.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
uncommittedPreferenceModel.setTabPlacement(SwingConstants.TOP);
}
});
bottomPlacement.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
uncommittedPreferenceModel.setTabPlacement(SwingConstants.BOTTOM);
}
});
statusBar.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
uncommittedPreferenceModel.setStatusBar(statusBar.isSelected());
}
});
toolBar.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
uncommittedPreferenceModel.setToolbar(toolBar.isSelected());
}
});
receivers.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
uncommittedPreferenceModel.setReceivers(receivers.isSelected());
}
});
uncommittedPreferenceModel.addPropertyChangeListener(
"tabPlacement",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
int value = ((Integer) evt.getNewValue()).intValue();
switch (value) {
case SwingConstants.TOP:
topPlacement.setSelected(true);
break;
case SwingConstants.BOTTOM:
bottomPlacement.setSelected(true);
break;
default:
break;
}
}
});
uncommittedPreferenceModel.addPropertyChangeListener(
"statusBar",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
statusBar.setSelected(
((Boolean) evt.getNewValue()).booleanValue());
}
});
uncommittedPreferenceModel.addPropertyChangeListener(
"toolbar",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
toolBar.setSelected(((Boolean) evt.getNewValue()).booleanValue());
}
});
uncommittedPreferenceModel.addPropertyChangeListener(
"receivers",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
receivers.setSelected(
((Boolean) evt.getNewValue()).booleanValue());
}
});
uncommittedPreferenceModel.addPropertyChangeListener(
"lookAndFeelClassName",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
String lf = evt.getNewValue().toString();
Enumeration enumeration = lookAndFeelGroup.getElements();
while (enumeration.hasMoreElements()) {
JRadioButton button = (JRadioButton) enumeration.nextElement();
- if (button.getName().equals(lf)) {
+ if (button.getName()!=null && button.getName().equals(lf)) {
button.setSelected(true);
break;
}
}
}
});
}
/**
*
*/
private void setupComponents() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JPanel tabPlacementBox = new JPanel();
tabPlacementBox.setLayout(
new BoxLayout(tabPlacementBox, BoxLayout.Y_AXIS));
tabPlacementBox.setBorder(
BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Tab Placement"));
ButtonGroup tabPlacementGroup = new ButtonGroup();
tabPlacementGroup.add(topPlacement);
tabPlacementGroup.add(bottomPlacement);
tabPlacementBox.add(topPlacement);
tabPlacementBox.add(bottomPlacement);
add(tabPlacementBox);
add(statusBar);
add(receivers);
add(toolBar);
JPanel lfPanel = new JPanel();
lfPanel.setLayout(new BoxLayout(lfPanel, BoxLayout.Y_AXIS));
lfPanel.setBorder(
BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Look & Feel"));
for (int i = 0; i < lookAndFeels.length; i++) {
final UIManager.LookAndFeelInfo lfInfo = lookAndFeels[i];
final JRadioButton lfItem = new JRadioButton(lfInfo.getName());
lfItem.setName(lfInfo.getClassName());
lfItem.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
uncommittedPreferenceModel.setLookAndFeelClassName(
lfInfo.getClassName());
}
});
lookAndFeelGroup.add(lfItem);
lfPanel.add(lfItem);
}
try {
final Class gtkLF =
Class.forName("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
final JRadioButton lfIGTK = new JRadioButton("GTK+ 2.0");
lfIGTK.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
uncommittedPreferenceModel.setLookAndFeelClassName(
gtkLF.getName());
}
});
lookAndFeelGroup.add(lfIGTK);
lfPanel.add(lfIGTK);
} catch (Exception e) {
LogLog.debug("Can't find new GTK L&F, might be Windows, or <JDK1.4.2");
}
add(lfPanel);
add(
new JLabel(
"Look and Feel change will apply the next time you start Chainsaw"));
}
}
/**
* @author psmith
*
*/
public class GeneralAllPrefPanel extends BasicPrefPanel {
private final JCheckBox showNoReceiverWarning =
new JCheckBox("Prompt me on startup if there are no Receivers defined");
private final JSlider responsiveSlider =
new JSlider(JSlider.HORIZONTAL, 1, 4, 2);
private final JCheckBox confirmExit = new JCheckBox("Confirm Exit");
Dictionary sliderLabelMap = new Hashtable();
/**
* @param title
*/
public GeneralAllPrefPanel() {
super("General");
GeneralAllPrefPanel.this.initComponents();
}
private void initComponents() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
identifierExpression = new JTextField(20);
Box p = new Box(BoxLayout.X_AXIS);
p.add(showNoReceiverWarning);
p.add(Box.createHorizontalGlue());
confirmExit.setToolTipText("Is set, you will be prompted to confirm the exit Chainsaw");
setupInitialValues();
setupListeners();
initSliderComponent();
add(responsiveSlider);
JPanel p1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
p1.add(new JLabel("Tab identifier"));
p1.add(Box.createHorizontalStrut(5));
p1.add(identifierExpression);
add(p1);
add(p);
add(confirmExit);
add(Box.createVerticalGlue());
}
private void initSliderComponent() {
responsiveSlider.setToolTipText(
"Adjust to set the responsiveness of the app. How often the view is updated.");
responsiveSlider.setSnapToTicks(true);
responsiveSlider.setLabelTable(sliderLabelMap);
responsiveSlider.setPaintLabels(true);
responsiveSlider.setPaintTrack(true);
responsiveSlider.setBorder(
BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Responsiveness"));
// responsiveSlider.setAlignmentY(0);
// responsiveSlider.setAlignmentX(0);
}
private void setupListeners() {
uncommittedPreferenceModel.addPropertyChangeListener(
"showNoReceiverWarning",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
showNoReceiverWarning.setSelected(
((Boolean) evt.getNewValue()).booleanValue());
}
});
uncommittedPreferenceModel.addPropertyChangeListener(
"identifierExpression",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
identifierExpression.setText(evt.getNewValue().toString());
}
});
uncommittedPreferenceModel.addPropertyChangeListener(
"responsiveness",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
int value = ((Integer) evt.getNewValue()).intValue();
if (value >= 1000) {
int newValue = (value - 750) / 1000;
LogLog.debug(
"Adjusting old Responsiveness value from " + value + " to "
+ newValue);
value = newValue;
}
responsiveSlider.setValue(value);
}
});
showNoReceiverWarning.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
uncommittedPreferenceModel.setShowNoReceiverWarning(
showNoReceiverWarning.isSelected());
}
});
responsiveSlider.getModel().addChangeListener(
new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (responsiveSlider.getValueIsAdjusting()) {
/**
* We'll wait until it stops.
*/
} else {
int value = responsiveSlider.getValue();
if (value == 0) {
value = 1;
}
LogLog.debug("Adjust responsiveness to " + value);
uncommittedPreferenceModel.setResponsiveness(value);
}
}
});
uncommittedPreferenceModel.addPropertyChangeListener(
"confirmExit",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
boolean value = ((Boolean) evt.getNewValue()).booleanValue();
confirmExit.setSelected(value);
}
});
confirmExit.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
uncommittedPreferenceModel.setConfirmExit(
confirmExit.isSelected());
}
});
}
private void setupInitialValues() {
sliderLabelMap.put(new Integer(1), new JLabel("Fastest"));
sliderLabelMap.put(new Integer(2), new JLabel("Fast"));
sliderLabelMap.put(new Integer(3), new JLabel("Medium"));
sliderLabelMap.put(new Integer(4), new JLabel("Slow"));
//
showNoReceiverWarning.setSelected(
uncommittedPreferenceModel.isShowNoReceiverWarning());
identifierExpression.setText(
uncommittedPreferenceModel.getIdentifierExpression());
}
}
}
| true | true | private void setupListeners() {
topPlacement.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
uncommittedPreferenceModel.setTabPlacement(SwingConstants.TOP);
}
});
bottomPlacement.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
uncommittedPreferenceModel.setTabPlacement(SwingConstants.BOTTOM);
}
});
statusBar.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
uncommittedPreferenceModel.setStatusBar(statusBar.isSelected());
}
});
toolBar.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
uncommittedPreferenceModel.setToolbar(toolBar.isSelected());
}
});
receivers.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
uncommittedPreferenceModel.setReceivers(receivers.isSelected());
}
});
uncommittedPreferenceModel.addPropertyChangeListener(
"tabPlacement",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
int value = ((Integer) evt.getNewValue()).intValue();
switch (value) {
case SwingConstants.TOP:
topPlacement.setSelected(true);
break;
case SwingConstants.BOTTOM:
bottomPlacement.setSelected(true);
break;
default:
break;
}
}
});
uncommittedPreferenceModel.addPropertyChangeListener(
"statusBar",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
statusBar.setSelected(
((Boolean) evt.getNewValue()).booleanValue());
}
});
uncommittedPreferenceModel.addPropertyChangeListener(
"toolbar",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
toolBar.setSelected(((Boolean) evt.getNewValue()).booleanValue());
}
});
uncommittedPreferenceModel.addPropertyChangeListener(
"receivers",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
receivers.setSelected(
((Boolean) evt.getNewValue()).booleanValue());
}
});
uncommittedPreferenceModel.addPropertyChangeListener(
"lookAndFeelClassName",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
String lf = evt.getNewValue().toString();
Enumeration enumeration = lookAndFeelGroup.getElements();
while (enumeration.hasMoreElements()) {
JRadioButton button = (JRadioButton) enumeration.nextElement();
if (button.getName().equals(lf)) {
button.setSelected(true);
break;
}
}
}
});
}
| private void setupListeners() {
topPlacement.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
uncommittedPreferenceModel.setTabPlacement(SwingConstants.TOP);
}
});
bottomPlacement.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
uncommittedPreferenceModel.setTabPlacement(SwingConstants.BOTTOM);
}
});
statusBar.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
uncommittedPreferenceModel.setStatusBar(statusBar.isSelected());
}
});
toolBar.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
uncommittedPreferenceModel.setToolbar(toolBar.isSelected());
}
});
receivers.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
uncommittedPreferenceModel.setReceivers(receivers.isSelected());
}
});
uncommittedPreferenceModel.addPropertyChangeListener(
"tabPlacement",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
int value = ((Integer) evt.getNewValue()).intValue();
switch (value) {
case SwingConstants.TOP:
topPlacement.setSelected(true);
break;
case SwingConstants.BOTTOM:
bottomPlacement.setSelected(true);
break;
default:
break;
}
}
});
uncommittedPreferenceModel.addPropertyChangeListener(
"statusBar",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
statusBar.setSelected(
((Boolean) evt.getNewValue()).booleanValue());
}
});
uncommittedPreferenceModel.addPropertyChangeListener(
"toolbar",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
toolBar.setSelected(((Boolean) evt.getNewValue()).booleanValue());
}
});
uncommittedPreferenceModel.addPropertyChangeListener(
"receivers",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
receivers.setSelected(
((Boolean) evt.getNewValue()).booleanValue());
}
});
uncommittedPreferenceModel.addPropertyChangeListener(
"lookAndFeelClassName",
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
String lf = evt.getNewValue().toString();
Enumeration enumeration = lookAndFeelGroup.getElements();
while (enumeration.hasMoreElements()) {
JRadioButton button = (JRadioButton) enumeration.nextElement();
if (button.getName()!=null && button.getName().equals(lf)) {
button.setSelected(true);
break;
}
}
}
});
}
|
diff --git a/src/edu/stanford/mobisocial/dungbeetle/DungBeetleContentProvider.java b/src/edu/stanford/mobisocial/dungbeetle/DungBeetleContentProvider.java
index d6e210c..e1c1a80 100644
--- a/src/edu/stanford/mobisocial/dungbeetle/DungBeetleContentProvider.java
+++ b/src/edu/stanford/mobisocial/dungbeetle/DungBeetleContentProvider.java
@@ -1,529 +1,534 @@
package edu.stanford.mobisocial.dungbeetle;
import java.security.interfaces.RSAPublicKey;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Binder;
import android.util.Log;
import android.util.Pair;
import edu.stanford.mobisocial.dungbeetle.feed.DbObjects;
import edu.stanford.mobisocial.dungbeetle.feed.iface.DbEntryHandler;
import edu.stanford.mobisocial.dungbeetle.feed.iface.OutgoingMessageHandler;
import edu.stanford.mobisocial.dungbeetle.feed.iface.UnprocessedMessageHandler;
import edu.stanford.mobisocial.dungbeetle.feed.objects.InviteToGroupObj;
import edu.stanford.mobisocial.dungbeetle.group_providers.GroupProviders;
import edu.stanford.mobisocial.dungbeetle.model.Contact;
import edu.stanford.mobisocial.dungbeetle.model.DbObject;
import edu.stanford.mobisocial.dungbeetle.model.Feed;
import edu.stanford.mobisocial.dungbeetle.model.Group;
import edu.stanford.mobisocial.dungbeetle.model.GroupMember;
import edu.stanford.mobisocial.dungbeetle.model.Subscriber;
import edu.stanford.mobisocial.dungbeetle.util.Maybe;
public class DungBeetleContentProvider extends ContentProvider {
public static final String AUTHORITY = "org.mobisocial.db";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY);
static final String TAG = "DungBeetleContentProvider";
static final boolean DBG = false;
public static final String SUPER_APP_ID = "edu.stanford.mobisocial.dungbeetle";
private DBHelper mHelper;
private IdentityProvider mIdent;
public DungBeetleContentProvider() {}
@Override
protected void finalize() throws Throwable {
mHelper.close();
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
final String appId = getCallingActivityId();
if(appId == null){
Log.d(TAG, "No AppId for calling activity. Ignoring query.");
return 0;
}
if(!appId.equals(SUPER_APP_ID)) return 0;
List<String> segs = uri.getPathSegments();
mHelper.getWritableDatabase().delete(segs.get(0), selection, selectionArgs);
getContext().getContentResolver().notifyChange(uri, null);
return 0;
}
@Override
public String getType(Uri uri) {
List<String> segs = uri.getPathSegments();
if (segs.size() == 3){
return "vnd.android.cursor.item/vnd.dungbeetle.feed";
}
else if (segs.size() == 2){
return "vnd.android.cursor.dir/vnd.dungbeetle.feed";
}
else{
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
}
private Uri uriWithId(Uri uri, long id){
Uri.Builder b = uri.buildUpon();
b.appendPath(String.valueOf(id));
return b.build();
}
/**
* Inserts a message locally that has been received from some agent,
* typically from a remote device.
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
ContentResolver resolver = getContext().getContentResolver();
Log.i(TAG, "Inserting at uri: " + uri + ", " + values);
final String appId = getCallingActivityId();
if (appId == null) {
Log.d(TAG, "No AppId for calling activity. Ignoring query.");
return null;
}
List<String> segs = uri.getPathSegments();
if (match(uri, "feeds", "me")) {
if (!appId.equals(SUPER_APP_ID)) {
return null;
}
try {
JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
mHelper.addToFeed(appId, "friend", values.getAsString(DbObject.TYPE),
json);
resolver.notifyChange(Feed.uriForName("me"), null);
resolver.notifyChange(Feed.uriForName("friend"), null);
return Uri.parse(uri.toString());
} catch(JSONException e){
return null;
}
} else if (match(uri, "feeds", "friend", ".+")) {
if (!appId.equals(SUPER_APP_ID)) {
return null;
}
try {
/*
* A "virtual feed" for direct messaging with a friend.
* This can be thought of us a sequence of objects "in reply to"
* a virtual object between two contacts.
*/
/*long timestamp = new Date().getTime();
String type = values.getAsString(DbObject.TYPE);
JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
mHelper.prepareForSending(json, type, timestamp, appId);
mHelper.addObjectByJson(Contact.MY_ID, json, new byte[0]);*/
// stitch, stitch
long contactId = Long.parseLong(segs.get(2));
String type = values.getAsString(DbObject.TYPE);
JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
Helpers.sendMessage(getContext(), contactId, json, type);
resolver.notifyChange(uri, null);
return uri;
}
catch(JSONException e){
return null;
}
} else if (match(uri, "feeds", ".+")) {
String feedName = segs.get(1);
try {
JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
mHelper.addToFeed(appId, feedName, values.getAsString(DbObject.TYPE),
json);
notifyDependencies(resolver, feedName);
if (DBG) Log.d(TAG, "just inserted " + values.getAsString(DbObject.JSON));
return Uri.parse(uri.toString()); // TODO: is there a reason for this?
}
catch(JSONException e) {
return null;
}
} else if(match(uri, "out")) {
try {
JSONObject obj = new JSONObject(values.getAsString("json"));
mHelper.addToOutgoing(appId, values.getAsString(DbObject.DESTINATION),
values.getAsString(DbObject.TYPE), obj);
resolver.notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
return Uri.parse(uri.toString());
}
catch(JSONException e){
return null;
}
} else if (match(uri, "contacts")) {
if (!appId.equals(SUPER_APP_ID)) {
return null;
}
long id = mHelper.insertContact(values);
resolver.notifyChange(Uri.parse(CONTENT_URI + "/contacts"), null);
return uriWithId(uri, id);
} else if (match(uri, "subscribers")) {
// Question: Should this be restricted?
// if(!appId.equals(SUPER_APP_ID)) return null;
long id = mHelper.insertSubscriber(values);
resolver.notifyChange(Uri.parse(CONTENT_URI + "/subscribers"), null);
return uriWithId(uri, id);
} else if (match(uri, "groups")) {
if (!appId.equals(SUPER_APP_ID))
return null;
long id = mHelper.insertGroup(values);
getContext().getContentResolver()
.notifyChange(Uri.parse(CONTENT_URI + "/groups"), null);
return uriWithId(uri, id);
} else if (match(uri, "group_members")) {
if (!appId.equals(SUPER_APP_ID)) {
return null;
}
long id = mHelper.insertGroupMember(values);
getContext().getContentResolver().notifyChange(
Uri.parse(CONTENT_URI + "/group_members"), null);
getContext().getContentResolver().notifyChange(
Uri.parse(CONTENT_URI + "/group_contacts"), null);
return uriWithId(uri, id);
}
else if (match(uri, "group_invitations")) {
if (!appId.equals(SUPER_APP_ID)) {
return null;
}
String groupName = values.getAsString(InviteToGroupObj.GROUP_NAME);
Uri dynUpdateUri = Uri.parse(values.getAsString(InviteToGroupObj.DYN_UPDATE_URI));
long gid = values.getAsLong("groupId");
SQLiteDatabase db = mHelper.getWritableDatabase();
mHelper.addToOutgoing(db, appId, values.getAsString(InviteToGroupObj.PARTICIPANTS),
InviteToGroupObj.TYPE, InviteToGroupObj.json(groupName, dynUpdateUri));
getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
return uriWithId(uri, gid);
}
else if (match(uri, "dynamic_groups")) {
if (!appId.equals(SUPER_APP_ID)) {
return null;
}
Uri gUri = Uri.parse(values.getAsString("uri"));
GroupProviders.GroupProvider gp = GroupProviders.forUri(gUri);
String feedName = gp.feedName(gUri);
Maybe<Group> mg = mHelper.groupByFeedName(feedName);
long id = -1;
try {
Group g = mg.get();
id = g.id;
} catch (Maybe.NoValError e) {
ContentValues cv = new ContentValues();
cv.put(Group.NAME, gp.groupName(gUri));
cv.put(Group.FEED_NAME, feedName);
cv.put(Group.DYN_UPDATE_URI, gUri.toString());
String table = DbObject.TABLE;
String[] columns = new String[] { DbObject.FEED_NAME };
String selection = DbObject.CHILD_FEED_NAME + " = ?";
String[] selectionArgs = new String[] { feedName };
Cursor parent = mHelper.getReadableDatabase().query(
table, columns, selection, selectionArgs, null, null, null);
if (parent.moveToFirst()) {
String parentName = parent.getString(0);
table = Group.TABLE;
columns = new String[] { Group._ID };
selection = Group.FEED_NAME + " = ?";
selectionArgs = new String[] { parentName };
Cursor parent2 = mHelper.getReadableDatabase().query(
table, columns, selection, selectionArgs, null, null, null);
if (parent2.moveToFirst()) {
cv.put(Group.PARENT_FEED_ID, parent2.getLong(0));
} else {
Log.e(TAG, "Parent feed found but no id for " + parentName);
}
parent2.close();
} else {
Log.w(TAG, "No parent feed for " + feedName);
}
parent.close();
id = mHelper.insertGroup(cv);
getContext().getContentResolver().notifyChange(
Uri.parse(CONTENT_URI + "/dynamic_groups"), null);
getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/groups"),
null);
}
return uriWithId(uri, id);
}
else if (match(uri, "dynamic_group_member")) {
if (!appId.equals(SUPER_APP_ID)) {
return null;
}
SQLiteDatabase db = mHelper.getWritableDatabase();
- db.beginTransaction();
+ try {
+ db.beginTransaction();
+ } catch(Exception e) {
+ Log.e(TAG, "Database probably locked:??", e);
+ return null;
+ }
try {
ContentValues cv = new ContentValues();
String pubKeyStr = values.getAsString(Contact.PUBLIC_KEY);
RSAPublicKey k = DBIdentityProvider.publicKeyFromString(pubKeyStr);
String personId = mIdent.personIdForPublicKey(k);
if (!personId.equals(mIdent.userPersonId())) {
cv.put(Contact.PUBLIC_KEY, values.getAsString(Contact.PUBLIC_KEY));
cv.put(Contact.NAME, values.getAsString(Contact.NAME));
cv.put(Contact.EMAIL, values.getAsString(Contact.EMAIL));
if (values.getAsString(Contact.PICTURE) != null) {
cv.put(Contact.PICTURE, values.getAsByteArray(Contact.PICTURE));
}
long cid = -1;
Contact contact = mHelper.contactForPersonId(personId).otherwise(Contact.NA());
if (contact.id > -1) {
cid = contact.id;
} else {
cid = mHelper.insertContact(db, cv);
}
if (cid > -1) {
ContentValues gv = new ContentValues();
gv.put(GroupMember.GLOBAL_CONTACT_ID,
values.getAsString(GroupMember.GLOBAL_CONTACT_ID));
gv.put(GroupMember.GROUP_ID, values.getAsLong(GroupMember.GROUP_ID));
gv.put(GroupMember.CONTACT_ID, cid);
mHelper.insertGroupMember(db, gv);
getContext().getContentResolver().notifyChange(
Uri.parse(CONTENT_URI + "/group_members"), null);
getContext().getContentResolver().notifyChange(
Uri.parse(CONTENT_URI + "/contacts"), null);
getContext().getContentResolver().notifyChange(
Uri.parse(CONTENT_URI + "/group_contacts"), null);
// Add subscription to this private group feed
ContentValues sv = new ContentValues();
sv = new ContentValues();
sv.put(Subscriber.CONTACT_ID, cid);
sv.put(Subscriber.FEED_NAME, values.getAsString(Group.FEED_NAME));
mHelper.insertSubscriber(db, sv);
ContentValues xv = new ContentValues();
xv.put(Subscriber.CONTACT_ID, cid);
xv.put(Subscriber.FEED_NAME, "friend");
mHelper.insertSubscriber(db, xv);
getContext().getContentResolver().notifyChange(
Uri.parse(CONTENT_URI + "/subscribers"), null);
db.setTransactionSuccessful();
}
return uriWithId(uri, cid);
} else {
Log.i(TAG, "Omitting self.");
return uriWithId(uri, Contact.MY_ID);
}
} finally {
db.endTransaction();
}
} else {
Log.e(TAG, "Failed to insert into " + uri);
return null;
}
}
/*private void restoreDatabase() {
File data = Environment.getDataDirectory();
String newDBPath = "/data/edu.stanford.mobisocial.dungbeetle/databases/"+DBHelper.DB_NAME+".new";
File newDB = new File(data, newDBPath);
if(newDB.exists()){
String currentDBPath = "/data/edu.stanford.mobisocial.dungbeetle/databases/"+DBHelper.DB_NAME;
File currentDB = new File(data, currentDBPath);
currentDB.delete();
currentDB = new File(data, currentDBPath);
newDB.renameTo(currentDB);
Log.w(TAG, "backup exists");
}
else {
//database does't exist yet.
Log.w(TAG, "backup does not exist");
}
}*/
@Override
public boolean onCreate() {
//restoreDatabase();
Log.i(TAG, "Creating DungBeetleContentProvider");
mHelper = new DBHelper(getContext());
mIdent = new DBIdentityProvider(mHelper);
return mHelper.getWritableDatabase() == null;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
ContentResolver resolver = getContext().getContentResolver();
final String realAppId = getCallingActivityId();
if (realAppId == null) {
Log.d(TAG, "No AppId for calling activity. Ignoring query.");
return null;
}
if (DBG) Log.d(TAG, "Processing query: " + uri + " from appId " + realAppId);
List<String> segs = uri.getPathSegments();
if(match(uri, "obj")) {
return mHelper.getReadableDatabase().query(DbObject.TABLE, projection, selection, selectionArgs, null, null, sortOrder);
} else if(match(uri, "feedlist")) {
Cursor c = mHelper.queryFeedList(projection, selection, selectionArgs, sortOrder);
c.setNotificationUri(resolver, Uri.parse(CONTENT_URI + "/feedlist"));
return c;
} else if(match(uri, "feeds", ".+", "head")){
boolean isMe = segs.get(1).equals("me");
String feedName = isMe ? "friend" : segs.get(1);
String select = isMe ? DBHelper.andClauses(
selection, DbObject.CONTACT_ID + "=" + Contact.MY_ID) : selection;
Cursor c = mHelper.queryFeedLatest(realAppId, feedName, projection,
select, selectionArgs, sortOrder);
c.setNotificationUri(resolver, Uri.parse(CONTENT_URI + "/feeds/" + feedName));
if(isMe) c.setNotificationUri(resolver, Uri.parse(CONTENT_URI + "/feeds/me"));
return c;
} else if(match(uri, "feeds", ".+")){
boolean isMe = segs.get(1).equals("me");
String feedName = isMe ? "friend" : segs.get(1);
String select = isMe ? DBHelper.andClauses(selection, DbObject.CONTACT_ID + "="
+ Contact.MY_ID) : selection;
Cursor c = mHelper.queryFeed(realAppId,
feedName, projection, select, selectionArgs, sortOrder);
c.setNotificationUri(resolver, Feed.uriForName(feedName));
if (isMe) c.setNotificationUri(resolver, Feed.uriForName("me"));
return c;
} else if (match(uri, "feeds", "friend", ".+")) {
Long contactId = Long.parseLong(segs.get(2));
String select = selection;
Cursor c = mHelper.queryFriend(realAppId, contactId, projection,
select, selectionArgs, sortOrder);
c.setNotificationUri(resolver, uri);
return c;
} else if(match(uri, "groups_membership", ".+")) {
if(!realAppId.equals(SUPER_APP_ID)) return null;
Long contactId = Long.valueOf(segs.get(1));
Cursor c = mHelper.queryGroupsMembership(contactId);
c.setNotificationUri(resolver, uri);
return c;
} else if(match(uri, "group_contacts", ".+")) {
if(!realAppId.equals(SUPER_APP_ID)) return null;
Long group_id = Long.valueOf(segs.get(1));
Cursor c = mHelper.queryGroupContacts(group_id);
c.setNotificationUri(resolver, uri);
return c;
} else if(match(uri, "local_user", ".+")) {
// currently available to any local app with a feed id.
String feed_name = uri.getLastPathSegment();
Cursor c = mHelper.queryLocalUser(feed_name);
c.setNotificationUri(resolver, uri);
return c;
} else if(match(uri, "feed_members", ".+")) {
String feedName = segs.get(1);
Cursor c = mHelper.queryFeedMembers(feedName, realAppId);
c.setNotificationUri(resolver, uri);
return c;
} else if(match(uri, "groups")) {
if(!realAppId.equals(SUPER_APP_ID)) return null;
Cursor c = mHelper.queryGroups();
c.setNotificationUri(resolver, Uri.parse(CONTENT_URI + "/groups"));
return c;
} else if(match(uri, "contacts") ||
match(uri, "subscribers") ||
match(uri, "group_members")){
if(!realAppId.equals(SUPER_APP_ID)) return null;
Cursor c = mHelper.getReadableDatabase().query(
segs.get(0), projection, selection, selectionArgs, null, null, sortOrder);
c.setNotificationUri(resolver, Uri.parse(CONTENT_URI + "/" + segs.get(0)));
return c;
} else{
Log.d(TAG, "Unrecognized query: " + uri);
return null;
}
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
final String appId = getCallingActivityId();
if (appId == null) {
Log.d(TAG, "No AppId for calling activity. Ignoring query.");
return 0;
}
if(!appId.equals(SUPER_APP_ID)) return 0;
List<String> segs = uri.getPathSegments();
// TODO: If uri is a feed:
//String appRestriction = DbObject.APP_ID + "='" + appId + "'";
//selection = DBHelper.andClauses(selection, appRestriction);
if (DBG) Log.d(TAG, "Updating uri " + uri + " with " + values);
mHelper.getWritableDatabase().update(segs.get(0), values, selection, selectionArgs);
getContext().getContentResolver().notifyChange(uri, null);
return 0;
}
// For unit tests
public DBHelper getDatabaseHelper(){
return mHelper;
}
// Helper for matching on url paths
private boolean match(Uri uri, String... regexes){
List<String> segs = uri.getPathSegments();
if(segs.size() == regexes.length){
for (int i = 0; i < regexes.length; i++) {
if (!segs.get(i).matches(regexes[i])) {
return false;
}
}
return true;
}
return false;
}
private String getCallingActivityId(){
int pid = Binder.getCallingPid();
ActivityManager am = (ActivityManager)
getContext().getSystemService(Activity.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> lstAppInfo =
am.getRunningAppProcesses();
for(ActivityManager.RunningAppProcessInfo ai : lstAppInfo) {
if (ai.pid == pid) {
return ai.processName;
}
}
return null;
}
private void notifyDependencies(ContentResolver resolver, String feedName) {
resolver.notifyChange(Feed.uriForName(feedName), null);
Cursor c = mHelper.getFeedDependencies(feedName);
while (c.moveToNext()) {
Uri uri = Feed.uriForName(c.getString(0));
resolver.notifyChange(uri, null);
}
c.close();
}
}
| true | true | public Uri insert(Uri uri, ContentValues values) {
ContentResolver resolver = getContext().getContentResolver();
Log.i(TAG, "Inserting at uri: " + uri + ", " + values);
final String appId = getCallingActivityId();
if (appId == null) {
Log.d(TAG, "No AppId for calling activity. Ignoring query.");
return null;
}
List<String> segs = uri.getPathSegments();
if (match(uri, "feeds", "me")) {
if (!appId.equals(SUPER_APP_ID)) {
return null;
}
try {
JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
mHelper.addToFeed(appId, "friend", values.getAsString(DbObject.TYPE),
json);
resolver.notifyChange(Feed.uriForName("me"), null);
resolver.notifyChange(Feed.uriForName("friend"), null);
return Uri.parse(uri.toString());
} catch(JSONException e){
return null;
}
} else if (match(uri, "feeds", "friend", ".+")) {
if (!appId.equals(SUPER_APP_ID)) {
return null;
}
try {
/*
* A "virtual feed" for direct messaging with a friend.
* This can be thought of us a sequence of objects "in reply to"
* a virtual object between two contacts.
*/
/*long timestamp = new Date().getTime();
String type = values.getAsString(DbObject.TYPE);
JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
mHelper.prepareForSending(json, type, timestamp, appId);
mHelper.addObjectByJson(Contact.MY_ID, json, new byte[0]);*/
// stitch, stitch
long contactId = Long.parseLong(segs.get(2));
String type = values.getAsString(DbObject.TYPE);
JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
Helpers.sendMessage(getContext(), contactId, json, type);
resolver.notifyChange(uri, null);
return uri;
}
catch(JSONException e){
return null;
}
} else if (match(uri, "feeds", ".+")) {
String feedName = segs.get(1);
try {
JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
mHelper.addToFeed(appId, feedName, values.getAsString(DbObject.TYPE),
json);
notifyDependencies(resolver, feedName);
if (DBG) Log.d(TAG, "just inserted " + values.getAsString(DbObject.JSON));
return Uri.parse(uri.toString()); // TODO: is there a reason for this?
}
catch(JSONException e) {
return null;
}
} else if(match(uri, "out")) {
try {
JSONObject obj = new JSONObject(values.getAsString("json"));
mHelper.addToOutgoing(appId, values.getAsString(DbObject.DESTINATION),
values.getAsString(DbObject.TYPE), obj);
resolver.notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
return Uri.parse(uri.toString());
}
catch(JSONException e){
return null;
}
} else if (match(uri, "contacts")) {
if (!appId.equals(SUPER_APP_ID)) {
return null;
}
long id = mHelper.insertContact(values);
resolver.notifyChange(Uri.parse(CONTENT_URI + "/contacts"), null);
return uriWithId(uri, id);
} else if (match(uri, "subscribers")) {
// Question: Should this be restricted?
// if(!appId.equals(SUPER_APP_ID)) return null;
long id = mHelper.insertSubscriber(values);
resolver.notifyChange(Uri.parse(CONTENT_URI + "/subscribers"), null);
return uriWithId(uri, id);
} else if (match(uri, "groups")) {
if (!appId.equals(SUPER_APP_ID))
return null;
long id = mHelper.insertGroup(values);
getContext().getContentResolver()
.notifyChange(Uri.parse(CONTENT_URI + "/groups"), null);
return uriWithId(uri, id);
} else if (match(uri, "group_members")) {
if (!appId.equals(SUPER_APP_ID)) {
return null;
}
long id = mHelper.insertGroupMember(values);
getContext().getContentResolver().notifyChange(
Uri.parse(CONTENT_URI + "/group_members"), null);
getContext().getContentResolver().notifyChange(
Uri.parse(CONTENT_URI + "/group_contacts"), null);
return uriWithId(uri, id);
}
else if (match(uri, "group_invitations")) {
if (!appId.equals(SUPER_APP_ID)) {
return null;
}
String groupName = values.getAsString(InviteToGroupObj.GROUP_NAME);
Uri dynUpdateUri = Uri.parse(values.getAsString(InviteToGroupObj.DYN_UPDATE_URI));
long gid = values.getAsLong("groupId");
SQLiteDatabase db = mHelper.getWritableDatabase();
mHelper.addToOutgoing(db, appId, values.getAsString(InviteToGroupObj.PARTICIPANTS),
InviteToGroupObj.TYPE, InviteToGroupObj.json(groupName, dynUpdateUri));
getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
return uriWithId(uri, gid);
}
else if (match(uri, "dynamic_groups")) {
if (!appId.equals(SUPER_APP_ID)) {
return null;
}
Uri gUri = Uri.parse(values.getAsString("uri"));
GroupProviders.GroupProvider gp = GroupProviders.forUri(gUri);
String feedName = gp.feedName(gUri);
Maybe<Group> mg = mHelper.groupByFeedName(feedName);
long id = -1;
try {
Group g = mg.get();
id = g.id;
} catch (Maybe.NoValError e) {
ContentValues cv = new ContentValues();
cv.put(Group.NAME, gp.groupName(gUri));
cv.put(Group.FEED_NAME, feedName);
cv.put(Group.DYN_UPDATE_URI, gUri.toString());
String table = DbObject.TABLE;
String[] columns = new String[] { DbObject.FEED_NAME };
String selection = DbObject.CHILD_FEED_NAME + " = ?";
String[] selectionArgs = new String[] { feedName };
Cursor parent = mHelper.getReadableDatabase().query(
table, columns, selection, selectionArgs, null, null, null);
if (parent.moveToFirst()) {
String parentName = parent.getString(0);
table = Group.TABLE;
columns = new String[] { Group._ID };
selection = Group.FEED_NAME + " = ?";
selectionArgs = new String[] { parentName };
Cursor parent2 = mHelper.getReadableDatabase().query(
table, columns, selection, selectionArgs, null, null, null);
if (parent2.moveToFirst()) {
cv.put(Group.PARENT_FEED_ID, parent2.getLong(0));
} else {
Log.e(TAG, "Parent feed found but no id for " + parentName);
}
parent2.close();
} else {
Log.w(TAG, "No parent feed for " + feedName);
}
parent.close();
id = mHelper.insertGroup(cv);
getContext().getContentResolver().notifyChange(
Uri.parse(CONTENT_URI + "/dynamic_groups"), null);
getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/groups"),
null);
}
return uriWithId(uri, id);
}
else if (match(uri, "dynamic_group_member")) {
if (!appId.equals(SUPER_APP_ID)) {
return null;
}
SQLiteDatabase db = mHelper.getWritableDatabase();
db.beginTransaction();
try {
ContentValues cv = new ContentValues();
String pubKeyStr = values.getAsString(Contact.PUBLIC_KEY);
RSAPublicKey k = DBIdentityProvider.publicKeyFromString(pubKeyStr);
String personId = mIdent.personIdForPublicKey(k);
if (!personId.equals(mIdent.userPersonId())) {
cv.put(Contact.PUBLIC_KEY, values.getAsString(Contact.PUBLIC_KEY));
cv.put(Contact.NAME, values.getAsString(Contact.NAME));
cv.put(Contact.EMAIL, values.getAsString(Contact.EMAIL));
if (values.getAsString(Contact.PICTURE) != null) {
cv.put(Contact.PICTURE, values.getAsByteArray(Contact.PICTURE));
}
long cid = -1;
Contact contact = mHelper.contactForPersonId(personId).otherwise(Contact.NA());
if (contact.id > -1) {
cid = contact.id;
} else {
cid = mHelper.insertContact(db, cv);
}
if (cid > -1) {
ContentValues gv = new ContentValues();
gv.put(GroupMember.GLOBAL_CONTACT_ID,
values.getAsString(GroupMember.GLOBAL_CONTACT_ID));
gv.put(GroupMember.GROUP_ID, values.getAsLong(GroupMember.GROUP_ID));
gv.put(GroupMember.CONTACT_ID, cid);
mHelper.insertGroupMember(db, gv);
getContext().getContentResolver().notifyChange(
Uri.parse(CONTENT_URI + "/group_members"), null);
getContext().getContentResolver().notifyChange(
Uri.parse(CONTENT_URI + "/contacts"), null);
getContext().getContentResolver().notifyChange(
Uri.parse(CONTENT_URI + "/group_contacts"), null);
// Add subscription to this private group feed
ContentValues sv = new ContentValues();
sv = new ContentValues();
sv.put(Subscriber.CONTACT_ID, cid);
sv.put(Subscriber.FEED_NAME, values.getAsString(Group.FEED_NAME));
mHelper.insertSubscriber(db, sv);
ContentValues xv = new ContentValues();
xv.put(Subscriber.CONTACT_ID, cid);
xv.put(Subscriber.FEED_NAME, "friend");
mHelper.insertSubscriber(db, xv);
getContext().getContentResolver().notifyChange(
Uri.parse(CONTENT_URI + "/subscribers"), null);
db.setTransactionSuccessful();
}
return uriWithId(uri, cid);
} else {
Log.i(TAG, "Omitting self.");
return uriWithId(uri, Contact.MY_ID);
}
} finally {
db.endTransaction();
}
} else {
Log.e(TAG, "Failed to insert into " + uri);
return null;
}
}
| public Uri insert(Uri uri, ContentValues values) {
ContentResolver resolver = getContext().getContentResolver();
Log.i(TAG, "Inserting at uri: " + uri + ", " + values);
final String appId = getCallingActivityId();
if (appId == null) {
Log.d(TAG, "No AppId for calling activity. Ignoring query.");
return null;
}
List<String> segs = uri.getPathSegments();
if (match(uri, "feeds", "me")) {
if (!appId.equals(SUPER_APP_ID)) {
return null;
}
try {
JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
mHelper.addToFeed(appId, "friend", values.getAsString(DbObject.TYPE),
json);
resolver.notifyChange(Feed.uriForName("me"), null);
resolver.notifyChange(Feed.uriForName("friend"), null);
return Uri.parse(uri.toString());
} catch(JSONException e){
return null;
}
} else if (match(uri, "feeds", "friend", ".+")) {
if (!appId.equals(SUPER_APP_ID)) {
return null;
}
try {
/*
* A "virtual feed" for direct messaging with a friend.
* This can be thought of us a sequence of objects "in reply to"
* a virtual object between two contacts.
*/
/*long timestamp = new Date().getTime();
String type = values.getAsString(DbObject.TYPE);
JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
mHelper.prepareForSending(json, type, timestamp, appId);
mHelper.addObjectByJson(Contact.MY_ID, json, new byte[0]);*/
// stitch, stitch
long contactId = Long.parseLong(segs.get(2));
String type = values.getAsString(DbObject.TYPE);
JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
Helpers.sendMessage(getContext(), contactId, json, type);
resolver.notifyChange(uri, null);
return uri;
}
catch(JSONException e){
return null;
}
} else if (match(uri, "feeds", ".+")) {
String feedName = segs.get(1);
try {
JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
mHelper.addToFeed(appId, feedName, values.getAsString(DbObject.TYPE),
json);
notifyDependencies(resolver, feedName);
if (DBG) Log.d(TAG, "just inserted " + values.getAsString(DbObject.JSON));
return Uri.parse(uri.toString()); // TODO: is there a reason for this?
}
catch(JSONException e) {
return null;
}
} else if(match(uri, "out")) {
try {
JSONObject obj = new JSONObject(values.getAsString("json"));
mHelper.addToOutgoing(appId, values.getAsString(DbObject.DESTINATION),
values.getAsString(DbObject.TYPE), obj);
resolver.notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
return Uri.parse(uri.toString());
}
catch(JSONException e){
return null;
}
} else if (match(uri, "contacts")) {
if (!appId.equals(SUPER_APP_ID)) {
return null;
}
long id = mHelper.insertContact(values);
resolver.notifyChange(Uri.parse(CONTENT_URI + "/contacts"), null);
return uriWithId(uri, id);
} else if (match(uri, "subscribers")) {
// Question: Should this be restricted?
// if(!appId.equals(SUPER_APP_ID)) return null;
long id = mHelper.insertSubscriber(values);
resolver.notifyChange(Uri.parse(CONTENT_URI + "/subscribers"), null);
return uriWithId(uri, id);
} else if (match(uri, "groups")) {
if (!appId.equals(SUPER_APP_ID))
return null;
long id = mHelper.insertGroup(values);
getContext().getContentResolver()
.notifyChange(Uri.parse(CONTENT_URI + "/groups"), null);
return uriWithId(uri, id);
} else if (match(uri, "group_members")) {
if (!appId.equals(SUPER_APP_ID)) {
return null;
}
long id = mHelper.insertGroupMember(values);
getContext().getContentResolver().notifyChange(
Uri.parse(CONTENT_URI + "/group_members"), null);
getContext().getContentResolver().notifyChange(
Uri.parse(CONTENT_URI + "/group_contacts"), null);
return uriWithId(uri, id);
}
else if (match(uri, "group_invitations")) {
if (!appId.equals(SUPER_APP_ID)) {
return null;
}
String groupName = values.getAsString(InviteToGroupObj.GROUP_NAME);
Uri dynUpdateUri = Uri.parse(values.getAsString(InviteToGroupObj.DYN_UPDATE_URI));
long gid = values.getAsLong("groupId");
SQLiteDatabase db = mHelper.getWritableDatabase();
mHelper.addToOutgoing(db, appId, values.getAsString(InviteToGroupObj.PARTICIPANTS),
InviteToGroupObj.TYPE, InviteToGroupObj.json(groupName, dynUpdateUri));
getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
return uriWithId(uri, gid);
}
else if (match(uri, "dynamic_groups")) {
if (!appId.equals(SUPER_APP_ID)) {
return null;
}
Uri gUri = Uri.parse(values.getAsString("uri"));
GroupProviders.GroupProvider gp = GroupProviders.forUri(gUri);
String feedName = gp.feedName(gUri);
Maybe<Group> mg = mHelper.groupByFeedName(feedName);
long id = -1;
try {
Group g = mg.get();
id = g.id;
} catch (Maybe.NoValError e) {
ContentValues cv = new ContentValues();
cv.put(Group.NAME, gp.groupName(gUri));
cv.put(Group.FEED_NAME, feedName);
cv.put(Group.DYN_UPDATE_URI, gUri.toString());
String table = DbObject.TABLE;
String[] columns = new String[] { DbObject.FEED_NAME };
String selection = DbObject.CHILD_FEED_NAME + " = ?";
String[] selectionArgs = new String[] { feedName };
Cursor parent = mHelper.getReadableDatabase().query(
table, columns, selection, selectionArgs, null, null, null);
if (parent.moveToFirst()) {
String parentName = parent.getString(0);
table = Group.TABLE;
columns = new String[] { Group._ID };
selection = Group.FEED_NAME + " = ?";
selectionArgs = new String[] { parentName };
Cursor parent2 = mHelper.getReadableDatabase().query(
table, columns, selection, selectionArgs, null, null, null);
if (parent2.moveToFirst()) {
cv.put(Group.PARENT_FEED_ID, parent2.getLong(0));
} else {
Log.e(TAG, "Parent feed found but no id for " + parentName);
}
parent2.close();
} else {
Log.w(TAG, "No parent feed for " + feedName);
}
parent.close();
id = mHelper.insertGroup(cv);
getContext().getContentResolver().notifyChange(
Uri.parse(CONTENT_URI + "/dynamic_groups"), null);
getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/groups"),
null);
}
return uriWithId(uri, id);
}
else if (match(uri, "dynamic_group_member")) {
if (!appId.equals(SUPER_APP_ID)) {
return null;
}
SQLiteDatabase db = mHelper.getWritableDatabase();
try {
db.beginTransaction();
} catch(Exception e) {
Log.e(TAG, "Database probably locked:??", e);
return null;
}
try {
ContentValues cv = new ContentValues();
String pubKeyStr = values.getAsString(Contact.PUBLIC_KEY);
RSAPublicKey k = DBIdentityProvider.publicKeyFromString(pubKeyStr);
String personId = mIdent.personIdForPublicKey(k);
if (!personId.equals(mIdent.userPersonId())) {
cv.put(Contact.PUBLIC_KEY, values.getAsString(Contact.PUBLIC_KEY));
cv.put(Contact.NAME, values.getAsString(Contact.NAME));
cv.put(Contact.EMAIL, values.getAsString(Contact.EMAIL));
if (values.getAsString(Contact.PICTURE) != null) {
cv.put(Contact.PICTURE, values.getAsByteArray(Contact.PICTURE));
}
long cid = -1;
Contact contact = mHelper.contactForPersonId(personId).otherwise(Contact.NA());
if (contact.id > -1) {
cid = contact.id;
} else {
cid = mHelper.insertContact(db, cv);
}
if (cid > -1) {
ContentValues gv = new ContentValues();
gv.put(GroupMember.GLOBAL_CONTACT_ID,
values.getAsString(GroupMember.GLOBAL_CONTACT_ID));
gv.put(GroupMember.GROUP_ID, values.getAsLong(GroupMember.GROUP_ID));
gv.put(GroupMember.CONTACT_ID, cid);
mHelper.insertGroupMember(db, gv);
getContext().getContentResolver().notifyChange(
Uri.parse(CONTENT_URI + "/group_members"), null);
getContext().getContentResolver().notifyChange(
Uri.parse(CONTENT_URI + "/contacts"), null);
getContext().getContentResolver().notifyChange(
Uri.parse(CONTENT_URI + "/group_contacts"), null);
// Add subscription to this private group feed
ContentValues sv = new ContentValues();
sv = new ContentValues();
sv.put(Subscriber.CONTACT_ID, cid);
sv.put(Subscriber.FEED_NAME, values.getAsString(Group.FEED_NAME));
mHelper.insertSubscriber(db, sv);
ContentValues xv = new ContentValues();
xv.put(Subscriber.CONTACT_ID, cid);
xv.put(Subscriber.FEED_NAME, "friend");
mHelper.insertSubscriber(db, xv);
getContext().getContentResolver().notifyChange(
Uri.parse(CONTENT_URI + "/subscribers"), null);
db.setTransactionSuccessful();
}
return uriWithId(uri, cid);
} else {
Log.i(TAG, "Omitting self.");
return uriWithId(uri, Contact.MY_ID);
}
} finally {
db.endTransaction();
}
} else {
Log.e(TAG, "Failed to insert into " + uri);
return null;
}
}
|
diff --git a/modules/amazon-ec2-provisioner/src/main/java/com/elasticgrid/platforms/ec2/EC2CloudPlatformManagerFactory.java b/modules/amazon-ec2-provisioner/src/main/java/com/elasticgrid/platforms/ec2/EC2CloudPlatformManagerFactory.java
index cec75f04..ff1e4024 100644
--- a/modules/amazon-ec2-provisioner/src/main/java/com/elasticgrid/platforms/ec2/EC2CloudPlatformManagerFactory.java
+++ b/modules/amazon-ec2-provisioner/src/main/java/com/elasticgrid/platforms/ec2/EC2CloudPlatformManagerFactory.java
@@ -1,88 +1,88 @@
/**
* Elastic Grid
* Copyright (C) 2008-2009 Elastic Grid, LLC.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.elasticgrid.platforms.ec2;
import com.elasticgrid.cluster.spi.CloudPlatformManagerFactory;
import com.elasticgrid.config.EC2Configuration;
import com.elasticgrid.model.ec2.EC2Cluster;
import com.elasticgrid.platforms.ec2.discovery.EC2ClusterLocator;
import com.elasticgrid.platforms.ec2.discovery.EC2SecurityGroupsClusterLocator;
import com.elasticgrid.utils.amazon.AWSUtils;
import com.xerox.amazonws.ec2.Jec2;
import java.io.IOException;
import java.util.Properties;
public class EC2CloudPlatformManagerFactory implements CloudPlatformManagerFactory<EC2Cluster> {
static EC2CloudPlatformManager instance;
static EC2SecurityGroupsClusterLocator clusterLocator;
static EC2Instantiator nodeInstantiator;
static Jec2 ec2;
public EC2CloudPlatformManager getInstance() throws IOException {
if (instance == null) {
Properties config = AWSUtils.loadEC2Configuration();
String awsAccessId = config.getProperty(EC2Configuration.AWS_ACCESS_ID);
String awsSecretKey = config.getProperty(EC2Configuration.AWS_SECRET_KEY);
boolean secured = Boolean.parseBoolean(config.getProperty(EC2Configuration.AWS_EC2_SECURED));
instance = new EC2CloudPlatformManager();
instance.setOverridesBucket(config.getProperty(EC2Configuration.EG_OVERRIDES_BUCKET));
instance.setAwsAccessID(awsAccessId);
instance.setAwsSecretKey(awsSecretKey);
instance.setAwsSecured(secured);
instance.setAmi32(config.getProperty(EC2Configuration.AWS_EC2_AMI32));
- instance.setAmi64(config.getProperty(EC2Configuration.AWS_EC2_AMI32));
+ instance.setAmi64(config.getProperty(EC2Configuration.AWS_EC2_AMI64));
instance.setClusterLocator(getClusterLocator());
instance.setNodeInstantiator(getNodeInstantiator());
String timeout = config.getProperty(EC2Configuration.EG_CLUSTER_START_STOP_TIMEOUT);
if (timeout != null)
instance.setStartStopTimeout(Integer.parseInt(timeout));
}
return instance;
}
public EC2ClusterLocator getClusterLocator() throws IOException {
if (clusterLocator == null) {
clusterLocator = new EC2SecurityGroupsClusterLocator();
clusterLocator.setEc2(getEC2());
}
return clusterLocator;
}
public EC2Instantiator getNodeInstantiator() throws IOException {
if (nodeInstantiator == null) {
nodeInstantiator = new EC2InstantiatorImpl();
((EC2InstantiatorImpl) nodeInstantiator).setEc2(getEC2());
}
return nodeInstantiator;
}
private Jec2 getEC2() throws IOException {
if (ec2 == null) {
Properties config = AWSUtils.loadEC2Configuration();
String awsAccessId = config.getProperty(EC2Configuration.AWS_ACCESS_ID);
String awsSecretKey = config.getProperty(EC2Configuration.AWS_SECRET_KEY);
boolean secured = Boolean.parseBoolean(config.getProperty(EC2Configuration.AWS_EC2_SECURED));
ec2 = new Jec2(awsAccessId, awsSecretKey, secured);
}
return ec2;
}
}
| true | true | public EC2CloudPlatformManager getInstance() throws IOException {
if (instance == null) {
Properties config = AWSUtils.loadEC2Configuration();
String awsAccessId = config.getProperty(EC2Configuration.AWS_ACCESS_ID);
String awsSecretKey = config.getProperty(EC2Configuration.AWS_SECRET_KEY);
boolean secured = Boolean.parseBoolean(config.getProperty(EC2Configuration.AWS_EC2_SECURED));
instance = new EC2CloudPlatformManager();
instance.setOverridesBucket(config.getProperty(EC2Configuration.EG_OVERRIDES_BUCKET));
instance.setAwsAccessID(awsAccessId);
instance.setAwsSecretKey(awsSecretKey);
instance.setAwsSecured(secured);
instance.setAmi32(config.getProperty(EC2Configuration.AWS_EC2_AMI32));
instance.setAmi64(config.getProperty(EC2Configuration.AWS_EC2_AMI32));
instance.setClusterLocator(getClusterLocator());
instance.setNodeInstantiator(getNodeInstantiator());
String timeout = config.getProperty(EC2Configuration.EG_CLUSTER_START_STOP_TIMEOUT);
if (timeout != null)
instance.setStartStopTimeout(Integer.parseInt(timeout));
}
return instance;
}
| public EC2CloudPlatformManager getInstance() throws IOException {
if (instance == null) {
Properties config = AWSUtils.loadEC2Configuration();
String awsAccessId = config.getProperty(EC2Configuration.AWS_ACCESS_ID);
String awsSecretKey = config.getProperty(EC2Configuration.AWS_SECRET_KEY);
boolean secured = Boolean.parseBoolean(config.getProperty(EC2Configuration.AWS_EC2_SECURED));
instance = new EC2CloudPlatformManager();
instance.setOverridesBucket(config.getProperty(EC2Configuration.EG_OVERRIDES_BUCKET));
instance.setAwsAccessID(awsAccessId);
instance.setAwsSecretKey(awsSecretKey);
instance.setAwsSecured(secured);
instance.setAmi32(config.getProperty(EC2Configuration.AWS_EC2_AMI32));
instance.setAmi64(config.getProperty(EC2Configuration.AWS_EC2_AMI64));
instance.setClusterLocator(getClusterLocator());
instance.setNodeInstantiator(getNodeInstantiator());
String timeout = config.getProperty(EC2Configuration.EG_CLUSTER_START_STOP_TIMEOUT);
if (timeout != null)
instance.setStartStopTimeout(Integer.parseInt(timeout));
}
return instance;
}
|
diff --git a/bundles/org.eclipse.e4.tools.emf.ui/src/org/eclipse/e4/tools/emf/ui/internal/common/component/PartEditor.java b/bundles/org.eclipse.e4.tools.emf.ui/src/org/eclipse/e4/tools/emf/ui/internal/common/component/PartEditor.java
index 340fa11e..929f17a9 100644
--- a/bundles/org.eclipse.e4.tools.emf.ui/src/org/eclipse/e4/tools/emf/ui/internal/common/component/PartEditor.java
+++ b/bundles/org.eclipse.e4.tools.emf.ui/src/org/eclipse/e4/tools/emf/ui/internal/common/component/PartEditor.java
@@ -1,330 +1,330 @@
/*******************************************************************************
* Copyright (c) 2010 BestSolution.at and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tom Schindl <[email protected]> - initial API and implementation
******************************************************************************/
package org.eclipse.e4.tools.emf.ui.internal.common.component;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map.Entry;
import org.eclipse.core.databinding.observable.list.IObservableList;
import org.eclipse.core.databinding.observable.list.WritableList;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.databinding.property.list.IListProperty;
import org.eclipse.e4.tools.emf.ui.common.component.AbstractComponentEditor;
import org.eclipse.e4.tools.emf.ui.internal.common.ModelEditor;
import org.eclipse.e4.tools.emf.ui.internal.common.VirtualEntry;
import org.eclipse.e4.ui.model.application.MApplicationPackage;
import org.eclipse.e4.ui.model.application.MPart;
import org.eclipse.emf.databinding.EMFDataBindingContext;
import org.eclipse.emf.databinding.EMFProperties;
import org.eclipse.emf.databinding.edit.EMFEditProperties;
import org.eclipse.emf.databinding.edit.IEMFEditListProperty;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.jface.databinding.swt.IWidgetValueProperty;
import org.eclipse.jface.databinding.swt.WidgetProperties;
import org.eclipse.jface.databinding.viewers.ObservableListContentProvider;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
public class PartEditor extends AbstractComponentEditor {
private Composite composite;
private Image image;
private EMFDataBindingContext context;
private IListProperty PART__MENUS = EMFProperties.list(MApplicationPackage.Literals.PART__MENUS);
private IListProperty HANDLER_CONTAINER__HANDLERS = EMFProperties.list(MApplicationPackage.Literals.HANDLER_CONTAINER__HANDLERS);
private IListProperty BINDING_CONTAINER__BINDINGS = EMFProperties.list(MApplicationPackage.Literals.BINDING_CONTAINER__BINDINGS);
public PartEditor(EditingDomain editingDomain) {
super(editingDomain);
}
@Override
public Image getImage(Object element, Display display) {
if( image == null ) {
try {
image = loadSharedImage(display, new URL("platform:/plugin/org.eclipse.e4.ui.model.workbench.edit/icons/full/obj16/Part.gif"));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return image;
}
@Override
public String getLabel(Object element) {
return "Part";
}
@Override
public String getDescription(Object element) {
return "Part Bla Bla Bla Bla";
}
@Override
public Composite getEditor(Composite parent, Object object) {
if( composite == null ) {
context = new EMFDataBindingContext();
composite = createForm(parent,context, getMaster());
}
getMaster().setValue(object);
return composite;
}
protected Composite createForm(Composite parent, EMFDataBindingContext context, IObservableValue master) {
parent = new Composite(parent,SWT.NONE);
parent.setLayout(new GridLayout(3, false));
IWidgetValueProperty textProp = WidgetProperties.text(SWT.Modify);
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Id");
Text t = new Text(parent, SWT.BORDER);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan=2;
t.setLayoutData(gd);
context.bindValue(textProp.observeDelayed(200,t), EMFEditProperties.value(getEditingDomain(), MApplicationPackage.Literals.APPLICATION_ELEMENT__ID).observeDetail(master));
}
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Label");
Text t = new Text(parent, SWT.BORDER);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan=2;
t.setLayoutData(gd);
context.bindValue(textProp.observeDelayed(200,t), EMFEditProperties.value(getEditingDomain(), MApplicationPackage.Literals.UI_LABEL__LABEL).observeDetail(master));
}
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Tooltip");
Text t = new Text(parent, SWT.BORDER);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan=2;
t.setLayoutData(gd);
context.bindValue(textProp.observeDelayed(200,t), EMFEditProperties.value(getEditingDomain(), MApplicationPackage.Literals.UI_LABEL__TOOLTIP).observeDetail(master));
}
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Icon URI");
Text t = new Text(parent, SWT.BORDER);
t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
context.bindValue(textProp.observeDelayed(200,t), EMFEditProperties.value(getEditingDomain(), MApplicationPackage.Literals.UI_LABEL__ICON_URI).observeDetail(master));
Button b = new Button(parent, SWT.PUSH|SWT.FLAT);
b.setText("Find ...");
}
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Class URI");
Text t = new Text(parent, SWT.BORDER);
t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
context.bindValue(textProp.observeDelayed(200,t), EMFEditProperties.value(getEditingDomain(), MApplicationPackage.Literals.CONTRIBUTION__URI).observeDetail(master));
Button b = new Button(parent, SWT.PUSH|SWT.FLAT);
b.setText("Find ...");
}
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Persited State");
l.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
TableViewer tableviewer = new TableViewer(parent);
ObservableListContentProvider cp = new ObservableListContentProvider();
tableviewer.setContentProvider(cp);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.heightHint = 80;
tableviewer.getControl().setLayoutData(gd);
TableViewerColumn column = new TableViewerColumn(tableviewer, SWT.NONE);
column.getColumn().setText("Key");
column.getColumn().setWidth(200);
column.setLabelProvider(new ColumnLabelProvider() {
@SuppressWarnings("unchecked")
@Override
public String getText(Object element) {
Entry<String, String> entry = (Entry<String, String>) element;
return entry.getKey();
}
- });
+ });
//FIXME How can we react upon changes in the Map-Value?
column = new TableViewerColumn(tableviewer, SWT.NONE);
column.getColumn().setText("Value");
column.getColumn().setWidth(200);
column.setLabelProvider(new ColumnLabelProvider() {
@SuppressWarnings("unchecked")
@Override
public String getText(Object element) {
Entry<String, String> entry = (Entry<String, String>) element;
return entry.getValue();
}
});
IEMFEditListProperty prop = EMFEditProperties.list(getEditingDomain(), MApplicationPackage.Literals.CONTRIBUTION__PERSISTED_STATE);
tableviewer.setInput(prop.observeDetail(getMaster()));
Composite buttonComp = new Composite(parent, SWT.NONE);
buttonComp.setLayoutData(new GridData(GridData.FILL,GridData.END,false,false));
GridLayout gl = new GridLayout();
gl.marginLeft=0;
gl.marginRight=0;
gl.marginWidth=0;
gl.marginHeight=0;
buttonComp.setLayout(gl);
Button b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
b.setText("Add ...");
b.setImage(getImage(b.getDisplay(), TABLE_ADD_IMAGE));
b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
b.setText("Remove");
b.setImage(getImage(b.getDisplay(), TABLE_DELETE_IMAGE));
b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
}
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Variables");
l.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
ListViewer viewer = new ListViewer(parent);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan=2;
gd.heightHint = 80;
viewer.getList().setLayoutData(gd);
}
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Properties");
l.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
TableViewer tableviewer = new TableViewer(parent);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan=2;
gd.heightHint = 80;
tableviewer.getTable().setHeaderVisible(true);
tableviewer.getControl().setLayoutData(gd);
TableViewerColumn column = new TableViewerColumn(tableviewer, SWT.NONE);
column.getColumn().setText("Key");
column.getColumn().setWidth(200);
column = new TableViewerColumn(tableviewer, SWT.NONE);
column.getColumn().setText("Value");
column.getColumn().setWidth(200);
}
ControlFactory.createTagsWidget(parent, this);
// // ------------------------------------------------------------
//
// l = new Label(parent, SWT.NONE);
// l.setText("");
//
// Composite booleanContainer = new Composite(parent,SWT.NONE);
// gd = new GridData(GridData.FILL_HORIZONTAL);
// gd.horizontalSpan=2;
// booleanContainer.setBackgroundMode(SWT.INHERIT_DEFAULT);
// booleanContainer.setLayoutData(gd);
// booleanContainer.setLayout(new GridLayout(4,false));
//
// Button checkbox = new Button(booleanContainer, SWT.CHECK);
// checkbox.setText("to render");
//
// checkbox = new Button(booleanContainer, SWT.CHECK);
// checkbox.setText("on Top");
//
// checkbox = new Button(booleanContainer, SWT.CHECK);
// checkbox.setText("visible");
//
// checkbox = new Button(booleanContainer, SWT.CHECK);
// checkbox.setText("closeable");
return parent;
}
@Override
public IObservableList getChildList(Object element) {
WritableList list = new WritableList();
list.add(new VirtualEntry<Object>( ModelEditor.VIRTUAL_MENU, PART__MENUS, element, "Menus") {
@Override
protected boolean accepted(Object o) {
return true;
}
});
list.add(new VirtualEntry<Object>( ModelEditor.VIRTUAL_HANDLER, HANDLER_CONTAINER__HANDLERS, element, "Handlers") {
@Override
protected boolean accepted(Object o) {
return true;
}
});
list.add(new VirtualEntry<Object>( ModelEditor.VIRTUAL_BINDING, BINDING_CONTAINER__BINDINGS, element, "Bindings") {
@Override
protected boolean accepted(Object o) {
return true;
}
});
return list;
}
@Override
public String getDetailLabel(Object element) {
MPart o = (MPart) element;
return o.getLabel();
}
}
| true | true | protected Composite createForm(Composite parent, EMFDataBindingContext context, IObservableValue master) {
parent = new Composite(parent,SWT.NONE);
parent.setLayout(new GridLayout(3, false));
IWidgetValueProperty textProp = WidgetProperties.text(SWT.Modify);
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Id");
Text t = new Text(parent, SWT.BORDER);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan=2;
t.setLayoutData(gd);
context.bindValue(textProp.observeDelayed(200,t), EMFEditProperties.value(getEditingDomain(), MApplicationPackage.Literals.APPLICATION_ELEMENT__ID).observeDetail(master));
}
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Label");
Text t = new Text(parent, SWT.BORDER);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan=2;
t.setLayoutData(gd);
context.bindValue(textProp.observeDelayed(200,t), EMFEditProperties.value(getEditingDomain(), MApplicationPackage.Literals.UI_LABEL__LABEL).observeDetail(master));
}
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Tooltip");
Text t = new Text(parent, SWT.BORDER);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan=2;
t.setLayoutData(gd);
context.bindValue(textProp.observeDelayed(200,t), EMFEditProperties.value(getEditingDomain(), MApplicationPackage.Literals.UI_LABEL__TOOLTIP).observeDetail(master));
}
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Icon URI");
Text t = new Text(parent, SWT.BORDER);
t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
context.bindValue(textProp.observeDelayed(200,t), EMFEditProperties.value(getEditingDomain(), MApplicationPackage.Literals.UI_LABEL__ICON_URI).observeDetail(master));
Button b = new Button(parent, SWT.PUSH|SWT.FLAT);
b.setText("Find ...");
}
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Class URI");
Text t = new Text(parent, SWT.BORDER);
t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
context.bindValue(textProp.observeDelayed(200,t), EMFEditProperties.value(getEditingDomain(), MApplicationPackage.Literals.CONTRIBUTION__URI).observeDetail(master));
Button b = new Button(parent, SWT.PUSH|SWT.FLAT);
b.setText("Find ...");
}
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Persited State");
l.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
TableViewer tableviewer = new TableViewer(parent);
ObservableListContentProvider cp = new ObservableListContentProvider();
tableviewer.setContentProvider(cp);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.heightHint = 80;
tableviewer.getControl().setLayoutData(gd);
TableViewerColumn column = new TableViewerColumn(tableviewer, SWT.NONE);
column.getColumn().setText("Key");
column.getColumn().setWidth(200);
column.setLabelProvider(new ColumnLabelProvider() {
@SuppressWarnings("unchecked")
@Override
public String getText(Object element) {
Entry<String, String> entry = (Entry<String, String>) element;
return entry.getKey();
}
});
//FIXME How can we react upon changes in the Map-Value?
column = new TableViewerColumn(tableviewer, SWT.NONE);
column.getColumn().setText("Value");
column.getColumn().setWidth(200);
column.setLabelProvider(new ColumnLabelProvider() {
@SuppressWarnings("unchecked")
@Override
public String getText(Object element) {
Entry<String, String> entry = (Entry<String, String>) element;
return entry.getValue();
}
});
IEMFEditListProperty prop = EMFEditProperties.list(getEditingDomain(), MApplicationPackage.Literals.CONTRIBUTION__PERSISTED_STATE);
tableviewer.setInput(prop.observeDetail(getMaster()));
Composite buttonComp = new Composite(parent, SWT.NONE);
buttonComp.setLayoutData(new GridData(GridData.FILL,GridData.END,false,false));
GridLayout gl = new GridLayout();
gl.marginLeft=0;
gl.marginRight=0;
gl.marginWidth=0;
gl.marginHeight=0;
buttonComp.setLayout(gl);
Button b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
b.setText("Add ...");
b.setImage(getImage(b.getDisplay(), TABLE_ADD_IMAGE));
b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
b.setText("Remove");
b.setImage(getImage(b.getDisplay(), TABLE_DELETE_IMAGE));
b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
}
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Variables");
l.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
ListViewer viewer = new ListViewer(parent);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan=2;
gd.heightHint = 80;
viewer.getList().setLayoutData(gd);
}
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Properties");
l.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
TableViewer tableviewer = new TableViewer(parent);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan=2;
gd.heightHint = 80;
tableviewer.getTable().setHeaderVisible(true);
tableviewer.getControl().setLayoutData(gd);
TableViewerColumn column = new TableViewerColumn(tableviewer, SWT.NONE);
column.getColumn().setText("Key");
column.getColumn().setWidth(200);
column = new TableViewerColumn(tableviewer, SWT.NONE);
column.getColumn().setText("Value");
column.getColumn().setWidth(200);
}
ControlFactory.createTagsWidget(parent, this);
// // ------------------------------------------------------------
//
// l = new Label(parent, SWT.NONE);
// l.setText("");
//
// Composite booleanContainer = new Composite(parent,SWT.NONE);
// gd = new GridData(GridData.FILL_HORIZONTAL);
// gd.horizontalSpan=2;
// booleanContainer.setBackgroundMode(SWT.INHERIT_DEFAULT);
// booleanContainer.setLayoutData(gd);
// booleanContainer.setLayout(new GridLayout(4,false));
//
// Button checkbox = new Button(booleanContainer, SWT.CHECK);
// checkbox.setText("to render");
//
// checkbox = new Button(booleanContainer, SWT.CHECK);
// checkbox.setText("on Top");
//
// checkbox = new Button(booleanContainer, SWT.CHECK);
// checkbox.setText("visible");
//
// checkbox = new Button(booleanContainer, SWT.CHECK);
// checkbox.setText("closeable");
return parent;
}
| protected Composite createForm(Composite parent, EMFDataBindingContext context, IObservableValue master) {
parent = new Composite(parent,SWT.NONE);
parent.setLayout(new GridLayout(3, false));
IWidgetValueProperty textProp = WidgetProperties.text(SWT.Modify);
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Id");
Text t = new Text(parent, SWT.BORDER);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan=2;
t.setLayoutData(gd);
context.bindValue(textProp.observeDelayed(200,t), EMFEditProperties.value(getEditingDomain(), MApplicationPackage.Literals.APPLICATION_ELEMENT__ID).observeDetail(master));
}
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Label");
Text t = new Text(parent, SWT.BORDER);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan=2;
t.setLayoutData(gd);
context.bindValue(textProp.observeDelayed(200,t), EMFEditProperties.value(getEditingDomain(), MApplicationPackage.Literals.UI_LABEL__LABEL).observeDetail(master));
}
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Tooltip");
Text t = new Text(parent, SWT.BORDER);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan=2;
t.setLayoutData(gd);
context.bindValue(textProp.observeDelayed(200,t), EMFEditProperties.value(getEditingDomain(), MApplicationPackage.Literals.UI_LABEL__TOOLTIP).observeDetail(master));
}
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Icon URI");
Text t = new Text(parent, SWT.BORDER);
t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
context.bindValue(textProp.observeDelayed(200,t), EMFEditProperties.value(getEditingDomain(), MApplicationPackage.Literals.UI_LABEL__ICON_URI).observeDetail(master));
Button b = new Button(parent, SWT.PUSH|SWT.FLAT);
b.setText("Find ...");
}
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Class URI");
Text t = new Text(parent, SWT.BORDER);
t.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
context.bindValue(textProp.observeDelayed(200,t), EMFEditProperties.value(getEditingDomain(), MApplicationPackage.Literals.CONTRIBUTION__URI).observeDetail(master));
Button b = new Button(parent, SWT.PUSH|SWT.FLAT);
b.setText("Find ...");
}
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Persited State");
l.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
TableViewer tableviewer = new TableViewer(parent);
ObservableListContentProvider cp = new ObservableListContentProvider();
tableviewer.setContentProvider(cp);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.heightHint = 80;
tableviewer.getControl().setLayoutData(gd);
TableViewerColumn column = new TableViewerColumn(tableviewer, SWT.NONE);
column.getColumn().setText("Key");
column.getColumn().setWidth(200);
column.setLabelProvider(new ColumnLabelProvider() {
@SuppressWarnings("unchecked")
@Override
public String getText(Object element) {
Entry<String, String> entry = (Entry<String, String>) element;
return entry.getKey();
}
});
//FIXME How can we react upon changes in the Map-Value?
column = new TableViewerColumn(tableviewer, SWT.NONE);
column.getColumn().setText("Value");
column.getColumn().setWidth(200);
column.setLabelProvider(new ColumnLabelProvider() {
@SuppressWarnings("unchecked")
@Override
public String getText(Object element) {
Entry<String, String> entry = (Entry<String, String>) element;
return entry.getValue();
}
});
IEMFEditListProperty prop = EMFEditProperties.list(getEditingDomain(), MApplicationPackage.Literals.CONTRIBUTION__PERSISTED_STATE);
tableviewer.setInput(prop.observeDetail(getMaster()));
Composite buttonComp = new Composite(parent, SWT.NONE);
buttonComp.setLayoutData(new GridData(GridData.FILL,GridData.END,false,false));
GridLayout gl = new GridLayout();
gl.marginLeft=0;
gl.marginRight=0;
gl.marginWidth=0;
gl.marginHeight=0;
buttonComp.setLayout(gl);
Button b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
b.setText("Add ...");
b.setImage(getImage(b.getDisplay(), TABLE_ADD_IMAGE));
b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
b = new Button(buttonComp, SWT.PUSH | SWT.FLAT);
b.setText("Remove");
b.setImage(getImage(b.getDisplay(), TABLE_DELETE_IMAGE));
b.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false));
}
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Variables");
l.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
ListViewer viewer = new ListViewer(parent);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan=2;
gd.heightHint = 80;
viewer.getList().setLayoutData(gd);
}
// ------------------------------------------------------------
{
Label l = new Label(parent, SWT.NONE);
l.setText("Properties");
l.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
TableViewer tableviewer = new TableViewer(parent);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan=2;
gd.heightHint = 80;
tableviewer.getTable().setHeaderVisible(true);
tableviewer.getControl().setLayoutData(gd);
TableViewerColumn column = new TableViewerColumn(tableviewer, SWT.NONE);
column.getColumn().setText("Key");
column.getColumn().setWidth(200);
column = new TableViewerColumn(tableviewer, SWT.NONE);
column.getColumn().setText("Value");
column.getColumn().setWidth(200);
}
ControlFactory.createTagsWidget(parent, this);
// // ------------------------------------------------------------
//
// l = new Label(parent, SWT.NONE);
// l.setText("");
//
// Composite booleanContainer = new Composite(parent,SWT.NONE);
// gd = new GridData(GridData.FILL_HORIZONTAL);
// gd.horizontalSpan=2;
// booleanContainer.setBackgroundMode(SWT.INHERIT_DEFAULT);
// booleanContainer.setLayoutData(gd);
// booleanContainer.setLayout(new GridLayout(4,false));
//
// Button checkbox = new Button(booleanContainer, SWT.CHECK);
// checkbox.setText("to render");
//
// checkbox = new Button(booleanContainer, SWT.CHECK);
// checkbox.setText("on Top");
//
// checkbox = new Button(booleanContainer, SWT.CHECK);
// checkbox.setText("visible");
//
// checkbox = new Button(booleanContainer, SWT.CHECK);
// checkbox.setText("closeable");
return parent;
}
|
diff --git a/orcid-web/src/main/java/org/orcid/pojo/ajaxForm/Contributor.java b/orcid-web/src/main/java/org/orcid/pojo/ajaxForm/Contributor.java
index 097c071ae0..2a00f17388 100644
--- a/orcid-web/src/main/java/org/orcid/pojo/ajaxForm/Contributor.java
+++ b/orcid-web/src/main/java/org/orcid/pojo/ajaxForm/Contributor.java
@@ -1,148 +1,148 @@
/**
* =============================================================================
*
* ORCID (R) Open Source
* http://orcid.org
*
* Copyright (c) 2012-2013 ORCID, Inc.
* Licensed under an MIT-Style License (MIT)
* http://orcid.org/open-source-license
*
* This copyright and license information (including a link to the full license)
* shall be included in its entirety in all copies or substantial portion of
* the software.
*
* =============================================================================
*/
package org.orcid.pojo.ajaxForm;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.orcid.jaxb.model.message.ContributorEmail;
import org.orcid.jaxb.model.message.ContributorOrcid;
import org.orcid.jaxb.model.message.ContributorRole;
import org.orcid.jaxb.model.message.CreditName;
import org.orcid.jaxb.model.message.SequenceType;
public class Contributor implements ErrorsInterface, Serializable {
private static final long serialVersionUID = 1L;
private List<String> errors = new ArrayList<String>();
private Text contributorSequence;
private Text email;
private Text orcid;
private Text creditName;
private Text contributorRole;
private Visibility creditNameVisibility;
public static Contributor valueOf(org.orcid.jaxb.model.message.Contributor contributor) {
Contributor c = new Contributor();
if (contributor != null) {
if (contributor.getContributorAttributes() != null) {
contributor.getContributorAttributes();
if (contributor.getContributorAttributes().getContributorRole() != null)
c.setContributorRole(Text.valueOf(contributor.getContributorAttributes().getContributorRole().value()));
- if (contributor.getContributorAttributes().getContributorRole() != null)
+ if (contributor.getContributorAttributes().getContributorSequence() != null)
c.setContributorSequence(Text.valueOf(contributor.getContributorAttributes().getContributorSequence().value()));
}
if (contributor.getContributorEmail() != null)
c.setEmail(Text.valueOf(contributor.getContributorEmail().getValue()));
if (contributor.getContributorOrcid() != null)
c.setOrcid(Text.valueOf(contributor.getContributorOrcid().getValue()));
if (contributor.getCreditName() != null) {
c.setCreditName(Text.valueOf(contributor.getCreditName().getContent()));
c.setCreditNameVisibility(Visibility.valueOf(contributor.getCreditName().getVisibility()));
}
}
return c;
}
public org.orcid.jaxb.model.message.Contributor toContributor() {
org.orcid.jaxb.model.message.Contributor c = new org.orcid.jaxb.model.message.Contributor();
if (this.getContributorRole() != null || this.getContributorSequence() != null) {
org.orcid.jaxb.model.message.ContributorAttributes ca = new org.orcid.jaxb.model.message.ContributorAttributes();
if (this.getContributorRole() != null && this.getContributorRole().getValue() != null)
ca.setContributorRole(ContributorRole.fromValue(this.getContributorRole().getValue()));
if (this.getContributorSequence() != null && this.getContributorSequence().getValue() != null)
ca.setContributorSequence(SequenceType.fromValue(this.getContributorSequence().getValue()));
c.setContributorAttributes(ca);
}
if (this.getEmail() != null)
c.setContributorEmail(new ContributorEmail(this.getEmail().getValue()));
if (this.getOrcid() != null)
c.setContributorOrcid(new ContributorOrcid(this.getOrcid().getValue()));
if (this.getCreditName() != null) {
CreditName cn = new CreditName(this.getCreditName().getValue());
cn.setVisibility(org.orcid.jaxb.model.message.Visibility.fromValue(this.getCreditNameVisibility().getVisibility().value()));
c.setCreditName(cn);
}
return c;
}
public List<String> getErrors() {
return errors;
}
public void setErrors(List<String> errors) {
this.errors = errors;
}
public Text getContributorSequence() {
return contributorSequence;
}
public void setContributorSequence(Text contributorSequence) {
this.contributorSequence = contributorSequence;
}
public Text getContributorRole() {
return contributorRole;
}
public void setContributorRole(Text contributorRole) {
this.contributorRole = contributorRole;
}
public Text getEmail() {
return email;
}
public void setEmail(Text email) {
this.email = email;
}
public Text getOrcid() {
return orcid;
}
public void setOrcid(Text orcid) {
this.orcid = orcid;
}
public Text getCreditName() {
return creditName;
}
public void setCreditName(Text creditName) {
this.creditName = creditName;
}
public Visibility getCreditNameVisibility() {
return creditNameVisibility;
}
public void setCreditNameVisibility(Visibility contributorRoleVisibility) {
this.creditNameVisibility = contributorRoleVisibility;
}
}
| true | true | public static Contributor valueOf(org.orcid.jaxb.model.message.Contributor contributor) {
Contributor c = new Contributor();
if (contributor != null) {
if (contributor.getContributorAttributes() != null) {
contributor.getContributorAttributes();
if (contributor.getContributorAttributes().getContributorRole() != null)
c.setContributorRole(Text.valueOf(contributor.getContributorAttributes().getContributorRole().value()));
if (contributor.getContributorAttributes().getContributorRole() != null)
c.setContributorSequence(Text.valueOf(contributor.getContributorAttributes().getContributorSequence().value()));
}
if (contributor.getContributorEmail() != null)
c.setEmail(Text.valueOf(contributor.getContributorEmail().getValue()));
if (contributor.getContributorOrcid() != null)
c.setOrcid(Text.valueOf(contributor.getContributorOrcid().getValue()));
if (contributor.getCreditName() != null) {
c.setCreditName(Text.valueOf(contributor.getCreditName().getContent()));
c.setCreditNameVisibility(Visibility.valueOf(contributor.getCreditName().getVisibility()));
}
}
return c;
}
| public static Contributor valueOf(org.orcid.jaxb.model.message.Contributor contributor) {
Contributor c = new Contributor();
if (contributor != null) {
if (contributor.getContributorAttributes() != null) {
contributor.getContributorAttributes();
if (contributor.getContributorAttributes().getContributorRole() != null)
c.setContributorRole(Text.valueOf(contributor.getContributorAttributes().getContributorRole().value()));
if (contributor.getContributorAttributes().getContributorSequence() != null)
c.setContributorSequence(Text.valueOf(contributor.getContributorAttributes().getContributorSequence().value()));
}
if (contributor.getContributorEmail() != null)
c.setEmail(Text.valueOf(contributor.getContributorEmail().getValue()));
if (contributor.getContributorOrcid() != null)
c.setOrcid(Text.valueOf(contributor.getContributorOrcid().getValue()));
if (contributor.getCreditName() != null) {
c.setCreditName(Text.valueOf(contributor.getCreditName().getContent()));
c.setCreditNameVisibility(Visibility.valueOf(contributor.getCreditName().getVisibility()));
}
}
return c;
}
|
diff --git a/ocl20/eclipse/tudresden.ocl20.pivot.ocl2parser/src/tudresden/ocl20/pivot/ocl2parser/internal/exception/BuildingASMException.java b/ocl20/eclipse/tudresden.ocl20.pivot.ocl2parser/src/tudresden/ocl20/pivot/ocl2parser/internal/exception/BuildingASMException.java
index d9dd4930e..be7da122a 100644
--- a/ocl20/eclipse/tudresden.ocl20.pivot.ocl2parser/src/tudresden/ocl20/pivot/ocl2parser/internal/exception/BuildingASMException.java
+++ b/ocl20/eclipse/tudresden.ocl20.pivot.ocl2parser/src/tudresden/ocl20/pivot/ocl2parser/internal/exception/BuildingASMException.java
@@ -1,45 +1,45 @@
/*
Copyright (C) 2007 Nils ([email protected])
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package tudresden.ocl20.pivot.ocl2parser.internal.exception;
import tudresden.ocl20.pivot.ocl2parser.gen.ocl2as.TokenAS;
public class BuildingASMException extends Exception {
/**
*
*/
private static final long serialVersionUID = 9015478079658887234L;
protected TokenAS token;
public BuildingASMException(String message, TokenAS errorToken) {
super(message);
token = errorToken;
}
public TokenAS getErrorToken() {
return token;
}
public String getMessage() {
String message = super.getMessage();
if (token == null) return message;
- message = message + " Error occrued at line " + token.getLine() +
+ message = message + " Error occured at line " + token.getLine() +
" and column " + token.getColumn() + ". The error occured at the token " + token.getValue() + ".";
return message;
}
}
| true | true | public String getMessage() {
String message = super.getMessage();
if (token == null) return message;
message = message + " Error occrued at line " + token.getLine() +
" and column " + token.getColumn() + ". The error occured at the token " + token.getValue() + ".";
return message;
}
| public String getMessage() {
String message = super.getMessage();
if (token == null) return message;
message = message + " Error occured at line " + token.getLine() +
" and column " + token.getColumn() + ". The error occured at the token " + token.getValue() + ".";
return message;
}
|
diff --git a/src/jvm/clojure/lang/DynamicClassLoader.java b/src/jvm/clojure/lang/DynamicClassLoader.java
index 7c58244e..3f3ab35e 100644
--- a/src/jvm/clojure/lang/DynamicClassLoader.java
+++ b/src/jvm/clojure/lang/DynamicClassLoader.java
@@ -1,80 +1,80 @@
/**
* Copyright (c) Rich Hickey. All rights reserved.
* The use and distribution terms for this software are covered by the
* Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
* which can be found in the file epl-v10.html at the root of this distribution.
* By using this software in any fashion, you are agreeing to be bound by
* the terms of this license.
* You must not remove this notice, or any other, from this software.
**/
/* rich Aug 21, 2007 */
package clojure.lang;
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;
import java.net.URLClassLoader;
import java.net.URL;
import java.lang.ref.WeakReference;
public class DynamicClassLoader extends URLClassLoader{
HashMap<Integer, Object[]> constantVals = new HashMap<Integer, Object[]>();
static ConcurrentHashMap<String, Map.Entry<WeakReference<Class>,Object> >classCache =
new ConcurrentHashMap<String, Map.Entry<WeakReference<Class>,Object> >();
static final URL[] EMPTY_URLS = new URL[]{};
public DynamicClassLoader(){
//pseudo test in lieu of hasContextClassLoader()
super(EMPTY_URLS,(Thread.currentThread().getContextClassLoader() == null ||
Thread.currentThread().getContextClassLoader() == ClassLoader.getSystemClassLoader())?
Compiler.class.getClassLoader():Thread.currentThread().getContextClassLoader());
}
public DynamicClassLoader(ClassLoader parent){
super(EMPTY_URLS,parent);
}
public Class defineClass(String name, byte[] bytes, Object srcForm){
- Map.Entry<WeakReference<Class>,Object> ce = classCache.get(name);
- if(ce != null)
- {
- WeakReference<Class> cr = ce.getKey();
- Class c = cr.get();
- if((c != null) && srcForm.equals(ce.getValue()))
- return c;
- }
+// Map.Entry<WeakReference<Class>,Object> ce = classCache.get(name);
+// if(ce != null)
+// {
+// WeakReference<Class> cr = ce.getKey();
+// Class c = cr.get();
+// if((c != null) && srcForm.equals(ce.getValue()))
+// return c;
+// }
Class c = defineClass(name, bytes, 0, bytes.length);
- classCache.put(name, new MapEntry(new WeakReference(c), srcForm));
+ classCache.put(name, new MapEntry(new WeakReference(c), null));
return c;
}
protected Class<?> findClass(String name) throws ClassNotFoundException{
Map.Entry<WeakReference<Class>,Object> ce = classCache.get(name);
if(ce != null)
{
WeakReference<Class> cr = ce.getKey();
Class c = cr.get();
if(c != null)
return c;
classCache.remove(name);
}
return super.findClass(name);
}
public void registerConstants(int id, Object[] val){
constantVals.put(id, val);
}
public Object[] getConstants(int id){
return constantVals.get(id);
}
public void addURL(URL url){
super.addURL(url);
}
}
| false | true | public Class defineClass(String name, byte[] bytes, Object srcForm){
Map.Entry<WeakReference<Class>,Object> ce = classCache.get(name);
if(ce != null)
{
WeakReference<Class> cr = ce.getKey();
Class c = cr.get();
if((c != null) && srcForm.equals(ce.getValue()))
return c;
}
Class c = defineClass(name, bytes, 0, bytes.length);
classCache.put(name, new MapEntry(new WeakReference(c), srcForm));
return c;
}
| public Class defineClass(String name, byte[] bytes, Object srcForm){
// Map.Entry<WeakReference<Class>,Object> ce = classCache.get(name);
// if(ce != null)
// {
// WeakReference<Class> cr = ce.getKey();
// Class c = cr.get();
// if((c != null) && srcForm.equals(ce.getValue()))
// return c;
// }
Class c = defineClass(name, bytes, 0, bytes.length);
classCache.put(name, new MapEntry(new WeakReference(c), null));
return c;
}
|
diff --git a/launcher/src/se/llbit/chunky/launcher/ChunkyDeployer.java b/launcher/src/se/llbit/chunky/launcher/ChunkyDeployer.java
index e69bc8a5..d130978a 100644
--- a/launcher/src/se/llbit/chunky/launcher/ChunkyDeployer.java
+++ b/launcher/src/se/llbit/chunky/launcher/ChunkyDeployer.java
@@ -1,432 +1,431 @@
/* Copyright (c) 2013-2014 Jesper Öqvist <[email protected]>
*
* This file is part of Chunky.
*
* Chunky 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.
*
* Chunky 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 Chunky. If not, see <http://www.gnu.org/licenses/>.
*/
package se.llbit.chunky.launcher;
import java.awt.Component;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import se.llbit.chunky.PersistentSettings;
import se.llbit.chunky.launcher.VersionInfo.Library;
import se.llbit.chunky.launcher.VersionInfo.LibraryStatus;
import se.llbit.json.JsonArray;
import se.llbit.json.JsonObject;
import se.llbit.json.JsonParser;
import se.llbit.json.JsonParser.SyntaxError;
import se.llbit.json.JsonValue;
/**
* Deploys the embedded Chunky version, or launches an existing local version.
* @author Jesper Öqvist <[email protected]>
*/
public class ChunkyDeployer {
/**
* Check the integrity of an installed version.
* @param version
* @return <code>true</code> if the version is installed locally
*/
public static boolean checkVersionIntegrity(String version) {
File chunkyDir = PersistentSettings.getSettingsDirectory();
File versionsDir = new File(chunkyDir, "versions");
File libDir = new File(chunkyDir, "lib");
if (!versionsDir.isDirectory() || !libDir.isDirectory()) {
return false;
}
File versionFile = new File(versionsDir, version + ".json");
if (!versionFile.isFile()) {
return false;
}
// check version
try {
FileInputStream in = new FileInputStream(versionFile);
JsonParser parser = new JsonParser(in);
JsonObject obj = parser.parse().object();
in.close();
String versionName = obj.get("name").stringValue("");
if (!versionName.equals(version)) {
System.err.println("Stored version name does not match file name");
return false;
}
JsonArray array = obj.get("libraries").array();
for (JsonValue value: array.getElementList()) {
VersionInfo.Library lib = new VersionInfo.Library(value.object());
switch (lib.testIntegrity(libDir)) {
case INCOMPLETE_INFO:
System.err.println("Missing library name or checksum");
return false;
case MD5_MISMATCH:
System.err.println("Library MD5 checksum mismatch");
return false;
case MISSING:
System.err.println("Missing library " + lib.name);
return false;
default:
break;
}
}
return true;
} catch (IOException e) {
System.err.println("Could not read version info file: " + e.getMessage());
} catch (SyntaxError e) {
System.err.println("Corrupted version info file: " + e.getMessage());
}
return false;
}
/**
* Unpacks the embedded Chunky jar files.
*/
public void deploy() {
List<VersionInfo> versions = availableVersions();
VersionInfo embedded = embeddedVersion();
if (embedded != null && (!versions.contains(embedded) || !checkVersionIntegrity(embedded.name))) {
if (System.getProperty("log4j.logLevel", "WARN").equals("INFO")) {
System.out.println("Deploying embedded version: " + embedded.name);
}
deployEmbeddedVersion(embedded);
if (!versions.contains(embedded)) {
versions.add(embedded);
Collections.sort(versions);
}
}
}
public static List<VersionInfo> availableVersions() {
File chunkyDir = PersistentSettings.getSettingsDirectory();
File versionsDir = new File(chunkyDir, "versions");
if (!versionsDir.isDirectory()) {
return Collections.emptyList();
}
List<VersionInfo> versions = new ArrayList<VersionInfo>();
for (File versionFile: versionsDir.listFiles()) {
if (versionFile.getName().endsWith(".json")) {
try {
FileInputStream in = new FileInputStream(versionFile);
JsonParser parser = new JsonParser(in);
versions.add(new VersionInfo(parser.parse().object()));
} catch (IOException e) {
System.err.println("Could not read version info file: " + e.getMessage());
} catch (SyntaxError e) {
System.err.println("Corrupted version info file: " + e.getMessage());
}
}
}
Collections.sort(versions);
return versions;
}
/**
* Unpack embedded libraries and deploy the embedded Chunky version.
* @param version
*/
private static void deployEmbeddedVersion(VersionInfo version) {
File chunkyDir = PersistentSettings.getSettingsDirectory();
File versionsDir = new File(chunkyDir, "versions");
if (!versionsDir.isDirectory()) {
versionsDir.mkdirs();
}
File libDir = new File(chunkyDir, "lib");
if (!libDir.isDirectory()) {
libDir.mkdirs();
}
try {
File versionJson = new File(versionsDir, version.name + ".json");
version.writeTo(versionJson);
ClassLoader parentCL = ChunkyLauncher.class.getClassLoader();
// deploy libraries that were not already installed correctly
for (Library lib: version.libraries) {
if (lib.testIntegrity(libDir) != LibraryStatus.PASSED) {
unpackLibrary(parentCL, "lib/" + lib.name,
new File(libDir, lib.name));
}
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Unpack the jar file to the target directory.
* @param parentCL
* @param name
* @param dest destination file
* @return the unpacked Jar file
* @throws IOException
*/
private static void unpackLibrary(ClassLoader parentCL, String name, File dest)
throws IOException {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
InputStream in = parentCL.getResourceAsStream(name);
byte[] buffer = new byte[4096];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
}
private static VersionInfo embeddedVersion() {
try {
ClassLoader parentCL = ChunkyLauncher.class.getClassLoader();
InputStream in = parentCL.getResourceAsStream("version.json");
try {
if (in != null) {
JsonParser parser = new JsonParser(in);
return new VersionInfo(parser.parse().object());
}
} catch (IOException e) {
} catch (SyntaxError e) {
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
} catch (SecurityException e) {
}
return null;
}
/**
* Launch a specific Chunky version
* @param parentComponent
* @param settings
* @return {@code true} on success, {@code false} if there is any problem
* launching Chunky (waits 200ms to see if everything launched)
*/
public boolean launchChunky(Component parentComponent, LauncherSettings settings, VersionInfo version) {
List<String> command = buildCommandLine(version, settings);
if (System.getProperty("log4j.logLevel", "WARN").equals("INFO")) {
System.out.println(commandString(command));
}
ProcessBuilder procBuilder = new ProcessBuilder(command);
+ final Logger logger;
+ if (!settings.headless && settings.debugConsole) {
+ DebugConsole console = new DebugConsole(null, settings.closeConsoleOnExit);
+ console.setVisible(true);
+ logger = console;
+ } else {
+ logger = new ConsoleLogger();
+ }
try {
final Process proc = procBuilder.start();
- final Logger logger;
- if (!settings.headless && settings.debugConsole) {
- DebugConsole console = new DebugConsole(null, settings.closeConsoleOnExit);
- console.setVisible(true);
- logger = console;
- } else {
- logger = new ConsoleLogger();
- }
final Scanner stdout = new Scanner(proc.getInputStream());
final Scanner stderr = new Scanner(proc.getErrorStream());
final Thread outputScanner = new Thread("Output Logger") {
@Override
public void run() {
while (!isInterrupted() && stdout.hasNextLine()) {
String line = stdout.nextLine();
logger.appendLine(line);
}
}
};
outputScanner.start();
final Thread errorScanner = new Thread("Error Logger") {
@Override
public void run() {
while (!isInterrupted() && stderr.hasNextLine()) {
String line = stderr.nextLine();
logger.appendErrorLine(line);
}
}
};
errorScanner.start();
ShutdownThread shutdownThread = new ShutdownThread(proc, logger, outputScanner, errorScanner);
shutdownThread.start();
try {
Thread.sleep(200);
int exitValue = shutdownThread.exitValue;
// check if process already exited with error code
if (exitValue != 0) {
return false;
}
} catch (InterruptedException e) {
}
return true;
} catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
+ logger.appendErrorLine(e.getMessage());
return false;
}
}
/**
* @param command
* @return command in string form
*/
public static String commandString(List<String> command) {
StringBuilder sb = new StringBuilder();
for (String part: command) {
if (sb.length() > 0) {
sb.append(" ");
}
sb.append(part);
}
return sb.toString();
}
public static List<String> buildCommandLine(VersionInfo version, LauncherSettings settings) {
List<String> cmd = new LinkedList<String>();
cmd.add(JreUtil.javaCommand(settings.jre));
cmd.add("-Xmx" + settings.memoryLimit + "m");
String[] parts = settings.javaOptions.split(" ");
for (String part: parts) {
if (!part.isEmpty()) {
cmd.add(part);
}
}
cmd.add("-classpath");
cmd.add(classpath(version,settings));
if (settings.verboseLogging) {
cmd.add("-Dlog4j.logLevel=INFO");
}
cmd.add("se.llbit.chunky.main.Chunky");
parts = settings.chunkyOptions.split(" ");
for (String part: parts) {
if (!part.isEmpty()) {
cmd.add(part);
}
}
return cmd;
}
private static String classpath(VersionInfo version, LauncherSettings settings) {
File chunkyDir = PersistentSettings.getSettingsDirectory();
File libDir = new File(chunkyDir, "lib");
List<File> jars = new ArrayList<File>();
for (VersionInfo.Library library: version.libraries) {
jars.add(library.getFile(libDir));
}
String classpath = "";
for (File file : jars) {
if (!classpath.isEmpty()) {
classpath += File.pathSeparator;
}
classpath += file.getAbsolutePath();
}
return classpath;
}
private static class ShutdownThread extends Thread {
public volatile int exitValue = 0;
private final Thread outputScanner;
private final Thread errorScanner;
private final Process proc;
private final Logger logger;
public ShutdownThread(Process proc, Logger logger, Thread output, Thread error) {
this.proc = proc;
this.logger = logger;
this.outputScanner = output;
this.errorScanner = error;
}
@Override
public void run() {
try {
outputScanner.join();
} catch (InterruptedException e) {
}
try {
errorScanner.join();
} catch (InterruptedException e) {
}
try {
proc.waitFor();
exitValue = proc.exitValue();
logger.processExited(exitValue);
} catch (InterruptedException e) {
}
}
}
public static VersionInfo resolveVersion(String name) {
List<VersionInfo> versions = availableVersions();
VersionInfo version = VersionInfo.LATEST;
for (VersionInfo info: versions) {
if (info.name.equals(name)) {
version = info;
break;
}
}
if (version == VersionInfo.LATEST) {
if (versions.size() > 0) {
return versions.get(0);
} else {
return VersionInfo.NONE;
}
} else {
return version;
}
}
public static boolean canLaunch(VersionInfo version, ChunkyLauncher launcher, boolean reportErrors) {
if (version == VersionInfo.NONE) {
// version not available!
System.err.println("No version installed");
if (reportErrors) {
Dialogs.error(launcher,
"Failed to launch Chunky - there is no local version installed. Try updating.",
"Failed to Launch");
}
return false;
}
if (!ChunkyDeployer.checkVersionIntegrity(version.name)) {
// TODO add some way to fix this??
System.err.println("Version integrity check failed for version " + version.name);
if (reportErrors) {
Dialogs.error(launcher,
"Version integrity check failed for version " + version.name + ". Try selecting another version.",
"Failed to Launch");
}
return false;
}
return true;
}
}
| false | true | public boolean launchChunky(Component parentComponent, LauncherSettings settings, VersionInfo version) {
List<String> command = buildCommandLine(version, settings);
if (System.getProperty("log4j.logLevel", "WARN").equals("INFO")) {
System.out.println(commandString(command));
}
ProcessBuilder procBuilder = new ProcessBuilder(command);
try {
final Process proc = procBuilder.start();
final Logger logger;
if (!settings.headless && settings.debugConsole) {
DebugConsole console = new DebugConsole(null, settings.closeConsoleOnExit);
console.setVisible(true);
logger = console;
} else {
logger = new ConsoleLogger();
}
final Scanner stdout = new Scanner(proc.getInputStream());
final Scanner stderr = new Scanner(proc.getErrorStream());
final Thread outputScanner = new Thread("Output Logger") {
@Override
public void run() {
while (!isInterrupted() && stdout.hasNextLine()) {
String line = stdout.nextLine();
logger.appendLine(line);
}
}
};
outputScanner.start();
final Thread errorScanner = new Thread("Error Logger") {
@Override
public void run() {
while (!isInterrupted() && stderr.hasNextLine()) {
String line = stderr.nextLine();
logger.appendErrorLine(line);
}
}
};
errorScanner.start();
ShutdownThread shutdownThread = new ShutdownThread(proc, logger, outputScanner, errorScanner);
shutdownThread.start();
try {
Thread.sleep(200);
int exitValue = shutdownThread.exitValue;
// check if process already exited with error code
if (exitValue != 0) {
return false;
}
} catch (InterruptedException e) {
}
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
| public boolean launchChunky(Component parentComponent, LauncherSettings settings, VersionInfo version) {
List<String> command = buildCommandLine(version, settings);
if (System.getProperty("log4j.logLevel", "WARN").equals("INFO")) {
System.out.println(commandString(command));
}
ProcessBuilder procBuilder = new ProcessBuilder(command);
final Logger logger;
if (!settings.headless && settings.debugConsole) {
DebugConsole console = new DebugConsole(null, settings.closeConsoleOnExit);
console.setVisible(true);
logger = console;
} else {
logger = new ConsoleLogger();
}
try {
final Process proc = procBuilder.start();
final Scanner stdout = new Scanner(proc.getInputStream());
final Scanner stderr = new Scanner(proc.getErrorStream());
final Thread outputScanner = new Thread("Output Logger") {
@Override
public void run() {
while (!isInterrupted() && stdout.hasNextLine()) {
String line = stdout.nextLine();
logger.appendLine(line);
}
}
};
outputScanner.start();
final Thread errorScanner = new Thread("Error Logger") {
@Override
public void run() {
while (!isInterrupted() && stderr.hasNextLine()) {
String line = stderr.nextLine();
logger.appendErrorLine(line);
}
}
};
errorScanner.start();
ShutdownThread shutdownThread = new ShutdownThread(proc, logger, outputScanner, errorScanner);
shutdownThread.start();
try {
Thread.sleep(200);
int exitValue = shutdownThread.exitValue;
// check if process already exited with error code
if (exitValue != 0) {
return false;
}
} catch (InterruptedException e) {
}
return true;
} catch (IOException e) {
logger.appendErrorLine(e.getMessage());
return false;
}
}
|
diff --git a/server/cluster-mgmt/src/main/java/com/vmware/bdd/command/CommandUtil.java b/server/cluster-mgmt/src/main/java/com/vmware/bdd/command/CommandUtil.java
index 1c1d3cf8..66eb5428 100644
--- a/server/cluster-mgmt/src/main/java/com/vmware/bdd/command/CommandUtil.java
+++ b/server/cluster-mgmt/src/main/java/com/vmware/bdd/command/CommandUtil.java
@@ -1,71 +1,73 @@
/***************************************************************************
* Copyright (c) 2012-2013 VMware, Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
package com.vmware.bdd.command;
import java.io.File;
import org.apache.log4j.Logger;
import com.vmware.aurora.global.Configuration;
import com.vmware.bdd.utils.AuAssert;
public class CommandUtil {
private static final Logger logger = Logger.getLogger(CommandUtil.class);
static File taskRootDir;
private static final String TASK_ID_STR = "${task_id}";
private static String routeKeyFormat = "task." + TASK_ID_STR;
static {
String taskRootDirStr = System.getProperty("serengeti.home.dir");
if (taskRootDirStr == null) {
taskRootDirStr = "/tmp/serengeti/";
}
taskRootDir = new File(taskRootDirStr, "logs/task/");
logger.info("setting task work dir to: " + taskRootDir.getAbsolutePath());
if (!taskRootDir.exists()) {
logger.info("task root directory does not exist, try to create one");
taskRootDir.mkdirs();
}
routeKeyFormat = Configuration.getString("task.rabbitmq.routekey_fmt",
routeKeyFormat);
AuAssert.check(routeKeyFormat.contains(TASK_ID_STR));
}
public static File createWorkDir(long executionId) {
File path = new File(taskRootDir, Long.toString(executionId));
if (!path.exists()) {
path.mkdirs();
}
String dirs[] = path.list();
long lastCmdId = 0;
- for (String dir : dirs) {
- long cmdId = Long.parseLong(dir);
- if (lastCmdId < cmdId) {
- lastCmdId = cmdId;
+ if (dirs != null) {
+ for (String dir : dirs) {
+ long cmdId = Long.parseLong(dir);
+ if (lastCmdId < cmdId) {
+ lastCmdId = cmdId;
+ }
}
}
Long nextCmdId = lastCmdId + 1;
path = new File(path, nextCmdId.toString());
path.mkdir();
return path;
}
}
| true | true | public static File createWorkDir(long executionId) {
File path = new File(taskRootDir, Long.toString(executionId));
if (!path.exists()) {
path.mkdirs();
}
String dirs[] = path.list();
long lastCmdId = 0;
for (String dir : dirs) {
long cmdId = Long.parseLong(dir);
if (lastCmdId < cmdId) {
lastCmdId = cmdId;
}
}
Long nextCmdId = lastCmdId + 1;
path = new File(path, nextCmdId.toString());
path.mkdir();
return path;
}
| public static File createWorkDir(long executionId) {
File path = new File(taskRootDir, Long.toString(executionId));
if (!path.exists()) {
path.mkdirs();
}
String dirs[] = path.list();
long lastCmdId = 0;
if (dirs != null) {
for (String dir : dirs) {
long cmdId = Long.parseLong(dir);
if (lastCmdId < cmdId) {
lastCmdId = cmdId;
}
}
}
Long nextCmdId = lastCmdId + 1;
path = new File(path, nextCmdId.toString());
path.mkdir();
return path;
}
|
diff --git a/src/ru/spbau/bioinf/tagfinder/IntencityTableGenerator.java b/src/ru/spbau/bioinf/tagfinder/IntencityTableGenerator.java
index 531f52d..a57f20b 100644
--- a/src/ru/spbau/bioinf/tagfinder/IntencityTableGenerator.java
+++ b/src/ru/spbau/bioinf/tagfinder/IntencityTableGenerator.java
@@ -1,164 +1,164 @@
package ru.spbau.bioinf.tagfinder;
import java.io.BufferedReader;
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import ru.spbau.bioinf.tagfinder.util.ReaderUtil;
public class IntencityTableGenerator {
public static void main(String[] args) throws Exception {
String file1 = "bar_exp_annotated_proper_none_intencity";
String file2 = "bar_exp_annotated_correct_none_intencity";
double[][] res = new double[100][3];
for (int gap = 1; gap <= 3; gap++) {
printTable(res, file1, gap, "Percentage of spectra in the $\\STbar$ data set, such that all their top-scoring " + gap + "-aa tags of length $k$ are proper (+) or improper (-).");
}
TexTableGenerator.createThreeRowsTable(res, "Average percentage of proper top-scoring tags", "k", "");
res = new double[100][3];
for (int gap = 1; gap <= 3; gap++) {
printTable(res, file2, gap, "Percentage of spectra in the $\\STbar$ data set, such that all their top-scoring " + gap + "-aa tags of length $k$ are correct (+) or incorrect (-).");
}
TexTableGenerator.createThreeRowsTable(res, "Average percentage of correct top-scoring tags", "k", "");
}
private static void printTable(double[][] res, String file, int gap, String caption) throws Exception {
BufferedReader in = ReaderUtil.createInputReader(new File("res", "share_" + file + "_" + gap + ".txt"));
double[] good = new double[100];
double[] bad = new double[100];
double[] both = new double[100];
int max = 0;
List<Double>[] percentage = new List[100];
do {
String s = in.readLine();
if (s.contains(",")) {
break;
}
if (s.indexOf(" ") == 0) {
break;
}
long[] data = CalculateRelation.getData(s);
int pos = 2;
int d = 1;
while (pos < data.length) {
max = Math.max(max, d);
if (data[pos] == 0) {
bad[d]++;
} else if (data[pos + 1] <= data[pos]) {
good[d]++;
} else {
both[d]++;
}
if (percentage[d] == null) {
percentage[d] = new ArrayList<Double>();
}
percentage[d].add(data[pos] * 100.0d / (data[pos] + data[pos + 1]));
d++;
pos += 2;
}
} while (true);
double[] ans = new double[max];
for (int i = 1; i <= max; i++) {
double total = 0;
for (double v : percentage[i]) {
total += v;
}
ans[i - 1] = total / percentage[i].size();
}
res[gap - 1] = ans;
TexTableGenerator.tableId++;
int tableId = TexTableGenerator.tableId;
PrintWriter dataFile = ReaderUtil.createOutputFile(new File("plots", tableId + ".dat"));
PrintWriter gplFile = ReaderUtil.createOutputFile(new File("plots", tableId + ".gpl"));
gplFile.print("set terminal postscript eps\n" +
"set out \"plots/" + tableId + ".eps\"\n" +
"set ylabel \"Percentage of spectre\"\n" +
"set xlabel \"Tag length\"\n" +
"plot");
- gplFile.println("\"plots/" + tableId + ".dat\" using 1:2 title 'correct',\\");
- gplFile.println("\"plots/" + tableId + ".dat\" using 1:3 title 'incorrect'");
+ gplFile.println("\"plots/" + tableId + ".dat\" using 1:2 title 'correct' with linespoints,\\");
+ gplFile.println("\"plots/" + tableId + ".dat\" using 1:3 title 'incorrect' with linespoints");
gplFile.close();
System.out.println("\\includegraphics{plots/" + TexTableGenerator.tableId + ".eps}\n");
int width = 20;
for (int start = 1; start <= max; start += width) {
int end = Math.min(start + width - 1, max);
System.out.print("\\begin{table}[ht]\\footnotesize\n" +
"\\vspace{3mm}\n" +
"{\\centering\n" +
"\\begin{center}\n" +
"\\begin{tabular}{|c|c|c|");
for (int i = start; i <= end; i++) {
System.out.print("c|");
}
int cols = end - start + 1;
System.out.println("}\n" +
" \\hline\n" +
" \\multicolumn{2}{|c|}{ } & \\multicolumn{ " + cols + "}{|c|}{$k$} \\\\\n" +
" \\cline{3-" + (cols + 2) + " }\n" +
" \\multicolumn{2}{|c|}{ } ");
for (int i = start; i <= end; i++) {
System.out.print(" & " + i);
}
System.out.print("\\\\\n" +
" \\hline\n" +
" \\multirow{2}{*}{spectra (\\%)} & + ");
for (int i = start; i <= end; i++) {
System.out.print(" & ");
double total = good[i] + bad[i] + both[i];
if (i <= 14) {
dataFile.print(i + " ");
if (total > 0) {
dataFile.println(" " + 100 * good[i] / total + " " + 100 * bad[i] / total);
} else {
dataFile.print(" ? ? ");
}
}
if (total > 0) {
System.out.print(ValidTags.df.format(100 * good[i] / total));
}
}
System.out.print(" \\\\\n" +
" & -- ");
for (int i = start; i <= end; i++) {
System.out.print(" & ");
double total = good[i] + bad[i] + both[i];
if (total > 0) {
System.out.print(ValidTags.df.format(100 * bad[i] / total));
}
}
System.out.println(" \\\\\n" +
" \\hline\n" +
"\\end{tabular}\n" +
"\\end{center}\n" +
"\\par}\n" +
"\\centering\n");
if (end == max) {
System.out.println("\\caption{" + caption + "}\n");
}
System.out.println("\\vspace{3mm}\n" +
"\\label{table:all-top-scoring}\n" +
"\\end{table}");
}
dataFile.close();
}
}
| true | true | private static void printTable(double[][] res, String file, int gap, String caption) throws Exception {
BufferedReader in = ReaderUtil.createInputReader(new File("res", "share_" + file + "_" + gap + ".txt"));
double[] good = new double[100];
double[] bad = new double[100];
double[] both = new double[100];
int max = 0;
List<Double>[] percentage = new List[100];
do {
String s = in.readLine();
if (s.contains(",")) {
break;
}
if (s.indexOf(" ") == 0) {
break;
}
long[] data = CalculateRelation.getData(s);
int pos = 2;
int d = 1;
while (pos < data.length) {
max = Math.max(max, d);
if (data[pos] == 0) {
bad[d]++;
} else if (data[pos + 1] <= data[pos]) {
good[d]++;
} else {
both[d]++;
}
if (percentage[d] == null) {
percentage[d] = new ArrayList<Double>();
}
percentage[d].add(data[pos] * 100.0d / (data[pos] + data[pos + 1]));
d++;
pos += 2;
}
} while (true);
double[] ans = new double[max];
for (int i = 1; i <= max; i++) {
double total = 0;
for (double v : percentage[i]) {
total += v;
}
ans[i - 1] = total / percentage[i].size();
}
res[gap - 1] = ans;
TexTableGenerator.tableId++;
int tableId = TexTableGenerator.tableId;
PrintWriter dataFile = ReaderUtil.createOutputFile(new File("plots", tableId + ".dat"));
PrintWriter gplFile = ReaderUtil.createOutputFile(new File("plots", tableId + ".gpl"));
gplFile.print("set terminal postscript eps\n" +
"set out \"plots/" + tableId + ".eps\"\n" +
"set ylabel \"Percentage of spectre\"\n" +
"set xlabel \"Tag length\"\n" +
"plot");
gplFile.println("\"plots/" + tableId + ".dat\" using 1:2 title 'correct',\\");
gplFile.println("\"plots/" + tableId + ".dat\" using 1:3 title 'incorrect'");
gplFile.close();
System.out.println("\\includegraphics{plots/" + TexTableGenerator.tableId + ".eps}\n");
int width = 20;
for (int start = 1; start <= max; start += width) {
int end = Math.min(start + width - 1, max);
System.out.print("\\begin{table}[ht]\\footnotesize\n" +
"\\vspace{3mm}\n" +
"{\\centering\n" +
"\\begin{center}\n" +
"\\begin{tabular}{|c|c|c|");
for (int i = start; i <= end; i++) {
System.out.print("c|");
}
int cols = end - start + 1;
System.out.println("}\n" +
" \\hline\n" +
" \\multicolumn{2}{|c|}{ } & \\multicolumn{ " + cols + "}{|c|}{$k$} \\\\\n" +
" \\cline{3-" + (cols + 2) + " }\n" +
" \\multicolumn{2}{|c|}{ } ");
for (int i = start; i <= end; i++) {
System.out.print(" & " + i);
}
System.out.print("\\\\\n" +
" \\hline\n" +
" \\multirow{2}{*}{spectra (\\%)} & + ");
for (int i = start; i <= end; i++) {
System.out.print(" & ");
double total = good[i] + bad[i] + both[i];
if (i <= 14) {
dataFile.print(i + " ");
if (total > 0) {
dataFile.println(" " + 100 * good[i] / total + " " + 100 * bad[i] / total);
} else {
dataFile.print(" ? ? ");
}
}
if (total > 0) {
System.out.print(ValidTags.df.format(100 * good[i] / total));
}
}
System.out.print(" \\\\\n" +
" & -- ");
for (int i = start; i <= end; i++) {
System.out.print(" & ");
double total = good[i] + bad[i] + both[i];
if (total > 0) {
System.out.print(ValidTags.df.format(100 * bad[i] / total));
}
}
System.out.println(" \\\\\n" +
" \\hline\n" +
"\\end{tabular}\n" +
"\\end{center}\n" +
"\\par}\n" +
"\\centering\n");
if (end == max) {
System.out.println("\\caption{" + caption + "}\n");
}
System.out.println("\\vspace{3mm}\n" +
"\\label{table:all-top-scoring}\n" +
"\\end{table}");
}
dataFile.close();
}
| private static void printTable(double[][] res, String file, int gap, String caption) throws Exception {
BufferedReader in = ReaderUtil.createInputReader(new File("res", "share_" + file + "_" + gap + ".txt"));
double[] good = new double[100];
double[] bad = new double[100];
double[] both = new double[100];
int max = 0;
List<Double>[] percentage = new List[100];
do {
String s = in.readLine();
if (s.contains(",")) {
break;
}
if (s.indexOf(" ") == 0) {
break;
}
long[] data = CalculateRelation.getData(s);
int pos = 2;
int d = 1;
while (pos < data.length) {
max = Math.max(max, d);
if (data[pos] == 0) {
bad[d]++;
} else if (data[pos + 1] <= data[pos]) {
good[d]++;
} else {
both[d]++;
}
if (percentage[d] == null) {
percentage[d] = new ArrayList<Double>();
}
percentage[d].add(data[pos] * 100.0d / (data[pos] + data[pos + 1]));
d++;
pos += 2;
}
} while (true);
double[] ans = new double[max];
for (int i = 1; i <= max; i++) {
double total = 0;
for (double v : percentage[i]) {
total += v;
}
ans[i - 1] = total / percentage[i].size();
}
res[gap - 1] = ans;
TexTableGenerator.tableId++;
int tableId = TexTableGenerator.tableId;
PrintWriter dataFile = ReaderUtil.createOutputFile(new File("plots", tableId + ".dat"));
PrintWriter gplFile = ReaderUtil.createOutputFile(new File("plots", tableId + ".gpl"));
gplFile.print("set terminal postscript eps\n" +
"set out \"plots/" + tableId + ".eps\"\n" +
"set ylabel \"Percentage of spectre\"\n" +
"set xlabel \"Tag length\"\n" +
"plot");
gplFile.println("\"plots/" + tableId + ".dat\" using 1:2 title 'correct' with linespoints,\\");
gplFile.println("\"plots/" + tableId + ".dat\" using 1:3 title 'incorrect' with linespoints");
gplFile.close();
System.out.println("\\includegraphics{plots/" + TexTableGenerator.tableId + ".eps}\n");
int width = 20;
for (int start = 1; start <= max; start += width) {
int end = Math.min(start + width - 1, max);
System.out.print("\\begin{table}[ht]\\footnotesize\n" +
"\\vspace{3mm}\n" +
"{\\centering\n" +
"\\begin{center}\n" +
"\\begin{tabular}{|c|c|c|");
for (int i = start; i <= end; i++) {
System.out.print("c|");
}
int cols = end - start + 1;
System.out.println("}\n" +
" \\hline\n" +
" \\multicolumn{2}{|c|}{ } & \\multicolumn{ " + cols + "}{|c|}{$k$} \\\\\n" +
" \\cline{3-" + (cols + 2) + " }\n" +
" \\multicolumn{2}{|c|}{ } ");
for (int i = start; i <= end; i++) {
System.out.print(" & " + i);
}
System.out.print("\\\\\n" +
" \\hline\n" +
" \\multirow{2}{*}{spectra (\\%)} & + ");
for (int i = start; i <= end; i++) {
System.out.print(" & ");
double total = good[i] + bad[i] + both[i];
if (i <= 14) {
dataFile.print(i + " ");
if (total > 0) {
dataFile.println(" " + 100 * good[i] / total + " " + 100 * bad[i] / total);
} else {
dataFile.print(" ? ? ");
}
}
if (total > 0) {
System.out.print(ValidTags.df.format(100 * good[i] / total));
}
}
System.out.print(" \\\\\n" +
" & -- ");
for (int i = start; i <= end; i++) {
System.out.print(" & ");
double total = good[i] + bad[i] + both[i];
if (total > 0) {
System.out.print(ValidTags.df.format(100 * bad[i] / total));
}
}
System.out.println(" \\\\\n" +
" \\hline\n" +
"\\end{tabular}\n" +
"\\end{center}\n" +
"\\par}\n" +
"\\centering\n");
if (end == max) {
System.out.println("\\caption{" + caption + "}\n");
}
System.out.println("\\vspace{3mm}\n" +
"\\label{table:all-top-scoring}\n" +
"\\end{table}");
}
dataFile.close();
}
|
diff --git a/src/test/java/spark/BooksIntegrationTest.java b/src/test/java/spark/BooksIntegrationTest.java
index bb1b7b5..959f100 100644
--- a/src/test/java/spark/BooksIntegrationTest.java
+++ b/src/test/java/spark/BooksIntegrationTest.java
@@ -1,196 +1,197 @@
package spark;
import java.io.FileNotFoundException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import junit.framework.Assert;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import spark.examples.books.Books;
import spark.utils.IOUtils;
public class BooksIntegrationTest {
private static int PORT = 4567;
private static String AUTHOR = "FOO";
private static String TITLE = "BAR";
private static String NEW_TITLE = "SPARK";
@AfterClass
public static void tearDown() {
Spark.clearRoutes();
Spark.stop();
}
@BeforeClass
public static void setup() {
Spark.before(new Filter(){
@Override
public void handle(Request request, Response response) {
response.header("FOZ", "BAZ");
}
});
Books.main(null);
Spark.after(new Filter(){
@Override
public void handle(Request request, Response response) {
response.header("FOO", "BAR");
}
});
try {
Thread.sleep(500);
} catch (Exception e) {
}
}
private static String id;
@Test
public void testCreateBook() {
try {
UrlResponse response = doMethod("POST", "/books?author=" + AUTHOR + "&title=" + TITLE, null);
id = response.body.trim();
Assert.assertNotNull(response);
Assert.assertNotNull(response.body);
Assert.assertTrue(Integer.valueOf(response.body) > 0);
Assert.assertEquals(201, response.status);
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
@Test
public void testListBooks() {
try {
UrlResponse response = doMethod("GET", "/books", null);
Assert.assertNotNull(response);
String body = response.body.trim();
System.out.println("BODY: " + body);
Assert.assertNotNull(body);
Assert.assertTrue(Integer.valueOf(body) > 0);
Assert.assertEquals(200, response.status);
Assert.assertTrue(response.body.contains(id));
} catch (Throwable e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Test
public void testGetBook() {
try {
// ensure there is a book
testCreateBook();
UrlResponse response = doMethod("GET", "/books/" + id, null);
String result = response.body;
Assert.assertNotNull(response);
Assert.assertNotNull(response.body);
Assert.assertEquals(200, response.status);
Assert.assertTrue(result.contains(AUTHOR));
Assert.assertTrue(result.contains(TITLE));
// verify response header set by filters:
Assert.assertTrue(response.headers.get("FOZ").get(0).equals("BAZ"));
Assert.assertTrue(response.headers.get("FOO").get(0).equals("BAR"));
// delete the book again
- testDeleteBook();
+ //Comment this delete to ensure the running of the tests
+ //testDeleteBook();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
@Test
public void testUpdateBook() {
try {
UrlResponse response = doMethod("PUT", "/books/" + id + "?title=" + NEW_TITLE, null);
String result = response.body;
Assert.assertNotNull(response);
Assert.assertNotNull(response.body);
Assert.assertEquals(200, response.status);
Assert.assertTrue(result.contains(id));
Assert.assertTrue(result.contains("updated"));
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
@Test
public void testGetUpdatedBook() {
try {
UrlResponse response = doMethod("GET", "/books/" + id, null);
String result = response.body;
Assert.assertNotNull(response);
Assert.assertNotNull(response.body);
Assert.assertEquals(200, response.status);
Assert.assertTrue(result.contains(AUTHOR));
Assert.assertTrue(result.contains(NEW_TITLE));
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
@Test
public void testDeleteBook() {
try {
UrlResponse response = doMethod("DELETE", "/books/" + id, null);
String result = response.body;
Assert.assertNotNull(response);
Assert.assertNotNull(response.body);
Assert.assertEquals(200, response.status);
Assert.assertTrue(result.contains(id));
Assert.assertTrue(result.contains("deleted"));
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
@Test
public void testBookNotFound() {
try {
doMethod("GET", "/books/" + id, null);
} catch (Exception e) {
if (e instanceof FileNotFoundException) {
Assert.assertTrue(true);
} else {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
private static UrlResponse doMethod(String requestMethod, String path, String body) throws Exception {
URL url = new URL("http://localhost:" + PORT + path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(requestMethod);
// connection.setDoOutput(true);
connection.connect();
// connection.getOutputStream().flush();
String res = IOUtils.toString(connection.getInputStream());
UrlResponse response = new UrlResponse();
response.body = res;
response.status = connection.getResponseCode();
response.headers = connection.getHeaderFields();
return response;
}
private static class UrlResponse {
public Map<String, List<String>> headers;
private String body;
private int status;
}
}
| true | true | public void testGetBook() {
try {
// ensure there is a book
testCreateBook();
UrlResponse response = doMethod("GET", "/books/" + id, null);
String result = response.body;
Assert.assertNotNull(response);
Assert.assertNotNull(response.body);
Assert.assertEquals(200, response.status);
Assert.assertTrue(result.contains(AUTHOR));
Assert.assertTrue(result.contains(TITLE));
// verify response header set by filters:
Assert.assertTrue(response.headers.get("FOZ").get(0).equals("BAZ"));
Assert.assertTrue(response.headers.get("FOO").get(0).equals("BAR"));
// delete the book again
testDeleteBook();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
| public void testGetBook() {
try {
// ensure there is a book
testCreateBook();
UrlResponse response = doMethod("GET", "/books/" + id, null);
String result = response.body;
Assert.assertNotNull(response);
Assert.assertNotNull(response.body);
Assert.assertEquals(200, response.status);
Assert.assertTrue(result.contains(AUTHOR));
Assert.assertTrue(result.contains(TITLE));
// verify response header set by filters:
Assert.assertTrue(response.headers.get("FOZ").get(0).equals("BAZ"));
Assert.assertTrue(response.headers.get("FOO").get(0).equals("BAR"));
// delete the book again
//Comment this delete to ensure the running of the tests
//testDeleteBook();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
|
diff --git a/Maze.java b/Maze.java
index a0f2196..6f56017 100644
--- a/Maze.java
+++ b/Maze.java
@@ -1,281 +1,281 @@
// name: Torin Rudeen
// dependencies: StdDraw, StdIn, StdOut
public class Maze
{
//input maze from file; 0 = passageway, 1 = wall, 2 = entrance, 3 = exit
// file begins with height followed by width.
public static int[][] load()
{
int height = StdIn.readInt();
int width = StdIn.readInt();
int[][] maze = new int[height][width];
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
maze[i][j] = StdIn.readInt();
}
}
return maze;
}
public static int[][] generate(int height, int width)
{
height = 2*height + 1;
width = 2*width + 1;
int[][] maze = new int[height][width];
boolean[][] visited = newBoolean(height, width, false);
// fill maze with walls.
for (int i = 0; i < height; i++)
{
{
for (int j = 0; j < width; j++)
{
if (i % 2 == 0 || j % 2 == 0) maze[i][j] = 1;
}
}
}
// place exit and entrance.
int endI = (((int) ((height - 1)*Math.random()))/2)*2 + 1;
int startI = (((int) ((height - 1)*Math.random()))/2)*2 + 1;
maze[endI][0] = 2;
maze[startI][width - 1] = 3;
// call carving function to carve maze itself.
carve(endI, 1, maze, visited);
return maze;
}
// recursive function, uses depth first search to carve out a perfect maze.
// (perfect = every square part of maze, one and only one path between any
// two spaces in the maze).
public static void carve(int currentI, int currentJ, int[][] maze,
boolean[][] visited)
{
// mark current cell as visited.
visited[currentI][currentJ] = true;
// fetch a random ordering of the cardinal directions.
int[][] directions = randomDirections();
// call itself recursively in the four compass directions, in the order
// determined above.
for (int i = 0; i < 4; i++)
{
int newI = currentI + 2*directions[i][0];
int newJ = currentJ + 2*directions[i][1];
// ensure target square is in maze and unvisited.
if (newI < 1 || newI >= maze.length - 1 || newJ < 1
|| newJ >= maze[0].length - 1) continue;
if (visited[newI][newJ] == true) continue;
// remove the wall between current square and target square, and
// then move to target square.
maze[currentI + directions[i][0]][currentJ + directions[i][1]] = 0;
carve(newI, newJ, maze, visited);
}
return;
}
// generates a random ordering of the cardinal directions, in array form.
public static int[][] randomDirections()
{
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int a[] = new int[2];
for (int i = 0; i < 3; i++)
{
a = directions[i];
int random = (int) (Math.random()*(3-i));
int target = i + random + 1;
directions[i] = directions[target];
directions[target] = a;
}
return directions;
}
// recursive algorithm to solve maze by depth first search. Note that
// this algorithm is designed to start at the exit and find the entrance.
// after the entrance is found, it will color the path leading back to the
// exit, meaning that the solution path will animate the way the user
// expects (from entrance to exit).
public static boolean solve(int[][] maze, int currentI, int currentJ,
boolean[][] checked)
{
// return if current square is out of the maze, a wall, the entrance,
// or has been checked. If current square is entrance, it returns true,
// signaling the start of the solution path.
if (currentI < 0 || currentI >= maze.length || currentJ < 0
|| currentJ >= maze[0].length) return false;
if (maze[currentI][currentJ] == 2) return true;
if (maze[currentI][currentJ] == 1) return false;
if (checked[currentI][currentJ] == true) return false;
// mark current cell as checked.
checked[currentI][currentJ] = true;
// fetch random ordering directions, as in carve(), and then call itself
// recursively in each of the four directions.
int[][] directions = randomDirections();
for (int i = 0; i < 4; i++)
{
// call self recursively. If solve() returns true, than called
// square is either the entrance or on the path to the entrance,
// so this square is on the path to the entrance. So, we color
// current square blue (unless we're already at the exit), and
// return true.
if (solve(maze, currentI + directions[i][0],
currentJ + directions[i][1], checked))
{
if (maze[currentI][currentJ] != 3)
StdDraw.filledSquare(currentJ,
maze.length - 0.5 - currentI, 0.51);
return true;
}
}
return false;
}
// prints out the generated or loaded maze.
public static void print(int[][] maze)
{
int height = maze.length;
int width = maze[0].length;
double yMax = height - 0.5;
double xMax = width - 0.5;
StdDraw.setXscale(-0.5, xMax);
StdDraw.setYscale(-0.5, yMax);
// enter animation mode
StdDraw.show(0);
// clear canvas
StdDraw.setPenColor(StdDraw.WHITE);
StdDraw.filledSquare(0, 0, Math.max(xMax, yMax));
StdDraw.setPenColor(StdDraw.BLACK);
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
if (maze[i][j] == 1) StdDraw.filledSquare(j, yMax - i, 0.51);
else if (maze[i][j] == 2)
{
StdDraw.setPenColor(StdDraw.GREEN);
StdDraw.filledSquare(j, yMax - i, 0.51);
StdDraw.setPenColor();
}
else if (maze[i][j] == 3)
{
StdDraw.setPenColor(StdDraw.RED);
StdDraw.filledSquare(j, yMax - i, 0.51);
StdDraw.setPenColor();
}
}
}
StdDraw.show();
}
// utility; generates a boolean array of the requested size, initialized
// to the requested value.
public static boolean[][] newBoolean(int a, int b, Boolean value)
{
boolean[][] array = new boolean[a][b];
for (int i = 0; i < a; i++)
{
for (int j = 0; j < b; j++)
{
array[i][j] = value;
}
}
return array;
}
public static void explore(int[][] maze, int currentI, int currentJ)
{
while (true)
{
if (maze[currentI][currentJ] == 3)
{
StdOut.println("Congratulations!");
break;
}
int[] direction = {0, 0};
}
return;
}
public static void main(String[] args)
{
while (true)
{
// generate a maze of the size user requests.
StdOut.println("What size of maze do you want?");
StdOut.println(" Values from 10 to 100 recommended.");
StdOut.println(" (type 0 to quit)");
int size = StdIn.readInt();
- if (size == 0) break;
- int[][] maze = generate(size, size);
+ if (size == 0) {System.exit(0);}
+ int[][] maze = generate(size, size);
int height = maze.length;
int width = maze[0].length;
// locates exit of maze, so we can begin solution finding from
// that point.
int endI = 0;
int endJ = 0;
int startI = 0;
int startJ = 0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
if (maze[i][j] == 3)
{
endI = i;
endJ = j;
}
if (maze[i][j] == 2)
{
startI = i;
startJ = j;
}
}
}
print(maze);
StdOut.println("What do you want to do now?");
while (true)
{
StdOut.println(" (1 to show solution, 2 to explore,"
+ " 0 to go to previous menu)");
int choice = StdIn.readInt();
if (choice == 1)
{
System.out.println("Animate solution? (1 = yes, 0 = no)");
int animate = StdIn.readInt();
if (animate != 1) { StdDraw.show(0); }
boolean[][] checked = newBoolean(height, width, false);
StdDraw.setPenColor(StdDraw.BLUE);
solve(maze, endI, endJ, checked);
if (animate != 1) { StdDraw.show(); }
}
else if (choice == 2)
{
StdOut.println("Sorry, this feature is not yet implemented.");
// explore(maze, startI, startJ);
}
else if (choice == 0) break;
else StdOut.println("Pardon me, I'm not all that bright."
+ " Could you please enter 1, 2, or 0?");
}
}
}
}
| true | true | public static void main(String[] args)
{
while (true)
{
// generate a maze of the size user requests.
StdOut.println("What size of maze do you want?");
StdOut.println(" Values from 10 to 100 recommended.");
StdOut.println(" (type 0 to quit)");
int size = StdIn.readInt();
if (size == 0) break;
int[][] maze = generate(size, size);
int height = maze.length;
int width = maze[0].length;
// locates exit of maze, so we can begin solution finding from
// that point.
int endI = 0;
int endJ = 0;
int startI = 0;
int startJ = 0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
if (maze[i][j] == 3)
{
endI = i;
endJ = j;
}
if (maze[i][j] == 2)
{
startI = i;
startJ = j;
}
}
}
print(maze);
StdOut.println("What do you want to do now?");
while (true)
{
StdOut.println(" (1 to show solution, 2 to explore,"
+ " 0 to go to previous menu)");
int choice = StdIn.readInt();
if (choice == 1)
{
System.out.println("Animate solution? (1 = yes, 0 = no)");
int animate = StdIn.readInt();
if (animate != 1) { StdDraw.show(0); }
boolean[][] checked = newBoolean(height, width, false);
StdDraw.setPenColor(StdDraw.BLUE);
solve(maze, endI, endJ, checked);
if (animate != 1) { StdDraw.show(); }
}
else if (choice == 2)
{
StdOut.println("Sorry, this feature is not yet implemented.");
// explore(maze, startI, startJ);
}
else if (choice == 0) break;
else StdOut.println("Pardon me, I'm not all that bright."
+ " Could you please enter 1, 2, or 0?");
}
}
}
| public static void main(String[] args)
{
while (true)
{
// generate a maze of the size user requests.
StdOut.println("What size of maze do you want?");
StdOut.println(" Values from 10 to 100 recommended.");
StdOut.println(" (type 0 to quit)");
int size = StdIn.readInt();
if (size == 0) {System.exit(0);}
int[][] maze = generate(size, size);
int height = maze.length;
int width = maze[0].length;
// locates exit of maze, so we can begin solution finding from
// that point.
int endI = 0;
int endJ = 0;
int startI = 0;
int startJ = 0;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
if (maze[i][j] == 3)
{
endI = i;
endJ = j;
}
if (maze[i][j] == 2)
{
startI = i;
startJ = j;
}
}
}
print(maze);
StdOut.println("What do you want to do now?");
while (true)
{
StdOut.println(" (1 to show solution, 2 to explore,"
+ " 0 to go to previous menu)");
int choice = StdIn.readInt();
if (choice == 1)
{
System.out.println("Animate solution? (1 = yes, 0 = no)");
int animate = StdIn.readInt();
if (animate != 1) { StdDraw.show(0); }
boolean[][] checked = newBoolean(height, width, false);
StdDraw.setPenColor(StdDraw.BLUE);
solve(maze, endI, endJ, checked);
if (animate != 1) { StdDraw.show(); }
}
else if (choice == 2)
{
StdOut.println("Sorry, this feature is not yet implemented.");
// explore(maze, startI, startJ);
}
else if (choice == 0) break;
else StdOut.println("Pardon me, I'm not all that bright."
+ " Could you please enter 1, 2, or 0?");
}
}
}
|
diff --git a/src/java/com/eviware/soapui/impl/wsdl/testcase/WsdlTestCase.java b/src/java/com/eviware/soapui/impl/wsdl/testcase/WsdlTestCase.java
index 1c3f80077..71f96fa05 100644
--- a/src/java/com/eviware/soapui/impl/wsdl/testcase/WsdlTestCase.java
+++ b/src/java/com/eviware/soapui/impl/wsdl/testcase/WsdlTestCase.java
@@ -1,1234 +1,1234 @@
/*
* soapUI, copyright (C) 2004-2011 eviware.com
*
* soapUI is free software; you can redistribute it and/or modify it under the
* terms of version 2.1 of the GNU Lesser General Public License as published by
* the Free Software Foundation.
*
* soapUI 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 at gnu.org.
*/
package com.eviware.soapui.impl.wsdl.testcase;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.log4j.Logger;
import com.eviware.soapui.SoapUI;
import com.eviware.soapui.config.LoadTestConfig;
import com.eviware.soapui.config.SecurityTestConfig;
import com.eviware.soapui.config.TestCaseConfig;
import com.eviware.soapui.config.TestStepConfig;
import com.eviware.soapui.config.WsrmVersionTypeConfig;
import com.eviware.soapui.impl.wsdl.AbstractTestPropertyHolderWsdlModelItem;
import com.eviware.soapui.impl.wsdl.WsdlTestSuite;
import com.eviware.soapui.impl.wsdl.loadtest.LoadTestAssertion;
import com.eviware.soapui.impl.wsdl.loadtest.WsdlLoadTest;
import com.eviware.soapui.impl.wsdl.loadtest.assertions.TestStepStatusAssertion;
import com.eviware.soapui.impl.wsdl.panels.teststeps.amf.AMFTestRunListener;
import com.eviware.soapui.impl.wsdl.support.wsrm.WsrmTestRunListener;
import com.eviware.soapui.impl.wsdl.support.wsrm.WsrmUtils;
import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestStep;
import com.eviware.soapui.impl.wsdl.teststeps.registry.HttpRequestStepFactory;
import com.eviware.soapui.impl.wsdl.teststeps.registry.WsdlTestStepFactory;
import com.eviware.soapui.impl.wsdl.teststeps.registry.WsdlTestStepRegistry;
import com.eviware.soapui.model.ModelItem;
import com.eviware.soapui.model.security.SecurityScan;
import com.eviware.soapui.model.support.ModelSupport;
import com.eviware.soapui.model.testsuite.LoadTest;
import com.eviware.soapui.model.testsuite.TestCase;
import com.eviware.soapui.model.testsuite.TestCaseRunContext;
import com.eviware.soapui.model.testsuite.TestCaseRunner;
import com.eviware.soapui.model.testsuite.TestRunListener;
import com.eviware.soapui.model.testsuite.TestStep;
import com.eviware.soapui.security.SecurityTest;
import com.eviware.soapui.support.StringUtils;
import com.eviware.soapui.support.UISupport;
import com.eviware.soapui.support.action.swing.ActionList;
import com.eviware.soapui.support.action.swing.DefaultActionList;
import com.eviware.soapui.support.resolver.ResolveDialog;
import com.eviware.soapui.support.scripting.SoapUIScriptEngine;
import com.eviware.soapui.support.scripting.SoapUIScriptEngineRegistry;
import com.eviware.soapui.support.types.StringToObjectMap;
/**
* TestCase implementation for WSDL projects
*
* @author Ole.Matzura
*/
public class WsdlTestCase extends AbstractTestPropertyHolderWsdlModelItem<TestCaseConfig> implements TestCase
{
private final static Logger logger = Logger.getLogger( WsdlTestCase.class );
public final static String KEEP_SESSION_PROPERTY = WsdlTestCase.class.getName() + "@keepSession";
public final static String FAIL_ON_ERROR_PROPERTY = WsdlTestCase.class.getName() + "@failOnError";
public final static String FAIL_ON_ERRORS_PROPERTY = WsdlTestCase.class.getName() + "@failOnErrors";
public final static String DISCARD_OK_RESULTS = WsdlTestCase.class.getName() + "@discardOkResults";
public final static String SETUP_SCRIPT_PROPERTY = WsdlTestCase.class.getName() + "@setupScript";
public final static String TEARDOWN_SCRIPT_PROPERTY = WsdlTestCase.class.getName() + "@tearDownScript";
public static final String TIMEOUT_PROPERTY = WsdlTestCase.class.getName() + "@timeout";
public static final String SEARCH_PROPERTIES_PROPERTY = WsdlTestCase.class.getName() + "@searchProperties";
private final WsdlTestSuite testSuite;
private List<WsdlTestStep> testSteps = new ArrayList<WsdlTestStep>();
private List<WsdlLoadTest> loadTests = new ArrayList<WsdlLoadTest>();
private List<SecurityTest> securityTests = new ArrayList<SecurityTest>();
private Set<TestRunListener> testRunListeners = new HashSet<TestRunListener>();
private DefaultActionList createActions;
private final boolean forLoadTest;
private SoapUIScriptEngine setupScriptEngine;
private SoapUIScriptEngine tearDownScriptEngine;
/**
* runFromHereContext is used only for run from here action
*/
private StringToObjectMap runFromHereContext = new StringToObjectMap();
public WsdlTestCase( WsdlTestSuite testSuite, TestCaseConfig config, boolean forLoadTest )
{
super( config, testSuite, "/testCase.gif" );
this.testSuite = testSuite;
this.forLoadTest = forLoadTest;
List<TestStepConfig> testStepConfigs = config.getTestStepList();
List<TestStepConfig> removed = new ArrayList<TestStepConfig>();
for( TestStepConfig tsc : testStepConfigs )
{
WsdlTestStep testStep = createTestStepFromConfig( tsc );
if( testStep != null )
{
ensureUniqueName( testStep );
testSteps.add( testStep );
}
else
{
removed.add( tsc );
}
}
if( removed.size() > 0 )
{
testStepConfigs.removeAll( removed );
}
if( !forLoadTest )
{
List<LoadTestConfig> loadTestConfigs = config.getLoadTestList();
for( LoadTestConfig tsc : loadTestConfigs )
{
WsdlLoadTest loadTest = buildLoadTest( tsc );
loadTests.add( loadTest );
}
}
- if( !forLoadTest )
- {
+// if( !forLoadTest )
+// {
List<SecurityTestConfig> securityTestConfigs = config.getSecurityTestList();
for( SecurityTestConfig tsc : securityTestConfigs )
{
SecurityTest securityTest = buildSecurityTest( tsc );
securityTests.add( securityTest );
}
- }
+// }
// init default configs
if( !config.isSetFailOnError() )
config.setFailOnError( true );
if( !config.isSetFailTestCaseOnErrors() )
config.setFailTestCaseOnErrors( true );
if( !config.isSetKeepSession() )
config.setKeepSession( false );
if( !config.isSetMaxResults() )
config.setMaxResults( 0 );
for( TestRunListener listener : SoapUI.getListenerRegistry().getListeners( TestRunListener.class ) )
{
addTestRunListener( listener );
}
if( !getConfig().isSetProperties() )
getConfig().addNewProperties();
setPropertiesConfig( getConfig().getProperties() );
WsrmTestRunListener wsrmListener = new WsrmTestRunListener();
addTestRunListener( wsrmListener );
addTestRunListener( new AMFTestRunListener() );
}
public boolean isForLoadTest()
{
return forLoadTest;
}
public WsdlLoadTest buildLoadTest( LoadTestConfig tsc )
{
return new WsdlLoadTest( this, tsc );
}
public boolean getKeepSession()
{
return getConfig().getKeepSession();
}
public void setKeepSession( boolean keepSession )
{
boolean old = getKeepSession();
if( old != keepSession )
{
getConfig().setKeepSession( keepSession );
notifyPropertyChanged( KEEP_SESSION_PROPERTY, old, keepSession );
}
}
public void setSetupScript( String script )
{
String oldScript = getSetupScript();
if( !getConfig().isSetSetupScript() )
getConfig().addNewSetupScript();
getConfig().getSetupScript().setStringValue( script );
if( setupScriptEngine != null )
setupScriptEngine.setScript( script );
notifyPropertyChanged( SETUP_SCRIPT_PROPERTY, oldScript, script );
}
public String getSetupScript()
{
return getConfig().isSetSetupScript() ? getConfig().getSetupScript().getStringValue() : null;
}
public void setTearDownScript( String script )
{
String oldScript = getTearDownScript();
if( !getConfig().isSetTearDownScript() )
getConfig().addNewTearDownScript();
getConfig().getTearDownScript().setStringValue( script );
if( tearDownScriptEngine != null )
tearDownScriptEngine.setScript( script );
notifyPropertyChanged( TEARDOWN_SCRIPT_PROPERTY, oldScript, script );
}
public String getTearDownScript()
{
return getConfig().isSetTearDownScript() ? getConfig().getTearDownScript().getStringValue() : null;
}
public boolean getFailOnError()
{
return getConfig().getFailOnError();
}
public boolean getFailTestCaseOnErrors()
{
return getConfig().getFailTestCaseOnErrors();
}
public void setFailOnError( boolean failOnError )
{
boolean old = getFailOnError();
if( old != failOnError )
{
getConfig().setFailOnError( failOnError );
notifyPropertyChanged( FAIL_ON_ERROR_PROPERTY, old, failOnError );
}
}
public void setFailTestCaseOnErrors( boolean failTestCaseOnErrors )
{
boolean old = getFailTestCaseOnErrors();
if( old != failTestCaseOnErrors )
{
getConfig().setFailTestCaseOnErrors( failTestCaseOnErrors );
notifyPropertyChanged( FAIL_ON_ERRORS_PROPERTY, old, failTestCaseOnErrors );
}
}
public boolean getSearchProperties()
{
return getConfig().getSearchProperties();
}
public void setSearchProperties( boolean searchProperties )
{
boolean old = getSearchProperties();
if( old != searchProperties )
{
getConfig().setSearchProperties( searchProperties );
notifyPropertyChanged( SEARCH_PROPERTIES_PROPERTY, old, searchProperties );
}
}
public boolean getDiscardOkResults()
{
return getConfig().getDiscardOkResults();
}
public void setDiscardOkResults( boolean discardOkResults )
{
boolean old = getDiscardOkResults();
if( old != discardOkResults )
{
getConfig().setDiscardOkResults( discardOkResults );
notifyPropertyChanged( DISCARD_OK_RESULTS, old, discardOkResults );
}
}
public int getMaxResults()
{
return getConfig().getMaxResults();
}
public void setMaxResults( int maxResults )
{
int old = getMaxResults();
if( old != maxResults )
{
getConfig().setMaxResults( maxResults );
notifyPropertyChanged( "maxResults", old, maxResults );
}
}
private WsdlTestStep createTestStepFromConfig( TestStepConfig tsc )
{
WsdlTestStepFactory factory = WsdlTestStepRegistry.getInstance().getFactory( tsc.getType() );
if( factory != null )
{
WsdlTestStep testStep = factory.buildTestStep( this, tsc, forLoadTest );
return testStep;
}
else
{
logger.error( "Failed to create test step for [" + tsc.getName() + "]" );
return null;
}
}
private boolean ensureUniqueName( WsdlTestStep testStep )
{
String name = testStep.getName();
while( name == null || getTestStepByName( name.trim() ) != null )
{
if( name == null )
name = testStep.getName();
else
{
int cnt = 0;
while( getTestStepByName( name.trim() ) != null )
{
cnt++ ;
name = testStep.getName() + " " + cnt;
}
if( cnt == 0 )
break;
}
name = UISupport.prompt( "TestStep name must be unique, please specify new name for step\n" + "["
+ testStep.getName() + "] in TestCase [" + getTestSuite().getProject().getName() + "->"
+ getTestSuite().getName() + "->" + getName() + "]", "Change TestStep name", name );
if( name == null )
return false;
}
if( !name.equals( testStep.getName() ) )
testStep.setName( name );
return true;
}
public WsdlLoadTest addNewLoadTest( String name )
{
WsdlLoadTest loadTest = buildLoadTest( getConfig().addNewLoadTest() );
loadTest.setStartDelay( 0 );
loadTest.setName( name );
loadTests.add( loadTest );
loadTest.addAssertion( TestStepStatusAssertion.STEP_STATUS_TYPE, LoadTestAssertion.ANY_TEST_STEP, false );
( getTestSuite() ).fireLoadTestAdded( loadTest );
return loadTest;
}
public void removeLoadTest( WsdlLoadTest loadTest )
{
int ix = loadTests.indexOf( loadTest );
loadTests.remove( ix );
try
{
( getTestSuite() ).fireLoadTestRemoved( loadTest );
}
finally
{
loadTest.release();
getConfig().removeLoadTest( ix );
}
}
public WsdlTestSuite getTestSuite()
{
return testSuite;
}
public WsdlTestStep cloneStep( WsdlTestStep testStep, String name )
{
return testStep.clone( this, name );
}
public WsdlTestStep getTestStepAt( int index )
{
return testSteps.get( index );
}
public int getTestStepCount()
{
return testSteps.size();
}
public WsdlLoadTest getLoadTestAt( int index )
{
return loadTests.get( index );
}
public LoadTest getLoadTestByName( String loadTestName )
{
return ( LoadTest )getWsdlModelItemByName( loadTests, loadTestName );
}
public int getLoadTestCount()
{
return loadTests.size();
}
public WsdlTestStep addTestStep( TestStepConfig stepConfig )
{
return insertTestStep( stepConfig, -1, true );
}
public WsdlTestStep addTestStep( String type, String name )
{
TestStepConfig newStepConfig = WsdlTestStepRegistry.getInstance().getFactory( type ).createNewTestStep( this,
name );
if( newStepConfig != null )
{
return addTestStep( newStepConfig );
}
else
return null;
}
public WsdlTestStep addTestStep( String type, String name, String endpoint, String method )
{
TestStepConfig newStepConfig = ( ( HttpRequestStepFactory )WsdlTestStepRegistry.getInstance().getFactory( type ) )
.createNewTestStep( this, name, endpoint, method );
if( newStepConfig != null )
{
return addTestStep( newStepConfig );
}
else
return null;
}
public WsdlTestStep insertTestStep( String type, String name, int index )
{
TestStepConfig newStepConfig = WsdlTestStepRegistry.getInstance().getFactory( type ).createNewTestStep( this,
name );
if( newStepConfig != null )
{
return insertTestStep( newStepConfig, index, false );
}
else
return null;
}
public WsdlTestStep importTestStep( WsdlTestStep testStep, String name, int index, boolean createCopy )
{
testStep.beforeSave();
TestStepConfig newStepConfig = ( TestStepConfig )testStep.getConfig().copy();
newStepConfig.setName( name );
WsdlTestStep result = insertTestStep( newStepConfig, index, createCopy );
if( result == null )
return null;
if( createCopy )
ModelSupport.unsetIds( result );
resolveTestCase();
return result;
}
private void resolveTestCase()
{
ResolveDialog resolver = new ResolveDialog( "Validate TestCase", "Checks TestCase for inconsistencies", null );
resolver.setShowOkMessage( false );
resolver.resolve( this );
}
public WsdlTestStep[] importTestSteps( WsdlTestStep[] testSteps, int index, boolean createCopies )
{
TestStepConfig[] newStepConfigs = new TestStepConfig[testSteps.length];
for( int c = 0; c < testSteps.length; c++ )
{
testSteps[c].beforeSave();
newStepConfigs[c] = ( TestStepConfig )testSteps[c].getConfig().copy();
}
WsdlTestStep[] result = insertTestSteps( newStepConfigs, index, createCopies );
resolveTestCase();
return result;
}
public WsdlTestStep insertTestStep( TestStepConfig stepConfig, int ix )
{
return insertTestStep( stepConfig, ix, true );
}
public WsdlTestStep insertTestStep( TestStepConfig stepConfig, int ix, boolean clearIds )
{
TestStepConfig newStepConfig = ix == -1 ? getConfig().addNewTestStep() : getConfig().insertNewTestStep( ix );
newStepConfig.set( stepConfig );
WsdlTestStep testStep = createTestStepFromConfig( newStepConfig );
if( !ensureUniqueName( testStep ) )
{
testStep.release();
getConfig().getTestStepList().remove( newStepConfig );
return null;
}
if( clearIds )
ModelSupport.unsetIds( testStep );
if( ix == -1 )
testSteps.add( testStep );
else
testSteps.add( ix , testStep );
testStep.afterLoad();
if( getTestSuite() != null )
( getTestSuite() ).fireTestStepAdded( testStep, ix == -1 ? testSteps.size() - 1 : ix );
notifyPropertyChanged( "testSteps", null, testStep );
return testStep;
}
public WsdlTestStep[] insertTestSteps( TestStepConfig[] stepConfig, int ix, boolean clearIds )
{
WsdlTestStep[] result = new WsdlTestStep[stepConfig.length];
for( int c = 0; c < stepConfig.length; c++ )
{
TestStepConfig newStepConfig = ix == -1 ? getConfig().addNewTestStep() : getConfig()
.insertNewTestStep( ix + c );
newStepConfig.set( stepConfig[c] );
WsdlTestStep testStep = createTestStepFromConfig( newStepConfig );
if( !ensureUniqueName( testStep ) )
return null;
if( clearIds )
ModelSupport.unsetIds( testStep );
if( ix == -1 )
testSteps.add( testStep );
else
testSteps.add( ix + c, testStep );
result[c] = testStep;
}
for( int c = 0; c < result.length; c++ )
{
result[c].afterLoad();
if( getTestSuite() != null )
( getTestSuite() ).fireTestStepAdded( result[c], getIndexOfTestStep( result[c] ) );
notifyPropertyChanged( "testSteps", null, result[c] );
}
return result;
}
public void removeTestStep( WsdlTestStep testStep )
{
int ix = testSteps.indexOf( testStep );
if( ix == -1 )
{
logger.error( "TestStep [" + testStep.getName() + "] passed to removeTestStep in testCase [" + getName()
+ "] not found" );
return;
}
testSteps.remove( ix );
for( SecurityTest securityTest : getSecurityTestList() )
{
List<SecurityScan> testStepChecks = securityTest.getTestStepSecurityScans( testStep.getId() );
for( Iterator<SecurityScan> iterator = testStepChecks.iterator(); iterator.hasNext(); )
{
SecurityScan chk = iterator.next();
securityTest.removeSecurityScanWhenRemoveTestStep( testStep, chk );
iterator.remove();
}
}
try
{
( getTestSuite() ).fireTestStepRemoved( testStep, ix );
}
finally
{
notifyPropertyChanged( "testSteps", testStep, null );
testStep.release();
for( int c = 0; c < getConfig().sizeOfTestStepArray(); c++ )
{
if( testStep.getConfig() == getConfig().getTestStepArray( c ) )
{
getConfig().removeTestStep( c );
break;
}
}
}
}
public WsdlTestCaseRunner run( StringToObjectMap properties, boolean async )
{
WsdlTestCaseRunner runner = new WsdlTestCaseRunner( this, properties );
runner.start( async );
return runner;
}
public void addTestRunListener( TestRunListener listener )
{
if( listener == null )
throw new RuntimeException( "listener must not be null" );
testRunListeners.add( listener );
}
public void removeTestRunListener( TestRunListener listener )
{
testRunListeners.remove( listener );
}
public TestRunListener[] getTestRunListeners()
{
return testRunListeners.toArray( new TestRunListener[testRunListeners.size()] );
}
public Map<String, TestStep> getTestSteps()
{
Map<String, TestStep> result = new HashMap<String, TestStep>();
for( TestStep testStep : testSteps )
result.put( testStep.getName(), testStep );
return result;
}
public Map<String, TestStep> getTestStepsOrdered()
{
Map<String, TestStep> result = new TreeMap<String, TestStep>();
for( TestStep testStep : testSteps )
result.put( testStep.getName(), testStep );
return result;
}
public Map<String, LoadTest> getLoadTests()
{
Map<String, LoadTest> result = new HashMap<String, LoadTest>();
for( LoadTest loadTest : loadTests )
result.put( loadTest.getName(), loadTest );
return result;
}
public int getIndexOfTestStep( TestStep step )
{
return testSteps.indexOf( step );
}
/**
* Moves a step by the specified offset, a bit awkward since xmlbeans doesn't
* support reordering of arrays, we need to create copies of the contained
* XmlObjects
*
* @param ix
* @param offset
*/
public void moveTestStep( int ix, int offset )
{
if( offset == 0 )
return;
WsdlTestStep step = testSteps.get( ix );
if( ix + offset >= testSteps.size() )
offset = testSteps.size() - ix - 1;
testSteps.remove( ix );
testSteps.add( ix + offset, step );
TestStepConfig[] configs = new TestStepConfig[testSteps.size()];
TestCaseConfig conf = getConfig();
for( int c = 0; c < testSteps.size(); c++ )
{
if( offset > 0 )
{
if( c < ix )
configs[c] = ( TestStepConfig )conf.getTestStepArray( c ).copy();
else if( c < ( ix + offset ) )
configs[c] = ( TestStepConfig )conf.getTestStepArray( c + 1 ).copy();
else if( c == ix + offset )
configs[c] = ( TestStepConfig )conf.getTestStepArray( ix ).copy();
else
configs[c] = ( TestStepConfig )conf.getTestStepArray( c ).copy();
}
else
{
if( c < ix + offset )
configs[c] = ( TestStepConfig )conf.getTestStepArray( c ).copy();
else if( c == ix + offset )
configs[c] = ( TestStepConfig )conf.getTestStepArray( ix ).copy();
else if( c <= ix )
configs[c] = ( TestStepConfig )conf.getTestStepArray( c - 1 ).copy();
else
configs[c] = ( TestStepConfig )conf.getTestStepArray( c ).copy();
}
}
conf.setTestStepArray( configs );
for( int c = 0; c < configs.length; c++ )
{
( testSteps.get( c ) ).resetConfigOnMove( conf.getTestStepArray( c ) );
}
( getTestSuite() ).fireTestStepMoved( step, ix, offset );
}
public int getIndexOfLoadTest( LoadTest loadTest )
{
return loadTests.indexOf( loadTest );
}
public int getTestStepIndexByName( String stepName )
{
for( int c = 0; c < testSteps.size(); c++ )
{
if( testSteps.get( c ).getName().equals( stepName ) )
return c;
}
return -1;
}
@SuppressWarnings( "unchecked" )
public <T extends TestStep> T findPreviousStepOfType( TestStep referenceStep, Class<T> stepClass )
{
int currentStepIndex = getIndexOfTestStep( referenceStep );
int ix = currentStepIndex - 1;
while( ix >= 0 && !stepClass.isAssignableFrom( getTestStepAt( ix ).getClass() ) )
{
ix-- ;
}
return ( T )( ix < 0 ? null : getTestStepAt( ix ) );
}
@SuppressWarnings( "unchecked" )
public <T extends TestStep> T findNextStepOfType( TestStep referenceStep, Class<T> stepClass )
{
int currentStepIndex = getIndexOfTestStep( referenceStep );
int ix = currentStepIndex + 1;
while( ix < getTestStepCount() && !stepClass.isAssignableFrom( getTestStepAt( ix ).getClass() ) )
{
ix++ ;
}
return ( T )( ix >= getTestStepCount() ? null : getTestStepAt( ix ) );
}
public List<TestStep> getTestStepList()
{
List<TestStep> result = new ArrayList<TestStep>();
for( TestStep step : testSteps )
result.add( step );
return result;
}
@SuppressWarnings( "unchecked" )
public <T extends TestStep> List<T> getTestStepsOfType( Class<T> stepType )
{
List<T> result = new ArrayList<T>();
for( TestStep step : testSteps )
if( step.getClass().isAssignableFrom( stepType ) )
result.add( ( T )step );
return result;
}
public WsdlTestStep getTestStepByName( String stepName )
{
return ( WsdlTestStep )getWsdlModelItemByName( testSteps, stepName );
}
public WsdlLoadTest cloneLoadTest( WsdlLoadTest loadTest, String name )
{
loadTest.beforeSave();
LoadTestConfig loadTestConfig = getConfig().addNewLoadTest();
loadTestConfig.set( loadTest.getConfig().copy() );
WsdlLoadTest newLoadTest = buildLoadTest( loadTestConfig );
newLoadTest.setName( name );
ModelSupport.unsetIds( newLoadTest );
newLoadTest.afterLoad();
loadTests.add( newLoadTest );
( getTestSuite() ).fireLoadTestAdded( newLoadTest );
return newLoadTest;
}
@Override
public void release()
{
super.release();
for( WsdlTestStep testStep : testSteps )
testStep.release();
for( WsdlLoadTest loadTest : loadTests )
loadTest.release();
for( SecurityTest securityTest : securityTests )
securityTest.release();
testRunListeners.clear();
if( setupScriptEngine != null )
setupScriptEngine.release();
if( tearDownScriptEngine != null )
tearDownScriptEngine.release();
}
public ActionList getCreateActions()
{
return createActions;
}
public void resetConfigOnMove( TestCaseConfig testCaseConfig )
{
setConfig( testCaseConfig );
int mod = 0;
List<TestStepConfig> configs = getConfig().getTestStepList();
for( int c = 0; c < configs.size(); c++ )
{
if( WsdlTestStepRegistry.getInstance().hasFactory( configs.get( c ) ) )
{
( testSteps.get( c - mod ) ).resetConfigOnMove( configs.get( c ) );
}
else
mod++ ;
}
List<LoadTestConfig> loadTestConfigs = getConfig().getLoadTestList();
for( int c = 0; c < loadTestConfigs.size(); c++ )
{
loadTests.get( c ).resetConfigOnMove( loadTestConfigs.get( c ) );
}
List<SecurityTestConfig> securityTestConfigs = getConfig().getSecurityTestList();
for( int c = 0; c < securityTestConfigs.size(); c++ )
{
securityTests.get( c ).resetConfigOnMove( securityTestConfigs.get( c ) );
}
setPropertiesConfig( testCaseConfig.getProperties() );
}
public List<LoadTest> getLoadTestList()
{
List<LoadTest> result = new ArrayList<LoadTest>();
for( LoadTest loadTest : loadTests )
result.add( loadTest );
return result;
}
public Object runSetupScript( TestCaseRunContext runContext, TestCaseRunner runner ) throws Exception
{
String script = getSetupScript();
if( StringUtils.isNullOrEmpty( script ) )
return null;
if( setupScriptEngine == null )
{
setupScriptEngine = SoapUIScriptEngineRegistry.create( this );
setupScriptEngine.setScript( script );
}
setupScriptEngine.setVariable( "testCase", this );
setupScriptEngine.setVariable( "context", runContext );
setupScriptEngine.setVariable( "testRunner", runner );
setupScriptEngine.setVariable( "log", SoapUI.ensureGroovyLog() );
return setupScriptEngine.run();
}
public Object runTearDownScript( TestCaseRunContext runContext, TestCaseRunner runner ) throws Exception
{
String script = getTearDownScript();
if( StringUtils.isNullOrEmpty( script ) )
return null;
if( tearDownScriptEngine == null )
{
tearDownScriptEngine = SoapUIScriptEngineRegistry.create( this );
tearDownScriptEngine.setScript( script );
}
tearDownScriptEngine.setVariable( "context", runContext );
tearDownScriptEngine.setVariable( "testCase", this );
tearDownScriptEngine.setVariable( "testRunner", runner );
tearDownScriptEngine.setVariable( "log", SoapUI.ensureGroovyLog() );
return tearDownScriptEngine.run();
}
public List<? extends ModelItem> getChildren()
{
List<ModelItem> result = new ArrayList<ModelItem>();
result.addAll( getTestStepList() );
result.addAll( getLoadTestList() );
result.addAll( getSecurityTestList() );
return result;
}
@Override
public void setName( String name )
{
String oldLabel = getLabel();
super.setName( name );
String label = getLabel();
if( oldLabel != null && !oldLabel.equals( label ) )
{
notifyPropertyChanged( LABEL_PROPERTY, oldLabel, label );
}
}
public String getLabel()
{
String name = getName();
if( isDisabled() )
return name + " (disabled)";
else
return name;
}
public boolean isDisabled()
{
return getConfig().getDisabled();
}
public void setDisabled( boolean disabled )
{
String oldLabel = getLabel();
boolean oldDisabled = isDisabled();
if( oldDisabled == disabled )
return;
if( disabled )
getConfig().setDisabled( disabled );
else if( getConfig().isSetDisabled() )
getConfig().unsetDisabled();
notifyPropertyChanged( DISABLED_PROPERTY, oldDisabled, disabled );
String label = getLabel();
if( !oldLabel.equals( label ) )
notifyPropertyChanged( LABEL_PROPERTY, oldLabel, label );
}
public long getTimeout()
{
return getConfig().getTimeout();
}
public void setTimeout( long timeout )
{
long old = getTimeout();
getConfig().setTimeout( timeout );
notifyPropertyChanged( TIMEOUT_PROPERTY, old, timeout );
}
public void exportTestCase( File file )
{
try
{
this.getConfig().newCursor().save( file );
}
catch( IOException e )
{
e.printStackTrace();
}
}
public void afterCopy( WsdlTestSuite oldTestSuite, WsdlTestCase oldTestCase )
{
for( WsdlTestStep testStep : testSteps )
testStep.afterCopy( oldTestSuite, oldTestCase );
}
public void importSecurityTests( WsdlTestSuite oldTestSuite, WsdlTestCase oldTestCase )
{
for( SecurityTest secTest : oldTestCase.getSecurityTestList() )
{
SecurityTest newSecurityTest = addNewSecurityTest( secTest.getName() );
for( int i = 0; i < oldTestCase.getTestStepList().size(); i++ )
{
TestStep oldStep = oldTestCase.getTestStepAt( i );
TestStep newStep = getTestStepAt( i );
for( SecurityScan secCheck : secTest.getTestStepSecurityScans( oldStep.getId() ) )
{
newSecurityTest.importSecurityScan( newStep, secCheck, true );
}
}
}
}
public void setWsrmEnabled( boolean enabled )
{
getConfig().setWsrmEnabled( enabled );
}
public void setWsrmAckTo( String ackTo )
{
getConfig().setWsrmAckTo( ackTo );
}
public void setWsrmExpires( Long expires )
{
getConfig().setWsrmExpires( expires );
}
public void setWsrmVersion( String version )
{
getConfig().setWsrmVersion( WsrmVersionTypeConfig.Enum.forString( version ) );
}
public boolean getWsrmEnabled()
{
return getConfig().getWsrmEnabled();
}
public String getWsrmAckTo()
{
return getConfig().getWsrmAckTo();
}
public long getWsrmExpires()
{
return getConfig().getWsrmExpires();
}
public String getWsrmVersion()
{
if( getConfig().getWsrmVersion() == null )
return WsrmVersionTypeConfig.X_1_0.toString();
return getConfig().getWsrmVersion().toString();
}
public String getWsrmVersionNamespace()
{
return WsrmUtils.getWsrmVersionNamespace( getConfig().getWsrmVersion() );
}
public void setAmfAuthorisation( boolean enabled )
{
getConfig().setAmfAuthorisation( enabled );
}
public boolean getAmfAuthorisation()
{
return getConfig().getAmfAuthorisation();
}
public void setAmfLogin( String login )
{
getConfig().setAmfLogin( login );
}
public String getAmfLogin()
{
if( getConfig().getAmfLogin() == null )
return "";
else
return getConfig().getAmfLogin();
}
public void setAmfPassword( String password )
{
getConfig().setAmfPassword( password );
}
public String getAmfPassword()
{
if( getConfig().getAmfPassword() == null )
return "";
else
return getConfig().getAmfPassword();
}
public void setAmfEndpoint( String endpoint )
{
getConfig().setAmfEndpoint( endpoint );
}
public String getAmfEndpoint()
{
if( getConfig().getAmfEndpoint() == null )
return "";
else
return getConfig().getAmfEndpoint();
}
@Override
public int getSecurityTestCount()
{
return securityTests.size();
}
@Override
public int getIndexOfSecurityTest( SecurityTest securityTest )
{
return securityTests.indexOf( securityTest );
}
@Override
public SecurityTest getSecurityTestAt( int index )
{
return securityTests.get( index );
}
@Override
public SecurityTest getSecurityTestByName( String securityTestName )
{
return ( SecurityTest )getWsdlModelItemByName( securityTests, securityTestName );
}
@Override
public List<SecurityTest> getSecurityTestList()
{
return securityTests;
}
public Map<String, SecurityTest> getSecurityTests()
{
Map<String, SecurityTest> result = new HashMap<String, SecurityTest>();
for( SecurityTest securityTest : securityTests )
result.put( securityTest.getName(), securityTest );
return result;
}
public SecurityTest addNewSecurityTest( String name )
{
SecurityTest securityTest = buildSecurityTest( getConfig().addNewSecurityTest() );
securityTest.setName( name );
securityTest.setFailOnError( true );
securityTest.setSkipDataSourceLoops( false );
securityTests.add( securityTest );
( getTestSuite() ).fireSecurityTestAdded( securityTest );
return securityTest;
}
protected SecurityTest buildSecurityTest( SecurityTestConfig addNewSecurityTest )
{
return new SecurityTest( this, addNewSecurityTest );
}
public SecurityTest cloneSecurityTest( SecurityTest securityTest, String name )
{
SecurityTestConfig securityTestConfig = getConfig().addNewSecurityTest();
securityTestConfig.set( securityTest.getConfig().copy() );
SecurityTest newSecurityTest = buildSecurityTest( securityTestConfig );
newSecurityTest.setName( name );
ModelSupport.unsetIds( newSecurityTest );
newSecurityTest.afterLoad();
securityTests.add( newSecurityTest );
( getTestSuite() ).fireSecurityTestAdded( newSecurityTest );
return newSecurityTest;
}
public void removeSecurityTest( SecurityTest securityTest )
{
int ix = securityTests.indexOf( securityTest );
securityTests.remove( ix );
try
{
( getTestSuite() ).fireSecurityTestRemoved( securityTest );
}
finally
{
securityTest.release();
getConfig().removeSecurityTest( ix );
}
}
public StringToObjectMap getRunFromHereContext()
{
return runFromHereContext;
}
public void setRunFromHereContext( StringToObjectMap runFromHereContext )
{
this.runFromHereContext = new StringToObjectMap( runFromHereContext );
}
}
| false | true | public WsdlTestCase( WsdlTestSuite testSuite, TestCaseConfig config, boolean forLoadTest )
{
super( config, testSuite, "/testCase.gif" );
this.testSuite = testSuite;
this.forLoadTest = forLoadTest;
List<TestStepConfig> testStepConfigs = config.getTestStepList();
List<TestStepConfig> removed = new ArrayList<TestStepConfig>();
for( TestStepConfig tsc : testStepConfigs )
{
WsdlTestStep testStep = createTestStepFromConfig( tsc );
if( testStep != null )
{
ensureUniqueName( testStep );
testSteps.add( testStep );
}
else
{
removed.add( tsc );
}
}
if( removed.size() > 0 )
{
testStepConfigs.removeAll( removed );
}
if( !forLoadTest )
{
List<LoadTestConfig> loadTestConfigs = config.getLoadTestList();
for( LoadTestConfig tsc : loadTestConfigs )
{
WsdlLoadTest loadTest = buildLoadTest( tsc );
loadTests.add( loadTest );
}
}
if( !forLoadTest )
{
List<SecurityTestConfig> securityTestConfigs = config.getSecurityTestList();
for( SecurityTestConfig tsc : securityTestConfigs )
{
SecurityTest securityTest = buildSecurityTest( tsc );
securityTests.add( securityTest );
}
}
// init default configs
if( !config.isSetFailOnError() )
config.setFailOnError( true );
if( !config.isSetFailTestCaseOnErrors() )
config.setFailTestCaseOnErrors( true );
if( !config.isSetKeepSession() )
config.setKeepSession( false );
if( !config.isSetMaxResults() )
config.setMaxResults( 0 );
for( TestRunListener listener : SoapUI.getListenerRegistry().getListeners( TestRunListener.class ) )
{
addTestRunListener( listener );
}
if( !getConfig().isSetProperties() )
getConfig().addNewProperties();
setPropertiesConfig( getConfig().getProperties() );
WsrmTestRunListener wsrmListener = new WsrmTestRunListener();
addTestRunListener( wsrmListener );
addTestRunListener( new AMFTestRunListener() );
}
| public WsdlTestCase( WsdlTestSuite testSuite, TestCaseConfig config, boolean forLoadTest )
{
super( config, testSuite, "/testCase.gif" );
this.testSuite = testSuite;
this.forLoadTest = forLoadTest;
List<TestStepConfig> testStepConfigs = config.getTestStepList();
List<TestStepConfig> removed = new ArrayList<TestStepConfig>();
for( TestStepConfig tsc : testStepConfigs )
{
WsdlTestStep testStep = createTestStepFromConfig( tsc );
if( testStep != null )
{
ensureUniqueName( testStep );
testSteps.add( testStep );
}
else
{
removed.add( tsc );
}
}
if( removed.size() > 0 )
{
testStepConfigs.removeAll( removed );
}
if( !forLoadTest )
{
List<LoadTestConfig> loadTestConfigs = config.getLoadTestList();
for( LoadTestConfig tsc : loadTestConfigs )
{
WsdlLoadTest loadTest = buildLoadTest( tsc );
loadTests.add( loadTest );
}
}
// if( !forLoadTest )
// {
List<SecurityTestConfig> securityTestConfigs = config.getSecurityTestList();
for( SecurityTestConfig tsc : securityTestConfigs )
{
SecurityTest securityTest = buildSecurityTest( tsc );
securityTests.add( securityTest );
}
// }
// init default configs
if( !config.isSetFailOnError() )
config.setFailOnError( true );
if( !config.isSetFailTestCaseOnErrors() )
config.setFailTestCaseOnErrors( true );
if( !config.isSetKeepSession() )
config.setKeepSession( false );
if( !config.isSetMaxResults() )
config.setMaxResults( 0 );
for( TestRunListener listener : SoapUI.getListenerRegistry().getListeners( TestRunListener.class ) )
{
addTestRunListener( listener );
}
if( !getConfig().isSetProperties() )
getConfig().addNewProperties();
setPropertiesConfig( getConfig().getProperties() );
WsrmTestRunListener wsrmListener = new WsrmTestRunListener();
addTestRunListener( wsrmListener );
addTestRunListener( new AMFTestRunListener() );
}
|
diff --git a/src/au/org/intersect/samifier/runner/ResultAnalyserRunner.java b/src/au/org/intersect/samifier/runner/ResultAnalyserRunner.java
index 38d8f5a..58686c4 100644
--- a/src/au/org/intersect/samifier/runner/ResultAnalyserRunner.java
+++ b/src/au/org/intersect/samifier/runner/ResultAnalyserRunner.java
@@ -1,97 +1,97 @@
package au.org.intersect.samifier.runner;
import au.org.intersect.samifier.domain.*;
import au.org.intersect.samifier.generator.PeptideSequenceGenerator;
import au.org.intersect.samifier.generator.PeptideSequenceGeneratorImpl;
import au.org.intersect.samifier.parser.*;
import au.org.intersect.samifier.reporter.DatabaseHelper;
import java.io.File;
import java.io.FileWriter;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public class ResultAnalyserRunner
{
private File searchResultsFile;
private File genomeFile;
private File proteinToOLNMapFile;
private File outputFile;
private File chromosomeDir;
private String sqlQuery;
private static DatabaseHelper hsqldb;
public ResultAnalyserRunner(File searchResultsFile, File genomeFile, File proteinToOLNMapFile, File outputFile, File chromosomeDir, String sqlQuery) throws Exception
{
this.searchResultsFile = searchResultsFile;
this.genomeFile = genomeFile;
this.proteinToOLNMapFile = proteinToOLNMapFile;
this.outputFile = outputFile;
this.chromosomeDir = chromosomeDir;
this.sqlQuery = sqlQuery;
}
public void initMemoryDb() throws Exception
{
hsqldb = new DatabaseHelper();
hsqldb.connect();
hsqldb.generateTables();
}
public void run() throws Exception
{
GenomeParserImpl genomeParser = new GenomeParserImpl();
Genome genome = genomeParser.parseGenomeFile(genomeFile);
ProteinToOLNParser proteinToOLNParser = new ProteinToOLNParserImpl();
ProteinToOLNMap proteinToOLNMap = proteinToOLNParser.parseMappingFile(proteinToOLNMapFile);
PeptideSearchResultsParser peptideSearchResultsParser = new PeptideSearchResultsParserImpl(proteinToOLNMap);
List<PeptideSearchResult> peptideSearchResults = peptideSearchResultsParser.parseResults(searchResultsFile);
PeptideSequenceGenerator sequenceGenerator = new PeptideSequenceGeneratorImpl(genome, proteinToOLNMap, chromosomeDir);
FileWriter output = new FileWriter(outputFile);
for (PeptideSearchResult peptideSearchResult : peptideSearchResults)
{
PeptideSequence peptideSequence = sequenceGenerator.getPeptideSequence(peptideSearchResult);
ResultsAnalyserOutputter outputter = new ResultsAnalyserOutputter(peptideSearchResult, proteinToOLNMap, genome, peptideSequence);
output.write(outputter.toString());
output.write(System.getProperty("line.separator"));
}
output.close();
}
public void runWithQuery() throws Exception
{
GenomeParserImpl genomeParser = new GenomeParserImpl();
Genome genome = genomeParser.parseGenomeFile(genomeFile);
ProteinToOLNParser proteinToOLNParser = new ProteinToOLNParserImpl();
- Map<String, String> proteinToOLNMap = proteinToOLNParser.parseMappingFile(proteinToOLNMapFile);
+ ProteinToOLNMap proteinToOLNMap = proteinToOLNParser.parseMappingFile(proteinToOLNMapFile);
PeptideSearchResultsParser peptideSearchResultsParser = new PeptideSearchResultsParserImpl(proteinToOLNMap);
List<PeptideSearchResult> peptideSearchResults = peptideSearchResultsParser.parseResults(searchResultsFile);
PeptideSequenceGenerator sequenceGenerator = new PeptideSequenceGeneratorImpl(genome, proteinToOLNMap, chromosomeDir);
FileWriter output = new FileWriter(outputFile);
for (PeptideSearchResult peptideSearchResult : peptideSearchResults)
{
PeptideSequence peptideSequence = sequenceGenerator.getPeptideSequence(peptideSearchResult);
ResultsAnalyserOutputter outputter = new ResultsAnalyserOutputter(peptideSearchResult, proteinToOLNMap, genome, peptideSequence);
hsqldb.executeQuery(outputter.toQuery());
}
Collection<String> resultSet = hsqldb.filterResult(sqlQuery.toString());
for (String set : resultSet)
{
output.write(set);
output.write(System.getProperty("line.separator"));
}
output.close();
}
}
| true | true | public void runWithQuery() throws Exception
{
GenomeParserImpl genomeParser = new GenomeParserImpl();
Genome genome = genomeParser.parseGenomeFile(genomeFile);
ProteinToOLNParser proteinToOLNParser = new ProteinToOLNParserImpl();
Map<String, String> proteinToOLNMap = proteinToOLNParser.parseMappingFile(proteinToOLNMapFile);
PeptideSearchResultsParser peptideSearchResultsParser = new PeptideSearchResultsParserImpl(proteinToOLNMap);
List<PeptideSearchResult> peptideSearchResults = peptideSearchResultsParser.parseResults(searchResultsFile);
PeptideSequenceGenerator sequenceGenerator = new PeptideSequenceGeneratorImpl(genome, proteinToOLNMap, chromosomeDir);
FileWriter output = new FileWriter(outputFile);
for (PeptideSearchResult peptideSearchResult : peptideSearchResults)
{
PeptideSequence peptideSequence = sequenceGenerator.getPeptideSequence(peptideSearchResult);
ResultsAnalyserOutputter outputter = new ResultsAnalyserOutputter(peptideSearchResult, proteinToOLNMap, genome, peptideSequence);
hsqldb.executeQuery(outputter.toQuery());
}
Collection<String> resultSet = hsqldb.filterResult(sqlQuery.toString());
for (String set : resultSet)
{
output.write(set);
output.write(System.getProperty("line.separator"));
}
output.close();
}
| public void runWithQuery() throws Exception
{
GenomeParserImpl genomeParser = new GenomeParserImpl();
Genome genome = genomeParser.parseGenomeFile(genomeFile);
ProteinToOLNParser proteinToOLNParser = new ProteinToOLNParserImpl();
ProteinToOLNMap proteinToOLNMap = proteinToOLNParser.parseMappingFile(proteinToOLNMapFile);
PeptideSearchResultsParser peptideSearchResultsParser = new PeptideSearchResultsParserImpl(proteinToOLNMap);
List<PeptideSearchResult> peptideSearchResults = peptideSearchResultsParser.parseResults(searchResultsFile);
PeptideSequenceGenerator sequenceGenerator = new PeptideSequenceGeneratorImpl(genome, proteinToOLNMap, chromosomeDir);
FileWriter output = new FileWriter(outputFile);
for (PeptideSearchResult peptideSearchResult : peptideSearchResults)
{
PeptideSequence peptideSequence = sequenceGenerator.getPeptideSequence(peptideSearchResult);
ResultsAnalyserOutputter outputter = new ResultsAnalyserOutputter(peptideSearchResult, proteinToOLNMap, genome, peptideSequence);
hsqldb.executeQuery(outputter.toQuery());
}
Collection<String> resultSet = hsqldb.filterResult(sqlQuery.toString());
for (String set : resultSet)
{
output.write(set);
output.write(System.getProperty("line.separator"));
}
output.close();
}
|
diff --git a/Sendgrid.java b/Sendgrid.java
index 8ea36a8..1a1d600 100755
--- a/Sendgrid.java
+++ b/Sendgrid.java
@@ -1,737 +1,741 @@
package googleSendgridJava;
import java.net.HttpURLConnection;
import java.util.*;
import java.io.IOException;
import java.util.Iterator;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.google.appengine.labs.repackaged.org.json.JSONArray;
public class Sendgrid {
private String from,
from_name,
reply_to,
subject,
text,
html;
protected Boolean use_headers = true;
private String serverResponse = "";
private ArrayList<String> to_list = new ArrayList<String>();
private ArrayList<String> to_name_list = new ArrayList<String>();
private ArrayList<String> bcc_list = new ArrayList<String>();
private JSONObject header_list = new JSONObject();
protected String domain = "https://sendgrid.com/",
endpoint= "api/mail.send.json",
username,
password;
public Sendgrid(String username, String password) {
this.username = username;
this.password = password;
try {
this.setCategory("google_sendgrid_java_lib");
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* getTos - Return the list of recipients
*
* @return List of recipients
*/
public ArrayList<String> getTos() {
return this.to_list;
}
/**
* setTo - Initialize a single email for the recipient 'to' field
* Destroy previous recipient 'to' data.
*
* @param email A list of email addresses
* @return The SendGrid object.
*/
public Sendgrid setTo(String email) {
this.to_list = new ArrayList<String>();
this.addTo(email);
return this;
}
/**
* addTo - Append an email address to the existing list of addresses
* Preserve previous recipient 'to' data.
*
* @param email Recipient email address
* @param name Recipient name
* @return The SendGrid object.
*/
public Sendgrid addTo(String email, String name) {
if (this._useHeaders() == true){
String toAddress = (name.length() > 0) ? name + "<" + email + ">" : email;
this.to_list.add(toAddress);
} else {
if (name.length() > 0){
this._addToName(name);
} else {
this._addToName("");
}
this.to_list.add(email);
}
return this;
}
/**
* addTo - Make the second parameter("name") of "addTo" method optional
*
* @param email A single email address
* @return The SendGrid object.
*/
public Sendgrid addTo(String email) {
return addTo(email, "");
}
/**
* getTos - Return the list of names for recipients
*
* @return List of names
*/
public ArrayList<String> getToNames() {
return this.to_name_list;
}
/**
* getFrom - Get the from email address
*
* @return The from email address
*/
public String getFrom() {
return this.from;
}
/**
* setFrom - Set the from email
*
* @param email An email address
* @return The SendGrid object.
*/
public Sendgrid setFrom(String email) {
this.from = email;
return this;
}
/**
* getFromName - Get the from name
*
* @return The from name
*/
public String getFromName() {
return this.from_name;
}
/**
* setFromName - Set the from name
*
* @param name The name
* @return The SendGrid object.
*/
public Sendgrid setFromName(String name) {
this.from_name = name;
return this;
}
/**
* getReplyTo - Get reply to address
*
* @return the reply to address
*/
public String getReplyTo() {
return this.reply_to;
}
/**
* setReplyTo - set the reply-to address
*
* @param email the email to reply to
* @return the SendGrid object.
*/
public Sendgrid setReplyTo(String email) {
this.reply_to = email;
return this;
}
/**
* getBccs - return the list of Blind Carbon Copy recipients
*
* @return ArrayList - the list of Blind Carbon Copy recipients
*/
public ArrayList<String> getBccs() {
return this.bcc_list;
}
/**
* setBcc - Initialize the list of Carbon Copy recipients
* destroy previous recipient Blind Carbon Copy data
*
* @param email an email address
* @return the SendGrid object.
* @throws JSONException
*/
public Sendgrid setBcc(String email) throws JSONException {
this.bcc_list = new ArrayList<String>();
this.bcc_list.add(email);
if (this._useHeaders() == true)
{
this.addFilterSetting("bcc", "enable", "1");
this.addFilterSetting("bcc", "email", email);
}
return this;
}
/**
* getSubject - Get the email subject
*
* @return The email subject
*/
public String getSubject() {
return this.subject;
}
/**
* setSubject - Set the email subject
*
* @param subject The email subject
* @return The SendGrid object
*/
public Sendgrid setSubject(String subject) {
this.subject = subject;
return this;
}
/**
* getText - Get the plain text part of the email
*
* @return the plain text part of the email
*/
public String getText() {
return this.text;
}
/**
* setText - Set the plain text part of the email
*
* @param text The plain text of the email
* @return The SendGrid object.
*/
public Sendgrid setText(String text) {
this.text = text;
return this;
}
/**
* getHtml - Get the HTML part of the email
*
* @return The HTML part of the email.
*/
public String getHtml() {
return this.html;
}
/**
* setHTML - Set the HTML part of the email
*
* @param html The HTML part of the email
* @return The SendGrid object.
*/
public Sendgrid setHtml(String html) {
this.html = html;
return this;
}
/**
* setCategories - Set the list of category headers
* destroys previous category header data
*
* @param category_list the list of category values
* @return the SendGrid object.
* @throws JSONException
*/
public Sendgrid setCategories(String[] category_list) throws JSONException {
JSONArray categories_json = new JSONArray(category_list);
this.header_list.put("category", categories_json);
this.addCategory("google_sendgrid_java_lib");
return this;
}
/**
* setCategory - Clears the category list and adds the given category
*
* @param category the new category to append
* @return the SendGrid object.
* @throws JSONException
*/
public Sendgrid setCategory(String category) throws JSONException {
JSONArray json_category = new JSONArray(new String[]{category});
this.header_list.put("category", json_category);
this.addCategory("google_sendgrid_java_lib");
return this;
}
/**
* addCategory - Append a category to the list of categories
*
* @param category the new category to append
* @return the SendGrid object.
* @throws JSONException
*/
public Sendgrid addCategory(String category) throws JSONException {
if (true == this.header_list.has("category")) {
((JSONArray) this.header_list.get("category")).put(category);
} else {
this.setCategory(category);
}
return this;
}
/**
* setSubstitutions - Substitute a value for list of values, where each value corresponds
* to the list emails in a one to one relationship. (IE, value[0] = email[0],
* value[1] = email[1])
*
* @param key_value_pairs key/value pairs where the value is an array of values
* @return the SendGrid object.
*/
public Sendgrid setSubstitutions(JSONObject key_value_pairs) {
try {
this.header_list.put("sub", key_value_pairs);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return this;
}
/**
* addSubstitution - Substitute a value for list of values, where each value corresponds
* to the list emails in a one to one relationship. (IE, value[0] = email[0],
* value[1] = email[1])
*
* @param from_key the value to be replaced
* @param to_values an array of values to replace the from_value
* @return the SendGrid object.
* @throws JSONException
* @throws IOException
* @throws JsonMappingException
* @throws JsonParseException
*/
public Sendgrid addSubstitution(String from_value, String[] to_values) throws JSONException {
if (false == this.header_list.has("sub")) {
this.header_list.put("sub", new JSONObject());
}
JSONArray json_values = new JSONArray(to_values);
((JSONObject) this.header_list.get("sub")).put(from_value, json_values);
return this;
}
/**
* setSection - Set a list of section values
*
* @param key_value_pairs key/value pairs
* @return the SendGrid object.
* @throws JSONException
*/
public Sendgrid setSections(JSONObject key_value_pairs) throws JSONException {
this.header_list.put("section", key_value_pairs);
return this;
}
/**
* addSection - append a section value to the list of section values
*
* @param from_value the value to be replaced
* @param to_value the value to replace
* @return the SendGrid object.
* @throws JSONException
*/
public Sendgrid addSection(String from_value, String to_value) throws JSONException {
if (false == this.header_list.has("section")) {
this.header_list.put("section", new JSONObject() );
}
((JSONObject) this.header_list.get("section")).put(from_value, to_value);
return this;
}
/**
* setUniqueArguments - Set a list of unique arguments, to be used for tracking purposes
*
* @param key_value_pairs - list of unique arguments
*/
public Sendgrid setUniqueArguments(JSONObject key_value_pairs) {
try {
this.header_list.put("unique_args", key_value_pairs);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return this;
}
/**
* addUniqueArgument - Set a key/value pair of unique arguments, to be used for tracking purposes
*
* @param key the key
* @param value the value
*/
public Sendgrid addUniqueArgument(String key, String value) {
if (false == this.header_list.has("unique_args")) {
try {
this.header_list.put("unique_args", new JSONObject());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
((JSONObject) this.header_list.get("unique_args")).put(key, value);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return this;
}
/**
* setFilterSettings - Set filter/app settings
*
* @param filter_settings - JSONObject of fiter settings
*/
public Sendgrid setFilterSettings(JSONObject filter_settings) {
try {
this.header_list.put("filters", filter_settings);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return this;
}
/**
* addFilterSetting - Append a filter setting to the list of filter settings
*
* @param filter_name filter name
* @param parameter_name parameter name
* @param parameter_value setting value
* @throws JSONException
*/
public Sendgrid addFilterSetting(String filter_name, String parameter_name, String parameter_value) throws JSONException {
if (false == this.header_list.has("filters")) {
this.header_list.put("filters", new JSONObject());
}
if (false == ((JSONObject) this.header_list.get("filters")).has(filter_name)) {
((JSONObject) this.header_list.get("filters")).put(filter_name, new JSONObject());
}
if (false == ((JSONObject) ((JSONObject) this.header_list.get("filters")).get(filter_name)).has("settings")) {
((JSONObject) ((JSONObject) this.header_list.get("filters")).get(filter_name)).put("settings", new JSONObject());
}
((JSONObject) ((JSONObject) ((JSONObject) this.header_list.get("filters")).get(filter_name)).get("settings"))
.put(parameter_name, parameter_value);
return this;
}
/**
* getHeaders - return the list of headers
*
* @return JSONObject with headers
*/
public JSONObject getHeaders() {
return this.header_list;
}
/**
* setHeaders - Sets the list headers
* destroys previous header data
*
* @param key_value_pairs the list of header data
* @return the SendGrid object.
*/
public Sendgrid setHeaders(JSONObject key_value_pairs) {
this.header_list = key_value_pairs;
return this;
}
/**
* getServerResponse - Get the server response message
*
* @return The server response message
*/
public String getServerResponse() {
return this.serverResponse;
}
/**
* _arrayToUrlPart - Converts an ArrayList to a url friendly string
*
* @param array the array to convert
* @param token the name of parameter
* @return a url part that can be concatenated to a url request
*/
protected String _arrayToUrlPart(ArrayList<String> array, String token) {
String string = "";
for(int i = 0;i < array.size();i++)
{
try {
string += "&" + token + "[]=" + URLEncoder.encode(array.get(i), "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return string;
}
/**
* _prepMessageData - Takes the mail message and returns a url friendly querystring
*
* @return the data query string to be posted
* @throws JSONException
*/
protected Map<String, String> _prepMessageData() throws JSONException {
Map<String,String> params = new HashMap<String, String>();
params.put("api_user", this.username);
params.put("api_key", this.password);
params.put("subject", this.getSubject());
if(this.getHtml() != null) {
params.put("html", this.getHtml());
}
if(this.getFromName() != null) {
params.put("fromname", this.getFromName());
}
params.put("text",this.getText());
params.put("from", this.getFrom());
if (this.getReplyTo() != null) {
params.put("replyto", this.getReplyTo());
}
if (this._useHeaders() == true) {
JSONObject headers = this.getHeaders();
params.put("to", this.getFrom());
JSONArray tos_json = new JSONArray(this.getTos());
headers.put("to", tos_json);
this.setHeaders(headers);
params.put("x-smtpapi", this.getHeaders().toString());
} else {
params.put("to", this.getTos().toString());
if (this.getToNames().size() > 0) {
params.put("toname", this.getToNames().toString());
}
}
return params;
}
/**
* Invoked when a warning is returned from the server that
* isn't critical
*/
public static interface WarningListener {
public void warning(String serverResponse, Throwable t);
}
/**
* send - Send an email
*
* @throws JSONException
*/
public void send() throws JSONException {
send(new WarningListener() {
public void warning(String w, Throwable t) {
serverResponse = w;
}
});
}
/**
* send - Send an email
*
* @param w callback that will receive warnings
* @throws JSONException
*/
public void send(WarningListener w) throws JSONException {
Map<String,String> data = new HashMap<String, String>();
data = this._prepMessageData();
StringBuffer requestParams = new StringBuffer();
Iterator<String> paramIterator = data.keySet().iterator();
while (paramIterator.hasNext()) {
final String key = paramIterator.next();
final String value = data.get(key);
if (key.equals("to") && this.getTos().size() > 0) {
if (this._useHeaders() == true){
- requestParams.append("to=" + value + "&");
+ try {
+ requestParams.append("to=" + URLEncoder.encode(value, "UTF-8") + "&");
+ } catch (UnsupportedEncodingException e) {
+ e.printStackTrace();
+ }
} else{
requestParams.append(this._arrayToUrlPart(this.getTos(), "to")+"&");
}
} else {
if (key.equals("toname") && this.getToNames().size() > 0) {
requestParams.append(this._arrayToUrlPart(this.getToNames(), "toname").substring(1)+"&");
} else {
try {
requestParams.append(URLEncoder.encode(key, "UTF-8"));
} catch (UnsupportedEncodingException e) {
w.warning("Unsupported Encoding Exception", e);
}
requestParams.append("=");
try {
requestParams.append(URLEncoder.encode(value, "UTF-8"));
} catch (UnsupportedEncodingException e) {
w.warning("Unsupported Encoding Exception", e);
}
requestParams.append("&");
}
}
}
String request = this.domain + this.endpoint;
if (this.getBccs().size() > 0){
request += "?" +this._arrayToUrlPart(this.getBccs(), "bcc").substring(1);
}
try {
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(requestParams.toString());
// Get the response
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line, response = "";
while ((line = reader.readLine()) != null) {
// Process line...
response += line;
}
reader.close();
writer.close();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// OK
serverResponse = "success";
} else {
// Server returned HTTP error code.
JSONObject apiResponse = new JSONObject(response);
JSONArray errorsObj = (JSONArray) apiResponse.get("errors");
for (int i = 0; i < errorsObj.length(); i++) {
if (i != 0) {
serverResponse += ", ";
}
serverResponse += errorsObj.get(i);
}
w.warning(serverResponse, null);
}
} catch (MalformedURLException e) {
w.warning("Malformed URL Exception", e);
} catch (IOException e) {
w.warning("IO Exception", e);
}
}
/**
* _addToName - Append an recipient name to the existing list of names
*
* @param email Recipient email address
* @param name Recipient name
* @return The SendGrid object.
*/
private Sendgrid _addToName(String name) {
this.to_name_list.add(name);
return this;
}
/**
* useHeaders - Checks to see whether or not we can or should you headers. In most cases,
* we prefer to send our recipients through the headers, but in some cases,
* we actually don't want to. However, there are certain circumstances in
* which we have to.
*/
private Boolean _useHeaders() {
if ((this._preferNotToUseHeaders() == true) && (this._isHeadersRequired() == false)) {
return false;
} else {
return true;
}
}
/**
* _preferNotToUseHeaders - There are certain cases in which headers are not a preferred choice
* to send email, as it limits some basic email functionality. Here, we
* check for any of those rules, and add them in to decide whether or
* not to use headers
*
* @return if true we don't
*/
private Boolean _preferNotToUseHeaders() {
if (this.getBccs().size() == 0)
{
return true;
}
if (this.use_headers != null && this.use_headers == false)
{
return true;
}
return false;
}
/**
* isHeaderRequired - determines whether or not we need to force recipients through the smtpapi headers
*
* @return if true headers are required
*/
private Boolean _isHeadersRequired() {
if (this.use_headers == true)
{
return true;
}
return false;
}
}
| true | true | public void send(WarningListener w) throws JSONException {
Map<String,String> data = new HashMap<String, String>();
data = this._prepMessageData();
StringBuffer requestParams = new StringBuffer();
Iterator<String> paramIterator = data.keySet().iterator();
while (paramIterator.hasNext()) {
final String key = paramIterator.next();
final String value = data.get(key);
if (key.equals("to") && this.getTos().size() > 0) {
if (this._useHeaders() == true){
requestParams.append("to=" + value + "&");
} else{
requestParams.append(this._arrayToUrlPart(this.getTos(), "to")+"&");
}
} else {
if (key.equals("toname") && this.getToNames().size() > 0) {
requestParams.append(this._arrayToUrlPart(this.getToNames(), "toname").substring(1)+"&");
} else {
try {
requestParams.append(URLEncoder.encode(key, "UTF-8"));
} catch (UnsupportedEncodingException e) {
w.warning("Unsupported Encoding Exception", e);
}
requestParams.append("=");
try {
requestParams.append(URLEncoder.encode(value, "UTF-8"));
} catch (UnsupportedEncodingException e) {
w.warning("Unsupported Encoding Exception", e);
}
requestParams.append("&");
}
}
}
String request = this.domain + this.endpoint;
if (this.getBccs().size() > 0){
request += "?" +this._arrayToUrlPart(this.getBccs(), "bcc").substring(1);
}
try {
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(requestParams.toString());
// Get the response
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line, response = "";
while ((line = reader.readLine()) != null) {
// Process line...
response += line;
}
reader.close();
writer.close();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// OK
serverResponse = "success";
} else {
// Server returned HTTP error code.
JSONObject apiResponse = new JSONObject(response);
JSONArray errorsObj = (JSONArray) apiResponse.get("errors");
for (int i = 0; i < errorsObj.length(); i++) {
if (i != 0) {
serverResponse += ", ";
}
serverResponse += errorsObj.get(i);
}
w.warning(serverResponse, null);
}
} catch (MalformedURLException e) {
w.warning("Malformed URL Exception", e);
} catch (IOException e) {
w.warning("IO Exception", e);
}
}
| public void send(WarningListener w) throws JSONException {
Map<String,String> data = new HashMap<String, String>();
data = this._prepMessageData();
StringBuffer requestParams = new StringBuffer();
Iterator<String> paramIterator = data.keySet().iterator();
while (paramIterator.hasNext()) {
final String key = paramIterator.next();
final String value = data.get(key);
if (key.equals("to") && this.getTos().size() > 0) {
if (this._useHeaders() == true){
try {
requestParams.append("to=" + URLEncoder.encode(value, "UTF-8") + "&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else{
requestParams.append(this._arrayToUrlPart(this.getTos(), "to")+"&");
}
} else {
if (key.equals("toname") && this.getToNames().size() > 0) {
requestParams.append(this._arrayToUrlPart(this.getToNames(), "toname").substring(1)+"&");
} else {
try {
requestParams.append(URLEncoder.encode(key, "UTF-8"));
} catch (UnsupportedEncodingException e) {
w.warning("Unsupported Encoding Exception", e);
}
requestParams.append("=");
try {
requestParams.append(URLEncoder.encode(value, "UTF-8"));
} catch (UnsupportedEncodingException e) {
w.warning("Unsupported Encoding Exception", e);
}
requestParams.append("&");
}
}
}
String request = this.domain + this.endpoint;
if (this.getBccs().size() > 0){
request += "?" +this._arrayToUrlPart(this.getBccs(), "bcc").substring(1);
}
try {
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(requestParams.toString());
// Get the response
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line, response = "";
while ((line = reader.readLine()) != null) {
// Process line...
response += line;
}
reader.close();
writer.close();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// OK
serverResponse = "success";
} else {
// Server returned HTTP error code.
JSONObject apiResponse = new JSONObject(response);
JSONArray errorsObj = (JSONArray) apiResponse.get("errors");
for (int i = 0; i < errorsObj.length(); i++) {
if (i != 0) {
serverResponse += ", ";
}
serverResponse += errorsObj.get(i);
}
w.warning(serverResponse, null);
}
} catch (MalformedURLException e) {
w.warning("Malformed URL Exception", e);
} catch (IOException e) {
w.warning("IO Exception", e);
}
}
|
diff --git a/ghana-national-test/src/main/java/org/motechproject/ghana/national/web/service/GNScheduleService.java b/ghana-national-test/src/main/java/org/motechproject/ghana/national/web/service/GNScheduleService.java
index fb1e3ef9..015f0179 100644
--- a/ghana-national-test/src/main/java/org/motechproject/ghana/national/web/service/GNScheduleService.java
+++ b/ghana-national-test/src/main/java/org/motechproject/ghana/national/web/service/GNScheduleService.java
@@ -1,160 +1,160 @@
package org.motechproject.ghana.national.web.service;
import org.motechproject.MotechException;
import org.motechproject.ghana.national.configuration.ScheduleNames;
import org.motechproject.ghana.national.domain.Patient;
import org.motechproject.ghana.national.service.PatientService;
import org.motechproject.ghana.national.web.domain.Alert;
import org.motechproject.ghana.national.web.domain.JobDetail;
import org.motechproject.openmrs.advice.ApiSession;
import org.motechproject.openmrs.advice.LoginAsAdmin;
import org.motechproject.scheduler.MotechSchedulerServiceImpl;
import org.motechproject.scheduletracking.api.domain.Enrollment;
import org.motechproject.scheduletracking.api.domain.EnrollmentStatus;
import org.motechproject.scheduletracking.api.domain.WindowName;
import org.motechproject.scheduletracking.api.events.constants.EventDataKeys;
import org.motechproject.scheduletracking.api.events.constants.EventSubjects;
import org.motechproject.scheduletracking.api.repository.AllEnrollments;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;
import java.lang.reflect.Field;
import java.util.*;
import java.util.Calendar;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.String.format;
@Service
public class GNScheduleService {
@Autowired
private AllEnrollments allEnrollments;
@Autowired
private SchedulerFactoryBean schedulerFactoryBean;
@Autowired
private PatientService patientService;
private Pattern ALERT_ORDER_INDEX_REGEX = Pattern.compile("^.*\\.(.*?)-repeat$");
public void filterActiveSchedulesWithin(Map<String, Map<String, List<Alert>>> patientSchedules, Date startDate, Date endDate) {
for (Map<String, List<Alert>> schedules : patientSchedules.values()) {
for (Map.Entry<String, List<Alert>> scheduleEntry : schedules.entrySet()) {
for (Alert alert : scheduleEntry.getValue()) {
if (alert.getAlertDate().after(endDate) || alert.getAlertDate().before(startDate)) {
scheduleEntry.getValue().remove(alert);
}
}
if (scheduleEntry.getValue().size() == 0) {
schedules.remove(scheduleEntry.getKey());
}
}
}
}
@LoginAsAdmin
@ApiSession
public Map<String, Map<String, List<Alert>>> getAllActiveSchedules() {
final List<Enrollment> enrollments = allEnrollments.getAll();
Map<String, Map<String, List<Alert>>> schedules = new HashMap<String, Map<String, List<Alert>>>();
for (Enrollment enrollment : enrollments) {
if (EnrollmentStatus.ACTIVE.equals(enrollment.getStatus())) {
final Map<String, List<Alert>> alerts = getAllSchedulesByMrsPatientId(enrollment.getExternalId());
schedules.put(patientService.patientByOpenmrsId(enrollment.getExternalId()).getMotechId(), alerts);
}
}
return schedules;
}
@LoginAsAdmin
@ApiSession
public Map<String, List<Alert>> getAllSchedulesByMotechId(final String patientId) {
Patient patientByMotechId = patientService.getPatientByMotechId(patientId);
return getAllSchedulesByMrsId(patientByMotechId.getMRSPatientId());
}
public Map<String, List<Alert>> getAllSchedulesByMrsId(String mrsPatientId) {
return getAllSchedulesByMrsPatientId(mrsPatientId);
}
private Map<String, List<Alert>> getAllSchedulesByMrsPatientId(String patientId) {
Map<String, List<Alert>> schedules = new ConcurrentHashMap<String, List<Alert>>();
try {
for (Field field : ScheduleNames.class.getFields()) {
final String scheduleName = (String) field.get(field);
Enrollment activeEnrollment = allEnrollments.getActiveEnrollment(patientId, scheduleName);
if (activeEnrollment != null) {
schedules.put(scheduleName + "(" + activeEnrollment.getCurrentMilestoneName() + ")", captureAlertsForNextMilestone(activeEnrollment.getId()));
}
}
} catch (Exception e) {
throw new MotechException("Encountered exception, ", e);
}
return schedules;
}
private List<Alert> captureAlertsForNextMilestone(String enrollmentId) throws SchedulerException {
final Scheduler scheduler = schedulerFactoryBean.getScheduler();
final String jobGroupName = MotechSchedulerServiceImpl.JOB_GROUP_NAME;
String[] jobNames = scheduler.getJobNames(jobGroupName);
List<org.motechproject.ghana.national.web.domain.JobDetail> alertTriggers = new ArrayList<JobDetail>();
for (String jobName : jobNames) {
if (jobName.contains(format("%s-%s", EventSubjects.MILESTONE_ALERT, enrollmentId))) {
Trigger[] triggersOfJob = scheduler.getTriggersOfJob(jobName, jobGroupName);
alertTriggers.add(new org.motechproject.ghana.national.web.domain.JobDetail((SimpleTrigger) triggersOfJob[0], scheduler.getJobDetail(jobName, jobGroupName)));
}
}
return createActualTestAlertTimes(alertTriggers);
}
private List<Alert> createActualTestAlertTimes(List<org.motechproject.ghana.national.web.domain.JobDetail> alertsJobDetails) {
sortBasedOnIndexInAlertName(alertsJobDetails);
List<Alert> actualAlertTimes = new CopyOnWriteArrayList<Alert>();
for (org.motechproject.ghana.national.web.domain.JobDetail jobDetail : alertsJobDetails) {
SimpleTrigger alert = jobDetail.trigger();
Date nextFireTime = alert.getNextFireTime();
JobDataMap dataMap = jobDetail.getJobDetail().getJobDataMap();
actualAlertTimes.add(new Alert(window(dataMap), nextFireTime));
- for (int i = 1; i <= alert.getRepeatCount(); i++) {
+ for (int i = 1; i <= alert.getRepeatCount() - alert.getTimesTriggered(); i++) {
Calendar calendar = Calendar.getInstance();
calendar.setTime((Date) nextFireTime.clone());
calendar.add(Calendar.DAY_OF_MONTH, toDays(i * alert.getRepeatInterval()));
actualAlertTimes.add(new Alert(window(dataMap), calendar.getTime()));
}
}
return actualAlertTimes;
}
private void sortBasedOnIndexInAlertName(List<org.motechproject.ghana.national.web.domain.JobDetail> alertJobDetails) {
Collections.sort(alertJobDetails, new Comparator<org.motechproject.ghana.national.web.domain.JobDetail>() {
@Override
public int compare(org.motechproject.ghana.national.web.domain.JobDetail jobDetail1, org.motechproject.ghana.national.web.domain.JobDetail jobDetail2) {
return extractIndexFromAlertName(jobDetail1.trigger().getName()).compareTo(extractIndexFromAlertName(jobDetail2.trigger().getName()));
}
});
}
private Integer extractIndexFromAlertName(String name) {
Matcher matcher = ALERT_ORDER_INDEX_REGEX.matcher(name);
return matcher.find() ? Integer.parseInt(matcher.group(1)) : null;
}
private int toDays(long milliseconds) {
return (int) (milliseconds / 1000 / 60 / 60 / 24);
}
private WindowName window(JobDataMap dataMap) {
return WindowName.valueOf((String) dataMap.get(EventDataKeys.WINDOW_NAME));
}
}
| true | true | private List<Alert> createActualTestAlertTimes(List<org.motechproject.ghana.national.web.domain.JobDetail> alertsJobDetails) {
sortBasedOnIndexInAlertName(alertsJobDetails);
List<Alert> actualAlertTimes = new CopyOnWriteArrayList<Alert>();
for (org.motechproject.ghana.national.web.domain.JobDetail jobDetail : alertsJobDetails) {
SimpleTrigger alert = jobDetail.trigger();
Date nextFireTime = alert.getNextFireTime();
JobDataMap dataMap = jobDetail.getJobDetail().getJobDataMap();
actualAlertTimes.add(new Alert(window(dataMap), nextFireTime));
for (int i = 1; i <= alert.getRepeatCount(); i++) {
Calendar calendar = Calendar.getInstance();
calendar.setTime((Date) nextFireTime.clone());
calendar.add(Calendar.DAY_OF_MONTH, toDays(i * alert.getRepeatInterval()));
actualAlertTimes.add(new Alert(window(dataMap), calendar.getTime()));
}
}
return actualAlertTimes;
}
| private List<Alert> createActualTestAlertTimes(List<org.motechproject.ghana.national.web.domain.JobDetail> alertsJobDetails) {
sortBasedOnIndexInAlertName(alertsJobDetails);
List<Alert> actualAlertTimes = new CopyOnWriteArrayList<Alert>();
for (org.motechproject.ghana.national.web.domain.JobDetail jobDetail : alertsJobDetails) {
SimpleTrigger alert = jobDetail.trigger();
Date nextFireTime = alert.getNextFireTime();
JobDataMap dataMap = jobDetail.getJobDetail().getJobDataMap();
actualAlertTimes.add(new Alert(window(dataMap), nextFireTime));
for (int i = 1; i <= alert.getRepeatCount() - alert.getTimesTriggered(); i++) {
Calendar calendar = Calendar.getInstance();
calendar.setTime((Date) nextFireTime.clone());
calendar.add(Calendar.DAY_OF_MONTH, toDays(i * alert.getRepeatInterval()));
actualAlertTimes.add(new Alert(window(dataMap), calendar.getTime()));
}
}
return actualAlertTimes;
}
|
diff --git a/src/main/java/org/helix/mobile/component/tab/TabRenderer.java b/src/main/java/org/helix/mobile/component/tab/TabRenderer.java
index 8d1eb6da..ddaac849 100644
--- a/src/main/java/org/helix/mobile/component/tab/TabRenderer.java
+++ b/src/main/java/org/helix/mobile/component/tab/TabRenderer.java
@@ -1,52 +1,54 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.helix.mobile.component.tab;
import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import org.primefaces.renderkit.CoreRenderer;
/**
* This rendering is invoked by each page, which checks to see if it in a tab bar and,
* if so, renders the tab bar.
*
* @author shallem
*/
public class TabRenderer extends CoreRenderer {
@Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
Tab tab = (Tab)component;
Boolean isActive = (Boolean)tab.getAttributes().get("active");
ResponseWriter writer = context.getResponseWriter();
writer.startElement("li", component);
writer.startElement("a", component);
writer.writeAttribute("href", "#" + tab.getPage(), null);
writer.writeAttribute("style", "height: 48px", null);
//writer.writeAttribute("data-icon", "custom", null);
+ String styleClass = "";
if (!tab.isCustomIcon()) {
writer.writeAttribute("data-icon", tab.getIcon(), null);
+ } else {
+ styleClass = "ui-icon-" + tab.getIcon();
}
- String styleClass = "ui-icon-" + tab.getIcon();
if (isActive) {
writer.writeAttribute("class", styleClass + " ui-btn-active", null);
} else {
writer.writeAttribute("class", styleClass, null);
}
if (tab.getName() != null) {
//writer.write(tab.getName());
}
}
@Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
ResponseWriter writer = context.getResponseWriter();
writer.endElement("a");
writer.endElement("li");
}
}
| false | true | public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
Tab tab = (Tab)component;
Boolean isActive = (Boolean)tab.getAttributes().get("active");
ResponseWriter writer = context.getResponseWriter();
writer.startElement("li", component);
writer.startElement("a", component);
writer.writeAttribute("href", "#" + tab.getPage(), null);
writer.writeAttribute("style", "height: 48px", null);
//writer.writeAttribute("data-icon", "custom", null);
if (!tab.isCustomIcon()) {
writer.writeAttribute("data-icon", tab.getIcon(), null);
}
String styleClass = "ui-icon-" + tab.getIcon();
if (isActive) {
writer.writeAttribute("class", styleClass + " ui-btn-active", null);
} else {
writer.writeAttribute("class", styleClass, null);
}
if (tab.getName() != null) {
//writer.write(tab.getName());
}
}
| public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
Tab tab = (Tab)component;
Boolean isActive = (Boolean)tab.getAttributes().get("active");
ResponseWriter writer = context.getResponseWriter();
writer.startElement("li", component);
writer.startElement("a", component);
writer.writeAttribute("href", "#" + tab.getPage(), null);
writer.writeAttribute("style", "height: 48px", null);
//writer.writeAttribute("data-icon", "custom", null);
String styleClass = "";
if (!tab.isCustomIcon()) {
writer.writeAttribute("data-icon", tab.getIcon(), null);
} else {
styleClass = "ui-icon-" + tab.getIcon();
}
if (isActive) {
writer.writeAttribute("class", styleClass + " ui-btn-active", null);
} else {
writer.writeAttribute("class", styleClass, null);
}
if (tab.getName() != null) {
//writer.write(tab.getName());
}
}
|
diff --git a/src/plugins/Library/Main.java b/src/plugins/Library/Main.java
index 6876017..3fccc97 100644
--- a/src/plugins/Library/Main.java
+++ b/src/plugins/Library/Main.java
@@ -1,1057 +1,1057 @@
/* This code is part of Freenet. It is distributed under the GNU General
* Public License, version 2 (or at your option any later version). See
* http://www.gnu.org/ for further details of the GPL. */
package plugins.Library;
import freenet.node.RequestStarter;
import freenet.pluginmanager.PluginReplySender;
import freenet.support.MutableBoolean;
import freenet.support.SimpleFieldSet;
import freenet.support.api.Bucket;
import freenet.support.io.BucketTools;
import freenet.support.io.Closer;
import freenet.support.io.FileBucket;
import freenet.support.io.FileUtil;
import freenet.support.io.LineReadingInputStream;
import freenet.support.io.NativeThread;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.logging.Level;
import plugins.Library.client.FreenetArchiver;
import plugins.Library.index.ProtoIndex;
import plugins.Library.index.ProtoIndexComponentSerialiser;
import plugins.Library.index.ProtoIndexSerialiser;
import plugins.Library.index.TermEntry;
import plugins.Library.index.TermPageEntry;
import plugins.Library.search.Search;
import plugins.Library.ui.WebInterface;
import plugins.Library.util.SkeletonBTreeMap;
import plugins.Library.util.SkeletonBTreeSet;
import plugins.Library.util.TaskAbortExceptionConvertor;
import plugins.Library.util.concurrent.Executors;
import plugins.Library.util.exec.SimpleProgress;
import plugins.Library.util.exec.TaskAbortException;
import plugins.Library.util.func.Closure;
import freenet.pluginmanager.FredPlugin;
import freenet.pluginmanager.FredPluginL10n;
import freenet.pluginmanager.FredPluginRealVersioned;
import freenet.pluginmanager.FredPluginThreadless;
import freenet.pluginmanager.FredPluginVersioned;
import freenet.pluginmanager.PluginRespirator;
import freenet.support.Executor;
import freenet.client.InsertException;
import freenet.keys.FreenetURI;
import freenet.keys.InsertableClientSSK;
import freenet.l10n.BaseL10n.LANGUAGE;
import freenet.pluginmanager.FredPluginFCP;
import freenet.support.Logger;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.security.MessageDigest;
import plugins.Library.index.TermEntryReaderWriter;
import plugins.Library.index.xml.LibrarianHandler;
import plugins.Library.io.serial.LiveArchiver;
import plugins.Library.io.serial.Serialiser.PullTask;
import plugins.Library.io.serial.Serialiser.PushTask;
/**
* Library class is the api for others to use search facilities, it is used by the interfaces
* @author MikeB
*/
public class Main implements FredPlugin, FredPluginVersioned, freenet.pluginmanager.FredPluginHTTP, // TODO remove this later
FredPluginRealVersioned, FredPluginThreadless, FredPluginL10n, FredPluginFCP {
private static PluginRespirator pr;
private Library library;
private WebInterface webinterface;
static volatile boolean logMINOR;
static volatile boolean logDEBUG;
static {
Logger.registerClass(Main.class);
}
public static PluginRespirator getPluginRespirator() {
return pr;
}
// FredPluginL10n
public void setLanguage(freenet.l10n.BaseL10n.LANGUAGE lang) {
// TODO implement
}
// FredPluginVersioned
public String getVersion() {
return library.getVersion() + " " + Version.vcsRevision();
}
// FredPluginRealVersioned
public long getRealVersion() {
return library.getVersion();
}
// FredPluginHTTP
// TODO remove this later
public String handleHTTPGet(freenet.support.api.HTTPRequest request) {
Throwable th;
try {
Class<?> tester = Class.forName("plugins.Library.Tester");
java.lang.reflect.Method method = tester.getMethod("runTest", Library.class, String.class);
try {
return (String)method.invoke(null, library, request.getParam("plugins.Library.Tester"));
} catch (java.lang.reflect.InvocationTargetException e) {
throw e.getCause();
}
} catch (ClassNotFoundException e) {
return "<p>To use Library, go to <b>Browsing -> Search Freenet</b> in the main menu in FProxy.</p><p>This page is only where the test suite would be, if it had been compiled in (give -Dtester= to ant).</p>";
} catch (Throwable t) {
th = t;
}
java.io.ByteArrayOutputStream bytes = new java.io.ByteArrayOutputStream();
th.printStackTrace(new java.io.PrintStream(bytes));
return "<pre>" + bytes + "</pre>";
}
// TODO remove this later
public String handleHTTPPost(freenet.support.api.HTTPRequest request) { return null; }
// FredPlugin
public void runPlugin(PluginRespirator pr) {
Main.pr = pr;
Executor exec = pr.getNode().executor;
library = Library.init(pr);
Search.setup(library, exec);
Executors.setDefaultExecutor(exec);
webinterface = new WebInterface(library, pr);
webinterface.load();
final String[] oldToMerge;
synchronized(freenetMergeSync) {
oldToMerge = new File(".").list(new FilenameFilter() {
public boolean accept(File arg0, String arg1) {
if(!(arg1.toLowerCase().startsWith(BASE_FILENAME_PUSH_DATA))) return false;
File f = new File(arg0, arg1);
if(!f.isFile()) return false;
if(f.length() == 0) { f.delete(); return false; }
String s = f.getName().substring(BASE_FILENAME_PUSH_DATA.length());
pushNumber = Math.max(pushNumber, Long.parseLong(s)+1);
return true;
}
});
}
final String[] dirsToMerge;
synchronized(freenetMergeSync) {
dirsToMerge = new File(".").list(new FilenameFilter() {
public boolean accept(File arg0, String arg1) {
if(!(arg1.toLowerCase().startsWith(DISK_DIR_PREFIX))) return false;
File f = new File(arg0, arg1);
String s = f.getName().substring(DISK_DIR_PREFIX.length());
dirNumber = Math.max(dirNumber, Integer.parseInt(s)+1);
return true;
}
});
}
if(oldToMerge != null && oldToMerge.length > 0) {
System.out.println("Found "+oldToMerge.length+" buckets of old index data to merge...");
Runnable r = new Runnable() {
public void run() {
synchronized(freenetMergeSync) {
for(String filename : oldToMerge) {
File f = new File(filename);
toMergeToDisk.add(new FileBucket(f, true, false, false, false, true));
}
}
wrapMergeToDisk();
}
};
pr.getNode().executor.execute(r, "Library: handle index data from previous run");
}
if(dirsToMerge != null && dirsToMerge.length > 0) {
System.out.println("Found "+dirsToMerge.length+" disk trees of old index data to merge...");
Runnable r = new Runnable() {
public void run() {
synchronized(freenetMergeSync) {
while(freenetMergeRunning) {
if(pushBroken) return;
System.err.println("Need to merge to Freenet, but last merge not finished yet. Waiting...");
try {
freenetMergeSync.wait();
} catch (InterruptedException e) {
// Ignore
}
}
if(pushBroken) return;
freenetMergeRunning = true;
}
try {
for(String filename : dirsToMerge) {
File f = new File(filename);
mergeToFreenet(f);
}
} finally {
synchronized(freenetMergeSync) {
freenetMergeRunning = false;
if(!pushBroken)
lastMergedToFreenet = System.currentTimeMillis();
freenetMergeSync.notifyAll();
}
}
}
};
pr.getNode().executor.execute(r, "Library: handle trees from previous run");
}
}
public void terminate() {
webinterface.unload();
}
public String getString(String key) {
return key;
}
private static String convertToHex(byte[] data) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while (two_halfs++ < 1);
}
return buf.toString();
}
//this function will return the String representation of the MD5 hash for the input string
public static String MD5(String text) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] b = text.getBytes("UTF-8");
md.update(b, 0, b.length);
byte[] md5hash = md.digest();
return convertToHex(md5hash);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private Object freenetMergeSync = new Object();
private boolean freenetMergeRunning = false;
private boolean diskMergeRunning = false;
private final ArrayList<Bucket> toMergeToDisk = new ArrayList<Bucket>();
static final int MAX_HANDLING_COUNT = 5;
// When pushing is broken, allow max handling to reach this level before stalling forever to prevent running out of disk space.
private int PUSH_BROKEN_MAX_HANDLING_COUNT = 10;
// Don't use too much disk space, take into account fact that XMLSpider slows down over time.
private boolean pushBroken;
/** The temporary on-disk index. We merge stuff into this until it exceeds a threshold size, then
* we create a new diskIdx and merge the old one into the idxFreenet. */
ProtoIndex idxDisk;
/** idxDisk gets merged into idxFreenet this long after the last merge completed. */
static final long MAX_TIME = 24*60*60*1000L;
/** idxDisk gets merged into idxFreenet after this many incoming updates from Spider. */
static final int MAX_UPDATES = 32;
/** idxDisk gets merged into idxFreenet after it has grown to this many terms.
* Note that the entire main tree of terms (not the sub-trees with the positions and urls in) must
* fit into memory during the merge process. */
static final int MAX_TERMS = 100*1000;
/** Maximum size of a single entry, in TermPageEntry count, on disk. If we exceed this we force an
* insert-to-freenet and move on to a new disk index. The problem is that the merge to Freenet has
* to keep the whole of each entry in RAM. This is only true for the data being merged in - the
* on-disk index - and not for the data on Freenet, which is pulled on demand. SCALABILITY */
static final int MAX_DISK_ENTRY_SIZE = 10000;
/** Like pushNumber, the number of the current disk dir, used to create idxDiskDir. */
private int dirNumber;
static final String DISK_DIR_PREFIX = "library-temp-index-";
/** Directory the current idxDisk is saved in. */
File idxDiskDir;
private int mergedToDisk;
ProtoIndexSerialiser srl = null;
FreenetURI lastUploadURI = null;
String lastDiskIndexName;
/** The uploaded index on Freenet. This never changes, it just gets updated. */
ProtoIndex idxFreenet;
FreenetURI privURI;
FreenetURI pubURI;
long edition;
long pushNumber;
static final String LAST_URL_FILENAME = "library.index.lastpushed.chk";
static final String PRIV_URI_FILENAME = "library.index.privkey";
static final String PUB_URI_FILENAME = "library.index.pubkey";
static final String EDITION_FILENAME = "library.index.next-edition";
static final String LAST_DISK_FILENAME = "library.index.lastpushed.disk";
static final String BASE_FILENAME_PUSH_DATA = "library.index.data.";
public void handle(PluginReplySender replysender, SimpleFieldSet params, final Bucket data, int accesstype) {
if("pushBuffer".equals(params.get("command"))){
if(data.size() == 0) {
Logger.error(this, "Bucket of data ("+data+") to push is empty", new Exception("error"));
System.err.println("Bucket of data ("+data+")to push from XMLSpider is empty");
data.free();
return;
}
// Process data off-thread, but only one load at a time.
// Hence it won't stall XMLSpider unless we get behind.
long pn;
synchronized(this) {
pn = pushNumber++;
}
final File pushFile = new File(BASE_FILENAME_PUSH_DATA+pn);
Bucket output = new FileBucket(pushFile, false, false, false, false, true);
try {
BucketTools.copy(data, output);
data.free();
System.out.println("Written data to "+pushFile);
} catch (IOException e1) {
System.err.println("Unable to back up push data #"+pn+" : "+e1);
e1.printStackTrace();
Logger.error(this, "Unable to back up push data #"+pn, e1);
output = data;
}
synchronized(freenetMergeSync) {
boolean waited = false;
while(toMergeToDisk.size() > MAX_HANDLING_COUNT && !pushBroken) {
Logger.error(this, "XMLSpider feeding us data too fast, waiting for background process to finish. Ahead of us in the queue: "+toMergeToDisk.size());
try {
waited = true;
freenetMergeSync.wait();
} catch (InterruptedException e) {
// Ignore
}
}
toMergeToDisk.add(output);
if(pushBroken) {
if(toMergeToDisk.size() < PUSH_BROKEN_MAX_HANDLING_COUNT)
// We have written the data, it will be recovered after restart.
Logger.error(this, "Pushing is broken, failing");
else {
// Wait forever to prevent running out of disk space.
// XMLSpider is single threaded.
// FIXME: Use an error return or a throwable to shut down XMLSpider.
while(true) {
try {
freenetMergeSync.wait();
} catch (InterruptedException e) {
// Ignore
}
}
}
return;
}
if(waited)
Logger.error(this, "Waited for previous handler to go away, moving on...");
//if(freenetMergeRunning) return; // Already running, no need to restart it.
if(diskMergeRunning) return; // Already running, no need to restart it.
}
Runnable r = new Runnable() {
public void run() {
// wrapMergeToFreenet();
wrapMergeToDisk();
}
};
pr.getNode().executor.execute(r, "Library: Handle data from XMLSpider");
} else {
Logger.error(this, "Unknown command : \""+params.get("command"));
}
}
/** Merge from the Bucket chain to the on-disk idxDisk. */
protected void wrapMergeToDisk() {
boolean first = true;
while(true) {
final Bucket data;
synchronized(freenetMergeSync) {
if(pushBroken) {
Logger.error(this, "Pushing broken");
return;
}
if(first && diskMergeRunning) {
Logger.error(this, "Already running a handler!");
return;
} else if((!first) && (!diskMergeRunning)) {
Logger.error(this, "Already running yet runningHandler is false?!");
return;
}
first = false;
if(toMergeToDisk.size() == 0) {
if(logMINOR) Logger.minor(this, "Nothing to handle");
diskMergeRunning = false;
freenetMergeSync.notifyAll();
return;
}
data = toMergeToDisk.remove(0);
freenetMergeSync.notifyAll();
diskMergeRunning = true;
}
try {
mergeToDisk(data);
} catch (Throwable t) {
// Failed.
synchronized(freenetMergeSync) {
diskMergeRunning = false;
pushBroken = true;
freenetMergeSync.notifyAll();
}
if(t instanceof RuntimeException)
throw (RuntimeException)t;
if(t instanceof Error)
throw (Error)t;
}
}
}
// This is a member variable because it is huge, and having huge stuff in local variables seems to upset the default garbage collector.
// It doesn't need to be synchronized because it's always used from innerInnerHandle, which never runs in parallel.
private Map<String, SortedSet<TermEntry>> newtrees;
// Ditto
private SortedSet<String> terms;
ProtoIndexSerialiser srlDisk = null;
private ProtoIndexComponentSerialiser leafsrlDisk;
private long lastMergedToFreenet = -1;
private void mergeToDisk(Bucket data) {
boolean newIndex = false;
if(idxDiskDir == null) {
newIndex = true;
dirNumber++;
idxDiskDir = new File(DISK_DIR_PREFIX + Integer.toString(dirNumber));
System.out.println("Created new disk dir for merging: "+idxDiskDir);
if(!(idxDiskDir.mkdir() || idxDiskDir.isDirectory())) {
Logger.error(this, "Unable to create new disk dir: "+idxDiskDir);
synchronized(this) {
pushBroken = true;
return;
}
}
}
if(srlDisk == null) {
srlDisk = ProtoIndexSerialiser.forIndex(idxDiskDir);
LiveArchiver<Map<String,Object>,SimpleProgress> archiver =
(LiveArchiver<Map<String,Object>,SimpleProgress>)(srlDisk.getChildSerialiser());
leafsrlDisk = ProtoIndexComponentSerialiser.get(ProtoIndexComponentSerialiser.FMT_FILE_LOCAL, archiver);
if(lastDiskIndexName == null) {
try {
- idxDisk = new ProtoIndex(new FreenetURI("CHK@yeah"), "test", null, null, 0L);
+ idxDisk = new ProtoIndex(new FreenetURI("CHK@"), "test", null, null, 0L);
} catch (java.net.MalformedURLException e) {
throw new AssertionError(e);
}
// FIXME more hacks: It's essential that we use the same FileArchiver instance here.
leafsrlDisk.setSerialiserFor(idxDisk);
} else {
try {
PullTask<ProtoIndex> pull = new PullTask<ProtoIndex>(lastDiskIndexName);
System.out.println("Pulling previous index "+lastDiskIndexName+" from disk so can update it.");
srlDisk.pull(pull);
System.out.println("Pulled previous index "+lastDiskIndexName+" from disk - updating...");
idxDisk = pull.data;
if(idxDisk.getSerialiser().getLeafSerialiser() != archiver)
throw new IllegalStateException("Different serialiser: "+idxFreenet.getSerialiser()+" should be "+leafsrl);
} catch (TaskAbortException e) {
Logger.error(this, "Failed to download previous index for spider update: "+e, e);
System.err.println("Failed to download previous index for spider update: "+e);
e.printStackTrace();
synchronized(freenetMergeSync) {
pushBroken = true;
}
return;
}
}
}
// Read data into newtrees and trees.
FileWriter w = null;
newtrees = new HashMap<String, SortedSet<TermEntry>>();
terms = new TreeSet<String>();
int entriesAdded = 0;
try {
Logger.normal(this, "Bucket of buffer received, "+data.size()+" bytes");
InputStream is = data.getInputStream();
SimpleFieldSet fs = new SimpleFieldSet(new LineReadingInputStream(is), 1024, 512, true, true, true);
idxDisk.setName(fs.get("index.title"));
idxDisk.setOwnerEmail(fs.get("index.owner.email"));
idxDisk.setOwner(fs.get("index.owner.name"));
idxDisk.setTotalPages(fs.getLong("totalPages", -1));
try{
while(true){ // Keep going til an EOFExcepiton is thrown
TermEntry readObject = TermEntryReaderWriter.getInstance().readObject(is);
SortedSet<TermEntry> set = newtrees.get(readObject.subj);
if(set == null)
newtrees.put(readObject.subj, set = new TreeSet<TermEntry>());
set.add(readObject);
terms.add(readObject.subj);
entriesAdded++;
}
}catch(EOFException e){
// EOF, do nothing
}
} catch (IOException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
if(terms.size() == 0) {
System.out.println("Nothing to merge");
synchronized(this) {
newtrees = null;
terms = null;
}
return;
}
// Do the upload
try {
final MutableBoolean maxDiskEntrySizeExceeded = new MutableBoolean();
maxDiskEntrySizeExceeded.value = false;
long mergeStartTime = System.currentTimeMillis();
if(newIndex) {
// created a new index, fill it with data.
// DON'T MERGE, merge with a lot of data will deadlock.
// FIXME throw in update() if it will deadlock.
for(String key : terms) {
SkeletonBTreeSet<TermEntry> tree = makeEntryTree(leafsrlDisk);
SortedSet<TermEntry> toMerge = newtrees.get(key);
tree.addAll(toMerge);
if(toMerge.size() > MAX_DISK_ENTRY_SIZE)
maxDiskEntrySizeExceeded.value = true;
toMerge = null;
tree.deflate();
assert(tree.isBare());
idxDisk.ttab.put(key, tree);
}
idxDisk.ttab.deflate();
} else {
// async merge
Closure<Map.Entry<String, SkeletonBTreeSet<TermEntry>>, TaskAbortException> clo = new
Closure<Map.Entry<String, SkeletonBTreeSet<TermEntry>>, TaskAbortException>() {
/*@Override**/ public void invoke(Map.Entry<String, SkeletonBTreeSet<TermEntry>> entry) throws TaskAbortException {
String key = entry.getKey();
SkeletonBTreeSet<TermEntry> tree = entry.getValue();
if(logMINOR) Logger.minor(this, "Processing: "+key+" : "+tree);
if(tree != null)
System.out.println("Merging data (on disk) in term "+key);
else
System.out.println("Adding new term to disk index: "+key);
//System.out.println("handling " + key + ((tree == null)? " (new)":" (old)"));
if (tree == null) {
entry.setValue(tree = makeEntryTree(leafsrlDisk));
}
assert(tree.isBare());
SortedSet<TermEntry> toMerge = newtrees.get(key);
tree.update(toMerge, null);
if(toMerge.size() > MAX_DISK_ENTRY_SIZE)
synchronized(maxDiskEntrySizeExceeded) {
maxDiskEntrySizeExceeded.value = true;
}
toMerge = null;
newtrees.remove(key);
assert(tree.isBare());
if(logMINOR) Logger.minor(this, "Updated: "+key+" : "+tree);
//System.out.println("handled " + key);
}
};
assert(idxDisk.ttab.isBare());
System.out.println("Merging "+terms.size()+" terms, tree.size = "+idxDisk.ttab.size()+" from "+data+"...");
idxDisk.ttab.update(terms, null, clo, new TaskAbortExceptionConvertor());
}
// Synchronize anyway so garbage collector knows about it.
synchronized(this) {
newtrees = null;
terms = null;
}
assert(idxDisk.ttab.isBare());
PushTask<ProtoIndex> task4 = new PushTask<ProtoIndex>(idxDisk);
srlDisk.push(task4);
long mergeEndTime = System.currentTimeMillis();
System.out.print(entriesAdded + " entries merged to disk in " + (mergeEndTime-mergeStartTime) + " ms, root at " + task4.meta + ", ");
// FileArchiver produces a String, which is a filename not including the prefix or suffix.
String uri = (String)task4.meta;
lastDiskIndexName = uri;
System.out.println("Pushed new index to file "+uri);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(LAST_DISK_FILENAME);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
osw.write(uri.toString());
osw.close();
fos = null;
data.free();
} catch (IOException e) {
Logger.error(this, "Failed to write filename of uploaded index: "+uri, e);
System.out.println("Failed to write filename of uploaded index: "+uri+" : "+e);
} finally {
Closer.close(fos);
}
try {
fos = new FileOutputStream(new File(idxDiskDir, LAST_DISK_FILENAME));
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
osw.write(uri.toString());
osw.close();
fos = null;
} catch (IOException e) {
Logger.error(this, "Failed to write filename of uploaded index: "+uri, e);
System.out.println("Failed to write filename of uploaded index: "+uri+" : "+e);
} finally {
Closer.close(fos);
}
// Maybe chain to mergeToFreenet ???
boolean termTooBig = false;
synchronized(maxDiskEntrySizeExceeded) {
termTooBig = maxDiskEntrySizeExceeded.value;
}
mergedToDisk++;
if(idxDisk.ttab.size() > MAX_TERMS || mergedToDisk > MAX_UPDATES || termTooBig ||
(lastMergedToFreenet > 0 && (System.currentTimeMillis() - lastMergedToFreenet) > MAX_TIME)) {
final ProtoIndex diskToMerge = idxDisk;
final File dir = idxDiskDir;
System.out.println("Exceeded threshold, starting new disk index and starting merge from disk to Freenet...");
mergedToDisk = 0;
lastMergedToFreenet = -1;
idxDisk = null;
srlDisk = null;
leafsrlDisk = null;
idxDiskDir = null;
lastDiskIndexName = null;
synchronized(freenetMergeSync) {
while(freenetMergeRunning) {
if(pushBroken) return;
System.err.println("Need to merge to Freenet, but last merge not finished yet. Waiting...");
try {
freenetMergeSync.wait();
} catch (InterruptedException e) {
// Ignore
}
}
if(pushBroken) return;
freenetMergeRunning = true;
}
Runnable r = new Runnable() {
public void run() {
try {
mergeToFreenet(diskToMerge, dir);
} catch (Throwable t) {
Logger.error(this, "Merge to Freenet failed: "+t, t);
System.err.println("Merge to Freenet failed: "+t);
t.printStackTrace();
synchronized(freenetMergeSync) {
pushBroken = true;
}
} finally {
synchronized(freenetMergeSync) {
freenetMergeRunning = false;
if(!pushBroken)
lastMergedToFreenet = System.currentTimeMillis();
freenetMergeSync.notifyAll();
}
}
}
};
pr.getNode().executor.execute(r, "Library: Merge data from disk to Freenet");
}
} catch (TaskAbortException e) {
Logger.error(this, "Failed to upload index for spider: "+e, e);
System.err.println("Failed to upload index for spider: "+e);
e.printStackTrace();
synchronized(freenetMergeSync) {
pushBroken = true;
}
}
}
static final String INDEX_DOCNAME = "index.yml";
private ProtoIndexComponentSerialiser leafsrl;
protected void mergeToFreenet(File diskDir) {
ProtoIndexSerialiser s = ProtoIndexSerialiser.forIndex(diskDir);
LiveArchiver<Map<String,Object>,SimpleProgress> archiver =
(LiveArchiver<Map<String,Object>,SimpleProgress>)(s.getChildSerialiser());
ProtoIndexComponentSerialiser leaf = ProtoIndexComponentSerialiser.get(ProtoIndexComponentSerialiser.FMT_FILE_LOCAL, null);
String f = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(diskDir, LAST_DISK_FILENAME));
BufferedReader br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
f = br.readLine();
System.out.println("Continuing old bucket: "+f);
fis.close();
fis = null;
} catch (IOException e) {
// Ignore
System.err.println("Unable to merge old data "+diskDir+" : "+e);
e.printStackTrace();
Logger.error(this, "Unable to merge old data "+diskDir+" : "+e, e);
} finally {
Closer.close(fis);
}
ProtoIndex idxDisk = null;
try {
PullTask<ProtoIndex> pull = new PullTask<ProtoIndex>(f);
System.out.println("Pulling previous index "+f+" from disk so can update it.");
s.pull(pull);
System.out.println("Pulled previous index "+f+" from disk - updating...");
idxDisk = pull.data;
if(idxDisk.getSerialiser().getLeafSerialiser() != archiver)
throw new IllegalStateException("Different serialiser: "+idxFreenet.getSerialiser()+" should be "+leafsrl);
} catch (TaskAbortException e) {
Logger.error(this, "Failed to download previous index for spider update: "+e, e);
System.err.println("Failed to download previous index for spider update: "+e);
e.printStackTrace();
synchronized(freenetMergeSync) {
pushBroken = true;
}
return;
}
mergeToFreenet(idxDisk, diskDir);
}
private final Object inflateSync = new Object();
protected void mergeToFreenet(ProtoIndex diskToMerge, File diskDir) {
if(lastUploadURI == null) {
File f = new File(LAST_URL_FILENAME);
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
BufferedReader br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
lastUploadURI = new FreenetURI(br.readLine());
System.out.println("Continuing from last index CHK: "+lastUploadURI);
fis.close();
fis = null;
} catch (IOException e) {
// Ignore
} finally {
Closer.close(fis);
}
}
if(privURI == null) {
File f = new File(PRIV_URI_FILENAME);
FileInputStream fis = null;
InsertableClientSSK privkey = null;
boolean newPrivKey = false;
try {
fis = new FileInputStream(f);
BufferedReader br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
privURI = new FreenetURI(br.readLine()).setDocName("index.yml"); // Else InsertableClientSSK doesn't like it.
privkey = InsertableClientSSK.create(privURI);
System.out.println("Read old privkey");
this.pubURI = privkey.getURI();
System.out.println("Recovered URI from disk, pubkey is "+pubURI);
fis.close();
fis = null;
} catch (IOException e) {
// Ignore
} finally {
Closer.close(fis);
}
if(privURI == null) {
InsertableClientSSK key = InsertableClientSSK.createRandom(pr.getNode().random, "index.yml");
privURI = key.getInsertURI();
pubURI = key.getURI();
newPrivKey = true;
System.out.println("Created new keypair, pubkey is "+pubURI);
}
FileOutputStream fos = null;
if(newPrivKey) {
try {
fos = new FileOutputStream(new File(PRIV_URI_FILENAME));
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
osw.write(privURI.toASCIIString());
osw.close();
fos = null;
} catch (IOException e) {
Logger.error(this, "Failed to write new private key");
System.out.println("Failed to write new private key : "+e);
} finally {
Closer.close(fos);
}
}
try {
fos = new FileOutputStream(new File(PUB_URI_FILENAME));
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
osw.write(pubURI.toASCIIString());
osw.close();
fos = null;
} catch (IOException e) {
Logger.error(this, "Failed to write new pubkey", e);
System.out.println("Failed to write new pubkey: "+e);
} finally {
Closer.close(fos);
}
try {
fis = new FileInputStream(new File(EDITION_FILENAME));
BufferedReader br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
try {
edition = Long.parseLong(br.readLine());
} catch (NumberFormatException e) {
edition = 1;
}
System.out.println("Edition: "+edition);
fis.close();
fis = null;
} catch (IOException e) {
// Ignore
edition = 1;
} finally {
Closer.close(fis);
}
}
if(FreenetArchiver.getCacheDir() == null) {
File dir = new File("library-spider-pushed-data-cache");
dir.mkdir();
FreenetArchiver.setCacheDir(dir);
}
if(srl == null) {
srl = ProtoIndexSerialiser.forIndex(lastUploadURI, RequestStarter.BULK_SPLITFILE_PRIORITY_CLASS);
LiveArchiver<Map<String,Object>,SimpleProgress> archiver =
(LiveArchiver<Map<String,Object>,SimpleProgress>)(srl.getChildSerialiser());
leafsrl = ProtoIndexComponentSerialiser.get(ProtoIndexComponentSerialiser.FMT_DEFAULT, archiver);
if(lastUploadURI == null) {
try {
idxFreenet = new ProtoIndex(new FreenetURI("CHK@yeah"), "test", null, null, 0L);
} catch (java.net.MalformedURLException e) {
throw new AssertionError(e);
}
// FIXME more hacks: It's essential that we use the same FreenetArchiver instance here.
leafsrl.setSerialiserFor(idxFreenet);
} else {
try {
PullTask<ProtoIndex> pull = new PullTask<ProtoIndex>(lastUploadURI);
System.out.println("Pulling previous index "+lastUploadURI+" so can update it.");
srl.pull(pull);
System.out.println("Pulled previous index "+lastUploadURI+" - updating...");
idxFreenet = pull.data;
if(idxFreenet.getSerialiser().getLeafSerialiser() != archiver)
throw new IllegalStateException("Different serialiser: "+idxFreenet.getSerialiser()+" should be "+leafsrl);
} catch (TaskAbortException e) {
Logger.error(this, "Failed to download previous index for spider update: "+e, e);
System.err.println("Failed to download previous index for spider update: "+e);
e.printStackTrace();
synchronized(freenetMergeSync) {
pushBroken = true;
}
return;
}
}
}
idxFreenet.setName(diskToMerge.getName());
idxFreenet.setOwnerEmail(diskToMerge.getOwnerEmail());
idxFreenet.setOwner(diskToMerge.getOwner());
// This is roughly accurate, it might not be exactly so if we process a bit out of order.
idxFreenet.setTotalPages(diskToMerge.getTotalPages());
final SkeletonBTreeMap<String, SkeletonBTreeSet<TermEntry>> newtrees = diskToMerge.ttab;
// Do the upload
// async merge
Closure<Map.Entry<String, SkeletonBTreeSet<TermEntry>>, TaskAbortException> clo = new
Closure<Map.Entry<String, SkeletonBTreeSet<TermEntry>>, TaskAbortException>() {
/*@Override**/ public void invoke(Map.Entry<String, SkeletonBTreeSet<TermEntry>> entry) throws TaskAbortException {
String key = entry.getKey();
SkeletonBTreeSet<TermEntry> tree = entry.getValue();
if(logMINOR) Logger.minor(this, "Processing: "+key+" : "+tree);
//System.out.println("handling " + key + ((tree == null)? " (new)":" (old)"));
boolean newTree = false;
if (tree == null) {
entry.setValue(tree = makeEntryTree(leafsrl));
newTree = true;
}
assert(tree.isBare());
SortedSet<TermEntry> data;
// Can't be run in parallel.
synchronized(inflateSync) {
newtrees.inflate(key, true);
SkeletonBTreeSet<TermEntry> entries;
entries = newtrees.get(key);
// CONCURRENCY: Because the lower-level trees are packed by the top tree, the bottom
// trees (SkeletonBTreeSet's) are not independant of each other. When the newtrees
// inflate above runs, it can deflate a tree that is still in use by another instance
// of this callback. Therefore we must COPY IT AND DEFLATE IT INSIDE THE LOCK.
entries.inflate();
data = new TreeSet<TermEntry>(entries);
entries.deflate();
assert(entries.isBare());
}
if(tree != null)
if(newTree) {
tree.addAll(data);
assert(tree.size() == data.size());
System.out.println("Added data to Freenet for term "+key+" : "+data.size());
} else {
int oldSize = tree.size();
tree.update(data, null);
// Note that it is possible for data.size() + oldSize != tree.size(), because we might be merging data we've already merged.
// But most of the time it will add up.
System.out.println("Merged data to Freenet in term "+key+" : "+data.size()+" + "+oldSize+" -> "+tree.size());
}
tree.deflate();
assert(tree.isBare());
if(logMINOR) Logger.minor(this, "Updated: "+key+" : "+tree);
//System.out.println("handled " + key);
}
};
try {
long mergeStartTime = System.currentTimeMillis();
assert(idxFreenet.ttab.isBare());
Iterator<String> it =
diskToMerge.ttab.keySetAutoDeflate().iterator();
TreeSet<String> terms = new TreeSet<String>();
while(it.hasNext()) terms.add(it.next());
System.out.println("Merging "+terms.size()+" terms from disk to Freenet...");
assert(terms.size() == diskToMerge.ttab.size());
assert(idxFreenet.ttab.isBare());
assert(diskToMerge.ttab.isBare());
long entriesAdded = terms.size();
idxFreenet.ttab.update(terms, null, clo, new TaskAbortExceptionConvertor());
assert(idxFreenet.ttab.isBare());
newtrees.deflate();
assert(diskToMerge.ttab.isBare());
PushTask<ProtoIndex> task4 = new PushTask<ProtoIndex>(idxFreenet);
task4.meta = FreenetURI.EMPTY_CHK_URI;
srl.push(task4);
FreenetArchiver arch = (FreenetArchiver) srl.getChildSerialiser();
arch.waitForAsyncInserts();
long mergeEndTime = System.currentTimeMillis();
System.out.print(entriesAdded + " entries merged in " + (mergeEndTime-mergeStartTime) + " ms, root at " + task4.meta + ", ");
FreenetURI uri = (FreenetURI)task4.meta;
lastUploadURI = uri;
System.out.println("Uploaded new index to "+uri);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(LAST_URL_FILENAME);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
osw.write(uri.toASCIIString());
osw.close();
fos = null;
newtrees.deflate();
diskToMerge = null;
terms = null;
System.out.println("Finished with disk index "+diskDir);
FileUtil.removeAll(diskDir);
} catch (IOException e) {
Logger.error(this, "Failed to write URL of uploaded index: "+uri, e);
System.out.println("Failed to write URL of uploaded index: "+uri+" : "+e);
} finally {
Closer.close(fos);
}
// Upload to USK
FreenetURI privUSK = privURI.setKeyType("USK").setDocName(INDEX_DOCNAME).setSuggestedEdition(edition);
try {
FreenetURI tmp = pr.getHLSimpleClient().insertRedirect(privUSK, uri);
edition = tmp.getEdition()+1;
System.out.println("Uploaded index as USK to "+tmp);
fos = null;
try {
fos = new FileOutputStream(EDITION_FILENAME);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
osw.write(Long.toString(edition));
osw.close();
fos = null;
} catch (IOException e) {
Logger.error(this, "Failed to write URL of uploaded index: "+uri, e);
System.out.println("Failed to write URL of uploaded index: "+uri+" : "+e);
} finally {
Closer.close(fos);
}
} catch (InsertException e) {
System.err.println("Failed to upload USK for index update: "+e);
e.printStackTrace();
Logger.error(this, "Failed to upload USK for index update", e);
}
} catch (TaskAbortException e) {
Logger.error(this, "Failed to upload index for spider: "+e, e);
System.err.println("Failed to upload index for spider: "+e);
e.printStackTrace();
synchronized(freenetMergeSync) {
pushBroken = true;
}
}
}
protected static SkeletonBTreeSet<TermEntry> makeEntryTree(ProtoIndexComponentSerialiser leafsrl) {
SkeletonBTreeSet<TermEntry> tree = new SkeletonBTreeSet<TermEntry>(ProtoIndex.BTREE_NODE_MIN);
leafsrl.setSerialiserFor(tree);
return tree;
}
}
| true | true | private void mergeToDisk(Bucket data) {
boolean newIndex = false;
if(idxDiskDir == null) {
newIndex = true;
dirNumber++;
idxDiskDir = new File(DISK_DIR_PREFIX + Integer.toString(dirNumber));
System.out.println("Created new disk dir for merging: "+idxDiskDir);
if(!(idxDiskDir.mkdir() || idxDiskDir.isDirectory())) {
Logger.error(this, "Unable to create new disk dir: "+idxDiskDir);
synchronized(this) {
pushBroken = true;
return;
}
}
}
if(srlDisk == null) {
srlDisk = ProtoIndexSerialiser.forIndex(idxDiskDir);
LiveArchiver<Map<String,Object>,SimpleProgress> archiver =
(LiveArchiver<Map<String,Object>,SimpleProgress>)(srlDisk.getChildSerialiser());
leafsrlDisk = ProtoIndexComponentSerialiser.get(ProtoIndexComponentSerialiser.FMT_FILE_LOCAL, archiver);
if(lastDiskIndexName == null) {
try {
idxDisk = new ProtoIndex(new FreenetURI("CHK@yeah"), "test", null, null, 0L);
} catch (java.net.MalformedURLException e) {
throw new AssertionError(e);
}
// FIXME more hacks: It's essential that we use the same FileArchiver instance here.
leafsrlDisk.setSerialiserFor(idxDisk);
} else {
try {
PullTask<ProtoIndex> pull = new PullTask<ProtoIndex>(lastDiskIndexName);
System.out.println("Pulling previous index "+lastDiskIndexName+" from disk so can update it.");
srlDisk.pull(pull);
System.out.println("Pulled previous index "+lastDiskIndexName+" from disk - updating...");
idxDisk = pull.data;
if(idxDisk.getSerialiser().getLeafSerialiser() != archiver)
throw new IllegalStateException("Different serialiser: "+idxFreenet.getSerialiser()+" should be "+leafsrl);
} catch (TaskAbortException e) {
Logger.error(this, "Failed to download previous index for spider update: "+e, e);
System.err.println("Failed to download previous index for spider update: "+e);
e.printStackTrace();
synchronized(freenetMergeSync) {
pushBroken = true;
}
return;
}
}
}
// Read data into newtrees and trees.
FileWriter w = null;
newtrees = new HashMap<String, SortedSet<TermEntry>>();
terms = new TreeSet<String>();
int entriesAdded = 0;
try {
Logger.normal(this, "Bucket of buffer received, "+data.size()+" bytes");
InputStream is = data.getInputStream();
SimpleFieldSet fs = new SimpleFieldSet(new LineReadingInputStream(is), 1024, 512, true, true, true);
idxDisk.setName(fs.get("index.title"));
idxDisk.setOwnerEmail(fs.get("index.owner.email"));
idxDisk.setOwner(fs.get("index.owner.name"));
idxDisk.setTotalPages(fs.getLong("totalPages", -1));
try{
while(true){ // Keep going til an EOFExcepiton is thrown
TermEntry readObject = TermEntryReaderWriter.getInstance().readObject(is);
SortedSet<TermEntry> set = newtrees.get(readObject.subj);
if(set == null)
newtrees.put(readObject.subj, set = new TreeSet<TermEntry>());
set.add(readObject);
terms.add(readObject.subj);
entriesAdded++;
}
}catch(EOFException e){
// EOF, do nothing
}
} catch (IOException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
if(terms.size() == 0) {
System.out.println("Nothing to merge");
synchronized(this) {
newtrees = null;
terms = null;
}
return;
}
// Do the upload
try {
final MutableBoolean maxDiskEntrySizeExceeded = new MutableBoolean();
maxDiskEntrySizeExceeded.value = false;
long mergeStartTime = System.currentTimeMillis();
if(newIndex) {
// created a new index, fill it with data.
// DON'T MERGE, merge with a lot of data will deadlock.
// FIXME throw in update() if it will deadlock.
for(String key : terms) {
SkeletonBTreeSet<TermEntry> tree = makeEntryTree(leafsrlDisk);
SortedSet<TermEntry> toMerge = newtrees.get(key);
tree.addAll(toMerge);
if(toMerge.size() > MAX_DISK_ENTRY_SIZE)
maxDiskEntrySizeExceeded.value = true;
toMerge = null;
tree.deflate();
assert(tree.isBare());
idxDisk.ttab.put(key, tree);
}
idxDisk.ttab.deflate();
} else {
// async merge
Closure<Map.Entry<String, SkeletonBTreeSet<TermEntry>>, TaskAbortException> clo = new
Closure<Map.Entry<String, SkeletonBTreeSet<TermEntry>>, TaskAbortException>() {
/*@Override**/ public void invoke(Map.Entry<String, SkeletonBTreeSet<TermEntry>> entry) throws TaskAbortException {
String key = entry.getKey();
SkeletonBTreeSet<TermEntry> tree = entry.getValue();
if(logMINOR) Logger.minor(this, "Processing: "+key+" : "+tree);
if(tree != null)
System.out.println("Merging data (on disk) in term "+key);
else
System.out.println("Adding new term to disk index: "+key);
//System.out.println("handling " + key + ((tree == null)? " (new)":" (old)"));
if (tree == null) {
entry.setValue(tree = makeEntryTree(leafsrlDisk));
}
assert(tree.isBare());
SortedSet<TermEntry> toMerge = newtrees.get(key);
tree.update(toMerge, null);
if(toMerge.size() > MAX_DISK_ENTRY_SIZE)
synchronized(maxDiskEntrySizeExceeded) {
maxDiskEntrySizeExceeded.value = true;
}
toMerge = null;
newtrees.remove(key);
assert(tree.isBare());
if(logMINOR) Logger.minor(this, "Updated: "+key+" : "+tree);
//System.out.println("handled " + key);
}
};
assert(idxDisk.ttab.isBare());
System.out.println("Merging "+terms.size()+" terms, tree.size = "+idxDisk.ttab.size()+" from "+data+"...");
idxDisk.ttab.update(terms, null, clo, new TaskAbortExceptionConvertor());
}
// Synchronize anyway so garbage collector knows about it.
synchronized(this) {
newtrees = null;
terms = null;
}
assert(idxDisk.ttab.isBare());
PushTask<ProtoIndex> task4 = new PushTask<ProtoIndex>(idxDisk);
srlDisk.push(task4);
long mergeEndTime = System.currentTimeMillis();
System.out.print(entriesAdded + " entries merged to disk in " + (mergeEndTime-mergeStartTime) + " ms, root at " + task4.meta + ", ");
// FileArchiver produces a String, which is a filename not including the prefix or suffix.
String uri = (String)task4.meta;
lastDiskIndexName = uri;
System.out.println("Pushed new index to file "+uri);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(LAST_DISK_FILENAME);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
osw.write(uri.toString());
osw.close();
fos = null;
data.free();
} catch (IOException e) {
Logger.error(this, "Failed to write filename of uploaded index: "+uri, e);
System.out.println("Failed to write filename of uploaded index: "+uri+" : "+e);
} finally {
Closer.close(fos);
}
try {
fos = new FileOutputStream(new File(idxDiskDir, LAST_DISK_FILENAME));
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
osw.write(uri.toString());
osw.close();
fos = null;
} catch (IOException e) {
Logger.error(this, "Failed to write filename of uploaded index: "+uri, e);
System.out.println("Failed to write filename of uploaded index: "+uri+" : "+e);
} finally {
Closer.close(fos);
}
// Maybe chain to mergeToFreenet ???
boolean termTooBig = false;
synchronized(maxDiskEntrySizeExceeded) {
termTooBig = maxDiskEntrySizeExceeded.value;
}
mergedToDisk++;
if(idxDisk.ttab.size() > MAX_TERMS || mergedToDisk > MAX_UPDATES || termTooBig ||
(lastMergedToFreenet > 0 && (System.currentTimeMillis() - lastMergedToFreenet) > MAX_TIME)) {
final ProtoIndex diskToMerge = idxDisk;
final File dir = idxDiskDir;
System.out.println("Exceeded threshold, starting new disk index and starting merge from disk to Freenet...");
mergedToDisk = 0;
lastMergedToFreenet = -1;
idxDisk = null;
srlDisk = null;
leafsrlDisk = null;
idxDiskDir = null;
lastDiskIndexName = null;
synchronized(freenetMergeSync) {
while(freenetMergeRunning) {
if(pushBroken) return;
System.err.println("Need to merge to Freenet, but last merge not finished yet. Waiting...");
try {
freenetMergeSync.wait();
} catch (InterruptedException e) {
// Ignore
}
}
if(pushBroken) return;
freenetMergeRunning = true;
}
Runnable r = new Runnable() {
public void run() {
try {
mergeToFreenet(diskToMerge, dir);
} catch (Throwable t) {
Logger.error(this, "Merge to Freenet failed: "+t, t);
System.err.println("Merge to Freenet failed: "+t);
t.printStackTrace();
synchronized(freenetMergeSync) {
pushBroken = true;
}
} finally {
synchronized(freenetMergeSync) {
freenetMergeRunning = false;
if(!pushBroken)
lastMergedToFreenet = System.currentTimeMillis();
freenetMergeSync.notifyAll();
}
}
}
};
pr.getNode().executor.execute(r, "Library: Merge data from disk to Freenet");
}
} catch (TaskAbortException e) {
| private void mergeToDisk(Bucket data) {
boolean newIndex = false;
if(idxDiskDir == null) {
newIndex = true;
dirNumber++;
idxDiskDir = new File(DISK_DIR_PREFIX + Integer.toString(dirNumber));
System.out.println("Created new disk dir for merging: "+idxDiskDir);
if(!(idxDiskDir.mkdir() || idxDiskDir.isDirectory())) {
Logger.error(this, "Unable to create new disk dir: "+idxDiskDir);
synchronized(this) {
pushBroken = true;
return;
}
}
}
if(srlDisk == null) {
srlDisk = ProtoIndexSerialiser.forIndex(idxDiskDir);
LiveArchiver<Map<String,Object>,SimpleProgress> archiver =
(LiveArchiver<Map<String,Object>,SimpleProgress>)(srlDisk.getChildSerialiser());
leafsrlDisk = ProtoIndexComponentSerialiser.get(ProtoIndexComponentSerialiser.FMT_FILE_LOCAL, archiver);
if(lastDiskIndexName == null) {
try {
idxDisk = new ProtoIndex(new FreenetURI("CHK@"), "test", null, null, 0L);
} catch (java.net.MalformedURLException e) {
throw new AssertionError(e);
}
// FIXME more hacks: It's essential that we use the same FileArchiver instance here.
leafsrlDisk.setSerialiserFor(idxDisk);
} else {
try {
PullTask<ProtoIndex> pull = new PullTask<ProtoIndex>(lastDiskIndexName);
System.out.println("Pulling previous index "+lastDiskIndexName+" from disk so can update it.");
srlDisk.pull(pull);
System.out.println("Pulled previous index "+lastDiskIndexName+" from disk - updating...");
idxDisk = pull.data;
if(idxDisk.getSerialiser().getLeafSerialiser() != archiver)
throw new IllegalStateException("Different serialiser: "+idxFreenet.getSerialiser()+" should be "+leafsrl);
} catch (TaskAbortException e) {
Logger.error(this, "Failed to download previous index for spider update: "+e, e);
System.err.println("Failed to download previous index for spider update: "+e);
e.printStackTrace();
synchronized(freenetMergeSync) {
pushBroken = true;
}
return;
}
}
}
// Read data into newtrees and trees.
FileWriter w = null;
newtrees = new HashMap<String, SortedSet<TermEntry>>();
terms = new TreeSet<String>();
int entriesAdded = 0;
try {
Logger.normal(this, "Bucket of buffer received, "+data.size()+" bytes");
InputStream is = data.getInputStream();
SimpleFieldSet fs = new SimpleFieldSet(new LineReadingInputStream(is), 1024, 512, true, true, true);
idxDisk.setName(fs.get("index.title"));
idxDisk.setOwnerEmail(fs.get("index.owner.email"));
idxDisk.setOwner(fs.get("index.owner.name"));
idxDisk.setTotalPages(fs.getLong("totalPages", -1));
try{
while(true){ // Keep going til an EOFExcepiton is thrown
TermEntry readObject = TermEntryReaderWriter.getInstance().readObject(is);
SortedSet<TermEntry> set = newtrees.get(readObject.subj);
if(set == null)
newtrees.put(readObject.subj, set = new TreeSet<TermEntry>());
set.add(readObject);
terms.add(readObject.subj);
entriesAdded++;
}
}catch(EOFException e){
// EOF, do nothing
}
} catch (IOException ex) {
java.util.logging.Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
if(terms.size() == 0) {
System.out.println("Nothing to merge");
synchronized(this) {
newtrees = null;
terms = null;
}
return;
}
// Do the upload
try {
final MutableBoolean maxDiskEntrySizeExceeded = new MutableBoolean();
maxDiskEntrySizeExceeded.value = false;
long mergeStartTime = System.currentTimeMillis();
if(newIndex) {
// created a new index, fill it with data.
// DON'T MERGE, merge with a lot of data will deadlock.
// FIXME throw in update() if it will deadlock.
for(String key : terms) {
SkeletonBTreeSet<TermEntry> tree = makeEntryTree(leafsrlDisk);
SortedSet<TermEntry> toMerge = newtrees.get(key);
tree.addAll(toMerge);
if(toMerge.size() > MAX_DISK_ENTRY_SIZE)
maxDiskEntrySizeExceeded.value = true;
toMerge = null;
tree.deflate();
assert(tree.isBare());
idxDisk.ttab.put(key, tree);
}
idxDisk.ttab.deflate();
} else {
// async merge
Closure<Map.Entry<String, SkeletonBTreeSet<TermEntry>>, TaskAbortException> clo = new
Closure<Map.Entry<String, SkeletonBTreeSet<TermEntry>>, TaskAbortException>() {
/*@Override**/ public void invoke(Map.Entry<String, SkeletonBTreeSet<TermEntry>> entry) throws TaskAbortException {
String key = entry.getKey();
SkeletonBTreeSet<TermEntry> tree = entry.getValue();
if(logMINOR) Logger.minor(this, "Processing: "+key+" : "+tree);
if(tree != null)
System.out.println("Merging data (on disk) in term "+key);
else
System.out.println("Adding new term to disk index: "+key);
//System.out.println("handling " + key + ((tree == null)? " (new)":" (old)"));
if (tree == null) {
entry.setValue(tree = makeEntryTree(leafsrlDisk));
}
assert(tree.isBare());
SortedSet<TermEntry> toMerge = newtrees.get(key);
tree.update(toMerge, null);
if(toMerge.size() > MAX_DISK_ENTRY_SIZE)
synchronized(maxDiskEntrySizeExceeded) {
maxDiskEntrySizeExceeded.value = true;
}
toMerge = null;
newtrees.remove(key);
assert(tree.isBare());
if(logMINOR) Logger.minor(this, "Updated: "+key+" : "+tree);
//System.out.println("handled " + key);
}
};
assert(idxDisk.ttab.isBare());
System.out.println("Merging "+terms.size()+" terms, tree.size = "+idxDisk.ttab.size()+" from "+data+"...");
idxDisk.ttab.update(terms, null, clo, new TaskAbortExceptionConvertor());
}
// Synchronize anyway so garbage collector knows about it.
synchronized(this) {
newtrees = null;
terms = null;
}
assert(idxDisk.ttab.isBare());
PushTask<ProtoIndex> task4 = new PushTask<ProtoIndex>(idxDisk);
srlDisk.push(task4);
long mergeEndTime = System.currentTimeMillis();
System.out.print(entriesAdded + " entries merged to disk in " + (mergeEndTime-mergeStartTime) + " ms, root at " + task4.meta + ", ");
// FileArchiver produces a String, which is a filename not including the prefix or suffix.
String uri = (String)task4.meta;
lastDiskIndexName = uri;
System.out.println("Pushed new index to file "+uri);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(LAST_DISK_FILENAME);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
osw.write(uri.toString());
osw.close();
fos = null;
data.free();
} catch (IOException e) {
Logger.error(this, "Failed to write filename of uploaded index: "+uri, e);
System.out.println("Failed to write filename of uploaded index: "+uri+" : "+e);
} finally {
Closer.close(fos);
}
try {
fos = new FileOutputStream(new File(idxDiskDir, LAST_DISK_FILENAME));
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
osw.write(uri.toString());
osw.close();
fos = null;
} catch (IOException e) {
Logger.error(this, "Failed to write filename of uploaded index: "+uri, e);
System.out.println("Failed to write filename of uploaded index: "+uri+" : "+e);
} finally {
Closer.close(fos);
}
// Maybe chain to mergeToFreenet ???
boolean termTooBig = false;
synchronized(maxDiskEntrySizeExceeded) {
termTooBig = maxDiskEntrySizeExceeded.value;
}
mergedToDisk++;
if(idxDisk.ttab.size() > MAX_TERMS || mergedToDisk > MAX_UPDATES || termTooBig ||
(lastMergedToFreenet > 0 && (System.currentTimeMillis() - lastMergedToFreenet) > MAX_TIME)) {
final ProtoIndex diskToMerge = idxDisk;
final File dir = idxDiskDir;
System.out.println("Exceeded threshold, starting new disk index and starting merge from disk to Freenet...");
mergedToDisk = 0;
lastMergedToFreenet = -1;
idxDisk = null;
srlDisk = null;
leafsrlDisk = null;
idxDiskDir = null;
lastDiskIndexName = null;
synchronized(freenetMergeSync) {
while(freenetMergeRunning) {
if(pushBroken) return;
System.err.println("Need to merge to Freenet, but last merge not finished yet. Waiting...");
try {
freenetMergeSync.wait();
} catch (InterruptedException e) {
// Ignore
}
}
if(pushBroken) return;
freenetMergeRunning = true;
}
Runnable r = new Runnable() {
public void run() {
try {
mergeToFreenet(diskToMerge, dir);
} catch (Throwable t) {
Logger.error(this, "Merge to Freenet failed: "+t, t);
System.err.println("Merge to Freenet failed: "+t);
t.printStackTrace();
synchronized(freenetMergeSync) {
pushBroken = true;
}
} finally {
synchronized(freenetMergeSync) {
freenetMergeRunning = false;
if(!pushBroken)
lastMergedToFreenet = System.currentTimeMillis();
freenetMergeSync.notifyAll();
}
}
}
};
pr.getNode().executor.execute(r, "Library: Merge data from disk to Freenet");
}
} catch (TaskAbortException e) {
|
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.ui.views/src/org/eclipse/tcf/te/ui/views/editor/Editor.java b/target_explorer/plugins/org.eclipse.tcf.te.ui.views/src/org/eclipse/tcf/te/ui/views/editor/Editor.java
index e1ad21640..533ea7789 100644
--- a/target_explorer/plugins/org.eclipse.tcf.te.ui.views/src/org/eclipse/tcf/te/ui/views/editor/Editor.java
+++ b/target_explorer/plugins/org.eclipse.tcf.te.ui.views/src/org/eclipse/tcf/te/ui/views/editor/Editor.java
@@ -1,399 +1,399 @@
/*******************************************************************************
* Copyright (c) 2011, 2012 Wind River Systems, Inc. and others. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.te.ui.views.editor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.tcf.te.ui.views.editor.pages.AbstractEditorPage;
import org.eclipse.tcf.te.ui.views.extensions.EditorPageBinding;
import org.eclipse.tcf.te.ui.views.extensions.EditorPageBindingExtensionPointManager;
import org.eclipse.tcf.te.ui.views.extensions.EditorPageExtensionPointManager;
import org.eclipse.tcf.te.ui.views.interfaces.IEditorPage;
import org.eclipse.tcf.te.ui.views.interfaces.IUIConstants;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPersistable;
import org.eclipse.ui.IPersistableEditor;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.XMLMemento;
import org.eclipse.ui.forms.editor.FormEditor;
import org.eclipse.ui.forms.editor.IFormPage;
import org.eclipse.ui.views.properties.IPropertySheetPage;
import org.eclipse.ui.views.properties.tabbed.ITabbedPropertySheetPageContributor;
import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage;
/**
* Editor implementation.
*/
public final class Editor extends FormEditor implements IPersistableEditor, ITabbedPropertySheetPageContributor {
// The reference to an memento to restore once the editor got activated
private IMemento mementoToRestore;
// The editor event listener instance
private EditorEventListener listener;
/* (non-Javadoc)
* @see org.eclipse.ui.forms.editor.FormEditor#addPages()
*/
@Override
protected void addPages() {
// Read extension point and add the contributed pages.
IEditorInput input = getEditorInput();
// Get all applicable editor page bindings
EditorPageBinding[] bindings = EditorPageBindingExtensionPointManager.getInstance().getApplicableEditorPageBindings(input);
for (EditorPageBinding binding : bindings) {
processPageBinding(binding);
}
if (mementoToRestore != null) {
// Loop over all registered pages and pass on the editor specific memento
// to the pages which implements IPersistableEditor as well
for (Object page : pages) {
if (page instanceof IPersistableEditor) {
((IPersistableEditor)page).restoreState(mementoToRestore);
}
}
mementoToRestore = null;
}
}
/**
* Override this method to delegate the setFocus to
* the active form page.
*/
@Override
public void setFocus() {
IFormPage fpage = getActivePageInstance();
if(fpage != null) {
fpage.setFocus();
}
else super.setFocus();
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.forms.editor.FormEditor#getActivePageInstance()
*/
@Override
public IFormPage getActivePageInstance() {
int index = getActivePage();
if (index != -1) {
return getPage(index);
}
return super.getActivePageInstance();
}
/**
* Returns the page which has the specified index.
*
* @param index The page's index.
* @return The page object or null if it does not exists.
*/
private IFormPage getPage(int index) {
for(int i=0;i<pages.size();i++) {
Object page = pages.get(i);
if (page instanceof IFormPage) {
IFormPage fpage = (IFormPage)page;
if (fpage.getIndex() == index)
return fpage;
}
}
return null;
}
/**
* Update the editor page list. Pages which are not longer valid
* will be removed and pages now being valid gets added.
*/
public void updatePageList() {
// Get the editor input object
IEditorInput input = getEditorInput();
// Get all applicable editor page bindings
List<EditorPageBinding> bindings = new ArrayList<EditorPageBinding>(Arrays.asList(EditorPageBindingExtensionPointManager.getInstance().getApplicableEditorPageBindings(input)));
// Get a copy of the currently added pages
List<Object> oldPages = pages != null ? new ArrayList<Object>(Arrays.asList(pages.toArray())) : new ArrayList<Object>();
// Loop through the old pages and determine if the page is still applicable
Iterator<Object> iterator = oldPages.iterator();
while (iterator.hasNext()) {
Object element = iterator.next();
// Skip over pages not being a form page.
if (!(element instanceof IFormPage)) continue;
IFormPage page = (IFormPage)element;
// Find the corresponding page binding
EditorPageBinding binding = null;
for (EditorPageBinding candidate : bindings) {
if (candidate.getPageId().equals(page.getId())) {
binding = candidate;
break;
}
}
if (binding != null) {
// Found binding -> page is still applicable
bindings.remove(binding);
} else {
// No binding found -> page is not longer applicable
removePage(pages.indexOf(page));
}
}
// If the are remaining bindings left, this are new pages.
// --> Process them now
for (EditorPageBinding binding : bindings) {
processPageBinding(binding);
}
}
/**
* Process the given editor page binding.
*
* @param binding The editor page binding. Must not be <code>null</code>.
*/
protected void processPageBinding(EditorPageBinding binding) {
Assert.isNotNull(binding);
String pageId = binding.getPageId();
if (pageId != null) {
// Get the corresponding editor page instance
IEditorPage page = EditorPageExtensionPointManager.getInstance().getEditorPage(pageId, true);
if (page != null) {
try {
// Associate this editor with the page instance.
// This is typically done in the constructor, but we are
// utilizing a default constructor to instantiate the page.
page.initialize(this);
// Read in the "insertBefore" and "insertAfter" properties of the binding
String insertBefore = binding.getInsertBefore().trim();
String insertAfter = binding.getInsertAfter().trim();
boolean pageAdded = false;
// insertBefore will be processed before insertAfter.
if (!"".equals(insertBefore)) { //$NON-NLS-1$
String[] pageIds = insertBefore.split(","); //$NON-NLS-1$
for (String insertBeforePageId : pageIds) {
// If it is "first", we insert the page at index 0
if ("first".equalsIgnoreCase(insertBeforePageId)) { //$NON-NLS-1$
- addPage(0, page);
+ if (getIndexOf(page.getId()) == -1) addPage(0, page);
pageAdded = true;
break;
}
// Find the index of the page we shall insert this page before
int index = getIndexOf(insertBeforePageId);
if (index != -1) {
- addPage(index, page);
+ if (getIndexOf(page.getId()) == -1) addPage(index, page);
pageAdded = true;
break;
}
}
}
// If the page hasn't been added till now, process insertAfter
if (!pageAdded && !"".equals(insertAfter)) { //$NON-NLS-1$
String[] pageIds = insertAfter.split(","); //$NON-NLS-1$
for (String insertAfterPageId : pageIds) {
// If it is "last", we insert the page at the end
if ("last".equalsIgnoreCase(insertAfterPageId)) { //$NON-NLS-1$
- addPage(page);
+ if (getIndexOf(page.getId()) == -1) addPage(page);
pageAdded = true;
break;
}
// Find the index of the page we shall insert this page after
int index = getIndexOf(insertAfterPageId);
if (index != -1 && index + 1 < pages.size()) {
- addPage(index + 1, page);
+ if (getIndexOf(page.getId()) == -1) addPage(index + 1, page);
pageAdded = true;
break;
}
}
}
// Add the page to the end if not added otherwise
- if (!pageAdded) addPage(page);
+ if (!pageAdded && getIndexOf(page.getId()) == -1) addPage(page);
} catch (PartInitException e) { /* ignored on purpose */ }
}
}
}
/**
* Returns the index of the page with the given id.
*
* @param pageId The page id. Must not be <code>null</code>.
* @return The page index or <code>-1</code> if not found.
*/
private int getIndexOf(String pageId) {
Assert.isNotNull(pageId);
for (int i = 0; i < pages.size(); i++) {
Object page = pages.get(i);
if (page instanceof IFormPage) {
IFormPage fpage = (IFormPage)page;
if (fpage.getId().equals(pageId))
return i;
}
}
return -1;
}
/* (non-Javadoc)
* @see org.eclipse.ui.forms.editor.FormPage#init(org.eclipse.ui.IEditorSite, org.eclipse.ui.IEditorInput)
*/
@Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException {
super.init(site, input);
// Update the part name
if (!"".equals(input.getName())) setPartName(input.getName()); //$NON-NLS-1$
// Dispose an existing event listener instance
if (listener != null) { listener.dispose(); listener = null; }
// Create the event listener. The event listener does register itself.
listener = new EditorEventListener(this);
}
/**
* Update the editor part name based on the current editor input.
*/
public void updatePartName() {
IEditorInput input = getEditorInput();
String oldPartName = getPartName();
if (input instanceof EditorInput) {
// Reset the editor input name to trigger recalculation
((EditorInput)input).name = null;
// If the name changed, apply the new name
if (!oldPartName.equals(input.getName())) setPartName(input.getName());
}
}
/* (non-Javadoc)
* @see org.eclipse.ui.forms.editor.FormEditor#dispose()
*/
@Override
public void dispose() {
// Dispose an existing event listener instance
if (listener != null) { listener.dispose(); listener = null; }
super.dispose();
}
/* (non-Javadoc)
* @see org.eclipse.ui.part.EditorPart#doSave(org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
public void doSave(IProgressMonitor monitor) {
commitPages(true);
// The pages may require some save post processing
for (Object page : pages) {
if (page instanceof AbstractEditorPage) {
((AbstractEditorPage)page).postDoSave(monitor);
}
}
editorDirtyStateChanged();
}
/* (non-Javadoc)
* @see org.eclipse.ui.part.EditorPart#doSaveAs()
*/
@Override
public void doSaveAs() {
}
/* (non-Javadoc)
* @see org.eclipse.ui.part.EditorPart#isSaveAsAllowed()
*/
@Override
public boolean isSaveAsAllowed() {
return false;
}
/* (non-Javadoc)
* @see org.eclipse.ui.IPersistableEditor#restoreState(org.eclipse.ui.IMemento)
*/
@Override
public void restoreState(IMemento memento) {
// Get the editor specific memento
mementoToRestore = internalGetMemento(memento);
}
/* (non-Javadoc)
* @see org.eclipse.ui.IPersistable#saveState(org.eclipse.ui.IMemento)
*/
@Override
public void saveState(IMemento memento) {
// Get the editor specific memento
memento = internalGetMemento(memento);
// Loop over all registered pages and pass on the editor specific memento
// to the pages which implements IPersistable as well
for (Object page : pages) {
if (page instanceof IPersistable) {
((IPersistable)page).saveState(memento);
}
}
}
/**
* Internal helper method accessing our editor local child memento
* from the given parent memento.
*/
private IMemento internalGetMemento(IMemento memento) {
// Assume the editor memento to be the same as the parent memento
IMemento editorMemento = memento;
// If the parent memento is not null, create a child within the parent
if (memento != null) {
editorMemento = memento.getChild(Editor.class.getName());
if (editorMemento == null) {
editorMemento = memento.createChild(Editor.class.getName());
}
} else {
// The parent memento is null. Create a new internal instance
// of a XMLMemento. This case is happening if the user switches
// to another perspective an the view becomes visible by this switch.
editorMemento = XMLMemento.createWriteRoot(Editor.class.getName());
}
return editorMemento;
}
/* (non-Javadoc)
* @see org.eclipse.ui.part.MultiPageEditorPart#getAdapter(java.lang.Class)
*/
@Override
public Object getAdapter(Class adapter) {
if (adapter == IPropertySheetPage.class) {
return new TabbedPropertySheetPage(this);
}
// We pass on the adapt request to the currently active page
Object adapterInstance = getActivePageInstance() != null ? getActivePageInstance().getAdapter(adapter) : null;
if (adapterInstance == null) {
// If failed to adapt via the currently active page, pass on to the super implementation
adapterInstance = super.getAdapter(adapter);
}
return adapterInstance;
}
/* (non-Javadoc)
* @see org.eclipse.ui.views.properties.tabbed.ITabbedPropertySheetPageContributor#getContributorId()
*/
@Override
public String getContributorId() {
return IUIConstants.TABBED_PROPERTIES_CONTRIBUTOR_ID;
}
}
| false | true | protected void processPageBinding(EditorPageBinding binding) {
Assert.isNotNull(binding);
String pageId = binding.getPageId();
if (pageId != null) {
// Get the corresponding editor page instance
IEditorPage page = EditorPageExtensionPointManager.getInstance().getEditorPage(pageId, true);
if (page != null) {
try {
// Associate this editor with the page instance.
// This is typically done in the constructor, but we are
// utilizing a default constructor to instantiate the page.
page.initialize(this);
// Read in the "insertBefore" and "insertAfter" properties of the binding
String insertBefore = binding.getInsertBefore().trim();
String insertAfter = binding.getInsertAfter().trim();
boolean pageAdded = false;
// insertBefore will be processed before insertAfter.
if (!"".equals(insertBefore)) { //$NON-NLS-1$
String[] pageIds = insertBefore.split(","); //$NON-NLS-1$
for (String insertBeforePageId : pageIds) {
// If it is "first", we insert the page at index 0
if ("first".equalsIgnoreCase(insertBeforePageId)) { //$NON-NLS-1$
addPage(0, page);
pageAdded = true;
break;
}
// Find the index of the page we shall insert this page before
int index = getIndexOf(insertBeforePageId);
if (index != -1) {
addPage(index, page);
pageAdded = true;
break;
}
}
}
// If the page hasn't been added till now, process insertAfter
if (!pageAdded && !"".equals(insertAfter)) { //$NON-NLS-1$
String[] pageIds = insertAfter.split(","); //$NON-NLS-1$
for (String insertAfterPageId : pageIds) {
// If it is "last", we insert the page at the end
if ("last".equalsIgnoreCase(insertAfterPageId)) { //$NON-NLS-1$
addPage(page);
pageAdded = true;
break;
}
// Find the index of the page we shall insert this page after
int index = getIndexOf(insertAfterPageId);
if (index != -1 && index + 1 < pages.size()) {
addPage(index + 1, page);
pageAdded = true;
break;
}
}
}
// Add the page to the end if not added otherwise
if (!pageAdded) addPage(page);
} catch (PartInitException e) { /* ignored on purpose */ }
}
}
}
| protected void processPageBinding(EditorPageBinding binding) {
Assert.isNotNull(binding);
String pageId = binding.getPageId();
if (pageId != null) {
// Get the corresponding editor page instance
IEditorPage page = EditorPageExtensionPointManager.getInstance().getEditorPage(pageId, true);
if (page != null) {
try {
// Associate this editor with the page instance.
// This is typically done in the constructor, but we are
// utilizing a default constructor to instantiate the page.
page.initialize(this);
// Read in the "insertBefore" and "insertAfter" properties of the binding
String insertBefore = binding.getInsertBefore().trim();
String insertAfter = binding.getInsertAfter().trim();
boolean pageAdded = false;
// insertBefore will be processed before insertAfter.
if (!"".equals(insertBefore)) { //$NON-NLS-1$
String[] pageIds = insertBefore.split(","); //$NON-NLS-1$
for (String insertBeforePageId : pageIds) {
// If it is "first", we insert the page at index 0
if ("first".equalsIgnoreCase(insertBeforePageId)) { //$NON-NLS-1$
if (getIndexOf(page.getId()) == -1) addPage(0, page);
pageAdded = true;
break;
}
// Find the index of the page we shall insert this page before
int index = getIndexOf(insertBeforePageId);
if (index != -1) {
if (getIndexOf(page.getId()) == -1) addPage(index, page);
pageAdded = true;
break;
}
}
}
// If the page hasn't been added till now, process insertAfter
if (!pageAdded && !"".equals(insertAfter)) { //$NON-NLS-1$
String[] pageIds = insertAfter.split(","); //$NON-NLS-1$
for (String insertAfterPageId : pageIds) {
// If it is "last", we insert the page at the end
if ("last".equalsIgnoreCase(insertAfterPageId)) { //$NON-NLS-1$
if (getIndexOf(page.getId()) == -1) addPage(page);
pageAdded = true;
break;
}
// Find the index of the page we shall insert this page after
int index = getIndexOf(insertAfterPageId);
if (index != -1 && index + 1 < pages.size()) {
if (getIndexOf(page.getId()) == -1) addPage(index + 1, page);
pageAdded = true;
break;
}
}
}
// Add the page to the end if not added otherwise
if (!pageAdded && getIndexOf(page.getId()) == -1) addPage(page);
} catch (PartInitException e) { /* ignored on purpose */ }
}
}
}
|
diff --git a/src/web/app/src/main/java/org/geoserver/filters/SessionDebugFilter.java b/src/web/app/src/main/java/org/geoserver/filters/SessionDebugFilter.java
index 2dae9ed44c..22e9eb7fb1 100644
--- a/src/web/app/src/main/java/org/geoserver/filters/SessionDebugFilter.java
+++ b/src/web/app/src/main/java/org/geoserver/filters/SessionDebugFilter.java
@@ -1,106 +1,106 @@
/* Copyright (c) 2001 - 2010 TOPP - www.openplans.org. All rights reserved.
* This code is licensed under the GPL 2.0 license, availible at the root
* application directory.
*/
package org.geoserver.filters;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;
import org.geotools.util.logging.Logging;
/**
* Utility filter that will dump a stack trace identifying any session creation outside of the user
* interface (OGC and REST services are supposed to be stateless, session creation is harmful to
* scalability)
*
* @author Andrea Aime - GeoSolutions
*/
public class SessionDebugFilter implements Filter {
static final Logger LOGGER = Logging.getLogger(SessionDebugWrapper.class);
public void destroy() {
// nothing to do
}
public void init(FilterConfig filterConfig) throws ServletException {
// nothing to do
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
if (req instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest) req;
chain.doFilter(new SessionDebugWrapper(request), res);
} else {
chain.doFilter(req, res);
}
}
/**
* {@link HttpServletRequest} wrapper that will dump a full trace for any session creation
* attempt
*
* @author Andrea Aime - GeoSolutions
*
*/
class SessionDebugWrapper extends HttpServletRequestWrapper {
public SessionDebugWrapper(HttpServletRequest request) {
super(request);
}
@Override
public HttpSession getSession() {
return this.getSession(true);
}
@Override
public HttpSession getSession(boolean create) {
// first off, try to grab an existing session
HttpSession session = super.getSession(false);
if (session != null || !create) {
return session;
}
// ok, no session but the caller really wants one,
// signal the issue in the logs
// are we creating the session in the web ui?
- if (getPathInfo().startsWith("/web")) {
+ if (getPathInfo().startsWith("web")) {
if(LOGGER.isLoggable(Level.FINE)) {
Exception e = new Exception("Full stack trace for the session creation path");
e.fillInStackTrace();
LOGGER.log(Level.FINE, "Creating a new http session inside the web UI (normal behavior)", e);
}
} else {
if(LOGGER.isLoggable(Level.INFO)) {
Exception e = new Exception("Full stack trace for the session creation path");
e.fillInStackTrace();
LOGGER.log(Level.INFO, "Creating a new http session outside of the web UI! " +
- "(normally not desirable), the path is" + getPathInfo(), e);
+ "(normally not desirable)", e);
}
}
// return the session
session = super.getSession(true);
return session;
}
}
}
| false | true | public HttpSession getSession(boolean create) {
// first off, try to grab an existing session
HttpSession session = super.getSession(false);
if (session != null || !create) {
return session;
}
// ok, no session but the caller really wants one,
// signal the issue in the logs
// are we creating the session in the web ui?
if (getPathInfo().startsWith("/web")) {
if(LOGGER.isLoggable(Level.FINE)) {
Exception e = new Exception("Full stack trace for the session creation path");
e.fillInStackTrace();
LOGGER.log(Level.FINE, "Creating a new http session inside the web UI (normal behavior)", e);
}
} else {
if(LOGGER.isLoggable(Level.INFO)) {
Exception e = new Exception("Full stack trace for the session creation path");
e.fillInStackTrace();
LOGGER.log(Level.INFO, "Creating a new http session outside of the web UI! " +
"(normally not desirable), the path is" + getPathInfo(), e);
}
}
// return the session
session = super.getSession(true);
return session;
}
| public HttpSession getSession(boolean create) {
// first off, try to grab an existing session
HttpSession session = super.getSession(false);
if (session != null || !create) {
return session;
}
// ok, no session but the caller really wants one,
// signal the issue in the logs
// are we creating the session in the web ui?
if (getPathInfo().startsWith("web")) {
if(LOGGER.isLoggable(Level.FINE)) {
Exception e = new Exception("Full stack trace for the session creation path");
e.fillInStackTrace();
LOGGER.log(Level.FINE, "Creating a new http session inside the web UI (normal behavior)", e);
}
} else {
if(LOGGER.isLoggable(Level.INFO)) {
Exception e = new Exception("Full stack trace for the session creation path");
e.fillInStackTrace();
LOGGER.log(Level.INFO, "Creating a new http session outside of the web UI! " +
"(normally not desirable)", e);
}
}
// return the session
session = super.getSession(true);
return session;
}
|
diff --git a/Android/RazorAHRS/src/de/tuberlin/qu/razorahrs/RazorAHRS.java b/Android/RazorAHRS/src/de/tuberlin/qu/razorahrs/RazorAHRS.java
index e68b736..39c8291 100644
--- a/Android/RazorAHRS/src/de/tuberlin/qu/razorahrs/RazorAHRS.java
+++ b/Android/RazorAHRS/src/de/tuberlin/qu/razorahrs/RazorAHRS.java
@@ -1,510 +1,513 @@
/*************************************************************************************
* Android Java Interface for Razor AHRS v1.3.3
* 9 Degree of Measurement Attitude and Heading Reference System
* for Sparkfun 9DOF Razor IMU
*
* Released under GNU GPL (General Public License) v3.0
* Copyright (C) 2011 Quality & Usability Lab, Deutsche Telekom Laboratories, TU Berlin
* Written by Peter Bartz ([email protected])
*
* Infos, updates, bug reports and feedback:
* http://dev.qu.tu-berlin.de/projects/sf-razor-9dof-ahrs
*************************************************************************************/
package de.tuberlin.qu.razorahrs;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import org.apache.http.util.EncodingUtils;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
/**
* Class to easily interface the Razor AHRS via Bluetooth.
* <p>
* Bluetooth seems to be even more picky on Android than it is anyway. Be sure to have a look at the
* section about Android Bluetooth in the tutorial at
* <a href="http://dev.qu.tu-berlin.de/projects/sf-razor-9dof-ahrs">
* http://dev.qu.tu-berlin.de/projects/sf-razor-9dof-ahrs</a>!
* <p>
* The app using this class has to
* <ul>
* <li>target Android 2.0 (API Level 5) or later.
* <li>specify the uses-permissions <code>BLUETOOTH</code> and <code>BLUETOOTH_ADMIN</code> in it's
* AndroidManifest.xml.
* <li>add this Library Project as a referenced library (Project Properties -> Android -> Library)
* </ul>
* <p>
* TODOs:
* <ul>
* <li>Add support for USB OTG (Android device used as USB host), if using FTDI is possible.
* </ul>
*
* @author Peter Bartz
*/
public class RazorAHRS {
private static final String TAG = "RazorAHRS";
private static final boolean DEBUG = false;
private static final String SYNCH_TOKEN = "#SYNCH";
private static final String NEW_LINE = "\r\n";
// Timeout to init Razor AHRS after a Bluetooth connection has been established
public static final int INIT_TIMEOUT_MS = 5000;
// IDs passed to internal message handler
private static final int MSG_ID__YPR_DATA = 0;
private static final int MSG_ID__IO_EXCEPTION_AND_DISCONNECT = 1;
private static final int MSG_ID__CONNECT_OK = 2;
private static final int MSG_ID__CONNECT_FAIL = 3;
private static final int MSG_ID__CONNECT_ATTEMPT = 4;
private static final UUID UUID_SPP = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private enum ConnectionState {
DISCONNECTED,
CONNECTING,
CONNECTED,
USER_DISCONNECT_REQUEST
}
volatile private ConnectionState connectionState = ConnectionState.DISCONNECTED;
volatile private BluetoothSocket btSocket;
volatile private BluetoothDevice btDevice;
volatile private InputStream inStream;
volatile private OutputStream outStream;
private RazorListener razorListener;
private boolean callbacksEnabled = true;
BluetoothThread btThread;
private int numConnectAttempts;
// Object pools
ObjectPool<float[]> float3Pool = new ObjectPool<float[]>(new ObjectPool.ObjectFactory<float[]>() {
@Override
public float[] newObject() {
return new float[3];
}
});
/**
* Constructor.
* Must be called from the thread where you want receive the RazorListener callbacks! So if you
* want to manipulate Android UI from the callbacks you have to call this from your main/UI
* thread.
*
* @param btDevice {@link android.bluetooth.BluetoothDevice BluetoothDevice} holding the Razor
* AHRS to connect to.
* @param razorListener {@link RazorListener} that will be notified of Razor AHRS events.
* @throws RuntimeException thrown if one of the parameters is null.
*/
public RazorAHRS(BluetoothDevice btDevice, RazorListener razorListener)
throws RuntimeException {
if (btDevice == null)
throw new RuntimeException("BluetoothDevice can not be null.");
this.btDevice = btDevice;
if (razorListener == null)
throw new RuntimeException("RazorListener can not be null.");
this.razorListener = razorListener;
}
/**
* @return <code>true</code> if listener callbacks are currently enabled, <code>false</code> else.
*/
public boolean getCallbacksEnabled() {
return callbacksEnabled;
}
/**
* Enables/disables listener callbacks.
* @param enabled
*/
public void setCallbacksEnabled(boolean enabled) {
callbacksEnabled = enabled;
}
/**
* Connect and start reading. Both is done asynchronously. {@link RazorListener#onConnectOk()}
* or {@link RazorListener#onConnectFail(IOException)} callbacks will be invoked.
*
* @param numConnectAttempts Number of attempts to make when trying to connect. Often connecting
* only works on the 2rd try or later. Bluetooth hooray.
*/
public void asyncConnect(int numConnectAttempts) {
if (DEBUG) Log.d(TAG, "asyncConnect() BEGIN");
// Disconnect and wait for running thread to end, if needed
if (btThread != null) {
asyncDisconnect();
try {
btThread.join();
} catch (InterruptedException e) { }
}
// Bluetooth thread not running any more, we're definitely in DISCONNECTED state now
// Create new thread to connect to Razor AHRS and read input
this.numConnectAttempts = numConnectAttempts;
connectionState = ConnectionState.CONNECTING;
btThread = new BluetoothThread();
btThread.start();
if (DEBUG) Log.d(TAG, "asyncConnect() END");
}
/**
* Disconnects from Razor AHRS. If still connecting this will also cancel the connection process.
*/
public void asyncDisconnect() {
if (DEBUG) Log.d(TAG, "asyncDisconnect() BEGIN");
synchronized (connectionState) {
if (DEBUG) Log.d(TAG, "asyncDisconnect() SNYNCHRONIZED");
// Don't go to USER_DISCONNECT_REQUEST state if we are disconnected already
if (connectionState == ConnectionState.DISCONNECTED)
return;
// This is a wanted disconnect, so we force (blocking) I/O to break
connectionState = ConnectionState.USER_DISCONNECT_REQUEST;
closeSocketAndStreams();
}
if (DEBUG) Log.d(TAG, "asyncDisconnect() END");
}
/**
* Writes out a string using ASCII encoding. Assumes we're connected. Does not handle
* exceptions itself.
*
* @param text Text to send out
* @throws IOException
*/
private void write(String text) throws IOException {
outStream.write(EncodingUtils.getAsciiBytes(text));
}
/**
* Closes I/O streams and Bluetooth socket.
*/
private void closeSocketAndStreams() {
if (DEBUG) Log.d(TAG, "closeSocketAndStreams() BEGIN");
// Try to switch off streaming output of Razor in preparation of next connect
try {
if (outStream != null)
write("#o0");
} catch (IOException e) { }
// Close Bluetooth socket => I/O operations immediately will throw exception
try {
if (btSocket != null)
btSocket.close();
} catch (IOException e) { }
if (DEBUG) Log.d(TAG, "closeSocketAndStreams() BT SOCKET CLOSED");
// Close streams
try {
if (inStream != null)
inStream.close();
} catch (IOException e) { }
try {
if (outStream != null)
outStream.close();
} catch (IOException e) { }
if (DEBUG) Log.d(TAG, "closeSocketAndStreams() STREAMS CLOSED");
// Do not set socket and streams null, because input thread might still access them
//inStream = null;
//outStream = null;
//btSocket = null;
if (DEBUG) Log.d(TAG, "closeSocketAndStreams() END");
}
/**
* Thread that handles connecting to and reading from Razor AHRS.
*/
private class BluetoothThread extends Thread {
byte[] inBuf = new byte[512];
int inBufPos = 0;
/**
* Blocks until it can read one byte of input, assumes we have a connection up and running.
*
* @return One byte from input stream
* @throws IOException If reading input stream fails
*/
private byte readByte() throws IOException {
int in = inStream.read();
if (in == -1)
throw new IOException("End of Stream");
return (byte) in;
}
/**
* Parse input stream for given token.
* @param token Token to find
* @param in Next byte from input stream
* @return <code>true</code> if token was found
*/
private boolean readToken(byte[] token, byte in) {
if (in == token[inBufPos++]) {
if (inBufPos == token.length) {
// Synch token found
inBufPos = 0;
if (DEBUG) Log.d(TAG, "Token found");
return true;
}
} else {
inBufPos = 0;
}
return false;
}
/**
* Synches with Razor AHRS and sets parameters.
* @throws IOException
*/
private void initRazor() throws IOException {
long t0, t1, t2;
// Start time
t0 = SystemClock.uptimeMillis();
/* See if Razor is there */
// Request synch token to see when Razor is up and running
final String contactSynchID = "00";
final String contactSynchRequest = "#s" + contactSynchID;
final byte[] contactSynchReply = EncodingUtils.getAsciiBytes(SYNCH_TOKEN + contactSynchID + NEW_LINE);
write(contactSynchRequest);
t1 = SystemClock.uptimeMillis();
while (true) {
// Check timeout
t2 = SystemClock.uptimeMillis();
if (t2 - t1 > 200) {
// 200ms elapsed since last request and no answer -> request synch again.
// (This happens when DTR is connected and Razor resets on connect)
write(contactSynchRequest);
t1 = t2;
}
if (t2 - t0 > INIT_TIMEOUT_MS)
// Timeout -> tracker not present
throw new IOException("Can not init Razor: response timeout");
// See if we can read something
if (inStream.available() > 0) {
// Synch token found?
if (readToken(contactSynchReply, readByte()))
break;
} else {
// No data available, wait
delay(5); // 5ms
}
}
/* Configure tracker */
// Set binary output mode, enable continuous streaming, disable errors and request synch
// token. So we're good, no matter what state the tracker currently is in.
final String configSynchID = "01";
final byte[] configSynchReply = EncodingUtils.getAsciiBytes(SYNCH_TOKEN + configSynchID + NEW_LINE);
write("#ob#o1#oe0#s" + configSynchID);
while (!readToken(configSynchReply, readByte())) { }
}
/**
* Opens Bluetooth connection to Razor AHRS.
* @throws IOException
*/
private void connect() throws IOException {
// Create Bluetooth socket
btSocket = btDevice.createRfcommSocketToServiceRecord(UUID_SPP);
if (btSocket == null) {
if (DEBUG) Log.d(TAG, "btSocket is null in connect()");
throw new IOException("Could not create Bluetooth socket");
}
// This could be used to create the RFCOMM socekt on older Android devices where
//createRfcommSocketToServiceRecord is not present yet.
/*try {
Method m = btDevice.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
btSocket = (BluetoothSocket) m.invoke(btDevice, Integer.valueOf(1));
} catch (Exception e) {
throw new IOException("Could not create Bluetooth socket using reflection");
}*/
// Connect socket to Razor AHRS
if (DEBUG) Log.d(TAG, "Canceling bt discovery");
BluetoothAdapter.getDefaultAdapter().cancelDiscovery(); // Recommended
if (DEBUG) Log.d(TAG, "Trying to connect() btSocket");
btSocket.connect();
// Get the input and output streams
if (DEBUG) Log.d(TAG, "Trying to create streams");
inStream = btSocket.getInputStream();
outStream = btSocket.getOutputStream();
if (inStream == null || outStream == null) {
if (DEBUG) Log.d(TAG, "Could not create I/O stream(s) in connect()");
throw new IOException("Could not create I/O stream(s)");
}
}
/**
* Bluetooth I/O thread entry method.
*/
public void run() {
if (DEBUG) Log.d(TAG, "Bluetooth I/O thread started");
try {
// Check if btDevice is set
if (btDevice == null) {
if (DEBUG) Log.d(TAG, "btDevice is null in run()");
throw new IOException("Bluetooth device is null");
}
// Make several attempts to connect
int i = 1;
while (true) {
if (DEBUG) Log.d(TAG, "Connect attempt " + i + " of " + numConnectAttempts);
sendToParentThread(MSG_ID__CONNECT_ATTEMPT, i);
try {
connect();
break; // Alrighty!
} catch (IOException e) {
if (DEBUG) Log.d(TAG, "Attempt failed: " + e.getMessage());
// Maximum number of attempts reached or cancel requested?
if (i == numConnectAttempts || connectionState == ConnectionState.USER_DISCONNECT_REQUEST)
throw e;
// We couldn't connect on first try, manually starting Bluetooth discovery
// often helps
if (DEBUG) Log.d(TAG, "Starting BT discovery");
BluetoothAdapter.getDefaultAdapter().startDiscovery();
delay(5000); // 5 seconds - long enough?
i++;
}
}
// Set Razor output mode
if (DEBUG) Log.d(TAG, "Trying to set Razor output mode");
initRazor();
// We're connected and initialized (unless disconnect was requested)
synchronized (connectionState) {
if (connectionState == ConnectionState.USER_DISCONNECT_REQUEST) {
closeSocketAndStreams();
throw new IOException(); // Dummy exception to force disconnect
}
else connectionState = ConnectionState.CONNECTED;
}
// Tell listener we're ready
sendToParentThread(MSG_ID__CONNECT_OK, null);
// Keep reading inStream until an exception occurs
if (DEBUG) Log.d(TAG, "Starting input loop");
while (true) {
// Read byte from input stream
inBuf[inBufPos++] = (byte) readByte();
if (inBufPos == 12) {
// We received a full frame, forward input to parent thread handler
float[] ypr = float3Pool.get();
ypr[0] = Float.intBitsToFloat((inBuf[0] & 0xff) + ((inBuf[1] & 0xff) << 8) + ((inBuf[2] & 0xff) << 16) + ((inBuf[3] & 0xff) << 24));
ypr[1] = Float.intBitsToFloat((inBuf[4] & 0xff) + ((inBuf[5] & 0xff) << 8) + ((inBuf[6] & 0xff) << 16) + ((inBuf[7] & 0xff) << 24));
ypr[2] = Float.intBitsToFloat((inBuf[8] & 0xff) + ((inBuf[9] & 0xff) << 8) + ((inBuf[10] & 0xff) << 16) + ((inBuf[11] & 0xff) << 24));
sendToParentThread(MSG_ID__YPR_DATA, ypr);
// Rewind input buffer position
inBufPos = 0;
}
}
} catch (IOException e) {
if (DEBUG) Log.d(TAG, "IOException in Bluetooth thread: " + e.getMessage());
synchronized (connectionState) {
// Don't forward exception if it was thrown because we broke I/O on purpose in
// other thread when user requested disconnect
if (connectionState != ConnectionState.USER_DISCONNECT_REQUEST) {
// There was a true I/O error, cleanup and forward exception
closeSocketAndStreams();
if (DEBUG) Log.d(TAG, "Forwarding exception");
- sendToParentThread(MSG_ID__IO_EXCEPTION_AND_DISCONNECT, e);
+ if (connectionState == ConnectionState.CONNECTING)
+ sendToParentThread(MSG_ID__CONNECT_FAIL, e);
+ else
+ sendToParentThread(MSG_ID__IO_EXCEPTION_AND_DISCONNECT, e);
} else {
// I/O error was caused on purpose, socket and streams are closed already
}
// I/O closed, thread done => we're disconnected now
connectionState = ConnectionState.DISCONNECTED;
}
}
}
/**
* Sends a message to Handler assigned to parent thread.
*
* @param msgId
* @param data
*/
private void sendToParentThread(int msgId, Object o) {
if (callbacksEnabled)
parentThreadHandler.obtainMessage(msgId, o).sendToTarget();
}
/**
* Sends a message to Handler assigned to parent thread.
*
* @param msgId
* @param data
*/
private void sendToParentThread(int msgId, int i) {
if (callbacksEnabled)
parentThreadHandler.obtainMessage(msgId, i, -1).sendToTarget();
}
/**
* Wrapper for {@link Thread#sleep(long)};
* @param ms Milliseconds
*/
void delay(long ms) {
try {
sleep(ms); // Sleep 5ms
} catch (InterruptedException e) { }
}
}
/**
* Handler that forwards messages to the RazorListener callbacks. This handler runs in the
* thread this RazorAHRS object was created in and receives data from the Bluetooth I/O thread.
*/
private Handler parentThreadHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_ID__YPR_DATA:
float[] ypr = (float[]) msg.obj;
razorListener.onAnglesUpdate(ypr[0], ypr[1], ypr[2]);
float3Pool.put(ypr);
break;
case MSG_ID__IO_EXCEPTION_AND_DISCONNECT:
razorListener.onIOExceptionAndDisconnect((IOException) msg.obj);
break;
case MSG_ID__CONNECT_ATTEMPT:
razorListener.onConnectAttempt(msg.arg1, numConnectAttempts);
break;
case MSG_ID__CONNECT_OK:
razorListener.onConnectOk();
break;
case MSG_ID__CONNECT_FAIL:
razorListener.onConnectFail((IOException) msg.obj);
break;
}
}
};
}
| true | true | public void run() {
if (DEBUG) Log.d(TAG, "Bluetooth I/O thread started");
try {
// Check if btDevice is set
if (btDevice == null) {
if (DEBUG) Log.d(TAG, "btDevice is null in run()");
throw new IOException("Bluetooth device is null");
}
// Make several attempts to connect
int i = 1;
while (true) {
if (DEBUG) Log.d(TAG, "Connect attempt " + i + " of " + numConnectAttempts);
sendToParentThread(MSG_ID__CONNECT_ATTEMPT, i);
try {
connect();
break; // Alrighty!
} catch (IOException e) {
if (DEBUG) Log.d(TAG, "Attempt failed: " + e.getMessage());
// Maximum number of attempts reached or cancel requested?
if (i == numConnectAttempts || connectionState == ConnectionState.USER_DISCONNECT_REQUEST)
throw e;
// We couldn't connect on first try, manually starting Bluetooth discovery
// often helps
if (DEBUG) Log.d(TAG, "Starting BT discovery");
BluetoothAdapter.getDefaultAdapter().startDiscovery();
delay(5000); // 5 seconds - long enough?
i++;
}
}
// Set Razor output mode
if (DEBUG) Log.d(TAG, "Trying to set Razor output mode");
initRazor();
// We're connected and initialized (unless disconnect was requested)
synchronized (connectionState) {
if (connectionState == ConnectionState.USER_DISCONNECT_REQUEST) {
closeSocketAndStreams();
throw new IOException(); // Dummy exception to force disconnect
}
else connectionState = ConnectionState.CONNECTED;
}
// Tell listener we're ready
sendToParentThread(MSG_ID__CONNECT_OK, null);
// Keep reading inStream until an exception occurs
if (DEBUG) Log.d(TAG, "Starting input loop");
while (true) {
// Read byte from input stream
inBuf[inBufPos++] = (byte) readByte();
if (inBufPos == 12) {
// We received a full frame, forward input to parent thread handler
float[] ypr = float3Pool.get();
ypr[0] = Float.intBitsToFloat((inBuf[0] & 0xff) + ((inBuf[1] & 0xff) << 8) + ((inBuf[2] & 0xff) << 16) + ((inBuf[3] & 0xff) << 24));
ypr[1] = Float.intBitsToFloat((inBuf[4] & 0xff) + ((inBuf[5] & 0xff) << 8) + ((inBuf[6] & 0xff) << 16) + ((inBuf[7] & 0xff) << 24));
ypr[2] = Float.intBitsToFloat((inBuf[8] & 0xff) + ((inBuf[9] & 0xff) << 8) + ((inBuf[10] & 0xff) << 16) + ((inBuf[11] & 0xff) << 24));
sendToParentThread(MSG_ID__YPR_DATA, ypr);
// Rewind input buffer position
inBufPos = 0;
}
}
} catch (IOException e) {
if (DEBUG) Log.d(TAG, "IOException in Bluetooth thread: " + e.getMessage());
synchronized (connectionState) {
// Don't forward exception if it was thrown because we broke I/O on purpose in
// other thread when user requested disconnect
if (connectionState != ConnectionState.USER_DISCONNECT_REQUEST) {
// There was a true I/O error, cleanup and forward exception
closeSocketAndStreams();
if (DEBUG) Log.d(TAG, "Forwarding exception");
sendToParentThread(MSG_ID__IO_EXCEPTION_AND_DISCONNECT, e);
} else {
// I/O error was caused on purpose, socket and streams are closed already
}
// I/O closed, thread done => we're disconnected now
connectionState = ConnectionState.DISCONNECTED;
}
}
}
| public void run() {
if (DEBUG) Log.d(TAG, "Bluetooth I/O thread started");
try {
// Check if btDevice is set
if (btDevice == null) {
if (DEBUG) Log.d(TAG, "btDevice is null in run()");
throw new IOException("Bluetooth device is null");
}
// Make several attempts to connect
int i = 1;
while (true) {
if (DEBUG) Log.d(TAG, "Connect attempt " + i + " of " + numConnectAttempts);
sendToParentThread(MSG_ID__CONNECT_ATTEMPT, i);
try {
connect();
break; // Alrighty!
} catch (IOException e) {
if (DEBUG) Log.d(TAG, "Attempt failed: " + e.getMessage());
// Maximum number of attempts reached or cancel requested?
if (i == numConnectAttempts || connectionState == ConnectionState.USER_DISCONNECT_REQUEST)
throw e;
// We couldn't connect on first try, manually starting Bluetooth discovery
// often helps
if (DEBUG) Log.d(TAG, "Starting BT discovery");
BluetoothAdapter.getDefaultAdapter().startDiscovery();
delay(5000); // 5 seconds - long enough?
i++;
}
}
// Set Razor output mode
if (DEBUG) Log.d(TAG, "Trying to set Razor output mode");
initRazor();
// We're connected and initialized (unless disconnect was requested)
synchronized (connectionState) {
if (connectionState == ConnectionState.USER_DISCONNECT_REQUEST) {
closeSocketAndStreams();
throw new IOException(); // Dummy exception to force disconnect
}
else connectionState = ConnectionState.CONNECTED;
}
// Tell listener we're ready
sendToParentThread(MSG_ID__CONNECT_OK, null);
// Keep reading inStream until an exception occurs
if (DEBUG) Log.d(TAG, "Starting input loop");
while (true) {
// Read byte from input stream
inBuf[inBufPos++] = (byte) readByte();
if (inBufPos == 12) {
// We received a full frame, forward input to parent thread handler
float[] ypr = float3Pool.get();
ypr[0] = Float.intBitsToFloat((inBuf[0] & 0xff) + ((inBuf[1] & 0xff) << 8) + ((inBuf[2] & 0xff) << 16) + ((inBuf[3] & 0xff) << 24));
ypr[1] = Float.intBitsToFloat((inBuf[4] & 0xff) + ((inBuf[5] & 0xff) << 8) + ((inBuf[6] & 0xff) << 16) + ((inBuf[7] & 0xff) << 24));
ypr[2] = Float.intBitsToFloat((inBuf[8] & 0xff) + ((inBuf[9] & 0xff) << 8) + ((inBuf[10] & 0xff) << 16) + ((inBuf[11] & 0xff) << 24));
sendToParentThread(MSG_ID__YPR_DATA, ypr);
// Rewind input buffer position
inBufPos = 0;
}
}
} catch (IOException e) {
if (DEBUG) Log.d(TAG, "IOException in Bluetooth thread: " + e.getMessage());
synchronized (connectionState) {
// Don't forward exception if it was thrown because we broke I/O on purpose in
// other thread when user requested disconnect
if (connectionState != ConnectionState.USER_DISCONNECT_REQUEST) {
// There was a true I/O error, cleanup and forward exception
closeSocketAndStreams();
if (DEBUG) Log.d(TAG, "Forwarding exception");
if (connectionState == ConnectionState.CONNECTING)
sendToParentThread(MSG_ID__CONNECT_FAIL, e);
else
sendToParentThread(MSG_ID__IO_EXCEPTION_AND_DISCONNECT, e);
} else {
// I/O error was caused on purpose, socket and streams are closed already
}
// I/O closed, thread done => we're disconnected now
connectionState = ConnectionState.DISCONNECTED;
}
}
}
|
diff --git a/java/v9t9-java/src/v9t9/emulator/hardware/memory/F99bMemoryModel.java b/java/v9t9-java/src/v9t9/emulator/hardware/memory/F99bMemoryModel.java
index c53ac9f73..0efd8e616 100644
--- a/java/v9t9-java/src/v9t9/emulator/hardware/memory/F99bMemoryModel.java
+++ b/java/v9t9-java/src/v9t9/emulator/hardware/memory/F99bMemoryModel.java
@@ -1,73 +1,73 @@
package v9t9.emulator.hardware.memory;
import java.io.IOException;
import v9t9.emulator.common.IEventNotifier;
import v9t9.emulator.common.Machine;
import v9t9.engine.files.DataFiles;
import v9t9.engine.memory.DiskMemoryEntry;
import v9t9.engine.memory.MemoryEntry;
/**
* F99b console memory model.
* @author ejs
*/
public class F99bMemoryModel extends BaseTI994AMemoryModel {
public F99bMemoryModel() {
super();
}
@Override
protected void initSettings() {
DataFiles.addSearchPath("../../tools/Forth99/bin");
DataFiles.addSearchPath("../../tools/Forth99/");
}
/* (non-Javadoc)
* @see v9t9.emulator.hardware.memory.StandardConsoleMemoryModel#loadMemory()
*/
@Override
public void loadMemory(IEventNotifier eventNotifier) {
DiskMemoryEntry cpuRomEntry;
String filename = "f99brom.bin";
try {
cpuRomEntry = DiskMemoryEntry.newByteMemoryFromFile(
0x400, 0x4000 - 0x400, "CPU ROM",
CPU,
filename, 0x400, false);
cpuRomEntry.load();
//for (int i = 0; i < cpuRomEntry.size; i++)
// CPU.writeByte(i, cpuRomEntry.readByte(i));
memory.addAndMap(cpuRomEntry);
cpuRomEntry.copySymbols(CPU);
} catch (IOException e) {
reportLoadError(eventNotifier, filename, e);
}
- loadConsoleGrom(eventNotifier, "nforth.grm");
+ loadConsoleGrom(eventNotifier, "forth99.grm");
}
protected void defineConsoleMemory(Machine machine) {
MemoryEntry entry = new MemoryEntry("48K RAM", CPU,
0x0400, 0xFC00, new EnhancedRamByteArea(0x4000, 0xFC00));
entry.getArea().setLatency(0);
memory.addAndMap(entry);
}
protected void defineMmioMemory(Machine machine) {
this.memory.addAndMap(new MemoryEntry("MMIO", CPU, 0x0000, 0x0400,
new F99ConsoleMmioArea(machine)));
}
/* (non-Javadoc)
* @see v9t9.emulator.hardware.memory.TI994AStandardConsoleMemoryModel#resetMemory()
*/
@Override
public void resetMemory() {
}
}
| true | true | public void loadMemory(IEventNotifier eventNotifier) {
DiskMemoryEntry cpuRomEntry;
String filename = "f99brom.bin";
try {
cpuRomEntry = DiskMemoryEntry.newByteMemoryFromFile(
0x400, 0x4000 - 0x400, "CPU ROM",
CPU,
filename, 0x400, false);
cpuRomEntry.load();
//for (int i = 0; i < cpuRomEntry.size; i++)
// CPU.writeByte(i, cpuRomEntry.readByte(i));
memory.addAndMap(cpuRomEntry);
cpuRomEntry.copySymbols(CPU);
} catch (IOException e) {
reportLoadError(eventNotifier, filename, e);
}
loadConsoleGrom(eventNotifier, "nforth.grm");
}
| public void loadMemory(IEventNotifier eventNotifier) {
DiskMemoryEntry cpuRomEntry;
String filename = "f99brom.bin";
try {
cpuRomEntry = DiskMemoryEntry.newByteMemoryFromFile(
0x400, 0x4000 - 0x400, "CPU ROM",
CPU,
filename, 0x400, false);
cpuRomEntry.load();
//for (int i = 0; i < cpuRomEntry.size; i++)
// CPU.writeByte(i, cpuRomEntry.readByte(i));
memory.addAndMap(cpuRomEntry);
cpuRomEntry.copySymbols(CPU);
} catch (IOException e) {
reportLoadError(eventNotifier, filename, e);
}
loadConsoleGrom(eventNotifier, "forth99.grm");
}
|
diff --git a/asm/test/conform/org/objectweb/asm/util/CheckClassAdapterUnitTest.java b/asm/test/conform/org/objectweb/asm/util/CheckClassAdapterUnitTest.java
index 786ff3b8..d6e4089f 100644
--- a/asm/test/conform/org/objectweb/asm/util/CheckClassAdapterUnitTest.java
+++ b/asm/test/conform/org/objectweb/asm/util/CheckClassAdapterUnitTest.java
@@ -1,869 +1,874 @@
/***
* ASM tests
* Copyright (c) 2002-2005 France Telecom
* 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 copyright holders 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 org.objectweb.asm.util;
import java.io.IOException;
import java.io.PrintWriter;
import junit.framework.TestCase;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassAdapter;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodAdapter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.attrs.Comment;
import org.objectweb.asm.commons.EmptyVisitor;
public class CheckClassAdapterUnitTest extends TestCase implements Opcodes {
public void testCheckClassVisitor() throws Exception {
String s = getClass().getName();
CheckClassAdapter.main(new String[0]);
CheckClassAdapter.main(new String[] { s });
CheckClassAdapter.main(new String[] { "output/test/cases/Interface.class" });
}
public void testVerifyValidClass() throws Exception {
ClassReader cr = new ClassReader(getClass().getName());
CheckClassAdapter.verify(cr, true, new PrintWriter(System.err));
}
public void testVerifyInvalidClass() {
ClassWriter cw = new ClassWriter(0);
cw.visit(V1_1, ACC_PUBLIC, "C", null, "java/lang/Object", null);
MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "m", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(ALOAD, 0);
mv.visitVarInsn(ISTORE, 30);
mv.visitInsn(RETURN);
mv.visitMaxs(1, 31);
mv.visitEnd();
cw.visitEnd();
ClassReader cr = new ClassReader(cw.toByteArray());
CheckClassAdapter.verify(cr, true, new PrintWriter(System.err));
}
public void testIllegalClassAccessFlag() {
ClassVisitor cv = new CheckClassAdapter(new EmptyVisitor());
try {
cv.visit(V1_1, 1 << 20, "C", null, "java/lang/Object", null);
fail();
} catch (Exception e) {
}
}
public void testIllegalSuperClass() {
ClassVisitor cv = new CheckClassAdapter(new EmptyVisitor());
try {
cv.visit(V1_1,
ACC_PUBLIC,
"java/lang/Object",
null,
"java/lang/Object",
null);
fail();
} catch (Exception e) {
}
}
public void testIllegalInterfaceSuperClass() {
ClassVisitor cv = new CheckClassAdapter(new EmptyVisitor());
try {
cv.visit(V1_1, ACC_INTERFACE, "I", null, "C", null);
fail();
} catch (Exception e) {
}
}
public void testIllegalClassSignature() {
ClassVisitor cv = new CheckClassAdapter(new EmptyVisitor());
try {
cv.visit(V1_1, ACC_PUBLIC, "C", "LC;I", "java/lang/Object", null);
fail();
} catch (Exception e) {
}
}
public void testIllegalClassAccessFlagSet() {
ClassVisitor cv = new CheckClassAdapter(new EmptyVisitor());
try {
cv.visit(V1_1,
ACC_FINAL + ACC_ABSTRACT,
"C",
null,
"java/lang/Object",
null);
fail();
} catch (Exception e) {
}
}
public void testIllegalClassMemberVisitBeforeStart() {
ClassVisitor cv = new CheckClassAdapter(new EmptyVisitor());
try {
cv.visitSource(null, null);
fail();
} catch (Exception e) {
}
}
public void testIllegalClassAttribute() {
ClassVisitor cv = new CheckClassAdapter(new EmptyVisitor());
cv.visit(V1_1, ACC_PUBLIC, "C", null, "java/lang/Object", null);
try {
cv.visitAttribute(null);
fail();
} catch (Exception e) {
}
}
public void testIllegalMultipleVisitCalls() {
ClassVisitor cv = new CheckClassAdapter(new EmptyVisitor());
cv.visit(V1_1, ACC_PUBLIC, "C", null, "java/lang/Object", null);
try {
cv.visit(V1_1, ACC_PUBLIC, "C", null, "java/lang/Object", null);
fail();
} catch (Exception e) {
}
}
public void testIllegalMultipleVisitSourceCalls() {
ClassVisitor cv = new CheckClassAdapter(new EmptyVisitor());
cv.visit(V1_1, ACC_PUBLIC, "C", null, "java/lang/Object", null);
cv.visitSource(null, null);
try {
cv.visitSource(null, null);
fail();
} catch (Exception e) {
}
}
public void testIllegalOuterClassName() {
ClassVisitor cv = new CheckClassAdapter(new EmptyVisitor());
cv.visit(V1_1, ACC_PUBLIC, "C", null, "java/lang/Object", null);
try {
cv.visitOuterClass(null, null, null);
fail();
} catch (Exception e) {
}
}
public void testIllegalMultipleVisitOuterClassCalls() {
ClassVisitor cv = new CheckClassAdapter(new EmptyVisitor());
cv.visit(V1_1, ACC_PUBLIC, "C", null, "java/lang/Object", null);
cv.visitOuterClass("name", null, null);
try {
cv.visitOuterClass(null, null, null);
fail();
} catch (Exception e) {
}
}
public void testIllegalFieldAccessFlagSet() {
ClassVisitor cv = new CheckClassAdapter(new EmptyVisitor());
cv.visit(V1_1, ACC_PUBLIC, "C", null, "java/lang/Object", null);
try {
cv.visitField(ACC_PUBLIC + ACC_PRIVATE, "i", "I", null, null);
fail();
} catch (Exception e) {
}
}
public void testIllegalFieldSignature() {
ClassVisitor cv = new CheckClassAdapter(new EmptyVisitor());
cv.visit(V1_1, ACC_PUBLIC, "C", null, "java/lang/Object", null);
try {
cv.visitField(ACC_PUBLIC, "i", "I", "L;", null);
fail();
} catch (Exception e) {
}
try {
cv.visitField(ACC_PUBLIC, "i", "I", "LC+", null);
fail();
} catch (Exception e) {
}
try {
cv.visitField(ACC_PUBLIC, "i", "I", "LC;I", null);
fail();
} catch (Exception e) {
}
}
public void testIllegalClassMemberVisitAfterEnd() {
ClassVisitor cv = new CheckClassAdapter(new EmptyVisitor());
cv.visit(V1_1, ACC_PUBLIC, "C", null, "java/lang/Object", null);
cv.visitEnd();
try {
cv.visitSource(null, null);
fail();
} catch (Exception e) {
}
}
public void testIllegalFieldMemberVisitAfterEnd() {
FieldVisitor fv = new CheckFieldAdapter(new EmptyVisitor());
fv.visitEnd();
try {
fv.visitAttribute(new Comment());
fail();
} catch (Exception e) {
}
}
public void testIllegalFieldAttribute() {
FieldVisitor fv = new CheckFieldAdapter(new EmptyVisitor());
try {
fv.visitAttribute(null);
fail();
} catch (Exception e) {
}
}
public void testIllegalAnnotationDesc() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
try {
mv.visitParameterAnnotation(0, "'", true);
fail();
} catch (Exception e) {
}
}
public void testIllegalAnnotationName() {
AnnotationVisitor av = new CheckAnnotationAdapter(new EmptyVisitor());
try {
av.visit(null, new Integer(0));
fail();
} catch (Exception e) {
}
}
public void testIllegalAnnotationValue() {
AnnotationVisitor av = new CheckAnnotationAdapter(new EmptyVisitor());
try {
av.visit("name", new Object());
fail();
} catch (Exception e) {
}
}
public void testIllegalAnnotationEnumValue() {
AnnotationVisitor av = new CheckAnnotationAdapter(new EmptyVisitor());
try {
av.visitEnum("name", "Lpkg/Enum;", null);
fail();
} catch (Exception e) {
}
}
public void testIllegalAnnotationValueAfterEnd() {
AnnotationVisitor av = new CheckAnnotationAdapter(new EmptyVisitor());
av.visitEnd();
try {
av.visit("name", new Integer(0));
fail();
} catch (Exception e) {
}
}
public void testIllegalMethodMemberVisitAfterEnd() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitEnd();
try {
mv.visitAttribute(new Comment());
fail();
} catch (Exception e) {
}
}
public void testIllegalMethodAttribute() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
try {
mv.visitAttribute(null);
fail();
} catch (Exception e) {
}
}
public void testIllegalMethodSignature() {
ClassVisitor cv = new CheckClassAdapter(new EmptyVisitor());
cv.visit(V1_1, ACC_PUBLIC, "C", null, "java/lang/Object", null);
try {
cv.visitMethod(ACC_PUBLIC, "m", "()V", "<T::LI.J<*+LA;>;>()V^LA;X", null);
fail();
} catch (Exception e) {
}
}
public void testIllegalMethodInsnVisitBeforeStart() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
try {
mv.visitInsn(NOP);
fail();
} catch (Exception e) {
}
}
public void testIllegalFrameType() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitFrame(123, 0, null, 0, null);
fail();
} catch (Exception e) {
}
}
public void testIllegalFrameLocalCount() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitFrame(F_SAME, 1, new Object[] { INTEGER }, 0, null);
fail();
} catch (Exception e) {
}
}
public void testIllegalFrameStackCount() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitFrame(F_SAME, 0, null, 1, new Object[] { INTEGER });
fail();
} catch (Exception e) {
}
}
public void testIllegalFrameLocalArray() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitFrame(F_APPEND, 1, new Object[0], 0, null);
fail();
} catch (Exception e) {
}
}
public void testIllegalFrameStackArray() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitFrame(F_SAME1, 0, null, 1, new Object[0]);
fail();
} catch (Exception e) {
}
}
public void testIllegalFrameValue() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitFrame(F_FULL, 1, new Object[] { "LC;" }, 0, null);
fail();
} catch (Exception e) {
}
try {
mv.visitFrame(F_FULL, 1, new Object[] { new Integer(0) }, 0, null);
fail();
} catch (Exception e) {
}
}
public void testIllegalMethodInsn() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitInsn(-1);
fail();
} catch (Exception e) {
}
}
public void testIllegalByteInsnOperand() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitIntInsn(BIPUSH, Integer.MAX_VALUE);
fail();
} catch (Exception e) {
}
}
public void testIllegalShortInsnOperand() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitIntInsn(SIPUSH, Integer.MAX_VALUE);
fail();
} catch (Exception e) {
}
}
public void testIllegalVarInsnOperand() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitVarInsn(ALOAD, -1);
fail();
} catch (Exception e) {
}
}
public void testIllegalIntInsnOperand() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitIntInsn(NEWARRAY, 0);
fail();
} catch (Exception e) {
}
}
public void testIllegalTypeInsnOperand() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitTypeInsn(NEW, "[I");
fail();
} catch (Exception e) {
}
}
public void testIllegalLabelInsnOperand() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
Label l = new Label();
mv.visitLabel(l);
try {
mv.visitLabel(l);
fail();
} catch (Exception e) {
}
}
public void testIllegalDebugLabelUse() throws IOException {
ClassReader cr = new ClassReader("java.lang.Object");
ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS);
- cr.accept(new ClassAdapter(cw) {
+ ClassVisitor cv = new ClassAdapter(cw) {
public MethodVisitor visitMethod(
int access,
String name,
String desc,
String signature,
String[] exceptions)
{
final MethodVisitor next = cv.visitMethod(access,
name,
desc,
signature,
exceptions);
if (next == null) {
return next;
}
return new MethodAdapter(new CheckMethodAdapter(next)) {
private Label entryLabel = null;
public void visitLabel(Label label) {
if (entryLabel == null) {
entryLabel = label;
}
mv.visitLabel(label);
}
public void visitMaxs(int maxStack, int maxLocals) {
Label unwindhandler = new Label();
mv.visitLabel(unwindhandler);
mv.visitInsn(Opcodes.ATHROW); // rethrow
mv.visitTryCatchBlock(entryLabel,
unwindhandler,
unwindhandler,
null);
mv.visitMaxs(maxStack, maxLocals);
}
};
}
- }, ClassReader.EXPAND_FRAMES);
+ };
+ try {
+ cr.accept(cv, ClassReader.EXPAND_FRAMES);
+ fail();
+ } catch (Exception e) {
+ }
}
public void testIllegalTableSwitchParameters1() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitTableSwitchInsn(1, 0, new Label(), new Label[0]);
fail();
} catch (Exception e) {
}
}
public void testIllegalTableSwitchParameters2() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitTableSwitchInsn(0, 1, null, new Label[0]);
fail();
} catch (Exception e) {
}
}
public void testIllegalTableSwitchParameters3() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitTableSwitchInsn(0, 1, new Label(), null);
fail();
} catch (Exception e) {
}
}
public void testIllegalTableSwitchParameters4() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitTableSwitchInsn(0, 1, new Label(), new Label[0]);
fail();
} catch (Exception e) {
}
}
public void testIllegalLookupSwitchParameters1() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitLookupSwitchInsn(new Label(), null, new Label[0]);
fail();
} catch (Exception e) {
}
}
public void testIllegalLookupSwitchParameters2() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitLookupSwitchInsn(new Label(), new int[0], null);
fail();
} catch (Exception e) {
}
}
public void testIllegalLookupSwitchParameters3() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitLookupSwitchInsn(new Label(), new int[0], new Label[1]);
fail();
} catch (Exception e) {
}
}
public void testIllegalFieldInsnNullOwner() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitFieldInsn(GETFIELD, null, "i", "I");
fail();
} catch (Exception e) {
}
}
public void testIllegalFieldInsnOwner() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitFieldInsn(GETFIELD, "-", "i", "I");
fail();
} catch (Exception e) {
}
}
public void testIllegalFieldInsnNullName() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitFieldInsn(GETFIELD, "C", null, "I");
fail();
} catch (Exception e) {
}
}
public void testIllegalFieldInsnName() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitFieldInsn(GETFIELD, "C", "-", "I");
fail();
} catch (Exception e) {
}
}
public void testIllegalFieldInsnName2() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitFieldInsn(GETFIELD, "C", "a-", "I");
fail();
} catch (Exception e) {
}
}
public void testIllegalFieldInsnNullDesc() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitFieldInsn(GETFIELD, "C", "i", null);
fail();
} catch (Exception e) {
}
}
public void testIllegalFieldInsnVoidDesc() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitFieldInsn(GETFIELD, "C", "i", "V");
fail();
} catch (Exception e) {
}
}
public void testIllegalFieldInsnPrimitiveDesc() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitFieldInsn(GETFIELD, "C", "i", "II");
fail();
} catch (Exception e) {
}
}
public void testIllegalFieldInsnArrayDesc() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitFieldInsn(GETFIELD, "C", "i", "[");
fail();
} catch (Exception e) {
}
}
public void testIllegalFieldInsnReferenceDesc() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitFieldInsn(GETFIELD, "C", "i", "L");
fail();
} catch (Exception e) {
}
}
public void testIllegalFieldInsnReferenceDesc2() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitFieldInsn(GETFIELD, "C", "i", "L-;");
fail();
} catch (Exception e) {
}
}
public void testIllegalMethodInsnNullName() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitMethodInsn(INVOKEVIRTUAL, "C", null, "()V");
fail();
} catch (Exception e) {
}
}
public void testIllegalMethodInsnName() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitMethodInsn(INVOKEVIRTUAL, "C", "-", "()V");
fail();
} catch (Exception e) {
}
}
public void testIllegalMethodInsnName2() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitMethodInsn(INVOKEVIRTUAL, "C", "a-", "()V");
fail();
} catch (Exception e) {
}
}
public void testIllegalMethodInsnNullDesc() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitMethodInsn(INVOKEVIRTUAL, "C", "m", null);
fail();
} catch (Exception e) {
}
}
public void testIllegalMethodInsnDesc() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitMethodInsn(INVOKEVIRTUAL, "C", "m", "I");
fail();
} catch (Exception e) {
}
}
public void testIllegalMethodInsnParameterDesc() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitMethodInsn(INVOKEVIRTUAL, "C", "m", "(V)V");
fail();
} catch (Exception e) {
}
}
public void testIllegalMethodInsnReturnDesc() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitMethodInsn(INVOKEVIRTUAL, "C", "m", "()VV");
fail();
} catch (Exception e) {
}
}
public void testIllegalLdcInsnOperand() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitLdcInsn(new Object());
fail();
} catch (Exception e) {
}
}
public void testIllegalMultiANewArrayDesc() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitMultiANewArrayInsn("I", 1);
fail();
} catch (Exception e) {
}
}
public void testIllegalMultiANewArrayDims() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitMultiANewArrayInsn("[[I", 0);
fail();
} catch (Exception e) {
}
}
public void testIllegalMultiANewArrayDims2() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitMultiANewArrayInsn("[[I", 3);
fail();
} catch (Exception e) {
}
}
public void testIllegalTryCatchBlock() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
Label m = new Label();
Label n = new Label();
mv.visitLabel(m);
try {
mv.visitTryCatchBlock(m, n, n, null);
fail();
} catch (Exception e) {
}
try {
mv.visitTryCatchBlock(n, m, n, null);
fail();
} catch (Exception e) {
}
try {
mv.visitTryCatchBlock(n, n, m, null);
fail();
} catch (Exception e) {
}
}
public void testIllegalLocalVariableLabels() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
Label m = new Label();
Label n = new Label();
mv.visitLabel(n);
mv.visitInsn(NOP);
mv.visitLabel(m);
try {
mv.visitLocalVariable("i", "I", null, m, n, 0);
fail();
} catch (Exception e) {
}
}
public void testIllegalLineNumerLabel() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
try {
mv.visitLineNumber(0, new Label());
fail();
} catch (Exception e) {
}
}
public void testIllegalInsnVisitAfterEnd() {
MethodVisitor mv = new CheckMethodAdapter(new EmptyVisitor());
mv.visitCode();
mv.visitMaxs(0, 0);
try {
mv.visitInsn(NOP);
fail();
} catch (Exception e) {
}
}
}
| false | true | public void testIllegalDebugLabelUse() throws IOException {
ClassReader cr = new ClassReader("java.lang.Object");
ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS);
cr.accept(new ClassAdapter(cw) {
public MethodVisitor visitMethod(
int access,
String name,
String desc,
String signature,
String[] exceptions)
{
final MethodVisitor next = cv.visitMethod(access,
name,
desc,
signature,
exceptions);
if (next == null) {
return next;
}
return new MethodAdapter(new CheckMethodAdapter(next)) {
private Label entryLabel = null;
public void visitLabel(Label label) {
if (entryLabel == null) {
entryLabel = label;
}
mv.visitLabel(label);
}
public void visitMaxs(int maxStack, int maxLocals) {
Label unwindhandler = new Label();
mv.visitLabel(unwindhandler);
mv.visitInsn(Opcodes.ATHROW); // rethrow
mv.visitTryCatchBlock(entryLabel,
unwindhandler,
unwindhandler,
null);
mv.visitMaxs(maxStack, maxLocals);
}
};
}
}, ClassReader.EXPAND_FRAMES);
}
| public void testIllegalDebugLabelUse() throws IOException {
ClassReader cr = new ClassReader("java.lang.Object");
ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS);
ClassVisitor cv = new ClassAdapter(cw) {
public MethodVisitor visitMethod(
int access,
String name,
String desc,
String signature,
String[] exceptions)
{
final MethodVisitor next = cv.visitMethod(access,
name,
desc,
signature,
exceptions);
if (next == null) {
return next;
}
return new MethodAdapter(new CheckMethodAdapter(next)) {
private Label entryLabel = null;
public void visitLabel(Label label) {
if (entryLabel == null) {
entryLabel = label;
}
mv.visitLabel(label);
}
public void visitMaxs(int maxStack, int maxLocals) {
Label unwindhandler = new Label();
mv.visitLabel(unwindhandler);
mv.visitInsn(Opcodes.ATHROW); // rethrow
mv.visitTryCatchBlock(entryLabel,
unwindhandler,
unwindhandler,
null);
mv.visitMaxs(maxStack, maxLocals);
}
};
}
};
try {
cr.accept(cv, ClassReader.EXPAND_FRAMES);
fail();
} catch (Exception e) {
}
}
|
diff --git a/flexoserver/flexoexternalbuilders/src/main/java/org/openflexo/builders/utils/FlexoBuilderProjectReferenceLoader.java b/flexoserver/flexoexternalbuilders/src/main/java/org/openflexo/builders/utils/FlexoBuilderProjectReferenceLoader.java
index 2c65e5bb1..c2077e0f6 100644
--- a/flexoserver/flexoexternalbuilders/src/main/java/org/openflexo/builders/utils/FlexoBuilderProjectReferenceLoader.java
+++ b/flexoserver/flexoexternalbuilders/src/main/java/org/openflexo/builders/utils/FlexoBuilderProjectReferenceLoader.java
@@ -1,226 +1,226 @@
package org.openflexo.builders.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.ZipException;
import org.apache.commons.io.IOUtils;
import org.openflexo.builders.FlexoExternalMain;
import org.openflexo.foundation.FlexoEditor;
import org.openflexo.foundation.rm.FlexoProject;
import org.openflexo.foundation.rm.FlexoProject.FlexoProjectReferenceLoader;
import org.openflexo.foundation.rm.FlexoProjectReference;
import org.openflexo.foundation.utils.ProjectInitializerException;
import org.openflexo.foundation.utils.ProjectLoadingCancelledException;
import org.openflexo.module.ProjectLoader;
import org.openflexo.toolbox.FileUtils;
import org.openflexo.toolbox.ZipUtils;
public class FlexoBuilderProjectReferenceLoader implements FlexoProjectReferenceLoader {
private String serverURL;
private String login;
private String password;
private final FlexoExternalMain externalMain;
private final ProjectLoader projectLoader;
public FlexoBuilderProjectReferenceLoader(FlexoExternalMain externalMain, ProjectLoader projectLoader, String serverURL, String login,
String password) {
super();
this.externalMain = externalMain;
this.projectLoader = projectLoader;
this.serverURL = serverURL;
this.login = login;
this.password = password;
}
@Override
public FlexoProject loadProject(FlexoProjectReference reference, boolean silentlyOnly) {
FlexoEditor editor = projectLoader.editorForProjectURIAndRevision(reference.getURI(), reference.getRevision());
if (editor != null) {
return editor.getProject();
}
if (serverURL != null && login != null && password != null) {
Map<String, String> param = new HashMap<String, String>();
param.put("login", login);
param.put("password", password);
param.put("uri", reference.getURI());
param.put("revision", String.valueOf(reference.getRevision()));
StringBuilder paramsAsString = new StringBuilder();
if (param != null && param.size() > 0) {
boolean first = true;
for (Entry<String, String> e : param.entrySet()) {
- paramsAsString.append(first ? "?" : "&");
+ paramsAsString.append(first ? "" : "&");
try {
paramsAsString.append(URLEncoder.encode(e.getKey(), "UTF-8")).append("=")
.append(URLEncoder.encode(e.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
first = false;
}
}
// Create a URL for the desired page
URL url;
try {
url = new URL(serverURL);
} catch (MalformedURLException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because server URL seems misconfigured: '" + serverURL + "'" + ".\n(" + e.getMessage() + ")");
return null;
}
HttpURLConnection conn;
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker cannot access server URL '" + url.toString() + "'" + ".\n(" + e.getMessage() + ")");
return null;
}
try {
conn.setRequestMethod("POST");
} catch (ProtocolException e) {
e.printStackTrace();
// Should never happen
}
conn.setDoOutput(true);
OutputStreamWriter wr;
try {
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(paramsAsString.toString());
wr.flush();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker cannot open server URL '" + url.toString() + "'" + ".\n(" + e.getMessage() + ")");
return null;
}
// Read all the text returned by the server
int httpStatus;
try {
httpStatus = conn.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not read HTTP response code for server URL '" + url.toString() + "'.\n(" + e.getMessage()
+ ")");
return null;
}
InputStream inputStream;
if (httpStatus < 400) {
try {
inputStream = conn.getInputStream();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not read data for server URL '" + url.toString() + "'.\n(" + e.getMessage() + ")"
+ "\nStatus: " + httpStatus);
return null;
}
String base = "Projects/" + reference.getName() + "_" + reference.getVersion();
File file = new File(externalMain.getWorkingDir(), base + ".zip");
int i = 0;
while (file.exists()) {
file = new File(externalMain.getWorkingDir(), base + "-" + i++ + ".zip");
}
file.getParentFile().mkdirs();
try {
FileUtils.saveToFile(file, inputStream);
} catch (IOException e) {
e.printStackTrace();
}
base = "ExtractedProjects/" + reference.getName() + "_" + reference.getVersion();
File extractionDirectory = new File(externalMain.getWorkingDir(), base);
i = 0;
while (extractionDirectory.exists()) {
extractionDirectory = new File(externalMain.getWorkingDir(), base + "-" + i++);
}
extractionDirectory.mkdirs();
try {
ZipUtils.unzip(file, extractionDirectory);
} catch (ZipException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not read the zip file returned by server URL '" + url.toString() + "'.\n("
+ e.getMessage() + ")");
return null;
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not extract the zip file returned by server URL '" + url.toString()
+ "' to the directory " + extractionDirectory.getAbsolutePath() + ".\n(" + e.getMessage() + ")");
return null;
}
File projectDirectory = FlexoExternalMain.searchProjectDirectory(extractionDirectory);
if (projectDirectory == null) {
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not find a project in the directory " + extractionDirectory.getAbsolutePath() + ".");
return null;
}
try {
editor = projectLoader.loadProject(projectDirectory, true);
} catch (ProjectLoadingCancelledException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because project loading was cancelled for directory " + projectDirectory.getAbsolutePath() + ".\n("
+ e.getMessage() + ")");
return null;
} catch (ProjectInitializerException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because project loading failed for directory " + projectDirectory.getAbsolutePath() + ".\n("
+ e.getMessage() + ")");
return null;
}
if (editor != null) {
return editor.getProject();
} else {
externalMain.reportMessage("Unable to load project " + reference.getName() + " " + reference.getVersion()
+ " located at " + projectDirectory.getAbsolutePath() + ".");
return null;
}
} else {
inputStream = conn.getErrorStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String str;
StringBuilder reply = new StringBuilder();
try {
while ((str = in.readLine()) != null) {
reply.append(str).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(wr);
IOUtils.closeQuietly(in);
}
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because an error occured for server URL '" + url.toString() + "'" + ".\nStatus: " + httpStatus + "\n"
+ reply.toString());
return null;
}
} else {
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because information and credentials are incomplete (server URL=" + serverURL + " login="
+ (login != null ? "OK" : "null") + " password=" + (password != null ? "OK" : "null"));
return null;
}
}
}
| true | true | public FlexoProject loadProject(FlexoProjectReference reference, boolean silentlyOnly) {
FlexoEditor editor = projectLoader.editorForProjectURIAndRevision(reference.getURI(), reference.getRevision());
if (editor != null) {
return editor.getProject();
}
if (serverURL != null && login != null && password != null) {
Map<String, String> param = new HashMap<String, String>();
param.put("login", login);
param.put("password", password);
param.put("uri", reference.getURI());
param.put("revision", String.valueOf(reference.getRevision()));
StringBuilder paramsAsString = new StringBuilder();
if (param != null && param.size() > 0) {
boolean first = true;
for (Entry<String, String> e : param.entrySet()) {
paramsAsString.append(first ? "?" : "&");
try {
paramsAsString.append(URLEncoder.encode(e.getKey(), "UTF-8")).append("=")
.append(URLEncoder.encode(e.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
first = false;
}
}
// Create a URL for the desired page
URL url;
try {
url = new URL(serverURL);
} catch (MalformedURLException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because server URL seems misconfigured: '" + serverURL + "'" + ".\n(" + e.getMessage() + ")");
return null;
}
HttpURLConnection conn;
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker cannot access server URL '" + url.toString() + "'" + ".\n(" + e.getMessage() + ")");
return null;
}
try {
conn.setRequestMethod("POST");
} catch (ProtocolException e) {
e.printStackTrace();
// Should never happen
}
conn.setDoOutput(true);
OutputStreamWriter wr;
try {
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(paramsAsString.toString());
wr.flush();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker cannot open server URL '" + url.toString() + "'" + ".\n(" + e.getMessage() + ")");
return null;
}
// Read all the text returned by the server
int httpStatus;
try {
httpStatus = conn.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not read HTTP response code for server URL '" + url.toString() + "'.\n(" + e.getMessage()
+ ")");
return null;
}
InputStream inputStream;
if (httpStatus < 400) {
try {
inputStream = conn.getInputStream();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not read data for server URL '" + url.toString() + "'.\n(" + e.getMessage() + ")"
+ "\nStatus: " + httpStatus);
return null;
}
String base = "Projects/" + reference.getName() + "_" + reference.getVersion();
File file = new File(externalMain.getWorkingDir(), base + ".zip");
int i = 0;
while (file.exists()) {
file = new File(externalMain.getWorkingDir(), base + "-" + i++ + ".zip");
}
file.getParentFile().mkdirs();
try {
FileUtils.saveToFile(file, inputStream);
} catch (IOException e) {
e.printStackTrace();
}
base = "ExtractedProjects/" + reference.getName() + "_" + reference.getVersion();
File extractionDirectory = new File(externalMain.getWorkingDir(), base);
i = 0;
while (extractionDirectory.exists()) {
extractionDirectory = new File(externalMain.getWorkingDir(), base + "-" + i++);
}
extractionDirectory.mkdirs();
try {
ZipUtils.unzip(file, extractionDirectory);
} catch (ZipException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not read the zip file returned by server URL '" + url.toString() + "'.\n("
+ e.getMessage() + ")");
return null;
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not extract the zip file returned by server URL '" + url.toString()
+ "' to the directory " + extractionDirectory.getAbsolutePath() + ".\n(" + e.getMessage() + ")");
return null;
}
File projectDirectory = FlexoExternalMain.searchProjectDirectory(extractionDirectory);
if (projectDirectory == null) {
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not find a project in the directory " + extractionDirectory.getAbsolutePath() + ".");
return null;
}
try {
editor = projectLoader.loadProject(projectDirectory, true);
} catch (ProjectLoadingCancelledException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because project loading was cancelled for directory " + projectDirectory.getAbsolutePath() + ".\n("
+ e.getMessage() + ")");
return null;
} catch (ProjectInitializerException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because project loading failed for directory " + projectDirectory.getAbsolutePath() + ".\n("
+ e.getMessage() + ")");
return null;
}
if (editor != null) {
return editor.getProject();
} else {
externalMain.reportMessage("Unable to load project " + reference.getName() + " " + reference.getVersion()
+ " located at " + projectDirectory.getAbsolutePath() + ".");
return null;
}
} else {
inputStream = conn.getErrorStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String str;
StringBuilder reply = new StringBuilder();
try {
while ((str = in.readLine()) != null) {
reply.append(str).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(wr);
IOUtils.closeQuietly(in);
}
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because an error occured for server URL '" + url.toString() + "'" + ".\nStatus: " + httpStatus + "\n"
+ reply.toString());
return null;
}
} else {
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because information and credentials are incomplete (server URL=" + serverURL + " login="
+ (login != null ? "OK" : "null") + " password=" + (password != null ? "OK" : "null"));
return null;
}
}
| public FlexoProject loadProject(FlexoProjectReference reference, boolean silentlyOnly) {
FlexoEditor editor = projectLoader.editorForProjectURIAndRevision(reference.getURI(), reference.getRevision());
if (editor != null) {
return editor.getProject();
}
if (serverURL != null && login != null && password != null) {
Map<String, String> param = new HashMap<String, String>();
param.put("login", login);
param.put("password", password);
param.put("uri", reference.getURI());
param.put("revision", String.valueOf(reference.getRevision()));
StringBuilder paramsAsString = new StringBuilder();
if (param != null && param.size() > 0) {
boolean first = true;
for (Entry<String, String> e : param.entrySet()) {
paramsAsString.append(first ? "" : "&");
try {
paramsAsString.append(URLEncoder.encode(e.getKey(), "UTF-8")).append("=")
.append(URLEncoder.encode(e.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
first = false;
}
}
// Create a URL for the desired page
URL url;
try {
url = new URL(serverURL);
} catch (MalformedURLException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because server URL seems misconfigured: '" + serverURL + "'" + ".\n(" + e.getMessage() + ")");
return null;
}
HttpURLConnection conn;
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker cannot access server URL '" + url.toString() + "'" + ".\n(" + e.getMessage() + ")");
return null;
}
try {
conn.setRequestMethod("POST");
} catch (ProtocolException e) {
e.printStackTrace();
// Should never happen
}
conn.setDoOutput(true);
OutputStreamWriter wr;
try {
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(paramsAsString.toString());
wr.flush();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker cannot open server URL '" + url.toString() + "'" + ".\n(" + e.getMessage() + ")");
return null;
}
// Read all the text returned by the server
int httpStatus;
try {
httpStatus = conn.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not read HTTP response code for server URL '" + url.toString() + "'.\n(" + e.getMessage()
+ ")");
return null;
}
InputStream inputStream;
if (httpStatus < 400) {
try {
inputStream = conn.getInputStream();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not read data for server URL '" + url.toString() + "'.\n(" + e.getMessage() + ")"
+ "\nStatus: " + httpStatus);
return null;
}
String base = "Projects/" + reference.getName() + "_" + reference.getVersion();
File file = new File(externalMain.getWorkingDir(), base + ".zip");
int i = 0;
while (file.exists()) {
file = new File(externalMain.getWorkingDir(), base + "-" + i++ + ".zip");
}
file.getParentFile().mkdirs();
try {
FileUtils.saveToFile(file, inputStream);
} catch (IOException e) {
e.printStackTrace();
}
base = "ExtractedProjects/" + reference.getName() + "_" + reference.getVersion();
File extractionDirectory = new File(externalMain.getWorkingDir(), base);
i = 0;
while (extractionDirectory.exists()) {
extractionDirectory = new File(externalMain.getWorkingDir(), base + "-" + i++);
}
extractionDirectory.mkdirs();
try {
ZipUtils.unzip(file, extractionDirectory);
} catch (ZipException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not read the zip file returned by server URL '" + url.toString() + "'.\n("
+ e.getMessage() + ")");
return null;
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not extract the zip file returned by server URL '" + url.toString()
+ "' to the directory " + extractionDirectory.getAbsolutePath() + ".\n(" + e.getMessage() + ")");
return null;
}
File projectDirectory = FlexoExternalMain.searchProjectDirectory(extractionDirectory);
if (projectDirectory == null) {
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not find a project in the directory " + extractionDirectory.getAbsolutePath() + ".");
return null;
}
try {
editor = projectLoader.loadProject(projectDirectory, true);
} catch (ProjectLoadingCancelledException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because project loading was cancelled for directory " + projectDirectory.getAbsolutePath() + ".\n("
+ e.getMessage() + ")");
return null;
} catch (ProjectInitializerException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because project loading failed for directory " + projectDirectory.getAbsolutePath() + ".\n("
+ e.getMessage() + ")");
return null;
}
if (editor != null) {
return editor.getProject();
} else {
externalMain.reportMessage("Unable to load project " + reference.getName() + " " + reference.getVersion()
+ " located at " + projectDirectory.getAbsolutePath() + ".");
return null;
}
} else {
inputStream = conn.getErrorStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String str;
StringBuilder reply = new StringBuilder();
try {
while ((str = in.readLine()) != null) {
reply.append(str).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(wr);
IOUtils.closeQuietly(in);
}
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because an error occured for server URL '" + url.toString() + "'" + ".\nStatus: " + httpStatus + "\n"
+ reply.toString());
return null;
}
} else {
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because information and credentials are incomplete (server URL=" + serverURL + " login="
+ (login != null ? "OK" : "null") + " password=" + (password != null ? "OK" : "null"));
return null;
}
}
|
diff --git a/test-modules/webservice-test/src/test/java/org/openlmis/functional/FacilityFeed.java b/test-modules/webservice-test/src/test/java/org/openlmis/functional/FacilityFeed.java
index e7e11a7d43..5c4e5404e4 100644
--- a/test-modules/webservice-test/src/test/java/org/openlmis/functional/FacilityFeed.java
+++ b/test-modules/webservice-test/src/test/java/org/openlmis/functional/FacilityFeed.java
@@ -1,474 +1,474 @@
/*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2013 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses. For additional information contact [email protected].
*/
package org.openlmis.functional;
import org.apache.commons.lang3.StringUtils;
import org.openlmis.UiUtils.HttpClient;
import org.openlmis.UiUtils.ResponseEntity;
import org.openlmis.pageobjects.HomePage;
import org.openlmis.pageobjects.LoginPage;
import org.openlmis.pageobjects.ManageFacilityPage;
import org.openlmis.pageobjects.UploadPage;
import org.openlmis.restapi.domain.Agent;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import static com.thoughtworks.selenium.SeleneseTestBase.*;
public class FacilityFeed extends JsonUtility {
public static final String FULL_JSON_TXT_FILE_NAME = "AgentValid.txt";
public static final String CREATE_URL = "http://localhost:9091/rest-api/agents.json";
public static final String UPDATE_URL = "http://localhost:9091/rest-api/agents/";
public static final String commTrackUser = "commTrack";
public static final String PHONE_NUMBER = "0099887766";
public static final String DEFAULT_AGENT_NAME = "Agent A1";
public static final String DEFAULT_PARENT_FACILITY_CODE = "F10";
public static final String ACTIVE_STATUS = "true";
public static final String DEFAULT_AGENT_CODE = "A2";
public static final String JSON_EXTENSION = ".json";
public static final String POST = "POST";
public static final String PUT = "PUT";
public static final String FACILITY_FEED_URL = "http://localhost:9091/feeds/facilities/recent";
@BeforeMethod(groups = {"webservice","webserviceSmoke"})
public void setUp() throws Exception {
super.setup();
super.setupTestData(true);
dbWrapper.updateRestrictLogin("commTrack", true);
}
@AfterMethod(groups = {"webservice","webserviceSmoke"})
public void tearDown() throws Exception {
dbWrapper.deleteData();
dbWrapper.closeConnection();
}
@Test(groups = {"webservice"}, dataProvider = "Data-Provider-Function-Positive")
public void testFacilityFeedUsingUI(String user, String program, String[] credentials) throws Exception {
HttpClient client = new HttpClient();
client.createContext();
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
dbWrapper.insertUser("200", user, "Ag/myf1Whs0fxr1FFfK8cs3q/VJ1qMs3yuMLDTeEcZEGzstj/waaUsQNQTIKk1U5JRzrDbPLCzCO1/vB5YGaEQ==", "F10", "[email protected]");
HomePage homePage = loginPage.loginAs(credentials[0], credentials[1]);
ManageFacilityPage manageFacilityPage = homePage.navigateCreateFacility();
homePage.clickCreateFacilityButton();
String geoZone = "Ngorongoro";
String facilityType = "Lvl3 Hospital";
String operatedBy = "MoH";
String facilityCodePrefix = "FCcode";
String facilityNamePrefix = "FCname";
String catchmentPopulationValue = "100";
String date_time = manageFacilityPage.enterValuesInFacilityAndClickSave(facilityCodePrefix, facilityNamePrefix, program, geoZone, facilityType, operatedBy, catchmentPopulationValue);
manageFacilityPage.verifyMessageOnFacilityScreen(facilityNamePrefix + date_time, "created");
ResponseEntity responseEntity = client.SendJSON("", FACILITY_FEED_URL, "GET", "", "");
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"code\":\"" + facilityCodePrefix + date_time + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"name\":\"" + facilityNamePrefix + date_time + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"facilityType\":\"" + facilityType + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"description\":\"Testing description\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"mainPhone\":\"9711231305\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"fax\":\"9711231305\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"address1\":\"Address1\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"address2\":\"Address2\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"geographicZone\":\"" + geoZone + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"catchmentPopulation\":" + catchmentPopulationValue + ""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"latitude\":-555.5555"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"longitude\":444.4444"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"altitude\":4545.4545"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"operatedBy\":\"" + operatedBy + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"coldStorageGrossCapacity\":3434.3434"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"coldStorageNetCapacity\":3535.3535"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"suppliesOthers\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectricity\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectronicSCC\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectronicDAR\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"active\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"virtualFacility\":false"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"comment\":\"Comments\""));
- assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"stringGoLiveDate\":\"25-12-2013\""));
- assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"stringGoDownDate\":\"26-12-2013"));
+ assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"stringGoLiveDate\":\"25-01-2014\""));
+ assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"stringGoDownDate\":\"26-01-2014"));
homePage.navigateSearchFacility();
manageFacilityPage.searchFacility(date_time);
manageFacilityPage.clickFacilityList(date_time);
manageFacilityPage.disableFacility(facilityCodePrefix + date_time, facilityNamePrefix + date_time);
manageFacilityPage.verifyDisabledFacility(facilityCodePrefix + date_time, facilityNamePrefix + date_time);
manageFacilityPage.enableFacility();
manageFacilityPage.verifyEnabledFacility();
responseEntity = client.SendJSON("", FACILITY_FEED_URL, "GET", "", "");
List<String> feedJSONList = XmlUtils.getNodeValues(responseEntity.getResponse(), "content");
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"active\":true"));
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"enabled\":true"));
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"sdp\":true"));
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"online\":true"));
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"gln\":\"Testing Gln\""));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"active\":false"));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"enabled\":false"));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"facilityType\":\"" + facilityType + "\""));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"operatedBy\":\"" + operatedBy + "\""));
assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"active\":false"));
assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"enabled\":true"));
assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"facilityType\":\"" + facilityType + "\""));
assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"operatedBy\":\"" + operatedBy + "\""));
manageFacilityPage = homePage.navigateSearchFacility();
manageFacilityPage.searchFacility(date_time);
manageFacilityPage.clickFacilityList(date_time);
manageFacilityPage.addProgram("VACCINES", true);
manageFacilityPage.saveFacility();
Thread.sleep(5000);
assertEquals(3, feedJSONList.size());
manageFacilityPage = homePage.navigateSearchFacility();
manageFacilityPage.searchFacility(date_time);
manageFacilityPage.clickFacilityList(date_time);
manageFacilityPage.removeFirstProgram();
manageFacilityPage.saveFacility();
Thread.sleep(5000);
assertEquals(3, feedJSONList.size());
homePage.logout(baseUrlGlobal);
}
@Test(groups = {"webservice"}, dataProvider = "Data-Provider-Function-Credentials")
public void shouldVerifyFacilityFeedForFacilityUpload(String[] credentials) throws Exception {
HttpClient client = new HttpClient();
client.createContext();
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
String geoZone = "virtualgeozone";
String facilityType = "Lvl3 Hospital";
String operatedBy = "MoH";
String facilityCodePrefix = "facilityf10";
String facilityNamePrefix = "facilityf10 Village Dispensary";
String facilityCodeUpdatedPrefix = "facilityf11";
String facilityNameUpdatedPrefix = "facilityf11 Village Dispensary";
String catchmentPopulationValue = "100";
String catchmentPopulationUpdatedValue = "9999999";
HomePage homePage = loginPage.loginAs(credentials[0], credentials[1]);
UploadPage uploadPage = homePage.navigateUploads();
uploadPage.uploadAndVerifyGeographicZone("QA_Geographic_Data_WebService.csv");
uploadPage.verifySuccessMessageOnUploadScreen();
uploadPage.uploadFacilities("QA_facilities_WebService.csv");
uploadPage.verifySuccessMessageOnUploadScreen();
ResponseEntity responseEntity = client.SendJSON("", FACILITY_FEED_URL, "GET", "", "");
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"code\":\"" + facilityCodePrefix + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"name\":\"" + facilityNamePrefix + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"facilityType\":\"" + facilityType + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"description\":\"IT department\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"mainPhone\":\"9711231305\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"fax\":\"9711231305\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"address1\":\"Address1\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"address2\":\"Address2\","));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"geographicZone\":\"" + geoZone + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"catchmentPopulation\":" + catchmentPopulationValue + ""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"latitude\":-555.5555"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"longitude\":444.4444"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"altitude\":4545.4545"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"operatedBy\":\"" + operatedBy + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"coldStorageGrossCapacity\":3434.3434"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"coldStorageNetCapacity\":3535.3535"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"suppliesOthers\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectricity\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectronicSCC\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectronicDAR\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"active\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"goLiveDate\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"goDownDate\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"stringGoLiveDate\":\"11-11-2012\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"stringGoDownDate\":\"11-11-1887"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"satellite\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"virtualFacility\":false"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"comment\":\"fc\""));
uploadPage.uploadFacilities("QA_facilities_Subsequent_WebService.csv");
uploadPage.verifySuccessMessageOnUploadScreen();
ResponseEntity responseEntityUpdated = client.SendJSON("", FACILITY_FEED_URL, "GET", "", "");
List<String> feedJSONList = XmlUtils.getNodeValues(responseEntityUpdated.getResponse(), "content");
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"code\":\"" + facilityCodeUpdatedPrefix + "\""));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"name\":\"" + facilityNameUpdatedPrefix + "\""));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"catchmentPopulation\":" + catchmentPopulationUpdatedValue));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"active\":false"));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"sdp\":true"));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"online\":true"));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"gln\":\"G7645\""));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"enabled\":true"));
homePage.logout(baseUrlGlobal);
}
@Test(groups = {"webserviceSmoke"})
public void testFacilityFeedUsingCommTrack() throws Exception {
HttpClient client = new HttpClient();
client.createContext();
Agent agentJson = readObjectFromFile(FULL_JSON_TXT_FILE_NAME, Agent.class);
agentJson.setAgentCode(DEFAULT_AGENT_CODE);
agentJson.setAgentName(DEFAULT_AGENT_NAME);
agentJson.setParentFacilityCode(DEFAULT_PARENT_FACILITY_CODE);
agentJson.setPhoneNumber(PHONE_NUMBER);
agentJson.setActive(ACTIVE_STATUS);
client.SendJSON(getJsonStringFor(agentJson),
CREATE_URL,
POST,
commTrackUser,
"Admin123");
String stringGoLiveDate = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
ResponseEntity responseEntity = client.SendJSON("", FACILITY_FEED_URL, "GET", "", "");
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"code\":\"" + DEFAULT_AGENT_CODE + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"name\":\"" + DEFAULT_AGENT_NAME + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"facilityType\":\"Lvl3 Hospital\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"mainPhone\":\"" + PHONE_NUMBER + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"geographicZone\":\"Ngorongoro\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"active\":" + ACTIVE_STATUS + ""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"stringGoLiveDate\":\"" + stringGoLiveDate + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"goLiveDate\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"virtualFacility\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"parentFacility\":\"" + DEFAULT_PARENT_FACILITY_CODE + "\""));
assertFalse("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"facilityIsOnline\":"));
assertFalse("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectricity\":"));
assertFalse("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectronicSCC\":"));
assertFalse("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectronicDAR\":"));
assertFalse("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"satelliteFacility\":"));
assertEquals(StringUtils.countMatches(responseEntity.getResponse(), ":"), 29);
agentJson.setActive("false");
client.SendJSON(getJsonStringFor(agentJson),
UPDATE_URL + DEFAULT_AGENT_CODE + JSON_EXTENSION,
PUT,
commTrackUser,
"Admin123");
ResponseEntity responseEntityUpdated = client.SendJSON("", FACILITY_FEED_URL, "GET", "", "");
assertTrue("Response entity : " + responseEntityUpdated.getResponse(), responseEntityUpdated.getResponse().contains("\"active\":false"));
assertFalse("Response entity : " + responseEntityUpdated.getResponse(), responseEntityUpdated.getResponse().contains("\"facilityIsOnline\":"));
assertFalse("Response entity : " + responseEntityUpdated.getResponse(), responseEntityUpdated.getResponse().contains("\"hasElectricity\":"));
assertFalse("Response entity : " + responseEntityUpdated.getResponse(), responseEntityUpdated.getResponse().contains("\"hasElectronicSCC\":"));
assertFalse("Response entity : " + responseEntityUpdated.getResponse(), responseEntityUpdated.getResponse().contains("\"hasElectronicDAR\":"));
assertFalse("Response entity : " + responseEntityUpdated.getResponse(), responseEntityUpdated.getResponse().contains("\"satelliteFacility\":"));
List<String> feedJSONList = XmlUtils.getNodeValues(responseEntityUpdated.getResponse(), "content");
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"active\":true"));
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"enabled\":true"));
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"sdp\":true"));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"active\":false"));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"enabled\":true"));
}
@Test(groups = {"webservice"})
public void testFacilityFeedUsingCommTrackWithoutHeaders() throws Exception {
HttpClient client = new HttpClient();
client.createContext();
Agent agentJson = readObjectFromFile(FULL_JSON_TXT_FILE_NAME, Agent.class);
agentJson.setAgentCode(DEFAULT_AGENT_CODE);
agentJson.setAgentName(DEFAULT_AGENT_NAME);
agentJson.setParentFacilityCode(DEFAULT_PARENT_FACILITY_CODE);
agentJson.setPhoneNumber(PHONE_NUMBER);
agentJson.setActive(ACTIVE_STATUS);
ResponseEntity responseEntity = client.SendJSONWithoutHeaders(getJsonStringFor(agentJson),
CREATE_URL,
POST,
"",
"");
assertTrue("Showing response as : " + responseEntity.getStatus(), responseEntity.getStatus() == 401);
}
@Test(groups = {"webserviceSmoke"})
public void testFacilityFeedUsingCommTrackUsingOpenLmisVendor() throws Exception {
HttpClient client = new HttpClient();
client.createContext();
Agent agentJson = readObjectFromFile(FULL_JSON_TXT_FILE_NAME, Agent.class);
agentJson.setAgentCode(DEFAULT_AGENT_CODE);
agentJson.setAgentName(DEFAULT_AGENT_NAME);
agentJson.setParentFacilityCode(DEFAULT_PARENT_FACILITY_CODE);
agentJson.setPhoneNumber(PHONE_NUMBER);
agentJson.setActive(ACTIVE_STATUS);
client.SendJSON(getJsonStringFor(agentJson),
CREATE_URL,
POST,
commTrackUser,
"Admin123");
ResponseEntity responseEntity = client.SendJSON("", FACILITY_FEED_URL + "?vendor=openlmis", "GET", "", "");
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"code\":\"" + DEFAULT_AGENT_CODE + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"name\":\"" + DEFAULT_AGENT_NAME + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"facilityType\":\"Lvl3 Hospital\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"mainPhone\":\"" + PHONE_NUMBER + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"geographicZone\":\"Ngorongoro\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"active\":" + ACTIVE_STATUS + ""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"goLiveDate\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"virtualFacility\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"parentFacility\":\"" + DEFAULT_PARENT_FACILITY_CODE + "\""));
agentJson.setActive("false");
client.SendJSON(getJsonStringFor(agentJson),
UPDATE_URL + DEFAULT_AGENT_CODE + JSON_EXTENSION,
PUT,
commTrackUser,
"Admin123");
ResponseEntity responseEntityUpdated = client.SendJSON("", FACILITY_FEED_URL + "?vendor=openlmis", "GET", "", "");
assertTrue("Response entity : " + responseEntityUpdated.getResponse(), responseEntityUpdated.getResponse().contains("\"active\":false"));
List<String> feedJSONList = XmlUtils.getNodeValues(responseEntityUpdated.getResponse(), "content");
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"active\":true"));
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"enabled\":true"));
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"sdp\":true"));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"active\":false"));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"enabled\":true"));
}
@Test(groups = {"webservice"})
public void testFacilityFeedUsingCommTrackUsingInvalidVendor() throws Exception {
HttpClient client = new HttpClient();
client.createContext();
Agent agentJson = readObjectFromFile(FULL_JSON_TXT_FILE_NAME, Agent.class);
agentJson.setAgentCode(DEFAULT_AGENT_CODE);
agentJson.setAgentName(DEFAULT_AGENT_NAME);
agentJson.setParentFacilityCode(DEFAULT_PARENT_FACILITY_CODE);
agentJson.setPhoneNumber(PHONE_NUMBER);
agentJson.setActive(ACTIVE_STATUS);
client.SendJSON(getJsonStringFor(agentJson),
CREATE_URL,
POST,
commTrackUser,
"Admin123");
ResponseEntity responseEntity = client.SendJSON("", FACILITY_FEED_URL + "?vendor=testing", "GET", "", "");
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"code\":\"" + DEFAULT_AGENT_CODE + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"name\":\"" + DEFAULT_AGENT_NAME + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"facilityType\":\"Lvl3 Hospital\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"mainPhone\":\"" + PHONE_NUMBER + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"geographicZone\":\"Ngorongoro\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"active\":" + ACTIVE_STATUS + ""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"goLiveDate\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"virtualFacility\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"parentFacility\":\"" + DEFAULT_PARENT_FACILITY_CODE + "\""));
agentJson.setActive("false");
client.SendJSON(getJsonStringFor(agentJson),
UPDATE_URL + DEFAULT_AGENT_CODE + JSON_EXTENSION,
PUT,
commTrackUser,
"Admin123");
ResponseEntity responseEntityUpdated = client.SendJSON("", FACILITY_FEED_URL + "?vendor=testing", "GET", "", "");
assertTrue("Response entity : " + responseEntityUpdated.getResponse(), responseEntityUpdated.getResponse().contains("\"active\":false"));
List<String> feedJSONList = XmlUtils.getNodeValues(responseEntityUpdated.getResponse(), "content");
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"active\":true"));
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"enabled\":true"));
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"sdp\":true"));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"active\":false"));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"enabled\":true"));
}
@Test(groups = {"webservice"})
public void testFacilityFeedForCommTrackVendorSpecificInfo() throws Exception {
HttpClient client = new HttpClient();
client.createContext();
Agent agentJson = readObjectFromFile(FULL_JSON_TXT_FILE_NAME, Agent.class);
agentJson.setAgentCode(DEFAULT_AGENT_CODE);
agentJson.setAgentName(DEFAULT_AGENT_NAME);
agentJson.setParentFacilityCode(DEFAULT_PARENT_FACILITY_CODE);
agentJson.setPhoneNumber(PHONE_NUMBER);
agentJson.setActive(ACTIVE_STATUS);
client.SendJSON(getJsonStringFor(agentJson),
CREATE_URL,
POST,
commTrackUser,
"Admin123");
ResponseEntity responseEntity = client.SendJSON("", FACILITY_FEED_URL + "?vendor=commtrack", "GET", "", "");
String response = responseEntity.getResponse();
assertTrue("Response entity : " + response, response.contains("\"facilityCode\":\"" + DEFAULT_AGENT_CODE + "\""));
assertTrue("Response entity : " + response, response.contains("\"facilityName\":\"" + DEFAULT_AGENT_NAME + "\""));
assertTrue("Response entity : " + response, response.contains("\"facilityType\":\"Lvl3 Hospital\""));
assertTrue("Response entity : " + response, response.contains("\"facilityMainPhone\":\"" + PHONE_NUMBER + "\""));
assertTrue("Response entity : " + response, response.contains("\"geographicZone\":\"Ngorongoro\""));
assertTrue("Response entity : " + response, response.contains("\"facilityIsActive\":" + ACTIVE_STATUS + ""));
assertTrue("Response entity : " + response, response.contains("\"facilityGoLiveDate\""));
assertTrue("Response entity : " + response, response.contains("\"facilityIsVirtual\":true"));
assertTrue("Response entity : " + response, response.contains("\"parentFacilityCode\":\"" + DEFAULT_PARENT_FACILITY_CODE + "\""));
agentJson.setActive("false");
client.SendJSON(getJsonStringFor(agentJson),
UPDATE_URL + DEFAULT_AGENT_CODE + JSON_EXTENSION,
PUT,
commTrackUser,
"Admin123");
ResponseEntity responseEntityUpdated = client.SendJSON("", FACILITY_FEED_URL + "?vendor=commtrack", "GET", "", "");
assertTrue("Response entity : " + responseEntityUpdated.getResponse(), responseEntityUpdated.getResponse().contains("\"facilityIsActive\":false"));
List<String> feedJSONList = XmlUtils.getNodeValues(responseEntityUpdated.getResponse(), "content");
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"facilityIsActive\":true"));
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"enabled\":true"));
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"facilityIsSDP\":true"));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"facilityIsActive\":false"));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"enabled\":true"));
}
@DataProvider(name = "Data-Provider-Function-Positive")
public Object[][] parameterIntTestProviderPositive() {
return new Object[][]{
{"User123", "HIV", new String[]{"Admin123", "Admin123"}}
};
}
@DataProvider(name = "Data-Provider-Function-Credentials")
public Object[][] parameterIntTestProviderCredentials() {
return new Object[][]{
{new String[]{"Admin123", "Admin123"}}
};
}
}
| true | true | public void testFacilityFeedUsingUI(String user, String program, String[] credentials) throws Exception {
HttpClient client = new HttpClient();
client.createContext();
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
dbWrapper.insertUser("200", user, "Ag/myf1Whs0fxr1FFfK8cs3q/VJ1qMs3yuMLDTeEcZEGzstj/waaUsQNQTIKk1U5JRzrDbPLCzCO1/vB5YGaEQ==", "F10", "[email protected]");
HomePage homePage = loginPage.loginAs(credentials[0], credentials[1]);
ManageFacilityPage manageFacilityPage = homePage.navigateCreateFacility();
homePage.clickCreateFacilityButton();
String geoZone = "Ngorongoro";
String facilityType = "Lvl3 Hospital";
String operatedBy = "MoH";
String facilityCodePrefix = "FCcode";
String facilityNamePrefix = "FCname";
String catchmentPopulationValue = "100";
String date_time = manageFacilityPage.enterValuesInFacilityAndClickSave(facilityCodePrefix, facilityNamePrefix, program, geoZone, facilityType, operatedBy, catchmentPopulationValue);
manageFacilityPage.verifyMessageOnFacilityScreen(facilityNamePrefix + date_time, "created");
ResponseEntity responseEntity = client.SendJSON("", FACILITY_FEED_URL, "GET", "", "");
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"code\":\"" + facilityCodePrefix + date_time + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"name\":\"" + facilityNamePrefix + date_time + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"facilityType\":\"" + facilityType + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"description\":\"Testing description\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"mainPhone\":\"9711231305\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"fax\":\"9711231305\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"address1\":\"Address1\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"address2\":\"Address2\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"geographicZone\":\"" + geoZone + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"catchmentPopulation\":" + catchmentPopulationValue + ""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"latitude\":-555.5555"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"longitude\":444.4444"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"altitude\":4545.4545"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"operatedBy\":\"" + operatedBy + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"coldStorageGrossCapacity\":3434.3434"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"coldStorageNetCapacity\":3535.3535"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"suppliesOthers\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectricity\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectronicSCC\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectronicDAR\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"active\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"virtualFacility\":false"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"comment\":\"Comments\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"stringGoLiveDate\":\"25-12-2013\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"stringGoDownDate\":\"26-12-2013"));
homePage.navigateSearchFacility();
manageFacilityPage.searchFacility(date_time);
manageFacilityPage.clickFacilityList(date_time);
manageFacilityPage.disableFacility(facilityCodePrefix + date_time, facilityNamePrefix + date_time);
manageFacilityPage.verifyDisabledFacility(facilityCodePrefix + date_time, facilityNamePrefix + date_time);
manageFacilityPage.enableFacility();
manageFacilityPage.verifyEnabledFacility();
responseEntity = client.SendJSON("", FACILITY_FEED_URL, "GET", "", "");
List<String> feedJSONList = XmlUtils.getNodeValues(responseEntity.getResponse(), "content");
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"active\":true"));
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"enabled\":true"));
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"sdp\":true"));
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"online\":true"));
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"gln\":\"Testing Gln\""));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"active\":false"));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"enabled\":false"));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"facilityType\":\"" + facilityType + "\""));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"operatedBy\":\"" + operatedBy + "\""));
assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"active\":false"));
assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"enabled\":true"));
assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"facilityType\":\"" + facilityType + "\""));
assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"operatedBy\":\"" + operatedBy + "\""));
manageFacilityPage = homePage.navigateSearchFacility();
manageFacilityPage.searchFacility(date_time);
manageFacilityPage.clickFacilityList(date_time);
manageFacilityPage.addProgram("VACCINES", true);
manageFacilityPage.saveFacility();
Thread.sleep(5000);
assertEquals(3, feedJSONList.size());
manageFacilityPage = homePage.navigateSearchFacility();
manageFacilityPage.searchFacility(date_time);
manageFacilityPage.clickFacilityList(date_time);
manageFacilityPage.removeFirstProgram();
manageFacilityPage.saveFacility();
Thread.sleep(5000);
assertEquals(3, feedJSONList.size());
homePage.logout(baseUrlGlobal);
}
| public void testFacilityFeedUsingUI(String user, String program, String[] credentials) throws Exception {
HttpClient client = new HttpClient();
client.createContext();
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
dbWrapper.insertUser("200", user, "Ag/myf1Whs0fxr1FFfK8cs3q/VJ1qMs3yuMLDTeEcZEGzstj/waaUsQNQTIKk1U5JRzrDbPLCzCO1/vB5YGaEQ==", "F10", "[email protected]");
HomePage homePage = loginPage.loginAs(credentials[0], credentials[1]);
ManageFacilityPage manageFacilityPage = homePage.navigateCreateFacility();
homePage.clickCreateFacilityButton();
String geoZone = "Ngorongoro";
String facilityType = "Lvl3 Hospital";
String operatedBy = "MoH";
String facilityCodePrefix = "FCcode";
String facilityNamePrefix = "FCname";
String catchmentPopulationValue = "100";
String date_time = manageFacilityPage.enterValuesInFacilityAndClickSave(facilityCodePrefix, facilityNamePrefix, program, geoZone, facilityType, operatedBy, catchmentPopulationValue);
manageFacilityPage.verifyMessageOnFacilityScreen(facilityNamePrefix + date_time, "created");
ResponseEntity responseEntity = client.SendJSON("", FACILITY_FEED_URL, "GET", "", "");
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"code\":\"" + facilityCodePrefix + date_time + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"name\":\"" + facilityNamePrefix + date_time + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"facilityType\":\"" + facilityType + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"description\":\"Testing description\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"mainPhone\":\"9711231305\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"fax\":\"9711231305\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"address1\":\"Address1\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"address2\":\"Address2\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"geographicZone\":\"" + geoZone + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"catchmentPopulation\":" + catchmentPopulationValue + ""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"latitude\":-555.5555"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"longitude\":444.4444"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"altitude\":4545.4545"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"operatedBy\":\"" + operatedBy + "\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"coldStorageGrossCapacity\":3434.3434"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"coldStorageNetCapacity\":3535.3535"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"suppliesOthers\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectricity\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectronicSCC\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectronicDAR\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"active\":true"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"virtualFacility\":false"));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"comment\":\"Comments\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"stringGoLiveDate\":\"25-01-2014\""));
assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"stringGoDownDate\":\"26-01-2014"));
homePage.navigateSearchFacility();
manageFacilityPage.searchFacility(date_time);
manageFacilityPage.clickFacilityList(date_time);
manageFacilityPage.disableFacility(facilityCodePrefix + date_time, facilityNamePrefix + date_time);
manageFacilityPage.verifyDisabledFacility(facilityCodePrefix + date_time, facilityNamePrefix + date_time);
manageFacilityPage.enableFacility();
manageFacilityPage.verifyEnabledFacility();
responseEntity = client.SendJSON("", FACILITY_FEED_URL, "GET", "", "");
List<String> feedJSONList = XmlUtils.getNodeValues(responseEntity.getResponse(), "content");
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"active\":true"));
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"enabled\":true"));
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"sdp\":true"));
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"online\":true"));
assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"gln\":\"Testing Gln\""));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"active\":false"));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"enabled\":false"));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"facilityType\":\"" + facilityType + "\""));
assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"operatedBy\":\"" + operatedBy + "\""));
assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"active\":false"));
assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"enabled\":true"));
assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"facilityType\":\"" + facilityType + "\""));
assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"operatedBy\":\"" + operatedBy + "\""));
manageFacilityPage = homePage.navigateSearchFacility();
manageFacilityPage.searchFacility(date_time);
manageFacilityPage.clickFacilityList(date_time);
manageFacilityPage.addProgram("VACCINES", true);
manageFacilityPage.saveFacility();
Thread.sleep(5000);
assertEquals(3, feedJSONList.size());
manageFacilityPage = homePage.navigateSearchFacility();
manageFacilityPage.searchFacility(date_time);
manageFacilityPage.clickFacilityList(date_time);
manageFacilityPage.removeFirstProgram();
manageFacilityPage.saveFacility();
Thread.sleep(5000);
assertEquals(3, feedJSONList.size());
homePage.logout(baseUrlGlobal);
}
|
diff --git a/src/main/java/nuroko/testing/DerivativeTest.java b/src/main/java/nuroko/testing/DerivativeTest.java
index 54dcba7..1d7a5b3 100644
--- a/src/main/java/nuroko/testing/DerivativeTest.java
+++ b/src/main/java/nuroko/testing/DerivativeTest.java
@@ -1,48 +1,48 @@
package nuroko.testing;
import mikera.vectorz.AVector;
import mikera.vectorz.Vector;
import mikera.vectorz.Vectorz;
import nuroko.module.AComponent;
import nuroko.module.loss.SquaredErrorLoss;
import static org.junit.Assert.*;
public class DerivativeTest {
private static final double EPS=0.000001;
public static void testDerivative(AComponent c) {
c=c.clone();
c.getGradient().fill(0.0);
AVector t=Vector.createLength(c.getOutputLength());
Vectorz.fillGaussian(t);
AVector x=Vector.createLength(c.getInputLength());
Vectorz.fillGaussian(x);
c.train(x,t,SquaredErrorLoss.INSTANCE,1.0);
AVector g=c.getGradient().clone();
AVector p=c.getParameters().clone();
AVector o=c.getOutput().clone();
double L=-o.distanceSquared(t);
int n=c.getParameterLength();
for (int i=0; i< n ; i++) {
c.getParameters().set(p);
c.getParameters().addAt(i, EPS);
AVector y=c.think(x);
double L2=-y.distanceSquared(t);
double expected=((L2-L)/EPS);
double calculated=g.get(i);
- if ((calculated!=0.0)&&(expected!=0.0)) {
+ if ((Math.abs(calculated)>0.00000001)&&(calculated!=0.0)&&(expected!=0.0)) {
double d= expected/calculated;
- boolean ok= (d>0.5)&&(d<2.0);
+ boolean ok= (d>=0.9)&&(d<=1.1);
assertTrue("Gradient at position "+i+" expected="+expected+" calculated="+calculated,ok);
}
}
}
}
| false | true | public static void testDerivative(AComponent c) {
c=c.clone();
c.getGradient().fill(0.0);
AVector t=Vector.createLength(c.getOutputLength());
Vectorz.fillGaussian(t);
AVector x=Vector.createLength(c.getInputLength());
Vectorz.fillGaussian(x);
c.train(x,t,SquaredErrorLoss.INSTANCE,1.0);
AVector g=c.getGradient().clone();
AVector p=c.getParameters().clone();
AVector o=c.getOutput().clone();
double L=-o.distanceSquared(t);
int n=c.getParameterLength();
for (int i=0; i< n ; i++) {
c.getParameters().set(p);
c.getParameters().addAt(i, EPS);
AVector y=c.think(x);
double L2=-y.distanceSquared(t);
double expected=((L2-L)/EPS);
double calculated=g.get(i);
if ((calculated!=0.0)&&(expected!=0.0)) {
double d= expected/calculated;
boolean ok= (d>0.5)&&(d<2.0);
assertTrue("Gradient at position "+i+" expected="+expected+" calculated="+calculated,ok);
}
}
}
| public static void testDerivative(AComponent c) {
c=c.clone();
c.getGradient().fill(0.0);
AVector t=Vector.createLength(c.getOutputLength());
Vectorz.fillGaussian(t);
AVector x=Vector.createLength(c.getInputLength());
Vectorz.fillGaussian(x);
c.train(x,t,SquaredErrorLoss.INSTANCE,1.0);
AVector g=c.getGradient().clone();
AVector p=c.getParameters().clone();
AVector o=c.getOutput().clone();
double L=-o.distanceSquared(t);
int n=c.getParameterLength();
for (int i=0; i< n ; i++) {
c.getParameters().set(p);
c.getParameters().addAt(i, EPS);
AVector y=c.think(x);
double L2=-y.distanceSquared(t);
double expected=((L2-L)/EPS);
double calculated=g.get(i);
if ((Math.abs(calculated)>0.00000001)&&(calculated!=0.0)&&(expected!=0.0)) {
double d= expected/calculated;
boolean ok= (d>=0.9)&&(d<=1.1);
assertTrue("Gradient at position "+i+" expected="+expected+" calculated="+calculated,ok);
}
}
}
|
diff --git a/src/main/java/de/paralleluniverse/Faithcaio/AuctionHouse/Auction.java b/src/main/java/de/paralleluniverse/Faithcaio/AuctionHouse/Auction.java
index 112d58e..4568e5b 100644
--- a/src/main/java/de/paralleluniverse/Faithcaio/AuctionHouse/Auction.java
+++ b/src/main/java/de/paralleluniverse/Faithcaio/AuctionHouse/Auction.java
@@ -1,38 +1,38 @@
package de.paralleluniverse.Faithcaio.AuctionHouse;
import java.util.Stack;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
/**
* Represents an auction
*
* @author Anselm
*/
public class Auction
{
public final int id;
public final ItemStack item;
public final Player owner;
public final long auctionEnd;
public final Stack<Bid> bids;
public Auction(int id, ItemStack item, Player owner, long auctionEnd)
{
this.id = id;
this.item = item;
this.owner = owner;
this.auctionEnd = auctionEnd;
this.bids = new Stack<Bid>();
}
- public boolean bid(Player bidder,double amount)
+ public boolean bid(final Player bidder, final double amount)
{
- if (amount<this.bids.peek().amount)
+ if (amount < this.bids.peek().getAmount())
{
return false;
}
this.bids.push(new Bid(bidder, amount));
return true;
}
}
| false | true | public boolean bid(Player bidder,double amount)
{
if (amount<this.bids.peek().amount)
{
return false;
}
this.bids.push(new Bid(bidder, amount));
return true;
}
| public boolean bid(final Player bidder, final double amount)
{
if (amount < this.bids.peek().getAmount())
{
return false;
}
this.bids.push(new Bid(bidder, amount));
return true;
}
|
diff --git a/app/beans/Recipe.java b/app/beans/Recipe.java
index 4436928..63fbd20 100644
--- a/app/beans/Recipe.java
+++ b/app/beans/Recipe.java
@@ -1,82 +1,82 @@
package beans;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import play.i18n.Messages;
import server.exceptions.ServerException;
import utils.CollectionUtils;
import java.io.File;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
/**
* User: guym
* Date: 1/28/13
* Time: 3:06 PM
*/
public class Recipe {
private File recipeRootDirectory;
public Recipe(File recipeFile) {
this.recipeRootDirectory = recipeFile;
}
public static enum Type {
APPLICATION("install-application", "application.groovy"), SERVICE("install-service", "service.groovy");
static Type getRecipeTypeByFileName(String fileName) {
for (Type type : values()) {
if (fileName.endsWith(type.fileIdentifier)){
return type;
}
}
return null;
}
String commandParam;
String fileIdentifier;
Type(String commandParam, String fileIdentifier) {
this.commandParam = commandParam;
this.fileIdentifier = fileIdentifier;
}
}
private static WildcardFileFilter fileFilter = null;
static {
List<String> wildCards = new LinkedList<String>();
for (Type type : Type.values()) {
wildCards.add("*" + type.fileIdentifier);
}
fileFilter = new WildcardFileFilter( wildCards );
}
private static List<String> wildCards = new LinkedList<String>();
/**
* @return recipe type Application or Service by recipe directory.
* @throws server.exceptions.ServerException
* if found a not valid recipe file.
*/
public Type getRecipeType() {
Collection<File> files = FileUtils.listFiles(recipeRootDirectory, fileFilter, null);
if (CollectionUtils.isEmpty( files ) ) {
throw new ServerException(Messages.get("recipe.not.valid.1",
Type.APPLICATION.fileIdentifier, Type.SERVICE.fileIdentifier));
}
if ( CollectionUtils.size( files ) > 1) {
throw new ServerException(Messages.get("recipe.not.valid.2",
Type.APPLICATION.fileIdentifier, Type.SERVICE.fileIdentifier));
}
- String filename = CollectionUtils.first(files);
- return Type.getRecipeTypeByFileName(filename);
+ File filename = CollectionUtils.first(files);
+ return Type.getRecipeTypeByFileName(filename.getName());
}
}
| true | true | public Type getRecipeType() {
Collection<File> files = FileUtils.listFiles(recipeRootDirectory, fileFilter, null);
if (CollectionUtils.isEmpty( files ) ) {
throw new ServerException(Messages.get("recipe.not.valid.1",
Type.APPLICATION.fileIdentifier, Type.SERVICE.fileIdentifier));
}
if ( CollectionUtils.size( files ) > 1) {
throw new ServerException(Messages.get("recipe.not.valid.2",
Type.APPLICATION.fileIdentifier, Type.SERVICE.fileIdentifier));
}
String filename = CollectionUtils.first(files);
return Type.getRecipeTypeByFileName(filename);
}
| public Type getRecipeType() {
Collection<File> files = FileUtils.listFiles(recipeRootDirectory, fileFilter, null);
if (CollectionUtils.isEmpty( files ) ) {
throw new ServerException(Messages.get("recipe.not.valid.1",
Type.APPLICATION.fileIdentifier, Type.SERVICE.fileIdentifier));
}
if ( CollectionUtils.size( files ) > 1) {
throw new ServerException(Messages.get("recipe.not.valid.2",
Type.APPLICATION.fileIdentifier, Type.SERVICE.fileIdentifier));
}
File filename = CollectionUtils.first(files);
return Type.getRecipeTypeByFileName(filename.getName());
}
|
diff --git a/jbriegel/cmd/build.java b/jbriegel/cmd/build.java
index 819e48b..54232f1 100644
--- a/jbriegel/cmd/build.java
+++ b/jbriegel/cmd/build.java
@@ -1,31 +1,31 @@
package org.de.metux.briegel.cmd;
import org.de.metux.briegel.base.EBriegelError;
import org.de.metux.briegel.robots.RecursiveBuild;
/* this command builds a given port */
public class build extends CommandBase
{
public void cmd_main(String argv[]) throws EBriegelError
{
- if ((argv == null) || (argv.length == 0))
+ if ((argv == null) || (argv.length == 0) || (argv[0] == null) || (argv[0].isEmpty()))
{
System.err.println(myname+": missing port name");
System.exit(exitcode_err_missing_port);
}
RecursiveBuild bot = new RecursiveBuild(argv[0],getPortConfig(argv[0]));
bot.run();
}
public build()
{
super("build");
}
public static void main(String argv[])
{
new build().run(argv);
}
}
| true | true | public void cmd_main(String argv[]) throws EBriegelError
{
if ((argv == null) || (argv.length == 0))
{
System.err.println(myname+": missing port name");
System.exit(exitcode_err_missing_port);
}
RecursiveBuild bot = new RecursiveBuild(argv[0],getPortConfig(argv[0]));
bot.run();
}
| public void cmd_main(String argv[]) throws EBriegelError
{
if ((argv == null) || (argv.length == 0) || (argv[0] == null) || (argv[0].isEmpty()))
{
System.err.println(myname+": missing port name");
System.exit(exitcode_err_missing_port);
}
RecursiveBuild bot = new RecursiveBuild(argv[0],getPortConfig(argv[0]));
bot.run();
}
|
diff --git a/org.eclipse.core.filebuffers/src/org/eclipse/core/filebuffers/FileBuffers.java b/org.eclipse.core.filebuffers/src/org/eclipse/core/filebuffers/FileBuffers.java
index 447f95e5d..7a2656424 100644
--- a/org.eclipse.core.filebuffers/src/org/eclipse/core/filebuffers/FileBuffers.java
+++ b/org.eclipse.core.filebuffers/src/org/eclipse/core/filebuffers/FileBuffers.java
@@ -1,108 +1,108 @@
/**********************************************************************
Copyright (c) 2000, 2003 IBM Corp. and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Common Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/cpl-v10.html
Contributors:
IBM Corporation - Initial implementation
**********************************************************************/
package org.eclipse.core.filebuffers;
import java.io.File;
import org.eclipse.core.internal.filebuffers.FileBuffersPlugin;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
/**
* Facade for the file buffers plug-in. Provides access to the
* text file buffer manager.
*
* @since 3.0
*/
public final class FileBuffers {
/**
* Cannot be instantiated.
*/
private FileBuffers() {
}
/**
* Returns the text file buffer manager.
*
* @return the text file buffer manager
*/
public static ITextFileBufferManager getTextFileBufferManager() {
return FileBuffersPlugin.getDefault().getFileBufferManager();
}
/**
* Returns the workspace file at the given location or <code>null</code> if
* the location is not a valid location in the workspace.
*
* @param location the location
* @return the workspace file at the location or <code>null</code>
*/
public static IFile getWorkspaceFileAtLocation(IPath location) {
IPath normalized= normalizeLocation(location);
if (normalized.segmentCount() >= 2) {
// @see IContainer#getFile for the required number of segments
IWorkspaceRoot workspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
IFile file= workspaceRoot.getFile(normalized);
if (file != null && file.exists())
return file;
}
return null;
}
/**
* Returns a copy of the given location in a normalized form.
*
* @param location the location to be normalized
* @return normalized copy of location
*/
public static IPath normalizeLocation(IPath location) {
IWorkspaceRoot workspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
IProject[] projects= workspaceRoot.getProjects();
for (int i= 0, length= projects.length; i < length; i++) {
IPath path= projects[i].getLocation();
- if (path.isPrefixOf(location)) {
+ if (path != null && path.isPrefixOf(location)) {
IPath filePath= location.removeFirstSegments(path.segmentCount());
filePath= projects[i].getFullPath().append(filePath);
return filePath.makeAbsolute();
}
}
return location.makeAbsolute();
}
/**
* Returns the file in the local file system for the given location.
* <p>
* The location is either a full path of a workspace resource or an
* absolute path in the local file system.
* </p>
*
* @param location
* @return
*/
public static File getSystemFileAtLocation(IPath location) {
if (location == null)
return null;
IFile file= getWorkspaceFileAtLocation(location);
if (file != null) {
IPath path= file.getLocation();
return path.toFile();
}
return location.toFile();
}
}
| true | true | public static IPath normalizeLocation(IPath location) {
IWorkspaceRoot workspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
IProject[] projects= workspaceRoot.getProjects();
for (int i= 0, length= projects.length; i < length; i++) {
IPath path= projects[i].getLocation();
if (path.isPrefixOf(location)) {
IPath filePath= location.removeFirstSegments(path.segmentCount());
filePath= projects[i].getFullPath().append(filePath);
return filePath.makeAbsolute();
}
}
return location.makeAbsolute();
}
| public static IPath normalizeLocation(IPath location) {
IWorkspaceRoot workspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
IProject[] projects= workspaceRoot.getProjects();
for (int i= 0, length= projects.length; i < length; i++) {
IPath path= projects[i].getLocation();
if (path != null && path.isPrefixOf(location)) {
IPath filePath= location.removeFirstSegments(path.segmentCount());
filePath= projects[i].getFullPath().append(filePath);
return filePath.makeAbsolute();
}
}
return location.makeAbsolute();
}
|
diff --git a/activemq-cpp/openwire-scripts/AmqCppClassesGenerator.java b/activemq-cpp/openwire-scripts/AmqCppClassesGenerator.java
index 8b11eb9b..490158d9 100644
--- a/activemq-cpp/openwire-scripts/AmqCppClassesGenerator.java
+++ b/activemq-cpp/openwire-scripts/AmqCppClassesGenerator.java
@@ -1,506 +1,504 @@
/*
*
* 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.activemq.openwire.tool;
import java.io.File;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import org.codehaus.jam.JClass;
import org.codehaus.jam.JProperty;
/**
*
* @version $Revision: 409828 $
*/
public class AmqCppClassesGenerator extends MultiSourceGenerator {
protected String targetDir="./src/main";
public Object run() {
filePostFix = getFilePostFix();
if (destDir == null) {
destDir = new File(
targetDir+"/activemq/connector/openwire/commands");
}
return super.run();
}
protected String getFilePostFix() {
return ".cpp";
}
protected String getProperBaseClassName( String className, String baseClass ) {
if( baseClass == null || className == null ) {
return null;
}
// The C++ BaseCommand class is a template, which requires either
// transport::Command, or transport::Response.
if( className.equals( "Response" ) ) {
return "BaseCommand<transport::Response>";
} else if( baseClass.equals( "BaseCommand" ) ) {
return "BaseCommand<transport::Command>";
}
// No change.
return baseClass;
}
public String toCppType(JClass type) {
String name = type.getSimpleName();
if (name.equals("String")) {
return "std::string";
}
else if( type.isArrayType() ) {
if( name.equals( "byte[]" ) )
name = "unsigned char[]";
JClass arrayClass = type.getArrayComponentType();
if( arrayClass.isPrimitiveType() ) {
return "std::vector<" + name.substring(0, name.length()-2) + ">";
} else {
return "std::vector<" + name.substring(0, name.length()-2) + "*>";
}
}
else if( name.equals( "Throwable" ) || name.equals( "Exception" ) ) {
return "BrokerError";
}
else if( name.equals("BaseDataStructure" ) ){
return "DataStructure";
}
else if( name.equals("ByteSequence") ) {
return "std::vector<unsigned char>";
}
else if( name.equals("boolean") ) {
return "bool";
}
else if( name.equals("long") ) {
return "long long";
}
else if( name.equals("byte") ) {
return "unsigned char";
}
else if( !type.isPrimitiveType() ) {
return name;
}
else {
return name;
}
}
/**
* Converts the Java type to a C++ default value
*/
public String toCppDefaultValue(JClass type) {
String name = type.getSimpleName();
if (name.equals("boolean")) {
return "false";
} else if( name.equals("String") ) {
return "\"\"";
} else if( !type.isPrimitiveType() ) {
return "NULL";
} else {
return "0";
}
}
protected void generateLicence(PrintWriter out) {
out.println("/*");
out.println(" * Licensed to the Apache Software Foundation (ASF) under one or more");
out.println(" * contributor license agreements. See the NOTICE file distributed with");
out.println(" * this work for additional information regarding copyright ownership.");
out.println(" * The ASF licenses this file to You under the Apache License, Version 2.0");
out.println(" * (the \"License\"); you may not use this file except in compliance with");
out.println(" * the License. You may obtain a copy of the License at");
out.println(" *");
out.println(" * http://www.apache.org/licenses/LICENSE-2.0");
out.println(" *");
out.println(" * Unless required by applicable law or agreed to in writing, software");
out.println(" * distributed under the License is distributed on an \"AS IS\" BASIS,");
out.println(" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.");
out.println(" * See the License for the specific language governing permissions and");
out.println(" * limitations under the License.");
out.println(" */");
}
protected void generateFile(PrintWriter out) throws Exception {
generateLicence(out);
out.println("#include <activemq/connector/openwire/commands/"+className+".h>");
out.println("#include <activemq/exceptions/NullPointerException.h>");
out.println("");
out.println("using namespace std;");
out.println("using namespace activemq;");
out.println("using namespace activemq::exceptions;");
out.println("using namespace activemq::connector;");
out.println("using namespace activemq::connector::openwire;");
out.println("using namespace activemq::connector::openwire::commands;");
out.println("");
out.println("/*");
out.println(" *");
out.println(" * Command and marshaling code for OpenWire format for "+className+"");
out.println(" *");
out.println(" *");
out.println(" * NOTE!: This file is autogenerated - do not modify!");
out.println(" * if you need to make a change, please see the Java Classes in the");
out.println(" * activemq-core module");
out.println(" *");
out.println(" */");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(""+className+"::"+className+"()");
out.println("{");
List properties = getProperties();
for (Iterator iter = properties.iterator(); iter.hasNext();) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String value = toCppDefaultValue(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
if( !type.startsWith("std::vector") ) {
out.println(" this->"+parameterName+" = "+value+";");
}
}
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(""+className+"::~"+className+"()");
out.println("{");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
if( property.getType().isPrimitiveType() ||
property.getType().getSimpleName().equals("String") ) {
continue;
}
if( !type.startsWith("std::vector" ) ) {
out.println(" delete this->" + parameterName + ";");
} else if( type.contains( "*" ) ) {
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < " + parameterName + ".size(); ++i" + parameterName + " ) {");
out.println(" delete " + parameterName + "[i" + parameterName + "];");
out.println(" }");
}
}
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("DataStructure* "+className+"::cloneDataStructure() const {");
String newInstance = decapitalize( className );
out.println(" "+className+"* "+newInstance+" = new "+className+"();");
out.println("");
out.println(" // Copy the data from the base class or classes");
out.println(" "+newInstance+"->copyDataStructure( this );");
out.println("");
out.println(" return "+newInstance+";");
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("void "+className+"::copyDataStructure( const DataStructure* src ) {");
out.println("");
if( baseClass != null ) {
out.println(" // Copy the data of the base class or classes");
out.println(" "+getProperBaseClassName( className, baseClass )+"::copyDataStructure( src );");
out.println("");
}
out.println(" const "+className+"* srcPtr = dynamic_cast<const "+className+"*>( src );");
out.println("");
out.println(" if( srcPtr == NULL || src == NULL ) {");
out.println(" ");
out.println(" throw exceptions::NullPointerException(");
out.println(" __FILE__, __LINE__,");
out.println(" \""+className+"::copyDataStructure - src is NULL or invalid\" );");
out.println(" }");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
String constNess = "";
String getter = property.getGetter().getSimpleName();
String setter = property.getSetter().getSimpleName();
if( property.getType().isPrimitiveType() ||
type.equals("std::string") ||
property.getType().getSimpleName().equals("ByteSequence") ){
out.println(" this->"+setter+"( srcPtr->"+getter+"() );");
} else if( property.getType().isArrayType() &&
!property.getType().getArrayComponentType().isPrimitiveType() ) {
String arrayType = property.getType().getArrayComponentType().getSimpleName();
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < srcPtr->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" if( srcPtr->"+getter+"()[i"+parameterName+"] != NULL ) {");
out.println(" this->"+getter+"().push_back( ");
out.println(" dynamic_cast<"+arrayType+"*>( ");
out.println(" srcPtr->"+getter+"()[i"+parameterName+"]->cloneDataStructure() ) );");
out.println(" } else {");
out.println(" this->"+getter+"().push_back( NULL );");
out.println(" }");
out.println(" }");
} else if( property.getType().isArrayType() &&
property.getType().getArrayComponentType().isPrimitiveType() ) {
out.println(" this->"+setter+"( srcPtr->"+getter+"() );");
} else {
out.println(" if( srcPtr->"+getter+"() != NULL ) {");
out.println(" this->"+setter+"( ");
out.println(" dynamic_cast<"+type+"*>( ");
out.println(" srcPtr->"+getter+"()->cloneDataStructure() ) );");
out.println(" }");
}
}
out.println("}");
// getDataStructureType
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("unsigned char "+className+"::getDataStructureType() const {");
out.println(" return "+className+"::ID_" + className.toUpperCase() + "; ");
out.println("}");
// toString
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("std::string "+className+"::toString() const {");
out.println("");
out.println(" ostringstream stream;" );
out.println("");
out.println(" stream << \"Begin Class = "+className+"\" << std::endl;" );
out.println(" stream << \" Value of "+className+"::ID_" + className.toUpperCase() + " = "+getOpenWireOpCode(jclass)+"\" << std::endl; ");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
String constNess = "";
String getter = property.getGetter().getSimpleName();
String setter = property.getSetter().getSimpleName();
if( property.getType().getSimpleName().equals("ByteSequence") ) {
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" stream << \" Value of "+propertyName+"[\" << i" + parameterName+" << \"] = \" << this->"+getter+"()[i"+parameterName+"] << std::endl;" );
out.println(" }" );
} else if( property.getType().isPrimitiveType() ||
type.equals("std::string") ){
out.println(" stream << \" Value of "+propertyName+" = \" << this->"+getter+"() << std::endl;");
} else if( property.getType().isArrayType() &&
!property.getType().getArrayComponentType().isPrimitiveType() ) {
String arrayType = property.getType().getArrayComponentType().getSimpleName();
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" stream << \" Value of "+propertyName+"[\" << i" + parameterName+" << \"] is Below:\" << std::endl;" );
out.println(" if( this->"+getter+"()[i"+parameterName+"] != NULL ) {");
out.println(" stream << this->"+getter+"()[i"+parameterName+"]->toString() << std::endl;");
out.println(" } else {");
out.println(" stream << \" Object is NULL\" << std::endl;");
out.println(" }");
out.println(" }");
} else if( property.getType().isArrayType() &&
property.getType().getArrayComponentType().isPrimitiveType() ) {
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" stream << \" Value of "+propertyName+"[\" << i"+parameterName+" << \"] = \" << this->"+getter+"()[i"+parameterName+"] << std::endl;");
out.println(" }");
} else {
out.println(" stream << \" Value of "+propertyName+" is Below:\" << std::endl;" );
out.println(" if( this->"+getter+"() != NULL ) {");
out.println(" stream << this->"+getter+"()->toString() << std::endl;");
out.println(" } else {");
out.println(" stream << \" Object is NULL\" << std::endl;");
out.println(" }");
}
}
if( baseClass != null ) {
-out.println(" // Copy the data of the base class or classes");
out.println(" stream << "+getProperBaseClassName( className, baseClass )+"::toString();");
}
out.println(" stream << \"End Class = "+className+"\" << std::endl;" );
out.println("");
out.println(" return stream.str();");
out.println("}");
// equals
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("bool "+className+"::equals( const DataStructure* value ) const {");
out.println(" const "+className+"* valuePtr = dynamic_cast<const "+className+"*>( value );");
out.println("");
out.println(" if( valuePtr == NULL || value == NULL ) {");
out.println(" return false;");
out.println(" }");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
String constNess = "";
String getter = property.getGetter().getSimpleName();
String setter = property.getSetter().getSimpleName();
if( property.getType().getSimpleName().equals("ByteSequence") ) {
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" if( "+propertyName+"[i" + parameterName+"] != this->"+getter+"()[i"+parameterName+"] ) {" );
out.println(" return false;" );
out.println(" }" );
out.println(" }" );
} else if( property.getType().isPrimitiveType() ||
type.equals("std::string") ){
out.println(" if( "+propertyName+" != valuePtr->"+getter+"() ) {");
out.println(" return false;" );
out.println(" }" );
} else if( property.getType().isArrayType() &&
!property.getType().getArrayComponentType().isPrimitiveType() ) {
String arrayType = property.getType().getArrayComponentType().getSimpleName();
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" if( this->"+getter+"()[i"+parameterName+"] != NULL )" );
out.println(" if( !( this->"+getter+"()[i"+parameterName+"]->equals( valuePtr->"+getter+"()[i"+parameterName+"] ) ) {" );
out.println(" return false;");
out.println(" }");
out.println(" } else if( valuePtr->"+getter+"()[i"+parameterName+"] != NULL ) {");
out.println(" return false;");
out.println(" }");
out.println(" }");
} else if( property.getType().isArrayType() &&
property.getType().getArrayComponentType().isPrimitiveType() ) {
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" if( "+propertyName+"[i"+parameterName+"] != valuePtr->"+getter+"()[i"+parameterName+"] ) {");
out.println(" return false;");
out.println(" }");
out.println(" }");
} else {
out.println(" if( this->"+getter+"() != NULL ) {");
out.println(" if( !( this->"+getter+"()[i"+parameterName+"]->equals( valuePtr->"+getter+"()[i"+parameterName+"] ) ) {" );
out.println(" return false;");
out.println(" }");
out.println(" } else if( valuePtr->"+getter+"()[i"+parameterName+"] != NULL ) {");
out.println(" return false;");
out.println(" }");
}
}
if( baseClass != null ) {
-out.println(" // Copy the data of the base class or classes");
out.println(" if( !"+getProperBaseClassName( className, baseClass )+"::equals( value ) ) {");
out.println(" return false;");
out.println(" }");
}
out.println(" return true;" );
out.println("}");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
String getter = property.getGetter().getSimpleName();
String setter = property.getSetter().getSimpleName();
String constNess = "";
if( !property.getType().isPrimitiveType() &&
!property.getType().getSimpleName().equals("ByteSequence") &&
!property.getType().getSimpleName().equals("String") &&
!type.startsWith("std::vector") ) {
type = type + "*";
} else if( property.getType().getSimpleName().equals("String") ||
type.startsWith( "std::vector") ) {
type = type + "&";
constNess = "const ";
}
out.println("");
if( property.getType().isPrimitiveType() ) {
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(type+" "+className+"::"+getter+"() const {");
out.println(" return "+parameterName+";");
out.println("}");
out.println("");
} else {
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("const "+type+" "+className+"::"+getter+"() const {");
out.println(" return "+parameterName+";");
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(""+type+" "+className+"::"+getter+"() {");
out.println(" return "+parameterName+";");
out.println("}");
out.println("");
}
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("void " + className + "::" + setter+"(" + constNess + type+ " " + parameterName +" ) {");
out.println(" this->"+parameterName+" = "+parameterName+";");
out.println("}");
}
out.println("");
}
public String getTargetDir() {
return targetDir;
}
public void setTargetDir(String targetDir) {
this.targetDir = targetDir;
}
}
| false | true | protected void generateFile(PrintWriter out) throws Exception {
generateLicence(out);
out.println("#include <activemq/connector/openwire/commands/"+className+".h>");
out.println("#include <activemq/exceptions/NullPointerException.h>");
out.println("");
out.println("using namespace std;");
out.println("using namespace activemq;");
out.println("using namespace activemq::exceptions;");
out.println("using namespace activemq::connector;");
out.println("using namespace activemq::connector::openwire;");
out.println("using namespace activemq::connector::openwire::commands;");
out.println("");
out.println("/*");
out.println(" *");
out.println(" * Command and marshaling code for OpenWire format for "+className+"");
out.println(" *");
out.println(" *");
out.println(" * NOTE!: This file is autogenerated - do not modify!");
out.println(" * if you need to make a change, please see the Java Classes in the");
out.println(" * activemq-core module");
out.println(" *");
out.println(" */");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(""+className+"::"+className+"()");
out.println("{");
List properties = getProperties();
for (Iterator iter = properties.iterator(); iter.hasNext();) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String value = toCppDefaultValue(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
if( !type.startsWith("std::vector") ) {
out.println(" this->"+parameterName+" = "+value+";");
}
}
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(""+className+"::~"+className+"()");
out.println("{");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
if( property.getType().isPrimitiveType() ||
property.getType().getSimpleName().equals("String") ) {
continue;
}
if( !type.startsWith("std::vector" ) ) {
out.println(" delete this->" + parameterName + ";");
} else if( type.contains( "*" ) ) {
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < " + parameterName + ".size(); ++i" + parameterName + " ) {");
out.println(" delete " + parameterName + "[i" + parameterName + "];");
out.println(" }");
}
}
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("DataStructure* "+className+"::cloneDataStructure() const {");
String newInstance = decapitalize( className );
out.println(" "+className+"* "+newInstance+" = new "+className+"();");
out.println("");
out.println(" // Copy the data from the base class or classes");
out.println(" "+newInstance+"->copyDataStructure( this );");
out.println("");
out.println(" return "+newInstance+";");
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("void "+className+"::copyDataStructure( const DataStructure* src ) {");
out.println("");
if( baseClass != null ) {
out.println(" // Copy the data of the base class or classes");
out.println(" "+getProperBaseClassName( className, baseClass )+"::copyDataStructure( src );");
out.println("");
}
out.println(" const "+className+"* srcPtr = dynamic_cast<const "+className+"*>( src );");
out.println("");
out.println(" if( srcPtr == NULL || src == NULL ) {");
out.println(" ");
out.println(" throw exceptions::NullPointerException(");
out.println(" __FILE__, __LINE__,");
out.println(" \""+className+"::copyDataStructure - src is NULL or invalid\" );");
out.println(" }");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
String constNess = "";
String getter = property.getGetter().getSimpleName();
String setter = property.getSetter().getSimpleName();
if( property.getType().isPrimitiveType() ||
type.equals("std::string") ||
property.getType().getSimpleName().equals("ByteSequence") ){
out.println(" this->"+setter+"( srcPtr->"+getter+"() );");
} else if( property.getType().isArrayType() &&
!property.getType().getArrayComponentType().isPrimitiveType() ) {
String arrayType = property.getType().getArrayComponentType().getSimpleName();
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < srcPtr->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" if( srcPtr->"+getter+"()[i"+parameterName+"] != NULL ) {");
out.println(" this->"+getter+"().push_back( ");
out.println(" dynamic_cast<"+arrayType+"*>( ");
out.println(" srcPtr->"+getter+"()[i"+parameterName+"]->cloneDataStructure() ) );");
out.println(" } else {");
out.println(" this->"+getter+"().push_back( NULL );");
out.println(" }");
out.println(" }");
} else if( property.getType().isArrayType() &&
property.getType().getArrayComponentType().isPrimitiveType() ) {
out.println(" this->"+setter+"( srcPtr->"+getter+"() );");
} else {
out.println(" if( srcPtr->"+getter+"() != NULL ) {");
out.println(" this->"+setter+"( ");
out.println(" dynamic_cast<"+type+"*>( ");
out.println(" srcPtr->"+getter+"()->cloneDataStructure() ) );");
out.println(" }");
}
}
out.println("}");
// getDataStructureType
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("unsigned char "+className+"::getDataStructureType() const {");
out.println(" return "+className+"::ID_" + className.toUpperCase() + "; ");
out.println("}");
// toString
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("std::string "+className+"::toString() const {");
out.println("");
out.println(" ostringstream stream;" );
out.println("");
out.println(" stream << \"Begin Class = "+className+"\" << std::endl;" );
out.println(" stream << \" Value of "+className+"::ID_" + className.toUpperCase() + " = "+getOpenWireOpCode(jclass)+"\" << std::endl; ");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
String constNess = "";
String getter = property.getGetter().getSimpleName();
String setter = property.getSetter().getSimpleName();
if( property.getType().getSimpleName().equals("ByteSequence") ) {
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" stream << \" Value of "+propertyName+"[\" << i" + parameterName+" << \"] = \" << this->"+getter+"()[i"+parameterName+"] << std::endl;" );
out.println(" }" );
} else if( property.getType().isPrimitiveType() ||
type.equals("std::string") ){
out.println(" stream << \" Value of "+propertyName+" = \" << this->"+getter+"() << std::endl;");
} else if( property.getType().isArrayType() &&
!property.getType().getArrayComponentType().isPrimitiveType() ) {
String arrayType = property.getType().getArrayComponentType().getSimpleName();
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" stream << \" Value of "+propertyName+"[\" << i" + parameterName+" << \"] is Below:\" << std::endl;" );
out.println(" if( this->"+getter+"()[i"+parameterName+"] != NULL ) {");
out.println(" stream << this->"+getter+"()[i"+parameterName+"]->toString() << std::endl;");
out.println(" } else {");
out.println(" stream << \" Object is NULL\" << std::endl;");
out.println(" }");
out.println(" }");
} else if( property.getType().isArrayType() &&
property.getType().getArrayComponentType().isPrimitiveType() ) {
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" stream << \" Value of "+propertyName+"[\" << i"+parameterName+" << \"] = \" << this->"+getter+"()[i"+parameterName+"] << std::endl;");
out.println(" }");
} else {
out.println(" stream << \" Value of "+propertyName+" is Below:\" << std::endl;" );
out.println(" if( this->"+getter+"() != NULL ) {");
out.println(" stream << this->"+getter+"()->toString() << std::endl;");
out.println(" } else {");
out.println(" stream << \" Object is NULL\" << std::endl;");
out.println(" }");
}
}
if( baseClass != null ) {
out.println(" // Copy the data of the base class or classes");
out.println(" stream << "+getProperBaseClassName( className, baseClass )+"::toString();");
}
out.println(" stream << \"End Class = "+className+"\" << std::endl;" );
out.println("");
out.println(" return stream.str();");
out.println("}");
// equals
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("bool "+className+"::equals( const DataStructure* value ) const {");
out.println(" const "+className+"* valuePtr = dynamic_cast<const "+className+"*>( value );");
out.println("");
out.println(" if( valuePtr == NULL || value == NULL ) {");
out.println(" return false;");
out.println(" }");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
String constNess = "";
String getter = property.getGetter().getSimpleName();
String setter = property.getSetter().getSimpleName();
if( property.getType().getSimpleName().equals("ByteSequence") ) {
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" if( "+propertyName+"[i" + parameterName+"] != this->"+getter+"()[i"+parameterName+"] ) {" );
out.println(" return false;" );
out.println(" }" );
out.println(" }" );
} else if( property.getType().isPrimitiveType() ||
type.equals("std::string") ){
out.println(" if( "+propertyName+" != valuePtr->"+getter+"() ) {");
out.println(" return false;" );
out.println(" }" );
} else if( property.getType().isArrayType() &&
!property.getType().getArrayComponentType().isPrimitiveType() ) {
String arrayType = property.getType().getArrayComponentType().getSimpleName();
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" if( this->"+getter+"()[i"+parameterName+"] != NULL )" );
out.println(" if( !( this->"+getter+"()[i"+parameterName+"]->equals( valuePtr->"+getter+"()[i"+parameterName+"] ) ) {" );
out.println(" return false;");
out.println(" }");
out.println(" } else if( valuePtr->"+getter+"()[i"+parameterName+"] != NULL ) {");
out.println(" return false;");
out.println(" }");
out.println(" }");
} else if( property.getType().isArrayType() &&
property.getType().getArrayComponentType().isPrimitiveType() ) {
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" if( "+propertyName+"[i"+parameterName+"] != valuePtr->"+getter+"()[i"+parameterName+"] ) {");
out.println(" return false;");
out.println(" }");
out.println(" }");
} else {
out.println(" if( this->"+getter+"() != NULL ) {");
out.println(" if( !( this->"+getter+"()[i"+parameterName+"]->equals( valuePtr->"+getter+"()[i"+parameterName+"] ) ) {" );
out.println(" return false;");
out.println(" }");
out.println(" } else if( valuePtr->"+getter+"()[i"+parameterName+"] != NULL ) {");
out.println(" return false;");
out.println(" }");
}
}
if( baseClass != null ) {
out.println(" // Copy the data of the base class or classes");
out.println(" if( !"+getProperBaseClassName( className, baseClass )+"::equals( value ) ) {");
out.println(" return false;");
out.println(" }");
}
out.println(" return true;" );
out.println("}");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
String getter = property.getGetter().getSimpleName();
String setter = property.getSetter().getSimpleName();
String constNess = "";
if( !property.getType().isPrimitiveType() &&
!property.getType().getSimpleName().equals("ByteSequence") &&
!property.getType().getSimpleName().equals("String") &&
!type.startsWith("std::vector") ) {
type = type + "*";
} else if( property.getType().getSimpleName().equals("String") ||
type.startsWith( "std::vector") ) {
type = type + "&";
constNess = "const ";
}
out.println("");
if( property.getType().isPrimitiveType() ) {
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(type+" "+className+"::"+getter+"() const {");
out.println(" return "+parameterName+";");
out.println("}");
out.println("");
} else {
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("const "+type+" "+className+"::"+getter+"() const {");
out.println(" return "+parameterName+";");
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(""+type+" "+className+"::"+getter+"() {");
out.println(" return "+parameterName+";");
out.println("}");
out.println("");
}
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("void " + className + "::" + setter+"(" + constNess + type+ " " + parameterName +" ) {");
out.println(" this->"+parameterName+" = "+parameterName+";");
out.println("}");
}
out.println("");
}
| protected void generateFile(PrintWriter out) throws Exception {
generateLicence(out);
out.println("#include <activemq/connector/openwire/commands/"+className+".h>");
out.println("#include <activemq/exceptions/NullPointerException.h>");
out.println("");
out.println("using namespace std;");
out.println("using namespace activemq;");
out.println("using namespace activemq::exceptions;");
out.println("using namespace activemq::connector;");
out.println("using namespace activemq::connector::openwire;");
out.println("using namespace activemq::connector::openwire::commands;");
out.println("");
out.println("/*");
out.println(" *");
out.println(" * Command and marshaling code for OpenWire format for "+className+"");
out.println(" *");
out.println(" *");
out.println(" * NOTE!: This file is autogenerated - do not modify!");
out.println(" * if you need to make a change, please see the Java Classes in the");
out.println(" * activemq-core module");
out.println(" *");
out.println(" */");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(""+className+"::"+className+"()");
out.println("{");
List properties = getProperties();
for (Iterator iter = properties.iterator(); iter.hasNext();) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String value = toCppDefaultValue(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
if( !type.startsWith("std::vector") ) {
out.println(" this->"+parameterName+" = "+value+";");
}
}
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(""+className+"::~"+className+"()");
out.println("{");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
if( property.getType().isPrimitiveType() ||
property.getType().getSimpleName().equals("String") ) {
continue;
}
if( !type.startsWith("std::vector" ) ) {
out.println(" delete this->" + parameterName + ";");
} else if( type.contains( "*" ) ) {
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < " + parameterName + ".size(); ++i" + parameterName + " ) {");
out.println(" delete " + parameterName + "[i" + parameterName + "];");
out.println(" }");
}
}
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("DataStructure* "+className+"::cloneDataStructure() const {");
String newInstance = decapitalize( className );
out.println(" "+className+"* "+newInstance+" = new "+className+"();");
out.println("");
out.println(" // Copy the data from the base class or classes");
out.println(" "+newInstance+"->copyDataStructure( this );");
out.println("");
out.println(" return "+newInstance+";");
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("void "+className+"::copyDataStructure( const DataStructure* src ) {");
out.println("");
if( baseClass != null ) {
out.println(" // Copy the data of the base class or classes");
out.println(" "+getProperBaseClassName( className, baseClass )+"::copyDataStructure( src );");
out.println("");
}
out.println(" const "+className+"* srcPtr = dynamic_cast<const "+className+"*>( src );");
out.println("");
out.println(" if( srcPtr == NULL || src == NULL ) {");
out.println(" ");
out.println(" throw exceptions::NullPointerException(");
out.println(" __FILE__, __LINE__,");
out.println(" \""+className+"::copyDataStructure - src is NULL or invalid\" );");
out.println(" }");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
String constNess = "";
String getter = property.getGetter().getSimpleName();
String setter = property.getSetter().getSimpleName();
if( property.getType().isPrimitiveType() ||
type.equals("std::string") ||
property.getType().getSimpleName().equals("ByteSequence") ){
out.println(" this->"+setter+"( srcPtr->"+getter+"() );");
} else if( property.getType().isArrayType() &&
!property.getType().getArrayComponentType().isPrimitiveType() ) {
String arrayType = property.getType().getArrayComponentType().getSimpleName();
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < srcPtr->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" if( srcPtr->"+getter+"()[i"+parameterName+"] != NULL ) {");
out.println(" this->"+getter+"().push_back( ");
out.println(" dynamic_cast<"+arrayType+"*>( ");
out.println(" srcPtr->"+getter+"()[i"+parameterName+"]->cloneDataStructure() ) );");
out.println(" } else {");
out.println(" this->"+getter+"().push_back( NULL );");
out.println(" }");
out.println(" }");
} else if( property.getType().isArrayType() &&
property.getType().getArrayComponentType().isPrimitiveType() ) {
out.println(" this->"+setter+"( srcPtr->"+getter+"() );");
} else {
out.println(" if( srcPtr->"+getter+"() != NULL ) {");
out.println(" this->"+setter+"( ");
out.println(" dynamic_cast<"+type+"*>( ");
out.println(" srcPtr->"+getter+"()->cloneDataStructure() ) );");
out.println(" }");
}
}
out.println("}");
// getDataStructureType
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("unsigned char "+className+"::getDataStructureType() const {");
out.println(" return "+className+"::ID_" + className.toUpperCase() + "; ");
out.println("}");
// toString
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("std::string "+className+"::toString() const {");
out.println("");
out.println(" ostringstream stream;" );
out.println("");
out.println(" stream << \"Begin Class = "+className+"\" << std::endl;" );
out.println(" stream << \" Value of "+className+"::ID_" + className.toUpperCase() + " = "+getOpenWireOpCode(jclass)+"\" << std::endl; ");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
String constNess = "";
String getter = property.getGetter().getSimpleName();
String setter = property.getSetter().getSimpleName();
if( property.getType().getSimpleName().equals("ByteSequence") ) {
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" stream << \" Value of "+propertyName+"[\" << i" + parameterName+" << \"] = \" << this->"+getter+"()[i"+parameterName+"] << std::endl;" );
out.println(" }" );
} else if( property.getType().isPrimitiveType() ||
type.equals("std::string") ){
out.println(" stream << \" Value of "+propertyName+" = \" << this->"+getter+"() << std::endl;");
} else if( property.getType().isArrayType() &&
!property.getType().getArrayComponentType().isPrimitiveType() ) {
String arrayType = property.getType().getArrayComponentType().getSimpleName();
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" stream << \" Value of "+propertyName+"[\" << i" + parameterName+" << \"] is Below:\" << std::endl;" );
out.println(" if( this->"+getter+"()[i"+parameterName+"] != NULL ) {");
out.println(" stream << this->"+getter+"()[i"+parameterName+"]->toString() << std::endl;");
out.println(" } else {");
out.println(" stream << \" Object is NULL\" << std::endl;");
out.println(" }");
out.println(" }");
} else if( property.getType().isArrayType() &&
property.getType().getArrayComponentType().isPrimitiveType() ) {
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" stream << \" Value of "+propertyName+"[\" << i"+parameterName+" << \"] = \" << this->"+getter+"()[i"+parameterName+"] << std::endl;");
out.println(" }");
} else {
out.println(" stream << \" Value of "+propertyName+" is Below:\" << std::endl;" );
out.println(" if( this->"+getter+"() != NULL ) {");
out.println(" stream << this->"+getter+"()->toString() << std::endl;");
out.println(" } else {");
out.println(" stream << \" Object is NULL\" << std::endl;");
out.println(" }");
}
}
if( baseClass != null ) {
out.println(" stream << "+getProperBaseClassName( className, baseClass )+"::toString();");
}
out.println(" stream << \"End Class = "+className+"\" << std::endl;" );
out.println("");
out.println(" return stream.str();");
out.println("}");
// equals
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("bool "+className+"::equals( const DataStructure* value ) const {");
out.println(" const "+className+"* valuePtr = dynamic_cast<const "+className+"*>( value );");
out.println("");
out.println(" if( valuePtr == NULL || value == NULL ) {");
out.println(" return false;");
out.println(" }");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
String constNess = "";
String getter = property.getGetter().getSimpleName();
String setter = property.getSetter().getSimpleName();
if( property.getType().getSimpleName().equals("ByteSequence") ) {
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" if( "+propertyName+"[i" + parameterName+"] != this->"+getter+"()[i"+parameterName+"] ) {" );
out.println(" return false;" );
out.println(" }" );
out.println(" }" );
} else if( property.getType().isPrimitiveType() ||
type.equals("std::string") ){
out.println(" if( "+propertyName+" != valuePtr->"+getter+"() ) {");
out.println(" return false;" );
out.println(" }" );
} else if( property.getType().isArrayType() &&
!property.getType().getArrayComponentType().isPrimitiveType() ) {
String arrayType = property.getType().getArrayComponentType().getSimpleName();
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" if( this->"+getter+"()[i"+parameterName+"] != NULL )" );
out.println(" if( !( this->"+getter+"()[i"+parameterName+"]->equals( valuePtr->"+getter+"()[i"+parameterName+"] ) ) {" );
out.println(" return false;");
out.println(" }");
out.println(" } else if( valuePtr->"+getter+"()[i"+parameterName+"] != NULL ) {");
out.println(" return false;");
out.println(" }");
out.println(" }");
} else if( property.getType().isArrayType() &&
property.getType().getArrayComponentType().isPrimitiveType() ) {
out.println(" for( size_t i" + parameterName + " = 0; i" + parameterName + " < this->"+getter+"().size(); ++i" + parameterName + " ) {");
out.println(" if( "+propertyName+"[i"+parameterName+"] != valuePtr->"+getter+"()[i"+parameterName+"] ) {");
out.println(" return false;");
out.println(" }");
out.println(" }");
} else {
out.println(" if( this->"+getter+"() != NULL ) {");
out.println(" if( !( this->"+getter+"()[i"+parameterName+"]->equals( valuePtr->"+getter+"()[i"+parameterName+"] ) ) {" );
out.println(" return false;");
out.println(" }");
out.println(" } else if( valuePtr->"+getter+"()[i"+parameterName+"] != NULL ) {");
out.println(" return false;");
out.println(" }");
}
}
if( baseClass != null ) {
out.println(" if( !"+getProperBaseClassName( className, baseClass )+"::equals( value ) ) {");
out.println(" return false;");
out.println(" }");
}
out.println(" return true;" );
out.println("}");
for( Iterator iter = properties.iterator(); iter.hasNext(); ) {
JProperty property = (JProperty) iter.next();
String type = toCppType(property.getType());
String propertyName = property.getSimpleName();
String parameterName = decapitalize(propertyName);
String getter = property.getGetter().getSimpleName();
String setter = property.getSetter().getSimpleName();
String constNess = "";
if( !property.getType().isPrimitiveType() &&
!property.getType().getSimpleName().equals("ByteSequence") &&
!property.getType().getSimpleName().equals("String") &&
!type.startsWith("std::vector") ) {
type = type + "*";
} else if( property.getType().getSimpleName().equals("String") ||
type.startsWith( "std::vector") ) {
type = type + "&";
constNess = "const ";
}
out.println("");
if( property.getType().isPrimitiveType() ) {
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(type+" "+className+"::"+getter+"() const {");
out.println(" return "+parameterName+";");
out.println("}");
out.println("");
} else {
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("const "+type+" "+className+"::"+getter+"() const {");
out.println(" return "+parameterName+";");
out.println("}");
out.println("");
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println(""+type+" "+className+"::"+getter+"() {");
out.println(" return "+parameterName+";");
out.println("}");
out.println("");
}
out.println("////////////////////////////////////////////////////////////////////////////////");
out.println("void " + className + "::" + setter+"(" + constNess + type+ " " + parameterName +" ) {");
out.println(" this->"+parameterName+" = "+parameterName+";");
out.println("}");
}
out.println("");
}
|
diff --git a/modules/tools/audio-manager/src/classes/org/jdesktop/wonderland/modules/audiomanager/client/AudioTreatmentComponentProperties.java b/modules/tools/audio-manager/src/classes/org/jdesktop/wonderland/modules/audiomanager/client/AudioTreatmentComponentProperties.java
index c4a204d6d..c4ee1203f 100644
--- a/modules/tools/audio-manager/src/classes/org/jdesktop/wonderland/modules/audiomanager/client/AudioTreatmentComponentProperties.java
+++ b/modules/tools/audio-manager/src/classes/org/jdesktop/wonderland/modules/audiomanager/client/AudioTreatmentComponentProperties.java
@@ -1,1004 +1,1004 @@
/**
* Project Wonderland
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved
*
* Redistributions in source code form must reproduce the above
* copyright and this condition.
*
* The contents of this file are subject to the GNU General Public
* License, Version 2 (the "License"); you may not use this file
* except in compliance with the License. A copy of the License is
* available at http://www.opensource.org/licenses/gpl-license.php.
*
* Sun designates this particular file as subject to the "Classpath"
* exception as provided by Sun in the License file that accompanied
* this code.
*/
package org.jdesktop.wonderland.modules.audiomanager.client;
import java.util.ResourceBundle;
import javax.swing.Icon;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.SpinnerNumberModel;
import org.jdesktop.wonderland.client.cell.properties.annotation.PropertiesFactory;
import org.jdesktop.wonderland.client.cell.properties.CellPropertiesEditor;
import org.jdesktop.wonderland.client.cell.properties.spi.PropertiesFactorySPI;
import org.jdesktop.wonderland.common.cell.state.CellServerState;
import org.jdesktop.wonderland.modules.audiomanager.common.AudioTreatmentComponentServerState;
import org.jdesktop.wonderland.modules.audiomanager.common.AudioTreatmentComponentServerState.PlayWhen;
import org.jdesktop.wonderland.modules.audiomanager.common.VolumeUtil;
import com.jme.bounding.BoundingBox;
import com.jme.bounding.BoundingSphere;
import com.jme.bounding.BoundingVolume;
import com.jme.math.Vector3f;
/**
*
* @author jp
* @author Ronny Standtke <[email protected]>
*/
@PropertiesFactory(AudioTreatmentComponentServerState.class)
public class AudioTreatmentComponentProperties extends javax.swing.JPanel
implements PropertiesFactorySPI {
private final static ResourceBundle BUNDLE = ResourceBundle.getBundle(
"org/jdesktop/wonderland/modules/audiomanager/client/resources/Bundle");
private CellPropertiesEditor editor;
private String originalGroupId;
private String originalFileTreatments;
private String originalUrlTreatments;
private int originalVolume;
private PlayWhen originalPlayWhen;
private boolean originalPlayOnce;
private float originalExtentRadius;
private boolean originalUseCellBounds;
private float originalFullVolumeAreaPercent;
private boolean originalDistanceAttenuated;
private int originalFalloff;
private boolean originalShowBounds;
private SpinnerNumberModel fullVolumeAreaPercentModel;
private SpinnerNumberModel extentRadiusModel;
private float extentRadius = 0;
private boolean useCellBounds;
private PlayWhen playWhen;
private boolean playOnce;
private boolean distanceAttenuated;
private BoundsViewerEntity boundsViewerEntity;
/** Creates new form AudioTreatmentComponentProperties */
public AudioTreatmentComponentProperties() {
initComponents();
String diagramFileName = BUNDLE.getString("AudioCapabilitiesDiagram");
String resourceName = "/org/jdesktop/wonderland/modules/audiomanager/" +
"client/resources/" + diagramFileName;
Icon icon = new ImageIcon(getClass().getResource(resourceName));
audioCapabilitiesLabel.setIcon(icon);
initialize();
}
private void initialize() {
// Set the maximum and minimum values for the spinners
Float value = new Float(25);
Float min = new Float(0);
Float max = new Float(100);
Float step = new Float(1);
fullVolumeAreaPercentModel =
new SpinnerNumberModel(value, min, max, step);
fullVolumeAreaPercentSpinner.setModel(fullVolumeAreaPercentModel);
value = new Float(10);
min = new Float(0);
max = new Float(100);
step = new Float(1);
extentRadiusModel = new SpinnerNumberModel(value, min, max, step);
extentRadiusSpinner.setModel(extentRadiusModel);
// Listen for changes to the text fields and spinners
audioGroupIdTextField.getDocument().addDocumentListener(
new AudioGroupTextFieldListener());
fileTextField.getDocument().addDocumentListener(
new AudioFileTreatmentsTextFieldListener());
urlTextField.getDocument().addDocumentListener(
new AudioUrlTreatmentsTextFieldListener());
fullVolumeAreaPercentModel.addChangeListener(
new FullVolumeAreaPercentChangeListener());
extentRadiusModel.addChangeListener(new ExtentRadiusChangeListener());
}
/**
* @{inheritDoc}
*/
public String getDisplayName() {
return BUNDLE.getString("Audio_Capabilities");
}
/**
* @{inheritDoc}
*/
public JPanel getPropertiesJPanel() {
return this;
}
/**
* @{inheritDoc}
*/
public void setCellPropertiesEditor(CellPropertiesEditor editor) {
this.editor = editor;
}
/**
* @{inheritDoc}
*/
public void open() {
initialize();
CellServerState state = editor.getCellServerState();
AudioTreatmentComponentServerState compState =
(AudioTreatmentComponentServerState) state.getComponentServerState(
AudioTreatmentComponentServerState.class);
if (state == null) {
return;
}
originalGroupId = compState.getGroupId();
audioGroupIdTextField.setText(originalGroupId);
String[] treatmentList = compState.getTreatments();
originalFileTreatments = "";
originalUrlTreatments = "";
for (int i = 0; i < treatmentList.length; i++) {
String treatment = treatmentList[i];
if (treatment.indexOf("://") > 0) {
if (treatment.indexOf("file://") >= 0) {
originalFileTreatments += treatment + " ";
} else {
originalUrlTreatments += treatment + " ";
}
} else {
originalFileTreatments += treatment + " ";
}
}
originalFileTreatments = originalFileTreatments.trim();
fileTextField.setText(originalFileTreatments);
originalUrlTreatments = originalUrlTreatments.trim();
urlTextField.setText(originalUrlTreatments);
originalVolume = VolumeUtil.getClientVolume(compState.getVolume());
volumeSlider.setValue(originalVolume);
originalPlayWhen = compState.getPlayWhen();
playWhen = originalPlayWhen;
switch (originalPlayWhen) {
case ALWAYS:
alwaysRadioButton.setSelected(true);
break;
case FIRST_IN_RANGE:
proximityRadioButton.setSelected(true);
break;
case MANUAL:
manualRadioButton.setSelected(true);
break;
}
originalPlayOnce = compState.getPlayOnce();
playOnce = originalPlayOnce;
playOnceCheckBox.setSelected(playOnce);
originalExtentRadius = (float) compState.getExtent();
extentRadius = originalExtentRadius;
extentRadiusSpinner.setValue(originalExtentRadius);
extentRadiusSpinner.setEnabled(originalUseCellBounds == false);
extentRadiusSpinner.setValue((Float) extentRadius);
originalFullVolumeAreaPercent = (float) compState.getFullVolumeAreaPercent();
fullVolumeAreaPercentSpinner.setValue(originalFullVolumeAreaPercent);
originalDistanceAttenuated = compState.getDistanceAttenuated();
distanceAttenuated = originalDistanceAttenuated;
distanceAttenuatedRadioButton.setSelected(originalDistanceAttenuated);
originalFalloff = (int) compState.getFalloff();
falloffSlider.setValue(originalFalloff);
if (originalDistanceAttenuated == true) {
falloffSlider.setEnabled(true);
} else {
falloffSlider.setEnabled(false);
}
BoundingVolume bounds = editor.getCell().getLocalBounds();
if (bounds instanceof BoundingSphere) {
originalUseCellBounds = compState.getUseCellBounds();
useCellBoundsRadioButton.setEnabled(true);
useCellBoundsRadioButton.setSelected(originalUseCellBounds);
} else {
originalUseCellBounds = false;
useCellBoundsRadioButton.setEnabled(false);
useCellBoundsRadioButton.setSelected(false);
}
originalShowBounds = compState.getShowBounds();
}
/**
* @{inheritDoc}
*/
public void close() {
if (boundsViewerEntity != null) {
boundsViewerEntity.dispose();
boundsViewerEntity = null;
}
}
/**
* @{inheritDoc}
*/
public void apply() {
// Figure out whether there already exists a server state for the
// component.
CellServerState state = editor.getCellServerState();
AudioTreatmentComponentServerState compState =
(AudioTreatmentComponentServerState) state.getComponentServerState(
AudioTreatmentComponentServerState.class);
if (state == null) {
return;
}
compState.setGroupId(audioGroupIdTextField.getText());
String treatments = fileTextField.getText();
treatments = treatments.replaceAll(",", " ");
treatments = treatments.replaceAll(" ", " ");
String urls = urlTextField.getText();
urls = urls.replaceAll(",", " ");
urls = urls.replaceAll(" ", " ");
if (urls.length() > 0) {
if (treatments.length() > 0) {
treatments += " " + urls.split(" ");
} else {
treatments = urls;
}
}
// Update the component state, add to the list of updated states
compState.setTreatments(treatments.split(" "));
compState.setVolume(VolumeUtil.getServerVolume(volumeSlider.getValue()));
compState.setPlayWhen(playWhen);
compState.setPlayOnce(playOnce);
compState.setExtent((Float) extentRadiusModel.getValue());
compState.setUseCellBounds(useCellBounds);
compState.setFullVolumeAreaPercent(
(Float) fullVolumeAreaPercentModel.getValue());
compState.setDistanceAttenuated(distanceAttenuated);
compState.setFalloff(falloffSlider.getValue());
editor.addToUpdateList(compState);
}
/**
* @{inheritDoc}
*/
public void restore() {
// Reset the GUI values to the original values
audioGroupIdTextField.setText(originalGroupId);
fileTextField.setText(originalFileTreatments);
urlTextField.setText(originalUrlTreatments);
volumeSlider.setValue(originalVolume);
switch (originalPlayWhen) {
case ALWAYS:
alwaysRadioButton.setSelected(true);
break;
case FIRST_IN_RANGE:
proximityRadioButton.setSelected(true);
break;
case MANUAL:
manualRadioButton.setSelected(true);
break;
}
playOnceCheckBox.setSelected(originalPlayOnce);
extentRadiusSpinner.setValue(originalExtentRadius);
extentRadiusSpinner.setEnabled(useCellBounds == false);
fullVolumeAreaPercentSpinner.setValue(originalFullVolumeAreaPercent);
distanceAttenuatedRadioButton.setSelected(originalDistanceAttenuated);
falloffSlider.setValue(originalFalloff);
falloffSlider.setEnabled(originalDistanceAttenuated);
showBoundsCheckBox.setSelected(originalShowBounds);
BoundingVolume bounds = editor.getCell().getLocalBounds();
if (bounds instanceof BoundingSphere) {
useCellBoundsRadioButton.setEnabled(true);
useCellBoundsRadioButton.setSelected(originalUseCellBounds);
} else {
useCellBoundsRadioButton.setEnabled(false);
useCellBoundsRadioButton.setSelected(false);
}
showBounds();
}
private void showBounds() {
if (boundsViewerEntity != null) {
boundsViewerEntity.dispose();
boundsViewerEntity = null;
}
if (showBoundsCheckBox.isSelected() == false) {
return;
}
boundsViewerEntity = new BoundsViewerEntity(editor.getCell());
if (useCellBoundsRadioButton.isSelected()) {
boundsViewerEntity.showBounds(editor.getCell().getLocalBounds());
} else {
boundsViewerEntity.showBounds(
new BoundingSphere((Float) extentRadiusSpinner.getValue(), new Vector3f()));
}
}
private boolean isDirty() {
String audioGroupId = audioGroupIdTextField.getText();
if (audioGroupId.equals(originalGroupId) == false) {
return true;
}
String treatments = fileTextField.getText();
if (treatments.equals(originalFileTreatments) == false) {
return true;
}
treatments = urlTextField.getText();
if (treatments.equals(originalUrlTreatments) == false) {
return true;
}
Float fullVolumeAreaPercent = (Float) fullVolumeAreaPercentModel.getValue();
if (fullVolumeAreaPercent != originalFullVolumeAreaPercent) {
return true;
}
if (useCellBounds != originalUseCellBounds) {
return true;
}
if (useCellBounds == false) {
Float extentRadius = (Float) extentRadiusModel.getValue();
if (extentRadius != originalExtentRadius) {
return true;
}
}
if (playWhen != originalPlayWhen) {
return true;
}
if (distanceAttenuated != originalDistanceAttenuated) {
return true;
}
if (distanceAttenuated == true) {
if (falloffSlider.getValue() != originalFalloff) {
return true;
}
}
if (volumeSlider.getValue() != originalVolume) {
return true;
}
if (originalShowBounds != showBoundsCheckBox.isSelected()) {
return true;
}
return false;
}
/**
* Inner class to listen for changes to the text field and fire off dirty
* or clean indications to the cell properties editor.
*/
class AudioGroupTextFieldListener implements DocumentListener {
public void insertUpdate(DocumentEvent e) {
checkDirty();
}
public void removeUpdate(DocumentEvent e) {
checkDirty();
}
public void changedUpdate(DocumentEvent e) {
checkDirty();
}
private void checkDirty() {
if (editor != null) {
editor.setPanelDirty(AudioTreatmentComponentProperties.class, isDirty());
}
}
}
/**
* Inner class to listen for changes to the text field and fire off dirty
* or clean indications to the cell properties editor.
*/
class AudioFileTreatmentsTextFieldListener implements DocumentListener {
public void insertUpdate(DocumentEvent e) {
checkDirty();
}
public void removeUpdate(DocumentEvent e) {
checkDirty();
}
public void changedUpdate(DocumentEvent e) {
checkDirty();
}
private void checkDirty() {
if (editor != null) {
editor.setPanelDirty(AudioTreatmentComponentProperties.class, isDirty());
}
}
}
/**
* Inner class to listen for changes to the text field and fire off dirty
* or clean indications to the cell properties editor.
*/
class AudioUrlTreatmentsTextFieldListener implements DocumentListener {
public void insertUpdate(DocumentEvent e) {
checkDirty();
}
public void removeUpdate(DocumentEvent e) {
checkDirty();
}
public void changedUpdate(DocumentEvent e) {
checkDirty();
}
private void checkDirty() {
if (editor != null) {
editor.setPanelDirty(AudioTreatmentComponentProperties.class, isDirty());
}
}
}
class FullVolumeAreaPercentChangeListener implements ChangeListener {
public void stateChanged(ChangeEvent e) {
if (editor != null) {
editor.setPanelDirty(AudioTreatmentComponentProperties.class, isDirty());
}
}
}
class ExtentRadiusChangeListener implements ChangeListener {
public void stateChanged(ChangeEvent e) {
if (editor != null) {
editor.setPanelDirty(AudioTreatmentComponentProperties.class, isDirty());
showBounds();
}
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
buttonGroup3 = new javax.swing.ButtonGroup();
buttonGroup2 = new javax.swing.ButtonGroup();
jLabel5 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
fileTextField = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
audioGroupIdTextField = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
browseButton = new javax.swing.JButton();
urlTextField = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
alwaysRadioButton = new javax.swing.JRadioButton();
proximityRadioButton = new javax.swing.JRadioButton();
manualRadioButton = new javax.swing.JRadioButton();
jLabel11 = new javax.swing.JLabel();
extentRadiusSpinner = new javax.swing.JSpinner();
jLabel12 = new javax.swing.JLabel();
fullVolumeAreaPercentSpinner = new javax.swing.JSpinner();
jLabel13 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
ambientRadioButton = new javax.swing.JRadioButton();
distanceAttenuatedRadioButton = new javax.swing.JRadioButton();
falloffSlider = new javax.swing.JSlider();
jLabel3 = new javax.swing.JLabel();
audioCapabilitiesLabel = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
volumeSlider = new javax.swing.JSlider();
playOnceCheckBox = new javax.swing.JCheckBox();
showBoundsCheckBox = new javax.swing.JCheckBox();
specifyRadiusRadioButton = new javax.swing.JRadioButton();
useCellBoundsRadioButton = new javax.swing.JRadioButton();
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jdesktop/wonderland/modules/audiomanager/client/resources/Bundle"); // NOI18N
jLabel5.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel5.text")); // NOI18N
jLabel1.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel1.text")); // NOI18N
jLabel2.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel2.text")); // NOI18N
jLabel7.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel7.text")); // NOI18N
jLabel8.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel8.text")); // NOI18N
jLabel9.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel9.text")); // NOI18N
browseButton.setText(bundle.getString("AudioTreatmentComponentProperties.browseButton.text")); // NOI18N
browseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
browseButtonActionPerformed(evt);
}
});
jLabel10.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel10.text")); // NOI18N
buttonGroup1.add(alwaysRadioButton);
alwaysRadioButton.setText(bundle.getString("AudioTreatmentComponentProperties.alwaysRadioButton.text")); // NOI18N
alwaysRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
alwaysRadioButtonActionPerformed(evt);
}
});
buttonGroup1.add(proximityRadioButton);
proximityRadioButton.setText(bundle.getString("AudioTreatmentComponentProperties.proximityRadioButton.text")); // NOI18N
proximityRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
proximityRadioButtonActionPerformed(evt);
}
});
buttonGroup1.add(manualRadioButton);
manualRadioButton.setText(bundle.getString("AudioTreatmentComponentProperties.manualRadioButton.text")); // NOI18N
manualRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
manualRadioButtonActionPerformed(evt);
}
});
jLabel11.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel11.text")); // NOI18N
extentRadiusSpinner.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
extentRadiusSpinnerStateChanged(evt);
}
});
jLabel12.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel12.text")); // NOI18N
fullVolumeAreaPercentSpinner.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
fullVolumeAreaPercentSpinnerStateChanged(evt);
}
});
jLabel13.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel13.text")); // NOI18N
jLabel14.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel14.text")); // NOI18N
buttonGroup3.add(ambientRadioButton);
ambientRadioButton.setText(bundle.getString("AudioTreatmentComponentProperties.ambientRadioButton.text")); // NOI18N
ambientRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ambientRadioButtonActionPerformed(evt);
}
});
buttonGroup3.add(distanceAttenuatedRadioButton);
distanceAttenuatedRadioButton.setText(bundle.getString("AudioTreatmentComponentProperties.distanceAttenuatedRadioButton.text")); // NOI18N
distanceAttenuatedRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
distanceAttenuatedRadioButtonActionPerformed(evt);
}
});
falloffSlider.setMinorTickSpacing(10);
falloffSlider.setPaintTicks(true);
falloffSlider.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
falloffSliderStateChanged(evt);
}
});
jLabel3.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel3.text")); // NOI18N
audioCapabilitiesLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jdesktop/wonderland/modules/audiomanager/client/resources/AudioCapabilitiesDiagram_en.png"))); // NOI18N
jLabel15.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel15.text")); // NOI18N
volumeSlider.setMajorTickSpacing(1);
volumeSlider.setMaximum(10);
volumeSlider.setPaintLabels(true);
volumeSlider.setPaintTicks(true);
volumeSlider.setValue(5);
volumeSlider.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
volumeSliderStateChanged(evt);
}
});
playOnceCheckBox.setText(bundle.getString("AudioTreatmentComponentProperties.playOnceCheckBox.text")); // NOI18N
playOnceCheckBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
playOnceCheckBoxActionPerformed(evt);
}
});
showBoundsCheckBox.setText(bundle.getString("AudioTreatmentComponentProperties.showBoundsCheckBox.text")); // NOI18N
showBoundsCheckBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showBoundsCheckBoxActionPerformed(evt);
}
});
- buttonGroup3.add(specifyRadiusRadioButton);
+ buttonGroup2.add(specifyRadiusRadioButton);
specifyRadiusRadioButton.setText(bundle.getString("AudioTreatmentComponentProperties.specifyRadiusRadioButton.text")); // NOI18N
specifyRadiusRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
specifyRadiusRadioButtonActionPerformed(evt);
}
});
- buttonGroup3.add(useCellBoundsRadioButton);
+ buttonGroup2.add(useCellBoundsRadioButton);
useCellBoundsRadioButton.setText(bundle.getString("AudioTreatmentComponentProperties.useCellBoundsRadioButton.text")); // NOI18N
useCellBoundsRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
useCellBoundsRadioButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(23, 23, 23)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(jLabel9)
.add(jLabel8)
.add(jLabel7)
.add(jLabel10)
.add(jLabel1)
.add(jLabel2))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(proximityRadioButton)
.add(alwaysRadioButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 76, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
.add(org.jdesktop.layout.GroupLayout.LEADING, urlTextField)
.add(org.jdesktop.layout.GroupLayout.LEADING, volumeSlider, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 255, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(manualRadioButton)
.add(layout.createSequentialGroup()
.add(29, 29, 29)
.add(playOnceCheckBox))
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
.add(org.jdesktop.layout.GroupLayout.LEADING, audioGroupIdTextField)
.add(org.jdesktop.layout.GroupLayout.LEADING, fileTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 251, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(browseButton))))
.add(layout.createSequentialGroup()
.add(151, 151, 151)
.add(jLabel3)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(jLabel15)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(falloffSlider, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 174, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel5))
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(jLabel11)
.add(jLabel12)
.add(jLabel14))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(fullVolumeAreaPercentSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 50, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel13))
.add(ambientRadioButton)
.add(distanceAttenuatedRadioButton))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(audioCapabilitiesLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 167, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(specifyRadiusRadioButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(extentRadiusSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 51, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
.add(useCellBoundsRadioButton))
.add(showBoundsCheckBox))))
.add(13, 13, 13))
);
layout.linkSize(new java.awt.Component[] {audioGroupIdTextField, fileTextField, urlTextField}, org.jdesktop.layout.GroupLayout.HORIZONTAL);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel7)
.add(audioGroupIdTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel1)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel8)
.add(fileTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(browseButton))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(urlTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jLabel9))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(jLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 36, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(volumeSlider, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(alwaysRadioButton)
.add(jLabel10))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(proximityRadioButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(manualRadioButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(playOnceCheckBox)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER)
.add(jLabel11)
.add(specifyRadiusRadioButton)
.add(extentRadiusSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(useCellBoundsRadioButton))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(showBoundsCheckBox)
.add(12, 12, 12)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER)
.add(jLabel12)
.add(fullVolumeAreaPercentSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jLabel13))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(ambientRadioButton)
.add(jLabel14))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(distanceAttenuatedRadioButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 22, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(20, 20, 20))
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.add(audioCapabilitiesLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 99, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)))
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER)
.add(jLabel3)
.add(jLabel15)
.add(falloffSlider, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jLabel5))
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed
JFileChooser chooser = new JFileChooser(fileTextField.getText());
int returnVal = chooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
fileTextField.setText(chooser.getSelectedFile().getAbsolutePath());
}
}//GEN-LAST:event_browseButtonActionPerformed
private void alwaysRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_alwaysRadioButtonActionPerformed
playWhen = PlayWhen.ALWAYS;
if (editor != null) {
editor.setPanelDirty(AudioTreatmentComponentProperties.class, isDirty());
}
}//GEN-LAST:event_alwaysRadioButtonActionPerformed
private void proximityRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_proximityRadioButtonActionPerformed
playWhen = PlayWhen.FIRST_IN_RANGE;
if (editor != null) {
editor.setPanelDirty(AudioTreatmentComponentProperties.class, isDirty());
}
}//GEN-LAST:event_proximityRadioButtonActionPerformed
private void manualRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_manualRadioButtonActionPerformed
playWhen = PlayWhen.MANUAL;
if (editor != null) {
editor.setPanelDirty(AudioTreatmentComponentProperties.class, isDirty());
}
}//GEN-LAST:event_manualRadioButtonActionPerformed
private void extentRadiusSpinnerStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_extentRadiusSpinnerStateChanged
if (editor != null) {
editor.setPanelDirty(AudioTreatmentComponentProperties.class, isDirty());
}
}//GEN-LAST:event_extentRadiusSpinnerStateChanged
private void fullVolumeAreaPercentSpinnerStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_fullVolumeAreaPercentSpinnerStateChanged
if (editor != null) {
editor.setPanelDirty(AudioTreatmentComponentProperties.class, isDirty());
}
}//GEN-LAST:event_fullVolumeAreaPercentSpinnerStateChanged
private void falloffSliderStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_falloffSliderStateChanged
if (editor != null) {
editor.setPanelDirty(AudioTreatmentComponentProperties.class, isDirty());
}
}//GEN-LAST:event_falloffSliderStateChanged
private void distanceAttenuatedRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_distanceAttenuatedRadioButtonActionPerformed
falloffSlider.setEnabled(true);
distanceAttenuated = true;
if (editor != null) {
editor.setPanelDirty(AudioTreatmentComponentProperties.class, isDirty());
}
}//GEN-LAST:event_distanceAttenuatedRadioButtonActionPerformed
private void ambientRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ambientRadioButtonActionPerformed
falloffSlider.setEnabled(false);
distanceAttenuated = false;
if (editor != null) {
editor.setPanelDirty(AudioTreatmentComponentProperties.class, isDirty());
}
}//GEN-LAST:event_ambientRadioButtonActionPerformed
private void volumeSliderStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_volumeSliderStateChanged
if (editor != null) {
editor.setPanelDirty(AudioTreatmentComponentProperties.class, isDirty());
}
}//GEN-LAST:event_volumeSliderStateChanged
private void playOnceCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_playOnceCheckBoxActionPerformed
playOnce = playOnceCheckBox.isSelected();
}//GEN-LAST:event_playOnceCheckBoxActionPerformed
private void showBoundsCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showBoundsCheckBoxActionPerformed
if (editor == null) {
return;
}
editor.setPanelDirty(ConeOfSilenceComponentProperties.class, isDirty());
showBounds();
}//GEN-LAST:event_showBoundsCheckBoxActionPerformed
private void specifyRadiusRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_specifyRadiusRadioButtonActionPerformed
useCellBounds = specifyRadiusRadioButton.isSelected() == false;
extentRadiusSpinner.setEnabled(useCellBounds == false);
if (editor != null) {
editor.setPanelDirty(AudioTreatmentComponentProperties.class, isDirty());
showBounds();
}
}//GEN-LAST:event_specifyRadiusRadioButtonActionPerformed
private void useCellBoundsRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_useCellBoundsRadioButtonActionPerformed
useCellBounds = useCellBoundsRadioButton.isSelected();
extentRadiusSpinner.setEnabled(useCellBounds == false);
if (editor != null) {
editor.setPanelDirty(AudioTreatmentComponentProperties.class, isDirty());
showBounds();
}
}//GEN-LAST:event_useCellBoundsRadioButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JRadioButton alwaysRadioButton;
private javax.swing.JRadioButton ambientRadioButton;
private javax.swing.JLabel audioCapabilitiesLabel;
private javax.swing.JTextField audioGroupIdTextField;
private javax.swing.JButton browseButton;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.ButtonGroup buttonGroup3;
private javax.swing.JRadioButton distanceAttenuatedRadioButton;
private javax.swing.JSpinner extentRadiusSpinner;
private javax.swing.JSlider falloffSlider;
private javax.swing.JTextField fileTextField;
private javax.swing.JSpinner fullVolumeAreaPercentSpinner;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JRadioButton manualRadioButton;
private javax.swing.JCheckBox playOnceCheckBox;
private javax.swing.JRadioButton proximityRadioButton;
private javax.swing.JCheckBox showBoundsCheckBox;
private javax.swing.JRadioButton specifyRadiusRadioButton;
private javax.swing.JTextField urlTextField;
private javax.swing.JRadioButton useCellBoundsRadioButton;
private javax.swing.JSlider volumeSlider;
// End of variables declaration//GEN-END:variables
}
| false | true | private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
buttonGroup3 = new javax.swing.ButtonGroup();
buttonGroup2 = new javax.swing.ButtonGroup();
jLabel5 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
fileTextField = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
audioGroupIdTextField = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
browseButton = new javax.swing.JButton();
urlTextField = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
alwaysRadioButton = new javax.swing.JRadioButton();
proximityRadioButton = new javax.swing.JRadioButton();
manualRadioButton = new javax.swing.JRadioButton();
jLabel11 = new javax.swing.JLabel();
extentRadiusSpinner = new javax.swing.JSpinner();
jLabel12 = new javax.swing.JLabel();
fullVolumeAreaPercentSpinner = new javax.swing.JSpinner();
jLabel13 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
ambientRadioButton = new javax.swing.JRadioButton();
distanceAttenuatedRadioButton = new javax.swing.JRadioButton();
falloffSlider = new javax.swing.JSlider();
jLabel3 = new javax.swing.JLabel();
audioCapabilitiesLabel = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
volumeSlider = new javax.swing.JSlider();
playOnceCheckBox = new javax.swing.JCheckBox();
showBoundsCheckBox = new javax.swing.JCheckBox();
specifyRadiusRadioButton = new javax.swing.JRadioButton();
useCellBoundsRadioButton = new javax.swing.JRadioButton();
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jdesktop/wonderland/modules/audiomanager/client/resources/Bundle"); // NOI18N
jLabel5.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel5.text")); // NOI18N
jLabel1.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel1.text")); // NOI18N
jLabel2.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel2.text")); // NOI18N
jLabel7.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel7.text")); // NOI18N
jLabel8.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel8.text")); // NOI18N
jLabel9.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel9.text")); // NOI18N
browseButton.setText(bundle.getString("AudioTreatmentComponentProperties.browseButton.text")); // NOI18N
browseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
browseButtonActionPerformed(evt);
}
});
jLabel10.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel10.text")); // NOI18N
buttonGroup1.add(alwaysRadioButton);
alwaysRadioButton.setText(bundle.getString("AudioTreatmentComponentProperties.alwaysRadioButton.text")); // NOI18N
alwaysRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
alwaysRadioButtonActionPerformed(evt);
}
});
buttonGroup1.add(proximityRadioButton);
proximityRadioButton.setText(bundle.getString("AudioTreatmentComponentProperties.proximityRadioButton.text")); // NOI18N
proximityRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
proximityRadioButtonActionPerformed(evt);
}
});
buttonGroup1.add(manualRadioButton);
manualRadioButton.setText(bundle.getString("AudioTreatmentComponentProperties.manualRadioButton.text")); // NOI18N
manualRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
manualRadioButtonActionPerformed(evt);
}
});
jLabel11.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel11.text")); // NOI18N
extentRadiusSpinner.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
extentRadiusSpinnerStateChanged(evt);
}
});
jLabel12.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel12.text")); // NOI18N
fullVolumeAreaPercentSpinner.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
fullVolumeAreaPercentSpinnerStateChanged(evt);
}
});
jLabel13.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel13.text")); // NOI18N
jLabel14.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel14.text")); // NOI18N
buttonGroup3.add(ambientRadioButton);
ambientRadioButton.setText(bundle.getString("AudioTreatmentComponentProperties.ambientRadioButton.text")); // NOI18N
ambientRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ambientRadioButtonActionPerformed(evt);
}
});
buttonGroup3.add(distanceAttenuatedRadioButton);
distanceAttenuatedRadioButton.setText(bundle.getString("AudioTreatmentComponentProperties.distanceAttenuatedRadioButton.text")); // NOI18N
distanceAttenuatedRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
distanceAttenuatedRadioButtonActionPerformed(evt);
}
});
falloffSlider.setMinorTickSpacing(10);
falloffSlider.setPaintTicks(true);
falloffSlider.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
falloffSliderStateChanged(evt);
}
});
jLabel3.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel3.text")); // NOI18N
audioCapabilitiesLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jdesktop/wonderland/modules/audiomanager/client/resources/AudioCapabilitiesDiagram_en.png"))); // NOI18N
jLabel15.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel15.text")); // NOI18N
volumeSlider.setMajorTickSpacing(1);
volumeSlider.setMaximum(10);
volumeSlider.setPaintLabels(true);
volumeSlider.setPaintTicks(true);
volumeSlider.setValue(5);
volumeSlider.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
volumeSliderStateChanged(evt);
}
});
playOnceCheckBox.setText(bundle.getString("AudioTreatmentComponentProperties.playOnceCheckBox.text")); // NOI18N
playOnceCheckBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
playOnceCheckBoxActionPerformed(evt);
}
});
showBoundsCheckBox.setText(bundle.getString("AudioTreatmentComponentProperties.showBoundsCheckBox.text")); // NOI18N
showBoundsCheckBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showBoundsCheckBoxActionPerformed(evt);
}
});
buttonGroup3.add(specifyRadiusRadioButton);
specifyRadiusRadioButton.setText(bundle.getString("AudioTreatmentComponentProperties.specifyRadiusRadioButton.text")); // NOI18N
specifyRadiusRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
specifyRadiusRadioButtonActionPerformed(evt);
}
});
buttonGroup3.add(useCellBoundsRadioButton);
useCellBoundsRadioButton.setText(bundle.getString("AudioTreatmentComponentProperties.useCellBoundsRadioButton.text")); // NOI18N
useCellBoundsRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
useCellBoundsRadioButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(23, 23, 23)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(jLabel9)
.add(jLabel8)
.add(jLabel7)
.add(jLabel10)
.add(jLabel1)
.add(jLabel2))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(proximityRadioButton)
.add(alwaysRadioButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 76, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
.add(org.jdesktop.layout.GroupLayout.LEADING, urlTextField)
.add(org.jdesktop.layout.GroupLayout.LEADING, volumeSlider, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 255, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(manualRadioButton)
.add(layout.createSequentialGroup()
.add(29, 29, 29)
.add(playOnceCheckBox))
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
.add(org.jdesktop.layout.GroupLayout.LEADING, audioGroupIdTextField)
.add(org.jdesktop.layout.GroupLayout.LEADING, fileTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 251, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(browseButton))))
.add(layout.createSequentialGroup()
.add(151, 151, 151)
.add(jLabel3)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(jLabel15)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(falloffSlider, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 174, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel5))
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(jLabel11)
.add(jLabel12)
.add(jLabel14))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(fullVolumeAreaPercentSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 50, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel13))
.add(ambientRadioButton)
.add(distanceAttenuatedRadioButton))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(audioCapabilitiesLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 167, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(specifyRadiusRadioButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(extentRadiusSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 51, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
.add(useCellBoundsRadioButton))
.add(showBoundsCheckBox))))
.add(13, 13, 13))
);
layout.linkSize(new java.awt.Component[] {audioGroupIdTextField, fileTextField, urlTextField}, org.jdesktop.layout.GroupLayout.HORIZONTAL);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel7)
.add(audioGroupIdTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel1)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel8)
.add(fileTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(browseButton))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(urlTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jLabel9))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(jLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 36, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(volumeSlider, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(alwaysRadioButton)
.add(jLabel10))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(proximityRadioButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(manualRadioButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(playOnceCheckBox)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER)
.add(jLabel11)
.add(specifyRadiusRadioButton)
.add(extentRadiusSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(useCellBoundsRadioButton))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(showBoundsCheckBox)
.add(12, 12, 12)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER)
.add(jLabel12)
.add(fullVolumeAreaPercentSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jLabel13))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(ambientRadioButton)
.add(jLabel14))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(distanceAttenuatedRadioButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 22, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(20, 20, 20))
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.add(audioCapabilitiesLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 99, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)))
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER)
.add(jLabel3)
.add(jLabel15)
.add(falloffSlider, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jLabel5))
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
buttonGroup1 = new javax.swing.ButtonGroup();
buttonGroup3 = new javax.swing.ButtonGroup();
buttonGroup2 = new javax.swing.ButtonGroup();
jLabel5 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
fileTextField = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
audioGroupIdTextField = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
browseButton = new javax.swing.JButton();
urlTextField = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
alwaysRadioButton = new javax.swing.JRadioButton();
proximityRadioButton = new javax.swing.JRadioButton();
manualRadioButton = new javax.swing.JRadioButton();
jLabel11 = new javax.swing.JLabel();
extentRadiusSpinner = new javax.swing.JSpinner();
jLabel12 = new javax.swing.JLabel();
fullVolumeAreaPercentSpinner = new javax.swing.JSpinner();
jLabel13 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
ambientRadioButton = new javax.swing.JRadioButton();
distanceAttenuatedRadioButton = new javax.swing.JRadioButton();
falloffSlider = new javax.swing.JSlider();
jLabel3 = new javax.swing.JLabel();
audioCapabilitiesLabel = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
volumeSlider = new javax.swing.JSlider();
playOnceCheckBox = new javax.swing.JCheckBox();
showBoundsCheckBox = new javax.swing.JCheckBox();
specifyRadiusRadioButton = new javax.swing.JRadioButton();
useCellBoundsRadioButton = new javax.swing.JRadioButton();
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jdesktop/wonderland/modules/audiomanager/client/resources/Bundle"); // NOI18N
jLabel5.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel5.text")); // NOI18N
jLabel1.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel1.text")); // NOI18N
jLabel2.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel2.text")); // NOI18N
jLabel7.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel7.text")); // NOI18N
jLabel8.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel8.text")); // NOI18N
jLabel9.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel9.text")); // NOI18N
browseButton.setText(bundle.getString("AudioTreatmentComponentProperties.browseButton.text")); // NOI18N
browseButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
browseButtonActionPerformed(evt);
}
});
jLabel10.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel10.text")); // NOI18N
buttonGroup1.add(alwaysRadioButton);
alwaysRadioButton.setText(bundle.getString("AudioTreatmentComponentProperties.alwaysRadioButton.text")); // NOI18N
alwaysRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
alwaysRadioButtonActionPerformed(evt);
}
});
buttonGroup1.add(proximityRadioButton);
proximityRadioButton.setText(bundle.getString("AudioTreatmentComponentProperties.proximityRadioButton.text")); // NOI18N
proximityRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
proximityRadioButtonActionPerformed(evt);
}
});
buttonGroup1.add(manualRadioButton);
manualRadioButton.setText(bundle.getString("AudioTreatmentComponentProperties.manualRadioButton.text")); // NOI18N
manualRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
manualRadioButtonActionPerformed(evt);
}
});
jLabel11.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel11.text")); // NOI18N
extentRadiusSpinner.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
extentRadiusSpinnerStateChanged(evt);
}
});
jLabel12.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel12.text")); // NOI18N
fullVolumeAreaPercentSpinner.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
fullVolumeAreaPercentSpinnerStateChanged(evt);
}
});
jLabel13.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel13.text")); // NOI18N
jLabel14.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel14.text")); // NOI18N
buttonGroup3.add(ambientRadioButton);
ambientRadioButton.setText(bundle.getString("AudioTreatmentComponentProperties.ambientRadioButton.text")); // NOI18N
ambientRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ambientRadioButtonActionPerformed(evt);
}
});
buttonGroup3.add(distanceAttenuatedRadioButton);
distanceAttenuatedRadioButton.setText(bundle.getString("AudioTreatmentComponentProperties.distanceAttenuatedRadioButton.text")); // NOI18N
distanceAttenuatedRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
distanceAttenuatedRadioButtonActionPerformed(evt);
}
});
falloffSlider.setMinorTickSpacing(10);
falloffSlider.setPaintTicks(true);
falloffSlider.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
falloffSliderStateChanged(evt);
}
});
jLabel3.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel3.text")); // NOI18N
audioCapabilitiesLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jdesktop/wonderland/modules/audiomanager/client/resources/AudioCapabilitiesDiagram_en.png"))); // NOI18N
jLabel15.setText(bundle.getString("AudioTreatmentComponentProperties.jLabel15.text")); // NOI18N
volumeSlider.setMajorTickSpacing(1);
volumeSlider.setMaximum(10);
volumeSlider.setPaintLabels(true);
volumeSlider.setPaintTicks(true);
volumeSlider.setValue(5);
volumeSlider.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
volumeSliderStateChanged(evt);
}
});
playOnceCheckBox.setText(bundle.getString("AudioTreatmentComponentProperties.playOnceCheckBox.text")); // NOI18N
playOnceCheckBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
playOnceCheckBoxActionPerformed(evt);
}
});
showBoundsCheckBox.setText(bundle.getString("AudioTreatmentComponentProperties.showBoundsCheckBox.text")); // NOI18N
showBoundsCheckBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showBoundsCheckBoxActionPerformed(evt);
}
});
buttonGroup2.add(specifyRadiusRadioButton);
specifyRadiusRadioButton.setText(bundle.getString("AudioTreatmentComponentProperties.specifyRadiusRadioButton.text")); // NOI18N
specifyRadiusRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
specifyRadiusRadioButtonActionPerformed(evt);
}
});
buttonGroup2.add(useCellBoundsRadioButton);
useCellBoundsRadioButton.setText(bundle.getString("AudioTreatmentComponentProperties.useCellBoundsRadioButton.text")); // NOI18N
useCellBoundsRadioButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
useCellBoundsRadioButtonActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(23, 23, 23)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(jLabel9)
.add(jLabel8)
.add(jLabel7)
.add(jLabel10)
.add(jLabel1)
.add(jLabel2))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(proximityRadioButton)
.add(alwaysRadioButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 76, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
.add(org.jdesktop.layout.GroupLayout.LEADING, urlTextField)
.add(org.jdesktop.layout.GroupLayout.LEADING, volumeSlider, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 255, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(manualRadioButton)
.add(layout.createSequentialGroup()
.add(29, 29, 29)
.add(playOnceCheckBox))
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
.add(org.jdesktop.layout.GroupLayout.LEADING, audioGroupIdTextField)
.add(org.jdesktop.layout.GroupLayout.LEADING, fileTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 251, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(browseButton))))
.add(layout.createSequentialGroup()
.add(151, 151, 151)
.add(jLabel3)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(jLabel15)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(falloffSlider, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 174, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel5))
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(jLabel11)
.add(jLabel12)
.add(jLabel14))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(fullVolumeAreaPercentSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 50, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel13))
.add(ambientRadioButton)
.add(distanceAttenuatedRadioButton))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
.add(audioCapabilitiesLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 167, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(specifyRadiusRadioButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(extentRadiusSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 51, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(18, 18, 18)
.add(useCellBoundsRadioButton))
.add(showBoundsCheckBox))))
.add(13, 13, 13))
);
layout.linkSize(new java.awt.Component[] {audioGroupIdTextField, fileTextField, urlTextField}, org.jdesktop.layout.GroupLayout.HORIZONTAL);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel7)
.add(audioGroupIdTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel1)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel8)
.add(fileTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(browseButton))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(urlTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jLabel9))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(jLabel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 36, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(volumeSlider, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(alwaysRadioButton)
.add(jLabel10))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(proximityRadioButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(manualRadioButton)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(playOnceCheckBox)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER)
.add(jLabel11)
.add(specifyRadiusRadioButton)
.add(extentRadiusSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(useCellBoundsRadioButton))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(showBoundsCheckBox)
.add(12, 12, 12)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER)
.add(jLabel12)
.add(fullVolumeAreaPercentSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jLabel13))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(ambientRadioButton)
.add(jLabel14))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(distanceAttenuatedRadioButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 22, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(20, 20, 20))
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.add(audioCapabilitiesLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 99, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)))
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.CENTER)
.add(jLabel3)
.add(jLabel15)
.add(falloffSlider, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jLabel5))
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/NodeIndexer.java b/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/NodeIndexer.java
index 86eff3391..620432c75 100644
--- a/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/NodeIndexer.java
+++ b/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/NodeIndexer.java
@@ -1,1014 +1,1011 @@
/*
* 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.exoplatform.services.jcr.impl.core.query.lucene;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Fieldable;
import org.exoplatform.services.document.DocumentReadException;
import org.exoplatform.services.document.DocumentReader;
import org.exoplatform.services.document.DocumentReaderService;
import org.exoplatform.services.document.HandlerNotFoundException;
import org.exoplatform.services.jcr.core.ExtendedPropertyType;
import org.exoplatform.services.jcr.core.value.ExtendedValue;
import org.exoplatform.services.jcr.dataflow.ItemDataConsumer;
import org.exoplatform.services.jcr.datamodel.InternalQName;
import org.exoplatform.services.jcr.datamodel.NodeData;
import org.exoplatform.services.jcr.datamodel.PropertyData;
import org.exoplatform.services.jcr.datamodel.QPathEntry;
import org.exoplatform.services.jcr.datamodel.ValueData;
import org.exoplatform.services.jcr.impl.Constants;
import org.exoplatform.services.jcr.impl.core.LocationFactory;
import org.exoplatform.services.jcr.impl.core.value.ValueFactoryImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.jcr.NamespaceException;
import javax.jcr.PropertyType;
import javax.jcr.RepositoryException;
/**
* Creates a lucene <code>Document</code> object from a {@link javax.jcr.Node}.
*/
public class NodeIndexer
{
/**
* The logger instance for this class.
*/
private static final Logger log = LoggerFactory.getLogger(NodeIndexer.class);
/**
* The default boost for a lucene field: 1.0f.
*/
protected static final float DEFAULT_BOOST = 1.0f;
/**
* The <code>NodeState</code> of the node to index
*/
protected final NodeData node;
/**
* The persistent item state provider
*/
protected final ItemDataConsumer stateProvider;
/**
* Namespace mappings to use for indexing. This is the internal
* namespace mapping.
*/
protected final NamespaceMappings mappings;
/**
* Name and Path resolver.
*/
protected final LocationFactory resolver;
/**
* Content extractor.
*/
protected final DocumentReaderService extractor;
/**
* The indexing configuration or <code>null</code> if none is available.
*/
protected IndexingConfiguration indexingConfig;
/**
* If set to <code>true</code> the fulltext field is stored and and a term
* vector is created with offset information.
*/
protected boolean supportHighlighting = false;
/**
* Indicates index format for this node indexer.
*/
protected IndexFormatVersion indexFormatVersion = IndexFormatVersion.V1;
/**
* List of {@link FieldNames#FULLTEXT} fields which should not be used in
* an excerpt.
*/
protected List doNotUseInExcerpt = new ArrayList();
private ValueFactoryImpl vFactory;
/**
* Creates a new node indexer.
*
* @param node the node state to index.
* @param stateProvider the persistent item state manager to retrieve properties.
* @param mappings internal namespace mappings.
* @param extractor content extractor
*/
public NodeIndexer(NodeData node, ItemDataConsumer stateProvider, NamespaceMappings mappings,
DocumentReaderService extractor)
{
this.node = node;
this.stateProvider = stateProvider;
this.mappings = mappings;
this.resolver = new LocationFactory(mappings);
this.extractor = extractor;
this.vFactory = new ValueFactoryImpl(this.resolver);
}
/**
* Returns the <code>NodeId</code> of the indexed node.
* @return the <code>NodeId</code> of the indexed node.
*/
public String getNodeId()
{
return node.getIdentifier();
}
/**
* If set to <code>true</code> additional information is stored in the index
* to support highlighting using the rep:excerpt pseudo property.
*
* @param b <code>true</code> to enable highlighting support.
*/
public void setSupportHighlighting(boolean b)
{
supportHighlighting = b;
}
/**
* Sets the index format version
*
* @param indexFormatVersion the index format version
*/
public void setIndexFormatVersion(IndexFormatVersion indexFormatVersion)
{
this.indexFormatVersion = indexFormatVersion;
}
/**
* Sets the indexing configuration for this node indexer.
*
* @param config the indexing configuration.
*/
public void setIndexingConfiguration(IndexingConfiguration config)
{
this.indexingConfig = config;
}
/**
* Creates a lucene Document.
*
* @return the lucene Document with the index layout.
* @throws RepositoryException if an error occurs while reading property
* values from the <code>ItemStateProvider</code>.
*/
protected Document createDoc() throws RepositoryException
{
doNotUseInExcerpt.clear();
Document doc = new Document();
doc.setBoost(getNodeBoost());
// special fields
// UUID
doc.add(new Field(FieldNames.UUID, node.getIdentifier(), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
try
{
if (node.getParentIdentifier() == null)
{
// root node
doc.add(new Field(FieldNames.PARENT, "", Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
addNodeName(doc, "", "");
}
else
{
addParentChildRelation(doc, node.getParentIdentifier());
}
}
catch (NamespaceException e)
{
// will never happen, because this.mappings will dynamically add
// unknown uri<->prefix mappings
}
for (PropertyData prop : stateProvider.listChildPropertiesData(node))
{
// add each property to the _PROPERTIES_SET for searching
// beginning with V2
if (indexFormatVersion.getVersion() >= IndexFormatVersion.V2.getVersion())
{
addPropertyName(doc, prop.getQPath().getName());
}
addValues(doc, prop);
}
// now add fields that are not used in excerpt (must go at the end)
for (Iterator it = doNotUseInExcerpt.iterator(); it.hasNext();)
{
doc.add((Fieldable)it.next());
}
return doc;
}
/**
* Wraps the exception <code>e</code> into a <code>RepositoryException</code>
* and throws the created exception.
*
* @param e the base exception.
*/
private void throwRepositoryException(Exception e) throws RepositoryException
{
String msg =
"Error while indexing node: " + node.getIdentifier() + " of " + "type: "
+ node.getPrimaryTypeName().getAsString();
throw new RepositoryException(msg, e);
}
/**
* Adds a {@link FieldNames#MVP} field to <code>doc</code> with the resolved
* <code>name</code> using the internal search index namespace mapping.
*
* @param doc the lucene document.
* @param name the name of the multi-value property.
* @throws RepositoryException
*/
private void addMVPName(Document doc, InternalQName name) throws RepositoryException
{
try
{
String propName = resolver.createJCRName(name).getAsString();
doc.add(new Field(FieldNames.MVP, propName, Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS,
Field.TermVector.NO));
}
catch (NamespaceException e)
{
// will never happen, prefixes are created dynamically
}
}
/**
* Adds a value to the lucene Document.
*
* @param doc the document.
* @param value the internal value.
* @param name the name of the property.
*/
private void addValues(final Document doc, final PropertyData prop) throws RepositoryException
{
int propType = prop.getType();
String fieldName = resolver.createJCRName(prop.getQPath().getName()).getAsString();
if (propType == PropertyType.BINARY)
{
List<ValueData> data = null;
if (node.getQPath().getName().equals(Constants.JCR_CONTENT))
{
// seems nt:file found, try for nt:resource props
PropertyData pmime =
(PropertyData)stateProvider.getItemData(node, new QPathEntry(Constants.JCR_MIMETYPE, 0));
if (pmime != null)
{
// ok, have a reader
// if the prop obtainer from cache it will contains a values,
// otherwise read prop with values from DM
PropertyData propData = prop.getValues().size() > 0 ? prop : ((PropertyData)stateProvider.getItemData(node,
new QPathEntry(Constants.JCR_DATA, 0)));
// index if have jcr:mimeType sibling for this binary property only
try
{
DocumentReader dreader =
extractor.getDocumentReader(new String(pmime.getValues().get(0).getAsByteArray()));
data = propData.getValues();
if (data == null)
log.warn("null value found at property " + prop.getQPath().getAsString());
// check the jcr:encoding property
PropertyData encProp =
(PropertyData)stateProvider.getItemData(node, new QPathEntry(Constants.JCR_ENCODING, 0));
if (encProp != null)
{
// encoding parameter used
String encoding = new String(encProp.getValues().get(0).getAsByteArray());
for (ValueData pvd : data)
{
InputStream is = null;
try
{
is = pvd.getAsStream();
Reader reader = new StringReader(dreader.getContentAsText(is, encoding));
doc.add(createFulltextField(reader));
}
finally
{
try
{
is.close();
}
catch (Throwable e)
{
}
}
}
}
else
{
// no encoding parameter
for (ValueData pvd : data)
{
InputStream is = null;
try
{
is = pvd.getAsStream();
Reader reader = new StringReader(dreader.getContentAsText(is));
doc.add(createFulltextField(reader));
}
finally
{
try
{
is.close();
}
catch (Throwable e)
{
}
}
}
}
if (data.size() > 1)
{
// real multi-valued
addMVPName(doc, prop.getQPath().getName());
}
}
catch (DocumentReadException e)
{
- if (log.isWarnEnabled())
- {
- log.warn("Can not indexing the document by path " + propData.getQPath().getAsString() + ", propery id '" + propData.getIdentifier() + "' : " + e, e);
- }
+ log.error("Can not indexing the document by path " + propData.getQPath().getAsString() + ", propery id '" + propData.getIdentifier() + "' : " + e, e);
}
catch (HandlerNotFoundException e)
{
// no handler - no index
if (log.isWarnEnabled())
{
log.warn("This content is not readable, document by path "+ propData.getQPath().getAsString() + ", propery id '" + propData.getIdentifier() + "' : " + e, e);
}
}
catch (IOException e)
{
// no data - no index
if (log.isWarnEnabled())
{
log.warn("Binary value indexer IO error, document by path " + propData.getQPath().getAsString() + ", propery id '" + propData.getIdentifier() + "' : " + e, e);
}
}
catch (Exception e)
{
log.error("Binary value indexer error, document by path " + propData.getQPath().getAsString() + ", propery id '" + propData.getIdentifier() + "' : " + e, e);
}
}
}
}
else
{
try
{
// if the prop obtainer from cache it will contains a values, otherwise
// read prop with values from DM
// WARN. DON'T USE access item BY PATH - it's may be a node in case of
// residual definitions in NT
List<ValueData> data =
prop.getValues().size() > 0 ? prop.getValues() : ((PropertyData)stateProvider.getItemData(prop.getIdentifier())).getValues();
if (data == null)
log.warn("null value found at property " + prop.getQPath().getAsString());
ExtendedValue val = null;
InternalQName name = prop.getQPath().getName();
for (ValueData value : data)
{
val = (ExtendedValue)vFactory.loadValue(value, propType);
switch (propType)
{
case PropertyType.BOOLEAN :
if (isIndexed(name))
{
addBooleanValue(doc, fieldName, Boolean.valueOf(val.getBoolean()));
}
break;
case PropertyType.DATE :
if (isIndexed(name))
{
addCalendarValue(doc, fieldName, val.getDate());
}
break;
case PropertyType.DOUBLE :
if (isIndexed(name))
{
addDoubleValue(doc, fieldName, new Double(val.getDouble()));
}
break;
case PropertyType.LONG :
if (isIndexed(name))
{
addLongValue(doc, fieldName, new Long(val.getLong()));
}
break;
case PropertyType.REFERENCE :
if (isIndexed(name))
{
addReferenceValue(doc, fieldName, val.getString());
}
break;
case PropertyType.PATH :
if (isIndexed(name))
{
addPathValue(doc, fieldName, val.getString());
}
break;
case PropertyType.STRING :
if (isIndexed(name))
{
// never fulltext index jcr:uuid String
if (name.equals(Constants.JCR_UUID))
{
addStringValue(doc, fieldName, val.getString(), false, false, DEFAULT_BOOST);
}
else
{
addStringValue(doc, fieldName, val.getString(), true, isIncludedInNodeIndex(name),
getPropertyBoost(name), useInExcerpt(name));
}
}
break;
case PropertyType.NAME :
// jcr:primaryType and jcr:mixinTypes are required for correct
// node type resolution in queries
if (isIndexed(name) || name.equals(Constants.JCR_PRIMARYTYPE)
|| name.equals(Constants.JCR_MIXINTYPES))
{
addNameValue(doc, fieldName, val.getString());
}
break;
case ExtendedPropertyType.PERMISSION :
break;
default :
throw new IllegalArgumentException("illegal internal value type " + propType);
}
// add length
// add not planed
if (indexFormatVersion.getVersion() >= IndexFormatVersion.V3.getVersion())
{
addLength(doc, fieldName, value, propType);
}
}
if (data.size() > 1)
// real multi-valued
addMVPName(doc, prop.getQPath().getName());
}
catch (RepositoryException e)
{
e.printStackTrace();
throw new RepositoryException("Index of property value error. " + prop.getQPath().getAsString() + ". " + e,
e);
}
}
}
/**
* Adds the property name to the lucene _:PROPERTIES_SET field.
*
* @param doc the document.
* @param name the name of the property.
* @throws RepositoryException
*/
private void addPropertyName(Document doc, InternalQName name) throws RepositoryException
{
String fieldName = name.getName();
try
{
fieldName = resolver.createJCRName(name).getAsString();
}
catch (NamespaceException e)
{
// will never happen
}
doc.add(new Field(FieldNames.PROPERTIES_SET, fieldName, Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
}
/**
* Adds the string representation of the boolean value to the document as
* the named field.
*
* @param doc The document to which to add the field
* @param fieldName The name of the field to add
* @param internalValue The value for the field to add to the document.
*/
protected void addBooleanValue(Document doc, String fieldName, Object internalValue)
{
doc.add(createFieldWithoutNorms(fieldName, internalValue.toString(), PropertyType.BOOLEAN));
}
/**
* Creates a field of name <code>fieldName</code> with the value of <code>
* internalValue</code>. The created field is indexed without norms.
*
* @param fieldName The name of the field to add
* @param internalValue The value for the field to add to the document.
* @param propertyType the property type.
*/
protected Field createFieldWithoutNorms(String fieldName, String internalValue, int propertyType)
{
if (indexFormatVersion.getVersion() >= IndexFormatVersion.V3.getVersion())
{
Field field =
new Field(FieldNames.PROPERTIES, new SingletonTokenStream(FieldNames.createNamedValue(fieldName,
internalValue), propertyType));
field.setOmitNorms(true);
return field;
}
else
{
return new Field(FieldNames.PROPERTIES, FieldNames.createNamedValue(fieldName, internalValue), Field.Store.NO,
Field.Index.NOT_ANALYZED_NO_NORMS, Field.TermVector.NO);
}
}
/**
* Adds the calendar value to the document as the named field. The calendar
* value is converted to an indexable string value using the
* {@link DateField} class.
*
* @param doc
* The document to which to add the field
* @param fieldName
* The name of the field to add
* @param internalValue
* The value for the field to add to the document.
*/
protected void addCalendarValue(Document doc, String fieldName, Object internalValue)
{
Calendar value = (Calendar)internalValue;
long millis = value.getTimeInMillis();
try
{
doc.add(createFieldWithoutNorms(fieldName, DateField.timeToString(millis), PropertyType.DATE));
}
catch (IllegalArgumentException e)
{
log.warn("'{}' is outside of supported date value range.", new Date(value.getTimeInMillis()));
}
}
/**
* Adds the double value to the document as the named field. The double
* value is converted to an indexable string value using the
* {@link DoubleField} class.
*
* @param doc The document to which to add the field
* @param fieldName The name of the field to add
* @param internalValue The value for the field to add to the document.
*/
protected void addDoubleValue(Document doc, String fieldName, Object internalValue)
{
double doubleVal = ((Double)internalValue).doubleValue();
doc.add(createFieldWithoutNorms(fieldName, DoubleField.doubleToString(doubleVal), PropertyType.DOUBLE));
}
/**
* Adds the long value to the document as the named field. The long
* value is converted to an indexable string value using the {@link LongField}
* class.
*
* @param doc The document to which to add the field
* @param fieldName The name of the field to add
* @param internalValue The value for the field to add to the document.
*/
protected void addLongValue(Document doc, String fieldName, Object internalValue)
{
long longVal = ((Long)internalValue).longValue();
doc.add(createFieldWithoutNorms(fieldName, LongField.longToString(longVal), PropertyType.LONG));
}
/**
* Adds the reference value to the document as the named field. The value's
* string representation is added as the reference data. Additionally the
* reference data is stored in the index.
*
* @param doc The document to which to add the field
* @param fieldName The name of the field to add
* @param internalValue The value for the field to add to the document.
*/
protected void addReferenceValue(Document doc, String fieldName, Object internalValue)
{
String uuid = internalValue.toString();
doc.add(createFieldWithoutNorms(fieldName, uuid, PropertyType.REFERENCE));
doc.add(new Field(FieldNames.PROPERTIES, FieldNames.createNamedValue(fieldName, uuid), Field.Store.YES,
Field.Index.NO, Field.TermVector.NO));
}
/**
* Adds the path value to the document as the named field. The path
* value is converted to an indexable string value using the name space
* mappings with which this class has been created.
*
* @param doc The document to which to add the field
* @param fieldName The name of the field to add
* @param internalValue The value for the field to add to the document.
*/
protected void addPathValue(Document doc, String fieldName, Object pathString)
{
doc.add(createFieldWithoutNorms(fieldName, pathString.toString(), PropertyType.PATH));
}
/**
* Adds the string value to the document both as the named field and for
* full text indexing.
*
* @param doc The document to which to add the field
* @param fieldName The name of the field to add
* @param internalValue The value for the field to add to the document.
* @deprecated Use {@link #addStringValue(Document, String, Object, boolean)
* addStringValue(Document, String, Object, boolean)} instead.
*/
protected void addStringValue(Document doc, String fieldName, Object internalValue)
{
addStringValue(doc, fieldName, internalValue, true, true, DEFAULT_BOOST);
}
/**
* Adds the string value to the document both as the named field and
* optionally for full text indexing if <code>tokenized</code> is
* <code>true</code>.
*
* @param doc The document to which to add the field
* @param fieldName The name of the field to add
* @param internalValue The value for the field to add to the document.
* @param tokenized If <code>true</code> the string is also tokenized
* and fulltext indexed.
*/
protected void addStringValue(Document doc, String fieldName, Object internalValue, boolean tokenized)
{
addStringValue(doc, fieldName, internalValue, tokenized, true, DEFAULT_BOOST);
}
/**
* Adds the string value to the document both as the named field and
* optionally for full text indexing if <code>tokenized</code> is
* <code>true</code>.
*
* @param doc The document to which to add the field
* @param fieldName The name of the field to add
* @param internalValue The value for the field to add to the
* document.
* @param tokenized If <code>true</code> the string is also
* tokenized and fulltext indexed.
* @param includeInNodeIndex If <code>true</code> the string is also
* tokenized and added to the node scope fulltext
* index.
* @param boost the boost value for this string field.
* @deprecated use {@link #addStringValue(Document, String, Object, boolean, boolean, float, boolean)} instead.
*/
protected void addStringValue(Document doc, String fieldName, Object internalValue, boolean tokenized,
boolean includeInNodeIndex, float boost)
{
addStringValue(doc, fieldName, internalValue, tokenized, includeInNodeIndex, boost, true);
}
/**
* Adds the string value to the document both as the named field and
* optionally for full text indexing if <code>tokenized</code> is
* <code>true</code>.
*
* @param doc The document to which to add the field
* @param fieldName The name of the field to add
* @param internalValue The value for the field to add to the
* document.
* @param tokenized If <code>true</code> the string is also
* tokenized and fulltext indexed.
* @param includeInNodeIndex If <code>true</code> the string is also
* tokenized and added to the node scope fulltext
* index.
* @param boost the boost value for this string field.
* @param useInExcerpt If <code>true</code> the string may show up in
* an excerpt.
*/
protected void addStringValue(Document doc, String fieldName, Object internalValue, boolean tokenized,
boolean includeInNodeIndex, float boost, boolean useInExcerpt)
{
// simple String
String stringValue = (String)internalValue;
doc.add(createFieldWithoutNorms(fieldName, stringValue, PropertyType.STRING));
if (tokenized)
{
if (stringValue.length() == 0)
{
return;
}
// create fulltext index on property
int idx = fieldName.indexOf(':');
fieldName = fieldName.substring(0, idx + 1) + FieldNames.FULLTEXT_PREFIX + fieldName.substring(idx + 1);
Field f = new Field(fieldName, stringValue, Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.NO);
f.setBoost(boost);
doc.add(f);
if (includeInNodeIndex)
{
// also create fulltext index of this value
boolean store = supportHighlighting && useInExcerpt;
f = createFulltextField(stringValue, store, supportHighlighting);
if (useInExcerpt)
{
doc.add(f);
}
else
{
doNotUseInExcerpt.add(f);
}
}
}
}
/**
* Adds the name value to the document as the named field. The name
* value is converted to an indexable string treating the internal value
* as a qualified name and mapping the name space using the name space
* mappings with which this class has been created.
*
* @param doc The document to which to add the field
* @param fieldName The name of the field to add
* @param internalValue The value for the field to add to the document.
*/
protected void addNameValue(Document doc, String fieldName, Object internalValue)
{
doc.add(createFieldWithoutNorms(fieldName, internalValue.toString(), PropertyType.NAME));
}
/**
* Creates a fulltext field for the string <code>value</code>.
*
* @param value the string value.
* @return a lucene field.
* @deprecated use {@link #createFulltextField(String, boolean, boolean)} instead.
*/
protected Field createFulltextField(String value)
{
return createFulltextField(value, supportHighlighting, supportHighlighting);
}
/**
* Creates a fulltext field for the string <code>value</code>.
*
* @param value the string value.
* @param store if the value of the field should be stored.
* @param withOffsets if a term vector with offsets should be stored.
* @return a lucene field.
*/
protected Field createFulltextField(String value, boolean store, boolean withOffsets)
{
Field.TermVector tv;
if (withOffsets)
{
tv = Field.TermVector.WITH_OFFSETS;
}
else
{
tv = Field.TermVector.NO;
}
if (store)
{
// store field compressed if greater than 16k
Field.Store stored;
if (value.length() > 0x4000)
{
stored = Field.Store.COMPRESS;
}
else
{
stored = Field.Store.YES;
}
return new Field(FieldNames.FULLTEXT, value, stored, Field.Index.ANALYZED, tv);
}
else
{
return new Field(FieldNames.FULLTEXT, value, Field.Store.NO, Field.Index.ANALYZED, tv);
}
}
/**
* Creates a fulltext field for the reader <code>value</code>.
*
* @param value the reader value.
* @return a lucene field.
*/
protected Fieldable createFulltextField(Reader value)
{
if (supportHighlighting)
{
return new LazyTextExtractorField(FieldNames.FULLTEXT, value, true, true);
}
else
{
return new LazyTextExtractorField(FieldNames.FULLTEXT, value, false, false);
}
}
/**
* Returns <code>true</code> if the property with the given name should be
* indexed.
*
* @param propertyName name of a property.
* @return <code>true</code> if the property should be fulltext indexed;
* <code>false</code> otherwise.
*/
protected boolean isIndexed(InternalQName propertyName)
{
if (indexingConfig == null)
{
return true;
}
else
{
return indexingConfig.isIndexed(node, propertyName);
}
}
/**
* Returns <code>true</code> if the property with the given name should also
* be added to the node scope index.
*
* @param propertyName the name of a property.
* @return <code>true</code> if it should be added to the node scope index;
* <code>false</code> otherwise.
*/
protected boolean isIncludedInNodeIndex(InternalQName propertyName)
{
if (indexingConfig == null)
{
return true;
}
else
{
return indexingConfig.isIncludedInNodeScopeIndex(node, propertyName);
}
}
/**
* Returns <code>true</code> if the content of the property with the given
* name should the used to create an excerpt.
*
* @param propertyName the name of a property.
* @return <code>true</code> if it should be used to create an excerpt;
* <code>false</code> otherwise.
*/
protected boolean useInExcerpt(InternalQName propertyName)
{
if (indexingConfig == null)
{
return true;
}
else
{
return indexingConfig.useInExcerpt(node, propertyName);
}
}
/**
* Returns the boost value for the given property name.
*
* @param propertyName the name of a property.
* @return the boost value for the given property name.
*/
protected float getPropertyBoost(InternalQName propertyName)
{
if (indexingConfig == null)
{
return DEFAULT_BOOST;
}
else
{
return indexingConfig.getPropertyBoost(node, propertyName);
}
}
/**
* @return the boost value for this {@link #node} state.
*/
protected float getNodeBoost()
{
if (indexingConfig == null)
{
return DEFAULT_BOOST;
}
else
{
return indexingConfig.getNodeBoost(node);
}
}
/**
* Adds a {@link FieldNames#PROPERTY_LENGTHS} field to <code>document</code>
* with a named length value.
*
* @param doc the lucene document.
* @param propertyName the property name.
* @param value the internal value.
* @param propType
*/
protected void addLength(Document doc, String propertyName, ValueData value, int propType)
{
long length = Util.getLength(value, propType);
if (length != -1)
{
doc.add(new Field(FieldNames.PROPERTY_LENGTHS, FieldNames.createNamedLength(propertyName, length),
Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
}
}
/**
* Depending on the index format version adds one or two fields to the
* document for the node name.
*
* @param doc the lucene document.
* @param namespaceURI the namespace URI of the node name.
* @param localName the local name of the node.
* @throws RepositoryException
*/
protected void addNodeName(Document doc, String namespaceURI, String localName) throws RepositoryException
{
String name = mappings.getNamespacePrefixByURI(namespaceURI) + ":" + localName;
doc.add(new Field(FieldNames.LABEL, name, Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
// as of version 3, also index combination of namespace URI and local name
if (indexFormatVersion.getVersion() >= IndexFormatVersion.V3.getVersion())
{
doc.add(new Field(FieldNames.NAMESPACE_URI, namespaceURI, Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
doc.add(new Field(FieldNames.LOCAL_NAME, localName, Field.Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
}
}
/**
* Adds a parent child relation to the given <code>doc</code>.
*
* @param doc the document.
* @param parentId the id of the parent node.
* @throws ItemStateException if the parent node cannot be read.
* @throws RepositoryException if the parent node does not have a child node
* entry for the current node.
*/
protected void addParentChildRelation(Document doc, String parentId) throws RepositoryException
{
doc.add(new Field(FieldNames.PARENT, parentId, Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS,
Field.TermVector.NO));
// NodeState parent = (NodeState) stateProvider.getItemState(parentId);
// ChildNodeEntry child = parent.getChildNodeEntry(node.getNodeId());
// if (child == null) {
// // this can only happen when jackrabbit
// // is running in a cluster.
// throw new RepositoryException(
// "Missing child node entry for node with id: "
// + node.getNodeId());
// }
InternalQName name = node.getQPath().getName();
addNodeName(doc, name.getNamespace(), name.getName());
}
}
| true | true | private void addValues(final Document doc, final PropertyData prop) throws RepositoryException
{
int propType = prop.getType();
String fieldName = resolver.createJCRName(prop.getQPath().getName()).getAsString();
if (propType == PropertyType.BINARY)
{
List<ValueData> data = null;
if (node.getQPath().getName().equals(Constants.JCR_CONTENT))
{
// seems nt:file found, try for nt:resource props
PropertyData pmime =
(PropertyData)stateProvider.getItemData(node, new QPathEntry(Constants.JCR_MIMETYPE, 0));
if (pmime != null)
{
// ok, have a reader
// if the prop obtainer from cache it will contains a values,
// otherwise read prop with values from DM
PropertyData propData = prop.getValues().size() > 0 ? prop : ((PropertyData)stateProvider.getItemData(node,
new QPathEntry(Constants.JCR_DATA, 0)));
// index if have jcr:mimeType sibling for this binary property only
try
{
DocumentReader dreader =
extractor.getDocumentReader(new String(pmime.getValues().get(0).getAsByteArray()));
data = propData.getValues();
if (data == null)
log.warn("null value found at property " + prop.getQPath().getAsString());
// check the jcr:encoding property
PropertyData encProp =
(PropertyData)stateProvider.getItemData(node, new QPathEntry(Constants.JCR_ENCODING, 0));
if (encProp != null)
{
// encoding parameter used
String encoding = new String(encProp.getValues().get(0).getAsByteArray());
for (ValueData pvd : data)
{
InputStream is = null;
try
{
is = pvd.getAsStream();
Reader reader = new StringReader(dreader.getContentAsText(is, encoding));
doc.add(createFulltextField(reader));
}
finally
{
try
{
is.close();
}
catch (Throwable e)
{
}
}
}
}
else
{
// no encoding parameter
for (ValueData pvd : data)
{
InputStream is = null;
try
{
is = pvd.getAsStream();
Reader reader = new StringReader(dreader.getContentAsText(is));
doc.add(createFulltextField(reader));
}
finally
{
try
{
is.close();
}
catch (Throwable e)
{
}
}
}
}
if (data.size() > 1)
{
// real multi-valued
addMVPName(doc, prop.getQPath().getName());
}
}
catch (DocumentReadException e)
{
if (log.isWarnEnabled())
{
log.warn("Can not indexing the document by path " + propData.getQPath().getAsString() + ", propery id '" + propData.getIdentifier() + "' : " + e, e);
}
}
catch (HandlerNotFoundException e)
{
// no handler - no index
if (log.isWarnEnabled())
{
log.warn("This content is not readable, document by path "+ propData.getQPath().getAsString() + ", propery id '" + propData.getIdentifier() + "' : " + e, e);
}
}
catch (IOException e)
{
// no data - no index
if (log.isWarnEnabled())
{
log.warn("Binary value indexer IO error, document by path " + propData.getQPath().getAsString() + ", propery id '" + propData.getIdentifier() + "' : " + e, e);
}
}
catch (Exception e)
{
log.error("Binary value indexer error, document by path " + propData.getQPath().getAsString() + ", propery id '" + propData.getIdentifier() + "' : " + e, e);
}
}
}
}
else
{
try
{
// if the prop obtainer from cache it will contains a values, otherwise
// read prop with values from DM
// WARN. DON'T USE access item BY PATH - it's may be a node in case of
// residual definitions in NT
List<ValueData> data =
prop.getValues().size() > 0 ? prop.getValues() : ((PropertyData)stateProvider.getItemData(prop.getIdentifier())).getValues();
if (data == null)
log.warn("null value found at property " + prop.getQPath().getAsString());
ExtendedValue val = null;
InternalQName name = prop.getQPath().getName();
for (ValueData value : data)
{
val = (ExtendedValue)vFactory.loadValue(value, propType);
switch (propType)
{
case PropertyType.BOOLEAN :
if (isIndexed(name))
{
addBooleanValue(doc, fieldName, Boolean.valueOf(val.getBoolean()));
}
break;
case PropertyType.DATE :
if (isIndexed(name))
{
addCalendarValue(doc, fieldName, val.getDate());
}
break;
case PropertyType.DOUBLE :
if (isIndexed(name))
{
addDoubleValue(doc, fieldName, new Double(val.getDouble()));
}
break;
case PropertyType.LONG :
if (isIndexed(name))
{
addLongValue(doc, fieldName, new Long(val.getLong()));
}
break;
case PropertyType.REFERENCE :
if (isIndexed(name))
{
addReferenceValue(doc, fieldName, val.getString());
}
break;
case PropertyType.PATH :
if (isIndexed(name))
{
addPathValue(doc, fieldName, val.getString());
}
break;
case PropertyType.STRING :
if (isIndexed(name))
{
// never fulltext index jcr:uuid String
if (name.equals(Constants.JCR_UUID))
{
addStringValue(doc, fieldName, val.getString(), false, false, DEFAULT_BOOST);
}
else
{
addStringValue(doc, fieldName, val.getString(), true, isIncludedInNodeIndex(name),
getPropertyBoost(name), useInExcerpt(name));
}
}
break;
case PropertyType.NAME :
// jcr:primaryType and jcr:mixinTypes are required for correct
// node type resolution in queries
if (isIndexed(name) || name.equals(Constants.JCR_PRIMARYTYPE)
|| name.equals(Constants.JCR_MIXINTYPES))
{
addNameValue(doc, fieldName, val.getString());
}
break;
case ExtendedPropertyType.PERMISSION :
break;
default :
throw new IllegalArgumentException("illegal internal value type " + propType);
}
// add length
// add not planed
if (indexFormatVersion.getVersion() >= IndexFormatVersion.V3.getVersion())
{
addLength(doc, fieldName, value, propType);
}
}
if (data.size() > 1)
// real multi-valued
addMVPName(doc, prop.getQPath().getName());
}
catch (RepositoryException e)
{
e.printStackTrace();
throw new RepositoryException("Index of property value error. " + prop.getQPath().getAsString() + ". " + e,
e);
}
}
}
| private void addValues(final Document doc, final PropertyData prop) throws RepositoryException
{
int propType = prop.getType();
String fieldName = resolver.createJCRName(prop.getQPath().getName()).getAsString();
if (propType == PropertyType.BINARY)
{
List<ValueData> data = null;
if (node.getQPath().getName().equals(Constants.JCR_CONTENT))
{
// seems nt:file found, try for nt:resource props
PropertyData pmime =
(PropertyData)stateProvider.getItemData(node, new QPathEntry(Constants.JCR_MIMETYPE, 0));
if (pmime != null)
{
// ok, have a reader
// if the prop obtainer from cache it will contains a values,
// otherwise read prop with values from DM
PropertyData propData = prop.getValues().size() > 0 ? prop : ((PropertyData)stateProvider.getItemData(node,
new QPathEntry(Constants.JCR_DATA, 0)));
// index if have jcr:mimeType sibling for this binary property only
try
{
DocumentReader dreader =
extractor.getDocumentReader(new String(pmime.getValues().get(0).getAsByteArray()));
data = propData.getValues();
if (data == null)
log.warn("null value found at property " + prop.getQPath().getAsString());
// check the jcr:encoding property
PropertyData encProp =
(PropertyData)stateProvider.getItemData(node, new QPathEntry(Constants.JCR_ENCODING, 0));
if (encProp != null)
{
// encoding parameter used
String encoding = new String(encProp.getValues().get(0).getAsByteArray());
for (ValueData pvd : data)
{
InputStream is = null;
try
{
is = pvd.getAsStream();
Reader reader = new StringReader(dreader.getContentAsText(is, encoding));
doc.add(createFulltextField(reader));
}
finally
{
try
{
is.close();
}
catch (Throwable e)
{
}
}
}
}
else
{
// no encoding parameter
for (ValueData pvd : data)
{
InputStream is = null;
try
{
is = pvd.getAsStream();
Reader reader = new StringReader(dreader.getContentAsText(is));
doc.add(createFulltextField(reader));
}
finally
{
try
{
is.close();
}
catch (Throwable e)
{
}
}
}
}
if (data.size() > 1)
{
// real multi-valued
addMVPName(doc, prop.getQPath().getName());
}
}
catch (DocumentReadException e)
{
log.error("Can not indexing the document by path " + propData.getQPath().getAsString() + ", propery id '" + propData.getIdentifier() + "' : " + e, e);
}
catch (HandlerNotFoundException e)
{
// no handler - no index
if (log.isWarnEnabled())
{
log.warn("This content is not readable, document by path "+ propData.getQPath().getAsString() + ", propery id '" + propData.getIdentifier() + "' : " + e, e);
}
}
catch (IOException e)
{
// no data - no index
if (log.isWarnEnabled())
{
log.warn("Binary value indexer IO error, document by path " + propData.getQPath().getAsString() + ", propery id '" + propData.getIdentifier() + "' : " + e, e);
}
}
catch (Exception e)
{
log.error("Binary value indexer error, document by path " + propData.getQPath().getAsString() + ", propery id '" + propData.getIdentifier() + "' : " + e, e);
}
}
}
}
else
{
try
{
// if the prop obtainer from cache it will contains a values, otherwise
// read prop with values from DM
// WARN. DON'T USE access item BY PATH - it's may be a node in case of
// residual definitions in NT
List<ValueData> data =
prop.getValues().size() > 0 ? prop.getValues() : ((PropertyData)stateProvider.getItemData(prop.getIdentifier())).getValues();
if (data == null)
log.warn("null value found at property " + prop.getQPath().getAsString());
ExtendedValue val = null;
InternalQName name = prop.getQPath().getName();
for (ValueData value : data)
{
val = (ExtendedValue)vFactory.loadValue(value, propType);
switch (propType)
{
case PropertyType.BOOLEAN :
if (isIndexed(name))
{
addBooleanValue(doc, fieldName, Boolean.valueOf(val.getBoolean()));
}
break;
case PropertyType.DATE :
if (isIndexed(name))
{
addCalendarValue(doc, fieldName, val.getDate());
}
break;
case PropertyType.DOUBLE :
if (isIndexed(name))
{
addDoubleValue(doc, fieldName, new Double(val.getDouble()));
}
break;
case PropertyType.LONG :
if (isIndexed(name))
{
addLongValue(doc, fieldName, new Long(val.getLong()));
}
break;
case PropertyType.REFERENCE :
if (isIndexed(name))
{
addReferenceValue(doc, fieldName, val.getString());
}
break;
case PropertyType.PATH :
if (isIndexed(name))
{
addPathValue(doc, fieldName, val.getString());
}
break;
case PropertyType.STRING :
if (isIndexed(name))
{
// never fulltext index jcr:uuid String
if (name.equals(Constants.JCR_UUID))
{
addStringValue(doc, fieldName, val.getString(), false, false, DEFAULT_BOOST);
}
else
{
addStringValue(doc, fieldName, val.getString(), true, isIncludedInNodeIndex(name),
getPropertyBoost(name), useInExcerpt(name));
}
}
break;
case PropertyType.NAME :
// jcr:primaryType and jcr:mixinTypes are required for correct
// node type resolution in queries
if (isIndexed(name) || name.equals(Constants.JCR_PRIMARYTYPE)
|| name.equals(Constants.JCR_MIXINTYPES))
{
addNameValue(doc, fieldName, val.getString());
}
break;
case ExtendedPropertyType.PERMISSION :
break;
default :
throw new IllegalArgumentException("illegal internal value type " + propType);
}
// add length
// add not planed
if (indexFormatVersion.getVersion() >= IndexFormatVersion.V3.getVersion())
{
addLength(doc, fieldName, value, propType);
}
}
if (data.size() > 1)
// real multi-valued
addMVPName(doc, prop.getQPath().getName());
}
catch (RepositoryException e)
{
e.printStackTrace();
throw new RepositoryException("Index of property value error. " + prop.getQPath().getAsString() + ". " + e,
e);
}
}
}
|
diff --git a/java/gadgets/src/main/java/org/apache/shindig/gadgets/http/UrlGenerator.java b/java/gadgets/src/main/java/org/apache/shindig/gadgets/http/UrlGenerator.java
index 0addd435..b566e809 100644
--- a/java/gadgets/src/main/java/org/apache/shindig/gadgets/http/UrlGenerator.java
+++ b/java/gadgets/src/main/java/org/apache/shindig/gadgets/http/UrlGenerator.java
@@ -1,177 +1,177 @@
/*
* 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.shindig.gadgets.http;
import org.apache.shindig.gadgets.Gadget;
import org.apache.shindig.gadgets.GadgetContext;
import org.apache.shindig.gadgets.GadgetFeature;
import org.apache.shindig.gadgets.GadgetFeatureFactory;
import org.apache.shindig.gadgets.GadgetFeatureRegistry;
import org.apache.shindig.gadgets.JsLibrary;
import org.apache.shindig.gadgets.SyndicatorConfig;
import org.apache.shindig.gadgets.UserPrefs;
import org.apache.shindig.gadgets.spec.GadgetSpec;
import org.apache.shindig.gadgets.spec.UserPref;
import org.apache.shindig.gadgets.spec.View;
import org.apache.shindig.util.HashUtil;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Generates urls for various public entrypoints
*/
public class UrlGenerator {
private final String jsPrefix;
private final String iframePrefix;
private final String jsChecksum;
private final SyndicatorConfig syndicatorConfig;
private final static Pattern ALLOWED_FEATURE_NAME
= Pattern.compile("[0-9a-zA-Z\\.\\-]+");
/**
* @param features The list of features that js is needed for.
* @return The url for the bundled javascript that includes all referenced
* feature libraries.
*/
public String getBundledJsUrl(Collection<String> features,
GadgetContext context) {
return jsPrefix + getBundledJsParam(features, context);
}
/**
* @param features
* @param context
* @return The bundled js parameter for type=url gadgets.
*/
public String getBundledJsParam(Collection<String> features,
GadgetContext context) {
StringBuilder buf = new StringBuilder();
boolean first = false;
for (String feature : features) {
if (ALLOWED_FEATURE_NAME.matcher(feature).matches()) {
if (!first) {
first = true;
} else {
buf.append(':');
}
buf.append(feature);
}
}
buf.append(".js?v=").append(jsChecksum)
.append("&synd=").append(context.getSyndicator())
.append("&debug=").append(context.getDebug() ? "1" : "0");
return buf.toString();
}
/**
* Generates iframe urls for meta data service.
* Use this rather than generating your own urls by hand.
*
* @param gadget
* @return The generated iframe url.
*/
public String getIframeUrl(Gadget gadget) {
StringBuilder buf = new StringBuilder();
GadgetContext context = gadget.getContext();
GadgetSpec spec = gadget.getSpec();
try {
String url = context.getUrl().toString();
View view = HttpUtil.getView(gadget, syndicatorConfig);
View.ContentType type;
if (view == null) {
type = View.ContentType.HTML;
} else {
- type = null;
+ type = view.getType();
}
switch (type) {
case URL:
// type = url
buf.append(view.getHref());
if (url.indexOf('?') == -1) {
buf.append('?');
} else {
buf.append('&');
}
break;
case HTML:
default:
buf.append(iframePrefix)
.append("url=")
.append(URLEncoder.encode(url, "UTF-8"))
.append("&");
break;
}
if (context.getModuleId() != 0) {
buf.append("mid=").append(context.getModuleId());
}
buf.append("&synd=").append(context.getSyndicator());
if (context.getIgnoreCache()) {
buf.append("&nocache=1");
} else {
buf.append("&v=").append(spec.getChecksum());
}
buf.append("&lang=").append(context.getLocale().getLanguage());
buf.append("&country=").append(context.getLocale().getCountry());
UserPrefs prefs = context.getUserPrefs();
for (UserPref pref : gadget.getSpec().getUserPrefs()) {
String name = pref.getName();
String value = prefs.getPref(name);
if (value == null) {
value = pref.getDefaultValue();
}
buf.append("&up_").append(URLEncoder.encode(pref.getName(), "UTF-8"))
.append("=").append(URLEncoder.encode(value, "UTF-8"));
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 Not supported!", e);
}
return buf.toString();
}
@Inject
public UrlGenerator(@Named("urls.iframe.prefix") String iframePrefix,
@Named("urls.js.prefix") String jsPrefix,
GadgetFeatureRegistry registry,
SyndicatorConfig syndicatorConfig) {
this.iframePrefix = iframePrefix;
this.jsPrefix = jsPrefix;
this.syndicatorConfig = syndicatorConfig;
StringBuilder jsBuf = new StringBuilder();
for (Map.Entry<String, GadgetFeatureRegistry.Entry> entry :
registry.getAllFeatures().entrySet()) {
GadgetFeatureFactory factory = entry.getValue().getFeature();
GadgetFeature feature = factory.create();
for (JsLibrary library : feature.getJsLibraries(null)) {
jsBuf.append(library.getContent());
}
}
jsChecksum = HashUtil.checksum(jsBuf.toString().getBytes());
}
}
| true | true | public String getIframeUrl(Gadget gadget) {
StringBuilder buf = new StringBuilder();
GadgetContext context = gadget.getContext();
GadgetSpec spec = gadget.getSpec();
try {
String url = context.getUrl().toString();
View view = HttpUtil.getView(gadget, syndicatorConfig);
View.ContentType type;
if (view == null) {
type = View.ContentType.HTML;
} else {
type = null;
}
switch (type) {
case URL:
// type = url
buf.append(view.getHref());
if (url.indexOf('?') == -1) {
buf.append('?');
} else {
buf.append('&');
}
break;
case HTML:
default:
buf.append(iframePrefix)
.append("url=")
.append(URLEncoder.encode(url, "UTF-8"))
.append("&");
break;
}
if (context.getModuleId() != 0) {
buf.append("mid=").append(context.getModuleId());
}
buf.append("&synd=").append(context.getSyndicator());
if (context.getIgnoreCache()) {
buf.append("&nocache=1");
} else {
buf.append("&v=").append(spec.getChecksum());
}
buf.append("&lang=").append(context.getLocale().getLanguage());
buf.append("&country=").append(context.getLocale().getCountry());
UserPrefs prefs = context.getUserPrefs();
for (UserPref pref : gadget.getSpec().getUserPrefs()) {
String name = pref.getName();
String value = prefs.getPref(name);
if (value == null) {
value = pref.getDefaultValue();
}
buf.append("&up_").append(URLEncoder.encode(pref.getName(), "UTF-8"))
.append("=").append(URLEncoder.encode(value, "UTF-8"));
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 Not supported!", e);
}
return buf.toString();
}
| public String getIframeUrl(Gadget gadget) {
StringBuilder buf = new StringBuilder();
GadgetContext context = gadget.getContext();
GadgetSpec spec = gadget.getSpec();
try {
String url = context.getUrl().toString();
View view = HttpUtil.getView(gadget, syndicatorConfig);
View.ContentType type;
if (view == null) {
type = View.ContentType.HTML;
} else {
type = view.getType();
}
switch (type) {
case URL:
// type = url
buf.append(view.getHref());
if (url.indexOf('?') == -1) {
buf.append('?');
} else {
buf.append('&');
}
break;
case HTML:
default:
buf.append(iframePrefix)
.append("url=")
.append(URLEncoder.encode(url, "UTF-8"))
.append("&");
break;
}
if (context.getModuleId() != 0) {
buf.append("mid=").append(context.getModuleId());
}
buf.append("&synd=").append(context.getSyndicator());
if (context.getIgnoreCache()) {
buf.append("&nocache=1");
} else {
buf.append("&v=").append(spec.getChecksum());
}
buf.append("&lang=").append(context.getLocale().getLanguage());
buf.append("&country=").append(context.getLocale().getCountry());
UserPrefs prefs = context.getUserPrefs();
for (UserPref pref : gadget.getSpec().getUserPrefs()) {
String name = pref.getName();
String value = prefs.getPref(name);
if (value == null) {
value = pref.getDefaultValue();
}
buf.append("&up_").append(URLEncoder.encode(pref.getName(), "UTF-8"))
.append("=").append(URLEncoder.encode(value, "UTF-8"));
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8 Not supported!", e);
}
return buf.toString();
}
|
diff --git a/spring/src/main/java/org/brekka/stillingar/spring/resource/BaseDirResolver.java b/spring/src/main/java/org/brekka/stillingar/spring/resource/BaseDirResolver.java
index 0202fc6..9b340d8 100644
--- a/spring/src/main/java/org/brekka/stillingar/spring/resource/BaseDirResolver.java
+++ b/spring/src/main/java/org/brekka/stillingar/spring/resource/BaseDirResolver.java
@@ -1,182 +1,182 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.brekka.stillingar.spring.resource;
import static java.lang.String.format;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.UrlResource;
/**
* The locations specified will be checked sequentially until the first valid location is encountered. The locations can
* include system property and/or environment variables which will be resolved prior to checking the location is valid.
*
* @author Andrew Taylor
*/
public class BaseDirResolver implements FactoryBean<Resource>, ApplicationContextAware {
/**
* Regex used to detect and replace system/environment properties.
*/
private static final Pattern VAR_REPLACE_REGEX = Pattern.compile("\\$\\{(env\\.)?([\\w\\._\\-]+)\\}");
/**
* Logger
*/
private static final Log log = LogFactory.getLog(BaseDirResolver.class);
/**
* The list of locations
*/
private final Collection<String> locations;
/**
* Environment var map
*/
private Map<String, String> envMap = System.getenv();
/**
* Optional application to use to resolve resources. If not present, then all locations will be assumed to be
* {@link FileSystemResource}.
*/
private ApplicationContext applicationContext;
/**
* @param locations The list of locations
*/
public BaseDirResolver(Collection<String> locations) {
this.locations = new ArrayList<String>(locations);
}
@Override
public Class<Resource> getObjectType() {
return Resource.class;
}
@Override
public Resource getObject() throws Exception {
Resource resource = null;
for (String location : this.locations) {
resource = resolve(location);
if (resource != null) {
break;
}
}
if (resource == null) {
resource = onUnresolvable(this.locations);
}
return resource;
}
/**
* Called when a location cannot be resolved to an actual location.
* @param locations the collection of locations strings, as they were passed to the constructor.
* @return a marker resource that will identify to the caller that the location was not resolvable.
*/
protected Resource onUnresolvable(Collection<String> locations) {
return new UnresolvableResource("None of these paths could be resolved " +
"to a valid configuration base directory: %s", locations);
}
/**
* Perform variable extraction on the location value and return the corresponding resource. If placeholder values
* are detected which cannot be resolved, then null will be returned (ie it is not resolvable).
*
* @param location the location to extrapolate placeholders for.
* @return the resource or null if all placeholders cannot be resolved.
*/
protected Resource resolve(String location) {
Resource resource = null;
Matcher matcher = VAR_REPLACE_REGEX.matcher(location);
boolean allValuesReplaced = true;
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
boolean env = matcher.group(1) != null;
String key = matcher.group(2);
String value;
if (env) {
// Resolve an environment variable
value = envMap.get(key);
} else {
// System property
value = System.getProperty(key);
}
allValuesReplaced &= (value != null);
if (!allValuesReplaced) {
break;
}
matcher.appendReplacement(sb, Matcher.quoteReplacement(value));
- matcher.appendTail(sb);
}
+ matcher.appendTail(sb);
if (allValuesReplaced) {
String url = sb.toString();
if (applicationContext != null) {
resource = applicationContext.getResource(url);
} else {
try {
resource = new UrlResource(url);
} catch (MalformedURLException e) {
// Ignore
if (log.isWarnEnabled()) {
log.warn(format("Failed to parse URL '%s'", url), e);
}
}
}
if (!resource.exists()) {
resource = null;
}
}
return resource;
}
@Override
public boolean isSingleton() {
return true;
}
/**
* Override the environment variables map. Intended for testing purposes but left public in case it is useful for somebody.
* @param envMap
*/
public void setEnvMap(Map<String, String> envMap) {
this.envMap = envMap;
}
/**
* If set, the resolver will use the {@link ResourceLoader#getResource(String)} method of the applicationContext to resolve
* the placeholder-replaced locations.
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
| false | true | protected Resource resolve(String location) {
Resource resource = null;
Matcher matcher = VAR_REPLACE_REGEX.matcher(location);
boolean allValuesReplaced = true;
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
boolean env = matcher.group(1) != null;
String key = matcher.group(2);
String value;
if (env) {
// Resolve an environment variable
value = envMap.get(key);
} else {
// System property
value = System.getProperty(key);
}
allValuesReplaced &= (value != null);
if (!allValuesReplaced) {
break;
}
matcher.appendReplacement(sb, Matcher.quoteReplacement(value));
matcher.appendTail(sb);
}
if (allValuesReplaced) {
String url = sb.toString();
if (applicationContext != null) {
resource = applicationContext.getResource(url);
} else {
try {
resource = new UrlResource(url);
} catch (MalformedURLException e) {
// Ignore
if (log.isWarnEnabled()) {
log.warn(format("Failed to parse URL '%s'", url), e);
}
}
}
if (!resource.exists()) {
resource = null;
}
}
return resource;
}
| protected Resource resolve(String location) {
Resource resource = null;
Matcher matcher = VAR_REPLACE_REGEX.matcher(location);
boolean allValuesReplaced = true;
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
boolean env = matcher.group(1) != null;
String key = matcher.group(2);
String value;
if (env) {
// Resolve an environment variable
value = envMap.get(key);
} else {
// System property
value = System.getProperty(key);
}
allValuesReplaced &= (value != null);
if (!allValuesReplaced) {
break;
}
matcher.appendReplacement(sb, Matcher.quoteReplacement(value));
}
matcher.appendTail(sb);
if (allValuesReplaced) {
String url = sb.toString();
if (applicationContext != null) {
resource = applicationContext.getResource(url);
} else {
try {
resource = new UrlResource(url);
} catch (MalformedURLException e) {
// Ignore
if (log.isWarnEnabled()) {
log.warn(format("Failed to parse URL '%s'", url), e);
}
}
}
if (!resource.exists()) {
resource = null;
}
}
return resource;
}
|
diff --git a/lib/src/org/transdroid/daemon/util/FakeTrustManager.java b/lib/src/org/transdroid/daemon/util/FakeTrustManager.java
index 160f703..bbb7bff 100644
--- a/lib/src/org/transdroid/daemon/util/FakeTrustManager.java
+++ b/lib/src/org/transdroid/daemon/util/FakeTrustManager.java
@@ -1,89 +1,89 @@
package org.transdroid.daemon.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
public class FakeTrustManager implements X509TrustManager {
private String certKey = null;
private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};
private static final String LOG_NAME = "TrustManager";
FakeTrustManager(String certKey){
super();
this.certKey = certKey;
}
FakeTrustManager(){
super();
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
if( this.certKey == null ){
// This is the Accept All certificates case.
return;
}
// Otherwise, we have a certKey defined. We should now examine the one we got from the server.
// They match? All is good. They don't, throw an exception.
- String our_key = this.certKey.replaceAll("[^a-f0-9]+", "");
+ String our_key = this.certKey.replaceAll("[^a-fA-F0-9]+", "");
try {
//Assume self-signed root is okay?
X509Certificate ss_cert = chain[0];
String thumbprint = FakeTrustManager.getThumbPrint(ss_cert);
DLog.d(LOG_NAME, thumbprint);
if( our_key.equalsIgnoreCase(thumbprint) ){
return;
}
else {
throw new CertificateException("Certificate key [" + thumbprint + "] doesn't match expected value.");
}
} catch (NoSuchAlgorithmException e) {
throw new CertificateException("Unable to check self-signed cert, unknown algorithm. " + e.toString());
}
}
public boolean isClientTrusted(X509Certificate[] chain) {
return true;
}
public boolean isServerTrusted(X509Certificate[] chain) {
return true;
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return _AcceptedIssuers;
}
// Thank you: http://stackoverflow.com/questions/1270703/how-to-retrieve-compute-an-x509-certificates-thumbprint-in-java
private static String getThumbPrint(X509Certificate cert) throws NoSuchAlgorithmException, CertificateEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] der = cert.getEncoded();
md.update(der);
byte[] digest = md.digest();
return hexify(digest);
}
private static String hexify (byte bytes[]) {
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
StringBuffer buf = new StringBuffer(bytes.length * 2);
for (int i = 0; i < bytes.length; ++i) {
buf.append(hexDigits[(bytes[i] & 0xf0) >> 4]);
buf.append(hexDigits[bytes[i] & 0x0f]);
}
return buf.toString();
}
}
| true | true | public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
if( this.certKey == null ){
// This is the Accept All certificates case.
return;
}
// Otherwise, we have a certKey defined. We should now examine the one we got from the server.
// They match? All is good. They don't, throw an exception.
String our_key = this.certKey.replaceAll("[^a-f0-9]+", "");
try {
//Assume self-signed root is okay?
X509Certificate ss_cert = chain[0];
String thumbprint = FakeTrustManager.getThumbPrint(ss_cert);
DLog.d(LOG_NAME, thumbprint);
if( our_key.equalsIgnoreCase(thumbprint) ){
return;
}
else {
throw new CertificateException("Certificate key [" + thumbprint + "] doesn't match expected value.");
}
} catch (NoSuchAlgorithmException e) {
throw new CertificateException("Unable to check self-signed cert, unknown algorithm. " + e.toString());
}
}
| public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
if( this.certKey == null ){
// This is the Accept All certificates case.
return;
}
// Otherwise, we have a certKey defined. We should now examine the one we got from the server.
// They match? All is good. They don't, throw an exception.
String our_key = this.certKey.replaceAll("[^a-fA-F0-9]+", "");
try {
//Assume self-signed root is okay?
X509Certificate ss_cert = chain[0];
String thumbprint = FakeTrustManager.getThumbPrint(ss_cert);
DLog.d(LOG_NAME, thumbprint);
if( our_key.equalsIgnoreCase(thumbprint) ){
return;
}
else {
throw new CertificateException("Certificate key [" + thumbprint + "] doesn't match expected value.");
}
} catch (NoSuchAlgorithmException e) {
throw new CertificateException("Unable to check self-signed cert, unknown algorithm. " + e.toString());
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.