diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/main/java/pl/agh/enrollme/service/PersonService.java b/src/main/java/pl/agh/enrollme/service/PersonService.java
index 9df4987..cee015c 100644
--- a/src/main/java/pl/agh/enrollme/service/PersonService.java
+++ b/src/main/java/pl/agh/enrollme/service/PersonService.java
@@ -1,99 +1,101 @@
package pl.agh.enrollme.service;
import org.primefaces.event.RowEditEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import pl.agh.enrollme.model.Person;
import pl.agh.enrollme.repository.IPersonDAO;
import java.util.ArrayList;
import java.util.List;
@Service
public class PersonService {
private static final Logger LOGGER = LoggerFactory.getLogger(PersonService.class);
@Autowired
private IPersonDAO personDAO;
private static List<Person> cache = new ArrayList<Person>();
static {
// cache.add(new Person(0, "Jamie", "Carr"));
// cache.add(new Person(1, "Jean", "Cobbs"));
// cache.add(new Person(2, "John", "Howard"));
// cache.add(new Person(3, "John", "Mudra"));
// cache.add(new Person(4, "Julia", "Webber"));
}
public List<String> suggestNames(String text) {
List<String> results = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
results.add(text + i);
}
return results;
}
public List<Person> suggestPeople(String text) {
List<Person> results = new ArrayList<Person>();
for (Person p : cache) {
if ((p.getFirstName() + " " + p.getLastName()).toLowerCase().startsWith(text.toLowerCase())) {
results.add(p);
}
}
return results;
}
public void onEdit(RowEditEvent event) {
LOGGER.debug("Row edited");
Person editedPerson = (Person)event.getObject();
if (editedPerson != null) {
LOGGER.debug("Updating person with id " + editedPerson.getId());
personDAO.update(editedPerson);
}
}
public void setEncodedPassword(Person person, String password) {
LOGGER.debug("Jestem w setencodedpassword");
PasswordEncoder encoder = new ShaPasswordEncoder(256);
String encodedPassword = encoder.encodePassword(password, null);
person.setPassword(encodedPassword);
}
public void setBooleans(Person person, Boolean enabled, Boolean credentialsNonExpired, Boolean accountNonExpired,
Boolean accountNonLocked) {
LOGGER.debug("Jestem w setBooleans");
person.setEnabled(enabled);
person.setAccountNonExpired(accountNonExpired);
person.setAccountNonLocked(accountNonLocked);
person.setCredentialsNonExpired(credentialsNonExpired);
}
public Person getCurrentUser() {
LOGGER.debug("Entering getCurrentUser");
final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
LOGGER.debug("Principal: " + principal + " retrieved");
UserDetails userDetails = null;
if(principal instanceof UserDetails) {
userDetails = (UserDetails) principal;
LOGGER.debug("Principal casted to UserDetails: " + userDetails);
} else {
LOGGER.warn("Principal " + principal + " is not an instance of UserDetails!");
throw new SecurityException("Principal " + principal + " is not an instance of UserDetails!");
}
- return (Person) userDetails;
+ Person person = (Person) userDetails;
+ person = personDAO.getByPK(person.getId());
+ return person;
}
}
| true | true | public Person getCurrentUser() {
LOGGER.debug("Entering getCurrentUser");
final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
LOGGER.debug("Principal: " + principal + " retrieved");
UserDetails userDetails = null;
if(principal instanceof UserDetails) {
userDetails = (UserDetails) principal;
LOGGER.debug("Principal casted to UserDetails: " + userDetails);
} else {
LOGGER.warn("Principal " + principal + " is not an instance of UserDetails!");
throw new SecurityException("Principal " + principal + " is not an instance of UserDetails!");
}
return (Person) userDetails;
}
| public Person getCurrentUser() {
LOGGER.debug("Entering getCurrentUser");
final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
LOGGER.debug("Principal: " + principal + " retrieved");
UserDetails userDetails = null;
if(principal instanceof UserDetails) {
userDetails = (UserDetails) principal;
LOGGER.debug("Principal casted to UserDetails: " + userDetails);
} else {
LOGGER.warn("Principal " + principal + " is not an instance of UserDetails!");
throw new SecurityException("Principal " + principal + " is not an instance of UserDetails!");
}
Person person = (Person) userDetails;
person = personDAO.getByPK(person.getId());
return person;
}
|
diff --git a/src/savant/format/WIGToContinuous.java b/src/savant/format/WIGToContinuous.java
index 632cb97a..d30ef7b7 100644
--- a/src/savant/format/WIGToContinuous.java
+++ b/src/savant/format/WIGToContinuous.java
@@ -1,277 +1,279 @@
/*
* Copyright 2010 University of Toronto
*
* 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.
*/
/*
* WIGToContinuous.java
* Created on Mar 1, 2010
*/
package savant.format;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import savant.format.header.FileType;
import savant.format.header.FileTypeHeader;
import savant.format.util.data.FieldType;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Class to convert a WIG file to a Savant continuous generic file.
*/
public class WIGToContinuous {
private static final Log log = LogFactory.getLog(WIGToContinuous.class);
public static final int RECORDS_PER_INTERRUPT_CHECK = 100;
private String inFile;
private String outFile;
private DataOutputStream out;
// stuff needed by IO; mandated by DataFormatUtils which we're depending on
private List<FieldType> fields;
private List<Object> modifiers;
// variables to keep track of progress processing the input file(s)
private long totalBytes;
private long byteCount;
private int progress; // 0 to 100%
private List<FormatProgressListener> listeners = new ArrayList<FormatProgressListener>();
public WIGToContinuous(String inFile, String outFile) {
this.inFile = inFile;
this.outFile = outFile;
initOutput();
}
public void format() throws InterruptedException {
try {
File inputFile = new File(inFile);
// Initialize the total size of the input file, for purposes of tracking progress
this.totalBytes = inputFile.length();
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
String lineIn;
String[] tokens;
// Skip the header if it exists.
lineIn = reader.readLine();
// update bytes read from input
this.byteCount += lineIn.getBytes().length;
tokens = lineIn.split("\\s");
if (tokens.length > 0 && tokens[0].equals("track")){
lineIn = reader.readLine();
// update bytes read from input
this.byteCount += lineIn.getBytes().length;
}
//Read the rest of the file
String mode = "none";
int span = 1;
int start = 1;
int step = 1;
int nextWrite = 1;
boolean done = false;
while (!done) {
for (int j=0; j<RECORDS_PER_INTERRUPT_CHECK; j++) {
if (lineIn == null) {
done = true;
break;
}
tokens = lineIn.split("\\s");
if(tokens.length < 1){
//skip blank lines
continue;
}
if (tokens[0].equals("variableStep")){
if(tokens.length < 2){
log.fatal("Error parsing file (variableStep line)");
System.exit(1);
}
mode = "variable";
if(tokens.length == 3){
span = Integer.parseInt(tokens[2].substring(5));
} else {
span = 1;
}
} else if (tokens[0].equals("fixedStep")){
if(tokens.length < 4){
log.fatal("Error parsing file (fixedStep line)");
System.exit(1);
}
mode = "fixed";
start = Integer.parseInt(tokens[2].substring(6));
step = Integer.parseInt(tokens[3].substring(5));
if (tokens.length == 5){
span = Integer.parseInt(tokens[4].substring(5));
} else {
span = 1;
}
} else if (mode.equals("variable")){
if (tokens.length < 2){
log.fatal("Error parsing file (to few tokens on varialbe line)");
System.exit(1);
}
int dest = Integer.parseInt(tokens[0]);
this.fillWithZeros(nextWrite,dest,out);
float val = Float.parseFloat(tokens[1]);
for (int i = 0; i < span; i++){
out.writeFloat(val);
}
nextWrite = dest + span;
} else if (mode.equals("fixed")){
this.fillWithZeros(nextWrite,start,out);
float val = Float.parseFloat(tokens[0]);
for (int i = 0; i < span; i++){
out.writeFloat(val);
}
nextWrite = start+span;
start += step;
} else if (mode.equals("none")){
log.fatal("Error parsing file (no format line)");
System.exit(1);
}
lineIn = reader.readLine();
// update bytes read from input
- this.byteCount += lineIn.getBytes().length;
+ if (lineIn != null) {
+ this.byteCount += lineIn.getBytes().length;
+ }
}
// check to see if format has been cancelled
if (Thread.interrupted()) throw new InterruptedException();
// update progress property for UI
updateProgress();
}
} catch (FileNotFoundException e) {
log.error("File not found " + inFile);
} catch (IOException io) {
log.error("Error converting file " + inFile, io);
} finally {
closeOutput();
}
}
public int getProgress() {
return progress;
}
public void setProgress(int progress) {
this.progress = progress;
fireProgressUpdate(progress);
}
public void addProgressListener(FormatProgressListener listener) {
listeners.add(listener);
}
public void removeProgressListener(FormatProgressListener listener) {
listeners.remove(listener);
}
private void fireProgressUpdate(int value) {
for (FormatProgressListener listener : listeners) {
listener.progressUpdate(value);
}
}
private void initOutput() {
try {
// open output stream
out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(outFile)));
// write file type header
FileTypeHeader fileTypeHeader = new FileTypeHeader(FileType.CONTINUOUS_GENERIC, 1);
out.writeInt(fileTypeHeader.fileType.getMagicNumber());
out.writeInt(fileTypeHeader.version);
// prepare and write fields header
fields = new ArrayList<FieldType>();
fields.add(FieldType.FLOAT);
modifiers = new ArrayList<Object>();
modifiers.add(null);
out.writeInt(fields.size());
for (FieldType ft : fields) {
out.writeInt(ft.ordinal());
}
} catch (IOException e) {
log.error("Error preparing output file", e);
}
}
private void closeOutput() {
try {
if (out != null) out.close();
} catch (IOException e) {
log.warn("Error closing output file", e);
}
}
private void fillWithZeros(int curent, int dest,DataOutputStream out) throws IOException{
for (int i = curent; i < dest;i++){
out.writeFloat(0.0f);
}
}
private void updateProgress() {
float proportionDone = (float)this.byteCount/(float)this.totalBytes;
int percentDone = (int)Math.round(proportionDone * 100.0);
setProgress(percentDone);
}
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Missing argument: input file and output file required");
System.exit(1);
}
System.out.println("Start process: " + new Date().toString());
WIGToContinuous instance = new WIGToContinuous(args[0], args[1]);
try {
instance.format();
} catch (InterruptedException e) {
System.out.println("Formatting interrupted.");
}
finally {
System.out.println("End process: " + new Date().toString());
}
}
}
| true | true | public void format() throws InterruptedException {
try {
File inputFile = new File(inFile);
// Initialize the total size of the input file, for purposes of tracking progress
this.totalBytes = inputFile.length();
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
String lineIn;
String[] tokens;
// Skip the header if it exists.
lineIn = reader.readLine();
// update bytes read from input
this.byteCount += lineIn.getBytes().length;
tokens = lineIn.split("\\s");
if (tokens.length > 0 && tokens[0].equals("track")){
lineIn = reader.readLine();
// update bytes read from input
this.byteCount += lineIn.getBytes().length;
}
//Read the rest of the file
String mode = "none";
int span = 1;
int start = 1;
int step = 1;
int nextWrite = 1;
boolean done = false;
while (!done) {
for (int j=0; j<RECORDS_PER_INTERRUPT_CHECK; j++) {
if (lineIn == null) {
done = true;
break;
}
tokens = lineIn.split("\\s");
if(tokens.length < 1){
//skip blank lines
continue;
}
if (tokens[0].equals("variableStep")){
if(tokens.length < 2){
log.fatal("Error parsing file (variableStep line)");
System.exit(1);
}
mode = "variable";
if(tokens.length == 3){
span = Integer.parseInt(tokens[2].substring(5));
} else {
span = 1;
}
} else if (tokens[0].equals("fixedStep")){
if(tokens.length < 4){
log.fatal("Error parsing file (fixedStep line)");
System.exit(1);
}
mode = "fixed";
start = Integer.parseInt(tokens[2].substring(6));
step = Integer.parseInt(tokens[3].substring(5));
if (tokens.length == 5){
span = Integer.parseInt(tokens[4].substring(5));
} else {
span = 1;
}
} else if (mode.equals("variable")){
if (tokens.length < 2){
log.fatal("Error parsing file (to few tokens on varialbe line)");
System.exit(1);
}
int dest = Integer.parseInt(tokens[0]);
this.fillWithZeros(nextWrite,dest,out);
float val = Float.parseFloat(tokens[1]);
for (int i = 0; i < span; i++){
out.writeFloat(val);
}
nextWrite = dest + span;
} else if (mode.equals("fixed")){
this.fillWithZeros(nextWrite,start,out);
float val = Float.parseFloat(tokens[0]);
for (int i = 0; i < span; i++){
out.writeFloat(val);
}
nextWrite = start+span;
start += step;
} else if (mode.equals("none")){
log.fatal("Error parsing file (no format line)");
System.exit(1);
}
lineIn = reader.readLine();
// update bytes read from input
this.byteCount += lineIn.getBytes().length;
}
// check to see if format has been cancelled
if (Thread.interrupted()) throw new InterruptedException();
// update progress property for UI
updateProgress();
}
} catch (FileNotFoundException e) {
log.error("File not found " + inFile);
} catch (IOException io) {
log.error("Error converting file " + inFile, io);
} finally {
closeOutput();
}
}
| public void format() throws InterruptedException {
try {
File inputFile = new File(inFile);
// Initialize the total size of the input file, for purposes of tracking progress
this.totalBytes = inputFile.length();
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
String lineIn;
String[] tokens;
// Skip the header if it exists.
lineIn = reader.readLine();
// update bytes read from input
this.byteCount += lineIn.getBytes().length;
tokens = lineIn.split("\\s");
if (tokens.length > 0 && tokens[0].equals("track")){
lineIn = reader.readLine();
// update bytes read from input
this.byteCount += lineIn.getBytes().length;
}
//Read the rest of the file
String mode = "none";
int span = 1;
int start = 1;
int step = 1;
int nextWrite = 1;
boolean done = false;
while (!done) {
for (int j=0; j<RECORDS_PER_INTERRUPT_CHECK; j++) {
if (lineIn == null) {
done = true;
break;
}
tokens = lineIn.split("\\s");
if(tokens.length < 1){
//skip blank lines
continue;
}
if (tokens[0].equals("variableStep")){
if(tokens.length < 2){
log.fatal("Error parsing file (variableStep line)");
System.exit(1);
}
mode = "variable";
if(tokens.length == 3){
span = Integer.parseInt(tokens[2].substring(5));
} else {
span = 1;
}
} else if (tokens[0].equals("fixedStep")){
if(tokens.length < 4){
log.fatal("Error parsing file (fixedStep line)");
System.exit(1);
}
mode = "fixed";
start = Integer.parseInt(tokens[2].substring(6));
step = Integer.parseInt(tokens[3].substring(5));
if (tokens.length == 5){
span = Integer.parseInt(tokens[4].substring(5));
} else {
span = 1;
}
} else if (mode.equals("variable")){
if (tokens.length < 2){
log.fatal("Error parsing file (to few tokens on varialbe line)");
System.exit(1);
}
int dest = Integer.parseInt(tokens[0]);
this.fillWithZeros(nextWrite,dest,out);
float val = Float.parseFloat(tokens[1]);
for (int i = 0; i < span; i++){
out.writeFloat(val);
}
nextWrite = dest + span;
} else if (mode.equals("fixed")){
this.fillWithZeros(nextWrite,start,out);
float val = Float.parseFloat(tokens[0]);
for (int i = 0; i < span; i++){
out.writeFloat(val);
}
nextWrite = start+span;
start += step;
} else if (mode.equals("none")){
log.fatal("Error parsing file (no format line)");
System.exit(1);
}
lineIn = reader.readLine();
// update bytes read from input
if (lineIn != null) {
this.byteCount += lineIn.getBytes().length;
}
}
// check to see if format has been cancelled
if (Thread.interrupted()) throw new InterruptedException();
// update progress property for UI
updateProgress();
}
} catch (FileNotFoundException e) {
log.error("File not found " + inFile);
} catch (IOException io) {
log.error("Error converting file " + inFile, io);
} finally {
closeOutput();
}
}
|
diff --git a/picketlink-idm-hibernate/src/test/java/org/picketlink/idm/test/support/hibernate/HibernateTestPOJO.java b/picketlink-idm-hibernate/src/test/java/org/picketlink/idm/test/support/hibernate/HibernateTestPOJO.java
index 20a4639..685fcc1 100644
--- a/picketlink-idm-hibernate/src/test/java/org/picketlink/idm/test/support/hibernate/HibernateTestPOJO.java
+++ b/picketlink-idm-hibernate/src/test/java/org/picketlink/idm/test/support/hibernate/HibernateTestPOJO.java
@@ -1,141 +1,141 @@
package org.picketlink.idm.test.support.hibernate;
import java.util.LinkedList;
import java.util.List;
import junit.framework.Assert;
import org.hibernate.SessionFactory;
import org.picketlink.idm.test.support.IdentityTestPOJO;
import org.picketlink.idm.test.support.JNDISupport;
public class HibernateTestPOJO extends IdentityTestPOJO
{
protected String dataSourceName = "hsqldb";
protected String hibernateConfig = "datasources/hibernates.xml";
protected String datasources = "datasources/datasources.xml";
protected HibernateSupport hibernateSupport;
public void start() throws Exception
{
overrideFromProperties();
JNDISupport jndiSupport = new JNDISupport();
jndiSupport.start();
identityConfig = "hibernate-test-identity-config.xml";
DataSourceConfig dataSourceConfig = DataSourceConfig.obtainConfig(datasources, dataSourceName);
HibernateSupport.Config hibernateSupportConfig = HibernateSupport.getConfig(dataSourceName, hibernateConfig);
hibernateSupport = new HibernateSupport();
hibernateSupport.setConfig(hibernateSupportConfig);
hibernateSupport.setDataSourceConfig(dataSourceConfig);
hibernateSupport.setJNDIName("java:/jbossidentity/HibernateStoreSessionFactory");
String prefix = "mappings/";
//Sybase support hack
- if (dataSourceName.startsWith("sybase-"))
+ if (dataSourceName.startsWith("sybase"))
{
prefix = "sybase-mappings/";
}
List<String> mappings = new LinkedList<String>();
mappings.add(prefix + "HibernateIdentityObject.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectCredentialBinaryValue.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectAttributeBinaryValue.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectAttribute.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectCredential.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectCredentialType.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectRelationship.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectRelationshipName.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectRelationshipType.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectType.hbm.xml");
mappings.add(prefix + "HibernateRealm.hbm.xml");
hibernateSupport.setMappings(mappings);
hibernateSupport.start();
}
public void stop() throws Exception
{
hibernateSupport.getSessionFactory().getStatistics().logSummary();
hibernateSupport.stop();
}
public void overrideFromProperties() throws Exception
{
String dsName = System.getProperties().getProperty("dataSourceName");
if (dsName != null && dsName.length() > 0 && !dsName.startsWith("$"))
{
setDataSourceName(dsName);
}
}
public SessionFactory getSessionFactory()
{
return getHibernateSupport().getSessionFactory();
}
public void setDataSourceName(String dataSourceName)
{
this.dataSourceName = dataSourceName;
}
public void setHibernateConfig(String hibernateConfig)
{
this.hibernateConfig = hibernateConfig;
}
public void setDatasources(String datasources)
{
this.datasources = datasources;
}
public String getDataSourceName()
{
return dataSourceName;
}
public String getHibernateConfig()
{
return hibernateConfig;
}
public String getDatasources()
{
return datasources;
}
public HibernateSupport getHibernateSupport()
{
return hibernateSupport;
}
public void begin()
{
getHibernateSupport().getCurrentSession().getTransaction().begin();
}
public void commit()
{
Assert.assertTrue(getHibernateSupport().commitTransaction());
}
}
| true | true | public void start() throws Exception
{
overrideFromProperties();
JNDISupport jndiSupport = new JNDISupport();
jndiSupport.start();
identityConfig = "hibernate-test-identity-config.xml";
DataSourceConfig dataSourceConfig = DataSourceConfig.obtainConfig(datasources, dataSourceName);
HibernateSupport.Config hibernateSupportConfig = HibernateSupport.getConfig(dataSourceName, hibernateConfig);
hibernateSupport = new HibernateSupport();
hibernateSupport.setConfig(hibernateSupportConfig);
hibernateSupport.setDataSourceConfig(dataSourceConfig);
hibernateSupport.setJNDIName("java:/jbossidentity/HibernateStoreSessionFactory");
String prefix = "mappings/";
//Sybase support hack
if (dataSourceName.startsWith("sybase-"))
{
prefix = "sybase-mappings/";
}
List<String> mappings = new LinkedList<String>();
mappings.add(prefix + "HibernateIdentityObject.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectCredentialBinaryValue.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectAttributeBinaryValue.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectAttribute.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectCredential.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectCredentialType.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectRelationship.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectRelationshipName.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectRelationshipType.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectType.hbm.xml");
mappings.add(prefix + "HibernateRealm.hbm.xml");
hibernateSupport.setMappings(mappings);
hibernateSupport.start();
}
| public void start() throws Exception
{
overrideFromProperties();
JNDISupport jndiSupport = new JNDISupport();
jndiSupport.start();
identityConfig = "hibernate-test-identity-config.xml";
DataSourceConfig dataSourceConfig = DataSourceConfig.obtainConfig(datasources, dataSourceName);
HibernateSupport.Config hibernateSupportConfig = HibernateSupport.getConfig(dataSourceName, hibernateConfig);
hibernateSupport = new HibernateSupport();
hibernateSupport.setConfig(hibernateSupportConfig);
hibernateSupport.setDataSourceConfig(dataSourceConfig);
hibernateSupport.setJNDIName("java:/jbossidentity/HibernateStoreSessionFactory");
String prefix = "mappings/";
//Sybase support hack
if (dataSourceName.startsWith("sybase"))
{
prefix = "sybase-mappings/";
}
List<String> mappings = new LinkedList<String>();
mappings.add(prefix + "HibernateIdentityObject.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectCredentialBinaryValue.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectAttributeBinaryValue.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectAttribute.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectCredential.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectCredentialType.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectRelationship.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectRelationshipName.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectRelationshipType.hbm.xml");
mappings.add(prefix + "HibernateIdentityObjectType.hbm.xml");
mappings.add(prefix + "HibernateRealm.hbm.xml");
hibernateSupport.setMappings(mappings);
hibernateSupport.start();
}
|
diff --git a/core/src/main/java/org/apache/mahout/classifier/naivebayes/test/TestNaiveBayesDriver.java b/core/src/main/java/org/apache/mahout/classifier/naivebayes/test/TestNaiveBayesDriver.java
index c82c4987..9fe8b6a0 100644
--- a/core/src/main/java/org/apache/mahout/classifier/naivebayes/test/TestNaiveBayesDriver.java
+++ b/core/src/main/java/org/apache/mahout/classifier/naivebayes/test/TestNaiveBayesDriver.java
@@ -1,162 +1,162 @@
/**
* 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.mahout.classifier.naivebayes.test;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.SequenceFile.Reader;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.util.ToolRunner;
import org.apache.mahout.classifier.ClassifierResult;
import org.apache.mahout.classifier.ResultAnalyzer;
import org.apache.mahout.classifier.naivebayes.AbstractNaiveBayesClassifier;
import org.apache.mahout.classifier.naivebayes.BayesUtils;
import org.apache.mahout.classifier.naivebayes.ComplementaryNaiveBayesClassifier;
import org.apache.mahout.classifier.naivebayes.NaiveBayesModel;
import org.apache.mahout.classifier.naivebayes.StandardNaiveBayesClassifier;
import org.apache.mahout.common.AbstractJob;
import org.apache.mahout.common.HadoopUtil;
import org.apache.mahout.common.Pair;
import org.apache.mahout.common.commandline.DefaultOptionCreator;
import org.apache.mahout.common.iterator.sequencefile.PathFilters;
import org.apache.mahout.common.iterator.sequencefile.PathType;
import org.apache.mahout.common.iterator.sequencefile.SequenceFileDirIterable;
import org.apache.mahout.math.Vector;
import org.apache.mahout.math.VectorWritable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Test the (Complementary) Naive Bayes model that was built during training
* by running the iterating the test set and comparing it to the model
*/
public class TestNaiveBayesDriver extends AbstractJob {
private static final Logger log = LoggerFactory.getLogger(TestNaiveBayesDriver.class);
public static final String LABEL_KEY = "labels";
public static final String COMPLEMENTARY = "class"; //b for bayes, c for complementary
public static void main(String[] args) throws Exception {
ToolRunner.run(new Configuration(), new TestNaiveBayesDriver(), args);
}
@Override
public int run(String[] args) throws Exception {
addInputOption();
addOutputOption();
addOption(addOption(DefaultOptionCreator.overwriteOption().create()));
addOption("model", "m", "The path to the model built during training", true);
addOption(buildOption("testComplementary", "c", "test complementary?", false, false, String.valueOf(false)));
- addOption(buildOption("runSequential", "seq", "run sequential?", true, false, String.valueOf(false)));
+ addOption(buildOption("runSequential", "seq", "run sequential?", false, false, String.valueOf(false)));
addOption("labelIndex", "l", "The path to the location of the label index", true);
Map<String, List<String>> parsedArgs = parseArguments(args);
if (parsedArgs == null) {
return -1;
}
if (hasOption(DefaultOptionCreator.OVERWRITE_OPTION)) {
HadoopUtil.delete(getConf(), getOutputPath());
}
- boolean complementary = parsedArgs.containsKey("testComplementary");
- boolean sequential = Boolean.parseBoolean(getOption("runSequential"));
+ boolean complementary = hasOption("testComplementary");
+ boolean sequential = hasOption("runSequential");
if (sequential) {
FileSystem fs = FileSystem.get(getConf());
NaiveBayesModel model = NaiveBayesModel.materialize(new Path(getOption("model")), getConf());
AbstractNaiveBayesClassifier classifier;
if (complementary) {
classifier = new ComplementaryNaiveBayesClassifier(model);
} else {
classifier = new StandardNaiveBayesClassifier(model);
}
SequenceFile.Writer writer =
new SequenceFile.Writer(fs, getConf(), getOutputPath(), Text.class, VectorWritable.class);
SequenceFile.Reader reader = new Reader(fs, getInputPath(), getConf());
Text key = new Text();
VectorWritable vw = new VectorWritable();
while (reader.next(key, vw)) {
writer.append(new Text(key.toString().split("/")[1]),
new VectorWritable(classifier.classifyFull(vw.get())));
}
writer.close();
reader.close();
} else {
boolean succeeded = runMapReduce(parsedArgs);
if (!succeeded) {
return -1;
}
}
//load the labels
Map<Integer, String> labelMap = BayesUtils.readLabelIndex(getConf(), new Path(getOption("labelIndex")));
//loop over the results and create the confusion matrix
SequenceFileDirIterable<Text, VectorWritable> dirIterable =
new SequenceFileDirIterable<Text, VectorWritable>(getOutputPath(),
PathType.LIST,
PathFilters.partFilter(),
getConf());
ResultAnalyzer analyzer = new ResultAnalyzer(labelMap.values(), "DEFAULT");
analyzeResults(labelMap, dirIterable, analyzer);
log.info("{} Results: {}", complementary ? "Complementary" : "Standard NB", analyzer);
return 0;
}
private boolean runMapReduce(Map<String, List<String>> parsedArgs) throws IOException,
InterruptedException, ClassNotFoundException {
Path model = new Path(getOption("model"));
HadoopUtil.cacheFiles(model, getConf());
//the output key is the expected value, the output value are the scores for all the labels
Job testJob = prepareJob(getInputPath(), getOutputPath(), SequenceFileInputFormat.class, BayesTestMapper.class,
Text.class, VectorWritable.class, SequenceFileOutputFormat.class);
//testJob.getConfiguration().set(LABEL_KEY, getOption("--labels"));
boolean complementary = parsedArgs.containsKey("testComplementary");
testJob.getConfiguration().set(COMPLEMENTARY, String.valueOf(complementary));
boolean succeeded = testJob.waitForCompletion(true);
return succeeded;
}
private static void analyzeResults(Map<Integer, String> labelMap,
SequenceFileDirIterable<Text, VectorWritable> dirIterable,
ResultAnalyzer analyzer) {
for (Pair<Text, VectorWritable> pair : dirIterable) {
int bestIdx = Integer.MIN_VALUE;
double bestScore = Long.MIN_VALUE;
for (Vector.Element element : pair.getSecond().get()) {
if (element.get() > bestScore) {
bestScore = element.get();
bestIdx = element.index();
}
}
if (bestIdx != Integer.MIN_VALUE) {
ClassifierResult classifierResult = new ClassifierResult(labelMap.get(bestIdx), bestScore);
analyzer.addInstance(pair.getFirst().toString(), classifierResult);
}
}
}
}
| false | true | public int run(String[] args) throws Exception {
addInputOption();
addOutputOption();
addOption(addOption(DefaultOptionCreator.overwriteOption().create()));
addOption("model", "m", "The path to the model built during training", true);
addOption(buildOption("testComplementary", "c", "test complementary?", false, false, String.valueOf(false)));
addOption(buildOption("runSequential", "seq", "run sequential?", true, false, String.valueOf(false)));
addOption("labelIndex", "l", "The path to the location of the label index", true);
Map<String, List<String>> parsedArgs = parseArguments(args);
if (parsedArgs == null) {
return -1;
}
if (hasOption(DefaultOptionCreator.OVERWRITE_OPTION)) {
HadoopUtil.delete(getConf(), getOutputPath());
}
boolean complementary = parsedArgs.containsKey("testComplementary");
boolean sequential = Boolean.parseBoolean(getOption("runSequential"));
if (sequential) {
FileSystem fs = FileSystem.get(getConf());
NaiveBayesModel model = NaiveBayesModel.materialize(new Path(getOption("model")), getConf());
AbstractNaiveBayesClassifier classifier;
if (complementary) {
classifier = new ComplementaryNaiveBayesClassifier(model);
} else {
classifier = new StandardNaiveBayesClassifier(model);
}
SequenceFile.Writer writer =
new SequenceFile.Writer(fs, getConf(), getOutputPath(), Text.class, VectorWritable.class);
SequenceFile.Reader reader = new Reader(fs, getInputPath(), getConf());
Text key = new Text();
VectorWritable vw = new VectorWritable();
while (reader.next(key, vw)) {
writer.append(new Text(key.toString().split("/")[1]),
new VectorWritable(classifier.classifyFull(vw.get())));
}
writer.close();
reader.close();
} else {
boolean succeeded = runMapReduce(parsedArgs);
if (!succeeded) {
return -1;
}
}
//load the labels
Map<Integer, String> labelMap = BayesUtils.readLabelIndex(getConf(), new Path(getOption("labelIndex")));
//loop over the results and create the confusion matrix
SequenceFileDirIterable<Text, VectorWritable> dirIterable =
new SequenceFileDirIterable<Text, VectorWritable>(getOutputPath(),
PathType.LIST,
PathFilters.partFilter(),
getConf());
ResultAnalyzer analyzer = new ResultAnalyzer(labelMap.values(), "DEFAULT");
analyzeResults(labelMap, dirIterable, analyzer);
log.info("{} Results: {}", complementary ? "Complementary" : "Standard NB", analyzer);
return 0;
}
| public int run(String[] args) throws Exception {
addInputOption();
addOutputOption();
addOption(addOption(DefaultOptionCreator.overwriteOption().create()));
addOption("model", "m", "The path to the model built during training", true);
addOption(buildOption("testComplementary", "c", "test complementary?", false, false, String.valueOf(false)));
addOption(buildOption("runSequential", "seq", "run sequential?", false, false, String.valueOf(false)));
addOption("labelIndex", "l", "The path to the location of the label index", true);
Map<String, List<String>> parsedArgs = parseArguments(args);
if (parsedArgs == null) {
return -1;
}
if (hasOption(DefaultOptionCreator.OVERWRITE_OPTION)) {
HadoopUtil.delete(getConf(), getOutputPath());
}
boolean complementary = hasOption("testComplementary");
boolean sequential = hasOption("runSequential");
if (sequential) {
FileSystem fs = FileSystem.get(getConf());
NaiveBayesModel model = NaiveBayesModel.materialize(new Path(getOption("model")), getConf());
AbstractNaiveBayesClassifier classifier;
if (complementary) {
classifier = new ComplementaryNaiveBayesClassifier(model);
} else {
classifier = new StandardNaiveBayesClassifier(model);
}
SequenceFile.Writer writer =
new SequenceFile.Writer(fs, getConf(), getOutputPath(), Text.class, VectorWritable.class);
SequenceFile.Reader reader = new Reader(fs, getInputPath(), getConf());
Text key = new Text();
VectorWritable vw = new VectorWritable();
while (reader.next(key, vw)) {
writer.append(new Text(key.toString().split("/")[1]),
new VectorWritable(classifier.classifyFull(vw.get())));
}
writer.close();
reader.close();
} else {
boolean succeeded = runMapReduce(parsedArgs);
if (!succeeded) {
return -1;
}
}
//load the labels
Map<Integer, String> labelMap = BayesUtils.readLabelIndex(getConf(), new Path(getOption("labelIndex")));
//loop over the results and create the confusion matrix
SequenceFileDirIterable<Text, VectorWritable> dirIterable =
new SequenceFileDirIterable<Text, VectorWritable>(getOutputPath(),
PathType.LIST,
PathFilters.partFilter(),
getConf());
ResultAnalyzer analyzer = new ResultAnalyzer(labelMap.values(), "DEFAULT");
analyzeResults(labelMap, dirIterable, analyzer);
log.info("{} Results: {}", complementary ? "Complementary" : "Standard NB", analyzer);
return 0;
}
|
diff --git a/astrid/plugin-src/com/todoroo/astrid/tags/TagFilterExposer.java b/astrid/plugin-src/com/todoroo/astrid/tags/TagFilterExposer.java
index c360b1014..a4c78b7ad 100644
--- a/astrid/plugin-src/com/todoroo/astrid/tags/TagFilterExposer.java
+++ b/astrid/plugin-src/com/todoroo/astrid/tags/TagFilterExposer.java
@@ -1,327 +1,327 @@
/**
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.tags;
import java.util.ArrayList;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Toast;
import com.timsu.astrid.R;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.service.ContextManager;
import com.todoroo.andlib.service.DependencyInjectionService;
import com.todoroo.andlib.sql.Criterion;
import com.todoroo.andlib.sql.QueryTemplate;
import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.andlib.utility.DialogUtilities;
import com.todoroo.astrid.actfm.TagViewFragment;
import com.todoroo.astrid.activity.TaskListFragment;
import com.todoroo.astrid.api.AstridApiConstants;
import com.todoroo.astrid.api.AstridFilterExposer;
import com.todoroo.astrid.api.Filter;
import com.todoroo.astrid.api.FilterCategory;
import com.todoroo.astrid.api.FilterListItem;
import com.todoroo.astrid.api.FilterWithCustomIntent;
import com.todoroo.astrid.api.FilterWithUpdate;
import com.todoroo.astrid.core.PluginServices;
import com.todoroo.astrid.dao.TaskDao.TaskCriteria;
import com.todoroo.astrid.data.Metadata;
import com.todoroo.astrid.data.TagData;
import com.todoroo.astrid.gtasks.GtasksPreferenceService;
import com.todoroo.astrid.service.AstridDependencyInjector;
import com.todoroo.astrid.service.TagDataService;
import com.todoroo.astrid.tags.TagService.Tag;
/**
* Exposes filters based on tags
*
* @author Tim Su <[email protected]>
*
*/
public class TagFilterExposer extends BroadcastReceiver implements AstridFilterExposer {
private static final String TAG = "tag"; //$NON-NLS-1$
public static final String TAG_SQL = "tagSql"; //$NON-NLS-1$
@Autowired TagDataService tagDataService;
@Autowired GtasksPreferenceService gtasksPreferenceService;
/** Create filter from new tag object */
@SuppressWarnings("nls")
public static FilterWithCustomIntent filterFromTag(Context context, Tag tag, Criterion criterion) {
String title = tag.tag;
QueryTemplate tagTemplate = tag.queryTemplate(criterion);
ContentValues contentValues = new ContentValues();
contentValues.put(Metadata.KEY.name, TagService.KEY);
contentValues.put(TagService.TAG.name, tag.tag);
FilterWithUpdate filter = new FilterWithUpdate(tag.tag,
title, tagTemplate,
contentValues);
if(tag.remoteId > 0) {
filter.listingTitle += " (" + tag.count + ")";
if(tag.count == 0)
filter.color = Color.GRAY;
}
TagData tagData = PluginServices.getTagDataService().getTag(tag.tag, TagData.ID, TagData.USER_ID, TagData.MEMBER_COUNT);
int deleteIntentLabel;
- if (tagData.getValue(TagData.MEMBER_COUNT) > 0 && tagData.getValue(TagData.USER_ID) != 0)
+ if (tagData != null && tagData.getValue(TagData.MEMBER_COUNT) > 0 && tagData.getValue(TagData.USER_ID) != 0)
deleteIntentLabel = R.string.tag_cm_leave;
else
deleteIntentLabel = R.string.tag_cm_delete;
filter.contextMenuLabels = new String[] {
context.getString(R.string.tag_cm_rename),
context.getString(deleteIntentLabel)
};
filter.contextMenuIntents = new Intent[] {
newTagIntent(context, RenameTagActivity.class, tag, tagTemplate.toString()),
newTagIntent(context, DeleteTagActivity.class, tag, tagTemplate.toString())
};
filter.customTaskList = new ComponentName(ContextManager.getContext(), TagViewFragment.class);
if(tag.image != null)
filter.imageUrl = tag.image;
if(tag.updateText != null)
filter.updateText = tag.updateText;
Bundle extras = new Bundle();
extras.putString(TagViewFragment.EXTRA_TAG_NAME, tag.tag);
extras.putLong(TagViewFragment.EXTRA_TAG_REMOTE_ID, tag.remoteId);
extras.putBoolean(TaskListFragment.TOKEN_OVERRIDE_ANIM, true);
filter.customExtras = extras;
return filter;
}
/** Create a filter from tag data object */
public static Filter filterFromTagData(Context context, TagData tagData) {
Tag tag = new Tag(tagData.getValue(TagData.NAME),
tagData.getValue(TagData.TASK_COUNT),
tagData.getValue(TagData.REMOTE_ID));
return filterFromTag(context, tag, TaskCriteria.activeAndVisible());
}
private static Intent newTagIntent(Context context, Class<? extends Activity> activity, Tag tag, String sql) {
Intent ret = new Intent(context, activity);
ret.putExtra(TAG, tag.tag);
ret.putExtra(TAG_SQL, sql);
return ret;
}
@Override
public void onReceive(Context context, Intent intent) {
FilterListItem[] listAsArray = prepareFilters(context);
Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_SEND_FILTERS);
broadcastIntent.putExtra(AstridApiConstants.EXTRAS_RESPONSE, listAsArray);
broadcastIntent.putExtra(AstridApiConstants.EXTRAS_ADDON, TagsPlugin.IDENTIFIER);
context.sendBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ);
}
private FilterListItem[] prepareFilters(Context context) {
DependencyInjectionService.getInstance().inject(this);
ContextManager.setContext(context);
ArrayList<FilterListItem> list = new ArrayList<FilterListItem>();
addTags(list);
// transmit filter list
FilterListItem[] listAsArray = list.toArray(new FilterListItem[list.size()]);
return listAsArray;
}
private void addTags(ArrayList<FilterListItem> list) {
ArrayList<Tag> tagList = TagService.getInstance().getTagList();
list.add(filterFromTags(tagList.toArray(new Tag[tagList.size()]),
R.string.tag_FEx_header));
}
private FilterCategory filterFromTags(Tag[] tags, int name) {
Filter[] filters = new Filter[tags.length + 1];
Context context = ContextManager.getContext();
Resources r = context.getResources();
// --- untagged
int untaggedLabel = gtasksPreferenceService.isLoggedIn() ?
R.string.tag_FEx_untagged_w_astrid : R.string.tag_FEx_untagged;
Filter untagged = new Filter(r.getString(untaggedLabel),
r.getString(R.string.tag_FEx_untagged),
TagService.untaggedTemplate(),
null);
untagged.listingIcon = ((BitmapDrawable)r.getDrawable(R.drawable.gl_lists)).getBitmap();
filters[0] = untagged;
for(int i = 0; i < tags.length; i++)
filters[i+1] = filterFromTag(context, tags[i], TaskCriteria.activeAndVisible());
FilterCategory filter = new FilterCategory(context.getString(name), filters);
return filter;
}
// --- tag manipulation activities
public abstract static class TagActivity extends Activity {
protected String tag;
protected String sql;
@Autowired public TagService tagService;
@Autowired public TagDataService tagDataService;
static {
AstridDependencyInjector.initialize();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tag = getIntent().getStringExtra(TAG);
sql = getIntent().getStringExtra(TAG_SQL);
if(tag == null) {
finish();
return;
}
DependencyInjectionService.getInstance().inject(this);
TagData tagData = tagDataService.getTag(tag, TagData.MEMBER_COUNT, TagData.USER_ID);
if(tagData != null && tagData.getValue(TagData.MEMBER_COUNT) > 0 && tagData.getValue(TagData.USER_ID) == 0) {
DialogUtilities.okCancelDialog(this, getString(R.string.actfm_tag_operation_owner_delete), getOkListener(), getCancelListener());
return;
}
showDialog(tagData);
}
protected DialogInterface.OnClickListener getOkListener() {
return new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
if (ok()) {
setResult(RESULT_OK);
} else {
toastNoChanges();
setResult(RESULT_CANCELED);
}
} finally {
finish();
}
}
};
}
protected DialogInterface.OnClickListener getCancelListener() {
return new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
toastNoChanges();
} finally {
setResult(RESULT_CANCELED);
finish();
}
}
};
}
private void toastNoChanges() {
Toast.makeText(this, R.string.TEA_no_tags_modified,
Toast.LENGTH_SHORT).show();
}
protected abstract void showDialog(TagData tagData);
protected abstract boolean ok();
}
public static class DeleteTagActivity extends TagActivity {
@Override
protected void showDialog(TagData tagData) {
int string;
if (tagData != null && tagData.getValue(TagData.MEMBER_COUNT) > 0)
string = R.string.DLG_leave_this_shared_tag_question;
else
string = R.string.DLG_delete_this_tag_question;
DialogUtilities.okCancelDialog(this, getString(string, tag), getOkListener(), getCancelListener());
}
@Override
protected boolean ok() {
int deleted = tagService.delete(tag);
TagData tagData = PluginServices.getTagDataService().getTag(tag, TagData.ID, TagData.DELETION_DATE, TagData.MEMBER_COUNT, TagData.USER_ID);
boolean shared = false;
if(tagData != null) {
tagData.setValue(TagData.DELETION_DATE, DateUtilities.now());
PluginServices.getTagDataService().save(tagData);
shared = tagData.getValue(TagData.MEMBER_COUNT) > 0 && tagData.getValue(TagData.USER_ID) != 0; // Was I a list member and NOT owner?
}
Toast.makeText(this, getString(shared ? R.string.TEA_tags_left : R.string.TEA_tags_deleted, tag, deleted),
Toast.LENGTH_SHORT).show();
Intent tagDeleted = new Intent(AstridApiConstants.BROADCAST_EVENT_TAG_DELETED);
tagDeleted.putExtra(TagViewFragment.EXTRA_TAG_NAME, tag);
tagDeleted.putExtra(TAG_SQL, sql);
sendBroadcast(tagDeleted);
return true;
}
}
public static class RenameTagActivity extends TagActivity {
private EditText editor;
@Override
protected void showDialog(TagData tagData) {
editor = new EditText(this);
DialogUtilities.viewDialog(this, getString(R.string.DLG_rename_this_tag_header, tag), editor, getOkListener(), getCancelListener());
}
@Override
protected boolean ok() {
if(editor == null)
return false;
String text = editor.getText().toString();
if (text == null || text.length() == 0) {
return false;
} else {
int renamed = tagService.rename(tag, text);
TagData tagData = tagDataService.getTag(tag, TagData.ID, TagData.NAME);
if (tagData != null) {
tagData.setValue(TagData.NAME, text);
tagDataService.save(tagData);
}
Toast.makeText(this, getString(R.string.TEA_tags_renamed, tag, text, renamed),
Toast.LENGTH_SHORT).show();
return true;
}
}
}
@Override
public FilterListItem[] getFilters() {
if (ContextManager.getContext() == null)
return null;
return prepareFilters(ContextManager.getContext());
}
}
| true | true | public static FilterWithCustomIntent filterFromTag(Context context, Tag tag, Criterion criterion) {
String title = tag.tag;
QueryTemplate tagTemplate = tag.queryTemplate(criterion);
ContentValues contentValues = new ContentValues();
contentValues.put(Metadata.KEY.name, TagService.KEY);
contentValues.put(TagService.TAG.name, tag.tag);
FilterWithUpdate filter = new FilterWithUpdate(tag.tag,
title, tagTemplate,
contentValues);
if(tag.remoteId > 0) {
filter.listingTitle += " (" + tag.count + ")";
if(tag.count == 0)
filter.color = Color.GRAY;
}
TagData tagData = PluginServices.getTagDataService().getTag(tag.tag, TagData.ID, TagData.USER_ID, TagData.MEMBER_COUNT);
int deleteIntentLabel;
if (tagData.getValue(TagData.MEMBER_COUNT) > 0 && tagData.getValue(TagData.USER_ID) != 0)
deleteIntentLabel = R.string.tag_cm_leave;
else
deleteIntentLabel = R.string.tag_cm_delete;
filter.contextMenuLabels = new String[] {
context.getString(R.string.tag_cm_rename),
context.getString(deleteIntentLabel)
};
filter.contextMenuIntents = new Intent[] {
newTagIntent(context, RenameTagActivity.class, tag, tagTemplate.toString()),
newTagIntent(context, DeleteTagActivity.class, tag, tagTemplate.toString())
};
filter.customTaskList = new ComponentName(ContextManager.getContext(), TagViewFragment.class);
if(tag.image != null)
filter.imageUrl = tag.image;
if(tag.updateText != null)
filter.updateText = tag.updateText;
Bundle extras = new Bundle();
extras.putString(TagViewFragment.EXTRA_TAG_NAME, tag.tag);
extras.putLong(TagViewFragment.EXTRA_TAG_REMOTE_ID, tag.remoteId);
extras.putBoolean(TaskListFragment.TOKEN_OVERRIDE_ANIM, true);
filter.customExtras = extras;
return filter;
}
| public static FilterWithCustomIntent filterFromTag(Context context, Tag tag, Criterion criterion) {
String title = tag.tag;
QueryTemplate tagTemplate = tag.queryTemplate(criterion);
ContentValues contentValues = new ContentValues();
contentValues.put(Metadata.KEY.name, TagService.KEY);
contentValues.put(TagService.TAG.name, tag.tag);
FilterWithUpdate filter = new FilterWithUpdate(tag.tag,
title, tagTemplate,
contentValues);
if(tag.remoteId > 0) {
filter.listingTitle += " (" + tag.count + ")";
if(tag.count == 0)
filter.color = Color.GRAY;
}
TagData tagData = PluginServices.getTagDataService().getTag(tag.tag, TagData.ID, TagData.USER_ID, TagData.MEMBER_COUNT);
int deleteIntentLabel;
if (tagData != null && tagData.getValue(TagData.MEMBER_COUNT) > 0 && tagData.getValue(TagData.USER_ID) != 0)
deleteIntentLabel = R.string.tag_cm_leave;
else
deleteIntentLabel = R.string.tag_cm_delete;
filter.contextMenuLabels = new String[] {
context.getString(R.string.tag_cm_rename),
context.getString(deleteIntentLabel)
};
filter.contextMenuIntents = new Intent[] {
newTagIntent(context, RenameTagActivity.class, tag, tagTemplate.toString()),
newTagIntent(context, DeleteTagActivity.class, tag, tagTemplate.toString())
};
filter.customTaskList = new ComponentName(ContextManager.getContext(), TagViewFragment.class);
if(tag.image != null)
filter.imageUrl = tag.image;
if(tag.updateText != null)
filter.updateText = tag.updateText;
Bundle extras = new Bundle();
extras.putString(TagViewFragment.EXTRA_TAG_NAME, tag.tag);
extras.putLong(TagViewFragment.EXTRA_TAG_REMOTE_ID, tag.remoteId);
extras.putBoolean(TaskListFragment.TOKEN_OVERRIDE_ANIM, true);
filter.customExtras = extras;
return filter;
}
|
diff --git a/servicemix-core/src/main/java/org/apache/servicemix/components/util/BinaryFileMarshaler.java b/servicemix-core/src/main/java/org/apache/servicemix/components/util/BinaryFileMarshaler.java
index e3974f460..988704a22 100644
--- a/servicemix-core/src/main/java/org/apache/servicemix/components/util/BinaryFileMarshaler.java
+++ b/servicemix-core/src/main/java/org/apache/servicemix/components/util/BinaryFileMarshaler.java
@@ -1,77 +1,77 @@
/*
* Copyright 2005-2006 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.servicemix.components.util;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.jbi.JBIException;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.MessagingException;
import javax.jbi.messaging.NormalizedMessage;
import org.apache.servicemix.jbi.util.FileUtil;
import org.apache.servicemix.jbi.util.StreamDataSource;
/**
* A FileMarshaler that converts the given input stream into a binary attachment.
*
* @author Guillaume Nodet
* @since 3.0
*/
public class BinaryFileMarshaler extends DefaultFileMarshaler {
private String attachment = "content";
private String contentType = null;
public String getAttachment() {
return attachment;
}
public void setAttachment(String attachment) {
this.attachment = attachment;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public void readMessage(MessageExchange exchange, NormalizedMessage message, InputStream in, String path) throws IOException, JBIException {
DataSource ds = new StreamDataSource(in, contentType);
DataHandler handler = new DataHandler(ds);
message.addAttachment(attachment, handler);
message.setProperty(FILE_NAME_PROPERTY, new File(path).getName());
message.setProperty(FILE_PATH_PROPERTY, path);
}
public void writeMessage(MessageExchange exchange, NormalizedMessage message, OutputStream out, String path) throws IOException, JBIException {
DataHandler handler = message.getAttachment(attachment);
- if (attachment == null) {
+ if (handler == null) {
throw new MessagingException("Could not find attachment: " + attachment);
}
InputStream is = handler.getInputStream();
FileUtil.copyInputStream(is, out);
}
}
| true | true | public void writeMessage(MessageExchange exchange, NormalizedMessage message, OutputStream out, String path) throws IOException, JBIException {
DataHandler handler = message.getAttachment(attachment);
if (attachment == null) {
throw new MessagingException("Could not find attachment: " + attachment);
}
InputStream is = handler.getInputStream();
FileUtil.copyInputStream(is, out);
}
| public void writeMessage(MessageExchange exchange, NormalizedMessage message, OutputStream out, String path) throws IOException, JBIException {
DataHandler handler = message.getAttachment(attachment);
if (handler == null) {
throw new MessagingException("Could not find attachment: " + attachment);
}
InputStream is = handler.getInputStream();
FileUtil.copyInputStream(is, out);
}
|
diff --git a/org.eclipse.rmf.reqif10.search.test/src/org/eclipse/rmf/reqif10/search/test/DateFilterTest.java b/org.eclipse.rmf.reqif10.search.test/src/org/eclipse/rmf/reqif10/search/test/DateFilterTest.java
index a381c117..c7fc0845 100644
--- a/org.eclipse.rmf.reqif10.search.test/src/org/eclipse/rmf/reqif10/search/test/DateFilterTest.java
+++ b/org.eclipse.rmf.reqif10.search.test/src/org/eclipse/rmf/reqif10/search/test/DateFilterTest.java
@@ -1,345 +1,345 @@
/*******************************************************************************
* Copyright (c) 2014 Formal Mind GmbH.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Ingo Weigelt - initial API and implementation
* Michael Jastram - adding SUPPORTED_OPERATIONS
******************************************************************************/
package org.eclipse.rmf.reqif10.search.test;
import static org.junit.Assert.fail;
import java.util.GregorianCalendar;
import java.util.Set;
import java.util.TimeZone;
import org.eclipse.rmf.reqif10.AttributeDefinitionDate;
import org.eclipse.rmf.reqif10.AttributeValueDate;
import org.eclipse.rmf.reqif10.DatatypeDefinitionDate;
import org.eclipse.rmf.reqif10.ReqIF10Factory;
import org.eclipse.rmf.reqif10.SpecObject;
import org.eclipse.rmf.reqif10.search.filter.DateFilter;
import org.eclipse.rmf.reqif10.search.filter.DateFilter.InternalAttribute;
import org.eclipse.rmf.reqif10.search.filter.IFilter;
import org.eclipse.rmf.reqif10.search.filter.IFilter.Operator;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class DateFilterTest extends AbstractFilterTest{
SpecObject specObject;
AttributeDefinitionDate attributeDefinition;
@Rule public ExpectedException thrown= ExpectedException.none();
@Override
public void createFixture(Object value){
GregorianCalendar theValue = (GregorianCalendar) value;
attributeDefinition = ReqIF10Factory.eINSTANCE.createAttributeDefinitionDate();
attributeDefinition.setIdentifier("AD_ID0");
DatatypeDefinitionDate definition = ReqIF10Factory.eINSTANCE.createDatatypeDefinitionDate();
definition.setIdentifier("DD_ID0");
attributeDefinition.setType(definition);
AttributeValueDate attributeValue = ReqIF10Factory.eINSTANCE.createAttributeValueDate();
attributeValue.setDefinition(attributeDefinition);
attributeValue.setTheValue(theValue);
SpecObject specObject = ReqIF10Factory.eINSTANCE.createSpecObject();
specObject.getValues().add(attributeValue);
specObject.setLastChange(new GregorianCalendar(2014, 11, 03));
createSpecObjectType(specObject, attributeDefinition);
setFixture(specObject);
}
@Before
public void setUp(){
createFixture(new GregorianCalendar(2014, 11, 03));
}
@Test
public void testIs() throws Exception {
DateFilter filter;
filter = new DateFilter(IFilter.Operator.IS, new GregorianCalendar(2014, 11, 03), null, attributeDefinition);
doMatch(filter, true);
filter = new DateFilter(IFilter.Operator.IS, new GregorianCalendar(2014, 11, 04), null, attributeDefinition);
doMatch(filter, false);
filter = new DateFilter(IFilter.Operator.IS, new GregorianCalendar(2014,11,03,0,0,0), null, attributeDefinition);
doMatch(filter, true);
// we do the match on date only, the time of the day should be ignored
createFixture(new GregorianCalendar(2014, 11, 03, 13, 14, 15));
filter = new DateFilter(IFilter.Operator.IS, new GregorianCalendar(2014,11,03), null, attributeDefinition);
doMatch(filter, true);
// for is and is_not operator the time of the day is ignored
filter = new DateFilter(IFilter.Operator.IS, new GregorianCalendar(2014,11,03,20,0,0), null, attributeDefinition);
doMatch(filter, true);
GregorianCalendar fixtureDate = new GregorianCalendar(2014, 11, 3, 23, 0, 0);
fixtureDate.setTimeZone(TimeZone.getTimeZone("GMT"));
- GregorianCalendar filterDate = new GregorianCalendar(TimeZone.getTimeZone("GMT-9"));
+ GregorianCalendar filterDate = new GregorianCalendar(TimeZone.getTimeZone("GMT+9"));
filterDate.set(2014, 11, 4, 8, 0, 0);
System.out.println((filterDate.getTimeInMillis() - fixtureDate.getTimeInMillis()) / 1000 / 60 / 60);
createFixture(fixtureDate);
filter = new DateFilter(IFilter.Operator.IS, filterDate, null, attributeDefinition);
doMatch(filter, true);
}
@Test
public void testIsOnInternal() throws Exception {
DateFilter filter;
filter = new DateFilter(IFilter.Operator.IS, new GregorianCalendar(2014, 11, 03), null, DateFilter.InternalAttribute.LAST_CHANGE);
doMatch(filter, true);
filter = new DateFilter(IFilter.Operator.IS, new GregorianCalendar(2014, 11, 04), null, DateFilter.InternalAttribute.LAST_CHANGE);
doMatch(filter, false);
filter = new DateFilter(IFilter.Operator.IS, new GregorianCalendar(2014,11,03,0,0,0), null, DateFilter.InternalAttribute.LAST_CHANGE);
doMatch(filter, true);
}
@Test
public void testIsNot() throws Exception {
DateFilter filter;
filter = new DateFilter(IFilter.Operator.IS_NOT, new GregorianCalendar(2014, 11, 04), null, attributeDefinition);
doMatch(filter, true);
filter = new DateFilter(IFilter.Operator.IS_NOT, new GregorianCalendar(2014, 11, 03), null, attributeDefinition);
doMatch(filter, false);
}
@Test
public void testIsNotOnInternal() throws Exception {
DateFilter filter;
filter = new DateFilter(IFilter.Operator.IS_NOT, new GregorianCalendar(2014, 11, 04), null, DateFilter.InternalAttribute.LAST_CHANGE);
doMatch(filter, true);
filter = new DateFilter(IFilter.Operator.IS_NOT, new GregorianCalendar(2014, 11, 03), null, DateFilter.InternalAttribute.LAST_CHANGE);
doMatch(filter, false);
}
@Test
public void testBetween() throws Exception {
DateFilter filter;
filter = new DateFilter(IFilter.Operator.BETWEEN, new GregorianCalendar(2014, 11, 01), new GregorianCalendar(2014, 11, 04), attributeDefinition);
doMatch(filter, true);
filter = new DateFilter(IFilter.Operator.BETWEEN, new GregorianCalendar(2014, 11, 04), new GregorianCalendar(2014, 11, 01), attributeDefinition);
doMatch(filter, true);
filter = new DateFilter(IFilter.Operator.BETWEEN, new GregorianCalendar(2014, 11, 03), new GregorianCalendar(2014, 11, 03), attributeDefinition);
doMatch(filter, true);
filter = new DateFilter(IFilter.Operator.BETWEEN, new GregorianCalendar(2014, 11, 01), new GregorianCalendar(2014, 11, 03), attributeDefinition);
doMatch(filter, true);
filter = new DateFilter(IFilter.Operator.BETWEEN, new GregorianCalendar(2014, 11, 03), new GregorianCalendar(2014, 11, 06), attributeDefinition);
doMatch(filter, true);
filter = new DateFilter(IFilter.Operator.BETWEEN, new GregorianCalendar(2014, 01, 01), new GregorianCalendar(2014, 11, 01), attributeDefinition);
doMatch(filter, false);
}
@Test
public void testBetweenOnInternal() throws Exception {
DateFilter filter;
filter = new DateFilter(IFilter.Operator.BETWEEN, new GregorianCalendar(2014, 11, 01), new GregorianCalendar(2014, 11, 04), DateFilter.InternalAttribute.LAST_CHANGE);
doMatch(filter, true);
filter = new DateFilter(IFilter.Operator.BETWEEN, new GregorianCalendar(2014, 11, 03), new GregorianCalendar(2014, 11, 03), DateFilter.InternalAttribute.LAST_CHANGE);
doMatch(filter, true);
filter = new DateFilter(IFilter.Operator.BETWEEN, new GregorianCalendar(2014, 01, 01), new GregorianCalendar(2014, 11, 01), DateFilter.InternalAttribute.LAST_CHANGE);
doMatch(filter, false);
}
@Test
public void testBefore() throws Exception {
DateFilter filter;
filter = new DateFilter(IFilter.Operator.BEFORE, new GregorianCalendar(2015, 1, 1), new GregorianCalendar(2014, 11, 04), attributeDefinition);
doMatch(filter, true);
filter = new DateFilter(IFilter.Operator.BEFORE, new GregorianCalendar(2014, 11, 3), null, attributeDefinition);
doMatch(filter, false);
filter = new DateFilter(IFilter.Operator.BEFORE, new GregorianCalendar(2014, 1, 1), null, attributeDefinition);
doMatch(filter, false);
}
@Test
public void testBeforeOnInternal(){
DateFilter filter;
filter = new DateFilter(IFilter.Operator.BEFORE, new GregorianCalendar(2015, 1, 1), new GregorianCalendar(2014, 11, 04), DateFilter.InternalAttribute.LAST_CHANGE);
doMatch(filter, true);
filter = new DateFilter(IFilter.Operator.BEFORE, new GregorianCalendar(2014, 11, 3), null, DateFilter.InternalAttribute.LAST_CHANGE);
doMatch(filter, false);
filter = new DateFilter(IFilter.Operator.BEFORE, new GregorianCalendar(2014, 1, 1), null, DateFilter.InternalAttribute.LAST_CHANGE);
doMatch(filter, false);
}
@Test
public void testAfter() throws Exception {
DateFilter filter;
filter = new DateFilter(IFilter.Operator.AFTER, new GregorianCalendar(2000, 1, 1), null, attributeDefinition);
doMatch(filter, true);
filter = new DateFilter(IFilter.Operator.AFTER, new GregorianCalendar(3000, 1, 1), null, attributeDefinition);
doMatch(filter, false);
filter = new DateFilter(IFilter.Operator.AFTER, new GregorianCalendar(2014, 11, 03), null, attributeDefinition);
doMatch(filter, false);
}
@Test
public void testAfterOnInternal() throws Exception {
DateFilter filter;
filter = new DateFilter(IFilter.Operator.AFTER, new GregorianCalendar(2000, 1, 1), null, DateFilter.InternalAttribute.LAST_CHANGE);
doMatch(filter, true);
filter = new DateFilter(IFilter.Operator.AFTER, new GregorianCalendar(3000, 1, 1), null, DateFilter.InternalAttribute.LAST_CHANGE);
doMatch(filter, false);
filter = new DateFilter(IFilter.Operator.AFTER, new GregorianCalendar(2014, 11, 03), null, DateFilter.InternalAttribute.LAST_CHANGE);
doMatch(filter, false);
}
public void doEmptyTest(){
DateFilter filter;
filter = new DateFilter(IFilter.Operator.IS, new GregorianCalendar(2014, 1, 1), null, attributeDefinition);
doMatch(filter, false);
filter = new DateFilter(IFilter.Operator.IS_NOT, new GregorianCalendar(2014, 1, 1), null, attributeDefinition);
doMatch(filter, true);
filter = new DateFilter(IFilter.Operator.BETWEEN, new GregorianCalendar(2014, 1, 1), new GregorianCalendar(2014, 1, 1), attributeDefinition);
doMatch(filter, false);
filter = new DateFilter(IFilter.Operator.BEFORE, new GregorianCalendar(2014, 1, 1), null, attributeDefinition);
doMatch(filter, false);
filter = new DateFilter(IFilter.Operator.AFTER, new GregorianCalendar(2000, 1, 1), null, attributeDefinition);
doMatch(filter, false);
}
@Test
public void testInternalAttributes() throws Exception {
// TODO: validate that all operators are tested against internalAttribute
fail("not yet implemented");
}
@Test
public void testIsSet() throws Exception {
DateFilter filter;
filter = new DateFilter(IFilter.Operator.IS_SET, new GregorianCalendar(2014, 1, 1), null, attributeDefinition);
doMatch(filter, true);
AttributeDefinitionDate attributeDefinition2 = ReqIF10Factory.eINSTANCE.createAttributeDefinitionDate();
attributeDefinition2.setIdentifier("AD_ID1");
filter = new DateFilter(IFilter.Operator.IS_SET, new GregorianCalendar(2014, 1, 1), null, attributeDefinition2);
doMatch(filter, false);
}
@Test
public void testIsNotSet() throws Exception {
DateFilter filter;
filter = new DateFilter(IFilter.Operator.IS_NOT_SET, new GregorianCalendar(2014, 1, 1), null, attributeDefinition);
doMatch(filter, false);
AttributeDefinitionDate attributeDefinition2 = ReqIF10Factory.eINSTANCE.createAttributeDefinitionDate();
attributeDefinition2.setIdentifier("AD_ID1");
filter = new DateFilter(IFilter.Operator.IS_NOT_SET, new GregorianCalendar(2014, 1, 1), null, attributeDefinition2);
doMatch(filter, true);
}
@Test
public void testIsSetInternal() throws Exception {
DateFilter filter;
filter = new DateFilter(Operator.IS_SET, new GregorianCalendar(2014, 1, 1), null, DateFilter.InternalAttribute.LAST_CHANGE);
doMatch(filter, true);
filter = new DateFilter(Operator.IS_SET, null, null, DateFilter.InternalAttribute.LAST_CHANGE);
doMatch(filter, true);
getFixture().setLastChange(null);
filter = new DateFilter(Operator.IS_SET, null, null, DateFilter.InternalAttribute.LAST_CHANGE);
doMatch(filter, false);
}
@Test
public void testIsNotSetInternal() throws Exception {
DateFilter filter;
filter = new DateFilter(Operator.IS_NOT_SET, new GregorianCalendar(2014, 1, 1), null, DateFilter.InternalAttribute.LAST_CHANGE);
doMatch(filter, false);
filter = new DateFilter(Operator.IS_NOT_SET, null, null, DateFilter.InternalAttribute.LAST_CHANGE);
doMatch(filter, false);
getFixture().setLastChange(null);
filter = new DateFilter(Operator.IS_NOT_SET, null, null, DateFilter.InternalAttribute.LAST_CHANGE);
doMatch(filter, true);
}
@Test
public void testExceptionsAttributeDefinition() throws Exception {
thrown.expect(IllegalArgumentException.class);
new DateFilter(IFilter.Operator.BEFORE, new GregorianCalendar(2014, 1, 1), null, (AttributeDefinitionDate) null);
}
@Test
public void testExceptionsInternalAttribute() throws Exception {
thrown.expect(IllegalArgumentException.class);
new DateFilter(IFilter.Operator.BEFORE, new GregorianCalendar(2014, 1, 1), null, (InternalAttribute) null);
}
@Override
public DateFilter createFilterInstance(Operator operator) {
return new DateFilter(operator, new GregorianCalendar(2014, 1, 1), null, attributeDefinition);
}
@Override
public Set<Operator> getSupportedOperators() {
return DateFilter.SUPPORTED_OPERATORS;
}
}
| true | true | public void testIs() throws Exception {
DateFilter filter;
filter = new DateFilter(IFilter.Operator.IS, new GregorianCalendar(2014, 11, 03), null, attributeDefinition);
doMatch(filter, true);
filter = new DateFilter(IFilter.Operator.IS, new GregorianCalendar(2014, 11, 04), null, attributeDefinition);
doMatch(filter, false);
filter = new DateFilter(IFilter.Operator.IS, new GregorianCalendar(2014,11,03,0,0,0), null, attributeDefinition);
doMatch(filter, true);
// we do the match on date only, the time of the day should be ignored
createFixture(new GregorianCalendar(2014, 11, 03, 13, 14, 15));
filter = new DateFilter(IFilter.Operator.IS, new GregorianCalendar(2014,11,03), null, attributeDefinition);
doMatch(filter, true);
// for is and is_not operator the time of the day is ignored
filter = new DateFilter(IFilter.Operator.IS, new GregorianCalendar(2014,11,03,20,0,0), null, attributeDefinition);
doMatch(filter, true);
GregorianCalendar fixtureDate = new GregorianCalendar(2014, 11, 3, 23, 0, 0);
fixtureDate.setTimeZone(TimeZone.getTimeZone("GMT"));
GregorianCalendar filterDate = new GregorianCalendar(TimeZone.getTimeZone("GMT-9"));
filterDate.set(2014, 11, 4, 8, 0, 0);
System.out.println((filterDate.getTimeInMillis() - fixtureDate.getTimeInMillis()) / 1000 / 60 / 60);
createFixture(fixtureDate);
filter = new DateFilter(IFilter.Operator.IS, filterDate, null, attributeDefinition);
doMatch(filter, true);
}
| public void testIs() throws Exception {
DateFilter filter;
filter = new DateFilter(IFilter.Operator.IS, new GregorianCalendar(2014, 11, 03), null, attributeDefinition);
doMatch(filter, true);
filter = new DateFilter(IFilter.Operator.IS, new GregorianCalendar(2014, 11, 04), null, attributeDefinition);
doMatch(filter, false);
filter = new DateFilter(IFilter.Operator.IS, new GregorianCalendar(2014,11,03,0,0,0), null, attributeDefinition);
doMatch(filter, true);
// we do the match on date only, the time of the day should be ignored
createFixture(new GregorianCalendar(2014, 11, 03, 13, 14, 15));
filter = new DateFilter(IFilter.Operator.IS, new GregorianCalendar(2014,11,03), null, attributeDefinition);
doMatch(filter, true);
// for is and is_not operator the time of the day is ignored
filter = new DateFilter(IFilter.Operator.IS, new GregorianCalendar(2014,11,03,20,0,0), null, attributeDefinition);
doMatch(filter, true);
GregorianCalendar fixtureDate = new GregorianCalendar(2014, 11, 3, 23, 0, 0);
fixtureDate.setTimeZone(TimeZone.getTimeZone("GMT"));
GregorianCalendar filterDate = new GregorianCalendar(TimeZone.getTimeZone("GMT+9"));
filterDate.set(2014, 11, 4, 8, 0, 0);
System.out.println((filterDate.getTimeInMillis() - fixtureDate.getTimeInMillis()) / 1000 / 60 / 60);
createFixture(fixtureDate);
filter = new DateFilter(IFilter.Operator.IS, filterDate, null, attributeDefinition);
doMatch(filter, true);
}
|
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/PlainStreetEdge.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/PlainStreetEdge.java
index 7489bda44..db0e119b9 100644
--- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/PlainStreetEdge.java
+++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/PlainStreetEdge.java
@@ -1,510 +1,510 @@
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.routing.edgetype;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.opentripplanner.common.TurnRestriction;
import org.opentripplanner.common.TurnRestrictionType;
import org.opentripplanner.common.geometry.DirectionUtils;
import org.opentripplanner.common.geometry.PackedCoordinateSequence;
import org.opentripplanner.routing.core.State;
import org.opentripplanner.routing.core.StateEditor;
import org.opentripplanner.routing.core.TraverseMode;
import org.opentripplanner.routing.core.RoutingRequest;
import org.opentripplanner.routing.graph.Edge;
import org.opentripplanner.routing.patch.Alert;
import org.opentripplanner.routing.util.ElevationProfileSegment;
import org.opentripplanner.routing.vertextype.StreetVertex;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.LineString;
/**
* This represents a street segment. This is unusual in an edge-based graph, but happens when we
* have to split a set of turns to accommodate a transit stop.
*
* @author novalis
*
*/
public class PlainStreetEdge extends StreetEdge implements Cloneable {
private static final long serialVersionUID = 1L;
private static final double GREENWAY_SAFETY_FACTOR = 0.1;
private ElevationProfileSegment elevationProfileSegment;
private double length;
private LineString geometry;
private String name;
private boolean wheelchairAccessible = true;
private StreetTraversalPermission permission;
private String id;
private int streetClass = CLASS_OTHERPATH;
public boolean back;
private boolean roundabout = false;
private Set<Alert> notes;
private boolean hasBogusName;
private boolean noThruTraffic;
/**
* This street is a staircase
*/
private boolean stairs;
private Set<Alert> wheelchairNotes;
private List<TurnRestriction> turnRestrictions = Collections.emptyList();
public int inAngle;
public int outAngle;
/**
* No-arg constructor used only for customization -- do not call this unless you know
* what you are doing
*/
public PlainStreetEdge() {
super(null, null);
}
// Presently, we have plainstreetedges that connect both IntersectionVertexes and
// TurnVertexes
public PlainStreetEdge(StreetVertex v1, StreetVertex v2, LineString geometry,
String name, double length,
StreetTraversalPermission permission, boolean back) {
super(v1, v2);
this.geometry = geometry;
this.length = length;
this.elevationProfileSegment = new ElevationProfileSegment(length);
this.name = name;
this.permission = permission;
this.back = back;
if (geometry != null) {
for (Coordinate c : geometry.getCoordinates()) {
if (Double.isNaN(c.x)) {
System.out.println("DOOM");
}
}
double angleR = DirectionUtils.getLastAngle(geometry);
outAngle = ((int) (180 * angleR / Math.PI) + 180 + 360) % 360;
angleR = DirectionUtils.getFirstAngle(geometry);
inAngle = ((int) (180 * angleR / Math.PI) + 180 + 360) % 360;
}
}
@Override
public boolean canTraverse(RoutingRequest options) {
if (options.wheelchairAccessible) {
if (!wheelchairAccessible) {
return false;
}
if (elevationProfileSegment.getMaxSlope() > options.maxSlope) {
return false;
}
}
if (options.getModes().getWalk() && permission.allows(StreetTraversalPermission.PEDESTRIAN)) {
return true;
}
if (options.getModes().getBicycle() && permission.allows(StreetTraversalPermission.BICYCLE)) {
return true;
}
if (options.getModes().getCar() && permission.allows(StreetTraversalPermission.CAR)) {
return true;
}
return false;
}
private boolean canTraverse(RoutingRequest options, TraverseMode mode) {
if (options.wheelchairAccessible) {
if (!wheelchairAccessible) {
return false;
}
if (elevationProfileSegment.getMaxSlope() > options.maxSlope) {
return false;
}
}
if (mode == TraverseMode.WALK && permission.allows(StreetTraversalPermission.PEDESTRIAN)) {
return true;
}
if (mode == TraverseMode.BICYCLE && permission.allows(StreetTraversalPermission.BICYCLE)) {
return true;
}
if (mode == TraverseMode.CAR && permission.allows(StreetTraversalPermission.CAR)) {
return true;
}
return false;
}
@Override
public PackedCoordinateSequence getElevationProfile() {
return elevationProfileSegment.getElevationProfile();
}
@Override
public boolean setElevationProfile(PackedCoordinateSequence elev, boolean computed) {
return elevationProfileSegment.setElevationProfile(elev, computed, permission.allows(StreetTraversalPermission.CAR));
}
@Override
public boolean isElevationFlattened() {
return elevationProfileSegment.isFlattened();
}
@Override
public double getDistance() {
return length;
}
@Override
public LineString getGeometry() {
return geometry;
}
@Override
public String getName() {
return name;
}
@Override
public State traverse(State s0) {
final RoutingRequest options = s0.getOptions();
return doTraverse(s0, options, s0.getNonTransitMode(options));
}
private State doTraverse(State s0, RoutingRequest options, TraverseMode traverseMode) {
Edge backEdge = s0.getBackEdge();
if (backEdge != null &&
(options.arriveBy ? (backEdge.getToVertex() == fromv) : (backEdge.getFromVertex() == tov))) {
//no illegal U-turns
return null;
}
if (!canTraverse(options, traverseMode)) {
if (traverseMode == TraverseMode.BICYCLE) {
// try walking bike since you can't ride here
return doTraverse(s0, options.getWalkingOptions(), TraverseMode.WALK);
}
return null;
}
- double speed = options.getSpeed(s0.getNonTransitMode(options));
+ double speed = options.getSpeed(traverseMode);
double time = length / speed;
double weight;
if (options.wheelchairAccessible) {
weight = elevationProfileSegment.getSlopeSpeedEffectiveLength() / speed;
} else if (traverseMode.equals(TraverseMode.BICYCLE)) {
time = elevationProfileSegment.getSlopeSpeedEffectiveLength() / speed;
switch (options.optimize) {
case SAFE:
weight = elevationProfileSegment.getBicycleSafetyEffectiveLength() / speed;
break;
case GREENWAYS:
weight = elevationProfileSegment.getBicycleSafetyEffectiveLength() / speed;
if (elevationProfileSegment.getBicycleSafetyEffectiveLength() / length <= GREENWAY_SAFETY_FACTOR) {
// greenways are treated as even safer than they really are
weight *= 0.66;
}
break;
case FLAT:
/* see notes in StreetVertex on speed overhead */
weight = length / speed + elevationProfileSegment.getSlopeWorkCost();
break;
case QUICK:
weight = elevationProfileSegment.getSlopeSpeedEffectiveLength() / speed;
break;
case TRIANGLE:
double quick = elevationProfileSegment.getSlopeSpeedEffectiveLength();
double safety = elevationProfileSegment.getBicycleSafetyEffectiveLength();
double slope = elevationProfileSegment.getSlopeWorkCost();
weight = quick * options.getTriangleTimeFactor() + slope
* options.getTriangleSlopeFactor() + safety
* options.getTriangleSafetyFactor();
weight /= speed;
break;
default:
weight = length / speed;
}
} else {
weight = time;
}
if (isStairs()) {
weight *= options.stairsReluctance;
} else {
weight *= options.walkReluctance;
}
StateEditor s1 = s0.edit(this);
s1.setBackMode(traverseMode);
if (wheelchairNotes != null && options.wheelchairAccessible) {
s1.addAlerts(wheelchairNotes);
}
PlainStreetEdge backPSE;
if (backEdge != null && backEdge instanceof PlainStreetEdge) {
backPSE = (PlainStreetEdge) backEdge;
int outAngle = 0;
int inAngle = 0;
if (options.arriveBy) {
if (!canTurnOnto(backPSE, s0, traverseMode))
return null;
outAngle = backPSE.getOutAngle();
inAngle = getInAngle();
} else {
if (!backPSE.canTurnOnto(this, s0, traverseMode))
return null;
outAngle = getOutAngle();
inAngle = backPSE.getInAngle();
}
int turnCost = Math.abs(outAngle - inAngle);
if (turnCost > 180) {
turnCost = 360 - turnCost;
}
final double realTurnCost = (turnCost / 20.0) / options.getSpeed(traverseMode);
s1.incrementWalkDistance(realTurnCost / 100); //just a tie-breaker
weight += realTurnCost;
long turnTime = (long) realTurnCost;
if (turnTime != realTurnCost) {
turnTime++;
}
time += turnTime;
}
s1.incrementWalkDistance(length);
int timeLong = (int) time;
if (timeLong != time) {
timeLong++;
}
s1.incrementTimeInSeconds(timeLong);
s1.incrementWeight(weight);
if (s1.weHaveWalkedTooFar(options))
return null;
s1.addAlerts(getNotes());
return s1.makeState();
}
@Override
public double weightLowerBound(RoutingRequest options) {
return timeLowerBound(options) * options.walkReluctance;
}
@Override
public double timeLowerBound(RoutingRequest options) {
return this.length / options.getSpeedUpperBound();
}
public void setSlopeSpeedEffectiveLength(double slopeSpeedEffectiveLength) {
elevationProfileSegment.setSlopeSpeedEffectiveLength(slopeSpeedEffectiveLength);
}
public double getSlopeSpeedEffectiveLength() {
return elevationProfileSegment.getSlopeSpeedEffectiveLength();
}
public void setSlopeWorkCost(double slopeWorkCost) {
elevationProfileSegment.setSlopeWorkCost(slopeWorkCost);
}
public double getWorkCost() {
return elevationProfileSegment.getSlopeWorkCost();
}
public void setBicycleSafetyEffectiveLength(double bicycleSafetyEffectiveLength) {
elevationProfileSegment.setBicycleSafetyEffectiveLength(bicycleSafetyEffectiveLength);
}
public double getBicycleSafetyEffectiveLength() {
return elevationProfileSegment.getBicycleSafetyEffectiveLength();
}
public double getLength() {
return length;
}
public StreetTraversalPermission getPermission() {
return permission;
}
public void setPermission(StreetTraversalPermission permission) {
this.permission = permission;
}
public void setWheelchairAccessible(boolean wheelchairAccessible) {
this.wheelchairAccessible = wheelchairAccessible;
}
public boolean isWheelchairAccessible() {
return wheelchairAccessible;
}
public String getId() {
return id;
}
private void writeObject(ObjectOutputStream out) throws IOException {
id = null;
out.defaultWriteObject();
}
public boolean getSlopeOverride() {
return elevationProfileSegment.getSlopeOverride();
}
public void setId(String id) {
this.id = id;
}
@Override
public PackedCoordinateSequence getElevationProfile(double start, double end) {
return elevationProfileSegment.getElevationProfile(start, end);
}
public void setSlopeOverride(boolean slopeOverride) {
elevationProfileSegment.setSlopeOverride(slopeOverride);
}
public void setRoundabout(boolean roundabout) {
this.roundabout = roundabout;
}
public boolean isRoundabout() {
return roundabout;
}
public Set<Alert> getNotes() {
return notes;
}
public void setNote(Set<Alert> notes) {
this.notes = notes;
}
@Override
public String toString() {
return "PlainStreetEdge(" + fromv + " -> " + tov + ")";
}
public boolean hasBogusName() {
return hasBogusName;
}
public void setBogusName(boolean hasBogusName) {
this.hasBogusName = hasBogusName;
}
public void setNoThruTraffic(boolean noThruTraffic) {
this.noThruTraffic = noThruTraffic;
}
public boolean isNoThruTraffic() {
return noThruTraffic;
}
public boolean isStairs() {
return stairs;
}
public void setStairs(boolean stairs) {
this.stairs = stairs;
}
public void setName(String name) {
this.name = name;
}
public void setWheelchairNote(Set<Alert> wheelchairNotes) {
this.wheelchairNotes = wheelchairNotes;
}
public Set<Alert> getWheelchairNotes() {
return wheelchairNotes;
}
public int getStreetClass() {
return streetClass;
}
public void setStreetClass(int streetClass) {
this.streetClass = streetClass;
}
public void addTurnRestriction(TurnRestriction turnRestriction) {
if (turnRestrictions.isEmpty()) {
turnRestrictions = new ArrayList<TurnRestriction>();
}
turnRestrictions.add(turnRestriction);
}
@Override
public PlainStreetEdge clone() {
try {
return (PlainStreetEdge) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
public List<TurnRestriction> getTurnRestrictions() {
return turnRestrictions;
}
public boolean canTurnOnto(Edge e, State state, TraverseMode mode) {
for (TurnRestriction restriction : turnRestrictions) {
/* FIXME: This is wrong for trips that end in the middle of restriction.to
*/
if (restriction.type == TurnRestrictionType.ONLY_TURN) {
if (restriction.to != e && restriction.modes.contains(mode)) {
return false;
}
} else {
if (restriction.to == e && restriction.modes.contains(mode)) {
return false;
}
}
}
return true;
}
public int getInAngle() {
return inAngle;
}
public int getOutAngle() {
return outAngle;
}
@Override
public ElevationProfileSegment getElevationProfileSegment() {
return elevationProfileSegment;
}
}
| true | true | private State doTraverse(State s0, RoutingRequest options, TraverseMode traverseMode) {
Edge backEdge = s0.getBackEdge();
if (backEdge != null &&
(options.arriveBy ? (backEdge.getToVertex() == fromv) : (backEdge.getFromVertex() == tov))) {
//no illegal U-turns
return null;
}
if (!canTraverse(options, traverseMode)) {
if (traverseMode == TraverseMode.BICYCLE) {
// try walking bike since you can't ride here
return doTraverse(s0, options.getWalkingOptions(), TraverseMode.WALK);
}
return null;
}
double speed = options.getSpeed(s0.getNonTransitMode(options));
double time = length / speed;
double weight;
if (options.wheelchairAccessible) {
weight = elevationProfileSegment.getSlopeSpeedEffectiveLength() / speed;
} else if (traverseMode.equals(TraverseMode.BICYCLE)) {
time = elevationProfileSegment.getSlopeSpeedEffectiveLength() / speed;
switch (options.optimize) {
case SAFE:
weight = elevationProfileSegment.getBicycleSafetyEffectiveLength() / speed;
break;
case GREENWAYS:
weight = elevationProfileSegment.getBicycleSafetyEffectiveLength() / speed;
if (elevationProfileSegment.getBicycleSafetyEffectiveLength() / length <= GREENWAY_SAFETY_FACTOR) {
// greenways are treated as even safer than they really are
weight *= 0.66;
}
break;
case FLAT:
/* see notes in StreetVertex on speed overhead */
weight = length / speed + elevationProfileSegment.getSlopeWorkCost();
break;
case QUICK:
weight = elevationProfileSegment.getSlopeSpeedEffectiveLength() / speed;
break;
case TRIANGLE:
double quick = elevationProfileSegment.getSlopeSpeedEffectiveLength();
double safety = elevationProfileSegment.getBicycleSafetyEffectiveLength();
double slope = elevationProfileSegment.getSlopeWorkCost();
weight = quick * options.getTriangleTimeFactor() + slope
* options.getTriangleSlopeFactor() + safety
* options.getTriangleSafetyFactor();
weight /= speed;
break;
default:
weight = length / speed;
}
} else {
weight = time;
}
if (isStairs()) {
weight *= options.stairsReluctance;
} else {
weight *= options.walkReluctance;
}
StateEditor s1 = s0.edit(this);
s1.setBackMode(traverseMode);
if (wheelchairNotes != null && options.wheelchairAccessible) {
s1.addAlerts(wheelchairNotes);
}
PlainStreetEdge backPSE;
if (backEdge != null && backEdge instanceof PlainStreetEdge) {
backPSE = (PlainStreetEdge) backEdge;
int outAngle = 0;
int inAngle = 0;
if (options.arriveBy) {
if (!canTurnOnto(backPSE, s0, traverseMode))
return null;
outAngle = backPSE.getOutAngle();
inAngle = getInAngle();
} else {
if (!backPSE.canTurnOnto(this, s0, traverseMode))
return null;
outAngle = getOutAngle();
inAngle = backPSE.getInAngle();
}
int turnCost = Math.abs(outAngle - inAngle);
if (turnCost > 180) {
turnCost = 360 - turnCost;
}
final double realTurnCost = (turnCost / 20.0) / options.getSpeed(traverseMode);
s1.incrementWalkDistance(realTurnCost / 100); //just a tie-breaker
weight += realTurnCost;
long turnTime = (long) realTurnCost;
if (turnTime != realTurnCost) {
turnTime++;
}
time += turnTime;
}
s1.incrementWalkDistance(length);
int timeLong = (int) time;
if (timeLong != time) {
timeLong++;
}
s1.incrementTimeInSeconds(timeLong);
s1.incrementWeight(weight);
if (s1.weHaveWalkedTooFar(options))
return null;
s1.addAlerts(getNotes());
return s1.makeState();
}
| private State doTraverse(State s0, RoutingRequest options, TraverseMode traverseMode) {
Edge backEdge = s0.getBackEdge();
if (backEdge != null &&
(options.arriveBy ? (backEdge.getToVertex() == fromv) : (backEdge.getFromVertex() == tov))) {
//no illegal U-turns
return null;
}
if (!canTraverse(options, traverseMode)) {
if (traverseMode == TraverseMode.BICYCLE) {
// try walking bike since you can't ride here
return doTraverse(s0, options.getWalkingOptions(), TraverseMode.WALK);
}
return null;
}
double speed = options.getSpeed(traverseMode);
double time = length / speed;
double weight;
if (options.wheelchairAccessible) {
weight = elevationProfileSegment.getSlopeSpeedEffectiveLength() / speed;
} else if (traverseMode.equals(TraverseMode.BICYCLE)) {
time = elevationProfileSegment.getSlopeSpeedEffectiveLength() / speed;
switch (options.optimize) {
case SAFE:
weight = elevationProfileSegment.getBicycleSafetyEffectiveLength() / speed;
break;
case GREENWAYS:
weight = elevationProfileSegment.getBicycleSafetyEffectiveLength() / speed;
if (elevationProfileSegment.getBicycleSafetyEffectiveLength() / length <= GREENWAY_SAFETY_FACTOR) {
// greenways are treated as even safer than they really are
weight *= 0.66;
}
break;
case FLAT:
/* see notes in StreetVertex on speed overhead */
weight = length / speed + elevationProfileSegment.getSlopeWorkCost();
break;
case QUICK:
weight = elevationProfileSegment.getSlopeSpeedEffectiveLength() / speed;
break;
case TRIANGLE:
double quick = elevationProfileSegment.getSlopeSpeedEffectiveLength();
double safety = elevationProfileSegment.getBicycleSafetyEffectiveLength();
double slope = elevationProfileSegment.getSlopeWorkCost();
weight = quick * options.getTriangleTimeFactor() + slope
* options.getTriangleSlopeFactor() + safety
* options.getTriangleSafetyFactor();
weight /= speed;
break;
default:
weight = length / speed;
}
} else {
weight = time;
}
if (isStairs()) {
weight *= options.stairsReluctance;
} else {
weight *= options.walkReluctance;
}
StateEditor s1 = s0.edit(this);
s1.setBackMode(traverseMode);
if (wheelchairNotes != null && options.wheelchairAccessible) {
s1.addAlerts(wheelchairNotes);
}
PlainStreetEdge backPSE;
if (backEdge != null && backEdge instanceof PlainStreetEdge) {
backPSE = (PlainStreetEdge) backEdge;
int outAngle = 0;
int inAngle = 0;
if (options.arriveBy) {
if (!canTurnOnto(backPSE, s0, traverseMode))
return null;
outAngle = backPSE.getOutAngle();
inAngle = getInAngle();
} else {
if (!backPSE.canTurnOnto(this, s0, traverseMode))
return null;
outAngle = getOutAngle();
inAngle = backPSE.getInAngle();
}
int turnCost = Math.abs(outAngle - inAngle);
if (turnCost > 180) {
turnCost = 360 - turnCost;
}
final double realTurnCost = (turnCost / 20.0) / options.getSpeed(traverseMode);
s1.incrementWalkDistance(realTurnCost / 100); //just a tie-breaker
weight += realTurnCost;
long turnTime = (long) realTurnCost;
if (turnTime != realTurnCost) {
turnTime++;
}
time += turnTime;
}
s1.incrementWalkDistance(length);
int timeLong = (int) time;
if (timeLong != time) {
timeLong++;
}
s1.incrementTimeInSeconds(timeLong);
s1.incrementWeight(weight);
if (s1.weHaveWalkedTooFar(options))
return null;
s1.addAlerts(getNotes());
return s1.makeState();
}
|
diff --git a/src/main/java/com/google/gson/FieldAttributes.java b/src/main/java/com/google/gson/FieldAttributes.java
index b69ebf9..0aa4751 100644
--- a/src/main/java/com/google/gson/FieldAttributes.java
+++ b/src/main/java/com/google/gson/FieldAttributes.java
@@ -1,255 +1,256 @@
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson;
import com.google.gson.internal.$Gson$Preconditions;
import com.google.gson.internal.$Gson$Types;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
/**
* A data object that stores attributes of a field.
*
* <p>This class is immutable; therefore, it can be safely shared across threads.
*
* @author Inderjeet Singh
* @author Joel Leitch
*
* @since 1.4
*/
public final class FieldAttributes {
private static final String MAX_CACHE_PROPERTY_NAME =
"com.google.gson.annotation_cache_size_hint";
private static final Cache<Pair<Class<?>, String>, Collection<Annotation>> ANNOTATION_CACHE =
new LruCache<Pair<Class<?>,String>, Collection<Annotation>>(getMaxCacheSize());
private final Class<?> declaringClazz;
private final Field field;
private final Class<?> declaredType;
private final boolean isSynthetic;
private final int modifiers;
private final String name;
private final Type resolvedType;
// Fields used for lazy initialization
private Type genericType;
private Collection<Annotation> annotations;
/**
* Constructs a Field Attributes object from the {@code f}.
*
* @param f the field to pull attributes from
* @param declaringType The type in which the field is declared
*/
FieldAttributes(Class<?> declaringClazz, Field f, Type declaringType) {
this.declaringClazz = $Gson$Preconditions.checkNotNull(declaringClazz);
this.name = f.getName();
this.declaredType = f.getType();
this.isSynthetic = f.isSynthetic();
this.modifiers = f.getModifiers();
this.field = f;
this.resolvedType = getTypeInfoForField(f, declaringType);
}
private static int getMaxCacheSize() {
final int defaultMaxCacheSize = 2000;
try {
String propertyValue = System.getProperty(
MAX_CACHE_PROPERTY_NAME, String.valueOf(defaultMaxCacheSize));
return Integer.parseInt(propertyValue);
} catch (NumberFormatException e) {
return defaultMaxCacheSize;
}
}
/**
* @return the declaring class that contains this field
*/
public Class<?> getDeclaringClass() {
return declaringClazz;
}
/**
* @return the name of the field
*/
public String getName() {
return name;
}
/**
* <p>For example, assume the following class definition:
* <pre class="code">
* public class Foo {
* private String bar;
* private List<String> red;
* }
*
* Type listParmeterizedType = new TypeToken<List<String>>() {}.getType();
* </pre>
*
* <p>This method would return {@code String.class} for the {@code bar} field and
* {@code listParameterizedType} for the {@code red} field.
*
* @return the specific type declared for this field
*/
public Type getDeclaredType() {
if (genericType == null) {
genericType = field.getGenericType();
}
return genericType;
}
/**
* Returns the {@code Class<?>} object that was declared for this field.
*
* <p>For example, assume the following class definition:
* <pre class="code">
* public class Foo {
* private String bar;
* private List<String> red;
* }
* </pre>
*
* <p>This method would return {@code String.class} for the {@code bar} field and
* {@code List.class} for the {@code red} field.
*
* @return the specific class object that was declared for the field
*/
public Class<?> getDeclaredClass() {
return declaredType;
}
/**
* Return the {@code T} annotation object from this field if it exist; otherwise returns
* {@code null}.
*
* @param annotation the class of the annotation that will be retrieved
* @return the annotation instance if it is bound to the field; otherwise {@code null}
*/
public <T extends Annotation> T getAnnotation(Class<T> annotation) {
return getAnnotationFromArray(getAnnotations(), annotation);
}
/**
* Return the annotations that are present on this field.
*
* @return an array of all the annotations set on the field
* @since 1.4
*/
public Collection<Annotation> getAnnotations() {
if (annotations == null) {
Pair<Class<?>, String> key = new Pair<Class<?>, String>(declaringClazz, name);
- annotations = ANNOTATION_CACHE.getElement(key);
- if (annotations == null) {
- annotations = Collections.unmodifiableCollection(
+ Collection<Annotation> cachedValue = ANNOTATION_CACHE.getElement(key);
+ if (cachedValue == null) {
+ cachedValue = Collections.unmodifiableCollection(
Arrays.asList(field.getAnnotations()));
- ANNOTATION_CACHE.addElement(key, annotations);
+ ANNOTATION_CACHE.addElement(key, cachedValue);
}
+ annotations = cachedValue;
}
return annotations;
}
/**
* Returns {@code true} if the field is defined with the {@code modifier}.
*
* <p>This method is meant to be called as:
* <pre class="code">
* boolean hasPublicModifier = fieldAttribute.hasModifier(java.lang.reflect.Modifier.PUBLIC);
* </pre>
*
* @see java.lang.reflect.Modifier
*/
public boolean hasModifier(int modifier) {
return (modifiers & modifier) != 0;
}
/**
* This is exposed internally only for the removing synthetic fields from the JSON output.
*
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
void set(Object instance, Object value) throws IllegalAccessException {
field.set(instance, value);
}
/**
* This is exposed internally only for the removing synthetic fields from the JSON output.
*
* @return true if the field is synthetic; otherwise false
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
Object get(Object instance) throws IllegalAccessException {
return field.get(instance);
}
/**
* This is exposed internally only for the removing synthetic fields from the JSON output.
*
* @return true if the field is synthetic; otherwise false
*/
boolean isSynthetic() {
return isSynthetic;
}
/**
* @deprecated remove this when {@link FieldNamingStrategy} is deleted.
*/
@Deprecated
Field getFieldObject() {
return field;
}
Type getResolvedType() {
return resolvedType;
}
@SuppressWarnings("unchecked")
private static <T extends Annotation> T getAnnotationFromArray(
Collection<Annotation> annotations, Class<T> annotation) {
for (Annotation a : annotations) {
if (a.annotationType() == annotation) {
return (T) a;
}
}
return null;
}
/**
* Evaluates the "actual" type for the field. If the field is a "TypeVariable" or has a
* "TypeVariable" in a parameterized type then it evaluates the real type.
*
* @param f the actual field object to retrieve the type from
* @param typeDefiningF the type that contains the field {@code f}
* @return the type information for the field
*/
static Type getTypeInfoForField(Field f, Type typeDefiningF) {
Class<?> rawType = $Gson$Types.getRawType(typeDefiningF);
if (!f.getDeclaringClass().isAssignableFrom(rawType)) {
// this field is unrelated to the type; the user probably omitted type information
return f.getGenericType();
}
return $Gson$Types.resolve(typeDefiningF, rawType, f.getGenericType());
}
}
| false | true | public Collection<Annotation> getAnnotations() {
if (annotations == null) {
Pair<Class<?>, String> key = new Pair<Class<?>, String>(declaringClazz, name);
annotations = ANNOTATION_CACHE.getElement(key);
if (annotations == null) {
annotations = Collections.unmodifiableCollection(
Arrays.asList(field.getAnnotations()));
ANNOTATION_CACHE.addElement(key, annotations);
}
}
return annotations;
}
| public Collection<Annotation> getAnnotations() {
if (annotations == null) {
Pair<Class<?>, String> key = new Pair<Class<?>, String>(declaringClazz, name);
Collection<Annotation> cachedValue = ANNOTATION_CACHE.getElement(key);
if (cachedValue == null) {
cachedValue = Collections.unmodifiableCollection(
Arrays.asList(field.getAnnotations()));
ANNOTATION_CACHE.addElement(key, cachedValue);
}
annotations = cachedValue;
}
return annotations;
}
|
diff --git a/java/coalitiongamesjava/experiment/OutputPrinter.java b/java/coalitiongamesjava/experiment/OutputPrinter.java
index b888ae7..a3feaec 100644
--- a/java/coalitiongamesjava/experiment/OutputPrinter.java
+++ b/java/coalitiongamesjava/experiment/OutputPrinter.java
@@ -1,287 +1,287 @@
package experiment;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import coalitiongames.Agent;
import coalitiongames.SearchResult;
import coalitiongames.SimpleSearchResult;
import experiment.ProblemGenerator.SimpleSearchAlgorithm;
public abstract class OutputPrinter {
private static final String OUTPUT_FILE = "outputFiles/";
private static final String DESCRIPTION_STRING = "descr";
private static final String DESCRIPTION_HEADER =
"n,kMin,kMax,algorithm,solver,dataFileName\n";
private static final String SUMMARY_STRING = "summary";
private static final String SUMMARY_HEADER =
"runNumber,runTimeInMillis,numberOfTeams\n";
private static final String RESULT_STRING = "results";
private static final String RESULTS_HEADER =
"runNumber,playerId,isCaptain,budget,budgetRank,"
+ "rsdOrderIndex,teamSizeWithSelf,teamUtility,"
+ "teamUtilityNoJitter,meanTeammateUtility,"
+ "meanTeammateUtilityNoJitter,fractionOfTotalUtility,"
+ "fractionOfTotalUtilityNoJitter,"
+ "envyAmount,envyAmountNoJitter,"
+ "envyAmountMinusSingleGood,envyAmountMinusSingleGoodNoJitter,"
+ "meanTeammateRank,meanTeammateRankNoJitter,sumOfReversedRanks,"
+ "sumOfReversedRanksNoJitter,favTeammateRank,"
+ "favTeammateRankNoJitter,leastFavTeammateRank,"
+ "leastFavTeammateRankNoJitter\n";
private static final char COMMA = ',';
private static final char NEWLINE = '\n';
private static final char UNDERBAR = '_';
public static void main(final String[] args) {
final List<SimpleSearchResult> searchResults =
new ArrayList<SimpleSearchResult>();
SimpleSearchResult result =
ProblemGenerator.getSimpleSearchResult(
"inputFiles/bkfrat_1.txt",
SimpleSearchAlgorithm.RSD_OPT
);
searchResults.add(result);
result = ProblemGenerator.getSimpleSearchResult(
"inputFiles/bkfrat_1.txt",
SimpleSearchAlgorithm.RSD_OPT
);
searchResults.add(result);
final String algorithmName = "rsdOpt";
final String solverName = "cplex";
final String inputFilePrefix = "bkfrat";
printOutput(searchResults, algorithmName, solverName, inputFilePrefix);
}
public static void printOutput(
final List<SimpleSearchResult> searchResults,
final String algorithmName,
final String solverName,
final String inputFilePrefix
) {
printDescriptionOutput(
searchResults.get(0), algorithmName, solverName, inputFilePrefix
);
printSummaryOutput(searchResults, algorithmName, inputFilePrefix);
printResultOutput(searchResults, algorithmName, inputFilePrefix);
}
private static void printDescriptionOutput(
final SimpleSearchResult searchResult,
final String algorithmName,
final String solverName,
final String inputFilePrefix
) {
final String descriptionFileName =
OUTPUT_FILE + algorithmName + UNDERBAR + inputFilePrefix + UNDERBAR
+ DESCRIPTION_STRING + FileHandler.CSV_EXTENSION;
final StringBuilder builder = new StringBuilder();
builder.append(DESCRIPTION_HEADER);
final int n = searchResult.getAgents().size();
final int kMin = searchResult.getkMin();
final int kMax = searchResult.getkMax();
builder.append(n).append(COMMA).append(kMin).append(COMMA).
append(kMax).append(COMMA).append(algorithmName).append(COMMA).
append(solverName).append(COMMA).
append(inputFilePrefix).append(NEWLINE);
FileHandler.writeToFile(descriptionFileName, builder.toString());
}
private static void printSummaryOutput(
final List<SimpleSearchResult> searchResults,
final String algorithmName,
final String inputFilePrefix
) {
final String summaryFileName =
OUTPUT_FILE + algorithmName + UNDERBAR + inputFilePrefix + UNDERBAR
+ SUMMARY_STRING + FileHandler.CSV_EXTENSION;
final StringBuilder builder = new StringBuilder();
builder.append(SUMMARY_HEADER);
for (int i = 0; i < searchResults.size(); i++) {
final SimpleSearchResult searchResult = searchResults.get(i);
final int runNumber = i + 1;
final long runTimeInMillis = searchResult.getDurationMillis();
final int numTeams = searchResult.getNumberOfTeams();
builder.append(runNumber).append(COMMA).
append(runTimeInMillis).append(COMMA).
append(numTeams).append(NEWLINE);
}
FileHandler.writeToFile(summaryFileName, builder.toString());
}
private static void printResultOutput(
final List<SimpleSearchResult> searchResults,
final String algorithmName,
final String inputFilePrefix
) {
final String resultsFileName =
OUTPUT_FILE + algorithmName + UNDERBAR + inputFilePrefix + UNDERBAR
+ RESULT_STRING + FileHandler.CSV_EXTENSION;
Writer output = null;
try {
output = new BufferedWriter(
new FileWriter(
FileHandler.getFileAndCreateIfNeeded(resultsFileName)
));
output.write(RESULTS_HEADER);
for (
int resultIndex = 0;
resultIndex < searchResults.size();
resultIndex++
) {
final SimpleSearchResult result =
searchResults.get(resultIndex);
final int runNumber = resultIndex + 1;
final List<Agent> agents = result.getAgents();
final List<Integer> isCaptainList = result.isCaptain();
List<Integer> budgetRanks = null;
if (result instanceof SearchResult) {
final SearchResult searchResult = (SearchResult) result;
budgetRanks = searchResult.getBudgetRanks();
}
final List<Integer> rsdOrderIndexes = result.getRsdIndexes();
final List<Integer> teamSizes = result.getTeamSizesWithSelf();
final List<Double> teamUtilities = result.getTeamUtilities();
final List<Integer> teamUtilitiesNoJitter =
result.getTeamUtilitiesNoJitter();
final List<Double> meanTeammateUtilities =
result.getMeanTeammateUtilities();
final List<Double> meanTeammateUtilitiesNoJitter =
result.getMeanTeammateUtilitiesNoJitter();
final List<Double> fractionsOfTotalUtility =
result.getFractionsOfTotalUtility();
final List<Double> fractionsOfTotalUtilityNoJitter =
result.getFractionsOfTotalUtilityNoJitter();
final List<Double> envyAmounts = result.getEnvyAmounts();
final List<Integer> envyAmountsNoJitter =
result.getEnvyAmountsNoJitter();
final List<Double> envyMinusSingleGood =
result.getEnvyAmountsMinusSingleGood();
final List<Integer> envyMinusSingleGoodNoJitter =
result.getEnvyAmountsMinusSingleGoodNoJitter();
final List<Double> meanTeammateRanks =
result.meanTeammateRanks();
final List<Double> meanTeammateRanksNoJitter =
result.meanTeammateRanksNoJitter();
final List<Integer> sumOfReversedRanks =
result.sumsOfReversedRanks();
final List<Double> sumOfReversedNoJitter =
result.sumsOfReversedRanksNoJitter();
final List<Integer> favTeammateRanks =
result.favTeammateRanks();
final List<Double> favTeammateRanksNoJitter =
result.favTeammateRanksNoJitter();
final List<Integer> leastFavTeammateRanks =
result.leastFavTeammateRanks();
final List<Double> leastFavTeammateRanksNoJitter =
result.leastFavTeammateRanksNoJitter();
for (int j = 0; j < agents.size(); j++) {
final Agent agent = agents.get(j);
final StringBuilder sb = new StringBuilder();
final int playerId = agent.getId();
final int isCaptain = isCaptainList.get(j);
final double budget = agent.getBudget();
int budgetRank;
if (budgetRanks == null) {
budgetRank = -1;
} else {
budgetRank = budgetRanks.get(j);
}
int rsdOrderIndex;
if (rsdOrderIndexes == null) {
rsdOrderIndex = -1;
} else {
rsdOrderIndex = rsdOrderIndexes.get(j);
}
final int teamSize = teamSizes.get(j);
final double teamUtility = teamUtilities.get(j);
final int teamUtilityNoJitter =
teamUtilitiesNoJitter.get(j);
final double meanTeammateUtility =
meanTeammateUtilities.get(j);
final double meanTeammateUtilityNoJitter =
meanTeammateUtilitiesNoJitter.get(j);
final double fractionOfTotalUtility =
fractionsOfTotalUtility.get(j);
final double fractionOfTotalUtilityNoJitter =
fractionsOfTotalUtilityNoJitter.get(j);
final double envyAmount = envyAmounts.get(j);
final int envyAmountNoJitter = envyAmountsNoJitter.get(j);
final double envyMinusSingle = envyMinusSingleGood.get(j);
final int envyMinusSingleNoJitter =
envyMinusSingleGoodNoJitter.get(j);
final double meanTeammateRank = meanTeammateRanks.get(j);
final double meanTeammateRankNoJitter =
meanTeammateRanksNoJitter.get(j);
final int sumOfReversedRank = sumOfReversedRanks.get(j);
final double sumOfReversedRankNoJitter =
sumOfReversedNoJitter.get(j);
final int favTeammateRank = favTeammateRanks.get(j);
final double favTeammateRankNoJitter =
favTeammateRanksNoJitter.get(j);
final int leastFavTeammateRank =
leastFavTeammateRanks.get(j);
final double leastFavTeammateRankNoJitter =
leastFavTeammateRanksNoJitter.get(j);
sb.append(runNumber).append(COMMA).
append(playerId).append(COMMA).
append(isCaptain).append(COMMA).
append(budget).append(COMMA).
append(budgetRank).append(COMMA).
append(rsdOrderIndex).append(COMMA).
append(teamSize).append(COMMA).
append(teamUtility).append(COMMA).
append(teamUtilityNoJitter).append(COMMA).
append(meanTeammateUtility).append(COMMA).
append(meanTeammateUtilityNoJitter).append(COMMA).
append(fractionOfTotalUtility).append(COMMA).
append(fractionOfTotalUtilityNoJitter).append(COMMA).
append(envyAmount).append(COMMA).
append(envyAmountNoJitter).append(COMMA).
append(envyMinusSingle).append(COMMA).
append(envyMinusSingleNoJitter).append(COMMA).
append(meanTeammateRank).append(COMMA).
append(meanTeammateRankNoJitter).append(COMMA).
append(sumOfReversedRank).append(COMMA).
append(sumOfReversedRankNoJitter).append(COMMA).
append(favTeammateRank).append(COMMA).
append(favTeammateRankNoJitter).append(COMMA).
append(leastFavTeammateRank).append(COMMA).
- append(leastFavTeammateRankNoJitter).append(COMMA);
+ append(leastFavTeammateRankNoJitter);
sb.append(NEWLINE);
output.write(sb.toString());
}
}
output.write(NEWLINE);
output.flush();
output.close();
} catch (IOException e) {
if (output != null) {
try {
output.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
e.printStackTrace();
return;
}
}
}
| true | true | private static void printResultOutput(
final List<SimpleSearchResult> searchResults,
final String algorithmName,
final String inputFilePrefix
) {
final String resultsFileName =
OUTPUT_FILE + algorithmName + UNDERBAR + inputFilePrefix + UNDERBAR
+ RESULT_STRING + FileHandler.CSV_EXTENSION;
Writer output = null;
try {
output = new BufferedWriter(
new FileWriter(
FileHandler.getFileAndCreateIfNeeded(resultsFileName)
));
output.write(RESULTS_HEADER);
for (
int resultIndex = 0;
resultIndex < searchResults.size();
resultIndex++
) {
final SimpleSearchResult result =
searchResults.get(resultIndex);
final int runNumber = resultIndex + 1;
final List<Agent> agents = result.getAgents();
final List<Integer> isCaptainList = result.isCaptain();
List<Integer> budgetRanks = null;
if (result instanceof SearchResult) {
final SearchResult searchResult = (SearchResult) result;
budgetRanks = searchResult.getBudgetRanks();
}
final List<Integer> rsdOrderIndexes = result.getRsdIndexes();
final List<Integer> teamSizes = result.getTeamSizesWithSelf();
final List<Double> teamUtilities = result.getTeamUtilities();
final List<Integer> teamUtilitiesNoJitter =
result.getTeamUtilitiesNoJitter();
final List<Double> meanTeammateUtilities =
result.getMeanTeammateUtilities();
final List<Double> meanTeammateUtilitiesNoJitter =
result.getMeanTeammateUtilitiesNoJitter();
final List<Double> fractionsOfTotalUtility =
result.getFractionsOfTotalUtility();
final List<Double> fractionsOfTotalUtilityNoJitter =
result.getFractionsOfTotalUtilityNoJitter();
final List<Double> envyAmounts = result.getEnvyAmounts();
final List<Integer> envyAmountsNoJitter =
result.getEnvyAmountsNoJitter();
final List<Double> envyMinusSingleGood =
result.getEnvyAmountsMinusSingleGood();
final List<Integer> envyMinusSingleGoodNoJitter =
result.getEnvyAmountsMinusSingleGoodNoJitter();
final List<Double> meanTeammateRanks =
result.meanTeammateRanks();
final List<Double> meanTeammateRanksNoJitter =
result.meanTeammateRanksNoJitter();
final List<Integer> sumOfReversedRanks =
result.sumsOfReversedRanks();
final List<Double> sumOfReversedNoJitter =
result.sumsOfReversedRanksNoJitter();
final List<Integer> favTeammateRanks =
result.favTeammateRanks();
final List<Double> favTeammateRanksNoJitter =
result.favTeammateRanksNoJitter();
final List<Integer> leastFavTeammateRanks =
result.leastFavTeammateRanks();
final List<Double> leastFavTeammateRanksNoJitter =
result.leastFavTeammateRanksNoJitter();
for (int j = 0; j < agents.size(); j++) {
final Agent agent = agents.get(j);
final StringBuilder sb = new StringBuilder();
final int playerId = agent.getId();
final int isCaptain = isCaptainList.get(j);
final double budget = agent.getBudget();
int budgetRank;
if (budgetRanks == null) {
budgetRank = -1;
} else {
budgetRank = budgetRanks.get(j);
}
int rsdOrderIndex;
if (rsdOrderIndexes == null) {
rsdOrderIndex = -1;
} else {
rsdOrderIndex = rsdOrderIndexes.get(j);
}
final int teamSize = teamSizes.get(j);
final double teamUtility = teamUtilities.get(j);
final int teamUtilityNoJitter =
teamUtilitiesNoJitter.get(j);
final double meanTeammateUtility =
meanTeammateUtilities.get(j);
final double meanTeammateUtilityNoJitter =
meanTeammateUtilitiesNoJitter.get(j);
final double fractionOfTotalUtility =
fractionsOfTotalUtility.get(j);
final double fractionOfTotalUtilityNoJitter =
fractionsOfTotalUtilityNoJitter.get(j);
final double envyAmount = envyAmounts.get(j);
final int envyAmountNoJitter = envyAmountsNoJitter.get(j);
final double envyMinusSingle = envyMinusSingleGood.get(j);
final int envyMinusSingleNoJitter =
envyMinusSingleGoodNoJitter.get(j);
final double meanTeammateRank = meanTeammateRanks.get(j);
final double meanTeammateRankNoJitter =
meanTeammateRanksNoJitter.get(j);
final int sumOfReversedRank = sumOfReversedRanks.get(j);
final double sumOfReversedRankNoJitter =
sumOfReversedNoJitter.get(j);
final int favTeammateRank = favTeammateRanks.get(j);
final double favTeammateRankNoJitter =
favTeammateRanksNoJitter.get(j);
final int leastFavTeammateRank =
leastFavTeammateRanks.get(j);
final double leastFavTeammateRankNoJitter =
leastFavTeammateRanksNoJitter.get(j);
sb.append(runNumber).append(COMMA).
append(playerId).append(COMMA).
append(isCaptain).append(COMMA).
append(budget).append(COMMA).
append(budgetRank).append(COMMA).
append(rsdOrderIndex).append(COMMA).
append(teamSize).append(COMMA).
append(teamUtility).append(COMMA).
append(teamUtilityNoJitter).append(COMMA).
append(meanTeammateUtility).append(COMMA).
append(meanTeammateUtilityNoJitter).append(COMMA).
append(fractionOfTotalUtility).append(COMMA).
append(fractionOfTotalUtilityNoJitter).append(COMMA).
append(envyAmount).append(COMMA).
append(envyAmountNoJitter).append(COMMA).
append(envyMinusSingle).append(COMMA).
append(envyMinusSingleNoJitter).append(COMMA).
append(meanTeammateRank).append(COMMA).
append(meanTeammateRankNoJitter).append(COMMA).
append(sumOfReversedRank).append(COMMA).
append(sumOfReversedRankNoJitter).append(COMMA).
append(favTeammateRank).append(COMMA).
append(favTeammateRankNoJitter).append(COMMA).
append(leastFavTeammateRank).append(COMMA).
append(leastFavTeammateRankNoJitter).append(COMMA);
sb.append(NEWLINE);
output.write(sb.toString());
}
}
output.write(NEWLINE);
output.flush();
output.close();
} catch (IOException e) {
if (output != null) {
try {
output.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
e.printStackTrace();
return;
}
}
| private static void printResultOutput(
final List<SimpleSearchResult> searchResults,
final String algorithmName,
final String inputFilePrefix
) {
final String resultsFileName =
OUTPUT_FILE + algorithmName + UNDERBAR + inputFilePrefix + UNDERBAR
+ RESULT_STRING + FileHandler.CSV_EXTENSION;
Writer output = null;
try {
output = new BufferedWriter(
new FileWriter(
FileHandler.getFileAndCreateIfNeeded(resultsFileName)
));
output.write(RESULTS_HEADER);
for (
int resultIndex = 0;
resultIndex < searchResults.size();
resultIndex++
) {
final SimpleSearchResult result =
searchResults.get(resultIndex);
final int runNumber = resultIndex + 1;
final List<Agent> agents = result.getAgents();
final List<Integer> isCaptainList = result.isCaptain();
List<Integer> budgetRanks = null;
if (result instanceof SearchResult) {
final SearchResult searchResult = (SearchResult) result;
budgetRanks = searchResult.getBudgetRanks();
}
final List<Integer> rsdOrderIndexes = result.getRsdIndexes();
final List<Integer> teamSizes = result.getTeamSizesWithSelf();
final List<Double> teamUtilities = result.getTeamUtilities();
final List<Integer> teamUtilitiesNoJitter =
result.getTeamUtilitiesNoJitter();
final List<Double> meanTeammateUtilities =
result.getMeanTeammateUtilities();
final List<Double> meanTeammateUtilitiesNoJitter =
result.getMeanTeammateUtilitiesNoJitter();
final List<Double> fractionsOfTotalUtility =
result.getFractionsOfTotalUtility();
final List<Double> fractionsOfTotalUtilityNoJitter =
result.getFractionsOfTotalUtilityNoJitter();
final List<Double> envyAmounts = result.getEnvyAmounts();
final List<Integer> envyAmountsNoJitter =
result.getEnvyAmountsNoJitter();
final List<Double> envyMinusSingleGood =
result.getEnvyAmountsMinusSingleGood();
final List<Integer> envyMinusSingleGoodNoJitter =
result.getEnvyAmountsMinusSingleGoodNoJitter();
final List<Double> meanTeammateRanks =
result.meanTeammateRanks();
final List<Double> meanTeammateRanksNoJitter =
result.meanTeammateRanksNoJitter();
final List<Integer> sumOfReversedRanks =
result.sumsOfReversedRanks();
final List<Double> sumOfReversedNoJitter =
result.sumsOfReversedRanksNoJitter();
final List<Integer> favTeammateRanks =
result.favTeammateRanks();
final List<Double> favTeammateRanksNoJitter =
result.favTeammateRanksNoJitter();
final List<Integer> leastFavTeammateRanks =
result.leastFavTeammateRanks();
final List<Double> leastFavTeammateRanksNoJitter =
result.leastFavTeammateRanksNoJitter();
for (int j = 0; j < agents.size(); j++) {
final Agent agent = agents.get(j);
final StringBuilder sb = new StringBuilder();
final int playerId = agent.getId();
final int isCaptain = isCaptainList.get(j);
final double budget = agent.getBudget();
int budgetRank;
if (budgetRanks == null) {
budgetRank = -1;
} else {
budgetRank = budgetRanks.get(j);
}
int rsdOrderIndex;
if (rsdOrderIndexes == null) {
rsdOrderIndex = -1;
} else {
rsdOrderIndex = rsdOrderIndexes.get(j);
}
final int teamSize = teamSizes.get(j);
final double teamUtility = teamUtilities.get(j);
final int teamUtilityNoJitter =
teamUtilitiesNoJitter.get(j);
final double meanTeammateUtility =
meanTeammateUtilities.get(j);
final double meanTeammateUtilityNoJitter =
meanTeammateUtilitiesNoJitter.get(j);
final double fractionOfTotalUtility =
fractionsOfTotalUtility.get(j);
final double fractionOfTotalUtilityNoJitter =
fractionsOfTotalUtilityNoJitter.get(j);
final double envyAmount = envyAmounts.get(j);
final int envyAmountNoJitter = envyAmountsNoJitter.get(j);
final double envyMinusSingle = envyMinusSingleGood.get(j);
final int envyMinusSingleNoJitter =
envyMinusSingleGoodNoJitter.get(j);
final double meanTeammateRank = meanTeammateRanks.get(j);
final double meanTeammateRankNoJitter =
meanTeammateRanksNoJitter.get(j);
final int sumOfReversedRank = sumOfReversedRanks.get(j);
final double sumOfReversedRankNoJitter =
sumOfReversedNoJitter.get(j);
final int favTeammateRank = favTeammateRanks.get(j);
final double favTeammateRankNoJitter =
favTeammateRanksNoJitter.get(j);
final int leastFavTeammateRank =
leastFavTeammateRanks.get(j);
final double leastFavTeammateRankNoJitter =
leastFavTeammateRanksNoJitter.get(j);
sb.append(runNumber).append(COMMA).
append(playerId).append(COMMA).
append(isCaptain).append(COMMA).
append(budget).append(COMMA).
append(budgetRank).append(COMMA).
append(rsdOrderIndex).append(COMMA).
append(teamSize).append(COMMA).
append(teamUtility).append(COMMA).
append(teamUtilityNoJitter).append(COMMA).
append(meanTeammateUtility).append(COMMA).
append(meanTeammateUtilityNoJitter).append(COMMA).
append(fractionOfTotalUtility).append(COMMA).
append(fractionOfTotalUtilityNoJitter).append(COMMA).
append(envyAmount).append(COMMA).
append(envyAmountNoJitter).append(COMMA).
append(envyMinusSingle).append(COMMA).
append(envyMinusSingleNoJitter).append(COMMA).
append(meanTeammateRank).append(COMMA).
append(meanTeammateRankNoJitter).append(COMMA).
append(sumOfReversedRank).append(COMMA).
append(sumOfReversedRankNoJitter).append(COMMA).
append(favTeammateRank).append(COMMA).
append(favTeammateRankNoJitter).append(COMMA).
append(leastFavTeammateRank).append(COMMA).
append(leastFavTeammateRankNoJitter);
sb.append(NEWLINE);
output.write(sb.toString());
}
}
output.write(NEWLINE);
output.flush();
output.close();
} catch (IOException e) {
if (output != null) {
try {
output.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
e.printStackTrace();
return;
}
}
|
diff --git a/tool/src/java/org/sakaiproject/lessonbuildertool/tool/producers/ShowPageProducer.java b/tool/src/java/org/sakaiproject/lessonbuildertool/tool/producers/ShowPageProducer.java
index d25a35a2..79b3a418 100644
--- a/tool/src/java/org/sakaiproject/lessonbuildertool/tool/producers/ShowPageProducer.java
+++ b/tool/src/java/org/sakaiproject/lessonbuildertool/tool/producers/ShowPageProducer.java
@@ -1,4077 +1,4077 @@
/**********************************************************************************
* $URL: $
* $Id: $
***********************************************************************************
*
* This was was originally part of Simple Page Tool and was
*
* Copyright (c) 2007 Sakai Project/Sakai Foundation
* Licensed under the Educational Community License version 1.0
*
* The author was Joshua Ryan [email protected]
*
* However this version is primarily new code. The new code is
*
* Copyright (c) 2010 Rutgers, the State University of New Jersey
*
* Author: Eric Jeney, [email protected]
*
* Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.lessonbuildertool.tool.producers;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.cover.ContentTypeImageService;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.event.api.UsageSession;
import org.sakaiproject.event.cover.UsageSessionService;
import org.sakaiproject.lessonbuildertool.SimplePage;
import org.sakaiproject.lessonbuildertool.SimplePageComment;
import org.sakaiproject.lessonbuildertool.SimplePageItem;
import org.sakaiproject.lessonbuildertool.SimplePageLogEntry;
import org.sakaiproject.lessonbuildertool.SimplePageQuestionAnswer;
import org.sakaiproject.lessonbuildertool.SimplePageQuestionResponse;
import org.sakaiproject.lessonbuildertool.SimplePageQuestionResponseTotals;
import org.sakaiproject.lessonbuildertool.SimplePagePeerEvalResult;
import org.sakaiproject.lessonbuildertool.SimpleStudentPage;
import org.sakaiproject.lessonbuildertool.model.SimplePageToolDao;
import org.sakaiproject.lessonbuildertool.service.BltiInterface;
import org.sakaiproject.lessonbuildertool.service.LessonEntity;
import org.sakaiproject.lessonbuildertool.tool.beans.SimplePageBean;
import org.sakaiproject.lessonbuildertool.tool.beans.SimplePageBean.GroupEntry;
import org.sakaiproject.lessonbuildertool.tool.beans.SimplePageBean.Status;
import org.sakaiproject.lessonbuildertool.tool.evolvers.SakaiFCKTextEvolver;
import org.sakaiproject.lessonbuildertool.tool.view.CommentsGradingPaneViewParameters;
import org.sakaiproject.lessonbuildertool.tool.view.CommentsViewParameters;
import org.sakaiproject.lessonbuildertool.tool.view.FilePickerViewParameters;
import org.sakaiproject.lessonbuildertool.tool.view.GeneralViewParameters;
import org.sakaiproject.lessonbuildertool.tool.view.QuestionGradingPaneViewParameters;
import org.sakaiproject.lessonbuildertool.tool.view.ExportCCViewParameters;
import org.sakaiproject.lessonbuildertool.service.LessonBuilderAccessService;
import org.sakaiproject.memory.api.Cache;
import org.sakaiproject.memory.api.MemoryService;
import org.sakaiproject.time.api.TimeService;
import org.sakaiproject.tool.api.Placement;
import org.sakaiproject.tool.api.Session;
import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.tool.api.ToolSession;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.user.api.UserNotDefinedException;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.FormattedText;
import org.sakaiproject.portal.util.CSSUtils;
import uk.org.ponder.localeutil.LocaleGetter;
import uk.org.ponder.messageutil.MessageLocator;
import uk.org.ponder.rsf.builtin.UVBProducer;
import uk.org.ponder.rsf.components.UIBoundBoolean;
import uk.org.ponder.rsf.components.UIBoundString;
import uk.org.ponder.rsf.components.UIBranchContainer;
import uk.org.ponder.rsf.components.UICommand;
import uk.org.ponder.rsf.components.UIComponent;
import uk.org.ponder.rsf.components.UIContainer;
import uk.org.ponder.rsf.components.UIELBinding;
import uk.org.ponder.rsf.components.UIForm;
import uk.org.ponder.rsf.components.UIInitBlock;
import uk.org.ponder.rsf.components.UIInput;
import uk.org.ponder.rsf.components.UIInternalLink;
import uk.org.ponder.rsf.components.UILink;
import uk.org.ponder.rsf.components.UIOutput;
import uk.org.ponder.rsf.components.UISelect;
import uk.org.ponder.rsf.components.UISelectChoice;
import uk.org.ponder.rsf.components.UIVerbatim;
import uk.org.ponder.rsf.components.decorators.UIDisabledDecorator;
import uk.org.ponder.rsf.components.decorators.UIFreeAttributeDecorator;
import uk.org.ponder.rsf.components.decorators.UIStyleDecorator;
import uk.org.ponder.rsf.components.decorators.UITooltipDecorator;
import uk.org.ponder.rsf.evolvers.FormatAwareDateInputEvolver;
import uk.org.ponder.rsf.evolvers.TextInputEvolver;
import uk.org.ponder.rsf.flow.jsfnav.NavigationCase;
import uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter;
import uk.org.ponder.rsf.view.ComponentChecker;
import uk.org.ponder.rsf.view.DefaultView;
import uk.org.ponder.rsf.view.ViewComponentProducer;
import uk.org.ponder.rsf.viewstate.SimpleViewParameters;
import uk.org.ponder.rsf.viewstate.ViewParameters;
import uk.org.ponder.rsf.viewstate.ViewParamsReporter;
import org.apache.commons.lang.StringEscapeUtils;
/**
* This produces the primary view of the page. It also handles the editing of
* the properties of most of the items (through JQuery dialogs).
*
* @author Eric Jeney <[email protected]>
*/
public class ShowPageProducer implements ViewComponentProducer, DefaultView, NavigationCaseReporter, ViewParamsReporter {
private static Log log = LogFactory.getLog(ShowPageProducer.class);
String reqStar = "<span class=\"reqStar\">*</span>";
private SimplePageBean simplePageBean;
private SimplePageToolDao simplePageToolDao;
private FormatAwareDateInputEvolver dateevolver;
private TimeService timeService;
private HttpServletRequest httpServletRequest;
private HttpServletResponse httpServletResponse;
// have to do it here because we need it in urlCache. It has to happen before Spring initialization
private static MemoryService memoryService = (MemoryService)ComponentManager.get(MemoryService.class);
private ToolManager toolManager;
public TextInputEvolver richTextEvolver;
private LessonBuilderAccessService lessonBuilderAccessService;
private Map<String,String> imageToMimeMap;
public void setImageToMimeMap(Map<String,String> map) {
this.imageToMimeMap = map;
}
public boolean useSakaiIcons = ServerConfigurationService.getBoolean("lessonbuilder.use-sakai-icons", false);
public boolean allowSessionId = ServerConfigurationService.getBoolean("session.parameter.allow", false);
public boolean allowCcExport = ServerConfigurationService.getBoolean("lessonbuilder.cc-export", true);
// I don't much like the static, because it opens us to a possible race
// condition, but I don't see much option
// see the setter. It has to be static because it's used in makeLink, which
// is static so it can be used
// by ReorderProducer. I wonder if this whole producer could be made
// application scope?
private static LessonEntity forumEntity;
private static LessonEntity quizEntity;
private static LessonEntity assignmentEntity;
private static LessonEntity bltiEntity;
public MessageLocator messageLocator;
private LocaleGetter localegetter;
public static final String VIEW_ID = "ShowPage";
private static final String DEFAULT_HTML_TYPES = "html,xhtml,htm,xht";
private static String[] htmlTypes = null;
// mp4 means it plays with the flash player if HTML5 doesn't work.
// flv is also played with the flash player, but it doesn't get a backup <OBJECT> inside the player
// Strobe claims to handle MOV files as well, but I feel safer passing them to quicktime, though that requires Quicktime installation
private static final String DEFAULT_MP4_TYPES = "video/mp4,video/m4v,audio/mpeg";
private static String[] mp4Types = null;
private static final String DEFAULT_HTML5_TYPES = "video/mp4,video/m4v,video/webm,video/ogg,audio/mpeg,audio/ogg,audio/wav,audio/x-wav,audio/webm,audio/ogg,audio/mp4,audio/aac";
// jw can also handle audio: audio/mp4,audio/mpeg,audio/ogg
private static String[] html5Types = null;
// WARNING: this must occur after memoryService, for obvious reasons.
// I'm doing it this way because it doesn't appear that Spring can do this kind of initialization
// and it's better to let Java's initialization code handle synchronization than do it ourselves in
// an init method
private static Cache urlCache = memoryService.newCache("org.sakaiproject.lessonbuildertool.tool.producers.ShowPageProducer.url.cache");
String browserString = ""; // set by checkIEVersion;
protected static final int DEFAULT_EXPIRATION = 10 * 60;
static final String ICONSTYLE = "\n.portletTitle .action img {\n background: url({}/help.gif) center right no-repeat;\n}\n.portletTitle .action img:hover, .portletTitle .action img:focus {\n background: url({}/help_h.gif) center right no-repeat\n}\n.portletTitle .title img {\n background: url({}/reload.gif) center left no-repeat;\n}\n.portletTitle .title img:hover, .portletTitle .title img:focus {\n background: url({}/reload_h.gif) center left no-repeat\n}\n";
public String getViewID() {
return VIEW_ID;
}
// this code is written to handle the fact the CSS uses NNNpx and old code
// NNN. We need to be able to convert.
// Length is intended to be a neutral representation. getOld returns without
// px, getNew with px, and getOrig
// the original version
public class Length {
String number;
String unit;
Length(String spec) {
spec = spec.trim();
int numlen;
for (numlen = 0; numlen < spec.length(); numlen++) {
if (!Character.isDigit(spec.charAt(numlen))) {
break;
}
}
number = spec.substring(0, numlen).trim();
unit = spec.substring(numlen).trim().toLowerCase();
}
public String getOld() {
return number + (unit.equals("px") ? "" : unit);
}
public String getNew() {
return number + (unit.equals("") ? "px" : unit);
}
}
// problem is it needs to work with a null argument
public static String getOrig(Length l) {
if (lengthOk(l))
return l.number + l.unit;
else
return "";
}
// do we have a valid length?
public static boolean lengthOk(Length l) {
if (l == null || l.number == null || l.number.equals("")) {
if (l != null && l.unit.equals("auto"))
return true;
return false;
}
return true;
}
// created style arguments. This was done at the time when i thought
// the OBJECT tag actually paid attention to the CSS size. it doesn't.
public String getStyle(Length w, Length h) {
String ret = null;
if (lengthOk(w))
ret = "width:" + w.getNew();
if (lengthOk(h)) {
if (ret != null)
ret = ret + ";";
ret = ret + "height:" + h.getNew();
}
return ret;
}
// produce abbreviated versions of URLs, for use in constructing titles
public String abbrevUrl(String url) {
if (url.startsWith("/")) {
int suffix = url.lastIndexOf("/");
if (suffix > 0) {
url = url.substring(suffix + 1);
}
if (url.startsWith("http:__")) {
url = url.substring(7);
suffix = url.indexOf("_");
if (suffix > 0) {
url = messageLocator.getMessage("simplepage.fromhost").replace("{}", url.substring(0, suffix));
}
} else if (url.startsWith("https:__")) {
url = url.substring(8);
suffix = url.indexOf("_");
if (suffix > 0) {
url = messageLocator.getMessage("simplepage.fromhost").replace("{}", url.substring(0, suffix));
}
}
} else {
// external, the hostname is probably best
try {
URL u = new URL(url);
url = messageLocator.getMessage("simplepage.fromhost").replace("{}", u.getHost());
} catch (Exception ignore) {
log.error("exception in abbrevurl " + ignore);
}
;
}
return url;
}
public String myUrl() {
// previously we computed something, but this will give us the official one
return ServerConfigurationService.getServerUrl();
}
// NOTE:
// pages should normally be called with 3 arguments:
// sendingPageId - the page to show
// itemId - the item used to choose the page, because pages can occur in
// different places, and we need
// to know the context in which this was called. Note that there's an item
// even for top-level pages
// path - push, next, or a number. The number is an index into the
// breadcrumbs if someone clicks
// on breadcrumbs. This item is used to maintain the path (the internal
// form of the breadcrumbs)
// missing is treated as next.
// for startup, none of this will be known, so getCurrentPage will find the
// top level page and item if
// nothing is specified
public void fillComponents(UIContainer tofill, ViewParameters viewParams, ComponentChecker checker) {
GeneralViewParameters params = (GeneralViewParameters) viewParams;
UIOutput.make(tofill, "html").decorate(new UIFreeAttributeDecorator("lang", localegetter.get().getLanguage()))
.decorate(new UIFreeAttributeDecorator("xml:lang", localegetter.get().getLanguage()));
boolean iframeJavascriptDone = false;
// security model:
// canEditPage and canReadPage are normal Sakai privileges. They apply
// to all
// pages in the site.
// However when presented with a page, we need to make sure it's
// actually in
// this site, or users could get to pages in other sites. That's done
// by updatePageObject. The model is that producers always work on the
// current page, and updatePageObject makes sure that is in the current
// site.
// At that point we can safely use canEditPage.
// somewhat misleading. sendingPage specifies the page we're supposed to
// go to. If path is "none", we don't want this page to be what we see
// when we come back to the tool
if (params.getSendingPage() != -1) {
// will fail if page not in this site
// security then depends upon making sure that we only deal with
// this page
try {
simplePageBean.updatePageObject(params.getSendingPage(), !params.getPath().equals("none"));
} catch (Exception e) {
log.warn("ShowPage permission exception " + e);
UIOutput.make(tofill, "error-div");
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.not_available"));
return;
}
}
boolean canEditPage = simplePageBean.canEditPage();
boolean canReadPage = simplePageBean.canReadPage();
boolean canSeeAll = simplePageBean.canSeeAll(); // always on if caneditpage
boolean cameFromGradingPane = params.getPath().equals("none");
if (!canReadPage) {
// this code is intended for the situation where site permissions
// haven't been set up.
// So if the user can't read the page (which is pretty abnormal),
// see if they have site.upd.
// if so, give them some explanation and offer to call the
// permissions helper
String ref = "/site/" + simplePageBean.getCurrentSiteId();
if (simplePageBean.canEditSite()) {
SimplePage currentPage = simplePageBean.getCurrentPage();
UIOutput.make(tofill, "needPermissions");
GeneralViewParameters permParams = new GeneralViewParameters();
permParams.setSendingPage(-1L);
createStandardToolBarLink(PermissionsHelperProducer.VIEW_ID, tofill, "callpermissions", "simplepage.permissions", permParams, "simplepage.permissions.tooltip");
}
// in any case, tell them they can't read the page
UIOutput.make(tofill, "error-div");
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.nopermissions"));
return;
}
if (params.addTool == GeneralViewParameters.COMMENTS) {
simplePageBean.addCommentsSection();
}else if(params.addTool == GeneralViewParameters.STUDENT_CONTENT) {
simplePageBean.addStudentContentSection();
}else if(params.addTool == GeneralViewParameters.STUDENT_PAGE) {
simplePageBean.createStudentPage(params.studentItemId);
canEditPage = simplePageBean.canEditPage();
}
// Find the MSIE version, if we're running it.
int ieVersion = checkIEVersion();
// as far as I can tell, none of these supports fck or ck
// we can make it configurable if necessary, or use WURFL
// however this test is consistent with CKeditor's check.
// that desireable, since if CKeditor is going to use a bare
// text block, we want to handle it as noEditor
String userAgent = httpServletRequest.getHeader("User-Agent");
if (userAgent == null)
userAgent = "";
boolean noEditor = userAgent.toLowerCase().indexOf("mobile") >= 0;
// set up locale
Locale M_locale = null;
String langLoc[] = localegetter.get().toString().split("_");
if (langLoc.length >= 2) {
if ("en".equals(langLoc[0]) && "ZA".equals(langLoc[1])) {
M_locale = new Locale("en", "GB");
} else {
M_locale = new Locale(langLoc[0], langLoc[1]);
}
} else {
M_locale = new Locale(langLoc[0]);
}
// clear session attribute if necessary, after calling Samigo
String clearAttr = params.getClearAttr();
if (clearAttr != null && !clearAttr.equals("")) {
Session session = SessionManager.getCurrentSession();
// don't let users clear random attributes
if (clearAttr.startsWith("LESSONBUILDER_RETURNURL")) {
session.setAttribute(clearAttr, null);
}
}
if (htmlTypes == null) {
String mmTypes = ServerConfigurationService.getString("lessonbuilder.html.types", DEFAULT_HTML_TYPES);
htmlTypes = mmTypes.split(",");
for (int i = 0; i < htmlTypes.length; i++) {
htmlTypes[i] = htmlTypes[i].trim().toLowerCase();
}
Arrays.sort(htmlTypes);
}
if (mp4Types == null) {
String m4Types = ServerConfigurationService.getString("lessonbuilder.mp4.types", DEFAULT_MP4_TYPES);
mp4Types = m4Types.split(",");
for (int i = 0; i < mp4Types.length; i++) {
mp4Types[i] = mp4Types[i].trim().toLowerCase();
}
Arrays.sort(mp4Types);
}
if (html5Types == null) {
String jTypes = ServerConfigurationService.getString("lessonbuilder.html5.types", DEFAULT_HTML5_TYPES);
html5Types = jTypes.split(",");
for (int i = 0; i < html5Types.length; i++) {
html5Types[i] = html5Types[i].trim().toLowerCase();
}
Arrays.sort(html5Types);
}
// remember that page tool was reset, so we need to give user the option
// of going to the last page from the previous session
SimplePageToolDao.PageData lastPage = simplePageBean.toolWasReset();
// if this page was copied from another site we may have to update links
// can only do the fixups if you can write. We could hack permissions, but
// I assume a site owner will access the site first
if (canEditPage)
simplePageBean.maybeUpdateLinks();
// if starting the tool, sendingpage isn't set. the following call
// will give us the top page.
SimplePage currentPage = simplePageBean.getCurrentPage();
// now we need to find our own item, for access checks, etc.
SimplePageItem pageItem = null;
if (currentPage != null) {
pageItem = simplePageBean.getCurrentPageItem(params.getItemId());
}
// one more security check: make sure the item actually involves this
// page.
// otherwise someone could pass us an item from a different page in
// another site
// actually this normally happens if the page doesn't exist and we don't
// have permission to create it
if (currentPage == null || pageItem == null ||
(pageItem.getType() != SimplePageItem.STUDENT_CONTENT &&Long.valueOf(pageItem.getSakaiId()) != currentPage.getPageId())) {
log.warn("ShowPage item not in page");
UIOutput.make(tofill, "error-div");
if (currentPage == null)
// most likely tool was created by site info but no page
// has created. It will created the first time an item is created,
// so from a user point of view it looks like no item has been added
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.noitems_error_user"));
else
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.not_available"));
return;
}
// check two parts of isitemvisible where we want to give specific errors
// potentially need time zone for setting release date
if (!canSeeAll && currentPage.getReleaseDate() != null && currentPage.getReleaseDate().after(new Date())) {
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, M_locale);
TimeZone tz = timeService.getLocalTimeZone();
df.setTimeZone(tz);
String releaseDate = df.format(currentPage.getReleaseDate());
String releaseMessage = messageLocator.getMessage("simplepage.not_yet_available_releasedate").replace("{}", releaseDate);
UIOutput.make(tofill, "error-div");
UIOutput.make(tofill, "error", releaseMessage);
return;
}
// the only thing not already tested in isItemVisible is groups. In theory
// no one should have a URL to a page for which they aren't in the group,
// so I'm not trying to give a better message than just hidden
if (!canSeeAll && currentPage.isHidden() || !simplePageBean.isItemVisible(pageItem)) {
UIOutput.make(tofill, "error-div");
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.not_available_hidden"));
return;
}
// I believe we've now checked all the args for permissions issues. All
// other item and
// page references are generated here based on the contents of the page
// and items.
// needed to process path arguments first, so refresh page goes the right page
if (simplePageBean.getTopRefresh()) {
UIOutput.make(tofill, "refresh");
return; // but there's no point doing anything more
}
// error from previous operation
// consumes the message, so don't do it if refreshing
List<String> errMessages = simplePageBean.errMessages();
if (errMessages != null) {
UIOutput.make(tofill, "error-div");
for (String e: errMessages) {
UIBranchContainer er = UIBranchContainer.make(tofill, "errors:");
UIOutput.make(er, "error-message", e);
}
}
if (canEditPage) {
// special instructor-only javascript setup.
// but not if we're refreshing
UIOutput.make(tofill, "instructoronly");
// Chome and IE will abort a page if some on it was input from
// a previous submit. I.e. if an HTML editor was used. In theory they
// only do this if part of it is Javascript, but in practice they do
// it for images as well. The protection isn't worthwhile, since it only
// protects the first time. Since it will reesult in a garbled page,
// people will just refresh the page, and then they'll get the new
// contents. The Chrome guys refuse to fix this so it just applies to Javascript
httpServletResponse.setHeader("X-XSS-Protection", "0");
}
if (currentPage == null || pageItem == null) {
UIOutput.make(tofill, "error-div");
if (canEditPage) {
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.impossible1"));
} else {
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.not_available"));
}
return;
}
// Set up customizable CSS
ContentResource cssLink = simplePageBean.getCssForCurrentPage();
if(cssLink != null) {
UIOutput.make(tofill, "customCSS").decorate(new UIFreeAttributeDecorator("href", cssLink.getUrl()));
}
// offer to go to saved page if this is the start of a session, in case
// user has logged off and logged on again.
// need to offer to go to previous page? even if a new session, no need
// if we're already on that page
if (lastPage != null && lastPage.pageId != currentPage.getPageId()) {
UIOutput.make(tofill, "refreshAlert");
UIOutput.make(tofill, "refresh-message", messageLocator.getMessage("simplepage.last-visited"));
// Should simply refresh
GeneralViewParameters p = new GeneralViewParameters(VIEW_ID);
p.setSendingPage(lastPage.pageId);
p.setItemId(lastPage.itemId);
// reset the path to the saved one
p.setPath("log");
String name = lastPage.name;
// Titles are set oddly by Student Content Pages
SimplePage lastPageObj = simplePageToolDao.getPage(lastPage.pageId);
if(lastPageObj.getOwner() != null) {
name = lastPageObj.getTitle();
}
UIInternalLink.make(tofill, "refresh-link", name, p);
}
// path is the breadcrumbs. Push, pop or reset depending upon path=
// programmer documentation.
String title;
String ownerName = null;
if(pageItem.getType() != SimplePageItem.STUDENT_CONTENT) {
title = pageItem.getName();
}else {
title = currentPage.getTitle();
if(!pageItem.isAnonymous() || canEditPage) {
try {
String owner = currentPage.getOwner();
String group = currentPage.getGroup();
if (group != null)
ownerName = simplePageBean.getCurrentSite().getGroup(group).getTitle();
else
ownerName = UserDirectoryService.getUser(owner).getDisplayName();
} catch (Exception ignore) {};
if (ownerName != null && !ownerName.equals(title))
title += " (" + ownerName + ")";
}
}
String newPath = null;
// If the path is "none", then we don't want to record this page as being viewed, or set a path
if(!params.getPath().equals("none")) {
newPath = simplePageBean.adjustPath(params.getPath(), currentPage.getPageId(), pageItem.getId(), title);
simplePageBean.adjustBackPath(params.getBackPath(), currentPage.getPageId(), pageItem.getId(), pageItem.getName());
}
// put out link to index of pages
GeneralViewParameters showAll = new GeneralViewParameters(PagePickerProducer.VIEW_ID);
showAll.setSource("summary");
UIInternalLink.make(tofill, "show-pages", messageLocator.getMessage("simplepage.showallpages"), showAll);
if (canEditPage) {
// show tool bar, but not if coming from grading pane
if(!cameFromGradingPane) {
createToolBar(tofill, currentPage, (pageItem.getType() == SimplePageItem.STUDENT_CONTENT));
}
UIOutput.make(tofill, "title-descrip");
String label = null;
if (pageItem.getType() == SimplePageItem.STUDENT_CONTENT)
label = messageLocator.getMessage("simplepage.editTitle");
else
label = messageLocator.getMessage("simplepage.title");
String descrip = null;
if (pageItem.getType() == SimplePageItem.STUDENT_CONTENT)
descrip = messageLocator.getMessage("simplepage.title-student-descrip");
else if (pageItem.getPageId() == 0)
descrip = messageLocator.getMessage("simplepage.title-top-descrip");
else
descrip = messageLocator.getMessage("simplepage.title-descrip");
UIOutput.make(tofill, "edit-title").decorate(new UIFreeAttributeDecorator("title", descrip));
UIOutput.make(tofill, "edit-title-text", label);
UIOutput.make(tofill, "title-descrip-text", descrip);
if (pageItem.getPageId() == 0 && currentPage.getOwner() == null) { // top level page
// need dropdown
UIOutput.make(tofill, "dropdown");
UIOutput.make(tofill, "moreDiv");
UIOutput.make(tofill, "new-page").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.new-page-tooltip")));
UIOutput.make(tofill, "import-cc").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.import_cc.tooltip")));
UIOutput.make(tofill, "export-cc").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.export_cc.tooltip")));
}
// Checks to see that user can edit and that this is either a top level page,
// or a top level student page (not a subpage to a student page)
if(simplePageBean.getEditPrivs() == 0 && (pageItem.getPageId() == 0)) {
UIOutput.make(tofill, "remove-li");
UIOutput.make(tofill, "remove-page").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.remove-page-tooltip")));
} else if (simplePageBean.getEditPrivs() == 0 && currentPage.getOwner() != null) {
// getEditPrivs < 2 if we want to let the student delete. Currently we don't. There can be comments
// from other students and the page can be shared
SimpleStudentPage studentPage = simplePageToolDao.findStudentPage(currentPage.getTopParent());
if (studentPage != null && studentPage.getPageId() == currentPage.getPageId()) {
System.out.println("is student page 2");
UIOutput.make(tofill, "remove-student");
- UIOutput.make(tofill, "remove-page-student").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.remove-page-tooltip")));
+ UIOutput.make(tofill, "remove-page-student").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.remove-student-page-explanation")));
}
}
UIOutput.make(tofill, "dialogDiv");
} else if (!canReadPage) {
return;
} else if (!canSeeAll) {
// see if there are any unsatisfied prerequisites
// if this isn't a top level page, this will check that the page above is
// accessible. That matters because we check visible, available and release
// only for this page but not for the containing page
List<String> needed = simplePageBean.pagesNeeded(pageItem);
if (needed.size() > 0) {
// yes. error and abort
if (pageItem.getPageId() != 0) {
// not top level. This should only happen from a "next"
// link.
// at any rate, the best approach is to send the user back
// to the calling page
List<SimplePageBean.PathEntry> path = simplePageBean.getHierarchy();
SimplePageBean.PathEntry containingPage = null;
if (path.size() > 1) {
// page above this. this page is on the top
containingPage = path.get(path.size() - 2);
}
if (containingPage != null) { // not a top level page, point
// to containing page
GeneralViewParameters view = new GeneralViewParameters(VIEW_ID);
view.setSendingPage(containingPage.pageId);
view.setItemId(containingPage.pageItemId);
view.setPath(Integer.toString(path.size() - 2));
UIInternalLink.make(tofill, "redirect-link", containingPage.title, view);
UIOutput.make(tofill, "redirect");
} else {
UIOutput.make(tofill, "error-div");
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.not_available"));
}
return;
}
// top level page where prereqs not satisified. Output list of
// pages he needs to do first
UIOutput.make(tofill, "pagetitle", currentPage.getTitle());
UIOutput.make(tofill, "error-div");
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.has_prerequistes"));
UIBranchContainer errorList = UIBranchContainer.make(tofill, "error-list:");
for (String errorItem : needed) {
UIBranchContainer errorListItem = UIBranchContainer.make(errorList, "error-item:");
UIOutput.make(errorListItem, "error-item-text", errorItem);
}
return;
}
}
ToolSession toolSession = SessionManager.getCurrentToolSession();
String helpurl = (String)toolSession.getAttribute("sakai-portal:help-action");
String reseturl = (String)toolSession.getAttribute("sakai-portal:reset-action");
String skinName = null;
String skinRepo = null;
String iconBase = null;
UIComponent titlediv = UIOutput.make(tofill, "titlediv");
// we need to do special CSS for old portal
if (helpurl == null)
titlediv.decorate(new UIStyleDecorator("oldPortal"));
if (helpurl != null || reseturl != null) {
// these URLs are defined if we're in the neo portal
// in that case we need our own help and reset icons. We want
// to take them from the current skin, so find its prefix.
// unfortunately the neoportal tacks neo- on front of the skin
// name, so this is more complex than you might think.
skinRepo = ServerConfigurationService.getString("skin.repo", "/library/skin");
iconBase = skinRepo + "/" + CSSUtils.adjustCssSkinFolder(null) + "/images";
UIVerbatim.make(tofill, "iconstyle", ICONSTYLE.replace("{}", iconBase));
}
if (helpurl != null) {
UILink.make(tofill, (pageItem.getPageId() == 0 ? "helpbutton" : "helpbutton2")).
decorate(new UIFreeAttributeDecorator("onclick",
"openWindow('" + helpurl + "', 'Help', 'resizeable=yes,toolbar=no,scrollbars=yes,menubar=yes,width=800,height=600'); return false")).
decorate(new UIFreeAttributeDecorator("title",
messageLocator.getMessage("simplepage.help-button")));
UIOutput.make(tofill, (pageItem.getPageId() == 0 ? "helpimage" : "helpimage2")).
decorate(new UIFreeAttributeDecorator("alt",
messageLocator.getMessage("simplepage.help-button")));
UIOutput.make(tofill, (pageItem.getPageId() == 0 ? "helpnewwindow" : "helpnewwindow2"),
messageLocator.getMessage("simplepage.opens-in-new"));
}
if (reseturl != null) {
UILink.make(tofill, (pageItem.getPageId() == 0 ? "resetbutton" : "resetbutton2")).
decorate(new UIFreeAttributeDecorator("onclick",
"location.href='" + reseturl + "'; return false")).
decorate(new UIFreeAttributeDecorator("title",
messageLocator.getMessage("simplepage.reset-button")));
UIOutput.make(tofill, (pageItem.getPageId() == 0 ? "resetimage" : "resetimage2")).
decorate(new UIFreeAttributeDecorator("alt",
messageLocator.getMessage("simplepage.reset-button")));
}
// note page accessed. the code checks to see whether all the required
// items on it have been finished, and if so marks it complete, else just updates
// access date save the path because if user goes to it later we want to restore the
// breadcrumbs
if(newPath != null) {
if(pageItem.getType() != SimplePageItem.STUDENT_CONTENT) {
simplePageBean.track(pageItem.getId(), newPath);
}else {
simplePageBean.track(pageItem.getId(), newPath, currentPage.getPageId());
}
}
UIOutput.make(tofill, "pagetitle", currentPage.getTitle());
if(currentPage.getOwner() != null && simplePageBean.getEditPrivs() == 0) {
SimpleStudentPage student = simplePageToolDao.findStudentPageByPageId(currentPage.getPageId());
// Make sure this is a top level student page
if(student != null && pageItem.getGradebookId() != null) {
UIOutput.make(tofill, "gradingSpan");
UIOutput.make(tofill, "commentsUUID", String.valueOf(student.getId()));
UIOutput.make(tofill, "commentPoints", String.valueOf((student.getPoints() != null? student.getPoints() : "")));
UIOutput pointsBox = UIOutput.make(tofill, "studentPointsBox");
UIOutput.make(tofill, "topmaxpoints", String.valueOf((pageItem.getGradebookPoints() != null? pageItem.getGradebookPoints():"")));
if (ownerName != null)
pointsBox.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.grade-for-student").replace("{}",ownerName)));
List<SimpleStudentPage> studentPages = simplePageToolDao.findStudentPages(student.getItemId());
Collections.sort(studentPages, new Comparator<SimpleStudentPage>() {
public int compare(SimpleStudentPage o1, SimpleStudentPage o2) {
String title1 = o1.getTitle();
if (title1 == null)
title1 = "";
String title2 = o2.getTitle();
if (title2 == null)
title2 = "";
return title1.compareTo(title2);
}
});
for(int in = 0; in < studentPages.size(); in++) {
if(studentPages.get(in).isDeleted()) {
studentPages.remove(in);
}
}
int i = -1;
for(int in = 0; in < studentPages.size(); in++) {
if(student.getId() == studentPages.get(in).getId()) {
i = in;
break;
}
}
if(i > 0) {
GeneralViewParameters eParams = new GeneralViewParameters(ShowPageProducer.VIEW_ID, studentPages.get(i-1).getPageId());
eParams.setItemId(studentPages.get(i-1).getItemId());
eParams.setPath("next");
UIInternalLink.make(tofill, "gradingBack", eParams);
}
if(i < studentPages.size() - 1) {
GeneralViewParameters eParams = new GeneralViewParameters(ShowPageProducer.VIEW_ID, studentPages.get(i+1).getPageId());
eParams.setItemId(studentPages.get(i+1).getItemId());
eParams.setPath("next");
UIInternalLink.make(tofill, "gradingForward", eParams);
}
printGradingForm(tofill);
}
}
// breadcrumbs
if (pageItem.getPageId() != 0) {
// Not top-level, so we have to show breadcrumbs
List<SimplePageBean.PathEntry> breadcrumbs = simplePageBean.getHierarchy();
int index = 0;
if (breadcrumbs.size() > 1 || reseturl != null || helpurl != null) {
UIOutput.make(tofill, "crumbdiv");
if (breadcrumbs.size() > 1)
for (SimplePageBean.PathEntry e : breadcrumbs) {
// don't show current page. We already have a title. This
// was too much
UIBranchContainer crumb = UIBranchContainer.make(tofill, "crumb:");
GeneralViewParameters view = new GeneralViewParameters(VIEW_ID);
view.setSendingPage(e.pageId);
view.setItemId(e.pageItemId);
view.setPath(Integer.toString(index));
if (index < breadcrumbs.size() - 1) {
// Not the last item
UIInternalLink.make(crumb, "crumb-link", e.title, view);
UIOutput.make(crumb, "crumb-follow", " > ");
} else {
UIOutput.make(crumb, "crumb-follow", e.title).decorate(new UIStyleDecorator("bold"));
}
index++;
}
}
}
// see if there's a next item in sequence.
simplePageBean.addPrevLink(tofill, pageItem);
simplePageBean.addNextLink(tofill, pageItem);
// swfObject is not currently used
boolean shownSwfObject = false;
// items to show
List<SimplePageItem> itemList = (List<SimplePageItem>) simplePageBean.getItemsOnPage(currentPage.getPageId());
// Move all items with sequence <= 0 to the end of the list.
// Count is necessary to guarantee we don't infinite loop over a
// list that only has items with sequence <= 0.
// Becauses sequence number is < 0, these start out at the beginning
int count = 1;
while(itemList.size() > count && itemList.get(0).getSequence() <= 0) {
itemList.add(itemList.remove(0));
count++;
}
// Make sure we only add the comments javascript file once,
// even if there are multiple comments tools on the page.
boolean addedCommentsScript = false;
int commentsCount = 0;
// Find the most recent comment on the page by current user
long postedCommentId = -1;
if (params.postedComment) {
postedCommentId = findMostRecentComment();
}
//
//
// MAIN list of items
//
// produce the main table
// Is anything visible?
// Note that we don't need to check whether any item is available, since the first visible
// item is always available.
boolean anyItemVisible = false;
if (itemList.size() > 0) {
UIBranchContainer container = UIBranchContainer.make(tofill, "itemContainer:");
boolean showRefresh = false;
int textboxcount = 1;
UIBranchContainer tableContainer = UIBranchContainer.make(container, "itemTable:");
// formatting: two columns:
// 1: edit buttons, omitted for student
// 2: main content
// For links, which have status icons, the main content is a flush
// left div with the icon
// followed by a div with margin-left:30px. That takes it beyond the
// icon, and avoids the
// wrap-around appearance you'd get without the margin.
// Normally the description is shown as a second div with
// indentation in the CSS.
// That puts it below the link. However with a link that's a button,
// we do float left
// for the button so the text wraps around it. I think that's
// probably what people would expect.
UIOutput.make(tableContainer, "colgroup");
if (canEditPage) {
UIOutput.make(tableContainer, "col1");
}
UIOutput.make(tableContainer, "col2");
// our accessiblity people say not to use TH for except for a data table
// the table header is for accessibility tools only, so it's
// positioned off screen
//if (canEditPage) {
// UIOutput.make(tableContainer, "header-edits");
// }
// UIOutput.make(tableContainer, "header-items");
for (SimplePageItem i : itemList) {
// listitem is mostly historical. it uses some shared HTML, but
// if I were
// doing it from scratch I wouldn't make this distinction. At
// the moment it's
// everything that isn't inline.
boolean listItem = !(i.getType() == SimplePageItem.TEXT || i.getType() == SimplePageItem.MULTIMEDIA
|| i.getType() == SimplePageItem.COMMENTS || i.getType() == SimplePageItem.STUDENT_CONTENT
|| i.getType() == SimplePageItem.QUESTION || i.getType() == SimplePageItem.PEEREVAL);
// (i.getType() == SimplePageItem.PAGE &&
// "button".equals(i.getFormat())))
if (!simplePageBean.isItemVisible(i, currentPage)) {
continue;
}
anyItemVisible = true;
UIBranchContainer tableRow = UIBranchContainer.make(tableContainer, "item:");
// set class name showing what the type is, so people can do funky CSS
String itemClassName = null;
switch (i.getType()) {
case SimplePageItem.RESOURCE: itemClassName = "resourceType"; break;
case SimplePageItem.PAGE: itemClassName = "pageType"; break;
case SimplePageItem.ASSIGNMENT: itemClassName = "assignmentType"; break;
case SimplePageItem.ASSESSMENT: itemClassName = "assessmentType"; break;
case SimplePageItem.TEXT: itemClassName = "textType"; break;
case SimplePageItem.URL: itemClassName = "urlType"; break;
case SimplePageItem.MULTIMEDIA: itemClassName = "multimediaType"; break;
case SimplePageItem.FORUM: itemClassName = "forumType"; break;
case SimplePageItem.COMMENTS: itemClassName = "commentsType"; break;
case SimplePageItem.STUDENT_CONTENT: itemClassName = "studentContentType"; break;
case SimplePageItem.QUESTION: itemClassName = "question"; break;
case SimplePageItem.BLTI: itemClassName = "bltiType"; break;
case SimplePageItem.PEEREVAL: itemClassName = "peereval"; break;
}
if (listItem){
itemClassName = itemClassName + " listType";
}
if (canEditPage) {
itemClassName = itemClassName + " canEdit";
}
tableRow.decorate(new UIFreeAttributeDecorator("class", itemClassName));
// you really need the HTML file open at the same time to make
// sense of the following code
if (listItem) { // Not an HTML Text, Element or Multimedia
// Element
if (canEditPage) {
UIOutput.make(tableRow, "current-item-id2", String.valueOf(i.getId()));
}
// users can declare a page item to be navigational. If so
// we display
// it to the left of the normal list items, and use a
// button. This is
// used for pages that are "next" pages, i.e. they replace
// this page
// rather than creating a new level in the breadcrumbs.
// Since they can't
// be required, they don't need the status image, which is
// good because
// they're displayed with colspan=2, so there's no space for
// the image.
boolean navButton = "button".equals(i.getFormat()) && !i.isRequired();
boolean notDone = false;
Status status = Status.NOT_REQUIRED;
if (!navButton) {
status = handleStatusImage(tableRow, i);
if (status == Status.REQUIRED) {
notDone = true;
}
}
boolean isInline = (i.getType() == SimplePageItem.BLTI && "inline".equals(i.getFormat()));
UIOutput linktd = UIOutput.make(tableRow, "item-td");
UIBranchContainer linkdiv = null;
if (!isInline) {
linkdiv = UIBranchContainer.make(tableRow, "link-div:");
UIOutput itemicon = UIOutput.make(linkdiv,"item-icon");
switch (i.getType()) {
case SimplePageItem.FORUM:
itemicon.decorate(new UIFreeAttributeDecorator("src", "/library/image/silk/comments.png"));
break;
case SimplePageItem.ASSIGNMENT:
itemicon.decorate(new UIFreeAttributeDecorator("src", "/library/image/silk/page_edit.png"));
break;
case SimplePageItem.ASSESSMENT:
itemicon.decorate(new UIFreeAttributeDecorator("src", "/library/image/silk/pencil.png"));
break;
case SimplePageItem.BLTI:
itemicon.decorate(new UIFreeAttributeDecorator("src", "/library/image/silk/application_go.png"));
break;
case SimplePageItem.PAGE:
itemicon.decorate(new UIFreeAttributeDecorator("src", "/library/image/silk/book_open.png"));
break;
case SimplePageItem.RESOURCE:
String mimeType = i.getHtml();
if("application/octet-stream".equals(mimeType)) {
// OS X reports octet stream for things like MS Excel documents.
// Force a mimeType lookup so we get a decent icon.
mimeType = null;
}
if (mimeType == null || mimeType.equals("")) {
String s = i.getSakaiId();
int j = s.lastIndexOf(".");
if (j >= 0)
s = s.substring(j+1);
mimeType = ContentTypeImageService.getContentType(s);
// System.out.println("type " + s + ">" + mimeType);
}
String src = null;
if (!useSakaiIcons)
src = imageToMimeMap.get(mimeType);
if (src == null) {
String image = ContentTypeImageService.getContentTypeImage(mimeType);
if (image != null)
src = "/library/image/" + image;
}
if(src != null) {
itemicon.decorate(new UIFreeAttributeDecorator("src", src));
}
break;
}
}
UIOutput descriptiondiv = null;
// refresh isn't actually used anymore. We've changed the
// way things are
// done so the user never has to request a refresh.
// FYI: this actually puts in an IFRAME for inline BLTI items
showRefresh = !makeLink(tableRow, "link", i, canSeeAll, currentPage, notDone, status) || showRefresh;
UILink.make(tableRow, "copylink", i.getName(), "http://lessonbuilder.sakaiproject.org/" + i.getId() + "/").
decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.copylink2").replace("{}", i.getName())));
// dummy is used when an assignment, quiz, or forum item is
// copied
// from another site. The way the copy code works, our
// import code
// doesn't have access to the necessary info to use the item
// from the
// new site. So we add a dummy, which generates an
// explanation that the
// author is going to have to choose the item from the
// current site
if (i.getSakaiId().equals(SimplePageItem.DUMMY)) {
String code = null;
switch (i.getType()) {
case SimplePageItem.ASSIGNMENT:
code = "simplepage.copied.assignment";
break;
case SimplePageItem.ASSESSMENT:
code = "simplepage.copied.assessment";
break;
case SimplePageItem.FORUM:
code = "simplepage.copied.forum";
break;
}
descriptiondiv = UIOutput.make(tableRow, "description", messageLocator.getMessage(code));
} else {
descriptiondiv = UIOutput.make(tableRow, "description", i.getDescription());
}
if (isInline)
descriptiondiv.decorate(new UIFreeAttributeDecorator("style", "margin-top: 4px"));
if (!isInline) {
// nav button gets float left so any description goes to its
// right. Otherwise the
// description block will display underneath
if ("button".equals(i.getFormat())) {
linkdiv.decorate(new UIFreeAttributeDecorator("style", "float:none"));
}
// for accessibility
if (navButton) {
linkdiv.decorate(new UIFreeAttributeDecorator("role", "navigation"));
}
}
// note that a lot of the info here is used by the
// javascript that prepares
// the jQuery dialogs
if (canEditPage) {
UIOutput.make(tableRow, "edit-td");
UILink.make(tableRow, "edit-link", messageLocator.getMessage("simplepage.editItem"), "").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.generic").replace("{}", i.getName())));
// the following information is displayed using <INPUT
// type=hidden ...
// it contains information needed to populate the "edit"
// popup dialog
UIOutput.make(tableRow, "prerequisite-info", String.valueOf(i.isPrerequisite()));
String itemGroupString = null;
boolean entityDeleted = false;
boolean notPublished = false;
if (i.getType() == SimplePageItem.ASSIGNMENT) {
// the type indicates whether scoring is letter
// grade, number, etc.
// the javascript needs this to present the right
// choices to the user
// types 6 and 8 aren't legal scoring types, so they
// are used as
// markers for quiz or forum. I ran out of numbers
// and started using
// text for things that aren't scoring types. That's
// better anyway
int type = 4;
LessonEntity assignment = null;
if (!i.getSakaiId().equals(SimplePageItem.DUMMY)) {
assignment = assignmentEntity.getEntity(i.getSakaiId(), simplePageBean);
if (assignment != null) {
type = assignment.getTypeOfGrade();
String editUrl = assignment.editItemUrl(simplePageBean);
if (editUrl != null) {
UIOutput.make(tableRow, "edit-url", editUrl);
}
itemGroupString = simplePageBean.getItemGroupString(i, assignment, true);
UIOutput.make(tableRow, "item-groups", itemGroupString);
if (!assignment.objectExists())
entityDeleted = true;
}
}
UIOutput.make(tableRow, "type", String.valueOf(type));
String requirement = String.valueOf(i.getSubrequirement());
if ((type == SimplePageItem.PAGE || type == SimplePageItem.ASSIGNMENT) && i.getSubrequirement()) {
requirement = i.getRequirementText();
}
UIOutput.make(tableRow, "requirement-text", requirement);
} else if (i.getType() == SimplePageItem.ASSESSMENT) {
UIOutput.make(tableRow, "type", "6"); // Not used by
// assignments,
// so it is
// safe to dedicate to assessments
UIOutput.make(tableRow, "requirement-text", (i.getSubrequirement() ? i.getRequirementText() : "false"));
LessonEntity quiz = quizEntity.getEntity(i.getSakaiId(),simplePageBean);
if (quiz != null) {
String editUrl = quiz.editItemUrl(simplePageBean);
if (editUrl != null) {
UIOutput.make(tableRow, "edit-url", editUrl);
}
editUrl = quiz.editItemSettingsUrl(simplePageBean);
if (editUrl != null) {
UIOutput.make(tableRow, "edit-settings-url", editUrl);
}
itemGroupString = simplePageBean.getItemGroupString(i, quiz, true);
UIOutput.make(tableRow, "item-groups", itemGroupString);
if (!quiz.objectExists())
entityDeleted = true;
} else
notPublished = quizEntity.notPublished(i.getSakaiId());
} else if (i.getType() == SimplePageItem.BLTI) {
UIOutput.make(tableRow, "type", "b");
LessonEntity blti= (bltiEntity == null ? null : bltiEntity.getEntity(i.getSakaiId()));
if (blti != null) {
String editUrl = blti.editItemUrl(simplePageBean);
if (editUrl != null)
UIOutput.make(tableRow, "edit-url", editUrl);
UIOutput.make(tableRow, "item-format", i.getFormat());
if (i.getHeight() != null)
UIOutput.make(tableRow, "item-height", i.getHeight());
itemGroupString = simplePageBean.getItemGroupString(i, null, true);
UIOutput.make(tableRow, "item-groups", itemGroupString );
if (!blti.objectExists())
entityDeleted = true;
}
} else if (i.getType() == SimplePageItem.FORUM) {
UIOutput.make(tableRow, "extra-info");
UIOutput.make(tableRow, "type", "8");
LessonEntity forum = forumEntity.getEntity(i.getSakaiId());
if (forum != null) {
String editUrl = forum.editItemUrl(simplePageBean);
if (editUrl != null) {
UIOutput.make(tableRow, "edit-url", editUrl);
}
itemGroupString = simplePageBean.getItemGroupString(i, forum, true);
UIOutput.make(tableRow, "item-groups", itemGroupString);
if (!forum.objectExists())
entityDeleted = true;
}
} else if (i.getType() == SimplePageItem.PAGE) {
UIOutput.make(tableRow, "type", "page");
UIOutput.make(tableRow, "page-next", Boolean.toString(i.getNextPage()));
UIOutput.make(tableRow, "page-button", Boolean.toString("button".equals(i.getFormat())));
itemGroupString = simplePageBean.getItemGroupString(i, null, true);
UIOutput.make(tableRow, "item-groups", itemGroupString);
} else if (i.getType() == SimplePageItem.RESOURCE) {
try {
itemGroupString = simplePageBean.getItemGroupStringOrErr(i, null, true);
} catch (IdUnusedException e) {
itemGroupString = "";
entityDeleted = true;
}
if (simplePageBean.getInherited())
UIOutput.make(tableRow, "item-groups", "--inherited--");
else
UIOutput.make(tableRow, "item-groups", itemGroupString );
UIOutput.make(tableRow, "item-samewindow", Boolean.toString(i.isSameWindow()));
UIVerbatim.make(tableRow, "item-path", getItemPath(i));
}
String releaseString = simplePageBean.getReleaseString(i);
if (itemGroupString != null || releaseString != null || entityDeleted || notPublished) {
if (itemGroupString != null)
itemGroupString = simplePageBean.getItemGroupTitles(itemGroupString, i);
if (itemGroupString != null) {
itemGroupString = " [" + itemGroupString + "]";
if (releaseString != null)
itemGroupString = " " + releaseString + itemGroupString;
} else if (releaseString != null)
itemGroupString = " " + releaseString;
if (notPublished) {
if (itemGroupString != null)
itemGroupString = itemGroupString + " " +
messageLocator.getMessage("simplepage.not-published");
else
itemGroupString = messageLocator.getMessage("simplepage.not-published");
}
if (entityDeleted) {
if (itemGroupString != null)
itemGroupString = itemGroupString + " " +
messageLocator.getMessage("simplepage.deleted-entity");
else
itemGroupString = messageLocator.getMessage("simplepage.deleted-entity");
}
if (itemGroupString != null)
UIOutput.make(tableRow, (isInline ? "item-group-titles-div" : "item-group-titles"), itemGroupString);
}
}
// the following are for the inline item types. Multimedia
// is the most complex because
// it can be IMG, IFRAME, or OBJECT, and Youtube is treated
// separately
} else if (i.getType() == SimplePageItem.MULTIMEDIA) {
// This code should be read together with the code in SimplePageBean
// that sets up this data, method addMultimedia. Most display is set
// up here, but note that show-page.js invokes the jquery oembed on all
// <A> items with class="oembed".
// historically this code was to display files ,and urls leading to things
// like MP4. as backup if we couldn't figure out what to do we'd put something
// in an iframe. The one exception is youtube, which we supposed explicitly.
// However we now support several ways to embed content. We use the
// multimediaDisplayType code to indicate which. The codes are
// 1 -- embed code, 2 -- av type, 3 -- oembed, 4 -- iframe
// 2 is the original code: MP4, image, and as a special case youtube urls
// since we have old entries with no type code, and that behave the same as
// 2, we start by converting 2 to null.
// then the logic is
// if type == null & youtube, do youtube
// if type == null & image, do iamge
// if type == null & not HTML do MP4 or other player for file
// final fallthrough to handel the new types, with IFRAME if all else fails
// the old code creates ojbects in ContentHosting for both files and URLs.
// The new code saves the embed code or URL itself as an atteibute of the item
// If I were doing it again, I wouldn't create the ContebtHosting item
// Note that IFRAME is only used for something where the far end claims the MIME
// type is HTML. For weird stuff like MS Word files I use the file display code, which
// will end up producing <OBJECT>.
// the reason this code is complex is that we try to choose
// the best
// HTML for displaying the particular type of object. We've
// added complexities
// over time as we get more experience with different
// object types and browsers.
String itemGroupString = null;
String itemGroupTitles = null;
boolean entityDeleted = false;
// new format explicit display indication
String mmDisplayType = i.getAttribute("multimediaDisplayType");
// 2 is the generic "use old display" so treat it as null
if ("".equals(mmDisplayType) || "2".equals(mmDisplayType))
mmDisplayType = null;
if (canSeeAll) {
try {
itemGroupString = simplePageBean.getItemGroupStringOrErr(i, null, true);
} catch (IdUnusedException e) {
itemGroupString = "";
entityDeleted = true;
}
itemGroupTitles = simplePageBean.getItemGroupTitles(itemGroupString, i);
if (entityDeleted) {
if (itemGroupTitles != null)
itemGroupTitles = itemGroupTitles + " " + messageLocator.getMessage("simplepage.deleted-entity");
else
itemGroupTitles = messageLocator.getMessage("simplepage.deleted-entity");
}
if (itemGroupTitles != null) {
itemGroupTitles = "[" + itemGroupTitles + "]";
}
UIOutput.make(tableRow, "item-groups", itemGroupString);
} else if (entityDeleted)
continue;
if (!"1".equals(mmDisplayType) && !"3".equals(mmDisplayType))
UIVerbatim.make(tableRow, "item-path", getItemPath(i));
// the reason this code is complex is that we try to choose
// the best
// HTML for displaying the particular type of object. We've
// added complexities
// over time as we get more experience with different
// object types and browsers.
StringTokenizer token = new StringTokenizer(i.getSakaiId(), ".");
String extension = "";
while (token.hasMoreTokens()) {
extension = token.nextToken().toLowerCase();
}
// the extension is almost never used. Normally we have
// the MIME type and use it. Extension is used only if
// for some reason we don't have the MIME type
UIComponent item;
String youtubeKey;
Length width = null;
if (i.getWidth() != null) {
width = new Length(i.getWidth());
}
Length height = null;
if (i.getHeight() != null) {
height = new Length(i.getHeight());
}
// Get the MIME type. For multimedia types is should be in
// the html field.
// The old code saved the URL there. So if it looks like a
// URL ignore it.
String mimeType = i.getHtml();
if (mimeType != null && (mimeType.startsWith("http") || mimeType.equals(""))) {
mimeType = null;
}
// here goes. dispatch on the type and produce the right tag
// type,
// followed by the hidden INPUT tags with information for the
// edit dialog
if (mmDisplayType == null && simplePageBean.isImageType(i)) {
if(canSeeAll || simplePageBean.isItemAvailable(i)) {
UIOutput.make(tableRow, "imageSpan");
if (itemGroupString != null) {
UIOutput.make(tableRow, "item-group-titles3", itemGroupTitles);
UIOutput.make(tableRow, "item-groups3", itemGroupString);
}
String imageName = i.getAlt();
if (imageName == null || imageName.equals("")) {
imageName = abbrevUrl(i.getURL());
}
item = UIOutput.make(tableRow, "image").decorate(new UIFreeAttributeDecorator("src", i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner()))).decorate(new UIFreeAttributeDecorator("alt", imageName));
if (lengthOk(width)) {
item.decorate(new UIFreeAttributeDecorator("width", width.getOld()));
}
if(lengthOk(height)) {
item.decorate(new UIFreeAttributeDecorator("height", height.getOld()));
}
} else {
UIComponent notAvailableText = UIOutput.make(tableRow, "notAvailableText", messageLocator.getMessage("simplepage.textItemUnavailable"));
// Grey it out
notAvailableText.decorate(new UIFreeAttributeDecorator("class", "disabled-text-item"));
}
// stuff for the jquery dialog
if (canEditPage) {
UIOutput.make(tableRow, "imageHeight", getOrig(height));
UIOutput.make(tableRow, "imageWidth", getOrig(width));
UIOutput.make(tableRow, "mimetype2", mimeType);
UIOutput.make(tableRow, "current-item-id4", Long.toString(i.getId()));
UIOutput.make(tableRow, "editmm-td");
UILink.make(tableRow, "iframe-edit", messageLocator.getMessage("simplepage.editItem"), "").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.url").replace("{}", abbrevUrl(i.getURL()))));
}
UIOutput.make(tableRow, "description2", i.getDescription());
} else if (mmDisplayType == null && (youtubeKey = simplePageBean.getYoutubeKey(i)) != null) {
String youtubeUrl = SimplePageBean.getYoutubeUrlFromKey(youtubeKey);
if(canSeeAll || simplePageBean.isItemAvailable(i)) {
UIOutput.make(tableRow, "youtubeSpan");
if (itemGroupString != null) {
UIOutput.make(tableRow, "item-group-titles4", itemGroupTitles);
UIOutput.make(tableRow, "item-groups4", itemGroupString);
}
// if width is blank or 100% scale the height
if (width != null && height != null && !height.number.equals("")) {
if (width.number.equals("") && width.unit.equals("") || width.number.equals("100") && width.unit.equals("%")) {
int h = Integer.parseInt(height.number);
if (h > 0) {
width.number = Integer.toString((int) Math.round(h * 1.641025641));
width.unit = height.unit;
}
}
}
// <object style="height: 390px; width: 640px"><param
// name="movie"
// value="http://www.youtube.com/v/AKIC7OQqBrA?version=3"><param
// name="allowFullScreen" value="true"><param
// name="allowScriptAccess" value="always"><embed
// src="http://www.youtube.com/v/AKIC7OQqBrA?version=3"
// type="application/x-shockwave-flash"
// allowfullscreen="true" allowScriptAccess="always"
// width="640" height="390"></object>
item = UIOutput.make(tableRow, "youtubeIFrame");
// youtube seems ok with length and width
if(lengthOk(height)) {
item.decorate(new UIFreeAttributeDecorator("height", height.getOld()));
}
if(lengthOk(width)) {
item.decorate(new UIFreeAttributeDecorator("width", width.getOld()));
}
item.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.youtube_player")));
item.decorate(new UIFreeAttributeDecorator("src", youtubeUrl));
} else {
UIComponent notAvailableText = UIOutput.make(tableRow, "notAvailableText", messageLocator.getMessage("simplepage.textItemUnavailable"));
// Grey it out
notAvailableText.decorate(new UIFreeAttributeDecorator("class", "disabled-text-item"));
}
if (canEditPage) {
UIOutput.make(tableRow, "youtubeId", String.valueOf(i.getId()));
UIOutput.make(tableRow, "currentYoutubeURL", youtubeUrl);
UIOutput.make(tableRow, "currentYoutubeHeight", getOrig(height));
UIOutput.make(tableRow, "currentYoutubeWidth", getOrig(width));
UIOutput.make(tableRow, "current-item-id5", Long.toString(i.getId()));
UIOutput.make(tableRow, "youtube-td");
UILink.make(tableRow, "youtube-edit", messageLocator.getMessage("simplepage.editItem"), "").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.youtube")));
}
UIOutput.make(tableRow, "description4", i.getDescription());
// as of Oct 28, 2010, we store the mime type. mimeType
// null is an old entry.
// For that use the old approach of checking the
// extension.
// Otherwise we want to use iframes for HTML and OBJECT
// for everything else
// We need the iframes because IE up through 8 doesn't
// reliably display
// HTML with OBJECT. Experiments show that everything
// else works with OBJECT
// for most browsers. Unfortunately IE, even IE 9,
// doesn't reliably call the
// right player with OBJECT. EMBED works. But it's not
// as nice because you can't
// nest error recovery code. So we use OBJECT for
// everything except IE, where we
// use EMBED. OBJECT does work with Flash.
// application/xhtml+xml is XHTML.
} else if (mmDisplayType == null &&
((mimeType != null && !mimeType.equals("text/html") && !mimeType.equals("application/xhtml+xml")) ||
// ((mimeType != null && (mimeType.startsWith("audio/") || mimeType.startsWith("video/"))) ||
(mimeType == null && !(Arrays.binarySearch(htmlTypes, extension) >= 0)))) {
// except where explicit display is set,
// this code is used for everything that isn't an image,
// Youtube, or HTML
// This could be audio, video, flash, or something random like MS word.
// Random stuff will turn into an object.
// HTML is done with an IFRAME in the next "if" case
// The explicit display types are handled there as well
// in theory the things that fall through to iframe are
// html and random stuff without a defined mime type
// random stuff with mime type is displayed with object
if (mimeType == null) {
mimeType = "";
}
String oMimeType = mimeType; // in case we change it for
// FLV or others
if (itemGroupString != null) {
UIOutput.make(tableRow, "item-group-titles5", itemGroupTitles);
UIOutput.make(tableRow, "item-groups5", itemGroupString);
}
UIOutput.make(tableRow, "movieSpan");
if(canSeeAll || simplePageBean.isItemAvailable(i)) {
UIComponent item2;
String movieUrl = i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner());
// movieUrl = "https://heidelberg.rutgers.edu" + movieUrl;
// Safari doens't always pass cookies to plugins, so we have to pass the arg
// this requires session.parameter.allow=true in sakai.properties
// don't pass the arg unless that is set, since the whole point of defaulting
// off is to not expose the session id
String sessionParameter = getSessionParameter(movieUrl);
if (sessionParameter != null)
movieUrl = movieUrl + "?lb.session=" + sessionParameter;
UIOutput.make(tableRow, "movie-link-div");
UILink.make(tableRow, "movie-link-link", messageLocator.getMessage("simplepage.download_file"), movieUrl);
// if (allowSessionId)
// movieUrl = movieUrl + "?sakai.session=" + SessionManager.getCurrentSession().getId();
boolean useFlvPlayer = false;
// isMp4 means we try the flash player (if not HTML5)
// we also try the flash player for FLV but for mp4 we do an
// additional backup if flash fails, but that doesn't make sense for FLV
boolean isMp4 = Arrays.binarySearch(mp4Types, mimeType) >= 0;
boolean isHtml5 = Arrays.binarySearch(html5Types, mimeType) >= 0;
// wrap whatever stuff we decide to put out in HTML5 if appropriate
// javascript is used to do the wrapping, because RSF can't really handle this
if (isHtml5) {
boolean isAudio = mimeType.startsWith("audio/");
UIComponent h5video = UIOutput.make(tableRow, (isAudio? "h5audio" : "h5video"));
UIComponent h5source = UIOutput.make(tableRow, (isAudio? "h5asource" : "h5source"));
if (lengthOk(height) && height.getOld().indexOf("%") < 0)
h5video.decorate(new UIFreeAttributeDecorator("height", height.getOld()));
if (lengthOk(width) && width.getOld().indexOf("%") < 0)
h5video.decorate(new UIFreeAttributeDecorator("width", width.getOld()));
h5source.decorate(new UIFreeAttributeDecorator("src", movieUrl)).
decorate(new UIFreeAttributeDecorator("type", mimeType));
}
// FLV is special. There's no player for flash video in
// the browser
// it shows with a special flash program, which I
// supply. For the moment MP4 is
// shown with the same player so it uses much of the
// same code
if (mimeType != null && (mimeType.equals("video/x-flv") || mimeType.equals("video/flv") || isMp4)) {
mimeType = "application/x-shockwave-flash";
movieUrl = "/lessonbuilder-tool/templates/StrobeMediaPlayback.swf";
useFlvPlayer = true;
}
// for IE, if we're not supplying a player it's safest
// to use embed
// otherwise Quicktime won't work. Oddly, with IE 9 only
// it works if you set CLASSID to the MIME type,
// but that's so unexpected that I hate to rely on it.
// EMBED is in HTML 5, so I think we're OK
// using it permanently for IE.
// I prefer OBJECT where possible because of the nesting
// ability.
boolean useEmbed = ieVersion > 0 && !mimeType.equals("application/x-shockwave-flash");
if (useEmbed) {
item2 = UIOutput.make(tableRow, "movieEmbed").decorate(new UIFreeAttributeDecorator("src", movieUrl)).decorate(new UIFreeAttributeDecorator("alt", messageLocator.getMessage("simplepage.mm_player").replace("{}", abbrevUrl(i.getURL()))));
} else {
item2 = UIOutput.make(tableRow, "movieObject").decorate(new UIFreeAttributeDecorator("data", movieUrl)).decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.mm_player").replace("{}", abbrevUrl(i.getURL()))));
}
if (mimeType != null) {
item2.decorate(new UIFreeAttributeDecorator("type", mimeType));
}
if (canEditPage) {
//item2.decorate(new UIFreeAttributeDecorator("style", "border: 1px solid black"));
}
// some object types seem to need a specification, so supply our default if necessary
if (lengthOk(height) && lengthOk(width)) {
item2.decorate(new UIFreeAttributeDecorator("height", height.getOld())).decorate(new UIFreeAttributeDecorator("width", width.getOld()));
} else {
if (oMimeType.startsWith("audio/"))
item2.decorate(new UIFreeAttributeDecorator("height", "100")).decorate(new UIFreeAttributeDecorator("width", "400"));
else
item2.decorate(new UIFreeAttributeDecorator("height", "300")).decorate(new UIFreeAttributeDecorator("width", "400"));
}
if (!useEmbed) {
if (useFlvPlayer) {
UIOutput.make(tableRow, "flashvars").decorate(new UIFreeAttributeDecorator("value", "src=" + URLEncoder.encode(myUrl() + i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner()))));
// need wmode=opaque for player to stack properly with dialogs, etc.
// there is a performance impact, but I'm guessing in our application we don't
// need ultimate performance for embedded video. I'm setting it only for
// the player, so flash games and other applications will still get wmode=window
UIOutput.make(tableRow, "wmode");
} else if (mimeType.equals("application/x-shockwave-flash"))
UIOutput.make(tableRow, "wmode");
UIOutput.make(tableRow, "movieURLInject").decorate(new UIFreeAttributeDecorator("value", movieUrl));
if (!isMp4) {
UIOutput.make(tableRow, "noplugin-p", messageLocator.getMessage("simplepage.noplugin"));
UIOutput.make(tableRow, "noplugin-br");
UILink.make(tableRow, "noplugin", i.getName(), movieUrl);
}
}
if (isMp4) {
// do fallback. for ie use EMBED
if (ieVersion > 0) {
item2 = UIOutput.make(tableRow, "mp4-embed").decorate(new UIFreeAttributeDecorator("src", i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner()))).decorate(new UIFreeAttributeDecorator("alt", messageLocator.getMessage("simplepage.mm_player").replace("{}", abbrevUrl(i.getURL()))));
} else {
item2 = UIOutput.make(tableRow, "mp4-object").decorate(new UIFreeAttributeDecorator("data", i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner()))).decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.mm_player").replace("{}", abbrevUrl(i.getURL()))));
}
if (oMimeType != null) {
item2.decorate(new UIFreeAttributeDecorator("type", oMimeType));
}
// some object types seem to need a specification, so give a default if needed
if (lengthOk(height) && lengthOk(width)) {
item2.decorate(new UIFreeAttributeDecorator("height", height.getOld())).decorate(new UIFreeAttributeDecorator("width", width.getOld()));
} else {
if (oMimeType.startsWith("audio/"))
item2.decorate(new UIFreeAttributeDecorator("height", "100")).decorate(new UIFreeAttributeDecorator("width", "100%"));
else
item2.decorate(new UIFreeAttributeDecorator("height", "300")).decorate(new UIFreeAttributeDecorator("width", "100%"));
}
if (!useEmbed) {
UIOutput.make(tableRow, "mp4-inject").decorate(new UIFreeAttributeDecorator("value", i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner())));
UIOutput.make(tableRow, "mp4-noplugin-p", messageLocator.getMessage("simplepage.noplugin"));
UILink.make(tableRow, "mp4-noplugin", i.getName(), i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner()));
}
}
} else {
UIVerbatim notAvailableText = UIVerbatim.make(tableRow, "notAvailableText", messageLocator.getMessage("simplepage.multimediaItemUnavailable"));
// Grey it out
notAvailableText.decorate(new UIFreeAttributeDecorator("class", "disabled-multimedia-item"));
}
if (canEditPage) {
UIOutput.make(tableRow, "movieId", String.valueOf(i.getId()));
UIOutput.make(tableRow, "movieHeight", getOrig(height));
UIOutput.make(tableRow, "movieWidth", getOrig(width));
UIOutput.make(tableRow, "mimetype5", oMimeType);
UIOutput.make(tableRow, "prerequisite", (i.isPrerequisite()) ? "true" : "false");
UIOutput.make(tableRow, "current-item-id6", Long.toString(i.getId()));
UIOutput.make(tableRow, "movie-td");
UILink.make(tableRow, "edit-movie", messageLocator.getMessage("simplepage.editItem"), "").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.url").replace("{}", abbrevUrl(i.getURL()))));
}
UIOutput.make(tableRow, "description3", i.getDescription());
} else {
// this is fallthrough for html or an explicit mm display type (i.e. embed code)
// odd types such as MS word will be handled by the AV code, and presented as <OBJECT>
// definition of resizeiframe, at top of page
if (!iframeJavascriptDone && getOrig(height).equals("auto")) {
UIOutput.make(tofill, "iframeJavascript");
iframeJavascriptDone = true;
}
UIOutput.make(tableRow, "iframeSpan");
if (itemGroupString != null) {
UIOutput.make(tableRow, "item-group-titles2", itemGroupTitles);
UIOutput.make(tableRow, "item-groups2", itemGroupString);
}
String itemUrl = i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner());
if ("1".equals(mmDisplayType)) {
// embed
item = UIVerbatim.make(tableRow, "mm-embed", i.getAttribute("multimediaEmbedCode"));
//String style = getStyle(width, height);
//if (style != null)
//item.decorate(new UIFreeAttributeDecorator("style", style));
} else if ("3".equals(mmDisplayType)) {
item = UILink.make(tableRow, "mm-oembed", i.getAttribute("multimediaUrl"), i.getAttribute("multimediaUrl"));
if (lengthOk(width))
item.decorate(new UIFreeAttributeDecorator("maxWidth", width.getOld()));
if (lengthOk(height))
item.decorate(new UIFreeAttributeDecorator("maxHeight", height.getOld()));
// oembed
} else {
UIOutput.make(tableRow, "iframe-link-div");
UILink.make(tableRow, "iframe-link-link", messageLocator.getMessage("simplepage.open_new_window"), itemUrl);
item = UIOutput.make(tableRow, "iframe").decorate(new UIFreeAttributeDecorator("src", itemUrl));
// if user specifies auto, use Javascript to resize the
// iframe when the
// content changes. This only works for URLs with the
// same origin, i.e.
// URLs in this sakai system
if (getOrig(height).equals("auto")) {
item.decorate(new UIFreeAttributeDecorator("onload", "resizeiframe('" + item.getFullID() + "')"));
if (lengthOk(width)) {
item.decorate(new UIFreeAttributeDecorator("width", width.getOld()));
}
item.decorate(new UIFreeAttributeDecorator("height", "300"));
} else {
// we seem OK without a spec
if (lengthOk(height) && lengthOk(width)) {
item.decorate(new UIFreeAttributeDecorator("height", height.getOld())).decorate(new UIFreeAttributeDecorator("width", width.getOld()));
}
}
}
item.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.web_content").replace("{}", abbrevUrl(i.getURL()))));
if (canEditPage) {
UIOutput.make(tableRow, "iframeHeight", getOrig(height));
UIOutput.make(tableRow, "iframeWidth", getOrig(width));
UIOutput.make(tableRow, "mimetype3", mimeType);
UIOutput.make(tableRow, "current-item-id3", Long.toString(i.getId()));
UIOutput.make(tableRow, "editmm-td");
UILink.make(tableRow, "iframe-edit", messageLocator.getMessage("simplepage.editItem"), "").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.url").replace("{}", abbrevUrl(i.getURL()))));
}
UIOutput.make(tableRow, "description5", i.getDescription());
}
// end of multimedia object
} else if (i.getType() == SimplePageItem.COMMENTS) {
// Load later using AJAX and CommentsProducer
UIOutput.make(tableRow, "commentsSpan");
boolean isAvailable = simplePageBean.isItemAvailable(i);
// faculty missing preqs get warning but still see the comments
if (!isAvailable && canSeeAll)
UIOutput.make(tableRow, "missing-prereqs", messageLocator.getMessage("simplepage.fake-missing-prereqs"));
// students get warning and not the content
if (!isAvailable && !canSeeAll) {
UIOutput.make(tableRow, "missing-prereqs", messageLocator.getMessage("simplepage.missing-prereqs"));
}else {
UIOutput.make(tableRow, "commentsDiv");
Placement placement = toolManager.getCurrentPlacement();
UIOutput.make(tableRow, "placementId", placement.getId());
// note: the URL will be rewritten in comments.js to look like
// /lessonbuilder-tool/faces/Comments...
CommentsViewParameters eParams = new CommentsViewParameters(CommentsProducer.VIEW_ID);
eParams.itemId = i.getId();
eParams.placementId = placement.getId();
if (params.postedComment) {
eParams.postedComment = postedCommentId;
}
eParams.siteId = simplePageBean.getCurrentSiteId();
eParams.pageId = currentPage.getPageId();
if(params.author != null && !params.author.equals("")) {
eParams.author = params.author;
eParams.showAllComments = true;
}
UIInternalLink.make(tableRow, "commentsLink", eParams);
if (!addedCommentsScript) {
UIOutput.make(tofill, "comments-script");
UIOutput.make(tofill, "fckScript");
addedCommentsScript = true;
UIOutput.make(tofill, "delete-dialog");
}
// forced comments have to be edited on the main page
if (canEditPage) {
// Checks to make sure that the comments item isn't on a student page.
// That it is graded. And that we didn't just come from the grading pane.
if(i.getPageId() > 0 && i.getGradebookId() != null && !cameFromGradingPane) {
CommentsGradingPaneViewParameters gp = new CommentsGradingPaneViewParameters(CommentGradingPaneProducer.VIEW_ID);
gp.placementId = toolManager.getCurrentPlacement().getId();
gp.commentsItemId = i.getId();
gp.pageId = currentPage.getPageId();
gp.pageItemId = pageItem.getId();
gp.siteId = simplePageBean.getCurrentSiteId();
UIInternalLink.make(tableRow, "gradingPaneLink", messageLocator.getMessage("simplepage.show-grading-pane-comments"), gp)
.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.show-grading-pane-comments")));
}
UIOutput.make(tableRow, "comments-td");
if (i.getSequence() > 0) {
UILink.make(tableRow, "edit-comments", messageLocator.getMessage("simplepage.editItem"), "")
.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.comments")));
UIOutput.make(tableRow, "commentsId", String.valueOf(i.getId()));
UIOutput.make(tableRow, "commentsAnon", String.valueOf(i.isAnonymous()));
UIOutput.make(tableRow, "commentsitem-required", String.valueOf(i.isRequired()));
UIOutput.make(tableRow, "commentsitem-prerequisite", String.valueOf(i.isPrerequisite()));
UIOutput.make(tableRow, "commentsGrade", String.valueOf(i.getGradebookId() != null));
UIOutput.make(tableRow, "commentsMaxPoints", String.valueOf(i.getGradebookPoints()));
String itemGroupString = simplePageBean.getItemGroupString(i, null, true);
if (itemGroupString != null) {
String itemGroupTitles = simplePageBean.getItemGroupTitles(itemGroupString, i);
if (itemGroupTitles != null) {
itemGroupTitles = "[" + itemGroupTitles + "]";
}
UIOutput.make(tableRow, "comments-groups", itemGroupString);
UIOutput.make(tableRow, "item-group-titles6", itemGroupTitles);
}
}
// Allows AJAX posting of comment grades
printGradingForm(tofill);
}
UIForm form = UIForm.make(tableRow, "comment-form");
UIInput.make(form, "comment-item-id", "#{simplePageBean.itemId}", String.valueOf(i.getId()));
UIInput.make(form, "comment-edit-id", "#{simplePageBean.editId}");
// usage * image is required and not done
if (i.isRequired() && !simplePageBean.isItemComplete(i))
UIOutput.make(tableRow, "comment-required-image");
UIOutput.make(tableRow, "add-comment-link");
UIOutput.make(tableRow, "add-comment-text", messageLocator.getMessage("simplepage.add-comment"));
UIInput fckInput = UIInput.make(form, "comment-text-area-evolved:", "#{simplePageBean.formattedComment}");
fckInput.decorate(new UIFreeAttributeDecorator("height", "175"));
fckInput.decorate(new UIFreeAttributeDecorator("width", "800"));
fckInput.decorate(new UIStyleDecorator("evolved-box"));
fckInput.decorate(new UIFreeAttributeDecorator("aria-label", messageLocator.getMessage("simplepage.editor")));
fckInput.decorate(new UIFreeAttributeDecorator("role", "dialog"));
if (!noEditor) {
fckInput.decorate(new UIStyleDecorator("using-editor")); // javascript needs to know
((SakaiFCKTextEvolver) richTextEvolver).evolveTextInput(fckInput, "" + commentsCount);
}
UICommand.make(form, "add-comment", "#{simplePageBean.addComment}");
}
}else if (i.getType() == SimplePageItem.PEEREVAL){
String owner=currentPage.getOwner();
String currentUser=UserDirectoryService.getCurrentUser().getId();
Long pageId=currentPage.getPageId();
UIOutput.make(tableRow, "peerReviewRubricStudent");
UIOutput.make(tableRow, "peer-review-form");
makePeerRubric(tableRow,i, makeStudentRubric);
boolean isOpen = false;
boolean isPastDue = false;
String peerEvalDateOpenStr = i.getAttribute("rubricOpenDate");
String peerEvalDateDueStr = i.getAttribute("rubricDueDate");
boolean peerEvalAllowSelfGrade = Boolean.parseBoolean(i.getAttribute("rubricAllowSelfGrade"));
boolean gradingSelf = owner.equals(currentUser) && peerEvalAllowSelfGrade;
if (peerEvalDateOpenStr != null && peerEvalDateDueStr != null) {
Date peerEvalNow = new Date();
Date peerEvalOpen = new Date(Long.valueOf(peerEvalDateOpenStr));
Date peerEvalDue = new Date(Long.valueOf(peerEvalDateDueStr));
isOpen = peerEvalNow.after(peerEvalOpen);
isPastDue = peerEvalNow.after(peerEvalDue);
}
if(isOpen){
if(owner.equals(currentUser)){ //owner gets their own data
class PeerEvaluation{
String category;
public int grade, count;
public PeerEvaluation(String category, int grade){this.category=category;this.grade=grade;count=1;}
public void increment(){count++;}
public boolean equals(Object o){
if ( !(o instanceof PeerEvaluation) ) return false;
PeerEvaluation pe = (PeerEvaluation)o;
return category.equals(pe.category) && grade==pe.grade;
}
public String toString(){return category + " " + grade + " [" + count + "]";}
}
ArrayList<PeerEvaluation> myEvaluations = new ArrayList<PeerEvaluation>();
List<SimplePagePeerEvalResult> evaluations = simplePageToolDao.findPeerEvalResultByOwner(pageId.longValue(), owner);
if(evaluations!=null)
for(SimplePagePeerEvalResult eval : evaluations){
PeerEvaluation target=new PeerEvaluation(eval.getRowText(), eval.getColumnValue());
int targetIndex=myEvaluations.indexOf(target);
if(targetIndex!=-1){
myEvaluations.get(targetIndex).increment();
}
else
myEvaluations.add(target);
}
UIOutput.make(tableRow, "my-existing-peer-eval-data");
for(PeerEvaluation eval: myEvaluations){
UIBranchContainer evalData = UIBranchContainer.make(tableRow, "my-peer-eval-data:");
UIOutput.make(evalData, "peer-eval-row-text", eval.category);
UIOutput.make(evalData, "peer-eval-grade", String.valueOf(eval.grade));
UIOutput.make(evalData, "peer-eval-count", String.valueOf(eval.count));
}
}
if(!owner.equals(currentUser) || gradingSelf){
List<SimplePagePeerEvalResult> evaluations = simplePageToolDao.findPeerEvalResult(pageId, currentUser, owner);
//existing evaluation data
if(evaluations!=null && evaluations.size()!=0){
UIOutput.make(tableRow, "existing-peer-eval-data");
for(SimplePagePeerEvalResult eval : evaluations){
UIBranchContainer evalData = UIBranchContainer.make(tableRow, "peer-eval-data:");
UIOutput.make(evalData, "peer-eval-row-text", eval.getRowText());
UIOutput.make(evalData, "peer-eval-grade", String.valueOf(eval.getColumnValue()));
}
}
//form for peer evaluation results
UIForm form = UIForm.make(tofill, "rubricSelection");
UIInput.make(form, "rubricPeerGrade", "#{simplePageBean.rubricPeerGrade}");
UICommand.make(form, "update-peer-eval-grade", messageLocator.getMessage("simplepage.edit"), "#{simplePageBean.savePeerEvalResult}");
}
//buttons
UIOutput.make(tableRow, "add-peereval-link");
UIOutput.make(tableRow, "add-peereval-text", messageLocator.getMessage("simplepage.view-peereval"));
if(isPastDue){
UIOutput.make(tableRow, "peer-eval-grade-directions", messageLocator.getMessage("simplepage.peer-eval.past-due-date"));
}else if(!owner.equals(currentUser) || gradingSelf){
UIOutput.make(tableRow, "save-peereval-link");
UIOutput.make(tableRow, "save-peereval-text", messageLocator.getMessage("simplepage.save"));
UIOutput.make(tableRow, "cancel-peereval-link");
UIOutput.make(tableRow, "cancel-peereval-text", messageLocator.getMessage("simplepage.cancel"));
UIOutput.make(tableRow, "peer-eval-grade-directions", messageLocator.getMessage("simplepage.peer-eval.click-on-cell"));
}else{ //owner who cannot grade himself
UIOutput.make(tableRow, "peer-eval-grade-directions", messageLocator.getMessage("simplepage.peer-eval.cant-eval-yourself"));
}
if(canEditPage)
UIOutput.make(tableRow, "peerReviewRubricStudent-edit");//lines up rubric with edit btn column for users with editing privs
}
}else if(i.getType() == SimplePageItem.STUDENT_CONTENT) {
UIOutput.make(tableRow, "studentSpan");
boolean isAvailable = simplePageBean.isItemAvailable(i);
// faculty missing preqs get warning but still see the comments
if (!isAvailable && canSeeAll)
UIOutput.make(tableRow, "student-missing-prereqs", messageLocator.getMessage("simplepage.student-fake-missing-prereqs"));
if (!isAvailable && !canSeeAll)
UIOutput.make(tableRow, "student-missing-prereqs", messageLocator.getMessage("simplepage.student-missing-prereqs"));
else {
UIOutput.make(tableRow, "studentDiv");
HashMap<Long, SimplePageLogEntry> cache = simplePageBean.cacheStudentPageLogEntries(i.getId());
List<SimpleStudentPage> studentPages = simplePageToolDao.findStudentPages(i.getId());
boolean hasOwnPage = false;
String userId = UserDirectoryService.getCurrentUser().getId();
Collections.sort(studentPages, new Comparator<SimpleStudentPage>() {
public int compare(SimpleStudentPage o1, SimpleStudentPage o2) {
String title1 = o1.getTitle();
if (title1 == null)
title1 = "";
String title2 = o2.getTitle();
if (title2 == null)
title2 = "";
return title1.compareTo(title2);
}
});
UIOutput contentList = UIOutput.make(tableRow, "studentContentTable");
UIOutput contentTitle = UIOutput.make(tableRow, "studentContentTitle", messageLocator.getMessage("simplepage.student"));
contentList.decorate(new UIFreeAttributeDecorator("aria-labelledby", contentTitle.getFullID()));
// Print each row in the table
for(SimpleStudentPage page : studentPages) {
if(page.isDeleted()) continue;
SimplePageLogEntry entry = cache.get(page.getPageId());
UIBranchContainer row = UIBranchContainer.make(tableRow, "studentRow:");
// There's content they haven't seen
if(entry == null || entry.getLastViewed().compareTo(page.getLastUpdated()) < 0) {
UIOutput.make(row, "newContentImg").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.new-student-content")));
} else
UIOutput.make(row, "newContentImgT");
// The comments tool exists, so we might have to show the icon
if(i.getShowComments() != null && i.getShowComments()) {
// New comments have been added since they last viewed the page
if(page.getLastCommentChange() != null && (entry == null || entry.getLastViewed().compareTo(page.getLastCommentChange()) < 0)) {
UIOutput.make(row, "newCommentsImg").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.new-student-comments")));
} else
UIOutput.make(row, "newCommentsImgT");
}
// Never visited page
if(entry == null) {
UIOutput.make(row, "newPageImg").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.new-student-page")));
} else
UIOutput.make(row, "newPageImgT");
GeneralViewParameters eParams = new GeneralViewParameters(ShowPageProducer.VIEW_ID, page.getPageId());
eParams.setItemId(i.getId());
eParams.setPath("push");
String studentTitle = page.getTitle();
String sownerName = null;
try {
if(!i.isAnonymous() || canEditPage) {
if (page.getGroup() != null)
sownerName = simplePageBean.getCurrentSite().getGroup(page.getGroup()).getTitle();
else
sownerName = UserDirectoryService.getUser(page.getOwner()).getDisplayName();
if (sownerName != null && sownerName.equals(studentTitle))
studentTitle = "(" + sownerName + ")";
else
studentTitle += " (" + sownerName + ")";
}else if (simplePageBean.isPageOwner(page)) {
studentTitle += " (" + messageLocator.getMessage("simplepage.comment-you") + ")";
}
} catch (UserNotDefinedException e) {
}
UIInternalLink.make(row, "studentLink", studentTitle, eParams);
if(simplePageBean.isPageOwner(page)) {
hasOwnPage = true;
}
if(i.getGradebookId() != null && simplePageBean.getEditPrivs() == 0) {
UIOutput.make(row, "studentGradingCell", String.valueOf((page.getPoints() != null? page.getPoints() : "")));
}
}
if(!hasOwnPage) {
UIBranchContainer row = UIBranchContainer.make(tableRow, "studentRow:");
UIOutput.make(row, "linkRow");
UIOutput.make(row, "linkCell");
if (i.isRequired() && !simplePageBean.isItemComplete(i))
UIOutput.make(row, "student-required-image");
GeneralViewParameters eParams = new GeneralViewParameters(ShowPageProducer.VIEW_ID);
eParams.addTool = GeneralViewParameters.STUDENT_PAGE;
eParams.studentItemId = i.getId();
UIInternalLink.make(row, "linkLink", messageLocator.getMessage("simplepage.add-page"), eParams);
}
if(canEditPage) {
// Checks to make sure that the comments are graded and that we didn't
// just come from a grading pane (would be confusing)
if(i.getAltGradebook() != null && !cameFromGradingPane) {
CommentsGradingPaneViewParameters gp = new CommentsGradingPaneViewParameters(CommentGradingPaneProducer.VIEW_ID);
gp.placementId = toolManager.getCurrentPlacement().getId();
gp.commentsItemId = i.getId();
gp.pageId = currentPage.getPageId();
gp.pageItemId = pageItem.getId();
gp.studentContentItem = true;
UIInternalLink.make(tableRow, "studentGradingPaneLink", messageLocator.getMessage("simplepage.show-grading-pane-content"), gp)
.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.show-grading-pane-content")));
}
UIOutput.make(tableRow, "student-td");
UILink.make(tableRow, "edit-student", messageLocator.getMessage("simplepage.editItem"), "")
.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.student")));
UIOutput.make(tableRow, "studentId", String.valueOf(i.getId()));
UIOutput.make(tableRow, "studentAnon", String.valueOf(i.isAnonymous()));
UIOutput.make(tableRow, "studentComments", String.valueOf(i.getShowComments()));
UIOutput.make(tableRow, "forcedAnon", String.valueOf(i.getForcedCommentsAnonymous()));
UIOutput.make(tableRow, "studentGrade", String.valueOf(i.getGradebookId() != null));
UIOutput.make(tableRow, "studentMaxPoints", String.valueOf(i.getGradebookPoints()));
UIOutput.make(tableRow, "studentGrade2", String.valueOf(i.getAltGradebook() != null));
UIOutput.make(tableRow, "studentMaxPoints2", String.valueOf(i.getAltPoints()));
UIOutput.make(tableRow, "studentitem-required", String.valueOf(i.isRequired()));
UIOutput.make(tableRow, "studentitem-prerequisite", String.valueOf(i.isPrerequisite()));
UIOutput.make(tableRow, "peer-eval", String.valueOf(i.getShowPeerEval()));
makePeerRubric(tableRow,i, makeMaintainRubric);
makeSamplePeerEval(tableRow);
String peerEvalDate = i.getAttribute("rubricOpenDate");
String peerDueDate = i.getAttribute("rubricDueDate");
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat stf = new SimpleDateFormat("hh:mm a");
Calendar peerevalcal = Calendar.getInstance();
if (peerEvalDate != null && peerDueDate != null) {
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, M_locale);
//Open date from attribute string
peerevalcal.setTimeInMillis(Long.valueOf(peerEvalDate));
String dateStr = sdf.format(peerevalcal.getTime());
String timeStr = stf.format(peerevalcal.getTime());
UIOutput.make(tableRow, "peer-eval-open-date", dateStr);
UIOutput.make(tableRow, "peer-eval-open-time", timeStr);
//Due date from attribute string
peerevalcal.setTimeInMillis(Long.valueOf(peerDueDate));
dateStr = sdf.format(peerevalcal.getTime());
timeStr = stf.format(peerevalcal.getTime());
UIOutput.make(tableRow, "peer-eval-due-date", dateStr);
UIOutput.make(tableRow, "peer-eval-due-time", timeStr);
UIOutput.make(tableRow, "peer-eval-allow-self", i.getAttribute("rubricAllowSelfGrade"));
}else{
//Default open and due date
Date now = new Date();
peerevalcal.setTime(now);
//Default open date: now
String dateStr = sdf.format(peerevalcal.getTime());
String timeStr = stf.format(peerevalcal.getTime());
UIOutput.make(tableRow, "peer-eval-open-date", dateStr);
UIOutput.make(tableRow, "peer-eval-open-time", timeStr);
//Default due date: 7 days from now
Date later = new Date(peerevalcal.getTimeInMillis() + 604800000);
peerevalcal.setTime(later);
dateStr = sdf.format(peerevalcal.getTime());
timeStr = stf.format(peerevalcal.getTime());
//System.out.println("Setting date to " + dateStr + " and time to " + timeStr);
UIOutput.make(tableRow, "peer-eval-due-date", dateStr);
UIOutput.make(tableRow, "peer-eval-due-time", timeStr);
UIOutput.make(tableRow, "peer-eval-allow-self", i.getAttribute("rubricAllowSelfGrade"));
}
//Peer Eval Stats link
GeneralViewParameters view = new GeneralViewParameters(PeerEvalStatsProducer.VIEW_ID);
view.setSendingPage(currentPage.getPageId());
view.setItemId(i.getId());
if(i.getShowPeerEval()){
UILink link = UIInternalLink.make(tableRow, "peer-eval-stats-link", view);
}
String itemGroupString = simplePageBean.getItemGroupString(i, null, true);
if (itemGroupString != null) {
String itemGroupTitles = simplePageBean.getItemGroupTitles(itemGroupString, i);
if (itemGroupTitles != null) {
itemGroupTitles = "[" + itemGroupTitles + "]";
}
UIOutput.make(tableRow, "student-groups", itemGroupString);
UIOutput.make(tableRow, "item-group-titles7", itemGroupTitles);
}
UIOutput.make(tableRow, "student-owner-groups", simplePageBean.getItemOwnerGroupString(i));
UIOutput.make(tableRow, "student-group-owned", (i.isGroupOwned()?"true":"false"));
}
}
}else if(i.getType() == SimplePageItem.QUESTION) {
SimplePageQuestionResponse response = simplePageToolDao.findQuestionResponse(i.getId(), simplePageBean.getCurrentUserId());
UIOutput.make(tableRow, "questionSpan");
boolean isAvailable = simplePageBean.isItemAvailable(i) || canSeeAll;
UIOutput.make(tableRow, "questionDiv");
UIOutput.make(tableRow, "questionText", i.getAttribute("questionText"));
List<SimplePageQuestionAnswer> answers = new ArrayList<SimplePageQuestionAnswer>();
if("multipleChoice".equals(i.getAttribute("questionType"))) {
answers = simplePageToolDao.findAnswerChoices(i);
UIOutput.make(tableRow, "multipleChoiceDiv");
UIForm questionForm = UIForm.make(tableRow, "multipleChoiceForm");
UIInput.make(questionForm, "multipleChoiceId", "#{simplePageBean.questionId}", String.valueOf(i.getId()));
String[] options = new String[answers.size()];
String initValue = null;
for(int j = 0; j < answers.size(); j++) {
options[j] = String.valueOf(answers.get(j).getId());
if(response != null && answers.get(j).getId() == response.getMultipleChoiceId()) {
initValue = String.valueOf(answers.get(j).getId());
}
}
UISelect multipleChoiceSelect = UISelect.make(questionForm, "multipleChoiceSelect:", options, "#{simplePageBean.questionResponse}", initValue);
if(!isAvailable || response != null) {
multipleChoiceSelect.decorate(new UIDisabledDecorator());
}
for(int j = 0; j < answers.size(); j++) {
UIBranchContainer answerContainer = UIBranchContainer.make(questionForm, "multipleChoiceAnswer:", String.valueOf(j));
UISelectChoice multipleChoiceInput = UISelectChoice.make(answerContainer, "multipleChoiceAnswerRadio", multipleChoiceSelect.getFullID(), j);
multipleChoiceInput.decorate(new UIFreeAttributeDecorator("id", multipleChoiceInput.getFullID()));
UIOutput.make(answerContainer, "multipleChoiceAnswerText", answers.get(j).getText())
.decorate(new UIFreeAttributeDecorator("for", multipleChoiceInput.getFullID()));
if(!isAvailable || response != null) {
multipleChoiceInput.decorate(new UIDisabledDecorator());
}
}
UICommand answerButton = UICommand.make(questionForm, "answerMultipleChoice", messageLocator.getMessage("simplepage.answer_question"), "#{simplePageBean.answerMultipleChoiceQuestion}");
if(!isAvailable || response != null) {
answerButton.decorate(new UIDisabledDecorator());
}
}else if("shortanswer".equals(i.getAttribute("questionType"))) {
UIOutput.make(tableRow, "shortanswerDiv");
UIForm questionForm = UIForm.make(tableRow, "shortanswerForm");
UIInput.make(questionForm, "shortanswerId", "#{simplePageBean.questionId}", String.valueOf(i.getId()));
UIInput shortanswerInput = UIInput.make(questionForm, "shortanswerInput", "#{simplePageBean.questionResponse}");
if(!isAvailable || response != null) {
shortanswerInput.decorate(new UIDisabledDecorator());
if(response.getShortanswer() != null) {
shortanswerInput.setValue(response.getShortanswer());
}
}
UICommand answerButton = UICommand.make(questionForm, "answerShortanswer", messageLocator.getMessage("simplepage.answer_question"), "#{simplePageBean.answerShortanswerQuestion}");
if(!isAvailable || response != null) {
answerButton.decorate(new UIDisabledDecorator());
}
}
Status questionStatus = getQuestionStatus(i, response);
addStatusImage(questionStatus, tableRow, "questionStatus", null);
String statusNote = getStatusNote(questionStatus);
if (statusNote != null) // accessibility version of icon
UIOutput.make(tableRow, "questionNote", statusNote);
String statusText = null;
if(questionStatus == Status.COMPLETED)
statusText = i.getAttribute("questionCorrectText");
else if(questionStatus == Status.FAILED)
statusText = i.getAttribute("questionIncorrectText");
if (statusText != null && !"".equals(statusText.trim()))
UIOutput.make(tableRow, "questionStatusText", statusText);
// Output the poll data
if("multipleChoice".equals(i.getAttribute("questionType")) &&
(canEditPage || ("true".equals(i.getAttribute("questionShowPoll")) &&
(questionStatus == Status.COMPLETED || questionStatus == Status.FAILED)))) {
UIOutput.make(tableRow, "showPollGraph", messageLocator.getMessage("simplepage.show-poll"));
UIOutput questionGraph = UIOutput.make(tableRow, "questionPollGraph");
questionGraph.decorate(new UIFreeAttributeDecorator("id", "poll" + i.getId()));
List<SimplePageQuestionResponseTotals> totals = simplePageToolDao.findQRTotals(i.getId());
HashMap<Long, Long> responseCounts = new HashMap<Long, Long>();
// in theory we don't need the first loop, as there should be a total
// entry for all possible answers. But in case things are out of sync ...
for(SimplePageQuestionAnswer answer : answers)
responseCounts.put(answer.getId(), 0L);
for(SimplePageQuestionResponseTotals total : totals)
responseCounts.put(total.getResponseId(), total.getCount());
for(int j = 0; j < answers.size(); j++) {
UIBranchContainer pollContainer = UIBranchContainer.make(tableRow, "questionPollData:", String.valueOf(j));
UIOutput.make(pollContainer, "questionPollText", answers.get(j).getText());
UIOutput.make(pollContainer, "questionPollNumber", String.valueOf(responseCounts.get(answers.get(j).getId())));
}
}
if(canEditPage) {
UIOutput.make(tableRow, "question-td");
// always show grading panel. Currently this is the only way to get feedback
if( !cameFromGradingPane) {
QuestionGradingPaneViewParameters gp = new QuestionGradingPaneViewParameters(QuestionGradingPaneProducer.VIEW_ID);
gp.placementId = toolManager.getCurrentPlacement().getId();
gp.questionItemId = i.getId();
gp.pageId = currentPage.getPageId();
gp.pageItemId = pageItem.getId();
UIInternalLink.make(tableRow, "questionGradingPaneLink", messageLocator.getMessage("simplepage.show-grading-pane"), gp)
.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.show-grading-pane")));
}
UILink.make(tableRow, "edit-question", messageLocator.getMessage("simplepage.editItem"), "")
.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.question")));
UIOutput.make(tableRow, "questionId", String.valueOf(i.getId()));
boolean graded = "true".equals(i.getAttribute("questionGraded")) || i.getGradebookId() != null;
UIOutput.make(tableRow, "questionGrade", String.valueOf(graded));
UIOutput.make(tableRow, "questionMaxPoints", String.valueOf(i.getGradebookPoints()));
UIOutput.make(tableRow, "questionGradebookTitle", String.valueOf(i.getGradebookTitle()));
UIOutput.make(tableRow, "questionitem-required", String.valueOf(i.isRequired()));
UIOutput.make(tableRow, "questionitem-prerequisite", String.valueOf(i.isPrerequisite()));
UIOutput.make(tableRow, "questionCorrectText", String.valueOf(i.getAttribute("questionCorrectText")));
UIOutput.make(tableRow, "questionIncorrectText", String.valueOf(i.getAttribute("questionIncorrectText")));
if("shortanswer".equals(i.getAttribute("questionType"))) {
UIOutput.make(tableRow, "questionType", "shortanswer");
UIOutput.make(tableRow, "questionAnswer", i.getAttribute("questionAnswer"));
}else {
UIOutput.make(tableRow, "questionType", "multipleChoice");
for(int j = 0; j < answers.size(); j++) {
UIBranchContainer answerContainer = UIBranchContainer.make(tableRow, "questionMultipleChoiceAnswer:", String.valueOf(j));
UIOutput.make(answerContainer, "questionMultipleChoiceAnswerId", String.valueOf(answers.get(j).getId()));
UIOutput.make(answerContainer, "questionMultipleChoiceAnswerText", answers.get(j).getText());
UIOutput.make(answerContainer, "questionMultipleChoiceAnswerCorrect", String.valueOf(answers.get(j).isCorrect()));
}
UIOutput.make(tableRow, "questionShowPoll", String.valueOf(i.getAttribute("questionShowPoll")));
}
}
} else {
// remaining type must be a block of HTML
UIOutput.make(tableRow, "itemSpan");
if (canSeeAll) {
String itemGroupString = simplePageBean.getItemGroupString(i, null, true);
String itemGroupTitles = simplePageBean.getItemGroupTitles(itemGroupString, i);
if (itemGroupTitles != null) {
itemGroupTitles = "[" + itemGroupTitles + "]";
}
UIOutput.make(tableRow, "item-groups-titles-text", itemGroupTitles);
}
if(canSeeAll || simplePageBean.isItemAvailable(i)) {
UIVerbatim.make(tableRow, "content", (i.getHtml() == null ? "" : i.getHtml()));
} else {
UIComponent unavailableText = UIOutput.make(tableRow, "content", messageLocator.getMessage("simplepage.textItemUnavailable"));
unavailableText.decorate(new UIFreeAttributeDecorator("class", "disabled-text-item"));
}
// editing is done using a special producer that calls FCK.
if (canEditPage) {
GeneralViewParameters eParams = new GeneralViewParameters();
eParams.setSendingPage(currentPage.getPageId());
eParams.setItemId(i.getId());
eParams.viewID = EditPageProducer.VIEW_ID;
UIOutput.make(tableRow, "edittext-td");
UIInternalLink.make(tableRow, "edit-link", messageLocator.getMessage("simplepage.editItem"), eParams).decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.textbox").replace("{}", Integer.toString(textboxcount))));
textboxcount++;
}
}
}
// end of items. This is the end for normal users. Following is
// special
// checks and putting out the dialogs for the popups, for
// instructors.
boolean showBreak = false;
// I believe refresh is now done automatically in all cases
// if (showRefresh) {
// UIOutput.make(tofill, "refreshAlert");
//
// // Should simply refresh
// GeneralViewParameters p = new GeneralViewParameters(VIEW_ID);
// p.setSendingPage(currentPage.getPageId());
// UIInternalLink.make(tofill, "refreshLink", p);
// showBreak = true;
// }
// stuff goes on the page in the order in the HTML file. So the fact
// that it's here doesn't mean it shows
// up at the end. This code produces errors and other odd stuff.
if (canSeeAll) {
// if the page is hidden, warn the faculty [students get stopped
// at
// the top]
if (currentPage.isHidden()) {
UIOutput.make(tofill, "hiddenAlert").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.pagehidden")));
UIVerbatim.make(tofill, "hidden-text", messageLocator.getMessage("simplepage.pagehidden.text"));
showBreak = true;
// similarly warn them if it isn't released yet
} else if (currentPage.getReleaseDate() != null && currentPage.getReleaseDate().after(new Date())) {
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, M_locale);
TimeZone tz = timeService.getLocalTimeZone();
df.setTimeZone(tz);
String releaseDate = df.format(currentPage.getReleaseDate());
UIOutput.make(tofill, "hiddenAlert").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.notreleased")));
UIVerbatim.make(tofill, "hidden-text", messageLocator.getMessage("simplepage.notreleased.text").replace("{}", releaseDate));
showBreak = true;
}
}
if (showBreak) {
UIOutput.make(tofill, "breakAfterWarnings");
}
}
// more warnings: if no item on the page, give faculty instructions,
// students an error
if (!anyItemVisible) {
if (canEditPage) {
UIOutput.make(tofill, "startupHelp")
.decorate(new UIFreeAttributeDecorator("src",
getLocalizedURL((currentPage.getOwner() != null) ? "student.html" : "general.html")))
.decorate(new UIFreeAttributeDecorator("id", "iframe"));
if (!iframeJavascriptDone) {
UIOutput.make(tofill, "iframeJavascript");
iframeJavascriptDone = true;
}
} else {
UIOutput.make(tofill, "error-div");
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.noitems_error_user"));
}
}
// now output the dialogs. but only for faculty (to avoid making the
// file bigger)
if (canEditPage) {
createSubpageDialog(tofill, currentPage);
}
createDialogs(tofill, currentPage, pageItem);
}
public void createDialogs(UIContainer tofill, SimplePage currentPage, SimplePageItem pageItem) {
createEditItemDialog(tofill, currentPage, pageItem);
createAddMultimediaDialog(tofill, currentPage);
createEditMultimediaDialog(tofill, currentPage);
createEditTitleDialog(tofill, currentPage, pageItem);
createNewPageDialog(tofill, currentPage, pageItem);
createRemovePageDialog(tofill, currentPage, pageItem);
createImportCcDialog(tofill);
createExportCcDialog(tofill);
createYoutubeDialog(tofill, currentPage);
createMovieDialog(tofill, currentPage);
createCommentsDialog(tofill);
createStudentContentDialog(tofill, currentPage);
createQuestionDialog(tofill, currentPage);
}
// get encrypted version of session id. This is our equivalent of session.id, except that we
// encrypt it so it can't be used for anything else in case someone captures it.
// we can't use time to avoid replay, as some time can go by between display of the page and
// when the user clicks. The only thing this can be used for is reading multimedia files. I
// think we're willing to risk that. I used to use session.id, but by default that's now off,
// and turning it on to use it here would expose us to more serious risks. Cache the encryption.
// we could include the whole URL in the encryption if it was worth the additional over head.
// I think it's not.
// url is /access/lessonbuilder/item/NNN/url. Because the server side
// sees a reference starting with /item, we send that.
public String getSessionParameter(String url) {
UsageSession session = UsageSessionService.getSession();
if (!url.startsWith("/access/lessonbuilder"))
return null;
url = url.substring("/access/lessonbuilder".length());
try {
Cipher sessionCipher = Cipher.getInstance("Blowfish");
sessionCipher.init(Cipher.ENCRYPT_MODE, lessonBuilderAccessService.getSessionKey());
String sessionParam = session.getId() + ":" + url;
byte[] sessionBytes = sessionParam.getBytes("UTF8");
sessionBytes = sessionCipher.doFinal(sessionBytes);
sessionParam = DatatypeConverter.printHexBinary(sessionBytes);
return sessionParam;
} catch (Exception e) {
System.out.println("unable to generate encrypted session id " + e);
return null;
}
}
public void setSimplePageBean(SimplePageBean simplePageBean) {
this.simplePageBean = simplePageBean;
}
public void setHttpServletRequest(HttpServletRequest httpServletRequest) {
this.httpServletRequest = httpServletRequest;
}
public void setHttpServletResponse(HttpServletResponse httpServletResponse) {
this.httpServletResponse = httpServletResponse;
}
private boolean makeLink(UIContainer container, String ID, SimplePageItem i, boolean canEditPage, SimplePage currentPage, boolean notDone, Status status) {
return makeLink(container, ID, i, simplePageBean, simplePageToolDao, messageLocator, canEditPage, currentPage, notDone, status);
}
/**
*
* @param container
* @param ID
* @param i
* @param simplePageBean
* @param simplePageToolDao
* @return Whether or not this item is available.
*/
protected static boolean makeLink(UIContainer container, String ID, SimplePageItem i, SimplePageBean simplePageBean, SimplePageToolDao simplePageToolDao, MessageLocator messageLocator,
boolean canEditPage, SimplePage currentPage, boolean notDone, Status status) {
String URL = "";
boolean available = simplePageBean.isItemAvailable(i);
boolean fake = !available; // by default, fake output if not available
String itemString = Long.toString(i.getId());
if (i.getSakaiId().equals(SimplePageItem.DUMMY)) {
fake = true; // dummy is fake, but still available
} else if (i.getType() == SimplePageItem.RESOURCE || i.getType() == SimplePageItem.URL) {
if (i.getType() == SimplePageItem.RESOURCE && i.isSameWindow()) {
if (available) {
GeneralViewParameters params = new GeneralViewParameters(ShowItemProducer.VIEW_ID);
params.setSendingPage(currentPage.getPageId());
params.setSource(i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner()));
params.setItemId(i.getId());
UILink link = UIInternalLink.make(container, "link", params);
link.decorate(new UIFreeAttributeDecorator("lessonbuilderitem", itemString));
}
} else {
if (available) {
URL = i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner());
UIInternalLink link = LinkTrackerProducer.make(container, ID, i.getName(), URL, i.getId(), notDone);
link.decorate(new UIFreeAttributeDecorator("lessonbuilderitem", itemString));
link.decorate(new UIFreeAttributeDecorator("target", "_blank"));
};
}
} else if (i.getType() == SimplePageItem.PAGE) {
SimplePage p = simplePageToolDao.getPage(Long.valueOf(i.getSakaiId()));
if(p != null) {
GeneralViewParameters eParams = new GeneralViewParameters(ShowPageProducer.VIEW_ID, p.getPageId());
eParams.setItemId(i.getId());
// nextpage indicates whether it should be pushed onto breadcrumbs
// or replace the top item
if (i.getNextPage()) {
eParams.setPath("next");
} else {
eParams.setPath("push");
}
boolean isbutton = false;
// button says to display the link as a button. use navIntrTool,
// which is standard
// Sakai CSS that generates the type of button used in toolbars. We
// have to override
// with background:transparent or we get remnants of the gray
if ("button".equals(i.getFormat())) {
isbutton = true;
UIOutput span = UIOutput.make(container, ID + "-button-span");
ID = ID + "-button";
if (!i.isRequired()) {
span.decorate(new UIFreeAttributeDecorator("class", "navIntraTool buttonItem"));
}
isbutton = true;
}
UILink link;
if (available) {
link = UIInternalLink.make(container, ID, eParams);
link.decorate(new UIFreeAttributeDecorator("lessonbuilderitem", itemString));
if (i.isPrerequisite()) {
simplePageBean.checkItemPermissions(i, true);
}
// at this point we know the page isn't available, i.e. user
// hasn't
// met all the prerequistes. Normally we give them a nonworking
// grayed out link. But if they are the author, we want to
// give them a real link. Otherwise if it's a subpage they have
// no way to get to it (currently -- we'll fix that)
// but we make it look like it's disabled so they can see what
// students see
} else if (canEditPage) {
// for author, need to be able to get to the subpage to edit it
// so put out a function button, but make it look disabled
fake = false; // so we don't get an fake button as well
link = UIInternalLink.make(container, ID, eParams);
link.decorate(new UIFreeAttributeDecorator("lessonbuilderitem", itemString));
fakeDisableLink(link, messageLocator);
} // otherwise fake
}else {
log.warn("Lesson Builder Item #" + i.getId() + " does not have an associated page.");
return false;
}
} else if (i.getType() == SimplePageItem.ASSIGNMENT) {
LessonEntity lessonEntity = assignmentEntity.getEntity(i.getSakaiId(), simplePageBean);
if (available && lessonEntity != null) {
if (i.isPrerequisite()) {
simplePageBean.checkItemPermissions(i, true);
}
GeneralViewParameters params = new GeneralViewParameters(ShowItemProducer.VIEW_ID);
params.setSendingPage(currentPage.getPageId());
params.setSource((lessonEntity == null) ? "dummy" : lessonEntity.getUrl());
params.setItemId(i.getId());
UILink link = UIInternalLink.make(container, "link", params);
link.decorate(new UIFreeAttributeDecorator("lessonbuilderitem", itemString));
} else {
if (i.isPrerequisite()) {
simplePageBean.checkItemPermissions(i, false);
}
fake = true; // need to set this in case it's available for missing entity
}
} else if (i.getType() == SimplePageItem.ASSESSMENT) {
LessonEntity lessonEntity = quizEntity.getEntity(i.getSakaiId(),simplePageBean);
if (available && lessonEntity != null) {
if (i.isPrerequisite()) {
simplePageBean.checkItemPermissions(i, true);
}
// we've hacked Samigo to look at a special lesson builder
// session
// attribute. otherwise at the end of the test, Samigo replaces
// the
// whole screen, exiting form our iframe. The other tools don't
// do this.
GeneralViewParameters view = new GeneralViewParameters(ShowItemProducer.VIEW_ID);
view.setSendingPage(currentPage.getPageId());
view.setClearAttr("LESSONBUILDER_RETURNURL_SAMIGO");
view.setSource((lessonEntity == null) ? "dummy" : lessonEntity.getUrl());
view.setItemId(i.getId());
UILink link = UIInternalLink.make(container, "link", view);
link.decorate(new UIFreeAttributeDecorator("lessonbuilderitem", itemString));
} else {
if (i.isPrerequisite()) {
simplePageBean.checkItemPermissions(i, false);
}
fake = true; // need to set this in case it's available for missing entity
}
} else if (i.getType() == SimplePageItem.FORUM) {
LessonEntity lessonEntity = forumEntity.getEntity(i.getSakaiId());
if (available && lessonEntity != null) {
if (i.isPrerequisite()) {
simplePageBean.checkItemPermissions(i, true);
}
GeneralViewParameters view = new GeneralViewParameters(ShowItemProducer.VIEW_ID);
view.setSendingPage(currentPage.getPageId());
view.setItemId(i.getId());
view.setSource((lessonEntity == null) ? "dummy" : lessonEntity.getUrl());
UILink link = UIInternalLink.make(container, "link", view);
link.decorate(new UIFreeAttributeDecorator("lessonbuilderitem", itemString));
} else {
if (i.isPrerequisite()) {
simplePageBean.checkItemPermissions(i, false);
}
fake = true; // need to set this in case it's available for missing entity
}
} else if (i.getType() == SimplePageItem.BLTI) {
LessonEntity lessonEntity = (bltiEntity == null ? null : bltiEntity.getEntity(i.getSakaiId()));
if ("inline".equals(i.getFormat())) {
// no availability
String height=null;
if (i.getHeight() != null && !i.getHeight().equals(""))
height = i.getHeight().replace("px",""); // just in case
UIComponent iframe = UIOutput.make(container, "blti-iframe");
if (lessonEntity != null)
iframe.decorate(new UIFreeAttributeDecorator("src", lessonEntity.getUrl()));
String h = "300";
if (height != null && !height.trim().equals(""))
h = height;
iframe.decorate(new UIFreeAttributeDecorator("height", h));
iframe.decorate(new UIFreeAttributeDecorator("title", i.getName()));
// normally we get the name from the link text, but there's no link text here
UIOutput.make(container, "item-name", i.getName());
} else if (!"window".equals(i.getFormat())) {
// this is the default if format isn't valid or is missing
if (available && lessonEntity != null) {
if (i.isPrerequisite()) {
simplePageBean.checkItemPermissions(i, true);
}
GeneralViewParameters view = new GeneralViewParameters(ShowItemProducer.VIEW_ID);
view.setSendingPage(currentPage.getPageId());
view.setItemId(i.getId());
view.setSource((lessonEntity==null)?"dummy":lessonEntity.getUrl());
UIComponent link = UIInternalLink.make(container, "link", view)
.decorate(new UIFreeAttributeDecorator("lessonbuilderitem", itemString));
} else {
if (i.isPrerequisite()) {
simplePageBean.checkItemPermissions(i, false);
}
fake = true; // need to set this in case it's available for missing entity
}
} else {
if (available && lessonEntity != null) {
URL = lessonEntity.getUrl();
UIInternalLink link = LinkTrackerProducer.make(container, ID, i.getName(), URL, i.getId(), notDone);
link.decorate(new UIFreeAttributeDecorator("lessonbuilderitem", itemString));
link.decorate(new UIFreeAttributeDecorator("target", "_blank"));
} else
fake = true; // need to set this in case it's available for missing entity
}
}
String note = null;
if (status == Status.COMPLETED) {
note = messageLocator.getMessage("simplepage.status.completed");
}
if (status == Status.REQUIRED) {
note = messageLocator.getMessage("simplepage.status.required");
}
if (fake) {
ID = ID + "-fake";
UIOutput link = UIOutput.make(container, ID, i.getName());
link.decorate(new UIFreeAttributeDecorator("lessonbuilderitem", itemString));
if (!available)
link.decorate(new UITooltipDecorator(messageLocator.getMessage("simplepage.complete_required")));
} else
UIOutput.make(container, ID + "-text", i.getName());
if (note != null) {
UIOutput.make(container, ID + "-note", note + " ");
}
return available;
}
private static void disableLink(UIComponent link, MessageLocator messageLocator) {
link.decorate(new UIFreeAttributeDecorator("onclick", "return false"));
link.decorate(new UIDisabledDecorator());
link.decorate(new UIStyleDecorator("disabled"));
link.decorate(new UIFreeAttributeDecorator("style", "color:#999 !important"));
link.decorate(new UITooltipDecorator(messageLocator.getMessage("simplepage.complete_required")));
}
// show is if it was disabled but don't actually
private static void fakeDisableLink(UILink link, MessageLocator messageLocator) {
link.decorate(new UIFreeAttributeDecorator("style", "color:#999 !important"));
link.decorate(new UITooltipDecorator(messageLocator.getMessage("simplepage.complete_required")));
}
public void setSimplePageToolDao(SimplePageToolDao s) {
simplePageToolDao = s;
}
public void setDateEvolver(FormatAwareDateInputEvolver dateevolver) {
this.dateevolver = dateevolver;
}
public void setTimeService(TimeService ts) {
timeService = ts;
}
public void setLocaleGetter(LocaleGetter localegetter) {
this.localegetter = localegetter;
}
public void setForumEntity(LessonEntity e) {
// forumEntity is static, so it may already have been set
// there is a possible race condition, but since the bean is
// a singleton both people in the race will be trying to set
// the same value. So it shouldn't matter
if (forumEntity == null) {
forumEntity = e;
}
}
public void setQuizEntity(LessonEntity e) {
// forumEntity is static, so it may already have been set
// there is a possible race condition, but since the bean is
// a singleton both people in the race will be trying to set
// the same value. So it shouldn't matter
if (quizEntity == null) {
quizEntity = e;
}
}
public void setAssignmentEntity(LessonEntity e) {
// forumEntity is static, so it may already have been set
// there is a possible race condition, but since the bean is
// a singleton both people in the race will be trying to set
// the same value. So it shouldn't matter
if (assignmentEntity == null) {
assignmentEntity = e;
}
}
public void setBltiEntity(LessonEntity e) {
if (bltiEntity == null)
bltiEntity = e;
}
public void setToolManager(ToolManager m) {
toolManager = m;
}
public void setLessonBuilderAccessService (LessonBuilderAccessService a) {
lessonBuilderAccessService = a;
}
public ViewParameters getViewParameters() {
return new GeneralViewParameters();
}
/**
* Checks for the version of IE. Returns 0 if we're not running IE.
* But there's a problem. IE 11 doesn't have the MSIE tag. But it stiill
* needs to be treated as IE, because the OBJECT tag won't work with Quicktime
* Since all I test is > 0, I use a simplified version that returns 0 or 1
* @return
*/
public int checkIEVersion() {
UsageSession usageSession = UsageSessionService.getSession();
if (usageSession == null)
return 0;
browserString = usageSession.getUserAgent();
if (browserString == null)
return 0;
int ieIndex = browserString.indexOf("Trident/");
if (ieIndex >= 0)
return 1;
else
return 0;
// int ieVersion = 0;
// if (ieIndex >= 0) {
// String ieV = browserString.substring(ieIndex + 6);
// int i = 0;
// int e = ieV.length();
// while (i < e) {
// if (Character.isDigit(ieV.charAt(i))) {
// i++;
// } else {
// break;
// }
// }
// if (i > 0) {
// ieV = ieV.substring(0, i);
// ieVersion = Integer.parseInt(ieV);
//} }
//
// return ieVersion;
}
private void createToolBar(UIContainer tofill, SimplePage currentPage, boolean isStudent) {
UIBranchContainer toolBar = UIBranchContainer.make(tofill, "tool-bar:");
boolean studentPage = currentPage.getOwner() != null;
// toolbar
// dropdowns
UIOutput.make(toolBar, "icondropc");
UIOutput.make(toolBar, "icondrop");
// right side
createToolBarLink(ReorderProducer.VIEW_ID, toolBar, "reorder", "simplepage.reorder", currentPage, "simplepage.reorder-tooltip");
UILink.make(toolBar, "help", messageLocator.getMessage("simplepage.help"),
getLocalizedURL( isStudent ? "student.html" : "general.html"));
if (!studentPage)
createToolBarLink(PermissionsHelperProducer.VIEW_ID, toolBar, "permissions", "simplepage.permissions", currentPage, "simplepage.permissions.tooltip");
// add content menu
createToolBarLink(EditPageProducer.VIEW_ID, tofill, "add-text", "simplepage.text", currentPage, "simplepage.text.tooltip").setItemId(null);
createFilePickerToolBarLink(ResourcePickerProducer.VIEW_ID, tofill, "add-multimedia", "simplepage.multimedia", true, false, currentPage, "simplepage.multimedia.tooltip");
createFilePickerToolBarLink(ResourcePickerProducer.VIEW_ID, tofill, "add-resource", "simplepage.resource", false, false, currentPage, "simplepage.resource.tooltip");
UILink subpagelink = UIInternalLink.makeURL(tofill, "subpage-link", "#");
// content menu not on students
if (!studentPage) {
// add website.
// Are we running a kernel with KNL-273?
Class contentHostingInterface = ContentHostingService.class;
try {
Method expandMethod = contentHostingInterface.getMethod("expandZippedResource", new Class[] { String.class });
UIOutput.make(tofill, "addwebsite-li");
createFilePickerToolBarLink(ResourcePickerProducer.VIEW_ID, tofill, "add-website", "simplepage.website", false, true, currentPage, "simplepage.website.tooltip");
} catch (NoSuchMethodException nsme) {
// A: No
} catch (Exception e) {
// A: Not sure
log.warn("SecurityException thrown by expandZippedResource method lookup", e);
}
UIOutput.make(tofill, "assignment-li");
createToolBarLink(AssignmentPickerProducer.VIEW_ID, tofill, "add-assignment", "simplepage.assignment", currentPage, "simplepage.assignment");
UIOutput.make(tofill, "quiz-li");
createToolBarLink(QuizPickerProducer.VIEW_ID, tofill, "add-quiz", "simplepage.quiz", currentPage, "simplepage.quiz");
UIOutput.make(tofill, "forum-li");
createToolBarLink(ForumPickerProducer.VIEW_ID, tofill, "add-forum", "simplepage.forum", currentPage, "simplepage.forum.tooltip");
UIOutput.make(tofill, "question-li");
UILink questionlink = UIInternalLink.makeURL(tofill, "question-link", "#");
GeneralViewParameters eParams = new GeneralViewParameters(VIEW_ID);
eParams.addTool = GeneralViewParameters.COMMENTS;
UIOutput.make(tofill, "student-li");
UIInternalLink.make(tofill, "add-comments", messageLocator.getMessage("simplepage.comments"), eParams).
decorate(new UITooltipDecorator(messageLocator.getMessage("simplepage.comments.tooltip")));
eParams = new GeneralViewParameters(VIEW_ID);
eParams.addTool = GeneralViewParameters.STUDENT_CONTENT;
UIOutput.make(tofill, "studentcontent-li");
UIInternalLink.make(tofill, "add-content", messageLocator.getMessage("simplepage.add-student-content"), eParams).
decorate(new UITooltipDecorator(messageLocator.getMessage("simplepage.student-descrip")));
// in case we're on an old system without current BLTI
if (bltiEntity != null && ((BltiInterface)bltiEntity).servicePresent()) {
UIOutput.make(tofill, "blti-li");
createToolBarLink(BltiPickerProducer.VIEW_ID, tofill, "add-blti", "simplepage.blti", currentPage, "simplepage.blti.tooltip");
}
}
}
private GeneralViewParameters createToolBarLink(String viewID, UIContainer tofill, String ID, String message, SimplePage currentPage, String tooltip) {
GeneralViewParameters params = new GeneralViewParameters();
params.setSendingPage(currentPage.getPageId());
createStandardToolBarLink(viewID, tofill, ID, message, params, tooltip);
return params;
}
private FilePickerViewParameters createFilePickerToolBarLink(String viewID, UIContainer tofill, String ID, String message, boolean resourceType, boolean website, SimplePage currentPage, String tooltip) {
FilePickerViewParameters fileparams = new FilePickerViewParameters();
fileparams.setSender(currentPage.getPageId());
fileparams.setResourceType(resourceType);
fileparams.setWebsite(website);
createStandardToolBarLink(viewID, tofill, ID, message, fileparams, tooltip);
return fileparams;
}
private void createStandardToolBarLink(String viewID, UIContainer tofill, String ID, String message, SimpleViewParameters params, String tooltip) {
params.viewID = viewID;
UILink link = UIInternalLink.make(tofill, ID, messageLocator.getMessage(message), params);
link.decorate(new UITooltipDecorator(messageLocator.getMessage(tooltip)));
}
public List reportNavigationCases() {
List<NavigationCase> togo = new ArrayList<NavigationCase>();
togo.add(new NavigationCase(null, new SimpleViewParameters(ShowPageProducer.VIEW_ID)));
togo.add(new NavigationCase("success", new SimpleViewParameters(ShowPageProducer.VIEW_ID)));
togo.add(new NavigationCase("cancel", new SimpleViewParameters(ShowPageProducer.VIEW_ID)));
togo.add(new NavigationCase("failure", new SimpleViewParameters(ReloadPageProducer.VIEW_ID)));
togo.add(new NavigationCase("reload", new SimpleViewParameters(ReloadPageProducer.VIEW_ID)));
togo.add(new NavigationCase("removed", new SimpleViewParameters(RemovePageProducer.VIEW_ID)));
return togo;
}
private void createSubpageDialog(UIContainer tofill, SimplePage currentPage) {
UIOutput.make(tofill, "subpage-dialog").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.subpage")));
UIForm form = UIForm.make(tofill, "subpage-form");
UIOutput.make(form, "subpage-label", messageLocator.getMessage("simplepage.pageTitle_label"));
UIInput.make(form, "subpage-title", "#{simplePageBean.subpageTitle}");
GeneralViewParameters view = new GeneralViewParameters(PagePickerProducer.VIEW_ID);
view.setSendingPage(currentPage.getPageId());
if(currentPage.getOwner() == null) {
UIInternalLink.make(form, "subpage-choose", messageLocator.getMessage("simplepage.choose_existing_page"), view);
}
UIBoundBoolean.make(form, "subpage-next", "#{simplePageBean.subpageNext}", false);
UIBoundBoolean.make(form, "subpage-button", "#{simplePageBean.subpageButton}", false);
UICommand.make(form, "create-subpage", messageLocator.getMessage("simplepage.create"), "#{simplePageBean.createSubpage}");
UICommand.make(form, "cancel-subpage", messageLocator.getMessage("simplepage.cancel"), null);
}
private void createEditItemDialog(UIContainer tofill, SimplePage currentPage, SimplePageItem pageItem) {
UIOutput.make(tofill, "edit-item-dialog").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edititem_header")));
UIForm form = UIForm.make(tofill, "edit-form");
UIOutput.make(form, "name-label", messageLocator.getMessage("simplepage.name_label"));
UIInput.make(form, "name", "#{simplePageBean.name}");
UIOutput.make(form, "description-label", messageLocator.getMessage("simplepage.description_label"));
UIInput.make(form, "description", "#{simplePageBean.description}");
UIOutput changeDiv = UIOutput.make(form, "changeDiv");
if(currentPage.getOwner() != null) changeDiv.decorate(new UIStyleDecorator("noDisplay"));
GeneralViewParameters params = new GeneralViewParameters();
params.setSendingPage(currentPage.getPageId());
params.viewID = AssignmentPickerProducer.VIEW_ID;
UIInternalLink.make(form, "change-assignment", messageLocator.getMessage("simplepage.change_assignment"), params);
params = new GeneralViewParameters();
params.setSendingPage(currentPage.getPageId());
params.viewID = QuizPickerProducer.VIEW_ID;
UIInternalLink.make(form, "change-quiz", messageLocator.getMessage("simplepage.change_quiz"), params);
params = new GeneralViewParameters();
params.setSendingPage(currentPage.getPageId());
params.viewID = ForumPickerProducer.VIEW_ID;
UIInternalLink.make(form, "change-forum", messageLocator.getMessage("simplepage.change_forum"), params);
params = new GeneralViewParameters();
params.setSendingPage(currentPage.getPageId());
params.viewID = BltiPickerProducer.VIEW_ID;
UIInternalLink.make(form, "change-blti", messageLocator.getMessage("simplepage.change_blti"), params);
FilePickerViewParameters fileparams = new FilePickerViewParameters();
fileparams.setSender(currentPage.getPageId());
fileparams.setResourceType(false);
fileparams.setWebsite(false);
fileparams.viewID = ResourcePickerProducer.VIEW_ID;
UIInternalLink.make(form, "change-resource", messageLocator.getMessage("simplepage.change_resource"), fileparams);
params = new GeneralViewParameters();
params.setSendingPage(currentPage.getPageId());
params.viewID = PagePickerProducer.VIEW_ID;
UIInternalLink.make(form, "change-page", messageLocator.getMessage("simplepage.change_page"), params);
params = new GeneralViewParameters();
params.setSendingPage(currentPage.getPageId());
params.setItemId(pageItem.getId());
params.setReturnView(VIEW_ID);
params.setTitle(messageLocator.getMessage("simplepage.return_from_edit"));
params.setSource("SRC");
params.viewID = ShowItemProducer.VIEW_ID;
UIInternalLink.make(form, "edit-item-object", params);
UIOutput.make(form, "edit-item-text");
params = new GeneralViewParameters();
params.setSendingPage(currentPage.getPageId());
params.setItemId(pageItem.getId());
params.setReturnView(VIEW_ID);
params.setTitle(messageLocator.getMessage("simplepage.return_from_edit"));
params.setSource("SRC");
params.viewID = ShowItemProducer.VIEW_ID;
UIInternalLink.make(form, "edit-item-settings", params);
UIOutput.make(form, "edit-item-settings-text");
UIBoundBoolean.make(form, "item-next", "#{simplePageBean.subpageNext}", false);
UIBoundBoolean.make(form, "item-button", "#{simplePageBean.subpageButton}", false);
UIInput.make(form, "item-id", "#{simplePageBean.itemId}");
UIOutput permDiv = UIOutput.make(form, "permDiv");
if(currentPage.getOwner() != null) permDiv.decorate(new UIStyleDecorator("noDisplay"));
UIBoundBoolean.make(form, "item-required2", "#{simplePageBean.subrequirement}", false);
UIBoundBoolean.make(form, "item-required", "#{simplePageBean.required}", false);
UIBoundBoolean.make(form, "item-prerequisites", "#{simplePageBean.prerequisite}", false);
UIBoundBoolean.make(form, "item-newwindow", "#{simplePageBean.newWindow}", false);
UISelect radios = UISelect.make(form, "format-select",
new String[] {"window", "inline", "page"},
"#{simplePageBean.format}", "");
UISelectChoice.make(form, "format-window", radios.getFullID(), 0);
UISelectChoice.make(form, "format-inline", radios.getFullID(), 1);
UISelectChoice.make(form, "format-page", radios.getFullID(), 2);
UIInput.make(form, "edit-height-value", "#{simplePageBean.height}");
UISelect.make(form, "assignment-dropdown", SimplePageBean.GRADES, "#{simplePageBean.dropDown}", SimplePageBean.GRADES[0]);
UIInput.make(form, "assignment-points", "#{simplePageBean.points}");
UICommand.make(form, "edit-item", messageLocator.getMessage("simplepage.edit"), "#{simplePageBean.editItem}");
// can't use site groups on user content, and don't want students to hack
// on groups for site content
if (currentPage.getOwner() == null)
createGroupList(form, null, "", "#{simplePageBean.selectedGroups}");
UICommand.make(form, "delete-item", messageLocator.getMessage("simplepage.delete"), "#{simplePageBean.deleteItem}");
UICommand.make(form, "edit-item-cancel", messageLocator.getMessage("simplepage.cancel"), null);
}
// for both add multimedia and add resource, as well as updating resources
// in the edit dialogs
public void createGroupList(UIContainer tofill, Collection<String> groupsSet, String prefix, String beanspec) {
List<GroupEntry> groups = simplePageBean.getCurrentGroups();
ArrayList<String> values = new ArrayList<String>();
ArrayList<String> initValues = new ArrayList<String>();
if (groups == null || groups.size() == 0)
return;
for (GroupEntry entry : groups) {
if (entry.name.startsWith("Access: ")) {
continue;
}
values.add(entry.id);
if (groupsSet != null && groupsSet.contains(entry.id)) {
initValues.add(entry.id);
}
}
if (groupsSet == null || groupsSet.size() == 0) {
initValues.add("");
}
// this could happen if the only groups are Access groups
if (values.size() == 0)
return;
UIOutput.make(tofill, prefix + "grouplist");
UISelect select = UISelect.makeMultiple(tofill, prefix + "group-list-span", values.toArray(new String[1]), beanspec, initValues.toArray(new String[1]));
int index = 0;
for (GroupEntry entry : groups) {
if (entry.name.startsWith("Access: ")) {
continue;
}
UIBranchContainer row = UIBranchContainer.make(tofill, prefix + "select-group-list:");
UISelectChoice.make(row, prefix + "select-group", select.getFullID(), index);
UIOutput.make(row, prefix + "select-group-text", entry.name);
index++;
}
}
// for both add multimedia and add resource, as well as updating resources
// in the edit dialogs
private void createAddMultimediaDialog(UIContainer tofill, SimplePage currentPage) {
UIOutput.make(tofill, "add-multimedia-dialog").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.resource")));
UILink.make(tofill, "mm-additional-instructions", messageLocator.getMessage("simplepage.additional-instructions-label"),
getLocalizedURL( "multimedia.html"));
UILink.make(tofill, "mm-additional-website-instructions", messageLocator.getMessage("simplepage.additional-website-instructions-label"),
getLocalizedURL( "website.html"));
UIForm form = UIForm.make(tofill, "add-multimedia-form");
UIOutput.make(form, "mm-file-label", messageLocator.getMessage("simplepage.upload_label"));
UIOutput.make(form, "mm-url-label", messageLocator.getMessage("simplepage.addLink_label"));
UIInput.make(form, "mm-url", "#{simplePageBean.mmUrl}");
FilePickerViewParameters fileparams = new FilePickerViewParameters();
fileparams.setSender(currentPage.getPageId());
fileparams.setResourceType(true);
fileparams.viewID = ResourcePickerProducer.VIEW_ID;
UILink link = UIInternalLink.make(form, "mm-choose", messageLocator.getMessage("simplepage.choose_existing_or"), fileparams);
UICommand.make(form, "mm-add-item", messageLocator.getMessage("simplepage.save_message"), "#{simplePageBean.addMultimedia}");
UIInput.make(form, "mm-item-id", "#{simplePageBean.itemId}");
UIInput.make(form, "mm-is-mm", "#{simplePageBean.isMultimedia}");
UIInput.make(form, "mm-display-type", "#{simplePageBean.multimediaDisplayType}");
UIInput.make(form, "mm-is-website", "#{simplePageBean.isWebsite}");
UICommand.make(form, "mm-cancel", messageLocator.getMessage("simplepage.cancel"), null);
}
private void createImportCcDialog(UIContainer tofill) {
UIOutput.make(tofill, "import-cc-dialog").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.import_cc")));
UIForm form = UIForm.make(tofill, "import-cc-form");
UICommand.make(form, "import-cc-submit", messageLocator.getMessage("simplepage.save_message"), "#{simplePageBean.importCc}");
UICommand.make(form, "mm-cancel", messageLocator.getMessage("simplepage.cancel"), null);
UIBoundBoolean.make(form, "import-toplevel", "#{simplePageBean.importtop}", false);
class ToolData {
String toolId;
String toolName;
}
int numQuizEngines = 0;
List<ToolData> quizEngines = new ArrayList<ToolData>();
for (LessonEntity q = quizEntity; q != null; q = q.getNextEntity()) {
String toolId = q.getToolId();
String toolName = simplePageBean.getCurrentToolTitle(q.getToolId());
// we only want the ones that are actually in our site
if (toolName != null) {
ToolData toolData = new ToolData();
toolData.toolId = toolId;
toolData.toolName = toolName;
numQuizEngines++;
quizEngines.add(toolData);
}
}
if (numQuizEngines == 0) {
UIVerbatim.make(form, "quizmsg", messageLocator.getMessage("simplepage.noquizengines"));
} else if (numQuizEngines == 1) {
UIInput.make(form, "quiztool", "#{simplePageBean.quiztool}", quizEntity.getToolId());
} else { // put up message and then radio buttons for each possibility
// need values array for RSF's select implementation. It sees radio
// buttons as a kind of select
ArrayList<String> values = new ArrayList<String>();
for (ToolData toolData : quizEngines) {
values.add(toolData.toolId);
}
// the message
UIOutput.make(form, "quizmsg", messageLocator.getMessage("simplepage.choosequizengine"));
// now the list of radio buttons
UISelect quizselect = UISelect.make(form, "quiztools", values.toArray(new String[1]), "#{simplePageBean.quiztool}", null);
int i = 0;
for (ToolData toolData : quizEngines) {
UIBranchContainer toolItem = UIBranchContainer.make(form, "quiztoolitem:", String.valueOf(i));
UISelectChoice.make(toolItem, "quiztoolbox", quizselect.getFullID(), i);
UIOutput.make(toolItem, "quiztoollabel", toolData.toolName);
i++;
}
}
int numTopicEngines = 0;
List<ToolData> topicEngines = new ArrayList<ToolData>();
for (LessonEntity q = forumEntity; q != null; q = q.getNextEntity()) {
String toolId = q.getToolId();
String toolName = simplePageBean.getCurrentToolTitle(q.getToolId());
// we only want the ones that are actually in our site
if (toolName != null) {
ToolData toolData = new ToolData();
toolData.toolId = toolId;
toolData.toolName = toolName;
numTopicEngines++;
topicEngines.add(toolData);
}
}
if (numTopicEngines == 0) {
UIVerbatim.make(form, "topicmsg", messageLocator.getMessage("simplepage.notopicengines"));
} else if (numTopicEngines == 1) {
UIInput.make(form, "topictool", "#{simplePageBean.topictool}", forumEntity.getToolId());
} else {
ArrayList<String> values = new ArrayList<String>();
for (ToolData toolData : topicEngines) {
values.add(toolData.toolId);
}
UIOutput.make(form, "topicmsg", messageLocator.getMessage("simplepage.choosetopicengine"));
UISelect topicselect = UISelect.make(form, "topictools", values.toArray(new String[1]), "#{simplePageBean.topictool}", null);
int i = 0;
for (ToolData toolData : topicEngines) {
UIBranchContainer toolItem = UIBranchContainer.make(form, "topictoolitem:", String.valueOf(i));
UISelectChoice.make(toolItem, "topictoolbox", topicselect.getFullID(), i);
UIOutput.make(toolItem, "topictoollabel", toolData.toolName);
i++;
}
}
int numAssignEngines = 0;
List<ToolData> assignEngines = new ArrayList<ToolData>();
for (LessonEntity q = assignmentEntity; q != null; q = q.getNextEntity()) {
String toolId = q.getToolId();
String toolName = simplePageBean.getCurrentToolTitle(q.getToolId());
// we only want the ones that are actually in our site
if (toolName != null) {
ToolData toolData = new ToolData();
toolData.toolId = toolId;
toolData.toolName = toolName;
numAssignEngines++;
assignEngines.add(toolData);
}
}
if (numAssignEngines == 0) {
UIVerbatim.make(form, "assignmsg", messageLocator.getMessage("simplepage.noassignengines"));
} else if (numAssignEngines == 1) {
UIInput.make(form, "assigntool", "#{simplePageBean.assigntool}", assignmentEntity.getToolId());
} else {
ArrayList<String> values = new ArrayList<String>();
for (ToolData toolData : assignEngines) {
values.add(toolData.toolId);
}
UIOutput.make(form, "assignmsg", messageLocator.getMessage("simplepage.chooseassignengine"));
UISelect assignselect = UISelect.make(form, "assigntools", values.toArray(new String[1]), "#{simplePageBean.assigntool}", null);
int i = 0;
for (ToolData toolData : assignEngines) {
UIBranchContainer toolItem = UIBranchContainer.make(form, "assigntoolitem:", String.valueOf(i));
UISelectChoice.make(toolItem, "assigntoolbox", assignselect.getFullID(), i);
UIOutput.make(toolItem, "assigntoollabel", toolData.toolName);
i++;
}
}
}
private void createExportCcDialog(UIContainer tofill) {
UIOutput.make(tofill, "export-cc-dialog").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.export-cc-title")));
UIForm form = UIForm.make(tofill, "export-cc-form");
UIOutput.make(form, "export-cc-v11"); // value is handled by JS, so RSF doesn't need to treat it as input
UIOutput.make(form, "export-cc-bank"); // value is handled by JS, so RSF doesn't need to treat it as input
UICommand.make(form, "export-cc-submit", messageLocator.getMessage("simplepage.exportcc-download"), "#{simplePageBean.importCc}");
UICommand.make(form, "export-cc-cancel", messageLocator.getMessage("simplepage.cancel"), null);
// the actual submission is with a GET. The submit button clicks this link.
ExportCCViewParameters view = new ExportCCViewParameters("exportCc");
view.setExportcc(true);
view.setVersion("1.2");
view.setBank("1");
UIInternalLink.make(form, "export-cc-link", "export cc link", view);
}
private void createEditMultimediaDialog(UIContainer tofill, SimplePage currentPage) {
UIOutput.make(tofill, "edit-multimedia-dialog").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.editMultimedia")));
UIOutput.make(tofill, "instructions");
UIForm form = UIForm.make(tofill, "edit-multimedia-form");
UIOutput.make(form, "height-label", messageLocator.getMessage("simplepage.height_label"));
UIInput.make(form, "height", "#{simplePageBean.height}");
UIOutput.make(form, "width-label", messageLocator.getMessage("simplepage.width_label"));
UIInput.make(form, "width", "#{simplePageBean.width}");
UIOutput.make(form, "description2-label", messageLocator.getMessage("simplepage.description_label"));
UIInput.make(form, "description2", "#{simplePageBean.description}");
FilePickerViewParameters fileparams = new FilePickerViewParameters();
fileparams.setSender(currentPage.getPageId());
fileparams.setResourceType(true);
fileparams.viewID = ResourcePickerProducer.VIEW_ID;
UIInternalLink.make(form, "change-resource-mm", messageLocator.getMessage("simplepage.change_resource"), fileparams);
UIOutput.make(form, "alt-label", messageLocator.getMessage("simplepage.alt_label"));
UIInput.make(form, "alt", "#{simplePageBean.alt}");
UIInput.make(form, "mimetype", "#{simplePageBean.mimetype}");
UICommand.make(form, "edit-multimedia-item", messageLocator.getMessage("simplepage.save_message"), "#{simplePageBean.editMultimedia}");
UIInput.make(form, "multimedia-item-id", "#{simplePageBean.itemId}");
UICommand.make(form, "delete-multimedia-item", messageLocator.getMessage("simplepage.delete"), "#{simplePageBean.deleteItem}");
UICommand.make(form, "edit-multimedia-cancel", messageLocator.getMessage("simplepage.cancel"), null);
}
private void createYoutubeDialog(UIContainer tofill, SimplePage currentPage) {
UIOutput.make(tofill, "youtube-dialog").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit_youtubelink")));
UIForm form = UIForm.make(tofill, "youtube-form");
UIInput.make(form, "youtubeURL", "#{simplePageBean.youtubeURL}");
UIInput.make(form, "youtubeEditId", "#{simplePageBean.youtubeId}");
UIInput.make(form, "youtubeHeight", "#{simplePageBean.height}");
UIInput.make(form, "youtubeWidth", "#{simplePageBean.width}");
UIOutput.make(form, "description4-label", messageLocator.getMessage("simplepage.description_label"));
UIInput.make(form, "description4", "#{simplePageBean.description}");
UICommand.make(form, "delete-youtube-item", messageLocator.getMessage("simplepage.delete"), "#{simplePageBean.deleteYoutubeItem}");
UICommand.make(form, "update-youtube", messageLocator.getMessage("simplepage.edit"), "#{simplePageBean.updateYoutube}");
UICommand.make(form, "cancel-youtube", messageLocator.getMessage("simplepage.cancel"), null);
if(currentPage.getOwner() == null) {
UIOutput.make(form, "editgroups-youtube");
}
}
private void createMovieDialog(UIContainer tofill, SimplePage currentPage) {
UIOutput.make(tofill, "movie-dialog").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edititem_header")));
UIForm form = UIForm.make(tofill, "movie-form");
UIInput.make(form, "movie-height", "#{simplePageBean.height}");
UIInput.make(form, "movie-width", "#{simplePageBean.width}");
UIInput.make(form, "movieEditId", "#{simplePageBean.itemId}");
UIOutput.make(form, "description3-label", messageLocator.getMessage("simplepage.description_label"));
UIInput.make(form, "description3", "#{simplePageBean.description}");
UIInput.make(form, "mimetype4", "#{simplePageBean.mimetype}");
FilePickerViewParameters fileparams = new FilePickerViewParameters();
fileparams.setSender(currentPage.getPageId());
fileparams.setResourceType(true);
fileparams.viewID = ResourcePickerProducer.VIEW_ID;
UIInternalLink.make(form, "change-resource-movie", messageLocator.getMessage("simplepage.change_resource"), fileparams);
UIBoundBoolean.make(form, "question-prerequisite", "#{simplePageBean.prerequisite}",false);
UICommand.make(form, "delete-movie-item", messageLocator.getMessage("simplepage.delete"), "#{simplePageBean.deleteItem}");
UICommand.make(form, "update-movie", messageLocator.getMessage("simplepage.edit"), "#{simplePageBean.updateMovie}");
UICommand.make(form, "movie-cancel", messageLocator.getMessage("simplepage.cancel"), null);
}
private void createEditTitleDialog(UIContainer tofill, SimplePage page, SimplePageItem pageItem) {
UIOutput.make(tofill, "edit-title-dialog").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.editTitle")));
UIForm form = UIForm.make(tofill, "title-form");
UIOutput.make(form, "pageTitleLabel", messageLocator.getMessage("simplepage.pageTitle_label"));
UIInput.make(form, "pageTitle", "#{simplePageBean.pageTitle}");
if (page.getOwner() == null) {
UIOutput.make(tofill, "hideContainer");
UIBoundBoolean.make(form, "hide", "#{simplePageBean.hidePage}", (page.isHidden()));
Date releaseDate = page.getReleaseDate();
UIBoundBoolean.make(form, "page-releasedate", "#{simplePageBean.hasReleaseDate}", (releaseDate != null));
if (releaseDate == null) {
releaseDate = new Date();
}
simplePageBean.setReleaseDate(releaseDate);
UIInput releaseForm = UIInput.make(form, "releaseDate:", "simplePageBean.releaseDate");
dateevolver.setStyle(FormatAwareDateInputEvolver.DATE_TIME_INPUT);
dateevolver.evolveDateInput(releaseForm, page.getReleaseDate());
if (pageItem.getPageId() == 0) {
UIOutput.make(form, "prereqContainer");
UIBoundBoolean.make(form, "page-required", "#{simplePageBean.required}", (pageItem.isRequired()));
UIBoundBoolean.make(form, "page-prerequisites", "#{simplePageBean.prerequisite}", (pageItem.isPrerequisite()));
}
}
UIOutput gradeBook = UIOutput.make(form, "gradeBookDiv");
if(page.getOwner() != null) gradeBook.decorate(new UIStyleDecorator("noDisplay"));
UIOutput.make(form, "page-gradebook");
Double points = page.getGradebookPoints();
String pointString = "";
if (points != null) {
pointString = points.toString();
}
if(page.getOwner() == null) {
UIOutput.make(form, "csssection");
ArrayList<ContentResource> sheets = simplePageBean.getAvailableCss();
String[] options = new String[sheets.size()+2];
String[] labels = new String[sheets.size()+2];
// Sets up the CSS arrays
options[0] = null;
labels[0] = messageLocator.getMessage("simplepage.default-css");
options[1] = null;
labels[1] = "----------";
for(int i = 0; i < sheets.size(); i++) {
if(sheets.get(i) != null) {
options[i+2] = sheets.get(i).getId();
labels[i+2] = sheets.get(i).getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}else {
// We show just one un-named separator if there are only site css, or system css, but not both.
// If we get here, it means we have both, so we name them.
options[i+2] = null;
labels[i+2] = "---" + messageLocator.getMessage("simplepage.system") + "---";
labels[1] = "---" + messageLocator.getMessage("simplepage.site") + "---";
}
}
UIOutput.make(form, "cssDropdownLabel", messageLocator.getMessage("simplepage.css-dropdown-label"));
UISelect.make(form, "cssDropdown", options, labels, "#{simplePageBean.dropDown}", page.getCssSheet());
UIOutput.make(form, "cssDefaultInstructions", messageLocator.getMessage("simplepage.css-default-instructions"));
UIOutput.make(form, "cssUploadLabel", messageLocator.getMessage("simplepage.css-upload-label"));
UIOutput.make(form, "cssUpload");
}
UIInput.make(form, "page-points", "#{simplePageBean.points}", pointString);
UICommand.make(form, "create-title", messageLocator.getMessage("simplepage.save"), "#{simplePageBean.editTitle}");
UICommand.make(form, "cancel-title", messageLocator.getMessage("simplepage.cancel"), "#{simplePageBean.cancel}");
}
private void createNewPageDialog(UIContainer tofill, SimplePage page, SimplePageItem pageItem) {
UIOutput.make(tofill, "new-page-dialog").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.new-page")));
UIForm form = UIForm.make(tofill, "new-page-form");
UIInput.make(form, "newPage", "#{simplePageBean.newPageTitle}");
UIInput.make(form, "new-page-number", "#{simplePageBean.numberOfPages}");
UIBoundBoolean.make(form, "new-page-copy", "#{simplePageBean.copyPage}", false);
GeneralViewParameters view = new GeneralViewParameters(PagePickerProducer.VIEW_ID);
view.setSendingPage(-1L);
view.newTopLevel = true;
UIInternalLink.make(tofill, "new-page-choose", messageLocator.getMessage("simplepage.lm_existing_page"), view);
UICommand.make(form, "new-page-submit", messageLocator.getMessage("simplepage.save"), "#{simplePageBean.addPages}");
UICommand.make(form, "new-page-cancel", messageLocator.getMessage("simplepage.cancel"), "#{simplePageBean.cancel}");
}
private void createRemovePageDialog(UIContainer tofill, SimplePage page, SimplePageItem pageItem) {
UIOutput.make(tofill, "remove-page-dialog").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.remove-page")));
UIOutput.make(tofill, "remove-page-explanation",
(page.getOwner() == null ? messageLocator.getMessage("simplepage.remove-page-explanation") :
messageLocator.getMessage("simplepage.remove-student-page-explanation")));
UIForm form = UIForm.make(tofill, "remove-page-form");
form.addParameter(new UIELBinding("#{simplePageBean.removeId}", page.getPageId()));
// if (page.getOwner() == null) {
// // top level normal page. Use the remove page producer, which can handle removing tools out from under RSF
// GeneralViewParameters params = new GeneralViewParameters(RemovePageProducer.VIEW_ID);
// UIInternalLink.make(form, "remove-page-submit", "", params).decorate(new UIFreeAttributeDecorator("value", messageLocator.getMessage("simplepage.remove")));
// } else
// // a student top level page. call remove page directly, as it will just return to show page
// UICommand.make(form, "remove-page-submit", messageLocator.getMessage("simplepage.remove"), "#{simplePageBean.removePage}");
UIComponent button = UICommand.make(form, "remove-page-submit", messageLocator.getMessage("simplepage.remove"), "#{simplePageBean.removePage}");
if (page.getOwner() == null) // not student page
button.decorate(new UIFreeAttributeDecorator("onclick",
"window.location='/lessonbuilder-tool/removePage?site=" + simplePageBean.getCurrentSiteId() +
"&page=" + page.getPageId() + "';return false;"));
UICommand.make(form, "remove-page-cancel", messageLocator.getMessage("simplepage.cancel"), "#{simplePageBean.cancel}");
}
private void createCommentsDialog(UIContainer tofill) {
UIOutput.make(tofill, "comments-dialog").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit_commentslink")));
UIForm form = UIForm.make(tofill, "comments-form");
UIInput.make(form, "commentsEditId", "#{simplePageBean.itemId}");
UIBoundBoolean.make(form, "comments-anonymous", "#{simplePageBean.anonymous}");
UIBoundBoolean.make(form, "comments-graded", "#{simplePageBean.graded}");
UIInput.make(form, "comments-max", "#{simplePageBean.maxPoints}");
UIBoundBoolean.make(form, "comments-required", "#{simplePageBean.required}");
UIBoundBoolean.make(form, "comments-prerequisite", "#{simplePageBean.prerequisite}");
UICommand.make(form, "delete-comments-item", messageLocator.getMessage("simplepage.delete"), "#{simplePageBean.deleteItem}");
UICommand.make(form, "update-comments", messageLocator.getMessage("simplepage.edit"), "#{simplePageBean.updateComments}");
UICommand.make(form, "cancel-comments", messageLocator.getMessage("simplepage.cancel"), null);
}
private void createStudentContentDialog(UIContainer tofill, SimplePage currentPage) {
UIOutput.make(tofill, "student-dialog").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit_studentlink")));
UIForm form = UIForm.make(tofill, "student-form");
UIInput.make(form, "studentEditId", "#{simplePageBean.itemId}");
UIBoundBoolean.make(form, "student-anonymous", "#{simplePageBean.anonymous}");
UIBoundBoolean.make(form, "student-comments", "#{simplePageBean.comments}");
UIBoundBoolean.make(form, "student-comments-anon", "#{simplePageBean.forcedAnon}");
UIBoundBoolean.make(form, "student-required", "#{simplePageBean.required}");
UIBoundBoolean.make(form, "student-prerequisite", "#{simplePageBean.prerequisite}");
UIOutput.make(form, "peer-evaluation-creation");
UIBoundBoolean.make(form, "peer-eval-check", "#{simplePageBean.peerEval}");
UIInput.make(form, "peer-eval-input-title", "#{simplePageBean.rubricTitle}");
UIInput.make(form, "peer-eval-input-row", "#{simplePageBean.rubricRow}");
UIOutput.make(form, "peer_eval_open_date_label", messageLocator.getMessage("simplepage.peer-eval.open_date"));
UIInput openDateField = UIInput.make(form, "peer_eval_open_date:", "#{simplePageBean.peerEvalOpenDate}");
dateevolver.setStyle(FormatAwareDateInputEvolver.DATE_TIME_INPUT);
dateevolver.evolveDateInput(openDateField);
UIOutput.make(form, "peer_eval_due_date_label", messageLocator.getMessage("simplepage.peer-eval.due_date"));
UIInput dueDateField = UIInput.make(form, "peer_eval_due_date:", "#{simplePageBean.peerEvalDueDate}");
dateevolver.setStyle(FormatAwareDateInputEvolver.DATE_TIME_INPUT);
dateevolver.evolveDateInput(dueDateField);
UIBoundBoolean.make(form, "peer-eval-allow-selfgrade", "#{simplePageBean.peerEvalAllowSelfGrade}");
UIBoundBoolean.make(form, "student-graded", "#{simplePageBean.graded}");
UIInput.make(form, "student-max", "#{simplePageBean.maxPoints}");
UIBoundBoolean.make(form, "student-comments-graded", "#{simplePageBean.sGraded}");
UIInput.make(form, "student-comments-max", "#{simplePageBean.sMaxPoints}");
UIBoundBoolean.make(form, "student-group-owned", "#{simplePageBean.groupOwned}");
createGroupList(form, null, "student-", "#{simplePageBean.studentSelectedGroups}");
UICommand.make(form, "delete-student-item", messageLocator.getMessage("simplepage.delete"), "#{simplePageBean.deleteItem}");
UICommand.make(form, "update-student", messageLocator.getMessage("simplepage.edit"), "#{simplePageBean.updateStudent}");
UICommand.make(form, "cancel-student", messageLocator.getMessage("simplepage.cancel"), null);
// RU Rubrics
UIOutput.make(tofill, "peer-eval-create-dialog").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.peer-eval-create-title")));
}
private void createQuestionDialog(UIContainer tofill, SimplePage currentPage) {
UIOutput.make(tofill, "question-dialog").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit_questionlink")));
UIForm form = UIForm.make(tofill, "question-form");
UISelect questionType = UISelect.make(form, "question-select", new String[] {"multipleChoice", "shortanswer"}, "#{simplePageBean.questionType}", "");
UISelectChoice.make(form, "multipleChoiceSelect", questionType.getFullID(), 0);
UISelectChoice.make(form, "shortanswerSelect", questionType.getFullID(), 1);
UIOutput.make(form, "question-shortans-del").decorate(new UIFreeAttributeDecorator("alt", messageLocator.getMessage("simplepage.delete")));
UIOutput.make(form, "question-mc-del").decorate(new UIFreeAttributeDecorator("alt", messageLocator.getMessage("simplepage.delete")));
UIInput.make(form, "questionEditId", "#{simplePageBean.itemId}");
UIBoundBoolean.make(form, "question-required", "#{simplePageBean.required}");
UIBoundBoolean.make(form, "question-prerequisite", "#{simplePageBean.prerequisite}");
UIInput.make(form, "question-text-input", "#{simplePageBean.questionText}");
UIInput.make(form, "question-answer-full-shortanswer", "#{simplePageBean.questionAnswer}");
UIBoundBoolean.make(form, "question-graded", "#{simplePageBean.graded}");
UIInput.make(form, "question-gradebook-title", "#{simplePageBean.gradebookTitle}");
UIInput.make(form, "question-max", "#{simplePageBean.maxPoints}");
UIInput.make(form, "question-multiplechoice-answer-complete", "#{simplePageBean.addAnswerData}");
UIInput.make(form, "question-multiplechoice-answer-id", null);
UIBoundBoolean.make(form, "question-multiplechoice-answer-correct");
UIInput.make(form, "question-multiplechoice-answer", null);
UIBoundBoolean.make(form, "question-show-poll", "#{simplePageBean.questionShowPoll}");
UIInput.make(form, "question-correct-text", "#{simplePageBean.questionCorrectText}");
UIInput.make(form, "question-incorrect-text", "#{simplePageBean.questionIncorrectText}");
UICommand.make(form, "delete-question-item", messageLocator.getMessage("simplepage.delete"), "#{simplePageBean.deleteItem}");
UICommand.make(form, "update-question", messageLocator.getMessage("simplepage.edit"), "#{simplePageBean.updateQuestion}");
UICommand.make(form, "cancel-question", messageLocator.getMessage("simplepage.cancel"), null);
}
/*
* return true if the item is required and not completed, i.e. if we need to
* update the status after the user views the item
*/
private Status handleStatusImage(UIContainer container, SimplePageItem i) {
if (i.getType() != SimplePageItem.TEXT && i.getType() != SimplePageItem.MULTIMEDIA) {
if (!i.isRequired()) {
addStatusImage(Status.NOT_REQUIRED, container, "status", i.getName());
return Status.NOT_REQUIRED;
} else if (simplePageBean.isItemComplete(i)) {
addStatusImage(Status.COMPLETED, container, "status", i.getName());
return Status.COMPLETED;
} else {
addStatusImage(Status.REQUIRED, container, "status", i.getName());
return Status.REQUIRED;
}
}
return Status.NOT_REQUIRED;
}
/**
* Returns a Status object with the status of a user's response to a question.
* For showing status images next to the question.
*/
private Status getQuestionStatus(SimplePageItem question, SimplePageQuestionResponse response) {
String questionType = question.getAttribute("questionType");
boolean noSpecifiedAnswers = false;
boolean manuallyGraded = false;
if ("multipleChoice".equals(questionType) &&
!simplePageToolDao.hasCorrectAnswer(question))
noSpecifiedAnswers = true;
else if ("shortanswer".equals(questionType) &&
"".equals(question.getAttribute("questionAnswer")))
noSpecifiedAnswers = true;
if (noSpecifiedAnswers && "true".equals(question.getAttribute("questionGraded")))
manuallyGraded = true;
if (noSpecifiedAnswers && !manuallyGraded) {
// poll. should we show completed if not required? Don't for
// other item types, but here there's no separate tool where you
// can look at the status. I'm currently showing completed, to
// be consistent with non-polls, where I always show a result
if (response != null)
return Status.COMPLETED;
if(question.isRequired())
return Status.REQUIRED;
return Status.NOT_REQUIRED;
}
if (manuallyGraded && (response != null && !response.isOverridden())) {
return Status.NEEDSGRADING;
} else if (response != null && response.isCorrect()) {
return Status.COMPLETED;
} else if (response != null && !response.isCorrect()) {
return Status.FAILED;
}else if(question.isRequired()) {
return Status.REQUIRED;
}else {
return Status.NOT_REQUIRED;
}
}
String getStatusNote(Status status) {
if (status == Status.COMPLETED)
return messageLocator.getMessage("simplepage.status.completed");
else if (status == Status.REQUIRED)
return messageLocator.getMessage("simplepage.status.required");
else if (status == Status.NEEDSGRADING)
return messageLocator.getMessage("simplepage.status.needsgrading");
else if (status == Status.FAILED)
return messageLocator.getMessage("simplepage.status.failed");
else
return null;
}
// add the checkmark or asterisk. This code supports a couple of other
// statuses that we
// never ended up using
private void addStatusImage(Status status, UIContainer container, String imageId, String name) {
String imagePath = "/lessonbuilder-tool/images/";
String imageAlt = "";
// better not to include alt or title. Bundle them with the link. Avoids
// complexity for screen reader
if (status == Status.COMPLETED) {
imagePath += "checkmark.png";
imageAlt = ""; // messageLocator.getMessage("simplepage.status.completed")
// + " " + name;
} else if (status == Status.DISABLED) {
imagePath += "unavailable.png";
imageAlt = ""; // messageLocator.getMessage("simplepage.status.disabled")
// + " " + name;
} else if (status == Status.FAILED) {
imagePath += "failed.png";
imageAlt = ""; // messageLocator.getMessage("simplepage.status.failed")
// + " " + name;
} else if (status == Status.REQUIRED) {
imagePath += "available.png";
imageAlt = ""; // messageLocator.getMessage("simplepage.status.required")
// + " " + name;
} else if (status == Status.NEEDSGRADING) {
imagePath += "blue-question.png";
imageAlt = ""; // messageLocator.getMessage("simplepage.status.required")
// + " " + name;
} else if (status == Status.NOT_REQUIRED) {
imagePath += "not-required.png";
// it's a blank image, no need for screen readers to say anything
imageAlt = ""; // messageLocator.getMessage("simplepage.status.notrequired");
}
UIOutput.make(container, "status-td");
UIOutput.make(container, imageId).decorate(new UIFreeAttributeDecorator("src", imagePath))
.decorate(new UIFreeAttributeDecorator("alt", imageAlt)).decorate(new UITooltipDecorator(imageAlt));
}
private String getLocalizedURL(String fileName) {
if (fileName == null || fileName.trim().length() == 0)
return fileName;
else {
fileName = fileName.trim();
}
Locale locale = new ResourceLoader().getLocale();
String helploc = ServerConfigurationService.getString("lessonbuilder.helpfolder", null);
// we need to test the localized URL and return the initial one if it
// doesn't exists
// defaultPath will be the one to use if the localized one doesn't exist
String defaultPath = null;
// this is the part up to where we add the locale
String prefix = null;
// this is the part after the locale
String suffix = null;
// this is an additional prefix needed to make a full URL, for testing
String testPrefix = null;
int suffixIndex = fileName.lastIndexOf(".");
if (suffixIndex >= 0) {
prefix = fileName.substring(0, suffixIndex);
suffix = fileName.substring(suffixIndex);
} else {
prefix = fileName;
suffix = "";
}
// if user specified, we make up an absolute URL
// otherwise use one relative to the servlet context
if (helploc != null) {
// user has specified a base URL. Will be absolute, but may not have
// http and hostname
defaultPath = helploc + fileName;
prefix = helploc + prefix;
if (helploc.startsWith("http:") || helploc.startsWith("https:")) {
testPrefix = ""; // absolute, can test as is
} else {
testPrefix = myUrl(); // relative, need to make absolute
}
} else {
// actual URL will be related to templates
defaultPath = "/lessonbuilder-tool/templates/instructions/" + fileName;
prefix = "/lessonbuilder-tool/templates/instructions/" + prefix;
// but have to test relative to servlet base
testPrefix = ""; // urlok will have to remove /lessonbuilder-tool
}
String[] localeDetails = locale.toString().split("_");
int localeSize = localeDetails.length;
String filePath = null;
String localizedPath = null;
if (localeSize > 2) {
localizedPath = prefix + "_" + locale.toString() + suffix;
filePath = testPrefix + localizedPath;
if (UrlOk(filePath))
return localizedPath;
}
if (localeSize > 1) {
localizedPath = prefix + "_" + locale.getLanguage() + "_" + locale.getCountry() + suffix;
filePath = testPrefix + localizedPath;
if (UrlOk(filePath))
return localizedPath;
}
if (localeSize > 0) {
localizedPath = prefix + "_" + locale.getLanguage() + suffix;
filePath = testPrefix + localizedPath;
if (UrlOk(filePath))
return localizedPath;
}
return defaultPath;
}
// this can be either a fully specified URL starting with http: or https:
// or something relative to the servlet base, e.g. /lessonbuilder-tool/template/instructions/general.html
private boolean UrlOk(String url) {
Boolean cached = (Boolean) urlCache.get(url);
if (cached != null)
return (boolean) cached;
if (url.startsWith("http:") || url.startsWith("https:")) {
// actual URL, check it out
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("HEAD");
con.setConnectTimeout(30 * 1000);
boolean ret = (con.getResponseCode() == HttpURLConnection.HTTP_OK);
urlCache.put(url, (Boolean) ret);
return ret;
} catch (java.net.SocketTimeoutException e) {
log.error("Internationalization url lookup timed out for " + url + ": Please check lessonbuilder.helpfolder. It appears that the host specified is not responding.");
urlCache.put(url, (Boolean) false);
return false;
} catch (ProtocolException e) {
urlCache.put(url, (Boolean) false);
return false;
} catch (IOException e) {
urlCache.put(url, (Boolean) false);
return false;
}
} else {
// remove the leading /lessonbuilder-tool, since getresource is
// relative to the top of the servlet
int i = url.indexOf("/", 1);
url = url.substring(i);
try {
// inside the war file, check the file system. That avoid issues
// with odd deployments behind load balancers, where the user's URL may not
// work from one of the front ends
if (httpServletRequest.getSession().getServletContext().getResource(url) == null) {
urlCache.put(url, (Boolean) false);
return false;
} else {
urlCache.put(url, (Boolean) true);
return true;
}
} catch (Exception e) { // probably malfformed url
log.error("Internationalization url lookup failed for " + url + ": " + e);
urlCache.put(url, (Boolean) true);
return true;
}
}
}
private long findMostRecentComment() {
List<SimplePageComment> comments = simplePageToolDao.findCommentsOnPageByAuthor(simplePageBean.getCurrentPage().getPageId(), UserDirectoryService.getCurrentUser().getId());
Collections.sort(comments, new Comparator<SimplePageComment>() {
public int compare(SimplePageComment c1, SimplePageComment c2) {
return c1.getTimePosted().compareTo(c2.getTimePosted());
}
});
if (comments.size() > 0)
return comments.get(comments.size() - 1).getId();
else
return -1;
}
private boolean printedGradingForm = false;
private void printGradingForm(UIContainer tofill) {
// Ajax grading form so faculty can grade comments
if(!printedGradingForm) {
UIForm gradingForm = UIForm.make(tofill, "gradingForm");
gradingForm.viewparams = new SimpleViewParameters(UVBProducer.VIEW_ID);
UIInput idInput = UIInput.make(gradingForm, "gradingForm-id", "gradingBean.id");
UIInput jsIdInput = UIInput.make(gradingForm, "gradingForm-jsId", "gradingBean.jsId");
UIInput pointsInput = UIInput.make(gradingForm, "gradingForm-points", "gradingBean.points");
UIInput typeInput = UIInput.make(gradingForm, "gradingForm-type", "gradingBean.type");
UIInitBlock.make(tofill, "gradingForm-init", "initGradingForm", new Object[] {idInput, pointsInput, jsIdInput, typeInput, "gradingBean.results"});
printedGradingForm = true;
}
}
private static String getItemPath(SimplePageItem i)
{
String itemPath = "";
boolean isURL = false;
String pathId = i.getType() == SimplePageItem.MULTIMEDIA ? "path-url":"path-url";
String[] itemPathTokens = i.getSakaiId().split("/");
for(int tokenIndex=3 ; tokenIndex < itemPathTokens.length ; tokenIndex++)
{
if(isURL)
{
itemPath+= "/<a target=\"_blank\" href=\"\" class=\"" + URLEncoder.encode(pathId) + "\">" + FormattedText.escapeHtml(itemPathTokens[tokenIndex],false) + "</a>";
isURL = false;
}
else
itemPath+="/" + FormattedText.escapeHtml(itemPathTokens[tokenIndex],false);
isURL = itemPathTokens[tokenIndex].equals("urls") ? true: false;
}
return itemPath;
}
//Output rubric data for a Student Content box.
private String[] makeStudentRubric = {"peer-eval-title-student", "peer-eval-row-student:", "peerReviewIdStudent", "peerReviewTextStudent"};
private String[] makeMaintainRubric = {"peer-eval-title", "peer-eval-row:", "peerReviewId", "peerReviewText"};
private void makePeerRubric(UIContainer parent, SimplePageItem i, String[] peerReviewRsfIds)
{
//System.out.println("makePeerRubric(): i.getAttributesString() " + i.getAttributeString());
//System.out.println("makePeerRubric(): i.getAttribute(\"rubricTitle\") " + i.getAttribute("rubricTitle"));
//System.out.println("makePeerRubric(): i.getJsonAttribute(\"rows\") " + i.getJsonAttribute("rows"));
UIOutput.make(parent, peerReviewRsfIds[0], String.valueOf(i.getAttribute("rubricTitle")));
class RubricRow implements Comparable{
public int id;
public String text;
public RubricRow(int id, String text){ this.id=id; this.text=text;}
public int compareTo(Object o){
RubricRow r = (RubricRow)o;
if(id==r.id)
return 0;
if(id>r.id)
return 1;
return -1;
}
}
ArrayList<RubricRow> rows = new ArrayList<RubricRow>();
List categories = (List) i.getJsonAttribute("rows");
if(categories != null){
for(Object o: categories){
Map cat = (Map)o;
rows.add(new RubricRow(Integer.parseInt(String.valueOf(cat.get("id"))), String.valueOf(cat.get("rowText"))));
}
}
//else{System.out.println("This rubric has no rows.");}
Collections.sort(rows);
for(RubricRow row : rows){
UIBranchContainer peerReviewRows = UIBranchContainer.make(parent, peerReviewRsfIds[1]);
UIOutput.make(peerReviewRows, peerReviewRsfIds[2], String.valueOf(row.id));
UIOutput.make(peerReviewRows, peerReviewRsfIds[3], row.text);
}
}
private void makeSamplePeerEval(UIContainer parent)
{
UIOutput.make(parent, "peer-eval-sample-title", "Sample Peer Evaluation");
UIBranchContainer peerReviewRows = UIBranchContainer.make(parent, "peer-eval-sample-data:");
UIOutput.make(peerReviewRows, "peer-eval-sample-id", "1");
UIOutput.make(peerReviewRows, "peer-eval-sample-text", messageLocator.getMessage("simplepage.peer-eval.sample.1"));
peerReviewRows = UIBranchContainer.make(parent, "peer-eval-sample-data:");
UIOutput.make(peerReviewRows, "peer-eval-sample-id", "2");
UIOutput.make(peerReviewRows, "peer-eval-sample-text", messageLocator.getMessage("simplepage.peer-eval.sample.2"));
peerReviewRows = UIBranchContainer.make(parent, "peer-eval-sample-data:");
UIOutput.make(peerReviewRows, "peer-eval-sample-id", "3");
UIOutput.make(peerReviewRows, "peer-eval-sample-text", messageLocator.getMessage("simplepage.peer-eval.sample.3"));
peerReviewRows = UIBranchContainer.make(parent, "peer-eval-sample-data:");
UIOutput.make(peerReviewRows, "peer-eval-sample-id", "4");
UIOutput.make(peerReviewRows, "peer-eval-sample-text", messageLocator.getMessage("simplepage.peer-eval.sample.4"));
}
}
| true | true | public void fillComponents(UIContainer tofill, ViewParameters viewParams, ComponentChecker checker) {
GeneralViewParameters params = (GeneralViewParameters) viewParams;
UIOutput.make(tofill, "html").decorate(new UIFreeAttributeDecorator("lang", localegetter.get().getLanguage()))
.decorate(new UIFreeAttributeDecorator("xml:lang", localegetter.get().getLanguage()));
boolean iframeJavascriptDone = false;
// security model:
// canEditPage and canReadPage are normal Sakai privileges. They apply
// to all
// pages in the site.
// However when presented with a page, we need to make sure it's
// actually in
// this site, or users could get to pages in other sites. That's done
// by updatePageObject. The model is that producers always work on the
// current page, and updatePageObject makes sure that is in the current
// site.
// At that point we can safely use canEditPage.
// somewhat misleading. sendingPage specifies the page we're supposed to
// go to. If path is "none", we don't want this page to be what we see
// when we come back to the tool
if (params.getSendingPage() != -1) {
// will fail if page not in this site
// security then depends upon making sure that we only deal with
// this page
try {
simplePageBean.updatePageObject(params.getSendingPage(), !params.getPath().equals("none"));
} catch (Exception e) {
log.warn("ShowPage permission exception " + e);
UIOutput.make(tofill, "error-div");
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.not_available"));
return;
}
}
boolean canEditPage = simplePageBean.canEditPage();
boolean canReadPage = simplePageBean.canReadPage();
boolean canSeeAll = simplePageBean.canSeeAll(); // always on if caneditpage
boolean cameFromGradingPane = params.getPath().equals("none");
if (!canReadPage) {
// this code is intended for the situation where site permissions
// haven't been set up.
// So if the user can't read the page (which is pretty abnormal),
// see if they have site.upd.
// if so, give them some explanation and offer to call the
// permissions helper
String ref = "/site/" + simplePageBean.getCurrentSiteId();
if (simplePageBean.canEditSite()) {
SimplePage currentPage = simplePageBean.getCurrentPage();
UIOutput.make(tofill, "needPermissions");
GeneralViewParameters permParams = new GeneralViewParameters();
permParams.setSendingPage(-1L);
createStandardToolBarLink(PermissionsHelperProducer.VIEW_ID, tofill, "callpermissions", "simplepage.permissions", permParams, "simplepage.permissions.tooltip");
}
// in any case, tell them they can't read the page
UIOutput.make(tofill, "error-div");
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.nopermissions"));
return;
}
if (params.addTool == GeneralViewParameters.COMMENTS) {
simplePageBean.addCommentsSection();
}else if(params.addTool == GeneralViewParameters.STUDENT_CONTENT) {
simplePageBean.addStudentContentSection();
}else if(params.addTool == GeneralViewParameters.STUDENT_PAGE) {
simplePageBean.createStudentPage(params.studentItemId);
canEditPage = simplePageBean.canEditPage();
}
// Find the MSIE version, if we're running it.
int ieVersion = checkIEVersion();
// as far as I can tell, none of these supports fck or ck
// we can make it configurable if necessary, or use WURFL
// however this test is consistent with CKeditor's check.
// that desireable, since if CKeditor is going to use a bare
// text block, we want to handle it as noEditor
String userAgent = httpServletRequest.getHeader("User-Agent");
if (userAgent == null)
userAgent = "";
boolean noEditor = userAgent.toLowerCase().indexOf("mobile") >= 0;
// set up locale
Locale M_locale = null;
String langLoc[] = localegetter.get().toString().split("_");
if (langLoc.length >= 2) {
if ("en".equals(langLoc[0]) && "ZA".equals(langLoc[1])) {
M_locale = new Locale("en", "GB");
} else {
M_locale = new Locale(langLoc[0], langLoc[1]);
}
} else {
M_locale = new Locale(langLoc[0]);
}
// clear session attribute if necessary, after calling Samigo
String clearAttr = params.getClearAttr();
if (clearAttr != null && !clearAttr.equals("")) {
Session session = SessionManager.getCurrentSession();
// don't let users clear random attributes
if (clearAttr.startsWith("LESSONBUILDER_RETURNURL")) {
session.setAttribute(clearAttr, null);
}
}
if (htmlTypes == null) {
String mmTypes = ServerConfigurationService.getString("lessonbuilder.html.types", DEFAULT_HTML_TYPES);
htmlTypes = mmTypes.split(",");
for (int i = 0; i < htmlTypes.length; i++) {
htmlTypes[i] = htmlTypes[i].trim().toLowerCase();
}
Arrays.sort(htmlTypes);
}
if (mp4Types == null) {
String m4Types = ServerConfigurationService.getString("lessonbuilder.mp4.types", DEFAULT_MP4_TYPES);
mp4Types = m4Types.split(",");
for (int i = 0; i < mp4Types.length; i++) {
mp4Types[i] = mp4Types[i].trim().toLowerCase();
}
Arrays.sort(mp4Types);
}
if (html5Types == null) {
String jTypes = ServerConfigurationService.getString("lessonbuilder.html5.types", DEFAULT_HTML5_TYPES);
html5Types = jTypes.split(",");
for (int i = 0; i < html5Types.length; i++) {
html5Types[i] = html5Types[i].trim().toLowerCase();
}
Arrays.sort(html5Types);
}
// remember that page tool was reset, so we need to give user the option
// of going to the last page from the previous session
SimplePageToolDao.PageData lastPage = simplePageBean.toolWasReset();
// if this page was copied from another site we may have to update links
// can only do the fixups if you can write. We could hack permissions, but
// I assume a site owner will access the site first
if (canEditPage)
simplePageBean.maybeUpdateLinks();
// if starting the tool, sendingpage isn't set. the following call
// will give us the top page.
SimplePage currentPage = simplePageBean.getCurrentPage();
// now we need to find our own item, for access checks, etc.
SimplePageItem pageItem = null;
if (currentPage != null) {
pageItem = simplePageBean.getCurrentPageItem(params.getItemId());
}
// one more security check: make sure the item actually involves this
// page.
// otherwise someone could pass us an item from a different page in
// another site
// actually this normally happens if the page doesn't exist and we don't
// have permission to create it
if (currentPage == null || pageItem == null ||
(pageItem.getType() != SimplePageItem.STUDENT_CONTENT &&Long.valueOf(pageItem.getSakaiId()) != currentPage.getPageId())) {
log.warn("ShowPage item not in page");
UIOutput.make(tofill, "error-div");
if (currentPage == null)
// most likely tool was created by site info but no page
// has created. It will created the first time an item is created,
// so from a user point of view it looks like no item has been added
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.noitems_error_user"));
else
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.not_available"));
return;
}
// check two parts of isitemvisible where we want to give specific errors
// potentially need time zone for setting release date
if (!canSeeAll && currentPage.getReleaseDate() != null && currentPage.getReleaseDate().after(new Date())) {
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, M_locale);
TimeZone tz = timeService.getLocalTimeZone();
df.setTimeZone(tz);
String releaseDate = df.format(currentPage.getReleaseDate());
String releaseMessage = messageLocator.getMessage("simplepage.not_yet_available_releasedate").replace("{}", releaseDate);
UIOutput.make(tofill, "error-div");
UIOutput.make(tofill, "error", releaseMessage);
return;
}
// the only thing not already tested in isItemVisible is groups. In theory
// no one should have a URL to a page for which they aren't in the group,
// so I'm not trying to give a better message than just hidden
if (!canSeeAll && currentPage.isHidden() || !simplePageBean.isItemVisible(pageItem)) {
UIOutput.make(tofill, "error-div");
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.not_available_hidden"));
return;
}
// I believe we've now checked all the args for permissions issues. All
// other item and
// page references are generated here based on the contents of the page
// and items.
// needed to process path arguments first, so refresh page goes the right page
if (simplePageBean.getTopRefresh()) {
UIOutput.make(tofill, "refresh");
return; // but there's no point doing anything more
}
// error from previous operation
// consumes the message, so don't do it if refreshing
List<String> errMessages = simplePageBean.errMessages();
if (errMessages != null) {
UIOutput.make(tofill, "error-div");
for (String e: errMessages) {
UIBranchContainer er = UIBranchContainer.make(tofill, "errors:");
UIOutput.make(er, "error-message", e);
}
}
if (canEditPage) {
// special instructor-only javascript setup.
// but not if we're refreshing
UIOutput.make(tofill, "instructoronly");
// Chome and IE will abort a page if some on it was input from
// a previous submit. I.e. if an HTML editor was used. In theory they
// only do this if part of it is Javascript, but in practice they do
// it for images as well. The protection isn't worthwhile, since it only
// protects the first time. Since it will reesult in a garbled page,
// people will just refresh the page, and then they'll get the new
// contents. The Chrome guys refuse to fix this so it just applies to Javascript
httpServletResponse.setHeader("X-XSS-Protection", "0");
}
if (currentPage == null || pageItem == null) {
UIOutput.make(tofill, "error-div");
if (canEditPage) {
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.impossible1"));
} else {
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.not_available"));
}
return;
}
// Set up customizable CSS
ContentResource cssLink = simplePageBean.getCssForCurrentPage();
if(cssLink != null) {
UIOutput.make(tofill, "customCSS").decorate(new UIFreeAttributeDecorator("href", cssLink.getUrl()));
}
// offer to go to saved page if this is the start of a session, in case
// user has logged off and logged on again.
// need to offer to go to previous page? even if a new session, no need
// if we're already on that page
if (lastPage != null && lastPage.pageId != currentPage.getPageId()) {
UIOutput.make(tofill, "refreshAlert");
UIOutput.make(tofill, "refresh-message", messageLocator.getMessage("simplepage.last-visited"));
// Should simply refresh
GeneralViewParameters p = new GeneralViewParameters(VIEW_ID);
p.setSendingPage(lastPage.pageId);
p.setItemId(lastPage.itemId);
// reset the path to the saved one
p.setPath("log");
String name = lastPage.name;
// Titles are set oddly by Student Content Pages
SimplePage lastPageObj = simplePageToolDao.getPage(lastPage.pageId);
if(lastPageObj.getOwner() != null) {
name = lastPageObj.getTitle();
}
UIInternalLink.make(tofill, "refresh-link", name, p);
}
// path is the breadcrumbs. Push, pop or reset depending upon path=
// programmer documentation.
String title;
String ownerName = null;
if(pageItem.getType() != SimplePageItem.STUDENT_CONTENT) {
title = pageItem.getName();
}else {
title = currentPage.getTitle();
if(!pageItem.isAnonymous() || canEditPage) {
try {
String owner = currentPage.getOwner();
String group = currentPage.getGroup();
if (group != null)
ownerName = simplePageBean.getCurrentSite().getGroup(group).getTitle();
else
ownerName = UserDirectoryService.getUser(owner).getDisplayName();
} catch (Exception ignore) {};
if (ownerName != null && !ownerName.equals(title))
title += " (" + ownerName + ")";
}
}
String newPath = null;
// If the path is "none", then we don't want to record this page as being viewed, or set a path
if(!params.getPath().equals("none")) {
newPath = simplePageBean.adjustPath(params.getPath(), currentPage.getPageId(), pageItem.getId(), title);
simplePageBean.adjustBackPath(params.getBackPath(), currentPage.getPageId(), pageItem.getId(), pageItem.getName());
}
// put out link to index of pages
GeneralViewParameters showAll = new GeneralViewParameters(PagePickerProducer.VIEW_ID);
showAll.setSource("summary");
UIInternalLink.make(tofill, "show-pages", messageLocator.getMessage("simplepage.showallpages"), showAll);
if (canEditPage) {
// show tool bar, but not if coming from grading pane
if(!cameFromGradingPane) {
createToolBar(tofill, currentPage, (pageItem.getType() == SimplePageItem.STUDENT_CONTENT));
}
UIOutput.make(tofill, "title-descrip");
String label = null;
if (pageItem.getType() == SimplePageItem.STUDENT_CONTENT)
label = messageLocator.getMessage("simplepage.editTitle");
else
label = messageLocator.getMessage("simplepage.title");
String descrip = null;
if (pageItem.getType() == SimplePageItem.STUDENT_CONTENT)
descrip = messageLocator.getMessage("simplepage.title-student-descrip");
else if (pageItem.getPageId() == 0)
descrip = messageLocator.getMessage("simplepage.title-top-descrip");
else
descrip = messageLocator.getMessage("simplepage.title-descrip");
UIOutput.make(tofill, "edit-title").decorate(new UIFreeAttributeDecorator("title", descrip));
UIOutput.make(tofill, "edit-title-text", label);
UIOutput.make(tofill, "title-descrip-text", descrip);
if (pageItem.getPageId() == 0 && currentPage.getOwner() == null) { // top level page
// need dropdown
UIOutput.make(tofill, "dropdown");
UIOutput.make(tofill, "moreDiv");
UIOutput.make(tofill, "new-page").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.new-page-tooltip")));
UIOutput.make(tofill, "import-cc").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.import_cc.tooltip")));
UIOutput.make(tofill, "export-cc").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.export_cc.tooltip")));
}
// Checks to see that user can edit and that this is either a top level page,
// or a top level student page (not a subpage to a student page)
if(simplePageBean.getEditPrivs() == 0 && (pageItem.getPageId() == 0)) {
UIOutput.make(tofill, "remove-li");
UIOutput.make(tofill, "remove-page").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.remove-page-tooltip")));
} else if (simplePageBean.getEditPrivs() == 0 && currentPage.getOwner() != null) {
// getEditPrivs < 2 if we want to let the student delete. Currently we don't. There can be comments
// from other students and the page can be shared
SimpleStudentPage studentPage = simplePageToolDao.findStudentPage(currentPage.getTopParent());
if (studentPage != null && studentPage.getPageId() == currentPage.getPageId()) {
System.out.println("is student page 2");
UIOutput.make(tofill, "remove-student");
UIOutput.make(tofill, "remove-page-student").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.remove-page-tooltip")));
}
}
UIOutput.make(tofill, "dialogDiv");
} else if (!canReadPage) {
return;
} else if (!canSeeAll) {
// see if there are any unsatisfied prerequisites
// if this isn't a top level page, this will check that the page above is
// accessible. That matters because we check visible, available and release
// only for this page but not for the containing page
List<String> needed = simplePageBean.pagesNeeded(pageItem);
if (needed.size() > 0) {
// yes. error and abort
if (pageItem.getPageId() != 0) {
// not top level. This should only happen from a "next"
// link.
// at any rate, the best approach is to send the user back
// to the calling page
List<SimplePageBean.PathEntry> path = simplePageBean.getHierarchy();
SimplePageBean.PathEntry containingPage = null;
if (path.size() > 1) {
// page above this. this page is on the top
containingPage = path.get(path.size() - 2);
}
if (containingPage != null) { // not a top level page, point
// to containing page
GeneralViewParameters view = new GeneralViewParameters(VIEW_ID);
view.setSendingPage(containingPage.pageId);
view.setItemId(containingPage.pageItemId);
view.setPath(Integer.toString(path.size() - 2));
UIInternalLink.make(tofill, "redirect-link", containingPage.title, view);
UIOutput.make(tofill, "redirect");
} else {
UIOutput.make(tofill, "error-div");
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.not_available"));
}
return;
}
// top level page where prereqs not satisified. Output list of
// pages he needs to do first
UIOutput.make(tofill, "pagetitle", currentPage.getTitle());
UIOutput.make(tofill, "error-div");
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.has_prerequistes"));
UIBranchContainer errorList = UIBranchContainer.make(tofill, "error-list:");
for (String errorItem : needed) {
UIBranchContainer errorListItem = UIBranchContainer.make(errorList, "error-item:");
UIOutput.make(errorListItem, "error-item-text", errorItem);
}
return;
}
}
ToolSession toolSession = SessionManager.getCurrentToolSession();
String helpurl = (String)toolSession.getAttribute("sakai-portal:help-action");
String reseturl = (String)toolSession.getAttribute("sakai-portal:reset-action");
String skinName = null;
String skinRepo = null;
String iconBase = null;
UIComponent titlediv = UIOutput.make(tofill, "titlediv");
// we need to do special CSS for old portal
if (helpurl == null)
titlediv.decorate(new UIStyleDecorator("oldPortal"));
if (helpurl != null || reseturl != null) {
// these URLs are defined if we're in the neo portal
// in that case we need our own help and reset icons. We want
// to take them from the current skin, so find its prefix.
// unfortunately the neoportal tacks neo- on front of the skin
// name, so this is more complex than you might think.
skinRepo = ServerConfigurationService.getString("skin.repo", "/library/skin");
iconBase = skinRepo + "/" + CSSUtils.adjustCssSkinFolder(null) + "/images";
UIVerbatim.make(tofill, "iconstyle", ICONSTYLE.replace("{}", iconBase));
}
if (helpurl != null) {
UILink.make(tofill, (pageItem.getPageId() == 0 ? "helpbutton" : "helpbutton2")).
decorate(new UIFreeAttributeDecorator("onclick",
"openWindow('" + helpurl + "', 'Help', 'resizeable=yes,toolbar=no,scrollbars=yes,menubar=yes,width=800,height=600'); return false")).
decorate(new UIFreeAttributeDecorator("title",
messageLocator.getMessage("simplepage.help-button")));
UIOutput.make(tofill, (pageItem.getPageId() == 0 ? "helpimage" : "helpimage2")).
decorate(new UIFreeAttributeDecorator("alt",
messageLocator.getMessage("simplepage.help-button")));
UIOutput.make(tofill, (pageItem.getPageId() == 0 ? "helpnewwindow" : "helpnewwindow2"),
messageLocator.getMessage("simplepage.opens-in-new"));
}
if (reseturl != null) {
UILink.make(tofill, (pageItem.getPageId() == 0 ? "resetbutton" : "resetbutton2")).
decorate(new UIFreeAttributeDecorator("onclick",
"location.href='" + reseturl + "'; return false")).
decorate(new UIFreeAttributeDecorator("title",
messageLocator.getMessage("simplepage.reset-button")));
UIOutput.make(tofill, (pageItem.getPageId() == 0 ? "resetimage" : "resetimage2")).
decorate(new UIFreeAttributeDecorator("alt",
messageLocator.getMessage("simplepage.reset-button")));
}
// note page accessed. the code checks to see whether all the required
// items on it have been finished, and if so marks it complete, else just updates
// access date save the path because if user goes to it later we want to restore the
// breadcrumbs
if(newPath != null) {
if(pageItem.getType() != SimplePageItem.STUDENT_CONTENT) {
simplePageBean.track(pageItem.getId(), newPath);
}else {
simplePageBean.track(pageItem.getId(), newPath, currentPage.getPageId());
}
}
UIOutput.make(tofill, "pagetitle", currentPage.getTitle());
if(currentPage.getOwner() != null && simplePageBean.getEditPrivs() == 0) {
SimpleStudentPage student = simplePageToolDao.findStudentPageByPageId(currentPage.getPageId());
// Make sure this is a top level student page
if(student != null && pageItem.getGradebookId() != null) {
UIOutput.make(tofill, "gradingSpan");
UIOutput.make(tofill, "commentsUUID", String.valueOf(student.getId()));
UIOutput.make(tofill, "commentPoints", String.valueOf((student.getPoints() != null? student.getPoints() : "")));
UIOutput pointsBox = UIOutput.make(tofill, "studentPointsBox");
UIOutput.make(tofill, "topmaxpoints", String.valueOf((pageItem.getGradebookPoints() != null? pageItem.getGradebookPoints():"")));
if (ownerName != null)
pointsBox.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.grade-for-student").replace("{}",ownerName)));
List<SimpleStudentPage> studentPages = simplePageToolDao.findStudentPages(student.getItemId());
Collections.sort(studentPages, new Comparator<SimpleStudentPage>() {
public int compare(SimpleStudentPage o1, SimpleStudentPage o2) {
String title1 = o1.getTitle();
if (title1 == null)
title1 = "";
String title2 = o2.getTitle();
if (title2 == null)
title2 = "";
return title1.compareTo(title2);
}
});
for(int in = 0; in < studentPages.size(); in++) {
if(studentPages.get(in).isDeleted()) {
studentPages.remove(in);
}
}
int i = -1;
for(int in = 0; in < studentPages.size(); in++) {
if(student.getId() == studentPages.get(in).getId()) {
i = in;
break;
}
}
if(i > 0) {
GeneralViewParameters eParams = new GeneralViewParameters(ShowPageProducer.VIEW_ID, studentPages.get(i-1).getPageId());
eParams.setItemId(studentPages.get(i-1).getItemId());
eParams.setPath("next");
UIInternalLink.make(tofill, "gradingBack", eParams);
}
if(i < studentPages.size() - 1) {
GeneralViewParameters eParams = new GeneralViewParameters(ShowPageProducer.VIEW_ID, studentPages.get(i+1).getPageId());
eParams.setItemId(studentPages.get(i+1).getItemId());
eParams.setPath("next");
UIInternalLink.make(tofill, "gradingForward", eParams);
}
printGradingForm(tofill);
}
}
// breadcrumbs
if (pageItem.getPageId() != 0) {
// Not top-level, so we have to show breadcrumbs
List<SimplePageBean.PathEntry> breadcrumbs = simplePageBean.getHierarchy();
int index = 0;
if (breadcrumbs.size() > 1 || reseturl != null || helpurl != null) {
UIOutput.make(tofill, "crumbdiv");
if (breadcrumbs.size() > 1)
for (SimplePageBean.PathEntry e : breadcrumbs) {
// don't show current page. We already have a title. This
// was too much
UIBranchContainer crumb = UIBranchContainer.make(tofill, "crumb:");
GeneralViewParameters view = new GeneralViewParameters(VIEW_ID);
view.setSendingPage(e.pageId);
view.setItemId(e.pageItemId);
view.setPath(Integer.toString(index));
if (index < breadcrumbs.size() - 1) {
// Not the last item
UIInternalLink.make(crumb, "crumb-link", e.title, view);
UIOutput.make(crumb, "crumb-follow", " > ");
} else {
UIOutput.make(crumb, "crumb-follow", e.title).decorate(new UIStyleDecorator("bold"));
}
index++;
}
}
}
// see if there's a next item in sequence.
simplePageBean.addPrevLink(tofill, pageItem);
simplePageBean.addNextLink(tofill, pageItem);
// swfObject is not currently used
boolean shownSwfObject = false;
// items to show
List<SimplePageItem> itemList = (List<SimplePageItem>) simplePageBean.getItemsOnPage(currentPage.getPageId());
// Move all items with sequence <= 0 to the end of the list.
// Count is necessary to guarantee we don't infinite loop over a
// list that only has items with sequence <= 0.
// Becauses sequence number is < 0, these start out at the beginning
int count = 1;
while(itemList.size() > count && itemList.get(0).getSequence() <= 0) {
itemList.add(itemList.remove(0));
count++;
}
// Make sure we only add the comments javascript file once,
// even if there are multiple comments tools on the page.
boolean addedCommentsScript = false;
int commentsCount = 0;
// Find the most recent comment on the page by current user
long postedCommentId = -1;
if (params.postedComment) {
postedCommentId = findMostRecentComment();
}
//
//
// MAIN list of items
//
// produce the main table
// Is anything visible?
// Note that we don't need to check whether any item is available, since the first visible
// item is always available.
boolean anyItemVisible = false;
if (itemList.size() > 0) {
UIBranchContainer container = UIBranchContainer.make(tofill, "itemContainer:");
boolean showRefresh = false;
int textboxcount = 1;
UIBranchContainer tableContainer = UIBranchContainer.make(container, "itemTable:");
// formatting: two columns:
// 1: edit buttons, omitted for student
// 2: main content
// For links, which have status icons, the main content is a flush
// left div with the icon
// followed by a div with margin-left:30px. That takes it beyond the
// icon, and avoids the
// wrap-around appearance you'd get without the margin.
// Normally the description is shown as a second div with
// indentation in the CSS.
// That puts it below the link. However with a link that's a button,
// we do float left
// for the button so the text wraps around it. I think that's
// probably what people would expect.
UIOutput.make(tableContainer, "colgroup");
if (canEditPage) {
UIOutput.make(tableContainer, "col1");
}
UIOutput.make(tableContainer, "col2");
// our accessiblity people say not to use TH for except for a data table
// the table header is for accessibility tools only, so it's
// positioned off screen
//if (canEditPage) {
// UIOutput.make(tableContainer, "header-edits");
// }
// UIOutput.make(tableContainer, "header-items");
for (SimplePageItem i : itemList) {
// listitem is mostly historical. it uses some shared HTML, but
// if I were
// doing it from scratch I wouldn't make this distinction. At
// the moment it's
// everything that isn't inline.
boolean listItem = !(i.getType() == SimplePageItem.TEXT || i.getType() == SimplePageItem.MULTIMEDIA
|| i.getType() == SimplePageItem.COMMENTS || i.getType() == SimplePageItem.STUDENT_CONTENT
|| i.getType() == SimplePageItem.QUESTION || i.getType() == SimplePageItem.PEEREVAL);
// (i.getType() == SimplePageItem.PAGE &&
// "button".equals(i.getFormat())))
if (!simplePageBean.isItemVisible(i, currentPage)) {
continue;
}
anyItemVisible = true;
UIBranchContainer tableRow = UIBranchContainer.make(tableContainer, "item:");
// set class name showing what the type is, so people can do funky CSS
String itemClassName = null;
switch (i.getType()) {
case SimplePageItem.RESOURCE: itemClassName = "resourceType"; break;
case SimplePageItem.PAGE: itemClassName = "pageType"; break;
case SimplePageItem.ASSIGNMENT: itemClassName = "assignmentType"; break;
case SimplePageItem.ASSESSMENT: itemClassName = "assessmentType"; break;
case SimplePageItem.TEXT: itemClassName = "textType"; break;
case SimplePageItem.URL: itemClassName = "urlType"; break;
case SimplePageItem.MULTIMEDIA: itemClassName = "multimediaType"; break;
case SimplePageItem.FORUM: itemClassName = "forumType"; break;
case SimplePageItem.COMMENTS: itemClassName = "commentsType"; break;
case SimplePageItem.STUDENT_CONTENT: itemClassName = "studentContentType"; break;
case SimplePageItem.QUESTION: itemClassName = "question"; break;
case SimplePageItem.BLTI: itemClassName = "bltiType"; break;
case SimplePageItem.PEEREVAL: itemClassName = "peereval"; break;
}
if (listItem){
itemClassName = itemClassName + " listType";
}
if (canEditPage) {
itemClassName = itemClassName + " canEdit";
}
tableRow.decorate(new UIFreeAttributeDecorator("class", itemClassName));
// you really need the HTML file open at the same time to make
// sense of the following code
if (listItem) { // Not an HTML Text, Element or Multimedia
// Element
if (canEditPage) {
UIOutput.make(tableRow, "current-item-id2", String.valueOf(i.getId()));
}
// users can declare a page item to be navigational. If so
// we display
// it to the left of the normal list items, and use a
// button. This is
// used for pages that are "next" pages, i.e. they replace
// this page
// rather than creating a new level in the breadcrumbs.
// Since they can't
// be required, they don't need the status image, which is
// good because
// they're displayed with colspan=2, so there's no space for
// the image.
boolean navButton = "button".equals(i.getFormat()) && !i.isRequired();
boolean notDone = false;
Status status = Status.NOT_REQUIRED;
if (!navButton) {
status = handleStatusImage(tableRow, i);
if (status == Status.REQUIRED) {
notDone = true;
}
}
boolean isInline = (i.getType() == SimplePageItem.BLTI && "inline".equals(i.getFormat()));
UIOutput linktd = UIOutput.make(tableRow, "item-td");
UIBranchContainer linkdiv = null;
if (!isInline) {
linkdiv = UIBranchContainer.make(tableRow, "link-div:");
UIOutput itemicon = UIOutput.make(linkdiv,"item-icon");
switch (i.getType()) {
case SimplePageItem.FORUM:
itemicon.decorate(new UIFreeAttributeDecorator("src", "/library/image/silk/comments.png"));
break;
case SimplePageItem.ASSIGNMENT:
itemicon.decorate(new UIFreeAttributeDecorator("src", "/library/image/silk/page_edit.png"));
break;
case SimplePageItem.ASSESSMENT:
itemicon.decorate(new UIFreeAttributeDecorator("src", "/library/image/silk/pencil.png"));
break;
case SimplePageItem.BLTI:
itemicon.decorate(new UIFreeAttributeDecorator("src", "/library/image/silk/application_go.png"));
break;
case SimplePageItem.PAGE:
itemicon.decorate(new UIFreeAttributeDecorator("src", "/library/image/silk/book_open.png"));
break;
case SimplePageItem.RESOURCE:
String mimeType = i.getHtml();
if("application/octet-stream".equals(mimeType)) {
// OS X reports octet stream for things like MS Excel documents.
// Force a mimeType lookup so we get a decent icon.
mimeType = null;
}
if (mimeType == null || mimeType.equals("")) {
String s = i.getSakaiId();
int j = s.lastIndexOf(".");
if (j >= 0)
s = s.substring(j+1);
mimeType = ContentTypeImageService.getContentType(s);
// System.out.println("type " + s + ">" + mimeType);
}
String src = null;
if (!useSakaiIcons)
src = imageToMimeMap.get(mimeType);
if (src == null) {
String image = ContentTypeImageService.getContentTypeImage(mimeType);
if (image != null)
src = "/library/image/" + image;
}
if(src != null) {
itemicon.decorate(new UIFreeAttributeDecorator("src", src));
}
break;
}
}
UIOutput descriptiondiv = null;
// refresh isn't actually used anymore. We've changed the
// way things are
// done so the user never has to request a refresh.
// FYI: this actually puts in an IFRAME for inline BLTI items
showRefresh = !makeLink(tableRow, "link", i, canSeeAll, currentPage, notDone, status) || showRefresh;
UILink.make(tableRow, "copylink", i.getName(), "http://lessonbuilder.sakaiproject.org/" + i.getId() + "/").
decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.copylink2").replace("{}", i.getName())));
// dummy is used when an assignment, quiz, or forum item is
// copied
// from another site. The way the copy code works, our
// import code
// doesn't have access to the necessary info to use the item
// from the
// new site. So we add a dummy, which generates an
// explanation that the
// author is going to have to choose the item from the
// current site
if (i.getSakaiId().equals(SimplePageItem.DUMMY)) {
String code = null;
switch (i.getType()) {
case SimplePageItem.ASSIGNMENT:
code = "simplepage.copied.assignment";
break;
case SimplePageItem.ASSESSMENT:
code = "simplepage.copied.assessment";
break;
case SimplePageItem.FORUM:
code = "simplepage.copied.forum";
break;
}
descriptiondiv = UIOutput.make(tableRow, "description", messageLocator.getMessage(code));
} else {
descriptiondiv = UIOutput.make(tableRow, "description", i.getDescription());
}
if (isInline)
descriptiondiv.decorate(new UIFreeAttributeDecorator("style", "margin-top: 4px"));
if (!isInline) {
// nav button gets float left so any description goes to its
// right. Otherwise the
// description block will display underneath
if ("button".equals(i.getFormat())) {
linkdiv.decorate(new UIFreeAttributeDecorator("style", "float:none"));
}
// for accessibility
if (navButton) {
linkdiv.decorate(new UIFreeAttributeDecorator("role", "navigation"));
}
}
// note that a lot of the info here is used by the
// javascript that prepares
// the jQuery dialogs
if (canEditPage) {
UIOutput.make(tableRow, "edit-td");
UILink.make(tableRow, "edit-link", messageLocator.getMessage("simplepage.editItem"), "").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.generic").replace("{}", i.getName())));
// the following information is displayed using <INPUT
// type=hidden ...
// it contains information needed to populate the "edit"
// popup dialog
UIOutput.make(tableRow, "prerequisite-info", String.valueOf(i.isPrerequisite()));
String itemGroupString = null;
boolean entityDeleted = false;
boolean notPublished = false;
if (i.getType() == SimplePageItem.ASSIGNMENT) {
// the type indicates whether scoring is letter
// grade, number, etc.
// the javascript needs this to present the right
// choices to the user
// types 6 and 8 aren't legal scoring types, so they
// are used as
// markers for quiz or forum. I ran out of numbers
// and started using
// text for things that aren't scoring types. That's
// better anyway
int type = 4;
LessonEntity assignment = null;
if (!i.getSakaiId().equals(SimplePageItem.DUMMY)) {
assignment = assignmentEntity.getEntity(i.getSakaiId(), simplePageBean);
if (assignment != null) {
type = assignment.getTypeOfGrade();
String editUrl = assignment.editItemUrl(simplePageBean);
if (editUrl != null) {
UIOutput.make(tableRow, "edit-url", editUrl);
}
itemGroupString = simplePageBean.getItemGroupString(i, assignment, true);
UIOutput.make(tableRow, "item-groups", itemGroupString);
if (!assignment.objectExists())
entityDeleted = true;
}
}
UIOutput.make(tableRow, "type", String.valueOf(type));
String requirement = String.valueOf(i.getSubrequirement());
if ((type == SimplePageItem.PAGE || type == SimplePageItem.ASSIGNMENT) && i.getSubrequirement()) {
requirement = i.getRequirementText();
}
UIOutput.make(tableRow, "requirement-text", requirement);
} else if (i.getType() == SimplePageItem.ASSESSMENT) {
UIOutput.make(tableRow, "type", "6"); // Not used by
// assignments,
// so it is
// safe to dedicate to assessments
UIOutput.make(tableRow, "requirement-text", (i.getSubrequirement() ? i.getRequirementText() : "false"));
LessonEntity quiz = quizEntity.getEntity(i.getSakaiId(),simplePageBean);
if (quiz != null) {
String editUrl = quiz.editItemUrl(simplePageBean);
if (editUrl != null) {
UIOutput.make(tableRow, "edit-url", editUrl);
}
editUrl = quiz.editItemSettingsUrl(simplePageBean);
if (editUrl != null) {
UIOutput.make(tableRow, "edit-settings-url", editUrl);
}
itemGroupString = simplePageBean.getItemGroupString(i, quiz, true);
UIOutput.make(tableRow, "item-groups", itemGroupString);
if (!quiz.objectExists())
entityDeleted = true;
} else
notPublished = quizEntity.notPublished(i.getSakaiId());
} else if (i.getType() == SimplePageItem.BLTI) {
UIOutput.make(tableRow, "type", "b");
LessonEntity blti= (bltiEntity == null ? null : bltiEntity.getEntity(i.getSakaiId()));
if (blti != null) {
String editUrl = blti.editItemUrl(simplePageBean);
if (editUrl != null)
UIOutput.make(tableRow, "edit-url", editUrl);
UIOutput.make(tableRow, "item-format", i.getFormat());
if (i.getHeight() != null)
UIOutput.make(tableRow, "item-height", i.getHeight());
itemGroupString = simplePageBean.getItemGroupString(i, null, true);
UIOutput.make(tableRow, "item-groups", itemGroupString );
if (!blti.objectExists())
entityDeleted = true;
}
} else if (i.getType() == SimplePageItem.FORUM) {
UIOutput.make(tableRow, "extra-info");
UIOutput.make(tableRow, "type", "8");
LessonEntity forum = forumEntity.getEntity(i.getSakaiId());
if (forum != null) {
String editUrl = forum.editItemUrl(simplePageBean);
if (editUrl != null) {
UIOutput.make(tableRow, "edit-url", editUrl);
}
itemGroupString = simplePageBean.getItemGroupString(i, forum, true);
UIOutput.make(tableRow, "item-groups", itemGroupString);
if (!forum.objectExists())
entityDeleted = true;
}
} else if (i.getType() == SimplePageItem.PAGE) {
UIOutput.make(tableRow, "type", "page");
UIOutput.make(tableRow, "page-next", Boolean.toString(i.getNextPage()));
UIOutput.make(tableRow, "page-button", Boolean.toString("button".equals(i.getFormat())));
itemGroupString = simplePageBean.getItemGroupString(i, null, true);
UIOutput.make(tableRow, "item-groups", itemGroupString);
} else if (i.getType() == SimplePageItem.RESOURCE) {
try {
itemGroupString = simplePageBean.getItemGroupStringOrErr(i, null, true);
} catch (IdUnusedException e) {
itemGroupString = "";
entityDeleted = true;
}
if (simplePageBean.getInherited())
UIOutput.make(tableRow, "item-groups", "--inherited--");
else
UIOutput.make(tableRow, "item-groups", itemGroupString );
UIOutput.make(tableRow, "item-samewindow", Boolean.toString(i.isSameWindow()));
UIVerbatim.make(tableRow, "item-path", getItemPath(i));
}
String releaseString = simplePageBean.getReleaseString(i);
if (itemGroupString != null || releaseString != null || entityDeleted || notPublished) {
if (itemGroupString != null)
itemGroupString = simplePageBean.getItemGroupTitles(itemGroupString, i);
if (itemGroupString != null) {
itemGroupString = " [" + itemGroupString + "]";
if (releaseString != null)
itemGroupString = " " + releaseString + itemGroupString;
} else if (releaseString != null)
itemGroupString = " " + releaseString;
if (notPublished) {
if (itemGroupString != null)
itemGroupString = itemGroupString + " " +
messageLocator.getMessage("simplepage.not-published");
else
itemGroupString = messageLocator.getMessage("simplepage.not-published");
}
if (entityDeleted) {
if (itemGroupString != null)
itemGroupString = itemGroupString + " " +
messageLocator.getMessage("simplepage.deleted-entity");
else
itemGroupString = messageLocator.getMessage("simplepage.deleted-entity");
}
if (itemGroupString != null)
UIOutput.make(tableRow, (isInline ? "item-group-titles-div" : "item-group-titles"), itemGroupString);
}
}
// the following are for the inline item types. Multimedia
// is the most complex because
// it can be IMG, IFRAME, or OBJECT, and Youtube is treated
// separately
} else if (i.getType() == SimplePageItem.MULTIMEDIA) {
// This code should be read together with the code in SimplePageBean
// that sets up this data, method addMultimedia. Most display is set
// up here, but note that show-page.js invokes the jquery oembed on all
// <A> items with class="oembed".
// historically this code was to display files ,and urls leading to things
// like MP4. as backup if we couldn't figure out what to do we'd put something
// in an iframe. The one exception is youtube, which we supposed explicitly.
// However we now support several ways to embed content. We use the
// multimediaDisplayType code to indicate which. The codes are
// 1 -- embed code, 2 -- av type, 3 -- oembed, 4 -- iframe
// 2 is the original code: MP4, image, and as a special case youtube urls
// since we have old entries with no type code, and that behave the same as
// 2, we start by converting 2 to null.
// then the logic is
// if type == null & youtube, do youtube
// if type == null & image, do iamge
// if type == null & not HTML do MP4 or other player for file
// final fallthrough to handel the new types, with IFRAME if all else fails
// the old code creates ojbects in ContentHosting for both files and URLs.
// The new code saves the embed code or URL itself as an atteibute of the item
// If I were doing it again, I wouldn't create the ContebtHosting item
// Note that IFRAME is only used for something where the far end claims the MIME
// type is HTML. For weird stuff like MS Word files I use the file display code, which
// will end up producing <OBJECT>.
// the reason this code is complex is that we try to choose
// the best
// HTML for displaying the particular type of object. We've
// added complexities
// over time as we get more experience with different
// object types and browsers.
String itemGroupString = null;
String itemGroupTitles = null;
boolean entityDeleted = false;
// new format explicit display indication
String mmDisplayType = i.getAttribute("multimediaDisplayType");
// 2 is the generic "use old display" so treat it as null
if ("".equals(mmDisplayType) || "2".equals(mmDisplayType))
mmDisplayType = null;
if (canSeeAll) {
try {
itemGroupString = simplePageBean.getItemGroupStringOrErr(i, null, true);
} catch (IdUnusedException e) {
itemGroupString = "";
entityDeleted = true;
}
itemGroupTitles = simplePageBean.getItemGroupTitles(itemGroupString, i);
if (entityDeleted) {
if (itemGroupTitles != null)
itemGroupTitles = itemGroupTitles + " " + messageLocator.getMessage("simplepage.deleted-entity");
else
itemGroupTitles = messageLocator.getMessage("simplepage.deleted-entity");
}
if (itemGroupTitles != null) {
itemGroupTitles = "[" + itemGroupTitles + "]";
}
UIOutput.make(tableRow, "item-groups", itemGroupString);
} else if (entityDeleted)
continue;
if (!"1".equals(mmDisplayType) && !"3".equals(mmDisplayType))
UIVerbatim.make(tableRow, "item-path", getItemPath(i));
// the reason this code is complex is that we try to choose
// the best
// HTML for displaying the particular type of object. We've
// added complexities
// over time as we get more experience with different
// object types and browsers.
StringTokenizer token = new StringTokenizer(i.getSakaiId(), ".");
String extension = "";
while (token.hasMoreTokens()) {
extension = token.nextToken().toLowerCase();
}
// the extension is almost never used. Normally we have
// the MIME type and use it. Extension is used only if
// for some reason we don't have the MIME type
UIComponent item;
String youtubeKey;
Length width = null;
if (i.getWidth() != null) {
width = new Length(i.getWidth());
}
Length height = null;
if (i.getHeight() != null) {
height = new Length(i.getHeight());
}
// Get the MIME type. For multimedia types is should be in
// the html field.
// The old code saved the URL there. So if it looks like a
// URL ignore it.
String mimeType = i.getHtml();
if (mimeType != null && (mimeType.startsWith("http") || mimeType.equals(""))) {
mimeType = null;
}
// here goes. dispatch on the type and produce the right tag
// type,
// followed by the hidden INPUT tags with information for the
// edit dialog
if (mmDisplayType == null && simplePageBean.isImageType(i)) {
if(canSeeAll || simplePageBean.isItemAvailable(i)) {
UIOutput.make(tableRow, "imageSpan");
if (itemGroupString != null) {
UIOutput.make(tableRow, "item-group-titles3", itemGroupTitles);
UIOutput.make(tableRow, "item-groups3", itemGroupString);
}
String imageName = i.getAlt();
if (imageName == null || imageName.equals("")) {
imageName = abbrevUrl(i.getURL());
}
item = UIOutput.make(tableRow, "image").decorate(new UIFreeAttributeDecorator("src", i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner()))).decorate(new UIFreeAttributeDecorator("alt", imageName));
if (lengthOk(width)) {
item.decorate(new UIFreeAttributeDecorator("width", width.getOld()));
}
if(lengthOk(height)) {
item.decorate(new UIFreeAttributeDecorator("height", height.getOld()));
}
} else {
UIComponent notAvailableText = UIOutput.make(tableRow, "notAvailableText", messageLocator.getMessage("simplepage.textItemUnavailable"));
// Grey it out
notAvailableText.decorate(new UIFreeAttributeDecorator("class", "disabled-text-item"));
}
// stuff for the jquery dialog
if (canEditPage) {
UIOutput.make(tableRow, "imageHeight", getOrig(height));
UIOutput.make(tableRow, "imageWidth", getOrig(width));
UIOutput.make(tableRow, "mimetype2", mimeType);
UIOutput.make(tableRow, "current-item-id4", Long.toString(i.getId()));
UIOutput.make(tableRow, "editmm-td");
UILink.make(tableRow, "iframe-edit", messageLocator.getMessage("simplepage.editItem"), "").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.url").replace("{}", abbrevUrl(i.getURL()))));
}
UIOutput.make(tableRow, "description2", i.getDescription());
} else if (mmDisplayType == null && (youtubeKey = simplePageBean.getYoutubeKey(i)) != null) {
String youtubeUrl = SimplePageBean.getYoutubeUrlFromKey(youtubeKey);
if(canSeeAll || simplePageBean.isItemAvailable(i)) {
UIOutput.make(tableRow, "youtubeSpan");
if (itemGroupString != null) {
UIOutput.make(tableRow, "item-group-titles4", itemGroupTitles);
UIOutput.make(tableRow, "item-groups4", itemGroupString);
}
// if width is blank or 100% scale the height
if (width != null && height != null && !height.number.equals("")) {
if (width.number.equals("") && width.unit.equals("") || width.number.equals("100") && width.unit.equals("%")) {
int h = Integer.parseInt(height.number);
if (h > 0) {
width.number = Integer.toString((int) Math.round(h * 1.641025641));
width.unit = height.unit;
}
}
}
// <object style="height: 390px; width: 640px"><param
// name="movie"
// value="http://www.youtube.com/v/AKIC7OQqBrA?version=3"><param
// name="allowFullScreen" value="true"><param
// name="allowScriptAccess" value="always"><embed
// src="http://www.youtube.com/v/AKIC7OQqBrA?version=3"
// type="application/x-shockwave-flash"
// allowfullscreen="true" allowScriptAccess="always"
// width="640" height="390"></object>
item = UIOutput.make(tableRow, "youtubeIFrame");
// youtube seems ok with length and width
if(lengthOk(height)) {
item.decorate(new UIFreeAttributeDecorator("height", height.getOld()));
}
if(lengthOk(width)) {
item.decorate(new UIFreeAttributeDecorator("width", width.getOld()));
}
item.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.youtube_player")));
item.decorate(new UIFreeAttributeDecorator("src", youtubeUrl));
} else {
UIComponent notAvailableText = UIOutput.make(tableRow, "notAvailableText", messageLocator.getMessage("simplepage.textItemUnavailable"));
// Grey it out
notAvailableText.decorate(new UIFreeAttributeDecorator("class", "disabled-text-item"));
}
if (canEditPage) {
UIOutput.make(tableRow, "youtubeId", String.valueOf(i.getId()));
UIOutput.make(tableRow, "currentYoutubeURL", youtubeUrl);
UIOutput.make(tableRow, "currentYoutubeHeight", getOrig(height));
UIOutput.make(tableRow, "currentYoutubeWidth", getOrig(width));
UIOutput.make(tableRow, "current-item-id5", Long.toString(i.getId()));
UIOutput.make(tableRow, "youtube-td");
UILink.make(tableRow, "youtube-edit", messageLocator.getMessage("simplepage.editItem"), "").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.youtube")));
}
UIOutput.make(tableRow, "description4", i.getDescription());
// as of Oct 28, 2010, we store the mime type. mimeType
// null is an old entry.
// For that use the old approach of checking the
// extension.
// Otherwise we want to use iframes for HTML and OBJECT
// for everything else
// We need the iframes because IE up through 8 doesn't
// reliably display
// HTML with OBJECT. Experiments show that everything
// else works with OBJECT
// for most browsers. Unfortunately IE, even IE 9,
// doesn't reliably call the
// right player with OBJECT. EMBED works. But it's not
// as nice because you can't
// nest error recovery code. So we use OBJECT for
// everything except IE, where we
// use EMBED. OBJECT does work with Flash.
// application/xhtml+xml is XHTML.
} else if (mmDisplayType == null &&
((mimeType != null && !mimeType.equals("text/html") && !mimeType.equals("application/xhtml+xml")) ||
// ((mimeType != null && (mimeType.startsWith("audio/") || mimeType.startsWith("video/"))) ||
(mimeType == null && !(Arrays.binarySearch(htmlTypes, extension) >= 0)))) {
// except where explicit display is set,
// this code is used for everything that isn't an image,
// Youtube, or HTML
// This could be audio, video, flash, or something random like MS word.
// Random stuff will turn into an object.
// HTML is done with an IFRAME in the next "if" case
// The explicit display types are handled there as well
// in theory the things that fall through to iframe are
// html and random stuff without a defined mime type
// random stuff with mime type is displayed with object
if (mimeType == null) {
mimeType = "";
}
String oMimeType = mimeType; // in case we change it for
// FLV or others
if (itemGroupString != null) {
UIOutput.make(tableRow, "item-group-titles5", itemGroupTitles);
UIOutput.make(tableRow, "item-groups5", itemGroupString);
}
UIOutput.make(tableRow, "movieSpan");
if(canSeeAll || simplePageBean.isItemAvailable(i)) {
UIComponent item2;
String movieUrl = i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner());
// movieUrl = "https://heidelberg.rutgers.edu" + movieUrl;
// Safari doens't always pass cookies to plugins, so we have to pass the arg
// this requires session.parameter.allow=true in sakai.properties
// don't pass the arg unless that is set, since the whole point of defaulting
// off is to not expose the session id
String sessionParameter = getSessionParameter(movieUrl);
if (sessionParameter != null)
movieUrl = movieUrl + "?lb.session=" + sessionParameter;
UIOutput.make(tableRow, "movie-link-div");
UILink.make(tableRow, "movie-link-link", messageLocator.getMessage("simplepage.download_file"), movieUrl);
// if (allowSessionId)
// movieUrl = movieUrl + "?sakai.session=" + SessionManager.getCurrentSession().getId();
boolean useFlvPlayer = false;
// isMp4 means we try the flash player (if not HTML5)
// we also try the flash player for FLV but for mp4 we do an
// additional backup if flash fails, but that doesn't make sense for FLV
boolean isMp4 = Arrays.binarySearch(mp4Types, mimeType) >= 0;
boolean isHtml5 = Arrays.binarySearch(html5Types, mimeType) >= 0;
// wrap whatever stuff we decide to put out in HTML5 if appropriate
// javascript is used to do the wrapping, because RSF can't really handle this
if (isHtml5) {
boolean isAudio = mimeType.startsWith("audio/");
UIComponent h5video = UIOutput.make(tableRow, (isAudio? "h5audio" : "h5video"));
UIComponent h5source = UIOutput.make(tableRow, (isAudio? "h5asource" : "h5source"));
if (lengthOk(height) && height.getOld().indexOf("%") < 0)
h5video.decorate(new UIFreeAttributeDecorator("height", height.getOld()));
if (lengthOk(width) && width.getOld().indexOf("%") < 0)
h5video.decorate(new UIFreeAttributeDecorator("width", width.getOld()));
h5source.decorate(new UIFreeAttributeDecorator("src", movieUrl)).
decorate(new UIFreeAttributeDecorator("type", mimeType));
}
// FLV is special. There's no player for flash video in
// the browser
// it shows with a special flash program, which I
// supply. For the moment MP4 is
// shown with the same player so it uses much of the
// same code
if (mimeType != null && (mimeType.equals("video/x-flv") || mimeType.equals("video/flv") || isMp4)) {
mimeType = "application/x-shockwave-flash";
movieUrl = "/lessonbuilder-tool/templates/StrobeMediaPlayback.swf";
useFlvPlayer = true;
}
// for IE, if we're not supplying a player it's safest
// to use embed
// otherwise Quicktime won't work. Oddly, with IE 9 only
// it works if you set CLASSID to the MIME type,
// but that's so unexpected that I hate to rely on it.
// EMBED is in HTML 5, so I think we're OK
// using it permanently for IE.
// I prefer OBJECT where possible because of the nesting
// ability.
boolean useEmbed = ieVersion > 0 && !mimeType.equals("application/x-shockwave-flash");
if (useEmbed) {
item2 = UIOutput.make(tableRow, "movieEmbed").decorate(new UIFreeAttributeDecorator("src", movieUrl)).decorate(new UIFreeAttributeDecorator("alt", messageLocator.getMessage("simplepage.mm_player").replace("{}", abbrevUrl(i.getURL()))));
} else {
item2 = UIOutput.make(tableRow, "movieObject").decorate(new UIFreeAttributeDecorator("data", movieUrl)).decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.mm_player").replace("{}", abbrevUrl(i.getURL()))));
}
if (mimeType != null) {
item2.decorate(new UIFreeAttributeDecorator("type", mimeType));
}
if (canEditPage) {
//item2.decorate(new UIFreeAttributeDecorator("style", "border: 1px solid black"));
}
// some object types seem to need a specification, so supply our default if necessary
if (lengthOk(height) && lengthOk(width)) {
item2.decorate(new UIFreeAttributeDecorator("height", height.getOld())).decorate(new UIFreeAttributeDecorator("width", width.getOld()));
} else {
if (oMimeType.startsWith("audio/"))
item2.decorate(new UIFreeAttributeDecorator("height", "100")).decorate(new UIFreeAttributeDecorator("width", "400"));
else
item2.decorate(new UIFreeAttributeDecorator("height", "300")).decorate(new UIFreeAttributeDecorator("width", "400"));
}
if (!useEmbed) {
if (useFlvPlayer) {
UIOutput.make(tableRow, "flashvars").decorate(new UIFreeAttributeDecorator("value", "src=" + URLEncoder.encode(myUrl() + i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner()))));
// need wmode=opaque for player to stack properly with dialogs, etc.
// there is a performance impact, but I'm guessing in our application we don't
// need ultimate performance for embedded video. I'm setting it only for
// the player, so flash games and other applications will still get wmode=window
UIOutput.make(tableRow, "wmode");
} else if (mimeType.equals("application/x-shockwave-flash"))
UIOutput.make(tableRow, "wmode");
UIOutput.make(tableRow, "movieURLInject").decorate(new UIFreeAttributeDecorator("value", movieUrl));
if (!isMp4) {
UIOutput.make(tableRow, "noplugin-p", messageLocator.getMessage("simplepage.noplugin"));
UIOutput.make(tableRow, "noplugin-br");
UILink.make(tableRow, "noplugin", i.getName(), movieUrl);
}
}
if (isMp4) {
// do fallback. for ie use EMBED
if (ieVersion > 0) {
item2 = UIOutput.make(tableRow, "mp4-embed").decorate(new UIFreeAttributeDecorator("src", i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner()))).decorate(new UIFreeAttributeDecorator("alt", messageLocator.getMessage("simplepage.mm_player").replace("{}", abbrevUrl(i.getURL()))));
} else {
item2 = UIOutput.make(tableRow, "mp4-object").decorate(new UIFreeAttributeDecorator("data", i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner()))).decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.mm_player").replace("{}", abbrevUrl(i.getURL()))));
}
if (oMimeType != null) {
item2.decorate(new UIFreeAttributeDecorator("type", oMimeType));
}
// some object types seem to need a specification, so give a default if needed
if (lengthOk(height) && lengthOk(width)) {
item2.decorate(new UIFreeAttributeDecorator("height", height.getOld())).decorate(new UIFreeAttributeDecorator("width", width.getOld()));
} else {
if (oMimeType.startsWith("audio/"))
item2.decorate(new UIFreeAttributeDecorator("height", "100")).decorate(new UIFreeAttributeDecorator("width", "100%"));
else
item2.decorate(new UIFreeAttributeDecorator("height", "300")).decorate(new UIFreeAttributeDecorator("width", "100%"));
}
if (!useEmbed) {
UIOutput.make(tableRow, "mp4-inject").decorate(new UIFreeAttributeDecorator("value", i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner())));
UIOutput.make(tableRow, "mp4-noplugin-p", messageLocator.getMessage("simplepage.noplugin"));
UILink.make(tableRow, "mp4-noplugin", i.getName(), i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner()));
}
}
} else {
UIVerbatim notAvailableText = UIVerbatim.make(tableRow, "notAvailableText", messageLocator.getMessage("simplepage.multimediaItemUnavailable"));
// Grey it out
notAvailableText.decorate(new UIFreeAttributeDecorator("class", "disabled-multimedia-item"));
}
if (canEditPage) {
UIOutput.make(tableRow, "movieId", String.valueOf(i.getId()));
UIOutput.make(tableRow, "movieHeight", getOrig(height));
UIOutput.make(tableRow, "movieWidth", getOrig(width));
UIOutput.make(tableRow, "mimetype5", oMimeType);
UIOutput.make(tableRow, "prerequisite", (i.isPrerequisite()) ? "true" : "false");
UIOutput.make(tableRow, "current-item-id6", Long.toString(i.getId()));
UIOutput.make(tableRow, "movie-td");
UILink.make(tableRow, "edit-movie", messageLocator.getMessage("simplepage.editItem"), "").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.url").replace("{}", abbrevUrl(i.getURL()))));
}
UIOutput.make(tableRow, "description3", i.getDescription());
} else {
// this is fallthrough for html or an explicit mm display type (i.e. embed code)
// odd types such as MS word will be handled by the AV code, and presented as <OBJECT>
// definition of resizeiframe, at top of page
if (!iframeJavascriptDone && getOrig(height).equals("auto")) {
UIOutput.make(tofill, "iframeJavascript");
iframeJavascriptDone = true;
}
UIOutput.make(tableRow, "iframeSpan");
if (itemGroupString != null) {
UIOutput.make(tableRow, "item-group-titles2", itemGroupTitles);
UIOutput.make(tableRow, "item-groups2", itemGroupString);
}
String itemUrl = i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner());
if ("1".equals(mmDisplayType)) {
// embed
item = UIVerbatim.make(tableRow, "mm-embed", i.getAttribute("multimediaEmbedCode"));
//String style = getStyle(width, height);
//if (style != null)
//item.decorate(new UIFreeAttributeDecorator("style", style));
} else if ("3".equals(mmDisplayType)) {
item = UILink.make(tableRow, "mm-oembed", i.getAttribute("multimediaUrl"), i.getAttribute("multimediaUrl"));
if (lengthOk(width))
item.decorate(new UIFreeAttributeDecorator("maxWidth", width.getOld()));
if (lengthOk(height))
item.decorate(new UIFreeAttributeDecorator("maxHeight", height.getOld()));
// oembed
} else {
UIOutput.make(tableRow, "iframe-link-div");
UILink.make(tableRow, "iframe-link-link", messageLocator.getMessage("simplepage.open_new_window"), itemUrl);
item = UIOutput.make(tableRow, "iframe").decorate(new UIFreeAttributeDecorator("src", itemUrl));
// if user specifies auto, use Javascript to resize the
// iframe when the
// content changes. This only works for URLs with the
// same origin, i.e.
// URLs in this sakai system
if (getOrig(height).equals("auto")) {
item.decorate(new UIFreeAttributeDecorator("onload", "resizeiframe('" + item.getFullID() + "')"));
if (lengthOk(width)) {
item.decorate(new UIFreeAttributeDecorator("width", width.getOld()));
}
item.decorate(new UIFreeAttributeDecorator("height", "300"));
} else {
// we seem OK without a spec
if (lengthOk(height) && lengthOk(width)) {
item.decorate(new UIFreeAttributeDecorator("height", height.getOld())).decorate(new UIFreeAttributeDecorator("width", width.getOld()));
}
}
}
item.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.web_content").replace("{}", abbrevUrl(i.getURL()))));
if (canEditPage) {
UIOutput.make(tableRow, "iframeHeight", getOrig(height));
UIOutput.make(tableRow, "iframeWidth", getOrig(width));
UIOutput.make(tableRow, "mimetype3", mimeType);
UIOutput.make(tableRow, "current-item-id3", Long.toString(i.getId()));
UIOutput.make(tableRow, "editmm-td");
UILink.make(tableRow, "iframe-edit", messageLocator.getMessage("simplepage.editItem"), "").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.url").replace("{}", abbrevUrl(i.getURL()))));
}
UIOutput.make(tableRow, "description5", i.getDescription());
}
// end of multimedia object
} else if (i.getType() == SimplePageItem.COMMENTS) {
// Load later using AJAX and CommentsProducer
UIOutput.make(tableRow, "commentsSpan");
boolean isAvailable = simplePageBean.isItemAvailable(i);
// faculty missing preqs get warning but still see the comments
if (!isAvailable && canSeeAll)
UIOutput.make(tableRow, "missing-prereqs", messageLocator.getMessage("simplepage.fake-missing-prereqs"));
// students get warning and not the content
if (!isAvailable && !canSeeAll) {
UIOutput.make(tableRow, "missing-prereqs", messageLocator.getMessage("simplepage.missing-prereqs"));
}else {
UIOutput.make(tableRow, "commentsDiv");
Placement placement = toolManager.getCurrentPlacement();
UIOutput.make(tableRow, "placementId", placement.getId());
// note: the URL will be rewritten in comments.js to look like
// /lessonbuilder-tool/faces/Comments...
CommentsViewParameters eParams = new CommentsViewParameters(CommentsProducer.VIEW_ID);
eParams.itemId = i.getId();
eParams.placementId = placement.getId();
if (params.postedComment) {
eParams.postedComment = postedCommentId;
}
eParams.siteId = simplePageBean.getCurrentSiteId();
eParams.pageId = currentPage.getPageId();
if(params.author != null && !params.author.equals("")) {
eParams.author = params.author;
eParams.showAllComments = true;
}
UIInternalLink.make(tableRow, "commentsLink", eParams);
if (!addedCommentsScript) {
UIOutput.make(tofill, "comments-script");
UIOutput.make(tofill, "fckScript");
addedCommentsScript = true;
UIOutput.make(tofill, "delete-dialog");
}
// forced comments have to be edited on the main page
if (canEditPage) {
// Checks to make sure that the comments item isn't on a student page.
// That it is graded. And that we didn't just come from the grading pane.
if(i.getPageId() > 0 && i.getGradebookId() != null && !cameFromGradingPane) {
CommentsGradingPaneViewParameters gp = new CommentsGradingPaneViewParameters(CommentGradingPaneProducer.VIEW_ID);
gp.placementId = toolManager.getCurrentPlacement().getId();
gp.commentsItemId = i.getId();
gp.pageId = currentPage.getPageId();
gp.pageItemId = pageItem.getId();
gp.siteId = simplePageBean.getCurrentSiteId();
UIInternalLink.make(tableRow, "gradingPaneLink", messageLocator.getMessage("simplepage.show-grading-pane-comments"), gp)
.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.show-grading-pane-comments")));
}
UIOutput.make(tableRow, "comments-td");
if (i.getSequence() > 0) {
UILink.make(tableRow, "edit-comments", messageLocator.getMessage("simplepage.editItem"), "")
.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.comments")));
UIOutput.make(tableRow, "commentsId", String.valueOf(i.getId()));
UIOutput.make(tableRow, "commentsAnon", String.valueOf(i.isAnonymous()));
UIOutput.make(tableRow, "commentsitem-required", String.valueOf(i.isRequired()));
UIOutput.make(tableRow, "commentsitem-prerequisite", String.valueOf(i.isPrerequisite()));
UIOutput.make(tableRow, "commentsGrade", String.valueOf(i.getGradebookId() != null));
UIOutput.make(tableRow, "commentsMaxPoints", String.valueOf(i.getGradebookPoints()));
String itemGroupString = simplePageBean.getItemGroupString(i, null, true);
if (itemGroupString != null) {
String itemGroupTitles = simplePageBean.getItemGroupTitles(itemGroupString, i);
if (itemGroupTitles != null) {
itemGroupTitles = "[" + itemGroupTitles + "]";
}
UIOutput.make(tableRow, "comments-groups", itemGroupString);
UIOutput.make(tableRow, "item-group-titles6", itemGroupTitles);
}
}
// Allows AJAX posting of comment grades
printGradingForm(tofill);
}
UIForm form = UIForm.make(tableRow, "comment-form");
UIInput.make(form, "comment-item-id", "#{simplePageBean.itemId}", String.valueOf(i.getId()));
UIInput.make(form, "comment-edit-id", "#{simplePageBean.editId}");
// usage * image is required and not done
if (i.isRequired() && !simplePageBean.isItemComplete(i))
UIOutput.make(tableRow, "comment-required-image");
UIOutput.make(tableRow, "add-comment-link");
UIOutput.make(tableRow, "add-comment-text", messageLocator.getMessage("simplepage.add-comment"));
UIInput fckInput = UIInput.make(form, "comment-text-area-evolved:", "#{simplePageBean.formattedComment}");
fckInput.decorate(new UIFreeAttributeDecorator("height", "175"));
fckInput.decorate(new UIFreeAttributeDecorator("width", "800"));
fckInput.decorate(new UIStyleDecorator("evolved-box"));
fckInput.decorate(new UIFreeAttributeDecorator("aria-label", messageLocator.getMessage("simplepage.editor")));
fckInput.decorate(new UIFreeAttributeDecorator("role", "dialog"));
if (!noEditor) {
fckInput.decorate(new UIStyleDecorator("using-editor")); // javascript needs to know
((SakaiFCKTextEvolver) richTextEvolver).evolveTextInput(fckInput, "" + commentsCount);
}
UICommand.make(form, "add-comment", "#{simplePageBean.addComment}");
}
}else if (i.getType() == SimplePageItem.PEEREVAL){
String owner=currentPage.getOwner();
String currentUser=UserDirectoryService.getCurrentUser().getId();
Long pageId=currentPage.getPageId();
UIOutput.make(tableRow, "peerReviewRubricStudent");
UIOutput.make(tableRow, "peer-review-form");
makePeerRubric(tableRow,i, makeStudentRubric);
boolean isOpen = false;
boolean isPastDue = false;
String peerEvalDateOpenStr = i.getAttribute("rubricOpenDate");
String peerEvalDateDueStr = i.getAttribute("rubricDueDate");
boolean peerEvalAllowSelfGrade = Boolean.parseBoolean(i.getAttribute("rubricAllowSelfGrade"));
boolean gradingSelf = owner.equals(currentUser) && peerEvalAllowSelfGrade;
if (peerEvalDateOpenStr != null && peerEvalDateDueStr != null) {
Date peerEvalNow = new Date();
Date peerEvalOpen = new Date(Long.valueOf(peerEvalDateOpenStr));
Date peerEvalDue = new Date(Long.valueOf(peerEvalDateDueStr));
isOpen = peerEvalNow.after(peerEvalOpen);
isPastDue = peerEvalNow.after(peerEvalDue);
}
if(isOpen){
if(owner.equals(currentUser)){ //owner gets their own data
class PeerEvaluation{
String category;
public int grade, count;
public PeerEvaluation(String category, int grade){this.category=category;this.grade=grade;count=1;}
public void increment(){count++;}
public boolean equals(Object o){
if ( !(o instanceof PeerEvaluation) ) return false;
PeerEvaluation pe = (PeerEvaluation)o;
return category.equals(pe.category) && grade==pe.grade;
}
public String toString(){return category + " " + grade + " [" + count + "]";}
}
ArrayList<PeerEvaluation> myEvaluations = new ArrayList<PeerEvaluation>();
List<SimplePagePeerEvalResult> evaluations = simplePageToolDao.findPeerEvalResultByOwner(pageId.longValue(), owner);
if(evaluations!=null)
for(SimplePagePeerEvalResult eval : evaluations){
PeerEvaluation target=new PeerEvaluation(eval.getRowText(), eval.getColumnValue());
int targetIndex=myEvaluations.indexOf(target);
if(targetIndex!=-1){
myEvaluations.get(targetIndex).increment();
}
else
myEvaluations.add(target);
}
UIOutput.make(tableRow, "my-existing-peer-eval-data");
for(PeerEvaluation eval: myEvaluations){
UIBranchContainer evalData = UIBranchContainer.make(tableRow, "my-peer-eval-data:");
UIOutput.make(evalData, "peer-eval-row-text", eval.category);
UIOutput.make(evalData, "peer-eval-grade", String.valueOf(eval.grade));
UIOutput.make(evalData, "peer-eval-count", String.valueOf(eval.count));
}
}
if(!owner.equals(currentUser) || gradingSelf){
List<SimplePagePeerEvalResult> evaluations = simplePageToolDao.findPeerEvalResult(pageId, currentUser, owner);
//existing evaluation data
if(evaluations!=null && evaluations.size()!=0){
UIOutput.make(tableRow, "existing-peer-eval-data");
for(SimplePagePeerEvalResult eval : evaluations){
UIBranchContainer evalData = UIBranchContainer.make(tableRow, "peer-eval-data:");
UIOutput.make(evalData, "peer-eval-row-text", eval.getRowText());
UIOutput.make(evalData, "peer-eval-grade", String.valueOf(eval.getColumnValue()));
}
}
//form for peer evaluation results
UIForm form = UIForm.make(tofill, "rubricSelection");
UIInput.make(form, "rubricPeerGrade", "#{simplePageBean.rubricPeerGrade}");
UICommand.make(form, "update-peer-eval-grade", messageLocator.getMessage("simplepage.edit"), "#{simplePageBean.savePeerEvalResult}");
}
//buttons
UIOutput.make(tableRow, "add-peereval-link");
UIOutput.make(tableRow, "add-peereval-text", messageLocator.getMessage("simplepage.view-peereval"));
if(isPastDue){
UIOutput.make(tableRow, "peer-eval-grade-directions", messageLocator.getMessage("simplepage.peer-eval.past-due-date"));
}else if(!owner.equals(currentUser) || gradingSelf){
UIOutput.make(tableRow, "save-peereval-link");
UIOutput.make(tableRow, "save-peereval-text", messageLocator.getMessage("simplepage.save"));
UIOutput.make(tableRow, "cancel-peereval-link");
UIOutput.make(tableRow, "cancel-peereval-text", messageLocator.getMessage("simplepage.cancel"));
UIOutput.make(tableRow, "peer-eval-grade-directions", messageLocator.getMessage("simplepage.peer-eval.click-on-cell"));
}else{ //owner who cannot grade himself
UIOutput.make(tableRow, "peer-eval-grade-directions", messageLocator.getMessage("simplepage.peer-eval.cant-eval-yourself"));
}
if(canEditPage)
UIOutput.make(tableRow, "peerReviewRubricStudent-edit");//lines up rubric with edit btn column for users with editing privs
}
}else if(i.getType() == SimplePageItem.STUDENT_CONTENT) {
UIOutput.make(tableRow, "studentSpan");
boolean isAvailable = simplePageBean.isItemAvailable(i);
// faculty missing preqs get warning but still see the comments
if (!isAvailable && canSeeAll)
UIOutput.make(tableRow, "student-missing-prereqs", messageLocator.getMessage("simplepage.student-fake-missing-prereqs"));
if (!isAvailable && !canSeeAll)
UIOutput.make(tableRow, "student-missing-prereqs", messageLocator.getMessage("simplepage.student-missing-prereqs"));
else {
UIOutput.make(tableRow, "studentDiv");
HashMap<Long, SimplePageLogEntry> cache = simplePageBean.cacheStudentPageLogEntries(i.getId());
List<SimpleStudentPage> studentPages = simplePageToolDao.findStudentPages(i.getId());
boolean hasOwnPage = false;
String userId = UserDirectoryService.getCurrentUser().getId();
Collections.sort(studentPages, new Comparator<SimpleStudentPage>() {
public int compare(SimpleStudentPage o1, SimpleStudentPage o2) {
String title1 = o1.getTitle();
if (title1 == null)
title1 = "";
String title2 = o2.getTitle();
if (title2 == null)
title2 = "";
return title1.compareTo(title2);
}
});
UIOutput contentList = UIOutput.make(tableRow, "studentContentTable");
UIOutput contentTitle = UIOutput.make(tableRow, "studentContentTitle", messageLocator.getMessage("simplepage.student"));
contentList.decorate(new UIFreeAttributeDecorator("aria-labelledby", contentTitle.getFullID()));
// Print each row in the table
for(SimpleStudentPage page : studentPages) {
if(page.isDeleted()) continue;
SimplePageLogEntry entry = cache.get(page.getPageId());
UIBranchContainer row = UIBranchContainer.make(tableRow, "studentRow:");
// There's content they haven't seen
if(entry == null || entry.getLastViewed().compareTo(page.getLastUpdated()) < 0) {
UIOutput.make(row, "newContentImg").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.new-student-content")));
} else
UIOutput.make(row, "newContentImgT");
// The comments tool exists, so we might have to show the icon
if(i.getShowComments() != null && i.getShowComments()) {
// New comments have been added since they last viewed the page
if(page.getLastCommentChange() != null && (entry == null || entry.getLastViewed().compareTo(page.getLastCommentChange()) < 0)) {
UIOutput.make(row, "newCommentsImg").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.new-student-comments")));
} else
UIOutput.make(row, "newCommentsImgT");
}
// Never visited page
if(entry == null) {
UIOutput.make(row, "newPageImg").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.new-student-page")));
} else
UIOutput.make(row, "newPageImgT");
GeneralViewParameters eParams = new GeneralViewParameters(ShowPageProducer.VIEW_ID, page.getPageId());
eParams.setItemId(i.getId());
eParams.setPath("push");
String studentTitle = page.getTitle();
String sownerName = null;
try {
if(!i.isAnonymous() || canEditPage) {
if (page.getGroup() != null)
sownerName = simplePageBean.getCurrentSite().getGroup(page.getGroup()).getTitle();
else
sownerName = UserDirectoryService.getUser(page.getOwner()).getDisplayName();
if (sownerName != null && sownerName.equals(studentTitle))
studentTitle = "(" + sownerName + ")";
else
studentTitle += " (" + sownerName + ")";
}else if (simplePageBean.isPageOwner(page)) {
studentTitle += " (" + messageLocator.getMessage("simplepage.comment-you") + ")";
}
} catch (UserNotDefinedException e) {
}
UIInternalLink.make(row, "studentLink", studentTitle, eParams);
if(simplePageBean.isPageOwner(page)) {
hasOwnPage = true;
}
if(i.getGradebookId() != null && simplePageBean.getEditPrivs() == 0) {
UIOutput.make(row, "studentGradingCell", String.valueOf((page.getPoints() != null? page.getPoints() : "")));
}
}
if(!hasOwnPage) {
UIBranchContainer row = UIBranchContainer.make(tableRow, "studentRow:");
UIOutput.make(row, "linkRow");
UIOutput.make(row, "linkCell");
if (i.isRequired() && !simplePageBean.isItemComplete(i))
UIOutput.make(row, "student-required-image");
GeneralViewParameters eParams = new GeneralViewParameters(ShowPageProducer.VIEW_ID);
eParams.addTool = GeneralViewParameters.STUDENT_PAGE;
eParams.studentItemId = i.getId();
UIInternalLink.make(row, "linkLink", messageLocator.getMessage("simplepage.add-page"), eParams);
}
if(canEditPage) {
// Checks to make sure that the comments are graded and that we didn't
// just come from a grading pane (would be confusing)
if(i.getAltGradebook() != null && !cameFromGradingPane) {
CommentsGradingPaneViewParameters gp = new CommentsGradingPaneViewParameters(CommentGradingPaneProducer.VIEW_ID);
gp.placementId = toolManager.getCurrentPlacement().getId();
gp.commentsItemId = i.getId();
gp.pageId = currentPage.getPageId();
gp.pageItemId = pageItem.getId();
gp.studentContentItem = true;
UIInternalLink.make(tableRow, "studentGradingPaneLink", messageLocator.getMessage("simplepage.show-grading-pane-content"), gp)
.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.show-grading-pane-content")));
}
UIOutput.make(tableRow, "student-td");
UILink.make(tableRow, "edit-student", messageLocator.getMessage("simplepage.editItem"), "")
.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.student")));
UIOutput.make(tableRow, "studentId", String.valueOf(i.getId()));
UIOutput.make(tableRow, "studentAnon", String.valueOf(i.isAnonymous()));
UIOutput.make(tableRow, "studentComments", String.valueOf(i.getShowComments()));
UIOutput.make(tableRow, "forcedAnon", String.valueOf(i.getForcedCommentsAnonymous()));
UIOutput.make(tableRow, "studentGrade", String.valueOf(i.getGradebookId() != null));
UIOutput.make(tableRow, "studentMaxPoints", String.valueOf(i.getGradebookPoints()));
UIOutput.make(tableRow, "studentGrade2", String.valueOf(i.getAltGradebook() != null));
UIOutput.make(tableRow, "studentMaxPoints2", String.valueOf(i.getAltPoints()));
UIOutput.make(tableRow, "studentitem-required", String.valueOf(i.isRequired()));
UIOutput.make(tableRow, "studentitem-prerequisite", String.valueOf(i.isPrerequisite()));
UIOutput.make(tableRow, "peer-eval", String.valueOf(i.getShowPeerEval()));
makePeerRubric(tableRow,i, makeMaintainRubric);
makeSamplePeerEval(tableRow);
String peerEvalDate = i.getAttribute("rubricOpenDate");
String peerDueDate = i.getAttribute("rubricDueDate");
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat stf = new SimpleDateFormat("hh:mm a");
Calendar peerevalcal = Calendar.getInstance();
if (peerEvalDate != null && peerDueDate != null) {
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, M_locale);
//Open date from attribute string
peerevalcal.setTimeInMillis(Long.valueOf(peerEvalDate));
String dateStr = sdf.format(peerevalcal.getTime());
String timeStr = stf.format(peerevalcal.getTime());
UIOutput.make(tableRow, "peer-eval-open-date", dateStr);
UIOutput.make(tableRow, "peer-eval-open-time", timeStr);
//Due date from attribute string
peerevalcal.setTimeInMillis(Long.valueOf(peerDueDate));
dateStr = sdf.format(peerevalcal.getTime());
timeStr = stf.format(peerevalcal.getTime());
UIOutput.make(tableRow, "peer-eval-due-date", dateStr);
UIOutput.make(tableRow, "peer-eval-due-time", timeStr);
UIOutput.make(tableRow, "peer-eval-allow-self", i.getAttribute("rubricAllowSelfGrade"));
}else{
//Default open and due date
Date now = new Date();
peerevalcal.setTime(now);
//Default open date: now
String dateStr = sdf.format(peerevalcal.getTime());
String timeStr = stf.format(peerevalcal.getTime());
UIOutput.make(tableRow, "peer-eval-open-date", dateStr);
UIOutput.make(tableRow, "peer-eval-open-time", timeStr);
//Default due date: 7 days from now
Date later = new Date(peerevalcal.getTimeInMillis() + 604800000);
peerevalcal.setTime(later);
dateStr = sdf.format(peerevalcal.getTime());
timeStr = stf.format(peerevalcal.getTime());
//System.out.println("Setting date to " + dateStr + " and time to " + timeStr);
UIOutput.make(tableRow, "peer-eval-due-date", dateStr);
UIOutput.make(tableRow, "peer-eval-due-time", timeStr);
UIOutput.make(tableRow, "peer-eval-allow-self", i.getAttribute("rubricAllowSelfGrade"));
}
//Peer Eval Stats link
GeneralViewParameters view = new GeneralViewParameters(PeerEvalStatsProducer.VIEW_ID);
view.setSendingPage(currentPage.getPageId());
view.setItemId(i.getId());
if(i.getShowPeerEval()){
UILink link = UIInternalLink.make(tableRow, "peer-eval-stats-link", view);
}
String itemGroupString = simplePageBean.getItemGroupString(i, null, true);
if (itemGroupString != null) {
String itemGroupTitles = simplePageBean.getItemGroupTitles(itemGroupString, i);
if (itemGroupTitles != null) {
itemGroupTitles = "[" + itemGroupTitles + "]";
}
UIOutput.make(tableRow, "student-groups", itemGroupString);
UIOutput.make(tableRow, "item-group-titles7", itemGroupTitles);
}
UIOutput.make(tableRow, "student-owner-groups", simplePageBean.getItemOwnerGroupString(i));
UIOutput.make(tableRow, "student-group-owned", (i.isGroupOwned()?"true":"false"));
}
}
}else if(i.getType() == SimplePageItem.QUESTION) {
SimplePageQuestionResponse response = simplePageToolDao.findQuestionResponse(i.getId(), simplePageBean.getCurrentUserId());
UIOutput.make(tableRow, "questionSpan");
boolean isAvailable = simplePageBean.isItemAvailable(i) || canSeeAll;
UIOutput.make(tableRow, "questionDiv");
UIOutput.make(tableRow, "questionText", i.getAttribute("questionText"));
List<SimplePageQuestionAnswer> answers = new ArrayList<SimplePageQuestionAnswer>();
if("multipleChoice".equals(i.getAttribute("questionType"))) {
answers = simplePageToolDao.findAnswerChoices(i);
UIOutput.make(tableRow, "multipleChoiceDiv");
UIForm questionForm = UIForm.make(tableRow, "multipleChoiceForm");
UIInput.make(questionForm, "multipleChoiceId", "#{simplePageBean.questionId}", String.valueOf(i.getId()));
String[] options = new String[answers.size()];
String initValue = null;
for(int j = 0; j < answers.size(); j++) {
options[j] = String.valueOf(answers.get(j).getId());
if(response != null && answers.get(j).getId() == response.getMultipleChoiceId()) {
initValue = String.valueOf(answers.get(j).getId());
}
}
UISelect multipleChoiceSelect = UISelect.make(questionForm, "multipleChoiceSelect:", options, "#{simplePageBean.questionResponse}", initValue);
if(!isAvailable || response != null) {
multipleChoiceSelect.decorate(new UIDisabledDecorator());
}
for(int j = 0; j < answers.size(); j++) {
UIBranchContainer answerContainer = UIBranchContainer.make(questionForm, "multipleChoiceAnswer:", String.valueOf(j));
UISelectChoice multipleChoiceInput = UISelectChoice.make(answerContainer, "multipleChoiceAnswerRadio", multipleChoiceSelect.getFullID(), j);
multipleChoiceInput.decorate(new UIFreeAttributeDecorator("id", multipleChoiceInput.getFullID()));
UIOutput.make(answerContainer, "multipleChoiceAnswerText", answers.get(j).getText())
.decorate(new UIFreeAttributeDecorator("for", multipleChoiceInput.getFullID()));
if(!isAvailable || response != null) {
multipleChoiceInput.decorate(new UIDisabledDecorator());
}
}
UICommand answerButton = UICommand.make(questionForm, "answerMultipleChoice", messageLocator.getMessage("simplepage.answer_question"), "#{simplePageBean.answerMultipleChoiceQuestion}");
if(!isAvailable || response != null) {
answerButton.decorate(new UIDisabledDecorator());
}
}else if("shortanswer".equals(i.getAttribute("questionType"))) {
UIOutput.make(tableRow, "shortanswerDiv");
UIForm questionForm = UIForm.make(tableRow, "shortanswerForm");
UIInput.make(questionForm, "shortanswerId", "#{simplePageBean.questionId}", String.valueOf(i.getId()));
UIInput shortanswerInput = UIInput.make(questionForm, "shortanswerInput", "#{simplePageBean.questionResponse}");
if(!isAvailable || response != null) {
shortanswerInput.decorate(new UIDisabledDecorator());
if(response.getShortanswer() != null) {
shortanswerInput.setValue(response.getShortanswer());
}
}
UICommand answerButton = UICommand.make(questionForm, "answerShortanswer", messageLocator.getMessage("simplepage.answer_question"), "#{simplePageBean.answerShortanswerQuestion}");
if(!isAvailable || response != null) {
answerButton.decorate(new UIDisabledDecorator());
}
}
Status questionStatus = getQuestionStatus(i, response);
addStatusImage(questionStatus, tableRow, "questionStatus", null);
String statusNote = getStatusNote(questionStatus);
if (statusNote != null) // accessibility version of icon
UIOutput.make(tableRow, "questionNote", statusNote);
String statusText = null;
if(questionStatus == Status.COMPLETED)
statusText = i.getAttribute("questionCorrectText");
else if(questionStatus == Status.FAILED)
statusText = i.getAttribute("questionIncorrectText");
if (statusText != null && !"".equals(statusText.trim()))
UIOutput.make(tableRow, "questionStatusText", statusText);
// Output the poll data
if("multipleChoice".equals(i.getAttribute("questionType")) &&
(canEditPage || ("true".equals(i.getAttribute("questionShowPoll")) &&
(questionStatus == Status.COMPLETED || questionStatus == Status.FAILED)))) {
UIOutput.make(tableRow, "showPollGraph", messageLocator.getMessage("simplepage.show-poll"));
UIOutput questionGraph = UIOutput.make(tableRow, "questionPollGraph");
questionGraph.decorate(new UIFreeAttributeDecorator("id", "poll" + i.getId()));
List<SimplePageQuestionResponseTotals> totals = simplePageToolDao.findQRTotals(i.getId());
HashMap<Long, Long> responseCounts = new HashMap<Long, Long>();
// in theory we don't need the first loop, as there should be a total
// entry for all possible answers. But in case things are out of sync ...
for(SimplePageQuestionAnswer answer : answers)
responseCounts.put(answer.getId(), 0L);
for(SimplePageQuestionResponseTotals total : totals)
responseCounts.put(total.getResponseId(), total.getCount());
for(int j = 0; j < answers.size(); j++) {
UIBranchContainer pollContainer = UIBranchContainer.make(tableRow, "questionPollData:", String.valueOf(j));
UIOutput.make(pollContainer, "questionPollText", answers.get(j).getText());
UIOutput.make(pollContainer, "questionPollNumber", String.valueOf(responseCounts.get(answers.get(j).getId())));
}
}
if(canEditPage) {
UIOutput.make(tableRow, "question-td");
// always show grading panel. Currently this is the only way to get feedback
if( !cameFromGradingPane) {
QuestionGradingPaneViewParameters gp = new QuestionGradingPaneViewParameters(QuestionGradingPaneProducer.VIEW_ID);
gp.placementId = toolManager.getCurrentPlacement().getId();
gp.questionItemId = i.getId();
gp.pageId = currentPage.getPageId();
gp.pageItemId = pageItem.getId();
UIInternalLink.make(tableRow, "questionGradingPaneLink", messageLocator.getMessage("simplepage.show-grading-pane"), gp)
.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.show-grading-pane")));
}
UILink.make(tableRow, "edit-question", messageLocator.getMessage("simplepage.editItem"), "")
.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.question")));
UIOutput.make(tableRow, "questionId", String.valueOf(i.getId()));
boolean graded = "true".equals(i.getAttribute("questionGraded")) || i.getGradebookId() != null;
UIOutput.make(tableRow, "questionGrade", String.valueOf(graded));
UIOutput.make(tableRow, "questionMaxPoints", String.valueOf(i.getGradebookPoints()));
UIOutput.make(tableRow, "questionGradebookTitle", String.valueOf(i.getGradebookTitle()));
UIOutput.make(tableRow, "questionitem-required", String.valueOf(i.isRequired()));
UIOutput.make(tableRow, "questionitem-prerequisite", String.valueOf(i.isPrerequisite()));
UIOutput.make(tableRow, "questionCorrectText", String.valueOf(i.getAttribute("questionCorrectText")));
UIOutput.make(tableRow, "questionIncorrectText", String.valueOf(i.getAttribute("questionIncorrectText")));
if("shortanswer".equals(i.getAttribute("questionType"))) {
UIOutput.make(tableRow, "questionType", "shortanswer");
UIOutput.make(tableRow, "questionAnswer", i.getAttribute("questionAnswer"));
}else {
UIOutput.make(tableRow, "questionType", "multipleChoice");
for(int j = 0; j < answers.size(); j++) {
UIBranchContainer answerContainer = UIBranchContainer.make(tableRow, "questionMultipleChoiceAnswer:", String.valueOf(j));
UIOutput.make(answerContainer, "questionMultipleChoiceAnswerId", String.valueOf(answers.get(j).getId()));
UIOutput.make(answerContainer, "questionMultipleChoiceAnswerText", answers.get(j).getText());
UIOutput.make(answerContainer, "questionMultipleChoiceAnswerCorrect", String.valueOf(answers.get(j).isCorrect()));
}
UIOutput.make(tableRow, "questionShowPoll", String.valueOf(i.getAttribute("questionShowPoll")));
}
}
} else {
// remaining type must be a block of HTML
UIOutput.make(tableRow, "itemSpan");
if (canSeeAll) {
String itemGroupString = simplePageBean.getItemGroupString(i, null, true);
String itemGroupTitles = simplePageBean.getItemGroupTitles(itemGroupString, i);
if (itemGroupTitles != null) {
itemGroupTitles = "[" + itemGroupTitles + "]";
}
UIOutput.make(tableRow, "item-groups-titles-text", itemGroupTitles);
}
if(canSeeAll || simplePageBean.isItemAvailable(i)) {
UIVerbatim.make(tableRow, "content", (i.getHtml() == null ? "" : i.getHtml()));
} else {
UIComponent unavailableText = UIOutput.make(tableRow, "content", messageLocator.getMessage("simplepage.textItemUnavailable"));
unavailableText.decorate(new UIFreeAttributeDecorator("class", "disabled-text-item"));
}
// editing is done using a special producer that calls FCK.
if (canEditPage) {
GeneralViewParameters eParams = new GeneralViewParameters();
eParams.setSendingPage(currentPage.getPageId());
eParams.setItemId(i.getId());
eParams.viewID = EditPageProducer.VIEW_ID;
UIOutput.make(tableRow, "edittext-td");
UIInternalLink.make(tableRow, "edit-link", messageLocator.getMessage("simplepage.editItem"), eParams).decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.textbox").replace("{}", Integer.toString(textboxcount))));
textboxcount++;
}
}
}
// end of items. This is the end for normal users. Following is
// special
// checks and putting out the dialogs for the popups, for
// instructors.
boolean showBreak = false;
// I believe refresh is now done automatically in all cases
// if (showRefresh) {
// UIOutput.make(tofill, "refreshAlert");
//
// // Should simply refresh
// GeneralViewParameters p = new GeneralViewParameters(VIEW_ID);
// p.setSendingPage(currentPage.getPageId());
// UIInternalLink.make(tofill, "refreshLink", p);
// showBreak = true;
// }
// stuff goes on the page in the order in the HTML file. So the fact
// that it's here doesn't mean it shows
// up at the end. This code produces errors and other odd stuff.
if (canSeeAll) {
// if the page is hidden, warn the faculty [students get stopped
// at
// the top]
if (currentPage.isHidden()) {
UIOutput.make(tofill, "hiddenAlert").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.pagehidden")));
UIVerbatim.make(tofill, "hidden-text", messageLocator.getMessage("simplepage.pagehidden.text"));
showBreak = true;
// similarly warn them if it isn't released yet
} else if (currentPage.getReleaseDate() != null && currentPage.getReleaseDate().after(new Date())) {
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, M_locale);
TimeZone tz = timeService.getLocalTimeZone();
df.setTimeZone(tz);
String releaseDate = df.format(currentPage.getReleaseDate());
UIOutput.make(tofill, "hiddenAlert").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.notreleased")));
UIVerbatim.make(tofill, "hidden-text", messageLocator.getMessage("simplepage.notreleased.text").replace("{}", releaseDate));
showBreak = true;
}
}
if (showBreak) {
UIOutput.make(tofill, "breakAfterWarnings");
}
}
// more warnings: if no item on the page, give faculty instructions,
// students an error
if (!anyItemVisible) {
if (canEditPage) {
UIOutput.make(tofill, "startupHelp")
.decorate(new UIFreeAttributeDecorator("src",
getLocalizedURL((currentPage.getOwner() != null) ? "student.html" : "general.html")))
.decorate(new UIFreeAttributeDecorator("id", "iframe"));
if (!iframeJavascriptDone) {
UIOutput.make(tofill, "iframeJavascript");
iframeJavascriptDone = true;
}
} else {
UIOutput.make(tofill, "error-div");
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.noitems_error_user"));
}
}
// now output the dialogs. but only for faculty (to avoid making the
// file bigger)
if (canEditPage) {
createSubpageDialog(tofill, currentPage);
}
createDialogs(tofill, currentPage, pageItem);
}
| public void fillComponents(UIContainer tofill, ViewParameters viewParams, ComponentChecker checker) {
GeneralViewParameters params = (GeneralViewParameters) viewParams;
UIOutput.make(tofill, "html").decorate(new UIFreeAttributeDecorator("lang", localegetter.get().getLanguage()))
.decorate(new UIFreeAttributeDecorator("xml:lang", localegetter.get().getLanguage()));
boolean iframeJavascriptDone = false;
// security model:
// canEditPage and canReadPage are normal Sakai privileges. They apply
// to all
// pages in the site.
// However when presented with a page, we need to make sure it's
// actually in
// this site, or users could get to pages in other sites. That's done
// by updatePageObject. The model is that producers always work on the
// current page, and updatePageObject makes sure that is in the current
// site.
// At that point we can safely use canEditPage.
// somewhat misleading. sendingPage specifies the page we're supposed to
// go to. If path is "none", we don't want this page to be what we see
// when we come back to the tool
if (params.getSendingPage() != -1) {
// will fail if page not in this site
// security then depends upon making sure that we only deal with
// this page
try {
simplePageBean.updatePageObject(params.getSendingPage(), !params.getPath().equals("none"));
} catch (Exception e) {
log.warn("ShowPage permission exception " + e);
UIOutput.make(tofill, "error-div");
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.not_available"));
return;
}
}
boolean canEditPage = simplePageBean.canEditPage();
boolean canReadPage = simplePageBean.canReadPage();
boolean canSeeAll = simplePageBean.canSeeAll(); // always on if caneditpage
boolean cameFromGradingPane = params.getPath().equals("none");
if (!canReadPage) {
// this code is intended for the situation where site permissions
// haven't been set up.
// So if the user can't read the page (which is pretty abnormal),
// see if they have site.upd.
// if so, give them some explanation and offer to call the
// permissions helper
String ref = "/site/" + simplePageBean.getCurrentSiteId();
if (simplePageBean.canEditSite()) {
SimplePage currentPage = simplePageBean.getCurrentPage();
UIOutput.make(tofill, "needPermissions");
GeneralViewParameters permParams = new GeneralViewParameters();
permParams.setSendingPage(-1L);
createStandardToolBarLink(PermissionsHelperProducer.VIEW_ID, tofill, "callpermissions", "simplepage.permissions", permParams, "simplepage.permissions.tooltip");
}
// in any case, tell them they can't read the page
UIOutput.make(tofill, "error-div");
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.nopermissions"));
return;
}
if (params.addTool == GeneralViewParameters.COMMENTS) {
simplePageBean.addCommentsSection();
}else if(params.addTool == GeneralViewParameters.STUDENT_CONTENT) {
simplePageBean.addStudentContentSection();
}else if(params.addTool == GeneralViewParameters.STUDENT_PAGE) {
simplePageBean.createStudentPage(params.studentItemId);
canEditPage = simplePageBean.canEditPage();
}
// Find the MSIE version, if we're running it.
int ieVersion = checkIEVersion();
// as far as I can tell, none of these supports fck or ck
// we can make it configurable if necessary, or use WURFL
// however this test is consistent with CKeditor's check.
// that desireable, since if CKeditor is going to use a bare
// text block, we want to handle it as noEditor
String userAgent = httpServletRequest.getHeader("User-Agent");
if (userAgent == null)
userAgent = "";
boolean noEditor = userAgent.toLowerCase().indexOf("mobile") >= 0;
// set up locale
Locale M_locale = null;
String langLoc[] = localegetter.get().toString().split("_");
if (langLoc.length >= 2) {
if ("en".equals(langLoc[0]) && "ZA".equals(langLoc[1])) {
M_locale = new Locale("en", "GB");
} else {
M_locale = new Locale(langLoc[0], langLoc[1]);
}
} else {
M_locale = new Locale(langLoc[0]);
}
// clear session attribute if necessary, after calling Samigo
String clearAttr = params.getClearAttr();
if (clearAttr != null && !clearAttr.equals("")) {
Session session = SessionManager.getCurrentSession();
// don't let users clear random attributes
if (clearAttr.startsWith("LESSONBUILDER_RETURNURL")) {
session.setAttribute(clearAttr, null);
}
}
if (htmlTypes == null) {
String mmTypes = ServerConfigurationService.getString("lessonbuilder.html.types", DEFAULT_HTML_TYPES);
htmlTypes = mmTypes.split(",");
for (int i = 0; i < htmlTypes.length; i++) {
htmlTypes[i] = htmlTypes[i].trim().toLowerCase();
}
Arrays.sort(htmlTypes);
}
if (mp4Types == null) {
String m4Types = ServerConfigurationService.getString("lessonbuilder.mp4.types", DEFAULT_MP4_TYPES);
mp4Types = m4Types.split(",");
for (int i = 0; i < mp4Types.length; i++) {
mp4Types[i] = mp4Types[i].trim().toLowerCase();
}
Arrays.sort(mp4Types);
}
if (html5Types == null) {
String jTypes = ServerConfigurationService.getString("lessonbuilder.html5.types", DEFAULT_HTML5_TYPES);
html5Types = jTypes.split(",");
for (int i = 0; i < html5Types.length; i++) {
html5Types[i] = html5Types[i].trim().toLowerCase();
}
Arrays.sort(html5Types);
}
// remember that page tool was reset, so we need to give user the option
// of going to the last page from the previous session
SimplePageToolDao.PageData lastPage = simplePageBean.toolWasReset();
// if this page was copied from another site we may have to update links
// can only do the fixups if you can write. We could hack permissions, but
// I assume a site owner will access the site first
if (canEditPage)
simplePageBean.maybeUpdateLinks();
// if starting the tool, sendingpage isn't set. the following call
// will give us the top page.
SimplePage currentPage = simplePageBean.getCurrentPage();
// now we need to find our own item, for access checks, etc.
SimplePageItem pageItem = null;
if (currentPage != null) {
pageItem = simplePageBean.getCurrentPageItem(params.getItemId());
}
// one more security check: make sure the item actually involves this
// page.
// otherwise someone could pass us an item from a different page in
// another site
// actually this normally happens if the page doesn't exist and we don't
// have permission to create it
if (currentPage == null || pageItem == null ||
(pageItem.getType() != SimplePageItem.STUDENT_CONTENT &&Long.valueOf(pageItem.getSakaiId()) != currentPage.getPageId())) {
log.warn("ShowPage item not in page");
UIOutput.make(tofill, "error-div");
if (currentPage == null)
// most likely tool was created by site info but no page
// has created. It will created the first time an item is created,
// so from a user point of view it looks like no item has been added
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.noitems_error_user"));
else
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.not_available"));
return;
}
// check two parts of isitemvisible where we want to give specific errors
// potentially need time zone for setting release date
if (!canSeeAll && currentPage.getReleaseDate() != null && currentPage.getReleaseDate().after(new Date())) {
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, M_locale);
TimeZone tz = timeService.getLocalTimeZone();
df.setTimeZone(tz);
String releaseDate = df.format(currentPage.getReleaseDate());
String releaseMessage = messageLocator.getMessage("simplepage.not_yet_available_releasedate").replace("{}", releaseDate);
UIOutput.make(tofill, "error-div");
UIOutput.make(tofill, "error", releaseMessage);
return;
}
// the only thing not already tested in isItemVisible is groups. In theory
// no one should have a URL to a page for which they aren't in the group,
// so I'm not trying to give a better message than just hidden
if (!canSeeAll && currentPage.isHidden() || !simplePageBean.isItemVisible(pageItem)) {
UIOutput.make(tofill, "error-div");
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.not_available_hidden"));
return;
}
// I believe we've now checked all the args for permissions issues. All
// other item and
// page references are generated here based on the contents of the page
// and items.
// needed to process path arguments first, so refresh page goes the right page
if (simplePageBean.getTopRefresh()) {
UIOutput.make(tofill, "refresh");
return; // but there's no point doing anything more
}
// error from previous operation
// consumes the message, so don't do it if refreshing
List<String> errMessages = simplePageBean.errMessages();
if (errMessages != null) {
UIOutput.make(tofill, "error-div");
for (String e: errMessages) {
UIBranchContainer er = UIBranchContainer.make(tofill, "errors:");
UIOutput.make(er, "error-message", e);
}
}
if (canEditPage) {
// special instructor-only javascript setup.
// but not if we're refreshing
UIOutput.make(tofill, "instructoronly");
// Chome and IE will abort a page if some on it was input from
// a previous submit. I.e. if an HTML editor was used. In theory they
// only do this if part of it is Javascript, but in practice they do
// it for images as well. The protection isn't worthwhile, since it only
// protects the first time. Since it will reesult in a garbled page,
// people will just refresh the page, and then they'll get the new
// contents. The Chrome guys refuse to fix this so it just applies to Javascript
httpServletResponse.setHeader("X-XSS-Protection", "0");
}
if (currentPage == null || pageItem == null) {
UIOutput.make(tofill, "error-div");
if (canEditPage) {
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.impossible1"));
} else {
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.not_available"));
}
return;
}
// Set up customizable CSS
ContentResource cssLink = simplePageBean.getCssForCurrentPage();
if(cssLink != null) {
UIOutput.make(tofill, "customCSS").decorate(new UIFreeAttributeDecorator("href", cssLink.getUrl()));
}
// offer to go to saved page if this is the start of a session, in case
// user has logged off and logged on again.
// need to offer to go to previous page? even if a new session, no need
// if we're already on that page
if (lastPage != null && lastPage.pageId != currentPage.getPageId()) {
UIOutput.make(tofill, "refreshAlert");
UIOutput.make(tofill, "refresh-message", messageLocator.getMessage("simplepage.last-visited"));
// Should simply refresh
GeneralViewParameters p = new GeneralViewParameters(VIEW_ID);
p.setSendingPage(lastPage.pageId);
p.setItemId(lastPage.itemId);
// reset the path to the saved one
p.setPath("log");
String name = lastPage.name;
// Titles are set oddly by Student Content Pages
SimplePage lastPageObj = simplePageToolDao.getPage(lastPage.pageId);
if(lastPageObj.getOwner() != null) {
name = lastPageObj.getTitle();
}
UIInternalLink.make(tofill, "refresh-link", name, p);
}
// path is the breadcrumbs. Push, pop or reset depending upon path=
// programmer documentation.
String title;
String ownerName = null;
if(pageItem.getType() != SimplePageItem.STUDENT_CONTENT) {
title = pageItem.getName();
}else {
title = currentPage.getTitle();
if(!pageItem.isAnonymous() || canEditPage) {
try {
String owner = currentPage.getOwner();
String group = currentPage.getGroup();
if (group != null)
ownerName = simplePageBean.getCurrentSite().getGroup(group).getTitle();
else
ownerName = UserDirectoryService.getUser(owner).getDisplayName();
} catch (Exception ignore) {};
if (ownerName != null && !ownerName.equals(title))
title += " (" + ownerName + ")";
}
}
String newPath = null;
// If the path is "none", then we don't want to record this page as being viewed, or set a path
if(!params.getPath().equals("none")) {
newPath = simplePageBean.adjustPath(params.getPath(), currentPage.getPageId(), pageItem.getId(), title);
simplePageBean.adjustBackPath(params.getBackPath(), currentPage.getPageId(), pageItem.getId(), pageItem.getName());
}
// put out link to index of pages
GeneralViewParameters showAll = new GeneralViewParameters(PagePickerProducer.VIEW_ID);
showAll.setSource("summary");
UIInternalLink.make(tofill, "show-pages", messageLocator.getMessage("simplepage.showallpages"), showAll);
if (canEditPage) {
// show tool bar, but not if coming from grading pane
if(!cameFromGradingPane) {
createToolBar(tofill, currentPage, (pageItem.getType() == SimplePageItem.STUDENT_CONTENT));
}
UIOutput.make(tofill, "title-descrip");
String label = null;
if (pageItem.getType() == SimplePageItem.STUDENT_CONTENT)
label = messageLocator.getMessage("simplepage.editTitle");
else
label = messageLocator.getMessage("simplepage.title");
String descrip = null;
if (pageItem.getType() == SimplePageItem.STUDENT_CONTENT)
descrip = messageLocator.getMessage("simplepage.title-student-descrip");
else if (pageItem.getPageId() == 0)
descrip = messageLocator.getMessage("simplepage.title-top-descrip");
else
descrip = messageLocator.getMessage("simplepage.title-descrip");
UIOutput.make(tofill, "edit-title").decorate(new UIFreeAttributeDecorator("title", descrip));
UIOutput.make(tofill, "edit-title-text", label);
UIOutput.make(tofill, "title-descrip-text", descrip);
if (pageItem.getPageId() == 0 && currentPage.getOwner() == null) { // top level page
// need dropdown
UIOutput.make(tofill, "dropdown");
UIOutput.make(tofill, "moreDiv");
UIOutput.make(tofill, "new-page").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.new-page-tooltip")));
UIOutput.make(tofill, "import-cc").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.import_cc.tooltip")));
UIOutput.make(tofill, "export-cc").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.export_cc.tooltip")));
}
// Checks to see that user can edit and that this is either a top level page,
// or a top level student page (not a subpage to a student page)
if(simplePageBean.getEditPrivs() == 0 && (pageItem.getPageId() == 0)) {
UIOutput.make(tofill, "remove-li");
UIOutput.make(tofill, "remove-page").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.remove-page-tooltip")));
} else if (simplePageBean.getEditPrivs() == 0 && currentPage.getOwner() != null) {
// getEditPrivs < 2 if we want to let the student delete. Currently we don't. There can be comments
// from other students and the page can be shared
SimpleStudentPage studentPage = simplePageToolDao.findStudentPage(currentPage.getTopParent());
if (studentPage != null && studentPage.getPageId() == currentPage.getPageId()) {
System.out.println("is student page 2");
UIOutput.make(tofill, "remove-student");
UIOutput.make(tofill, "remove-page-student").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.remove-student-page-explanation")));
}
}
UIOutput.make(tofill, "dialogDiv");
} else if (!canReadPage) {
return;
} else if (!canSeeAll) {
// see if there are any unsatisfied prerequisites
// if this isn't a top level page, this will check that the page above is
// accessible. That matters because we check visible, available and release
// only for this page but not for the containing page
List<String> needed = simplePageBean.pagesNeeded(pageItem);
if (needed.size() > 0) {
// yes. error and abort
if (pageItem.getPageId() != 0) {
// not top level. This should only happen from a "next"
// link.
// at any rate, the best approach is to send the user back
// to the calling page
List<SimplePageBean.PathEntry> path = simplePageBean.getHierarchy();
SimplePageBean.PathEntry containingPage = null;
if (path.size() > 1) {
// page above this. this page is on the top
containingPage = path.get(path.size() - 2);
}
if (containingPage != null) { // not a top level page, point
// to containing page
GeneralViewParameters view = new GeneralViewParameters(VIEW_ID);
view.setSendingPage(containingPage.pageId);
view.setItemId(containingPage.pageItemId);
view.setPath(Integer.toString(path.size() - 2));
UIInternalLink.make(tofill, "redirect-link", containingPage.title, view);
UIOutput.make(tofill, "redirect");
} else {
UIOutput.make(tofill, "error-div");
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.not_available"));
}
return;
}
// top level page where prereqs not satisified. Output list of
// pages he needs to do first
UIOutput.make(tofill, "pagetitle", currentPage.getTitle());
UIOutput.make(tofill, "error-div");
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.has_prerequistes"));
UIBranchContainer errorList = UIBranchContainer.make(tofill, "error-list:");
for (String errorItem : needed) {
UIBranchContainer errorListItem = UIBranchContainer.make(errorList, "error-item:");
UIOutput.make(errorListItem, "error-item-text", errorItem);
}
return;
}
}
ToolSession toolSession = SessionManager.getCurrentToolSession();
String helpurl = (String)toolSession.getAttribute("sakai-portal:help-action");
String reseturl = (String)toolSession.getAttribute("sakai-portal:reset-action");
String skinName = null;
String skinRepo = null;
String iconBase = null;
UIComponent titlediv = UIOutput.make(tofill, "titlediv");
// we need to do special CSS for old portal
if (helpurl == null)
titlediv.decorate(new UIStyleDecorator("oldPortal"));
if (helpurl != null || reseturl != null) {
// these URLs are defined if we're in the neo portal
// in that case we need our own help and reset icons. We want
// to take them from the current skin, so find its prefix.
// unfortunately the neoportal tacks neo- on front of the skin
// name, so this is more complex than you might think.
skinRepo = ServerConfigurationService.getString("skin.repo", "/library/skin");
iconBase = skinRepo + "/" + CSSUtils.adjustCssSkinFolder(null) + "/images";
UIVerbatim.make(tofill, "iconstyle", ICONSTYLE.replace("{}", iconBase));
}
if (helpurl != null) {
UILink.make(tofill, (pageItem.getPageId() == 0 ? "helpbutton" : "helpbutton2")).
decorate(new UIFreeAttributeDecorator("onclick",
"openWindow('" + helpurl + "', 'Help', 'resizeable=yes,toolbar=no,scrollbars=yes,menubar=yes,width=800,height=600'); return false")).
decorate(new UIFreeAttributeDecorator("title",
messageLocator.getMessage("simplepage.help-button")));
UIOutput.make(tofill, (pageItem.getPageId() == 0 ? "helpimage" : "helpimage2")).
decorate(new UIFreeAttributeDecorator("alt",
messageLocator.getMessage("simplepage.help-button")));
UIOutput.make(tofill, (pageItem.getPageId() == 0 ? "helpnewwindow" : "helpnewwindow2"),
messageLocator.getMessage("simplepage.opens-in-new"));
}
if (reseturl != null) {
UILink.make(tofill, (pageItem.getPageId() == 0 ? "resetbutton" : "resetbutton2")).
decorate(new UIFreeAttributeDecorator("onclick",
"location.href='" + reseturl + "'; return false")).
decorate(new UIFreeAttributeDecorator("title",
messageLocator.getMessage("simplepage.reset-button")));
UIOutput.make(tofill, (pageItem.getPageId() == 0 ? "resetimage" : "resetimage2")).
decorate(new UIFreeAttributeDecorator("alt",
messageLocator.getMessage("simplepage.reset-button")));
}
// note page accessed. the code checks to see whether all the required
// items on it have been finished, and if so marks it complete, else just updates
// access date save the path because if user goes to it later we want to restore the
// breadcrumbs
if(newPath != null) {
if(pageItem.getType() != SimplePageItem.STUDENT_CONTENT) {
simplePageBean.track(pageItem.getId(), newPath);
}else {
simplePageBean.track(pageItem.getId(), newPath, currentPage.getPageId());
}
}
UIOutput.make(tofill, "pagetitle", currentPage.getTitle());
if(currentPage.getOwner() != null && simplePageBean.getEditPrivs() == 0) {
SimpleStudentPage student = simplePageToolDao.findStudentPageByPageId(currentPage.getPageId());
// Make sure this is a top level student page
if(student != null && pageItem.getGradebookId() != null) {
UIOutput.make(tofill, "gradingSpan");
UIOutput.make(tofill, "commentsUUID", String.valueOf(student.getId()));
UIOutput.make(tofill, "commentPoints", String.valueOf((student.getPoints() != null? student.getPoints() : "")));
UIOutput pointsBox = UIOutput.make(tofill, "studentPointsBox");
UIOutput.make(tofill, "topmaxpoints", String.valueOf((pageItem.getGradebookPoints() != null? pageItem.getGradebookPoints():"")));
if (ownerName != null)
pointsBox.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.grade-for-student").replace("{}",ownerName)));
List<SimpleStudentPage> studentPages = simplePageToolDao.findStudentPages(student.getItemId());
Collections.sort(studentPages, new Comparator<SimpleStudentPage>() {
public int compare(SimpleStudentPage o1, SimpleStudentPage o2) {
String title1 = o1.getTitle();
if (title1 == null)
title1 = "";
String title2 = o2.getTitle();
if (title2 == null)
title2 = "";
return title1.compareTo(title2);
}
});
for(int in = 0; in < studentPages.size(); in++) {
if(studentPages.get(in).isDeleted()) {
studentPages.remove(in);
}
}
int i = -1;
for(int in = 0; in < studentPages.size(); in++) {
if(student.getId() == studentPages.get(in).getId()) {
i = in;
break;
}
}
if(i > 0) {
GeneralViewParameters eParams = new GeneralViewParameters(ShowPageProducer.VIEW_ID, studentPages.get(i-1).getPageId());
eParams.setItemId(studentPages.get(i-1).getItemId());
eParams.setPath("next");
UIInternalLink.make(tofill, "gradingBack", eParams);
}
if(i < studentPages.size() - 1) {
GeneralViewParameters eParams = new GeneralViewParameters(ShowPageProducer.VIEW_ID, studentPages.get(i+1).getPageId());
eParams.setItemId(studentPages.get(i+1).getItemId());
eParams.setPath("next");
UIInternalLink.make(tofill, "gradingForward", eParams);
}
printGradingForm(tofill);
}
}
// breadcrumbs
if (pageItem.getPageId() != 0) {
// Not top-level, so we have to show breadcrumbs
List<SimplePageBean.PathEntry> breadcrumbs = simplePageBean.getHierarchy();
int index = 0;
if (breadcrumbs.size() > 1 || reseturl != null || helpurl != null) {
UIOutput.make(tofill, "crumbdiv");
if (breadcrumbs.size() > 1)
for (SimplePageBean.PathEntry e : breadcrumbs) {
// don't show current page. We already have a title. This
// was too much
UIBranchContainer crumb = UIBranchContainer.make(tofill, "crumb:");
GeneralViewParameters view = new GeneralViewParameters(VIEW_ID);
view.setSendingPage(e.pageId);
view.setItemId(e.pageItemId);
view.setPath(Integer.toString(index));
if (index < breadcrumbs.size() - 1) {
// Not the last item
UIInternalLink.make(crumb, "crumb-link", e.title, view);
UIOutput.make(crumb, "crumb-follow", " > ");
} else {
UIOutput.make(crumb, "crumb-follow", e.title).decorate(new UIStyleDecorator("bold"));
}
index++;
}
}
}
// see if there's a next item in sequence.
simplePageBean.addPrevLink(tofill, pageItem);
simplePageBean.addNextLink(tofill, pageItem);
// swfObject is not currently used
boolean shownSwfObject = false;
// items to show
List<SimplePageItem> itemList = (List<SimplePageItem>) simplePageBean.getItemsOnPage(currentPage.getPageId());
// Move all items with sequence <= 0 to the end of the list.
// Count is necessary to guarantee we don't infinite loop over a
// list that only has items with sequence <= 0.
// Becauses sequence number is < 0, these start out at the beginning
int count = 1;
while(itemList.size() > count && itemList.get(0).getSequence() <= 0) {
itemList.add(itemList.remove(0));
count++;
}
// Make sure we only add the comments javascript file once,
// even if there are multiple comments tools on the page.
boolean addedCommentsScript = false;
int commentsCount = 0;
// Find the most recent comment on the page by current user
long postedCommentId = -1;
if (params.postedComment) {
postedCommentId = findMostRecentComment();
}
//
//
// MAIN list of items
//
// produce the main table
// Is anything visible?
// Note that we don't need to check whether any item is available, since the first visible
// item is always available.
boolean anyItemVisible = false;
if (itemList.size() > 0) {
UIBranchContainer container = UIBranchContainer.make(tofill, "itemContainer:");
boolean showRefresh = false;
int textboxcount = 1;
UIBranchContainer tableContainer = UIBranchContainer.make(container, "itemTable:");
// formatting: two columns:
// 1: edit buttons, omitted for student
// 2: main content
// For links, which have status icons, the main content is a flush
// left div with the icon
// followed by a div with margin-left:30px. That takes it beyond the
// icon, and avoids the
// wrap-around appearance you'd get without the margin.
// Normally the description is shown as a second div with
// indentation in the CSS.
// That puts it below the link. However with a link that's a button,
// we do float left
// for the button so the text wraps around it. I think that's
// probably what people would expect.
UIOutput.make(tableContainer, "colgroup");
if (canEditPage) {
UIOutput.make(tableContainer, "col1");
}
UIOutput.make(tableContainer, "col2");
// our accessiblity people say not to use TH for except for a data table
// the table header is for accessibility tools only, so it's
// positioned off screen
//if (canEditPage) {
// UIOutput.make(tableContainer, "header-edits");
// }
// UIOutput.make(tableContainer, "header-items");
for (SimplePageItem i : itemList) {
// listitem is mostly historical. it uses some shared HTML, but
// if I were
// doing it from scratch I wouldn't make this distinction. At
// the moment it's
// everything that isn't inline.
boolean listItem = !(i.getType() == SimplePageItem.TEXT || i.getType() == SimplePageItem.MULTIMEDIA
|| i.getType() == SimplePageItem.COMMENTS || i.getType() == SimplePageItem.STUDENT_CONTENT
|| i.getType() == SimplePageItem.QUESTION || i.getType() == SimplePageItem.PEEREVAL);
// (i.getType() == SimplePageItem.PAGE &&
// "button".equals(i.getFormat())))
if (!simplePageBean.isItemVisible(i, currentPage)) {
continue;
}
anyItemVisible = true;
UIBranchContainer tableRow = UIBranchContainer.make(tableContainer, "item:");
// set class name showing what the type is, so people can do funky CSS
String itemClassName = null;
switch (i.getType()) {
case SimplePageItem.RESOURCE: itemClassName = "resourceType"; break;
case SimplePageItem.PAGE: itemClassName = "pageType"; break;
case SimplePageItem.ASSIGNMENT: itemClassName = "assignmentType"; break;
case SimplePageItem.ASSESSMENT: itemClassName = "assessmentType"; break;
case SimplePageItem.TEXT: itemClassName = "textType"; break;
case SimplePageItem.URL: itemClassName = "urlType"; break;
case SimplePageItem.MULTIMEDIA: itemClassName = "multimediaType"; break;
case SimplePageItem.FORUM: itemClassName = "forumType"; break;
case SimplePageItem.COMMENTS: itemClassName = "commentsType"; break;
case SimplePageItem.STUDENT_CONTENT: itemClassName = "studentContentType"; break;
case SimplePageItem.QUESTION: itemClassName = "question"; break;
case SimplePageItem.BLTI: itemClassName = "bltiType"; break;
case SimplePageItem.PEEREVAL: itemClassName = "peereval"; break;
}
if (listItem){
itemClassName = itemClassName + " listType";
}
if (canEditPage) {
itemClassName = itemClassName + " canEdit";
}
tableRow.decorate(new UIFreeAttributeDecorator("class", itemClassName));
// you really need the HTML file open at the same time to make
// sense of the following code
if (listItem) { // Not an HTML Text, Element or Multimedia
// Element
if (canEditPage) {
UIOutput.make(tableRow, "current-item-id2", String.valueOf(i.getId()));
}
// users can declare a page item to be navigational. If so
// we display
// it to the left of the normal list items, and use a
// button. This is
// used for pages that are "next" pages, i.e. they replace
// this page
// rather than creating a new level in the breadcrumbs.
// Since they can't
// be required, they don't need the status image, which is
// good because
// they're displayed with colspan=2, so there's no space for
// the image.
boolean navButton = "button".equals(i.getFormat()) && !i.isRequired();
boolean notDone = false;
Status status = Status.NOT_REQUIRED;
if (!navButton) {
status = handleStatusImage(tableRow, i);
if (status == Status.REQUIRED) {
notDone = true;
}
}
boolean isInline = (i.getType() == SimplePageItem.BLTI && "inline".equals(i.getFormat()));
UIOutput linktd = UIOutput.make(tableRow, "item-td");
UIBranchContainer linkdiv = null;
if (!isInline) {
linkdiv = UIBranchContainer.make(tableRow, "link-div:");
UIOutput itemicon = UIOutput.make(linkdiv,"item-icon");
switch (i.getType()) {
case SimplePageItem.FORUM:
itemicon.decorate(new UIFreeAttributeDecorator("src", "/library/image/silk/comments.png"));
break;
case SimplePageItem.ASSIGNMENT:
itemicon.decorate(new UIFreeAttributeDecorator("src", "/library/image/silk/page_edit.png"));
break;
case SimplePageItem.ASSESSMENT:
itemicon.decorate(new UIFreeAttributeDecorator("src", "/library/image/silk/pencil.png"));
break;
case SimplePageItem.BLTI:
itemicon.decorate(new UIFreeAttributeDecorator("src", "/library/image/silk/application_go.png"));
break;
case SimplePageItem.PAGE:
itemicon.decorate(new UIFreeAttributeDecorator("src", "/library/image/silk/book_open.png"));
break;
case SimplePageItem.RESOURCE:
String mimeType = i.getHtml();
if("application/octet-stream".equals(mimeType)) {
// OS X reports octet stream for things like MS Excel documents.
// Force a mimeType lookup so we get a decent icon.
mimeType = null;
}
if (mimeType == null || mimeType.equals("")) {
String s = i.getSakaiId();
int j = s.lastIndexOf(".");
if (j >= 0)
s = s.substring(j+1);
mimeType = ContentTypeImageService.getContentType(s);
// System.out.println("type " + s + ">" + mimeType);
}
String src = null;
if (!useSakaiIcons)
src = imageToMimeMap.get(mimeType);
if (src == null) {
String image = ContentTypeImageService.getContentTypeImage(mimeType);
if (image != null)
src = "/library/image/" + image;
}
if(src != null) {
itemicon.decorate(new UIFreeAttributeDecorator("src", src));
}
break;
}
}
UIOutput descriptiondiv = null;
// refresh isn't actually used anymore. We've changed the
// way things are
// done so the user never has to request a refresh.
// FYI: this actually puts in an IFRAME for inline BLTI items
showRefresh = !makeLink(tableRow, "link", i, canSeeAll, currentPage, notDone, status) || showRefresh;
UILink.make(tableRow, "copylink", i.getName(), "http://lessonbuilder.sakaiproject.org/" + i.getId() + "/").
decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.copylink2").replace("{}", i.getName())));
// dummy is used when an assignment, quiz, or forum item is
// copied
// from another site. The way the copy code works, our
// import code
// doesn't have access to the necessary info to use the item
// from the
// new site. So we add a dummy, which generates an
// explanation that the
// author is going to have to choose the item from the
// current site
if (i.getSakaiId().equals(SimplePageItem.DUMMY)) {
String code = null;
switch (i.getType()) {
case SimplePageItem.ASSIGNMENT:
code = "simplepage.copied.assignment";
break;
case SimplePageItem.ASSESSMENT:
code = "simplepage.copied.assessment";
break;
case SimplePageItem.FORUM:
code = "simplepage.copied.forum";
break;
}
descriptiondiv = UIOutput.make(tableRow, "description", messageLocator.getMessage(code));
} else {
descriptiondiv = UIOutput.make(tableRow, "description", i.getDescription());
}
if (isInline)
descriptiondiv.decorate(new UIFreeAttributeDecorator("style", "margin-top: 4px"));
if (!isInline) {
// nav button gets float left so any description goes to its
// right. Otherwise the
// description block will display underneath
if ("button".equals(i.getFormat())) {
linkdiv.decorate(new UIFreeAttributeDecorator("style", "float:none"));
}
// for accessibility
if (navButton) {
linkdiv.decorate(new UIFreeAttributeDecorator("role", "navigation"));
}
}
// note that a lot of the info here is used by the
// javascript that prepares
// the jQuery dialogs
if (canEditPage) {
UIOutput.make(tableRow, "edit-td");
UILink.make(tableRow, "edit-link", messageLocator.getMessage("simplepage.editItem"), "").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.generic").replace("{}", i.getName())));
// the following information is displayed using <INPUT
// type=hidden ...
// it contains information needed to populate the "edit"
// popup dialog
UIOutput.make(tableRow, "prerequisite-info", String.valueOf(i.isPrerequisite()));
String itemGroupString = null;
boolean entityDeleted = false;
boolean notPublished = false;
if (i.getType() == SimplePageItem.ASSIGNMENT) {
// the type indicates whether scoring is letter
// grade, number, etc.
// the javascript needs this to present the right
// choices to the user
// types 6 and 8 aren't legal scoring types, so they
// are used as
// markers for quiz or forum. I ran out of numbers
// and started using
// text for things that aren't scoring types. That's
// better anyway
int type = 4;
LessonEntity assignment = null;
if (!i.getSakaiId().equals(SimplePageItem.DUMMY)) {
assignment = assignmentEntity.getEntity(i.getSakaiId(), simplePageBean);
if (assignment != null) {
type = assignment.getTypeOfGrade();
String editUrl = assignment.editItemUrl(simplePageBean);
if (editUrl != null) {
UIOutput.make(tableRow, "edit-url", editUrl);
}
itemGroupString = simplePageBean.getItemGroupString(i, assignment, true);
UIOutput.make(tableRow, "item-groups", itemGroupString);
if (!assignment.objectExists())
entityDeleted = true;
}
}
UIOutput.make(tableRow, "type", String.valueOf(type));
String requirement = String.valueOf(i.getSubrequirement());
if ((type == SimplePageItem.PAGE || type == SimplePageItem.ASSIGNMENT) && i.getSubrequirement()) {
requirement = i.getRequirementText();
}
UIOutput.make(tableRow, "requirement-text", requirement);
} else if (i.getType() == SimplePageItem.ASSESSMENT) {
UIOutput.make(tableRow, "type", "6"); // Not used by
// assignments,
// so it is
// safe to dedicate to assessments
UIOutput.make(tableRow, "requirement-text", (i.getSubrequirement() ? i.getRequirementText() : "false"));
LessonEntity quiz = quizEntity.getEntity(i.getSakaiId(),simplePageBean);
if (quiz != null) {
String editUrl = quiz.editItemUrl(simplePageBean);
if (editUrl != null) {
UIOutput.make(tableRow, "edit-url", editUrl);
}
editUrl = quiz.editItemSettingsUrl(simplePageBean);
if (editUrl != null) {
UIOutput.make(tableRow, "edit-settings-url", editUrl);
}
itemGroupString = simplePageBean.getItemGroupString(i, quiz, true);
UIOutput.make(tableRow, "item-groups", itemGroupString);
if (!quiz.objectExists())
entityDeleted = true;
} else
notPublished = quizEntity.notPublished(i.getSakaiId());
} else if (i.getType() == SimplePageItem.BLTI) {
UIOutput.make(tableRow, "type", "b");
LessonEntity blti= (bltiEntity == null ? null : bltiEntity.getEntity(i.getSakaiId()));
if (blti != null) {
String editUrl = blti.editItemUrl(simplePageBean);
if (editUrl != null)
UIOutput.make(tableRow, "edit-url", editUrl);
UIOutput.make(tableRow, "item-format", i.getFormat());
if (i.getHeight() != null)
UIOutput.make(tableRow, "item-height", i.getHeight());
itemGroupString = simplePageBean.getItemGroupString(i, null, true);
UIOutput.make(tableRow, "item-groups", itemGroupString );
if (!blti.objectExists())
entityDeleted = true;
}
} else if (i.getType() == SimplePageItem.FORUM) {
UIOutput.make(tableRow, "extra-info");
UIOutput.make(tableRow, "type", "8");
LessonEntity forum = forumEntity.getEntity(i.getSakaiId());
if (forum != null) {
String editUrl = forum.editItemUrl(simplePageBean);
if (editUrl != null) {
UIOutput.make(tableRow, "edit-url", editUrl);
}
itemGroupString = simplePageBean.getItemGroupString(i, forum, true);
UIOutput.make(tableRow, "item-groups", itemGroupString);
if (!forum.objectExists())
entityDeleted = true;
}
} else if (i.getType() == SimplePageItem.PAGE) {
UIOutput.make(tableRow, "type", "page");
UIOutput.make(tableRow, "page-next", Boolean.toString(i.getNextPage()));
UIOutput.make(tableRow, "page-button", Boolean.toString("button".equals(i.getFormat())));
itemGroupString = simplePageBean.getItemGroupString(i, null, true);
UIOutput.make(tableRow, "item-groups", itemGroupString);
} else if (i.getType() == SimplePageItem.RESOURCE) {
try {
itemGroupString = simplePageBean.getItemGroupStringOrErr(i, null, true);
} catch (IdUnusedException e) {
itemGroupString = "";
entityDeleted = true;
}
if (simplePageBean.getInherited())
UIOutput.make(tableRow, "item-groups", "--inherited--");
else
UIOutput.make(tableRow, "item-groups", itemGroupString );
UIOutput.make(tableRow, "item-samewindow", Boolean.toString(i.isSameWindow()));
UIVerbatim.make(tableRow, "item-path", getItemPath(i));
}
String releaseString = simplePageBean.getReleaseString(i);
if (itemGroupString != null || releaseString != null || entityDeleted || notPublished) {
if (itemGroupString != null)
itemGroupString = simplePageBean.getItemGroupTitles(itemGroupString, i);
if (itemGroupString != null) {
itemGroupString = " [" + itemGroupString + "]";
if (releaseString != null)
itemGroupString = " " + releaseString + itemGroupString;
} else if (releaseString != null)
itemGroupString = " " + releaseString;
if (notPublished) {
if (itemGroupString != null)
itemGroupString = itemGroupString + " " +
messageLocator.getMessage("simplepage.not-published");
else
itemGroupString = messageLocator.getMessage("simplepage.not-published");
}
if (entityDeleted) {
if (itemGroupString != null)
itemGroupString = itemGroupString + " " +
messageLocator.getMessage("simplepage.deleted-entity");
else
itemGroupString = messageLocator.getMessage("simplepage.deleted-entity");
}
if (itemGroupString != null)
UIOutput.make(tableRow, (isInline ? "item-group-titles-div" : "item-group-titles"), itemGroupString);
}
}
// the following are for the inline item types. Multimedia
// is the most complex because
// it can be IMG, IFRAME, or OBJECT, and Youtube is treated
// separately
} else if (i.getType() == SimplePageItem.MULTIMEDIA) {
// This code should be read together with the code in SimplePageBean
// that sets up this data, method addMultimedia. Most display is set
// up here, but note that show-page.js invokes the jquery oembed on all
// <A> items with class="oembed".
// historically this code was to display files ,and urls leading to things
// like MP4. as backup if we couldn't figure out what to do we'd put something
// in an iframe. The one exception is youtube, which we supposed explicitly.
// However we now support several ways to embed content. We use the
// multimediaDisplayType code to indicate which. The codes are
// 1 -- embed code, 2 -- av type, 3 -- oembed, 4 -- iframe
// 2 is the original code: MP4, image, and as a special case youtube urls
// since we have old entries with no type code, and that behave the same as
// 2, we start by converting 2 to null.
// then the logic is
// if type == null & youtube, do youtube
// if type == null & image, do iamge
// if type == null & not HTML do MP4 or other player for file
// final fallthrough to handel the new types, with IFRAME if all else fails
// the old code creates ojbects in ContentHosting for both files and URLs.
// The new code saves the embed code or URL itself as an atteibute of the item
// If I were doing it again, I wouldn't create the ContebtHosting item
// Note that IFRAME is only used for something where the far end claims the MIME
// type is HTML. For weird stuff like MS Word files I use the file display code, which
// will end up producing <OBJECT>.
// the reason this code is complex is that we try to choose
// the best
// HTML for displaying the particular type of object. We've
// added complexities
// over time as we get more experience with different
// object types and browsers.
String itemGroupString = null;
String itemGroupTitles = null;
boolean entityDeleted = false;
// new format explicit display indication
String mmDisplayType = i.getAttribute("multimediaDisplayType");
// 2 is the generic "use old display" so treat it as null
if ("".equals(mmDisplayType) || "2".equals(mmDisplayType))
mmDisplayType = null;
if (canSeeAll) {
try {
itemGroupString = simplePageBean.getItemGroupStringOrErr(i, null, true);
} catch (IdUnusedException e) {
itemGroupString = "";
entityDeleted = true;
}
itemGroupTitles = simplePageBean.getItemGroupTitles(itemGroupString, i);
if (entityDeleted) {
if (itemGroupTitles != null)
itemGroupTitles = itemGroupTitles + " " + messageLocator.getMessage("simplepage.deleted-entity");
else
itemGroupTitles = messageLocator.getMessage("simplepage.deleted-entity");
}
if (itemGroupTitles != null) {
itemGroupTitles = "[" + itemGroupTitles + "]";
}
UIOutput.make(tableRow, "item-groups", itemGroupString);
} else if (entityDeleted)
continue;
if (!"1".equals(mmDisplayType) && !"3".equals(mmDisplayType))
UIVerbatim.make(tableRow, "item-path", getItemPath(i));
// the reason this code is complex is that we try to choose
// the best
// HTML for displaying the particular type of object. We've
// added complexities
// over time as we get more experience with different
// object types and browsers.
StringTokenizer token = new StringTokenizer(i.getSakaiId(), ".");
String extension = "";
while (token.hasMoreTokens()) {
extension = token.nextToken().toLowerCase();
}
// the extension is almost never used. Normally we have
// the MIME type and use it. Extension is used only if
// for some reason we don't have the MIME type
UIComponent item;
String youtubeKey;
Length width = null;
if (i.getWidth() != null) {
width = new Length(i.getWidth());
}
Length height = null;
if (i.getHeight() != null) {
height = new Length(i.getHeight());
}
// Get the MIME type. For multimedia types is should be in
// the html field.
// The old code saved the URL there. So if it looks like a
// URL ignore it.
String mimeType = i.getHtml();
if (mimeType != null && (mimeType.startsWith("http") || mimeType.equals(""))) {
mimeType = null;
}
// here goes. dispatch on the type and produce the right tag
// type,
// followed by the hidden INPUT tags with information for the
// edit dialog
if (mmDisplayType == null && simplePageBean.isImageType(i)) {
if(canSeeAll || simplePageBean.isItemAvailable(i)) {
UIOutput.make(tableRow, "imageSpan");
if (itemGroupString != null) {
UIOutput.make(tableRow, "item-group-titles3", itemGroupTitles);
UIOutput.make(tableRow, "item-groups3", itemGroupString);
}
String imageName = i.getAlt();
if (imageName == null || imageName.equals("")) {
imageName = abbrevUrl(i.getURL());
}
item = UIOutput.make(tableRow, "image").decorate(new UIFreeAttributeDecorator("src", i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner()))).decorate(new UIFreeAttributeDecorator("alt", imageName));
if (lengthOk(width)) {
item.decorate(new UIFreeAttributeDecorator("width", width.getOld()));
}
if(lengthOk(height)) {
item.decorate(new UIFreeAttributeDecorator("height", height.getOld()));
}
} else {
UIComponent notAvailableText = UIOutput.make(tableRow, "notAvailableText", messageLocator.getMessage("simplepage.textItemUnavailable"));
// Grey it out
notAvailableText.decorate(new UIFreeAttributeDecorator("class", "disabled-text-item"));
}
// stuff for the jquery dialog
if (canEditPage) {
UIOutput.make(tableRow, "imageHeight", getOrig(height));
UIOutput.make(tableRow, "imageWidth", getOrig(width));
UIOutput.make(tableRow, "mimetype2", mimeType);
UIOutput.make(tableRow, "current-item-id4", Long.toString(i.getId()));
UIOutput.make(tableRow, "editmm-td");
UILink.make(tableRow, "iframe-edit", messageLocator.getMessage("simplepage.editItem"), "").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.url").replace("{}", abbrevUrl(i.getURL()))));
}
UIOutput.make(tableRow, "description2", i.getDescription());
} else if (mmDisplayType == null && (youtubeKey = simplePageBean.getYoutubeKey(i)) != null) {
String youtubeUrl = SimplePageBean.getYoutubeUrlFromKey(youtubeKey);
if(canSeeAll || simplePageBean.isItemAvailable(i)) {
UIOutput.make(tableRow, "youtubeSpan");
if (itemGroupString != null) {
UIOutput.make(tableRow, "item-group-titles4", itemGroupTitles);
UIOutput.make(tableRow, "item-groups4", itemGroupString);
}
// if width is blank or 100% scale the height
if (width != null && height != null && !height.number.equals("")) {
if (width.number.equals("") && width.unit.equals("") || width.number.equals("100") && width.unit.equals("%")) {
int h = Integer.parseInt(height.number);
if (h > 0) {
width.number = Integer.toString((int) Math.round(h * 1.641025641));
width.unit = height.unit;
}
}
}
// <object style="height: 390px; width: 640px"><param
// name="movie"
// value="http://www.youtube.com/v/AKIC7OQqBrA?version=3"><param
// name="allowFullScreen" value="true"><param
// name="allowScriptAccess" value="always"><embed
// src="http://www.youtube.com/v/AKIC7OQqBrA?version=3"
// type="application/x-shockwave-flash"
// allowfullscreen="true" allowScriptAccess="always"
// width="640" height="390"></object>
item = UIOutput.make(tableRow, "youtubeIFrame");
// youtube seems ok with length and width
if(lengthOk(height)) {
item.decorate(new UIFreeAttributeDecorator("height", height.getOld()));
}
if(lengthOk(width)) {
item.decorate(new UIFreeAttributeDecorator("width", width.getOld()));
}
item.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.youtube_player")));
item.decorate(new UIFreeAttributeDecorator("src", youtubeUrl));
} else {
UIComponent notAvailableText = UIOutput.make(tableRow, "notAvailableText", messageLocator.getMessage("simplepage.textItemUnavailable"));
// Grey it out
notAvailableText.decorate(new UIFreeAttributeDecorator("class", "disabled-text-item"));
}
if (canEditPage) {
UIOutput.make(tableRow, "youtubeId", String.valueOf(i.getId()));
UIOutput.make(tableRow, "currentYoutubeURL", youtubeUrl);
UIOutput.make(tableRow, "currentYoutubeHeight", getOrig(height));
UIOutput.make(tableRow, "currentYoutubeWidth", getOrig(width));
UIOutput.make(tableRow, "current-item-id5", Long.toString(i.getId()));
UIOutput.make(tableRow, "youtube-td");
UILink.make(tableRow, "youtube-edit", messageLocator.getMessage("simplepage.editItem"), "").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.youtube")));
}
UIOutput.make(tableRow, "description4", i.getDescription());
// as of Oct 28, 2010, we store the mime type. mimeType
// null is an old entry.
// For that use the old approach of checking the
// extension.
// Otherwise we want to use iframes for HTML and OBJECT
// for everything else
// We need the iframes because IE up through 8 doesn't
// reliably display
// HTML with OBJECT. Experiments show that everything
// else works with OBJECT
// for most browsers. Unfortunately IE, even IE 9,
// doesn't reliably call the
// right player with OBJECT. EMBED works. But it's not
// as nice because you can't
// nest error recovery code. So we use OBJECT for
// everything except IE, where we
// use EMBED. OBJECT does work with Flash.
// application/xhtml+xml is XHTML.
} else if (mmDisplayType == null &&
((mimeType != null && !mimeType.equals("text/html") && !mimeType.equals("application/xhtml+xml")) ||
// ((mimeType != null && (mimeType.startsWith("audio/") || mimeType.startsWith("video/"))) ||
(mimeType == null && !(Arrays.binarySearch(htmlTypes, extension) >= 0)))) {
// except where explicit display is set,
// this code is used for everything that isn't an image,
// Youtube, or HTML
// This could be audio, video, flash, or something random like MS word.
// Random stuff will turn into an object.
// HTML is done with an IFRAME in the next "if" case
// The explicit display types are handled there as well
// in theory the things that fall through to iframe are
// html and random stuff without a defined mime type
// random stuff with mime type is displayed with object
if (mimeType == null) {
mimeType = "";
}
String oMimeType = mimeType; // in case we change it for
// FLV or others
if (itemGroupString != null) {
UIOutput.make(tableRow, "item-group-titles5", itemGroupTitles);
UIOutput.make(tableRow, "item-groups5", itemGroupString);
}
UIOutput.make(tableRow, "movieSpan");
if(canSeeAll || simplePageBean.isItemAvailable(i)) {
UIComponent item2;
String movieUrl = i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner());
// movieUrl = "https://heidelberg.rutgers.edu" + movieUrl;
// Safari doens't always pass cookies to plugins, so we have to pass the arg
// this requires session.parameter.allow=true in sakai.properties
// don't pass the arg unless that is set, since the whole point of defaulting
// off is to not expose the session id
String sessionParameter = getSessionParameter(movieUrl);
if (sessionParameter != null)
movieUrl = movieUrl + "?lb.session=" + sessionParameter;
UIOutput.make(tableRow, "movie-link-div");
UILink.make(tableRow, "movie-link-link", messageLocator.getMessage("simplepage.download_file"), movieUrl);
// if (allowSessionId)
// movieUrl = movieUrl + "?sakai.session=" + SessionManager.getCurrentSession().getId();
boolean useFlvPlayer = false;
// isMp4 means we try the flash player (if not HTML5)
// we also try the flash player for FLV but for mp4 we do an
// additional backup if flash fails, but that doesn't make sense for FLV
boolean isMp4 = Arrays.binarySearch(mp4Types, mimeType) >= 0;
boolean isHtml5 = Arrays.binarySearch(html5Types, mimeType) >= 0;
// wrap whatever stuff we decide to put out in HTML5 if appropriate
// javascript is used to do the wrapping, because RSF can't really handle this
if (isHtml5) {
boolean isAudio = mimeType.startsWith("audio/");
UIComponent h5video = UIOutput.make(tableRow, (isAudio? "h5audio" : "h5video"));
UIComponent h5source = UIOutput.make(tableRow, (isAudio? "h5asource" : "h5source"));
if (lengthOk(height) && height.getOld().indexOf("%") < 0)
h5video.decorate(new UIFreeAttributeDecorator("height", height.getOld()));
if (lengthOk(width) && width.getOld().indexOf("%") < 0)
h5video.decorate(new UIFreeAttributeDecorator("width", width.getOld()));
h5source.decorate(new UIFreeAttributeDecorator("src", movieUrl)).
decorate(new UIFreeAttributeDecorator("type", mimeType));
}
// FLV is special. There's no player for flash video in
// the browser
// it shows with a special flash program, which I
// supply. For the moment MP4 is
// shown with the same player so it uses much of the
// same code
if (mimeType != null && (mimeType.equals("video/x-flv") || mimeType.equals("video/flv") || isMp4)) {
mimeType = "application/x-shockwave-flash";
movieUrl = "/lessonbuilder-tool/templates/StrobeMediaPlayback.swf";
useFlvPlayer = true;
}
// for IE, if we're not supplying a player it's safest
// to use embed
// otherwise Quicktime won't work. Oddly, with IE 9 only
// it works if you set CLASSID to the MIME type,
// but that's so unexpected that I hate to rely on it.
// EMBED is in HTML 5, so I think we're OK
// using it permanently for IE.
// I prefer OBJECT where possible because of the nesting
// ability.
boolean useEmbed = ieVersion > 0 && !mimeType.equals("application/x-shockwave-flash");
if (useEmbed) {
item2 = UIOutput.make(tableRow, "movieEmbed").decorate(new UIFreeAttributeDecorator("src", movieUrl)).decorate(new UIFreeAttributeDecorator("alt", messageLocator.getMessage("simplepage.mm_player").replace("{}", abbrevUrl(i.getURL()))));
} else {
item2 = UIOutput.make(tableRow, "movieObject").decorate(new UIFreeAttributeDecorator("data", movieUrl)).decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.mm_player").replace("{}", abbrevUrl(i.getURL()))));
}
if (mimeType != null) {
item2.decorate(new UIFreeAttributeDecorator("type", mimeType));
}
if (canEditPage) {
//item2.decorate(new UIFreeAttributeDecorator("style", "border: 1px solid black"));
}
// some object types seem to need a specification, so supply our default if necessary
if (lengthOk(height) && lengthOk(width)) {
item2.decorate(new UIFreeAttributeDecorator("height", height.getOld())).decorate(new UIFreeAttributeDecorator("width", width.getOld()));
} else {
if (oMimeType.startsWith("audio/"))
item2.decorate(new UIFreeAttributeDecorator("height", "100")).decorate(new UIFreeAttributeDecorator("width", "400"));
else
item2.decorate(new UIFreeAttributeDecorator("height", "300")).decorate(new UIFreeAttributeDecorator("width", "400"));
}
if (!useEmbed) {
if (useFlvPlayer) {
UIOutput.make(tableRow, "flashvars").decorate(new UIFreeAttributeDecorator("value", "src=" + URLEncoder.encode(myUrl() + i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner()))));
// need wmode=opaque for player to stack properly with dialogs, etc.
// there is a performance impact, but I'm guessing in our application we don't
// need ultimate performance for embedded video. I'm setting it only for
// the player, so flash games and other applications will still get wmode=window
UIOutput.make(tableRow, "wmode");
} else if (mimeType.equals("application/x-shockwave-flash"))
UIOutput.make(tableRow, "wmode");
UIOutput.make(tableRow, "movieURLInject").decorate(new UIFreeAttributeDecorator("value", movieUrl));
if (!isMp4) {
UIOutput.make(tableRow, "noplugin-p", messageLocator.getMessage("simplepage.noplugin"));
UIOutput.make(tableRow, "noplugin-br");
UILink.make(tableRow, "noplugin", i.getName(), movieUrl);
}
}
if (isMp4) {
// do fallback. for ie use EMBED
if (ieVersion > 0) {
item2 = UIOutput.make(tableRow, "mp4-embed").decorate(new UIFreeAttributeDecorator("src", i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner()))).decorate(new UIFreeAttributeDecorator("alt", messageLocator.getMessage("simplepage.mm_player").replace("{}", abbrevUrl(i.getURL()))));
} else {
item2 = UIOutput.make(tableRow, "mp4-object").decorate(new UIFreeAttributeDecorator("data", i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner()))).decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.mm_player").replace("{}", abbrevUrl(i.getURL()))));
}
if (oMimeType != null) {
item2.decorate(new UIFreeAttributeDecorator("type", oMimeType));
}
// some object types seem to need a specification, so give a default if needed
if (lengthOk(height) && lengthOk(width)) {
item2.decorate(new UIFreeAttributeDecorator("height", height.getOld())).decorate(new UIFreeAttributeDecorator("width", width.getOld()));
} else {
if (oMimeType.startsWith("audio/"))
item2.decorate(new UIFreeAttributeDecorator("height", "100")).decorate(new UIFreeAttributeDecorator("width", "100%"));
else
item2.decorate(new UIFreeAttributeDecorator("height", "300")).decorate(new UIFreeAttributeDecorator("width", "100%"));
}
if (!useEmbed) {
UIOutput.make(tableRow, "mp4-inject").decorate(new UIFreeAttributeDecorator("value", i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner())));
UIOutput.make(tableRow, "mp4-noplugin-p", messageLocator.getMessage("simplepage.noplugin"));
UILink.make(tableRow, "mp4-noplugin", i.getName(), i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner()));
}
}
} else {
UIVerbatim notAvailableText = UIVerbatim.make(tableRow, "notAvailableText", messageLocator.getMessage("simplepage.multimediaItemUnavailable"));
// Grey it out
notAvailableText.decorate(new UIFreeAttributeDecorator("class", "disabled-multimedia-item"));
}
if (canEditPage) {
UIOutput.make(tableRow, "movieId", String.valueOf(i.getId()));
UIOutput.make(tableRow, "movieHeight", getOrig(height));
UIOutput.make(tableRow, "movieWidth", getOrig(width));
UIOutput.make(tableRow, "mimetype5", oMimeType);
UIOutput.make(tableRow, "prerequisite", (i.isPrerequisite()) ? "true" : "false");
UIOutput.make(tableRow, "current-item-id6", Long.toString(i.getId()));
UIOutput.make(tableRow, "movie-td");
UILink.make(tableRow, "edit-movie", messageLocator.getMessage("simplepage.editItem"), "").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.url").replace("{}", abbrevUrl(i.getURL()))));
}
UIOutput.make(tableRow, "description3", i.getDescription());
} else {
// this is fallthrough for html or an explicit mm display type (i.e. embed code)
// odd types such as MS word will be handled by the AV code, and presented as <OBJECT>
// definition of resizeiframe, at top of page
if (!iframeJavascriptDone && getOrig(height).equals("auto")) {
UIOutput.make(tofill, "iframeJavascript");
iframeJavascriptDone = true;
}
UIOutput.make(tableRow, "iframeSpan");
if (itemGroupString != null) {
UIOutput.make(tableRow, "item-group-titles2", itemGroupTitles);
UIOutput.make(tableRow, "item-groups2", itemGroupString);
}
String itemUrl = i.getItemURL(simplePageBean.getCurrentSiteId(),currentPage.getOwner());
if ("1".equals(mmDisplayType)) {
// embed
item = UIVerbatim.make(tableRow, "mm-embed", i.getAttribute("multimediaEmbedCode"));
//String style = getStyle(width, height);
//if (style != null)
//item.decorate(new UIFreeAttributeDecorator("style", style));
} else if ("3".equals(mmDisplayType)) {
item = UILink.make(tableRow, "mm-oembed", i.getAttribute("multimediaUrl"), i.getAttribute("multimediaUrl"));
if (lengthOk(width))
item.decorate(new UIFreeAttributeDecorator("maxWidth", width.getOld()));
if (lengthOk(height))
item.decorate(new UIFreeAttributeDecorator("maxHeight", height.getOld()));
// oembed
} else {
UIOutput.make(tableRow, "iframe-link-div");
UILink.make(tableRow, "iframe-link-link", messageLocator.getMessage("simplepage.open_new_window"), itemUrl);
item = UIOutput.make(tableRow, "iframe").decorate(new UIFreeAttributeDecorator("src", itemUrl));
// if user specifies auto, use Javascript to resize the
// iframe when the
// content changes. This only works for URLs with the
// same origin, i.e.
// URLs in this sakai system
if (getOrig(height).equals("auto")) {
item.decorate(new UIFreeAttributeDecorator("onload", "resizeiframe('" + item.getFullID() + "')"));
if (lengthOk(width)) {
item.decorate(new UIFreeAttributeDecorator("width", width.getOld()));
}
item.decorate(new UIFreeAttributeDecorator("height", "300"));
} else {
// we seem OK without a spec
if (lengthOk(height) && lengthOk(width)) {
item.decorate(new UIFreeAttributeDecorator("height", height.getOld())).decorate(new UIFreeAttributeDecorator("width", width.getOld()));
}
}
}
item.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.web_content").replace("{}", abbrevUrl(i.getURL()))));
if (canEditPage) {
UIOutput.make(tableRow, "iframeHeight", getOrig(height));
UIOutput.make(tableRow, "iframeWidth", getOrig(width));
UIOutput.make(tableRow, "mimetype3", mimeType);
UIOutput.make(tableRow, "current-item-id3", Long.toString(i.getId()));
UIOutput.make(tableRow, "editmm-td");
UILink.make(tableRow, "iframe-edit", messageLocator.getMessage("simplepage.editItem"), "").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.url").replace("{}", abbrevUrl(i.getURL()))));
}
UIOutput.make(tableRow, "description5", i.getDescription());
}
// end of multimedia object
} else if (i.getType() == SimplePageItem.COMMENTS) {
// Load later using AJAX and CommentsProducer
UIOutput.make(tableRow, "commentsSpan");
boolean isAvailable = simplePageBean.isItemAvailable(i);
// faculty missing preqs get warning but still see the comments
if (!isAvailable && canSeeAll)
UIOutput.make(tableRow, "missing-prereqs", messageLocator.getMessage("simplepage.fake-missing-prereqs"));
// students get warning and not the content
if (!isAvailable && !canSeeAll) {
UIOutput.make(tableRow, "missing-prereqs", messageLocator.getMessage("simplepage.missing-prereqs"));
}else {
UIOutput.make(tableRow, "commentsDiv");
Placement placement = toolManager.getCurrentPlacement();
UIOutput.make(tableRow, "placementId", placement.getId());
// note: the URL will be rewritten in comments.js to look like
// /lessonbuilder-tool/faces/Comments...
CommentsViewParameters eParams = new CommentsViewParameters(CommentsProducer.VIEW_ID);
eParams.itemId = i.getId();
eParams.placementId = placement.getId();
if (params.postedComment) {
eParams.postedComment = postedCommentId;
}
eParams.siteId = simplePageBean.getCurrentSiteId();
eParams.pageId = currentPage.getPageId();
if(params.author != null && !params.author.equals("")) {
eParams.author = params.author;
eParams.showAllComments = true;
}
UIInternalLink.make(tableRow, "commentsLink", eParams);
if (!addedCommentsScript) {
UIOutput.make(tofill, "comments-script");
UIOutput.make(tofill, "fckScript");
addedCommentsScript = true;
UIOutput.make(tofill, "delete-dialog");
}
// forced comments have to be edited on the main page
if (canEditPage) {
// Checks to make sure that the comments item isn't on a student page.
// That it is graded. And that we didn't just come from the grading pane.
if(i.getPageId() > 0 && i.getGradebookId() != null && !cameFromGradingPane) {
CommentsGradingPaneViewParameters gp = new CommentsGradingPaneViewParameters(CommentGradingPaneProducer.VIEW_ID);
gp.placementId = toolManager.getCurrentPlacement().getId();
gp.commentsItemId = i.getId();
gp.pageId = currentPage.getPageId();
gp.pageItemId = pageItem.getId();
gp.siteId = simplePageBean.getCurrentSiteId();
UIInternalLink.make(tableRow, "gradingPaneLink", messageLocator.getMessage("simplepage.show-grading-pane-comments"), gp)
.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.show-grading-pane-comments")));
}
UIOutput.make(tableRow, "comments-td");
if (i.getSequence() > 0) {
UILink.make(tableRow, "edit-comments", messageLocator.getMessage("simplepage.editItem"), "")
.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.comments")));
UIOutput.make(tableRow, "commentsId", String.valueOf(i.getId()));
UIOutput.make(tableRow, "commentsAnon", String.valueOf(i.isAnonymous()));
UIOutput.make(tableRow, "commentsitem-required", String.valueOf(i.isRequired()));
UIOutput.make(tableRow, "commentsitem-prerequisite", String.valueOf(i.isPrerequisite()));
UIOutput.make(tableRow, "commentsGrade", String.valueOf(i.getGradebookId() != null));
UIOutput.make(tableRow, "commentsMaxPoints", String.valueOf(i.getGradebookPoints()));
String itemGroupString = simplePageBean.getItemGroupString(i, null, true);
if (itemGroupString != null) {
String itemGroupTitles = simplePageBean.getItemGroupTitles(itemGroupString, i);
if (itemGroupTitles != null) {
itemGroupTitles = "[" + itemGroupTitles + "]";
}
UIOutput.make(tableRow, "comments-groups", itemGroupString);
UIOutput.make(tableRow, "item-group-titles6", itemGroupTitles);
}
}
// Allows AJAX posting of comment grades
printGradingForm(tofill);
}
UIForm form = UIForm.make(tableRow, "comment-form");
UIInput.make(form, "comment-item-id", "#{simplePageBean.itemId}", String.valueOf(i.getId()));
UIInput.make(form, "comment-edit-id", "#{simplePageBean.editId}");
// usage * image is required and not done
if (i.isRequired() && !simplePageBean.isItemComplete(i))
UIOutput.make(tableRow, "comment-required-image");
UIOutput.make(tableRow, "add-comment-link");
UIOutput.make(tableRow, "add-comment-text", messageLocator.getMessage("simplepage.add-comment"));
UIInput fckInput = UIInput.make(form, "comment-text-area-evolved:", "#{simplePageBean.formattedComment}");
fckInput.decorate(new UIFreeAttributeDecorator("height", "175"));
fckInput.decorate(new UIFreeAttributeDecorator("width", "800"));
fckInput.decorate(new UIStyleDecorator("evolved-box"));
fckInput.decorate(new UIFreeAttributeDecorator("aria-label", messageLocator.getMessage("simplepage.editor")));
fckInput.decorate(new UIFreeAttributeDecorator("role", "dialog"));
if (!noEditor) {
fckInput.decorate(new UIStyleDecorator("using-editor")); // javascript needs to know
((SakaiFCKTextEvolver) richTextEvolver).evolveTextInput(fckInput, "" + commentsCount);
}
UICommand.make(form, "add-comment", "#{simplePageBean.addComment}");
}
}else if (i.getType() == SimplePageItem.PEEREVAL){
String owner=currentPage.getOwner();
String currentUser=UserDirectoryService.getCurrentUser().getId();
Long pageId=currentPage.getPageId();
UIOutput.make(tableRow, "peerReviewRubricStudent");
UIOutput.make(tableRow, "peer-review-form");
makePeerRubric(tableRow,i, makeStudentRubric);
boolean isOpen = false;
boolean isPastDue = false;
String peerEvalDateOpenStr = i.getAttribute("rubricOpenDate");
String peerEvalDateDueStr = i.getAttribute("rubricDueDate");
boolean peerEvalAllowSelfGrade = Boolean.parseBoolean(i.getAttribute("rubricAllowSelfGrade"));
boolean gradingSelf = owner.equals(currentUser) && peerEvalAllowSelfGrade;
if (peerEvalDateOpenStr != null && peerEvalDateDueStr != null) {
Date peerEvalNow = new Date();
Date peerEvalOpen = new Date(Long.valueOf(peerEvalDateOpenStr));
Date peerEvalDue = new Date(Long.valueOf(peerEvalDateDueStr));
isOpen = peerEvalNow.after(peerEvalOpen);
isPastDue = peerEvalNow.after(peerEvalDue);
}
if(isOpen){
if(owner.equals(currentUser)){ //owner gets their own data
class PeerEvaluation{
String category;
public int grade, count;
public PeerEvaluation(String category, int grade){this.category=category;this.grade=grade;count=1;}
public void increment(){count++;}
public boolean equals(Object o){
if ( !(o instanceof PeerEvaluation) ) return false;
PeerEvaluation pe = (PeerEvaluation)o;
return category.equals(pe.category) && grade==pe.grade;
}
public String toString(){return category + " " + grade + " [" + count + "]";}
}
ArrayList<PeerEvaluation> myEvaluations = new ArrayList<PeerEvaluation>();
List<SimplePagePeerEvalResult> evaluations = simplePageToolDao.findPeerEvalResultByOwner(pageId.longValue(), owner);
if(evaluations!=null)
for(SimplePagePeerEvalResult eval : evaluations){
PeerEvaluation target=new PeerEvaluation(eval.getRowText(), eval.getColumnValue());
int targetIndex=myEvaluations.indexOf(target);
if(targetIndex!=-1){
myEvaluations.get(targetIndex).increment();
}
else
myEvaluations.add(target);
}
UIOutput.make(tableRow, "my-existing-peer-eval-data");
for(PeerEvaluation eval: myEvaluations){
UIBranchContainer evalData = UIBranchContainer.make(tableRow, "my-peer-eval-data:");
UIOutput.make(evalData, "peer-eval-row-text", eval.category);
UIOutput.make(evalData, "peer-eval-grade", String.valueOf(eval.grade));
UIOutput.make(evalData, "peer-eval-count", String.valueOf(eval.count));
}
}
if(!owner.equals(currentUser) || gradingSelf){
List<SimplePagePeerEvalResult> evaluations = simplePageToolDao.findPeerEvalResult(pageId, currentUser, owner);
//existing evaluation data
if(evaluations!=null && evaluations.size()!=0){
UIOutput.make(tableRow, "existing-peer-eval-data");
for(SimplePagePeerEvalResult eval : evaluations){
UIBranchContainer evalData = UIBranchContainer.make(tableRow, "peer-eval-data:");
UIOutput.make(evalData, "peer-eval-row-text", eval.getRowText());
UIOutput.make(evalData, "peer-eval-grade", String.valueOf(eval.getColumnValue()));
}
}
//form for peer evaluation results
UIForm form = UIForm.make(tofill, "rubricSelection");
UIInput.make(form, "rubricPeerGrade", "#{simplePageBean.rubricPeerGrade}");
UICommand.make(form, "update-peer-eval-grade", messageLocator.getMessage("simplepage.edit"), "#{simplePageBean.savePeerEvalResult}");
}
//buttons
UIOutput.make(tableRow, "add-peereval-link");
UIOutput.make(tableRow, "add-peereval-text", messageLocator.getMessage("simplepage.view-peereval"));
if(isPastDue){
UIOutput.make(tableRow, "peer-eval-grade-directions", messageLocator.getMessage("simplepage.peer-eval.past-due-date"));
}else if(!owner.equals(currentUser) || gradingSelf){
UIOutput.make(tableRow, "save-peereval-link");
UIOutput.make(tableRow, "save-peereval-text", messageLocator.getMessage("simplepage.save"));
UIOutput.make(tableRow, "cancel-peereval-link");
UIOutput.make(tableRow, "cancel-peereval-text", messageLocator.getMessage("simplepage.cancel"));
UIOutput.make(tableRow, "peer-eval-grade-directions", messageLocator.getMessage("simplepage.peer-eval.click-on-cell"));
}else{ //owner who cannot grade himself
UIOutput.make(tableRow, "peer-eval-grade-directions", messageLocator.getMessage("simplepage.peer-eval.cant-eval-yourself"));
}
if(canEditPage)
UIOutput.make(tableRow, "peerReviewRubricStudent-edit");//lines up rubric with edit btn column for users with editing privs
}
}else if(i.getType() == SimplePageItem.STUDENT_CONTENT) {
UIOutput.make(tableRow, "studentSpan");
boolean isAvailable = simplePageBean.isItemAvailable(i);
// faculty missing preqs get warning but still see the comments
if (!isAvailable && canSeeAll)
UIOutput.make(tableRow, "student-missing-prereqs", messageLocator.getMessage("simplepage.student-fake-missing-prereqs"));
if (!isAvailable && !canSeeAll)
UIOutput.make(tableRow, "student-missing-prereqs", messageLocator.getMessage("simplepage.student-missing-prereqs"));
else {
UIOutput.make(tableRow, "studentDiv");
HashMap<Long, SimplePageLogEntry> cache = simplePageBean.cacheStudentPageLogEntries(i.getId());
List<SimpleStudentPage> studentPages = simplePageToolDao.findStudentPages(i.getId());
boolean hasOwnPage = false;
String userId = UserDirectoryService.getCurrentUser().getId();
Collections.sort(studentPages, new Comparator<SimpleStudentPage>() {
public int compare(SimpleStudentPage o1, SimpleStudentPage o2) {
String title1 = o1.getTitle();
if (title1 == null)
title1 = "";
String title2 = o2.getTitle();
if (title2 == null)
title2 = "";
return title1.compareTo(title2);
}
});
UIOutput contentList = UIOutput.make(tableRow, "studentContentTable");
UIOutput contentTitle = UIOutput.make(tableRow, "studentContentTitle", messageLocator.getMessage("simplepage.student"));
contentList.decorate(new UIFreeAttributeDecorator("aria-labelledby", contentTitle.getFullID()));
// Print each row in the table
for(SimpleStudentPage page : studentPages) {
if(page.isDeleted()) continue;
SimplePageLogEntry entry = cache.get(page.getPageId());
UIBranchContainer row = UIBranchContainer.make(tableRow, "studentRow:");
// There's content they haven't seen
if(entry == null || entry.getLastViewed().compareTo(page.getLastUpdated()) < 0) {
UIOutput.make(row, "newContentImg").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.new-student-content")));
} else
UIOutput.make(row, "newContentImgT");
// The comments tool exists, so we might have to show the icon
if(i.getShowComments() != null && i.getShowComments()) {
// New comments have been added since they last viewed the page
if(page.getLastCommentChange() != null && (entry == null || entry.getLastViewed().compareTo(page.getLastCommentChange()) < 0)) {
UIOutput.make(row, "newCommentsImg").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.new-student-comments")));
} else
UIOutput.make(row, "newCommentsImgT");
}
// Never visited page
if(entry == null) {
UIOutput.make(row, "newPageImg").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.new-student-page")));
} else
UIOutput.make(row, "newPageImgT");
GeneralViewParameters eParams = new GeneralViewParameters(ShowPageProducer.VIEW_ID, page.getPageId());
eParams.setItemId(i.getId());
eParams.setPath("push");
String studentTitle = page.getTitle();
String sownerName = null;
try {
if(!i.isAnonymous() || canEditPage) {
if (page.getGroup() != null)
sownerName = simplePageBean.getCurrentSite().getGroup(page.getGroup()).getTitle();
else
sownerName = UserDirectoryService.getUser(page.getOwner()).getDisplayName();
if (sownerName != null && sownerName.equals(studentTitle))
studentTitle = "(" + sownerName + ")";
else
studentTitle += " (" + sownerName + ")";
}else if (simplePageBean.isPageOwner(page)) {
studentTitle += " (" + messageLocator.getMessage("simplepage.comment-you") + ")";
}
} catch (UserNotDefinedException e) {
}
UIInternalLink.make(row, "studentLink", studentTitle, eParams);
if(simplePageBean.isPageOwner(page)) {
hasOwnPage = true;
}
if(i.getGradebookId() != null && simplePageBean.getEditPrivs() == 0) {
UIOutput.make(row, "studentGradingCell", String.valueOf((page.getPoints() != null? page.getPoints() : "")));
}
}
if(!hasOwnPage) {
UIBranchContainer row = UIBranchContainer.make(tableRow, "studentRow:");
UIOutput.make(row, "linkRow");
UIOutput.make(row, "linkCell");
if (i.isRequired() && !simplePageBean.isItemComplete(i))
UIOutput.make(row, "student-required-image");
GeneralViewParameters eParams = new GeneralViewParameters(ShowPageProducer.VIEW_ID);
eParams.addTool = GeneralViewParameters.STUDENT_PAGE;
eParams.studentItemId = i.getId();
UIInternalLink.make(row, "linkLink", messageLocator.getMessage("simplepage.add-page"), eParams);
}
if(canEditPage) {
// Checks to make sure that the comments are graded and that we didn't
// just come from a grading pane (would be confusing)
if(i.getAltGradebook() != null && !cameFromGradingPane) {
CommentsGradingPaneViewParameters gp = new CommentsGradingPaneViewParameters(CommentGradingPaneProducer.VIEW_ID);
gp.placementId = toolManager.getCurrentPlacement().getId();
gp.commentsItemId = i.getId();
gp.pageId = currentPage.getPageId();
gp.pageItemId = pageItem.getId();
gp.studentContentItem = true;
UIInternalLink.make(tableRow, "studentGradingPaneLink", messageLocator.getMessage("simplepage.show-grading-pane-content"), gp)
.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.show-grading-pane-content")));
}
UIOutput.make(tableRow, "student-td");
UILink.make(tableRow, "edit-student", messageLocator.getMessage("simplepage.editItem"), "")
.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.student")));
UIOutput.make(tableRow, "studentId", String.valueOf(i.getId()));
UIOutput.make(tableRow, "studentAnon", String.valueOf(i.isAnonymous()));
UIOutput.make(tableRow, "studentComments", String.valueOf(i.getShowComments()));
UIOutput.make(tableRow, "forcedAnon", String.valueOf(i.getForcedCommentsAnonymous()));
UIOutput.make(tableRow, "studentGrade", String.valueOf(i.getGradebookId() != null));
UIOutput.make(tableRow, "studentMaxPoints", String.valueOf(i.getGradebookPoints()));
UIOutput.make(tableRow, "studentGrade2", String.valueOf(i.getAltGradebook() != null));
UIOutput.make(tableRow, "studentMaxPoints2", String.valueOf(i.getAltPoints()));
UIOutput.make(tableRow, "studentitem-required", String.valueOf(i.isRequired()));
UIOutput.make(tableRow, "studentitem-prerequisite", String.valueOf(i.isPrerequisite()));
UIOutput.make(tableRow, "peer-eval", String.valueOf(i.getShowPeerEval()));
makePeerRubric(tableRow,i, makeMaintainRubric);
makeSamplePeerEval(tableRow);
String peerEvalDate = i.getAttribute("rubricOpenDate");
String peerDueDate = i.getAttribute("rubricDueDate");
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat stf = new SimpleDateFormat("hh:mm a");
Calendar peerevalcal = Calendar.getInstance();
if (peerEvalDate != null && peerDueDate != null) {
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, M_locale);
//Open date from attribute string
peerevalcal.setTimeInMillis(Long.valueOf(peerEvalDate));
String dateStr = sdf.format(peerevalcal.getTime());
String timeStr = stf.format(peerevalcal.getTime());
UIOutput.make(tableRow, "peer-eval-open-date", dateStr);
UIOutput.make(tableRow, "peer-eval-open-time", timeStr);
//Due date from attribute string
peerevalcal.setTimeInMillis(Long.valueOf(peerDueDate));
dateStr = sdf.format(peerevalcal.getTime());
timeStr = stf.format(peerevalcal.getTime());
UIOutput.make(tableRow, "peer-eval-due-date", dateStr);
UIOutput.make(tableRow, "peer-eval-due-time", timeStr);
UIOutput.make(tableRow, "peer-eval-allow-self", i.getAttribute("rubricAllowSelfGrade"));
}else{
//Default open and due date
Date now = new Date();
peerevalcal.setTime(now);
//Default open date: now
String dateStr = sdf.format(peerevalcal.getTime());
String timeStr = stf.format(peerevalcal.getTime());
UIOutput.make(tableRow, "peer-eval-open-date", dateStr);
UIOutput.make(tableRow, "peer-eval-open-time", timeStr);
//Default due date: 7 days from now
Date later = new Date(peerevalcal.getTimeInMillis() + 604800000);
peerevalcal.setTime(later);
dateStr = sdf.format(peerevalcal.getTime());
timeStr = stf.format(peerevalcal.getTime());
//System.out.println("Setting date to " + dateStr + " and time to " + timeStr);
UIOutput.make(tableRow, "peer-eval-due-date", dateStr);
UIOutput.make(tableRow, "peer-eval-due-time", timeStr);
UIOutput.make(tableRow, "peer-eval-allow-self", i.getAttribute("rubricAllowSelfGrade"));
}
//Peer Eval Stats link
GeneralViewParameters view = new GeneralViewParameters(PeerEvalStatsProducer.VIEW_ID);
view.setSendingPage(currentPage.getPageId());
view.setItemId(i.getId());
if(i.getShowPeerEval()){
UILink link = UIInternalLink.make(tableRow, "peer-eval-stats-link", view);
}
String itemGroupString = simplePageBean.getItemGroupString(i, null, true);
if (itemGroupString != null) {
String itemGroupTitles = simplePageBean.getItemGroupTitles(itemGroupString, i);
if (itemGroupTitles != null) {
itemGroupTitles = "[" + itemGroupTitles + "]";
}
UIOutput.make(tableRow, "student-groups", itemGroupString);
UIOutput.make(tableRow, "item-group-titles7", itemGroupTitles);
}
UIOutput.make(tableRow, "student-owner-groups", simplePageBean.getItemOwnerGroupString(i));
UIOutput.make(tableRow, "student-group-owned", (i.isGroupOwned()?"true":"false"));
}
}
}else if(i.getType() == SimplePageItem.QUESTION) {
SimplePageQuestionResponse response = simplePageToolDao.findQuestionResponse(i.getId(), simplePageBean.getCurrentUserId());
UIOutput.make(tableRow, "questionSpan");
boolean isAvailable = simplePageBean.isItemAvailable(i) || canSeeAll;
UIOutput.make(tableRow, "questionDiv");
UIOutput.make(tableRow, "questionText", i.getAttribute("questionText"));
List<SimplePageQuestionAnswer> answers = new ArrayList<SimplePageQuestionAnswer>();
if("multipleChoice".equals(i.getAttribute("questionType"))) {
answers = simplePageToolDao.findAnswerChoices(i);
UIOutput.make(tableRow, "multipleChoiceDiv");
UIForm questionForm = UIForm.make(tableRow, "multipleChoiceForm");
UIInput.make(questionForm, "multipleChoiceId", "#{simplePageBean.questionId}", String.valueOf(i.getId()));
String[] options = new String[answers.size()];
String initValue = null;
for(int j = 0; j < answers.size(); j++) {
options[j] = String.valueOf(answers.get(j).getId());
if(response != null && answers.get(j).getId() == response.getMultipleChoiceId()) {
initValue = String.valueOf(answers.get(j).getId());
}
}
UISelect multipleChoiceSelect = UISelect.make(questionForm, "multipleChoiceSelect:", options, "#{simplePageBean.questionResponse}", initValue);
if(!isAvailable || response != null) {
multipleChoiceSelect.decorate(new UIDisabledDecorator());
}
for(int j = 0; j < answers.size(); j++) {
UIBranchContainer answerContainer = UIBranchContainer.make(questionForm, "multipleChoiceAnswer:", String.valueOf(j));
UISelectChoice multipleChoiceInput = UISelectChoice.make(answerContainer, "multipleChoiceAnswerRadio", multipleChoiceSelect.getFullID(), j);
multipleChoiceInput.decorate(new UIFreeAttributeDecorator("id", multipleChoiceInput.getFullID()));
UIOutput.make(answerContainer, "multipleChoiceAnswerText", answers.get(j).getText())
.decorate(new UIFreeAttributeDecorator("for", multipleChoiceInput.getFullID()));
if(!isAvailable || response != null) {
multipleChoiceInput.decorate(new UIDisabledDecorator());
}
}
UICommand answerButton = UICommand.make(questionForm, "answerMultipleChoice", messageLocator.getMessage("simplepage.answer_question"), "#{simplePageBean.answerMultipleChoiceQuestion}");
if(!isAvailable || response != null) {
answerButton.decorate(new UIDisabledDecorator());
}
}else if("shortanswer".equals(i.getAttribute("questionType"))) {
UIOutput.make(tableRow, "shortanswerDiv");
UIForm questionForm = UIForm.make(tableRow, "shortanswerForm");
UIInput.make(questionForm, "shortanswerId", "#{simplePageBean.questionId}", String.valueOf(i.getId()));
UIInput shortanswerInput = UIInput.make(questionForm, "shortanswerInput", "#{simplePageBean.questionResponse}");
if(!isAvailable || response != null) {
shortanswerInput.decorate(new UIDisabledDecorator());
if(response.getShortanswer() != null) {
shortanswerInput.setValue(response.getShortanswer());
}
}
UICommand answerButton = UICommand.make(questionForm, "answerShortanswer", messageLocator.getMessage("simplepage.answer_question"), "#{simplePageBean.answerShortanswerQuestion}");
if(!isAvailable || response != null) {
answerButton.decorate(new UIDisabledDecorator());
}
}
Status questionStatus = getQuestionStatus(i, response);
addStatusImage(questionStatus, tableRow, "questionStatus", null);
String statusNote = getStatusNote(questionStatus);
if (statusNote != null) // accessibility version of icon
UIOutput.make(tableRow, "questionNote", statusNote);
String statusText = null;
if(questionStatus == Status.COMPLETED)
statusText = i.getAttribute("questionCorrectText");
else if(questionStatus == Status.FAILED)
statusText = i.getAttribute("questionIncorrectText");
if (statusText != null && !"".equals(statusText.trim()))
UIOutput.make(tableRow, "questionStatusText", statusText);
// Output the poll data
if("multipleChoice".equals(i.getAttribute("questionType")) &&
(canEditPage || ("true".equals(i.getAttribute("questionShowPoll")) &&
(questionStatus == Status.COMPLETED || questionStatus == Status.FAILED)))) {
UIOutput.make(tableRow, "showPollGraph", messageLocator.getMessage("simplepage.show-poll"));
UIOutput questionGraph = UIOutput.make(tableRow, "questionPollGraph");
questionGraph.decorate(new UIFreeAttributeDecorator("id", "poll" + i.getId()));
List<SimplePageQuestionResponseTotals> totals = simplePageToolDao.findQRTotals(i.getId());
HashMap<Long, Long> responseCounts = new HashMap<Long, Long>();
// in theory we don't need the first loop, as there should be a total
// entry for all possible answers. But in case things are out of sync ...
for(SimplePageQuestionAnswer answer : answers)
responseCounts.put(answer.getId(), 0L);
for(SimplePageQuestionResponseTotals total : totals)
responseCounts.put(total.getResponseId(), total.getCount());
for(int j = 0; j < answers.size(); j++) {
UIBranchContainer pollContainer = UIBranchContainer.make(tableRow, "questionPollData:", String.valueOf(j));
UIOutput.make(pollContainer, "questionPollText", answers.get(j).getText());
UIOutput.make(pollContainer, "questionPollNumber", String.valueOf(responseCounts.get(answers.get(j).getId())));
}
}
if(canEditPage) {
UIOutput.make(tableRow, "question-td");
// always show grading panel. Currently this is the only way to get feedback
if( !cameFromGradingPane) {
QuestionGradingPaneViewParameters gp = new QuestionGradingPaneViewParameters(QuestionGradingPaneProducer.VIEW_ID);
gp.placementId = toolManager.getCurrentPlacement().getId();
gp.questionItemId = i.getId();
gp.pageId = currentPage.getPageId();
gp.pageItemId = pageItem.getId();
UIInternalLink.make(tableRow, "questionGradingPaneLink", messageLocator.getMessage("simplepage.show-grading-pane"), gp)
.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.show-grading-pane")));
}
UILink.make(tableRow, "edit-question", messageLocator.getMessage("simplepage.editItem"), "")
.decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.question")));
UIOutput.make(tableRow, "questionId", String.valueOf(i.getId()));
boolean graded = "true".equals(i.getAttribute("questionGraded")) || i.getGradebookId() != null;
UIOutput.make(tableRow, "questionGrade", String.valueOf(graded));
UIOutput.make(tableRow, "questionMaxPoints", String.valueOf(i.getGradebookPoints()));
UIOutput.make(tableRow, "questionGradebookTitle", String.valueOf(i.getGradebookTitle()));
UIOutput.make(tableRow, "questionitem-required", String.valueOf(i.isRequired()));
UIOutput.make(tableRow, "questionitem-prerequisite", String.valueOf(i.isPrerequisite()));
UIOutput.make(tableRow, "questionCorrectText", String.valueOf(i.getAttribute("questionCorrectText")));
UIOutput.make(tableRow, "questionIncorrectText", String.valueOf(i.getAttribute("questionIncorrectText")));
if("shortanswer".equals(i.getAttribute("questionType"))) {
UIOutput.make(tableRow, "questionType", "shortanswer");
UIOutput.make(tableRow, "questionAnswer", i.getAttribute("questionAnswer"));
}else {
UIOutput.make(tableRow, "questionType", "multipleChoice");
for(int j = 0; j < answers.size(); j++) {
UIBranchContainer answerContainer = UIBranchContainer.make(tableRow, "questionMultipleChoiceAnswer:", String.valueOf(j));
UIOutput.make(answerContainer, "questionMultipleChoiceAnswerId", String.valueOf(answers.get(j).getId()));
UIOutput.make(answerContainer, "questionMultipleChoiceAnswerText", answers.get(j).getText());
UIOutput.make(answerContainer, "questionMultipleChoiceAnswerCorrect", String.valueOf(answers.get(j).isCorrect()));
}
UIOutput.make(tableRow, "questionShowPoll", String.valueOf(i.getAttribute("questionShowPoll")));
}
}
} else {
// remaining type must be a block of HTML
UIOutput.make(tableRow, "itemSpan");
if (canSeeAll) {
String itemGroupString = simplePageBean.getItemGroupString(i, null, true);
String itemGroupTitles = simplePageBean.getItemGroupTitles(itemGroupString, i);
if (itemGroupTitles != null) {
itemGroupTitles = "[" + itemGroupTitles + "]";
}
UIOutput.make(tableRow, "item-groups-titles-text", itemGroupTitles);
}
if(canSeeAll || simplePageBean.isItemAvailable(i)) {
UIVerbatim.make(tableRow, "content", (i.getHtml() == null ? "" : i.getHtml()));
} else {
UIComponent unavailableText = UIOutput.make(tableRow, "content", messageLocator.getMessage("simplepage.textItemUnavailable"));
unavailableText.decorate(new UIFreeAttributeDecorator("class", "disabled-text-item"));
}
// editing is done using a special producer that calls FCK.
if (canEditPage) {
GeneralViewParameters eParams = new GeneralViewParameters();
eParams.setSendingPage(currentPage.getPageId());
eParams.setItemId(i.getId());
eParams.viewID = EditPageProducer.VIEW_ID;
UIOutput.make(tableRow, "edittext-td");
UIInternalLink.make(tableRow, "edit-link", messageLocator.getMessage("simplepage.editItem"), eParams).decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.edit-title.textbox").replace("{}", Integer.toString(textboxcount))));
textboxcount++;
}
}
}
// end of items. This is the end for normal users. Following is
// special
// checks and putting out the dialogs for the popups, for
// instructors.
boolean showBreak = false;
// I believe refresh is now done automatically in all cases
// if (showRefresh) {
// UIOutput.make(tofill, "refreshAlert");
//
// // Should simply refresh
// GeneralViewParameters p = new GeneralViewParameters(VIEW_ID);
// p.setSendingPage(currentPage.getPageId());
// UIInternalLink.make(tofill, "refreshLink", p);
// showBreak = true;
// }
// stuff goes on the page in the order in the HTML file. So the fact
// that it's here doesn't mean it shows
// up at the end. This code produces errors and other odd stuff.
if (canSeeAll) {
// if the page is hidden, warn the faculty [students get stopped
// at
// the top]
if (currentPage.isHidden()) {
UIOutput.make(tofill, "hiddenAlert").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.pagehidden")));
UIVerbatim.make(tofill, "hidden-text", messageLocator.getMessage("simplepage.pagehidden.text"));
showBreak = true;
// similarly warn them if it isn't released yet
} else if (currentPage.getReleaseDate() != null && currentPage.getReleaseDate().after(new Date())) {
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, M_locale);
TimeZone tz = timeService.getLocalTimeZone();
df.setTimeZone(tz);
String releaseDate = df.format(currentPage.getReleaseDate());
UIOutput.make(tofill, "hiddenAlert").decorate(new UIFreeAttributeDecorator("title", messageLocator.getMessage("simplepage.notreleased")));
UIVerbatim.make(tofill, "hidden-text", messageLocator.getMessage("simplepage.notreleased.text").replace("{}", releaseDate));
showBreak = true;
}
}
if (showBreak) {
UIOutput.make(tofill, "breakAfterWarnings");
}
}
// more warnings: if no item on the page, give faculty instructions,
// students an error
if (!anyItemVisible) {
if (canEditPage) {
UIOutput.make(tofill, "startupHelp")
.decorate(new UIFreeAttributeDecorator("src",
getLocalizedURL((currentPage.getOwner() != null) ? "student.html" : "general.html")))
.decorate(new UIFreeAttributeDecorator("id", "iframe"));
if (!iframeJavascriptDone) {
UIOutput.make(tofill, "iframeJavascript");
iframeJavascriptDone = true;
}
} else {
UIOutput.make(tofill, "error-div");
UIOutput.make(tofill, "error", messageLocator.getMessage("simplepage.noitems_error_user"));
}
}
// now output the dialogs. but only for faculty (to avoid making the
// file bigger)
if (canEditPage) {
createSubpageDialog(tofill, currentPage);
}
createDialogs(tofill, currentPage, pageItem);
}
|
diff --git a/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java b/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java
index 6e30388d5..e71b6cb77 100644
--- a/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java
+++ b/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java
@@ -1,2056 +1,2053 @@
//
// ZeissLSMReader.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;
import ome.xml.model.primitives.NonNegativeInteger;
import ome.xml.model.primitives.PositiveInteger;
import loci.common.DataTools;
import loci.common.DateTools;
import loci.common.Location;
import loci.common.RandomAccessInputStream;
import loci.common.services.DependencyException;
import loci.common.services.ServiceFactory;
import loci.formats.CoreMetadata;
import loci.formats.FormatException;
import loci.formats.FormatReader;
import loci.formats.FormatTools;
import loci.formats.ImageTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import loci.formats.services.MDBService;
import loci.formats.tiff.IFD;
import loci.formats.tiff.IFDList;
import loci.formats.tiff.PhotoInterp;
import loci.formats.tiff.TiffCompression;
import loci.formats.tiff.TiffConstants;
import loci.formats.tiff.TiffParser;
/**
* ZeissLSMReader is the file format reader for Zeiss LSM files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://dev.loci.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java">Trac</a>,
* <a href="http://dev.loci.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/ZeissLSMReader.java">SVN</a></dd></dl>
*
* @author Eric Kjellman egkjellman at wisc.edu
* @author Melissa Linkert melissa at glencoesoftware.com
* @author Curtis Rueden ctrueden at wisc.edu
*/
public class ZeissLSMReader extends FormatReader {
// -- Constants --
public static final String[] MDB_SUFFIX = {"mdb"};
/** Tag identifying a Zeiss LSM file. */
private static final int ZEISS_ID = 34412;
/** Data types. */
private static final int TYPE_SUBBLOCK = 0;
private static final int TYPE_ASCII = 2;
private static final int TYPE_LONG = 4;
private static final int TYPE_RATIONAL = 5;
/** Subblock types. */
private static final int SUBBLOCK_RECORDING = 0x10000000;
private static final int SUBBLOCK_LASER = 0x50000000;
private static final int SUBBLOCK_TRACK = 0x40000000;
private static final int SUBBLOCK_DETECTION_CHANNEL = 0x70000000;
private static final int SUBBLOCK_ILLUMINATION_CHANNEL = 0x90000000;
private static final int SUBBLOCK_BEAM_SPLITTER = 0xb0000000;
private static final int SUBBLOCK_DATA_CHANNEL = 0xd0000000;
private static final int SUBBLOCK_TIMER = 0x12000000;
private static final int SUBBLOCK_MARKER = 0x14000000;
private static final int SUBBLOCK_END = (int) 0xffffffff;
/** Data types. */
private static final int RECORDING_NAME = 0x10000001;
private static final int RECORDING_DESCRIPTION = 0x10000002;
private static final int RECORDING_OBJECTIVE = 0x10000004;
private static final int RECORDING_ZOOM = 0x10000016;
private static final int RECORDING_SAMPLE_0TIME = 0x10000036;
private static final int RECORDING_CAMERA_BINNING = 0x10000052;
private static final int TRACK_ACQUIRE = 0x40000006;
private static final int TRACK_TIME_BETWEEN_STACKS = 0x4000000b;
private static final int LASER_NAME = 0x50000001;
private static final int LASER_ACQUIRE = 0x50000002;
private static final int LASER_POWER = 0x50000003;
private static final int CHANNEL_DETECTOR_GAIN = 0x70000003;
private static final int CHANNEL_PINHOLE_DIAMETER = 0x70000009;
private static final int CHANNEL_AMPLIFIER_GAIN = 0x70000005;
private static final int CHANNEL_FILTER_SET = 0x7000000f;
private static final int CHANNEL_FILTER = 0x70000010;
private static final int CHANNEL_ACQUIRE = 0x7000000b;
private static final int CHANNEL_NAME = 0x70000014;
private static final int ILLUM_CHANNEL_ATTENUATION = 0x90000002;
private static final int ILLUM_CHANNEL_WAVELENGTH = 0x90000003;
private static final int ILLUM_CHANNEL_ACQUIRE = 0x90000004;
private static final int START_TIME = 0x10000036;
private static final int DATA_CHANNEL_NAME = 0xd0000001;
private static final int DATA_CHANNEL_ACQUIRE = 0xd0000017;
private static final int BEAM_SPLITTER_FILTER = 0xb0000002;
private static final int BEAM_SPLITTER_FILTER_SET = 0xb0000003;
/** Drawing element types. */
private static final int TEXT = 13;
private static final int LINE = 14;
private static final int SCALE_BAR = 15;
private static final int OPEN_ARROW = 16;
private static final int CLOSED_ARROW = 17;
private static final int RECTANGLE = 18;
private static final int ELLIPSE = 19;
private static final int CLOSED_POLYLINE = 20;
private static final int OPEN_POLYLINE = 21;
private static final int CLOSED_BEZIER = 22;
private static final int OPEN_BEZIER = 23;
private static final int CIRCLE = 24;
private static final int PALETTE = 25;
private static final int POLYLINE_ARROW = 26;
private static final int BEZIER_WITH_ARROW = 27;
private static final int ANGLE = 28;
private static final int CIRCLE_3POINT = 29;
// -- Static fields --
private static Hashtable<Integer, String> metadataKeys = createKeys();
// -- Fields --
private double pixelSizeX, pixelSizeY, pixelSizeZ;
private byte[][] lut = null;
private Vector<Double> timestamps;
private int validChannels;
private String[] lsmFilenames;
private Vector<IFDList> ifdsList;
private TiffParser tiffParser;
private int nextLaser = 0, nextDetector = 0;
private int nextFilter = 0, nextDichroicChannel = 0, nextDichroic = 0;
private int nextDataChannel = 0, nextIllumChannel = 0, nextDetectChannel = 0;
private boolean splitPlanes = false;
private double zoom;
private Vector<String> imageNames;
private String binning;
private Vector<Double> xCoordinates, yCoordinates, zCoordinates;
private int dimensionM, dimensionP;
private Hashtable<String, Integer> seriesCounts;
private double originX, originY, originZ;
private int totalROIs = 0;
private int prevPlane = -1;
private byte[] prevBuf = null;
// -- Constructor --
/** Constructs a new Zeiss LSM reader. */
public ZeissLSMReader() {
super("Zeiss Laser-Scanning Microscopy", new String[] {"lsm", "mdb"});
domains = new String[] {FormatTools.LM_DOMAIN};
hasCompanionFiles = true;
}
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isSingleFile(String) */
public boolean isSingleFile(String id) throws FormatException, IOException {
if (checkSuffix(id, MDB_SUFFIX)) return false;
return isGroupFiles() ? getMDBFile(id) != null : true;
}
/* @see loci.formats.IFormatReader#close(boolean) */
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
pixelSizeX = pixelSizeY = pixelSizeZ = 0;
lut = null;
timestamps = null;
validChannels = 0;
lsmFilenames = null;
ifdsList = null;
tiffParser = null;
nextLaser = nextDetector = 0;
nextFilter = nextDichroicChannel = nextDichroic = 0;
nextDataChannel = nextIllumChannel = nextDetectChannel = 0;
splitPlanes = false;
zoom = 0;
imageNames = null;
binning = null;
totalROIs = 0;
prevPlane = -1;
prevBuf = null;
xCoordinates = null;
yCoordinates = null;
zCoordinates = null;
dimensionM = 0;
dimensionP = 0;
seriesCounts = null;
originX = originY = originZ = 0d;
}
}
/* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */
public boolean isThisType(RandomAccessInputStream stream) throws IOException {
final int blockLen = 4;
if (!FormatTools.validStream(stream, blockLen, false)) return false;
TiffParser parser = new TiffParser(stream);
return parser.isValidHeader() || stream.readShort() == 0x5374;
}
/* @see loci.formats.IFormatReader#fileGroupOption(String) */
public int fileGroupOption(String id) throws FormatException, IOException {
return FormatTools.MUST_GROUP;
}
/* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */
public String[] getSeriesUsedFiles(boolean noPixels) {
FormatTools.assertId(currentId, true, 1);
if (noPixels) {
if (checkSuffix(currentId, MDB_SUFFIX)) return new String[] {currentId};
return null;
}
if (lsmFilenames == null) return new String[] {currentId};
if (lsmFilenames.length == 1 && currentId.equals(lsmFilenames[0])) {
return lsmFilenames;
}
return new String[] {currentId, getLSMFileFromSeries(getSeries())};
}
/* @see loci.formats.IFormatReader#get8BitLookupTable() */
public byte[][] get8BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
if (lut == null || lut[getSeries()] == null ||
getPixelType() != FormatTools.UINT8)
{
return null;
}
byte[][] b = new byte[3][256];
for (int i=2; i>=3-validChannels; i--) {
for (int j=0; j<256; j++) {
b[i][j] = (byte) j;
}
}
return b;
}
/* @see loci.formats.IFormatReader#get16BitLookupTable() */
public short[][] get16BitLookupTable() throws FormatException, IOException {
FormatTools.assertId(currentId, true, 1);
if (lut == null || lut[getSeries()] == null ||
getPixelType() != FormatTools.UINT16)
{
return null;
}
short[][] s = new short[3][65536];
for (int i=2; i>=3-validChannels; i--) {
for (int j=0; j<s[i].length; j++) {
s[i][j] = (short) j;
}
}
return s;
}
/* @see loci.formats.IFormatReader#setSeries(int) */
public void setSeries(int series) {
if (series != getSeries()) {
prevBuf = null;
}
super.setSeries(series);
}
/**
* @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int)
*/
public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h)
throws FormatException, IOException
{
FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h);
in = new RandomAccessInputStream(getLSMFileFromSeries(getSeries()));
in.order(!isLittleEndian());
tiffParser = new TiffParser(in);
IFDList ifds = ifdsList.get(getSeries());
if (splitPlanes && getSizeC() > 1 && ifds.size() == getSizeZ() * getSizeT())
{
int bpp = FormatTools.getBytesPerPixel(getPixelType());
int plane = no / getSizeC();
int c = no % getSizeC();
if (prevPlane != plane || prevBuf == null ||
prevBuf.length < buf.length * getSizeC())
{
prevBuf = new byte[buf.length * getSizeC()];
tiffParser.getSamples(ifds.get(plane), prevBuf, x, y, w, h);
prevPlane = plane;
}
ImageTools.splitChannels(prevBuf, buf, c, getSizeC(), bpp, false, false);
}
else {
tiffParser.getSamples(ifds.get(no), buf, x, y, w, h);
}
in.close();
return buf;
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
if (!checkSuffix(id, MDB_SUFFIX) && isGroupFiles()) {
String mdb = getMDBFile(id);
if (mdb != null) {
setId(mdb);
return;
}
lsmFilenames = new String[] {id};
}
else if (checkSuffix(id, MDB_SUFFIX)) {
lsmFilenames = parseMDB(id);
}
else lsmFilenames = new String[] {id};
if (lsmFilenames.length == 0) {
throw new FormatException("LSM files were not found.");
}
timestamps = new Vector<Double>();
imageNames = new Vector<String>();
xCoordinates = new Vector<Double>();
yCoordinates = new Vector<Double>();
zCoordinates = new Vector<Double>();
seriesCounts = new Hashtable<String, Integer>();
int seriesCount = 0;
for (String filename : lsmFilenames) {
int extraSeries = getExtraSeries(filename);
seriesCounts.put(filename, extraSeries);
seriesCount += extraSeries;
}
core = new CoreMetadata[seriesCount];
ifdsList = new Vector<IFDList>();
ifdsList.setSize(core.length);
int realSeries = 0;
for (int i=0; i<lsmFilenames.length; i++) {
RandomAccessInputStream stream =
new RandomAccessInputStream(lsmFilenames[i]);
int count = seriesCounts.get(lsmFilenames[i]);
boolean littleEndian = stream.read() == TiffConstants.LITTLE;
stream.order(littleEndian);
TiffParser tp = new TiffParser(stream);
long[] ifdOffsets = tp.getIFDOffsets();
int ifdsPerSeries = (ifdOffsets.length / 2) / count;
int offset = 0;
Object zeissTag = null;
for (int s=0; s<count; s++, realSeries++) {
core[realSeries] = new CoreMetadata();
core[realSeries].littleEndian = littleEndian;
IFDList ifds = new IFDList();
while (ifds.size() < ifdsPerSeries) {
IFD ifd = tp.getIFD(ifdOffsets[offset]);
if (offset == 0) zeissTag = ifd.get(ZEISS_ID);
if (offset > 0 && ifds.size() == 0) {
ifd.putIFDValue(ZEISS_ID, zeissTag);
}
ifds.add(ifd);
if (zeissTag != null) offset += 2;
else offset++;
}
ifdsList.set(realSeries, ifds);
}
stream.close();
}
MetadataStore store = makeFilterMetadata();
for (int series=0; series<ifdsList.size(); series++) {
IFDList ifds = ifdsList.get(series);
for (IFD ifd : ifds) {
// check that predictor is set to 1 if anything other
// than LZW compression is used
if (ifd.getCompression() != TiffCompression.LZW) {
ifd.putIFDValue(IFD.PREDICTOR, 1);
}
}
// fix the offsets for > 4 GB files
RandomAccessInputStream s =
new RandomAccessInputStream(getLSMFileFromSeries(series));
for (int i=1; i<ifds.size(); i++) {
long[] stripOffsets = ifds.get(i).getStripOffsets();
long[] previousStripOffsets = ifds.get(i - 1).getStripOffsets();
if (stripOffsets == null || previousStripOffsets == null) {
throw new FormatException(
"Strip offsets are missing; this is an invalid file.");
}
boolean neededAdjustment = false;
for (int j=0; j<stripOffsets.length; j++) {
if (j >= previousStripOffsets.length) break;
if (stripOffsets[j] < previousStripOffsets[j]) {
stripOffsets[j] = (previousStripOffsets[j] & ~0xffffffffL) |
(stripOffsets[j] & 0xffffffffL);
if (stripOffsets[j] < previousStripOffsets[j]) {
stripOffsets[j] += 0x100000000L;
}
neededAdjustment = true;
}
if (neededAdjustment) {
ifds.get(i).putIFDValue(IFD.STRIP_OFFSETS, stripOffsets);
}
}
}
s.close();
initMetadata(series);
}
for (int i=0; i<getSeriesCount(); i++) {
core[i].imageCount = core[i].sizeZ * core[i].sizeC * core[i].sizeT;
}
MetadataTools.populatePixels(store, this, true);
for (int series=0; series<ifdsList.size(); series++) {
setSeries(series);
if (series < imageNames.size()) {
store.setImageName(imageNames.get(series), series);
}
store.setPixelsBinDataBigEndian(!isLittleEndian(), series, 0);
}
setSeries(0);
}
// -- Helper methods --
private String getMDBFile(String id) throws FormatException, IOException {
Location parentFile = new Location(id).getAbsoluteFile().getParentFile();
String[] fileList = parentFile.list();
for (int i=0; i<fileList.length; i++) {
if (fileList[i].startsWith(".")) continue;
if (checkSuffix(fileList[i], MDB_SUFFIX)) {
Location file =
new Location(parentFile, fileList[i]).getAbsoluteFile();
if (file.isDirectory()) continue;
// make sure that the .mdb references this .lsm
String[] lsms = parseMDB(file.getAbsolutePath());
for (String lsm : lsms) {
if (id.endsWith(lsm) || lsm.endsWith(id)) {
return file.getAbsolutePath();
}
}
}
}
return null;
}
private int getEffectiveSeries(int currentSeries) {
int seriesCount = 0;
for (int i=0; i<lsmFilenames.length; i++) {
Integer count = seriesCounts.get(lsmFilenames[i]);
if (count == null) count = 1;
seriesCount += count;
if (seriesCount > currentSeries) return i;
}
return -1;
}
private String getLSMFileFromSeries(int currentSeries) {
int effectiveSeries = getEffectiveSeries(currentSeries);
return effectiveSeries < 0 ? null : lsmFilenames[effectiveSeries];
}
private int getExtraSeries(String file) throws FormatException, IOException {
in = new RandomAccessInputStream(file);
boolean littleEndian = in.read() == TiffConstants.LITTLE;
in.order(littleEndian);
tiffParser = new TiffParser(in);
IFD ifd = tiffParser.getFirstIFD();
RandomAccessInputStream ras = getCZTag(ifd);
if (ras == null) return 1;
ras.order(littleEndian);
ras.seek(264);
dimensionP = ras.readInt();
dimensionM = ras.readInt();
ras.close();
int nSeries = dimensionM * dimensionP;
return nSeries <= 0 ? 1 : nSeries;
}
private int getPosition(int currentSeries) {
int effectiveSeries = getEffectiveSeries(currentSeries);
int firstPosition = 0;
for (int i=0; i<effectiveSeries; i++) {
firstPosition += seriesCounts.get(lsmFilenames[i]);
}
return currentSeries - firstPosition;
}
private RandomAccessInputStream getCZTag(IFD ifd)
throws FormatException, IOException
{
// get TIF_CZ_LSMINFO structure
short[] s = ifd.getIFDShortArray(ZEISS_ID);
if (s == null) {
LOGGER.warn("Invalid Zeiss LSM file. Tag {} not found.", ZEISS_ID);
TiffReader reader = new TiffReader();
reader.setId(getLSMFileFromSeries(series));
core[getSeries()] = reader.getCoreMetadata()[0];
reader.close();
return null;
}
byte[] cz = new byte[s.length];
for (int i=0; i<s.length; i++) {
cz[i] = (byte) s[i];
}
RandomAccessInputStream ras = new RandomAccessInputStream(cz);
ras.order(isLittleEndian());
return ras;
}
protected void initMetadata(int series) throws FormatException, IOException {
setSeries(series);
IFDList ifds = ifdsList.get(series);
IFD ifd = ifds.get(0);
in = new RandomAccessInputStream(getLSMFileFromSeries(series));
in.order(isLittleEndian());
tiffParser = new TiffParser(in);
PhotoInterp photo = ifd.getPhotometricInterpretation();
int samples = ifd.getSamplesPerPixel();
core[series].sizeX = (int) ifd.getImageWidth();
core[series].sizeY = (int) ifd.getImageLength();
core[series].rgb = samples > 1 || photo == PhotoInterp.RGB;
core[series].interleaved = false;
core[series].sizeC = isRGB() ? samples : 1;
core[series].pixelType = ifd.getPixelType();
core[series].imageCount = ifds.size();
core[series].sizeZ = getImageCount();
core[series].sizeT = 1;
LOGGER.info("Reading LSM metadata for series #{}", series);
MetadataStore store = makeFilterMetadata();
int instrument = getEffectiveSeries(series);
String imageName = getLSMFileFromSeries(series);
if (imageName.indexOf(".") != -1) {
imageName = imageName.substring(0, imageName.lastIndexOf("."));
}
if (imageName.indexOf(File.separator) != -1) {
imageName =
imageName.substring(imageName.lastIndexOf(File.separator) + 1);
}
if (lsmFilenames.length != getSeriesCount()) {
imageName += " #" + (getPosition(series) + 1);
}
// link Instrument and Image
store.setImageID(MetadataTools.createLSID("Image", series), series);
String instrumentID = MetadataTools.createLSID("Instrument", instrument);
store.setInstrumentID(instrumentID, instrument);
store.setImageInstrumentRef(instrumentID, series);
RandomAccessInputStream ras = getCZTag(ifd);
if (ras == null) {
imageNames.add(imageName);
return;
}
ras.seek(16);
core[series].sizeZ = ras.readInt();
ras.skipBytes(4);
core[series].sizeT = ras.readInt();
int dataType = ras.readInt();
switch (dataType) {
case 2:
addSeriesMeta("DataType", "12 bit unsigned integer");
break;
case 5:
addSeriesMeta("DataType", "32 bit float");
break;
case 0:
addSeriesMeta("DataType", "varying data types");
break;
default:
addSeriesMeta("DataType", "8 bit unsigned integer");
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
ras.seek(0);
addSeriesMeta("MagicNumber ", ras.readInt());
addSeriesMeta("StructureSize", ras.readInt());
addSeriesMeta("DimensionX", ras.readInt());
addSeriesMeta("DimensionY", ras.readInt());
ras.seek(32);
addSeriesMeta("ThumbnailX", ras.readInt());
addSeriesMeta("ThumbnailY", ras.readInt());
// pixel sizes are stored in meters, we need them in microns
pixelSizeX = ras.readDouble() * 1000000;
pixelSizeY = ras.readDouble() * 1000000;
pixelSizeZ = ras.readDouble() * 1000000;
addSeriesMeta("VoxelSizeX", new Double(pixelSizeX));
addSeriesMeta("VoxelSizeY", new Double(pixelSizeY));
addSeriesMeta("VoxelSizeZ", new Double(pixelSizeZ));
originX = ras.readDouble() * 1000000;
originY = ras.readDouble() * 1000000;
originZ = ras.readDouble() * 1000000;
addSeriesMeta("OriginX", originX);
addSeriesMeta("OriginY", originY);
addSeriesMeta("OriginZ", originZ);
}
else ras.seek(88);
int scanType = ras.readShort();
switch (scanType) {
case 0:
addSeriesMeta("ScanType", "x-y-z scan");
core[series].dimensionOrder = "XYZCT";
break;
case 1:
addSeriesMeta("ScanType", "z scan (x-z plane)");
core[series].dimensionOrder = "XYZCT";
break;
case 2:
addSeriesMeta("ScanType", "line scan");
core[series].dimensionOrder = "XYZCT";
break;
case 3:
addSeriesMeta("ScanType", "time series x-y");
core[series].dimensionOrder = "XYTCZ";
break;
case 4:
addSeriesMeta("ScanType", "time series x-z");
core[series].dimensionOrder = "XYZTC";
break;
case 5:
addSeriesMeta("ScanType", "time series 'Mean of ROIs'");
core[series].dimensionOrder = "XYTCZ";
break;
case 6:
addSeriesMeta("ScanType", "time series x-y-z");
core[series].dimensionOrder = "XYZTC";
break;
case 7:
addSeriesMeta("ScanType", "spline scan");
core[series].dimensionOrder = "XYCTZ";
break;
case 8:
addSeriesMeta("ScanType", "spline scan x-z");
core[series].dimensionOrder = "XYCZT";
break;
case 9:
addSeriesMeta("ScanType", "time series spline plane x-z");
core[series].dimensionOrder = "XYTCZ";
break;
case 10:
addSeriesMeta("ScanType", "point mode");
core[series].dimensionOrder = "XYZCT";
break;
default:
addSeriesMeta("ScanType", "x-y-z scan");
core[series].dimensionOrder = "XYZCT";
}
core[series].indexed =
lut != null && lut[series] != null && getSizeC() == 1;
if (isIndexed()) {
core[series].sizeC = 1;
core[series].rgb = false;
}
if (getSizeC() == 0) core[series].sizeC = 1;
if (isRGB()) {
// shuffle C to front of order string
core[series].dimensionOrder = getDimensionOrder().replaceAll("C", "");
core[series].dimensionOrder = getDimensionOrder().replaceAll("XY", "XYC");
}
if (getEffectiveSizeC() == 0) {
core[series].imageCount = getSizeZ() * getSizeT();
}
else {
core[series].imageCount = getSizeZ() * getSizeT() * getEffectiveSizeC();
}
if (getImageCount() != ifds.size()) {
int diff = getImageCount() - ifds.size();
core[series].imageCount = ifds.size();
if (diff % getSizeZ() == 0) {
core[series].sizeT -= (diff / getSizeZ());
}
else if (diff % getSizeT() == 0) {
core[series].sizeZ -= (diff / getSizeT());
}
else if (getSizeZ() > 1) {
core[series].sizeZ = ifds.size();
core[series].sizeT = 1;
}
else if (getSizeT() > 1) {
core[series].sizeT = ifds.size();
core[series].sizeZ = 1;
}
}
if (getSizeZ() == 0) core[series].sizeZ = getImageCount();
if (getSizeT() == 0) core[series].sizeT = getImageCount() / getSizeZ();
long channelColorsOffset = 0;
long timeStampOffset = 0;
long eventListOffset = 0;
long scanInformationOffset = 0;
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
int spectralScan = ras.readShort();
if (spectralScan != 1) {
addSeriesMeta("SpectralScan", "no spectral scan");
}
else addSeriesMeta("SpectralScan", "acquired with spectral scan");
int type = ras.readInt();
switch (type) {
case 1:
addSeriesMeta("DataType2", "calculated data");
break;
case 2:
addSeriesMeta("DataType2", "animation");
break;
default:
addSeriesMeta("DataType2", "original scan data");
}
long[] overlayOffsets = new long[9];
String[] overlayKeys = new String[] {"VectorOverlay", "InputLut",
"OutputLut", "ROI", "BleachROI", "MeanOfRoisOverlay",
"TopoIsolineOverlay", "TopoProfileOverlay", "LinescanOverlay"};
overlayOffsets[0] = ras.readInt();
overlayOffsets[1] = ras.readInt();
overlayOffsets[2] = ras.readInt();
channelColorsOffset = ras.readInt();
addSeriesMeta("TimeInterval", ras.readDouble());
ras.skipBytes(4);
scanInformationOffset = ras.readInt();
ras.skipBytes(4);
timeStampOffset = ras.readInt();
eventListOffset = ras.readInt();
overlayOffsets[3] = ras.readInt();
overlayOffsets[4] = ras.readInt();
ras.skipBytes(4);
addSeriesMeta("DisplayAspectX", ras.readDouble());
addSeriesMeta("DisplayAspectY", ras.readDouble());
addSeriesMeta("DisplayAspectZ", ras.readDouble());
addSeriesMeta("DisplayAspectTime", ras.readDouble());
overlayOffsets[5] = ras.readInt();
overlayOffsets[6] = ras.readInt();
overlayOffsets[7] = ras.readInt();
overlayOffsets[8] = ras.readInt();
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.NO_OVERLAYS)
{
for (int i=0; i<overlayOffsets.length; i++) {
parseOverlays(series, overlayOffsets[i], overlayKeys[i], store);
}
}
totalROIs = 0;
addSeriesMeta("ToolbarFlags", ras.readInt());
int wavelengthOffset = ras.readInt();
ras.skipBytes(64);
}
else ras.skipBytes(182);
MetadataTools.setDefaultCreationDate(store, getCurrentFile(), series);
if (getSizeC() > 1) {
if (!splitPlanes) splitPlanes = isRGB();
core[series].rgb = false;
if (splitPlanes) core[series].imageCount *= getSizeC();
}
for (int c=0; c<getEffectiveSizeC(); c++) {
String lsid = MetadataTools.createLSID("Channel", series, c);
store.setChannelID(lsid, series, c);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
// NB: the Zeiss LSM 5.5 specification indicates that there should be
// 15 32-bit integers here; however, there are actually 16 32-bit
// integers before the tile position offset.
// We have confirmed with Zeiss that this is correct, and the 6.0
// specification was updated to contain the correct information.
ras.skipBytes(64);
int tilePositionOffset = ras.readInt();
ras.skipBytes(36);
int positionOffset = ras.readInt();
// read referenced structures
addSeriesMeta("DimensionZ", getSizeZ());
addSeriesMeta("DimensionChannels", getSizeC());
addSeriesMeta("DimensionM", dimensionM);
addSeriesMeta("DimensionP", dimensionP);
if (positionOffset != 0) {
in.seek(positionOffset);
int nPositions = in.readInt();
for (int i=0; i<nPositions; i++) {
double xPos = originX + in.readDouble() * 1000000;
double yPos = originY + in.readDouble() * 1000000;
double zPos = originZ + in.readDouble() * 1000000;
xCoordinates.add(xPos);
yCoordinates.add(yPos);
zCoordinates.add(zPos);
}
}
if (tilePositionOffset != 0) {
in.seek(tilePositionOffset);
int nTiles = in.readInt();
for (int i=0; i<nTiles; i++) {
xCoordinates.add(originX + in.readDouble() * 1000000);
yCoordinates.add(originY + in.readDouble() * 1000000);
zCoordinates.add(originZ + in.readDouble() * 1000000);
}
}
if (channelColorsOffset != 0) {
in.seek(channelColorsOffset + 16);
int namesOffset = in.readInt();
// read the name of each channel
if (namesOffset > 0) {
in.skipBytes(namesOffset - 16);
for (int i=0; i<getSizeC(); i++) {
if (in.getFilePointer() >= in.length() - 1) break;
// we want to read until we find a null char
String name = in.readCString();
if (name.length() <= 128) {
addSeriesMeta("ChannelName" + i, name);
}
}
}
}
if (timeStampOffset != 0) {
in.seek(timeStampOffset + 8);
for (int i=0; i<getSizeT(); i++) {
double stamp = in.readDouble();
addSeriesMeta("TimeStamp" + i, stamp);
timestamps.add(new Double(stamp));
}
}
if (eventListOffset != 0) {
in.seek(eventListOffset + 4);
int numEvents = in.readInt();
in.seek(in.getFilePointer() - 4);
in.order(!in.isLittleEndian());
int tmpEvents = in.readInt();
if (numEvents < 0) numEvents = tmpEvents;
else numEvents = (int) Math.min(numEvents, tmpEvents);
in.order(!in.isLittleEndian());
if (numEvents > 65535) numEvents = 0;
for (int i=0; i<numEvents; i++) {
if (in.getFilePointer() + 16 <= in.length()) {
int size = in.readInt();
double eventTime = in.readDouble();
int eventType = in.readInt();
addSeriesMeta("Event" + i + " Time", eventTime);
addSeriesMeta("Event" + i + " Type", eventType);
long fp = in.getFilePointer();
int len = size - 16;
if (len > 65536) len = 65536;
if (len < 0) len = 0;
addSeriesMeta("Event" + i + " Description", in.readString(len));
in.seek(fp + size - 16);
if (in.getFilePointer() < 0) break;
}
}
}
if (scanInformationOffset != 0) {
in.seek(scanInformationOffset);
nextLaser = nextDetector = 0;
nextFilter = nextDichroicChannel = nextDichroic = 0;
nextDataChannel = nextDetectChannel = nextIllumChannel = 0;
Vector<SubBlock> blocks = new Vector<SubBlock>();
while (in.getFilePointer() < in.length() - 12) {
if (in.getFilePointer() < 0) break;
int entry = in.readInt();
int blockType = in.readInt();
int dataSize = in.readInt();
if (blockType == TYPE_SUBBLOCK) {
SubBlock block = null;
switch (entry) {
case SUBBLOCK_RECORDING:
block = new Recording();
break;
case SUBBLOCK_LASER:
block = new Laser();
break;
case SUBBLOCK_TRACK:
block = new Track();
break;
case SUBBLOCK_DETECTION_CHANNEL:
block = new DetectionChannel();
break;
case SUBBLOCK_ILLUMINATION_CHANNEL:
block = new IlluminationChannel();
break;
case SUBBLOCK_BEAM_SPLITTER:
block = new BeamSplitter();
break;
case SUBBLOCK_DATA_CHANNEL:
block = new DataChannel();
break;
case SUBBLOCK_TIMER:
block = new Timer();
break;
case SUBBLOCK_MARKER:
block = new Marker();
break;
}
if (block != null) {
blocks.add(block);
}
}
else if (dataSize + in.getFilePointer() <= in.length()) {
in.skipBytes(dataSize);
}
else break;
}
Vector<SubBlock> nonAcquiredBlocks = new Vector<SubBlock>();
SubBlock[] metadataBlocks = blocks.toArray(new SubBlock[0]);
for (SubBlock block : metadataBlocks) {
block.addToHashtable();
if (!block.acquire) {
nonAcquiredBlocks.add(block);
blocks.remove(block);
}
}
for (int i=0; i<blocks.size(); i++) {
SubBlock block = blocks.get(i);
// every valid IlluminationChannel must be immediately followed by
// a valid DataChannel or IlluminationChannel
if ((block instanceof IlluminationChannel) && i < blocks.size() - 1) {
SubBlock nextBlock = blocks.get(i + 1);
if (!(nextBlock instanceof DataChannel) &&
!(nextBlock instanceof IlluminationChannel))
{
((IlluminationChannel) block).wavelength = null;
}
}
// every valid DetectionChannel must be immediately preceded by
// a valid Track or DetectionChannel
else if ((block instanceof DetectionChannel) && i > 0) {
SubBlock prevBlock = blocks.get(i - 1);
if (!(prevBlock instanceof Track) &&
!(prevBlock instanceof DetectionChannel))
{
block.acquire = false;
nonAcquiredBlocks.add(block);
}
}
if (block.acquire) populateMetadataStore(block, store, series);
}
for (SubBlock block : nonAcquiredBlocks) {
populateMetadataStore(block, store, series);
}
}
}
imageNames.add(imageName);
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
Double pixX = new Double(pixelSizeX);
Double pixY = new Double(pixelSizeY);
Double pixZ = new Double(pixelSizeZ);
store.setPixelsPhysicalSizeX(pixX, series);
store.setPixelsPhysicalSizeY(pixY, series);
store.setPixelsPhysicalSizeZ(pixZ, series);
double firstStamp = 0;
if (timestamps.size() > 0) {
firstStamp = timestamps.get(0).doubleValue();
}
for (int i=0; i<getImageCount(); i++) {
int[] zct = FormatTools.getZCTCoords(this, i);
if (zct[2] < timestamps.size()) {
double thisStamp = timestamps.get(zct[2]).doubleValue();
store.setPlaneDeltaT(thisStamp - firstStamp, series, i);
int index = zct[2] + 1;
double nextStamp = index < timestamps.size() ?
timestamps.get(index).doubleValue() : thisStamp;
if (i == getSizeT() - 1 && zct[2] > 0) {
thisStamp = timestamps.get(zct[2] - 1).doubleValue();
}
store.setPlaneExposureTime(nextStamp - thisStamp, series, i);
}
- if (xCoordinates.size() > 0) {
- double planesPerStage =
- (double) getImageCount() / xCoordinates.size();
- int stage = (int) (i / planesPerStage);
- store.setPlanePositionX(xCoordinates.get(stage), series, i);
- store.setPlanePositionY(yCoordinates.get(stage), series, i);
- store.setPlanePositionZ(zCoordinates.get(stage), series, i);
+ if (xCoordinates.size() > series) {
+ store.setPlanePositionX(xCoordinates.get(series), series, i);
+ store.setPlanePositionY(yCoordinates.get(series), series, i);
+ store.setPlanePositionZ(zCoordinates.get(series), series, i);
}
}
}
ras.close();
in.close();
}
protected void populateMetadataStore(SubBlock block, MetadataStore store,
int series)
throws FormatException
{
if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) {
return;
}
int instrument = getEffectiveSeries(series);
// NB: block.acquire can be false. If that is the case, Instrument data
// is the only thing that should be populated.
if (block instanceof Recording) {
Recording recording = (Recording) block;
String objectiveID = MetadataTools.createLSID("Objective", instrument, 0);
if (recording.acquire) {
store.setImageDescription(recording.description, series);
store.setImageAcquiredDate(recording.startTime, series);
store.setImageObjectiveSettingsID(objectiveID, series);
binning = recording.binning;
}
store.setObjectiveCorrection(
getCorrection(recording.correction), instrument, 0);
store.setObjectiveImmersion(
getImmersion(recording.immersion), instrument, 0);
if (recording.magnification != null && recording.magnification > 0) {
store.setObjectiveNominalMagnification(
new PositiveInteger(recording.magnification), instrument, 0);
}
store.setObjectiveLensNA(recording.lensNA, instrument, 0);
store.setObjectiveIris(recording.iris, instrument, 0);
store.setObjectiveID(objectiveID, instrument, 0);
}
else if (block instanceof Laser) {
Laser laser = (Laser) block;
if (laser.medium != null) {
store.setLaserLaserMedium(getLaserMedium(laser.medium),
instrument, nextLaser);
}
if (laser.type != null) {
store.setLaserType(getLaserType(laser.type), instrument, nextLaser);
}
if (laser.model != null) {
store.setLaserModel(laser.model, instrument, nextLaser);
}
String lightSourceID =
MetadataTools.createLSID("LightSource", instrument, nextLaser);
store.setLaserID(lightSourceID, instrument, nextLaser);
nextLaser++;
}
else if (block instanceof Track) {
Track track = (Track) block;
if (track.acquire) {
store.setPixelsTimeIncrement(track.timeIncrement, series);
}
}
else if (block instanceof DataChannel) {
DataChannel channel = (DataChannel) block;
if (channel.name != null && nextDataChannel < getSizeC() &&
channel.acquire)
{
store.setChannelName(channel.name, series, nextDataChannel++);
}
}
else if (block instanceof DetectionChannel) {
DetectionChannel channel = (DetectionChannel) block;
if (channel.pinhole != null && channel.pinhole.doubleValue() != 0f &&
nextDetectChannel < getSizeC() && channel.acquire)
{
store.setChannelPinholeSize(channel.pinhole, series, nextDetectChannel);
}
if (channel.filter != null) {
String id = MetadataTools.createLSID("Filter", instrument, nextFilter);
if (channel.acquire && nextDetectChannel < getSizeC()) {
store.setLightPathEmissionFilterRef(
id, instrument, nextDetectChannel, 0);
}
store.setFilterID(id, instrument, nextFilter);
store.setFilterModel(channel.filter, instrument, nextFilter);
int space = channel.filter.indexOf(" ");
if (space != -1) {
String type = channel.filter.substring(0, space).trim();
if (type.equals("BP")) type = "BandPass";
else if (type.equals("LP")) type = "LongPass";
store.setFilterType(getFilterType(type), instrument, nextFilter);
String transmittance = channel.filter.substring(space + 1).trim();
String[] v = transmittance.split("-");
try {
store.setTransmittanceRangeCutIn(
PositiveInteger.valueOf(v[0].trim()), instrument, nextFilter);
}
catch (NumberFormatException e) { }
if (v.length > 1) {
try {
store.setTransmittanceRangeCutOut(
PositiveInteger.valueOf(v[1].trim()), instrument, nextFilter);
}
catch (NumberFormatException e) { }
}
}
nextFilter++;
}
if (channel.channelName != null) {
String detectorID =
MetadataTools.createLSID("Detector", instrument, nextDetector);
store.setDetectorID(detectorID, instrument, nextDetector);
if (channel.acquire && nextDetector < getSizeC()) {
store.setDetectorSettingsID(detectorID, series, nextDetector);
store.setDetectorSettingsBinning(
getBinning(binning), series, nextDetector);
}
}
if (channel.amplificationGain != null) {
store.setDetectorAmplificationGain(
channel.amplificationGain, instrument, nextDetector);
}
if (channel.gain != null) {
store.setDetectorGain(channel.gain, instrument, nextDetector);
}
store.setDetectorType(getDetectorType("PMT"), instrument, nextDetector);
store.setDetectorZoom(zoom, instrument, nextDetector);
nextDetectChannel++;
nextDetector++;
}
else if (block instanceof BeamSplitter) {
BeamSplitter beamSplitter = (BeamSplitter) block;
if (beamSplitter.filterSet != null) {
if (beamSplitter.filter != null) {
String id = MetadataTools.createLSID(
"Dichroic", instrument, nextDichroic);
store.setDichroicID(id, instrument, nextDichroic);
store.setDichroicModel(beamSplitter.filter, instrument, nextDichroic);
if (nextDichroicChannel < getEffectiveSizeC()) {
store.setLightPathDichroicRef(id, series, nextDichroicChannel);
}
nextDichroic++;
}
nextDichroicChannel++;
}
}
}
/** Parses overlay-related fields. */
protected void parseOverlays(int series, long data, String suffix,
MetadataStore store) throws IOException
{
if (data == 0) return;
String prefix = "Series " + series + " ";
in.seek(data);
int numberOfShapes = in.readInt();
int size = in.readInt();
if (size <= 194) return;
in.skipBytes(20);
boolean valid = in.readInt() == 1;
in.skipBytes(164);
for (int i=totalROIs; i<totalROIs+numberOfShapes; i++) {
long offset = in.getFilePointer();
int type = in.readInt();
int blockLength = in.readInt();
double lineWidth = in.readInt();
int measurements = in.readInt();
double textOffsetX = in.readDouble();
double textOffsetY = in.readDouble();
int color = in.readInt();
boolean validShape = in.readInt() != 0;
int knotWidth = in.readInt();
int catchArea = in.readInt();
int fontHeight = in.readInt();
int fontWidth = in.readInt();
int fontEscapement = in.readInt();
int fontOrientation = in.readInt();
int fontWeight = in.readInt();
boolean fontItalic = in.readInt() != 0;
boolean fontUnderlined = in.readInt() != 0;
boolean fontStrikeout = in.readInt() != 0;
int fontCharSet = in.readInt();
int fontOutputPrecision = in.readInt();
int fontClipPrecision = in.readInt();
int fontQuality = in.readInt();
int fontPitchAndFamily = in.readInt();
String fontName = DataTools.stripString(in.readString(64));
boolean enabled = in.readShort() == 0;
boolean moveable = in.readInt() == 0;
in.skipBytes(34);
String roiID = MetadataTools.createLSID("ROI", i);
String shapeID = MetadataTools.createLSID("Shape", i, 0);
switch (type) {
case TEXT:
double x = in.readDouble();
double y = in.readDouble();
String text = DataTools.stripString(in.readCString());
store.setTextValue(text, i, 0);
store.setTextFontSize(new NonNegativeInteger(fontHeight), i, 0);
store.setTextStrokeWidth(lineWidth, i, 0);
store.setROIID(roiID, i);
store.setTextID(shapeID, i, 0);
break;
case LINE:
in.skipBytes(4);
double startX = in.readDouble();
double startY = in.readDouble();
double endX = in.readDouble();
double endY = in.readDouble();
store.setLineX1(startX, i, 0);
store.setLineY1(startY, i, 0);
store.setLineX2(endX, i, 0);
store.setLineY2(endY, i, 0);
store.setLineFontSize(new NonNegativeInteger(fontHeight), i, 0);
store.setLineStrokeWidth(lineWidth, i, 0);
store.setROIID(roiID, i);
store.setLineID(shapeID, i, 0);
break;
case SCALE_BAR:
case OPEN_ARROW:
case CLOSED_ARROW:
case PALETTE:
in.skipBytes(36);
break;
case RECTANGLE:
in.skipBytes(4);
double topX = in.readDouble();
double topY = in.readDouble();
double bottomX = in.readDouble();
double bottomY = in.readDouble();
double width = Math.abs(bottomX - topX);
double height = Math.abs(bottomY - topY);
topX = Math.min(topX, bottomX);
topY = Math.min(topY, bottomY);
store.setRectangleX(topX, i, 0);
store.setRectangleY(topY, i, 0);
store.setRectangleWidth(width, i, 0);
store.setRectangleHeight(height, i, 0);
store.setRectangleFontSize(new NonNegativeInteger(fontHeight), i, 0);
store.setRectangleStrokeWidth(lineWidth, i, 0);
store.setROIID(roiID, i);
store.setRectangleID(shapeID, i, 0);
break;
case ELLIPSE:
int knots = in.readInt();
double[] xs = new double[knots];
double[] ys = new double[knots];
for (int j=0; j<xs.length; j++) {
xs[j] = in.readDouble();
ys[j] = in.readDouble();
}
double rx = 0, ry = 0, centerX = 0, centerY = 0;
if (knots == 4) {
double r1x = Math.abs(xs[2] - xs[0]) / 2;
double r1y = Math.abs(ys[2] - ys[0]) / 2;
double r2x = Math.abs(xs[3] - xs[1]) / 2;
double r2y = Math.abs(ys[3] - ys[1]) / 2;
if (r1x > r2x) {
ry = r1y;
rx = r2x;
centerX = Math.min(xs[3], xs[1]) + rx;
centerY = Math.min(ys[2], ys[0]) + ry;
}
else {
ry = r2y;
rx = r1x;
centerX = Math.min(xs[2], xs[0]) + rx;
centerY = Math.min(ys[3], ys[1]) + ry;
}
}
else if (knots == 3) {
// we are given the center point and one cut point for each axis
centerX = xs[0];
centerY = ys[0];
rx = Math.sqrt(Math.pow(xs[1] - xs[0], 2) +
Math.pow(ys[1] - ys[0], 2));
ry = Math.sqrt(Math.pow(xs[2] - xs[0], 2) +
Math.pow(ys[2] - ys[0], 2));
// calculate rotation angle
double slope = (ys[2] - centerY) / (xs[2] - centerX);
double theta = Math.toDegrees(Math.atan(slope));
store.setEllipseTransform("rotate(" + theta + " " + centerX +
" " + centerY + ")", i, 0);
}
store.setEllipseX(centerX, i, 0);
store.setEllipseY(centerY, i, 0);
store.setEllipseRadiusX(rx, i, 0);
store.setEllipseRadiusY(ry, i, 0);
store.setEllipseFontSize(new NonNegativeInteger(fontHeight), i, 0);
store.setEllipseStrokeWidth(lineWidth, i, 0);
store.setROIID(roiID, i);
store.setEllipseID(shapeID, i, 0);
break;
case CIRCLE:
in.skipBytes(4);
centerX = in.readDouble();
centerY = in.readDouble();
double curveX = in.readDouble();
double curveY = in.readDouble();
double radius = Math.sqrt(Math.pow(curveX - centerX, 2) +
Math.pow(curveY - centerY, 2));
store.setEllipseX(centerX, i, 0);
store.setEllipseY(centerY, i, 0);
store.setEllipseRadiusX(radius, i, 0);
store.setEllipseRadiusY(radius, i, 0);
store.setEllipseFontSize(new NonNegativeInteger(fontHeight), i, 0);
store.setEllipseStrokeWidth(lineWidth, i, 0);
store.setROIID(roiID, i);
store.setEllipseID(shapeID, i, 0);
break;
case CIRCLE_3POINT:
in.skipBytes(4);
// given 3 points on the perimeter of the circle, we need to
// calculate the center and radius
double[][] points = new double[3][2];
for (int j=0; j<points.length; j++) {
for (int k=0; k<points[j].length; k++) {
points[j][k] = in.readDouble();
}
}
double s = 0.5 * ((points[1][0] - points[2][0]) *
(points[0][0] - points[2][0]) - (points[1][1] - points[2][1]) *
(points[2][1] - points[0][1]));
double div = (points[0][0] - points[1][0]) *
(points[2][1] - points[0][1]) - (points[1][1] - points[0][1]) *
(points[0][0] - points[2][0]);
s /= div;
double cx = 0.5 * (points[0][0] + points[1][0]) +
s * (points[1][1] - points[0][1]);
double cy = 0.5 * (points[0][1] + points[1][1]) +
s * (points[0][0] - points[1][0]);
double r = Math.sqrt(Math.pow(points[0][0] - cx, 2) +
Math.pow(points[0][1] - cy, 2));
store.setEllipseX(cx, i, 0);
store.setEllipseY(cy, i, 0);
store.setEllipseRadiusX(r, i, 0);
store.setEllipseRadiusY(r, i, 0);
store.setEllipseFontSize(new NonNegativeInteger(fontHeight), i, 0);
store.setEllipseStrokeWidth(lineWidth, i, 0);
store.setROIID(roiID, i);
store.setEllipseID(shapeID, i, 0);
break;
case ANGLE:
in.skipBytes(4);
points = new double[3][2];
for (int j=0; j<points.length; j++) {
for (int k=0; k<points[j].length; k++) {
points[j][k] = in.readDouble();
}
}
StringBuffer p = new StringBuffer();
for (int j=0; j<points.length; j++) {
p.append(points[j][0]);
p.append(",");
p.append(points[j][1]);
if (j < points.length - 1) p.append(" ");
}
store.setPolylinePoints(p.toString(), i, 0);
store.setPolylineFontSize(new NonNegativeInteger(fontHeight), i, 0);
store.setPolylineStrokeWidth(lineWidth, i, 0);
store.setROIID(roiID, i);
store.setPolylineID(shapeID, i, 0);
break;
case CLOSED_POLYLINE:
case OPEN_POLYLINE:
case POLYLINE_ARROW:
int nKnots = in.readInt();
points = new double[nKnots][2];
for (int j=0; j<points.length; j++) {
for (int k=0; k<points[j].length; k++) {
points[j][k] = in.readDouble();
}
}
p = new StringBuffer();
for (int j=0; j<points.length; j++) {
p.append(points[j][0]);
p.append(",");
p.append(points[j][1]);
if (j < points.length - 1) p.append(" ");
}
store.setPolylinePoints(p.toString(), i, 0);
store.setPolylineClosed(type == CLOSED_POLYLINE, i, 0);
store.setPolylineFontSize(new NonNegativeInteger(fontHeight), i, 0);
store.setPolylineStrokeWidth(lineWidth, i, 0);
store.setROIID(roiID, i);
store.setPolylineID(shapeID, i, 0);
break;
case CLOSED_BEZIER:
case OPEN_BEZIER:
case BEZIER_WITH_ARROW:
nKnots = in.readInt();
points = new double[nKnots][2];
for (int j=0; j<points.length; j++) {
for (int k=0; k<points[j].length; k++) {
points[j][k] = in.readDouble();
}
}
p = new StringBuffer();
for (int j=0; j<points.length; j++) {
p.append(points[j][0]);
p.append(",");
p.append(points[j][1]);
if (j < points.length - 1) p.append(" ");
}
store.setPolylinePoints(p.toString(), i, 0);
store.setPolylineClosed(type != OPEN_BEZIER, i, 0);
store.setPolylineFontSize(new NonNegativeInteger(fontHeight), i, 0);
store.setPolylineStrokeWidth(lineWidth, i, 0);
store.setROIID(roiID, i);
store.setPolylineID(shapeID, i, 0);
break;
default:
i--;
numberOfShapes--;
continue;
}
// populate shape attributes
in.seek(offset + blockLength);
}
totalROIs += numberOfShapes;
}
/** Parse a .mdb file and return a list of referenced .lsm files. */
private String[] parseMDB(String mdbFile) throws FormatException, IOException
{
Location mdb = new Location(mdbFile).getAbsoluteFile();
Location parent = mdb.getParentFile();
MDBService mdbService = null;
try {
ServiceFactory factory = new ServiceFactory();
mdbService = factory.getInstance(MDBService.class);
}
catch (DependencyException de) {
throw new FormatException("MDB Tools Java library not found", de);
}
mdbService.initialize(mdbFile);
Vector<Vector<String[]>> tables = mdbService.parseDatabase();
Vector<String> referencedLSMs = new Vector<String>();
for (Vector<String[]> table : tables) {
String[] columnNames = table.get(0);
String tableName = columnNames[0];
for (int row=1; row<table.size(); row++) {
String[] tableRow = table.get(row);
for (int col=0; col<tableRow.length; col++) {
String key = tableName + " " + columnNames[col + 1] + " " + row;
if (currentId != null) {
addGlobalMeta(key, tableRow[col]);
}
if (tableName.equals("Recordings") && columnNames[col + 1] != null &&
columnNames[col + 1].equals("SampleData"))
{
String filename = tableRow[col].trim();
filename = filename.replace('\\', File.separatorChar);
filename = filename.replace('/', File.separatorChar);
filename =
filename.substring(filename.lastIndexOf(File.separator) + 1);
if (filename.length() > 0) {
Location file = new Location(parent, filename);
if (file.exists()) {
referencedLSMs.add(file.getAbsolutePath());
}
}
}
}
}
}
if (referencedLSMs.size() > 0) {
return referencedLSMs.toArray(new String[0]);
}
String[] fileList = parent.list();
for (int i=0; i<fileList.length; i++) {
if (checkSuffix(fileList[i], new String[] {"lsm"}) &&
!fileList[i].startsWith("."))
{
referencedLSMs.add(new Location(parent, fileList[i]).getAbsolutePath());
}
}
return referencedLSMs.toArray(new String[0]);
}
private static Hashtable<Integer, String> createKeys() {
Hashtable<Integer, String> h = new Hashtable<Integer, String>();
h.put(new Integer(0x10000001), "Name");
h.put(new Integer(0x4000000c), "Name");
h.put(new Integer(0x50000001), "Name");
h.put(new Integer(0x90000001), "Name");
h.put(new Integer(0x90000005), "Detection Channel Name");
h.put(new Integer(0xb0000003), "Name");
h.put(new Integer(0xd0000001), "Name");
h.put(new Integer(0x12000001), "Name");
h.put(new Integer(0x14000001), "Name");
h.put(new Integer(0x10000002), "Description");
h.put(new Integer(0x14000002), "Description");
h.put(new Integer(0x10000003), "Notes");
h.put(new Integer(0x10000004), "Objective");
h.put(new Integer(0x10000005), "Processing Summary");
h.put(new Integer(0x10000006), "Special Scan Mode");
h.put(new Integer(0x10000007), "Scan Type");
h.put(new Integer(0x10000008), "Scan Mode");
h.put(new Integer(0x10000009), "Number of Stacks");
h.put(new Integer(0x1000000a), "Lines Per Plane");
h.put(new Integer(0x1000000b), "Samples Per Line");
h.put(new Integer(0x1000000c), "Planes Per Volume");
h.put(new Integer(0x1000000d), "Images Width");
h.put(new Integer(0x1000000e), "Images Height");
h.put(new Integer(0x1000000f), "Number of Planes");
h.put(new Integer(0x10000010), "Number of Stacks");
h.put(new Integer(0x10000011), "Number of Channels");
h.put(new Integer(0x10000012), "Linescan XY Size");
h.put(new Integer(0x10000013), "Scan Direction");
h.put(new Integer(0x10000014), "Time Series");
h.put(new Integer(0x10000015), "Original Scan Data");
h.put(new Integer(0x10000016), "Zoom X");
h.put(new Integer(0x10000017), "Zoom Y");
h.put(new Integer(0x10000018), "Zoom Z");
h.put(new Integer(0x10000019), "Sample 0X");
h.put(new Integer(0x1000001a), "Sample 0Y");
h.put(new Integer(0x1000001b), "Sample 0Z");
h.put(new Integer(0x1000001c), "Sample Spacing");
h.put(new Integer(0x1000001d), "Line Spacing");
h.put(new Integer(0x1000001e), "Plane Spacing");
h.put(new Integer(0x1000001f), "Plane Width");
h.put(new Integer(0x10000020), "Plane Height");
h.put(new Integer(0x10000021), "Volume Depth");
h.put(new Integer(0x10000034), "Rotation");
h.put(new Integer(0x10000035), "Precession");
h.put(new Integer(0x10000036), "Sample 0Time");
h.put(new Integer(0x10000037), "Start Scan Trigger In");
h.put(new Integer(0x10000038), "Start Scan Trigger Out");
h.put(new Integer(0x10000039), "Start Scan Event");
h.put(new Integer(0x10000040), "Start Scan Time");
h.put(new Integer(0x10000041), "Stop Scan Trigger In");
h.put(new Integer(0x10000042), "Stop Scan Trigger Out");
h.put(new Integer(0x10000043), "Stop Scan Event");
h.put(new Integer(0x10000044), "Stop Scan Time");
h.put(new Integer(0x10000045), "Use ROIs");
h.put(new Integer(0x10000046), "Use Reduced Memory ROIs");
h.put(new Integer(0x10000047), "User");
h.put(new Integer(0x10000048), "Use B/C Correction");
h.put(new Integer(0x10000049), "Position B/C Contrast 1");
h.put(new Integer(0x10000050), "Position B/C Contrast 2");
h.put(new Integer(0x10000051), "Interpolation Y");
h.put(new Integer(0x10000052), "Camera Binning");
h.put(new Integer(0x10000053), "Camera Supersampling");
h.put(new Integer(0x10000054), "Camera Frame Width");
h.put(new Integer(0x10000055), "Camera Frame Height");
h.put(new Integer(0x10000056), "Camera Offset X");
h.put(new Integer(0x10000057), "Camera Offset Y");
h.put(new Integer(0x40000001), "Multiplex Type");
h.put(new Integer(0x40000002), "Multiplex Order");
h.put(new Integer(0x40000003), "Sampling Mode");
h.put(new Integer(0x40000004), "Sampling Method");
h.put(new Integer(0x40000005), "Sampling Number");
h.put(new Integer(0x40000006), "Acquire");
h.put(new Integer(0x50000002), "Acquire");
h.put(new Integer(0x7000000b), "Acquire");
h.put(new Integer(0x90000004), "Acquire");
h.put(new Integer(0xd0000017), "Acquire");
h.put(new Integer(0x40000007), "Sample Observation Time");
h.put(new Integer(0x40000008), "Time Between Stacks");
h.put(new Integer(0x4000000d), "Collimator 1 Name");
h.put(new Integer(0x4000000e), "Collimator 1 Position");
h.put(new Integer(0x4000000f), "Collimator 2 Name");
h.put(new Integer(0x40000010), "Collimator 2 Position");
h.put(new Integer(0x40000011), "Is Bleach Track");
h.put(new Integer(0x40000012), "Bleach After Scan Number");
h.put(new Integer(0x40000013), "Bleach Scan Number");
h.put(new Integer(0x40000014), "Trigger In");
h.put(new Integer(0x12000004), "Trigger In");
h.put(new Integer(0x14000003), "Trigger In");
h.put(new Integer(0x40000015), "Trigger Out");
h.put(new Integer(0x12000005), "Trigger Out");
h.put(new Integer(0x14000004), "Trigger Out");
h.put(new Integer(0x40000016), "Is Ratio Track");
h.put(new Integer(0x40000017), "Bleach Count");
h.put(new Integer(0x40000018), "SPI Center Wavelength");
h.put(new Integer(0x40000019), "Pixel Time");
h.put(new Integer(0x40000020), "ID Condensor Frontlens");
h.put(new Integer(0x40000021), "Condensor Frontlens");
h.put(new Integer(0x40000022), "ID Field Stop");
h.put(new Integer(0x40000023), "Field Stop Value");
h.put(new Integer(0x40000024), "ID Condensor Aperture");
h.put(new Integer(0x40000025), "Condensor Aperture");
h.put(new Integer(0x40000026), "ID Condensor Revolver");
h.put(new Integer(0x40000027), "Condensor Revolver");
h.put(new Integer(0x40000028), "ID Transmission Filter 1");
h.put(new Integer(0x40000029), "ID Transmission 1");
h.put(new Integer(0x40000030), "ID Transmission Filter 2");
h.put(new Integer(0x40000031), "ID Transmission 2");
h.put(new Integer(0x40000032), "Repeat Bleach");
h.put(new Integer(0x40000033), "Enable Spot Bleach Pos");
h.put(new Integer(0x40000034), "Spot Bleach Position X");
h.put(new Integer(0x40000035), "Spot Bleach Position Y");
h.put(new Integer(0x40000036), "Bleach Position Z");
h.put(new Integer(0x50000003), "Power");
h.put(new Integer(0x90000002), "Power");
h.put(new Integer(0x70000003), "Detector Gain");
h.put(new Integer(0x70000005), "Amplifier Gain");
h.put(new Integer(0x70000007), "Amplifier Offset");
h.put(new Integer(0x70000009), "Pinhole Diameter");
h.put(new Integer(0x7000000c), "Detector Name");
h.put(new Integer(0x7000000d), "Amplifier Name");
h.put(new Integer(0x7000000e), "Pinhole Name");
h.put(new Integer(0x7000000f), "Filter Set Name");
h.put(new Integer(0x70000010), "Filter Name");
h.put(new Integer(0x70000013), "Integrator Name");
h.put(new Integer(0x70000014), "Detection Channel Name");
h.put(new Integer(0x70000015), "Detector Gain B/C 1");
h.put(new Integer(0x70000016), "Detector Gain B/C 2");
h.put(new Integer(0x70000017), "Amplifier Gain B/C 1");
h.put(new Integer(0x70000018), "Amplifier Gain B/C 2");
h.put(new Integer(0x70000019), "Amplifier Offset B/C 1");
h.put(new Integer(0x70000020), "Amplifier Offset B/C 2");
h.put(new Integer(0x70000021), "Spectral Scan Channels");
h.put(new Integer(0x70000022), "SPI Wavelength Start");
h.put(new Integer(0x70000023), "SPI Wavelength End");
h.put(new Integer(0x70000026), "Dye Name");
h.put(new Integer(0xd0000014), "Dye Name");
h.put(new Integer(0x70000027), "Dye Folder");
h.put(new Integer(0xd0000015), "Dye Folder");
h.put(new Integer(0x90000003), "Wavelength");
h.put(new Integer(0x90000006), "Power B/C 1");
h.put(new Integer(0x90000007), "Power B/C 2");
h.put(new Integer(0xb0000001), "Filter Set");
h.put(new Integer(0xb0000002), "Filter");
h.put(new Integer(0xd0000004), "Color");
h.put(new Integer(0xd0000005), "Sample Type");
h.put(new Integer(0xd0000006), "Bits Per Sample");
h.put(new Integer(0xd0000007), "Ratio Type");
h.put(new Integer(0xd0000008), "Ratio Track 1");
h.put(new Integer(0xd0000009), "Ratio Track 2");
h.put(new Integer(0xd000000a), "Ratio Channel 1");
h.put(new Integer(0xd000000b), "Ratio Channel 2");
h.put(new Integer(0xd000000c), "Ratio Const. 1");
h.put(new Integer(0xd000000d), "Ratio Const. 2");
h.put(new Integer(0xd000000e), "Ratio Const. 3");
h.put(new Integer(0xd000000f), "Ratio Const. 4");
h.put(new Integer(0xd0000010), "Ratio Const. 5");
h.put(new Integer(0xd0000011), "Ratio Const. 6");
h.put(new Integer(0xd0000012), "Ratio First Images 1");
h.put(new Integer(0xd0000013), "Ratio First Images 2");
h.put(new Integer(0xd0000016), "Spectrum");
h.put(new Integer(0x12000003), "Interval");
return h;
}
private Integer readEntry() throws IOException {
return new Integer(in.readInt());
}
private Object readValue() throws IOException {
int blockType = in.readInt();
int dataSize = in.readInt();
switch (blockType) {
case TYPE_LONG:
return new Long(in.readInt());
case TYPE_RATIONAL:
return new Double(in.readDouble());
case TYPE_ASCII:
String s = in.readString(dataSize).trim();
StringBuffer sb = new StringBuffer();
for (int i=0; i<s.length(); i++) {
if (s.charAt(i) >= 10) sb.append(s.charAt(i));
else break;
}
return sb.toString();
case TYPE_SUBBLOCK:
return null;
}
in.skipBytes(dataSize);
return "";
}
// -- Helper classes --
class SubBlock {
public Hashtable<Integer, Object> blockData;
public boolean acquire = true;
public SubBlock() {
try {
read();
}
catch (IOException e) {
LOGGER.debug("Failed to read sub-block data", e);
}
}
protected int getIntValue(int key) {
Object o = blockData.get(new Integer(key));
if (o == null) return -1;
return !(o instanceof Number) ? -1 : ((Number) o).intValue();
}
protected float getFloatValue(int key) {
Object o = blockData.get(new Integer(key));
if (o == null) return -1f;
return !(o instanceof Number) ? -1f : ((Number) o).floatValue();
}
protected double getDoubleValue(int key) {
Object o = blockData.get(new Integer(key));
if (o == null) return -1d;
return !(o instanceof Number) ? -1d : ((Number) o).doubleValue();
}
protected String getStringValue(int key) {
Object o = blockData.get(new Integer(key));
return o == null ? null : o.toString();
}
protected void read() throws IOException {
blockData = new Hashtable<Integer, Object>();
Integer entry = readEntry();
Object value = readValue();
while (value != null) {
if (!blockData.containsKey(entry)) blockData.put(entry, value);
entry = readEntry();
value = readValue();
}
}
public void addToHashtable() {
String prefix = this.getClass().getSimpleName() + " #";
int index = 1;
while (getSeriesMeta(prefix + index + " Acquire") != null) index++;
prefix += index;
Integer[] keys = blockData.keySet().toArray(new Integer[0]);
for (Integer key : keys) {
if (metadataKeys.get(key) != null) {
addSeriesMeta(prefix + " " + metadataKeys.get(key),
blockData.get(key));
if (metadataKeys.get(key).equals("Bits Per Sample")) {
core[getSeries()].bitsPerPixel =
Integer.parseInt(blockData.get(key).toString());
}
}
}
addGlobalMeta(prefix + " Acquire", new Boolean(acquire));
}
}
class Recording extends SubBlock {
public String description;
public String name;
public String binning;
public String startTime;
// Objective data
public String correction, immersion;
public Integer magnification;
public Double lensNA;
public Boolean iris;
protected void read() throws IOException {
super.read();
description = getStringValue(RECORDING_DESCRIPTION);
name = getStringValue(RECORDING_NAME);
binning = getStringValue(RECORDING_CAMERA_BINNING);
if (binning != null && binning.indexOf("x") == -1) {
if (binning.equals("0")) binning = null;
else binning += "x" + binning;
}
// start time in days since Dec 30 1899
long stamp = (long) (getDoubleValue(RECORDING_SAMPLE_0TIME) * 86400000);
if (stamp > 0) {
startTime = DateTools.convertDate(stamp, DateTools.MICROSOFT);
}
zoom = getDoubleValue(RECORDING_ZOOM);
String objective = getStringValue(RECORDING_OBJECTIVE);
correction = "";
if (objective == null) objective = "";
String[] tokens = objective.split(" ");
int next = 0;
for (; next<tokens.length; next++) {
if (tokens[next].indexOf("/") != -1) break;
correction += tokens[next];
}
if (next < tokens.length) {
String p = tokens[next++];
try {
magnification = new Integer(p.substring(0, p.indexOf("/") - 1));
}
catch (NumberFormatException e) { }
try {
lensNA = new Double(p.substring(p.indexOf("/") + 1));
}
catch (NumberFormatException e) { }
}
immersion = next < tokens.length ? tokens[next++] : "Unknown";
iris = Boolean.FALSE;
if (next < tokens.length) {
iris = new Boolean(tokens[next++].trim().equalsIgnoreCase("iris"));
}
}
}
class Laser extends SubBlock {
public String medium, type, model;
public Double power;
protected void read() throws IOException {
super.read();
model = getStringValue(LASER_NAME);
type = getStringValue(LASER_NAME);
if (type == null) type = "";
medium = "";
if (type.startsWith("HeNe")) {
medium = "HeNe";
type = "Gas";
}
else if (type.startsWith("Argon")) {
medium = "Ar";
type = "Gas";
}
else if (type.equals("Titanium:Sapphire") || type.equals("Mai Tai")) {
medium = "TiSapphire";
type = "SolidState";
}
else if (type.equals("YAG")) {
medium = "";
type = "SolidState";
}
else if (type.equals("Ar/Kr")) {
medium = "";
type = "Gas";
}
acquire = getIntValue(LASER_ACQUIRE) != 0;
power = getDoubleValue(LASER_POWER);
}
}
class Track extends SubBlock {
public Double timeIncrement;
protected void read() throws IOException {
super.read();
timeIncrement = getDoubleValue(TRACK_TIME_BETWEEN_STACKS);
acquire = getIntValue(TRACK_ACQUIRE) != 0;
}
}
class DetectionChannel extends SubBlock {
public Double pinhole;
public Double gain, amplificationGain;
public String filter, filterSet;
public String channelName;
protected void read() throws IOException {
super.read();
pinhole = new Double(getDoubleValue(CHANNEL_PINHOLE_DIAMETER));
gain = new Double(getDoubleValue(CHANNEL_DETECTOR_GAIN));
amplificationGain = new Double(getDoubleValue(CHANNEL_AMPLIFIER_GAIN));
filter = getStringValue(CHANNEL_FILTER);
if (filter != null) {
filter = filter.trim();
if (filter.length() == 0 || filter.equals("None")) {
filter = null;
}
}
filterSet = getStringValue(CHANNEL_FILTER_SET);
channelName = getStringValue(CHANNEL_NAME);
acquire = getIntValue(CHANNEL_ACQUIRE) != 0;
}
}
class IlluminationChannel extends SubBlock {
public Integer wavelength;
public Double attenuation;
protected void read() throws IOException {
super.read();
wavelength = new Integer(getIntValue(ILLUM_CHANNEL_WAVELENGTH));
attenuation = new Double(getDoubleValue(ILLUM_CHANNEL_ATTENUATION));
acquire = getIntValue(ILLUM_CHANNEL_ACQUIRE) != 0;
}
}
class DataChannel extends SubBlock {
public String name;
protected void read() throws IOException {
super.read();
name = getStringValue(DATA_CHANNEL_NAME);
for (int i=0; i<name.length(); i++) {
if (name.charAt(i) < 10) {
name = name.substring(0, i);
break;
}
}
acquire = getIntValue(DATA_CHANNEL_ACQUIRE) != 0;
}
}
class BeamSplitter extends SubBlock {
public String filter, filterSet;
protected void read() throws IOException {
super.read();
filter = getStringValue(BEAM_SPLITTER_FILTER);
if (filter != null) {
filter = filter.trim();
if (filter.length() == 0 || filter.equals("None")) {
filter = null;
}
}
filterSet = getStringValue(BEAM_SPLITTER_FILTER_SET);
}
}
class Timer extends SubBlock { }
class Marker extends SubBlock { }
}
| true | true | protected void initMetadata(int series) throws FormatException, IOException {
setSeries(series);
IFDList ifds = ifdsList.get(series);
IFD ifd = ifds.get(0);
in = new RandomAccessInputStream(getLSMFileFromSeries(series));
in.order(isLittleEndian());
tiffParser = new TiffParser(in);
PhotoInterp photo = ifd.getPhotometricInterpretation();
int samples = ifd.getSamplesPerPixel();
core[series].sizeX = (int) ifd.getImageWidth();
core[series].sizeY = (int) ifd.getImageLength();
core[series].rgb = samples > 1 || photo == PhotoInterp.RGB;
core[series].interleaved = false;
core[series].sizeC = isRGB() ? samples : 1;
core[series].pixelType = ifd.getPixelType();
core[series].imageCount = ifds.size();
core[series].sizeZ = getImageCount();
core[series].sizeT = 1;
LOGGER.info("Reading LSM metadata for series #{}", series);
MetadataStore store = makeFilterMetadata();
int instrument = getEffectiveSeries(series);
String imageName = getLSMFileFromSeries(series);
if (imageName.indexOf(".") != -1) {
imageName = imageName.substring(0, imageName.lastIndexOf("."));
}
if (imageName.indexOf(File.separator) != -1) {
imageName =
imageName.substring(imageName.lastIndexOf(File.separator) + 1);
}
if (lsmFilenames.length != getSeriesCount()) {
imageName += " #" + (getPosition(series) + 1);
}
// link Instrument and Image
store.setImageID(MetadataTools.createLSID("Image", series), series);
String instrumentID = MetadataTools.createLSID("Instrument", instrument);
store.setInstrumentID(instrumentID, instrument);
store.setImageInstrumentRef(instrumentID, series);
RandomAccessInputStream ras = getCZTag(ifd);
if (ras == null) {
imageNames.add(imageName);
return;
}
ras.seek(16);
core[series].sizeZ = ras.readInt();
ras.skipBytes(4);
core[series].sizeT = ras.readInt();
int dataType = ras.readInt();
switch (dataType) {
case 2:
addSeriesMeta("DataType", "12 bit unsigned integer");
break;
case 5:
addSeriesMeta("DataType", "32 bit float");
break;
case 0:
addSeriesMeta("DataType", "varying data types");
break;
default:
addSeriesMeta("DataType", "8 bit unsigned integer");
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
ras.seek(0);
addSeriesMeta("MagicNumber ", ras.readInt());
addSeriesMeta("StructureSize", ras.readInt());
addSeriesMeta("DimensionX", ras.readInt());
addSeriesMeta("DimensionY", ras.readInt());
ras.seek(32);
addSeriesMeta("ThumbnailX", ras.readInt());
addSeriesMeta("ThumbnailY", ras.readInt());
// pixel sizes are stored in meters, we need them in microns
pixelSizeX = ras.readDouble() * 1000000;
pixelSizeY = ras.readDouble() * 1000000;
pixelSizeZ = ras.readDouble() * 1000000;
addSeriesMeta("VoxelSizeX", new Double(pixelSizeX));
addSeriesMeta("VoxelSizeY", new Double(pixelSizeY));
addSeriesMeta("VoxelSizeZ", new Double(pixelSizeZ));
originX = ras.readDouble() * 1000000;
originY = ras.readDouble() * 1000000;
originZ = ras.readDouble() * 1000000;
addSeriesMeta("OriginX", originX);
addSeriesMeta("OriginY", originY);
addSeriesMeta("OriginZ", originZ);
}
else ras.seek(88);
int scanType = ras.readShort();
switch (scanType) {
case 0:
addSeriesMeta("ScanType", "x-y-z scan");
core[series].dimensionOrder = "XYZCT";
break;
case 1:
addSeriesMeta("ScanType", "z scan (x-z plane)");
core[series].dimensionOrder = "XYZCT";
break;
case 2:
addSeriesMeta("ScanType", "line scan");
core[series].dimensionOrder = "XYZCT";
break;
case 3:
addSeriesMeta("ScanType", "time series x-y");
core[series].dimensionOrder = "XYTCZ";
break;
case 4:
addSeriesMeta("ScanType", "time series x-z");
core[series].dimensionOrder = "XYZTC";
break;
case 5:
addSeriesMeta("ScanType", "time series 'Mean of ROIs'");
core[series].dimensionOrder = "XYTCZ";
break;
case 6:
addSeriesMeta("ScanType", "time series x-y-z");
core[series].dimensionOrder = "XYZTC";
break;
case 7:
addSeriesMeta("ScanType", "spline scan");
core[series].dimensionOrder = "XYCTZ";
break;
case 8:
addSeriesMeta("ScanType", "spline scan x-z");
core[series].dimensionOrder = "XYCZT";
break;
case 9:
addSeriesMeta("ScanType", "time series spline plane x-z");
core[series].dimensionOrder = "XYTCZ";
break;
case 10:
addSeriesMeta("ScanType", "point mode");
core[series].dimensionOrder = "XYZCT";
break;
default:
addSeriesMeta("ScanType", "x-y-z scan");
core[series].dimensionOrder = "XYZCT";
}
core[series].indexed =
lut != null && lut[series] != null && getSizeC() == 1;
if (isIndexed()) {
core[series].sizeC = 1;
core[series].rgb = false;
}
if (getSizeC() == 0) core[series].sizeC = 1;
if (isRGB()) {
// shuffle C to front of order string
core[series].dimensionOrder = getDimensionOrder().replaceAll("C", "");
core[series].dimensionOrder = getDimensionOrder().replaceAll("XY", "XYC");
}
if (getEffectiveSizeC() == 0) {
core[series].imageCount = getSizeZ() * getSizeT();
}
else {
core[series].imageCount = getSizeZ() * getSizeT() * getEffectiveSizeC();
}
if (getImageCount() != ifds.size()) {
int diff = getImageCount() - ifds.size();
core[series].imageCount = ifds.size();
if (diff % getSizeZ() == 0) {
core[series].sizeT -= (diff / getSizeZ());
}
else if (diff % getSizeT() == 0) {
core[series].sizeZ -= (diff / getSizeT());
}
else if (getSizeZ() > 1) {
core[series].sizeZ = ifds.size();
core[series].sizeT = 1;
}
else if (getSizeT() > 1) {
core[series].sizeT = ifds.size();
core[series].sizeZ = 1;
}
}
if (getSizeZ() == 0) core[series].sizeZ = getImageCount();
if (getSizeT() == 0) core[series].sizeT = getImageCount() / getSizeZ();
long channelColorsOffset = 0;
long timeStampOffset = 0;
long eventListOffset = 0;
long scanInformationOffset = 0;
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
int spectralScan = ras.readShort();
if (spectralScan != 1) {
addSeriesMeta("SpectralScan", "no spectral scan");
}
else addSeriesMeta("SpectralScan", "acquired with spectral scan");
int type = ras.readInt();
switch (type) {
case 1:
addSeriesMeta("DataType2", "calculated data");
break;
case 2:
addSeriesMeta("DataType2", "animation");
break;
default:
addSeriesMeta("DataType2", "original scan data");
}
long[] overlayOffsets = new long[9];
String[] overlayKeys = new String[] {"VectorOverlay", "InputLut",
"OutputLut", "ROI", "BleachROI", "MeanOfRoisOverlay",
"TopoIsolineOverlay", "TopoProfileOverlay", "LinescanOverlay"};
overlayOffsets[0] = ras.readInt();
overlayOffsets[1] = ras.readInt();
overlayOffsets[2] = ras.readInt();
channelColorsOffset = ras.readInt();
addSeriesMeta("TimeInterval", ras.readDouble());
ras.skipBytes(4);
scanInformationOffset = ras.readInt();
ras.skipBytes(4);
timeStampOffset = ras.readInt();
eventListOffset = ras.readInt();
overlayOffsets[3] = ras.readInt();
overlayOffsets[4] = ras.readInt();
ras.skipBytes(4);
addSeriesMeta("DisplayAspectX", ras.readDouble());
addSeriesMeta("DisplayAspectY", ras.readDouble());
addSeriesMeta("DisplayAspectZ", ras.readDouble());
addSeriesMeta("DisplayAspectTime", ras.readDouble());
overlayOffsets[5] = ras.readInt();
overlayOffsets[6] = ras.readInt();
overlayOffsets[7] = ras.readInt();
overlayOffsets[8] = ras.readInt();
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.NO_OVERLAYS)
{
for (int i=0; i<overlayOffsets.length; i++) {
parseOverlays(series, overlayOffsets[i], overlayKeys[i], store);
}
}
totalROIs = 0;
addSeriesMeta("ToolbarFlags", ras.readInt());
int wavelengthOffset = ras.readInt();
ras.skipBytes(64);
}
else ras.skipBytes(182);
MetadataTools.setDefaultCreationDate(store, getCurrentFile(), series);
if (getSizeC() > 1) {
if (!splitPlanes) splitPlanes = isRGB();
core[series].rgb = false;
if (splitPlanes) core[series].imageCount *= getSizeC();
}
for (int c=0; c<getEffectiveSizeC(); c++) {
String lsid = MetadataTools.createLSID("Channel", series, c);
store.setChannelID(lsid, series, c);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
// NB: the Zeiss LSM 5.5 specification indicates that there should be
// 15 32-bit integers here; however, there are actually 16 32-bit
// integers before the tile position offset.
// We have confirmed with Zeiss that this is correct, and the 6.0
// specification was updated to contain the correct information.
ras.skipBytes(64);
int tilePositionOffset = ras.readInt();
ras.skipBytes(36);
int positionOffset = ras.readInt();
// read referenced structures
addSeriesMeta("DimensionZ", getSizeZ());
addSeriesMeta("DimensionChannels", getSizeC());
addSeriesMeta("DimensionM", dimensionM);
addSeriesMeta("DimensionP", dimensionP);
if (positionOffset != 0) {
in.seek(positionOffset);
int nPositions = in.readInt();
for (int i=0; i<nPositions; i++) {
double xPos = originX + in.readDouble() * 1000000;
double yPos = originY + in.readDouble() * 1000000;
double zPos = originZ + in.readDouble() * 1000000;
xCoordinates.add(xPos);
yCoordinates.add(yPos);
zCoordinates.add(zPos);
}
}
if (tilePositionOffset != 0) {
in.seek(tilePositionOffset);
int nTiles = in.readInt();
for (int i=0; i<nTiles; i++) {
xCoordinates.add(originX + in.readDouble() * 1000000);
yCoordinates.add(originY + in.readDouble() * 1000000);
zCoordinates.add(originZ + in.readDouble() * 1000000);
}
}
if (channelColorsOffset != 0) {
in.seek(channelColorsOffset + 16);
int namesOffset = in.readInt();
// read the name of each channel
if (namesOffset > 0) {
in.skipBytes(namesOffset - 16);
for (int i=0; i<getSizeC(); i++) {
if (in.getFilePointer() >= in.length() - 1) break;
// we want to read until we find a null char
String name = in.readCString();
if (name.length() <= 128) {
addSeriesMeta("ChannelName" + i, name);
}
}
}
}
if (timeStampOffset != 0) {
in.seek(timeStampOffset + 8);
for (int i=0; i<getSizeT(); i++) {
double stamp = in.readDouble();
addSeriesMeta("TimeStamp" + i, stamp);
timestamps.add(new Double(stamp));
}
}
if (eventListOffset != 0) {
in.seek(eventListOffset + 4);
int numEvents = in.readInt();
in.seek(in.getFilePointer() - 4);
in.order(!in.isLittleEndian());
int tmpEvents = in.readInt();
if (numEvents < 0) numEvents = tmpEvents;
else numEvents = (int) Math.min(numEvents, tmpEvents);
in.order(!in.isLittleEndian());
if (numEvents > 65535) numEvents = 0;
for (int i=0; i<numEvents; i++) {
if (in.getFilePointer() + 16 <= in.length()) {
int size = in.readInt();
double eventTime = in.readDouble();
int eventType = in.readInt();
addSeriesMeta("Event" + i + " Time", eventTime);
addSeriesMeta("Event" + i + " Type", eventType);
long fp = in.getFilePointer();
int len = size - 16;
if (len > 65536) len = 65536;
if (len < 0) len = 0;
addSeriesMeta("Event" + i + " Description", in.readString(len));
in.seek(fp + size - 16);
if (in.getFilePointer() < 0) break;
}
}
}
if (scanInformationOffset != 0) {
in.seek(scanInformationOffset);
nextLaser = nextDetector = 0;
nextFilter = nextDichroicChannel = nextDichroic = 0;
nextDataChannel = nextDetectChannel = nextIllumChannel = 0;
Vector<SubBlock> blocks = new Vector<SubBlock>();
while (in.getFilePointer() < in.length() - 12) {
if (in.getFilePointer() < 0) break;
int entry = in.readInt();
int blockType = in.readInt();
int dataSize = in.readInt();
if (blockType == TYPE_SUBBLOCK) {
SubBlock block = null;
switch (entry) {
case SUBBLOCK_RECORDING:
block = new Recording();
break;
case SUBBLOCK_LASER:
block = new Laser();
break;
case SUBBLOCK_TRACK:
block = new Track();
break;
case SUBBLOCK_DETECTION_CHANNEL:
block = new DetectionChannel();
break;
case SUBBLOCK_ILLUMINATION_CHANNEL:
block = new IlluminationChannel();
break;
case SUBBLOCK_BEAM_SPLITTER:
block = new BeamSplitter();
break;
case SUBBLOCK_DATA_CHANNEL:
block = new DataChannel();
break;
case SUBBLOCK_TIMER:
block = new Timer();
break;
case SUBBLOCK_MARKER:
block = new Marker();
break;
}
if (block != null) {
blocks.add(block);
}
}
else if (dataSize + in.getFilePointer() <= in.length()) {
in.skipBytes(dataSize);
}
else break;
}
Vector<SubBlock> nonAcquiredBlocks = new Vector<SubBlock>();
SubBlock[] metadataBlocks = blocks.toArray(new SubBlock[0]);
for (SubBlock block : metadataBlocks) {
block.addToHashtable();
if (!block.acquire) {
nonAcquiredBlocks.add(block);
blocks.remove(block);
}
}
for (int i=0; i<blocks.size(); i++) {
SubBlock block = blocks.get(i);
// every valid IlluminationChannel must be immediately followed by
// a valid DataChannel or IlluminationChannel
if ((block instanceof IlluminationChannel) && i < blocks.size() - 1) {
SubBlock nextBlock = blocks.get(i + 1);
if (!(nextBlock instanceof DataChannel) &&
!(nextBlock instanceof IlluminationChannel))
{
((IlluminationChannel) block).wavelength = null;
}
}
// every valid DetectionChannel must be immediately preceded by
// a valid Track or DetectionChannel
else if ((block instanceof DetectionChannel) && i > 0) {
SubBlock prevBlock = blocks.get(i - 1);
if (!(prevBlock instanceof Track) &&
!(prevBlock instanceof DetectionChannel))
{
block.acquire = false;
nonAcquiredBlocks.add(block);
}
}
if (block.acquire) populateMetadataStore(block, store, series);
}
for (SubBlock block : nonAcquiredBlocks) {
populateMetadataStore(block, store, series);
}
}
}
imageNames.add(imageName);
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
Double pixX = new Double(pixelSizeX);
Double pixY = new Double(pixelSizeY);
Double pixZ = new Double(pixelSizeZ);
store.setPixelsPhysicalSizeX(pixX, series);
store.setPixelsPhysicalSizeY(pixY, series);
store.setPixelsPhysicalSizeZ(pixZ, series);
double firstStamp = 0;
if (timestamps.size() > 0) {
firstStamp = timestamps.get(0).doubleValue();
}
for (int i=0; i<getImageCount(); i++) {
int[] zct = FormatTools.getZCTCoords(this, i);
if (zct[2] < timestamps.size()) {
double thisStamp = timestamps.get(zct[2]).doubleValue();
store.setPlaneDeltaT(thisStamp - firstStamp, series, i);
int index = zct[2] + 1;
double nextStamp = index < timestamps.size() ?
timestamps.get(index).doubleValue() : thisStamp;
if (i == getSizeT() - 1 && zct[2] > 0) {
thisStamp = timestamps.get(zct[2] - 1).doubleValue();
}
store.setPlaneExposureTime(nextStamp - thisStamp, series, i);
}
if (xCoordinates.size() > 0) {
double planesPerStage =
(double) getImageCount() / xCoordinates.size();
int stage = (int) (i / planesPerStage);
store.setPlanePositionX(xCoordinates.get(stage), series, i);
store.setPlanePositionY(yCoordinates.get(stage), series, i);
store.setPlanePositionZ(zCoordinates.get(stage), series, i);
}
}
}
ras.close();
in.close();
}
| protected void initMetadata(int series) throws FormatException, IOException {
setSeries(series);
IFDList ifds = ifdsList.get(series);
IFD ifd = ifds.get(0);
in = new RandomAccessInputStream(getLSMFileFromSeries(series));
in.order(isLittleEndian());
tiffParser = new TiffParser(in);
PhotoInterp photo = ifd.getPhotometricInterpretation();
int samples = ifd.getSamplesPerPixel();
core[series].sizeX = (int) ifd.getImageWidth();
core[series].sizeY = (int) ifd.getImageLength();
core[series].rgb = samples > 1 || photo == PhotoInterp.RGB;
core[series].interleaved = false;
core[series].sizeC = isRGB() ? samples : 1;
core[series].pixelType = ifd.getPixelType();
core[series].imageCount = ifds.size();
core[series].sizeZ = getImageCount();
core[series].sizeT = 1;
LOGGER.info("Reading LSM metadata for series #{}", series);
MetadataStore store = makeFilterMetadata();
int instrument = getEffectiveSeries(series);
String imageName = getLSMFileFromSeries(series);
if (imageName.indexOf(".") != -1) {
imageName = imageName.substring(0, imageName.lastIndexOf("."));
}
if (imageName.indexOf(File.separator) != -1) {
imageName =
imageName.substring(imageName.lastIndexOf(File.separator) + 1);
}
if (lsmFilenames.length != getSeriesCount()) {
imageName += " #" + (getPosition(series) + 1);
}
// link Instrument and Image
store.setImageID(MetadataTools.createLSID("Image", series), series);
String instrumentID = MetadataTools.createLSID("Instrument", instrument);
store.setInstrumentID(instrumentID, instrument);
store.setImageInstrumentRef(instrumentID, series);
RandomAccessInputStream ras = getCZTag(ifd);
if (ras == null) {
imageNames.add(imageName);
return;
}
ras.seek(16);
core[series].sizeZ = ras.readInt();
ras.skipBytes(4);
core[series].sizeT = ras.readInt();
int dataType = ras.readInt();
switch (dataType) {
case 2:
addSeriesMeta("DataType", "12 bit unsigned integer");
break;
case 5:
addSeriesMeta("DataType", "32 bit float");
break;
case 0:
addSeriesMeta("DataType", "varying data types");
break;
default:
addSeriesMeta("DataType", "8 bit unsigned integer");
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
ras.seek(0);
addSeriesMeta("MagicNumber ", ras.readInt());
addSeriesMeta("StructureSize", ras.readInt());
addSeriesMeta("DimensionX", ras.readInt());
addSeriesMeta("DimensionY", ras.readInt());
ras.seek(32);
addSeriesMeta("ThumbnailX", ras.readInt());
addSeriesMeta("ThumbnailY", ras.readInt());
// pixel sizes are stored in meters, we need them in microns
pixelSizeX = ras.readDouble() * 1000000;
pixelSizeY = ras.readDouble() * 1000000;
pixelSizeZ = ras.readDouble() * 1000000;
addSeriesMeta("VoxelSizeX", new Double(pixelSizeX));
addSeriesMeta("VoxelSizeY", new Double(pixelSizeY));
addSeriesMeta("VoxelSizeZ", new Double(pixelSizeZ));
originX = ras.readDouble() * 1000000;
originY = ras.readDouble() * 1000000;
originZ = ras.readDouble() * 1000000;
addSeriesMeta("OriginX", originX);
addSeriesMeta("OriginY", originY);
addSeriesMeta("OriginZ", originZ);
}
else ras.seek(88);
int scanType = ras.readShort();
switch (scanType) {
case 0:
addSeriesMeta("ScanType", "x-y-z scan");
core[series].dimensionOrder = "XYZCT";
break;
case 1:
addSeriesMeta("ScanType", "z scan (x-z plane)");
core[series].dimensionOrder = "XYZCT";
break;
case 2:
addSeriesMeta("ScanType", "line scan");
core[series].dimensionOrder = "XYZCT";
break;
case 3:
addSeriesMeta("ScanType", "time series x-y");
core[series].dimensionOrder = "XYTCZ";
break;
case 4:
addSeriesMeta("ScanType", "time series x-z");
core[series].dimensionOrder = "XYZTC";
break;
case 5:
addSeriesMeta("ScanType", "time series 'Mean of ROIs'");
core[series].dimensionOrder = "XYTCZ";
break;
case 6:
addSeriesMeta("ScanType", "time series x-y-z");
core[series].dimensionOrder = "XYZTC";
break;
case 7:
addSeriesMeta("ScanType", "spline scan");
core[series].dimensionOrder = "XYCTZ";
break;
case 8:
addSeriesMeta("ScanType", "spline scan x-z");
core[series].dimensionOrder = "XYCZT";
break;
case 9:
addSeriesMeta("ScanType", "time series spline plane x-z");
core[series].dimensionOrder = "XYTCZ";
break;
case 10:
addSeriesMeta("ScanType", "point mode");
core[series].dimensionOrder = "XYZCT";
break;
default:
addSeriesMeta("ScanType", "x-y-z scan");
core[series].dimensionOrder = "XYZCT";
}
core[series].indexed =
lut != null && lut[series] != null && getSizeC() == 1;
if (isIndexed()) {
core[series].sizeC = 1;
core[series].rgb = false;
}
if (getSizeC() == 0) core[series].sizeC = 1;
if (isRGB()) {
// shuffle C to front of order string
core[series].dimensionOrder = getDimensionOrder().replaceAll("C", "");
core[series].dimensionOrder = getDimensionOrder().replaceAll("XY", "XYC");
}
if (getEffectiveSizeC() == 0) {
core[series].imageCount = getSizeZ() * getSizeT();
}
else {
core[series].imageCount = getSizeZ() * getSizeT() * getEffectiveSizeC();
}
if (getImageCount() != ifds.size()) {
int diff = getImageCount() - ifds.size();
core[series].imageCount = ifds.size();
if (diff % getSizeZ() == 0) {
core[series].sizeT -= (diff / getSizeZ());
}
else if (diff % getSizeT() == 0) {
core[series].sizeZ -= (diff / getSizeT());
}
else if (getSizeZ() > 1) {
core[series].sizeZ = ifds.size();
core[series].sizeT = 1;
}
else if (getSizeT() > 1) {
core[series].sizeT = ifds.size();
core[series].sizeZ = 1;
}
}
if (getSizeZ() == 0) core[series].sizeZ = getImageCount();
if (getSizeT() == 0) core[series].sizeT = getImageCount() / getSizeZ();
long channelColorsOffset = 0;
long timeStampOffset = 0;
long eventListOffset = 0;
long scanInformationOffset = 0;
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
int spectralScan = ras.readShort();
if (spectralScan != 1) {
addSeriesMeta("SpectralScan", "no spectral scan");
}
else addSeriesMeta("SpectralScan", "acquired with spectral scan");
int type = ras.readInt();
switch (type) {
case 1:
addSeriesMeta("DataType2", "calculated data");
break;
case 2:
addSeriesMeta("DataType2", "animation");
break;
default:
addSeriesMeta("DataType2", "original scan data");
}
long[] overlayOffsets = new long[9];
String[] overlayKeys = new String[] {"VectorOverlay", "InputLut",
"OutputLut", "ROI", "BleachROI", "MeanOfRoisOverlay",
"TopoIsolineOverlay", "TopoProfileOverlay", "LinescanOverlay"};
overlayOffsets[0] = ras.readInt();
overlayOffsets[1] = ras.readInt();
overlayOffsets[2] = ras.readInt();
channelColorsOffset = ras.readInt();
addSeriesMeta("TimeInterval", ras.readDouble());
ras.skipBytes(4);
scanInformationOffset = ras.readInt();
ras.skipBytes(4);
timeStampOffset = ras.readInt();
eventListOffset = ras.readInt();
overlayOffsets[3] = ras.readInt();
overlayOffsets[4] = ras.readInt();
ras.skipBytes(4);
addSeriesMeta("DisplayAspectX", ras.readDouble());
addSeriesMeta("DisplayAspectY", ras.readDouble());
addSeriesMeta("DisplayAspectZ", ras.readDouble());
addSeriesMeta("DisplayAspectTime", ras.readDouble());
overlayOffsets[5] = ras.readInt();
overlayOffsets[6] = ras.readInt();
overlayOffsets[7] = ras.readInt();
overlayOffsets[8] = ras.readInt();
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.NO_OVERLAYS)
{
for (int i=0; i<overlayOffsets.length; i++) {
parseOverlays(series, overlayOffsets[i], overlayKeys[i], store);
}
}
totalROIs = 0;
addSeriesMeta("ToolbarFlags", ras.readInt());
int wavelengthOffset = ras.readInt();
ras.skipBytes(64);
}
else ras.skipBytes(182);
MetadataTools.setDefaultCreationDate(store, getCurrentFile(), series);
if (getSizeC() > 1) {
if (!splitPlanes) splitPlanes = isRGB();
core[series].rgb = false;
if (splitPlanes) core[series].imageCount *= getSizeC();
}
for (int c=0; c<getEffectiveSizeC(); c++) {
String lsid = MetadataTools.createLSID("Channel", series, c);
store.setChannelID(lsid, series, c);
}
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
// NB: the Zeiss LSM 5.5 specification indicates that there should be
// 15 32-bit integers here; however, there are actually 16 32-bit
// integers before the tile position offset.
// We have confirmed with Zeiss that this is correct, and the 6.0
// specification was updated to contain the correct information.
ras.skipBytes(64);
int tilePositionOffset = ras.readInt();
ras.skipBytes(36);
int positionOffset = ras.readInt();
// read referenced structures
addSeriesMeta("DimensionZ", getSizeZ());
addSeriesMeta("DimensionChannels", getSizeC());
addSeriesMeta("DimensionM", dimensionM);
addSeriesMeta("DimensionP", dimensionP);
if (positionOffset != 0) {
in.seek(positionOffset);
int nPositions = in.readInt();
for (int i=0; i<nPositions; i++) {
double xPos = originX + in.readDouble() * 1000000;
double yPos = originY + in.readDouble() * 1000000;
double zPos = originZ + in.readDouble() * 1000000;
xCoordinates.add(xPos);
yCoordinates.add(yPos);
zCoordinates.add(zPos);
}
}
if (tilePositionOffset != 0) {
in.seek(tilePositionOffset);
int nTiles = in.readInt();
for (int i=0; i<nTiles; i++) {
xCoordinates.add(originX + in.readDouble() * 1000000);
yCoordinates.add(originY + in.readDouble() * 1000000);
zCoordinates.add(originZ + in.readDouble() * 1000000);
}
}
if (channelColorsOffset != 0) {
in.seek(channelColorsOffset + 16);
int namesOffset = in.readInt();
// read the name of each channel
if (namesOffset > 0) {
in.skipBytes(namesOffset - 16);
for (int i=0; i<getSizeC(); i++) {
if (in.getFilePointer() >= in.length() - 1) break;
// we want to read until we find a null char
String name = in.readCString();
if (name.length() <= 128) {
addSeriesMeta("ChannelName" + i, name);
}
}
}
}
if (timeStampOffset != 0) {
in.seek(timeStampOffset + 8);
for (int i=0; i<getSizeT(); i++) {
double stamp = in.readDouble();
addSeriesMeta("TimeStamp" + i, stamp);
timestamps.add(new Double(stamp));
}
}
if (eventListOffset != 0) {
in.seek(eventListOffset + 4);
int numEvents = in.readInt();
in.seek(in.getFilePointer() - 4);
in.order(!in.isLittleEndian());
int tmpEvents = in.readInt();
if (numEvents < 0) numEvents = tmpEvents;
else numEvents = (int) Math.min(numEvents, tmpEvents);
in.order(!in.isLittleEndian());
if (numEvents > 65535) numEvents = 0;
for (int i=0; i<numEvents; i++) {
if (in.getFilePointer() + 16 <= in.length()) {
int size = in.readInt();
double eventTime = in.readDouble();
int eventType = in.readInt();
addSeriesMeta("Event" + i + " Time", eventTime);
addSeriesMeta("Event" + i + " Type", eventType);
long fp = in.getFilePointer();
int len = size - 16;
if (len > 65536) len = 65536;
if (len < 0) len = 0;
addSeriesMeta("Event" + i + " Description", in.readString(len));
in.seek(fp + size - 16);
if (in.getFilePointer() < 0) break;
}
}
}
if (scanInformationOffset != 0) {
in.seek(scanInformationOffset);
nextLaser = nextDetector = 0;
nextFilter = nextDichroicChannel = nextDichroic = 0;
nextDataChannel = nextDetectChannel = nextIllumChannel = 0;
Vector<SubBlock> blocks = new Vector<SubBlock>();
while (in.getFilePointer() < in.length() - 12) {
if (in.getFilePointer() < 0) break;
int entry = in.readInt();
int blockType = in.readInt();
int dataSize = in.readInt();
if (blockType == TYPE_SUBBLOCK) {
SubBlock block = null;
switch (entry) {
case SUBBLOCK_RECORDING:
block = new Recording();
break;
case SUBBLOCK_LASER:
block = new Laser();
break;
case SUBBLOCK_TRACK:
block = new Track();
break;
case SUBBLOCK_DETECTION_CHANNEL:
block = new DetectionChannel();
break;
case SUBBLOCK_ILLUMINATION_CHANNEL:
block = new IlluminationChannel();
break;
case SUBBLOCK_BEAM_SPLITTER:
block = new BeamSplitter();
break;
case SUBBLOCK_DATA_CHANNEL:
block = new DataChannel();
break;
case SUBBLOCK_TIMER:
block = new Timer();
break;
case SUBBLOCK_MARKER:
block = new Marker();
break;
}
if (block != null) {
blocks.add(block);
}
}
else if (dataSize + in.getFilePointer() <= in.length()) {
in.skipBytes(dataSize);
}
else break;
}
Vector<SubBlock> nonAcquiredBlocks = new Vector<SubBlock>();
SubBlock[] metadataBlocks = blocks.toArray(new SubBlock[0]);
for (SubBlock block : metadataBlocks) {
block.addToHashtable();
if (!block.acquire) {
nonAcquiredBlocks.add(block);
blocks.remove(block);
}
}
for (int i=0; i<blocks.size(); i++) {
SubBlock block = blocks.get(i);
// every valid IlluminationChannel must be immediately followed by
// a valid DataChannel or IlluminationChannel
if ((block instanceof IlluminationChannel) && i < blocks.size() - 1) {
SubBlock nextBlock = blocks.get(i + 1);
if (!(nextBlock instanceof DataChannel) &&
!(nextBlock instanceof IlluminationChannel))
{
((IlluminationChannel) block).wavelength = null;
}
}
// every valid DetectionChannel must be immediately preceded by
// a valid Track or DetectionChannel
else if ((block instanceof DetectionChannel) && i > 0) {
SubBlock prevBlock = blocks.get(i - 1);
if (!(prevBlock instanceof Track) &&
!(prevBlock instanceof DetectionChannel))
{
block.acquire = false;
nonAcquiredBlocks.add(block);
}
}
if (block.acquire) populateMetadataStore(block, store, series);
}
for (SubBlock block : nonAcquiredBlocks) {
populateMetadataStore(block, store, series);
}
}
}
imageNames.add(imageName);
if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) {
Double pixX = new Double(pixelSizeX);
Double pixY = new Double(pixelSizeY);
Double pixZ = new Double(pixelSizeZ);
store.setPixelsPhysicalSizeX(pixX, series);
store.setPixelsPhysicalSizeY(pixY, series);
store.setPixelsPhysicalSizeZ(pixZ, series);
double firstStamp = 0;
if (timestamps.size() > 0) {
firstStamp = timestamps.get(0).doubleValue();
}
for (int i=0; i<getImageCount(); i++) {
int[] zct = FormatTools.getZCTCoords(this, i);
if (zct[2] < timestamps.size()) {
double thisStamp = timestamps.get(zct[2]).doubleValue();
store.setPlaneDeltaT(thisStamp - firstStamp, series, i);
int index = zct[2] + 1;
double nextStamp = index < timestamps.size() ?
timestamps.get(index).doubleValue() : thisStamp;
if (i == getSizeT() - 1 && zct[2] > 0) {
thisStamp = timestamps.get(zct[2] - 1).doubleValue();
}
store.setPlaneExposureTime(nextStamp - thisStamp, series, i);
}
if (xCoordinates.size() > series) {
store.setPlanePositionX(xCoordinates.get(series), series, i);
store.setPlanePositionY(yCoordinates.get(series), series, i);
store.setPlanePositionZ(zCoordinates.get(series), series, i);
}
}
}
ras.close();
in.close();
}
|
diff --git a/src/powercrystals/minefactoryreloaded/setup/MineFactoryReloadedWorldGen.java b/src/powercrystals/minefactoryreloaded/setup/MineFactoryReloadedWorldGen.java
index ec895787..b9120125 100644
--- a/src/powercrystals/minefactoryreloaded/setup/MineFactoryReloadedWorldGen.java
+++ b/src/powercrystals/minefactoryreloaded/setup/MineFactoryReloadedWorldGen.java
@@ -1,55 +1,55 @@
package powercrystals.minefactoryreloaded.setup;
import java.util.Random;
import powercrystals.minefactoryreloaded.MFRRegistry;
import powercrystals.minefactoryreloaded.MineFactoryReloadedCore;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.gen.feature.WorldGenLakes;
import cpw.mods.fml.common.IWorldGenerator;
public class MineFactoryReloadedWorldGen implements IWorldGenerator
{
@Override
public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider)
{
int x = chunkX * 16 + random.nextInt(16);
int z = chunkZ * 16 + random.nextInt(16);
if(MineFactoryReloadedCore.rubberTreeWorldGen.getBoolean(true))
{
BiomeGenBase b = world.getBiomeGenForCoords(x, z);
if(MFRRegistry.getRubberTreeBiomes().contains(b.biomeName))
{
if(random.nextInt(100) < 40)
{
new WorldGenRubberTree().generate(world, random, x, random.nextInt(3) + 4, z);
}
}
}
- if(MineFactoryReloadedCore.mfrLakeWorldGen.getBoolean(true))
+ if(MineFactoryReloadedCore.mfrLakeWorldGen.getBoolean(true) && world.provider.canRespawnHere())
{
- if(random.nextInt(11) == 0)
+ if(random.nextInt(16) == 0)
{
int lakeX = x - 8 + random.nextInt(16);
int lakeY = random.nextInt(128);
int lakeZ = z - 8 + random.nextInt(16);
new WorldGenLakes(MineFactoryReloadedCore.sludgeStill.blockID).generate(world, random, lakeX, lakeY, lakeZ);
}
- if(random.nextInt(11) == 0)
+ if(random.nextInt(16) == 0)
{
int lakeX = x - 8 + random.nextInt(16);
int lakeY = random.nextInt(128);
int lakeZ = z - 8 + random.nextInt(16);
new WorldGenLakes(MineFactoryReloadedCore.sewageStill.blockID).generate(world, random, lakeX, lakeY, lakeZ);
}
}
}
}
| false | true | public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider)
{
int x = chunkX * 16 + random.nextInt(16);
int z = chunkZ * 16 + random.nextInt(16);
if(MineFactoryReloadedCore.rubberTreeWorldGen.getBoolean(true))
{
BiomeGenBase b = world.getBiomeGenForCoords(x, z);
if(MFRRegistry.getRubberTreeBiomes().contains(b.biomeName))
{
if(random.nextInt(100) < 40)
{
new WorldGenRubberTree().generate(world, random, x, random.nextInt(3) + 4, z);
}
}
}
if(MineFactoryReloadedCore.mfrLakeWorldGen.getBoolean(true))
{
if(random.nextInt(11) == 0)
{
int lakeX = x - 8 + random.nextInt(16);
int lakeY = random.nextInt(128);
int lakeZ = z - 8 + random.nextInt(16);
new WorldGenLakes(MineFactoryReloadedCore.sludgeStill.blockID).generate(world, random, lakeX, lakeY, lakeZ);
}
if(random.nextInt(11) == 0)
{
int lakeX = x - 8 + random.nextInt(16);
int lakeY = random.nextInt(128);
int lakeZ = z - 8 + random.nextInt(16);
new WorldGenLakes(MineFactoryReloadedCore.sewageStill.blockID).generate(world, random, lakeX, lakeY, lakeZ);
}
}
}
| public void generate(Random random, int chunkX, int chunkZ, World world, IChunkProvider chunkGenerator, IChunkProvider chunkProvider)
{
int x = chunkX * 16 + random.nextInt(16);
int z = chunkZ * 16 + random.nextInt(16);
if(MineFactoryReloadedCore.rubberTreeWorldGen.getBoolean(true))
{
BiomeGenBase b = world.getBiomeGenForCoords(x, z);
if(MFRRegistry.getRubberTreeBiomes().contains(b.biomeName))
{
if(random.nextInt(100) < 40)
{
new WorldGenRubberTree().generate(world, random, x, random.nextInt(3) + 4, z);
}
}
}
if(MineFactoryReloadedCore.mfrLakeWorldGen.getBoolean(true) && world.provider.canRespawnHere())
{
if(random.nextInt(16) == 0)
{
int lakeX = x - 8 + random.nextInt(16);
int lakeY = random.nextInt(128);
int lakeZ = z - 8 + random.nextInt(16);
new WorldGenLakes(MineFactoryReloadedCore.sludgeStill.blockID).generate(world, random, lakeX, lakeY, lakeZ);
}
if(random.nextInt(16) == 0)
{
int lakeX = x - 8 + random.nextInt(16);
int lakeY = random.nextInt(128);
int lakeZ = z - 8 + random.nextInt(16);
new WorldGenLakes(MineFactoryReloadedCore.sewageStill.blockID).generate(world, random, lakeX, lakeY, lakeZ);
}
}
}
|
diff --git a/src/org/opensolaris/opengrok/analysis/Definitions.java b/src/org/opensolaris/opengrok/analysis/Definitions.java
index 910cff9..aee6c47 100644
--- a/src/org/opensolaris/opengrok/analysis/Definitions.java
+++ b/src/org/opensolaris/opengrok/analysis/Definitions.java
@@ -1,164 +1,171 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* See LICENSE.txt included in this distribution for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2008 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
package org.opensolaris.opengrok.analysis;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Definitions implements Serializable {
/** Map from symbol to the line numbers on which the symbol is defined. */
private final Map<String, Set<Integer>> symbols;
/** List of all the tags. */
private final List<Tag> tags;
Definitions() {
symbols = new HashMap<String, Set<Integer>>();
tags = new ArrayList<Tag>();
}
/**
* Get all symbols used in definitions.
* @return a set containing all the symbols
*/
public Set<String> getSymbols() {
return symbols.keySet();
}
/**
* Check if there is a tag for a symbol.
* @param symbol the symbol to check
* @return {@code true} iff there is a tag for {@code symbol}
*/
public boolean hasSymbol(String symbol) {
return symbols.containsKey(symbol);
}
/**
* Check whether the specified symbol is defined on the given line.
* @param symbol the symbol to look for
* @param lineNumber the line to check
* @return {@code true} iff {@code symbol} is defined on the specified line
*/
public boolean hasDefinitionAt(String symbol, int lineNumber) {
Set<Integer> lines = symbols.get(symbol);
return lines != null && lines.contains(lineNumber);
}
/**
* Return the number of occurrences of definitions with the specified
* symbol.
* @param symbol the symbol to count the occurrences of
* @return the number of times the specified symbol is defined
*/
public int occurrences(String symbol) {
Set<Integer> lines = symbols.get(symbol);
return lines == null ? 0 : lines.size();
}
/**
* Return the number of distinct symbols.
* @return number of distinct symbols
*/
public int numberOfSymbols() {
return symbols.size();
}
/**
* Get a list of all tags.
* @return all tags
*/
public List<Tag> getTags() {
return tags;
}
/**
* Class that represents a single tag.
*/
public static class Tag implements Serializable {
/** Line number of the tag. */
public final int line;
/** The symbol used in the definition. */
public final String symbol;
/** The type of the tag. */
public final String type;
/** The full line on which the definition occurs. */
public final String text;
private Tag(int line, String symbol, String type, String text) {
this.line = line;
this.symbol = symbol;
this.type = type;
this.text = text;
}
}
void addTag(int line, String symbol, String type, String text) {
+ // The strings are frequently repeated (a symbol can be used in
+ // multiple definitions, multiple definitions can have the same type,
+ // one line can contain multiple definitions). Intern them to minimize
+ // the space consumed by them (see bug #809).
+ symbol = symbol.intern();
+ type = type.intern();
+ text = text.intern();
tags.add(new Tag(line, symbol, type, text));
Set<Integer> lines = symbols.get(symbol);
if (lines == null) {
lines = new HashSet<Integer>();
symbols.put(symbol, lines);
}
lines.add(line);
}
/**
* Create a binary representation of this object.
* @return a byte array representing this object
* @throws IOException if an error happens when writing to the array
*/
public byte[] serialize() throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
new ObjectOutputStream(bytes).writeObject(this);
return bytes.toByteArray();
}
/**
* Deserialize a binary representation of a {@code Definitions} object.
* @param bytes a byte array containing the {@code Definitions} object
* @return a {@code Definitions} object
* @throws IOException if an I/O error happens when reading the array
* @throws ClassNotFoundException if the class definition for an object
* stored in the byte array cannot be found
* @throws ClassCastException if the array contains an object of another
* type than {@code Definitions}
*/
public static Definitions deserialize(byte[] bytes)
throws IOException, ClassNotFoundException {
ObjectInputStream in =
new ObjectInputStream(new ByteArrayInputStream(bytes));
return (Definitions) in.readObject();
}
}
| true | true | void addTag(int line, String symbol, String type, String text) {
tags.add(new Tag(line, symbol, type, text));
Set<Integer> lines = symbols.get(symbol);
if (lines == null) {
lines = new HashSet<Integer>();
symbols.put(symbol, lines);
}
lines.add(line);
}
| void addTag(int line, String symbol, String type, String text) {
// The strings are frequently repeated (a symbol can be used in
// multiple definitions, multiple definitions can have the same type,
// one line can contain multiple definitions). Intern them to minimize
// the space consumed by them (see bug #809).
symbol = symbol.intern();
type = type.intern();
text = text.intern();
tags.add(new Tag(line, symbol, type, text));
Set<Integer> lines = symbols.get(symbol);
if (lines == null) {
lines = new HashSet<Integer>();
symbols.put(symbol, lines);
}
lines.add(line);
}
|
diff --git a/cat-core/src/main/java/com/dianping/cat/Cat.java b/cat-core/src/main/java/com/dianping/cat/Cat.java
index 3bef2600..b385024a 100644
--- a/cat-core/src/main/java/com/dianping/cat/Cat.java
+++ b/cat-core/src/main/java/com/dianping/cat/Cat.java
@@ -1,181 +1,185 @@
package com.dianping.cat;
import java.io.File;
import java.io.InputStream;
import org.codehaus.plexus.DefaultPlexusContainer;
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.PlexusContainerException;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import com.dianping.cat.configuration.ClientConfigMerger;
import com.dianping.cat.configuration.ClientConfigValidator;
import com.dianping.cat.configuration.model.entity.Config;
import com.dianping.cat.configuration.model.transform.DefaultXmlParser;
import com.dianping.cat.message.MessageProducer;
import com.dianping.cat.message.spi.MessageManager;
import com.site.helper.Files;
/**
* This is the main entry point to the system.
*
* @author Frankie Wu
*/
public class Cat {
public static final String CAT_CLIENT_XML = "/META-INF/cat/client.xml";
private static Cat s_instance = new Cat();
private volatile boolean m_initialized;
private MessageProducer m_producer;
private MessageManager m_manager;
private PlexusContainer m_container;
private Cat() {
}
public static void destroy() {
s_instance = new Cat();
}
static Cat getInstance() {
if (!s_instance.m_initialized) {
try {
s_instance.setContainer(new DefaultPlexusContainer());
s_instance.m_initialized = true;
} catch (PlexusContainerException e) {
throw new RuntimeException("Error when creating Plexus container, "
+ "please make sure the environment was setup correctly!", e);
}
}
return s_instance;
}
public static MessageProducer getProducer() {
return getInstance().m_producer;
}
public static MessageManager getManager() {
return getInstance().m_manager;
}
// this should be called during application initialization time
public static void initialize(File configFile) {
Config config = loadClientConfig(configFile);
if (config != null) {
getInstance().m_manager.initializeClient(config);
} else {
getInstance().m_manager.initializeClient(null);
System.out.println("[WARN] Cat client is disabled due to no config file found!");
}
}
public static void initialize(PlexusContainer container, File configFile) {
if (container != null) {
if (!s_instance.m_initialized) {
s_instance.setContainer(container);
s_instance.m_initialized = true;
} else {
throw new RuntimeException("Cat has already been initialized before!");
}
}
initialize(configFile);
}
static Config loadClientConfig(File configFile) {
Config globalConfig = null;
Config clientConfig = null;
try {
// read the global configure from local file system
// so that OPS can:
// - configure the cat servers to connect
// - enable/disable Cat for specific domain(s)
- if (configFile != null && configFile.exists()) {
- String xml = Files.forIO().readFrom(configFile.getCanonicalFile(), "utf-8");
+ if (configFile != null) {
+ if (configFile.exists()) {
+ String xml = Files.forIO().readFrom(configFile.getCanonicalFile(), "utf-8");
- globalConfig = new DefaultXmlParser().parse(xml);
+ globalConfig = new DefaultXmlParser().parse(xml);
+ } else {
+ System.out.format("[WARN] global config file(%s) not found, IGNORED.", configFile);
+ }
}
// load the client configure from Java class-path
if (clientConfig == null) {
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(CAT_CLIENT_XML);
if (in == null) {
in = Cat.class.getResourceAsStream(CAT_CLIENT_XML);
}
if (in != null) {
String xml = Files.forIO().readFrom(in, "utf-8");
clientConfig = new DefaultXmlParser().parse(xml);
}
}
} catch (Exception e) {
throw new RuntimeException(String.format("Error when loading configuration file(%s)!", configFile), e);
}
// merge the two configures together to make it effected
if (globalConfig != null && clientConfig != null) {
globalConfig.accept(new ClientConfigMerger(clientConfig));
}
// do validation
if (clientConfig != null) {
clientConfig.accept(new ClientConfigValidator());
}
return clientConfig;
}
public static boolean isInitialized() {
return s_instance.m_initialized;
}
public static <T> T lookup(Class<T> role) throws ComponentLookupException {
return lookup(role, null);
}
@SuppressWarnings("unchecked")
public static <T> T lookup(Class<T> role, String hint) throws ComponentLookupException {
return (T) getInstance().m_container.lookup(role, hint);
}
// this should be called when a thread ends to clean some thread local data
public static void reset() {
getInstance().m_manager.reset();
}
// this should be called when a thread starts to create some thread local
// data
public static void setup(String sessionToken) {
MessageManager manager = getInstance().m_manager;
manager.setup();
manager.getThreadLocalMessageTree().setSessionToken(sessionToken);
}
void setContainer(PlexusContainer container) {
m_container = container;
try {
m_manager = (MessageManager) container.lookup(MessageManager.class);
} catch (ComponentLookupException e) {
throw new RuntimeException("Unable to get instance of MessageManager, "
+ "please make sure the environment was setup correctly!", e);
}
try {
m_producer = (MessageProducer) container.lookup(MessageProducer.class);
} catch (ComponentLookupException e) {
throw new RuntimeException("Unable to get instance of MessageProducer, "
+ "please make sure the environment was setup correctly!", e);
}
}
}
| false | true | static Config loadClientConfig(File configFile) {
Config globalConfig = null;
Config clientConfig = null;
try {
// read the global configure from local file system
// so that OPS can:
// - configure the cat servers to connect
// - enable/disable Cat for specific domain(s)
if (configFile != null && configFile.exists()) {
String xml = Files.forIO().readFrom(configFile.getCanonicalFile(), "utf-8");
globalConfig = new DefaultXmlParser().parse(xml);
}
// load the client configure from Java class-path
if (clientConfig == null) {
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(CAT_CLIENT_XML);
if (in == null) {
in = Cat.class.getResourceAsStream(CAT_CLIENT_XML);
}
if (in != null) {
String xml = Files.forIO().readFrom(in, "utf-8");
clientConfig = new DefaultXmlParser().parse(xml);
}
}
} catch (Exception e) {
throw new RuntimeException(String.format("Error when loading configuration file(%s)!", configFile), e);
}
// merge the two configures together to make it effected
if (globalConfig != null && clientConfig != null) {
globalConfig.accept(new ClientConfigMerger(clientConfig));
}
// do validation
if (clientConfig != null) {
clientConfig.accept(new ClientConfigValidator());
}
return clientConfig;
}
| static Config loadClientConfig(File configFile) {
Config globalConfig = null;
Config clientConfig = null;
try {
// read the global configure from local file system
// so that OPS can:
// - configure the cat servers to connect
// - enable/disable Cat for specific domain(s)
if (configFile != null) {
if (configFile.exists()) {
String xml = Files.forIO().readFrom(configFile.getCanonicalFile(), "utf-8");
globalConfig = new DefaultXmlParser().parse(xml);
} else {
System.out.format("[WARN] global config file(%s) not found, IGNORED.", configFile);
}
}
// load the client configure from Java class-path
if (clientConfig == null) {
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(CAT_CLIENT_XML);
if (in == null) {
in = Cat.class.getResourceAsStream(CAT_CLIENT_XML);
}
if (in != null) {
String xml = Files.forIO().readFrom(in, "utf-8");
clientConfig = new DefaultXmlParser().parse(xml);
}
}
} catch (Exception e) {
throw new RuntimeException(String.format("Error when loading configuration file(%s)!", configFile), e);
}
// merge the two configures together to make it effected
if (globalConfig != null && clientConfig != null) {
globalConfig.accept(new ClientConfigMerger(clientConfig));
}
// do validation
if (clientConfig != null) {
clientConfig.accept(new ClientConfigValidator());
}
return clientConfig;
}
|
diff --git a/public/java/src/org/broadinstitute/sting/gatk/datasources/reads/LowMemoryIntervalSharder.java b/public/java/src/org/broadinstitute/sting/gatk/datasources/reads/LowMemoryIntervalSharder.java
index ba6321121..bf5f33dc3 100644
--- a/public/java/src/org/broadinstitute/sting/gatk/datasources/reads/LowMemoryIntervalSharder.java
+++ b/public/java/src/org/broadinstitute/sting/gatk/datasources/reads/LowMemoryIntervalSharder.java
@@ -1,68 +1,68 @@
/*
* Copyright (c) 2011, The Broad Institute
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.broadinstitute.sting.gatk.datasources.reads;
import net.sf.picard.util.PeekableIterator;
import org.broadinstitute.sting.utils.GenomeLocParser;
import org.broadinstitute.sting.utils.GenomeLocSortedSet;
import java.util.Iterator;
/**
* Handles the process of aggregating BAM intervals into individual shards.
*/
public class LowMemoryIntervalSharder implements Iterator<FilePointer> {
/**
* The iterator actually laying out the data for BAM scheduling.
*/
private final PeekableIterator<FilePointer> wrappedIterator;
/**
* The parser, for interval manipulation.
*/
private final GenomeLocParser parser;
public LowMemoryIntervalSharder(final SAMDataSource dataSource, final GenomeLocSortedSet loci) {
wrappedIterator = new PeekableIterator<FilePointer>(new BAMScheduler(dataSource,loci));
parser = loci.getGenomeLocParser();
}
public boolean hasNext() {
return wrappedIterator.hasNext();
}
/**
* Accumulate shards where there's no additional cost to processing the next shard in the sequence.
* @return The next file pointer to process.
*/
public FilePointer next() {
FilePointer current = wrappedIterator.next();
- while(wrappedIterator.hasNext() && current.minus(wrappedIterator.peek()) == 0)
+ while(wrappedIterator.hasNext() && current.isRegionUnmapped == wrappedIterator.peek().isRegionUnmapped && current.minus(wrappedIterator.peek()) == 0)
current = current.combine(parser,wrappedIterator.next());
return current;
}
public void remove() { throw new UnsupportedOperationException("Unable to remove from an interval sharder."); }
}
| true | true | public FilePointer next() {
FilePointer current = wrappedIterator.next();
while(wrappedIterator.hasNext() && current.minus(wrappedIterator.peek()) == 0)
current = current.combine(parser,wrappedIterator.next());
return current;
}
| public FilePointer next() {
FilePointer current = wrappedIterator.next();
while(wrappedIterator.hasNext() && current.isRegionUnmapped == wrappedIterator.peek().isRegionUnmapped && current.minus(wrappedIterator.peek()) == 0)
current = current.combine(parser,wrappedIterator.next());
return current;
}
|
diff --git a/core/src/test/java/com/nuodb/migrator/integration/mysql/StructureTest.java b/core/src/test/java/com/nuodb/migrator/integration/mysql/StructureTest.java
index b9199d40..89ece3dc 100644
--- a/core/src/test/java/com/nuodb/migrator/integration/mysql/StructureTest.java
+++ b/core/src/test/java/com/nuodb/migrator/integration/mysql/StructureTest.java
@@ -1,405 +1,405 @@
/**
* Copyright (c) 2012, NuoDB, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of NuoDB, Inc. 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 NUODB, INC. BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.nuodb.migrator.integration.mysql;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.nuodb.migrator.integration.MigrationTestBase;
import com.nuodb.migrator.integration.types.MySQLTypes;
/**
* Test to make sure all the Tables, Constraints, Views, Triggers etc have been
* migrated.
*
* @author Krishnamoorthy Dhandapani
*/
public class StructureTest extends MigrationTestBase {
/*
* test if all the Tables are migrated with the right columns
*/
@Test(groups = { "integrationtest" }, dependsOnGroups = { "dataloadperformed" })
public void testTables() throws Exception {
String sqlStr1 = "select TABLE_NAME from information_schema.TABLES where TABLE_TYPE='BASE TABLE' AND TABLE_SCHEMA = ?";
String sqlStr2 = "select tablename from system.TABLES where TYPE = 'TABLE' and schema = ?";
PreparedStatement stmt1 = null, stmt2 = null;
ResultSet rs1 = null, rs2 = null;
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
try {
stmt1 = sourceConnection.prepareStatement(sqlStr1);
stmt1.setString(1, sourceConnection.getCatalog());
rs1 = stmt1.executeQuery();
Assert.assertNotNull(rs1);
while (rs1.next()) {
list1.add(rs1.getString(1).toUpperCase());
}
Assert.assertFalse(list1.isEmpty());
stmt2 = nuodbConnection.prepareStatement(sqlStr2);
stmt2.setString(1, nuodbSchemaUsed);
rs2 = stmt2.executeQuery();
Assert.assertNotNull(rs2);
while (rs2.next()) {
list2.add(rs2.getString(1).toUpperCase());
}
Assert.assertFalse(list2.isEmpty());
for (String tname : list1) {
Assert.assertTrue(list2.contains(tname));
verifyTableColumns(tname);
}
} finally {
closeAll(rs1, stmt1, rs2, stmt2);
}
}
/*
* TODO: Need to add check for complex data types with scale and precision
*/
private void verifyTableColumns(String tableName) throws Exception {
String sqlStr1 = "select * from information_schema.COLUMNS where TABLE_SCHEMA = ? and TABLE_NAME = ? order by ORDINAL_POSITION";
String sqlStr2 = "select * from system.FIELDS F inner join system.DATATYPES D on "
+ "F.DATATYPE = D.ID and F.SCHEMA = ? and F.TABLENAME = ? order by F.FIELDPOSITION";
String[] colNames = new String[] { "COLUMN_NAME", "ORDINAL_POSITION",
"COLUMN_DEFAULT", "IS_NULLABLE", "DATA_TYPE",
"CHARACTER_MAXIMUM_LENGTH", "NUMERIC_PRECISION",
"NUMERIC_SCALE", "CHARACTER_SET_NAME", "COLLATION_NAME",
"COLUMN_TYPE" };
PreparedStatement stmt1 = null, stmt2 = null;
ResultSet rs1 = null, rs2 = null;
HashMap<String, HashMap<String, String>> tabColMap = new HashMap<String, HashMap<String, String>>();
try {
stmt1 = sourceConnection.prepareStatement(sqlStr1);
stmt1.setString(1, sourceConnection.getCatalog());
- stmt1.setString(2, tableName);
+ stmt1.setString(2, tableName.toLowerCase());
rs1 = stmt1.executeQuery();
Assert.assertNotNull(rs1);
while (rs1.next()) {
HashMap<String, String> tabColDetailsMap = new HashMap<String, String>();
for (String colName : colNames) {
tabColDetailsMap.put(colName, rs1.getString(colName));
}
Assert.assertFalse(tabColDetailsMap.isEmpty(), tableName
+ " column details empty at source");
tabColMap.put(tabColDetailsMap.get(colNames[0]),
tabColDetailsMap);
}
Assert.assertFalse(tabColMap.isEmpty(), tableName
+ " column details map empty at source");
stmt2 = nuodbConnection.prepareStatement(sqlStr2);
stmt2.setString(1, nuodbSchemaUsed);
stmt2.setString(2, tableName);
rs2 = stmt2.executeQuery();
Assert.assertNotNull(rs2);
while (rs2.next()) {
String colName = rs2.getString("FIELD");
HashMap<String, String> tabColDetailsMap = tabColMap
.get(colName);
Assert.assertNotNull(tabColDetailsMap);
Assert.assertEquals(colName, tabColDetailsMap.get(colNames[0]));
Assert.assertEquals(rs2.getInt("JDBCTYPE"), MySQLTypes
.getMappedJDBCType(tabColDetailsMap.get(colNames[4])));
// System.out.print("mysqlcoltype="
// + tabColDetailsMap.get(colNames[4]) + ",");
// System.out.println("mysqlval="
// + tabColDetailsMap.get(colNames[5]));
Assert.assertEquals(rs2.getString("LENGTH"), MySQLTypes
.getMappedLength(tabColDetailsMap.get(colNames[4]),
tabColDetailsMap.get(colNames[5])));
// TBD
// String val = tabColDetailsMap.get(colNames[7]);
// Assert.assertEquals(rs2.getInt("SCALE"), val == null ? 0
// : Integer.parseInt(val));
// Assert.assertEquals(rs2.getString("PRECISION"),
// tabColDetailsMap.get(colNames[6]));
String val = tabColDetailsMap.get(colNames[2]);
Assert.assertEquals(rs2.getString("DEFAULTVALUE"), MySQLTypes
.getMappedDefault(tabColDetailsMap.get(colNames[4]),
tabColDetailsMap.get(colNames[2])));
}
} finally {
closeAll(rs1, stmt1, rs2, stmt2);
}
}
/*
* test if all the Views are migrated
*/
@Test(groups = { "integrationtest", "disabled" }, dependsOnGroups = { "dataloadperformed" })
public void testViews() throws Exception {
// MYSQL Views are not migrated yet.
}
/*
* test if all the Primary and Unique Key Constraints are migrated
*/
@Test(groups = { "integrationtest" }, dependsOnGroups = { "dataloadperformed" })
public void testPrimaryAndUniqueKeyConstraints() throws Exception {
String sqlStr1 = "select TC.TABLE_NAME, C.COLUMN_NAME, C.COLUMN_KEY from information_schema.TABLE_CONSTRAINTS TC "
+ "inner join information_schema.COLUMNS C on TC.CONSTRAINT_SCHEMA=? "
+ "and C.TABLE_SCHEMA = TC.CONSTRAINT_SCHEMA "
+ "and TC.TABLE_NAME=C.TABLE_NAME AND C.COLUMN_KEY=SUBSTRING(TC.CONSTRAINT_TYPE,1,3) "
+ "AND C.COLUMN_KEY IN ('PRI', 'UNI')";
String sqlStr2 = "SELECT FIELD FROM SYSTEM.INDEXES INNER JOIN SYSTEM.INDEXFIELDS ON "
+ "INDEXES.SCHEMA=INDEXFIELDS.SCHEMA AND "
+ "INDEXES.TABLENAME=INDEXFIELDS.TABLENAME AND "
+ "INDEXES.INDEXNAME=INDEXFIELDS.INDEXNAME WHERE SCHEMA=? AND TABLENAME=? AND INDEXTYPE=?";
PreparedStatement stmt1 = null, stmt2 = null;
ResultSet rs1 = null, rs2 = null;
try {
stmt1 = sourceConnection.prepareStatement(sqlStr1);
stmt1.setString(1, sourceConnection.getCatalog());
rs1 = stmt1.executeQuery();
Assert.assertNotNull(rs1);
while (rs1.next()) {
String tName = rs1.getString("TABLE_NAME");
String cName = rs1.getString("COLUMN_NAME");
String cKey = rs1.getString("COLUMN_KEY");
stmt2 = nuodbConnection.prepareStatement(sqlStr2);
stmt2.setString(1, nuodbSchemaUsed);
stmt2.setString(2, tName);
stmt2.setInt(3, MySQLTypes.getKeyType(cKey));
rs2 = stmt2.executeQuery();
boolean found = false;
while (rs2.next()) {
found = true;
Assert.assertEquals(rs2.getString(1), cName);
}
Assert.assertTrue(found);
rs2.close();
stmt2.close();
}
} finally {
closeAll(rs1, stmt1, rs2, stmt2);
}
}
/*
* test if all the Check Constraints are migrated
*/
@Test(groups = { "integrationtest", "disabled" }, dependsOnGroups = { "dataloadperformed" })
public void testCheckConstraints() throws Exception {
// MYSQL Does not have any implementations for CHECK constraints
}
/*
* test if all the Foreign Key Constraints are migrated
*/
@Test(groups = { "integrationtest" }, dependsOnGroups = { "dataloadperformed" })
public void testForeignKeyConstraints() throws Exception {
String sqlStr1 = "select TC.TABLE_NAME, CU.COLUMN_NAME, CU.REFERENCED_TABLE_NAME, CU.REFERENCED_COLUMN_NAME "
+ "from information_schema.TABLE_CONSTRAINTS TC INNER JOIN information_schema.KEY_COLUMN_USAGE CU "
+ "on TC.CONSTRAINT_SCHEMA=? and CU.TABLE_SCHEMA = TC.CONSTRAINT_SCHEMA and "
+ "TC.TABLE_NAME = CU.TABLE_NAME AND TC.CONSTRAINT_TYPE = 'FOREIGN KEY';";
String sqlStr2 = "SELECT PRIMARYTABLE.SCHEMA AS PKTABLE_SCHEM, PRIMARYTABLE.TABLENAME AS PKTABLE_NAME, "
+ " PRIMARYFIELD.FIELD AS PKCOLUMN_NAME, FOREIGNTABLE.SCHEMA AS FKTABLE_SCHEM, "
+ " FOREIGNTABLE.TABLENAME AS FKTABLE_NAME, FOREIGNFIELD.FIELD AS FKCOLUMN_NAME, "
+ " FOREIGNKEYS.POSITION+1 AS KEY_SEQ, FOREIGNKEYS.UPDATERULE AS UPDATE_RULE, "
+ " FOREIGNKEYS.DELETERULE AS DELETE_RULE, FOREIGNKEYS.DEFERRABILITY AS DEFERRABILITY "
+ "FROM SYSTEM.FOREIGNKEYS "
+ "INNER JOIN SYSTEM.TABLES PRIMARYTABLE ON PRIMARYTABLEID=PRIMARYTABLE.TABLEID "
+ "INNER JOIN SYSTEM.FIELDS PRIMARYFIELD ON PRIMARYTABLE.SCHEMA=PRIMARYFIELD.SCHEMA "
+ "AND PRIMARYTABLE.TABLENAME=PRIMARYFIELD.TABLENAME "
+ "AND FOREIGNKEYS.PRIMARYFIELDID=PRIMARYFIELD.FIELDID "
+ "INNER JOIN SYSTEM.TABLES FOREIGNTABLE ON FOREIGNTABLEID=FOREIGNTABLE.TABLEID "
+ "INNER JOIN SYSTEM.FIELDS FOREIGNFIELD ON FOREIGNTABLE.SCHEMA=FOREIGNFIELD.SCHEMA "
+ "AND FOREIGNTABLE.TABLENAME=FOREIGNFIELD.TABLENAME "
+ "AND FOREIGNKEYS.FOREIGNFIELDID=FOREIGNFIELD.FIELDID "
+ "WHERE SCHEMA=? AND TABLENAME=? ORDER BY PKTABLE_SCHEM, PKTABLE_NAME, KEY_SEQ ASC";
PreparedStatement stmt1 = null, stmt2 = null;
ResultSet rs1 = null, rs2 = null;
try {
stmt1 = sourceConnection.prepareStatement(sqlStr1);
stmt1.setString(1, sourceConnection.getCatalog());
rs1 = stmt1.executeQuery();
Assert.assertNotNull(rs1);
while (rs1.next()) {
String tName = rs1.getString("TABLE_NAME");
String cName = rs1.getString("COLUMN_NAME");
String rtName = rs1.getString("REFERENCED_TABLE_NAME");
String rcName = rs1.getString("REFERENCED_COLUMN_NAME");
stmt2 = nuodbConnection.prepareStatement(sqlStr2);
stmt2.setString(1, nuodbSchemaUsed);
stmt2.setString(2, tName);
rs2 = stmt2.executeQuery();
boolean found = false;
while (rs2.next()) {
found = true;
Assert.assertEquals(rs2.getString("FKTABLE_SCHEM"),
rs2.getString("PKTABLE_SCHEM"));
Assert.assertEquals(rs2.getString("FKTABLE_NAME"), tName);
Assert.assertEquals(rs2.getString("FKCOLUMN_NAME"), cName);
Assert.assertEquals(rs2.getString("PKTABLE_NAME"), rtName);
Assert.assertEquals(rs2.getString("PKCOLUMN_NAME"), rcName);
}
Assert.assertTrue(found);
rs2.close();
stmt2.close();
}
} finally {
closeAll(rs1, stmt1, rs2, stmt2);
}
}
/*
* test if all the auto increment settings are migrated
*/
@Test(groups = { "integrationtest" }, dependsOnGroups = { "dataloadperformed" })
public void testAutoIncrement() throws Exception {
String sqlStr1 = "select T.TABLE_NAME, T.AUTO_INCREMENT, C.COLUMN_NAME "
+ "from information_schema.TABLES T INNER JOIN information_schema.COLUMNS C "
+ "on T.TABLE_SCHEMA=? and C.TABLE_SCHEMA = T.TABLE_SCHEMA and "
+ "T.TABLE_NAME = C.TABLE_NAME AND C.EXTRA = 'auto_increment' AND "
+ "T.AUTO_INCREMENT IS NOT NULL";
String sqlStr2 = "SELECT S.SEQUENCENAME FROM SYSTEM.SEQUENCES S "
+ "INNER JOIN SYSTEM.FIELDS F ON S.SCHEMA=F.SCHEMA "
+ "WHERE F.SCHEMA=? AND F.TABLENAME=? AND F.FIELD=?";
PreparedStatement stmt1 = null, stmt2 = null;
ResultSet rs1 = null, rs2 = null;
try {
stmt1 = sourceConnection.prepareStatement(sqlStr1);
stmt1.setString(1, sourceConnection.getCatalog());
rs1 = stmt1.executeQuery();
Assert.assertNotNull(rs1);
while (rs1.next()) {
String tName = rs1.getString("TABLE_NAME");
String cName = rs1.getString("COLUMN_NAME");
long ai = rs1.getLong("AUTO_INCREMENT");
stmt2 = nuodbConnection.prepareStatement(sqlStr2);
stmt2.setString(1, nuodbSchemaUsed);
stmt2.setString(2, tName);
stmt2.setString(3, cName);
rs2 = stmt2.executeQuery();
boolean found = false;
while (rs2.next()) {
found = true;
String seqName = rs2.getString("SEQUENCENAME");
Assert.assertNotNull(seqName);
if (seqName.equals(nuodbSchemaUsed + "$"
+ "IDENTITY_SEQUENCE")) {
continue;
}
Assert.assertEquals(seqName.substring(0, 4), "SEQ_");
// TODO: Need to check start value - Don't know how yet
}
Assert.assertTrue(found);
rs2.close();
stmt2.close();
}
} finally {
closeAll(rs1, stmt1, rs2, stmt2);
}
}
/*
* test if all the Indexes are migrated
*/
@Test(groups = { "integrationtest" }, dependsOnGroups = { "dataloadperformed" })
public void testIndexes() throws Exception {
String sqlStr1 = "select C.TABLE_NAME, C.COLUMN_NAME "
+ "from information_schema.COLUMNS C "
+ "where C.TABLE_SCHEMA=? AND C.COLUMN_KEY = 'MUL'";
String sqlStr2 = "SELECT I.INDEXNAME FROM SYSTEM.INDEXES I "
+ "INNER JOIN SYSTEM.INDEXFIELDS F ON I.SCHEMA=F.SCHEMA AND I.TABLENAME=F.TABLENAME AND I.INDEXNAME=F.INDEXNAME "
+ "WHERE I.INDEXTYPE=2 AND F.SCHEMA=? AND F.TABLENAME=? AND F.FIELD=?";
PreparedStatement stmt1 = null, stmt2 = null;
ResultSet rs1 = null, rs2 = null;
try {
stmt1 = sourceConnection.prepareStatement(sqlStr1);
stmt1.setString(1, sourceConnection.getCatalog());
rs1 = stmt1.executeQuery();
Assert.assertNotNull(rs1);
while (rs1.next()) {
String tName = rs1.getString("TABLE_NAME");
String cName = rs1.getString("COLUMN_NAME");
stmt2 = nuodbConnection.prepareStatement(sqlStr2);
stmt2.setString(1, nuodbSchemaUsed);
stmt2.setString(2, tName);
stmt2.setString(3, cName);
rs2 = stmt2.executeQuery();
boolean found = false;
while (rs2.next()) {
found = true;
String idxName = rs2.getString("INDEXNAME");
Assert.assertNotNull(idxName);
Assert.assertEquals(idxName.substring(0, 4), "IDX_");
}
Assert.assertTrue(found);
rs2.close();
stmt2.close();
}
} finally {
closeAll(rs1, stmt1, rs2, stmt2);
}
}
/*
* test if all the Triggers are migrated
*/
@Test(groups = { "integrationtest", "disabled" }, dependsOnGroups = { "dataloadperformed" })
public void testTriggers() throws Exception {
// MYSQL Triggers are not migrated yet.
}
}
| true | true | private void verifyTableColumns(String tableName) throws Exception {
String sqlStr1 = "select * from information_schema.COLUMNS where TABLE_SCHEMA = ? and TABLE_NAME = ? order by ORDINAL_POSITION";
String sqlStr2 = "select * from system.FIELDS F inner join system.DATATYPES D on "
+ "F.DATATYPE = D.ID and F.SCHEMA = ? and F.TABLENAME = ? order by F.FIELDPOSITION";
String[] colNames = new String[] { "COLUMN_NAME", "ORDINAL_POSITION",
"COLUMN_DEFAULT", "IS_NULLABLE", "DATA_TYPE",
"CHARACTER_MAXIMUM_LENGTH", "NUMERIC_PRECISION",
"NUMERIC_SCALE", "CHARACTER_SET_NAME", "COLLATION_NAME",
"COLUMN_TYPE" };
PreparedStatement stmt1 = null, stmt2 = null;
ResultSet rs1 = null, rs2 = null;
HashMap<String, HashMap<String, String>> tabColMap = new HashMap<String, HashMap<String, String>>();
try {
stmt1 = sourceConnection.prepareStatement(sqlStr1);
stmt1.setString(1, sourceConnection.getCatalog());
stmt1.setString(2, tableName);
rs1 = stmt1.executeQuery();
Assert.assertNotNull(rs1);
while (rs1.next()) {
HashMap<String, String> tabColDetailsMap = new HashMap<String, String>();
for (String colName : colNames) {
tabColDetailsMap.put(colName, rs1.getString(colName));
}
Assert.assertFalse(tabColDetailsMap.isEmpty(), tableName
+ " column details empty at source");
tabColMap.put(tabColDetailsMap.get(colNames[0]),
tabColDetailsMap);
}
Assert.assertFalse(tabColMap.isEmpty(), tableName
+ " column details map empty at source");
stmt2 = nuodbConnection.prepareStatement(sqlStr2);
stmt2.setString(1, nuodbSchemaUsed);
stmt2.setString(2, tableName);
rs2 = stmt2.executeQuery();
Assert.assertNotNull(rs2);
while (rs2.next()) {
String colName = rs2.getString("FIELD");
HashMap<String, String> tabColDetailsMap = tabColMap
.get(colName);
Assert.assertNotNull(tabColDetailsMap);
Assert.assertEquals(colName, tabColDetailsMap.get(colNames[0]));
Assert.assertEquals(rs2.getInt("JDBCTYPE"), MySQLTypes
.getMappedJDBCType(tabColDetailsMap.get(colNames[4])));
// System.out.print("mysqlcoltype="
// + tabColDetailsMap.get(colNames[4]) + ",");
// System.out.println("mysqlval="
// + tabColDetailsMap.get(colNames[5]));
Assert.assertEquals(rs2.getString("LENGTH"), MySQLTypes
.getMappedLength(tabColDetailsMap.get(colNames[4]),
tabColDetailsMap.get(colNames[5])));
// TBD
// String val = tabColDetailsMap.get(colNames[7]);
// Assert.assertEquals(rs2.getInt("SCALE"), val == null ? 0
// : Integer.parseInt(val));
// Assert.assertEquals(rs2.getString("PRECISION"),
// tabColDetailsMap.get(colNames[6]));
String val = tabColDetailsMap.get(colNames[2]);
Assert.assertEquals(rs2.getString("DEFAULTVALUE"), MySQLTypes
.getMappedDefault(tabColDetailsMap.get(colNames[4]),
tabColDetailsMap.get(colNames[2])));
}
} finally {
closeAll(rs1, stmt1, rs2, stmt2);
}
}
| private void verifyTableColumns(String tableName) throws Exception {
String sqlStr1 = "select * from information_schema.COLUMNS where TABLE_SCHEMA = ? and TABLE_NAME = ? order by ORDINAL_POSITION";
String sqlStr2 = "select * from system.FIELDS F inner join system.DATATYPES D on "
+ "F.DATATYPE = D.ID and F.SCHEMA = ? and F.TABLENAME = ? order by F.FIELDPOSITION";
String[] colNames = new String[] { "COLUMN_NAME", "ORDINAL_POSITION",
"COLUMN_DEFAULT", "IS_NULLABLE", "DATA_TYPE",
"CHARACTER_MAXIMUM_LENGTH", "NUMERIC_PRECISION",
"NUMERIC_SCALE", "CHARACTER_SET_NAME", "COLLATION_NAME",
"COLUMN_TYPE" };
PreparedStatement stmt1 = null, stmt2 = null;
ResultSet rs1 = null, rs2 = null;
HashMap<String, HashMap<String, String>> tabColMap = new HashMap<String, HashMap<String, String>>();
try {
stmt1 = sourceConnection.prepareStatement(sqlStr1);
stmt1.setString(1, sourceConnection.getCatalog());
stmt1.setString(2, tableName.toLowerCase());
rs1 = stmt1.executeQuery();
Assert.assertNotNull(rs1);
while (rs1.next()) {
HashMap<String, String> tabColDetailsMap = new HashMap<String, String>();
for (String colName : colNames) {
tabColDetailsMap.put(colName, rs1.getString(colName));
}
Assert.assertFalse(tabColDetailsMap.isEmpty(), tableName
+ " column details empty at source");
tabColMap.put(tabColDetailsMap.get(colNames[0]),
tabColDetailsMap);
}
Assert.assertFalse(tabColMap.isEmpty(), tableName
+ " column details map empty at source");
stmt2 = nuodbConnection.prepareStatement(sqlStr2);
stmt2.setString(1, nuodbSchemaUsed);
stmt2.setString(2, tableName);
rs2 = stmt2.executeQuery();
Assert.assertNotNull(rs2);
while (rs2.next()) {
String colName = rs2.getString("FIELD");
HashMap<String, String> tabColDetailsMap = tabColMap
.get(colName);
Assert.assertNotNull(tabColDetailsMap);
Assert.assertEquals(colName, tabColDetailsMap.get(colNames[0]));
Assert.assertEquals(rs2.getInt("JDBCTYPE"), MySQLTypes
.getMappedJDBCType(tabColDetailsMap.get(colNames[4])));
// System.out.print("mysqlcoltype="
// + tabColDetailsMap.get(colNames[4]) + ",");
// System.out.println("mysqlval="
// + tabColDetailsMap.get(colNames[5]));
Assert.assertEquals(rs2.getString("LENGTH"), MySQLTypes
.getMappedLength(tabColDetailsMap.get(colNames[4]),
tabColDetailsMap.get(colNames[5])));
// TBD
// String val = tabColDetailsMap.get(colNames[7]);
// Assert.assertEquals(rs2.getInt("SCALE"), val == null ? 0
// : Integer.parseInt(val));
// Assert.assertEquals(rs2.getString("PRECISION"),
// tabColDetailsMap.get(colNames[6]));
String val = tabColDetailsMap.get(colNames[2]);
Assert.assertEquals(rs2.getString("DEFAULTVALUE"), MySQLTypes
.getMappedDefault(tabColDetailsMap.get(colNames[4]),
tabColDetailsMap.get(colNames[2])));
}
} finally {
closeAll(rs1, stmt1, rs2, stmt2);
}
}
|
diff --git a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestVariableResolver.java b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestVariableResolver.java
index c4d5845bae..2766f82a78 100644
--- a/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestVariableResolver.java
+++ b/solr/contrib/dataimporthandler/src/test/org/apache/solr/handler/dataimport/TestVariableResolver.java
@@ -1,166 +1,165 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.handler.dataimport;
import org.junit.Ignore;
import org.junit.Test;
import org.apache.solr.util.DateMathParser;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* <p>
* Test for VariableResolver
* </p>
*
*
* @since solr 1.3
*/
public class TestVariableResolver extends AbstractDataImportHandlerTestCase {
@Test
public void testSimpleNamespace() {
VariableResolver vri = new VariableResolver();
Map<String,Object> ns = new HashMap<String,Object>();
ns.put("world", "WORLD");
vri.addNamespace("hello", ns);
assertEquals("WORLD", vri.resolve("hello.world"));
}
@Test
public void testDefaults() {
// System.out.println(System.setProperty(TestVariableResolver.class.getName(),"hello"));
System.setProperty(TestVariableResolver.class.getName(), "hello");
// System.out.println("s.gP()"+
// System.getProperty(TestVariableResolver.class.getName()));
Properties p = new Properties();
p.put("hello", "world");
VariableResolver vri = new VariableResolver(p);
Object val = vri.resolve(TestVariableResolver.class.getName());
// System.out.println("val = " + val);
assertEquals("hello", val);
assertEquals("world", vri.resolve("hello"));
}
@Test
public void testNestedNamespace() {
VariableResolver vri = new VariableResolver();
Map<String,Object> ns = new HashMap<String,Object>();
ns.put("world", "WORLD");
vri.addNamespace("hello", ns);
ns = new HashMap<String,Object>();
ns.put("world1", "WORLD1");
vri.addNamespace("hello.my", ns);
assertEquals("WORLD1", vri.resolve("hello.my.world1"));
}
@Test
public void test3LevelNestedNamespace() {
VariableResolver vri = new VariableResolver();
Map<String,Object> ns = new HashMap<String,Object>();
ns.put("world", "WORLD");
vri.addNamespace("hello", ns);
ns = new HashMap<String,Object>();
ns.put("world1", "WORLD1");
vri.addNamespace("hello.my.new", ns);
assertEquals("WORLD1", vri.resolve("hello.my.new.world1"));
}
@Test
public void dateNamespaceWithValue() {
VariableResolver vri = new VariableResolver();
vri.setEvaluators(new DataImporter().getEvaluators(Collections
.<Map<String,String>> emptyList()));
Map<String,Object> ns = new HashMap<String,Object>();
Date d = new Date();
ns.put("dt", d);
vri.addNamespace("A", ns);
assertEquals(
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT).format(d),
vri.replaceTokens("${dataimporter.functions.formatDate(A.dt,'yyyy-MM-dd HH:mm:ss')}"));
}
@Test
public void dateNamespaceWithExpr() throws Exception {
VariableResolver vri = new VariableResolver();
vri.setEvaluators(new DataImporter().getEvaluators(Collections
.<Map<String,String>> emptyList()));
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
DateMathParser dmp = new DateMathParser(TimeZone.getDefault(), Locale.ROOT);
String s = vri
.replaceTokens("${dataimporter.functions.formatDate('NOW/DAY','yyyy-MM-dd HH:mm')}");
assertEquals(
new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ROOT).format(dmp.parseMath("/DAY")),
s);
}
@Test
public void testDefaultNamespace() {
VariableResolver vri = new VariableResolver();
Map<String,Object> ns = new HashMap<String,Object>();
ns.put("world", "WORLD");
vri.addNamespace(null, ns);
assertEquals("WORLD", vri.resolve("world"));
}
@Test
public void testDefaultNamespace1() {
VariableResolver vri = new VariableResolver();
Map<String,Object> ns = new HashMap<String,Object>();
ns.put("world", "WORLD");
vri.addNamespace(null, ns);
assertEquals("WORLD", vri.resolve("world"));
}
@Test
public void testFunctionNamespace1() throws Exception {
VariableResolver resolver = new VariableResolver();
final List<Map<String,String>> l = new ArrayList<Map<String,String>>();
Map<String,String> m = new HashMap<String,String>();
m.put("name", "test");
m.put("class", E.class.getName());
l.add(m);
resolver.setEvaluators(new DataImporter().getEvaluators(l));
ContextImpl context = new ContextImpl(null, resolver, null,
Context.FULL_DUMP, Collections.EMPTY_MAP, null, null);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
- DateMathParser dmp = new DateMathParser(TimeZone.getDefault(),
- Locale.getDefault());
+ DateMathParser dmp = new DateMathParser(TimeZone.getDefault(), Locale.ROOT);
String s = resolver
.replaceTokens("${dataimporter.functions.formatDate('NOW/DAY','yyyy-MM-dd HH:mm')}");
assertEquals(
new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ROOT).format(dmp.parseMath("/DAY")),
s);
assertEquals("Hello World",
resolver.replaceTokens("${dataimporter.functions.test('TEST')}"));
}
public static class E extends Evaluator {
@Override
public String evaluate(String expression, Context context) {
return "Hello World";
}
}
}
| true | true | public void testFunctionNamespace1() throws Exception {
VariableResolver resolver = new VariableResolver();
final List<Map<String,String>> l = new ArrayList<Map<String,String>>();
Map<String,String> m = new HashMap<String,String>();
m.put("name", "test");
m.put("class", E.class.getName());
l.add(m);
resolver.setEvaluators(new DataImporter().getEvaluators(l));
ContextImpl context = new ContextImpl(null, resolver, null,
Context.FULL_DUMP, Collections.EMPTY_MAP, null, null);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
DateMathParser dmp = new DateMathParser(TimeZone.getDefault(),
Locale.getDefault());
String s = resolver
.replaceTokens("${dataimporter.functions.formatDate('NOW/DAY','yyyy-MM-dd HH:mm')}");
assertEquals(
new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ROOT).format(dmp.parseMath("/DAY")),
s);
assertEquals("Hello World",
resolver.replaceTokens("${dataimporter.functions.test('TEST')}"));
}
| public void testFunctionNamespace1() throws Exception {
VariableResolver resolver = new VariableResolver();
final List<Map<String,String>> l = new ArrayList<Map<String,String>>();
Map<String,String> m = new HashMap<String,String>();
m.put("name", "test");
m.put("class", E.class.getName());
l.add(m);
resolver.setEvaluators(new DataImporter().getEvaluators(l));
ContextImpl context = new ContextImpl(null, resolver, null,
Context.FULL_DUMP, Collections.EMPTY_MAP, null, null);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
DateMathParser dmp = new DateMathParser(TimeZone.getDefault(), Locale.ROOT);
String s = resolver
.replaceTokens("${dataimporter.functions.formatDate('NOW/DAY','yyyy-MM-dd HH:mm')}");
assertEquals(
new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ROOT).format(dmp.parseMath("/DAY")),
s);
assertEquals("Hello World",
resolver.replaceTokens("${dataimporter.functions.test('TEST')}"));
}
|
diff --git a/src/com/google/bitcoin/examples/PrintPeers.java b/src/com/google/bitcoin/examples/PrintPeers.java
index cf3a0d7..bb411ba 100644
--- a/src/com/google/bitcoin/examples/PrintPeers.java
+++ b/src/com/google/bitcoin/examples/PrintPeers.java
@@ -1,114 +1,114 @@
/**
* Copyright 2011 John Sample.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.bitcoin.examples;
import com.google.bitcoin.core.NetworkConnection;
import com.google.bitcoin.core.NetworkParameters;
import com.google.bitcoin.core.TCPNetworkConnection;
import com.google.bitcoin.discovery.DnsDiscovery;
import com.google.bitcoin.discovery.IrcDiscovery;
import com.google.bitcoin.discovery.PeerDiscoveryException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.concurrent.*;
/**
* Prints a list of IP addresses connected to the rendezvous point on the LFnet IRC channel.
*/
public class PrintPeers {
private static InetSocketAddress[] dnsPeers, ircPeers;
private static void printElapsed(long start) {
long now = System.currentTimeMillis();
System.out.println(String.format("Took %.2f seconds", (now - start) / 1000.0));
}
private static void printPeers(InetSocketAddress[] addresses) {
for (InetSocketAddress address : addresses) {
String hostAddress = address.getAddress().getHostAddress();
System.out.println(String.format("%s:%d", hostAddress.toString(), address.getPort()));
}
}
private static void printIRC() throws PeerDiscoveryException {
long start = System.currentTimeMillis();
IrcDiscovery d = new IrcDiscovery("#bitcoin") {
@Override
protected void onIRCReceive(String message) {
System.out.println("<- " + message);
}
@Override
protected void onIRCSend(String message) {
System.out.println("-> " + message);
}
};
ircPeers = d.getPeers();
printPeers(ircPeers);
printElapsed(start);
}
private static void printDNS() throws PeerDiscoveryException {
long start = System.currentTimeMillis();
DnsDiscovery dns = new DnsDiscovery(NetworkParameters.prodNet());
dnsPeers = dns.getPeers();
printPeers(dnsPeers);
printElapsed(start);
}
public static void main(String[] args) throws Exception {
System.out.println("=== IRC ===");
printIRC();
System.out.println("=== DNS ===");
printDNS();
System.out.println("=== Version/chain heights ===");
ExecutorService pool = Executors.newFixedThreadPool(100);
ArrayList<InetAddress> addrs = new ArrayList<InetAddress>();
for (InetSocketAddress peer : dnsPeers) addrs.add(peer.getAddress());
for (InetSocketAddress peer : ircPeers) addrs.add(peer.getAddress());
System.out.println("Scanning " + addrs.size() + " peers:");
final Object lock = new Object();
final long[] bestHeight = new long[1];
for (final InetAddress addr : addrs) {
pool.submit(new Runnable() {
public void run() {
try {
NetworkConnection conn = new TCPNetworkConnection(addr,
NetworkParameters.prodNet(), 0, 1000);
synchronized (lock) {
long nodeHeight = conn.getVersionMessage().bestHeight;
long diff = bestHeight[0] - nodeHeight;
if (diff > 0) {
System.out.println("Node is behind by " + diff + " blocks: " + addr.toString());
} else {
bestHeight[0] = nodeHeight;
}
}
conn.shutdown();
} catch (Exception e) {
}
}
});
}
- pool.awaitTermination(1, TimeUnit.DAYS);
+ pool.awaitTermination(3600 * 24, TimeUnit.SECONDS); // 1 Day
}
}
| true | true | public static void main(String[] args) throws Exception {
System.out.println("=== IRC ===");
printIRC();
System.out.println("=== DNS ===");
printDNS();
System.out.println("=== Version/chain heights ===");
ExecutorService pool = Executors.newFixedThreadPool(100);
ArrayList<InetAddress> addrs = new ArrayList<InetAddress>();
for (InetSocketAddress peer : dnsPeers) addrs.add(peer.getAddress());
for (InetSocketAddress peer : ircPeers) addrs.add(peer.getAddress());
System.out.println("Scanning " + addrs.size() + " peers:");
final Object lock = new Object();
final long[] bestHeight = new long[1];
for (final InetAddress addr : addrs) {
pool.submit(new Runnable() {
public void run() {
try {
NetworkConnection conn = new TCPNetworkConnection(addr,
NetworkParameters.prodNet(), 0, 1000);
synchronized (lock) {
long nodeHeight = conn.getVersionMessage().bestHeight;
long diff = bestHeight[0] - nodeHeight;
if (diff > 0) {
System.out.println("Node is behind by " + diff + " blocks: " + addr.toString());
} else {
bestHeight[0] = nodeHeight;
}
}
conn.shutdown();
} catch (Exception e) {
}
}
});
}
pool.awaitTermination(1, TimeUnit.DAYS);
}
| public static void main(String[] args) throws Exception {
System.out.println("=== IRC ===");
printIRC();
System.out.println("=== DNS ===");
printDNS();
System.out.println("=== Version/chain heights ===");
ExecutorService pool = Executors.newFixedThreadPool(100);
ArrayList<InetAddress> addrs = new ArrayList<InetAddress>();
for (InetSocketAddress peer : dnsPeers) addrs.add(peer.getAddress());
for (InetSocketAddress peer : ircPeers) addrs.add(peer.getAddress());
System.out.println("Scanning " + addrs.size() + " peers:");
final Object lock = new Object();
final long[] bestHeight = new long[1];
for (final InetAddress addr : addrs) {
pool.submit(new Runnable() {
public void run() {
try {
NetworkConnection conn = new TCPNetworkConnection(addr,
NetworkParameters.prodNet(), 0, 1000);
synchronized (lock) {
long nodeHeight = conn.getVersionMessage().bestHeight;
long diff = bestHeight[0] - nodeHeight;
if (diff > 0) {
System.out.println("Node is behind by " + diff + " blocks: " + addr.toString());
} else {
bestHeight[0] = nodeHeight;
}
}
conn.shutdown();
} catch (Exception e) {
}
}
});
}
pool.awaitTermination(3600 * 24, TimeUnit.SECONDS); // 1 Day
}
|
diff --git a/src/java/org/apache/nutch/indexer/solr/SolrIndexer.java b/src/java/org/apache/nutch/indexer/solr/SolrIndexer.java
index ce18e111..6d32d8ea 100644
--- a/src/java/org/apache/nutch/indexer/solr/SolrIndexer.java
+++ b/src/java/org/apache/nutch/indexer/solr/SolrIndexer.java
@@ -1,107 +1,107 @@
/*
* 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.nutch.indexer.solr;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.indexer.IndexerMapReduce;
import org.apache.nutch.indexer.NutchIndexWriterFactory;
import org.apache.nutch.util.NutchConfiguration;
import org.apache.nutch.util.NutchJob;
public class SolrIndexer extends Configured implements Tool {
public static Log LOG = LogFactory.getLog(SolrIndexer.class);
public SolrIndexer() {
super(null);
}
public SolrIndexer(Configuration conf) {
super(conf);
}
- private void indexSolr(String solrUrl, Path crawlDb, Path linkDb,
+ public void indexSolr(String solrUrl, Path crawlDb, Path linkDb,
List<Path> segments) throws IOException {
LOG.info("SolrIndexer: starting");
final JobConf job = new NutchJob(getConf());
job.setJobName("index-solr " + solrUrl);
IndexerMapReduce.initMRJob(crawlDb, linkDb, segments, job);
job.set(SolrConstants.SERVER_URL, solrUrl);
NutchIndexWriterFactory.addClassToConf(job, SolrWriter.class);
job.setReduceSpeculativeExecution(false);
final Path tmp = new Path("tmp_" + System.currentTimeMillis() + "-" +
new Random().nextInt());
FileOutputFormat.setOutputPath(job, tmp);
try {
JobClient.runJob(job);
} finally {
FileSystem.get(job).delete(tmp, true);
}
LOG.info("SolrIndexer: done");
}
public int run(String[] args) throws Exception {
if (args.length < 4) {
System.err.println("Usage: SolrIndexer <solr url> <crawldb> <linkdb> <segment> ...");
return -1;
}
final Path crawlDb = new Path(args[1]);
final Path linkDb = new Path(args[2]);
final List<Path> segments = new ArrayList<Path>();
for (int i = 3; i < args.length; i++) {
segments.add(new Path(args[i]));
}
try {
indexSolr(args[0], crawlDb, linkDb, segments);
return 0;
} catch (final Exception e) {
LOG.fatal("SolrIndexer: " + StringUtils.stringifyException(e));
return -1;
}
}
public static void main(String[] args) throws Exception {
final int res = ToolRunner.run(NutchConfiguration.create(), new SolrIndexer(), args);
System.exit(res);
}
}
| true | true | private void indexSolr(String solrUrl, Path crawlDb, Path linkDb,
List<Path> segments) throws IOException {
LOG.info("SolrIndexer: starting");
final JobConf job = new NutchJob(getConf());
job.setJobName("index-solr " + solrUrl);
IndexerMapReduce.initMRJob(crawlDb, linkDb, segments, job);
job.set(SolrConstants.SERVER_URL, solrUrl);
NutchIndexWriterFactory.addClassToConf(job, SolrWriter.class);
job.setReduceSpeculativeExecution(false);
final Path tmp = new Path("tmp_" + System.currentTimeMillis() + "-" +
new Random().nextInt());
FileOutputFormat.setOutputPath(job, tmp);
try {
JobClient.runJob(job);
} finally {
FileSystem.get(job).delete(tmp, true);
}
LOG.info("SolrIndexer: done");
}
| public void indexSolr(String solrUrl, Path crawlDb, Path linkDb,
List<Path> segments) throws IOException {
LOG.info("SolrIndexer: starting");
final JobConf job = new NutchJob(getConf());
job.setJobName("index-solr " + solrUrl);
IndexerMapReduce.initMRJob(crawlDb, linkDb, segments, job);
job.set(SolrConstants.SERVER_URL, solrUrl);
NutchIndexWriterFactory.addClassToConf(job, SolrWriter.class);
job.setReduceSpeculativeExecution(false);
final Path tmp = new Path("tmp_" + System.currentTimeMillis() + "-" +
new Random().nextInt());
FileOutputFormat.setOutputPath(job, tmp);
try {
JobClient.runJob(job);
} finally {
FileSystem.get(job).delete(tmp, true);
}
LOG.info("SolrIndexer: done");
}
|
diff --git a/plugins/org.eclipse.jst.common.frameworks/src/org/eclipse/jst/common/componentcore/util/ProjectValidationHelper.java b/plugins/org.eclipse.jst.common.frameworks/src/org/eclipse/jst/common/componentcore/util/ProjectValidationHelper.java
index 752002a1c..644bdd7b2 100644
--- a/plugins/org.eclipse.jst.common.frameworks/src/org/eclipse/jst/common/componentcore/util/ProjectValidationHelper.java
+++ b/plugins/org.eclipse.jst.common.frameworks/src/org/eclipse/jst/common/componentcore/util/ProjectValidationHelper.java
@@ -1,52 +1,53 @@
/*******************************************************************************
* Copyright (c) 2003, 2004 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.jst.common.componentcore.util;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IProject;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jem.workbench.utility.JemProjectUtilities;
import org.eclipse.wst.common.componentcore.ComponentCore;
import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
import org.eclipse.wst.validation.internal.IProjectValidationHelper;
public class ProjectValidationHelper implements IProjectValidationHelper {
private static IContainer[] EMPTY_RESULT = new IContainer[] {};
public IContainer[] getOutputContainers(IProject project) {
if (project == null || JemProjectUtilities.getJavaProject(project)==null)
return EMPTY_RESULT;
IVirtualComponent comp = ComponentCore.createComponent(project);
if (comp == null || !comp.exists())
return EMPTY_RESULT;
return ComponentUtilities.getOutputContainers(comp);
}
public IContainer[] getSourceContainers(IProject project) {
if (project == null || JemProjectUtilities.getJavaProject(project)==null)
return EMPTY_RESULT;
IVirtualComponent comp = ComponentCore.createComponent(project);
if (comp == null || !comp.exists())
return EMPTY_RESULT;
IPackageFragmentRoot[] roots = ComponentUtilities.getSourceContainers(comp);
List result = new ArrayList();
for (int i=0; i<roots.length; i++) {
- result.add(roots[i].getResource());
+ if (roots[i].getResource() != null && roots[i].getResource() instanceof IContainer)
+ result.add(roots[i].getResource());
}
return (IContainer[]) result.toArray(new IContainer[result.size()]);
}
}
| true | true | public IContainer[] getSourceContainers(IProject project) {
if (project == null || JemProjectUtilities.getJavaProject(project)==null)
return EMPTY_RESULT;
IVirtualComponent comp = ComponentCore.createComponent(project);
if (comp == null || !comp.exists())
return EMPTY_RESULT;
IPackageFragmentRoot[] roots = ComponentUtilities.getSourceContainers(comp);
List result = new ArrayList();
for (int i=0; i<roots.length; i++) {
result.add(roots[i].getResource());
}
return (IContainer[]) result.toArray(new IContainer[result.size()]);
}
| public IContainer[] getSourceContainers(IProject project) {
if (project == null || JemProjectUtilities.getJavaProject(project)==null)
return EMPTY_RESULT;
IVirtualComponent comp = ComponentCore.createComponent(project);
if (comp == null || !comp.exists())
return EMPTY_RESULT;
IPackageFragmentRoot[] roots = ComponentUtilities.getSourceContainers(comp);
List result = new ArrayList();
for (int i=0; i<roots.length; i++) {
if (roots[i].getResource() != null && roots[i].getResource() instanceof IContainer)
result.add(roots[i].getResource());
}
return (IContainer[]) result.toArray(new IContainer[result.size()]);
}
|
diff --git a/petascope/src/main/java/petascope/wcs2/extensions/AbstractFormatExtension.java b/petascope/src/main/java/petascope/wcs2/extensions/AbstractFormatExtension.java
index cb07650e..c597a37f 100644
--- a/petascope/src/main/java/petascope/wcs2/extensions/AbstractFormatExtension.java
+++ b/petascope/src/main/java/petascope/wcs2/extensions/AbstractFormatExtension.java
@@ -1,146 +1,145 @@
/*
* This file is part of rasdaman community.
*
* Rasdaman community 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.
*
* Rasdaman community 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 rasdaman community. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2003 - 2010 Peter Baumann / rasdaman GmbH.
*
* For more information please see <http://www.rasdaman.org>
* or contact Peter Baumann via <[email protected]>.
*/
package petascope.wcs2.extensions;
import java.util.Iterator;
import petascope.core.DbMetadataSource;
import petascope.core.Metadata;
import petascope.exceptions.ExceptionCode;
import petascope.exceptions.RasdamanException;
import petascope.exceptions.WCPSException;
import petascope.exceptions.WCSException;
import petascope.util.Pair;
import petascope.util.ras.RasUtil;
import petascope.util.WcsUtil;
import petascope.util.ras.RasQueryResult;
import petascope.wcps.server.core.DomainElement;
import petascope.wcps.server.core.WCPS;
import petascope.wcs2.parsers.GetCoverageMetadata;
import petascope.wcs2.parsers.GetCoverageRequest;
import petascope.wcs2.parsers.GetCoverageRequest.DimensionSlice;
import petascope.wcs2.parsers.GetCoverageRequest.DimensionSubset;
import petascope.wcs2.parsers.GetCoverageRequest.DimensionTrim;
/**
* An abstract implementation of {@link FormatExtension}, which provides some
* convenience methods to concrete implementations.
*
* @author <a href="mailto:[email protected]">Dimitar Misev</a>
*/
public abstract class AbstractFormatExtension implements FormatExtension {
protected static WCPS wcps;
/**
* Update m with the correct bounds and axes (mostly useful when there's slicing/trimming in the request)
*/
protected void setBounds(GetCoverageRequest request, GetCoverageMetadata m, DbMetadataSource meta) throws WCSException {
Pair<Object, String> pair = executeRasqlQuery(request, m, meta, "sdom", null);
if (pair.fst != null) {
RasQueryResult res = new RasQueryResult(pair.fst);
if (!res.getScalars().isEmpty()) {
// TODO: can be done better with Minterval instead of sdom2bounds
Pair<String, String> bounds = WcsUtil.sdom2bounds(res.getScalars().get(0));
m.setAxisLabels(pair.snd);
m.setLow(bounds.fst);
m.setHigh(bounds.snd);
}
}
}
/**
* Execute rasql query, given GetCoverage request, request metadata, and format of result.
*
* @return (result of executing the query, axes)
* @throws WCSException
*/
protected Pair<Object, String> executeRasqlQuery(GetCoverageRequest request,
GetCoverageMetadata m, DbMetadataSource meta, String format, String params) throws WCSException {
if (wcps == null) {
try {
wcps = new WCPS(meta);
} catch (Exception ex) {
throw new WCSException(ExceptionCode.InternalComponentError, "Error initializing WCPS engine", ex);
}
}
Pair<String, String> pair = constructWcpsQuery(request, m.getMetadata(), format, params);
String rquery = null;
try {
rquery = RasUtil.abstractWCPSToRasql(pair.fst, wcps);
} catch (WCPSException ex) {
throw new WCSException(ExceptionCode.WcpsError, "Error converting WCPS query to rasql query", ex);
}
Object res = null;
try {
if ("sdom".equals(format) && !rquery.contains(":")) {
res = null;
} else {
res = RasUtil.executeRasqlQuery(rquery);
}
} catch (RasdamanException ex) {
throw new WCSException(ExceptionCode.RasdamanRequestFailed, "Error executing rasql query", ex);
}
return Pair.of(res, pair.snd);
}
/**
* Given a GetCoverage request, construct an abstract WCPS query.
* @param req GetCoverage request
* @param cov coverage metadata
* @return (WCPS query in abstract syntax, axes)
*/
protected Pair<String, String> constructWcpsQuery(GetCoverageRequest req, Metadata cov, String format, String params) {
String axes = "";
Iterator<DomainElement> dit = cov.getDomainIterator();
while (dit.hasNext()) {
axes += dit.next().getName() + " ";
}
String proc = "c";
// process subsetting operations
for (DimensionSubset subset : req.getSubsets()) {
String dim = subset.getDimension();
DomainElement de = cov.getDomainByName(dim);
String crs = "CRS:1";
- for (String c : de.getCrsSet()) {
- crs = c;
- break;
+ if (subset.getCrs() != null) {
+ crs = subset.getCrs();
}
if (subset instanceof DimensionTrim) {
DimensionTrim trim = (DimensionTrim) subset;
proc = "trim(" + proc + ",{" + dim + ":\"" + crs + "\" (" + trim.
getTrimLow() + ":" + trim.getTrimHigh() + ")})";
} else if (subset instanceof DimensionSlice) {
DimensionSlice slice = (DimensionSlice) subset;
proc = "slice(" + proc + ",{" + dim + "(" + slice.getSlicePoint() + ")})";
axes = axes.replaceFirst(dim + " ?", ""); // remove axis
}
}
if (params != null) {
format += ", \"" + params + "\"";
}
String query = "for c in (" + req.getCoverageId() + ") return encode(" + proc + ", \"" + format + "\")";
return Pair.of(query, axes.trim());
}
}
| true | true | protected Pair<String, String> constructWcpsQuery(GetCoverageRequest req, Metadata cov, String format, String params) {
String axes = "";
Iterator<DomainElement> dit = cov.getDomainIterator();
while (dit.hasNext()) {
axes += dit.next().getName() + " ";
}
String proc = "c";
// process subsetting operations
for (DimensionSubset subset : req.getSubsets()) {
String dim = subset.getDimension();
DomainElement de = cov.getDomainByName(dim);
String crs = "CRS:1";
for (String c : de.getCrsSet()) {
crs = c;
break;
}
if (subset instanceof DimensionTrim) {
DimensionTrim trim = (DimensionTrim) subset;
proc = "trim(" + proc + ",{" + dim + ":\"" + crs + "\" (" + trim.
getTrimLow() + ":" + trim.getTrimHigh() + ")})";
} else if (subset instanceof DimensionSlice) {
DimensionSlice slice = (DimensionSlice) subset;
proc = "slice(" + proc + ",{" + dim + "(" + slice.getSlicePoint() + ")})";
axes = axes.replaceFirst(dim + " ?", ""); // remove axis
}
}
if (params != null) {
format += ", \"" + params + "\"";
}
String query = "for c in (" + req.getCoverageId() + ") return encode(" + proc + ", \"" + format + "\")";
return Pair.of(query, axes.trim());
}
| protected Pair<String, String> constructWcpsQuery(GetCoverageRequest req, Metadata cov, String format, String params) {
String axes = "";
Iterator<DomainElement> dit = cov.getDomainIterator();
while (dit.hasNext()) {
axes += dit.next().getName() + " ";
}
String proc = "c";
// process subsetting operations
for (DimensionSubset subset : req.getSubsets()) {
String dim = subset.getDimension();
DomainElement de = cov.getDomainByName(dim);
String crs = "CRS:1";
if (subset.getCrs() != null) {
crs = subset.getCrs();
}
if (subset instanceof DimensionTrim) {
DimensionTrim trim = (DimensionTrim) subset;
proc = "trim(" + proc + ",{" + dim + ":\"" + crs + "\" (" + trim.
getTrimLow() + ":" + trim.getTrimHigh() + ")})";
} else if (subset instanceof DimensionSlice) {
DimensionSlice slice = (DimensionSlice) subset;
proc = "slice(" + proc + ",{" + dim + "(" + slice.getSlicePoint() + ")})";
axes = axes.replaceFirst(dim + " ?", ""); // remove axis
}
}
if (params != null) {
format += ", \"" + params + "\"";
}
String query = "for c in (" + req.getCoverageId() + ") return encode(" + proc + ", \"" + format + "\")";
return Pair.of(query, axes.trim());
}
|
diff --git a/src/main/java/uk/co/thomasc/wordmaster/view/game/SwipeController.java b/src/main/java/uk/co/thomasc/wordmaster/view/game/SwipeController.java
index 430b56c..8596d57 100644
--- a/src/main/java/uk/co/thomasc/wordmaster/view/game/SwipeController.java
+++ b/src/main/java/uk/co/thomasc/wordmaster/view/game/SwipeController.java
@@ -1,177 +1,178 @@
package uk.co.thomasc.wordmaster.view.game;
import java.util.ArrayList;
import java.util.List;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import uk.co.thomasc.wordmaster.BaseGame;
import uk.co.thomasc.wordmaster.R;
import uk.co.thomasc.wordmaster.api.GetTurnsRequestListener;
import uk.co.thomasc.wordmaster.api.ServerAPI;
import uk.co.thomasc.wordmaster.objects.Game;
import uk.co.thomasc.wordmaster.objects.Turn;
import uk.co.thomasc.wordmaster.objects.callbacks.TurnAddedListener;
import uk.co.thomasc.wordmaster.view.DialogPanel;
import uk.co.thomasc.wordmaster.view.Errors;
import uk.co.thomasc.wordmaster.view.RussoText;
import uk.co.thomasc.wordmaster.view.game.PullToRefreshListView.OnRefreshListener;
import uk.co.thomasc.wordmaster.view.menu.MenuDetailFragment;
public class SwipeController extends FragmentStatePagerAdapter {
private static String gid;
private float pageWidth = 1.0f;
public SwipeController(BaseGame fm, String gameid) {
super(fm.getSupportFragmentManager());
pageWidth = fm.wideLayout ? 0.5f : 1.0f;
SwipeController.gid = gameid;
}
@Override
public float getPageWidth(int position) {
return pageWidth;
}
@Override
public Fragment getItem(int arg0) {
Fragment fragment = new Pages();
Bundle args = new Bundle();
args.putBoolean(Pages.ARG_OBJECT, arg0 == 0);
args.putString(MenuDetailFragment.ARG_ITEM_ID, SwipeController.gid);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
return 2;
}
public static class Pages extends Fragment implements TurnAddedListener {
public static final String ARG_OBJECT = "object";
private ToggleListener listener = new ToggleListener();
private GameAdapter adapter;
private Game game;
private PullToRefreshListView listView;
@Override
public void onDestroy() {
super.onDestroy();
if (game != null) {
game.removeTurnListener(this);
}
}
@Override
public void onTurnAdded(final Turn turn, final boolean newerTurn) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
adapter.add(turn);
if (newerTurn) {
listView.scrollToBottom();
}
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView;
if (getArguments().getBoolean(Pages.ARG_OBJECT)) {
rootView = new PullToRefreshListView(getActivity());
((BaseGame) getActivity()).gameAdapter = adapter = new GameAdapter(getActivity());
game = Game.getGame(SwipeController.gid);
if (game != null) {
for (Turn t : game.getTurns()) {
adapter.add(t);
}
game.addTurnListener(this);
((PullToRefreshListView) rootView).setAdapter(adapter);
listView = (PullToRefreshListView) rootView;
+ listView.setBackgroundColor(Color.WHITE);
listView.setCacheColorHint(Color.WHITE);
listView.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh() {
int pivot = game.getPivotOldest();
ServerAPI.getTurns(game.getID(), pivot, -10, (BaseGame) getActivity(), new GetTurnsRequestListener() {
@Override
public void onRequestFailed() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
listView.onRefreshComplete();
DialogPanel errorMessage = (DialogPanel) getActivity().findViewById(R.id.errorMessage);
errorMessage.show(Errors.NETWORK);
}
});
}
@Override
public void onRequestComplete(List<Turn> turns) {
ArrayList<Turn> gameTurns = game.getTurns();
for (Turn turn : turns) {
if (!gameTurns.contains(turn)) {
game.addTurn(turn);
}
}
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
listView.onRefreshComplete();
}
});
}
});
}
});
}
} else {
game = Game.getGame(SwipeController.gid);
rootView = inflater.inflate(R.layout.alphabet, container, false);
LinearLayout root = (LinearLayout) rootView;
int index = 0;
for (int i = 0; i < root.getChildCount(); i++) {
LinearLayout child = (LinearLayout) root.getChildAt(i);
for (int j = 0; j < child.getChildCount(); j++) {
RussoText txt = (RussoText) child.getChildAt(j);
txt.setOnClickListener(listener);
txt.setId(index);
boolean strike = game.getAlpha(index++);
txt.setTextColor(getResources().getColor(strike ? R.color.hiddenletter : R.color.maintext));
txt.setStrike(strike);
}
}
}
return rootView;
}
private class ToggleListener implements OnClickListener {
@Override
public void onClick(View v) {
RussoText txt = (RussoText) v;
txt.setTextColor(getResources().getColor(txt.isStrike() ? R.color.maintext : R.color.hiddenletter));
txt.setStrike(!txt.isStrike());
game.updateAlpha(txt.getId(), txt.isStrike(), (BaseGame) getActivity());
}
}
}
}
| true | true | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView;
if (getArguments().getBoolean(Pages.ARG_OBJECT)) {
rootView = new PullToRefreshListView(getActivity());
((BaseGame) getActivity()).gameAdapter = adapter = new GameAdapter(getActivity());
game = Game.getGame(SwipeController.gid);
if (game != null) {
for (Turn t : game.getTurns()) {
adapter.add(t);
}
game.addTurnListener(this);
((PullToRefreshListView) rootView).setAdapter(adapter);
listView = (PullToRefreshListView) rootView;
listView.setCacheColorHint(Color.WHITE);
listView.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh() {
int pivot = game.getPivotOldest();
ServerAPI.getTurns(game.getID(), pivot, -10, (BaseGame) getActivity(), new GetTurnsRequestListener() {
@Override
public void onRequestFailed() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
listView.onRefreshComplete();
DialogPanel errorMessage = (DialogPanel) getActivity().findViewById(R.id.errorMessage);
errorMessage.show(Errors.NETWORK);
}
});
}
@Override
public void onRequestComplete(List<Turn> turns) {
ArrayList<Turn> gameTurns = game.getTurns();
for (Turn turn : turns) {
if (!gameTurns.contains(turn)) {
game.addTurn(turn);
}
}
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
listView.onRefreshComplete();
}
});
}
});
}
});
}
} else {
game = Game.getGame(SwipeController.gid);
rootView = inflater.inflate(R.layout.alphabet, container, false);
LinearLayout root = (LinearLayout) rootView;
int index = 0;
for (int i = 0; i < root.getChildCount(); i++) {
LinearLayout child = (LinearLayout) root.getChildAt(i);
for (int j = 0; j < child.getChildCount(); j++) {
RussoText txt = (RussoText) child.getChildAt(j);
txt.setOnClickListener(listener);
txt.setId(index);
boolean strike = game.getAlpha(index++);
txt.setTextColor(getResources().getColor(strike ? R.color.hiddenletter : R.color.maintext));
txt.setStrike(strike);
}
}
}
return rootView;
}
| public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView;
if (getArguments().getBoolean(Pages.ARG_OBJECT)) {
rootView = new PullToRefreshListView(getActivity());
((BaseGame) getActivity()).gameAdapter = adapter = new GameAdapter(getActivity());
game = Game.getGame(SwipeController.gid);
if (game != null) {
for (Turn t : game.getTurns()) {
adapter.add(t);
}
game.addTurnListener(this);
((PullToRefreshListView) rootView).setAdapter(adapter);
listView = (PullToRefreshListView) rootView;
listView.setBackgroundColor(Color.WHITE);
listView.setCacheColorHint(Color.WHITE);
listView.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh() {
int pivot = game.getPivotOldest();
ServerAPI.getTurns(game.getID(), pivot, -10, (BaseGame) getActivity(), new GetTurnsRequestListener() {
@Override
public void onRequestFailed() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
listView.onRefreshComplete();
DialogPanel errorMessage = (DialogPanel) getActivity().findViewById(R.id.errorMessage);
errorMessage.show(Errors.NETWORK);
}
});
}
@Override
public void onRequestComplete(List<Turn> turns) {
ArrayList<Turn> gameTurns = game.getTurns();
for (Turn turn : turns) {
if (!gameTurns.contains(turn)) {
game.addTurn(turn);
}
}
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
listView.onRefreshComplete();
}
});
}
});
}
});
}
} else {
game = Game.getGame(SwipeController.gid);
rootView = inflater.inflate(R.layout.alphabet, container, false);
LinearLayout root = (LinearLayout) rootView;
int index = 0;
for (int i = 0; i < root.getChildCount(); i++) {
LinearLayout child = (LinearLayout) root.getChildAt(i);
for (int j = 0; j < child.getChildCount(); j++) {
RussoText txt = (RussoText) child.getChildAt(j);
txt.setOnClickListener(listener);
txt.setId(index);
boolean strike = game.getAlpha(index++);
txt.setTextColor(getResources().getColor(strike ? R.color.hiddenletter : R.color.maintext));
txt.setStrike(strike);
}
}
}
return rootView;
}
|
diff --git a/bundleplugin/src/main/java/org/apache/felix/bundleplugin/BundlePlugin.java b/bundleplugin/src/main/java/org/apache/felix/bundleplugin/BundlePlugin.java
index 14fb93a96..56f139cc7 100644
--- a/bundleplugin/src/main/java/org/apache/felix/bundleplugin/BundlePlugin.java
+++ b/bundleplugin/src/main/java/org/apache/felix/bundleplugin/BundlePlugin.java
@@ -1,765 +1,765 @@
/*
* 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.felix.bundleplugin;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
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 java.util.jar.Manifest;
import java.util.zip.ZipException;
import org.apache.maven.archiver.MavenArchiveConfiguration;
import org.apache.maven.archiver.MavenArchiver;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager;
import org.apache.maven.model.License;
import org.apache.maven.model.Model;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.shared.osgi.Maven2OsgiConverter;
import org.codehaus.plexus.archiver.UnArchiver;
import org.codehaus.plexus.archiver.manager.ArchiverManager;
import org.codehaus.plexus.util.DirectoryScanner;
import org.codehaus.plexus.util.StringInputStream;
import aQute.lib.osgi.Analyzer;
import aQute.lib.osgi.Builder;
import aQute.lib.osgi.EmbeddedResource;
import aQute.lib.osgi.FileResource;
import aQute.lib.osgi.Jar;
/**
* Create an OSGi bundle from Maven project
*
* @goal bundle
* @phase package
* @requiresDependencyResolution runtime
* @description build an OSGi bundle jar
*/
public class BundlePlugin extends AbstractMojo {
/**
* Directory where the manifest will be written
*
* @parameter expression="${manifestLocation}" default-value="${project.build.outputDirectory}/META-INF"
*/
protected File manifestLocation;
/**
* When true, unpack the bundle contents to the outputDirectory
*
* @parameter expression="${unpackBundle}"
*/
protected boolean unpackBundle;
/**
* @component
*/
private ArchiverManager archiverManager;
/**
* @component
*/
private ArtifactHandlerManager artifactHandlerManager;
/**
* Project types which this plugin supports.
*
* @parameter
*/
private List supportedProjectTypes = Arrays.asList(new String[]{"jar","bundle"});
/**
* The directory for the generated bundles.
*
* @parameter expression="${project.build.outputDirectory}"
* @required
*/
private File outputDirectory;
/**
* The directory for the pom
*
* @parameter expression="${basedir}"
* @required
*/
private File baseDir;
/**
* The directory for the generated JAR.
*
* @parameter expression="${project.build.directory}"
* @required
*/
private String buildDirectory;
/**
* The Maven project.
*
* @parameter expression="${project}"
* @required
* @readonly
*/
private MavenProject project;
/**
* The name of the generated JAR file.
*
* @parameter
*/
private Map instructions = new HashMap();
/**
* @component
*/
private Maven2OsgiConverter maven2OsgiConverter;
private static final String MAVEN_RESOURCES = "{maven-resources}";
private static final String MAVEN_RESOURCES_REGEX = "\\{maven-resources\\}";
private static final String[] EMPTY_STRING_ARRAY = {};
private static final String[] DEFAULT_INCLUDES = {"**/**"};
protected Maven2OsgiConverter getMaven2OsgiConverter()
{
return this.maven2OsgiConverter;
}
void setMaven2OsgiConverter(Maven2OsgiConverter maven2OsgiConverter)
{
this.maven2OsgiConverter = maven2OsgiConverter;
}
protected MavenProject getProject()
{
return this.project;
}
/**
* @see org.apache.maven.plugin.AbstractMojo#execute()
*/
public void execute() throws MojoExecutionException
{
Properties properties = new Properties();
// ignore project types not supported, useful when the plugin is configured in the parent pom
if (!this.supportedProjectTypes.contains(this.getProject().getArtifact().getType()))
{
this.getLog().debug("Ignoring project " + this.getProject().getArtifact() + " : type " + this.getProject().getArtifact().getType() +
" is not supported by bundle plugin, supported types are " + this.supportedProjectTypes );
return;
}
this.execute(this.project, this.instructions, properties);
}
protected void execute(MavenProject project, Map instructions, Properties properties)
throws MojoExecutionException
{
try
{
this.execute(project, instructions, properties, this.getClasspath(project));
}
catch ( IOException e )
{
throw new MojoExecutionException("Error calculating classpath for project " + project, e);
}
}
/* transform directives from their XML form to the expected BND syntax (eg. _include becomes -include) */
protected Map transformDirectives(Map instructions)
{
Map transformedInstructions = new HashMap();
for (Iterator i = instructions.entrySet().iterator(); i.hasNext();)
{
Map.Entry e = (Map.Entry)i.next();
String key = (String)e.getKey();
if (key.startsWith("_"))
{
key = "-"+key.substring(1);
}
String value = (String)e.getValue();
if (null == value)
{
value = "";
}
else
{
value = value.replaceAll("[\r\n]", "");
}
transformedInstructions.put(key, value);
}
return transformedInstructions;
}
protected void execute(MavenProject project, Map instructions, Properties properties, Jar[] classpath)
throws MojoExecutionException
{
try
{
File jarFile = new File(this.getBuildDirectory(), this.getBundleName(project));
properties.putAll(this.getDefaultProperties(project));
String bsn = project.getGroupId() + "." + project.getArtifactId();
if (!instructions.containsKey(Analyzer.PRIVATE_PACKAGE))
{
properties.put(Analyzer.EXPORT_PACKAGE, bsn + ".*");
}
properties.putAll(this.transformDirectives(instructions));
// pass maven resource paths onto BND analyzer
final String mavenResourcePaths = this.getMavenResourcePaths(project);
final String includeResource = (String)properties.get(Analyzer.INCLUDE_RESOURCE);
if (includeResource != null)
{
if (includeResource.indexOf(MAVEN_RESOURCES) >= 0)
{
// if there is no maven resource path, we do a special treatment and replace
// every occurance of MAVEN_RESOURCES and a following comma with an empty string
if ( mavenResourcePaths.length() == 0 )
{
String cleanedResource = removeMavenResourcesTag( includeResource );
if ( cleanedResource.length() > 0 )
{
properties.put(Analyzer.INCLUDE_RESOURCE, cleanedResource);
}
else
{
properties.remove(Analyzer.INCLUDE_RESOURCE);
}
}
else
{
String combinedResource = includeResource.replaceAll(MAVEN_RESOURCES_REGEX, mavenResourcePaths);
properties.put(Analyzer.INCLUDE_RESOURCE, combinedResource);
}
}
else if ( mavenResourcePaths.length() > 0 )
{
this.getLog().warn(Analyzer.INCLUDE_RESOURCE + ": overriding " + mavenResourcePaths + " with " +
includeResource + " (add " + MAVEN_RESOURCES + " if you want to include the maven resources)");
}
}
else if (mavenResourcePaths.length() > 0 )
{
properties.put(Analyzer.INCLUDE_RESOURCE, mavenResourcePaths);
}
Builder builder = new Builder();
builder.setBase(project.getBasedir());
builder.setProperties(properties);
builder.setClasspath(classpath);
Collection embeddableArtifacts = getEmbeddableArtifacts(project, properties);
if (embeddableArtifacts.size() > 0)
{
// add BND instructions to embed selected dependencies
new DependencyEmbedder(embeddableArtifacts).processHeaders(properties);
}
builder.build();
Jar jar = builder.getJar();
this.doMavenMetadata(project, jar);
builder.setJar(jar);
List errors = builder.getErrors();
List warnings = builder.getWarnings();
for (Iterator w = warnings.iterator(); w.hasNext();)
{
String msg = (String) w.next();
this.getLog().warn("Warning building bundle " + project.getArtifact() + " : " + msg);
}
for (Iterator e = errors.iterator(); e.hasNext();)
{
String msg = (String) e.next();
this.getLog().error("Error building bundle " + project.getArtifact() + " : " + msg);
}
if (errors.size() > 0)
{
String failok = properties.getProperty( "-failok" );
if (null == failok || "false".equalsIgnoreCase( failok ))
{
jarFile.delete();
throw new MojoFailureException("Error(s) found in bundle configuration");
}
}
try
{
/*
* Grab customized manifest entries from the maven-jar-plugin configuration
*/
MavenArchiveConfiguration archiveConfig = JarPluginConfiguration.getArchiveConfiguration( project );
String mavenManifestText = new MavenArchiver().getManifest( project, archiveConfig ).toString();
Manifest mavenManifest = new Manifest();
mavenManifest.read( new StringInputStream( mavenManifestText ) );
/*
* Overlay customized Maven manifest with the generated bundle manifest
*/
Manifest bundleManifest = jar.getManifest();
bundleManifest.getMainAttributes().putAll( mavenManifest.getMainAttributes() );
bundleManifest.getMainAttributes().putValue( "Created-By", "Apache Maven Bundle Plugin" );
bundleManifest.getEntries().putAll( mavenManifest.getEntries() );
jar.setManifest( bundleManifest );
}
catch (Exception e)
{
- getLog().warn( "Unable to merge Maven manifest" );
+ getLog().warn( "Unable to merge Maven manifest: " + e.getLocalizedMessage() );
}
jarFile.getParentFile().mkdirs();
builder.getJar().write(jarFile);
Artifact bundleArtifact = project.getArtifact();
bundleArtifact.setFile(jarFile);
if (unpackBundle)
{
File outputDir = this.getOutputDirectory();
if (null == outputDir)
{
outputDir = new File( this.getBuildDirectory(), "classes" );
}
try
{
/*
* this directory must exist before unpacking, otherwise the plexus
* unarchiver decides to use the current working directory instead!
*/
if (!outputDir.exists())
{
outputDir.mkdirs();
}
UnArchiver unArchiver = archiverManager.getUnArchiver( "jar" );
unArchiver.setDestDirectory( outputDir );
unArchiver.setSourceFile( jarFile );
unArchiver.extract();
}
catch ( Exception e )
{
getLog().error( "Problem unpacking " + jarFile + " to " + outputDir, e );
}
}
if (manifestLocation != null)
{
File outputFile = new File( manifestLocation, "MANIFEST.MF" );
try
{
Manifest manifest = builder.getJar().getManifest();
ManifestPlugin.writeManifest( manifest, outputFile );
}
catch ( IOException e )
{
getLog().error( "Error trying to write Manifest to file " + outputFile, e );
}
}
// workaround for MNG-1682: force maven to install artifact using the "jar" handler
bundleArtifact.setArtifactHandler( artifactHandlerManager.getArtifactHandler( "jar" ) );
}
catch (MojoFailureException e)
{
getLog().error( e.getLocalizedMessage() );
throw new MojoExecutionException( "Error(s) found in bundle configuration", e );
}
catch (Exception e)
{
getLog().error( "An internal error occurred", e );
throw new MojoExecutionException( "Internal error in maven-bundle-plugin", e );
}
}
private String removeMavenResourcesTag( String includeResource )
{
StringBuffer buf = new StringBuffer();
String[] clauses = includeResource.split(",");
for (int i = 0; i < clauses.length; i++)
{
String clause = clauses[i].trim();
if (!MAVEN_RESOURCES.equals(clause))
{
if (buf.length() > 0)
{
buf.append(',');
}
buf.append(clause);
}
}
return buf.toString();
}
private Map getProperies(Model projectModel, String prefix, Object model)
{
Map properties = new HashMap();
Method methods[] = Model.class.getDeclaredMethods();
for (int i = 0; i < methods.length; i++)
{
String name = methods[i].getName();
if ( name.startsWith("get") )
{
try
{
Object v = methods[i].invoke(projectModel, null );
if ( v != null )
{
name = prefix + Character.toLowerCase(name.charAt(3)) + name.substring(4);
if ( v.getClass().isArray() )
properties.put( name, Arrays.asList((Object[])v).toString() );
else
properties.put( name, v );
}
}
catch (Exception e)
{
// too bad
}
}
}
return properties;
}
private StringBuffer printLicenses(List licenses)
{
if (licenses == null || licenses.size() == 0)
return null;
StringBuffer sb = new StringBuffer();
String del = "";
for (Iterator i = licenses.iterator(); i.hasNext();)
{
License l = (License) i.next();
String url = l.getUrl();
if (url == null) continue;
sb.append(del);
sb.append(url);
del = ", ";
}
if (sb.length() == 0) return null;
return sb;
}
/**
* @param jar
* @throws IOException
*/
private void doMavenMetadata(MavenProject project, Jar jar) throws IOException {
String path = "META-INF/maven/" + project.getGroupId() + "/"
+ project.getArtifactId();
File pomFile = new File(this.baseDir, "pom.xml");
jar.putResource(path + "/pom.xml", new FileResource(pomFile));
Properties p = new Properties();
p.put("version", project.getVersion());
p.put("groupId", project.getGroupId());
p.put("artifactId", project.getArtifactId());
ByteArrayOutputStream out = new ByteArrayOutputStream();
p.store(out, "Generated by org.apache.felix.plugin.bundle");
jar.putResource(path + "/pom.properties", new EmbeddedResource(out
.toByteArray(), System.currentTimeMillis()));
}
/**
* @return
* @throws ZipException
* @throws IOException
*/
protected Jar[] getClasspath(MavenProject project) throws ZipException, IOException
{
List list = new ArrayList();
if (this.getOutputDirectory() != null && this.getOutputDirectory().exists())
{
list.add(new Jar(".", this.getOutputDirectory()));
}
Set artifacts = project.getArtifacts();
for (Iterator it = artifacts.iterator(); it.hasNext();)
{
Artifact artifact = (Artifact) it.next();
if (artifact.getArtifactHandler().isAddedToClasspath())
{
if (Artifact.SCOPE_COMPILE.equals(artifact.getScope())
|| Artifact.SCOPE_SYSTEM.equals(artifact.getScope())
|| Artifact.SCOPE_PROVIDED.equals(artifact.getScope()))
{
File file = this.getFile(artifact);
if (file == null)
{
getLog().warn( "File is not available for artifact " + artifact + " in project " + project.getArtifact() );
continue;
}
Jar jar = new Jar(artifact.getArtifactId(), file);
list.add(jar);
}
}
}
Jar[] cp = new Jar[list.size()];
list.toArray(cp);
return cp;
}
/**
* Get the file for an Artifact
*
* @param artifact
*/
protected File getFile(Artifact artifact)
{
return artifact.getFile();
}
private void header(Properties properties, String key, Object value)
{
if (value == null)
return;
if (value instanceof Collection && ((Collection) value).isEmpty())
return;
properties.put(key, value.toString().replaceAll("[\r\n]", ""));
}
/**
* Convert a Maven version into an OSGi compliant version
*
* @param version Maven version
* @return the OSGi version
*/
protected String convertVersionToOsgi(String version)
{
return this.getMaven2OsgiConverter().getVersion( version );
}
/**
* TODO this should return getMaven2Osgi().getBundleFileName( project.getArtifact() )
*/
protected String getBundleName(MavenProject project)
{
return project.getBuild().getFinalName() + ".jar";
}
protected String getBuildDirectory()
{
return this.buildDirectory;
}
void setBuildDirectory(String buildirectory)
{
this.buildDirectory = buildirectory;
}
protected Properties getDefaultProperties(MavenProject project)
{
Properties properties = new Properties();
String bsn;
try
{
bsn = maven2OsgiConverter.getBundleSymbolicName( project.getArtifact() );
}
catch (Exception e)
{
bsn = project.getGroupId() + "." + project.getArtifactId();
}
// Setup defaults
properties.put(Analyzer.BUNDLE_SYMBOLICNAME, bsn);
properties.put(Analyzer.IMPORT_PACKAGE, "*");
properties.put(Analyzer.BUNDLE_VERSION, project.getVersion());
this.header(properties, Analyzer.BUNDLE_DESCRIPTION, project
.getDescription());
StringBuffer licenseText = this.printLicenses(project.getLicenses());
if (licenseText != null) {
this.header(properties, Analyzer.BUNDLE_LICENSE, licenseText);
}
this.header(properties, Analyzer.BUNDLE_NAME, project.getName());
if (project.getOrganization() != null)
{
this.header(properties, Analyzer.BUNDLE_VENDOR, project
.getOrganization().getName());
if (project.getOrganization().getUrl() != null)
{
this.header(properties, Analyzer.BUNDLE_DOCURL, project
.getOrganization().getUrl());
}
}
properties.putAll(project.getProperties());
properties.putAll(project.getModel().getProperties());
properties.putAll( this.getProperies(project.getModel(), "project.build.", project.getBuild()));
properties.putAll( this.getProperies(project.getModel(), "pom.", project.getModel()));
properties.putAll( this.getProperies(project.getModel(), "project.", project));
properties.put("project.baseDir", this.baseDir );
properties.put("project.build.directory", this.getBuildDirectory() );
properties.put("project.build.outputdirectory", this.getOutputDirectory() );
return properties;
}
void setBasedir(File basedir)
{
this.baseDir = basedir;
}
File getOutputDirectory()
{
return this.outputDirectory;
}
void setOutputDirectory(File outputDirectory)
{
this.outputDirectory = outputDirectory;
}
String getMavenResourcePaths(MavenProject project)
{
final String basePath = project.getBasedir().getAbsolutePath();
StringBuffer resourcePaths = new StringBuffer();
for (Iterator i = project.getResources().iterator(); i.hasNext();)
{
org.apache.maven.model.Resource resource = (org.apache.maven.model.Resource)i.next();
final String sourcePath = resource.getDirectory();
final String targetPath = resource.getTargetPath();
// ignore empty or non-local resources
if (new File(sourcePath).exists() && ((targetPath == null) || (targetPath.indexOf("..") < 0)))
{
DirectoryScanner scanner = new DirectoryScanner();
scanner.setBasedir( resource.getDirectory() );
if ( resource.getIncludes() != null && !resource.getIncludes().isEmpty() )
{
scanner.setIncludes( (String[]) resource.getIncludes().toArray( EMPTY_STRING_ARRAY ) );
}
else
{
scanner.setIncludes( DEFAULT_INCLUDES );
}
if ( resource.getExcludes() != null && !resource.getExcludes().isEmpty() )
{
scanner.setExcludes( (String[]) resource.getExcludes().toArray( EMPTY_STRING_ARRAY ) );
}
scanner.addDefaultExcludes();
scanner.scan();
List includedFiles = Arrays.asList( scanner.getIncludedFiles() );
for ( Iterator j = includedFiles.iterator(); j.hasNext(); )
{
String name = (String) j.next();
String path = sourcePath + '/' + name;
// make relative to project
if (path.startsWith(basePath))
{
if ( path.length() == basePath.length() )
{
path = ".";
}
else
{
path = path.substring( basePath.length() + 1 );
}
}
// replace windows backslash with a slash
// this is a workaround for a problem with bnd 0.0.189
if ( File.separatorChar != '/' )
{
name = name.replace(File.separatorChar, '/');
path = path.replace(File.separatorChar, '/');
}
// copy to correct place
path = name + '=' + path;
if (targetPath != null)
{
path = targetPath + '/' + path;
}
if (resourcePaths.length() > 0)
{
resourcePaths.append(',');
}
if (resource.isFiltering())
{
resourcePaths.append('{');
resourcePaths.append(path);
resourcePaths.append('}');
}
else
{
resourcePaths.append(path);
}
}
}
}
return resourcePaths.toString();
}
Collection getEmbeddableArtifacts(MavenProject project, Properties properties)
{
String embedTransitive = properties.getProperty(DependencyEmbedder.EMBED_TRANSITIVE);
if (Boolean.valueOf(embedTransitive).booleanValue())
{
// includes transitive dependencies
return project.getArtifacts();
}
else
{
// only includes direct dependencies
return project.getDependencyArtifacts();
}
}
}
| true | true | protected void execute(MavenProject project, Map instructions, Properties properties, Jar[] classpath)
throws MojoExecutionException
{
try
{
File jarFile = new File(this.getBuildDirectory(), this.getBundleName(project));
properties.putAll(this.getDefaultProperties(project));
String bsn = project.getGroupId() + "." + project.getArtifactId();
if (!instructions.containsKey(Analyzer.PRIVATE_PACKAGE))
{
properties.put(Analyzer.EXPORT_PACKAGE, bsn + ".*");
}
properties.putAll(this.transformDirectives(instructions));
// pass maven resource paths onto BND analyzer
final String mavenResourcePaths = this.getMavenResourcePaths(project);
final String includeResource = (String)properties.get(Analyzer.INCLUDE_RESOURCE);
if (includeResource != null)
{
if (includeResource.indexOf(MAVEN_RESOURCES) >= 0)
{
// if there is no maven resource path, we do a special treatment and replace
// every occurance of MAVEN_RESOURCES and a following comma with an empty string
if ( mavenResourcePaths.length() == 0 )
{
String cleanedResource = removeMavenResourcesTag( includeResource );
if ( cleanedResource.length() > 0 )
{
properties.put(Analyzer.INCLUDE_RESOURCE, cleanedResource);
}
else
{
properties.remove(Analyzer.INCLUDE_RESOURCE);
}
}
else
{
String combinedResource = includeResource.replaceAll(MAVEN_RESOURCES_REGEX, mavenResourcePaths);
properties.put(Analyzer.INCLUDE_RESOURCE, combinedResource);
}
}
else if ( mavenResourcePaths.length() > 0 )
{
this.getLog().warn(Analyzer.INCLUDE_RESOURCE + ": overriding " + mavenResourcePaths + " with " +
includeResource + " (add " + MAVEN_RESOURCES + " if you want to include the maven resources)");
}
}
else if (mavenResourcePaths.length() > 0 )
{
properties.put(Analyzer.INCLUDE_RESOURCE, mavenResourcePaths);
}
Builder builder = new Builder();
builder.setBase(project.getBasedir());
builder.setProperties(properties);
builder.setClasspath(classpath);
Collection embeddableArtifacts = getEmbeddableArtifacts(project, properties);
if (embeddableArtifacts.size() > 0)
{
// add BND instructions to embed selected dependencies
new DependencyEmbedder(embeddableArtifacts).processHeaders(properties);
}
builder.build();
Jar jar = builder.getJar();
this.doMavenMetadata(project, jar);
builder.setJar(jar);
List errors = builder.getErrors();
List warnings = builder.getWarnings();
for (Iterator w = warnings.iterator(); w.hasNext();)
{
String msg = (String) w.next();
this.getLog().warn("Warning building bundle " + project.getArtifact() + " : " + msg);
}
for (Iterator e = errors.iterator(); e.hasNext();)
{
String msg = (String) e.next();
this.getLog().error("Error building bundle " + project.getArtifact() + " : " + msg);
}
if (errors.size() > 0)
{
String failok = properties.getProperty( "-failok" );
if (null == failok || "false".equalsIgnoreCase( failok ))
{
jarFile.delete();
throw new MojoFailureException("Error(s) found in bundle configuration");
}
}
try
{
/*
* Grab customized manifest entries from the maven-jar-plugin configuration
*/
MavenArchiveConfiguration archiveConfig = JarPluginConfiguration.getArchiveConfiguration( project );
String mavenManifestText = new MavenArchiver().getManifest( project, archiveConfig ).toString();
Manifest mavenManifest = new Manifest();
mavenManifest.read( new StringInputStream( mavenManifestText ) );
/*
* Overlay customized Maven manifest with the generated bundle manifest
*/
Manifest bundleManifest = jar.getManifest();
bundleManifest.getMainAttributes().putAll( mavenManifest.getMainAttributes() );
bundleManifest.getMainAttributes().putValue( "Created-By", "Apache Maven Bundle Plugin" );
bundleManifest.getEntries().putAll( mavenManifest.getEntries() );
jar.setManifest( bundleManifest );
}
catch (Exception e)
{
getLog().warn( "Unable to merge Maven manifest" );
}
jarFile.getParentFile().mkdirs();
builder.getJar().write(jarFile);
Artifact bundleArtifact = project.getArtifact();
bundleArtifact.setFile(jarFile);
if (unpackBundle)
{
File outputDir = this.getOutputDirectory();
if (null == outputDir)
{
outputDir = new File( this.getBuildDirectory(), "classes" );
}
try
{
/*
* this directory must exist before unpacking, otherwise the plexus
* unarchiver decides to use the current working directory instead!
*/
if (!outputDir.exists())
{
outputDir.mkdirs();
}
UnArchiver unArchiver = archiverManager.getUnArchiver( "jar" );
unArchiver.setDestDirectory( outputDir );
unArchiver.setSourceFile( jarFile );
unArchiver.extract();
}
catch ( Exception e )
{
getLog().error( "Problem unpacking " + jarFile + " to " + outputDir, e );
}
}
if (manifestLocation != null)
{
File outputFile = new File( manifestLocation, "MANIFEST.MF" );
try
{
Manifest manifest = builder.getJar().getManifest();
ManifestPlugin.writeManifest( manifest, outputFile );
}
catch ( IOException e )
{
getLog().error( "Error trying to write Manifest to file " + outputFile, e );
}
}
// workaround for MNG-1682: force maven to install artifact using the "jar" handler
bundleArtifact.setArtifactHandler( artifactHandlerManager.getArtifactHandler( "jar" ) );
}
catch (MojoFailureException e)
{
getLog().error( e.getLocalizedMessage() );
throw new MojoExecutionException( "Error(s) found in bundle configuration", e );
}
catch (Exception e)
{
getLog().error( "An internal error occurred", e );
throw new MojoExecutionException( "Internal error in maven-bundle-plugin", e );
}
}
| protected void execute(MavenProject project, Map instructions, Properties properties, Jar[] classpath)
throws MojoExecutionException
{
try
{
File jarFile = new File(this.getBuildDirectory(), this.getBundleName(project));
properties.putAll(this.getDefaultProperties(project));
String bsn = project.getGroupId() + "." + project.getArtifactId();
if (!instructions.containsKey(Analyzer.PRIVATE_PACKAGE))
{
properties.put(Analyzer.EXPORT_PACKAGE, bsn + ".*");
}
properties.putAll(this.transformDirectives(instructions));
// pass maven resource paths onto BND analyzer
final String mavenResourcePaths = this.getMavenResourcePaths(project);
final String includeResource = (String)properties.get(Analyzer.INCLUDE_RESOURCE);
if (includeResource != null)
{
if (includeResource.indexOf(MAVEN_RESOURCES) >= 0)
{
// if there is no maven resource path, we do a special treatment and replace
// every occurance of MAVEN_RESOURCES and a following comma with an empty string
if ( mavenResourcePaths.length() == 0 )
{
String cleanedResource = removeMavenResourcesTag( includeResource );
if ( cleanedResource.length() > 0 )
{
properties.put(Analyzer.INCLUDE_RESOURCE, cleanedResource);
}
else
{
properties.remove(Analyzer.INCLUDE_RESOURCE);
}
}
else
{
String combinedResource = includeResource.replaceAll(MAVEN_RESOURCES_REGEX, mavenResourcePaths);
properties.put(Analyzer.INCLUDE_RESOURCE, combinedResource);
}
}
else if ( mavenResourcePaths.length() > 0 )
{
this.getLog().warn(Analyzer.INCLUDE_RESOURCE + ": overriding " + mavenResourcePaths + " with " +
includeResource + " (add " + MAVEN_RESOURCES + " if you want to include the maven resources)");
}
}
else if (mavenResourcePaths.length() > 0 )
{
properties.put(Analyzer.INCLUDE_RESOURCE, mavenResourcePaths);
}
Builder builder = new Builder();
builder.setBase(project.getBasedir());
builder.setProperties(properties);
builder.setClasspath(classpath);
Collection embeddableArtifacts = getEmbeddableArtifacts(project, properties);
if (embeddableArtifacts.size() > 0)
{
// add BND instructions to embed selected dependencies
new DependencyEmbedder(embeddableArtifacts).processHeaders(properties);
}
builder.build();
Jar jar = builder.getJar();
this.doMavenMetadata(project, jar);
builder.setJar(jar);
List errors = builder.getErrors();
List warnings = builder.getWarnings();
for (Iterator w = warnings.iterator(); w.hasNext();)
{
String msg = (String) w.next();
this.getLog().warn("Warning building bundle " + project.getArtifact() + " : " + msg);
}
for (Iterator e = errors.iterator(); e.hasNext();)
{
String msg = (String) e.next();
this.getLog().error("Error building bundle " + project.getArtifact() + " : " + msg);
}
if (errors.size() > 0)
{
String failok = properties.getProperty( "-failok" );
if (null == failok || "false".equalsIgnoreCase( failok ))
{
jarFile.delete();
throw new MojoFailureException("Error(s) found in bundle configuration");
}
}
try
{
/*
* Grab customized manifest entries from the maven-jar-plugin configuration
*/
MavenArchiveConfiguration archiveConfig = JarPluginConfiguration.getArchiveConfiguration( project );
String mavenManifestText = new MavenArchiver().getManifest( project, archiveConfig ).toString();
Manifest mavenManifest = new Manifest();
mavenManifest.read( new StringInputStream( mavenManifestText ) );
/*
* Overlay customized Maven manifest with the generated bundle manifest
*/
Manifest bundleManifest = jar.getManifest();
bundleManifest.getMainAttributes().putAll( mavenManifest.getMainAttributes() );
bundleManifest.getMainAttributes().putValue( "Created-By", "Apache Maven Bundle Plugin" );
bundleManifest.getEntries().putAll( mavenManifest.getEntries() );
jar.setManifest( bundleManifest );
}
catch (Exception e)
{
getLog().warn( "Unable to merge Maven manifest: " + e.getLocalizedMessage() );
}
jarFile.getParentFile().mkdirs();
builder.getJar().write(jarFile);
Artifact bundleArtifact = project.getArtifact();
bundleArtifact.setFile(jarFile);
if (unpackBundle)
{
File outputDir = this.getOutputDirectory();
if (null == outputDir)
{
outputDir = new File( this.getBuildDirectory(), "classes" );
}
try
{
/*
* this directory must exist before unpacking, otherwise the plexus
* unarchiver decides to use the current working directory instead!
*/
if (!outputDir.exists())
{
outputDir.mkdirs();
}
UnArchiver unArchiver = archiverManager.getUnArchiver( "jar" );
unArchiver.setDestDirectory( outputDir );
unArchiver.setSourceFile( jarFile );
unArchiver.extract();
}
catch ( Exception e )
{
getLog().error( "Problem unpacking " + jarFile + " to " + outputDir, e );
}
}
if (manifestLocation != null)
{
File outputFile = new File( manifestLocation, "MANIFEST.MF" );
try
{
Manifest manifest = builder.getJar().getManifest();
ManifestPlugin.writeManifest( manifest, outputFile );
}
catch ( IOException e )
{
getLog().error( "Error trying to write Manifest to file " + outputFile, e );
}
}
// workaround for MNG-1682: force maven to install artifact using the "jar" handler
bundleArtifact.setArtifactHandler( artifactHandlerManager.getArtifactHandler( "jar" ) );
}
catch (MojoFailureException e)
{
getLog().error( e.getLocalizedMessage() );
throw new MojoExecutionException( "Error(s) found in bundle configuration", e );
}
catch (Exception e)
{
getLog().error( "An internal error occurred", e );
throw new MojoExecutionException( "Internal error in maven-bundle-plugin", e );
}
}
|
diff --git a/src/main/java/com/github/fge/uritemplate/parse/ExpressionParser.java b/src/main/java/com/github/fge/uritemplate/parse/ExpressionParser.java
index 338b5ca..3681d43 100644
--- a/src/main/java/com/github/fge/uritemplate/parse/ExpressionParser.java
+++ b/src/main/java/com/github/fge/uritemplate/parse/ExpressionParser.java
@@ -1,142 +1,140 @@
/*
* Copyright (c) 2013, Francis Galiegue <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Lesser 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
* Lesser GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.fge.uritemplate.parse;
import com.github.fge.uritemplate.URITemplateParseException;
import com.github.fge.uritemplate.expression.ExpressionType;
import com.github.fge.uritemplate.expression.TemplateExpression;
import com.github.fge.uritemplate.expression.URITemplateExpression;
import com.github.fge.uritemplate.vars.VariableSpec;
import com.google.common.base.CharMatcher;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import java.nio.CharBuffer;
import java.util.List;
import java.util.Map;
import static com.github.fge.uritemplate.ExceptionMessages.*;
public final class ExpressionParser
implements TemplateParser
{
private static final Map<Character, ExpressionType> EXPRESSION_TYPE_MAP;
private static final CharMatcher COMMA = CharMatcher.is(',');
private static final CharMatcher END_EXPRESSION = CharMatcher.is('}');
static {
final ImmutableMap.Builder<Character, ExpressionType> builder
= ImmutableMap.builder();
char c;
ExpressionType type;
c = '+';
type = ExpressionType.RESERVED;
builder.put(c, type);
c = '#';
type = ExpressionType.FRAGMENT;
builder.put(c, type);
c = '.';
type = ExpressionType.NAME_LABELS;
builder.put(c, type);
c = '/';
type = ExpressionType.PATH_SEGMENTS;
builder.put(c, type);
c = ';';
type = ExpressionType.PATH_PARAMETERS;
builder.put(c, type);
c = '?';
type = ExpressionType.QUERY_STRING;
builder.put(c, type);
c = '&';
type = ExpressionType.QUERY_CONT;
builder.put(c, type);
EXPRESSION_TYPE_MAP = builder.build();
}
@Override
public URITemplateExpression parse(final CharBuffer buffer)
throws URITemplateParseException
{
// Swallow the '{'
buffer.get();
/*
* Error if the buffer is empty after that
*/
if (!buffer.hasRemaining())
- throw new URITemplateParseException(UNEXPECTED_EOF, buffer,
- true);
+ throw new URITemplateParseException(UNEXPECTED_EOF, buffer, true);
/*
* If the next char is a known expression type, swallow it; otherwise,
* select SIMPLE.
*/
ExpressionType type = ExpressionType.SIMPLE;
char c = buffer.charAt(0);
if (EXPRESSION_TYPE_MAP.containsKey(c))
type = EXPRESSION_TYPE_MAP.get(buffer.get());
/*
* Now, swallow varspec by varspec.
*/
final List<VariableSpec> varspecs = Lists.newArrayList();
while (true) {
/*
* Swallow one varspec
*/
varspecs.add(VariableSpecParser.parse(buffer));
/*
* Error if the buffer is empty after that
*/
if (!buffer.hasRemaining())
throw new URITemplateParseException(UNEXPECTED_EOF, buffer,
true);
/*
* Grab next character
*/
c = buffer.get();
/*
* If it is a comma, swallow next varspec
*/
if (COMMA.matches(c))
continue;
/*
* If it is a closing bracket, we're done
*/
if (END_EXPRESSION.matches(c))
break;
/*
* If we reach this point, this is an error
*/
- throw new URITemplateParseException(UNEXPECTED_TOKEN, buffer,
- true);
+ throw new URITemplateParseException(UNEXPECTED_TOKEN, buffer, true);
}
return new TemplateExpression(type, varspecs);
}
}
| false | true | public URITemplateExpression parse(final CharBuffer buffer)
throws URITemplateParseException
{
// Swallow the '{'
buffer.get();
/*
* Error if the buffer is empty after that
*/
if (!buffer.hasRemaining())
throw new URITemplateParseException(UNEXPECTED_EOF, buffer,
true);
/*
* If the next char is a known expression type, swallow it; otherwise,
* select SIMPLE.
*/
ExpressionType type = ExpressionType.SIMPLE;
char c = buffer.charAt(0);
if (EXPRESSION_TYPE_MAP.containsKey(c))
type = EXPRESSION_TYPE_MAP.get(buffer.get());
/*
* Now, swallow varspec by varspec.
*/
final List<VariableSpec> varspecs = Lists.newArrayList();
while (true) {
/*
* Swallow one varspec
*/
varspecs.add(VariableSpecParser.parse(buffer));
/*
* Error if the buffer is empty after that
*/
if (!buffer.hasRemaining())
throw new URITemplateParseException(UNEXPECTED_EOF, buffer,
true);
/*
* Grab next character
*/
c = buffer.get();
/*
* If it is a comma, swallow next varspec
*/
if (COMMA.matches(c))
continue;
/*
* If it is a closing bracket, we're done
*/
if (END_EXPRESSION.matches(c))
break;
/*
* If we reach this point, this is an error
*/
throw new URITemplateParseException(UNEXPECTED_TOKEN, buffer,
true);
}
return new TemplateExpression(type, varspecs);
}
| public URITemplateExpression parse(final CharBuffer buffer)
throws URITemplateParseException
{
// Swallow the '{'
buffer.get();
/*
* Error if the buffer is empty after that
*/
if (!buffer.hasRemaining())
throw new URITemplateParseException(UNEXPECTED_EOF, buffer, true);
/*
* If the next char is a known expression type, swallow it; otherwise,
* select SIMPLE.
*/
ExpressionType type = ExpressionType.SIMPLE;
char c = buffer.charAt(0);
if (EXPRESSION_TYPE_MAP.containsKey(c))
type = EXPRESSION_TYPE_MAP.get(buffer.get());
/*
* Now, swallow varspec by varspec.
*/
final List<VariableSpec> varspecs = Lists.newArrayList();
while (true) {
/*
* Swallow one varspec
*/
varspecs.add(VariableSpecParser.parse(buffer));
/*
* Error if the buffer is empty after that
*/
if (!buffer.hasRemaining())
throw new URITemplateParseException(UNEXPECTED_EOF, buffer,
true);
/*
* Grab next character
*/
c = buffer.get();
/*
* If it is a comma, swallow next varspec
*/
if (COMMA.matches(c))
continue;
/*
* If it is a closing bracket, we're done
*/
if (END_EXPRESSION.matches(c))
break;
/*
* If we reach this point, this is an error
*/
throw new URITemplateParseException(UNEXPECTED_TOKEN, buffer, true);
}
return new TemplateExpression(type, varspecs);
}
|
diff --git a/src/net/java/sip/communicator/impl/neomedia/codec/video/h264/JNIEncoder.java b/src/net/java/sip/communicator/impl/neomedia/codec/video/h264/JNIEncoder.java
index 4fd749e5f..0b0abdfa8 100644
--- a/src/net/java/sip/communicator/impl/neomedia/codec/video/h264/JNIEncoder.java
+++ b/src/net/java/sip/communicator/impl/neomedia/codec/video/h264/JNIEncoder.java
@@ -1,341 +1,340 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.neomedia.codec.video.h264;
import java.awt.*;
import javax.media.*;
import javax.media.format.*;
import net.java.sip.communicator.impl.neomedia.codec.*;
import net.java.sip.communicator.impl.neomedia.codec.video.*;
import net.sf.fmj.media.*;
/**
* Encodes supplied data in h264
*
* @author Damian Minkov
* @author Lubomir Marinov
* @author Sebastien Vincent
*/
public class JNIEncoder
extends AbstractCodec
implements Codec
{
private static final String PLUGIN_NAME = "H.264 Encoder";
private static final int INPUT_BUFFER_PADDING_SIZE = 8;
private static final Format[] defOutputFormats =
{ new VideoFormat(Constants.H264) };
// the frame rate we will use
private static final int TARGET_FRAME_RATE = 15;
// The codec we will use
private long avcontext;
// the encoded data is stored in avpicture
private long avframe;
// we use this buffer to supply data to encoder
private byte[] encFrameBuffer;
// the supplied data length
private int encFrameLen;
private long rawFrameBuffer;
// key frame every four seconds
private static final int IFRAME_INTERVAL = TARGET_FRAME_RATE * 4;
private int framesSinceLastIFrame = IFRAME_INTERVAL + 1;
/**
* Constructor
*/
public JNIEncoder()
{
float sourceFrameRate = TARGET_FRAME_RATE;
inputFormats = new Format[1];
inputFormats[0] = new YUVFormat(null, -1, Format.byteArray,
sourceFrameRate, YUVFormat.YUV_420, -1, -1, 0, -1, -1);
inputFormat = null;
outputFormat = null;
}
private Format[] getMatchingOutputFormats(Format in)
{
VideoFormat videoIn = (VideoFormat) in;
Dimension inSize = videoIn.getSize();
return
new VideoFormat[]
{ new VideoFormat(Constants.H264, inSize, Format.NOT_SPECIFIED,
Format.byteArray, videoIn.getFrameRate()) };
}
/**
* Return the list of formats supported at the output.
*/
public Format[] getSupportedOutputFormats(Format in)
{
// null input format
if (in == null)
return defOutputFormats;
// mismatch input format
if (!(in instanceof VideoFormat)
|| (null == JNIDecoder.matches(in, inputFormats)))
return new Format[0];
return getMatchingOutputFormats(in);
}
@Override
public Format setInputFormat(Format in)
{
// mismatch input format
if (!(in instanceof VideoFormat)
|| null == JNIDecoder.matches(in, inputFormats))
return null;
VideoFormat videoIn = (VideoFormat) in;
Dimension inSize = videoIn.getSize();
if (inSize == null)
{
/* XXX code reached ? */
inSize = new Dimension(Constants.VIDEO_WIDTH, Constants.VIDEO_HEIGHT);
}
YUVFormat yuv = (YUVFormat) videoIn;
if (yuv.getOffsetU() > yuv.getOffsetV())
return null;
int strideY = inSize.width;
int strideUV = strideY / 2;
int offsetU = strideY * inSize.height;
int offsetV = offsetU + strideUV * inSize.height / 2;
int inputYuvLength = (strideY + strideUV) * inSize.height;
float sourceFrameRate = videoIn.getFrameRate();
inputFormat =
new YUVFormat(inSize, inputYuvLength + INPUT_BUFFER_PADDING_SIZE,
Format.byteArray, sourceFrameRate, YUVFormat.YUV_420, strideY,
strideUV, 0, offsetU, offsetV);
// Return the selected inputFormat
return inputFormat;
}
@Override
public Format setOutputFormat(Format out)
{
// mismatch output format
if (!(out instanceof VideoFormat)
|| null == JNIDecoder.matches(out,
getMatchingOutputFormats(inputFormat)))
return null;
VideoFormat videoOut = (VideoFormat) out;
Dimension outSize = videoOut.getSize();
if (outSize == null)
{
Dimension inSize = ((VideoFormat) inputFormat).getSize();
if (inSize == null)
{
/* XXX code reached ? */
outSize = new Dimension(Constants.VIDEO_WIDTH, Constants.VIDEO_HEIGHT);
}
else
outSize = inSize;
}
outputFormat =
new VideoFormat(videoOut.getEncoding(), outSize, outSize.width
* outSize.height, Format.byteArray, videoOut.getFrameRate());
// Return the selected outputFormat
return outputFormat;
}
public synchronized int process(Buffer inBuffer, Buffer outBuffer)
{
if (isEOM(inBuffer))
{
propagateEOM(outBuffer);
reset();
return BUFFER_PROCESSED_OK;
}
if (inBuffer.isDiscard())
{
outBuffer.setDiscard(true);
reset();
return BUFFER_PROCESSED_OK;
}
Format inFormat = inBuffer.getFormat();
if (inFormat != inputFormat && !(inFormat.matches(inputFormat)))
{
setInputFormat(inFormat);
}
if (inBuffer.getLength() < 10)
{
outBuffer.setDiscard(true);
reset();
return BUFFER_PROCESSED_OK;
}
// copy data to avframe
FFMPEG.memcpy(rawFrameBuffer, (byte[]) inBuffer.getData(), inBuffer
.getOffset(), encFrameLen);
if (framesSinceLastIFrame >= IFRAME_INTERVAL)
{
FFMPEG.avframe_set_key_frame(avframe, true);
framesSinceLastIFrame = 0;
}
else
{
framesSinceLastIFrame++;
FFMPEG.avframe_set_key_frame(avframe, false);
}
// encode data
int encLen =
FFMPEG.avcodec_encode_video(avcontext, encFrameBuffer, encFrameLen,
avframe);
byte[] r = new byte[encLen];
System.arraycopy(encFrameBuffer, 0, r, 0, r.length);
outBuffer.setData(r);
outBuffer.setLength(r.length);
outBuffer.setOffset(0);
return BUFFER_PROCESSED_OK;
}
@Override
public synchronized void open()
throws ResourceUnavailableException
{
int width = 0;
int height = 0;
if (opened)
return;
if (inputFormat == null)
throw new ResourceUnavailableException("No input format selected");
if (outputFormat == null)
throw new ResourceUnavailableException("No output format selected");
width = (int)((VideoFormat)outputFormat).getSize().getWidth();
height = (int)((VideoFormat)outputFormat).getSize().getHeight();
long avcodec = FFMPEG.avcodec_find_encoder(FFMPEG.CODEC_ID_H264);
avcontext = FFMPEG.avcodec_alloc_context();
FFMPEG.avcodeccontext_set_pix_fmt(avcontext, FFMPEG.PIX_FMT_YUV420P);
FFMPEG.avcodeccontext_set_size(avcontext, width, height);
FFMPEG.avcodeccontext_set_qcompress(avcontext, 0.6f);
//int _bitRate = 768000;
int _bitRate = 256000;
// average bit rate
FFMPEG.avcodeccontext_set_bit_rate(avcontext, _bitRate);
// so to be 1 in x264
FFMPEG.avcodeccontext_set_bit_rate_tolerance(avcontext, _bitRate);
FFMPEG.avcodeccontext_set_rc_max_rate(avcontext, _bitRate);
FFMPEG.avcodeccontext_set_sample_aspect_ratio(avcontext, 0, 0);
FFMPEG.avcodeccontext_set_thread_count(avcontext, 0);
FFMPEG.avcodeccontext_set_time_base(avcontext, 1000, 25500); // ???
FFMPEG.avcodeccontext_set_quantizer(avcontext, 10, 51, 4);
// avcontext.chromaoffset = -2;
FFMPEG.avcodeccontext_add_partitions(avcontext, 0x111);
// X264_PART_I4X4 0x001
// X264_PART_P8X8 0x010
// X264_PART_B8X8 0x100
FFMPEG.avcodeccontext_set_mb_decision(avcontext,
FFMPEG.FF_MB_DECISION_SIMPLE);
FFMPEG.avcodeccontext_set_rc_eq(avcontext, "blurCplx^(1-qComp)");
FFMPEG.avcodeccontext_add_flags(avcontext,
FFMPEG.CODEC_FLAG_LOOP_FILTER);
FFMPEG.avcodeccontext_set_me_method(avcontext, 1);
FFMPEG.avcodeccontext_set_me_subpel_quality(avcontext, 6);
FFMPEG.avcodeccontext_set_me_range(avcontext, 16);
FFMPEG.avcodeccontext_set_me_cmp(avcontext, FFMPEG.FF_CMP_CHROMA);
FFMPEG.avcodeccontext_set_scenechange_threshold(avcontext, 40);
// Constant quality mode (also known as constant ratefactor)
FFMPEG.avcodeccontext_set_crf(avcontext, 0);
FFMPEG.avcodeccontext_set_rc_buffer_size(avcontext, 0);
FFMPEG.avcodeccontext_set_gop_size(avcontext, IFRAME_INTERVAL);
FFMPEG.avcodeccontext_set_i_quant_factor(avcontext, 1f / 1.4f);
if (FFMPEG.avcodec_open(avcontext, avcodec) < 0)
throw new RuntimeException("Could not open codec");
encFrameLen = (width * height * 3) / 2;
rawFrameBuffer = FFMPEG.av_malloc(encFrameLen);
avframe = FFMPEG.avcodec_alloc_frame();
int size = width * height;
FFMPEG.avframe_set_data(avframe, rawFrameBuffer, size, size / 4);
- FFMPEG.avframe_set_linesize(avframe, width, height / 2,
- width / 2);
+ FFMPEG.avframe_set_linesize(avframe, width, width / 2, width / 2);
encFrameBuffer = new byte[encFrameLen];
opened = true;
super.open();
}
@Override
public synchronized void close()
{
if (opened)
{
opened = false;
super.close();
FFMPEG.avcodec_close(avcontext);
FFMPEG.av_free(avcontext);
avcontext = 0;
FFMPEG.av_free(avframe);
avframe = 0;
FFMPEG.av_free(rawFrameBuffer);
rawFrameBuffer = 0;
encFrameBuffer = null;
}
}
@Override
public String getName()
{
return PLUGIN_NAME;
}
}
| true | true | public synchronized void open()
throws ResourceUnavailableException
{
int width = 0;
int height = 0;
if (opened)
return;
if (inputFormat == null)
throw new ResourceUnavailableException("No input format selected");
if (outputFormat == null)
throw new ResourceUnavailableException("No output format selected");
width = (int)((VideoFormat)outputFormat).getSize().getWidth();
height = (int)((VideoFormat)outputFormat).getSize().getHeight();
long avcodec = FFMPEG.avcodec_find_encoder(FFMPEG.CODEC_ID_H264);
avcontext = FFMPEG.avcodec_alloc_context();
FFMPEG.avcodeccontext_set_pix_fmt(avcontext, FFMPEG.PIX_FMT_YUV420P);
FFMPEG.avcodeccontext_set_size(avcontext, width, height);
FFMPEG.avcodeccontext_set_qcompress(avcontext, 0.6f);
//int _bitRate = 768000;
int _bitRate = 256000;
// average bit rate
FFMPEG.avcodeccontext_set_bit_rate(avcontext, _bitRate);
// so to be 1 in x264
FFMPEG.avcodeccontext_set_bit_rate_tolerance(avcontext, _bitRate);
FFMPEG.avcodeccontext_set_rc_max_rate(avcontext, _bitRate);
FFMPEG.avcodeccontext_set_sample_aspect_ratio(avcontext, 0, 0);
FFMPEG.avcodeccontext_set_thread_count(avcontext, 0);
FFMPEG.avcodeccontext_set_time_base(avcontext, 1000, 25500); // ???
FFMPEG.avcodeccontext_set_quantizer(avcontext, 10, 51, 4);
// avcontext.chromaoffset = -2;
FFMPEG.avcodeccontext_add_partitions(avcontext, 0x111);
// X264_PART_I4X4 0x001
// X264_PART_P8X8 0x010
// X264_PART_B8X8 0x100
FFMPEG.avcodeccontext_set_mb_decision(avcontext,
FFMPEG.FF_MB_DECISION_SIMPLE);
FFMPEG.avcodeccontext_set_rc_eq(avcontext, "blurCplx^(1-qComp)");
FFMPEG.avcodeccontext_add_flags(avcontext,
FFMPEG.CODEC_FLAG_LOOP_FILTER);
FFMPEG.avcodeccontext_set_me_method(avcontext, 1);
FFMPEG.avcodeccontext_set_me_subpel_quality(avcontext, 6);
FFMPEG.avcodeccontext_set_me_range(avcontext, 16);
FFMPEG.avcodeccontext_set_me_cmp(avcontext, FFMPEG.FF_CMP_CHROMA);
FFMPEG.avcodeccontext_set_scenechange_threshold(avcontext, 40);
// Constant quality mode (also known as constant ratefactor)
FFMPEG.avcodeccontext_set_crf(avcontext, 0);
FFMPEG.avcodeccontext_set_rc_buffer_size(avcontext, 0);
FFMPEG.avcodeccontext_set_gop_size(avcontext, IFRAME_INTERVAL);
FFMPEG.avcodeccontext_set_i_quant_factor(avcontext, 1f / 1.4f);
if (FFMPEG.avcodec_open(avcontext, avcodec) < 0)
throw new RuntimeException("Could not open codec");
encFrameLen = (width * height * 3) / 2;
rawFrameBuffer = FFMPEG.av_malloc(encFrameLen);
avframe = FFMPEG.avcodec_alloc_frame();
int size = width * height;
FFMPEG.avframe_set_data(avframe, rawFrameBuffer, size, size / 4);
FFMPEG.avframe_set_linesize(avframe, width, height / 2,
width / 2);
encFrameBuffer = new byte[encFrameLen];
opened = true;
super.open();
}
| public synchronized void open()
throws ResourceUnavailableException
{
int width = 0;
int height = 0;
if (opened)
return;
if (inputFormat == null)
throw new ResourceUnavailableException("No input format selected");
if (outputFormat == null)
throw new ResourceUnavailableException("No output format selected");
width = (int)((VideoFormat)outputFormat).getSize().getWidth();
height = (int)((VideoFormat)outputFormat).getSize().getHeight();
long avcodec = FFMPEG.avcodec_find_encoder(FFMPEG.CODEC_ID_H264);
avcontext = FFMPEG.avcodec_alloc_context();
FFMPEG.avcodeccontext_set_pix_fmt(avcontext, FFMPEG.PIX_FMT_YUV420P);
FFMPEG.avcodeccontext_set_size(avcontext, width, height);
FFMPEG.avcodeccontext_set_qcompress(avcontext, 0.6f);
//int _bitRate = 768000;
int _bitRate = 256000;
// average bit rate
FFMPEG.avcodeccontext_set_bit_rate(avcontext, _bitRate);
// so to be 1 in x264
FFMPEG.avcodeccontext_set_bit_rate_tolerance(avcontext, _bitRate);
FFMPEG.avcodeccontext_set_rc_max_rate(avcontext, _bitRate);
FFMPEG.avcodeccontext_set_sample_aspect_ratio(avcontext, 0, 0);
FFMPEG.avcodeccontext_set_thread_count(avcontext, 0);
FFMPEG.avcodeccontext_set_time_base(avcontext, 1000, 25500); // ???
FFMPEG.avcodeccontext_set_quantizer(avcontext, 10, 51, 4);
// avcontext.chromaoffset = -2;
FFMPEG.avcodeccontext_add_partitions(avcontext, 0x111);
// X264_PART_I4X4 0x001
// X264_PART_P8X8 0x010
// X264_PART_B8X8 0x100
FFMPEG.avcodeccontext_set_mb_decision(avcontext,
FFMPEG.FF_MB_DECISION_SIMPLE);
FFMPEG.avcodeccontext_set_rc_eq(avcontext, "blurCplx^(1-qComp)");
FFMPEG.avcodeccontext_add_flags(avcontext,
FFMPEG.CODEC_FLAG_LOOP_FILTER);
FFMPEG.avcodeccontext_set_me_method(avcontext, 1);
FFMPEG.avcodeccontext_set_me_subpel_quality(avcontext, 6);
FFMPEG.avcodeccontext_set_me_range(avcontext, 16);
FFMPEG.avcodeccontext_set_me_cmp(avcontext, FFMPEG.FF_CMP_CHROMA);
FFMPEG.avcodeccontext_set_scenechange_threshold(avcontext, 40);
// Constant quality mode (also known as constant ratefactor)
FFMPEG.avcodeccontext_set_crf(avcontext, 0);
FFMPEG.avcodeccontext_set_rc_buffer_size(avcontext, 0);
FFMPEG.avcodeccontext_set_gop_size(avcontext, IFRAME_INTERVAL);
FFMPEG.avcodeccontext_set_i_quant_factor(avcontext, 1f / 1.4f);
if (FFMPEG.avcodec_open(avcontext, avcodec) < 0)
throw new RuntimeException("Could not open codec");
encFrameLen = (width * height * 3) / 2;
rawFrameBuffer = FFMPEG.av_malloc(encFrameLen);
avframe = FFMPEG.avcodec_alloc_frame();
int size = width * height;
FFMPEG.avframe_set_data(avframe, rawFrameBuffer, size, size / 4);
FFMPEG.avframe_set_linesize(avframe, width, width / 2, width / 2);
encFrameBuffer = new byte[encFrameLen];
opened = true;
super.open();
}
|
diff --git a/test-modules/functional-tests/src/test/java/org/openlmis/functional/ConvertToOrderPagination.java b/test-modules/functional-tests/src/test/java/org/openlmis/functional/ConvertToOrderPagination.java
index d9c3101617..cb67902598 100644
--- a/test-modules/functional-tests/src/test/java/org/openlmis/functional/ConvertToOrderPagination.java
+++ b/test-modules/functional-tests/src/test/java/org/openlmis/functional/ConvertToOrderPagination.java
@@ -1,327 +1,329 @@
/*
* 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 cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Then;
import org.openlmis.UiUtils.CaptureScreenshotOnFailureListener;
import org.openlmis.UiUtils.TestCaseHelper;
import org.openlmis.UiUtils.TestWebDriver;
import org.openlmis.pageobjects.ConvertOrderPage;
import org.openlmis.pageobjects.HomePage;
import org.openlmis.pageobjects.LoginPage;
import org.openlmis.pageobjects.ViewOrdersPage;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.testng.annotations.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import static com.thoughtworks.selenium.SeleneseTestBase.assertTrue;
import static com.thoughtworks.selenium.SeleneseTestNgHelper.assertEquals;
@TransactionConfiguration(defaultRollback = true)
@Transactional
@Listeners(CaptureScreenshotOnFailureListener.class)
public class ConvertToOrderPagination extends TestCaseHelper {
@BeforeMethod(groups = "requisition")
@Before
public void setUp() throws Exception {
super.setup();
}
@And("^I have \"([^\"]*)\" requisitions for convert to order$")
public void haveRequisitionsToBeConvertedToOrder(String requisitions) throws IOException, SQLException {
String userSIC = "storeIncharge";
setUpData("HIV", userSIC);
dbWrapper.insertRequisitions(Integer.parseInt(requisitions), "MALARIA", true);
dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "MALARIA");
dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "MALARIA");
dbWrapper.insertApprovedQuantity(10);
dbWrapper.updatePacksToShip("1");
dbWrapper.insertFulfilmentRoleAssignment(userSIC, "store in-charge", "F10");
}
@And("^I select \"([^\"]*)\" requisition on page \"([^\"]*)\"$")
public void selectRequisition(String numberOfRequisitions, String page) throws IOException, SQLException {
testWebDriver.sleep(5000);
testWebDriver.handleScrollByPixels(0, 1000);
String url = ((JavascriptExecutor) TestWebDriver.getDriver()).executeScript("return window.location.href").toString();
url = url.substring(0, url.length() - 1) + page;
testWebDriver.getUrl(url);
selectRequisitionToBeConvertedToOrder(Integer.parseInt(numberOfRequisitions));
}
@And("^I access convert to order$")
public void accessConvertToOrder() throws IOException, SQLException {
ConvertOrderPage convertOrderPage = new ConvertOrderPage(testWebDriver);
convertToOrder(convertOrderPage);
}
@Then("^\"([^\"]*)\" requisition converted to order$")
public void requisitionConvertedToOrder(String requisitions) throws IOException, SQLException {
HomePage homePage = new HomePage(testWebDriver);
ViewOrdersPage viewOrdersPage = homePage.navigateViewOrders();
int numberOfLineItems = viewOrdersPage.getNumberOfLineItems();
assertTrue("Number of line items on view order screen should be equal to " + Integer.parseInt(requisitions), numberOfLineItems == Integer.parseInt(requisitions));
}
@Test(groups = {"requisition"}, dataProvider = "Data-Provider-Function-Positive")
public void shouldConvertOnlyCurrentPageRequisitions(String program, String userSIC, String password) throws Exception {
setUpData(program, userSIC);
dbWrapper.insertRequisitions(50, "MALARIA", true);
dbWrapper.insertRequisitions(1, "TB", true);
dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "MALARIA");
dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "TB");
dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "MALARIA");
dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "TB");
+ dbWrapper.insertApprovedQuantity(10);
+ dbWrapper.updatePacksToShip("1");
dbWrapper.insertFulfilmentRoleAssignment("storeIncharge", "store in-charge", "F10");
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
ConvertOrderPage convertOrderPage = homePage.navigateConvertToOrder();
verifyNumberOfPageLinks(51, 50);
verifyNextAndLastLinksEnabled();
verifyPreviousAndFirstLinksDisabled();
clickPageNumberLink(2);
verifyPageLinksFromLastPage();
verifyPreviousAndFirstLinksEnabled();
verifyNextAndLastLinksDisabled();
selectRequisitionToBeConvertedToOrder(1);
clickPageNumberLink(1);
selectRequisitionToBeConvertedToOrder(1);
convertToOrder(convertOrderPage);
verifyNumberOfPageLinks(49, 50);
ViewOrdersPage viewOrdersPage = homePage.navigateViewOrders();
int numberOfLineItems = viewOrdersPage.getNumberOfLineItems();
assertTrue("Number of line items on view order screen should be equal to 1", numberOfLineItems == 1);
viewOrdersPage.verifyProgram(1, "MALARIA");
}
private void clickPageNumberLink(int pageNumber) {
testWebDriver.getElementByXpath("//a[contains(text(), '" + pageNumber + "') and @class='ng-binding']").click();
testWebDriver.sleep(2000);
}
@Test(groups = {"requisition"}, dataProvider = "Data-Provider-Function-Positive")
public void shouldVerifyIntroductionOfPagination(String program, String userSIC, String password) throws Exception {
setUpData(program, userSIC);
dbWrapper.insertRequisitions(49, "MALARIA", true);
dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "MALARIA");
dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "MALARIA");
dbWrapper.insertFulfilmentRoleAssignment("storeIncharge", "store in-charge", "F10");
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
homePage.navigateConvertToOrder();
verifyNumberOfPageLinks(49, 50);
dbWrapper.insertRequisitions(2, "HIV", true);
dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "HIV");
dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "HIV");
homePage.navigateHomePage();
homePage.navigateConvertToOrder();
verifyNumberOfPageLinks(51, 50);
}
@Test(groups = {"requisition"}, dataProvider = "Data-Provider-Function-Positive")
public void shouldVerifyIntroductionOfPaginationForBoundaryValue(String program, String userSIC, String password) throws Exception {
setUpData(program, userSIC);
dbWrapper.insertRequisitions(50, "MALARIA", true);
dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "MALARIA");
dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "MALARIA");
dbWrapper.insertFulfilmentRoleAssignment("storeIncharge", "store in-charge", "F10");
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
homePage.navigateConvertToOrder();
verifyNumberOfPageLinks(50, 50);
verifyPageLinkNotPresent(2);
dbWrapper.insertRequisitions(1, "HIV", true);
dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "HIV");
dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "HIV");
homePage.navigateHomePage();
homePage.navigateConvertToOrder();
verifyNumberOfPageLinks(51, 50);
}
@Test(groups = {"requisition"}, dataProvider = "Data-Provider-Function-Positive")
public void shouldVerifySearch(String program, String userSIC, String password) throws Exception {
setUpData(program, userSIC);
dbWrapper.insertRequisitions(55, "MALARIA", true);
dbWrapper.insertRequisitions(40, "TB", true);
dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "MALARIA");
dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "TB");
dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "MALARIA");
dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "TB");
dbWrapper.insertFulfilmentRoleAssignment("storeIncharge", "store in-charge", "F10");
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
ConvertOrderPage convertOrderPage = homePage.navigateConvertToOrder();
verifyNumberOfPageLinks(80, 50);
convertOrderPage.searchWithOption("All", "TB");
verifyNumberOfPageLinks(40, 50);
verifyProgramInGrid(40, 50, "TB");
verifyPageLinkNotPresent(2);
convertOrderPage.searchWithOption("All", "MALARIA");
verifyNumberOfPageLinks(55, 50);
verifyProgramInGrid(55, 50, "MALARIA");
}
@Test(groups = {"requisition"}, dataProvider = "Data-Provider-Function-Positive")
public void shouldVerifySearchWithDifferentOptions(String program, String userSIC, String password) throws Exception {
setUpData(program, userSIC);
dbWrapper.insertRequisitions(55, "MALARIA", true);
dbWrapper.insertRequisitions(40, "TB", false);
dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "MALARIA");
dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "TB");
dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "MALARIA");
dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "TB");
dbWrapper.insertFulfilmentRoleAssignment("storeIncharge", "store in-charge", "F10");
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
ConvertOrderPage convertOrderPage = homePage.navigateConvertToOrder();
convertOrderPage.searchWithIndex(5, "Village Dispensary");
verifyNumberOfPageLinks(55, 50);
verifySupplyingDepotInGrid(55, 50, "Village Dispensary");
}
private void setUpData(String program, String userSIC) throws SQLException, IOException {
setupProductTestData("P10", "P11", program, "Lvl3 Hospital");
dbWrapper.insertFacilities("F10", "F11");
dbWrapper.configureTemplate(program);
List<String> rightsList = new ArrayList<String>();
rightsList.add("CONVERT_TO_ORDER");
rightsList.add("VIEW_ORDER");
setupTestUserRoleRightsData("200", userSIC, rightsList);
dbWrapper.insertSupervisoryNode("F10", "N1", "Node 1", "null");
dbWrapper.insertRoleAssignment("200", "store in-charge");
dbWrapper.insertSchedule("Q1stM", "QuarterMonthly", "QuarterMonth");
dbWrapper.insertSchedule("M", "Monthly", "Month");
dbWrapper.insertProcessingPeriod("Period1", "first period", "2012-12-01", "2013-01-15", 1, "Q1stM");
dbWrapper.insertProcessingPeriod("Period2", "second period", "2013-01-16", "2013-01-30", 1, "M");
setupRequisitionGroupData("RG1", "RG2", "N1", "N2", "F10", "F11");
dbWrapper.insertSupplyLines("N1", program, "F10", true);
}
public void selectRequisitionToBeConvertedToOrder(int whichRequisition) {
testWebDriver.waitForPageToLoad();
List <WebElement> x= testWebDriver.getElementsByXpath("//input[@class='ngSelectionCheckbox']");
testWebDriver.waitForElementToAppear(x.get(whichRequisition - 1));
x.get(whichRequisition-1).click();
}
private void convertToOrder(ConvertOrderPage convertOrderPage) {
convertOrderPage.clickConvertToOrderButton();
convertOrderPage.clickOk();
}
public void verifyProgramInGrid(int numberOfProducts, int numberOfLineItemsPerPage, String program) throws Exception {
int numberOfPages = numberOfProducts / numberOfLineItemsPerPage;
if (numberOfProducts % numberOfLineItemsPerPage != 0) {
numberOfPages = numberOfPages + 1;
}
int trackPages = 0;
while (numberOfPages != trackPages) {
testWebDriver.getElementByXpath("//a[contains(text(), '" + (trackPages + 1) + "') and @class='ng-binding']").click();
testWebDriver.waitForPageToLoad();
for (int i = 1; i < testWebDriver.getElementsSizeByXpath("//div[@class='ngCanvas']/div"); i++)
assertEquals(testWebDriver.getElementByXpath("//div[@class='ngCanvas']/div[" + i + "]/div[2]/div[2]/div/span").getText().trim(), program);
trackPages++;
}
}
public void verifySupplyingDepotInGrid(int numberOfProducts, int numberOfLineItemsPerPage, String supplyingDepot) throws Exception {
int numberOfPages = numberOfProducts / numberOfLineItemsPerPage;
if (numberOfProducts % numberOfLineItemsPerPage != 0) {
numberOfPages = numberOfPages + 1;
}
int trackPages = 0;
while (numberOfPages != trackPages) {
testWebDriver.getElementByXpath("//a[contains(text(), '" + (trackPages + 1) + "') and @class='ng-binding']").click();
testWebDriver.waitForPageToLoad();
for (int i = 1; i < testWebDriver.getElementsSizeByXpath("//div[@class='ngCanvas']/div"); i++)
assertEquals(testWebDriver.getElementByXpath("//div[@class='ngCanvas']/div[" + i + "]/div[9]/div[2]/div/span").getText().trim(), supplyingDepot);
trackPages++;
}
}
public void verifyPageLinkNotPresent(int i) throws Exception {
boolean flag = false;
try {
testWebDriver.getElementByXpath("//a[contains(text(), '" + i + "') and @class='ng-binding']").click();
} catch (NoSuchElementException e) {
flag = true;
} catch (ElementNotVisibleException e) {
flag = true;
}
assertTrue("Link number" + i + " should not appear", flag);
}
@Test(groups = {"requisition"}, dataProvider = "Data-Provider-Function-Positive")
public void VerifyConvertToOrderAccessOnRequisition(String program, String userSIC, String password) throws Exception {
setUpData(program, userSIC);
dbWrapper.insertRequisitions(50, "MALARIA", true);
dbWrapper.insertRequisitions(1, "TB", true);
dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "MALARIA");
dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "TB");
dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "MALARIA");
dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "TB");
dbWrapper.insertFulfilmentRoleAssignment("storeIncharge", "store in-charge", "F10");
dbWrapper.updateSupplyLines("F10", "F11");
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
ConvertOrderPage convertOrderPage = homePage.navigateConvertToOrder();
assertEquals("No requisitions to be converted to orders", convertOrderPage.getNoRequisitionPendingMessage());
}
@AfterMethod(groups = "requisition")
@After
public void tearDown() throws Exception {
testWebDriver.sleep(500);
if (!testWebDriver.getElementById("username").isDisplayed()) {
HomePage homePage = new HomePage(testWebDriver);
homePage.logout(baseUrlGlobal);
dbWrapper.deleteData();
dbWrapper.closeConnection();
}
}
@DataProvider(name = "Data-Provider-Function-Positive")
public Object[][] parameterIntTestProviderPositive() {
return new Object[][]{
{"HIV", "storeIncharge", "Admin123"}
};
}
}
| true | true | public void shouldConvertOnlyCurrentPageRequisitions(String program, String userSIC, String password) throws Exception {
setUpData(program, userSIC);
dbWrapper.insertRequisitions(50, "MALARIA", true);
dbWrapper.insertRequisitions(1, "TB", true);
dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "MALARIA");
dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "TB");
dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "MALARIA");
dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "TB");
dbWrapper.insertFulfilmentRoleAssignment("storeIncharge", "store in-charge", "F10");
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
ConvertOrderPage convertOrderPage = homePage.navigateConvertToOrder();
verifyNumberOfPageLinks(51, 50);
verifyNextAndLastLinksEnabled();
verifyPreviousAndFirstLinksDisabled();
clickPageNumberLink(2);
verifyPageLinksFromLastPage();
verifyPreviousAndFirstLinksEnabled();
verifyNextAndLastLinksDisabled();
selectRequisitionToBeConvertedToOrder(1);
clickPageNumberLink(1);
selectRequisitionToBeConvertedToOrder(1);
convertToOrder(convertOrderPage);
verifyNumberOfPageLinks(49, 50);
ViewOrdersPage viewOrdersPage = homePage.navigateViewOrders();
int numberOfLineItems = viewOrdersPage.getNumberOfLineItems();
assertTrue("Number of line items on view order screen should be equal to 1", numberOfLineItems == 1);
viewOrdersPage.verifyProgram(1, "MALARIA");
}
| public void shouldConvertOnlyCurrentPageRequisitions(String program, String userSIC, String password) throws Exception {
setUpData(program, userSIC);
dbWrapper.insertRequisitions(50, "MALARIA", true);
dbWrapper.insertRequisitions(1, "TB", true);
dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "MALARIA");
dbWrapper.updateRequisitionStatus("SUBMITTED", userSIC, "TB");
dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "MALARIA");
dbWrapper.updateRequisitionStatus("APPROVED", userSIC, "TB");
dbWrapper.insertApprovedQuantity(10);
dbWrapper.updatePacksToShip("1");
dbWrapper.insertFulfilmentRoleAssignment("storeIncharge", "store in-charge", "F10");
LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal);
HomePage homePage = loginPage.loginAs(userSIC, password);
ConvertOrderPage convertOrderPage = homePage.navigateConvertToOrder();
verifyNumberOfPageLinks(51, 50);
verifyNextAndLastLinksEnabled();
verifyPreviousAndFirstLinksDisabled();
clickPageNumberLink(2);
verifyPageLinksFromLastPage();
verifyPreviousAndFirstLinksEnabled();
verifyNextAndLastLinksDisabled();
selectRequisitionToBeConvertedToOrder(1);
clickPageNumberLink(1);
selectRequisitionToBeConvertedToOrder(1);
convertToOrder(convertOrderPage);
verifyNumberOfPageLinks(49, 50);
ViewOrdersPage viewOrdersPage = homePage.navigateViewOrders();
int numberOfLineItems = viewOrdersPage.getNumberOfLineItems();
assertTrue("Number of line items on view order screen should be equal to 1", numberOfLineItems == 1);
viewOrdersPage.verifyProgram(1, "MALARIA");
}
|
diff --git a/src/main/java/jannovar/Jannovar.java b/src/main/java/jannovar/Jannovar.java
index 5b1ecc22..f5dd15fe 100644
--- a/src/main/java/jannovar/Jannovar.java
+++ b/src/main/java/jannovar/Jannovar.java
@@ -1,953 +1,955 @@
package jannovar;
/** Command line functions from apache */
import jannovar.annotation.Annotation;
import jannovar.annotation.AnnotationList;
import jannovar.common.ChromosomeMap;
import jannovar.common.Constants;
import jannovar.common.Constants.Release;
import jannovar.exception.AnnotationException;
import jannovar.exception.FileDownloadException;
import jannovar.exception.InvalidAttributException;
import jannovar.exception.JannovarException;
import jannovar.exception.VCFParseException;
import jannovar.exome.Variant;
import jannovar.io.EnsemblFastaParser;
import jannovar.io.FastaParser;
import jannovar.io.GFFparser;
import jannovar.io.RefSeqFastaParser;
import jannovar.io.SerializationManager;
import jannovar.io.TranscriptDataDownloader;
import jannovar.io.UCSCKGParser;
import jannovar.io.VCFLine;
import jannovar.io.VCFReader;
import jannovar.reference.Chromosome;
import jannovar.reference.TranscriptModel;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.Parser;
/**
* This is the driver class for a program called Jannovar. It has two purposes
* <OL>
* <LI>Take the UCSC files knownGene.txt, kgXref.txt, knownGeneMrna.txt, and
* knownToLocusLink.txt, and to create corresponding
* {@link jannovar.reference.TranscriptModel TranscriptModel} objects and to
* serialize them. The resulting serialized file can be used both by this
* program itself (see next item) or by the main Exomizer program to annotated
* VCF file.
* <LI>Using the serialized file of {@link jannovar.reference.TranscriptModel
* TranscriptModel} objects (see above item) annotate a VCF file using
* annovar-type program logic. Note that this functionality is also used by the
* main Exomizer program and thus this program can be used as a stand-alone
* annotator ("Jannovar") or as a way of testing the code for the Exomizer.
* </OL>
* <P>
* To run the "Jannovar" executable:
* <P>
* {@code java -Xms1G -Xmx1G -jar Jannovar.jar -V xyz.vcf -D $SERIAL}
* <P>
* This will annotate a VCF file. The results of jannovar annotation are shown
* in the form
*
* <PRE>
* Annotation {original VCF line}
* </PRE>
* <P>
* Just a reminder, to set up annovar to do this, use the following commands.
*
* <PRE>
* perl annotate_variation.pl --downdb knownGene --buildver hg19 humandb/
* </PRE>
*
* then, to annotate a VCF file called BLA.vcf, we first need to convert it to
* Annovar input format and run the main annovar program as follows.
*
* <PRE>
* $ perl convert2annovar.pl BLA.vcf -format vcf4 > BLA.av
* $ perl annotate_variation.pl -buildver hg19 --geneanno BLA.av --dbtype knowngene humandb/
* </PRE>
*
* This will create two files with all variants and a special file with exonic
* variants.
* <p>
* There are three ways of using this program.
* <ol>
* <li>To create a serialized version of the UCSC gene definition data. In this
* case, the command-line flag <b>- S</b> is provide as is the path to the four
* UCSC files. Then, {@code anno.serialize()} is true and a file <b>ucsc.ser</b>
* is created.
* <li>To deserialize the serialized data (<b>ucsc.ser</b>). In this case, the
* flag <b>- D</b> must be used.
* <li>To simply read in the UCSC data without creating a serialized file.
* </ol>
* Whichever of the three versions is chosen, the user may additionally pass the
* path to a VCF file using the <b>-v</b> flag. If so, then this file will be
* annotated using the UCSC data, and a new version of the file will be written
* to a file called test.vcf.jannovar (assuming the original file was named
* test.vcf). The
*
* @author Peter N Robinson
* @version 0.33 (29 December, 2013)
*/
public class Jannovar {
/**
* Location of a directory which will be used as download directory with
* subfolders (by genome release e.g. hg19,mm9) in whichthe files defining
* the transcript models will be stored. (the files may or may not be
* compressed with gzip). The same variable is also used to indicate the
* output location of the serialized file. The default value is "data/hg19/"
*/
private String dirPath = null;
/**
* Flag to indicate that Jannovar should download known gene definitions
* files from the UCSC server.
*/
private boolean createUCSC;
/**
* Flag to indicate Jannovar should download transcript definition files for
* RefSeq.
*/
private boolean createRefseq;
/**
* Flag to indicate Jannovar should download transcript definition files for
* Ensembl.
*/
private boolean createEnsembl;
/** List of all lines from knownGene.txt file from UCSC */
private ArrayList<TranscriptModel> transcriptModelList = null;
/** Map of Chromosomes */
private HashMap<Byte, Chromosome> chromosomeMap = null;
/** List of variants from input file to be analysed. */
private final ArrayList<Variant> variantList = null;
/** Name of the UCSC serialized data file that will be created by Jannovar. */
private static final String UCSCserializationFileName = "ucsc_%s.ser";
/**
* Name of the Ensembl serialized data file that will be created by
* Jannovar.
*/
private static final String EnsemblSerializationFileName = "ensembl_%s.ser";
/**
* Name of the refSeq serialized data file that will be created by Jannovar.
*/
private static final String RefseqSerializationFileName = "refseq_%s.ser";
/**
* Flag to indicate that Jannovar should serialize the UCSC data. This flag
* is set to true automatically if the user enters --create-ucsc (then, the
* four files are downloaded and subsequently serialized). If the user
* enters the flag {@code -U path}, then Jannovar interprets path as the
* location of a directory that already contains the UCSC files (either
* compressed or uncompressed), and sets this flag to true to perform
* serialization and then to exit. The name of the serialized file that gets
* created is "ucsc.ser" (this cannot be changed from the command line, see
* {@link #UCSCserializationFileName}).
*/
private boolean performSerialization = false;
/**
* Name of file with serialized UCSC data. This should be the complete path
* to the file, and will be used for annotating VCF files.
*/
private String serializedFile = null;
/** Path to a VCF file waiting to be annotated. */
private String VCFfilePath = null;
/** An FTP proxy for downloading the UCSC files from behind a firewall. */
private String proxy = null;
/** An FTP proxy port for downloading the UCSC files from behind a firewall. */
private String proxyPort = null;
/**
* Flag indicating whether to output annotations in Jannovar format
* (default: false).
*/
private boolean jannovarFormat;
/**
* Flag indication whether the annotations for all affected transcripts
* should be reported.
*/
private boolean showAll;
/**
* genome release for the download and the creation of the serialized
* transcript model file
*/
private Release genomeRelease = Release.HG19;
/** Output folder for the annotated VCF files (default: current folder) */
private String outVCFfolder = null;
/** chromosomal position an NA change (e.g. chr1:12345C>A) */
private String chromosomalChange;
public static void main(String argv[]) {
Jannovar anno = new Jannovar(argv);
/*
* Option 1. Download the UCSC files from the server, create the
* ucsc.ser file, and return.
*/
try {
if (anno.createUCSC()) {
anno.downloadTranscriptFiles(jannovar.common.Constants.UCSC, anno.genomeRelease);
anno.inputTranscriptModelDataFromUCSCFiles();
anno.serializeUCSCdata();
return;
} else if (anno.createEnsembl()) {
anno.downloadTranscriptFiles(jannovar.common.Constants.ENSEMBL, anno.genomeRelease);
anno.inputTranscriptModelDataFromEnsembl();
anno.serializeEnsemblData();
return;
} else if (anno.createRefseq()) {
anno.downloadTranscriptFiles(jannovar.common.Constants.REFSEQ, anno.genomeRelease);
anno.inputTranscriptModelDataFromRefseq();
anno.serializeRefseqData();
return;
}
} catch (JannovarException e) {
System.err.println("[ERROR] Error while attempting to download transcript definition files.");
System.err.println("[ERROR] " + e.toString());
System.err.println("[ERROR] A common error is the failure to set the network proxy (see tutorial).");
System.exit(1);
}
/*
* Option 2. The user must provide the ucsc.ser file to do analysis. (or
* the ensembl.ser or refseq.ser files). We can either annotate a VCF
* file (3a) or create a separate annotation file (3b).
*/
if (anno.deserialize()) {
try {
anno.deserializeTranscriptDefinitionFile();
} catch (JannovarException je) {
System.out.println("[ERROR] Could not deserialize UCSC data: " + je.toString());
System.exit(1);
}
} else {
System.err.println("[ERROR] You need to pass ucscs.ser file to perform analysis.");
usage();
System.exit(1);
}
/*
* When we get here, the program has deserialized data and put it into
* the Chromosome objects. We can now start to annotate variants.
*/
if (anno.hasVCFfile()) {
try {
anno.annotateVCF(); /* 3a or 3b */
} catch (JannovarException je) {
System.out.println("[ERROR] Could not annotate VCF data: " + je.toString());
System.exit(1);
}
} else {
if (anno.chromosomalChange == null) {
System.out.println("[ERROR] No VCF file found and no chromosomal position and variation was found");
} else {
try {
anno.annotatePosition();
} catch (JannovarException je) {
System.out.println("[ERROR] Could not annotate input data: " + anno.chromosomalChange);
System.exit(1);
}
}
}
}
/**
* The constructor parses the command-line arguments.
*
* @param argv
* the arguments passed through the command
*/
public Jannovar(String argv[]) {
parseCommandLineArguments(argv);
if (!this.dirPath.endsWith(System.getProperty("file.separator")))
this.dirPath += System.getProperty("file.separator");
if (this.outVCFfolder != null && !this.outVCFfolder.endsWith(System.getProperty("file.separator")))
this.outVCFfolder += System.getProperty("file.separator");
}
/**
* @return true if user wants to download UCSC files
*/
public boolean createUCSC() {
return this.createUCSC;
}
/**
* @return true if user wants to download refseq files
*/
public boolean createRefseq() {
return this.createRefseq;
}
/**
* @return true if user wants to download ENSEMBL files
*/
public boolean createEnsembl() {
return this.createEnsembl;
}
/**
* This function creates a {@link TranscriptDataDownloader} object in order
* to download the required transcript data files. If the user has set the
* proxy and proxy port via the command line, we use these to download the
* files.
*
* @param source
* the source of the transcript data (e.g. RefSeq, Ensembl, UCSC)
* @param rel
* the genome {@link Release}
*/
public void downloadTranscriptFiles(int source, Release rel) {
TranscriptDataDownloader downloader;
try {
if (this.proxy != null && this.proxyPort != null) {
downloader = new TranscriptDataDownloader(this.dirPath + genomeRelease.getUCSCString(genomeRelease), this.proxy, this.proxyPort);
} else {
downloader = new TranscriptDataDownloader(this.dirPath + genomeRelease.getUCSCString(genomeRelease));
}
downloader.downloadTranscriptFiles(source, rel);
} catch (FileDownloadException e) {
System.err.println(e);
System.exit(1);
}
}
/**
* @return true if we should serialize the UCSC data.
*/
public boolean serialize() {
return this.performSerialization;
}
/**
* @return true if we should deserialize a file with UCSC data to perform
* analysis
*/
public boolean deserialize() {
return this.serializedFile != null;
}
/**
* @return true if we should annotate a VCF file
*/
public boolean hasVCFfile() {
return this.VCFfilePath != null;
}
/**
* Annotate a single line of a VCF file, and output the line together with
* the new INFO fields representing the annotations.
*
* @param line
* an object representing the original VCF line
* @param v
* the Variant object that was parsed from the line
* @param out
* A file handle to write to.
*/
private void annotateVCFLine(VCFLine line, Variant v, Writer out) throws IOException, AnnotationException {
byte chr = v.getChromosomeAsByte();
int pos = v.get_position();
String ref = v.get_ref();
String alt = v.get_alt();
if (alt.charAt(0) == '[' || alt.charAt(0) == ']') {
out.write(line.getOriginalVCFLine() + "\n");
} else {
Chromosome c = chromosomeMap.get(chr);
if (c == null) {
String e = String.format("Could not identify chromosome \"%d\"", chr);
throw new AnnotationException(e);
}
AnnotationList anno = c.getAnnotationList(pos, ref, alt);
if (anno == null) {
String e = String.format("No annotations found for variant %s", v.toString());
throw new AnnotationException(e);
}
String annotation;
String effect;
if (this.showAll) {
annotation = anno.getAllTranscriptAnnotations();
effect = anno.getAllTranscriptVariantEffects();
} else {
annotation = anno.getSingleTranscriptAnnotation();
effect = anno.getVariantType().toString();
}
String A[] = line.getOriginalVCFLine().split("\t");
for (int i = 0; i < 7; ++i)
out.write(A[i] + "\t");
/* Now add the stuff to the INFO line */
String INFO;
/*
* The if clause is necessary to avoid writing a final ";" if the
* INFO lineis empty, which wouldbe invalid VCF format.
*/
if (A[7].length() > 0)
INFO = String.format("EFFECT=%s;HGVS=%s;%s", effect, annotation, A[7]);
else
INFO = String.format("EFFECT=%s;HGVS=%s", effect, annotation, A[7]);
out.write(INFO + "\t");
for (int i = 8; i < A.length; ++i)
out.write(A[i] + "\t");
out.write("\n");
}
}
/**
* This function outputs a single line in Jannovar format.
*
* @param n
* The current number (one for each variant in the VCF file)
* @param v
* The current variant with one or more annotations
* @param out
* File handle to write Jannovar file.
*/
private void outputJannovarLine(int n, Variant v, Writer out) throws IOException, AnnotationException {
byte chr = v.getChromosomeAsByte();
String chrStr = v.get_chromosome_as_string();
int pos = v.get_position();
String ref = v.get_ref();
String alt = v.get_alt();
String gtype = v.getGenotypeAsString();
float qual = v.getVariantPhredScore();
Chromosome c = chromosomeMap.get(chr);
if (c == null) {
String e = String.format("Could not identify chromosome \"%d\"", chr);
throw new AnnotationException(e);
}
AnnotationList anno = c.getAnnotationList(pos, ref, alt);
if (anno == null) {
String e = String.format("No annotations found for variant %s", v.toString());
throw new AnnotationException(e);
}
ArrayList<Annotation> lst = anno.getAnnotationList();
for (Annotation a : lst) {
String effect = a.getVariantTypeAsString();
String annt = a.getVariantAnnotation();
String sym = a.getGeneSymbol();
String s = String.format("%d\t%s\t%s\t%s\t%s\t%d\t%s\t%s\t%s\t%.1f", n, effect, sym, annt, chrStr, pos, ref, alt, gtype, qual);
out.write(s + "\n");
}
}
/**
* This function outputs a VCF file that corresponds to the original VCF
* file but additionally has annotations for each variant. A new file is
* created with the suffix "jv.vcf";
*/
private void outputAnnotatedVCF(VCFReader parser) throws JannovarException {
File f = new File(this.VCFfilePath);
String outname = f.getName();
if (outVCFfolder != null)
outname = outVCFfolder + outname;
int i = outname.lastIndexOf("vcf");
if (i < 0) {
i = outname.lastIndexOf("VCF");
}
if (i < 0) {
outname = outname + ".jv.vcf";
} else {
outname = outname.substring(0, i) + "jv.vcf";
}
try {
FileWriter fstream = new FileWriter(outname);
BufferedWriter out = new BufferedWriter(fstream);
/** Write the header of the new VCF file */
ArrayList<String> lst = parser.getAnnotatedVCFHeader();
for (String s : lst) {
out.write(s + "\n");
}
/** Now write each of the variants. */
Iterator<VCFLine> iter = parser.getVCFLineIterator();
while (iter.hasNext()) {
VCFLine line = iter.next();
Variant v = line.toVariant();
try {
annotateVCFLine(line, v, out);
} catch (AnnotationException e) {
System.out.println("[WARN] Annotation error: " + e.toString());
}
}
out.close();
} catch (IOException e) {
System.out.println("[ERROR] Error writing annotated VCF file");
System.out.println("[ERROR] " + e.toString());
System.exit(1);
}
System.out.println("[INFO] Wrote annotated VCF file to \"" + outname + "\"");
}
/**
* This function writes detailed annotations to file. One annotation is
* written for each of the transcripts affected by a variant, and the file
* is a tab-separated file in "Jannovar" format.
*
* @param parser
* The VCFParser that has extracted a list of variants from the
* VCF file.
*/
private void outputJannovarFormatFile(VCFReader parser) throws JannovarException {
File f = new File(this.VCFfilePath);
String outname = f.getName() + ".jannovar";
try {
FileWriter fstream = new FileWriter(outname);
BufferedWriter out = new BufferedWriter(fstream);
/** Output each of the variants. */
int n = 0;
Iterator<Variant> iter = parser.getVariantIterator();
while (iter.hasNext()) {
n++;
Variant v = iter.next();
try {
outputJannovarLine(n, v, out);
} catch (AnnotationException e) {
System.out.println("[WARN] Annotation error: " + e.toString());
}
}
out.close();
} catch (IOException e) {
System.err.println("[ERROR] Error writing annotated VCF file");
System.err.println("[ERROR] " + e.toString());
System.exit(1);
}
System.out.println("[INFO] Wrote annotations to \"" + outname + "\"");
}
/**
* THis function will simply annotate given chromosomal position with HGVS
* compliant output e.g. chr1:909238G>C -->
* PLEKHN1:NM_032129.2:c.1460G>C,p.(Arg487Pro)
*
* @throws AnnotationException
*/
private void annotatePosition() throws AnnotationException {
System.out.println("input: " + this.chromosomalChange);
Pattern pat = Pattern.compile("(chr[0-9MXY]+):([0-9]+)([ACGTN])>([ACGTN])");
Matcher mat = pat.matcher(this.chromosomalChange);
if (!mat.matches() | mat.groupCount() != 4) {
System.err.println("[ERROR] Input string for the chromosomal change does not fit the regular expression ... :(");
System.exit(3);
}
byte chr = ChromosomeMap.identifier2chromosom.get(mat.group(1));
int pos = Integer.parseInt(mat.group(2));
String ref = mat.group(3);
String alt = mat.group(4);
Chromosome c = chromosomeMap.get(chr);
if (c == null) {
String e = String.format("Could not identify chromosome \"%d\"", chr);
throw new AnnotationException(e);
}
AnnotationList anno = c.getAnnotationList(pos, ref, alt);
if (anno == null) {
String e = String.format("No annotations found for variant %s", this.chromosomalChange);
throw new AnnotationException(e);
}
String annotation;
String effect;
if (this.showAll) {
annotation = anno.getAllTranscriptAnnotations();
effect = anno.getAllTranscriptVariantEffects();
} else {
annotation = anno.getSingleTranscriptAnnotation();
effect = anno.getVariantType().toString();
}
System.out.println(String.format("EFFECT=%s;HGVS=%s", effect, annotation));
}
/**
* This function inputs a VCF file, and prints the annotated version thereof
* to a file (name of the original file with the suffix .jannovar).
*
* @throws jannovar.exception.JannovarException
*/
public void annotateVCF() throws JannovarException {
VCFReader parser = new VCFReader(this.VCFfilePath);
VCFLine.setStoreVCFLines();
try {
parser.inputVCFheader();
} catch (VCFParseException e) {
System.err.println("[ERROR] Unable to parse VCF file");
System.err.println(e.toString());
System.exit(1);
}
if (this.jannovarFormat) {
outputJannovarFormatFile(parser);
} else {
outputAnnotatedVCF(parser);
}
}
/**
* Inputs the GFF data from RefSeq files, convert the resulting
* {@link jannovar.reference.TranscriptModel TranscriptModel} objects to
* {@link jannovar.interval.Interval Interval} objects, and store these in a
* serialized file.
*
* @throws JannovarException
*/
public void serializeRefseqData() throws JannovarException {
SerializationManager manager = new SerializationManager();
System.out.println("[INFO] Serializing RefSeq data as " + String.format(dirPath + Jannovar.RefseqSerializationFileName, genomeRelease.getUCSCString(genomeRelease)));
manager.serializeKnownGeneList(String.format(dirPath + Jannovar.RefseqSerializationFileName, genomeRelease.getUCSCString(genomeRelease)), this.transcriptModelList);
}
/**
* Inputs the GFF data from Ensembl files, convert the resulting
* {@link jannovar.reference.TranscriptModel TranscriptModel} objects to
* {@link jannovar.interval.Interval Interval} objects, and store these in a
* serialized file.
*
* @throws jannovar.exception.JannovarException
*/
public void serializeEnsemblData() throws JannovarException {
SerializationManager manager = new SerializationManager();
System.out.println("[INFO] Serializing Ensembl data as " + String.format(dirPath + Jannovar.EnsemblSerializationFileName, genomeRelease.getUCSCString(genomeRelease)));
manager.serializeKnownGeneList(String.format(dirPath + Jannovar.EnsemblSerializationFileName, genomeRelease.getUCSCString(genomeRelease)), this.transcriptModelList);
}
/**
* Inputs the KnownGenes data from UCSC files, convert the resulting
* {@link jannovar.reference.TranscriptModel TranscriptModel} objects to
* {@link jannovar.interval.Interval Interval} objects, and store these in a
* serialized file.
*
* @throws jannovar.exception.JannovarException
*/
public void serializeUCSCdata() throws JannovarException {
SerializationManager manager = new SerializationManager();
System.out.println("[INFO] Serializing UCSC data as " + String.format(dirPath + Jannovar.UCSCserializationFileName, genomeRelease.getUCSCString(genomeRelease)));
manager.serializeKnownGeneList(String.format(dirPath + Jannovar.UCSCserializationFileName, genomeRelease.getUCSCString(genomeRelease)), this.transcriptModelList);
}
/**
* To run Jannovar, the user must pass a transcript definition file with the
* -D flag. This can be one of the files ucsc.ser, ensembl.ser, or
* refseq.ser (or a comparable file) containing a serialized version of the
* TranscriptModel objects created to contain info about the transcript
* definitions (exon positions etc.) extracted from UCSC, Ensembl, or Refseq
* and necessary for annotation.
*
* @throws JannovarException
*/
public void deserializeTranscriptDefinitionFile() throws JannovarException {
ArrayList<TranscriptModel> kgList;
SerializationManager manager = new SerializationManager();
kgList = manager.deserializeKnownGeneList(this.serializedFile);
this.chromosomeMap = Chromosome.constructChromosomeMapWithIntervalTree(kgList);
}
/**
* Input the RefSeq data.
*/
private void inputTranscriptModelDataFromRefseq() {
// parse GFF/GTF
GFFparser gff = new GFFparser();
String path = this.dirPath + genomeRelease.getUCSCString(genomeRelease);
if (!path.endsWith(System.getProperty("file.separator")))
path += System.getProperty("file.separator");
switch (this.genomeRelease) {
case MM9:
gff.parse(path + Constants.refseq_gff_mm9);
break;
case MM10:
gff.parse(path + Constants.refseq_gff_mm10);
break;
case HG18:
gff.parse(path + Constants.refseq_gff_hg18);
break;
case HG19:
gff.parse(path + Constants.refseq_gff_hg19);
break;
case HG38:
gff.parse(path + Constants.refseq_gff_hg38);
break;
default:
System.err.println("[ERROR] Unknown release: " + genomeRelease);
System.exit(20);
break;
}
try {
this.transcriptModelList = gff.getTranscriptModelBuilder().buildTranscriptModels();
} catch (InvalidAttributException e) {
System.err.println("[ERROR] Unable to input data from the Refseq files");
e.printStackTrace();
System.exit(1);
}
// add sequences
FastaParser efp = new RefSeqFastaParser(path + Constants.refseq_rna, transcriptModelList);
int before = transcriptModelList.size();
transcriptModelList = efp.parse();
int after = transcriptModelList.size();
// System.out.println(String.format("[INFO] removed %d (%d --> %d) transcript models w/o rna sequence",
// before-after,before, after));
System.out.println(String.format("[INFO] Found %d transcript models from Refseq GFF resource, %d of which had sequences", before, after));
}
/**
* Input the Ensembl data.
*/
private void inputTranscriptModelDataFromEnsembl() {
// parse GFF/GTF
GFFparser gff = new GFFparser();
String path;
path = this.dirPath + genomeRelease.getUCSCString(genomeRelease);
if (!path.endsWith(System.getProperty("file.separator")))
path += System.getProperty("file.separator");
switch (this.genomeRelease) {
case MM9:
path += Constants.ensembl_mm9;
break;
case MM10:
path += Constants.ensembl_mm10;
break;
case HG18:
path += Constants.ensembl_hg18;
break;
case HG19:
path += Constants.ensembl_hg19;
break;
default:
System.err.println("[ERROR] Unknown release: " + genomeRelease);
System.exit(20);
break;
}
gff.parse(path + Constants.ensembl_gtf);
try {
this.transcriptModelList = gff.getTranscriptModelBuilder().buildTranscriptModels();
// System.out.println("[INFO] Got: "+this.transcriptModelList.size()
// + " Ensembl transcripts");
} catch (InvalidAttributException e) {
System.err.println("[ERROR] Unable to input data from the Ensembl files");
e.printStackTrace();
System.exit(1);
}
// add sequences
EnsemblFastaParser efp = new EnsemblFastaParser(path + Constants.ensembl_cdna, transcriptModelList);
int before = transcriptModelList.size();
transcriptModelList = efp.parse();
int after = transcriptModelList.size();
// System.out.println(String.format("[INFO] removed %d (%d --> %d) transcript models w/o rna sequence",
// before-after,before, after));
System.out.println(String.format("[INFO] Found %d transcript models from Ensembl GFF resource, %d of which had sequences", before, after));
}
/**
* Input the four UCSC files for the KnownGene data.
*/
private void inputTranscriptModelDataFromUCSCFiles() {
String path = this.dirPath + genomeRelease.getUCSCString(genomeRelease);
if (!path.endsWith(System.getProperty("file.separator")))
path += System.getProperty("file.separator");
UCSCKGParser parser = new UCSCKGParser(path);
try {
parser.parseUCSCFiles();
} catch (Exception e) {
System.err.println("[ERROR] Unable to input data from the UCSC files");
e.printStackTrace();
System.exit(1);
}
this.transcriptModelList = parser.getKnownGeneList();
}
/**
* A simple printout of the chromosome map for debugging purposes.
*/
public void debugShowChromosomeMap() {
for (Byte c : chromosomeMap.keySet()) {
Chromosome chromo = chromosomeMap.get(c);
System.out.println("Chrom. " + c + ": " + chromo.getNumberOfGenes() + " genes");
}
}
/**
* Parse the command line.
*
* @param args
* Copy of the command line arguments.
*/
private void parseCommandLineArguments(String[] args) {
try {
Options options = new Options();
options.addOption(new Option("h", "help", false, "Shows this help"));
options.addOption(new Option("U", "downloaded-data", true, "Path to directory with previously downloaded transcript definition files."));
options.addOption(new Option("S", "serialize", false, "Serialize"));
options.addOption(new Option("D", "deserialize", true, "Path to serialized file with UCSC data"));
options.addOption(new Option("d", "data", true, "Path to write data storage folder (genome files, serialized files, ...)"));
options.addOption(new Option("O", "output", true, "Path to output folder for the annotated VCF file"));
options.addOption(new Option("V", "vcf", true, "Path to VCF file"));
options.addOption(new Option("a", "showall", false, "report annotations for all transcripts to VCF file"));
options.addOption(new Option("P", "position", true, "chromosomal position to HGVS (e.g. chr1:909238G>C)"));
options.addOption(new Option("J", "janno", false, "Output Jannovar format"));
options.addOption(new Option("g", "genome", true, "genome build (mm9, mm10, hg18, hg19, hg38 - only refseq), default hg19"));
options.addOption(new Option(null, "create-ucsc", false, "Create UCSC definition file"));
options.addOption(new Option(null, "create-refseq", false, "Create RefSeq definition file"));
options.addOption(new Option(null, "create-ensembl", false, "Create Ensembl definition file"));
options.addOption(new Option(null, "proxy", true, "FTP Proxy"));
options.addOption(new Option(null, "proxy-port", true, "FTP Proxy Port"));
Parser parser = new GnuParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("h") || cmd.hasOption("H") || args.length == 0) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("java -jar Jannovar.jar [-options]", options);
usage();
System.exit(0);
}
this.jannovarFormat = cmd.hasOption("J");
this.showAll = cmd.hasOption('a');
if (cmd.hasOption("create-ucsc")) {
this.createUCSC = true;
this.performSerialization = true;
} else {
this.createUCSC = false;
}
if (cmd.hasOption("create-refseq")) {
this.createRefseq = true;
this.performSerialization = true;
} else {
this.createRefseq = false;
}
if (cmd.hasOption("create-ensembl")) {
this.createEnsembl = true;
this.performSerialization = true;
} else {
this.createEnsembl = false;
}
// path to the data storage
if (cmd.hasOption('d'))
this.dirPath = cmd.getOptionValue('d');
else
this.dirPath = Constants.DEFAULT_DATA;
if (!this.dirPath.endsWith(System.getProperty("file.separator")))
this.dirPath += System.getProperty("file.separator");
if (cmd.hasOption("genome")) {
String g = cmd.getOptionValue("genome");
if (g.equals("mm9")) {
this.genomeRelease = Release.MM9;
}
if (g.equals("mm10")) {
this.genomeRelease = Release.MM10;
}
if (g.equals("hg18")) {
this.genomeRelease = Release.HG18;
}
if (g.equals("hg19")) {
this.genomeRelease = Release.HG19;
}
- if (g.equals("hg38") && this.createRefseq) {
- this.genomeRelease = Release.HG38;
- } else {
- System.out.println("[INFO] Genome release hg38 only available for Refseq");
- System.exit(0);
+ if (g.equals("hg38")) {
+ if (this.createRefseq)
+ this.genomeRelease = Release.HG38;
+ else {
+ System.out.println("[INFO] Genome release hg38 only available for Refseq");
+ System.exit(0);
+ }
}
} else {
if (performSerialization)
System.out.println("[INFO] Genome release set to default: hg19");
this.genomeRelease = Release.HG19;
}
if (cmd.hasOption('O')) {
outVCFfolder = cmd.getOptionValue('O');
File file = new File(outVCFfolder);
if (!file.exists())
file.mkdirs();
}
if (cmd.hasOption('S')) {
this.performSerialization = true;
}
if (cmd.hasOption("proxy")) {
this.proxy = cmd.getOptionValue("proxy");
}
if (cmd.hasOption("proxy-port")) {
this.proxyPort = cmd.getOptionValue("proxy-port");
}
if (cmd.hasOption("U")) {
this.dirPath = getRequiredOptionValue(cmd, 'U');
}
if (cmd.hasOption('D')) {
this.serializedFile = cmd.getOptionValue('D');
}
if (cmd.hasOption("V"))
this.VCFfilePath = cmd.getOptionValue("V");
if (cmd.hasOption("P"))
this.chromosomalChange = cmd.getOptionValue("P");
} catch (ParseException pe) {
System.err.println("Error parsing command line options");
System.err.println(pe.getMessage());
System.exit(1);
}
}
/**
* This function is used to ensure that certain options are passed to the
* program before we start execution.
*
* @param cmd
* An apache CommandLine object that stores the command line
* arguments
* @param name
* Name of the argument that must be present
* @return Value of the required option as a String.
*/
private static String getRequiredOptionValue(CommandLine cmd, char name) {
String val = cmd.getOptionValue(name);
if (val == null) {
System.err.println("Aborting because the required argument \"-" + name + "\" wasn't specified! Use the -h for more help.");
System.exit(-1);
}
return val;
}
private static void usage() {
System.out.println("*** Jannovar: Usage ****");
System.out.println("Use case 1: Download UCSC data and create transcript data file (ucsc_hg19.ser)");
System.out.println("$ java -jar Jannovar.jar --create-ucsc [-U name of output directory]");
System.out.println("Use case 2: Add annotations to a VCF file");
System.out.println("$ java -jar Jannovar.jar -D ucsc_hg19.ser -V example.vcf");
System.out.println("Use case 3: Write new file with Jannovar-format annotations of a VCF file");
System.out.println("$ java -jar Jannovar -D ucsc_hg19.ser -V vcfPath -J");
System.out.println("*** See the tutorial for details ***");
}
}
/* eof */
| true | true | private void parseCommandLineArguments(String[] args) {
try {
Options options = new Options();
options.addOption(new Option("h", "help", false, "Shows this help"));
options.addOption(new Option("U", "downloaded-data", true, "Path to directory with previously downloaded transcript definition files."));
options.addOption(new Option("S", "serialize", false, "Serialize"));
options.addOption(new Option("D", "deserialize", true, "Path to serialized file with UCSC data"));
options.addOption(new Option("d", "data", true, "Path to write data storage folder (genome files, serialized files, ...)"));
options.addOption(new Option("O", "output", true, "Path to output folder for the annotated VCF file"));
options.addOption(new Option("V", "vcf", true, "Path to VCF file"));
options.addOption(new Option("a", "showall", false, "report annotations for all transcripts to VCF file"));
options.addOption(new Option("P", "position", true, "chromosomal position to HGVS (e.g. chr1:909238G>C)"));
options.addOption(new Option("J", "janno", false, "Output Jannovar format"));
options.addOption(new Option("g", "genome", true, "genome build (mm9, mm10, hg18, hg19, hg38 - only refseq), default hg19"));
options.addOption(new Option(null, "create-ucsc", false, "Create UCSC definition file"));
options.addOption(new Option(null, "create-refseq", false, "Create RefSeq definition file"));
options.addOption(new Option(null, "create-ensembl", false, "Create Ensembl definition file"));
options.addOption(new Option(null, "proxy", true, "FTP Proxy"));
options.addOption(new Option(null, "proxy-port", true, "FTP Proxy Port"));
Parser parser = new GnuParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("h") || cmd.hasOption("H") || args.length == 0) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("java -jar Jannovar.jar [-options]", options);
usage();
System.exit(0);
}
this.jannovarFormat = cmd.hasOption("J");
this.showAll = cmd.hasOption('a');
if (cmd.hasOption("create-ucsc")) {
this.createUCSC = true;
this.performSerialization = true;
} else {
this.createUCSC = false;
}
if (cmd.hasOption("create-refseq")) {
this.createRefseq = true;
this.performSerialization = true;
} else {
this.createRefseq = false;
}
if (cmd.hasOption("create-ensembl")) {
this.createEnsembl = true;
this.performSerialization = true;
} else {
this.createEnsembl = false;
}
// path to the data storage
if (cmd.hasOption('d'))
this.dirPath = cmd.getOptionValue('d');
else
this.dirPath = Constants.DEFAULT_DATA;
if (!this.dirPath.endsWith(System.getProperty("file.separator")))
this.dirPath += System.getProperty("file.separator");
if (cmd.hasOption("genome")) {
String g = cmd.getOptionValue("genome");
if (g.equals("mm9")) {
this.genomeRelease = Release.MM9;
}
if (g.equals("mm10")) {
this.genomeRelease = Release.MM10;
}
if (g.equals("hg18")) {
this.genomeRelease = Release.HG18;
}
if (g.equals("hg19")) {
this.genomeRelease = Release.HG19;
}
if (g.equals("hg38") && this.createRefseq) {
this.genomeRelease = Release.HG38;
} else {
System.out.println("[INFO] Genome release hg38 only available for Refseq");
System.exit(0);
}
} else {
if (performSerialization)
System.out.println("[INFO] Genome release set to default: hg19");
this.genomeRelease = Release.HG19;
}
if (cmd.hasOption('O')) {
outVCFfolder = cmd.getOptionValue('O');
File file = new File(outVCFfolder);
if (!file.exists())
file.mkdirs();
}
if (cmd.hasOption('S')) {
this.performSerialization = true;
}
if (cmd.hasOption("proxy")) {
this.proxy = cmd.getOptionValue("proxy");
}
if (cmd.hasOption("proxy-port")) {
this.proxyPort = cmd.getOptionValue("proxy-port");
}
if (cmd.hasOption("U")) {
this.dirPath = getRequiredOptionValue(cmd, 'U');
}
if (cmd.hasOption('D')) {
this.serializedFile = cmd.getOptionValue('D');
}
if (cmd.hasOption("V"))
this.VCFfilePath = cmd.getOptionValue("V");
if (cmd.hasOption("P"))
this.chromosomalChange = cmd.getOptionValue("P");
} catch (ParseException pe) {
System.err.println("Error parsing command line options");
System.err.println(pe.getMessage());
System.exit(1);
}
}
| private void parseCommandLineArguments(String[] args) {
try {
Options options = new Options();
options.addOption(new Option("h", "help", false, "Shows this help"));
options.addOption(new Option("U", "downloaded-data", true, "Path to directory with previously downloaded transcript definition files."));
options.addOption(new Option("S", "serialize", false, "Serialize"));
options.addOption(new Option("D", "deserialize", true, "Path to serialized file with UCSC data"));
options.addOption(new Option("d", "data", true, "Path to write data storage folder (genome files, serialized files, ...)"));
options.addOption(new Option("O", "output", true, "Path to output folder for the annotated VCF file"));
options.addOption(new Option("V", "vcf", true, "Path to VCF file"));
options.addOption(new Option("a", "showall", false, "report annotations for all transcripts to VCF file"));
options.addOption(new Option("P", "position", true, "chromosomal position to HGVS (e.g. chr1:909238G>C)"));
options.addOption(new Option("J", "janno", false, "Output Jannovar format"));
options.addOption(new Option("g", "genome", true, "genome build (mm9, mm10, hg18, hg19, hg38 - only refseq), default hg19"));
options.addOption(new Option(null, "create-ucsc", false, "Create UCSC definition file"));
options.addOption(new Option(null, "create-refseq", false, "Create RefSeq definition file"));
options.addOption(new Option(null, "create-ensembl", false, "Create Ensembl definition file"));
options.addOption(new Option(null, "proxy", true, "FTP Proxy"));
options.addOption(new Option(null, "proxy-port", true, "FTP Proxy Port"));
Parser parser = new GnuParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("h") || cmd.hasOption("H") || args.length == 0) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("java -jar Jannovar.jar [-options]", options);
usage();
System.exit(0);
}
this.jannovarFormat = cmd.hasOption("J");
this.showAll = cmd.hasOption('a');
if (cmd.hasOption("create-ucsc")) {
this.createUCSC = true;
this.performSerialization = true;
} else {
this.createUCSC = false;
}
if (cmd.hasOption("create-refseq")) {
this.createRefseq = true;
this.performSerialization = true;
} else {
this.createRefseq = false;
}
if (cmd.hasOption("create-ensembl")) {
this.createEnsembl = true;
this.performSerialization = true;
} else {
this.createEnsembl = false;
}
// path to the data storage
if (cmd.hasOption('d'))
this.dirPath = cmd.getOptionValue('d');
else
this.dirPath = Constants.DEFAULT_DATA;
if (!this.dirPath.endsWith(System.getProperty("file.separator")))
this.dirPath += System.getProperty("file.separator");
if (cmd.hasOption("genome")) {
String g = cmd.getOptionValue("genome");
if (g.equals("mm9")) {
this.genomeRelease = Release.MM9;
}
if (g.equals("mm10")) {
this.genomeRelease = Release.MM10;
}
if (g.equals("hg18")) {
this.genomeRelease = Release.HG18;
}
if (g.equals("hg19")) {
this.genomeRelease = Release.HG19;
}
if (g.equals("hg38")) {
if (this.createRefseq)
this.genomeRelease = Release.HG38;
else {
System.out.println("[INFO] Genome release hg38 only available for Refseq");
System.exit(0);
}
}
} else {
if (performSerialization)
System.out.println("[INFO] Genome release set to default: hg19");
this.genomeRelease = Release.HG19;
}
if (cmd.hasOption('O')) {
outVCFfolder = cmd.getOptionValue('O');
File file = new File(outVCFfolder);
if (!file.exists())
file.mkdirs();
}
if (cmd.hasOption('S')) {
this.performSerialization = true;
}
if (cmd.hasOption("proxy")) {
this.proxy = cmd.getOptionValue("proxy");
}
if (cmd.hasOption("proxy-port")) {
this.proxyPort = cmd.getOptionValue("proxy-port");
}
if (cmd.hasOption("U")) {
this.dirPath = getRequiredOptionValue(cmd, 'U');
}
if (cmd.hasOption('D')) {
this.serializedFile = cmd.getOptionValue('D');
}
if (cmd.hasOption("V"))
this.VCFfilePath = cmd.getOptionValue("V");
if (cmd.hasOption("P"))
this.chromosomalChange = cmd.getOptionValue("P");
} catch (ParseException pe) {
System.err.println("Error parsing command line options");
System.err.println(pe.getMessage());
System.exit(1);
}
}
|
diff --git a/openFaces/source/org/openfaces/renderkit/table/GroupingBoxRenderer.java b/openFaces/source/org/openfaces/renderkit/table/GroupingBoxRenderer.java
index 1f1502493..9ad5e86fa 100644
--- a/openFaces/source/org/openfaces/renderkit/table/GroupingBoxRenderer.java
+++ b/openFaces/source/org/openfaces/renderkit/table/GroupingBoxRenderer.java
@@ -1,70 +1,70 @@
/*
* OpenFaces - JSF Component Library 2.0
* Copyright (C) 2007-2011, TeamDev Ltd.
* [email protected]
* Unless agreed in writing the contents of this file are subject to
* the GNU Lesser General Public License Version 2.1 (the "LGPL" License).
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* Please visit http://openfaces.org/licensing/ for more details.
*/
package org.openfaces.renderkit.table;
import org.openfaces.component.table.DataTable;
import org.openfaces.component.table.GroupingBox;
import org.openfaces.util.Rendering;
import org.openfaces.util.ScriptBuilder;
import org.openfaces.util.Styles;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import java.io.IOException;
public class GroupingBoxRenderer extends org.openfaces.renderkit.RendererBase {
@Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
super.encodeBegin(context, component);
final ResponseWriter writer = context.getResponseWriter();
final GroupingBox groupingBox = (GroupingBox) component;
final UIComponent parent = groupingBox.getParent();
if (!(parent instanceof DataTable))
throw new IllegalStateException("<o:groupingBox> can only be placed as a child component inside of " +
"a <o:dataTable> component. Though the following parent component has been encountered: " +
parent.getClass().getName());
final DataTable table = (DataTable) groupingBox.getParent();
final String boxClassName = Styles.getCSSClass(context, component, groupingBox.getStyle(), "o_groupingBox", groupingBox.getStyleClass());
final String headerClassName = Styles.getCSSClass(context, component, groupingBox.getHeaderStyle(), "o_groupingBox_header", groupingBox.getHeaderStyleClass());
final String promptClassName = Styles.getCSSClass(context, component, groupingBox.getPromptTextStyle(), "o_groupingBox_promptText", groupingBox.getPromptTextStyleClass());
final String connectorStyle = groupingBox.getConnectorStyle();
writer.startElement("table", component);
- writer.writeAttribute("style", "width: 100%;", null);
+ writer.writeAttribute("class", boxClassName, null);
writeIdAttribute(context, component);
writer.writeAttribute("cellspacing", "0", null);
writer.writeAttribute("cellpadding", "0", null);
writer.writeAttribute("border", "0", null);
writer.startElement("tr", component);
writer.startElement("td", component);
- writer.writeAttribute("class", boxClassName, null);
+ writer.writeAttribute("style", "position: relative", null);
writer.startElement("span", component);
writer.writeAttribute("class", promptClassName, null);
writer.append(groupingBox.getPromptText());
writer.endElement("span");
writer.endElement("td");
writer.endElement("tr");
writer.endElement("table");
Rendering.renderInitScript(context, new ScriptBuilder()
.initScript(context, component, "O$.Table._initRowGroupingBox",
table,
connectorStyle, headerClassName,
groupingBox.getHeaderHorizOffset(), groupingBox.getHeaderVertOffset())
.semicolon());
Styles.renderStyleClasses(context, component);
}
}
| false | true | public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
super.encodeBegin(context, component);
final ResponseWriter writer = context.getResponseWriter();
final GroupingBox groupingBox = (GroupingBox) component;
final UIComponent parent = groupingBox.getParent();
if (!(parent instanceof DataTable))
throw new IllegalStateException("<o:groupingBox> can only be placed as a child component inside of " +
"a <o:dataTable> component. Though the following parent component has been encountered: " +
parent.getClass().getName());
final DataTable table = (DataTable) groupingBox.getParent();
final String boxClassName = Styles.getCSSClass(context, component, groupingBox.getStyle(), "o_groupingBox", groupingBox.getStyleClass());
final String headerClassName = Styles.getCSSClass(context, component, groupingBox.getHeaderStyle(), "o_groupingBox_header", groupingBox.getHeaderStyleClass());
final String promptClassName = Styles.getCSSClass(context, component, groupingBox.getPromptTextStyle(), "o_groupingBox_promptText", groupingBox.getPromptTextStyleClass());
final String connectorStyle = groupingBox.getConnectorStyle();
writer.startElement("table", component);
writer.writeAttribute("style", "width: 100%;", null);
writeIdAttribute(context, component);
writer.writeAttribute("cellspacing", "0", null);
writer.writeAttribute("cellpadding", "0", null);
writer.writeAttribute("border", "0", null);
writer.startElement("tr", component);
writer.startElement("td", component);
writer.writeAttribute("class", boxClassName, null);
writer.startElement("span", component);
writer.writeAttribute("class", promptClassName, null);
writer.append(groupingBox.getPromptText());
writer.endElement("span");
writer.endElement("td");
writer.endElement("tr");
writer.endElement("table");
Rendering.renderInitScript(context, new ScriptBuilder()
.initScript(context, component, "O$.Table._initRowGroupingBox",
table,
connectorStyle, headerClassName,
groupingBox.getHeaderHorizOffset(), groupingBox.getHeaderVertOffset())
.semicolon());
Styles.renderStyleClasses(context, component);
}
| public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
super.encodeBegin(context, component);
final ResponseWriter writer = context.getResponseWriter();
final GroupingBox groupingBox = (GroupingBox) component;
final UIComponent parent = groupingBox.getParent();
if (!(parent instanceof DataTable))
throw new IllegalStateException("<o:groupingBox> can only be placed as a child component inside of " +
"a <o:dataTable> component. Though the following parent component has been encountered: " +
parent.getClass().getName());
final DataTable table = (DataTable) groupingBox.getParent();
final String boxClassName = Styles.getCSSClass(context, component, groupingBox.getStyle(), "o_groupingBox", groupingBox.getStyleClass());
final String headerClassName = Styles.getCSSClass(context, component, groupingBox.getHeaderStyle(), "o_groupingBox_header", groupingBox.getHeaderStyleClass());
final String promptClassName = Styles.getCSSClass(context, component, groupingBox.getPromptTextStyle(), "o_groupingBox_promptText", groupingBox.getPromptTextStyleClass());
final String connectorStyle = groupingBox.getConnectorStyle();
writer.startElement("table", component);
writer.writeAttribute("class", boxClassName, null);
writeIdAttribute(context, component);
writer.writeAttribute("cellspacing", "0", null);
writer.writeAttribute("cellpadding", "0", null);
writer.writeAttribute("border", "0", null);
writer.startElement("tr", component);
writer.startElement("td", component);
writer.writeAttribute("style", "position: relative", null);
writer.startElement("span", component);
writer.writeAttribute("class", promptClassName, null);
writer.append(groupingBox.getPromptText());
writer.endElement("span");
writer.endElement("td");
writer.endElement("tr");
writer.endElement("table");
Rendering.renderInitScript(context, new ScriptBuilder()
.initScript(context, component, "O$.Table._initRowGroupingBox",
table,
connectorStyle, headerClassName,
groupingBox.getHeaderHorizOffset(), groupingBox.getHeaderVertOffset())
.semicolon());
Styles.renderStyleClasses(context, component);
}
|
diff --git a/src/main/java/com/biasedbit/http/client/processor/AbstractAccumulatorProcessor.java b/src/main/java/com/biasedbit/http/client/processor/AbstractAccumulatorProcessor.java
index 54b4001..6b07ff6 100644
--- a/src/main/java/com/biasedbit/http/client/processor/AbstractAccumulatorProcessor.java
+++ b/src/main/java/com/biasedbit/http/client/processor/AbstractAccumulatorProcessor.java
@@ -1,121 +1,124 @@
/*
* Copyright 2013 BiasedBit
*
* 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.biasedbit.http.client.processor;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
/**
* @author <a href="http://biasedbit.com/">Bruno de Carvalho</a>
*/
public abstract class AbstractAccumulatorProcessor<T>
implements HttpResponseProcessor<T> {
// internal vars --------------------------------------------------------------------------------------------------
protected final List<Integer> acceptedCodes;
protected ChannelBuffer buffer;
protected volatile boolean finished;
protected T result;
// constructors ---------------------------------------------------------------------------------------------------
public AbstractAccumulatorProcessor() { acceptedCodes = null; }
public AbstractAccumulatorProcessor(List<Integer> acceptedCodes) { this.acceptedCodes = acceptedCodes; }
public AbstractAccumulatorProcessor(int... acceptedCodes) {
this.acceptedCodes = new ArrayList<>(acceptedCodes.length);
for (int acceptedCode : acceptedCodes) this.acceptedCodes.add(acceptedCode);
}
// HttpResponseProcessor ------------------------------------------------------------------------------------------
@Override public boolean willProcessResponse(HttpResponse response)
throws Exception {
if (!isAcceptableResponse(response)) return false;
// Content already present. Deal with it and bail out.
if ((response.getContent() != null) && (response.getContent().readableBytes() > 0)) {
result = convertBufferToResult(response.getContent());
finished = true;
return true;
}
// No content readily available
long length = HttpHeaders.getContentLength(response, -1);
- if (length > Integer.MAX_VALUE) {
+ if ((length > Integer.MAX_VALUE) || (length < -1)) {
+ // Even though get/setContentLength works with longs, the value seems to be converted to an int so we need
+ // to check if overflowed (-1 is no content length, < -1 is an overflowed length)
finished = true;
return false;
}
if (length == 0) {
// No content
finished = true;
return false;
}
// If the response is chunked, then prepare the buffers for incoming data.
if (response.isChunked()) {
- if (length == -1) {
+ if (length < 0) {
// No content header, but there may be content... use a dynamic buffer (not so good for performance...)
buffer = ChannelBuffers.dynamicBuffer(2048);
} else {
// When content is zipped and autoInflate is set to true, the Content-Length header remains the same
// even though the contents are expanded. Thus using a fixed size buffer would break with
// ArrayIndexOutOfBoundsException
buffer = ChannelBuffers.dynamicBuffer((int) length);
}
return true;
}
+ // Non-chunked request without content
finished = true;
return false;
}
@Override public void addData(ChannelBuffer content)
throws Exception {
if (!finished) buffer.writeBytes(content);
}
@Override public void addLastData(ChannelBuffer content)
throws Exception {
if (!finished) {
buffer.writeBytes(content);
result = convertBufferToResult(buffer);
buffer = null;
finished = true;
}
}
@Override public T getProcessedResponse() { return result; }
// protected helpers ----------------------------------------------------------------------------------------------
protected abstract T convertBufferToResult(ChannelBuffer buffer);
protected boolean isAcceptableResponse(HttpResponse response) {
if (acceptedCodes == null) return true;
else return acceptedCodes.contains(response.getStatus().getCode());
}
}
| false | true | @Override public boolean willProcessResponse(HttpResponse response)
throws Exception {
if (!isAcceptableResponse(response)) return false;
// Content already present. Deal with it and bail out.
if ((response.getContent() != null) && (response.getContent().readableBytes() > 0)) {
result = convertBufferToResult(response.getContent());
finished = true;
return true;
}
// No content readily available
long length = HttpHeaders.getContentLength(response, -1);
if (length > Integer.MAX_VALUE) {
finished = true;
return false;
}
if (length == 0) {
// No content
finished = true;
return false;
}
// If the response is chunked, then prepare the buffers for incoming data.
if (response.isChunked()) {
if (length == -1) {
// No content header, but there may be content... use a dynamic buffer (not so good for performance...)
buffer = ChannelBuffers.dynamicBuffer(2048);
} else {
// When content is zipped and autoInflate is set to true, the Content-Length header remains the same
// even though the contents are expanded. Thus using a fixed size buffer would break with
// ArrayIndexOutOfBoundsException
buffer = ChannelBuffers.dynamicBuffer((int) length);
}
return true;
}
finished = true;
return false;
}
| @Override public boolean willProcessResponse(HttpResponse response)
throws Exception {
if (!isAcceptableResponse(response)) return false;
// Content already present. Deal with it and bail out.
if ((response.getContent() != null) && (response.getContent().readableBytes() > 0)) {
result = convertBufferToResult(response.getContent());
finished = true;
return true;
}
// No content readily available
long length = HttpHeaders.getContentLength(response, -1);
if ((length > Integer.MAX_VALUE) || (length < -1)) {
// Even though get/setContentLength works with longs, the value seems to be converted to an int so we need
// to check if overflowed (-1 is no content length, < -1 is an overflowed length)
finished = true;
return false;
}
if (length == 0) {
// No content
finished = true;
return false;
}
// If the response is chunked, then prepare the buffers for incoming data.
if (response.isChunked()) {
if (length < 0) {
// No content header, but there may be content... use a dynamic buffer (not so good for performance...)
buffer = ChannelBuffers.dynamicBuffer(2048);
} else {
// When content is zipped and autoInflate is set to true, the Content-Length header remains the same
// even though the contents are expanded. Thus using a fixed size buffer would break with
// ArrayIndexOutOfBoundsException
buffer = ChannelBuffers.dynamicBuffer((int) length);
}
return true;
}
// Non-chunked request without content
finished = true;
return false;
}
|
diff --git a/org.eclipse.virgo.kernel.deployer.dm/src/main/java/org/eclipse/virgo/kernel/deployer/app/spring/UserRegionModuleContextAccessor.java b/org.eclipse.virgo.kernel.deployer.dm/src/main/java/org/eclipse/virgo/kernel/deployer/app/spring/UserRegionModuleContextAccessor.java
index 5471f663..487a8437 100644
--- a/org.eclipse.virgo.kernel.deployer.dm/src/main/java/org/eclipse/virgo/kernel/deployer/app/spring/UserRegionModuleContextAccessor.java
+++ b/org.eclipse.virgo.kernel.deployer.dm/src/main/java/org/eclipse/virgo/kernel/deployer/app/spring/UserRegionModuleContextAccessor.java
@@ -1,72 +1,76 @@
/*******************************************************************************
* Copyright (c) 2008, 2010 VMware 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:
* VMware Inc. - initial contribution
*******************************************************************************/
package org.eclipse.virgo.kernel.deployer.app.spring;
import java.util.Collection;
import org.eclipse.virgo.kernel.serviceability.Assert;
import org.eclipse.virgo.kernel.serviceability.NonNull;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.springframework.context.ApplicationContext;
import org.springframework.osgi.context.ConfigurableOsgiBundleApplicationContext;
import org.eclipse.virgo.kernel.module.ModuleContext;
import org.eclipse.virgo.kernel.module.ModuleContextAccessor;
/**
* {@link UserRegionModuleContextAccessor} accesses {@link ModuleContext ModuleContexts} in the user region.
* <p />
*
* <strong>Concurrent Semantics</strong><br />
*
* Thread safe.
*
*/
final class UserRegionModuleContextAccessor implements ModuleContextAccessor {
/**
* {@inheritDoc}
*/
public ModuleContext getModuleContext(@NonNull Bundle bundle) {
BundleContext bundleContext = bundle.getBundleContext();
// The bundle must have a bundle context in order to have a module context.
if (bundleContext != null) {
String symbolicName = bundle.getSymbolicName();
try {
Collection<ServiceReference<ApplicationContext>> refs = bundleContext.getServiceReferences(ApplicationContext.class,
"(Bundle-SymbolicName=" + symbolicName + ")");
if (refs.size() != 0) {
for (ServiceReference<ApplicationContext> ref : refs) {
- ApplicationContext appCtx = (ApplicationContext) bundleContext.getService(ref);
+ Object service = bundleContext.getService(ref);
try {
- if (appCtx instanceof ConfigurableOsgiBundleApplicationContext) {
- ConfigurableOsgiBundleApplicationContext cAppCtx = (ConfigurableOsgiBundleApplicationContext) appCtx;
- if (bundleContext == cAppCtx.getBundleContext()) {
- return new ModuleContextWrapper(cAppCtx);
+ // Avoid kernel region application contexts.
+ if (service instanceof ApplicationContext) {
+ ApplicationContext appCtx = (ApplicationContext) service;
+ if (appCtx instanceof ConfigurableOsgiBundleApplicationContext) {
+ ConfigurableOsgiBundleApplicationContext cAppCtx = (ConfigurableOsgiBundleApplicationContext) appCtx;
+ if (bundleContext == cAppCtx.getBundleContext()) {
+ return new ModuleContextWrapper(cAppCtx);
+ }
}
}
} finally {
bundleContext.ungetService(ref);
}
}
}
} catch (InvalidSyntaxException e) {
Assert.isFalse(true, "Unexpected exception %s", e.getMessage());
}
}
return null;
}
}
| false | true | public ModuleContext getModuleContext(@NonNull Bundle bundle) {
BundleContext bundleContext = bundle.getBundleContext();
// The bundle must have a bundle context in order to have a module context.
if (bundleContext != null) {
String symbolicName = bundle.getSymbolicName();
try {
Collection<ServiceReference<ApplicationContext>> refs = bundleContext.getServiceReferences(ApplicationContext.class,
"(Bundle-SymbolicName=" + symbolicName + ")");
if (refs.size() != 0) {
for (ServiceReference<ApplicationContext> ref : refs) {
ApplicationContext appCtx = (ApplicationContext) bundleContext.getService(ref);
try {
if (appCtx instanceof ConfigurableOsgiBundleApplicationContext) {
ConfigurableOsgiBundleApplicationContext cAppCtx = (ConfigurableOsgiBundleApplicationContext) appCtx;
if (bundleContext == cAppCtx.getBundleContext()) {
return new ModuleContextWrapper(cAppCtx);
}
}
} finally {
bundleContext.ungetService(ref);
}
}
}
} catch (InvalidSyntaxException e) {
Assert.isFalse(true, "Unexpected exception %s", e.getMessage());
}
}
return null;
}
| public ModuleContext getModuleContext(@NonNull Bundle bundle) {
BundleContext bundleContext = bundle.getBundleContext();
// The bundle must have a bundle context in order to have a module context.
if (bundleContext != null) {
String symbolicName = bundle.getSymbolicName();
try {
Collection<ServiceReference<ApplicationContext>> refs = bundleContext.getServiceReferences(ApplicationContext.class,
"(Bundle-SymbolicName=" + symbolicName + ")");
if (refs.size() != 0) {
for (ServiceReference<ApplicationContext> ref : refs) {
Object service = bundleContext.getService(ref);
try {
// Avoid kernel region application contexts.
if (service instanceof ApplicationContext) {
ApplicationContext appCtx = (ApplicationContext) service;
if (appCtx instanceof ConfigurableOsgiBundleApplicationContext) {
ConfigurableOsgiBundleApplicationContext cAppCtx = (ConfigurableOsgiBundleApplicationContext) appCtx;
if (bundleContext == cAppCtx.getBundleContext()) {
return new ModuleContextWrapper(cAppCtx);
}
}
}
} finally {
bundleContext.ungetService(ref);
}
}
}
} catch (InvalidSyntaxException e) {
Assert.isFalse(true, "Unexpected exception %s", e.getMessage());
}
}
return null;
}
|
diff --git a/nuxeo-platform-suggestbox-core/src/main/java/org/nuxeo/ecm/platform/suggestbox/service/suggesters/DocumentSearchByDateSuggester.java b/nuxeo-platform-suggestbox-core/src/main/java/org/nuxeo/ecm/platform/suggestbox/service/suggesters/DocumentSearchByDateSuggester.java
index 091a144..c3f688c 100644
--- a/nuxeo-platform-suggestbox-core/src/main/java/org/nuxeo/ecm/platform/suggestbox/service/suggesters/DocumentSearchByDateSuggester.java
+++ b/nuxeo-platform-suggestbox-core/src/main/java/org/nuxeo/ecm/platform/suggestbox/service/suggesters/DocumentSearchByDateSuggester.java
@@ -1,91 +1,91 @@
package org.nuxeo.ecm.platform.suggestbox.service.suggesters;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.nuxeo.ecm.platform.suggestbox.service.CommonSuggestionTypes;
import org.nuxeo.ecm.platform.suggestbox.service.ComponentInitializationException;
import org.nuxeo.ecm.platform.suggestbox.service.SearchDocumentsSuggestion;
import org.nuxeo.ecm.platform.suggestbox.service.Suggester;
import org.nuxeo.ecm.platform.suggestbox.service.Suggestion;
import org.nuxeo.ecm.platform.suggestbox.service.SuggestionContext;
import org.nuxeo.ecm.platform.suggestbox.service.SuggestionException;
import org.nuxeo.ecm.platform.suggestbox.service.descriptors.SuggesterDescriptor;
import org.nuxeo.ecm.platform.suggestbox.utils.DateMatcher;
/**
* Simple stateless suggester that parses the input and suggest to search
* document by date if the input can be interpreted as a date in the user
* locale.
*/
public class DocumentSearchByDateSuggester implements Suggester {
final static String type = CommonSuggestionTypes.SEARCH_DOCUMENTS;
final static String LABEL_BEFORE_PREFIX = "label.search.beforeDate_";
final static String LABEL_AFTER_PREFIX = "label.search.afterDate_";
protected String[] searchFields;
protected String label;
protected String iconURL;
@Override
public List<Suggestion> suggest(String userInput, SuggestionContext context)
throws SuggestionException {
List<Suggestion> suggestions = new ArrayList<Suggestion>();
I18nHelper i18n = I18nHelper.instanceFor(context.messages);
// TODO: use SimpleDateFormat and use the locale information from the
// context
DateMatcher matcher = DateMatcher.fromInput(userInput);
DateFormat labelDateFormatter = SimpleDateFormat.getDateInstance(
SimpleDateFormat.MEDIUM, context.locale);
if (matcher.hasMatch()) {
Date date = matcher.getDateSuggestion().getTime();
String formattedDateLabel = labelDateFormatter.format(date);
for (String field : searchFields) {
- String searchFieldAfter = field + "_min ";
+ String searchFieldAfter = field + "_min";
String labelAfterPrefix = LABEL_AFTER_PREFIX
+ field.replace(':', '_');
String labelAfter = i18n.translate(labelAfterPrefix,
formattedDateLabel);
suggestions.add(new SearchDocumentsSuggestion(labelAfter,
iconURL).withSearchCriterion(searchFieldAfter, date));
- String searchFieldBefore = field + "_max ";
+ String searchFieldBefore = field + "_max";
String labelBeforePrefix = LABEL_BEFORE_PREFIX
+ field.replace(':', '_');
String labelBefore = i18n.translate(labelBeforePrefix,
formattedDateLabel);
suggestions.add(new SearchDocumentsSuggestion(labelBefore,
iconURL).withSearchCriterion(searchFieldBefore, date));
}
}
return suggestions;
}
@Override
public void initWithParameters(SuggesterDescriptor descriptor)
throws ComponentInitializationException {
Map<String, String> params = descriptor.getParameters();
iconURL = params.get("iconURL");
String searchFields = params.get("searchFields");
if (searchFields == null || iconURL == null) {
throw new ComponentInitializationException(
String.format("Could not initialize suggester '%s': "
+ "searchFields and iconURL"
+ " are mandatory parameters", descriptor.getName()));
}
this.searchFields = searchFields.split(", *");
}
}
| false | true | public List<Suggestion> suggest(String userInput, SuggestionContext context)
throws SuggestionException {
List<Suggestion> suggestions = new ArrayList<Suggestion>();
I18nHelper i18n = I18nHelper.instanceFor(context.messages);
// TODO: use SimpleDateFormat and use the locale information from the
// context
DateMatcher matcher = DateMatcher.fromInput(userInput);
DateFormat labelDateFormatter = SimpleDateFormat.getDateInstance(
SimpleDateFormat.MEDIUM, context.locale);
if (matcher.hasMatch()) {
Date date = matcher.getDateSuggestion().getTime();
String formattedDateLabel = labelDateFormatter.format(date);
for (String field : searchFields) {
String searchFieldAfter = field + "_min ";
String labelAfterPrefix = LABEL_AFTER_PREFIX
+ field.replace(':', '_');
String labelAfter = i18n.translate(labelAfterPrefix,
formattedDateLabel);
suggestions.add(new SearchDocumentsSuggestion(labelAfter,
iconURL).withSearchCriterion(searchFieldAfter, date));
String searchFieldBefore = field + "_max ";
String labelBeforePrefix = LABEL_BEFORE_PREFIX
+ field.replace(':', '_');
String labelBefore = i18n.translate(labelBeforePrefix,
formattedDateLabel);
suggestions.add(new SearchDocumentsSuggestion(labelBefore,
iconURL).withSearchCriterion(searchFieldBefore, date));
}
}
return suggestions;
}
| public List<Suggestion> suggest(String userInput, SuggestionContext context)
throws SuggestionException {
List<Suggestion> suggestions = new ArrayList<Suggestion>();
I18nHelper i18n = I18nHelper.instanceFor(context.messages);
// TODO: use SimpleDateFormat and use the locale information from the
// context
DateMatcher matcher = DateMatcher.fromInput(userInput);
DateFormat labelDateFormatter = SimpleDateFormat.getDateInstance(
SimpleDateFormat.MEDIUM, context.locale);
if (matcher.hasMatch()) {
Date date = matcher.getDateSuggestion().getTime();
String formattedDateLabel = labelDateFormatter.format(date);
for (String field : searchFields) {
String searchFieldAfter = field + "_min";
String labelAfterPrefix = LABEL_AFTER_PREFIX
+ field.replace(':', '_');
String labelAfter = i18n.translate(labelAfterPrefix,
formattedDateLabel);
suggestions.add(new SearchDocumentsSuggestion(labelAfter,
iconURL).withSearchCriterion(searchFieldAfter, date));
String searchFieldBefore = field + "_max";
String labelBeforePrefix = LABEL_BEFORE_PREFIX
+ field.replace(':', '_');
String labelBefore = i18n.translate(labelBeforePrefix,
formattedDateLabel);
suggestions.add(new SearchDocumentsSuggestion(labelBefore,
iconURL).withSearchCriterion(searchFieldBefore, date));
}
}
return suggestions;
}
|
diff --git a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/impl/query/PreparedCubeQuery.java b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/impl/query/PreparedCubeQuery.java
index 1a34b0aba..d2a767e42 100644
--- a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/impl/query/PreparedCubeQuery.java
+++ b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/impl/query/PreparedCubeQuery.java
@@ -1,199 +1,197 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.olap.impl.query;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.data.engine.api.DataEngineContext;
import org.eclipse.birt.data.engine.api.IBaseQueryResults;
import org.eclipse.birt.data.engine.api.IDataScriptEngine;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.impl.DataEngineSession;
import org.eclipse.birt.data.engine.olap.api.ICubeQueryResults;
import org.eclipse.birt.data.engine.olap.api.IPreparedCubeQuery;
import org.eclipse.birt.data.engine.olap.api.query.IBaseCubeQueryDefinition;
import org.eclipse.birt.data.engine.olap.api.query.ICubeQueryDefinition;
import org.eclipse.birt.data.engine.olap.util.OlapQueryUtil;
import org.mozilla.javascript.Scriptable;
/**
*
*/
public class PreparedCubeQuery implements IPreparedCubeQuery
{
private ICubeQueryDefinition cubeQueryDefn;
private DataEngineSession session;
private DataEngineContext context;
private Map appContext;
/**
*
* @param defn
* @param scope
*/
public PreparedCubeQuery( ICubeQueryDefinition defn, DataEngineSession session, DataEngineContext context, Map appContext ) throws DataException
{
this.cubeQueryDefn = defn;
this.session = session;
this.context = context;
this.appContext = appContext;
if ( !containsDrillFilter( defn ) )
validateQuery( );
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.olap.api.IPreparedCubeQuery#execute(org.mozilla.javascript.Scriptable)
*/
public ICubeQueryResults execute( Scriptable scope ) throws DataException
{
return this.execute( null, scope );
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.olap.api.IPreparedCubeQuery#execute(org.eclipse.birt.data.engine.api.IBaseQueryResults, org.mozilla.javascript.Scriptable)
*/
public ICubeQueryResults execute( IBaseQueryResults outerResults, Scriptable scope ) throws DataException
{
Scriptable cubeScope = null;
try
{
// Create a scope for each query execution.
cubeScope = ( (IDataScriptEngine) session.getEngineContext( )
.getScriptContext( )
.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSContext( session.getEngineContext( )
- .getScriptContext( ) )
- .newObject( scope == null ? this.session.getSharedScope( )
- : scope );
+ .getScriptContext( ) ).initStandardObjects( );
cubeScope.setParentScope( scope == null
? this.session.getSharedScope( ) : scope );
cubeScope.setPrototype( scope == null
? this.session.getSharedScope( ) : scope );
}
catch ( BirtException e )
{
throw DataException.wrap( e );
}
Object delegateObject = null;
try
{
delegateObject = Thread.currentThread( )
.getContextClassLoader( )
.loadClass( "org.eclipse.birt.data.engine.olap.impl.query.PreparedCubeQueryDelegate" )
.getConstructor( ICubeQueryDefinition.class,
DataEngineSession.class,
DataEngineContext.class,
Map.class )
.newInstance( cubeQueryDefn, session, context, appContext );
}
catch ( ClassNotFoundException e )
{
}
catch ( InstantiationException e )
{
}
catch ( IllegalAccessException e )
{
}
catch ( SecurityException e )
{
}
catch ( IllegalArgumentException e )
{
}
catch ( InvocationTargetException e )
{
}
catch ( NoSuchMethodException e )
{
}
if( delegateObject != null )
{
try
{
Method method = delegateObject.getClass( )
.getMethod( "execute", new Class[]{
IBaseQueryResults.class, Scriptable.class
} );
return (ICubeQueryResults) method.invoke( delegateObject,
new Object[]{
outerResults, scope
} );
}
catch ( SecurityException e )
{
}
catch ( NoSuchMethodException e )
{
}
catch ( IllegalArgumentException e )
{
}
catch ( IllegalAccessException e )
{
}
catch ( InvocationTargetException e )
{
}
}
return new CubeQueryResults( outerResults,
this,
this.session,
cubeScope,
this.context,
appContext );
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.olap.api.IPreparedCubeQuery#getCubeQueryDefinition()
*/
public IBaseCubeQueryDefinition getCubeQueryDefinition( )
{
return this.cubeQueryDefn;
}
private void validateQuery( ) throws DataException
{
validateBinding( );
}
private void validateBinding( ) throws DataException
{
OlapQueryUtil.validateBinding( cubeQueryDefn, false );
}
private boolean containsDrillFilter( ICubeQueryDefinition defn )
{
if ( defn.getEdge( ICubeQueryDefinition.ROW_EDGE ) != null
&& !defn.getEdge( ICubeQueryDefinition.ROW_EDGE )
.getDrillFilter( )
.isEmpty( ) )
{
return true;
}
if ( defn.getEdge( ICubeQueryDefinition.COLUMN_EDGE ) != null
&& !defn.getEdge( ICubeQueryDefinition.COLUMN_EDGE )
.getDrillFilter( )
.isEmpty( ) )
{
return true;
}
return false;
}
}
| true | true | public ICubeQueryResults execute( IBaseQueryResults outerResults, Scriptable scope ) throws DataException
{
Scriptable cubeScope = null;
try
{
// Create a scope for each query execution.
cubeScope = ( (IDataScriptEngine) session.getEngineContext( )
.getScriptContext( )
.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSContext( session.getEngineContext( )
.getScriptContext( ) )
.newObject( scope == null ? this.session.getSharedScope( )
: scope );
cubeScope.setParentScope( scope == null
? this.session.getSharedScope( ) : scope );
cubeScope.setPrototype( scope == null
? this.session.getSharedScope( ) : scope );
}
catch ( BirtException e )
{
throw DataException.wrap( e );
}
Object delegateObject = null;
try
{
delegateObject = Thread.currentThread( )
.getContextClassLoader( )
.loadClass( "org.eclipse.birt.data.engine.olap.impl.query.PreparedCubeQueryDelegate" )
.getConstructor( ICubeQueryDefinition.class,
DataEngineSession.class,
DataEngineContext.class,
Map.class )
.newInstance( cubeQueryDefn, session, context, appContext );
}
catch ( ClassNotFoundException e )
{
}
catch ( InstantiationException e )
{
}
catch ( IllegalAccessException e )
{
}
catch ( SecurityException e )
{
}
catch ( IllegalArgumentException e )
{
}
catch ( InvocationTargetException e )
{
}
catch ( NoSuchMethodException e )
{
}
if( delegateObject != null )
{
try
{
Method method = delegateObject.getClass( )
.getMethod( "execute", new Class[]{
IBaseQueryResults.class, Scriptable.class
} );
return (ICubeQueryResults) method.invoke( delegateObject,
new Object[]{
outerResults, scope
} );
}
catch ( SecurityException e )
{
}
catch ( NoSuchMethodException e )
{
}
catch ( IllegalArgumentException e )
{
}
catch ( IllegalAccessException e )
{
}
catch ( InvocationTargetException e )
{
}
}
return new CubeQueryResults( outerResults,
this,
this.session,
cubeScope,
this.context,
appContext );
}
| public ICubeQueryResults execute( IBaseQueryResults outerResults, Scriptable scope ) throws DataException
{
Scriptable cubeScope = null;
try
{
// Create a scope for each query execution.
cubeScope = ( (IDataScriptEngine) session.getEngineContext( )
.getScriptContext( )
.getScriptEngine( IDataScriptEngine.ENGINE_NAME ) ).getJSContext( session.getEngineContext( )
.getScriptContext( ) ).initStandardObjects( );
cubeScope.setParentScope( scope == null
? this.session.getSharedScope( ) : scope );
cubeScope.setPrototype( scope == null
? this.session.getSharedScope( ) : scope );
}
catch ( BirtException e )
{
throw DataException.wrap( e );
}
Object delegateObject = null;
try
{
delegateObject = Thread.currentThread( )
.getContextClassLoader( )
.loadClass( "org.eclipse.birt.data.engine.olap.impl.query.PreparedCubeQueryDelegate" )
.getConstructor( ICubeQueryDefinition.class,
DataEngineSession.class,
DataEngineContext.class,
Map.class )
.newInstance( cubeQueryDefn, session, context, appContext );
}
catch ( ClassNotFoundException e )
{
}
catch ( InstantiationException e )
{
}
catch ( IllegalAccessException e )
{
}
catch ( SecurityException e )
{
}
catch ( IllegalArgumentException e )
{
}
catch ( InvocationTargetException e )
{
}
catch ( NoSuchMethodException e )
{
}
if( delegateObject != null )
{
try
{
Method method = delegateObject.getClass( )
.getMethod( "execute", new Class[]{
IBaseQueryResults.class, Scriptable.class
} );
return (ICubeQueryResults) method.invoke( delegateObject,
new Object[]{
outerResults, scope
} );
}
catch ( SecurityException e )
{
}
catch ( NoSuchMethodException e )
{
}
catch ( IllegalArgumentException e )
{
}
catch ( IllegalAccessException e )
{
}
catch ( InvocationTargetException e )
{
}
}
return new CubeQueryResults( outerResults,
this,
this.session,
cubeScope,
this.context,
appContext );
}
|
diff --git a/gae/src/org/tangram/gae/GaeBeanFactory.java b/gae/src/org/tangram/gae/GaeBeanFactory.java
index 5e07984c..a5008a80 100644
--- a/gae/src/org/tangram/gae/GaeBeanFactory.java
+++ b/gae/src/org/tangram/gae/GaeBeanFactory.java
@@ -1,137 +1,137 @@
/**
*
* Copyright 2013 Martin Goellnitz
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.tangram.gae;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jmx.access.InvocationFailureException;
import org.tangram.content.Content;
import org.tangram.jdo.AbstractJdoBeanFactory;
import org.tangram.mutable.MutableCode;
public class GaeBeanFactory extends AbstractJdoBeanFactory {
private static final Log log = LogFactory.getLog(GaeBeanFactory.class);
private boolean useHdrDatastore = true;
public boolean isUseHdrDatastore() {
return useHdrDatastore;
}
public void setUseHdrDatastore(boolean useHdrDatastore) {
this.useHdrDatastore = useHdrDatastore;
}
/**
* set cross group transactions only to true on HDR data stores.
*
* So projects which actually don't use it can still run in the same setup.
*/
@Override
protected Map<? extends Object, ? extends Object> getFactoryConfigOverrides() {
Map<Object, Object> result = new HashMap<Object, Object>();
if (isUseHdrDatastore()) {
result.put("datanucleus.appengine.datastoreEnableXGTransactions", Boolean.TRUE);
} // if
return result;
} // getFactoryConfigOverrides()
/**
* we had to override the whole getBeans, so this one should never be called.
*/
@Override
protected Object getObjectId(String internalId, Class<? extends Content> kindClass) {
throw new InvocationFailureException("GAE implementation is somewhat different");
} // getObjectId()
@Override
@SuppressWarnings("unchecked")
public <T extends Content> T getBean(Class<T> cls, String id) {
- if (activateCaching&&(cache.containsKey(id))) {
+ if (isActivateCaching()&&(cache.containsKey(id))) {
statistics.increase("get bean cached");
return (T) cache.get(id);
} // if
T result = null;
try {
Key key = null;
String kind = null;
long numericId = 0;
int idx = id.indexOf(':');
if (idx>0) {
kind = id.substring(0, idx);
numericId = Long.parseLong(id.substring(idx+1));
} else {
if (id.length()>25) {
Key k = KeyFactory.stringToKey(id);
kind = k.getKind();
numericId = k.getId();
} // if
} // if
if (log.isDebugEnabled()) {
log.debug("getBean() kind="+kind);
log.debug("getBean() numericId="+numericId);
} // if
key = KeyFactory.createKey(kind, numericId);
if (modelClasses==null) {
getClasses();
} // if
Class<? extends Content> kindClass = tableNameMapping.get(kind);
if (!(cls.isAssignableFrom(kindClass))) {
throw new Exception("Passed over class "+cls.getSimpleName()+" does not match "+kindClass.getSimpleName());
} // if
result = (T) manager.getObjectById(kindClass, key);
result.setBeanFactory(this);
- if (activateCaching) {
+ if (isActivateCaching()) {
cache.put(id, result);
} // if
} catch (Exception e) {
if (log.isWarnEnabled()) {
String simpleName = e.getClass().getSimpleName();
log.warn("getBean() object not found for id '"+id+"' "+simpleName+": "+e.getLocalizedMessage(), e);
} // if
} // try/catch/finally
statistics.increase("get bean uncached");
return result;
} // getBean()
@Override
protected String getClassNamesCacheKey() {
return com.google.appengine.api.utils.SystemProperty.applicationVersion.get();
} // getClassNamesCacheKey()
@Override
public Class<? extends MutableCode> getCodeClass() {
return Code.class;
} // getCodeClass()
} // GaeBeanFactory
| false | true | public <T extends Content> T getBean(Class<T> cls, String id) {
if (activateCaching&&(cache.containsKey(id))) {
statistics.increase("get bean cached");
return (T) cache.get(id);
} // if
T result = null;
try {
Key key = null;
String kind = null;
long numericId = 0;
int idx = id.indexOf(':');
if (idx>0) {
kind = id.substring(0, idx);
numericId = Long.parseLong(id.substring(idx+1));
} else {
if (id.length()>25) {
Key k = KeyFactory.stringToKey(id);
kind = k.getKind();
numericId = k.getId();
} // if
} // if
if (log.isDebugEnabled()) {
log.debug("getBean() kind="+kind);
log.debug("getBean() numericId="+numericId);
} // if
key = KeyFactory.createKey(kind, numericId);
if (modelClasses==null) {
getClasses();
} // if
Class<? extends Content> kindClass = tableNameMapping.get(kind);
if (!(cls.isAssignableFrom(kindClass))) {
throw new Exception("Passed over class "+cls.getSimpleName()+" does not match "+kindClass.getSimpleName());
} // if
result = (T) manager.getObjectById(kindClass, key);
result.setBeanFactory(this);
if (activateCaching) {
cache.put(id, result);
} // if
} catch (Exception e) {
if (log.isWarnEnabled()) {
String simpleName = e.getClass().getSimpleName();
log.warn("getBean() object not found for id '"+id+"' "+simpleName+": "+e.getLocalizedMessage(), e);
} // if
} // try/catch/finally
statistics.increase("get bean uncached");
return result;
} // getBean()
| public <T extends Content> T getBean(Class<T> cls, String id) {
if (isActivateCaching()&&(cache.containsKey(id))) {
statistics.increase("get bean cached");
return (T) cache.get(id);
} // if
T result = null;
try {
Key key = null;
String kind = null;
long numericId = 0;
int idx = id.indexOf(':');
if (idx>0) {
kind = id.substring(0, idx);
numericId = Long.parseLong(id.substring(idx+1));
} else {
if (id.length()>25) {
Key k = KeyFactory.stringToKey(id);
kind = k.getKind();
numericId = k.getId();
} // if
} // if
if (log.isDebugEnabled()) {
log.debug("getBean() kind="+kind);
log.debug("getBean() numericId="+numericId);
} // if
key = KeyFactory.createKey(kind, numericId);
if (modelClasses==null) {
getClasses();
} // if
Class<? extends Content> kindClass = tableNameMapping.get(kind);
if (!(cls.isAssignableFrom(kindClass))) {
throw new Exception("Passed over class "+cls.getSimpleName()+" does not match "+kindClass.getSimpleName());
} // if
result = (T) manager.getObjectById(kindClass, key);
result.setBeanFactory(this);
if (isActivateCaching()) {
cache.put(id, result);
} // if
} catch (Exception e) {
if (log.isWarnEnabled()) {
String simpleName = e.getClass().getSimpleName();
log.warn("getBean() object not found for id '"+id+"' "+simpleName+": "+e.getLocalizedMessage(), e);
} // if
} // try/catch/finally
statistics.increase("get bean uncached");
return result;
} // getBean()
|
diff --git a/src/org/gridsphere/provider/portletui/beans/GroupBean.java b/src/org/gridsphere/provider/portletui/beans/GroupBean.java
index 64709daf9..4b23e17e8 100644
--- a/src/org/gridsphere/provider/portletui/beans/GroupBean.java
+++ b/src/org/gridsphere/provider/portletui/beans/GroupBean.java
@@ -1,58 +1,58 @@
package org.gridsphere.provider.portletui.beans;
/**
* The <code>GroupBean</code> provides a way to visually group elements with an optional label.
*/
public class GroupBean extends BaseComponentBean implements TagBean {
private String label = null;
private String height = null;
private String width = null;
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getWidth() {
return width;
}
public void setWidth(String width) {
this.width = width;
}
public String toStartString() {
- if (width != null) this.addCssStyle(" width=\"" + width + "\" ");
- if (height != null) this.addCssStyle(" height=\"" + height + "\" ");
+ if (width != null) this.addCssStyle(" width:" + width + "; ");
+ if (height != null) this.addCssStyle(" height:" + height + "; ");
StringBuffer sb = new StringBuffer();
sb.append("<fieldset");
sb.append(getFormattedCss());
sb.append(">");
if (this.label != null) {
sb.append("<legend>");
sb.append(label);
sb.append("</legend>");
}
return sb.toString();
}
public String toEndString() {
return "</fieldset>";
}
}
| true | true | public String toStartString() {
if (width != null) this.addCssStyle(" width=\"" + width + "\" ");
if (height != null) this.addCssStyle(" height=\"" + height + "\" ");
StringBuffer sb = new StringBuffer();
sb.append("<fieldset");
sb.append(getFormattedCss());
sb.append(">");
if (this.label != null) {
sb.append("<legend>");
sb.append(label);
sb.append("</legend>");
}
return sb.toString();
}
| public String toStartString() {
if (width != null) this.addCssStyle(" width:" + width + "; ");
if (height != null) this.addCssStyle(" height:" + height + "; ");
StringBuffer sb = new StringBuffer();
sb.append("<fieldset");
sb.append(getFormattedCss());
sb.append(">");
if (this.label != null) {
sb.append("<legend>");
sb.append(label);
sb.append("</legend>");
}
return sb.toString();
}
|
diff --git a/src/main/java/de/jetwick/ui/HomePage.java b/src/main/java/de/jetwick/ui/HomePage.java
index 53a3a6e..ab2b1be 100644
--- a/src/main/java/de/jetwick/ui/HomePage.java
+++ b/src/main/java/de/jetwick/ui/HomePage.java
@@ -1,826 +1,828 @@
/**
* Copyright (C) 2010 Peter Karich <jetwick_@_pannous_._info>
*
* 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 de.jetwick.ui;
import de.jetwick.tw.MyTweetGrabber;
import com.google.inject.Inject;
import com.google.inject.Provider;
import de.jetwick.data.UrlEntry;
import de.jetwick.es.ElasticTweetSearch;
import de.jetwick.es.ElasticUserSearch;
import de.jetwick.es.JetwickQuery;
import de.jetwick.es.SavedSearch;
import de.jetwick.es.SimilarQuery;
import de.jetwick.data.JTweet;
import de.jetwick.data.JUser;
import de.jetwick.es.TweetQuery;
import de.jetwick.tw.TwitterSearch;
import de.jetwick.tw.queue.QueueThread;
import de.jetwick.ui.jschart.JSDateFilter;
import de.jetwick.util.Helper;
import de.jetwick.wikipedia.WikipediaLazyLoadPanel;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import org.apache.wicket.PageParameters;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.Model;
import org.apache.wicket.protocol.http.WebRequest;
import org.apache.wicket.protocol.http.WebResponse;
import org.apache.wicket.request.target.basic.RedirectRequestTarget;
import org.elasticsearch.action.search.SearchResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import twitter4j.TwitterException;
import twitter4j.http.AccessToken;
/**
* TODO clean up this bloated class
* @author Peter Karich, peat_hal 'at' users 'dot' sourceforge 'dot' net
*/
public class HomePage extends WebPage {
private static final long serialVersionUID = 1L;
private final Logger logger = LoggerFactory.getLogger(getClass());
private JetwickQuery lastQuery;
private int hitsPerPage = 15;
private FeedbackPanel feedbackPanel;
private ResultsPanel resultsPanel;
private FacetPanel facetPanel;
private SavedSearchPanel ssPanel;
private TagCloudPanel tagCloud;
private NavigationPanel navigationPanel;
private SearchBox searchBox;
private String language = "en";
private String remoteHost = "";
private WikipediaLazyLoadPanel wikiPanel;
private UrlTrendPanel urlTrends;
@Inject
private Provider<ElasticTweetSearch> twindexProvider;
@Inject
private Provider<ElasticUserSearch> uindexProvider;
@Inject
private MyTweetGrabber grabber;
private JSDateFilter dateFilter;
private transient Thread tweetThread;
private static int TWEETS_IF_HIT = 30;
private static int TWEETS_IF_NO_HIT = 40;
private String userName = "";
// for testing
HomePage() {
}
HomePage(JetwickQuery q) {
init(q, PageParameters.NULL, 0, false);
}
public HomePage(final PageParameters parameters) {
String callback = parameters.getString("callback");
if ("true".equals(callback)) {
try {
logger.info("Received callback");
AccessToken token = CallbackHelper.getParseTwitterUrl(getTwitterSearch(), parameters);
getMySession().setTwitterSearch(token, uindexProvider.get(), (WebResponse) getResponse());
} catch (Exception ex) {
logger.error("Error while receiving callback", ex);
String msg = TwitterSearch.getMessage(ex);
if (msg.length() > 0)
error(msg);
else
error("Error when getting information from twitter! Please login again!");
getMySession().logout(uindexProvider.get(), (WebResponse) getResponse());
}
// avoid showing the url parameters (e.g. refresh would let it failure!)
setRedirect(true);
setResponsePage(HomePage.class);
} else {
initSession();
init(createQuery(parameters), parameters, 0, true);
}
}
private void initSession() {
try {
getMySession().init((WebRequest) getRequest(), uindexProvider.get());
String msg = getMySession().getSessionTimeOutMessage();
if (!msg.isEmpty())
warn(msg);
} catch (Exception ex) {
logger.error("Error on twitter4j init.", ex);
error("Couldn't login. Please file report to http://twitter.com/jetwick " + new Date());
}
}
@Override
protected void configureResponse() {
super.configureResponse();
// 1. searchAndGetUsers for wikileak
// 2. apply de filter
// 3. Show latest tweets (of user sebringl)
// back button + de filter => WicketRuntimeException: component filterPanel:filterNames:1:filterValues:2:filterValueLink not found on page de.jetwick.ui.HomePage
// http://www.richardnichols.net/2010/03/apache-wicket-force-page-reload-to-fix-ajax-back/
// http://blogs.atlassian.com/developer/2007/12/cachecontrol_nostore_considere.html
// TODO M2.1
WebResponse response = getWebRequestCycle().getWebResponse();
response.setHeader("Cache-Control", "no-cache, max-age=0,must-revalidate, no-store");
}
public ElasticTweetSearch getTweetSearch() {
return twindexProvider.get();
}
public TwitterSearch getTwitterSearch() {
return getMySession().getTwitterSearch();
}
public MySession getMySession() {
return (MySession) getSession();
}
public Thread getQueueThread() {
return tweetThread;
}
public JetwickQuery createQuery(PageParameters parameters) {
// TODO M2.1 parameters.get("hits").toString can cause NPE!!
String hitsStr = parameters.getString("hits");
if (hitsStr != null) {
try {
hitsPerPage = Integer.parseInt(hitsStr);
hitsPerPage = Math.min(100, hitsPerPage);
} catch (Exception ex) {
logger.warn("Couldn't parse hits per page:" + hitsStr + " " + ex.getMessage());
}
}
String idStr = parameters.getString("id");
JetwickQuery q = null;
if (idStr != null) {
try {
int index = idStr.lastIndexOf("/");
if (index > 0 && index + 1 < idStr.length())
idStr = idStr.substring(index + 1);
q = new TweetQuery(true).createIdQuery(Long.parseLong(idStr));
} catch (Exception ignore) {
}
}
if (q == null) {
String originStr = parameters.getString("findOrigin");
if (originStr != null) {
logger.info("[stats] findOrigin from lastQuery:" + lastQuery);
q = getTweetSearch().createFindOriginQuery(lastQuery, originStr, 3);
}
}
String queryStr = parameters.getString("q");
if (queryStr == null)
queryStr = "";
userName = "";
if (q == null) {
userName = parameters.getString("u");
if (userName == null)
userName = parameters.getString("user");
if (userName == null)
userName = "";
q = new TweetQuery(queryStr).addUserFilter(userName);
}
String fromDateStr = parameters.getString("until");
if (fromDateStr != null) {
if (!fromDateStr.contains("T"))
fromDateStr += "T00:00:00Z";
q.addFilterQuery(ElasticTweetSearch.DATE, "[" + fromDateStr + " TO *]");
}
// front page/empty => sort against relevance
// user search => sort against latest date
// other => sort against retweets if no sort specified
String sort = parameters.getString("sort");
if ("retweets".equals(sort))
q.setSort(ElasticTweetSearch.RT_COUNT, "desc");
else if ("latest".equals(sort))
q.setSort(ElasticTweetSearch.DATE, "desc");
else if ("oldest".equals(sort))
q.setSort(ElasticTweetSearch.DATE, "asc");
else if ("relevance".equals(sort))
q.setSort(ElasticTweetSearch.RELEVANCE, "desc");
else {
q.setSort(ElasticTweetSearch.RT_COUNT, "desc");
if (!Helper.isEmpty(userName))
q.setSort(ElasticTweetSearch.DATE, "desc");
}
// front page: avoid slow queries for matchall query and filter against latest tweets only
if (queryStr.isEmpty() && q.getFilterQueries().isEmpty() && fromDateStr == null) {
logger.info(addIP("[stats] q=''"));
q.addLatestDateFilter(8);
if (Helper.isEmpty(sort))
q.setSort(ElasticTweetSearch.RELEVANCE, "desc");
}
String filter = parameters.getString("filter");
if (Helper.isEmpty(userName) && !"none".equals(filter)) {
q.addNoSpamFilter().addNoDupsFilter().addIsOriginalTweetFilter();
}
return q;
}
public void updateAfterAjax(AjaxRequestTarget target, boolean updateSearchBox) {
if (target != null) {
target.addComponent(facetPanel);
target.addComponent(resultsPanel);
//already in resultsPanel target.addComponent(lazyLoadAdPanel);
target.addComponent(navigationPanel);
if (updateSearchBox)
target.addComponent(searchBox);
target.addComponent(tagCloud);
target.addComponent(dateFilter);
target.addComponent(urlTrends);
target.addComponent(feedbackPanel);
target.addComponent(ssPanel);
// no ajax for wikipedia to avoid requests
//target.addComponent(wikiPanel);
// this does not work (scroll to top)
// target.focusComponent(searchBox);
}
}
public void init(JetwickQuery query, PageParameters parameters, int page, boolean twitterFallback) {
setStatelessHint(true);
feedbackPanel = new FeedbackPanel("feedback");
add(feedbackPanel.setOutputMarkupId(true));
add(new Label("title", new Model() {
@Override
public Serializable getObject() {
String str = "";
if (!searchBox.getQuery().isEmpty())
str += searchBox.getQuery() + " ";
if (!searchBox.getUserName().isEmpty()) {
if (str.isEmpty())
str = "User " + searchBox.getUserName() + " ";
else
str = "Search " + str + "in user " + searchBox.getUserName() + " ";
}
if (str.isEmpty())
return "Jetwick Twitter Search";
return "Jetwick | " + str + "| Twitter Search Without Noise";
}
}));
add(new ExternalLinksPanel("externalRefs"));
add(new ExternalLinksPanelRight("externalRefsRight"));
urlTrends = new UrlTrendPanel("urltrends") {
@Override
protected void onUrlClick(AjaxRequestTarget target, String name) {
JetwickQuery q;
if (lastQuery != null)
q = lastQuery;
else
q = new TweetQuery(true);
if (name == null) {
q.removeFilterQueries(ElasticTweetSearch.FIRST_URL_TITLE);
} else
q.addFilterQuery(ElasticTweetSearch.FIRST_URL_TITLE, name);
doSearch(q, 0, true);
updateAfterAjax(target, false);
}
@Override
protected void onDirectUrlClick(AjaxRequestTarget target, String name) {
if (lastQuery == null || name == null || name.isEmpty())
return;
TweetQuery q = new TweetQuery(true);
q.addFilterQuery(ElasticTweetSearch.FIRST_URL_TITLE, name);
try {
List<JTweet> tweets = getTweetSearch().collectObjects(getTweetSearch().search(q.setSize(1)));
if (tweets.size() > 0 && tweets.get(0).getUrlEntries().size() > 0) {
// TODO there could be more than 1 url!
UrlEntry entry = tweets.get(0).getUrlEntries().iterator().next();
getRequestCycle().setRequestTarget(new RedirectRequestTarget(entry.getResolvedUrl()));
}
} catch (Exception ex) {
logger.error("Error while executing onDirectUrlClick", ex);
}
}
};
add(urlTrends.setOutputMarkupId(true));
final String searchType = parameters.getString("search");
ssPanel = new SavedSearchPanel("savedSearches") {
@Override
public void onClick(AjaxRequestTarget target, long ssId) {
if (searchType != null && !searchType.isEmpty() && !SearchBox.ALL.equals(searchType)) {
warn("Removed user filter when executing your saved search");
searchBox.setSearchType(SearchBox.ALL);
}
JUser user = getMySession().getUser();
SavedSearch ss = user.getSavedSearch(ssId);
if (ss != null) {
doSearch(ss.getQuery(), 0, true);
uindexProvider.get().save(user, true);
}
updateSSCounts(target);
updateAfterAjax(target, true);
}
@Override
public void onRemove(AjaxRequestTarget target, long ssId) {
JUser user = getMySession().getUser();
user.removeSavedSearch(ssId);
uindexProvider.get().save(user, true);
updateSSCounts(target);
}
@Override
public void onSave(AjaxRequestTarget target, long ssId) {
SavedSearch ss = new SavedSearch(ssId, lastQuery);
JUser user = getMySession().getUser();
user.addSavedSearch(ss);
uindexProvider.get().save(user, true);
updateSSCounts(target);
}
@Override
public void updateSSCounts(AjaxRequestTarget target) {
try {
JUser user = getMySession().getUser();
if (user != null) {
update(getTweetSearch().updateSavedSearches(user.getSavedSearches()));
if (target != null)
target.addComponent(ssPanel);
logger.info("Updated saved search counts for " + user.getScreenName());
}
} catch (Exception ex) {
logger.error("Error while searching in savedSearches", ex);
}
}
@Override
public String translate(long id) {
SavedSearch ss = getMySession().getUser().getSavedSearch(id);
return ss.getName();
}
};
if (!getMySession().hasLoggedIn())
ssPanel.setVisible(false);
add(ssPanel.setOutputMarkupId(true));
add(new UserPanel("userPanel", this) {
@Override
public void onLogout() {
getMySession().logout(uindexProvider.get(), (WebResponse) getResponse());
setResponsePage(HomePage.class);
}
@Override
public void updateAfterAjax(AjaxRequestTarget target) {
HomePage.this.updateAfterAjax(target, false);
}
@Override
public void onShowTweets(AjaxRequestTarget target, String userName) {
doSearch(new TweetQuery(true).addUserFilter(userName), 0, false);
HomePage.this.updateAfterAjax(target, true);
}
@Override
protected Collection<String> getUserChoices(String input) {
return getTweetSearch().getUserChoices(lastQuery, input);
}
});
tagCloud = new TagCloudPanel("tagcloud") {
@Override
protected void onTagClick(String name) {
if (lastQuery != null) {
lastQuery.setQuery((lastQuery.getQuery() + " " + name).trim());
doSearch(lastQuery, 0, true);
} else {
// never happens?
PageParameters pp = new PageParameters();
pp.add("q", name);
setResponsePage(HomePage.class, pp);
}
}
@Override
protected void onFindOriginClick(String tag) {
PageParameters pp = new PageParameters();
pp.add("findOrigin", tag);
doSearch(createQuery(pp), 0, true);
// this preserves parameters but cannot be context sensitive!
// setResponsePage(HomePage.class, pp);
}
};
add(tagCloud.setOutputMarkupId(true));
navigationPanel = new NavigationPanel("navigation", hitsPerPage) {
@Override
public void onPageChange(AjaxRequestTarget target, int page) {
// this does not scroll to top:
// doOldSearch(page);
// updateAfterAjax(target);
doOldSearch(page);
}
};
add(navigationPanel.setOutputMarkupId(true));
facetPanel = new FacetPanel("filterPanel") {
public void onRemoveAllFilter(AjaxRequestTarget target, String key) {
if (lastQuery != null)
lastQuery.removeFilterQueries(key);
else {
logger.error("last query cannot be null but was! ... when clicking on facets!?");
return;
}
doOldSearch(0);
updateAfterAjax(target, false);
}
@Override
public void onFacetChange(AjaxRequestTarget target, String key, Object val, boolean selected) {
if (lastQuery != null) {
if (selected)
lastQuery.addFilterQuery(key, val);
else
lastQuery.removeFilterQuery(key, val);
} else {
logger.error("last query cannot be null but was! ... when clicking on facets!?");
return;
}
doOldSearch(0);
updateAfterAjax(target, false);
}
};
add(facetPanel.setOutputMarkupId(true));
dateFilter = new JSDateFilter("dateFilter") {
@Override
protected void onFacetChange(AjaxRequestTarget target, String filter, Boolean selected) {
if (lastQuery != null) {
if (selected == null) {
lastQuery.removeFilterQueries(filter);
} else if (selected) {
lastQuery.replaceFilterQuery(filter);
} else
lastQuery.reduceFilterQuery(filter);
} else {
logger.error("last query cannot be null but was! ... when clicking on facets!?");
return;
}
doOldSearch(0);
updateAfterAjax(target, false);
}
@Override
protected boolean isAlreadyFiltered(String key, Object val) {
if (lastQuery != null)
return lastQuery.containsFilter(key, val);
return false;
}
@Override
public String getFilterName(String key) {
return facetPanel.getFilterName(key);
}
};
add(dateFilter.setOutputMarkupId(true));
// TODO M2.1
language = getWebRequestCycle().getWebRequest().getHttpServletRequest().getLocale().getLanguage();
remoteHost = getWebRequestCycle().getWebRequest().getHttpServletRequest().getRemoteHost();
resultsPanel = new ResultsPanel("results", language) {
@Override
public void onSortClicked(AjaxRequestTarget target, String sortKey, String sortVal) {
if (lastQuery != null) {
lastQuery.setSort(sortKey, sortVal);
doSearch(lastQuery, 0, false);
updateAfterAjax(target, false);
}
}
@Override
public void onUserClick(String userName, String queryStr) {
PageParameters p = new PageParameters();
if (queryStr != null && !queryStr.isEmpty())
p.add("q", queryStr);
- if (userName != null)
+ if (userName != null) {
p.add("user", userName.trim());
+ searchBox.setSearchType(SearchBox.USER);
+ }
doSearch(createQuery(p), 0, true);
}
@Override
public Collection<JTweet> onTweetClick(long id, boolean retweet) {
logger.info("[stats] search replies of:" + id + " retweet:" + retweet);
return getTweetSearch().searchReplies(id, retweet);
}
@Override
public void onFindSimilar(JTweet tweet, AjaxRequestTarget target) {
JetwickQuery query = new SimilarQuery(tweet, true);
if (tweet.getTextTerms().size() == 0) {
warn("Try a different tweet. This tweet is too short.");
return;
}
logger.info("[stats] similar search:" + query.toString());
doSearch(query, 0, false);
updateAfterAjax(target, false);
}
@Override
public Collection<JTweet> onInReplyOfClick(long id) {
JTweet tw = getTweetSearch().findByTwitterId(id);
logger.info("[stats] search tweet:" + id + " " + tw);
if (tw != null)
return Arrays.asList(tw);
else
return new ArrayList();
}
@Override
public String getTweetsAsString() {
if (lastQuery != null)
return twindexProvider.get().getTweetsAsString(lastQuery);
return "";
}
@Override
public void onHtmlExport() {
if (lastQuery != null) {
PrinterPage printerPage = new PrinterPage();
List<JTweet> tweets = twindexProvider.get().searchTweets(lastQuery);
printerPage.setResults(tweets);
setResponsePage(printerPage);
}
}
};
add(resultsPanel.setOutputMarkupId(true));
add(wikiPanel = new WikipediaLazyLoadPanel("wikipanel"));
String tmpUserName = null;
if (getMySession().hasLoggedIn())
tmpUserName = getMySession().getUser().getScreenName();
searchBox = new SearchBox("searchbox", tmpUserName, searchType) {
@Override
protected Collection<String> getQueryChoices(String input) {
return getTweetSearch().getQueryChoices(lastQuery, input);
}
@Override
protected void onSelectionChange(AjaxRequestTarget target, String newValue) {
JetwickQuery tmpQ = lastQuery.getCopy().setQuery(newValue);
tmpQ.removeFilterQueries(ElasticTweetSearch.DATE);
doSearch(tmpQ, 0, false, true);
updateAfterAjax(target, false);
}
@Override
protected Collection<String> getUserChoices(String input) {
return getTweetSearch().getUserChoices(lastQuery, input);
}
};
add(searchBox.setOutputMarkupId(true));
if (SearchBox.FRIENDS.equalsIgnoreCase(searchType)) {
if (getMySession().hasLoggedIn()) {
Collection<String> friends = getMySession().getFriends(uindexProvider.get());
if (friends.isEmpty()) {
info("You recently logged in. Please try again in 2 minutes to use friend search.");
} else {
query = new TweetQuery(query.getQuery()).createFriendsQuery(friends).
setSort(ElasticTweetSearch.DATE, "desc");
page = 0;
twitterFallback = false;
}
} else {
info("Login to use friend search. Follow us to recieve private messages on updates (rare frequency).");
// warn("Please login to search friends of " + parameters.getString("user"));
}
}
doSearch(query, page, twitterFallback);
}
/**
* used from facets (which adds filter queries) and
* from footer which changes the page
*/
public void doOldSearch(int page) {
logger.info(addIP("[stats] change old search. page:" + page));
doSearch(lastQuery, page, false);
}
public void doSearch(JetwickQuery query, int page, boolean twitterFallback) {
doSearch(query, page, twitterFallback, false);
}
public void doSearch(JetwickQuery query, int page, boolean twitterFallback, boolean instantSearch) {
String queryString;
if (!instantSearch) {
// change text field
searchBox.init(query.setEscape(false).getQuery(), query.extractUserName());
}
queryString = query.setEscape(true).getQuery();
// if query is lastQuery then user is saved in filter not in a pageParam
String userName = searchBox.getUserName();
resultsPanel.setAdQuery(queryString);
wikiPanel.setParams(queryString, language);
boolean startBGThread = true;
// do not trigger background searchAndGetUsers if this query is the identical
// to the last searchAndGetUsers or if it is an instant searchAndGetUsers
if (instantSearch || lastQuery != null
&& queryString.equals(lastQuery.getQuery())
&& userName.equals(lastQuery.extractUserName()))
startBGThread = false;
// do not trigger twitter searchAndGetUsers if a searchAndGetUsers through a users' tweets is triggered
if (!userName.isEmpty() && !queryString.isEmpty())
twitterFallback = false;
if (query.containsFilterKey("id"))
twitterFallback = false;
if (!instantSearch)
lastQuery = query;
Collection<JUser> users = new LinkedHashSet<JUser>();
query.attachPagability(page, hitsPerPage);
long start = System.currentTimeMillis();
long totalHits = 0;
SearchResponse rsp = null;
try {
rsp = getTweetSearch().search(users, query);
totalHits = rsp.getHits().getTotalHits();
logger.info(addIP("[stats] " + totalHits + " hits for: " + query.toString()));
} catch (Exception ex) {
logger.error("Error while searching " + query.toString(), ex);
}
resultsPanel.clear();
Collection<JTweet> tweets = null;
String msg = "";
if (totalHits > 0) {
float time = (System.currentTimeMillis() - start) / 100.0f;
time = Math.round(time) / 10f;
msg = "Found " + totalHits + " tweets in " + time + " s";
} else {
if (queryString.isEmpty()) {
if (userName.isEmpty()) {
// something is wrong with our index because q='' and user='' should give us all docs!
logger.warn(addIP("[stats] 0 results for q='' using news!"));
queryString = "news";
startBGThread = false;
} else
msg = "for user '" + userName + "'";
}
if (twitterFallback) {
// try TWITTER SEARCH
users.clear();
try {
if (getTwitterSearch().getRateLimitFromCache() > TwitterSearch.LIMIT) {
if (!userName.isEmpty()) {
tweets = getTwitterSearch().getTweets(new JUser(userName), users, TWEETS_IF_NO_HIT);
} else
tweets = getTwitterSearch().searchAndGetUsers(queryString, users, TWEETS_IF_NO_HIT, 1);
}
} catch (TwitterException ex) {
logger.warn("Warning while querying twitter:" + ex.getMessage());
} catch (Exception ex) {
logger.error("Error while querying twitter:" + ex.getMessage());
}
}
if (users.isEmpty()) {
if (!msg.isEmpty())
msg = " " + msg;
msg = "Sorry, nothing found" + msg + ".";
} else {
resultsPanel.setQueryMessageWarn("Sparse results.");
msg = "Using twitter-search " + msg + ".";
logger.warn("[stats] qNotFound:" + query.getQuery());
}
if (startBGThread)
msg += " Please try again in two minutes to get jetwicked results.";
}
if (startBGThread) {
try {
tweetThread = new Thread(queueTweets(tweets, queryString, userName));
tweetThread.start();
} catch (Exception ex) {
logger.error("Couldn't queue tweets. query" + queryString + " user=" + userName);
}
} else
tweetThread = null;
facetPanel.update(rsp, query);
tagCloud.update(rsp, query);
urlTrends.update(rsp, query);
resultsPanel.setQueryMessage(msg);
resultsPanel.setQuery(queryString);
resultsPanel.setUser(userName);
resultsPanel.setHitsPerPage(hitsPerPage);
dateFilter.update(rsp);
if (!query.getSortFields().isEmpty()) {
resultsPanel.setSort(query.getSortFields().get(0).getKey(), query.getSortFields().get(0).getValue());
} else
resultsPanel.setSort(null, null);
resultsPanel.setTweetsPerUser(-1);
for (JUser user : users) {
resultsPanel.add(user);
}
navigationPanel.setPage(page);
navigationPanel.setHits(totalHits);
navigationPanel.setHitsPerPage(hitsPerPage);
navigationPanel.updateVisibility();
logger.info(addIP("Finished Constructing UI."));
}
public QueueThread queueTweets(Collection<JTweet> tweets,
String qs, String userName) {
return grabber.init(tweets, qs, userName).setTweetsCount(TWEETS_IF_HIT).
setTwitterSearch(getTwitterSearch()).queueTweetPackage();
}
String addIP(String str) {
String q = "";
if (getWebRequestCycle() != null)
q = getWebRequestCycle().getWebRequest().getParameter("q");
return str + " IP=" + remoteHost
+ " session=" + getWebRequestCycle().getSession().getId()
+ " q=" + q;
}
}
| false | true | public void init(JetwickQuery query, PageParameters parameters, int page, boolean twitterFallback) {
setStatelessHint(true);
feedbackPanel = new FeedbackPanel("feedback");
add(feedbackPanel.setOutputMarkupId(true));
add(new Label("title", new Model() {
@Override
public Serializable getObject() {
String str = "";
if (!searchBox.getQuery().isEmpty())
str += searchBox.getQuery() + " ";
if (!searchBox.getUserName().isEmpty()) {
if (str.isEmpty())
str = "User " + searchBox.getUserName() + " ";
else
str = "Search " + str + "in user " + searchBox.getUserName() + " ";
}
if (str.isEmpty())
return "Jetwick Twitter Search";
return "Jetwick | " + str + "| Twitter Search Without Noise";
}
}));
add(new ExternalLinksPanel("externalRefs"));
add(new ExternalLinksPanelRight("externalRefsRight"));
urlTrends = new UrlTrendPanel("urltrends") {
@Override
protected void onUrlClick(AjaxRequestTarget target, String name) {
JetwickQuery q;
if (lastQuery != null)
q = lastQuery;
else
q = new TweetQuery(true);
if (name == null) {
q.removeFilterQueries(ElasticTweetSearch.FIRST_URL_TITLE);
} else
q.addFilterQuery(ElasticTweetSearch.FIRST_URL_TITLE, name);
doSearch(q, 0, true);
updateAfterAjax(target, false);
}
@Override
protected void onDirectUrlClick(AjaxRequestTarget target, String name) {
if (lastQuery == null || name == null || name.isEmpty())
return;
TweetQuery q = new TweetQuery(true);
q.addFilterQuery(ElasticTweetSearch.FIRST_URL_TITLE, name);
try {
List<JTweet> tweets = getTweetSearch().collectObjects(getTweetSearch().search(q.setSize(1)));
if (tweets.size() > 0 && tweets.get(0).getUrlEntries().size() > 0) {
// TODO there could be more than 1 url!
UrlEntry entry = tweets.get(0).getUrlEntries().iterator().next();
getRequestCycle().setRequestTarget(new RedirectRequestTarget(entry.getResolvedUrl()));
}
} catch (Exception ex) {
logger.error("Error while executing onDirectUrlClick", ex);
}
}
};
add(urlTrends.setOutputMarkupId(true));
final String searchType = parameters.getString("search");
ssPanel = new SavedSearchPanel("savedSearches") {
@Override
public void onClick(AjaxRequestTarget target, long ssId) {
if (searchType != null && !searchType.isEmpty() && !SearchBox.ALL.equals(searchType)) {
warn("Removed user filter when executing your saved search");
searchBox.setSearchType(SearchBox.ALL);
}
JUser user = getMySession().getUser();
SavedSearch ss = user.getSavedSearch(ssId);
if (ss != null) {
doSearch(ss.getQuery(), 0, true);
uindexProvider.get().save(user, true);
}
updateSSCounts(target);
updateAfterAjax(target, true);
}
@Override
public void onRemove(AjaxRequestTarget target, long ssId) {
JUser user = getMySession().getUser();
user.removeSavedSearch(ssId);
uindexProvider.get().save(user, true);
updateSSCounts(target);
}
@Override
public void onSave(AjaxRequestTarget target, long ssId) {
SavedSearch ss = new SavedSearch(ssId, lastQuery);
JUser user = getMySession().getUser();
user.addSavedSearch(ss);
uindexProvider.get().save(user, true);
updateSSCounts(target);
}
@Override
public void updateSSCounts(AjaxRequestTarget target) {
try {
JUser user = getMySession().getUser();
if (user != null) {
update(getTweetSearch().updateSavedSearches(user.getSavedSearches()));
if (target != null)
target.addComponent(ssPanel);
logger.info("Updated saved search counts for " + user.getScreenName());
}
} catch (Exception ex) {
logger.error("Error while searching in savedSearches", ex);
}
}
@Override
public String translate(long id) {
SavedSearch ss = getMySession().getUser().getSavedSearch(id);
return ss.getName();
}
};
if (!getMySession().hasLoggedIn())
ssPanel.setVisible(false);
add(ssPanel.setOutputMarkupId(true));
add(new UserPanel("userPanel", this) {
@Override
public void onLogout() {
getMySession().logout(uindexProvider.get(), (WebResponse) getResponse());
setResponsePage(HomePage.class);
}
@Override
public void updateAfterAjax(AjaxRequestTarget target) {
HomePage.this.updateAfterAjax(target, false);
}
@Override
public void onShowTweets(AjaxRequestTarget target, String userName) {
doSearch(new TweetQuery(true).addUserFilter(userName), 0, false);
HomePage.this.updateAfterAjax(target, true);
}
@Override
protected Collection<String> getUserChoices(String input) {
return getTweetSearch().getUserChoices(lastQuery, input);
}
});
tagCloud = new TagCloudPanel("tagcloud") {
@Override
protected void onTagClick(String name) {
if (lastQuery != null) {
lastQuery.setQuery((lastQuery.getQuery() + " " + name).trim());
doSearch(lastQuery, 0, true);
} else {
// never happens?
PageParameters pp = new PageParameters();
pp.add("q", name);
setResponsePage(HomePage.class, pp);
}
}
@Override
protected void onFindOriginClick(String tag) {
PageParameters pp = new PageParameters();
pp.add("findOrigin", tag);
doSearch(createQuery(pp), 0, true);
// this preserves parameters but cannot be context sensitive!
// setResponsePage(HomePage.class, pp);
}
};
add(tagCloud.setOutputMarkupId(true));
navigationPanel = new NavigationPanel("navigation", hitsPerPage) {
@Override
public void onPageChange(AjaxRequestTarget target, int page) {
// this does not scroll to top:
// doOldSearch(page);
// updateAfterAjax(target);
doOldSearch(page);
}
};
add(navigationPanel.setOutputMarkupId(true));
facetPanel = new FacetPanel("filterPanel") {
public void onRemoveAllFilter(AjaxRequestTarget target, String key) {
if (lastQuery != null)
lastQuery.removeFilterQueries(key);
else {
logger.error("last query cannot be null but was! ... when clicking on facets!?");
return;
}
doOldSearch(0);
updateAfterAjax(target, false);
}
@Override
public void onFacetChange(AjaxRequestTarget target, String key, Object val, boolean selected) {
if (lastQuery != null) {
if (selected)
lastQuery.addFilterQuery(key, val);
else
lastQuery.removeFilterQuery(key, val);
} else {
logger.error("last query cannot be null but was! ... when clicking on facets!?");
return;
}
doOldSearch(0);
updateAfterAjax(target, false);
}
};
add(facetPanel.setOutputMarkupId(true));
dateFilter = new JSDateFilter("dateFilter") {
@Override
protected void onFacetChange(AjaxRequestTarget target, String filter, Boolean selected) {
if (lastQuery != null) {
if (selected == null) {
lastQuery.removeFilterQueries(filter);
} else if (selected) {
lastQuery.replaceFilterQuery(filter);
} else
lastQuery.reduceFilterQuery(filter);
} else {
logger.error("last query cannot be null but was! ... when clicking on facets!?");
return;
}
doOldSearch(0);
updateAfterAjax(target, false);
}
@Override
protected boolean isAlreadyFiltered(String key, Object val) {
if (lastQuery != null)
return lastQuery.containsFilter(key, val);
return false;
}
@Override
public String getFilterName(String key) {
return facetPanel.getFilterName(key);
}
};
add(dateFilter.setOutputMarkupId(true));
// TODO M2.1
language = getWebRequestCycle().getWebRequest().getHttpServletRequest().getLocale().getLanguage();
remoteHost = getWebRequestCycle().getWebRequest().getHttpServletRequest().getRemoteHost();
resultsPanel = new ResultsPanel("results", language) {
@Override
public void onSortClicked(AjaxRequestTarget target, String sortKey, String sortVal) {
if (lastQuery != null) {
lastQuery.setSort(sortKey, sortVal);
doSearch(lastQuery, 0, false);
updateAfterAjax(target, false);
}
}
@Override
public void onUserClick(String userName, String queryStr) {
PageParameters p = new PageParameters();
if (queryStr != null && !queryStr.isEmpty())
p.add("q", queryStr);
if (userName != null)
p.add("user", userName.trim());
doSearch(createQuery(p), 0, true);
}
@Override
public Collection<JTweet> onTweetClick(long id, boolean retweet) {
logger.info("[stats] search replies of:" + id + " retweet:" + retweet);
return getTweetSearch().searchReplies(id, retweet);
}
@Override
public void onFindSimilar(JTweet tweet, AjaxRequestTarget target) {
JetwickQuery query = new SimilarQuery(tweet, true);
if (tweet.getTextTerms().size() == 0) {
warn("Try a different tweet. This tweet is too short.");
return;
}
logger.info("[stats] similar search:" + query.toString());
doSearch(query, 0, false);
updateAfterAjax(target, false);
}
@Override
public Collection<JTweet> onInReplyOfClick(long id) {
JTweet tw = getTweetSearch().findByTwitterId(id);
logger.info("[stats] search tweet:" + id + " " + tw);
if (tw != null)
return Arrays.asList(tw);
else
return new ArrayList();
}
@Override
public String getTweetsAsString() {
if (lastQuery != null)
return twindexProvider.get().getTweetsAsString(lastQuery);
return "";
}
@Override
public void onHtmlExport() {
if (lastQuery != null) {
PrinterPage printerPage = new PrinterPage();
List<JTweet> tweets = twindexProvider.get().searchTweets(lastQuery);
printerPage.setResults(tweets);
setResponsePage(printerPage);
}
}
};
add(resultsPanel.setOutputMarkupId(true));
add(wikiPanel = new WikipediaLazyLoadPanel("wikipanel"));
String tmpUserName = null;
if (getMySession().hasLoggedIn())
tmpUserName = getMySession().getUser().getScreenName();
searchBox = new SearchBox("searchbox", tmpUserName, searchType) {
@Override
protected Collection<String> getQueryChoices(String input) {
return getTweetSearch().getQueryChoices(lastQuery, input);
}
@Override
protected void onSelectionChange(AjaxRequestTarget target, String newValue) {
JetwickQuery tmpQ = lastQuery.getCopy().setQuery(newValue);
tmpQ.removeFilterQueries(ElasticTweetSearch.DATE);
doSearch(tmpQ, 0, false, true);
updateAfterAjax(target, false);
}
@Override
protected Collection<String> getUserChoices(String input) {
return getTweetSearch().getUserChoices(lastQuery, input);
}
};
add(searchBox.setOutputMarkupId(true));
if (SearchBox.FRIENDS.equalsIgnoreCase(searchType)) {
if (getMySession().hasLoggedIn()) {
Collection<String> friends = getMySession().getFriends(uindexProvider.get());
if (friends.isEmpty()) {
info("You recently logged in. Please try again in 2 minutes to use friend search.");
} else {
query = new TweetQuery(query.getQuery()).createFriendsQuery(friends).
setSort(ElasticTweetSearch.DATE, "desc");
page = 0;
twitterFallback = false;
}
} else {
info("Login to use friend search. Follow us to recieve private messages on updates (rare frequency).");
// warn("Please login to search friends of " + parameters.getString("user"));
}
}
doSearch(query, page, twitterFallback);
}
| public void init(JetwickQuery query, PageParameters parameters, int page, boolean twitterFallback) {
setStatelessHint(true);
feedbackPanel = new FeedbackPanel("feedback");
add(feedbackPanel.setOutputMarkupId(true));
add(new Label("title", new Model() {
@Override
public Serializable getObject() {
String str = "";
if (!searchBox.getQuery().isEmpty())
str += searchBox.getQuery() + " ";
if (!searchBox.getUserName().isEmpty()) {
if (str.isEmpty())
str = "User " + searchBox.getUserName() + " ";
else
str = "Search " + str + "in user " + searchBox.getUserName() + " ";
}
if (str.isEmpty())
return "Jetwick Twitter Search";
return "Jetwick | " + str + "| Twitter Search Without Noise";
}
}));
add(new ExternalLinksPanel("externalRefs"));
add(new ExternalLinksPanelRight("externalRefsRight"));
urlTrends = new UrlTrendPanel("urltrends") {
@Override
protected void onUrlClick(AjaxRequestTarget target, String name) {
JetwickQuery q;
if (lastQuery != null)
q = lastQuery;
else
q = new TweetQuery(true);
if (name == null) {
q.removeFilterQueries(ElasticTweetSearch.FIRST_URL_TITLE);
} else
q.addFilterQuery(ElasticTweetSearch.FIRST_URL_TITLE, name);
doSearch(q, 0, true);
updateAfterAjax(target, false);
}
@Override
protected void onDirectUrlClick(AjaxRequestTarget target, String name) {
if (lastQuery == null || name == null || name.isEmpty())
return;
TweetQuery q = new TweetQuery(true);
q.addFilterQuery(ElasticTweetSearch.FIRST_URL_TITLE, name);
try {
List<JTweet> tweets = getTweetSearch().collectObjects(getTweetSearch().search(q.setSize(1)));
if (tweets.size() > 0 && tweets.get(0).getUrlEntries().size() > 0) {
// TODO there could be more than 1 url!
UrlEntry entry = tweets.get(0).getUrlEntries().iterator().next();
getRequestCycle().setRequestTarget(new RedirectRequestTarget(entry.getResolvedUrl()));
}
} catch (Exception ex) {
logger.error("Error while executing onDirectUrlClick", ex);
}
}
};
add(urlTrends.setOutputMarkupId(true));
final String searchType = parameters.getString("search");
ssPanel = new SavedSearchPanel("savedSearches") {
@Override
public void onClick(AjaxRequestTarget target, long ssId) {
if (searchType != null && !searchType.isEmpty() && !SearchBox.ALL.equals(searchType)) {
warn("Removed user filter when executing your saved search");
searchBox.setSearchType(SearchBox.ALL);
}
JUser user = getMySession().getUser();
SavedSearch ss = user.getSavedSearch(ssId);
if (ss != null) {
doSearch(ss.getQuery(), 0, true);
uindexProvider.get().save(user, true);
}
updateSSCounts(target);
updateAfterAjax(target, true);
}
@Override
public void onRemove(AjaxRequestTarget target, long ssId) {
JUser user = getMySession().getUser();
user.removeSavedSearch(ssId);
uindexProvider.get().save(user, true);
updateSSCounts(target);
}
@Override
public void onSave(AjaxRequestTarget target, long ssId) {
SavedSearch ss = new SavedSearch(ssId, lastQuery);
JUser user = getMySession().getUser();
user.addSavedSearch(ss);
uindexProvider.get().save(user, true);
updateSSCounts(target);
}
@Override
public void updateSSCounts(AjaxRequestTarget target) {
try {
JUser user = getMySession().getUser();
if (user != null) {
update(getTweetSearch().updateSavedSearches(user.getSavedSearches()));
if (target != null)
target.addComponent(ssPanel);
logger.info("Updated saved search counts for " + user.getScreenName());
}
} catch (Exception ex) {
logger.error("Error while searching in savedSearches", ex);
}
}
@Override
public String translate(long id) {
SavedSearch ss = getMySession().getUser().getSavedSearch(id);
return ss.getName();
}
};
if (!getMySession().hasLoggedIn())
ssPanel.setVisible(false);
add(ssPanel.setOutputMarkupId(true));
add(new UserPanel("userPanel", this) {
@Override
public void onLogout() {
getMySession().logout(uindexProvider.get(), (WebResponse) getResponse());
setResponsePage(HomePage.class);
}
@Override
public void updateAfterAjax(AjaxRequestTarget target) {
HomePage.this.updateAfterAjax(target, false);
}
@Override
public void onShowTweets(AjaxRequestTarget target, String userName) {
doSearch(new TweetQuery(true).addUserFilter(userName), 0, false);
HomePage.this.updateAfterAjax(target, true);
}
@Override
protected Collection<String> getUserChoices(String input) {
return getTweetSearch().getUserChoices(lastQuery, input);
}
});
tagCloud = new TagCloudPanel("tagcloud") {
@Override
protected void onTagClick(String name) {
if (lastQuery != null) {
lastQuery.setQuery((lastQuery.getQuery() + " " + name).trim());
doSearch(lastQuery, 0, true);
} else {
// never happens?
PageParameters pp = new PageParameters();
pp.add("q", name);
setResponsePage(HomePage.class, pp);
}
}
@Override
protected void onFindOriginClick(String tag) {
PageParameters pp = new PageParameters();
pp.add("findOrigin", tag);
doSearch(createQuery(pp), 0, true);
// this preserves parameters but cannot be context sensitive!
// setResponsePage(HomePage.class, pp);
}
};
add(tagCloud.setOutputMarkupId(true));
navigationPanel = new NavigationPanel("navigation", hitsPerPage) {
@Override
public void onPageChange(AjaxRequestTarget target, int page) {
// this does not scroll to top:
// doOldSearch(page);
// updateAfterAjax(target);
doOldSearch(page);
}
};
add(navigationPanel.setOutputMarkupId(true));
facetPanel = new FacetPanel("filterPanel") {
public void onRemoveAllFilter(AjaxRequestTarget target, String key) {
if (lastQuery != null)
lastQuery.removeFilterQueries(key);
else {
logger.error("last query cannot be null but was! ... when clicking on facets!?");
return;
}
doOldSearch(0);
updateAfterAjax(target, false);
}
@Override
public void onFacetChange(AjaxRequestTarget target, String key, Object val, boolean selected) {
if (lastQuery != null) {
if (selected)
lastQuery.addFilterQuery(key, val);
else
lastQuery.removeFilterQuery(key, val);
} else {
logger.error("last query cannot be null but was! ... when clicking on facets!?");
return;
}
doOldSearch(0);
updateAfterAjax(target, false);
}
};
add(facetPanel.setOutputMarkupId(true));
dateFilter = new JSDateFilter("dateFilter") {
@Override
protected void onFacetChange(AjaxRequestTarget target, String filter, Boolean selected) {
if (lastQuery != null) {
if (selected == null) {
lastQuery.removeFilterQueries(filter);
} else if (selected) {
lastQuery.replaceFilterQuery(filter);
} else
lastQuery.reduceFilterQuery(filter);
} else {
logger.error("last query cannot be null but was! ... when clicking on facets!?");
return;
}
doOldSearch(0);
updateAfterAjax(target, false);
}
@Override
protected boolean isAlreadyFiltered(String key, Object val) {
if (lastQuery != null)
return lastQuery.containsFilter(key, val);
return false;
}
@Override
public String getFilterName(String key) {
return facetPanel.getFilterName(key);
}
};
add(dateFilter.setOutputMarkupId(true));
// TODO M2.1
language = getWebRequestCycle().getWebRequest().getHttpServletRequest().getLocale().getLanguage();
remoteHost = getWebRequestCycle().getWebRequest().getHttpServletRequest().getRemoteHost();
resultsPanel = new ResultsPanel("results", language) {
@Override
public void onSortClicked(AjaxRequestTarget target, String sortKey, String sortVal) {
if (lastQuery != null) {
lastQuery.setSort(sortKey, sortVal);
doSearch(lastQuery, 0, false);
updateAfterAjax(target, false);
}
}
@Override
public void onUserClick(String userName, String queryStr) {
PageParameters p = new PageParameters();
if (queryStr != null && !queryStr.isEmpty())
p.add("q", queryStr);
if (userName != null) {
p.add("user", userName.trim());
searchBox.setSearchType(SearchBox.USER);
}
doSearch(createQuery(p), 0, true);
}
@Override
public Collection<JTweet> onTweetClick(long id, boolean retweet) {
logger.info("[stats] search replies of:" + id + " retweet:" + retweet);
return getTweetSearch().searchReplies(id, retweet);
}
@Override
public void onFindSimilar(JTweet tweet, AjaxRequestTarget target) {
JetwickQuery query = new SimilarQuery(tweet, true);
if (tweet.getTextTerms().size() == 0) {
warn("Try a different tweet. This tweet is too short.");
return;
}
logger.info("[stats] similar search:" + query.toString());
doSearch(query, 0, false);
updateAfterAjax(target, false);
}
@Override
public Collection<JTweet> onInReplyOfClick(long id) {
JTweet tw = getTweetSearch().findByTwitterId(id);
logger.info("[stats] search tweet:" + id + " " + tw);
if (tw != null)
return Arrays.asList(tw);
else
return new ArrayList();
}
@Override
public String getTweetsAsString() {
if (lastQuery != null)
return twindexProvider.get().getTweetsAsString(lastQuery);
return "";
}
@Override
public void onHtmlExport() {
if (lastQuery != null) {
PrinterPage printerPage = new PrinterPage();
List<JTweet> tweets = twindexProvider.get().searchTweets(lastQuery);
printerPage.setResults(tweets);
setResponsePage(printerPage);
}
}
};
add(resultsPanel.setOutputMarkupId(true));
add(wikiPanel = new WikipediaLazyLoadPanel("wikipanel"));
String tmpUserName = null;
if (getMySession().hasLoggedIn())
tmpUserName = getMySession().getUser().getScreenName();
searchBox = new SearchBox("searchbox", tmpUserName, searchType) {
@Override
protected Collection<String> getQueryChoices(String input) {
return getTweetSearch().getQueryChoices(lastQuery, input);
}
@Override
protected void onSelectionChange(AjaxRequestTarget target, String newValue) {
JetwickQuery tmpQ = lastQuery.getCopy().setQuery(newValue);
tmpQ.removeFilterQueries(ElasticTweetSearch.DATE);
doSearch(tmpQ, 0, false, true);
updateAfterAjax(target, false);
}
@Override
protected Collection<String> getUserChoices(String input) {
return getTweetSearch().getUserChoices(lastQuery, input);
}
};
add(searchBox.setOutputMarkupId(true));
if (SearchBox.FRIENDS.equalsIgnoreCase(searchType)) {
if (getMySession().hasLoggedIn()) {
Collection<String> friends = getMySession().getFriends(uindexProvider.get());
if (friends.isEmpty()) {
info("You recently logged in. Please try again in 2 minutes to use friend search.");
} else {
query = new TweetQuery(query.getQuery()).createFriendsQuery(friends).
setSort(ElasticTweetSearch.DATE, "desc");
page = 0;
twitterFallback = false;
}
} else {
info("Login to use friend search. Follow us to recieve private messages on updates (rare frequency).");
// warn("Please login to search friends of " + parameters.getString("user"));
}
}
doSearch(query, page, twitterFallback);
}
|
diff --git a/src/local/cascading/tap/local/FileTap.java b/src/local/cascading/tap/local/FileTap.java
index 8d48290c..2c978260 100644
--- a/src/local/cascading/tap/local/FileTap.java
+++ b/src/local/cascading/tap/local/FileTap.java
@@ -1,205 +1,206 @@
/*
* Copyright (c) 2007-2011 Concurrent, Inc. All Rights Reserved.
*
* Project and contact information: http://www.cascading.org/
*
* This file is part of the Cascading project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cascading.tap.local;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Properties;
import cascading.flow.local.LocalFlowProcess;
import cascading.scheme.local.LocalScheme;
import cascading.tap.SinkMode;
import cascading.tap.Tap;
import cascading.tap.TapException;
import cascading.tuple.TupleEntryChainIterator;
import cascading.tuple.TupleEntryCollector;
import cascading.tuple.TupleEntryIterator;
import cascading.tuple.TupleEntrySchemeIterator;
import cascading.util.Util;
/**
* Class FileTap is a {@link Tap} sub-class that allows for direct local file access.
* <p/>
* FileTap must be used with the {@link cascading.flow.local.LocalFlowConnector} to create
* {@link cascading.flow.Flow} instances that run in "local" mode.
*/
public class FileTap extends Tap<LocalFlowProcess, Properties, FileInputStream, FileOutputStream>
{
private final String path;
/**
* Constructor FileTap creates a new FileTap instance using the given {@link cascading.scheme.Scheme} and file {@code path}.
*
* @param scheme of type LocalScheme
* @param path of type String
*/
public FileTap( LocalScheme scheme, String path )
{
this( scheme, path, SinkMode.KEEP );
}
/**
* Constructor FileTap creates a new FileTap instance using the given {@link cascading.scheme.Scheme},
* file {@code path}, and {@code SinkMode}.
*
* @param scheme of type LocalScheme
* @param path of type String
* @param sinkMode of type SinkMode
*/
public FileTap( LocalScheme scheme, String path, SinkMode sinkMode )
{
super( scheme, sinkMode );
this.path = path;
}
@Override
public String getIdentifier()
{
return path;
}
@Override
public TupleEntryIterator openForRead( LocalFlowProcess flowProcess, FileInputStream input ) throws IOException
{
if( input == null )
{
// return an empty iterator
if( !new File( path ).exists() )
return new TupleEntryChainIterator( getSourceFields(), new Iterator[ 0 ] );
input = new FileInputStream( path );
}
Closeable reader = (Closeable) ( (LocalScheme) getScheme() ).createInput( input );
return new TupleEntrySchemeIterator( flowProcess, getScheme(), reader );
}
@SuppressWarnings({"ResultOfMethodCallIgnored"})
@Override
public TupleEntryCollector openForWrite( LocalFlowProcess flowProcess, FileOutputStream output ) throws IOException
{
// ignore the output. will catch the failure downstream if any.
// not ignoring the output causes race conditions with other systems writing to the same directory.
- File parentFile = new File( path ).getParentFile();
+ File parentFile = new File( path ).getAbsoluteFile().getParentFile();
- if( parentFile.exists() && parentFile.isFile() )
+ if( parentFile != null && parentFile.exists() && parentFile.isFile() )
throw new TapException( "cannot create parent directory, it already exists as a file: " + parentFile.getAbsolutePath() );
// don't test for success, just fighting a race condition otherwise
// will get caught downstream
- parentFile.mkdirs();
+ if( parentFile != null )
+ parentFile.mkdirs();
if( output == null )
output = new FileOutputStream( path, isUpdate() ); // append if we are in update mode
Closeable writer = (Closeable) ( (LocalScheme) getScheme() ).createOutput( output );
LocalTupleEntryCollector schemeCollector = new LocalTupleEntryCollector( flowProcess, getScheme(), writer );
schemeCollector.prepare();
return schemeCollector;
}
/**
* Method getSize returns the size of the file referenced by this tap.
*
* @param conf of type Properties
* @return The size of the file reference by this tap.
* @throws IOException
*/
public long getSize( Properties conf ) throws IOException
{
File file = new File( path );
if( file.isDirectory() )
return 0;
return file.length();
}
@Override
public boolean createResource( Properties conf ) throws IOException
{
File parentFile = new File( path ).getParentFile();
return parentFile.exists() || parentFile.mkdirs();
}
@Override
public boolean deleteResource( Properties conf ) throws IOException
{
return new File( path ).delete();
}
@Override
public boolean resourceExists( Properties conf ) throws IOException
{
return new File( path ).exists();
}
@Override
public long getModifiedTime( Properties conf ) throws IOException
{
return new File( path ).lastModified();
}
@Override
public boolean equals( Object object )
{
if( this == object )
return true;
if( !( object instanceof FileTap ) )
return false;
if( !super.equals( object ) )
return false;
FileTap fileTap = (FileTap) object;
if( path != null ? !path.equals( fileTap.path ) : fileTap.path != null )
return false;
return true;
}
@Override
public int hashCode()
{
int result = super.hashCode();
result = 31 * result + ( path != null ? path.hashCode() : 0 );
return result;
}
/** @see Object#toString() */
@Override
public String toString()
{
if( path != null )
return getClass().getSimpleName() + "[\"" + getScheme() + "\"]" + "[\"" + Util.sanitizeUrl( path ) + "\"]"; // sanitize
else
return getClass().getSimpleName() + "[\"" + getScheme() + "\"]" + "[not initialized]";
}
}
| false | true | public TupleEntryCollector openForWrite( LocalFlowProcess flowProcess, FileOutputStream output ) throws IOException
{
// ignore the output. will catch the failure downstream if any.
// not ignoring the output causes race conditions with other systems writing to the same directory.
File parentFile = new File( path ).getParentFile();
if( parentFile.exists() && parentFile.isFile() )
throw new TapException( "cannot create parent directory, it already exists as a file: " + parentFile.getAbsolutePath() );
// don't test for success, just fighting a race condition otherwise
// will get caught downstream
parentFile.mkdirs();
if( output == null )
output = new FileOutputStream( path, isUpdate() ); // append if we are in update mode
Closeable writer = (Closeable) ( (LocalScheme) getScheme() ).createOutput( output );
LocalTupleEntryCollector schemeCollector = new LocalTupleEntryCollector( flowProcess, getScheme(), writer );
schemeCollector.prepare();
return schemeCollector;
}
| public TupleEntryCollector openForWrite( LocalFlowProcess flowProcess, FileOutputStream output ) throws IOException
{
// ignore the output. will catch the failure downstream if any.
// not ignoring the output causes race conditions with other systems writing to the same directory.
File parentFile = new File( path ).getAbsoluteFile().getParentFile();
if( parentFile != null && parentFile.exists() && parentFile.isFile() )
throw new TapException( "cannot create parent directory, it already exists as a file: " + parentFile.getAbsolutePath() );
// don't test for success, just fighting a race condition otherwise
// will get caught downstream
if( parentFile != null )
parentFile.mkdirs();
if( output == null )
output = new FileOutputStream( path, isUpdate() ); // append if we are in update mode
Closeable writer = (Closeable) ( (LocalScheme) getScheme() ).createOutput( output );
LocalTupleEntryCollector schemeCollector = new LocalTupleEntryCollector( flowProcess, getScheme(), writer );
schemeCollector.prepare();
return schemeCollector;
}
|
diff --git a/src/main/java/uk/co/revthefox/foxbot/commands/CommandPing.java b/src/main/java/uk/co/revthefox/foxbot/commands/CommandPing.java
index 8a82f4e..c501254 100644
--- a/src/main/java/uk/co/revthefox/foxbot/commands/CommandPing.java
+++ b/src/main/java/uk/co/revthefox/foxbot/commands/CommandPing.java
@@ -1,68 +1,68 @@
package uk.co.revthefox.foxbot.commands;
import org.apache.commons.lang3.StringUtils;
import org.pircbotx.Channel;
import org.pircbotx.User;
import org.pircbotx.hooks.events.MessageEvent;
import uk.co.revthefox.foxbot.FoxBot;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class CommandPing extends Command
{
private FoxBot foxbot;
public CommandPing(FoxBot foxbot)
{
super("ping", "command.ping");
this.foxbot = foxbot;
}
@Override
public void execute(final MessageEvent event, final String[] args)
{
Channel channel = event.getChannel();
User sender = event.getUser();
String host;
int port = 80;
if (args.length == 1 || args.length == 2)
{
try
{
host = args[0];
port = args.length == 2 ? Integer.parseInt(args[1]) : port;
long start = System.currentTimeMillis();
Socket socket = new Socket(InetAddress.getByName(host), port);
long end = System.currentTimeMillis();
socket.close();
channel.sendMessage(foxbot.getUtils().colourise(String.format("(%s) &aPing response time: &r%sms",foxbot.getUtils().munge(sender.getNick()), end - start)));
}
catch (UnknownHostException ex)
{
foxbot.sendNotice(sender, String.format("%s is an unknown address!", args[0]));
}
catch (IOException ex)
{
- foxbot.sendNotice(sender, foxbot.getUtils().colourise(String.format("Port %s seems to be blocked on the server you are pinging.", args[1])));
+ foxbot.sendMessage(channel, foxbot.getUtils().colourise(String.format("(%s) Port &a%s&r seems to be closed on %s",sender.getNick(), args[1], args[0])));
}
catch (NumberFormatException ex)
{
foxbot.sendNotice(sender, String.format("%s is not a number!", args[1]));
}
catch (IllegalArgumentException ex)
{
foxbot.sendNotice(sender, String.format("%s is too high a number for a port!", args[1]));
}
return;
}
foxbot.sendNotice(sender, String.format("Wrong number of args! Use %sping <address> [port]", foxbot.getConfig().getCommandPrefix()));
}
}
//
| true | true | public void execute(final MessageEvent event, final String[] args)
{
Channel channel = event.getChannel();
User sender = event.getUser();
String host;
int port = 80;
if (args.length == 1 || args.length == 2)
{
try
{
host = args[0];
port = args.length == 2 ? Integer.parseInt(args[1]) : port;
long start = System.currentTimeMillis();
Socket socket = new Socket(InetAddress.getByName(host), port);
long end = System.currentTimeMillis();
socket.close();
channel.sendMessage(foxbot.getUtils().colourise(String.format("(%s) &aPing response time: &r%sms",foxbot.getUtils().munge(sender.getNick()), end - start)));
}
catch (UnknownHostException ex)
{
foxbot.sendNotice(sender, String.format("%s is an unknown address!", args[0]));
}
catch (IOException ex)
{
foxbot.sendNotice(sender, foxbot.getUtils().colourise(String.format("Port %s seems to be blocked on the server you are pinging.", args[1])));
}
catch (NumberFormatException ex)
{
foxbot.sendNotice(sender, String.format("%s is not a number!", args[1]));
}
catch (IllegalArgumentException ex)
{
foxbot.sendNotice(sender, String.format("%s is too high a number for a port!", args[1]));
}
return;
}
foxbot.sendNotice(sender, String.format("Wrong number of args! Use %sping <address> [port]", foxbot.getConfig().getCommandPrefix()));
}
| public void execute(final MessageEvent event, final String[] args)
{
Channel channel = event.getChannel();
User sender = event.getUser();
String host;
int port = 80;
if (args.length == 1 || args.length == 2)
{
try
{
host = args[0];
port = args.length == 2 ? Integer.parseInt(args[1]) : port;
long start = System.currentTimeMillis();
Socket socket = new Socket(InetAddress.getByName(host), port);
long end = System.currentTimeMillis();
socket.close();
channel.sendMessage(foxbot.getUtils().colourise(String.format("(%s) &aPing response time: &r%sms",foxbot.getUtils().munge(sender.getNick()), end - start)));
}
catch (UnknownHostException ex)
{
foxbot.sendNotice(sender, String.format("%s is an unknown address!", args[0]));
}
catch (IOException ex)
{
foxbot.sendMessage(channel, foxbot.getUtils().colourise(String.format("(%s) Port &a%s&r seems to be closed on %s",sender.getNick(), args[1], args[0])));
}
catch (NumberFormatException ex)
{
foxbot.sendNotice(sender, String.format("%s is not a number!", args[1]));
}
catch (IllegalArgumentException ex)
{
foxbot.sendNotice(sender, String.format("%s is too high a number for a port!", args[1]));
}
return;
}
foxbot.sendNotice(sender, String.format("Wrong number of args! Use %sping <address> [port]", foxbot.getConfig().getCommandPrefix()));
}
|
diff --git a/server/src/org/bedework/eventreg/web/UpdateAdminRegController.java b/server/src/org/bedework/eventreg/web/UpdateAdminRegController.java
index 1472e05..dea7b50 100644
--- a/server/src/org/bedework/eventreg/web/UpdateAdminRegController.java
+++ b/server/src/org/bedework/eventreg/web/UpdateAdminRegController.java
@@ -1,41 +1,41 @@
/* ********************************************************************
Licensed to Jasig under one or more contributor license
agreements. See the NOTICE file distributed with this work
for additional information regarding copyright ownership.
Jasig 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.bedework.eventreg.web;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author douglm
*/
public class UpdateAdminRegController extends AdminAuthAbstractController {
@Override
public ModelAndView doRequest(final HttpServletRequest request,
final HttpServletResponse response) throws Throwable {
ModelAndView mv = updateRegistration(true);
if (mv != null) {
return mv;
}
- return sessModel("forward:adminagenda.do");
+ return sessModel(getForwardTo());
}
}
| true | true | public ModelAndView doRequest(final HttpServletRequest request,
final HttpServletResponse response) throws Throwable {
ModelAndView mv = updateRegistration(true);
if (mv != null) {
return mv;
}
return sessModel("forward:adminagenda.do");
}
| public ModelAndView doRequest(final HttpServletRequest request,
final HttpServletResponse response) throws Throwable {
ModelAndView mv = updateRegistration(true);
if (mv != null) {
return mv;
}
return sessModel(getForwardTo());
}
|
diff --git a/src/mouse/DataProcessor.java b/src/mouse/DataProcessor.java
index 0ce1b2e..b5f0477 100644
--- a/src/mouse/DataProcessor.java
+++ b/src/mouse/DataProcessor.java
@@ -1,410 +1,412 @@
package mouse;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.Interval;
import mouse.dbTableModels.Antenna;
import mouse.dbTableModels.AntennaReading;
import mouse.dbTableModels.AntennaRecord;
import mouse.dbTableModels.Box;
import mouse.dbTableModels.Direction;
import mouse.dbTableModels.DirectionResult;
import mouse.dbTableModels.AntennaReadingTimeStampComparator;
import mouse.dbTableModels.Directions;
import mouse.dbTableModels.MeetingResult;
import mouse.dbTableModels.StayResult;
import mouse.dbTableModels.Transponder;
import mouse.postgresql.AntennaReadings;
import mouse.postgresql.DirectionResults;
import mouse.postgresql.MeetingResults;
import mouse.postgresql.PostgreSQLManager;
import mouse.postgresql.StayResults;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.bean.MappingStrategy;
public class DataProcessor {
public static final int COLUMN_COUNT = 5;
public static final int DATE_TIME_STAMP_COLUMN = 1;
public static final int DEVICE_ID_COLUMN = 2;
public static final int ANTENNA_ID_COLUMN = 3;
public static final int RFID_COLUMN = 4;
private final String inputCSVFileName;
private final ArrayList<AntennaReading> antennaReadings = new ArrayList<AntennaReading>();
private final ArrayList<DirectionResult> directionResults = new ArrayList<DirectionResult>();
private final ArrayList<StayResult> stayResults = new ArrayList<StayResult>();
private final ArrayList<MeetingResult> meetingResults = new ArrayList<MeetingResult>();
private final PostgreSQLManager psqlManager;
public DataProcessor(String inputCSVFileName, String username, String password, Object host, Object port, String dbName) {
this.inputCSVFileName = inputCSVFileName;
Column[] columns = columns(inputCSVFileName, true);
psqlManager = new PostgreSQLManager(username, password, columns);
}
public String getInputCSVFileName() {
return inputCSVFileName;
}
public ArrayList<AntennaReading> getAntennaReadings() {
return antennaReadings;
}
public ArrayList<DirectionResult> getDirectionResults() {
return directionResults;
}
public ArrayList<StayResult> getStayResults() {
return stayResults;
}
public ArrayList<MeetingResult> getMeetingResults() {
return meetingResults;
}
public PostgreSQLManager getPsqlManager() {
return psqlManager;
}
/**
* Processes the input data and writes into the according tables
* @return
*/
public boolean process() {
if (!psqlManager.initTables())
return false;
if (!psqlManager.storeStaticTables()) {
return false;
}
if (!readAntennaReadingsCSV(inputCSVFileName))
return false;
if (!generateDirectionResults())
return false;
if (!generateStayResults())
return false;
if (!generateMeetingResults())
return false;
return true;
}
/**
* Scans the input file and returns Columns of antennas, boxes and transponders
* @param inputCSVFileName
* @param unique
* @return
*/
private Column[] columns(String inputCSVFileName, boolean unique) {
int[] staticColumnNumbers = new int[] {ANTENNA_ID_COLUMN, DEVICE_ID_COLUMN, RFID_COLUMN};
Column[] columns = new Column[COLUMN_COUNT];
for (int i = 0; i < COLUMN_COUNT; ++i) {
columns[i] = new Column();
}
CSVReader reader;
try {
reader = new CSVReader(new FileReader(inputCSVFileName), ';', '\'', 1); //skip the first (header) line
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
for (int i : staticColumnNumbers) {
if (unique && columns[i].getEntries().contains(nextLine[i]))
continue;
columns[i].addEntry(nextLine[i]);
}
}
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return columns;
}
/**
* Reads the content of a given CSV file into antennaReadings array
*
* @param sourceFile
*/
private boolean readAntennaReadingsCSV(String sourceFile) {
System.out.println("Reading input file: " + sourceFile);
CSVReader reader;
try {
reader = new CSVReader(new FileReader(sourceFile), ';', '\'', 1); //skip the first (header) line
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
TimeStamp timeStamp;
try {
timeStamp = new TimeStamp(nextLine[1]);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
reader.close();
return false;
}
String boxName = nextLine[2];
Box box = Box.getBoxByName(boxName);
String antennaPosition = nextLine[3];
Antenna antenna = Antenna.getAntenna(box, antennaPosition);
String rfid = nextLine[4];
if (StringUtils.isEmpty(rfid))
continue;
Transponder transponder = Transponder.getTransponder(rfid);
AntennaReading antennaReading = new AntennaReading(timeStamp, transponder, antenna);
antennaReadings.add(antennaReading);
}
reader.close();
System.out.println("OK\nSaving antenna readings into DB");
AntennaReadings antennaReadingsTable = psqlManager.getAntennaReadings();
antennaReadingsTable.setTableModels(
antennaReadings.toArray(new AntennaReading[antennaReadings.size()]));
String insertQueries = antennaReadingsTable.insertQuery(antennaReadingsTable.getTableModels());
String[] ids = psqlManager.executeQueries(insertQueries);
for (int i = 0; i < antennaReadings.size(); ++i) {
antennaReadings.get(i).setId(ids[i]);
}
System.out.println("OK");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
/**
* Generates entry rows from antennaReadings array to directionResults array
*/
private boolean generateDirectionResults() {
HashMap<MouseInBox, AntennaRecord> mouseInBoxSet = new HashMap<MouseInBox, AntennaRecord>();
ArrayList<AntennaReading> antennaReadingsCopy = new ArrayList<AntennaReading>(antennaReadings);
Iterator<AntennaReading> it = antennaReadingsCopy.iterator();
while (it.hasNext()) {
AntennaReading antennaReading = it.next();
Transponder mouse = antennaReading.getTransponder();
Antenna antenna = antennaReading.getAntena();
Box box = antenna.getBox();
TimeStamp timestamp = antennaReading.getTimeStamp();
MouseInBox mouseInBox = new MouseInBox(mouse, box, antenna, timestamp);
AntennaRecord antennaRecord = mouseInBoxSet.get(mouseInBox);
if (!mouseInBoxSet.containsKey(mouseInBox)) {
mouseInBoxSet.put(mouseInBox, new AntennaRecord(antenna, timestamp));
} else if (!antennaRecord.equals(antenna)) {
Antenna in;
Antenna out;
if (timestamp.before(antennaRecord.getRecordTime())) {
in = antenna;
out = antennaRecord.getAntenna();
} else {
in = antennaRecord.getAntenna();
out = antenna;
}
Direction direction = new Direction(in, out);
if (direction.toString() == null)
continue;
Transponder transponder = antennaReading.getTransponder();
DirectionResult dirResult = new DirectionResult(timestamp, direction, transponder, box);
directionResults.add(dirResult);
} else {
//If the mouse entered and never left the box before entering it again,
//or left and never entered before living again,
//count the time from the last recorded time
mouseInBoxSet.put(mouseInBox, new AntennaRecord(antenna, timestamp));
}
it.remove();
}
System.out.println("OK\nSaving direction results into DB");
DirectionResults dirResultsTable = psqlManager.getDirectionResults();
dirResultsTable.setTableModels(
directionResults.toArray(new DirectionResult[directionResults.size()]));
String insertQueries = dirResultsTable.insertQuery(dirResultsTable.getTableModels());
String[] ids = psqlManager.executeQueries(insertQueries);
for (int i = 0; i < directionResults.size(); ++i) {
directionResults.get(i).setId(ids[i]);
}
System.out.println("OK");
return true;
}
/**
* Generate entry rows from directionResults array to stayResults array
*/
private boolean generateStayResults() {
HashMap<MouseInBox, DirectionResult> mouseInBoxSet = new HashMap<MouseInBox, DirectionResult>();
ArrayList<DirectionResult> directionResultsCopy = new ArrayList<DirectionResult>(directionResults);
Iterator<DirectionResult> it = directionResultsCopy.iterator();
while (it.hasNext()) {
DirectionResult dirRes = it.next();
Transponder mouse = dirRes.getTransponder();
Box box = dirRes.getBox();
TimeStamp timeStamp = dirRes.getTimeStamp();
MouseInBox mouseInBox = new MouseInBox(mouse, box, null, timeStamp); //TODO: perhaps a new type is needed instead of putting null for Antenna
DirectionResult secondDir = mouseInBoxSet.get(mouseInBox);
DirectionResult firstDir = dirRes;
if (secondDir == null) {
mouseInBoxSet.put(mouseInBox, dirRes);
it.remove();
continue;
} else {
//The first event musts be before the second
if (firstDir.getTimeStamp().after(secondDir.getTimeStamp())) {
//System.out.println("swapping");
DirectionResult temp = firstDir;
firstDir = secondDir;
secondDir = temp;
}
if (firstDir.getDirection().getType() == Directions.In &&
secondDir.getDirection().getType() == Directions.Out) {
TimeStamp start = firstDir.getTimeStamp();
TimeStamp stop = secondDir.getTimeStamp();
StayResult stayResult = new StayResult(start, stop, mouse, box, firstDir, secondDir);
stayResults.add(stayResult);
if (mouseInBoxSet.remove(mouseInBox) == null) {
System.out.println("fuck you, too!");
} else {
System.out.println("good boy!");
}
it.remove();
}
}
}
System.out.println("OK\nSaving stay results into DB");
StayResults stayResultsTable = psqlManager.getStayResults();
stayResultsTable.setTableModels(
stayResults.toArray(new StayResult[stayResults.size()]));
String insertQueries = stayResultsTable.insertQuery(stayResultsTable.getTableModels());
String[] ids = psqlManager.executeQueries(insertQueries);
for (int i = 0; i < stayResults.size(); ++i) {
stayResults.get(i).setId(ids[i]);
}
System.out.println("OK");
return true;
}
/**
* Generates entry rows from stayResults array to meetingResults array
*/
private boolean generateMeetingResults() {
HashMap<Box, ArrayList<MouseInterval>> boxSet = new HashMap<Box, ArrayList<MouseInterval>>();
for (StayResult stayResult : stayResults) {
Box box = stayResult.getBox();
ArrayList<MouseInterval> mouseIntervals = boxSet.get(box);
if (mouseIntervals == null) {
mouseIntervals = new ArrayList<MouseInterval>();
}
Transponder mouse = stayResult.getTransponder();
TimeStamp start = stayResult.getStart();
TimeStamp stop = stayResult.getStop();
MouseInterval mouseInterval = new MouseInterval(mouse, start, stop);
mouseIntervals.add(mouseInterval);
boxSet.put(box, mouseIntervals);
}
Iterator<Entry<Box, ArrayList<MouseInterval>>> it = boxSet.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Box, ArrayList<MouseInterval>> pair =
(Map.Entry<Box, ArrayList<MouseInterval>>) it.next();
Box box = pair.getKey();
ArrayList<MouseInterval> mouseIntervals = pair.getValue();
for (MouseInterval mouseInterval : mouseIntervals) {
Transponder transponderFrom = mouseInterval.getMouse();
for (MouseInterval innerMouseInterval : mouseIntervals) {
if (innerMouseInterval.getMouse() == mouseInterval.getMouse())
continue;
+ if (innerMouseInterval.getStart().before(mouseInterval.getStart()))
+ continue; //Avoid duplicate entries
Transponder transponderTo = innerMouseInterval.getMouse();
TimeStamp start = mouseInterval.getStart().after(innerMouseInterval.getStart())
? mouseInterval.getStart()
: innerMouseInterval.getStart();
TimeStamp stop = mouseInterval.getStop().before(innerMouseInterval.getStop())
? mouseInterval.getStop()
: innerMouseInterval.getStop();
if (stop.before(start))
continue;
Transponder terminatedBy = mouseInterval.getStop().before(innerMouseInterval.getStop())
? transponderFrom
: transponderTo;
float duration = (new Interval(start.getTime(), stop.getTime())).getEndMillis();
MeetingResult meetingResult = new MeetingResult(transponderFrom, transponderTo, start,
stop, duration, terminatedBy == transponderFrom ? 0 : 1, box);
meetingResults.add(meetingResult);
}
}
it.remove();
}
System.out.println("OK\nSaving meeting results into DB");
MeetingResults meetingResultsTable = psqlManager.getMeetingResults();
meetingResultsTable.setTableModels(
meetingResults.toArray(new MeetingResult[meetingResults.size()]));
String insertQueries = meetingResultsTable.insertQuery(meetingResultsTable.getTableModels());
String[] ids = psqlManager.executeQueries(insertQueries);
for (int i = 0; i < meetingResults.size(); ++i) {
meetingResults.get(i).setId(ids[i]);
}
System.out.println("OK");
return true;
}
}
| true | true | private boolean generateMeetingResults() {
HashMap<Box, ArrayList<MouseInterval>> boxSet = new HashMap<Box, ArrayList<MouseInterval>>();
for (StayResult stayResult : stayResults) {
Box box = stayResult.getBox();
ArrayList<MouseInterval> mouseIntervals = boxSet.get(box);
if (mouseIntervals == null) {
mouseIntervals = new ArrayList<MouseInterval>();
}
Transponder mouse = stayResult.getTransponder();
TimeStamp start = stayResult.getStart();
TimeStamp stop = stayResult.getStop();
MouseInterval mouseInterval = new MouseInterval(mouse, start, stop);
mouseIntervals.add(mouseInterval);
boxSet.put(box, mouseIntervals);
}
Iterator<Entry<Box, ArrayList<MouseInterval>>> it = boxSet.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Box, ArrayList<MouseInterval>> pair =
(Map.Entry<Box, ArrayList<MouseInterval>>) it.next();
Box box = pair.getKey();
ArrayList<MouseInterval> mouseIntervals = pair.getValue();
for (MouseInterval mouseInterval : mouseIntervals) {
Transponder transponderFrom = mouseInterval.getMouse();
for (MouseInterval innerMouseInterval : mouseIntervals) {
if (innerMouseInterval.getMouse() == mouseInterval.getMouse())
continue;
Transponder transponderTo = innerMouseInterval.getMouse();
TimeStamp start = mouseInterval.getStart().after(innerMouseInterval.getStart())
? mouseInterval.getStart()
: innerMouseInterval.getStart();
TimeStamp stop = mouseInterval.getStop().before(innerMouseInterval.getStop())
? mouseInterval.getStop()
: innerMouseInterval.getStop();
if (stop.before(start))
continue;
Transponder terminatedBy = mouseInterval.getStop().before(innerMouseInterval.getStop())
? transponderFrom
: transponderTo;
float duration = (new Interval(start.getTime(), stop.getTime())).getEndMillis();
MeetingResult meetingResult = new MeetingResult(transponderFrom, transponderTo, start,
stop, duration, terminatedBy == transponderFrom ? 0 : 1, box);
meetingResults.add(meetingResult);
}
}
it.remove();
}
System.out.println("OK\nSaving meeting results into DB");
MeetingResults meetingResultsTable = psqlManager.getMeetingResults();
meetingResultsTable.setTableModels(
meetingResults.toArray(new MeetingResult[meetingResults.size()]));
String insertQueries = meetingResultsTable.insertQuery(meetingResultsTable.getTableModels());
String[] ids = psqlManager.executeQueries(insertQueries);
for (int i = 0; i < meetingResults.size(); ++i) {
meetingResults.get(i).setId(ids[i]);
}
System.out.println("OK");
return true;
}
| private boolean generateMeetingResults() {
HashMap<Box, ArrayList<MouseInterval>> boxSet = new HashMap<Box, ArrayList<MouseInterval>>();
for (StayResult stayResult : stayResults) {
Box box = stayResult.getBox();
ArrayList<MouseInterval> mouseIntervals = boxSet.get(box);
if (mouseIntervals == null) {
mouseIntervals = new ArrayList<MouseInterval>();
}
Transponder mouse = stayResult.getTransponder();
TimeStamp start = stayResult.getStart();
TimeStamp stop = stayResult.getStop();
MouseInterval mouseInterval = new MouseInterval(mouse, start, stop);
mouseIntervals.add(mouseInterval);
boxSet.put(box, mouseIntervals);
}
Iterator<Entry<Box, ArrayList<MouseInterval>>> it = boxSet.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Box, ArrayList<MouseInterval>> pair =
(Map.Entry<Box, ArrayList<MouseInterval>>) it.next();
Box box = pair.getKey();
ArrayList<MouseInterval> mouseIntervals = pair.getValue();
for (MouseInterval mouseInterval : mouseIntervals) {
Transponder transponderFrom = mouseInterval.getMouse();
for (MouseInterval innerMouseInterval : mouseIntervals) {
if (innerMouseInterval.getMouse() == mouseInterval.getMouse())
continue;
if (innerMouseInterval.getStart().before(mouseInterval.getStart()))
continue; //Avoid duplicate entries
Transponder transponderTo = innerMouseInterval.getMouse();
TimeStamp start = mouseInterval.getStart().after(innerMouseInterval.getStart())
? mouseInterval.getStart()
: innerMouseInterval.getStart();
TimeStamp stop = mouseInterval.getStop().before(innerMouseInterval.getStop())
? mouseInterval.getStop()
: innerMouseInterval.getStop();
if (stop.before(start))
continue;
Transponder terminatedBy = mouseInterval.getStop().before(innerMouseInterval.getStop())
? transponderFrom
: transponderTo;
float duration = (new Interval(start.getTime(), stop.getTime())).getEndMillis();
MeetingResult meetingResult = new MeetingResult(transponderFrom, transponderTo, start,
stop, duration, terminatedBy == transponderFrom ? 0 : 1, box);
meetingResults.add(meetingResult);
}
}
it.remove();
}
System.out.println("OK\nSaving meeting results into DB");
MeetingResults meetingResultsTable = psqlManager.getMeetingResults();
meetingResultsTable.setTableModels(
meetingResults.toArray(new MeetingResult[meetingResults.size()]));
String insertQueries = meetingResultsTable.insertQuery(meetingResultsTable.getTableModels());
String[] ids = psqlManager.executeQueries(insertQueries);
for (int i = 0; i < meetingResults.size(); ++i) {
meetingResults.get(i).setId(ids[i]);
}
System.out.println("OK");
return true;
}
|
diff --git a/src/VASSAL/tools/imageop/Op.java b/src/VASSAL/tools/imageop/Op.java
index 0d559d13..54953baa 100644
--- a/src/VASSAL/tools/imageop/Op.java
+++ b/src/VASSAL/tools/imageop/Op.java
@@ -1,130 +1,130 @@
/*
* $Id$
*
* Copyright (c) 2007-2010 by Joel Uckelman
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License (LGPL) as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, copies are available
* at http://www.opensource.org.
*/
package VASSAL.tools.imageop;
import java.awt.image.BufferedImage;
import VASSAL.build.BadDataReport;
import VASSAL.counters.GamePiece;
import VASSAL.tools.ErrorDialog;
import VASSAL.tools.image.ImageIOException;
import VASSAL.tools.image.ImageNotFoundException;
import VASSAL.tools.image.UnrecognizedImageTypeException;
import VASSAL.tools.opcache.OpFailedException;
public class Op {
protected Op() {}
public static SourceOp load(String name) {
if (!name.startsWith("/"))
name = "images/" + name;
if (name.endsWith(".svg"))
return new SourceOpSVGImpl(name);
else
return new SourceOpBitmapImpl(name);
}
public static SourceOp load(BufferedImage image) {
return new ImageSourceOpBitmapImpl(image);
}
public static SourceOp loadLarge(String name) {
if (name.endsWith(".svg"))
return new SourceOpSVGImpl(name);
else
return new SourceOpTiledBitmapImpl(name);
}
public static ScaleOp scale(ImageOp sop, double scale) {
if (sop instanceof SVGOp)
return new RotateScaleOpSVGImpl((SVGOp) sop, 0.0, scale);
else
// FIXME: Using ScaleOpTiledBitmapImpl for all scaling is wrong, because
// non-map images aren't in the disk cache!
// return new ScaleOpBitmapImpl(sop, scale);
return new ScaleOpTiledBitmapImpl(sop, scale);
}
public static RotateOp rotate(ImageOp sop, double angle) {
if (sop instanceof SVGOp)
return new RotateScaleOpSVGImpl((SVGOp) sop, angle, 1.0);
else if (angle % 90.0 == 0.0)
return new OrthoRotateOpBitmapImpl(sop, (int) angle);
else
return new RotateScaleOpBitmapImpl(sop, angle, 1.0);
}
public static RotateScaleOp rotateScale(ImageOp sop,
double angle, double scale) {
if (sop instanceof SVGOp)
return new RotateScaleOpSVGImpl((SVGOp) sop, angle, scale);
else
return new RotateScaleOpBitmapImpl(sop, angle, scale);
}
public static CropOp crop(ImageOp sop, int x0, int y0, int x1, int y1) {
return new CropOpBitmapImpl(sop, x0, y0, x1, y1);
}
public static GamePieceOp piece(GamePiece gp) {
return new GamePieceOpImpl(gp);
}
public static void clearCache() {
AbstractOpImpl.clearCache();
}
public static boolean handleException(Exception e) {
for (Throwable c = e; c != null; c = c.getCause()) {
if (c instanceof OpFailedException) {
// We ignore OpFailedExceptions since the original exceptions
// which caused them have already been reported.
return true;
}
else if (c instanceof ImageNotFoundException) {
ErrorDialog.dataError(new BadDataReport(
"Image not found",
((ImageNotFoundException) c).getFile().getName(),
- c
+ null
));
return true;
}
else if (c instanceof UnrecognizedImageTypeException) {
ErrorDialog.dataError(new BadDataReport(
"Unrecognized image type",
((UnrecognizedImageTypeException) c).getFile().getName(),
c
));
return true;
}
else if (c instanceof ImageIOException) {
ErrorDialog.dataError(new BadDataReport(
"Error reading image",
((ImageIOException) c).getFile().getName(),
c
));
return true;
}
}
return false;
}
}
| true | true | public static boolean handleException(Exception e) {
for (Throwable c = e; c != null; c = c.getCause()) {
if (c instanceof OpFailedException) {
// We ignore OpFailedExceptions since the original exceptions
// which caused them have already been reported.
return true;
}
else if (c instanceof ImageNotFoundException) {
ErrorDialog.dataError(new BadDataReport(
"Image not found",
((ImageNotFoundException) c).getFile().getName(),
c
));
return true;
}
else if (c instanceof UnrecognizedImageTypeException) {
ErrorDialog.dataError(new BadDataReport(
"Unrecognized image type",
((UnrecognizedImageTypeException) c).getFile().getName(),
c
));
return true;
}
else if (c instanceof ImageIOException) {
ErrorDialog.dataError(new BadDataReport(
"Error reading image",
((ImageIOException) c).getFile().getName(),
c
));
return true;
}
}
return false;
}
| public static boolean handleException(Exception e) {
for (Throwable c = e; c != null; c = c.getCause()) {
if (c instanceof OpFailedException) {
// We ignore OpFailedExceptions since the original exceptions
// which caused them have already been reported.
return true;
}
else if (c instanceof ImageNotFoundException) {
ErrorDialog.dataError(new BadDataReport(
"Image not found",
((ImageNotFoundException) c).getFile().getName(),
null
));
return true;
}
else if (c instanceof UnrecognizedImageTypeException) {
ErrorDialog.dataError(new BadDataReport(
"Unrecognized image type",
((UnrecognizedImageTypeException) c).getFile().getName(),
c
));
return true;
}
else if (c instanceof ImageIOException) {
ErrorDialog.dataError(new BadDataReport(
"Error reading image",
((ImageIOException) c).getFile().getName(),
c
));
return true;
}
}
return false;
}
|
diff --git a/src/main/java/org/nuxeo/build/ant/RenameTask.java b/src/main/java/org/nuxeo/build/ant/RenameTask.java
index 2f8c84c..d84cd4d 100644
--- a/src/main/java/org/nuxeo/build/ant/RenameTask.java
+++ b/src/main/java/org/nuxeo/build/ant/RenameTask.java
@@ -1,61 +1,61 @@
/*
* (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:
* bstefanescu
*/
package org.nuxeo.build.ant;
import java.io.File;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
/**
* @author <a href="mailto:[email protected]">Bogdan Stefanescu</a>
*
*/
public class RenameTask extends Task {
protected File from;
protected File to;
public void setFrom(File from) {
this.from = from;
}
public void setTo(File to) {
this.to = to;
}
@Override
public void execute() throws BuildException {
String fromName = from.getName();
if (fromName.endsWith("*")) {
String prefix = fromName.substring(0, fromName.length() - 1);
File dir = from.getParentFile();
File[] files = dir.listFiles();
for (int k = 0; k < files.length; k++) {
File f = files[k];
- if (f.getAbsolutePath().startsWith(prefix)) {
+ if (f.getName().startsWith(prefix)) {
f.renameTo(to);
return;
}
}
} else {
from.renameTo(to);
}
}
}
| true | true | public void execute() throws BuildException {
String fromName = from.getName();
if (fromName.endsWith("*")) {
String prefix = fromName.substring(0, fromName.length() - 1);
File dir = from.getParentFile();
File[] files = dir.listFiles();
for (int k = 0; k < files.length; k++) {
File f = files[k];
if (f.getAbsolutePath().startsWith(prefix)) {
f.renameTo(to);
return;
}
}
} else {
from.renameTo(to);
}
}
| public void execute() throws BuildException {
String fromName = from.getName();
if (fromName.endsWith("*")) {
String prefix = fromName.substring(0, fromName.length() - 1);
File dir = from.getParentFile();
File[] files = dir.listFiles();
for (int k = 0; k < files.length; k++) {
File f = files[k];
if (f.getName().startsWith(prefix)) {
f.renameTo(to);
return;
}
}
} else {
from.renameTo(to);
}
}
|
diff --git a/src/com/jidesoft/swing/JideScrollPaneLayout.java b/src/com/jidesoft/swing/JideScrollPaneLayout.java
index 23e4f49a..c691730b 100644
--- a/src/com/jidesoft/swing/JideScrollPaneLayout.java
+++ b/src/com/jidesoft/swing/JideScrollPaneLayout.java
@@ -1,1062 +1,1062 @@
/*
* @(#)${NAME}.java
*
* Copyright 2002 - 2005 JIDE Software Inc. All rights reserved.
*/
package com.jidesoft.swing;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
/**
* The layout manager used by <code>JideScrollPane</code>. <code>JideScrollPaneLayout</code> is responsible for eleven
* components: a viewport, two scrollbars, a row header, a column header, a row footer, a column footer, and four
* "corner" components.
*/
public class JideScrollPaneLayout extends ScrollPaneLayout implements JideScrollPaneConstants {
/**
* The row footer child. Default is <code>null</code>.
*
* @see JideScrollPane#setRowFooter
*/
protected JViewport _rowFoot;
/**
* The row sub column header componeng. Default is <code>null</code>.
*
* @see JideScrollPane#setSubColumnHeader
*/
protected JViewport _subColHead;
/**
* The column footer child. Default is <code>null</code>.
*
* @see JideScrollPane#setColumnFooter
*/
protected JViewport _colFoot;
/**
* The component to the left of horizontal scroll bar.
*/
protected Component _hLeft;
/**
* The component to the right of horizontal scroll bar.
*/
protected Component _hRight;
/**
* The component to the top of vertical scroll bar.
*/
protected Component _vTop;
/**
* The component to the bottom of vertical scroll bar.
*/
protected Component _vBottom;
private static final long serialVersionUID = 7897026041296359186L;
@Override
public void syncWithScrollPane(JScrollPane sp) {
super.syncWithScrollPane(sp);
if (sp instanceof JideScrollPane) {
_rowFoot = ((JideScrollPane) sp).getRowFooter();
_colFoot = ((JideScrollPane) sp).getColumnFooter();
_subColHead = ((JideScrollPane) sp).getSubColumnHeader();
_hLeft = ((JideScrollPane) sp).getScrollBarCorner(HORIZONTAL_LEFT);
_hRight = ((JideScrollPane) sp).getScrollBarCorner(HORIZONTAL_RIGHT);
_vTop = ((JideScrollPane) sp).getScrollBarCorner(VERTICAL_TOP);
_vBottom = ((JideScrollPane) sp).getScrollBarCorner(VERTICAL_BOTTOM);
}
}
protected boolean isHsbCoversWholeWidth(JScrollPane sp) {
return sp instanceof JideScrollPane && ((JideScrollPane) sp).isHorizontalScrollBarCoversWholeWidth();
}
protected boolean isVsbCoversWholeHeight(JScrollPane sp) {
return sp instanceof JideScrollPane && ((JideScrollPane) sp).isVerticalScrollBarCoversWholeHeight();
}
protected boolean isColumnHeadersHeightUnified(JScrollPane sp) {
return sp instanceof JideScrollPane && ((JideScrollPane) sp).isColumnHeadersHeightUnified();
}
protected boolean isColumnFootersHeightUnified(JScrollPane sp) {
return sp instanceof JideScrollPane && ((JideScrollPane) sp).isColumnFootersHeightUnified();
}
@Override
public void addLayoutComponent(String s, Component c) {
if (s.equals(ROW_FOOTER)) {
_rowFoot = (JViewport) addSingletonComponent(_rowFoot, c);
}
else if (s.equals(SUB_COLUMN_HEADER)) {
_subColHead = (JViewport) addSingletonComponent(_subColHead, c);
}
else if (s.equals(COLUMN_FOOTER)) {
_colFoot = (JViewport) addSingletonComponent(_colFoot, c);
}
else if (s.equals(HORIZONTAL_LEFT)) {
_hLeft = addSingletonComponent(_hLeft, c);
}
else if (s.equals(HORIZONTAL_RIGHT)) {
_hRight = addSingletonComponent(_hRight, c);
}
else if (s.equals(VERTICAL_TOP)) {
_vTop = addSingletonComponent(_vTop, c);
}
else if (s.equals(VERTICAL_BOTTOM)) {
_vBottom = addSingletonComponent(_vBottom, c);
}
else {
super.addLayoutComponent(s, c);
}
}
@Override
public void removeLayoutComponent(Component c) {
if (c == _rowFoot) {
_rowFoot = null;
}
else if (c == _subColHead) {
_subColHead = null;
}
else if (c == _colFoot) {
_colFoot = null;
}
else if (c == _hLeft) {
_hLeft = null;
}
else if (c == _hRight) {
_hRight = null;
}
else if (c == _vTop) {
_vTop = null;
}
else if (c == _vBottom) {
_vBottom = null;
}
else {
super.removeLayoutComponent(c);
}
}
/**
* Returns the <code>JViewport</code> object that is the row footer.
*
* @return the <code>JViewport</code> object that is the row footer
*
* @see JideScrollPane#getRowFooter
*/
public JViewport getRowFooter() {
return _rowFoot;
}
/**
* Returns the <code>JViewport</code> object that is the row sub column header.
*
* @return the <code>JViewport</code> object that is the row sub column header.
*
* @see com.jidesoft.swing.JideScrollPane#getSubColumnHeader()
*/
public JViewport getRowSubColumnHeader() {
return _subColHead;
}
/**
* Returns the <code>JViewport</code> object that is the column footer.
*
* @return the <code>JViewport</code> object that is the column footer
*
* @see JideScrollPane#getColumnFooter
*/
public JViewport getColumnFooter() {
return _colFoot;
}
/**
* Returns the <code>Component</code> at the specified corner.
*
* @param key the <code>String</code> specifying the corner
* @return the <code>Component</code> at the specified corner, as defined in {@link ScrollPaneConstants}; if
* <code>key</code> is not one of the four corners, <code>null</code> is returned
*
* @see JScrollPane#getCorner
*/
public Component getScrollBarCorner(String key) {
if (key.equals(HORIZONTAL_LEFT)) {
return _hLeft;
}
else if (key.equals(HORIZONTAL_RIGHT)) {
return _hRight;
}
else if (key.equals(VERTICAL_BOTTOM)) {
return _vBottom;
}
else if (key.equals(VERTICAL_TOP)) {
return _vTop;
}
else {
return super.getCorner(key);
}
}
/**
* The preferred size of a <code>ScrollPane</code> is the size of the insets, plus the preferred size of the
* viewport, plus the preferred size of the visible headers, plus the preferred size of the scrollbars that will
* appear given the current view and the current scrollbar displayPolicies. <p>Note that the rowHeader is calculated
* as part of the preferred width and the colHeader is calculated as part of the preferred size.
*
* @param parent the <code>Container</code> that will be laid out
* @return a <code>Dimension</code> object specifying the preferred size of the viewport and any scrollbars
*
* @see ViewportLayout
* @see LayoutManager
*/
@Override
public Dimension preferredLayoutSize(Container parent) {
/* Sync the (now obsolete) policy fields with the
* JScrollPane.
*/
JScrollPane scrollPane = (JScrollPane) parent;
vsbPolicy = scrollPane.getVerticalScrollBarPolicy();
hsbPolicy = scrollPane.getHorizontalScrollBarPolicy();
Insets insets = parent.getInsets();
int prefWidth = insets.left + insets.right;
int prefHeight = insets.top + insets.bottom;
/* Note that viewport.getViewSize() is equivalent to
* viewport.getView().getPreferredSize() modulo a null
* view or a view whose size was explicitly set.
*/
Dimension extentSize = null;
Dimension viewSize = null;
Component view = null;
if (viewport != null) {
extentSize = viewport.getPreferredSize();
viewSize = viewport.getViewSize();
view = viewport.getView();
}
/* If there's a viewport add its preferredSize.
*/
if (extentSize != null) {
prefWidth += extentSize.width;
prefHeight += extentSize.height;
}
/* If there's a JScrollPane.viewportBorder, add its insets.
*/
Border viewportBorder = scrollPane.getViewportBorder();
if (viewportBorder != null) {
Insets vpbInsets = viewportBorder.getBorderInsets(parent);
prefWidth += vpbInsets.left + vpbInsets.right;
prefHeight += vpbInsets.top + vpbInsets.bottom;
}
/* If a header exists and it's visible, factor its
* preferred size in.
*/
int rowHeaderWidth = 0;
if (rowHead != null && rowHead.isVisible()) {
rowHeaderWidth = rowHead.getPreferredSize().width;
}
if (upperLeft != null && upperLeft.isVisible()) {
rowHeaderWidth = Math.max(rowHeaderWidth, upperLeft.getPreferredSize().width);
}
if (lowerLeft != null && lowerLeft.isVisible()) {
rowHeaderWidth = Math.max(rowHeaderWidth, lowerLeft.getPreferredSize().width);
}
prefWidth += rowHeaderWidth;
int upperHeight = getUpperHeight();
prefHeight += upperHeight;
if ((_rowFoot != null) && _rowFoot.isVisible()) {
prefWidth += _rowFoot.getPreferredSize().width;
}
int lowerHeight = getLowerHeight();
prefHeight += lowerHeight;
/* If a scrollbar is going to appear, factor its preferred size in.
* If the scrollbars policy is AS_NEEDED, this can be a little
* tricky:
*
* - If the view is a Scrollable then scrollableTracksViewportWidth
* and scrollableTracksViewportHeight can be used to effectively
* disable scrolling (if they're true) in their respective dimensions.
*
* - Assuming that a scrollbar hasn't been disabled by the
* previous constraint, we need to decide if the scrollbar is going
* to appear to correctly compute the JScrollPanes preferred size.
* To do this we compare the preferredSize of the viewport (the
* extentSize) to the preferredSize of the view. Although we're
* not responsible for laying out the view we'll assume that the
* JViewport will always give it its preferredSize.
*/
if ((vsb != null) && (vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
if (vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS) {
prefWidth += vsb.getPreferredSize().width;
}
else if ((viewSize != null) && (extentSize != null)) {
boolean canScroll = true;
if (view instanceof Scrollable) {
canScroll = !((Scrollable) view).getScrollableTracksViewportHeight();
}
if (canScroll && (viewSize.height > extentSize.height)) {
prefWidth += vsb.getPreferredSize().width;
}
}
}
if ((hsb != null) && (hsbPolicy != HORIZONTAL_SCROLLBAR_NEVER)) {
if (hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) {
prefHeight += hsb.getPreferredSize().height;
}
else if ((viewSize != null) && (extentSize != null)) {
boolean canScroll = true;
if (view instanceof Scrollable) {
canScroll = !((Scrollable) view).getScrollableTracksViewportWidth();
}
if (canScroll && (viewSize.width > extentSize.width)) {
prefHeight += hsb.getPreferredSize().height;
}
}
}
return new Dimension(prefWidth, prefHeight);
}
private int getUpperHeight() {
int upperHeight = 0;
if ((upperLeft != null) && upperLeft.isVisible()) {
upperHeight = upperLeft.getPreferredSize().height;
}
if ((upperRight != null) && upperRight.isVisible()) {
upperHeight = Math.max(upperRight.getPreferredSize().height, upperHeight);
}
if ((colHead != null) && colHead.isVisible()) {
upperHeight = Math.max(colHead.getPreferredSize().height, upperHeight);
}
return upperHeight;
}
private int getLowerHeight() {
int lowerHeight = 0;
if ((lowerLeft != null) && lowerLeft.isVisible()) {
lowerHeight = lowerLeft.getPreferredSize().height;
}
if ((lowerRight != null) && lowerRight.isVisible()) {
lowerHeight = Math.max(lowerRight.getPreferredSize().height, lowerHeight);
}
if ((_colFoot != null) && _colFoot.isVisible()) {
lowerHeight = Math.max(_colFoot.getPreferredSize().height, lowerHeight);
}
return lowerHeight;
}
/**
* The minimum size of a <code>ScrollPane</code> is the size of the insets plus minimum size of the viewport, plus
* the scrollpane's viewportBorder insets, plus the minimum size of the visible headers, plus the minimum size of
* the scrollbars whose displayPolicy isn't NEVER.
*
* @param parent the <code>Container</code> that will be laid out
* @return a <code>Dimension</code> object specifying the minimum size
*/
@Override
public Dimension minimumLayoutSize(Container parent) {
/* Sync the (now obsolete) policy fields with the
* JScrollPane.
*/
JScrollPane scrollPane = (JScrollPane) parent;
vsbPolicy = scrollPane.getVerticalScrollBarPolicy();
hsbPolicy = scrollPane.getHorizontalScrollBarPolicy();
Insets insets = parent.getInsets();
int minWidth = insets.left + insets.right;
int minHeight = insets.top + insets.bottom;
/* If there's a viewport add its minimumSize.
*/
if (viewport != null) {
Dimension size = viewport.getMinimumSize();
minWidth += size.width;
minHeight += size.height;
}
/* If there's a JScrollPane.viewportBorder, add its insets.
*/
Border viewportBorder = scrollPane.getViewportBorder();
if (viewportBorder != null) {
Insets vpbInsets = viewportBorder.getBorderInsets(parent);
minWidth += vpbInsets.left + vpbInsets.right;
minHeight += vpbInsets.top + vpbInsets.bottom;
}
/* If a header exists and it's visible, factor its
* minimum size in.
*/
int rowHeaderWidth = 0;
if (rowHead != null && rowHead.isVisible()) {
Dimension size = rowHead.getMinimumSize();
rowHeaderWidth = size.width;
minHeight = Math.max(minHeight, size.height);
}
if (upperLeft != null && upperLeft.isVisible()) {
rowHeaderWidth = Math.max(rowHeaderWidth, upperLeft.getMinimumSize().width);
}
if (lowerLeft != null && lowerLeft.isVisible()) {
rowHeaderWidth = Math.max(rowHeaderWidth, lowerLeft.getMinimumSize().width);
}
minWidth += rowHeaderWidth;
int upperHeight = 0;
if ((upperLeft != null) && upperLeft.isVisible()) {
upperHeight = upperLeft.getMinimumSize().height;
}
if ((upperRight != null) && upperRight.isVisible()) {
upperHeight = Math.max(upperRight.getMinimumSize().height, upperHeight);
}
if ((colHead != null) && colHead.isVisible()) {
Dimension size = colHead.getMinimumSize();
minWidth = Math.max(minWidth, size.width);
upperHeight = Math.max(size.height, upperHeight);
}
minHeight += upperHeight;
if (_subColHead != null && _subColHead.isVisible()) {
Dimension size = _subColHead.getMinimumSize();
minWidth = Math.max(minWidth, size.width);
minHeight += size.height;
}
// JIDE: added for JideScrollPaneLayout
int lowerHeight = 0;
if ((lowerLeft != null) && lowerLeft.isVisible()) {
lowerHeight = lowerLeft.getMinimumSize().height;
}
if ((lowerRight != null) && lowerRight.isVisible()) {
lowerHeight = Math.max(lowerRight.getMinimumSize().height, lowerHeight);
}
if ((_colFoot != null) && _colFoot.isVisible()) {
Dimension size = _colFoot.getMinimumSize();
minWidth = Math.max(minWidth, size.width);
lowerHeight = Math.max(size.height, lowerHeight);
}
minHeight += lowerHeight;
if ((_rowFoot != null) && _rowFoot.isVisible()) {
Dimension size = _rowFoot.getMinimumSize();
minWidth = Math.max(minWidth, size.width);
minHeight += size.height;
}
// JIDE: End of added for JideScrollPaneLayout
/* If a scrollbar might appear, factor its minimum
* size in.
*/
if ((vsb != null) && (vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
Dimension size = vsb.getMinimumSize();
minWidth += size.width;
minHeight = Math.max(minHeight, size.height);
}
if ((hsb != null) && (hsbPolicy != HORIZONTAL_SCROLLBAR_NEVER)) {
Dimension size = hsb.getMinimumSize();
minWidth = Math.max(minWidth, size.width);
minHeight += size.height;
}
return new Dimension(minWidth, minHeight);
}
/**
* Lays out the scrollpane. The positioning of components depends on the following constraints: <ul> <li> The row
* header, if present and visible, gets its preferred width and the viewport's height.
* <p/>
* <li> The column header, if present and visible, gets its preferred height and the viewport's width.
* <p/>
* <li> If a vertical scrollbar is needed, i.e. if the viewport's extent height is smaller than its view height or
* if the <code>displayPolicy</code> is ALWAYS, it's treated like the row header with respect to its dimensions and
* is made visible.
* <p/>
* <li> If a horizontal scrollbar is needed, it is treated like the column header (see the paragraph above regarding
* the vertical scrollbar).
* <p/>
* <li> If the scrollpane has a non-<code>null</code> <code>viewportBorder</code>, then space is allocated for
* that.
* <p/>
* <li> The viewport gets the space available after accounting for the previous constraints.
* <p/>
* <li> The corner components, if provided, are aligned with the ends of the scrollbars and headers. If there is a
* vertical scrollbar, the right corners appear; if there is a horizontal scrollbar, the lower corners appear; a row
* header gets left corners, and a column header gets upper corners. </ul>
*
* @param parent the <code>Container</code> to lay out
*/
@Override
public void layoutContainer(Container parent) {
/* Sync the (now obsolete) policy fields with the
* JScrollPane.
*/
JScrollPane scrollPane = (JScrollPane) parent;
vsbPolicy = scrollPane.getVerticalScrollBarPolicy();
hsbPolicy = scrollPane.getHorizontalScrollBarPolicy();
Rectangle availR = scrollPane.getBounds();
availR.x = availR.y = 0;
Insets insets = parent.getInsets();
availR.x = insets.left;
availR.y = insets.top;
availR.width -= insets.left + insets.right;
availR.height -= insets.top + insets.bottom;
/* If there's a visible column header remove the space it
* needs from the top of availR. The column header is treated
* as if it were fixed height, arbitrary width.
*/
Rectangle colHeadR = new Rectangle(0, availR.y, 0, 0);
int upperHeight = getUpperHeight();
if ((colHead != null) && (colHead.isVisible())) {
int colHeadHeight = Math.min(availR.height, upperHeight);
colHeadR.height = colHeadHeight;
availR.y += colHeadHeight;
availR.height -= colHeadHeight;
}
Rectangle subColHeadR = new Rectangle(0, availR.y, 0, 0);
if (_subColHead != null && _subColHead.isVisible()) {
int subColHeadHeight = Math.min(availR.height, _subColHead.getPreferredSize().height);
subColHeadR.height = subColHeadHeight;
availR.y += subColHeadHeight;
availR.height -= subColHeadHeight;
}
/* If there's a visible row header remove the space it needs
* from the left or right of availR. The row header is treated
* as if it were fixed width, arbitrary height.
*/
Rectangle rowHeadR = new Rectangle(0, 0, 0, 0);
if ((rowHead != null) && (rowHead.isVisible())) {
int rowHeadWidth = rowHead.getPreferredSize().width;
if (upperLeft != null && upperLeft.isVisible()) {
rowHeadWidth = Math.max(rowHeadWidth, upperLeft.getPreferredSize().width);
}
if (lowerLeft != null && lowerLeft.isVisible()) {
rowHeadWidth = Math.max(rowHeadWidth, lowerLeft.getPreferredSize().width);
}
rowHeadR.width = rowHeadWidth;
availR.width -= rowHeadWidth;
rowHeadR.x = availR.x;
availR.x += rowHeadWidth;
}
/* If there's a JScrollPane.viewportBorder, remove the
* space it occupies for availR.
*/
Border viewportBorder = scrollPane.getViewportBorder();
Insets vpbInsets;
if (viewportBorder != null) {
vpbInsets = viewportBorder.getBorderInsets(parent);
availR.x += vpbInsets.left;
availR.y += vpbInsets.top;
availR.width -= vpbInsets.left + vpbInsets.right;
availR.height -= vpbInsets.top + vpbInsets.bottom;
}
else {
vpbInsets = new Insets(0, 0, 0, 0);
}
/* If there's a visible row footer remove the space it needs
* from the left or right of availR. The row footer is treated
* as if it were fixed width, arbitrary height.
*/
Rectangle rowFootR = new Rectangle(0, 0, 0, 0);
if ((_rowFoot != null) && (_rowFoot.isVisible())) {
int rowFootWidth = _rowFoot.getPreferredSize().width;
if (upperRight != null && upperRight.isVisible()) {
rowFootWidth = Math.max(rowFootWidth, upperRight.getPreferredSize().width);
}
if (lowerRight != null && lowerRight.isVisible()) {
rowFootWidth = Math.max(rowFootWidth, lowerRight.getPreferredSize().width);
}
rowFootR.width = rowFootWidth;
availR.width -= rowFootWidth;
rowFootR.x = availR.x + availR.width;
}
/* If there's a visible column footer remove the space it
* needs from the top of availR. The column footer is treated
* as if it were fixed height, arbitrary width.
*/
Rectangle colFootR = new Rectangle(0, availR.y, 0, 0);
int lowerHeight = getLowerHeight();
if ((_colFoot != null) && (_colFoot.isVisible())) {
int colFootHeight = Math.min(availR.height, lowerHeight);
colFootR.height = colFootHeight;
availR.height -= colFootHeight;
colFootR.y = availR.y + availR.height;
}
/* At this point availR is the space available for the viewport
* and scrollbars. rowHeadR is correct except for its height and y
* and colHeadR is correct except for its width and x. Once we're
* through computing the dimensions of these three parts we can
* go back and set the dimensions of rowHeadR.height, rowHeadR.y,
* colHeadR.width, colHeadR.x and the bounds for the corners.
*
* We'll decide about putting up scrollbars by comparing the
* viewport views preferred size with the viewports extent
* size (generally just its size). Using the preferredSize is
* reasonable because layout proceeds top down - so we expect
* the viewport to be laid out next. And we assume that the
* viewports layout manager will give the view it's preferred
* size. One exception to this is when the view implements
* Scrollable and Scrollable.getViewTracksViewport{Width,Height}
* methods return true. If the view is tracking the viewports
* width we don't bother with a horizontal scrollbar, similarly
* if view.getViewTracksViewport(Height) is true we don't bother
* with a vertical scrollbar.
*/
Component view = (viewport != null) ? viewport.getView() : null;
Dimension viewPrefSize = (view != null) ? view.getPreferredSize() : new Dimension(0, 0);
Dimension extentSize =
(viewport != null) ? viewport.toViewCoordinates(availR.getSize())
: new Dimension(0, 0);
boolean viewTracksViewportWidth = false;
boolean viewTracksViewportHeight = false;
boolean isEmpty = (availR.width < 0 || availR.height < 0);
Scrollable sv;
// Don't bother checking the Scrollable methods if there is no room
// for the viewport, we aren't going to show any scrollbars in this
// case anyway.
if (!isEmpty && view instanceof Scrollable) {
sv = (Scrollable) view;
viewTracksViewportWidth = sv.getScrollableTracksViewportWidth();
viewTracksViewportHeight = sv.getScrollableTracksViewportHeight();
}
else {
sv = null;
}
/* If there's a vertical scrollbar and we need one, allocate
* space for it (we'll make it visible later). A vertical
* scrollbar is considered to be fixed width, arbitrary height.
*/
Rectangle vsbR = new Rectangle(0, isVsbCoversWholeHeight(scrollPane) ? insets.top : availR.y - vpbInsets.top, 0, 0);
boolean vsbNeeded;
if (vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS) {
vsbNeeded = true;
}
else if (vsbPolicy == VERTICAL_SCROLLBAR_NEVER) {
vsbNeeded = false;
}
else if (isEmpty) {
vsbNeeded = false;
}
else { // vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED
vsbNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || (rowHead != null && rowHead.getView() != null && rowHead.getView().getPreferredSize().height > extentSize.height));
if (!vsbNeeded && scrollPane instanceof JideScrollPane && ((JideScrollPane) scrollPane).isKeepCornerVisible() && (_vBottom != null || _vTop != null)) {
vsbNeeded = true;
}
}
if ((vsb != null) && vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets, true);
extentSize = viewport.toViewCoordinates(availR.getSize());
}
/* If there's a horizontal scrollbar and we need one, allocate
* space for it (we'll make it visible later). A horizontal
* scrollbar is considered to be fixed height, arbitrary width.
*/
Rectangle hsbR = new Rectangle(isHsbCoversWholeWidth(scrollPane) ? insets.left : availR.x - vpbInsets.left, 0, 0, 0);
boolean hsbNeeded;
if (hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) {
hsbNeeded = true;
}
else if (hsbPolicy == HORIZONTAL_SCROLLBAR_NEVER) {
hsbNeeded = false;
}
else if (isEmpty) {
hsbNeeded = false;
}
else { // hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED
hsbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || (colHead != null && colHead.getView() != null && colHead.getView().getPreferredSize().width > extentSize.width));
if (!hsbNeeded && scrollPane instanceof JideScrollPane && ((JideScrollPane) scrollPane).isKeepCornerVisible() && (_hLeft != null || _hRight != null)) {
hsbNeeded = true;
}
}
if ((hsb != null) && hsbNeeded) {
adjustForHSB(true, availR, hsbR, vpbInsets);
/* If we added the horizontal scrollbar then we've implicitly
* reduced the vertical space available to the viewport.
* As a consequence we may have to add the vertical scrollbar,
* if that hasn't been done so already. Of course we
* don't bother with any of this if the vsbPolicy is NEVER.
*/
if ((vsb != null) && !vsbNeeded &&
(vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
extentSize = viewport.toViewCoordinates(availR.getSize());
vsbNeeded = viewPrefSize.height > extentSize.height;
if (!vsbNeeded && scrollPane instanceof JideScrollPane && ((JideScrollPane) scrollPane).isKeepCornerVisible() && (_vBottom != null || _vTop != null)) {
vsbNeeded = true;
}
if (vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets, true);
}
}
}
/* Set the size of the viewport first, and then recheck the Scrollable
* methods. Some components base their return values for the Scrollable
* methods on the size of the Viewport, so that if we don't
* ask after resetting the bounds we may have gotten the wrong
* answer.
*/
// Get the scrollPane's orientation.
boolean ltr = scrollPane.getComponentOrientation().isLeftToRight();
if (viewport != null) {
viewport.setBounds(adjustBounds(parent, availR, ltr));
// viewport.setViewSize(availR.getSize()); // to fix the strange scroll bar problem reported on http://www.jidesoft.com/forum/viewtopic.php?p=20526#20526
if (sv != null) {
extentSize = viewport.toViewCoordinates(availR.getSize());
boolean oldHSBNeeded = hsbNeeded;
boolean oldVSBNeeded = vsbNeeded;
viewTracksViewportWidth = sv.getScrollableTracksViewportWidth();
viewTracksViewportHeight = sv.getScrollableTracksViewportHeight();
if (vsb != null && vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED) {
boolean newVSBNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || (rowHead != null && rowHead.getView() != null && rowHead.getView().getPreferredSize().height > extentSize.height));
if (!newVSBNeeded && scrollPane instanceof JideScrollPane && ((JideScrollPane) scrollPane).isKeepCornerVisible() && (_vBottom != null || _vTop != null)) {
newVSBNeeded = true;
}
if (newVSBNeeded != vsbNeeded) {
vsbNeeded = newVSBNeeded;
adjustForVSB(vsbNeeded, availR, vsbR, vpbInsets, true);
extentSize = viewport.toViewCoordinates
(availR.getSize());
}
}
if (hsb != null && hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED) {
boolean newHSBbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || (colHead != null && colHead.getView() != null && colHead.getView().getPreferredSize().width > extentSize.width));
if (!newHSBbNeeded && scrollPane instanceof JideScrollPane && ((JideScrollPane) scrollPane).isKeepCornerVisible() && (_hLeft != null || _hRight != null)) {
newHSBbNeeded = true;
}
if (newHSBbNeeded != hsbNeeded) {
hsbNeeded = newHSBbNeeded;
adjustForHSB(hsbNeeded, availR, hsbR, vpbInsets);
if ((vsb != null) && !vsbNeeded &&
(vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
extentSize = viewport.toViewCoordinates
(availR.getSize());
vsbNeeded = viewPrefSize.height >
extentSize.height;
if (!vsbNeeded && scrollPane instanceof JideScrollPane && ((JideScrollPane) scrollPane).isKeepCornerVisible() && (_vBottom != null || _vTop != null)) {
vsbNeeded = true;
}
if (vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets, true);
}
}
if (_rowFoot != null && _rowFoot.isVisible()) {
vsbR.x += rowFootR.width;
}
}
}
if (oldHSBNeeded != hsbNeeded ||
oldVSBNeeded != vsbNeeded) {
viewport.setBounds(adjustBounds(parent, availR, ltr));
// You could argue that we should recheck the
// Scrollable methods again until they stop changing,
// but they might never stop changing, so we stop here
// and don't do any additional checks.
}
}
}
/*
* We now have the final size of the viewport: availR.
* Now fixup the header and scrollbar widths/heights.
*/
vsbR.height = isVsbCoversWholeHeight(scrollPane) ? scrollPane.getHeight() - insets.bottom - insets.top : availR.height + vpbInsets.top + vpbInsets.bottom;
hsbR.width = isHsbCoversWholeWidth(scrollPane) ? scrollPane.getWidth() - vsbR.width - insets.left - insets.right : availR.width + vpbInsets.left + vpbInsets.right;
rowHeadR.height = availR.height + vpbInsets.top + vpbInsets.bottom;
rowHeadR.y = availR.y - vpbInsets.top;
colHeadR.width = availR.width + vpbInsets.left + vpbInsets.right;
colHeadR.x = availR.x - vpbInsets.left;
subColHeadR.width = colHeadR.width;
subColHeadR.x = colHeadR.x;
colFootR.x = availR.x;
colFootR.y = rowHeadR.y + rowHeadR.height;
colFootR.width = availR.width;
rowFootR.x = availR.x + availR.width;
rowFootR.y = availR.y;
rowFootR.height = availR.height;
vsbR.x += rowFootR.width;
hsbR.y += colFootR.height;
/* Set the bounds of the remaining components. The scrollbars
* are made invisible if they're not needed.
*/
if (rowHead != null) {
rowHead.setBounds(adjustBounds(parent, rowHeadR, ltr));
}
if (_rowFoot != null) {
_rowFoot.setBounds(adjustBounds(parent, rowFootR, ltr));
}
int columnHeaderHeight = isColumnHeadersHeightUnified(scrollPane) ? Math.max(colHeadR.height,
Math.max(upperLeft == null ? 0 : upperLeft.getPreferredSize().height, upperRight == null ? 0 : upperRight.getPreferredSize().height)) : 0;
int columnFooterHeight = isColumnFootersHeightUnified(scrollPane) ? Math.max(colFootR.height,
Math.max(lowerLeft == null ? 0 : lowerLeft.getPreferredSize().height, lowerRight == null ? 0 : lowerRight.getPreferredSize().height)) : 0;
if (colHead != null) {
int height = isColumnHeadersHeightUnified(scrollPane) ? columnHeaderHeight : Math.min(colHeadR.height, colHead.getPreferredSize().height);
colHead.setBounds(adjustBounds(parent, new Rectangle(colHeadR.x, colHeadR.y + colHeadR.height - height, colHeadR.width, height), ltr));
}
if (_subColHead != null) {
_subColHead.setBounds(adjustBounds(parent, subColHeadR, ltr));
}
if (_colFoot != null) {
int height = isColumnFootersHeightUnified(scrollPane) ? columnFooterHeight : Math.min(colFootR.height, _colFoot.getPreferredSize().height);
_colFoot.setBounds(adjustBounds(parent, new Rectangle(colFootR.x, colFootR.y, colFootR.width, height), ltr));
}
else {
if (isColumnFootersHeightUnified(scrollPane)) {
columnFooterHeight = hsbR.height;
}
}
if (vsb != null) {
if (vsbNeeded) {
vsb.setVisible(true);
if (vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED && !isEmpty && !(!viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || (rowHead != null && rowHead.getView() != null && rowHead.getView().getPreferredSize().height > extentSize.height)))) {
vsb.setVisible(false);
}
if (_vTop == null && _vBottom == null)
vsb.setBounds(adjustBounds(parent, vsbR, ltr));
else {
Rectangle rect = new Rectangle(vsbR);
if (_vTop != null) {
Dimension dim = _vTop.getPreferredSize();
rect.y += dim.height;
rect.height -= dim.height;
_vTop.setVisible(true);
_vTop.setBounds(adjustBounds(parent, new Rectangle(vsbR.x, vsbR.y, vsbR.width, dim.height), ltr));
}
if (_vBottom != null) {
Dimension dim = _vBottom.getPreferredSize();
rect.height -= dim.height;
_vBottom.setVisible(true);
_vBottom.setBounds(adjustBounds(parent, new Rectangle(vsbR.x, vsbR.y + vsbR.height - dim.height, vsbR.width, dim.height), ltr));
}
vsb.setBounds(adjustBounds(parent, rect, ltr));
}
}
else {
if (viewPrefSize.height > extentSize.height) {
vsb.setVisible(true);
vsb.setBounds(adjustBounds(parent, new Rectangle(vsbR.x, vsbR.y, 0, vsbR.height), ltr));
}
else {
vsb.setVisible(false);
}
if (_vTop != null)
_vTop.setVisible(false);
if (_vBottom != null)
_vBottom.setVisible(false);
}
}
if (hsb != null) {
if (hsbNeeded) {
hsb.setVisible(true);
if (hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED && !isEmpty && !(!viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || (colHead != null && colHead.getView() != null && colHead.getView().getPreferredSize().width > extentSize.width)))) {
hsb.setVisible(false);
}
if (_hLeft == null && _hRight == null)
hsb.setBounds(adjustBounds(parent, hsbR, ltr));
else {
Rectangle rect = new Rectangle(hsbR);
if (_hLeft != null) {
Dimension dim = _hLeft.getPreferredSize();
rect.x += dim.width;
rect.width -= dim.width;
_hLeft.setVisible(true);
_hLeft.setBounds(adjustBounds(parent, new Rectangle(hsbR.x, hsbR.y, dim.width, hsbR.height), ltr));
_hLeft.doLayout();
}
if (_hRight != null) {
Dimension dim = _hRight.getPreferredSize();
rect.width -= dim.width;
_hRight.setVisible(true);
_hRight.setBounds(adjustBounds(parent, new Rectangle(hsbR.x + hsbR.width - dim.width, hsbR.y, dim.width, hsbR.height), ltr));
}
hsb.setBounds(adjustBounds(parent, rect, ltr));
}
}
else {
if (viewPrefSize.width > extentSize.width) {
hsb.setVisible(true);
hsb.setBounds(adjustBounds(parent, new Rectangle(hsbR.x, hsbR.y, hsbR.width, 0), ltr));
}
else {
hsb.setVisible(false);
}
if (_hLeft != null)
_hLeft.setVisible(false);
if (_hRight != null)
_hRight.setVisible(false);
}
}
if (lowerLeft != null && lowerLeft.isVisible()) {
int height = isColumnFootersHeightUnified(scrollPane) ? columnFooterHeight : Math.min(lowerLeft.getPreferredSize().height, colFootR.height);
lowerLeft.setBounds(adjustBounds(parent, new Rectangle(rowHeadR.x, colFootR.y != 0 ? colFootR.y : hsbR.y, rowHeadR.width, height), ltr));
}
if (lowerRight != null && lowerRight.isVisible()) {
int height = isColumnFootersHeightUnified(scrollPane) ? columnFooterHeight : Math.min(lowerRight.getPreferredSize().height, colFootR.height);
- lowerRight.setBounds(adjustBounds(parent, new Rectangle(rowFootR.x, colFootR.y != 0 ? colFootR.y : hsbR.y, rowFootR.width + (isVsbCoversWholeHeight(scrollPane) ? 0 : vsbR.width), height), ltr));
+ lowerRight.setBounds(adjustBounds(parent, new Rectangle(rowFootR.x, colFootR.y != 0 ? colFootR.y : hsbR.y, rowFootR.width, height), ltr));
}
if (upperLeft != null && upperLeft.isVisible()) {
int height = isColumnHeadersHeightUnified(scrollPane) ? columnHeaderHeight : Math.min(upperLeft.getPreferredSize().height, colHeadR.height);
upperLeft.setBounds(adjustBounds(parent, new Rectangle(rowHeadR.x, colHeadR.y + colHeadR.height - height, rowHeadR.width, height), ltr));
}
if (upperRight != null && upperRight.isVisible()) {
int height = isColumnHeadersHeightUnified(scrollPane) ? columnHeaderHeight : Math.min(upperRight.getPreferredSize().height, colHeadR.height);
- upperRight.setBounds(adjustBounds(parent, new Rectangle(rowFootR.x, colHeadR.y + colHeadR.height - height, rowFootR.width + (isVsbCoversWholeHeight(scrollPane) ? 0 : vsbR.width), height), ltr));
+ upperRight.setBounds(adjustBounds(parent, new Rectangle(rowFootR.x, colHeadR.y + colHeadR.height - height, rowFootR.width, height), ltr));
}
}
private Rectangle adjustBounds(Container container, Rectangle rect, boolean ltr) {
if (ltr) {
return rect;
}
else {
Rectangle r = new Rectangle(rect);
int w = container.getWidth();
r.x = w - (rect.x + rect.width);
return r;
}
}
//
// Adjusts the <code>Rectangle</code> <code>available</code> based on if the vertical scrollbar is needed
// (<code>wantsVSB</code>). The location of the vsb is updated in <code>vsbR</code>, and the viewport border insets
// (<code>vpbInsets</code>) are used to offset the vsb. This is only called when <code>wantsVSB</code> has changed,
// eg you shouldn't invoke adjustForVSB(true) twice.
//
private void adjustForVSB(boolean wantsVSB, Rectangle available,
Rectangle vsbR, Insets vpbInsets,
boolean leftToRight) {
int oldWidth = vsbR.width;
if (wantsVSB) {
int vsbWidth = Math.max(0, vsb.getPreferredSize().width);
available.width -= vsbWidth;
vsbR.width = vsbWidth;
if (leftToRight) {
vsbR.x = available.x + available.width + vpbInsets.right;
}
else {
vsbR.x = available.x - vpbInsets.left;
available.x += vsbWidth;
}
}
else {
available.width += oldWidth;
}
}
//
// Adjusts the <code>Rectangle</code> <code>available</code> based on if the horizontal scrollbar is needed
// (<code>wantsHSB</code>). The location of the hsb is updated in <code>hsbR</code>, and the viewport border insets
// (<code>vpbInsets</code>) are used to offset the hsb. This is only called when <code>wantsHSB</code> has changed,
// eg you shouldn't invoked adjustForHSB(true) twice.
//
private void adjustForHSB(boolean wantsHSB, Rectangle available,
Rectangle hsbR, Insets vpbInsets) {
int oldHeight = hsbR.height;
if (wantsHSB) {
int hsbHeight = Math.max(0, hsb.getPreferredSize().height);
available.height -= hsbHeight;
hsbR.y = available.y + available.height + vpbInsets.bottom;
hsbR.height = hsbHeight;
}
else {
available.height += oldHeight;
}
}
/**
* The UI resource version of <code>ScrollPaneLayout</code>.
*/
static class UIResource extends JideScrollPaneLayout implements javax.swing.plaf.UIResource {
private static final long serialVersionUID = 1057343395078846689L;
}
}
| false | true | public void layoutContainer(Container parent) {
/* Sync the (now obsolete) policy fields with the
* JScrollPane.
*/
JScrollPane scrollPane = (JScrollPane) parent;
vsbPolicy = scrollPane.getVerticalScrollBarPolicy();
hsbPolicy = scrollPane.getHorizontalScrollBarPolicy();
Rectangle availR = scrollPane.getBounds();
availR.x = availR.y = 0;
Insets insets = parent.getInsets();
availR.x = insets.left;
availR.y = insets.top;
availR.width -= insets.left + insets.right;
availR.height -= insets.top + insets.bottom;
/* If there's a visible column header remove the space it
* needs from the top of availR. The column header is treated
* as if it were fixed height, arbitrary width.
*/
Rectangle colHeadR = new Rectangle(0, availR.y, 0, 0);
int upperHeight = getUpperHeight();
if ((colHead != null) && (colHead.isVisible())) {
int colHeadHeight = Math.min(availR.height, upperHeight);
colHeadR.height = colHeadHeight;
availR.y += colHeadHeight;
availR.height -= colHeadHeight;
}
Rectangle subColHeadR = new Rectangle(0, availR.y, 0, 0);
if (_subColHead != null && _subColHead.isVisible()) {
int subColHeadHeight = Math.min(availR.height, _subColHead.getPreferredSize().height);
subColHeadR.height = subColHeadHeight;
availR.y += subColHeadHeight;
availR.height -= subColHeadHeight;
}
/* If there's a visible row header remove the space it needs
* from the left or right of availR. The row header is treated
* as if it were fixed width, arbitrary height.
*/
Rectangle rowHeadR = new Rectangle(0, 0, 0, 0);
if ((rowHead != null) && (rowHead.isVisible())) {
int rowHeadWidth = rowHead.getPreferredSize().width;
if (upperLeft != null && upperLeft.isVisible()) {
rowHeadWidth = Math.max(rowHeadWidth, upperLeft.getPreferredSize().width);
}
if (lowerLeft != null && lowerLeft.isVisible()) {
rowHeadWidth = Math.max(rowHeadWidth, lowerLeft.getPreferredSize().width);
}
rowHeadR.width = rowHeadWidth;
availR.width -= rowHeadWidth;
rowHeadR.x = availR.x;
availR.x += rowHeadWidth;
}
/* If there's a JScrollPane.viewportBorder, remove the
* space it occupies for availR.
*/
Border viewportBorder = scrollPane.getViewportBorder();
Insets vpbInsets;
if (viewportBorder != null) {
vpbInsets = viewportBorder.getBorderInsets(parent);
availR.x += vpbInsets.left;
availR.y += vpbInsets.top;
availR.width -= vpbInsets.left + vpbInsets.right;
availR.height -= vpbInsets.top + vpbInsets.bottom;
}
else {
vpbInsets = new Insets(0, 0, 0, 0);
}
/* If there's a visible row footer remove the space it needs
* from the left or right of availR. The row footer is treated
* as if it were fixed width, arbitrary height.
*/
Rectangle rowFootR = new Rectangle(0, 0, 0, 0);
if ((_rowFoot != null) && (_rowFoot.isVisible())) {
int rowFootWidth = _rowFoot.getPreferredSize().width;
if (upperRight != null && upperRight.isVisible()) {
rowFootWidth = Math.max(rowFootWidth, upperRight.getPreferredSize().width);
}
if (lowerRight != null && lowerRight.isVisible()) {
rowFootWidth = Math.max(rowFootWidth, lowerRight.getPreferredSize().width);
}
rowFootR.width = rowFootWidth;
availR.width -= rowFootWidth;
rowFootR.x = availR.x + availR.width;
}
/* If there's a visible column footer remove the space it
* needs from the top of availR. The column footer is treated
* as if it were fixed height, arbitrary width.
*/
Rectangle colFootR = new Rectangle(0, availR.y, 0, 0);
int lowerHeight = getLowerHeight();
if ((_colFoot != null) && (_colFoot.isVisible())) {
int colFootHeight = Math.min(availR.height, lowerHeight);
colFootR.height = colFootHeight;
availR.height -= colFootHeight;
colFootR.y = availR.y + availR.height;
}
/* At this point availR is the space available for the viewport
* and scrollbars. rowHeadR is correct except for its height and y
* and colHeadR is correct except for its width and x. Once we're
* through computing the dimensions of these three parts we can
* go back and set the dimensions of rowHeadR.height, rowHeadR.y,
* colHeadR.width, colHeadR.x and the bounds for the corners.
*
* We'll decide about putting up scrollbars by comparing the
* viewport views preferred size with the viewports extent
* size (generally just its size). Using the preferredSize is
* reasonable because layout proceeds top down - so we expect
* the viewport to be laid out next. And we assume that the
* viewports layout manager will give the view it's preferred
* size. One exception to this is when the view implements
* Scrollable and Scrollable.getViewTracksViewport{Width,Height}
* methods return true. If the view is tracking the viewports
* width we don't bother with a horizontal scrollbar, similarly
* if view.getViewTracksViewport(Height) is true we don't bother
* with a vertical scrollbar.
*/
Component view = (viewport != null) ? viewport.getView() : null;
Dimension viewPrefSize = (view != null) ? view.getPreferredSize() : new Dimension(0, 0);
Dimension extentSize =
(viewport != null) ? viewport.toViewCoordinates(availR.getSize())
: new Dimension(0, 0);
boolean viewTracksViewportWidth = false;
boolean viewTracksViewportHeight = false;
boolean isEmpty = (availR.width < 0 || availR.height < 0);
Scrollable sv;
// Don't bother checking the Scrollable methods if there is no room
// for the viewport, we aren't going to show any scrollbars in this
// case anyway.
if (!isEmpty && view instanceof Scrollable) {
sv = (Scrollable) view;
viewTracksViewportWidth = sv.getScrollableTracksViewportWidth();
viewTracksViewportHeight = sv.getScrollableTracksViewportHeight();
}
else {
sv = null;
}
/* If there's a vertical scrollbar and we need one, allocate
* space for it (we'll make it visible later). A vertical
* scrollbar is considered to be fixed width, arbitrary height.
*/
Rectangle vsbR = new Rectangle(0, isVsbCoversWholeHeight(scrollPane) ? insets.top : availR.y - vpbInsets.top, 0, 0);
boolean vsbNeeded;
if (vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS) {
vsbNeeded = true;
}
else if (vsbPolicy == VERTICAL_SCROLLBAR_NEVER) {
vsbNeeded = false;
}
else if (isEmpty) {
vsbNeeded = false;
}
else { // vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED
vsbNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || (rowHead != null && rowHead.getView() != null && rowHead.getView().getPreferredSize().height > extentSize.height));
if (!vsbNeeded && scrollPane instanceof JideScrollPane && ((JideScrollPane) scrollPane).isKeepCornerVisible() && (_vBottom != null || _vTop != null)) {
vsbNeeded = true;
}
}
if ((vsb != null) && vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets, true);
extentSize = viewport.toViewCoordinates(availR.getSize());
}
/* If there's a horizontal scrollbar and we need one, allocate
* space for it (we'll make it visible later). A horizontal
* scrollbar is considered to be fixed height, arbitrary width.
*/
Rectangle hsbR = new Rectangle(isHsbCoversWholeWidth(scrollPane) ? insets.left : availR.x - vpbInsets.left, 0, 0, 0);
boolean hsbNeeded;
if (hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) {
hsbNeeded = true;
}
else if (hsbPolicy == HORIZONTAL_SCROLLBAR_NEVER) {
hsbNeeded = false;
}
else if (isEmpty) {
hsbNeeded = false;
}
else { // hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED
hsbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || (colHead != null && colHead.getView() != null && colHead.getView().getPreferredSize().width > extentSize.width));
if (!hsbNeeded && scrollPane instanceof JideScrollPane && ((JideScrollPane) scrollPane).isKeepCornerVisible() && (_hLeft != null || _hRight != null)) {
hsbNeeded = true;
}
}
if ((hsb != null) && hsbNeeded) {
adjustForHSB(true, availR, hsbR, vpbInsets);
/* If we added the horizontal scrollbar then we've implicitly
* reduced the vertical space available to the viewport.
* As a consequence we may have to add the vertical scrollbar,
* if that hasn't been done so already. Of course we
* don't bother with any of this if the vsbPolicy is NEVER.
*/
if ((vsb != null) && !vsbNeeded &&
(vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
extentSize = viewport.toViewCoordinates(availR.getSize());
vsbNeeded = viewPrefSize.height > extentSize.height;
if (!vsbNeeded && scrollPane instanceof JideScrollPane && ((JideScrollPane) scrollPane).isKeepCornerVisible() && (_vBottom != null || _vTop != null)) {
vsbNeeded = true;
}
if (vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets, true);
}
}
}
/* Set the size of the viewport first, and then recheck the Scrollable
* methods. Some components base their return values for the Scrollable
* methods on the size of the Viewport, so that if we don't
* ask after resetting the bounds we may have gotten the wrong
* answer.
*/
// Get the scrollPane's orientation.
boolean ltr = scrollPane.getComponentOrientation().isLeftToRight();
if (viewport != null) {
viewport.setBounds(adjustBounds(parent, availR, ltr));
// viewport.setViewSize(availR.getSize()); // to fix the strange scroll bar problem reported on http://www.jidesoft.com/forum/viewtopic.php?p=20526#20526
if (sv != null) {
extentSize = viewport.toViewCoordinates(availR.getSize());
boolean oldHSBNeeded = hsbNeeded;
boolean oldVSBNeeded = vsbNeeded;
viewTracksViewportWidth = sv.getScrollableTracksViewportWidth();
viewTracksViewportHeight = sv.getScrollableTracksViewportHeight();
if (vsb != null && vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED) {
boolean newVSBNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || (rowHead != null && rowHead.getView() != null && rowHead.getView().getPreferredSize().height > extentSize.height));
if (!newVSBNeeded && scrollPane instanceof JideScrollPane && ((JideScrollPane) scrollPane).isKeepCornerVisible() && (_vBottom != null || _vTop != null)) {
newVSBNeeded = true;
}
if (newVSBNeeded != vsbNeeded) {
vsbNeeded = newVSBNeeded;
adjustForVSB(vsbNeeded, availR, vsbR, vpbInsets, true);
extentSize = viewport.toViewCoordinates
(availR.getSize());
}
}
if (hsb != null && hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED) {
boolean newHSBbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || (colHead != null && colHead.getView() != null && colHead.getView().getPreferredSize().width > extentSize.width));
if (!newHSBbNeeded && scrollPane instanceof JideScrollPane && ((JideScrollPane) scrollPane).isKeepCornerVisible() && (_hLeft != null || _hRight != null)) {
newHSBbNeeded = true;
}
if (newHSBbNeeded != hsbNeeded) {
hsbNeeded = newHSBbNeeded;
adjustForHSB(hsbNeeded, availR, hsbR, vpbInsets);
if ((vsb != null) && !vsbNeeded &&
(vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
extentSize = viewport.toViewCoordinates
(availR.getSize());
vsbNeeded = viewPrefSize.height >
extentSize.height;
if (!vsbNeeded && scrollPane instanceof JideScrollPane && ((JideScrollPane) scrollPane).isKeepCornerVisible() && (_vBottom != null || _vTop != null)) {
vsbNeeded = true;
}
if (vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets, true);
}
}
if (_rowFoot != null && _rowFoot.isVisible()) {
vsbR.x += rowFootR.width;
}
}
}
if (oldHSBNeeded != hsbNeeded ||
oldVSBNeeded != vsbNeeded) {
viewport.setBounds(adjustBounds(parent, availR, ltr));
// You could argue that we should recheck the
// Scrollable methods again until they stop changing,
// but they might never stop changing, so we stop here
// and don't do any additional checks.
}
}
}
/*
* We now have the final size of the viewport: availR.
* Now fixup the header and scrollbar widths/heights.
*/
vsbR.height = isVsbCoversWholeHeight(scrollPane) ? scrollPane.getHeight() - insets.bottom - insets.top : availR.height + vpbInsets.top + vpbInsets.bottom;
hsbR.width = isHsbCoversWholeWidth(scrollPane) ? scrollPane.getWidth() - vsbR.width - insets.left - insets.right : availR.width + vpbInsets.left + vpbInsets.right;
rowHeadR.height = availR.height + vpbInsets.top + vpbInsets.bottom;
rowHeadR.y = availR.y - vpbInsets.top;
colHeadR.width = availR.width + vpbInsets.left + vpbInsets.right;
colHeadR.x = availR.x - vpbInsets.left;
subColHeadR.width = colHeadR.width;
subColHeadR.x = colHeadR.x;
colFootR.x = availR.x;
colFootR.y = rowHeadR.y + rowHeadR.height;
colFootR.width = availR.width;
rowFootR.x = availR.x + availR.width;
rowFootR.y = availR.y;
rowFootR.height = availR.height;
vsbR.x += rowFootR.width;
hsbR.y += colFootR.height;
/* Set the bounds of the remaining components. The scrollbars
* are made invisible if they're not needed.
*/
if (rowHead != null) {
rowHead.setBounds(adjustBounds(parent, rowHeadR, ltr));
}
if (_rowFoot != null) {
_rowFoot.setBounds(adjustBounds(parent, rowFootR, ltr));
}
int columnHeaderHeight = isColumnHeadersHeightUnified(scrollPane) ? Math.max(colHeadR.height,
Math.max(upperLeft == null ? 0 : upperLeft.getPreferredSize().height, upperRight == null ? 0 : upperRight.getPreferredSize().height)) : 0;
int columnFooterHeight = isColumnFootersHeightUnified(scrollPane) ? Math.max(colFootR.height,
Math.max(lowerLeft == null ? 0 : lowerLeft.getPreferredSize().height, lowerRight == null ? 0 : lowerRight.getPreferredSize().height)) : 0;
if (colHead != null) {
int height = isColumnHeadersHeightUnified(scrollPane) ? columnHeaderHeight : Math.min(colHeadR.height, colHead.getPreferredSize().height);
colHead.setBounds(adjustBounds(parent, new Rectangle(colHeadR.x, colHeadR.y + colHeadR.height - height, colHeadR.width, height), ltr));
}
if (_subColHead != null) {
_subColHead.setBounds(adjustBounds(parent, subColHeadR, ltr));
}
if (_colFoot != null) {
int height = isColumnFootersHeightUnified(scrollPane) ? columnFooterHeight : Math.min(colFootR.height, _colFoot.getPreferredSize().height);
_colFoot.setBounds(adjustBounds(parent, new Rectangle(colFootR.x, colFootR.y, colFootR.width, height), ltr));
}
else {
if (isColumnFootersHeightUnified(scrollPane)) {
columnFooterHeight = hsbR.height;
}
}
if (vsb != null) {
if (vsbNeeded) {
vsb.setVisible(true);
if (vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED && !isEmpty && !(!viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || (rowHead != null && rowHead.getView() != null && rowHead.getView().getPreferredSize().height > extentSize.height)))) {
vsb.setVisible(false);
}
if (_vTop == null && _vBottom == null)
vsb.setBounds(adjustBounds(parent, vsbR, ltr));
else {
Rectangle rect = new Rectangle(vsbR);
if (_vTop != null) {
Dimension dim = _vTop.getPreferredSize();
rect.y += dim.height;
rect.height -= dim.height;
_vTop.setVisible(true);
_vTop.setBounds(adjustBounds(parent, new Rectangle(vsbR.x, vsbR.y, vsbR.width, dim.height), ltr));
}
if (_vBottom != null) {
Dimension dim = _vBottom.getPreferredSize();
rect.height -= dim.height;
_vBottom.setVisible(true);
_vBottom.setBounds(adjustBounds(parent, new Rectangle(vsbR.x, vsbR.y + vsbR.height - dim.height, vsbR.width, dim.height), ltr));
}
vsb.setBounds(adjustBounds(parent, rect, ltr));
}
}
else {
if (viewPrefSize.height > extentSize.height) {
vsb.setVisible(true);
vsb.setBounds(adjustBounds(parent, new Rectangle(vsbR.x, vsbR.y, 0, vsbR.height), ltr));
}
else {
vsb.setVisible(false);
}
if (_vTop != null)
_vTop.setVisible(false);
if (_vBottom != null)
_vBottom.setVisible(false);
}
}
if (hsb != null) {
if (hsbNeeded) {
hsb.setVisible(true);
if (hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED && !isEmpty && !(!viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || (colHead != null && colHead.getView() != null && colHead.getView().getPreferredSize().width > extentSize.width)))) {
hsb.setVisible(false);
}
if (_hLeft == null && _hRight == null)
hsb.setBounds(adjustBounds(parent, hsbR, ltr));
else {
Rectangle rect = new Rectangle(hsbR);
if (_hLeft != null) {
Dimension dim = _hLeft.getPreferredSize();
rect.x += dim.width;
rect.width -= dim.width;
_hLeft.setVisible(true);
_hLeft.setBounds(adjustBounds(parent, new Rectangle(hsbR.x, hsbR.y, dim.width, hsbR.height), ltr));
_hLeft.doLayout();
}
if (_hRight != null) {
Dimension dim = _hRight.getPreferredSize();
rect.width -= dim.width;
_hRight.setVisible(true);
_hRight.setBounds(adjustBounds(parent, new Rectangle(hsbR.x + hsbR.width - dim.width, hsbR.y, dim.width, hsbR.height), ltr));
}
hsb.setBounds(adjustBounds(parent, rect, ltr));
}
}
else {
if (viewPrefSize.width > extentSize.width) {
hsb.setVisible(true);
hsb.setBounds(adjustBounds(parent, new Rectangle(hsbR.x, hsbR.y, hsbR.width, 0), ltr));
}
else {
hsb.setVisible(false);
}
if (_hLeft != null)
_hLeft.setVisible(false);
if (_hRight != null)
_hRight.setVisible(false);
}
}
if (lowerLeft != null && lowerLeft.isVisible()) {
int height = isColumnFootersHeightUnified(scrollPane) ? columnFooterHeight : Math.min(lowerLeft.getPreferredSize().height, colFootR.height);
lowerLeft.setBounds(adjustBounds(parent, new Rectangle(rowHeadR.x, colFootR.y != 0 ? colFootR.y : hsbR.y, rowHeadR.width, height), ltr));
}
if (lowerRight != null && lowerRight.isVisible()) {
int height = isColumnFootersHeightUnified(scrollPane) ? columnFooterHeight : Math.min(lowerRight.getPreferredSize().height, colFootR.height);
lowerRight.setBounds(adjustBounds(parent, new Rectangle(rowFootR.x, colFootR.y != 0 ? colFootR.y : hsbR.y, rowFootR.width + (isVsbCoversWholeHeight(scrollPane) ? 0 : vsbR.width), height), ltr));
}
if (upperLeft != null && upperLeft.isVisible()) {
int height = isColumnHeadersHeightUnified(scrollPane) ? columnHeaderHeight : Math.min(upperLeft.getPreferredSize().height, colHeadR.height);
upperLeft.setBounds(adjustBounds(parent, new Rectangle(rowHeadR.x, colHeadR.y + colHeadR.height - height, rowHeadR.width, height), ltr));
}
if (upperRight != null && upperRight.isVisible()) {
int height = isColumnHeadersHeightUnified(scrollPane) ? columnHeaderHeight : Math.min(upperRight.getPreferredSize().height, colHeadR.height);
upperRight.setBounds(adjustBounds(parent, new Rectangle(rowFootR.x, colHeadR.y + colHeadR.height - height, rowFootR.width + (isVsbCoversWholeHeight(scrollPane) ? 0 : vsbR.width), height), ltr));
}
}
| public void layoutContainer(Container parent) {
/* Sync the (now obsolete) policy fields with the
* JScrollPane.
*/
JScrollPane scrollPane = (JScrollPane) parent;
vsbPolicy = scrollPane.getVerticalScrollBarPolicy();
hsbPolicy = scrollPane.getHorizontalScrollBarPolicy();
Rectangle availR = scrollPane.getBounds();
availR.x = availR.y = 0;
Insets insets = parent.getInsets();
availR.x = insets.left;
availR.y = insets.top;
availR.width -= insets.left + insets.right;
availR.height -= insets.top + insets.bottom;
/* If there's a visible column header remove the space it
* needs from the top of availR. The column header is treated
* as if it were fixed height, arbitrary width.
*/
Rectangle colHeadR = new Rectangle(0, availR.y, 0, 0);
int upperHeight = getUpperHeight();
if ((colHead != null) && (colHead.isVisible())) {
int colHeadHeight = Math.min(availR.height, upperHeight);
colHeadR.height = colHeadHeight;
availR.y += colHeadHeight;
availR.height -= colHeadHeight;
}
Rectangle subColHeadR = new Rectangle(0, availR.y, 0, 0);
if (_subColHead != null && _subColHead.isVisible()) {
int subColHeadHeight = Math.min(availR.height, _subColHead.getPreferredSize().height);
subColHeadR.height = subColHeadHeight;
availR.y += subColHeadHeight;
availR.height -= subColHeadHeight;
}
/* If there's a visible row header remove the space it needs
* from the left or right of availR. The row header is treated
* as if it were fixed width, arbitrary height.
*/
Rectangle rowHeadR = new Rectangle(0, 0, 0, 0);
if ((rowHead != null) && (rowHead.isVisible())) {
int rowHeadWidth = rowHead.getPreferredSize().width;
if (upperLeft != null && upperLeft.isVisible()) {
rowHeadWidth = Math.max(rowHeadWidth, upperLeft.getPreferredSize().width);
}
if (lowerLeft != null && lowerLeft.isVisible()) {
rowHeadWidth = Math.max(rowHeadWidth, lowerLeft.getPreferredSize().width);
}
rowHeadR.width = rowHeadWidth;
availR.width -= rowHeadWidth;
rowHeadR.x = availR.x;
availR.x += rowHeadWidth;
}
/* If there's a JScrollPane.viewportBorder, remove the
* space it occupies for availR.
*/
Border viewportBorder = scrollPane.getViewportBorder();
Insets vpbInsets;
if (viewportBorder != null) {
vpbInsets = viewportBorder.getBorderInsets(parent);
availR.x += vpbInsets.left;
availR.y += vpbInsets.top;
availR.width -= vpbInsets.left + vpbInsets.right;
availR.height -= vpbInsets.top + vpbInsets.bottom;
}
else {
vpbInsets = new Insets(0, 0, 0, 0);
}
/* If there's a visible row footer remove the space it needs
* from the left or right of availR. The row footer is treated
* as if it were fixed width, arbitrary height.
*/
Rectangle rowFootR = new Rectangle(0, 0, 0, 0);
if ((_rowFoot != null) && (_rowFoot.isVisible())) {
int rowFootWidth = _rowFoot.getPreferredSize().width;
if (upperRight != null && upperRight.isVisible()) {
rowFootWidth = Math.max(rowFootWidth, upperRight.getPreferredSize().width);
}
if (lowerRight != null && lowerRight.isVisible()) {
rowFootWidth = Math.max(rowFootWidth, lowerRight.getPreferredSize().width);
}
rowFootR.width = rowFootWidth;
availR.width -= rowFootWidth;
rowFootR.x = availR.x + availR.width;
}
/* If there's a visible column footer remove the space it
* needs from the top of availR. The column footer is treated
* as if it were fixed height, arbitrary width.
*/
Rectangle colFootR = new Rectangle(0, availR.y, 0, 0);
int lowerHeight = getLowerHeight();
if ((_colFoot != null) && (_colFoot.isVisible())) {
int colFootHeight = Math.min(availR.height, lowerHeight);
colFootR.height = colFootHeight;
availR.height -= colFootHeight;
colFootR.y = availR.y + availR.height;
}
/* At this point availR is the space available for the viewport
* and scrollbars. rowHeadR is correct except for its height and y
* and colHeadR is correct except for its width and x. Once we're
* through computing the dimensions of these three parts we can
* go back and set the dimensions of rowHeadR.height, rowHeadR.y,
* colHeadR.width, colHeadR.x and the bounds for the corners.
*
* We'll decide about putting up scrollbars by comparing the
* viewport views preferred size with the viewports extent
* size (generally just its size). Using the preferredSize is
* reasonable because layout proceeds top down - so we expect
* the viewport to be laid out next. And we assume that the
* viewports layout manager will give the view it's preferred
* size. One exception to this is when the view implements
* Scrollable and Scrollable.getViewTracksViewport{Width,Height}
* methods return true. If the view is tracking the viewports
* width we don't bother with a horizontal scrollbar, similarly
* if view.getViewTracksViewport(Height) is true we don't bother
* with a vertical scrollbar.
*/
Component view = (viewport != null) ? viewport.getView() : null;
Dimension viewPrefSize = (view != null) ? view.getPreferredSize() : new Dimension(0, 0);
Dimension extentSize =
(viewport != null) ? viewport.toViewCoordinates(availR.getSize())
: new Dimension(0, 0);
boolean viewTracksViewportWidth = false;
boolean viewTracksViewportHeight = false;
boolean isEmpty = (availR.width < 0 || availR.height < 0);
Scrollable sv;
// Don't bother checking the Scrollable methods if there is no room
// for the viewport, we aren't going to show any scrollbars in this
// case anyway.
if (!isEmpty && view instanceof Scrollable) {
sv = (Scrollable) view;
viewTracksViewportWidth = sv.getScrollableTracksViewportWidth();
viewTracksViewportHeight = sv.getScrollableTracksViewportHeight();
}
else {
sv = null;
}
/* If there's a vertical scrollbar and we need one, allocate
* space for it (we'll make it visible later). A vertical
* scrollbar is considered to be fixed width, arbitrary height.
*/
Rectangle vsbR = new Rectangle(0, isVsbCoversWholeHeight(scrollPane) ? insets.top : availR.y - vpbInsets.top, 0, 0);
boolean vsbNeeded;
if (vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS) {
vsbNeeded = true;
}
else if (vsbPolicy == VERTICAL_SCROLLBAR_NEVER) {
vsbNeeded = false;
}
else if (isEmpty) {
vsbNeeded = false;
}
else { // vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED
vsbNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || (rowHead != null && rowHead.getView() != null && rowHead.getView().getPreferredSize().height > extentSize.height));
if (!vsbNeeded && scrollPane instanceof JideScrollPane && ((JideScrollPane) scrollPane).isKeepCornerVisible() && (_vBottom != null || _vTop != null)) {
vsbNeeded = true;
}
}
if ((vsb != null) && vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets, true);
extentSize = viewport.toViewCoordinates(availR.getSize());
}
/* If there's a horizontal scrollbar and we need one, allocate
* space for it (we'll make it visible later). A horizontal
* scrollbar is considered to be fixed height, arbitrary width.
*/
Rectangle hsbR = new Rectangle(isHsbCoversWholeWidth(scrollPane) ? insets.left : availR.x - vpbInsets.left, 0, 0, 0);
boolean hsbNeeded;
if (hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) {
hsbNeeded = true;
}
else if (hsbPolicy == HORIZONTAL_SCROLLBAR_NEVER) {
hsbNeeded = false;
}
else if (isEmpty) {
hsbNeeded = false;
}
else { // hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED
hsbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || (colHead != null && colHead.getView() != null && colHead.getView().getPreferredSize().width > extentSize.width));
if (!hsbNeeded && scrollPane instanceof JideScrollPane && ((JideScrollPane) scrollPane).isKeepCornerVisible() && (_hLeft != null || _hRight != null)) {
hsbNeeded = true;
}
}
if ((hsb != null) && hsbNeeded) {
adjustForHSB(true, availR, hsbR, vpbInsets);
/* If we added the horizontal scrollbar then we've implicitly
* reduced the vertical space available to the viewport.
* As a consequence we may have to add the vertical scrollbar,
* if that hasn't been done so already. Of course we
* don't bother with any of this if the vsbPolicy is NEVER.
*/
if ((vsb != null) && !vsbNeeded &&
(vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
extentSize = viewport.toViewCoordinates(availR.getSize());
vsbNeeded = viewPrefSize.height > extentSize.height;
if (!vsbNeeded && scrollPane instanceof JideScrollPane && ((JideScrollPane) scrollPane).isKeepCornerVisible() && (_vBottom != null || _vTop != null)) {
vsbNeeded = true;
}
if (vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets, true);
}
}
}
/* Set the size of the viewport first, and then recheck the Scrollable
* methods. Some components base their return values for the Scrollable
* methods on the size of the Viewport, so that if we don't
* ask after resetting the bounds we may have gotten the wrong
* answer.
*/
// Get the scrollPane's orientation.
boolean ltr = scrollPane.getComponentOrientation().isLeftToRight();
if (viewport != null) {
viewport.setBounds(adjustBounds(parent, availR, ltr));
// viewport.setViewSize(availR.getSize()); // to fix the strange scroll bar problem reported on http://www.jidesoft.com/forum/viewtopic.php?p=20526#20526
if (sv != null) {
extentSize = viewport.toViewCoordinates(availR.getSize());
boolean oldHSBNeeded = hsbNeeded;
boolean oldVSBNeeded = vsbNeeded;
viewTracksViewportWidth = sv.getScrollableTracksViewportWidth();
viewTracksViewportHeight = sv.getScrollableTracksViewportHeight();
if (vsb != null && vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED) {
boolean newVSBNeeded = !viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || (rowHead != null && rowHead.getView() != null && rowHead.getView().getPreferredSize().height > extentSize.height));
if (!newVSBNeeded && scrollPane instanceof JideScrollPane && ((JideScrollPane) scrollPane).isKeepCornerVisible() && (_vBottom != null || _vTop != null)) {
newVSBNeeded = true;
}
if (newVSBNeeded != vsbNeeded) {
vsbNeeded = newVSBNeeded;
adjustForVSB(vsbNeeded, availR, vsbR, vpbInsets, true);
extentSize = viewport.toViewCoordinates
(availR.getSize());
}
}
if (hsb != null && hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED) {
boolean newHSBbNeeded = !viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || (colHead != null && colHead.getView() != null && colHead.getView().getPreferredSize().width > extentSize.width));
if (!newHSBbNeeded && scrollPane instanceof JideScrollPane && ((JideScrollPane) scrollPane).isKeepCornerVisible() && (_hLeft != null || _hRight != null)) {
newHSBbNeeded = true;
}
if (newHSBbNeeded != hsbNeeded) {
hsbNeeded = newHSBbNeeded;
adjustForHSB(hsbNeeded, availR, hsbR, vpbInsets);
if ((vsb != null) && !vsbNeeded &&
(vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
extentSize = viewport.toViewCoordinates
(availR.getSize());
vsbNeeded = viewPrefSize.height >
extentSize.height;
if (!vsbNeeded && scrollPane instanceof JideScrollPane && ((JideScrollPane) scrollPane).isKeepCornerVisible() && (_vBottom != null || _vTop != null)) {
vsbNeeded = true;
}
if (vsbNeeded) {
adjustForVSB(true, availR, vsbR, vpbInsets, true);
}
}
if (_rowFoot != null && _rowFoot.isVisible()) {
vsbR.x += rowFootR.width;
}
}
}
if (oldHSBNeeded != hsbNeeded ||
oldVSBNeeded != vsbNeeded) {
viewport.setBounds(adjustBounds(parent, availR, ltr));
// You could argue that we should recheck the
// Scrollable methods again until they stop changing,
// but they might never stop changing, so we stop here
// and don't do any additional checks.
}
}
}
/*
* We now have the final size of the viewport: availR.
* Now fixup the header and scrollbar widths/heights.
*/
vsbR.height = isVsbCoversWholeHeight(scrollPane) ? scrollPane.getHeight() - insets.bottom - insets.top : availR.height + vpbInsets.top + vpbInsets.bottom;
hsbR.width = isHsbCoversWholeWidth(scrollPane) ? scrollPane.getWidth() - vsbR.width - insets.left - insets.right : availR.width + vpbInsets.left + vpbInsets.right;
rowHeadR.height = availR.height + vpbInsets.top + vpbInsets.bottom;
rowHeadR.y = availR.y - vpbInsets.top;
colHeadR.width = availR.width + vpbInsets.left + vpbInsets.right;
colHeadR.x = availR.x - vpbInsets.left;
subColHeadR.width = colHeadR.width;
subColHeadR.x = colHeadR.x;
colFootR.x = availR.x;
colFootR.y = rowHeadR.y + rowHeadR.height;
colFootR.width = availR.width;
rowFootR.x = availR.x + availR.width;
rowFootR.y = availR.y;
rowFootR.height = availR.height;
vsbR.x += rowFootR.width;
hsbR.y += colFootR.height;
/* Set the bounds of the remaining components. The scrollbars
* are made invisible if they're not needed.
*/
if (rowHead != null) {
rowHead.setBounds(adjustBounds(parent, rowHeadR, ltr));
}
if (_rowFoot != null) {
_rowFoot.setBounds(adjustBounds(parent, rowFootR, ltr));
}
int columnHeaderHeight = isColumnHeadersHeightUnified(scrollPane) ? Math.max(colHeadR.height,
Math.max(upperLeft == null ? 0 : upperLeft.getPreferredSize().height, upperRight == null ? 0 : upperRight.getPreferredSize().height)) : 0;
int columnFooterHeight = isColumnFootersHeightUnified(scrollPane) ? Math.max(colFootR.height,
Math.max(lowerLeft == null ? 0 : lowerLeft.getPreferredSize().height, lowerRight == null ? 0 : lowerRight.getPreferredSize().height)) : 0;
if (colHead != null) {
int height = isColumnHeadersHeightUnified(scrollPane) ? columnHeaderHeight : Math.min(colHeadR.height, colHead.getPreferredSize().height);
colHead.setBounds(adjustBounds(parent, new Rectangle(colHeadR.x, colHeadR.y + colHeadR.height - height, colHeadR.width, height), ltr));
}
if (_subColHead != null) {
_subColHead.setBounds(adjustBounds(parent, subColHeadR, ltr));
}
if (_colFoot != null) {
int height = isColumnFootersHeightUnified(scrollPane) ? columnFooterHeight : Math.min(colFootR.height, _colFoot.getPreferredSize().height);
_colFoot.setBounds(adjustBounds(parent, new Rectangle(colFootR.x, colFootR.y, colFootR.width, height), ltr));
}
else {
if (isColumnFootersHeightUnified(scrollPane)) {
columnFooterHeight = hsbR.height;
}
}
if (vsb != null) {
if (vsbNeeded) {
vsb.setVisible(true);
if (vsbPolicy == VERTICAL_SCROLLBAR_AS_NEEDED && !isEmpty && !(!viewTracksViewportHeight && (viewPrefSize.height > extentSize.height || (rowHead != null && rowHead.getView() != null && rowHead.getView().getPreferredSize().height > extentSize.height)))) {
vsb.setVisible(false);
}
if (_vTop == null && _vBottom == null)
vsb.setBounds(adjustBounds(parent, vsbR, ltr));
else {
Rectangle rect = new Rectangle(vsbR);
if (_vTop != null) {
Dimension dim = _vTop.getPreferredSize();
rect.y += dim.height;
rect.height -= dim.height;
_vTop.setVisible(true);
_vTop.setBounds(adjustBounds(parent, new Rectangle(vsbR.x, vsbR.y, vsbR.width, dim.height), ltr));
}
if (_vBottom != null) {
Dimension dim = _vBottom.getPreferredSize();
rect.height -= dim.height;
_vBottom.setVisible(true);
_vBottom.setBounds(adjustBounds(parent, new Rectangle(vsbR.x, vsbR.y + vsbR.height - dim.height, vsbR.width, dim.height), ltr));
}
vsb.setBounds(adjustBounds(parent, rect, ltr));
}
}
else {
if (viewPrefSize.height > extentSize.height) {
vsb.setVisible(true);
vsb.setBounds(adjustBounds(parent, new Rectangle(vsbR.x, vsbR.y, 0, vsbR.height), ltr));
}
else {
vsb.setVisible(false);
}
if (_vTop != null)
_vTop.setVisible(false);
if (_vBottom != null)
_vBottom.setVisible(false);
}
}
if (hsb != null) {
if (hsbNeeded) {
hsb.setVisible(true);
if (hsbPolicy == HORIZONTAL_SCROLLBAR_AS_NEEDED && !isEmpty && !(!viewTracksViewportWidth && (viewPrefSize.width > extentSize.width || (colHead != null && colHead.getView() != null && colHead.getView().getPreferredSize().width > extentSize.width)))) {
hsb.setVisible(false);
}
if (_hLeft == null && _hRight == null)
hsb.setBounds(adjustBounds(parent, hsbR, ltr));
else {
Rectangle rect = new Rectangle(hsbR);
if (_hLeft != null) {
Dimension dim = _hLeft.getPreferredSize();
rect.x += dim.width;
rect.width -= dim.width;
_hLeft.setVisible(true);
_hLeft.setBounds(adjustBounds(parent, new Rectangle(hsbR.x, hsbR.y, dim.width, hsbR.height), ltr));
_hLeft.doLayout();
}
if (_hRight != null) {
Dimension dim = _hRight.getPreferredSize();
rect.width -= dim.width;
_hRight.setVisible(true);
_hRight.setBounds(adjustBounds(parent, new Rectangle(hsbR.x + hsbR.width - dim.width, hsbR.y, dim.width, hsbR.height), ltr));
}
hsb.setBounds(adjustBounds(parent, rect, ltr));
}
}
else {
if (viewPrefSize.width > extentSize.width) {
hsb.setVisible(true);
hsb.setBounds(adjustBounds(parent, new Rectangle(hsbR.x, hsbR.y, hsbR.width, 0), ltr));
}
else {
hsb.setVisible(false);
}
if (_hLeft != null)
_hLeft.setVisible(false);
if (_hRight != null)
_hRight.setVisible(false);
}
}
if (lowerLeft != null && lowerLeft.isVisible()) {
int height = isColumnFootersHeightUnified(scrollPane) ? columnFooterHeight : Math.min(lowerLeft.getPreferredSize().height, colFootR.height);
lowerLeft.setBounds(adjustBounds(parent, new Rectangle(rowHeadR.x, colFootR.y != 0 ? colFootR.y : hsbR.y, rowHeadR.width, height), ltr));
}
if (lowerRight != null && lowerRight.isVisible()) {
int height = isColumnFootersHeightUnified(scrollPane) ? columnFooterHeight : Math.min(lowerRight.getPreferredSize().height, colFootR.height);
lowerRight.setBounds(adjustBounds(parent, new Rectangle(rowFootR.x, colFootR.y != 0 ? colFootR.y : hsbR.y, rowFootR.width, height), ltr));
}
if (upperLeft != null && upperLeft.isVisible()) {
int height = isColumnHeadersHeightUnified(scrollPane) ? columnHeaderHeight : Math.min(upperLeft.getPreferredSize().height, colHeadR.height);
upperLeft.setBounds(adjustBounds(parent, new Rectangle(rowHeadR.x, colHeadR.y + colHeadR.height - height, rowHeadR.width, height), ltr));
}
if (upperRight != null && upperRight.isVisible()) {
int height = isColumnHeadersHeightUnified(scrollPane) ? columnHeaderHeight : Math.min(upperRight.getPreferredSize().height, colHeadR.height);
upperRight.setBounds(adjustBounds(parent, new Rectangle(rowFootR.x, colHeadR.y + colHeadR.height - height, rowFootR.width, height), ltr));
}
}
|
diff --git a/sonar-server/src/main/java/org/sonar/server/issue/DefaultIssueFinder.java b/sonar-server/src/main/java/org/sonar/server/issue/DefaultIssueFinder.java
index 28342e46bc..c477d9af3c 100644
--- a/sonar-server/src/main/java/org/sonar/server/issue/DefaultIssueFinder.java
+++ b/sonar-server/src/main/java/org/sonar/server/issue/DefaultIssueFinder.java
@@ -1,302 +1,308 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2013 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube 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.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.issue;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.component.Component;
import org.sonar.api.issue.*;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.Rule;
import org.sonar.api.user.User;
import org.sonar.api.user.UserFinder;
import org.sonar.api.utils.Paging;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.DefaultIssueComment;
import org.sonar.core.issue.db.IssueChangeDao;
import org.sonar.core.issue.db.IssueDao;
import org.sonar.core.issue.db.IssueDto;
import org.sonar.core.persistence.MyBatis;
import org.sonar.core.resource.ResourceDao;
import org.sonar.core.rule.DefaultRuleFinder;
import org.sonar.core.user.AuthorizationDao;
import org.sonar.server.platform.UserSession;
import javax.annotation.CheckForNull;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Maps.newHashMap;
/**
* @since 3.6
*/
public class DefaultIssueFinder implements IssueFinder {
private static final Logger LOG = LoggerFactory.getLogger(DefaultIssueFinder.class);
private final MyBatis myBatis;
private final IssueDao issueDao;
private final IssueChangeDao issueChangeDao;
private final AuthorizationDao authorizationDao;
private final DefaultRuleFinder ruleFinder;
private final UserFinder userFinder;
private final ResourceDao resourceDao;
private final ActionPlanService actionPlanService;
public DefaultIssueFinder(MyBatis myBatis,
IssueDao issueDao, IssueChangeDao issueChangeDao,
AuthorizationDao authorizationDao,
DefaultRuleFinder ruleFinder,
UserFinder userFinder,
ResourceDao resourceDao,
ActionPlanService actionPlanService) {
this.myBatis = myBatis;
this.issueDao = issueDao;
this.issueChangeDao = issueChangeDao;
this.authorizationDao = authorizationDao;
this.ruleFinder = ruleFinder;
this.userFinder = userFinder;
this.resourceDao = resourceDao;
this.actionPlanService = actionPlanService;
}
DefaultIssue findByKey(String issueKey, String requiredRole) {
IssueDto dto = issueDao.selectByKey(issueKey);
if (dto == null) {
throw new IllegalStateException("Unknown issue: " + issueKey);
}
if (!authorizationDao.isAuthorizedComponentId(dto.getResourceId(), UserSession.get().userId(), requiredRole)) {
throw new IllegalStateException("User does not have the role " + requiredRole + " required to change the issue: " + issueKey);
}
return dto.toDefaultIssue();
}
public IssueQueryResult find(IssueQuery query) {
LOG.debug("IssueQuery : {}", query);
SqlSession sqlSession = myBatis.openSession();
try {
// 1. Select the ids of all the issues that match the query
List<IssueDto> allIssues = issueDao.selectIssueAndComponentIds(query, sqlSession);
// 2. Apply security, if needed
List<IssueDto> authorizedIssues;
if (query.requiredRole() != null) {
authorizedIssues = keepAuthorized(allIssues, query.requiredRole(), sqlSession);
} else {
authorizedIssues = allIssues;
}
// 3. Apply pagination
Paging paging = Paging.create(query.pageSize(), query.pageIndex(), authorizedIssues.size());
Set<Long> pagedIssueIds = pagedIssueIds(authorizedIssues, paging);
// 4. Load issues and their related data (rules, components, comments, action plans, ...)
Collection<IssueDto> pagedIssues = issueDao.selectByIds(pagedIssueIds, sqlSession);
Map<String, DefaultIssue> issuesByKey = newHashMap();
List<Issue> issues = newArrayList();
Set<Integer> ruleIds = Sets.newHashSet();
Set<Integer> componentIds = Sets.newHashSet();
Set<String> actionPlanKeys = Sets.newHashSet();
Set<String> users = Sets.newHashSet();
for (IssueDto dto : pagedIssues) {
DefaultIssue defaultIssue = dto.toDefaultIssue();
issuesByKey.put(dto.getKee(), defaultIssue);
issues.add(defaultIssue);
ruleIds.add(dto.getRuleId());
componentIds.add(dto.getResourceId());
actionPlanKeys.add(dto.getActionPlanKey());
- users.add(dto.getUserLogin());
- users.add(dto.getAssignee());
+ if (dto.getUserLogin() != null) {
+ users.add(dto.getUserLogin());
+ }
+ if (dto.getAssignee() != null) {
+ users.add(dto.getAssignee());
+ }
}
List<DefaultIssueComment> comments = issueChangeDao.selectCommentsByIssues(sqlSession, issuesByKey.keySet());
for (DefaultIssueComment comment : comments) {
DefaultIssue issue = issuesByKey.get(comment.issueKey());
issue.addComment(comment);
- users.add(comment.userLogin());
+ if (comment.userLogin() != null) {
+ users.add(comment.userLogin());
+ }
}
return new DefaultResults(issues,
findRules(ruleIds),
findComponents(componentIds),
findActionPlans(actionPlanKeys),
findUsers(users),
paging,
authorizedIssues.size() != allIssues.size());
} finally {
MyBatis.closeQuietly(sqlSession);
}
}
private List<IssueDto> keepAuthorized(List<IssueDto> issues, String requiredRole, SqlSession sqlSession) {
final Set<Integer> authorizedComponentIds = authorizationDao.keepAuthorizedComponentIds(
extractResourceIds(issues),
UserSession.get().userId(),
requiredRole,
sqlSession
);
return newArrayList(Iterables.filter(issues, new Predicate<IssueDto>() {
@Override
public boolean apply(IssueDto issueDto) {
return authorizedComponentIds.contains(issueDto.getResourceId());
}
}));
}
private Set<Integer> extractResourceIds(List<IssueDto> issues) {
Set<Integer> componentIds = Sets.newLinkedHashSet();
for (IssueDto issue : issues) {
componentIds.add(issue.getResourceId());
}
return componentIds;
}
private Set<Long> pagedIssueIds(Collection<IssueDto> issues, Paging paging) {
Set<Long> issueIds = Sets.newLinkedHashSet();
int index = 0;
for (IssueDto issue : issues) {
if (index >= paging.offset() && issueIds.size() < paging.pageSize()) {
issueIds.add(issue.getId());
} else if (issueIds.size() >= paging.pageSize()) {
break;
}
index++;
}
return issueIds;
}
private Collection<Rule> findRules(Set<Integer> ruleIds) {
return ruleFinder.findByIds(ruleIds);
}
private Collection<User> findUsers(Set<String> logins) {
return userFinder.findByLogins(Lists.newArrayList(logins));
}
private Collection<Component> findComponents(Set<Integer> componentIds) {
return resourceDao.findByIds(componentIds);
}
private Collection<ActionPlan> findActionPlans(Set<String> actionPlanKeys) {
return actionPlanService.findByKeys(actionPlanKeys);
}
public Issue findByKey(String key) {
IssueDto dto = issueDao.selectByKey(key);
return dto != null ? dto.toDefaultIssue() : null;
}
static class DefaultResults implements IssueQueryResult {
private final List<Issue> issues;
private final Map<RuleKey, Rule> rulesByKey = Maps.newHashMap();
private final Map<String, Component> componentsByKey = Maps.newHashMap();
private final Map<String, ActionPlan> actionPlansByKey = Maps.newHashMap();
private final Map<String, User> usersByLogin = Maps.newHashMap();
private final boolean securityExclusions;
private final Paging paging;
DefaultResults(List<Issue> issues,
Collection<Rule> rules,
Collection<Component> components,
Collection<ActionPlan> actionPlans,
Collection<User> users,
Paging paging, boolean securityExclusions) {
this.issues = issues;
for (Rule rule : rules) {
rulesByKey.put(rule.ruleKey(), rule);
}
for (Component component : components) {
componentsByKey.put(component.key(), component);
}
for (ActionPlan actionPlan : actionPlans) {
actionPlansByKey.put(actionPlan.key(), actionPlan);
}
for (User user : users) {
usersByLogin.put(user.login(), user);
}
this.paging = paging;
this.securityExclusions = securityExclusions;
}
@Override
public List<Issue> issues() {
return issues;
}
@Override
public Rule rule(Issue issue) {
return rulesByKey.get(issue.ruleKey());
}
@Override
public Collection<Rule> rules() {
return rulesByKey.values();
}
@Override
public Component component(Issue issue) {
return componentsByKey.get(issue.componentKey());
}
@Override
public Collection<Component> components() {
return componentsByKey.values();
}
@Override
public ActionPlan actionPlan(Issue issue) {
return actionPlansByKey.get(issue.actionPlanKey());
}
@Override
public Collection<ActionPlan> actionPlans() {
return actionPlansByKey.values();
}
@Override
public Collection<User> users() {
return usersByLogin.values();
}
@Override
@CheckForNull
public User user(String login) {
return usersByLogin.get(login);
}
@Override
public boolean securityExclusions() {
return securityExclusions;
}
@Override
public Paging paging() {
return paging;
}
}
}
| false | true | public IssueQueryResult find(IssueQuery query) {
LOG.debug("IssueQuery : {}", query);
SqlSession sqlSession = myBatis.openSession();
try {
// 1. Select the ids of all the issues that match the query
List<IssueDto> allIssues = issueDao.selectIssueAndComponentIds(query, sqlSession);
// 2. Apply security, if needed
List<IssueDto> authorizedIssues;
if (query.requiredRole() != null) {
authorizedIssues = keepAuthorized(allIssues, query.requiredRole(), sqlSession);
} else {
authorizedIssues = allIssues;
}
// 3. Apply pagination
Paging paging = Paging.create(query.pageSize(), query.pageIndex(), authorizedIssues.size());
Set<Long> pagedIssueIds = pagedIssueIds(authorizedIssues, paging);
// 4. Load issues and their related data (rules, components, comments, action plans, ...)
Collection<IssueDto> pagedIssues = issueDao.selectByIds(pagedIssueIds, sqlSession);
Map<String, DefaultIssue> issuesByKey = newHashMap();
List<Issue> issues = newArrayList();
Set<Integer> ruleIds = Sets.newHashSet();
Set<Integer> componentIds = Sets.newHashSet();
Set<String> actionPlanKeys = Sets.newHashSet();
Set<String> users = Sets.newHashSet();
for (IssueDto dto : pagedIssues) {
DefaultIssue defaultIssue = dto.toDefaultIssue();
issuesByKey.put(dto.getKee(), defaultIssue);
issues.add(defaultIssue);
ruleIds.add(dto.getRuleId());
componentIds.add(dto.getResourceId());
actionPlanKeys.add(dto.getActionPlanKey());
users.add(dto.getUserLogin());
users.add(dto.getAssignee());
}
List<DefaultIssueComment> comments = issueChangeDao.selectCommentsByIssues(sqlSession, issuesByKey.keySet());
for (DefaultIssueComment comment : comments) {
DefaultIssue issue = issuesByKey.get(comment.issueKey());
issue.addComment(comment);
users.add(comment.userLogin());
}
return new DefaultResults(issues,
findRules(ruleIds),
findComponents(componentIds),
findActionPlans(actionPlanKeys),
findUsers(users),
paging,
authorizedIssues.size() != allIssues.size());
} finally {
MyBatis.closeQuietly(sqlSession);
}
}
| public IssueQueryResult find(IssueQuery query) {
LOG.debug("IssueQuery : {}", query);
SqlSession sqlSession = myBatis.openSession();
try {
// 1. Select the ids of all the issues that match the query
List<IssueDto> allIssues = issueDao.selectIssueAndComponentIds(query, sqlSession);
// 2. Apply security, if needed
List<IssueDto> authorizedIssues;
if (query.requiredRole() != null) {
authorizedIssues = keepAuthorized(allIssues, query.requiredRole(), sqlSession);
} else {
authorizedIssues = allIssues;
}
// 3. Apply pagination
Paging paging = Paging.create(query.pageSize(), query.pageIndex(), authorizedIssues.size());
Set<Long> pagedIssueIds = pagedIssueIds(authorizedIssues, paging);
// 4. Load issues and their related data (rules, components, comments, action plans, ...)
Collection<IssueDto> pagedIssues = issueDao.selectByIds(pagedIssueIds, sqlSession);
Map<String, DefaultIssue> issuesByKey = newHashMap();
List<Issue> issues = newArrayList();
Set<Integer> ruleIds = Sets.newHashSet();
Set<Integer> componentIds = Sets.newHashSet();
Set<String> actionPlanKeys = Sets.newHashSet();
Set<String> users = Sets.newHashSet();
for (IssueDto dto : pagedIssues) {
DefaultIssue defaultIssue = dto.toDefaultIssue();
issuesByKey.put(dto.getKee(), defaultIssue);
issues.add(defaultIssue);
ruleIds.add(dto.getRuleId());
componentIds.add(dto.getResourceId());
actionPlanKeys.add(dto.getActionPlanKey());
if (dto.getUserLogin() != null) {
users.add(dto.getUserLogin());
}
if (dto.getAssignee() != null) {
users.add(dto.getAssignee());
}
}
List<DefaultIssueComment> comments = issueChangeDao.selectCommentsByIssues(sqlSession, issuesByKey.keySet());
for (DefaultIssueComment comment : comments) {
DefaultIssue issue = issuesByKey.get(comment.issueKey());
issue.addComment(comment);
if (comment.userLogin() != null) {
users.add(comment.userLogin());
}
}
return new DefaultResults(issues,
findRules(ruleIds),
findComponents(componentIds),
findActionPlans(actionPlanKeys),
findUsers(users),
paging,
authorizedIssues.size() != allIssues.size());
} finally {
MyBatis.closeQuietly(sqlSession);
}
}
|
diff --git a/trunk/java/src/xpra/Start.java b/trunk/java/src/xpra/Start.java
index f5828c8e1..d2067dfa1 100644
--- a/trunk/java/src/xpra/Start.java
+++ b/trunk/java/src/xpra/Start.java
@@ -1,22 +1,29 @@
package xpra;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public abstract class Start {
public static final String DEFAULT_HOST = "localhost";
public static final int DEFAULT_PORT = 10000;
public void run(String[] args) throws IOException {
- Socket socket = new Socket(DEFAULT_HOST, DEFAULT_PORT);
- socket.setKeepAlive(true);
- InputStream is = socket.getInputStream();
- OutputStream os = socket.getOutputStream();
- this.makeClient(is, os).run(args);
+ Socket socket = null;
+ try {
+ socket = new Socket(DEFAULT_HOST, DEFAULT_PORT);
+ socket.setKeepAlive(true);
+ InputStream is = socket.getInputStream();
+ OutputStream os = socket.getOutputStream();
+ this.makeClient(is, os).run(args);
+ }
+ finally {
+ if (socket!=null)
+ socket.close();
+ }
}
public abstract AbstractClient makeClient(InputStream is, OutputStream os);
}
| true | true | public void run(String[] args) throws IOException {
Socket socket = new Socket(DEFAULT_HOST, DEFAULT_PORT);
socket.setKeepAlive(true);
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
this.makeClient(is, os).run(args);
}
| public void run(String[] args) throws IOException {
Socket socket = null;
try {
socket = new Socket(DEFAULT_HOST, DEFAULT_PORT);
socket.setKeepAlive(true);
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
this.makeClient(is, os).run(args);
}
finally {
if (socket!=null)
socket.close();
}
}
|
diff --git a/src/main/java/com/github/kpacha/jkata/pokerhand/PokerCard.java b/src/main/java/com/github/kpacha/jkata/pokerhand/PokerCard.java
index b94959f..456528f 100644
--- a/src/main/java/com/github/kpacha/jkata/pokerhand/PokerCard.java
+++ b/src/main/java/com/github/kpacha/jkata/pokerhand/PokerCard.java
@@ -1,19 +1,21 @@
package com.github.kpacha.jkata.pokerhand;
public class PokerCard {
private String card;
public PokerCard(String card) {
this.card = card;
}
public int getNumericValue() {
+ if (card.charAt(0) == 'Q')
+ return 11;
if (card.charAt(0) == 'J')
return 10;
if (card.charAt(0) == '9')
return 9;
return 5;
}
}
| true | true | public int getNumericValue() {
if (card.charAt(0) == 'J')
return 10;
if (card.charAt(0) == '9')
return 9;
return 5;
}
| public int getNumericValue() {
if (card.charAt(0) == 'Q')
return 11;
if (card.charAt(0) == 'J')
return 10;
if (card.charAt(0) == '9')
return 9;
return 5;
}
|
diff --git a/cdi/tests/org.jboss.tools.cdi.bot.test/src/org/jboss/tools/cdi/bot/test/editor/BeansEditor.java b/cdi/tests/org.jboss.tools.cdi.bot.test/src/org/jboss/tools/cdi/bot/test/editor/BeansEditor.java
index e79e6d4fb..b897e864e 100644
--- a/cdi/tests/org.jboss.tools.cdi.bot.test/src/org/jboss/tools/cdi/bot/test/editor/BeansEditor.java
+++ b/cdi/tests/org.jboss.tools.cdi.bot.test/src/org/jboss/tools/cdi/bot/test/editor/BeansEditor.java
@@ -1,132 +1,132 @@
/*******************************************************************************
* Copyright (c) 2010 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.cdi.bot.test.editor;
import org.apache.log4j.Level;
import org.eclipse.swtbot.eclipse.finder.SWTWorkbenchBot;
import org.eclipse.swtbot.swt.finder.SWTBot;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotButton;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTable;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotText;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTree;
import org.eclipse.swtbot.swt.finder.widgets.SWTBotTreeItem;
import org.eclipse.ui.IEditorReference;
import org.jboss.tools.ui.bot.ext.SWTBotExt;
import org.jboss.tools.ui.bot.ext.widgets.SWTBotMultiPageEditor;
/**
* @author Lukas Jungmann
*/
public class BeansEditor extends SWTBotMultiPageEditor {
public enum Item {
INTERCEPTOR("Interceptors"), DECORATOR("Decorators"),
CLASS("Alternatives"), STEREOTYPE("Alternatives");
private final String node;
private Item(String node) {
this.node = node;
}
private String getNode() {
return node;
}
public String getElementName() {
switch (this) {
case STEREOTYPE:
return "stereotype";
default:
return "class";
}
}
}
private SWTBotExt bot = new SWTBotExt();
private static final String ROOT_NODE = "beans.xml";
public BeansEditor(IEditorReference editorReference, SWTWorkbenchBot bot) {
super(editorReference, bot);
}
public BeansEditor add(Item item, String name) {
return modify(item, name, "Add...", new AddDialogHandler(item, name));
}
public BeansEditor remove(Item item, String name) {
return modify(item, name, "Remove...", new DeleteDialogHandler());
}
public String getSelectedItem() {
return bot().tree().selection().get(0, 0);
}
private BeansEditor modify(Item item, String name, String actionLabel, DialogHandler h) {
- SWTBotTree tree = bot.tree(1);
+ SWTBotTree tree = bot.tree(2);
for (SWTBotTreeItem ti:tree.getAllItems()) {
log.setLevel(Level.FATAL);
log.fatal(ti.getText());
}
tree.expandNode(ROOT_NODE, item.getNode()).select().click();
selectItem(item, name);
getItemButton(item, actionLabel).click();
h.handle(bot.activeShell());
bot.sleep(500);
this.setFocus();
return this;
}
private void selectItem(Item item, String name) {
SWTBotTable t = item == Item.STEREOTYPE ? bot.table(1) : bot.table(0);
if (t.containsItem(name)) {
t.select(name);
}
}
private SWTBotButton getItemButton(Item i, String label) {
return i == Item.STEREOTYPE ? bot.button(label, 1) : bot.button(label, 0);
}
private interface DialogHandler {
void handle(SWTBotShell dialog);
}
private class AddDialogHandler implements DialogHandler {
private final Item type;
private final String name;
public AddDialogHandler(Item type, String name) {
this.type = type;
this.name = name;
}
public void handle(SWTBotShell dialog) {
SWTBot sh = dialog.bot();
SWTBotText t = type == Item.STEREOTYPE
? sh.textWithLabel("Stereotype:*")
: sh.textWithLabel("Class:*");
t.setText(name);
sh.button("Finish").click();
}
}
private class DeleteDialogHandler implements DialogHandler {
public void handle(SWTBotShell dialog) {
dialog.bot().button("OK").click();
}
}
}
| true | true | private BeansEditor modify(Item item, String name, String actionLabel, DialogHandler h) {
SWTBotTree tree = bot.tree(1);
for (SWTBotTreeItem ti:tree.getAllItems()) {
log.setLevel(Level.FATAL);
log.fatal(ti.getText());
}
tree.expandNode(ROOT_NODE, item.getNode()).select().click();
selectItem(item, name);
getItemButton(item, actionLabel).click();
h.handle(bot.activeShell());
bot.sleep(500);
this.setFocus();
return this;
}
| private BeansEditor modify(Item item, String name, String actionLabel, DialogHandler h) {
SWTBotTree tree = bot.tree(2);
for (SWTBotTreeItem ti:tree.getAllItems()) {
log.setLevel(Level.FATAL);
log.fatal(ti.getText());
}
tree.expandNode(ROOT_NODE, item.getNode()).select().click();
selectItem(item, name);
getItemButton(item, actionLabel).click();
h.handle(bot.activeShell());
bot.sleep(500);
this.setFocus();
return this;
}
|
diff --git a/src/edu/wpi/first/wpilibj/templates/debugging/DebugInfo.java b/src/edu/wpi/first/wpilibj/templates/debugging/DebugInfo.java
index 0f3e49f..05aed24 100644
--- a/src/edu/wpi/first/wpilibj/templates/debugging/DebugInfo.java
+++ b/src/edu/wpi/first/wpilibj/templates/debugging/DebugInfo.java
@@ -1,24 +1,24 @@
package edu.wpi.first.wpilibj.templates.debugging;
/**
* This is an abstract DebugInfo class, use various other classes in the
* debugging package if you want to create one of these.
*
* @author daboross
*/
public abstract class DebugInfo extends DebugOutput {
protected abstract String key();
protected abstract String message();
protected abstract boolean isConsole();
protected abstract boolean isDashboard();
protected abstract int debugLevel();
protected void debug() {
- RobotDebugger.push(this);
+ RobotDebugger.pushInfo(this);
}
}
| true | true | protected void debug() {
RobotDebugger.push(this);
}
| protected void debug() {
RobotDebugger.pushInfo(this);
}
|
diff --git a/src/org/eclipse/imp/lpg/editor/ContentProposer.java b/src/org/eclipse/imp/lpg/editor/ContentProposer.java
index 222a7ae..8b92da4 100644
--- a/src/org/eclipse/imp/lpg/editor/ContentProposer.java
+++ b/src/org/eclipse/imp/lpg/editor/ContentProposer.java
@@ -1,38 +1,39 @@
/*
* Created on Nov 1, 2005
*/
package org.jikespg.uide.editor;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.uide.editor.IContentProposer;
import org.eclipse.uide.parser.IASTNodeLocator;
import org.eclipse.uide.parser.IParseController;
import org.jikespg.uide.parser.JikesPGParser.ASTNode;
import org.jikespg.uide.parser.JikesPGParser.rhsSymbol;
import org.jikespg.uide.parser.JikesPGParser.rhsSymbolMacro;
import com.ibm.lpg.IToken;
import com.ibm.lpg.PrsStream;
public class ContentProposer implements IContentProposer {
public ICompletionProposal[] getContentProposals(IParseController controller, int offset) {
PrsStream parseStream= controller.getParser().getParseStream();
int thisTokIdx= parseStream.getTokenIndexAtCharacter(offset);
+ if (thisTokIdx < 0) thisTokIdx= - thisTokIdx;
IToken prevTok= parseStream.getTokenAt(thisTokIdx - 1);
ASTNode currentAst= (ASTNode) controller.getCurrentAst();
IASTNodeLocator locator= controller.getNodeLocator();
ASTNode prevNode= null; // locator.findNode(currentAst, prevTok.getStartOffset());
ASTNode parentNode= null; // locator.findParent(currentAst, prevNode);
if (parentNode instanceof rhsSymbol) {
rhsSymbol symbol= (rhsSymbol) parentNode;
} else if (parentNode instanceof rhsSymbolMacro) {
rhsSymbolMacro macro= (rhsSymbolMacro) parentNode;
}
return null;
}
}
| true | true | public ICompletionProposal[] getContentProposals(IParseController controller, int offset) {
PrsStream parseStream= controller.getParser().getParseStream();
int thisTokIdx= parseStream.getTokenIndexAtCharacter(offset);
IToken prevTok= parseStream.getTokenAt(thisTokIdx - 1);
ASTNode currentAst= (ASTNode) controller.getCurrentAst();
IASTNodeLocator locator= controller.getNodeLocator();
ASTNode prevNode= null; // locator.findNode(currentAst, prevTok.getStartOffset());
ASTNode parentNode= null; // locator.findParent(currentAst, prevNode);
if (parentNode instanceof rhsSymbol) {
rhsSymbol symbol= (rhsSymbol) parentNode;
} else if (parentNode instanceof rhsSymbolMacro) {
rhsSymbolMacro macro= (rhsSymbolMacro) parentNode;
}
return null;
}
| public ICompletionProposal[] getContentProposals(IParseController controller, int offset) {
PrsStream parseStream= controller.getParser().getParseStream();
int thisTokIdx= parseStream.getTokenIndexAtCharacter(offset);
if (thisTokIdx < 0) thisTokIdx= - thisTokIdx;
IToken prevTok= parseStream.getTokenAt(thisTokIdx - 1);
ASTNode currentAst= (ASTNode) controller.getCurrentAst();
IASTNodeLocator locator= controller.getNodeLocator();
ASTNode prevNode= null; // locator.findNode(currentAst, prevTok.getStartOffset());
ASTNode parentNode= null; // locator.findParent(currentAst, prevNode);
if (parentNode instanceof rhsSymbol) {
rhsSymbol symbol= (rhsSymbol) parentNode;
} else if (parentNode instanceof rhsSymbolMacro) {
rhsSymbolMacro macro= (rhsSymbolMacro) parentNode;
}
return null;
}
|
diff --git a/src/fuschia/tagger/common/RepositoryCreator.java b/src/fuschia/tagger/common/RepositoryCreator.java
index 457c3d4..46ee092 100644
--- a/src/fuschia/tagger/common/RepositoryCreator.java
+++ b/src/fuschia/tagger/common/RepositoryCreator.java
@@ -1,204 +1,204 @@
/**
* File: TaggerThread.java
* Date: Apr 17, 2012
* Author: Morteza Ansarinia <[email protected]>
*/
package fuschia.tagger.common;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import opennlp.tools.cmdline.postag.POSModelLoader;
import opennlp.tools.postag.POSModel;
import opennlp.tools.postag.POSTaggerME;
import opennlp.tools.tokenize.WhitespaceTokenizer;
import fuschia.tagger.common.DocumentRepository;
public class RepositoryCreator extends Thread {
private String strWorkingDirectory;
public DocumentRepository results;
public static void main(String[] args) {
try {
RepositoryCreator creator = new RepositoryCreator("/Volumes/Personal HD/Friends/Salar/");
creator.start();
while(creator.isAlive());
creator.results.saveToFile("/Users/morteza/911.cmap.gz");
} catch (Exception e) {
e.printStackTrace();
}
}
public RepositoryCreator(String strWorkingDirectory) {
super();
this.strWorkingDirectory = new String(strWorkingDirectory);
results = null;
}
public List<File> getAllFiles(String rootPath) {
List<File> result = new ArrayList<File>();
File[] files = new File(rootPath).listFiles();
String filenameRegex = "[A-Z]{2,4}\\d{1,3}[BC]?(\\sunsure)?-Q[0-9]*\\.txt";
for (File file : files) {
// Directories
if (file.isDirectory() && file.exists() && file.canRead()) {
List<File> children = getAllFiles(file.getPath());
result.addAll(children);
continue;
}
// Files
if (file.isFile() && file.exists() && file.canRead()) {
if (Pattern.matches(filenameRegex, file.getName())) {
result.add(file);
}
}
}
return result;
}
public void run() {
try {
results = new DocumentRepository();
POSModel model = new POSModelLoader().load(new File("resources/en-pos-maxent.bin"));
POSTaggerME tagger = new POSTaggerME(model);
List<File> files = getAllFiles(strWorkingDirectory);
System.out.println("Num of files: " + files.size());
if (files == null || files.size() == 0) {
results = null;
return;
}
sleep(10); // FIXME: Just to update logs view
int index = 0;
int surveyId = 0;
int[][] verbCounts =new int[56][7];
int[][] adjectiveCounts =new int[56][7];
Pattern questionNumberPattern = Pattern.compile("[^0-9]+[0-9]+[^0-9]+([0-9]+)[^0-9]+");
int questionNumber = 0;
for (File file : files) {
index++;
if(index%1000==0)
System.out.println("processing "+ (index) + " of " +files.size());
Scanner lineScanner = new Scanner(new FileReader(file));
Matcher m = questionNumberPattern.matcher(file.getName());
if(m.find()){
questionNumber = Integer.valueOf(m.group(1));
// mark question for writing to the output file
}
m.reset();
if (file.getPath().indexOf("SURVEY 1") != -1)
surveyId = 1;
else if (file.getPath().indexOf("SURVEY 2") != -1)
surveyId = 2;
else if (file.getPath().indexOf("SURVEY 3") != -1)
surveyId = 3;
else
surveyId = 0;
String txt = new String();
while (lineScanner.hasNextLine()) {
txt = txt + lineScanner.nextLine();
}
lineScanner.close();
lineScanner = null;
String tokens[] = WhitespaceTokenizer.INSTANCE.tokenize(txt);
String[] tags = tagger.tag(tokens);
if (surveyId>0) {
verbCounts[questionNumber][surveyId*2-1] += tags.length;
adjectiveCounts[questionNumber][surveyId*2-1] += tags.length;
for (int i=0;i<tags.length;i++) {
if (tags[i].startsWith("VB")) {
verbCounts[questionNumber][surveyId*2]++;
} else if (tags[i].startsWith("JJ")
|| tags[i].startsWith("RB")
|| tags[i].startsWith("WRB")) {
adjectiveCounts[questionNumber][surveyId*2]++;
}
}
}
// Create and add appropriate document object
- String documentId = ((surveyId==0)?".":"s."+String.valueOf(surveyId))
+ String documentId = ((surveyId==0)?".":"s"+String.valueOf(surveyId)+".")
+ file.getName().substring(0,file.getName().length() - 4);
results.addDocument(documentId, new Document(file.getName(), tokens, tags));
}
System.out.println("Writing Construal CSV output...");
BufferedWriter fVerbs = new BufferedWriter(new FileWriter(new File("/Users/morteza/verbs.csv")));
BufferedWriter fAdjectives = new BufferedWriter(new FileWriter(new File("/Users/morteza/adjectives.csv")));
for (int q=0; q< 56 ; q++) {
String vLine = "";
String aLine="";
if (verbCounts[q][1]+verbCounts[q][3]+verbCounts[q][5]>0) {
vLine +=verbCounts[q][1]+","; // tag count (s1)
vLine +=verbCounts[q][2]+",";
vLine +=verbCounts[q][3]+","; // tag count (s2)
vLine +=verbCounts[q][4]+",";
vLine +=verbCounts[q][5]+","; // tag count (s3)
vLine +=verbCounts[q][6];
fVerbs.write(String.valueOf(q) + "," + vLine);
fVerbs.newLine();
fVerbs.flush();
}
if (adjectiveCounts[q][1]+adjectiveCounts[q][3]+adjectiveCounts[q][5]>0) {
aLine +=adjectiveCounts[q][1]+",";
aLine +=adjectiveCounts[q][2]+",";
aLine +=adjectiveCounts[q][3]+",";
aLine +=adjectiveCounts[q][4]+",";
aLine +=adjectiveCounts[q][5]+",";
aLine +=adjectiveCounts[q][6];
fAdjectives.write(String.valueOf(q) + "," + aLine);
fAdjectives.newLine();
fAdjectives.flush();
}
}
fVerbs.flush();
fAdjectives.flush();
fVerbs.close();
fAdjectives.close();
System.out.println("Finished!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true | true | public void run() {
try {
results = new DocumentRepository();
POSModel model = new POSModelLoader().load(new File("resources/en-pos-maxent.bin"));
POSTaggerME tagger = new POSTaggerME(model);
List<File> files = getAllFiles(strWorkingDirectory);
System.out.println("Num of files: " + files.size());
if (files == null || files.size() == 0) {
results = null;
return;
}
sleep(10); // FIXME: Just to update logs view
int index = 0;
int surveyId = 0;
int[][] verbCounts =new int[56][7];
int[][] adjectiveCounts =new int[56][7];
Pattern questionNumberPattern = Pattern.compile("[^0-9]+[0-9]+[^0-9]+([0-9]+)[^0-9]+");
int questionNumber = 0;
for (File file : files) {
index++;
if(index%1000==0)
System.out.println("processing "+ (index) + " of " +files.size());
Scanner lineScanner = new Scanner(new FileReader(file));
Matcher m = questionNumberPattern.matcher(file.getName());
if(m.find()){
questionNumber = Integer.valueOf(m.group(1));
// mark question for writing to the output file
}
m.reset();
if (file.getPath().indexOf("SURVEY 1") != -1)
surveyId = 1;
else if (file.getPath().indexOf("SURVEY 2") != -1)
surveyId = 2;
else if (file.getPath().indexOf("SURVEY 3") != -1)
surveyId = 3;
else
surveyId = 0;
String txt = new String();
while (lineScanner.hasNextLine()) {
txt = txt + lineScanner.nextLine();
}
lineScanner.close();
lineScanner = null;
String tokens[] = WhitespaceTokenizer.INSTANCE.tokenize(txt);
String[] tags = tagger.tag(tokens);
if (surveyId>0) {
verbCounts[questionNumber][surveyId*2-1] += tags.length;
adjectiveCounts[questionNumber][surveyId*2-1] += tags.length;
for (int i=0;i<tags.length;i++) {
if (tags[i].startsWith("VB")) {
verbCounts[questionNumber][surveyId*2]++;
} else if (tags[i].startsWith("JJ")
|| tags[i].startsWith("RB")
|| tags[i].startsWith("WRB")) {
adjectiveCounts[questionNumber][surveyId*2]++;
}
}
}
// Create and add appropriate document object
String documentId = ((surveyId==0)?".":"s."+String.valueOf(surveyId))
+ file.getName().substring(0,file.getName().length() - 4);
results.addDocument(documentId, new Document(file.getName(), tokens, tags));
}
System.out.println("Writing Construal CSV output...");
BufferedWriter fVerbs = new BufferedWriter(new FileWriter(new File("/Users/morteza/verbs.csv")));
BufferedWriter fAdjectives = new BufferedWriter(new FileWriter(new File("/Users/morteza/adjectives.csv")));
for (int q=0; q< 56 ; q++) {
String vLine = "";
String aLine="";
if (verbCounts[q][1]+verbCounts[q][3]+verbCounts[q][5]>0) {
vLine +=verbCounts[q][1]+","; // tag count (s1)
vLine +=verbCounts[q][2]+",";
vLine +=verbCounts[q][3]+","; // tag count (s2)
vLine +=verbCounts[q][4]+",";
vLine +=verbCounts[q][5]+","; // tag count (s3)
vLine +=verbCounts[q][6];
fVerbs.write(String.valueOf(q) + "," + vLine);
fVerbs.newLine();
fVerbs.flush();
}
if (adjectiveCounts[q][1]+adjectiveCounts[q][3]+adjectiveCounts[q][5]>0) {
aLine +=adjectiveCounts[q][1]+",";
aLine +=adjectiveCounts[q][2]+",";
aLine +=adjectiveCounts[q][3]+",";
aLine +=adjectiveCounts[q][4]+",";
aLine +=adjectiveCounts[q][5]+",";
aLine +=adjectiveCounts[q][6];
fAdjectives.write(String.valueOf(q) + "," + aLine);
fAdjectives.newLine();
fAdjectives.flush();
}
}
fVerbs.flush();
fAdjectives.flush();
fVerbs.close();
fAdjectives.close();
System.out.println("Finished!");
} catch (Exception e) {
e.printStackTrace();
}
}
| public void run() {
try {
results = new DocumentRepository();
POSModel model = new POSModelLoader().load(new File("resources/en-pos-maxent.bin"));
POSTaggerME tagger = new POSTaggerME(model);
List<File> files = getAllFiles(strWorkingDirectory);
System.out.println("Num of files: " + files.size());
if (files == null || files.size() == 0) {
results = null;
return;
}
sleep(10); // FIXME: Just to update logs view
int index = 0;
int surveyId = 0;
int[][] verbCounts =new int[56][7];
int[][] adjectiveCounts =new int[56][7];
Pattern questionNumberPattern = Pattern.compile("[^0-9]+[0-9]+[^0-9]+([0-9]+)[^0-9]+");
int questionNumber = 0;
for (File file : files) {
index++;
if(index%1000==0)
System.out.println("processing "+ (index) + " of " +files.size());
Scanner lineScanner = new Scanner(new FileReader(file));
Matcher m = questionNumberPattern.matcher(file.getName());
if(m.find()){
questionNumber = Integer.valueOf(m.group(1));
// mark question for writing to the output file
}
m.reset();
if (file.getPath().indexOf("SURVEY 1") != -1)
surveyId = 1;
else if (file.getPath().indexOf("SURVEY 2") != -1)
surveyId = 2;
else if (file.getPath().indexOf("SURVEY 3") != -1)
surveyId = 3;
else
surveyId = 0;
String txt = new String();
while (lineScanner.hasNextLine()) {
txt = txt + lineScanner.nextLine();
}
lineScanner.close();
lineScanner = null;
String tokens[] = WhitespaceTokenizer.INSTANCE.tokenize(txt);
String[] tags = tagger.tag(tokens);
if (surveyId>0) {
verbCounts[questionNumber][surveyId*2-1] += tags.length;
adjectiveCounts[questionNumber][surveyId*2-1] += tags.length;
for (int i=0;i<tags.length;i++) {
if (tags[i].startsWith("VB")) {
verbCounts[questionNumber][surveyId*2]++;
} else if (tags[i].startsWith("JJ")
|| tags[i].startsWith("RB")
|| tags[i].startsWith("WRB")) {
adjectiveCounts[questionNumber][surveyId*2]++;
}
}
}
// Create and add appropriate document object
String documentId = ((surveyId==0)?".":"s"+String.valueOf(surveyId)+".")
+ file.getName().substring(0,file.getName().length() - 4);
results.addDocument(documentId, new Document(file.getName(), tokens, tags));
}
System.out.println("Writing Construal CSV output...");
BufferedWriter fVerbs = new BufferedWriter(new FileWriter(new File("/Users/morteza/verbs.csv")));
BufferedWriter fAdjectives = new BufferedWriter(new FileWriter(new File("/Users/morteza/adjectives.csv")));
for (int q=0; q< 56 ; q++) {
String vLine = "";
String aLine="";
if (verbCounts[q][1]+verbCounts[q][3]+verbCounts[q][5]>0) {
vLine +=verbCounts[q][1]+","; // tag count (s1)
vLine +=verbCounts[q][2]+",";
vLine +=verbCounts[q][3]+","; // tag count (s2)
vLine +=verbCounts[q][4]+",";
vLine +=verbCounts[q][5]+","; // tag count (s3)
vLine +=verbCounts[q][6];
fVerbs.write(String.valueOf(q) + "," + vLine);
fVerbs.newLine();
fVerbs.flush();
}
if (adjectiveCounts[q][1]+adjectiveCounts[q][3]+adjectiveCounts[q][5]>0) {
aLine +=adjectiveCounts[q][1]+",";
aLine +=adjectiveCounts[q][2]+",";
aLine +=adjectiveCounts[q][3]+",";
aLine +=adjectiveCounts[q][4]+",";
aLine +=adjectiveCounts[q][5]+",";
aLine +=adjectiveCounts[q][6];
fAdjectives.write(String.valueOf(q) + "," + aLine);
fAdjectives.newLine();
fAdjectives.flush();
}
}
fVerbs.flush();
fAdjectives.flush();
fVerbs.close();
fAdjectives.close();
System.out.println("Finished!");
} catch (Exception e) {
e.printStackTrace();
}
}
|
diff --git a/src/main/java/org/primefaces/behavior/printer/PrinterBehavior.java b/src/main/java/org/primefaces/behavior/printer/PrinterBehavior.java
index 67ca84529..fa2026008 100644
--- a/src/main/java/org/primefaces/behavior/printer/PrinterBehavior.java
+++ b/src/main/java/org/primefaces/behavior/printer/PrinterBehavior.java
@@ -1,53 +1,53 @@
/*
* Copyright 2013 jagatai.
*
* 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.primefaces.behavior.printer;
import javax.faces.application.ResourceDependencies;
import javax.faces.application.ResourceDependency;
import javax.faces.component.behavior.ClientBehaviorBase;
import javax.faces.component.behavior.ClientBehaviorContext;
import javax.faces.context.FacesContext;
import org.primefaces.expression.SearchExpressionFacade;
@ResourceDependencies({
@ResourceDependency(library="primefaces", name="jquery/jquery.js"),
@ResourceDependency(library="primefaces", name="jquery/jquery-plugins.js"),
@ResourceDependency(library="primefaces", name="printer/printer.js"),
@ResourceDependency(library="primefaces", name="primefaces.js")
})
public class PrinterBehavior extends ClientBehaviorBase {
private String target;
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
@Override
public String getScript(ClientBehaviorContext behaviorContext) {
FacesContext context = behaviorContext.getFacesContext();
String components = SearchExpressionFacade.resolveComponentForClient(
context, behaviorContext.getComponent(), target);
- return "PrimeFaces.Expressions.resolveComponentsAsSelector('" + components + "').jqprint();return false;";
+ return "PrimeFaces.expressions.SearchExpressionFacade.resolveComponentsAsSelector('" + components + "').jqprint();return false;";
}
}
| true | true | public String getScript(ClientBehaviorContext behaviorContext) {
FacesContext context = behaviorContext.getFacesContext();
String components = SearchExpressionFacade.resolveComponentForClient(
context, behaviorContext.getComponent(), target);
return "PrimeFaces.Expressions.resolveComponentsAsSelector('" + components + "').jqprint();return false;";
}
| public String getScript(ClientBehaviorContext behaviorContext) {
FacesContext context = behaviorContext.getFacesContext();
String components = SearchExpressionFacade.resolveComponentForClient(
context, behaviorContext.getComponent(), target);
return "PrimeFaces.expressions.SearchExpressionFacade.resolveComponentsAsSelector('" + components + "').jqprint();return false;";
}
|
diff --git a/src/DocViewer/src/com/vangent/hieos/DocViewer/client/entrypoint/DocViewer.java b/src/DocViewer/src/com/vangent/hieos/DocViewer/client/entrypoint/DocViewer.java
index bce14f70..5f9ec5e7 100644
--- a/src/DocViewer/src/com/vangent/hieos/DocViewer/client/entrypoint/DocViewer.java
+++ b/src/DocViewer/src/com/vangent/hieos/DocViewer/client/entrypoint/DocViewer.java
@@ -1,366 +1,366 @@
/*
* This code is subject to the HIEOS License, Version 1.0
*
* Copyright(c) 2011 Vangent, Inc. All rights reserved.
*
* 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.vangent.hieos.DocViewer.client.entrypoint;
import com.google.gwt.core.client.EntryPoint;
//import com.google.gwt.event.dom.client.ClickEvent;
//import com.google.gwt.event.dom.client.ClickHandler;
//import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.RootPanel;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.util.ValueCallback;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.Img;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.toolbar.ToolStrip;
import com.smartgwt.client.widgets.toolbar.ToolStripButton;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.HeaderItem;
import com.smartgwt.client.widgets.form.fields.PasswordItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.layout.LayoutSpacer;
import com.vangent.hieos.DocViewer.client.controller.AuthenticationObserver;
import com.vangent.hieos.DocViewer.client.controller.ConfigObserver;
import com.vangent.hieos.DocViewer.client.controller.DocViewerController;
import com.vangent.hieos.DocViewer.client.model.authentication.AuthenticationContext;
import com.vangent.hieos.DocViewer.client.model.config.Config;
import com.vangent.hieos.DocViewer.client.model.patient.Patient;
import com.vangent.hieos.DocViewer.client.model.patient.PatientRecord;
import com.vangent.hieos.DocViewer.client.model.patient.PatientUtil;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*
* @author Bernie Thuman
*/
public class DocViewer implements EntryPoint {
private final DocViewerController controller = new DocViewerController();
private final Canvas mainCanvas = new Canvas();
private Canvas currentCanvas = null;
/**
*
*/
public void onModuleLoad() {
// Load client configuration ...
this.loadConfig();
// Load the Login page
// this.loadLoginPage();
}
/**
*
*/
private void loadConfig() {
// Load client configuration ...
ConfigObserver observer = new ConfigObserver(this, controller);
controller.loadConfig(observer);
}
/**
* This is the entry point method.
*/
public void loadLoginPage() {
// Get Title and Logo details from config file
// String title = "HIEOS Doc Viewer";
// String logoFileName = "search_computer.png";
// String logoWidth = "100";
// String logoHeigth = "100";
Config config = controller.getConfig();
String title = config.get(Config.KEY_TITLE);
String logoFileName = config.get(Config.KEY_LOGO_FILE_NAME);
Integer logoWidth = config.getAsInteger(Config.KEY_LOGO_WIDTH);
Integer logoHeight = config.getAsInteger(Config.KEY_LOGO_HEIGHT);
// Set up Login Form
final DynamicForm loginForm = new DynamicForm();
loginForm.setWidth(400);
loginForm.setHeight100();
HeaderItem header = new HeaderItem();
header.setDefaultValue(title);
header.setAlign(Alignment.CENTER);
final Img logo = new Img(logoFileName, logoWidth, logoHeight);
Label logonLabel = new Label();
logonLabel.setWidth(200);
logonLabel.setHeight100();
logonLabel.setAlign(Alignment.CENTER);
logonLabel.setContents("Enter your account details below");
final TextItem userIdItem = new TextItem("userid", "User ID");
final PasswordItem passwordItem = new PasswordItem("Password",
"Password");
userIdItem.setRequired(true);
userIdItem.setRequiredMessage("Please specify User Id");
passwordItem.setRequired(true);
final IButton loginButton = new IButton("Login");
loginButton.setIcon("login-blue.png");
loginButton.setLayoutAlign(Alignment.CENTER);
final DocViewer entryPoint = this;
loginButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
boolean validatedOk = loginForm.validate();
if (validatedOk == true) {
AuthenticationObserver authObserver = new AuthenticationObserver(
entryPoint);
controller.authenticateUser(authObserver,
userIdItem.getValueAsString(),
passwordItem.getValueAsString());
}
}
});
loginForm.setFields(header, userIdItem, passwordItem);
// Now, lay it out.
final VLayout layout = new VLayout();
layout.setShowEdges(true);
layout.setEdgeSize(3);
layout.setPadding(8);
layout.addMember(logo);
layout.addMember(loginForm);
final LayoutSpacer spacer = new LayoutSpacer();
spacer.setHeight(3);
layout.addMember(spacer);
layout.addMember(loginButton);
this.addCanvasToRootPanel(layout);
}
/**
*
* @param authContext
*/
public void loadMainPageOnLoginSuccess(AuthenticationContext authContext) {
controller.setAuthContext(authContext);
if (authContext.getSuccessStatus() == true) {
loadMainPage();
} else {
// Login failure.
SC.warn("Invalid User ID and/or Password. Please check your credentials and try again.");
}
}
/**
*
*/
public void loadMainPage() {
// Create the ToolStrip.
final ToolStrip toolStrip = this.createToolStrip();
// Configure the content pane.
mainCanvas.setWidth100();
mainCanvas.setHeight100();
controller.setMainCanvas(mainCanvas);
// Create the layout.
final VLayout vLayout = new VLayout();
vLayout.setWidth("98%");
vLayout.setHeight("98%");
vLayout.setAlign(Alignment.CENTER);
// Add members to the layout.
vLayout.addMember(toolStrip);
final LayoutSpacer spacer = new LayoutSpacer();
spacer.setHeight(4);
vLayout.addMember(spacer);
vLayout.addMember(mainCanvas);
this.addCanvasToRootPanel(vLayout);
// Show the find patients view.
controller.showFindPatients();
}
/**
*
* @param canvas
*/
private void addCanvasToRootPanel(Canvas canvas) {
final RootPanel rootPanel = RootPanel.get();
// Remove old canvas (if exists).
if (currentCanvas != null) {
rootPanel.remove(currentCanvas);
}
currentCanvas = canvas;
rootPanel.add(canvas);
// Remove loading wrapper (established in host HTML page).
final RootPanel loadingWrapper = RootPanel.get("loadingWrapper");
if (loadingWrapper != null) {
RootPanel.getBodyElement().removeChild(loadingWrapper.getElement());
}
}
/**
*
* @return
*/
private ToolStrip createToolStrip() {
// Create the "Find Patient" button.
final ToolStripButton findPatientButton = new ToolStripButton();
findPatientButton.setTitle("Find Patients");
findPatientButton.setTooltip("Search network for available patients");
findPatientButton.setIcon("person.png");
findPatientButton
.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
public void onClick(ClickEvent event) {
controller.showFindPatients();
}
});
// Create the "Show Documents" button.
final ToolStripButton showDocumentsButton = new ToolStripButton();
showDocumentsButton.setTitle("Show Documents");
showDocumentsButton
.setTooltip("Show documents for patients already selected");
showDocumentsButton.setIcon("document.png");
showDocumentsButton
.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
public void onClick(ClickEvent event) {
controller.showPatients();
}
});
// Create the "Patient Consent" button.
final ToolStripButton patientConsentButton = new ToolStripButton();
patientConsentButton.setTitle("Patient Consent");
patientConsentButton.setTooltip("Add/Update Patient Consent");
patientConsentButton.setIcon("privacy.png");
patientConsentButton
.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
public void onClick(ClickEvent event) {
- SC.warn("Under construction");
+ SC.warn("Under construction!");
}
});
// Create "Find Documents" button.
final ToolStripButton findDocumentsButton = new ToolStripButton();
findDocumentsButton.setTooltip("Find documents given a patient id");
findDocumentsButton.setTitle("Find Documents");
findDocumentsButton.setIcon("document.png");
findDocumentsButton
.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
public void onClick(ClickEvent event) {
// SC.showConsole();
final PatientIDValueCallback callback = new PatientIDValueCallback(
controller);
SC.askforValue("Find Documents", "Patient ID:",
callback);
}
});
// Create "Logout" button.
final ToolStripButton logoutButton = new ToolStripButton();
logoutButton.setTooltip("Logout");
logoutButton.setTitle("Logout");
logoutButton.setIcon("logout.png");
logoutButton
.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
public void onClick(ClickEvent event) {
// Clear the authentication Context
controller.setAuthContext(null);
// Load the Login page
loadLoginPage();
}
});
// Title:
final Label title = new Label("HIEOS DocViewer");
title.setWidth(120);
title.setIcon("application.png");
// Now create the tool strip (that holds the buttons).
final ToolStrip toolStrip = new ToolStrip();
toolStrip.setHeight(30);
toolStrip.setWidth100();
// Layout the tool strip.
toolStrip.addSpacer(5);
toolStrip.addMember(title);
toolStrip.addSeparator();
toolStrip.addButton(findPatientButton);
toolStrip.addButton(showDocumentsButton);
toolStrip.addButton(patientConsentButton);
toolStrip.addButton(findDocumentsButton);
toolStrip.addFill();
toolStrip.addButton(logoutButton);
return toolStrip;
}
/**
*
* @author Bernie Thuman
*
*/
public class PatientIDValueCallback implements ValueCallback {
private DocViewerController controller;
/**
*
* @param controller
*/
PatientIDValueCallback(DocViewerController controller) {
this.controller = controller;
}
@Override
public void execute(String patientID) {
// TODO Auto-generated method stub
if (patientID == null || patientID.length() == 0) {
// Nothing to do.
// SC.say("Nothing to do ...");
return;
}
// SC.say("Patient ID entered = " + patientID);
boolean validFormat = PatientUtil
.validatePIDStringFormat(patientID);
if (validFormat != true) {
SC.warn("Patient ID must be in <b>EUID</b>^^^&<b>UNIVERSAL_ID</b>&ISO format");
return;
}
// Create patient instance -- just with patient id.
final Patient patient = new Patient();
patient.setEuid(PatientUtil.getIDFromPIDString(patientID));
patient.setEuidUniversalID(PatientUtil
.getUniversalIDFromPIDString(patientID));
patient.setFamilyName(null);
patient.setGivenName(null);
patient.setGender(null);
patient.setDateOfBirth(null);
patient.setSSN("N/A");
patient.setMatchConfidencePercentage(100);
// Now do the document search.
final PatientRecord patientRecord = new PatientRecord(patient);
controller.findDocuments(patientRecord);
}
}
}
| true | true | private ToolStrip createToolStrip() {
// Create the "Find Patient" button.
final ToolStripButton findPatientButton = new ToolStripButton();
findPatientButton.setTitle("Find Patients");
findPatientButton.setTooltip("Search network for available patients");
findPatientButton.setIcon("person.png");
findPatientButton
.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
public void onClick(ClickEvent event) {
controller.showFindPatients();
}
});
// Create the "Show Documents" button.
final ToolStripButton showDocumentsButton = new ToolStripButton();
showDocumentsButton.setTitle("Show Documents");
showDocumentsButton
.setTooltip("Show documents for patients already selected");
showDocumentsButton.setIcon("document.png");
showDocumentsButton
.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
public void onClick(ClickEvent event) {
controller.showPatients();
}
});
// Create the "Patient Consent" button.
final ToolStripButton patientConsentButton = new ToolStripButton();
patientConsentButton.setTitle("Patient Consent");
patientConsentButton.setTooltip("Add/Update Patient Consent");
patientConsentButton.setIcon("privacy.png");
patientConsentButton
.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
public void onClick(ClickEvent event) {
SC.warn("Under construction");
}
});
// Create "Find Documents" button.
final ToolStripButton findDocumentsButton = new ToolStripButton();
findDocumentsButton.setTooltip("Find documents given a patient id");
findDocumentsButton.setTitle("Find Documents");
findDocumentsButton.setIcon("document.png");
findDocumentsButton
.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
public void onClick(ClickEvent event) {
// SC.showConsole();
final PatientIDValueCallback callback = new PatientIDValueCallback(
controller);
SC.askforValue("Find Documents", "Patient ID:",
callback);
}
});
// Create "Logout" button.
final ToolStripButton logoutButton = new ToolStripButton();
logoutButton.setTooltip("Logout");
logoutButton.setTitle("Logout");
logoutButton.setIcon("logout.png");
logoutButton
.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
public void onClick(ClickEvent event) {
// Clear the authentication Context
controller.setAuthContext(null);
// Load the Login page
loadLoginPage();
}
});
// Title:
final Label title = new Label("HIEOS DocViewer");
title.setWidth(120);
title.setIcon("application.png");
// Now create the tool strip (that holds the buttons).
final ToolStrip toolStrip = new ToolStrip();
toolStrip.setHeight(30);
toolStrip.setWidth100();
// Layout the tool strip.
toolStrip.addSpacer(5);
toolStrip.addMember(title);
toolStrip.addSeparator();
toolStrip.addButton(findPatientButton);
toolStrip.addButton(showDocumentsButton);
toolStrip.addButton(patientConsentButton);
toolStrip.addButton(findDocumentsButton);
toolStrip.addFill();
toolStrip.addButton(logoutButton);
return toolStrip;
}
| private ToolStrip createToolStrip() {
// Create the "Find Patient" button.
final ToolStripButton findPatientButton = new ToolStripButton();
findPatientButton.setTitle("Find Patients");
findPatientButton.setTooltip("Search network for available patients");
findPatientButton.setIcon("person.png");
findPatientButton
.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
public void onClick(ClickEvent event) {
controller.showFindPatients();
}
});
// Create the "Show Documents" button.
final ToolStripButton showDocumentsButton = new ToolStripButton();
showDocumentsButton.setTitle("Show Documents");
showDocumentsButton
.setTooltip("Show documents for patients already selected");
showDocumentsButton.setIcon("document.png");
showDocumentsButton
.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
public void onClick(ClickEvent event) {
controller.showPatients();
}
});
// Create the "Patient Consent" button.
final ToolStripButton patientConsentButton = new ToolStripButton();
patientConsentButton.setTitle("Patient Consent");
patientConsentButton.setTooltip("Add/Update Patient Consent");
patientConsentButton.setIcon("privacy.png");
patientConsentButton
.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
public void onClick(ClickEvent event) {
SC.warn("Under construction!");
}
});
// Create "Find Documents" button.
final ToolStripButton findDocumentsButton = new ToolStripButton();
findDocumentsButton.setTooltip("Find documents given a patient id");
findDocumentsButton.setTitle("Find Documents");
findDocumentsButton.setIcon("document.png");
findDocumentsButton
.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
public void onClick(ClickEvent event) {
// SC.showConsole();
final PatientIDValueCallback callback = new PatientIDValueCallback(
controller);
SC.askforValue("Find Documents", "Patient ID:",
callback);
}
});
// Create "Logout" button.
final ToolStripButton logoutButton = new ToolStripButton();
logoutButton.setTooltip("Logout");
logoutButton.setTitle("Logout");
logoutButton.setIcon("logout.png");
logoutButton
.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler() {
public void onClick(ClickEvent event) {
// Clear the authentication Context
controller.setAuthContext(null);
// Load the Login page
loadLoginPage();
}
});
// Title:
final Label title = new Label("HIEOS DocViewer");
title.setWidth(120);
title.setIcon("application.png");
// Now create the tool strip (that holds the buttons).
final ToolStrip toolStrip = new ToolStrip();
toolStrip.setHeight(30);
toolStrip.setWidth100();
// Layout the tool strip.
toolStrip.addSpacer(5);
toolStrip.addMember(title);
toolStrip.addSeparator();
toolStrip.addButton(findPatientButton);
toolStrip.addButton(showDocumentsButton);
toolStrip.addButton(patientConsentButton);
toolStrip.addButton(findDocumentsButton);
toolStrip.addFill();
toolStrip.addButton(logoutButton);
return toolStrip;
}
|
diff --git a/src/main/org/hornetq/ra/HornetQRASessionFactoryImpl.java b/src/main/org/hornetq/ra/HornetQRASessionFactoryImpl.java
index 16da2b071..31a0ec82f 100644
--- a/src/main/org/hornetq/ra/HornetQRASessionFactoryImpl.java
+++ b/src/main/org/hornetq/ra/HornetQRASessionFactoryImpl.java
@@ -1,1071 +1,1072 @@
/*
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
*
* 1. Definitions.
*
* "License" shall mean the terms and conditions for use, reproduction,
* and distribution as defined by Sections 1 through 9 of this document.
*
* "Licensor" shall mean the copyright owner or entity authorized by
* the copyright owner that is granting the License.
*
* "Legal Entity" shall mean the union of the acting entity and all
* other entities that control, are controlled by, or are under common
* control with that entity. For the purposes of this definition,
* "control" means (i) the power, direct or indirect, to cause the
* direction or management of such entity, whether by contract or
* otherwise, or (ii) ownership of fifty percent (50%) or more of the
* outstanding shares, or (iii) beneficial ownership of such entity.
*
* "You" (or "Your") shall mean an individual or Legal Entity
* exercising permissions granted by this License.
*
* "Source" form shall mean the preferred form for making modifications,
* including but not limited to software source code, documentation
* source, and configuration files.
*
* "Object" form shall mean any form resulting from mechanical
* transformation or translation of a Source form, including but
* not limited to compiled object code, generated documentation,
* and conversions to other media types.
*
* "Work" shall mean the work of authorship, whether in Source or
* Object form, made available under the License, as indicated by a
* copyright notice that is included in or attached to the work
* (an example is provided in the Appendix below).
*
* "Derivative Works" shall mean any work, whether in Source or Object
* form, that is based on (or derived from) the Work and for which the
* editorial revisions, annotations, elaborations, or other modifications
* represent, as a whole, an original work of authorship. For the purposes
* of this License, Derivative Works shall not include works that remain
* separable from, or merely link (or bind by name) to the interfaces of,
* the Work and Derivative Works thereof.
*
* "Contribution" shall mean any work of authorship, including
* the original version of the Work and any modifications or additions
* to that Work or Derivative Works thereof, that is intentionally
* submitted to Licensor for inclusion in the Work by the copyright owner
* or by an individual or Legal Entity authorized to submit on behalf of
* the copyright owner. For the purposes of this definition, "submitted"
* means any form of electronic, verbal, or written communication sent
* to the Licensor or its representatives, including but not limited to
* communication on electronic mailing lists, source code control systems,
* and issue tracking systems that are managed by, or on behalf of, the
* Licensor for the purpose of discussing and improving the Work, but
* excluding communication that is conspicuously marked or otherwise
* designated in writing by the copyright owner as "Not a Contribution."
*
* "Contributor" shall mean Licensor and any individual or Legal Entity
* on behalf of whom a Contribution has been received by Licensor and
* subsequently incorporated within the Work.
*
* 2. Grant of Copyright License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* copyright license to reproduce, prepare Derivative Works of,
* publicly display, publicly perform, sublicense, and distribute the
* Work and such Derivative Works in Source or Object form.
*
* 3. Grant of Patent License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* (except as stated in this section) patent license to make, have made,
* use, offer to sell, sell, import, and otherwise transfer the Work,
* where such license applies only to those patent claims licensable
* by such Contributor that are necessarily infringed by their
* Contribution(s) alone or by combination of their Contribution(s)
* with the Work to which such Contribution(s) was submitted. If You
* institute patent litigation against any entity (including a
* cross-claim or counterclaim in a lawsuit) alleging that the Work
* or a Contribution incorporated within the Work constitutes direct
* or contributory patent infringement, then any patent licenses
* granted to You under this License for that Work shall terminate
* as of the date such litigation is filed.
*
* 4. Redistribution. You may reproduce and distribute copies of the
* Work or Derivative Works thereof in any medium, with or without
* modifications, and in Source or Object form, provided that You
* meet the following conditions:
*
* (a) You must give any other recipients of the Work or
* Derivative Works a copy of this License; and
*
* (b) You must cause any modified files to carry prominent notices
* stating that You changed the files; and
*
* (c) You must retain, in the Source form of any Derivative Works
* that You distribute, all copyright, patent, trademark, and
* attribution notices from the Source form of the Work,
* excluding those notices that do not pertain to any part of
* the Derivative Works; and
*
* (d) If the Work includes a "NOTICE" text file as part of its
* distribution, then any Derivative Works that You distribute must
* include a readable copy of the attribution notices contained
* within such NOTICE file, excluding those notices that do not
* pertain to any part of the Derivative Works, in at least one
* of the following places: within a NOTICE text file distributed
* as part of the Derivative Works; within the Source form or
* documentation, if provided along with the Derivative Works; or,
* within a display generated by the Derivative Works, if and
* wherever such third-party notices normally appear. The contents
* of the NOTICE file are for informational purposes only and
* do not modify the License. You may add Your own attribution
* notices within Derivative Works that You distribute, alongside
* or as an addendum to the NOTICE text from the Work, provided
* that such additional attribution notices cannot be construed
* as modifying the License.
*
* You may add Your own copyright statement to Your modifications and
* may provide additional or different license terms and conditions
* for use, reproduction, or distribution of Your modifications, or
* for any such Derivative Works as a whole, provided Your use,
* reproduction, and distribution of the Work otherwise complies with
* the conditions stated in this License.
*
* 5. Submission of Contributions. Unless You explicitly state otherwise,
* any Contribution intentionally submitted for inclusion in the Work
* by You to the Licensor shall be under the terms and conditions of
* this License, without any additional terms or conditions.
* Notwithstanding the above, nothing herein shall supersede or modify
* the terms of any separate license agreement you may have executed
* with Licensor regarding such Contributions.
*
* 6. Trademarks. This License does not grant permission to use the trade
* names, trademarks, service marks, or product names of the Licensor,
* except as required for reasonable and customary use in describing the
* origin of the Work and reproducing the content of the NOTICE file.
*
* 7. Disclaimer of Warranty. Unless required by applicable law or
* agreed to in writing, Licensor provides the Work (and each
* Contributor provides its Contributions) on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied, including, without limitation, any warranties or conditions
* of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
* PARTICULAR PURPOSE. You are solely responsible for determining the
* appropriateness of using or redistributing the Work and assume any
* risks associated with Your exercise of permissions under this License.
*
* 8. Limitation of Liability. In no event and under no legal theory,
* whether in tort (including negligence), contract, or otherwise,
* unless required by applicable law (such as deliberate and grossly
* negligent acts) or agreed to in writing, shall any Contributor be
* liable to You for damages, including any direct, indirect, special,
* incidental, or consequential damages of any character arising as a
* result of this License or out of the use or inability to use the
* Work (including but not limited to damages for loss of goodwill,
* work stoppage, computer failure or malfunction, or any and all
* other commercial damages or losses), even if such Contributor
* has been advised of the possibility of such damages.
*
* 9. Accepting Warranty or Additional Liability. While redistributing
* the Work or Derivative Works thereof, You may choose to offer,
* and charge a fee for, acceptance of support, warranty, indemnity,
* or other liability obligations and/or rights consistent with this
* License. However, in accepting such obligations, You may act only
* on Your own behalf and on Your sole responsibility, not on behalf
* of any other Contributor, and only if You agree to indemnify,
* defend, and hold each Contributor harmless for any liability
* incurred by, or claims asserted against, such Contributor by reason
* of your accepting any such warranty or additional liability.
*
* END OF TERMS AND CONDITIONS
*
* APPENDIX: How to apply the Apache License to your work.
*
* To apply the Apache License to your work, attach the following
* boilerplate notice, with the fields enclosed by brackets "[]"
* replaced with your own identifying information. (Don't include
* the brackets!) The text should be enclosed in the appropriate
* comment syntax for the file format. We also recommend that a
* file or class name and description of purpose be included on the
* same "printed page" as the copyright notice for easier
* identification within third-party archives.
*
* Copyright [yyyy] [name of copyright owner]
*
* 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.hornetq.ra;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.jms.ConnectionConsumer;
import javax.jms.ConnectionMetaData;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.IllegalStateException;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueSession;
import javax.jms.ServerSessionPool;
import javax.jms.Session;
import javax.jms.TemporaryQueue;
import javax.jms.TemporaryTopic;
import javax.jms.Topic;
import javax.jms.TopicSession;
import javax.jms.XAQueueSession;
import javax.jms.XASession;
import javax.jms.XATopicSession;
import javax.naming.Reference;
import javax.resource.Referenceable;
import javax.resource.spi.ConnectionManager;
import org.hornetq.core.logging.Logger;
/**
* Implements the JMS Connection API and produces {@link HornetQRASession} objects.
*
* @author <a href="mailto:[email protected]">Adrian Brock</a>
* @author <a href="mailto:[email protected]">Jesper Pedersen</a>
* @version $Revision: $
*/
public class HornetQRASessionFactoryImpl implements HornetQRASessionFactory, Referenceable
{
/** The logger */
private static final Logger log = Logger.getLogger(HornetQRASessionFactoryImpl.class);
/** Trace enabled */
private static boolean trace = log.isTraceEnabled();
/** Are we closed? */
private boolean closed = false;
/** The naming reference */
private Reference reference;
/** The user name */
private String userName;
/** The password */
private String password;
/** The client ID */
private String clientID;
/** The connection type */
private final int type;
/** Whether we are started */
private boolean started = false;
/** The managed connection factory */
private final HornetQRAManagedConnectionFactory mcf;
/** The connection manager */
private ConnectionManager cm;
/** The sessions */
private final Set sessions = new HashSet();
/** The temporary queues */
private final Set tempQueues = new HashSet();
/** The temporary topics */
private final Set tempTopics = new HashSet();
/**
* Constructor
* @param mcf The managed connection factory
* @param cm The connection manager
* @param type The connection type
*/
public HornetQRASessionFactoryImpl(final HornetQRAManagedConnectionFactory mcf, final ConnectionManager cm, final int type)
{
this.mcf = mcf;
if (cm == null)
{
this.cm = new HornetQRAConnectionManager();
}
else
{
this.cm = cm;
}
this.type = type;
if (trace)
{
log.trace("constructor(" + mcf + ", " + cm + ", " + type);
}
}
/**
* Set the naming reference
* @param reference The reference
*/
public void setReference(final Reference reference)
{
if (trace)
{
log.trace("setReference(" + reference + ")");
}
this.reference = reference;
}
/**
* Get the naming reference
* @return The reference
*/
public Reference getReference()
{
if (trace)
{
log.trace("getReference()");
}
return reference;
}
/**
* Set the user name
* @param name The user name
*/
public void setUserName(final String name)
{
if (trace)
{
log.trace("setUserName(" + name + ")");
}
userName = name;
}
/**
* Set the password
* @param password The password
*/
public void setPassword(final String password)
{
if (trace)
{
log.trace("setPassword(****)");
}
this.password = password;
}
/**
* Get the client ID
* @return The client ID
* @exception JMSException Thrown if an error occurs
*/
public String getClientID() throws JMSException
{
if (trace)
{
log.trace("getClientID()");
}
checkClosed();
if (clientID == null)
{
return ((HornetQResourceAdapter)mcf.getResourceAdapter()).getProperties().getClientID();
}
return clientID;
}
/**
* Set the client ID -- throws IllegalStateException
* @param cID The client ID
* @exception JMSException Thrown if an error occurs
*/
public void setClientID(final String cID) throws JMSException
{
if (trace)
{
log.trace("setClientID(" + cID + ")");
}
throw new IllegalStateException(ISE);
}
/**
* Create a queue session
* @param transacted Use transactions
* @param acknowledgeMode The acknowledge mode
* @return The queue session
* @exception JMSException Thrown if an error occurs
*/
public QueueSession createQueueSession(final boolean transacted, final int acknowledgeMode) throws JMSException
{
if (trace)
{
log.trace("createQueueSession(" + transacted + ", " + acknowledgeMode + ")");
}
checkClosed();
if (type == HornetQRAConnectionFactory.TOPIC_CONNECTION || type == HornetQRAConnectionFactory.XA_TOPIC_CONNECTION)
{
throw new IllegalStateException("Can not get a queue session from a topic connection");
}
return allocateConnection(transacted, acknowledgeMode, type);
}
/**
* Create a XA queue session
* @return The XA queue session
* @exception JMSException Thrown if an error occurs
*/
public XAQueueSession createXAQueueSession() throws JMSException
{
if (trace)
{
log.trace("createXAQueueSession()");
}
checkClosed();
if (type == HornetQRAConnectionFactory.CONNECTION || type == HornetQRAConnectionFactory.TOPIC_CONNECTION ||
type == HornetQRAConnectionFactory.XA_TOPIC_CONNECTION)
{
throw new IllegalStateException("Can not get a topic session from a queue connection");
}
return allocateConnection(type);
}
/**
* Create a connection consumer -- throws IllegalStateException
* @param queue The queue
* @param messageSelector The message selector
* @param sessionPool The session pool
* @param maxMessages The number of max messages
* @return The connection consumer
* @exception JMSException Thrown if an error occurs
*/
public ConnectionConsumer createConnectionConsumer(final Queue queue,
final String messageSelector,
final ServerSessionPool sessionPool,
final int maxMessages) throws JMSException
{
if (trace)
{
log.trace("createConnectionConsumer(" + queue +
", " +
messageSelector +
", " +
sessionPool +
", " +
maxMessages +
")");
}
throw new IllegalStateException(ISE);
}
/**
* Create a topic session
* @param transacted Use transactions
* @param acknowledgeMode The acknowledge mode
* @return The topic session
* @exception JMSException Thrown if an error occurs
*/
public TopicSession createTopicSession(final boolean transacted, final int acknowledgeMode) throws JMSException
{
if (trace)
{
log.trace("createTopicSession(" + transacted + ", " + acknowledgeMode + ")");
}
checkClosed();
if (type == HornetQRAConnectionFactory.QUEUE_CONNECTION || type == HornetQRAConnectionFactory.XA_QUEUE_CONNECTION)
{
throw new IllegalStateException("Can not get a topic session from a queue connection");
}
return allocateConnection(transacted, acknowledgeMode, type);
}
/**
* Create a XA topic session
* @return The XA topic session
* @exception JMSException Thrown if an error occurs
*/
public XATopicSession createXATopicSession() throws JMSException
{
if (trace)
{
log.trace("createXATopicSession()");
}
checkClosed();
if (type == HornetQRAConnectionFactory.CONNECTION || type == HornetQRAConnectionFactory.QUEUE_CONNECTION ||
type == HornetQRAConnectionFactory.XA_QUEUE_CONNECTION)
{
throw new IllegalStateException("Can not get a topic session from a queue connection");
}
return allocateConnection(type);
}
/**
* Create a connection consumer -- throws IllegalStateException
* @param topic The topic
* @param messageSelector The message selector
* @param sessionPool The session pool
* @param maxMessages The number of max messages
* @return The connection consumer
* @exception JMSException Thrown if an error occurs
*/
public ConnectionConsumer createConnectionConsumer(final Topic topic,
final String messageSelector,
final ServerSessionPool sessionPool,
final int maxMessages) throws JMSException
{
if (trace)
{
log.trace("createConnectionConsumer(" + topic +
", " +
messageSelector +
", " +
sessionPool +
", " +
maxMessages +
")");
}
throw new IllegalStateException(ISE);
}
/**
* Create a durable connection consumer -- throws IllegalStateException
* @param topic The topic
* @param subscriptionName The subscription name
* @param messageSelector The message selector
* @param sessionPool The session pool
* @param maxMessages The number of max messages
* @return The connection consumer
* @exception JMSException Thrown if an error occurs
*/
public ConnectionConsumer createDurableConnectionConsumer(final Topic topic,
final String subscriptionName,
final String messageSelector,
final ServerSessionPool sessionPool,
final int maxMessages) throws JMSException
{
if (trace)
{
log.trace("createConnectionConsumer(" + topic +
", " +
subscriptionName +
", " +
messageSelector +
", " +
sessionPool +
", " +
maxMessages +
")");
}
throw new IllegalStateException(ISE);
}
/**
* Create a connection consumer -- throws IllegalStateException
* @param destination The destination
* @param pool The session pool
* @param maxMessages The number of max messages
* @return The connection consumer
* @exception JMSException Thrown if an error occurs
*/
public ConnectionConsumer createConnectionConsumer(final Destination destination,
final ServerSessionPool pool,
final int maxMessages) throws JMSException
{
if (trace)
{
log.trace("createConnectionConsumer(" + destination + ", " + pool + ", " + maxMessages + ")");
}
throw new IllegalStateException(ISE);
}
/**
* Create a connection consumer -- throws IllegalStateException
* @param destination The destination
* @param name The name
* @param pool The session pool
* @param maxMessages The number of max messages
* @return The connection consumer
* @exception JMSException Thrown if an error occurs
*/
public ConnectionConsumer createConnectionConsumer(final Destination destination,
final String name,
final ServerSessionPool pool,
final int maxMessages) throws JMSException
{
if (trace)
{
log.trace("createConnectionConsumer(" + destination + ", " + name + ", " + pool + ", " + maxMessages + ")");
}
throw new IllegalStateException(ISE);
}
/**
* Create a session
* @param transacted Use transactions
* @param acknowledgeMode The acknowledge mode
* @return The session
* @exception JMSException Thrown if an error occurs
*/
public Session createSession(final boolean transacted, final int acknowledgeMode) throws JMSException
{
if (trace)
{
log.trace("createSession(" + transacted + ", " + acknowledgeMode + ")");
}
checkClosed();
return allocateConnection(transacted, acknowledgeMode, type);
}
/**
* Create a XA session
* @return The XA session
* @exception JMSException Thrown if an error occurs
*/
public XASession createXASession() throws JMSException
{
if (trace)
{
log.trace("createXASession()");
}
checkClosed();
return allocateConnection(type);
}
/**
* Get the connection metadata
* @return The connection metadata
* @exception JMSException Thrown if an error occurs
*/
public ConnectionMetaData getMetaData() throws JMSException
{
if (trace)
{
log.trace("getMetaData()");
}
checkClosed();
return mcf.getMetaData();
}
/**
* Get the exception listener -- throws IllegalStateException
* @return The exception listener
* @exception JMSException Thrown if an error occurs
*/
public ExceptionListener getExceptionListener() throws JMSException
{
if (trace)
{
log.trace("getExceptionListener()");
}
throw new IllegalStateException(ISE);
}
/**
* Set the exception listener -- throws IllegalStateException
* @param listener The exception listener
* @exception JMSException Thrown if an error occurs
*/
public void setExceptionListener(final ExceptionListener listener) throws JMSException
{
if (trace)
{
log.trace("setExceptionListener(" + listener + ")");
}
throw new IllegalStateException(ISE);
}
/**
* Start
* @exception JMSException Thrown if an error occurs
*/
public void start() throws JMSException
{
checkClosed();
if (trace)
{
log.trace("start() " + this);
}
synchronized (sessions)
{
if (started)
{
return;
}
started = true;
for (Iterator i = sessions.iterator(); i.hasNext();)
{
HornetQRASession session = (HornetQRASession)i.next();
session.start();
}
}
}
/**
* Stop -- throws IllegalStateException
* @exception JMSException Thrown if an error occurs
*/
public void stop() throws JMSException
{
if (trace)
{
log.trace("stop() " + this);
}
throw new IllegalStateException(ISE);
}
/**
* Close
* @exception JMSException Thrown if an error occurs
*/
public void close() throws JMSException
{
if (trace)
{
log.trace("close() " + this);
}
if (closed)
{
return;
}
closed = true;
synchronized (sessions)
{
for (Iterator i = sessions.iterator(); i.hasNext();)
{
HornetQRASession session = (HornetQRASession)i.next();
try
{
session.closeSession();
}
catch (Throwable t)
{
log.trace("Error closing session", t);
}
i.remove();
}
}
synchronized (tempQueues)
{
for (Iterator i = tempQueues.iterator(); i.hasNext();)
{
TemporaryQueue temp = (TemporaryQueue)i.next();
try
{
if (trace)
{
log.trace("Closing temporary queue " + temp + " for " + this);
}
temp.delete();
}
catch (Throwable t)
{
log.trace("Error deleting temporary queue", t);
}
i.remove();
}
}
synchronized (tempTopics)
{
for (Iterator i = tempTopics.iterator(); i.hasNext();)
{
TemporaryTopic temp = (TemporaryTopic)i.next();
try
{
if (trace)
{
log.trace("Closing temporary topic " + temp + " for " + this);
}
temp.delete();
}
catch (Throwable t)
{
log.trace("Error deleting temporary queue", t);
}
i.remove();
}
}
}
/**
* Close session
* @param session The session
* @exception JMSException Thrown if an error occurs
*/
public void closeSession(final HornetQRASession session) throws JMSException
{
if (trace)
{
log.trace("closeSession(" + session + ")");
}
synchronized (sessions)
{
sessions.remove(session);
}
}
/**
* Add temporary queue
* @param temp The temporary queue
*/
public void addTemporaryQueue(final TemporaryQueue temp)
{
if (trace)
{
log.trace("addTemporaryQueue(" + temp + ")");
}
synchronized (tempQueues)
{
tempQueues.add(temp);
}
}
/**
* Add temporary topic
* @param temp The temporary topic
*/
public void addTemporaryTopic(final TemporaryTopic temp)
{
if (trace)
{
log.trace("addTemporaryTopic(" + temp + ")");
}
synchronized (tempTopics)
{
tempTopics.add(temp);
}
}
/**
* Allocation a connection
* @param sessionType The session type
* @return The session
* @exception JMSException Thrown if an error occurs
*/
protected HornetQRASession allocateConnection(final int sessionType) throws JMSException
{
if (trace)
{
log.trace("allocateConnection(" + sessionType + ")");
}
try
{
synchronized (sessions)
{
if (sessions.isEmpty() == false)
{
throw new IllegalStateException("Only allowed one session per connection. See the J2EE spec, e.g. J2EE1.4 Section 6.6");
}
HornetQRAConnectionRequestInfo info = new HornetQRAConnectionRequestInfo(sessionType);
info.setUserName(userName);
info.setPassword(password);
info.setClientID(clientID);
info.setDefaults(((HornetQResourceAdapter)mcf.getResourceAdapter()).getProperties());
if (trace)
{
log.trace("Allocating session for " + this + " with request info=" + info);
}
HornetQRASession session = (HornetQRASession)cm.allocateConnection(mcf, info);
try
{
if (trace)
{
log.trace("Allocated " + this + " session=" + session);
}
session.setHornetQSessionFactory(this);
if (started)
{
session.start();
}
sessions.add(session);
return session;
}
catch (Throwable t)
{
try
{
session.close();
}
catch (Throwable ignored)
{
}
if (t instanceof Exception)
{
throw (Exception)t;
}
else
{
throw new RuntimeException("Unexpected error: ", t);
}
}
}
}
catch (Exception e)
{
log.error("Could not create session", e);
JMSException je = new JMSException("Could not create a session: " + e.getMessage());
je.setLinkedException(e);
throw je;
}
}
/**
* Allocation a connection
* @param transacted Use transactions
* @param acknowledgeMode The acknowledge mode
* @param sessionType The session type
* @return The session
* @exception JMSException Thrown if an error occurs
*/
protected HornetQRASession allocateConnection(final boolean transacted, int acknowledgeMode, final int sessionType) throws JMSException
{
if (trace)
{
log.trace("allocateConnection(" + transacted + ", " + acknowledgeMode + ", " + sessionType + ")");
}
try
{
synchronized (sessions)
{
if (sessions.isEmpty() == false)
{
throw new IllegalStateException("Only allowed one session per connection. See the J2EE spec, e.g. J2EE1.4 Section 6.6");
}
if (transacted)
{
acknowledgeMode = Session.SESSION_TRANSACTED;
}
HornetQRAConnectionRequestInfo info = new HornetQRAConnectionRequestInfo(transacted, acknowledgeMode, sessionType);
info.setUserName(userName);
info.setPassword(password);
info.setClientID(clientID);
+ info.setDefaults(((HornetQResourceAdapter)mcf.getResourceAdapter()).getProperties());
if (trace)
{
log.trace("Allocating session for " + this + " with request info=" + info);
}
HornetQRASession session = (HornetQRASession)cm.allocateConnection(mcf, info);
try
{
if (trace)
{
log.trace("Allocated " + this + " session=" + session);
}
session.setHornetQSessionFactory(this);
if (started)
{
session.start();
}
sessions.add(session);
return session;
}
catch (Throwable t)
{
try
{
session.close();
}
catch (Throwable ignored)
{
}
if (t instanceof Exception)
{
throw (Exception)t;
}
else
{
throw new RuntimeException("Unexpected error: ", t);
}
}
}
}
catch (Exception e)
{
log.error("Could not create session", e);
JMSException je = new JMSException("Could not create a session: " + e.getMessage());
je.setLinkedException(e);
throw je;
}
}
/**
* Check if we are closed
* @exception IllegalStateException Thrown if closed
*/
protected void checkClosed() throws IllegalStateException
{
if (trace)
{
log.trace("checkClosed()" + this);
}
if (closed)
{
throw new IllegalStateException("The connection is closed");
}
}
}
| true | true | protected HornetQRASession allocateConnection(final boolean transacted, int acknowledgeMode, final int sessionType) throws JMSException
{
if (trace)
{
log.trace("allocateConnection(" + transacted + ", " + acknowledgeMode + ", " + sessionType + ")");
}
try
{
synchronized (sessions)
{
if (sessions.isEmpty() == false)
{
throw new IllegalStateException("Only allowed one session per connection. See the J2EE spec, e.g. J2EE1.4 Section 6.6");
}
if (transacted)
{
acknowledgeMode = Session.SESSION_TRANSACTED;
}
HornetQRAConnectionRequestInfo info = new HornetQRAConnectionRequestInfo(transacted, acknowledgeMode, sessionType);
info.setUserName(userName);
info.setPassword(password);
info.setClientID(clientID);
if (trace)
{
log.trace("Allocating session for " + this + " with request info=" + info);
}
HornetQRASession session = (HornetQRASession)cm.allocateConnection(mcf, info);
try
{
if (trace)
{
log.trace("Allocated " + this + " session=" + session);
}
session.setHornetQSessionFactory(this);
if (started)
{
session.start();
}
sessions.add(session);
return session;
}
catch (Throwable t)
{
try
{
session.close();
}
catch (Throwable ignored)
{
}
if (t instanceof Exception)
{
throw (Exception)t;
}
else
{
throw new RuntimeException("Unexpected error: ", t);
}
}
}
}
catch (Exception e)
{
log.error("Could not create session", e);
JMSException je = new JMSException("Could not create a session: " + e.getMessage());
je.setLinkedException(e);
throw je;
}
}
| protected HornetQRASession allocateConnection(final boolean transacted, int acknowledgeMode, final int sessionType) throws JMSException
{
if (trace)
{
log.trace("allocateConnection(" + transacted + ", " + acknowledgeMode + ", " + sessionType + ")");
}
try
{
synchronized (sessions)
{
if (sessions.isEmpty() == false)
{
throw new IllegalStateException("Only allowed one session per connection. See the J2EE spec, e.g. J2EE1.4 Section 6.6");
}
if (transacted)
{
acknowledgeMode = Session.SESSION_TRANSACTED;
}
HornetQRAConnectionRequestInfo info = new HornetQRAConnectionRequestInfo(transacted, acknowledgeMode, sessionType);
info.setUserName(userName);
info.setPassword(password);
info.setClientID(clientID);
info.setDefaults(((HornetQResourceAdapter)mcf.getResourceAdapter()).getProperties());
if (trace)
{
log.trace("Allocating session for " + this + " with request info=" + info);
}
HornetQRASession session = (HornetQRASession)cm.allocateConnection(mcf, info);
try
{
if (trace)
{
log.trace("Allocated " + this + " session=" + session);
}
session.setHornetQSessionFactory(this);
if (started)
{
session.start();
}
sessions.add(session);
return session;
}
catch (Throwable t)
{
try
{
session.close();
}
catch (Throwable ignored)
{
}
if (t instanceof Exception)
{
throw (Exception)t;
}
else
{
throw new RuntimeException("Unexpected error: ", t);
}
}
}
}
catch (Exception e)
{
log.error("Could not create session", e);
JMSException je = new JMSException("Could not create a session: " + e.getMessage());
je.setLinkedException(e);
throw je;
}
}
|
diff --git a/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java b/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java
index 2ef58357b..7461ce52f 100644
--- a/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java
+++ b/lucene/src/java/org/apache/lucene/index/DocumentsWriter.java
@@ -1,1161 +1,1161 @@
package org.apache.lucene.index;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.PrintStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Similarity;
import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMFile;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.RecyclingByteBlockAllocator;
import org.apache.lucene.util.ThreadInterruptedException;
import org.apache.lucene.util.RamUsageEstimator;
import static org.apache.lucene.util.ByteBlockPool.BYTE_BLOCK_MASK;
import static org.apache.lucene.util.ByteBlockPool.BYTE_BLOCK_SIZE;
/**
* This class accepts multiple added documents and directly
* writes a single segment file. It does this more
* efficiently than creating a single segment per document
* (with DocumentWriter) and doing standard merges on those
* segments.
*
* Each added document is passed to the {@link DocConsumer},
* which in turn processes the document and interacts with
* other consumers in the indexing chain. Certain
* consumers, like {@link StoredFieldsWriter} and {@link
* TermVectorsTermsWriter}, digest a document and
* immediately write bytes to the "doc store" files (ie,
* they do not consume RAM per document, except while they
* are processing the document).
*
* Other consumers, eg {@link FreqProxTermsWriter} and
* {@link NormsWriter}, buffer bytes in RAM and flush only
* when a new segment is produced.
* Once we have used our allowed RAM buffer, or the number
* of added docs is large enough (in the case we are
* flushing by doc count instead of RAM usage), we create a
* real segment and flush it to the Directory.
*
* Threads:
*
* Multiple threads are allowed into addDocument at once.
* There is an initial synchronized call to getThreadState
* which allocates a ThreadState for this thread. The same
* thread will get the same ThreadState over time (thread
* affinity) so that if there are consistent patterns (for
* example each thread is indexing a different content
* source) then we make better use of RAM. Then
* processDocument is called on that ThreadState without
* synchronization (most of the "heavy lifting" is in this
* call). Finally the synchronized "finishDocument" is
* called to flush changes to the directory.
*
* When flush is called by IndexWriter we forcefully idle
* all threads and flush only once they are all idle. This
* means you can call flush with a given thread even while
* other threads are actively adding/deleting documents.
*
*
* Exceptions:
*
* Because this class directly updates in-memory posting
* lists, and flushes stored fields and term vectors
* directly to files in the directory, there are certain
* limited times when an exception can corrupt this state.
* For example, a disk full while flushing stored fields
* leaves this file in a corrupt state. Or, an OOM
* exception while appending to the in-memory posting lists
* can corrupt that posting list. We call such exceptions
* "aborting exceptions". In these cases we must call
* abort() to discard all docs added since the last flush.
*
* All other exceptions ("non-aborting exceptions") can
* still partially update the index structures. These
* updates are consistent, but, they represent only a part
* of the document seen up until the exception was hit.
* When this happens, we immediately mark the document as
* deleted so that the document is always atomically ("all
* or none") added to the index.
*/
final class DocumentsWriter {
final AtomicLong bytesUsed = new AtomicLong(0);
IndexWriter writer;
Directory directory;
String segment; // Current segment we are working on
private int nextDocID; // Next docID to be added
private int numDocs; // # of docs added, but not yet flushed
// Max # ThreadState instances; if there are more threads
// than this they share ThreadStates
private DocumentsWriterThreadState[] threadStates = new DocumentsWriterThreadState[0];
private final HashMap<Thread,DocumentsWriterThreadState> threadBindings = new HashMap<Thread,DocumentsWriterThreadState>();
boolean bufferIsFull; // True when it's time to write segment
private boolean aborting; // True if an abort is pending
PrintStream infoStream;
int maxFieldLength = IndexWriterConfig.UNLIMITED_FIELD_LENGTH;
Similarity similarity;
// max # simultaneous threads; if there are more than
// this, they wait for others to finish first
private final int maxThreadStates;
// Deletes for our still-in-RAM (to be flushed next) segment
private SegmentDeletes pendingDeletes = new SegmentDeletes();
static class DocState {
DocumentsWriter docWriter;
Analyzer analyzer;
int maxFieldLength;
PrintStream infoStream;
Similarity similarity;
int docID;
Document doc;
String maxTermPrefix;
// Only called by asserts
public boolean testPoint(String name) {
return docWriter.writer.testPoint(name);
}
public void clear() {
// don't hold onto doc nor analyzer, in case it is
// largish:
doc = null;
analyzer = null;
}
}
/** Consumer returns this on each doc. This holds any
* state that must be flushed synchronized "in docID
* order". We gather these and flush them in order. */
abstract static class DocWriter {
DocWriter next;
int docID;
abstract void finish() throws IOException;
abstract void abort();
abstract long sizeInBytes();
void setNext(DocWriter next) {
this.next = next;
}
}
/**
* Create and return a new DocWriterBuffer.
*/
PerDocBuffer newPerDocBuffer() {
return new PerDocBuffer();
}
/**
* RAMFile buffer for DocWriters.
*/
@SuppressWarnings("serial")
class PerDocBuffer extends RAMFile {
/**
* Allocate bytes used from shared pool.
*/
protected byte[] newBuffer(int size) {
assert size == PER_DOC_BLOCK_SIZE;
return perDocAllocator.getByteBlock();
}
/**
* Recycle the bytes used.
*/
synchronized void recycle() {
if (buffers.size() > 0) {
setLength(0);
// Recycle the blocks
perDocAllocator.recycleByteBlocks(buffers);
buffers.clear();
sizeInBytes = 0;
assert numBuffers() == 0;
}
}
}
/**
* The IndexingChain must define the {@link #getChain(DocumentsWriter)} method
* which returns the DocConsumer that the DocumentsWriter calls to process the
* documents.
*/
abstract static class IndexingChain {
abstract DocConsumer getChain(DocumentsWriter documentsWriter);
}
static final IndexingChain defaultIndexingChain = new IndexingChain() {
@Override
DocConsumer getChain(DocumentsWriter documentsWriter) {
/*
This is the current indexing chain:
DocConsumer / DocConsumerPerThread
--> code: DocFieldProcessor / DocFieldProcessorPerThread
--> DocFieldConsumer / DocFieldConsumerPerThread / DocFieldConsumerPerField
--> code: DocFieldConsumers / DocFieldConsumersPerThread / DocFieldConsumersPerField
--> code: DocInverter / DocInverterPerThread / DocInverterPerField
--> InvertedDocConsumer / InvertedDocConsumerPerThread / InvertedDocConsumerPerField
--> code: TermsHash / TermsHashPerThread / TermsHashPerField
--> TermsHashConsumer / TermsHashConsumerPerThread / TermsHashConsumerPerField
--> code: FreqProxTermsWriter / FreqProxTermsWriterPerThread / FreqProxTermsWriterPerField
--> code: TermVectorsTermsWriter / TermVectorsTermsWriterPerThread / TermVectorsTermsWriterPerField
--> InvertedDocEndConsumer / InvertedDocConsumerPerThread / InvertedDocConsumerPerField
--> code: NormsWriter / NormsWriterPerThread / NormsWriterPerField
--> code: StoredFieldsWriter / StoredFieldsWriterPerThread / StoredFieldsWriterPerField
*/
// Build up indexing chain:
final TermsHashConsumer termVectorsWriter = new TermVectorsTermsWriter(documentsWriter);
final TermsHashConsumer freqProxWriter = new FreqProxTermsWriter();
/*
* nesting TermsHash instances here to allow the secondary (TermVectors) share the interned postings
* via a shared ByteBlockPool. See TermsHashPerField for details.
*/
final TermsHash termVectorsTermHash = new TermsHash(documentsWriter, false, termVectorsWriter, null);
final InvertedDocConsumer termsHash = new TermsHash(documentsWriter, true, freqProxWriter, termVectorsTermHash);
final NormsWriter normsWriter = new NormsWriter();
final DocInverter docInverter = new DocInverter(termsHash, normsWriter);
return new DocFieldProcessor(documentsWriter, docInverter);
}
};
final DocConsumer consumer;
// How much RAM we can use before flushing. This is 0 if
// we are flushing by doc count instead.
private long ramBufferSize = (long) (IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB*1024*1024);
private long waitQueuePauseBytes = (long) (ramBufferSize*0.1);
private long waitQueueResumeBytes = (long) (ramBufferSize*0.05);
// If we've allocated 5% over our RAM budget, we then
// free down to 95%
private long freeLevel = (long) (IndexWriterConfig.DEFAULT_RAM_BUFFER_SIZE_MB*1024*1024*0.95);
// Flush @ this number of docs. If ramBufferSize is
// non-zero we will flush by RAM usage instead.
private int maxBufferedDocs = IndexWriterConfig.DEFAULT_MAX_BUFFERED_DOCS;
private boolean closed;
private final FieldInfos fieldInfos;
private final BufferedDeletes bufferedDeletes;
private final IndexWriter.FlushControl flushControl;
DocumentsWriter(Directory directory, IndexWriter writer, IndexingChain indexingChain, int maxThreadStates, FieldInfos fieldInfos, BufferedDeletes bufferedDeletes) throws IOException {
this.directory = directory;
this.writer = writer;
this.similarity = writer.getConfig().getSimilarity();
this.maxThreadStates = maxThreadStates;
this.fieldInfos = fieldInfos;
this.bufferedDeletes = bufferedDeletes;
flushControl = writer.flushControl;
consumer = indexingChain.getChain(this);
}
// Buffer a specific docID for deletion. Currently only
// used when we hit a exception when adding a document
synchronized void deleteDocID(int docIDUpto) {
pendingDeletes.addDocID(docIDUpto);
// NOTE: we do not trigger flush here. This is
// potentially a RAM leak, if you have an app that tries
// to add docs but every single doc always hits a
// non-aborting exception. Allowing a flush here gets
// very messy because we are only invoked when handling
// exceptions so to do this properly, while handling an
// exception we'd have to go off and flush new deletes
// which is risky (likely would hit some other
// confounding exception).
}
boolean deleteQueries(Query... queries) {
final boolean doFlush = flushControl.waitUpdate(0, queries.length);
synchronized(this) {
for (Query query : queries) {
pendingDeletes.addQuery(query, numDocs);
}
}
return doFlush;
}
boolean deleteQuery(Query query) {
final boolean doFlush = flushControl.waitUpdate(0, 1);
synchronized(this) {
pendingDeletes.addQuery(query, numDocs);
}
return doFlush;
}
boolean deleteTerms(Term... terms) {
final boolean doFlush = flushControl.waitUpdate(0, terms.length);
synchronized(this) {
for (Term term : terms) {
pendingDeletes.addTerm(term, numDocs);
}
}
return doFlush;
}
boolean deleteTerm(Term term, boolean skipWait) {
final boolean doFlush = flushControl.waitUpdate(0, 1, skipWait);
synchronized(this) {
pendingDeletes.addTerm(term, numDocs);
}
return doFlush;
}
public FieldInfos getFieldInfos() {
return fieldInfos;
}
/** If non-null, various details of indexing are printed
* here. */
synchronized void setInfoStream(PrintStream infoStream) {
this.infoStream = infoStream;
for(int i=0;i<threadStates.length;i++) {
threadStates[i].docState.infoStream = infoStream;
}
}
synchronized void setMaxFieldLength(int maxFieldLength) {
this.maxFieldLength = maxFieldLength;
for(int i=0;i<threadStates.length;i++) {
threadStates[i].docState.maxFieldLength = maxFieldLength;
}
}
synchronized void setSimilarity(Similarity similarity) {
this.similarity = similarity;
for(int i=0;i<threadStates.length;i++) {
threadStates[i].docState.similarity = similarity;
}
}
/** Set how much RAM we can use before flushing. */
synchronized void setRAMBufferSizeMB(double mb) {
if (mb == IndexWriterConfig.DISABLE_AUTO_FLUSH) {
ramBufferSize = IndexWriterConfig.DISABLE_AUTO_FLUSH;
waitQueuePauseBytes = 4*1024*1024;
waitQueueResumeBytes = 2*1024*1024;
} else {
ramBufferSize = (long) (mb*1024*1024);
waitQueuePauseBytes = (long) (ramBufferSize*0.1);
waitQueueResumeBytes = (long) (ramBufferSize*0.05);
freeLevel = (long) (0.95 * ramBufferSize);
}
}
synchronized double getRAMBufferSizeMB() {
if (ramBufferSize == IndexWriterConfig.DISABLE_AUTO_FLUSH) {
return ramBufferSize;
} else {
return ramBufferSize/1024./1024.;
}
}
/** Set max buffered docs, which means we will flush by
* doc count instead of by RAM usage. */
void setMaxBufferedDocs(int count) {
maxBufferedDocs = count;
}
int getMaxBufferedDocs() {
return maxBufferedDocs;
}
/** Get current segment name we are writing. */
synchronized String getSegment() {
return segment;
}
/** Returns how many docs are currently buffered in RAM. */
synchronized int getNumDocs() {
return numDocs;
}
void message(String message) {
if (infoStream != null) {
writer.message("DW: " + message);
}
}
synchronized void setAborting() {
if (infoStream != null) {
message("setAborting");
}
aborting = true;
}
/** Called if we hit an exception at a bad time (when
* updating the index files) and must discard all
* currently buffered docs. This resets our state,
* discarding any docs added since last flush. */
synchronized void abort() throws IOException {
if (infoStream != null) {
message("docWriter: abort");
}
boolean success = false;
try {
// Forcefully remove waiting ThreadStates from line
waitQueue.abort();
// Wait for all other threads to finish with
// DocumentsWriter:
waitIdle();
if (infoStream != null) {
message("docWriter: abort waitIdle done");
}
assert 0 == waitQueue.numWaiting: "waitQueue.numWaiting=" + waitQueue.numWaiting;
waitQueue.waitingBytes = 0;
pendingDeletes.clear();
for (DocumentsWriterThreadState threadState : threadStates)
try {
threadState.consumer.abort();
} catch (Throwable t) {
}
try {
consumer.abort();
} catch (Throwable t) {
}
// Reset all postings data
doAfterFlush();
success = true;
} finally {
aborting = false;
notifyAll();
if (infoStream != null) {
message("docWriter: done abort; success=" + success);
}
}
}
/** Reset after a flush */
private void doAfterFlush() throws IOException {
// All ThreadStates should be idle when we are called
assert allThreadsIdle();
threadBindings.clear();
waitQueue.reset();
segment = null;
numDocs = 0;
nextDocID = 0;
bufferIsFull = false;
for(int i=0;i<threadStates.length;i++) {
threadStates[i].doAfterFlush();
}
}
private synchronized boolean allThreadsIdle() {
for(int i=0;i<threadStates.length;i++) {
if (!threadStates[i].isIdle) {
return false;
}
}
return true;
}
synchronized boolean anyChanges() {
return numDocs != 0 || pendingDeletes.any();
}
// for testing
public SegmentDeletes getPendingDeletes() {
return pendingDeletes;
}
private void pushDeletes(SegmentInfo newSegment, SegmentInfos segmentInfos) {
// Lock order: DW -> BD
if (pendingDeletes.any()) {
if (newSegment != null) {
if (infoStream != null) {
message("flush: push buffered deletes to newSegment");
}
bufferedDeletes.pushDeletes(pendingDeletes, newSegment);
} else if (segmentInfos.size() > 0) {
if (infoStream != null) {
message("flush: push buffered deletes to previously flushed segment " + segmentInfos.lastElement());
}
bufferedDeletes.pushDeletes(pendingDeletes, segmentInfos.lastElement(), true);
} else {
if (infoStream != null) {
message("flush: drop buffered deletes: no segments");
}
// We can safely discard these deletes: since
// there are no segments, the deletions cannot
// affect anything.
}
pendingDeletes = new SegmentDeletes();
}
}
public boolean anyDeletions() {
return pendingDeletes.any();
}
/** Flush all pending docs to a new segment */
// Lock order: IW -> DW
synchronized SegmentInfo flush(IndexWriter writer, IndexFileDeleter deleter, MergePolicy mergePolicy, SegmentInfos segmentInfos) throws IOException {
// We change writer's segmentInfos:
assert Thread.holdsLock(writer);
waitIdle();
if (numDocs == 0) {
// nothing to do!
if (infoStream != null) {
message("flush: no docs; skipping");
}
// Lock order: IW -> DW -> BD
pushDeletes(null, segmentInfos);
return null;
}
if (aborting) {
if (infoStream != null) {
message("flush: skip because aborting is set");
}
return null;
}
boolean success = false;
SegmentInfo newSegment;
try {
assert nextDocID == numDocs;
assert waitQueue.numWaiting == 0;
assert waitQueue.waitingBytes == 0;
if (infoStream != null) {
message("flush postings as segment " + segment + " numDocs=" + numDocs);
}
final SegmentWriteState flushState = new SegmentWriteState(infoStream, directory, segment, fieldInfos,
numDocs, writer.getConfig().getTermIndexInterval(),
SegmentCodecs.build(fieldInfos, writer.codecs));
newSegment = new SegmentInfo(segment, numDocs, directory, false, fieldInfos.hasProx(), flushState.segmentCodecs, false);
Collection<DocConsumerPerThread> threads = new HashSet<DocConsumerPerThread>();
for (DocumentsWriterThreadState threadState : threadStates) {
threads.add(threadState.consumer);
}
- long startNumBytesUsed = bytesUsed();
+ double startMBUsed = bytesUsed()/1024./1024.;
consumer.flush(threads, flushState);
newSegment.setHasVectors(flushState.hasVectors);
if (infoStream != null) {
message("new segment has " + (flushState.hasVectors ? "vectors" : "no vectors"));
message("flushedFiles=" + flushState.flushedFiles);
message("flushed codecs=" + newSegment.getSegmentCodecs());
}
if (mergePolicy.useCompoundFile(segmentInfos, newSegment)) {
final String cfsFileName = IndexFileNames.segmentFileName(segment, "", IndexFileNames.COMPOUND_FILE_EXTENSION);
if (infoStream != null) {
message("flush: create compound file \"" + cfsFileName + "\"");
}
CompoundFileWriter cfsWriter = new CompoundFileWriter(directory, cfsFileName);
for(String fileName : flushState.flushedFiles) {
cfsWriter.addFile(fileName);
}
cfsWriter.close();
deleter.deleteNewFiles(flushState.flushedFiles);
newSegment.setUseCompoundFile(true);
}
if (infoStream != null) {
message("flush: segment=" + newSegment);
- final long newSegmentSizeNoStore = newSegment.sizeInBytes(false);
- final long newSegmentSize = newSegment.sizeInBytes(true);
- message(" ramUsed=" + nf.format(startNumBytesUsed / 1024. / 1024.) + " MB" +
- " newFlushedSize=" + nf.format(newSegmentSize / 1024 / 1024) + " MB" +
- " (" + nf.format(newSegmentSizeNoStore / 1024 / 1024) + " MB w/o doc stores)" +
- " docs/MB=" + nf.format(numDocs / (newSegmentSize / 1024. / 1024.)) +
- " new/old=" + nf.format(100.0 * newSegmentSizeNoStore / startNumBytesUsed) + "%");
+ final double newSegmentSizeNoStore = newSegment.sizeInBytes(false)/1024./1024.;
+ final double newSegmentSize = newSegment.sizeInBytes(true)/1024./1024.;
+ message(" ramUsed=" + nf.format(startMBUsed) + " MB" +
+ " newFlushedSize=" + nf.format(newSegmentSize) + " MB" +
+ " (" + nf.format(newSegmentSizeNoStore) + " MB w/o doc stores)" +
+ " docs/MB=" + nf.format(numDocs / newSegmentSize) +
+ " new/old=" + nf.format(100.0 * newSegmentSizeNoStore / startMBUsed) + "%");
}
success = true;
} finally {
notifyAll();
if (!success) {
if (segment != null) {
deleter.refresh(segment);
}
abort();
}
}
doAfterFlush();
// Lock order: IW -> DW -> BD
pushDeletes(newSegment, segmentInfos);
return newSegment;
}
synchronized void close() {
closed = true;
notifyAll();
}
/** Returns a free (idle) ThreadState that may be used for
* indexing this one document. This call also pauses if a
* flush is pending. If delTerm is non-null then we
* buffer this deleted term after the thread state has
* been acquired. */
synchronized DocumentsWriterThreadState getThreadState(Document doc, Term delTerm) throws IOException {
final Thread currentThread = Thread.currentThread();
assert !Thread.holdsLock(writer);
// First, find a thread state. If this thread already
// has affinity to a specific ThreadState, use that one
// again.
DocumentsWriterThreadState state = threadBindings.get(currentThread);
if (state == null) {
// First time this thread has called us since last
// flush. Find the least loaded thread state:
DocumentsWriterThreadState minThreadState = null;
for(int i=0;i<threadStates.length;i++) {
DocumentsWriterThreadState ts = threadStates[i];
if (minThreadState == null || ts.numThreads < minThreadState.numThreads) {
minThreadState = ts;
}
}
if (minThreadState != null && (minThreadState.numThreads == 0 || threadStates.length >= maxThreadStates)) {
state = minThreadState;
state.numThreads++;
} else {
// Just create a new "private" thread state
DocumentsWriterThreadState[] newArray = new DocumentsWriterThreadState[1+threadStates.length];
if (threadStates.length > 0) {
System.arraycopy(threadStates, 0, newArray, 0, threadStates.length);
}
state = newArray[threadStates.length] = new DocumentsWriterThreadState(this);
threadStates = newArray;
}
threadBindings.put(currentThread, state);
}
// Next, wait until my thread state is idle (in case
// it's shared with other threads), and no flush/abort
// pending
waitReady(state);
// Allocate segment name if this is the first doc since
// last flush:
if (segment == null) {
segment = writer.newSegmentName();
assert numDocs == 0;
}
state.docState.docID = nextDocID++;
if (delTerm != null) {
pendingDeletes.addTerm(delTerm, state.docState.docID);
}
numDocs++;
state.isIdle = false;
return state;
}
boolean addDocument(Document doc, Analyzer analyzer) throws CorruptIndexException, IOException {
return updateDocument(doc, analyzer, null);
}
boolean updateDocument(Document doc, Analyzer analyzer, Term delTerm)
throws CorruptIndexException, IOException {
// Possibly trigger a flush, or wait until any running flush completes:
boolean doFlush = flushControl.waitUpdate(1, delTerm != null ? 1 : 0);
// This call is synchronized but fast
final DocumentsWriterThreadState state = getThreadState(doc, delTerm);
final DocState docState = state.docState;
docState.doc = doc;
docState.analyzer = analyzer;
boolean success = false;
try {
// This call is not synchronized and does all the
// work
final DocWriter perDoc;
try {
perDoc = state.consumer.processDocument();
} finally {
docState.clear();
}
// This call is synchronized but fast
finishDocument(state, perDoc);
success = true;
} finally {
if (!success) {
// If this thread state had decided to flush, we
// must clear it so another thread can flush
if (doFlush) {
flushControl.clearFlushPending();
}
if (infoStream != null) {
message("exception in updateDocument aborting=" + aborting);
}
synchronized(this) {
state.isIdle = true;
notifyAll();
if (aborting) {
abort();
} else {
skipDocWriter.docID = docState.docID;
boolean success2 = false;
try {
waitQueue.add(skipDocWriter);
success2 = true;
} finally {
if (!success2) {
abort();
return false;
}
}
// Immediately mark this document as deleted
// since likely it was partially added. This
// keeps indexing as "all or none" (atomic) when
// adding a document:
deleteDocID(state.docState.docID);
}
}
}
}
doFlush |= flushControl.flushByRAMUsage("new document");
return doFlush;
}
public synchronized void waitIdle() {
while (!allThreadsIdle()) {
try {
wait();
} catch (InterruptedException ie) {
throw new ThreadInterruptedException(ie);
}
}
}
synchronized void waitReady(DocumentsWriterThreadState state) {
while (!closed && (!state.isIdle || aborting)) {
try {
wait();
} catch (InterruptedException ie) {
throw new ThreadInterruptedException(ie);
}
}
if (closed) {
throw new AlreadyClosedException("this IndexWriter is closed");
}
}
/** Does the synchronized work to finish/flush the
* inverted document. */
private void finishDocument(DocumentsWriterThreadState perThread, DocWriter docWriter) throws IOException {
// Must call this w/o holding synchronized(this) else
// we'll hit deadlock:
balanceRAM();
synchronized(this) {
assert docWriter == null || docWriter.docID == perThread.docState.docID;
if (aborting) {
// We are currently aborting, and another thread is
// waiting for me to become idle. We just forcefully
// idle this threadState; it will be fully reset by
// abort()
if (docWriter != null) {
try {
docWriter.abort();
} catch (Throwable t) {
}
}
perThread.isIdle = true;
// wakes up any threads waiting on the wait queue
notifyAll();
return;
}
final boolean doPause;
if (docWriter != null) {
doPause = waitQueue.add(docWriter);
} else {
skipDocWriter.docID = perThread.docState.docID;
doPause = waitQueue.add(skipDocWriter);
}
if (doPause) {
waitForWaitQueue();
}
perThread.isIdle = true;
// wakes up any threads waiting on the wait queue
notifyAll();
}
}
synchronized void waitForWaitQueue() {
do {
try {
wait();
} catch (InterruptedException ie) {
throw new ThreadInterruptedException(ie);
}
} while (!waitQueue.doResume());
}
private static class SkipDocWriter extends DocWriter {
@Override
void finish() {
}
@Override
void abort() {
}
@Override
long sizeInBytes() {
return 0;
}
}
final SkipDocWriter skipDocWriter = new SkipDocWriter();
NumberFormat nf = NumberFormat.getInstance();
/* Initial chunks size of the shared byte[] blocks used to
store postings data */
final static int BYTE_BLOCK_NOT_MASK = ~BYTE_BLOCK_MASK;
/* if you increase this, you must fix field cache impl for
* getTerms/getTermsIndex requires <= 32768 */
final static int MAX_TERM_LENGTH_UTF8 = BYTE_BLOCK_SIZE-2;
/* Initial chunks size of the shared int[] blocks used to
store postings data */
final static int INT_BLOCK_SHIFT = 13;
final static int INT_BLOCK_SIZE = 1 << INT_BLOCK_SHIFT;
final static int INT_BLOCK_MASK = INT_BLOCK_SIZE - 1;
private List<int[]> freeIntBlocks = new ArrayList<int[]>();
/* Allocate another int[] from the shared pool */
synchronized int[] getIntBlock() {
final int size = freeIntBlocks.size();
final int[] b;
if (0 == size) {
b = new int[INT_BLOCK_SIZE];
bytesUsed.addAndGet(INT_BLOCK_SIZE*RamUsageEstimator.NUM_BYTES_INT);
} else {
b = freeIntBlocks.remove(size-1);
}
return b;
}
long bytesUsed() {
return bytesUsed.get() + pendingDeletes.bytesUsed.get();
}
/* Return int[]s to the pool */
synchronized void recycleIntBlocks(int[][] blocks, int start, int end) {
for(int i=start;i<end;i++) {
freeIntBlocks.add(blocks[i]);
blocks[i] = null;
}
}
final RecyclingByteBlockAllocator byteBlockAllocator = new RecyclingByteBlockAllocator(BYTE_BLOCK_SIZE, Integer.MAX_VALUE, bytesUsed);
final static int PER_DOC_BLOCK_SIZE = 1024;
final RecyclingByteBlockAllocator perDocAllocator = new RecyclingByteBlockAllocator(PER_DOC_BLOCK_SIZE, Integer.MAX_VALUE, bytesUsed);
String toMB(long v) {
return nf.format(v/1024./1024.);
}
/* We have three pools of RAM: Postings, byte blocks
* (holds freq/prox posting data) and per-doc buffers
* (stored fields/term vectors). Different docs require
* varying amount of storage from these classes. For
* example, docs with many unique single-occurrence short
* terms will use up the Postings RAM and hardly any of
* the other two. Whereas docs with very large terms will
* use alot of byte blocks RAM. This method just frees
* allocations from the pools once we are over-budget,
* which balances the pools to match the current docs. */
void balanceRAM() {
final boolean doBalance;
final long deletesRAMUsed;
deletesRAMUsed = bufferedDeletes.bytesUsed();
synchronized(this) {
if (ramBufferSize == IndexWriterConfig.DISABLE_AUTO_FLUSH || bufferIsFull) {
return;
}
doBalance = bytesUsed() + deletesRAMUsed >= ramBufferSize;
}
if (doBalance) {
if (infoStream != null) {
message(" RAM: balance allocations: usedMB=" + toMB(bytesUsed()) +
" vs trigger=" + toMB(ramBufferSize) +
" deletesMB=" + toMB(deletesRAMUsed) +
" byteBlockFree=" + toMB(byteBlockAllocator.bytesUsed()) +
" perDocFree=" + toMB(perDocAllocator.bytesUsed()));
}
final long startBytesUsed = bytesUsed() + deletesRAMUsed;
int iter = 0;
// We free equally from each pool in 32 KB
// chunks until we are below our threshold
// (freeLevel)
boolean any = true;
while(bytesUsed()+deletesRAMUsed > freeLevel) {
synchronized(this) {
if (0 == perDocAllocator.numBufferedBlocks() &&
0 == byteBlockAllocator.numBufferedBlocks() &&
0 == freeIntBlocks.size() && !any) {
// Nothing else to free -- must flush now.
bufferIsFull = bytesUsed()+deletesRAMUsed > ramBufferSize;
if (infoStream != null) {
if (bytesUsed()+deletesRAMUsed > ramBufferSize) {
message(" nothing to free; set bufferIsFull");
} else {
message(" nothing to free");
}
}
break;
}
if ((0 == iter % 4) && byteBlockAllocator.numBufferedBlocks() > 0) {
byteBlockAllocator.freeBlocks(1);
}
if ((1 == iter % 4) && freeIntBlocks.size() > 0) {
freeIntBlocks.remove(freeIntBlocks.size()-1);
bytesUsed.addAndGet(-INT_BLOCK_SIZE * RamUsageEstimator.NUM_BYTES_INT);
}
if ((2 == iter % 4) && perDocAllocator.numBufferedBlocks() > 0) {
perDocAllocator.freeBlocks(32); // Remove upwards of 32 blocks (each block is 1K)
}
}
if ((3 == iter % 4) && any) {
// Ask consumer to free any recycled state
any = consumer.freeRAM();
}
iter++;
}
if (infoStream != null) {
message(" after free: freedMB=" + nf.format((startBytesUsed-bytesUsed()-deletesRAMUsed)/1024./1024.) + " usedMB=" + nf.format((bytesUsed()+deletesRAMUsed)/1024./1024.));
}
}
}
final WaitQueue waitQueue = new WaitQueue();
private class WaitQueue {
DocWriter[] waiting;
int nextWriteDocID;
int nextWriteLoc;
int numWaiting;
long waitingBytes;
public WaitQueue() {
waiting = new DocWriter[10];
}
synchronized void reset() {
// NOTE: nextWriteLoc doesn't need to be reset
assert numWaiting == 0;
assert waitingBytes == 0;
nextWriteDocID = 0;
}
synchronized boolean doResume() {
return waitingBytes <= waitQueueResumeBytes;
}
synchronized boolean doPause() {
return waitingBytes > waitQueuePauseBytes;
}
synchronized void abort() {
int count = 0;
for(int i=0;i<waiting.length;i++) {
final DocWriter doc = waiting[i];
if (doc != null) {
doc.abort();
waiting[i] = null;
count++;
}
}
waitingBytes = 0;
assert count == numWaiting;
numWaiting = 0;
}
private void writeDocument(DocWriter doc) throws IOException {
assert doc == skipDocWriter || nextWriteDocID == doc.docID;
boolean success = false;
try {
doc.finish();
nextWriteDocID++;
nextWriteLoc++;
assert nextWriteLoc <= waiting.length;
if (nextWriteLoc == waiting.length) {
nextWriteLoc = 0;
}
success = true;
} finally {
if (!success) {
setAborting();
}
}
}
synchronized public boolean add(DocWriter doc) throws IOException {
assert doc.docID >= nextWriteDocID;
if (doc.docID == nextWriteDocID) {
writeDocument(doc);
while(true) {
doc = waiting[nextWriteLoc];
if (doc != null) {
numWaiting--;
waiting[nextWriteLoc] = null;
waitingBytes -= doc.sizeInBytes();
writeDocument(doc);
} else {
break;
}
}
} else {
// I finished before documents that were added
// before me. This can easily happen when I am a
// small doc and the docs before me were large, or,
// just due to luck in the thread scheduling. Just
// add myself to the queue and when that large doc
// finishes, it will flush me:
int gap = doc.docID - nextWriteDocID;
if (gap >= waiting.length) {
// Grow queue
DocWriter[] newArray = new DocWriter[ArrayUtil.oversize(gap, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
assert nextWriteLoc >= 0;
System.arraycopy(waiting, nextWriteLoc, newArray, 0, waiting.length-nextWriteLoc);
System.arraycopy(waiting, 0, newArray, waiting.length-nextWriteLoc, nextWriteLoc);
nextWriteLoc = 0;
waiting = newArray;
gap = doc.docID - nextWriteDocID;
}
int loc = nextWriteLoc + gap;
if (loc >= waiting.length) {
loc -= waiting.length;
}
// We should only wrap one time
assert loc < waiting.length;
// Nobody should be in my spot!
assert waiting[loc] == null;
waiting[loc] = doc;
numWaiting++;
waitingBytes += doc.sizeInBytes();
}
return doPause();
}
}
}
| false | true | synchronized SegmentInfo flush(IndexWriter writer, IndexFileDeleter deleter, MergePolicy mergePolicy, SegmentInfos segmentInfos) throws IOException {
// We change writer's segmentInfos:
assert Thread.holdsLock(writer);
waitIdle();
if (numDocs == 0) {
// nothing to do!
if (infoStream != null) {
message("flush: no docs; skipping");
}
// Lock order: IW -> DW -> BD
pushDeletes(null, segmentInfos);
return null;
}
if (aborting) {
if (infoStream != null) {
message("flush: skip because aborting is set");
}
return null;
}
boolean success = false;
SegmentInfo newSegment;
try {
assert nextDocID == numDocs;
assert waitQueue.numWaiting == 0;
assert waitQueue.waitingBytes == 0;
if (infoStream != null) {
message("flush postings as segment " + segment + " numDocs=" + numDocs);
}
final SegmentWriteState flushState = new SegmentWriteState(infoStream, directory, segment, fieldInfos,
numDocs, writer.getConfig().getTermIndexInterval(),
SegmentCodecs.build(fieldInfos, writer.codecs));
newSegment = new SegmentInfo(segment, numDocs, directory, false, fieldInfos.hasProx(), flushState.segmentCodecs, false);
Collection<DocConsumerPerThread> threads = new HashSet<DocConsumerPerThread>();
for (DocumentsWriterThreadState threadState : threadStates) {
threads.add(threadState.consumer);
}
long startNumBytesUsed = bytesUsed();
consumer.flush(threads, flushState);
newSegment.setHasVectors(flushState.hasVectors);
if (infoStream != null) {
message("new segment has " + (flushState.hasVectors ? "vectors" : "no vectors"));
message("flushedFiles=" + flushState.flushedFiles);
message("flushed codecs=" + newSegment.getSegmentCodecs());
}
if (mergePolicy.useCompoundFile(segmentInfos, newSegment)) {
final String cfsFileName = IndexFileNames.segmentFileName(segment, "", IndexFileNames.COMPOUND_FILE_EXTENSION);
if (infoStream != null) {
message("flush: create compound file \"" + cfsFileName + "\"");
}
CompoundFileWriter cfsWriter = new CompoundFileWriter(directory, cfsFileName);
for(String fileName : flushState.flushedFiles) {
cfsWriter.addFile(fileName);
}
cfsWriter.close();
deleter.deleteNewFiles(flushState.flushedFiles);
newSegment.setUseCompoundFile(true);
}
if (infoStream != null) {
message("flush: segment=" + newSegment);
final long newSegmentSizeNoStore = newSegment.sizeInBytes(false);
final long newSegmentSize = newSegment.sizeInBytes(true);
message(" ramUsed=" + nf.format(startNumBytesUsed / 1024. / 1024.) + " MB" +
" newFlushedSize=" + nf.format(newSegmentSize / 1024 / 1024) + " MB" +
" (" + nf.format(newSegmentSizeNoStore / 1024 / 1024) + " MB w/o doc stores)" +
" docs/MB=" + nf.format(numDocs / (newSegmentSize / 1024. / 1024.)) +
" new/old=" + nf.format(100.0 * newSegmentSizeNoStore / startNumBytesUsed) + "%");
}
success = true;
} finally {
notifyAll();
if (!success) {
if (segment != null) {
deleter.refresh(segment);
}
abort();
}
}
doAfterFlush();
// Lock order: IW -> DW -> BD
pushDeletes(newSegment, segmentInfos);
return newSegment;
}
| synchronized SegmentInfo flush(IndexWriter writer, IndexFileDeleter deleter, MergePolicy mergePolicy, SegmentInfos segmentInfos) throws IOException {
// We change writer's segmentInfos:
assert Thread.holdsLock(writer);
waitIdle();
if (numDocs == 0) {
// nothing to do!
if (infoStream != null) {
message("flush: no docs; skipping");
}
// Lock order: IW -> DW -> BD
pushDeletes(null, segmentInfos);
return null;
}
if (aborting) {
if (infoStream != null) {
message("flush: skip because aborting is set");
}
return null;
}
boolean success = false;
SegmentInfo newSegment;
try {
assert nextDocID == numDocs;
assert waitQueue.numWaiting == 0;
assert waitQueue.waitingBytes == 0;
if (infoStream != null) {
message("flush postings as segment " + segment + " numDocs=" + numDocs);
}
final SegmentWriteState flushState = new SegmentWriteState(infoStream, directory, segment, fieldInfos,
numDocs, writer.getConfig().getTermIndexInterval(),
SegmentCodecs.build(fieldInfos, writer.codecs));
newSegment = new SegmentInfo(segment, numDocs, directory, false, fieldInfos.hasProx(), flushState.segmentCodecs, false);
Collection<DocConsumerPerThread> threads = new HashSet<DocConsumerPerThread>();
for (DocumentsWriterThreadState threadState : threadStates) {
threads.add(threadState.consumer);
}
double startMBUsed = bytesUsed()/1024./1024.;
consumer.flush(threads, flushState);
newSegment.setHasVectors(flushState.hasVectors);
if (infoStream != null) {
message("new segment has " + (flushState.hasVectors ? "vectors" : "no vectors"));
message("flushedFiles=" + flushState.flushedFiles);
message("flushed codecs=" + newSegment.getSegmentCodecs());
}
if (mergePolicy.useCompoundFile(segmentInfos, newSegment)) {
final String cfsFileName = IndexFileNames.segmentFileName(segment, "", IndexFileNames.COMPOUND_FILE_EXTENSION);
if (infoStream != null) {
message("flush: create compound file \"" + cfsFileName + "\"");
}
CompoundFileWriter cfsWriter = new CompoundFileWriter(directory, cfsFileName);
for(String fileName : flushState.flushedFiles) {
cfsWriter.addFile(fileName);
}
cfsWriter.close();
deleter.deleteNewFiles(flushState.flushedFiles);
newSegment.setUseCompoundFile(true);
}
if (infoStream != null) {
message("flush: segment=" + newSegment);
final double newSegmentSizeNoStore = newSegment.sizeInBytes(false)/1024./1024.;
final double newSegmentSize = newSegment.sizeInBytes(true)/1024./1024.;
message(" ramUsed=" + nf.format(startMBUsed) + " MB" +
" newFlushedSize=" + nf.format(newSegmentSize) + " MB" +
" (" + nf.format(newSegmentSizeNoStore) + " MB w/o doc stores)" +
" docs/MB=" + nf.format(numDocs / newSegmentSize) +
" new/old=" + nf.format(100.0 * newSegmentSizeNoStore / startMBUsed) + "%");
}
success = true;
} finally {
notifyAll();
if (!success) {
if (segment != null) {
deleter.refresh(segment);
}
abort();
}
}
doAfterFlush();
// Lock order: IW -> DW -> BD
pushDeletes(newSegment, segmentInfos);
return newSegment;
}
|
diff --git a/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/JndiEncBuilder.java b/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/JndiEncBuilder.java
index 5781dfe848..23243630ad 100644
--- a/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/JndiEncBuilder.java
+++ b/container/openejb-core/src/main/java/org/apache/openejb/assembler/classic/JndiEncBuilder.java
@@ -1,424 +1,424 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openejb.assembler.classic;
import org.apache.openejb.BeanType;
import org.apache.openejb.OpenEJBException;
import org.apache.openejb.loader.SystemInstance;
import org.apache.openejb.persistence.JtaEntityManager;
import org.apache.openejb.persistence.JtaEntityManagerRegistry;
import org.apache.openejb.core.CoreUserTransaction;
import org.apache.openejb.core.ivm.naming.IntraVmJndiReference;
import org.apache.openejb.core.ivm.naming.JndiReference;
import org.apache.openejb.core.ivm.naming.ObjectReference;
import org.apache.openejb.core.ivm.naming.PersistenceUnitReference;
import org.apache.openejb.core.ivm.naming.Reference;
import org.apache.openejb.core.ivm.naming.PersistenceContextReference;
import org.apache.openejb.core.ivm.naming.JndiUrlReference;
import org.apache.openejb.core.ivm.naming.IvmContext;
import org.apache.openejb.core.ivm.naming.NameNode;
import org.apache.openejb.core.ivm.naming.ParsedName;
import org.apache.openejb.core.ivm.naming.SystemComponentReference;
import org.apache.xbean.naming.context.WritableContext;
import org.omg.CORBA.ORB;
import javax.ejb.EJBContext;
import javax.ejb.spi.HandleDelegate;
import javax.naming.Context;
import javax.naming.LinkRef;
import javax.naming.NamingException;
import javax.naming.Name;
import javax.persistence.EntityManagerFactory;
import javax.transaction.TransactionManager;
import javax.transaction.TransactionSynchronizationRegistry;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.SortedSet;
import java.util.TreeSet;
import java.net.URI;
import java.net.URISyntaxException;
/**
* TODO: This class is essentially an over glorified sym-linker. The names
* we were linking to are no longer guaranteed to be what we assume them to
* be. We need to come up with a different internal naming structure for
* the global JNDI and finally create the default which will be the default
* symlinked version of all the components.
*/
public class JndiEncBuilder {
private final boolean beanManagedTransactions;
private final String moduleId;
private final JndiEncInfo jndiEnc;
private final URI moduleUri;
// JPA factory indexes
private final Map<String, EntityManagerFactory> localFactories;
private final Map<String, EntityManagerFactory> absoluteFactories = new TreeMap<String,EntityManagerFactory>();
private final Map<String, SortedSet<String>> factoryPaths = new TreeMap<String,SortedSet<String>>();
public JndiEncBuilder(JndiEncInfo jndiEnc, String moduleId) throws OpenEJBException {
this(jndiEnc, null, null, null, moduleId);
}
public JndiEncBuilder(JndiEncInfo jndiEnc, String transactionType, BeanType ejbType, Map<String, Map<String, EntityManagerFactory>> allFactories, String moduleId) throws OpenEJBException {
beanManagedTransactions = transactionType != null && transactionType.equalsIgnoreCase("Bean");
this.moduleId = moduleId;
try {
moduleUri = new URI(moduleId);
} catch (URISyntaxException e) {
throw new OpenEJBException(e);
}
this.jndiEnc = jndiEnc;
// build map of path#untiName --> EMF
// and map of unitName --> TreeSet(path#untiName)
if (allFactories == null) allFactories = new HashMap<String, Map<String, EntityManagerFactory>>();
for (Map.Entry<String, Map<String, EntityManagerFactory>> entry : allFactories.entrySet()) {
String path = entry.getKey();
Map<String, EntityManagerFactory> entityManagers = entry.getValue();
for (Map.Entry<String, EntityManagerFactory> entityManagersEntry : entityManagers.entrySet()) {
String unitName = entityManagersEntry.getKey();
EntityManagerFactory entityManagerFactory = entityManagersEntry.getValue();
String absolutePath = path + "#" + unitName;
absoluteFactories.put(absolutePath, entityManagerFactory);
SortedSet<String> absolutePaths = factoryPaths.get(unitName);
if (absolutePaths == null) {
absolutePaths = new TreeSet<String>();
factoryPaths.put(unitName, absolutePaths);
}
absolutePaths.add(absolutePath);
}
}
Map<String, EntityManagerFactory> factories = allFactories.get(moduleId);
if (factories == null) factories = new HashMap<String, EntityManagerFactory>();
localFactories = factories;
}
public Context build() throws OpenEJBException {
Map<String, Object> bindings = buildMap();
Context context;
if (System.getProperty("openejb.naming","ivm").equals("xbean")) {
context = createXBeanWritableContext(bindings);
} else {
context = createIvmContext();
// bind the bindings
for (Iterator iterator = bindings.entrySet().iterator(); iterator.hasNext();) {
Map.Entry entry = (Map.Entry) iterator.next();
String name = (String) entry.getKey();
Object value = entry.getValue();
if (value == null) continue;
try {
Name parsedName = context.getNameParser("").parse(name);
for (int i = 1; i < parsedName.size(); i++) {
Name contextName = parsedName.getPrefix(i);
if (!bindingExists(context, contextName)) {
context.createSubcontext(contextName);
}
}
context.bind(name, value);
} catch (NamingException e) {
throw new org.apache.openejb.SystemException("Unable to bind '" + name + "' into bean's enc.", e);
}
}
}
return context;
}
public Map<String, Object> buildMap() throws OpenEJBException {
Map<String, Object> bindings = new HashMap<String, Object>();
// bind TransactionManager
TransactionManager transactionManager = SystemInstance.get().getComponent(TransactionManager.class);
bindings.put("java:comp/TransactionManager", transactionManager);
// bind TransactionSynchronizationRegistry
TransactionSynchronizationRegistry synchronizationRegistry = SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class);
bindings.put("java:comp/TransactionSynchronizationRegistry", synchronizationRegistry);
ORB orb = SystemInstance.get().getComponent(ORB.class);
// bind CORBA stuff
if (orb != null) {
bindings.put("java:comp/ORB", new ObjectReference(orb));
- bindings.put("java:comp/HandleDelegate", new ObjectReference(SystemInstance.get().getComponent(ORB.class)));
+ bindings.put("java:comp/HandleDelegate", new ObjectReference(SystemInstance.get().getComponent(HandleDelegate.class)));
}
// get JtaEntityManagerRegistry
JtaEntityManagerRegistry jtaEntityManagerRegistry = SystemInstance.get().getComponent(JtaEntityManagerRegistry.class);
// bind UserTransaction if bean managed transactions
if (beanManagedTransactions) {
Object userTransaction = new CoreUserTransaction(transactionManager);
bindings.put("java:comp/UserTransaction", userTransaction);
}
for (EjbReferenceInfo referenceInfo : jndiEnc.ejbReferences) {
Reference reference = null;
if (referenceInfo.location != null) {
reference = buildReferenceLocation(referenceInfo.location);
} else {
// TODO: Before JndiNameStrategy can be used, this assumption has to be updated
if (referenceInfo.homeType == null){
String jndiName = "java:openejb/ejb/" + referenceInfo.ejbDeploymentId + "BusinessRemote";
reference = new IntraVmJndiReference(jndiName);
} else {
// TODO: Before JndiNameStrategy can be used, this assumption has to be updated
String jndiName = "java:openejb/ejb/" + referenceInfo.ejbDeploymentId;
reference = new IntraVmJndiReference(jndiName);
}
}
bindings.put(normalize(referenceInfo.referenceName), wrapReference(reference));
}
for (EjbLocalReferenceInfo referenceInfo : jndiEnc.ejbLocalReferences) {
Reference reference = null;
if (referenceInfo.location != null) {
reference = buildReferenceLocation(referenceInfo.location);
} else if (referenceInfo.homeType == null){
// TODO: Before JndiNameStrategy can be used, this assumption has to be updated
String jndiName = "java:openejb/ejb/" + referenceInfo.ejbDeploymentId + "BusinessLocal";
reference = new IntraVmJndiReference(jndiName);
} else {
String jndiName = "java:openejb/ejb/" + referenceInfo.ejbDeploymentId + "Local";
reference = new IntraVmJndiReference(jndiName);
}
bindings.put(normalize(referenceInfo.referenceName), wrapReference(reference));
}
for (EnvEntryInfo entry : jndiEnc.envEntries) {
if (entry.location != null) {
Reference reference = buildReferenceLocation(entry.location);
bindings.put(normalize(entry.name), reference);
continue;
}
try {
Class type = Class.forName(entry.type.trim());
Object obj = null;
if (type == String.class)
obj = new String(entry.value);
else if (type == Double.class) {
obj = new Double(entry.value);
} else if (type == Integer.class) {
obj = new Integer(entry.value);
} else if (type == Long.class) {
obj = new Long(entry.value);
} else if (type == Float.class) {
obj = new Float(entry.value);
} else if (type == Short.class) {
obj = new Short(entry.value);
} else if (type == Boolean.class) {
obj = new Boolean(entry.value);
} else if (type == Byte.class) {
obj = new Byte(entry.value);
} else if (type == Character.class) {
StringBuilder sb = new StringBuilder(entry.value + " ");
obj = new Character(sb.charAt(0));
} else {
throw new IllegalArgumentException("Invalid env-ref-type " + type);
}
bindings.put(normalize(entry.name), obj);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Invalid environment entry type: " + entry.type.trim() + " for entry: " + entry.name);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("The env-entry-value for entry " + entry.name + " was not recognizable as type " + entry.type + ". Received Message: " + e.getLocalizedMessage());
}
}
for (ResourceReferenceInfo referenceInfo : jndiEnc.resourceRefs) {
Reference reference = null;
if (referenceInfo.location != null) {
reference = buildReferenceLocation(referenceInfo.location);
} else if (referenceInfo.resourceID != null) {
String jndiName = "java:openejb/Connector/" + referenceInfo.resourceID;
reference = new IntraVmJndiReference(jndiName);
} else {
String jndiName = "java:openejb/Connector/" + referenceInfo.referenceName;
reference = new IntraVmJndiReference(jndiName);
}
bindings.put(normalize(referenceInfo.referenceName), wrapReference(reference));
}
for (ResourceEnvReferenceInfo referenceInfo : jndiEnc.resourceEnvRefs) {
LinkRef linkRef = null;
try {
Class<?> type = Class.forName(referenceInfo.resourceEnvRefType, true, EJBContext.class.getClassLoader());
if (EJBContext.class.isAssignableFrom(type)) {
String jndiName = "java:comp/EJBContext";
linkRef = new LinkRef(jndiName);
bindings.put(normalize(referenceInfo.resourceEnvRefName), linkRef);
continue;
}
} catch (ClassNotFoundException e) {
// throw new OpenEJBException(e);
}
if (referenceInfo.location != null){
Reference reference = buildReferenceLocation(referenceInfo.location);
bindings.put(normalize(referenceInfo.resourceEnvRefName), wrapReference(reference));
}
//TODO code for handling other resource-env-refs need to be added here.
}
for (PersistenceUnitReferenceInfo referenceInfo : jndiEnc.persistenceUnitRefs) {
if (referenceInfo.location != null){
Reference reference = buildReferenceLocation(referenceInfo.location);
bindings.put(normalize(referenceInfo.referenceName), wrapReference(reference));
continue;
}
EntityManagerFactory factory = findEntityManagerFactory(referenceInfo.persistenceUnitName);
if (factory == null) {
throw new IllegalArgumentException("Persistence unit " + referenceInfo.persistenceUnitName + " for persistence-unit-ref " +
referenceInfo.referenceName + " not found");
}
Reference reference = new PersistenceUnitReference(factory);
bindings.put(normalize(referenceInfo.referenceName), wrapReference(reference));
}
for (PersistenceContextReferenceInfo contextInfo : jndiEnc.persistenceContextRefs) {
if (contextInfo.location != null){
Reference reference = buildReferenceLocation(contextInfo.location);
bindings.put(normalize(contextInfo.referenceName), wrapReference(reference));
continue;
}
EntityManagerFactory factory = findEntityManagerFactory(contextInfo.persistenceUnitName);
if (factory == null) {
throw new IllegalArgumentException("Persistence unit " + contextInfo.persistenceUnitName + " for persistence-context-ref " +
contextInfo.referenceName + " not found");
}
JtaEntityManager jtaEntityManager = new JtaEntityManager(jtaEntityManagerRegistry, factory, contextInfo.properties, contextInfo.extended);
Reference reference = new PersistenceContextReference(jtaEntityManager);
bindings.put(normalize(contextInfo.referenceName), wrapReference(reference));
}
for (MessageDestinationReferenceInfo referenceInfo : jndiEnc.messageDestinationRefs) {
if (referenceInfo.location != null){
Reference reference = buildReferenceLocation(referenceInfo.location);
bindings.put(normalize(referenceInfo.referenceName), wrapReference(reference));
}
}
for (ServiceReferenceInfo referenceInfo : jndiEnc.serviceRefs) {
if (referenceInfo.location != null){
Reference reference = buildReferenceLocation(referenceInfo.location);
bindings.put(normalize(referenceInfo.referenceName), wrapReference(reference));
}
}
return bindings;
}
private WritableContext createXBeanWritableContext(Map bindings) {
WritableContext context = null;
try {
context = new WritableContext("", bindings);
} catch (NamingException e) {
throw new IllegalStateException(e);
}
return context;
}
private IvmContext createIvmContext() {
IvmContext context = new IvmContext(new NameNode(null, new ParsedName("comp"), null));
try {
context.createSubcontext("comp").createSubcontext("env");
} catch (NamingException e) {
throw new IllegalStateException("Unable to create subcontext 'java:comp/env'. Exception:"+e.getMessage(),e);
}
return context;
}
public static boolean bindingExists(Context context, Name contextName) {
try {
return context.lookup(contextName) != null;
} catch (NamingException e) {
}
return false;
}
private Reference buildReferenceLocation(ReferenceLocationInfo location) {
if (location.jndiProviderId != null){
String subContextName = "java:openejb/remote_jndi_contexts/" + location.jndiProviderId;
return new JndiReference(subContextName, location.jndiName);
} else {
return new JndiUrlReference(location.jndiName);
}
}
private String normalize(String name) {
if (name.charAt(0) == '/')
name = name.substring(1);
if (!(name.startsWith("java:comp/env") || name.startsWith("comp/env"))) {
if (name.startsWith("env/"))
name = "java:comp/" + name;
else
name = "java:comp/env/" + name;
}
return name;
}
private Object wrapReference(Reference reference) {
return reference;
}
public EntityManagerFactory findEntityManagerFactory(String persistenceName) throws OpenEJBException {
if (persistenceName != null && !"".equals(persistenceName)) {
if (persistenceName.indexOf("#") == -1 ) {
EntityManagerFactory factory = localFactories.get(persistenceName);
if (factory != null) return factory;
// search for a unique match in allFactories;
SortedSet<String> absolutePaths = factoryPaths.get(persistenceName);
if (absolutePaths == null || absolutePaths.size() != 1) {
// todo warn with valid names
return null;
}
String absolutePath = absolutePaths.iterator().next();
factory = absoluteFactories.get(absolutePath);
return factory;
} else {
String absoluteName = moduleUri.resolve(persistenceName).toString();
EntityManagerFactory factory = absoluteFactories.get(absoluteName);
return factory;
}
} else if (localFactories.size() == 1) {
return localFactories.values().toArray(new EntityManagerFactory[1])[0];
} else {
throw new OpenEJBException("Deployment failed as the Persistence Unit could not be located. Try adding the 'persistence-unit-name' tag in ejb-jar.xml ");
}
}
}
| true | true | public Map<String, Object> buildMap() throws OpenEJBException {
Map<String, Object> bindings = new HashMap<String, Object>();
// bind TransactionManager
TransactionManager transactionManager = SystemInstance.get().getComponent(TransactionManager.class);
bindings.put("java:comp/TransactionManager", transactionManager);
// bind TransactionSynchronizationRegistry
TransactionSynchronizationRegistry synchronizationRegistry = SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class);
bindings.put("java:comp/TransactionSynchronizationRegistry", synchronizationRegistry);
ORB orb = SystemInstance.get().getComponent(ORB.class);
// bind CORBA stuff
if (orb != null) {
bindings.put("java:comp/ORB", new ObjectReference(orb));
bindings.put("java:comp/HandleDelegate", new ObjectReference(SystemInstance.get().getComponent(ORB.class)));
}
// get JtaEntityManagerRegistry
JtaEntityManagerRegistry jtaEntityManagerRegistry = SystemInstance.get().getComponent(JtaEntityManagerRegistry.class);
// bind UserTransaction if bean managed transactions
if (beanManagedTransactions) {
Object userTransaction = new CoreUserTransaction(transactionManager);
bindings.put("java:comp/UserTransaction", userTransaction);
}
for (EjbReferenceInfo referenceInfo : jndiEnc.ejbReferences) {
Reference reference = null;
if (referenceInfo.location != null) {
reference = buildReferenceLocation(referenceInfo.location);
} else {
// TODO: Before JndiNameStrategy can be used, this assumption has to be updated
if (referenceInfo.homeType == null){
String jndiName = "java:openejb/ejb/" + referenceInfo.ejbDeploymentId + "BusinessRemote";
reference = new IntraVmJndiReference(jndiName);
} else {
// TODO: Before JndiNameStrategy can be used, this assumption has to be updated
String jndiName = "java:openejb/ejb/" + referenceInfo.ejbDeploymentId;
reference = new IntraVmJndiReference(jndiName);
}
}
bindings.put(normalize(referenceInfo.referenceName), wrapReference(reference));
}
for (EjbLocalReferenceInfo referenceInfo : jndiEnc.ejbLocalReferences) {
Reference reference = null;
if (referenceInfo.location != null) {
reference = buildReferenceLocation(referenceInfo.location);
} else if (referenceInfo.homeType == null){
// TODO: Before JndiNameStrategy can be used, this assumption has to be updated
String jndiName = "java:openejb/ejb/" + referenceInfo.ejbDeploymentId + "BusinessLocal";
reference = new IntraVmJndiReference(jndiName);
} else {
String jndiName = "java:openejb/ejb/" + referenceInfo.ejbDeploymentId + "Local";
reference = new IntraVmJndiReference(jndiName);
}
bindings.put(normalize(referenceInfo.referenceName), wrapReference(reference));
}
for (EnvEntryInfo entry : jndiEnc.envEntries) {
if (entry.location != null) {
Reference reference = buildReferenceLocation(entry.location);
bindings.put(normalize(entry.name), reference);
continue;
}
try {
Class type = Class.forName(entry.type.trim());
Object obj = null;
if (type == String.class)
obj = new String(entry.value);
else if (type == Double.class) {
obj = new Double(entry.value);
} else if (type == Integer.class) {
obj = new Integer(entry.value);
} else if (type == Long.class) {
obj = new Long(entry.value);
} else if (type == Float.class) {
obj = new Float(entry.value);
} else if (type == Short.class) {
obj = new Short(entry.value);
} else if (type == Boolean.class) {
obj = new Boolean(entry.value);
} else if (type == Byte.class) {
obj = new Byte(entry.value);
} else if (type == Character.class) {
StringBuilder sb = new StringBuilder(entry.value + " ");
obj = new Character(sb.charAt(0));
} else {
throw new IllegalArgumentException("Invalid env-ref-type " + type);
}
bindings.put(normalize(entry.name), obj);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Invalid environment entry type: " + entry.type.trim() + " for entry: " + entry.name);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("The env-entry-value for entry " + entry.name + " was not recognizable as type " + entry.type + ". Received Message: " + e.getLocalizedMessage());
}
}
for (ResourceReferenceInfo referenceInfo : jndiEnc.resourceRefs) {
Reference reference = null;
if (referenceInfo.location != null) {
reference = buildReferenceLocation(referenceInfo.location);
} else if (referenceInfo.resourceID != null) {
String jndiName = "java:openejb/Connector/" + referenceInfo.resourceID;
reference = new IntraVmJndiReference(jndiName);
} else {
String jndiName = "java:openejb/Connector/" + referenceInfo.referenceName;
reference = new IntraVmJndiReference(jndiName);
}
bindings.put(normalize(referenceInfo.referenceName), wrapReference(reference));
}
for (ResourceEnvReferenceInfo referenceInfo : jndiEnc.resourceEnvRefs) {
LinkRef linkRef = null;
try {
Class<?> type = Class.forName(referenceInfo.resourceEnvRefType, true, EJBContext.class.getClassLoader());
if (EJBContext.class.isAssignableFrom(type)) {
String jndiName = "java:comp/EJBContext";
linkRef = new LinkRef(jndiName);
bindings.put(normalize(referenceInfo.resourceEnvRefName), linkRef);
continue;
}
} catch (ClassNotFoundException e) {
// throw new OpenEJBException(e);
}
if (referenceInfo.location != null){
Reference reference = buildReferenceLocation(referenceInfo.location);
bindings.put(normalize(referenceInfo.resourceEnvRefName), wrapReference(reference));
}
//TODO code for handling other resource-env-refs need to be added here.
}
for (PersistenceUnitReferenceInfo referenceInfo : jndiEnc.persistenceUnitRefs) {
if (referenceInfo.location != null){
Reference reference = buildReferenceLocation(referenceInfo.location);
bindings.put(normalize(referenceInfo.referenceName), wrapReference(reference));
continue;
}
EntityManagerFactory factory = findEntityManagerFactory(referenceInfo.persistenceUnitName);
if (factory == null) {
throw new IllegalArgumentException("Persistence unit " + referenceInfo.persistenceUnitName + " for persistence-unit-ref " +
referenceInfo.referenceName + " not found");
}
Reference reference = new PersistenceUnitReference(factory);
bindings.put(normalize(referenceInfo.referenceName), wrapReference(reference));
}
for (PersistenceContextReferenceInfo contextInfo : jndiEnc.persistenceContextRefs) {
if (contextInfo.location != null){
Reference reference = buildReferenceLocation(contextInfo.location);
bindings.put(normalize(contextInfo.referenceName), wrapReference(reference));
continue;
}
EntityManagerFactory factory = findEntityManagerFactory(contextInfo.persistenceUnitName);
if (factory == null) {
throw new IllegalArgumentException("Persistence unit " + contextInfo.persistenceUnitName + " for persistence-context-ref " +
contextInfo.referenceName + " not found");
}
JtaEntityManager jtaEntityManager = new JtaEntityManager(jtaEntityManagerRegistry, factory, contextInfo.properties, contextInfo.extended);
Reference reference = new PersistenceContextReference(jtaEntityManager);
bindings.put(normalize(contextInfo.referenceName), wrapReference(reference));
}
for (MessageDestinationReferenceInfo referenceInfo : jndiEnc.messageDestinationRefs) {
if (referenceInfo.location != null){
Reference reference = buildReferenceLocation(referenceInfo.location);
bindings.put(normalize(referenceInfo.referenceName), wrapReference(reference));
}
}
for (ServiceReferenceInfo referenceInfo : jndiEnc.serviceRefs) {
if (referenceInfo.location != null){
Reference reference = buildReferenceLocation(referenceInfo.location);
bindings.put(normalize(referenceInfo.referenceName), wrapReference(reference));
}
}
return bindings;
}
| public Map<String, Object> buildMap() throws OpenEJBException {
Map<String, Object> bindings = new HashMap<String, Object>();
// bind TransactionManager
TransactionManager transactionManager = SystemInstance.get().getComponent(TransactionManager.class);
bindings.put("java:comp/TransactionManager", transactionManager);
// bind TransactionSynchronizationRegistry
TransactionSynchronizationRegistry synchronizationRegistry = SystemInstance.get().getComponent(TransactionSynchronizationRegistry.class);
bindings.put("java:comp/TransactionSynchronizationRegistry", synchronizationRegistry);
ORB orb = SystemInstance.get().getComponent(ORB.class);
// bind CORBA stuff
if (orb != null) {
bindings.put("java:comp/ORB", new ObjectReference(orb));
bindings.put("java:comp/HandleDelegate", new ObjectReference(SystemInstance.get().getComponent(HandleDelegate.class)));
}
// get JtaEntityManagerRegistry
JtaEntityManagerRegistry jtaEntityManagerRegistry = SystemInstance.get().getComponent(JtaEntityManagerRegistry.class);
// bind UserTransaction if bean managed transactions
if (beanManagedTransactions) {
Object userTransaction = new CoreUserTransaction(transactionManager);
bindings.put("java:comp/UserTransaction", userTransaction);
}
for (EjbReferenceInfo referenceInfo : jndiEnc.ejbReferences) {
Reference reference = null;
if (referenceInfo.location != null) {
reference = buildReferenceLocation(referenceInfo.location);
} else {
// TODO: Before JndiNameStrategy can be used, this assumption has to be updated
if (referenceInfo.homeType == null){
String jndiName = "java:openejb/ejb/" + referenceInfo.ejbDeploymentId + "BusinessRemote";
reference = new IntraVmJndiReference(jndiName);
} else {
// TODO: Before JndiNameStrategy can be used, this assumption has to be updated
String jndiName = "java:openejb/ejb/" + referenceInfo.ejbDeploymentId;
reference = new IntraVmJndiReference(jndiName);
}
}
bindings.put(normalize(referenceInfo.referenceName), wrapReference(reference));
}
for (EjbLocalReferenceInfo referenceInfo : jndiEnc.ejbLocalReferences) {
Reference reference = null;
if (referenceInfo.location != null) {
reference = buildReferenceLocation(referenceInfo.location);
} else if (referenceInfo.homeType == null){
// TODO: Before JndiNameStrategy can be used, this assumption has to be updated
String jndiName = "java:openejb/ejb/" + referenceInfo.ejbDeploymentId + "BusinessLocal";
reference = new IntraVmJndiReference(jndiName);
} else {
String jndiName = "java:openejb/ejb/" + referenceInfo.ejbDeploymentId + "Local";
reference = new IntraVmJndiReference(jndiName);
}
bindings.put(normalize(referenceInfo.referenceName), wrapReference(reference));
}
for (EnvEntryInfo entry : jndiEnc.envEntries) {
if (entry.location != null) {
Reference reference = buildReferenceLocation(entry.location);
bindings.put(normalize(entry.name), reference);
continue;
}
try {
Class type = Class.forName(entry.type.trim());
Object obj = null;
if (type == String.class)
obj = new String(entry.value);
else if (type == Double.class) {
obj = new Double(entry.value);
} else if (type == Integer.class) {
obj = new Integer(entry.value);
} else if (type == Long.class) {
obj = new Long(entry.value);
} else if (type == Float.class) {
obj = new Float(entry.value);
} else if (type == Short.class) {
obj = new Short(entry.value);
} else if (type == Boolean.class) {
obj = new Boolean(entry.value);
} else if (type == Byte.class) {
obj = new Byte(entry.value);
} else if (type == Character.class) {
StringBuilder sb = new StringBuilder(entry.value + " ");
obj = new Character(sb.charAt(0));
} else {
throw new IllegalArgumentException("Invalid env-ref-type " + type);
}
bindings.put(normalize(entry.name), obj);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Invalid environment entry type: " + entry.type.trim() + " for entry: " + entry.name);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("The env-entry-value for entry " + entry.name + " was not recognizable as type " + entry.type + ". Received Message: " + e.getLocalizedMessage());
}
}
for (ResourceReferenceInfo referenceInfo : jndiEnc.resourceRefs) {
Reference reference = null;
if (referenceInfo.location != null) {
reference = buildReferenceLocation(referenceInfo.location);
} else if (referenceInfo.resourceID != null) {
String jndiName = "java:openejb/Connector/" + referenceInfo.resourceID;
reference = new IntraVmJndiReference(jndiName);
} else {
String jndiName = "java:openejb/Connector/" + referenceInfo.referenceName;
reference = new IntraVmJndiReference(jndiName);
}
bindings.put(normalize(referenceInfo.referenceName), wrapReference(reference));
}
for (ResourceEnvReferenceInfo referenceInfo : jndiEnc.resourceEnvRefs) {
LinkRef linkRef = null;
try {
Class<?> type = Class.forName(referenceInfo.resourceEnvRefType, true, EJBContext.class.getClassLoader());
if (EJBContext.class.isAssignableFrom(type)) {
String jndiName = "java:comp/EJBContext";
linkRef = new LinkRef(jndiName);
bindings.put(normalize(referenceInfo.resourceEnvRefName), linkRef);
continue;
}
} catch (ClassNotFoundException e) {
// throw new OpenEJBException(e);
}
if (referenceInfo.location != null){
Reference reference = buildReferenceLocation(referenceInfo.location);
bindings.put(normalize(referenceInfo.resourceEnvRefName), wrapReference(reference));
}
//TODO code for handling other resource-env-refs need to be added here.
}
for (PersistenceUnitReferenceInfo referenceInfo : jndiEnc.persistenceUnitRefs) {
if (referenceInfo.location != null){
Reference reference = buildReferenceLocation(referenceInfo.location);
bindings.put(normalize(referenceInfo.referenceName), wrapReference(reference));
continue;
}
EntityManagerFactory factory = findEntityManagerFactory(referenceInfo.persistenceUnitName);
if (factory == null) {
throw new IllegalArgumentException("Persistence unit " + referenceInfo.persistenceUnitName + " for persistence-unit-ref " +
referenceInfo.referenceName + " not found");
}
Reference reference = new PersistenceUnitReference(factory);
bindings.put(normalize(referenceInfo.referenceName), wrapReference(reference));
}
for (PersistenceContextReferenceInfo contextInfo : jndiEnc.persistenceContextRefs) {
if (contextInfo.location != null){
Reference reference = buildReferenceLocation(contextInfo.location);
bindings.put(normalize(contextInfo.referenceName), wrapReference(reference));
continue;
}
EntityManagerFactory factory = findEntityManagerFactory(contextInfo.persistenceUnitName);
if (factory == null) {
throw new IllegalArgumentException("Persistence unit " + contextInfo.persistenceUnitName + " for persistence-context-ref " +
contextInfo.referenceName + " not found");
}
JtaEntityManager jtaEntityManager = new JtaEntityManager(jtaEntityManagerRegistry, factory, contextInfo.properties, contextInfo.extended);
Reference reference = new PersistenceContextReference(jtaEntityManager);
bindings.put(normalize(contextInfo.referenceName), wrapReference(reference));
}
for (MessageDestinationReferenceInfo referenceInfo : jndiEnc.messageDestinationRefs) {
if (referenceInfo.location != null){
Reference reference = buildReferenceLocation(referenceInfo.location);
bindings.put(normalize(referenceInfo.referenceName), wrapReference(reference));
}
}
for (ServiceReferenceInfo referenceInfo : jndiEnc.serviceRefs) {
if (referenceInfo.location != null){
Reference reference = buildReferenceLocation(referenceInfo.location);
bindings.put(normalize(referenceInfo.referenceName), wrapReference(reference));
}
}
return bindings;
}
|
diff --git a/src/main/java/org/dasein/cloud/cloudstack/compute/VirtualMachines.java b/src/main/java/org/dasein/cloud/cloudstack/compute/VirtualMachines.java
index f12c7d0..de5e74f 100644
--- a/src/main/java/org/dasein/cloud/cloudstack/compute/VirtualMachines.java
+++ b/src/main/java/org/dasein/cloud/cloudstack/compute/VirtualMachines.java
@@ -1,1484 +1,1485 @@
/**
* Copyright (C) 2009-2013 enstratius, 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.dasein.cloud.cloudstack.compute;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Callable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.dasein.cloud.CloudException;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.ProviderContext;
import org.dasein.cloud.Requirement;
import org.dasein.cloud.ResourceStatus;
import org.dasein.cloud.Tag;
import org.dasein.cloud.cloudstack.CSCloud;
import org.dasein.cloud.cloudstack.CSException;
import org.dasein.cloud.cloudstack.CSMethod;
import org.dasein.cloud.cloudstack.CSServiceProvider;
import org.dasein.cloud.cloudstack.CSTopology;
import org.dasein.cloud.cloudstack.CSVersion;
import org.dasein.cloud.cloudstack.Param;
import org.dasein.cloud.cloudstack.network.Network;
import org.dasein.cloud.cloudstack.network.SecurityGroup;
import org.dasein.cloud.compute.*;
import org.dasein.cloud.network.RawAddress;
import org.dasein.cloud.util.APITrace;
import org.dasein.util.CalendarWrapper;
import org.dasein.util.uom.storage.Gigabyte;
import org.dasein.util.uom.storage.Megabyte;
import org.dasein.util.uom.storage.Storage;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.logicblaze.lingo.util.DefaultTimeoutMap;
public class VirtualMachines extends AbstractVMSupport {
static public final Logger logger = Logger.getLogger(VirtualMachines.class);
static private final String DEPLOY_VIRTUAL_MACHINE = "deployVirtualMachine";
static private final String DESTROY_VIRTUAL_MACHINE = "destroyVirtualMachine";
static private final String GET_VIRTUAL_MACHINE_PASSWORD = "getVMPassword";
static private final String LIST_VIRTUAL_MACHINES = "listVirtualMachines";
static private final String LIST_SERVICE_OFFERINGS = "listServiceOfferings";
static private final String REBOOT_VIRTUAL_MACHINE = "rebootVirtualMachine";
static private final String RESET_VIRTUAL_MACHINE_PASSWORD = "resetPasswordForVirtualMachine";
static private final String RESIZE_VIRTUAL_MACHINE = "scaleVirtualMachine";
static private final String START_VIRTUAL_MACHINE = "startVirtualMachine";
static private final String STOP_VIRTUAL_MACHINE = "stopVirtualMachine";
static private Properties cloudMappings;
static private Map<String,Map<String,String>> customNetworkMappings;
static private Map<String,Map<String,Set<String>>> customServiceMappings;
static private DefaultTimeoutMap productCache = new DefaultTimeoutMap();
private CSCloud provider;
public VirtualMachines(CSCloud provider) {
super(provider);
this.provider = provider;
}
@Override
public VirtualMachine alterVirtualMachine(@Nonnull String vmId, @Nonnull VMScalingOptions options) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.alterVM");
try {
String productId = options.getProviderProductId();
if (vmId == null || options.getProviderProductId() == null) {
throw new CloudException("No vmid and/or product id set for this operation");
}
CSMethod method = new CSMethod(provider);
VirtualMachine vm = getVirtualMachine(vmId);
if (vm.getProductId().equals(productId)) {
return vm;
}
boolean restart = false;
if (!vm.getCurrentState().equals(VmState.STOPPED)) {
restart = true;
stop(vmId, true);
}
long timeout = System.currentTimeMillis()+(CalendarWrapper.MINUTE*20L);
while (System.currentTimeMillis() < timeout) {
if (!vm.getCurrentState().equals(VmState.STOPPED)) {
try {
Thread.sleep(15000L);
vm = getVirtualMachine(vmId);
}
catch (InterruptedException ignore) {}
}
else {
break;
}
}
vm = getVirtualMachine(vmId);
if (!vm.getCurrentState().equals(VmState.STOPPED)) {
throw new CloudException("Unable to stop vm for scaling");
}
Document doc = method.get(method.buildUrl(RESIZE_VIRTUAL_MACHINE, new Param("id", vmId), new Param("serviceOfferingId", productId)), RESIZE_VIRTUAL_MACHINE);
NodeList matches = doc.getElementsByTagName("scalevirtualmachineresponse");
String jobId = null;
for( int i=0; i<matches.getLength(); i++ ) {
NodeList attrs = matches.item(i).getChildNodes();
for( int j=0; j<attrs.getLength(); j++ ) {
Node node = attrs.item(j);
if (node != null && node.getNodeName().equalsIgnoreCase("jobid") ) {
jobId = node.getFirstChild().getNodeValue();
}
}
}
if( jobId == null ) {
throw new CloudException("Could not scale server");
}
Document responseDoc = provider.waitForJob(doc, "Scale Server");
if (responseDoc != null){
NodeList nodeList = responseDoc.getElementsByTagName("virtualmachine");
if (nodeList.getLength() > 0) {
Node virtualMachine = nodeList.item(0);
vm = toVirtualMachine(virtualMachine);
if( vm != null ) {
if (restart) {
start(vmId);
}
return vm;
}
}
}
if (restart) {
start(vmId);
}
return getVirtualMachine(vmId);
}
finally {
APITrace.end();
}
}
@Nullable
@Override
public VMScalingCapabilities describeVerticalScalingCapabilities() throws CloudException, InternalException {
return VMScalingCapabilities.getInstance(false,true,Requirement.NONE,Requirement.NONE);
}
@Override
public int getCostFactor(@Nonnull VmState state) throws InternalException, CloudException {
return 100;
}
@Override
public int getMaximumVirtualMachineCount() throws CloudException, InternalException {
return -2;
}
@Override
public @Nullable VirtualMachineProduct getProduct(@Nonnull String productId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.getProduct");
try {
for( Architecture architecture : Architecture.values() ) {
for( VirtualMachineProduct product : listProducts(architecture) ) {
if( product.getProviderProductId().equals(productId) ) {
return product;
}
}
}
if( logger.isDebugEnabled() ) {
logger.debug("Unknown product ID for cloud.com: " + productId);
}
return null;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull String getProviderTermForServer(@Nonnull Locale locale) {
return "virtual machine";
}
private String getRootPassword(@Nonnull String serverId) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.getPassword");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was specified for this request");
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(GET_VIRTUAL_MACHINE_PASSWORD, new Param("id", serverId)), GET_VIRTUAL_MACHINE_PASSWORD);
if (doc != null){
NodeList matches = doc.getElementsByTagName("getvmpasswordresponse");
for( int i=0; i<matches.getLength(); i++ ) {
Node node = matches.item(i);
if( node != null ) {
NodeList attributes = node.getChildNodes();
for( int j=0; j<attributes.getLength(); j++ ) {
Node attribute = attributes.item(j);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("password") ) {
NodeList nodes = attribute.getChildNodes();
for( int k=0; k<nodes.getLength(); k++ ) {
Node password = nodes.item(k);
name = password.getNodeName().toLowerCase();
if( password.getChildNodes().getLength() > 0 ) {
value = password.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("encryptedpassword") ) {
return value;
}
}
}
}
}
}
}
logger.warn("Unable to find password for vm with id "+serverId);
return null;
}
catch (CSException e) {
if (e.getHttpCode() == 431) {
logger.warn("No password found for vm "+serverId);
}
return null;
}
finally {
APITrace.end();
}
}
@Override
public @Nullable VirtualMachine getVirtualMachine(@Nonnull String serverId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.getVirtualMachine");
try {
CSMethod method = new CSMethod(provider);
try {
Document doc = method.get(method.buildUrl(LIST_VIRTUAL_MACHINES, new Param("id", serverId)), LIST_VIRTUAL_MACHINES);
NodeList matches = doc.getElementsByTagName("virtualmachine");
if( matches.getLength() < 1 ) {
return null;
}
for( int i=0; i<matches.getLength(); i++ ) {
VirtualMachine s = toVirtualMachine(matches.item(i));
if( s != null && s.getProviderVirtualMachineId().equals(serverId) ) {
return s;
}
}
}
catch( CloudException e ) {
if( e.getMessage().contains("does not exist") ) {
return null;
}
throw e;
}
return null;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Requirement identifyImageRequirement(@Nonnull ImageClass cls) throws CloudException, InternalException {
return (cls.equals(ImageClass.MACHINE) ? Requirement.REQUIRED : Requirement.NONE);
}
@Override
public @Nonnull Requirement identifyPasswordRequirement(Platform platform) throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Requirement identifyRootVolumeRequirement() throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Requirement identifyShellKeyRequirement(Platform platform) throws CloudException, InternalException {
return Requirement.OPTIONAL;
}
@Override
public @Nonnull Requirement identifyStaticIPRequirement() throws CloudException, InternalException {
return Requirement.NONE;
}
@Override
public @Nonnull Requirement identifyVlanRequirement() throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.identifyVlanRequirement");
try {
if( provider.getServiceProvider().equals(CSServiceProvider.DATAPIPE) ) {
return Requirement.NONE;
}
if( provider.getVersion().greaterThan(CSVersion.CS21) ) {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was set for this request");
}
String regionId = ctx.getRegionId();
if( regionId == null ) {
throw new CloudException("No region was set for this request");
}
return (provider.getDataCenterServices().requiresNetwork(regionId) ? Requirement.REQUIRED : Requirement.OPTIONAL);
}
return Requirement.OPTIONAL;
}
finally {
APITrace.end();
}
}
@Override
public boolean isAPITerminationPreventable() throws CloudException, InternalException {
return false;
}
@Override
public boolean isBasicAnalyticsSupported() throws CloudException, InternalException {
return false;
}
@Override
public boolean isExtendedAnalyticsSupported() throws CloudException, InternalException {
return false;
}
@Override
public boolean isSubscribed() throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.isSubscribed");
try {
CSMethod method = new CSMethod(provider);
try {
method.get(method.buildUrl(CSTopology.LIST_ZONES, new Param("available", "true")), CSTopology.LIST_ZONES);
return true;
}
catch( CSException e ) {
int code = e.getHttpCode();
if( code == HttpServletResponse.SC_FORBIDDEN || code == 401 || code == 531 ) {
return false;
}
throw e;
}
catch( CloudException e ) {
int code = e.getHttpCode();
if( code == HttpServletResponse.SC_FORBIDDEN || code == HttpServletResponse.SC_UNAUTHORIZED ) {
return false;
}
throw e;
}
}
finally {
APITrace.end();
}
}
@Override
public boolean isUserDataSupported() throws CloudException, InternalException {
return true;
}
@Override
public @Nonnull VirtualMachine launch(@Nonnull VMLaunchOptions withLaunchOptions) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.launch");
try {
String id = withLaunchOptions.getStandardProductId();
VirtualMachineProduct product = getProduct(id);
if( product == null ) {
throw new CloudException("Invalid product ID: " + id);
}
if( provider.getVersion().greaterThan(CSVersion.CS21) ) {
return launch22(withLaunchOptions.getMachineImageId(), product, withLaunchOptions.getDataCenterId(), withLaunchOptions.getFriendlyName(), withLaunchOptions.getBootstrapKey(), withLaunchOptions.getVlanId(), withLaunchOptions.getFirewallIds(), withLaunchOptions.getUserData());
}
else {
return launch21(withLaunchOptions.getMachineImageId(), product, withLaunchOptions.getDataCenterId(), withLaunchOptions.getFriendlyName());
}
}
finally {
APITrace.end();
}
}
@Override
@Deprecated
@SuppressWarnings("deprecation")
public @Nonnull VirtualMachine launch(@Nonnull String imageId, @Nonnull VirtualMachineProduct product, @Nonnull String inZoneId, @Nonnull String name, @Nonnull String description, @Nullable String usingKey, @Nullable String withVlanId, boolean withMonitoring, boolean asSandbox, @Nullable String[] protectedByFirewalls, @Nullable Tag ... tags) throws InternalException, CloudException {
if( provider.getVersion().greaterThan(CSVersion.CS21) ) {
StringBuilder userData = new StringBuilder();
if( tags != null && tags.length > 0 ) {
for( Tag tag : tags ) {
userData.append(tag.getKey());
userData.append("=");
userData.append(tag.getValue());
userData.append("\n");
}
}
else {
userData.append("created=Dasein Cloud\n");
}
return launch22(imageId, product, inZoneId, name, usingKey, withVlanId, protectedByFirewalls, userData.toString());
}
else {
return launch21(imageId, product, inZoneId, name);
}
}
private VirtualMachine launch21(String imageId, VirtualMachineProduct product, String inZoneId, String name) throws InternalException, CloudException {
CSMethod method = new CSMethod(provider);
return launch(method.get(method.buildUrl(DEPLOY_VIRTUAL_MACHINE, new Param("zoneId", getContext().getRegionId()), new Param("serviceOfferingId", product.getProviderProductId()), new Param("templateId", imageId), new Param("displayName", name) ), DEPLOY_VIRTUAL_MACHINE));
}
private void load() {
try {
InputStream input = VirtualMachines.class.getResourceAsStream("/cloudMappings.cfg");
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
Properties properties = new Properties();
String line;
while( (line = reader.readLine()) != null ) {
if( line.startsWith("#") ) {
continue;
}
int idx = line.indexOf('=');
if( idx < 0 || line.endsWith("=") ) {
continue;
}
String cloudUrl = line.substring(0, idx);
String cloudId = line.substring(idx+1);
properties.put(cloudUrl, cloudId);
}
cloudMappings = properties;
}
catch( Throwable ignore ) {
// ignore
}
try {
InputStream input = VirtualMachines.class.getResourceAsStream("/customNetworkMappings.cfg");
HashMap<String,Map<String,String>> mapping = new HashMap<String,Map<String,String>>();
Properties properties = new Properties();
properties.load(input);
for( Object key : properties.keySet() ) {
String[] trueKey = ((String)key).split(",");
Map<String,String> current = mapping.get(trueKey[0]);
if( current == null ) {
current = new HashMap<String,String>();
mapping.put(trueKey[0], current);
}
current.put(trueKey[1], (String)properties.get(key));
}
customNetworkMappings = mapping;
}
catch( Throwable ignore ) {
// ignore
}
try {
InputStream input = VirtualMachines.class.getResourceAsStream("/customServiceMappings.cfg");
HashMap<String,Map<String,Set<String>>> mapping = new HashMap<String,Map<String,Set<String>>>();
Properties properties = new Properties();
properties.load(input);
for( Object key : properties.keySet() ) {
String value = (String)properties.get(key);
if( value != null ) {
String[] trueKey = ((String)key).split(",");
Map<String,Set<String>> tmp = mapping.get(trueKey[0]);
if( tmp == null ) {
tmp =new HashMap<String,Set<String>>();
mapping.put(trueKey[0], tmp);
}
TreeSet<String> m = new TreeSet<String>();
String[] offerings = value.split(",");
if( offerings == null || offerings.length < 1 ) {
m.add(value);
}
else {
Collections.addAll(m, offerings);
}
tmp.put(trueKey[1], m);
}
}
customServiceMappings = mapping;
}
catch( Throwable ignore ) {
// ignore
}
}
private @Nonnull VirtualMachine launch22(@Nonnull String imageId, @Nonnull VirtualMachineProduct product, @Nullable String inZoneId, @Nonnull String name, @Nullable String withKeypair, @Nullable String targetVlanId, @Nullable String[] protectedByFirewalls, @Nullable String userData) throws InternalException, CloudException {
ProviderContext ctx = provider.getContext();
List<String> vlans = null;
if( ctx == null ) {
throw new InternalException("No context was provided for this request");
}
String regionId = ctx.getRegionId();
if( regionId == null ) {
throw new InternalException("No region is established for this request");
}
String prdId = product.getProviderProductId();
if( customNetworkMappings == null ) {
load();
}
if( customNetworkMappings != null ) {
String cloudId = cloudMappings.getProperty(ctx.getEndpoint());
if( cloudId != null ) {
Map<String,String> map = customNetworkMappings.get(cloudId);
if( map != null ) {
String id = map.get(prdId);
if( id != null ) {
targetVlanId = id;
}
}
}
}
if( targetVlanId != null && targetVlanId.length() < 1 ) {
targetVlanId = null;
}
if( userData == null ) {
userData = "";
}
String securityGroupIds = null;
Param[] params;
if( protectedByFirewalls != null && protectedByFirewalls.length > 0 ) {
StringBuilder str = new StringBuilder();
int idx = 0;
for( String fw : protectedByFirewalls ) {
fw = fw.trim();
if( !fw.equals("") ) {
str.append(fw);
if( (idx++) < protectedByFirewalls.length-1 ) {
str.append(",");
}
}
}
securityGroupIds = str.toString();
}
int count = 4;
if( userData != null && userData.length() > 0 ) {
count++;
}
if( withKeypair != null ) {
count++;
}
if( targetVlanId == null ) {
Network vlan = provider.getNetworkServices().getVlanSupport();
if( vlan != null && vlan.isSubscribed() ) {
if( provider.getDataCenterServices().requiresNetwork(regionId) ) {
vlans = vlan.findFreeNetworks();
}
}
}
else {
vlans = new ArrayList<String>();
vlans.add(targetVlanId);
}
if( vlans != null && vlans.size() > 0 ) {
count++;
}
if( securityGroupIds != null && securityGroupIds.length() > 0 ) {
if( !provider.getServiceProvider().equals(CSServiceProvider.DATAPIPE) && !provider.getDataCenterServices().supportsSecurityGroups(regionId, vlans == null || vlans.size() < 1) ) {
securityGroupIds = null;
}
else {
count++;
}
}
else if( provider.getDataCenterServices().supportsSecurityGroups(regionId, vlans == null || vlans.size() < 1) ) {
/*
String sgId = null;
if( withVlanId == null ) {
Collection<Firewall> firewalls = provider.getNetworkServices().getFirewallSupport().list();
for( Firewall fw : firewalls ) {
if( fw.getName().equalsIgnoreCase("default") && fw.getProviderVlanId() == null ) {
sgId = fw.getProviderFirewallId();
break;
}
}
if( sgId == null ) {
try {
sgId = provider.getNetworkServices().getFirewallSupport().create("default", "Default security group");
}
catch( Throwable t ) {
logger.warn("Unable to create a default security group, gonna try anyways: " + t.getMessage());
}
}
if( sgId != null ) {
securityGroupIds = sgId;
}
}
else {
Collection<Firewall> firewalls = provider.getNetworkServices().getFirewallSupport().list();
for( Firewall fw : firewalls ) {
if( (fw.getName().equalsIgnoreCase("default") || fw.getName().equalsIgnoreCase("default-" + withVlanId)) && withVlanId.equals(fw.getProviderVlanId()) ) {
sgId = fw.getProviderFirewallId();
break;
}
}
if( sgId == null ) {
try {
sgId = provider.getNetworkServices().getFirewallSupport().createInVLAN("default-" + withVlanId, "Default " + withVlanId + " security group", withVlanId);
}
catch( Throwable t ) {
logger.warn("Unable to create a default security group, gonna try anyways: " + t.getMessage());
}
}
}
if( sgId != null ) {
securityGroupIds = sgId;
count++;
}
*/
}
params = new Param[count];
params[0] = new Param("zoneId", getContext().getRegionId());
params[1] = new Param("serviceOfferingId", prdId);
params[2] = new Param("templateId", imageId);
params[3] = new Param("displayName", name);
int i = 4;
if( userData != null && userData.length() > 0 ) {
try {
params[i++] = new Param("userdata", new String(Base64.encodeBase64(userData.getBytes("utf-8")), "utf-8"));
}
catch( UnsupportedEncodingException e ) {
e.printStackTrace();
}
}
if( withKeypair != null ) {
params[i++] = new Param("keypair", withKeypair);
}
if( securityGroupIds != null && securityGroupIds.length() > 0 ) {
params[i++] = new Param("securitygroupids", securityGroupIds);
}
if( vlans != null && vlans.size() > 0 ) {
CloudException lastError = null;
for( String withVlanId : vlans ) {
params[i] = new Param("networkIds", withVlanId);
try {
CSMethod method = new CSMethod(provider);
return launch(method.get(method.buildUrl(DEPLOY_VIRTUAL_MACHINE, params), DEPLOY_VIRTUAL_MACHINE));
}
catch( CloudException e ) {
if( e.getMessage().contains("sufficient address capacity") ) {
lastError = e;
continue;
}
throw e;
}
}
if( lastError == null ) {
throw lastError;
}
throw new CloudException("Unable to identify a network into which a VM can be launched");
}
else {
CSMethod method = new CSMethod(provider);
return launch(method.get(method.buildUrl(DEPLOY_VIRTUAL_MACHINE, params), DEPLOY_VIRTUAL_MACHINE));
}
}
private @Nonnull VirtualMachine launch(@Nonnull Document doc) throws InternalException, CloudException {
NodeList matches = doc.getElementsByTagName("deployvirtualmachineresponse");
String serverId = null;
String jobId = null;
for( int i=0; i<matches.getLength(); i++ ) {
NodeList attrs = matches.item(i).getChildNodes();
for( int j=0; j<attrs.getLength(); j++ ) {
Node node = attrs.item(j);
if( node != null && (node.getNodeName().equalsIgnoreCase("virtualmachineid") || node.getNodeName().equalsIgnoreCase("id")) ) {
serverId = node.getFirstChild().getNodeValue();
break;
}
else if (node != null && node.getNodeName().equalsIgnoreCase("jobid") ) {
jobId = node.getFirstChild().getNodeValue();
}
}
if( serverId != null ) {
break;
}
}
if( serverId == null && jobId == null ) {
throw new CloudException("Could not launch server");
}
// TODO: very odd logic below; figure out what it thinks it is doing
VirtualMachine vm = null;
// have to wait on jobs as sometimes they fail and we need to bubble error message up
Document responseDoc = provider.waitForJob(doc, "Launch Server");
//parse vm from job completion response to capture vm passwords on initial launch.
if (responseDoc != null){
NodeList nodeList = responseDoc.getElementsByTagName("virtualmachine");
if (nodeList.getLength() > 0) {
Node virtualMachine = nodeList.item(0);
vm = toVirtualMachine(virtualMachine);
if( vm != null ) {
return vm;
}
}
}
if (vm == null){
vm = getVirtualMachine(serverId);
}
if( vm == null ) {
throw new CloudException("No virtual machine provided: " + serverId);
}
return vm;
}
@Override
public @Nonnull Iterable<String> listFirewalls(@Nonnull String vmId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listFirewalls");
try {
SecurityGroup support = provider.getNetworkServices().getFirewallSupport();
if( support == null ) {
return Collections.emptyList();
}
return support.listFirewallsForVM(vmId);
}
finally {
APITrace.end();
}
}
private void setFirewalls(@Nonnull VirtualMachine vm) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.setFirewalls");
try {
SecurityGroup support = provider.getNetworkServices().getFirewallSupport();
if( support == null ) {
return;
}
ArrayList<String> ids = new ArrayList<String>();
Iterable<String> firewalls;
try {
firewalls = support.listFirewallsForVM(vm.getProviderVirtualMachineId());
} catch (Throwable t) {
logger.error("Problem listing firewalls (listSecurityGroups) for '" + vm.getProviderVirtualMachineId() + "': " + t.getMessage());
return;
}
for( String id : firewalls ) {
ids.add(id);
}
vm.setProviderFirewallIds(ids.toArray(new String[ids.size()]));
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<VirtualMachineProduct> listProducts(@Nonnull Architecture architecture) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listProducts");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was configured for this request");
}
Map<Architecture,Collection<VirtualMachineProduct>> cached;
String endpoint = provider.getContext().getEndpoint();
String accountId = provider.getContext().getAccountNumber();
String regionId = provider.getContext().getRegionId();
productCache.purge();
cached = (HashMap<Architecture, Collection<VirtualMachineProduct>>) productCache.get(endpoint+"_"+accountId+"_"+regionId);
if (cached != null && !cached.isEmpty()) {
if( cached.containsKey(architecture) ) {
Collection<VirtualMachineProduct> products = cached.get(architecture);
if( products != null ) {
return products;
}
}
}
else {
cached = new HashMap<Architecture, Collection<VirtualMachineProduct>>();
productCache.put(endpoint+"_"+accountId+"_"+regionId, cached, CalendarWrapper.HOUR * 4);
}
List<VirtualMachineProduct> products;
Set<String> mapping = null;
if( customServiceMappings == null ) {
load();
}
if( customServiceMappings != null ) {
String cloudId = cloudMappings.getProperty(provider.getContext().getEndpoint());
if( cloudId != null ) {
Map<String,Set<String>> map = customServiceMappings.get(cloudId);
if( map != null ) {
mapping = map.get(provider.getContext().getRegionId());
}
}
}
products = new ArrayList<VirtualMachineProduct>();
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(LIST_SERVICE_OFFERINGS, new Param("zoneId", ctx.getRegionId())), LIST_SERVICE_OFFERINGS);
NodeList matches = doc.getElementsByTagName("serviceoffering");
for( int i=0; i<matches.getLength(); i++ ) {
String id = null, name = null;
Node node = matches.item(i);
NodeList attributes;
int memory = 0;
int cpu = 0;
attributes = node.getChildNodes();
for( int j=0; j<attributes.getLength(); j++ ) {
Node n = attributes.item(j);
String value;
if( n.getChildNodes().getLength() > 0 ) {
value = n.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( n.getNodeName().equals("id") ) {
id = value;
}
else if( n.getNodeName().equals("name") ) {
name = value;
}
else if( n.getNodeName().equals("cpunumber") ) {
cpu = Integer.parseInt(value);
}
else if( n.getNodeName().equals("memory") ) {
memory = Integer.parseInt(value);
}
if( id != null && name != null && cpu > 0 && memory > 0 ) {
break;
}
}
if( id != null ) {
if( mapping == null || mapping.contains(id) ) {
VirtualMachineProduct product;
product = new VirtualMachineProduct();
product.setProviderProductId(id);
product.setName(name + " (" + cpu + " CPU/" + memory + "MB RAM)");
product.setDescription(name + " (" + cpu + " CPU/" + memory + "MB RAM)");
product.setRamSize(new Storage<Megabyte>(memory, Storage.MEGABYTE));
product.setCpuCount(cpu);
product.setRootVolumeSize(new Storage<Gigabyte>(1, Storage.GIGABYTE));
products.add(product);
}
}
}
cached.put(architecture, products);
return products;
}
finally {
APITrace.end();
}
}
private transient Collection<Architecture> architectures;
@Override
public Iterable<Architecture> listSupportedArchitectures() throws InternalException, CloudException {
if( architectures == null ) {
ArrayList<Architecture> a = new ArrayList<Architecture>();
a.add(Architecture.I32);
a.add(Architecture.I64);
architectures = Collections.unmodifiableList(a);
}
return architectures;
}
@Override
public @Nonnull Iterable<ResourceStatus> listVirtualMachineStatus() throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listVirtualMachineStatus");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was specified for this request");
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(LIST_VIRTUAL_MACHINES, new Param("zoneId", ctx.getRegionId())), LIST_VIRTUAL_MACHINES);
ArrayList<ResourceStatus> servers = new ArrayList<ResourceStatus>();
NodeList matches = doc.getElementsByTagName("virtualmachine");
for( int i=0; i<matches.getLength(); i++ ) {
Node node = matches.item(i);
if( node != null ) {
ResourceStatus vm = toStatus(node);
if( vm != null ) {
servers.add(vm);
}
}
}
return servers;
}
finally {
APITrace.end();
}
}
@Override
public @Nonnull Iterable<VirtualMachine> listVirtualMachines() throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.listVirtualMachines");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was specified for this request");
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(LIST_VIRTUAL_MACHINES, new Param("zoneId", ctx.getRegionId())), LIST_VIRTUAL_MACHINES);
ArrayList<VirtualMachine> servers = new ArrayList<VirtualMachine>();
NodeList matches = doc.getElementsByTagName("virtualmachine");
for( int i=0; i<matches.getLength(); i++ ) {
Node node = matches.item(i);
if( node != null ) {
try {
VirtualMachine vm = toVirtualMachine(node);
if( vm != null ) {
servers.add(vm);
}
} catch (Throwable t) {
logger.error("Problem discovering a virtual machine: " + t.getMessage());
}
}
}
return servers;
}
finally {
APITrace.end();
}
}
private String resetPassword(@Nonnull String serverId) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.resetPassword");
try {
ProviderContext ctx = provider.getContext();
if( ctx == null ) {
throw new CloudException("No context was specified for this request");
}
CSMethod method = new CSMethod(provider);
Document doc = method.get(method.buildUrl(RESET_VIRTUAL_MACHINE_PASSWORD, new Param("id", serverId)), RESET_VIRTUAL_MACHINE_PASSWORD);
Document responseDoc = provider.waitForJob(doc, "reset vm password");
if (responseDoc != null){
NodeList matches = responseDoc.getElementsByTagName("virtualmachine");
for( int i=0; i<matches.getLength(); i++ ) {
Node node = matches.item(i);
if( node != null ) {
NodeList attributes = node.getChildNodes();
for( int j=0; j<attributes.getLength(); j++ ) {
Node attribute = attributes.item(j);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("password") ) {
return value;
}
}
}
}
}
logger.warn("Unable to find password for vm with id "+serverId);
return null;
}
finally {
APITrace.end();
}
}
@Override
public void reboot(@Nonnull String serverId) throws CloudException, InternalException {
APITrace.begin(getProvider(), "VM.reboot");
try {
CSMethod method = new CSMethod(provider);
method.get(method.buildUrl(REBOOT_VIRTUAL_MACHINE, new Param("id", serverId)), REBOOT_VIRTUAL_MACHINE);
}
finally {
APITrace.end();
}
}
@Override
public void start(@Nonnull String serverId) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.start");
try {
CSMethod method = new CSMethod(provider);
method.get(method.buildUrl(START_VIRTUAL_MACHINE, new Param("id", serverId)), START_VIRTUAL_MACHINE);
}
finally {
APITrace.end();
}
}
@Override
public void stop(@Nonnull String vmId, boolean force) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.stop");
try {
CSMethod method = new CSMethod(provider);
method.get(method.buildUrl(STOP_VIRTUAL_MACHINE, new Param("id", vmId), new Param("forced", String.valueOf(force))), STOP_VIRTUAL_MACHINE);
}
finally {
APITrace.end();
}
}
@Override
public boolean supportsPauseUnpause(@Nonnull VirtualMachine vm) {
return false;
}
@Override
public boolean supportsStartStop(@Nonnull VirtualMachine vm) {
return true;
}
@Override
public boolean supportsSuspendResume(@Nonnull VirtualMachine vm) {
return false;
}
@Override
public void terminate(@Nonnull String serverId, @Nullable String explanation) throws InternalException, CloudException {
APITrace.begin(getProvider(), "VM.terminate");
try {
CSMethod method = new CSMethod(provider);
method.get(method.buildUrl(DESTROY_VIRTUAL_MACHINE, new Param("id", serverId)), DESTROY_VIRTUAL_MACHINE);
}
finally {
APITrace.end();
}
}
private @Nullable ResourceStatus toStatus(@Nullable Node node) throws CloudException, InternalException {
if( node == null ) {
return null;
}
NodeList attributes = node.getChildNodes();
VmState state = null;
String serverId = null;
for( int i=0; i<attributes.getLength(); i++ ) {
Node attribute = attributes.item(i);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("virtualmachineid") || name.equals("id") ) {
serverId = value;
}
else if( name.equals("state") ) {
if( value == null ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("stopped") ) {
state = VmState.STOPPED;
}
else if( value.equalsIgnoreCase("running") ) {
state = VmState.RUNNING;
}
else if( value.equalsIgnoreCase("stopping") ) {
state = VmState.STOPPING;
}
else if( value.equalsIgnoreCase("starting") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("creating") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("migrating") ) {
state = VmState.REBOOTING;
}
else if( value.equalsIgnoreCase("destroyed") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("error") ) {
logger.warn("VM is in an error state.");
return null;
}
else if( value.equalsIgnoreCase("expunging") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("ha") ) {
state = VmState.REBOOTING;
}
else {
throw new CloudException("Unexpected server state: " + value);
}
}
if( serverId != null && state != null ) {
break;
}
}
if( serverId == null ) {
return null;
}
if( state == null ) {
state = VmState.PENDING;
}
return new ResourceStatus(serverId, state);
}
private @Nullable VirtualMachine toVirtualMachine(@Nullable Node node) throws CloudException, InternalException {
if( node == null ) {
return null;
}
HashMap<String,String> properties = new HashMap<String,String>();
VirtualMachine server = new VirtualMachine();
NodeList attributes = node.getChildNodes();
String productId = null;
server.setProviderOwnerId(provider.getContext().getAccountNumber());
server.setClonable(false);
server.setImagable(false);
server.setPausable(true);
server.setPersistent(true);
+ server.setArchitecture(Architecture.I64);
for( int i=0; i<attributes.getLength(); i++ ) {
Node attribute = attributes.item(i);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("virtualmachineid") || name.equals("id") ) {
server.setProviderVirtualMachineId(value);
logger.info("Processing VM id '" + value + "'");
}
else if( name.equals("name") ) {
server.setDescription(value);
}
/*
else if( name.equals("haenable") ) {
server.setPersistent(value != null && value.equalsIgnoreCase("true"));
}
*/
else if( name.equals("displayname") ) {
server.setName(value);
}
else if( name.equals("ipaddress") ) { // v2.1
if( value != null ) {
server.setPrivateAddresses(new RawAddress(value));
}
server.setPrivateDnsAddress(value);
}
else if( name.equals("password") ) {
server.setRootPassword(value);
}
else if( name.equals("nic") ) { // v2.2
if( attribute.hasChildNodes() ) {
NodeList parts = attribute.getChildNodes();
String addr = null;
for( int j=0; j<parts.getLength(); j++ ) {
Node part = parts.item(j);
if( part.getNodeName().equalsIgnoreCase("ipaddress") ) {
if( part.hasChildNodes() ) {
addr = part.getFirstChild().getNodeValue();
if( addr != null ) {
addr = addr.trim();
}
}
}
else if( part.getNodeName().equalsIgnoreCase("networkid") ) {
server.setProviderVlanId(part.getFirstChild().getNodeValue().trim());
}
}
if( addr != null ) {
boolean pub = false;
if( !addr.startsWith("10.") && !addr.startsWith("192.168.") ) {
if( addr.startsWith("172.") ) {
String[] nums = addr.split("\\.");
if( nums.length != 4 ) {
pub = true;
}
else {
try {
int x = Integer.parseInt(nums[1]);
if( x < 16 || x > 31 ) {
pub = true;
}
}
catch( NumberFormatException ignore ) {
// ignore
}
}
}
else {
pub = true;
}
}
if( pub ) {
server.setPublicAddresses(new RawAddress(addr));
if( server.getPublicDnsAddress() == null ) {
server.setPublicDnsAddress(addr);
}
}
else {
server.setPrivateAddresses(new RawAddress(addr));
if( server.getPrivateDnsAddress() == null ) {
server.setPrivateDnsAddress(addr);
}
}
}
}
}
else if( name.equals("osarchitecture") ) {
if( value != null && value.equals("32") ) {
server.setArchitecture(Architecture.I32);
}
else {
server.setArchitecture(Architecture.I64);
}
}
else if( name.equals("created") ) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); //2009-02-03T05:26:32.612278
try {
server.setCreationTimestamp(df.parse(value).getTime());
}
catch( ParseException e ) {
logger.warn("Invalid date: " + value);
server.setLastBootTimestamp(0L);
}
}
else if( name.equals("state") ) {
VmState state;
//(Running, Stopped, Stopping, Starting, Creating, Migrating, HA).
if( value.equalsIgnoreCase("stopped") ) {
state = VmState.STOPPED;
server.setImagable(true);
}
else if( value.equalsIgnoreCase("running") ) {
state = VmState.RUNNING;
}
else if( value.equalsIgnoreCase("stopping") ) {
state = VmState.STOPPING;
}
else if( value.equalsIgnoreCase("starting") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("creating") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("migrating") ) {
state = VmState.REBOOTING;
}
else if( value.equalsIgnoreCase("destroyed") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("error") ) {
logger.warn("VM is in an error state.");
return null;
}
else if( value.equalsIgnoreCase("expunging") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("ha") ) {
state = VmState.REBOOTING;
}
else {
throw new CloudException("Unexpected server state: " + value);
}
server.setCurrentState(state);
}
else if( name.equals("zoneid") ) {
server.setProviderRegionId(value);
server.setProviderDataCenterId(value);
}
else if( name.equals("templateid") ) {
server.setProviderMachineImageId(value);
}
else if( name.equals("templatename") ) {
Platform platform = Platform.guess(value);
if (platform.equals(Platform.UNKNOWN)){
platform = guessForWindows(value);
}
server.setPlatform(platform);
}
else if( name.equals("serviceofferingid") ) {
productId = value;
}
else if( value != null ) {
properties.put(name, value);
}
}
if( server.getName() == null ) {
server.setName(server.getProviderVirtualMachineId());
}
if( server.getDescription() == null ) {
server.setDescription(server.getName());
}
server.setProviderAssignedIpAddressId(null);
if( server.getProviderRegionId() == null ) {
server.setProviderRegionId(provider.getContext().getRegionId());
}
if( server.getProviderDataCenterId() == null ) {
server.setProviderDataCenterId(provider.getContext().getRegionId());
}
if( productId != null ) {
server.setProductId(productId);
}
if (server.getPlatform().equals(Platform.UNKNOWN) || server.getArchitecture() == null){
Templates support = provider.getComputeServices().getImageSupport();
if (support != null){
MachineImage image =support.getImage(server.getProviderMachineImageId());
if (image != null){
if (server.getPlatform().equals(Platform.UNKNOWN)) {
server.setPlatform(image.getPlatform());
}
if (server.getArchitecture() == null) {
server.setArchitecture(image.getArchitecture());
}
}
}
}
setFirewalls(server);
/*final String finalServerId = server.getProviderVirtualMachineId();
// commenting out for now until we can find a way to return plain text rather than encrypted
server.setPasswordCallback(new Callable<String>() {
@Override
public String call() throws Exception {
return getRootPassword(finalServerId);
}
}
); */
server.setTags(properties);
return server;
}
private Platform guessForWindows(String name){
if (name == null){
return Platform.UNKNOWN;
}
String platform = name.toLowerCase();
if (platform.contains("windows") || platform.contains("win") ){
return Platform.WINDOWS;
}
return Platform.UNKNOWN;
}
}
| true | true | private @Nullable VirtualMachine toVirtualMachine(@Nullable Node node) throws CloudException, InternalException {
if( node == null ) {
return null;
}
HashMap<String,String> properties = new HashMap<String,String>();
VirtualMachine server = new VirtualMachine();
NodeList attributes = node.getChildNodes();
String productId = null;
server.setProviderOwnerId(provider.getContext().getAccountNumber());
server.setClonable(false);
server.setImagable(false);
server.setPausable(true);
server.setPersistent(true);
for( int i=0; i<attributes.getLength(); i++ ) {
Node attribute = attributes.item(i);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("virtualmachineid") || name.equals("id") ) {
server.setProviderVirtualMachineId(value);
logger.info("Processing VM id '" + value + "'");
}
else if( name.equals("name") ) {
server.setDescription(value);
}
/*
else if( name.equals("haenable") ) {
server.setPersistent(value != null && value.equalsIgnoreCase("true"));
}
*/
else if( name.equals("displayname") ) {
server.setName(value);
}
else if( name.equals("ipaddress") ) { // v2.1
if( value != null ) {
server.setPrivateAddresses(new RawAddress(value));
}
server.setPrivateDnsAddress(value);
}
else if( name.equals("password") ) {
server.setRootPassword(value);
}
else if( name.equals("nic") ) { // v2.2
if( attribute.hasChildNodes() ) {
NodeList parts = attribute.getChildNodes();
String addr = null;
for( int j=0; j<parts.getLength(); j++ ) {
Node part = parts.item(j);
if( part.getNodeName().equalsIgnoreCase("ipaddress") ) {
if( part.hasChildNodes() ) {
addr = part.getFirstChild().getNodeValue();
if( addr != null ) {
addr = addr.trim();
}
}
}
else if( part.getNodeName().equalsIgnoreCase("networkid") ) {
server.setProviderVlanId(part.getFirstChild().getNodeValue().trim());
}
}
if( addr != null ) {
boolean pub = false;
if( !addr.startsWith("10.") && !addr.startsWith("192.168.") ) {
if( addr.startsWith("172.") ) {
String[] nums = addr.split("\\.");
if( nums.length != 4 ) {
pub = true;
}
else {
try {
int x = Integer.parseInt(nums[1]);
if( x < 16 || x > 31 ) {
pub = true;
}
}
catch( NumberFormatException ignore ) {
// ignore
}
}
}
else {
pub = true;
}
}
if( pub ) {
server.setPublicAddresses(new RawAddress(addr));
if( server.getPublicDnsAddress() == null ) {
server.setPublicDnsAddress(addr);
}
}
else {
server.setPrivateAddresses(new RawAddress(addr));
if( server.getPrivateDnsAddress() == null ) {
server.setPrivateDnsAddress(addr);
}
}
}
}
}
else if( name.equals("osarchitecture") ) {
if( value != null && value.equals("32") ) {
server.setArchitecture(Architecture.I32);
}
else {
server.setArchitecture(Architecture.I64);
}
}
else if( name.equals("created") ) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); //2009-02-03T05:26:32.612278
try {
server.setCreationTimestamp(df.parse(value).getTime());
}
catch( ParseException e ) {
logger.warn("Invalid date: " + value);
server.setLastBootTimestamp(0L);
}
}
else if( name.equals("state") ) {
VmState state;
//(Running, Stopped, Stopping, Starting, Creating, Migrating, HA).
if( value.equalsIgnoreCase("stopped") ) {
state = VmState.STOPPED;
server.setImagable(true);
}
else if( value.equalsIgnoreCase("running") ) {
state = VmState.RUNNING;
}
else if( value.equalsIgnoreCase("stopping") ) {
state = VmState.STOPPING;
}
else if( value.equalsIgnoreCase("starting") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("creating") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("migrating") ) {
state = VmState.REBOOTING;
}
else if( value.equalsIgnoreCase("destroyed") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("error") ) {
logger.warn("VM is in an error state.");
return null;
}
else if( value.equalsIgnoreCase("expunging") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("ha") ) {
state = VmState.REBOOTING;
}
else {
throw new CloudException("Unexpected server state: " + value);
}
server.setCurrentState(state);
}
else if( name.equals("zoneid") ) {
server.setProviderRegionId(value);
server.setProviderDataCenterId(value);
}
else if( name.equals("templateid") ) {
server.setProviderMachineImageId(value);
}
else if( name.equals("templatename") ) {
Platform platform = Platform.guess(value);
if (platform.equals(Platform.UNKNOWN)){
platform = guessForWindows(value);
}
server.setPlatform(platform);
}
else if( name.equals("serviceofferingid") ) {
productId = value;
}
else if( value != null ) {
properties.put(name, value);
}
}
if( server.getName() == null ) {
server.setName(server.getProviderVirtualMachineId());
}
if( server.getDescription() == null ) {
server.setDescription(server.getName());
}
server.setProviderAssignedIpAddressId(null);
if( server.getProviderRegionId() == null ) {
server.setProviderRegionId(provider.getContext().getRegionId());
}
if( server.getProviderDataCenterId() == null ) {
server.setProviderDataCenterId(provider.getContext().getRegionId());
}
if( productId != null ) {
server.setProductId(productId);
}
if (server.getPlatform().equals(Platform.UNKNOWN) || server.getArchitecture() == null){
Templates support = provider.getComputeServices().getImageSupport();
if (support != null){
MachineImage image =support.getImage(server.getProviderMachineImageId());
if (image != null){
if (server.getPlatform().equals(Platform.UNKNOWN)) {
server.setPlatform(image.getPlatform());
}
if (server.getArchitecture() == null) {
server.setArchitecture(image.getArchitecture());
}
}
}
}
setFirewalls(server);
/*final String finalServerId = server.getProviderVirtualMachineId();
// commenting out for now until we can find a way to return plain text rather than encrypted
server.setPasswordCallback(new Callable<String>() {
@Override
public String call() throws Exception {
return getRootPassword(finalServerId);
}
}
); */
server.setTags(properties);
return server;
}
| private @Nullable VirtualMachine toVirtualMachine(@Nullable Node node) throws CloudException, InternalException {
if( node == null ) {
return null;
}
HashMap<String,String> properties = new HashMap<String,String>();
VirtualMachine server = new VirtualMachine();
NodeList attributes = node.getChildNodes();
String productId = null;
server.setProviderOwnerId(provider.getContext().getAccountNumber());
server.setClonable(false);
server.setImagable(false);
server.setPausable(true);
server.setPersistent(true);
server.setArchitecture(Architecture.I64);
for( int i=0; i<attributes.getLength(); i++ ) {
Node attribute = attributes.item(i);
String name = attribute.getNodeName().toLowerCase();
String value;
if( attribute.getChildNodes().getLength() > 0 ) {
value = attribute.getFirstChild().getNodeValue();
}
else {
value = null;
}
if( name.equals("virtualmachineid") || name.equals("id") ) {
server.setProviderVirtualMachineId(value);
logger.info("Processing VM id '" + value + "'");
}
else if( name.equals("name") ) {
server.setDescription(value);
}
/*
else if( name.equals("haenable") ) {
server.setPersistent(value != null && value.equalsIgnoreCase("true"));
}
*/
else if( name.equals("displayname") ) {
server.setName(value);
}
else if( name.equals("ipaddress") ) { // v2.1
if( value != null ) {
server.setPrivateAddresses(new RawAddress(value));
}
server.setPrivateDnsAddress(value);
}
else if( name.equals("password") ) {
server.setRootPassword(value);
}
else if( name.equals("nic") ) { // v2.2
if( attribute.hasChildNodes() ) {
NodeList parts = attribute.getChildNodes();
String addr = null;
for( int j=0; j<parts.getLength(); j++ ) {
Node part = parts.item(j);
if( part.getNodeName().equalsIgnoreCase("ipaddress") ) {
if( part.hasChildNodes() ) {
addr = part.getFirstChild().getNodeValue();
if( addr != null ) {
addr = addr.trim();
}
}
}
else if( part.getNodeName().equalsIgnoreCase("networkid") ) {
server.setProviderVlanId(part.getFirstChild().getNodeValue().trim());
}
}
if( addr != null ) {
boolean pub = false;
if( !addr.startsWith("10.") && !addr.startsWith("192.168.") ) {
if( addr.startsWith("172.") ) {
String[] nums = addr.split("\\.");
if( nums.length != 4 ) {
pub = true;
}
else {
try {
int x = Integer.parseInt(nums[1]);
if( x < 16 || x > 31 ) {
pub = true;
}
}
catch( NumberFormatException ignore ) {
// ignore
}
}
}
else {
pub = true;
}
}
if( pub ) {
server.setPublicAddresses(new RawAddress(addr));
if( server.getPublicDnsAddress() == null ) {
server.setPublicDnsAddress(addr);
}
}
else {
server.setPrivateAddresses(new RawAddress(addr));
if( server.getPrivateDnsAddress() == null ) {
server.setPrivateDnsAddress(addr);
}
}
}
}
}
else if( name.equals("osarchitecture") ) {
if( value != null && value.equals("32") ) {
server.setArchitecture(Architecture.I32);
}
else {
server.setArchitecture(Architecture.I64);
}
}
else if( name.equals("created") ) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); //2009-02-03T05:26:32.612278
try {
server.setCreationTimestamp(df.parse(value).getTime());
}
catch( ParseException e ) {
logger.warn("Invalid date: " + value);
server.setLastBootTimestamp(0L);
}
}
else if( name.equals("state") ) {
VmState state;
//(Running, Stopped, Stopping, Starting, Creating, Migrating, HA).
if( value.equalsIgnoreCase("stopped") ) {
state = VmState.STOPPED;
server.setImagable(true);
}
else if( value.equalsIgnoreCase("running") ) {
state = VmState.RUNNING;
}
else if( value.equalsIgnoreCase("stopping") ) {
state = VmState.STOPPING;
}
else if( value.equalsIgnoreCase("starting") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("creating") ) {
state = VmState.PENDING;
}
else if( value.equalsIgnoreCase("migrating") ) {
state = VmState.REBOOTING;
}
else if( value.equalsIgnoreCase("destroyed") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("error") ) {
logger.warn("VM is in an error state.");
return null;
}
else if( value.equalsIgnoreCase("expunging") ) {
state = VmState.TERMINATED;
}
else if( value.equalsIgnoreCase("ha") ) {
state = VmState.REBOOTING;
}
else {
throw new CloudException("Unexpected server state: " + value);
}
server.setCurrentState(state);
}
else if( name.equals("zoneid") ) {
server.setProviderRegionId(value);
server.setProviderDataCenterId(value);
}
else if( name.equals("templateid") ) {
server.setProviderMachineImageId(value);
}
else if( name.equals("templatename") ) {
Platform platform = Platform.guess(value);
if (platform.equals(Platform.UNKNOWN)){
platform = guessForWindows(value);
}
server.setPlatform(platform);
}
else if( name.equals("serviceofferingid") ) {
productId = value;
}
else if( value != null ) {
properties.put(name, value);
}
}
if( server.getName() == null ) {
server.setName(server.getProviderVirtualMachineId());
}
if( server.getDescription() == null ) {
server.setDescription(server.getName());
}
server.setProviderAssignedIpAddressId(null);
if( server.getProviderRegionId() == null ) {
server.setProviderRegionId(provider.getContext().getRegionId());
}
if( server.getProviderDataCenterId() == null ) {
server.setProviderDataCenterId(provider.getContext().getRegionId());
}
if( productId != null ) {
server.setProductId(productId);
}
if (server.getPlatform().equals(Platform.UNKNOWN) || server.getArchitecture() == null){
Templates support = provider.getComputeServices().getImageSupport();
if (support != null){
MachineImage image =support.getImage(server.getProviderMachineImageId());
if (image != null){
if (server.getPlatform().equals(Platform.UNKNOWN)) {
server.setPlatform(image.getPlatform());
}
if (server.getArchitecture() == null) {
server.setArchitecture(image.getArchitecture());
}
}
}
}
setFirewalls(server);
/*final String finalServerId = server.getProviderVirtualMachineId();
// commenting out for now until we can find a way to return plain text rather than encrypted
server.setPasswordCallback(new Callable<String>() {
@Override
public String call() throws Exception {
return getRootPassword(finalServerId);
}
}
); */
server.setTags(properties);
return server;
}
|
diff --git a/src/AtomicIncrementRequest.java b/src/AtomicIncrementRequest.java
index 9c48f66..e1fe22d 100644
--- a/src/AtomicIncrementRequest.java
+++ b/src/AtomicIncrementRequest.java
@@ -1,221 +1,225 @@
/*
* Copyright (C) 2010-2012 The Async HBase Authors. All rights reserved.
* This file is part of Async HBase.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the StumbleUpon nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.hbase.async;
import org.jboss.netty.buffer.ChannelBuffer;
/**
* Atomically increments a value in HBase.
*
* <h1>A note on passing {@code byte} arrays in argument</h1>
* None of the method that receive a {@code byte[]} in argument will copy it.
* For more info, please refer to the documentation of {@link HBaseRpc}.
* <h1>A note on passing {@code String}s in argument</h1>
* All strings are assumed to use the platform's default charset.
*/
public final class AtomicIncrementRequest extends HBaseRpc
implements HBaseRpc.HasTable, HBaseRpc.HasKey,
HBaseRpc.HasFamily, HBaseRpc.HasQualifier {
private static final byte[] INCREMENT_COLUMN_VALUE = new byte[] {
'i', 'n', 'c', 'r', 'e', 'm', 'e', 'n', 't',
'C', 'o', 'l', 'u', 'm', 'n',
'V', 'a', 'l', 'u', 'e'
};
private final byte[] family;
private final byte[] qualifier;
private long amount;
private boolean durable = true;
/**
* Constructor.
* <strong>These byte arrays will NOT be copied.</strong>
* @param table The non-empty name of the table to use.
* @param key The row key of the value to increment.
* @param family The column family of the value to increment.
* @param qualifier The column qualifier of the value to increment.
* @param amount Amount by which to increment the value in HBase.
* If negative, the value in HBase will be decremented.
*/
public AtomicIncrementRequest(final byte[] table,
final byte[] key,
final byte[] family,
final byte[] qualifier,
final long amount) {
super(INCREMENT_COLUMN_VALUE, table, key);
KeyValue.checkFamily(family);
KeyValue.checkQualifier(qualifier);
this.family = family;
this.qualifier = qualifier;
this.amount = amount;
}
/**
* Constructor. This is equivalent to:
* {@link #AtomicIncrementRequest(byte[], byte[], byte[], byte[], long)
* AtomicIncrementRequest}{@code (table, key, family, qualifier, 1)}
* <p>
* <strong>These byte arrays will NOT be copied.</strong>
* @param table The non-empty name of the table to use.
* @param key The row key of the value to increment.
* @param family The column family of the value to increment.
* @param qualifier The column qualifier of the value to increment.
*/
public AtomicIncrementRequest(final byte[] table,
final byte[] key,
final byte[] family,
final byte[] qualifier) {
this(table, key, family, qualifier, 1);
}
/**
* Constructor.
* All strings are assumed to use the platform's default charset.
* @param table The non-empty name of the table to use.
* @param key The row key of the value to increment.
* @param family The column family of the value to increment.
* @param qualifier The column qualifier of the value to increment.
* @param amount Amount by which to increment the value in HBase.
* If negative, the value in HBase will be decremented.
*/
public AtomicIncrementRequest(final String table,
final String key,
final String family,
final String qualifier,
final long amount) {
this(table.getBytes(), key.getBytes(), family.getBytes(),
qualifier.getBytes(), amount);
}
/**
* Constructor. This is equivalent to:
* All strings are assumed to use the platform's default charset.
* {@link #AtomicIncrementRequest(String, String, String, String, long)
* AtomicIncrementRequest}{@code (table, key, family, qualifier, 1)}
* @param table The non-empty name of the table to use.
* @param key The row key of the value to increment.
* @param family The column family of the value to increment.
* @param qualifier The column qualifier of the value to increment.
*/
public AtomicIncrementRequest(final String table,
final String key,
final String family,
final String qualifier) {
this(table.getBytes(), key.getBytes(), family.getBytes(),
qualifier.getBytes(), 1);
}
/**
* Returns the amount by which the value is going to be incremented.
*/
public long getAmount() {
return amount;
}
/**
* Changes the amount by which the value is going to be incremented.
* @param amount The new amount. If negative, the value will be decremented.
*/
public void setAmount(final long amount) {
this.amount = amount;
}
@Override
public byte[] table() {
return table;
}
@Override
public byte[] key() {
return key;
}
@Override
public byte[] family() {
return family;
}
@Override
public byte[] qualifier() {
return qualifier;
}
public String toString() {
return super.toStringWithQualifier("AtomicIncrementRequest",
family, qualifier,
", amount=" + amount);
}
// ---------------------- //
// Package private stuff. //
// ---------------------- //
/**
* Changes whether or not this atomic increment should use the WAL.
* @param durable {@code true} to use the WAL, {@code false} otherwise.
*/
void setDurable(final boolean durable) {
this.durable = durable;
}
private int predictSerializedSize() {
int size = 0;
size += 4; // int: Number of parameters.
size += 1; // byte: Type of the 1st parameter.
size += 3; // vint: region name length (3 bytes => max length = 32768).
size += region.name().length; // The region name.
size += 1; // byte: Type of the 2nd parameter.
size += 3; // vint: row key length (3 bytes => max length = 32768).
size += key.length; // The row key.
+ size += 1; // byte: Type of the 3rd parameter.
size += 1; // vint: Family length (guaranteed on 1 byte).
size += family.length; // The family.
+ size += 1; // byte: Type of the 4th parameter.
size += 3; // vint: Qualifier length.
size += qualifier.length; // The qualifier.
+ size += 1; // byte: Type of the 5th parameter.
size += 8; // long: Amount.
+ size += 1; // byte: Type of the 6th parameter.
size += 1; // bool: Whether or not to write to the WAL.
return size;
}
/** Serializes this request. */
ChannelBuffer serialize(final byte server_version) {
final ChannelBuffer buf = newBuffer(server_version,
predictSerializedSize());
buf.writeInt(6); // Number of parameters.
writeHBaseByteArray(buf, region.name());
writeHBaseByteArray(buf, key);
writeHBaseByteArray(buf, family);
writeHBaseByteArray(buf, qualifier);
writeHBaseLong(buf, amount);
writeHBaseBool(buf, durable);
return buf;
}
}
| false | true | private int predictSerializedSize() {
int size = 0;
size += 4; // int: Number of parameters.
size += 1; // byte: Type of the 1st parameter.
size += 3; // vint: region name length (3 bytes => max length = 32768).
size += region.name().length; // The region name.
size += 1; // byte: Type of the 2nd parameter.
size += 3; // vint: row key length (3 bytes => max length = 32768).
size += key.length; // The row key.
size += 1; // vint: Family length (guaranteed on 1 byte).
size += family.length; // The family.
size += 3; // vint: Qualifier length.
size += qualifier.length; // The qualifier.
size += 8; // long: Amount.
size += 1; // bool: Whether or not to write to the WAL.
return size;
}
| private int predictSerializedSize() {
int size = 0;
size += 4; // int: Number of parameters.
size += 1; // byte: Type of the 1st parameter.
size += 3; // vint: region name length (3 bytes => max length = 32768).
size += region.name().length; // The region name.
size += 1; // byte: Type of the 2nd parameter.
size += 3; // vint: row key length (3 bytes => max length = 32768).
size += key.length; // The row key.
size += 1; // byte: Type of the 3rd parameter.
size += 1; // vint: Family length (guaranteed on 1 byte).
size += family.length; // The family.
size += 1; // byte: Type of the 4th parameter.
size += 3; // vint: Qualifier length.
size += qualifier.length; // The qualifier.
size += 1; // byte: Type of the 5th parameter.
size += 8; // long: Amount.
size += 1; // byte: Type of the 6th parameter.
size += 1; // bool: Whether or not to write to the WAL.
return size;
}
|
diff --git a/src/org/ssgwt/client/ui/form/ComplexInput.java b/src/org/ssgwt/client/ui/form/ComplexInput.java
index 065374b..c250a3a 100644
--- a/src/org/ssgwt/client/ui/form/ComplexInput.java
+++ b/src/org/ssgwt/client/ui/form/ComplexInput.java
@@ -1,666 +1,667 @@
package org.ssgwt.client.ui.form;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
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.HasValue;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import org.ssgwt.client.ui.form.event.ComplexInputFormRemoveEvent;
import org.ssgwt.client.ui.form.event.ComplexInputFormAddEvent;
/**
* Abstract Complex Input is an input field that contains a dynamic form and a
* view ui that is binded and used to display the view state of the field
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param <T> is the type if data used like a VO
*/
public abstract class ComplexInput<T> extends Composite
implements
HasValue<T>,
InputField<T, T>,
ComplexInputFormRemoveEvent.ComplexInputFormRemoveHasHandlers,
ComplexInputFormAddEvent.ComplexInputFormAddHasHandlers {
/**
* This is the main panel.
*/
protected FlowPanel mainPanel = new FlowPanel();
/**
* The panel that holds the dynamicForm.
*/
protected FlowPanel dynamicFormPanel = new FlowPanel();
/**
* The panel that holds the view.
*
* The ui binder is added to it
*/
protected FlowPanel viewPanel = new FlowPanel();
/**
* The panel data contains the data of the field.
*
* The view and dynamicForm.
*/
protected FlowPanel dataPanel = new FlowPanel();
/**
* Panel that holds the action buttons
*/
private FlowPanel actionPanel = new FlowPanel();
/**
* The Panel that holds the view buttons
*/
protected FlowPanel viewButtons = new FlowPanel();
/**
* The Panel that holds the edit buttons
*/
protected FlowPanel editButtons = new FlowPanel();
/**
* The save buttons.
*/
protected Button saveButton = new Button("Save");
/**
* The undo button
*/
protected Button undoButton = new Button("Undo");
/**
* The add buttons
*/
protected Button addButton = new Button("Add");
/**
* The edit label
*/
protected Label editLabel = new Label("Edit /");
/**
* The remove label
*/
protected Label removeLabel = new Label("Remove");
/**
* The panel that will be used to display either the info message
* or the validation error
*/
private FlowPanel messagePanel;
/**
* The table-panel that will be used to display either the info message
* or the validation error
*/
private FlowPanel messageTable;
/**
* The row-panel that will be used to display either the info message
* or the validation error
*/
private FlowPanel messageRow;
/**
* The cell-label that will hold either the info message or the
* validation error
*/
private Label messageCell;
/**
* Flowpanel to hold the message panel
*/
private FlowPanel messageContainer;
/**
* Injected Object
*/
protected Object injectedObject;
/**
* Class constructor
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
public ComplexInput() {
initWidget(mainPanel);
}
/**
* Style to display elements inline
*/
private String displayInline = "ssGWT-displayInlineBlockMiddel";
/**
* language Input Click Labels style
*/
private String languageInputClickLabels = "ssGWT-languageInputClickLabels";
/**
* Save Button style
*/
private String complexSaveButton = "ssGWT-complexSaveButton";
/**
* Label Button style
*/
private String complexLabelButton = "ssGWT-complexLabelButton";
/**
* Undo Button style
*/
private String complexUndoButton = "ssGWT-complexUndoButton";
/**
* Add Button style
*/
private String complexAddButton = "ssGWT-complexAddButton";
/**
* Action Container style
*/
private String complexActionContainer = "ssGWT-complexActionContainer";
/**
* Function to construct all the components and add it to the main panel
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
public void constructor() {
//create view components
messagePanel = new FlowPanel();
messageTable = new FlowPanel();
messageRow = new FlowPanel();
messageCell = new Label();
messageContainer = new FlowPanel();
messageContainer.add(messagePanel);
messagePanel.setVisible(false);
mainPanel.add(messagePanel);
dynamicFormPanel.add(getDynamicForm());
dynamicFormPanel.setStyleName(displayInline);
viewPanel.add(getUiBinder());
viewPanel.setStyleName(displayInline);
viewPanel.setVisible(false);
dataPanel.add(dynamicFormPanel);
dataPanel.add(viewPanel);
dataPanel.setStyleName(displayInline);
viewButtons.add(editLabel);
editLabel.setStyleName(displayInline, true);
editLabel.setStyleName(languageInputClickLabels, true);
editLabel.setStyleName(complexLabelButton, true);
viewButtons.add(removeLabel);
removeLabel.setStyleName(displayInline, true);
removeLabel.setStyleName(languageInputClickLabels, true);
removeLabel.setStyleName(complexLabelButton, true);
viewButtons.setStyleName(displayInline, true);
editButtons.add(saveButton);
saveButton.setStyleName(complexSaveButton);
editButtons.add(undoButton);
undoButton.setStyleName(displayInline);
undoButton.setStyleName(complexUndoButton, true);
editButtons.setStyleName(displayInline);
addButton.setStyleName(complexAddButton);
actionPanel.add(addButton);
actionPanel.setStyleName(displayInline);
actionPanel.setStyleName(complexActionContainer, true);
mainPanel.add(dataPanel);
mainPanel.add(actionPanel);
/**
* Add click handler on editLabel
*/
editLabel.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
setEditDtate();
}
});
/**
* Add click handler on removeLabel
*/
removeLabel.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
removeField();
}
});
/**
* Add click handler on addButton
*/
addButton.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
addField();
}
});
/**
* Add click handler on saveButton
*/
saveButton.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
saveField();
}
});
/**
* Add click handler on undoButton
*/
undoButton.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
+ clearMessage();
setViewState();
}
});
}
/**
* Abstract function for the get of the ui view
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @return the ui as a Widget
*/
public abstract Widget getUiBinder();
/**
* Abstract function for the get of the DynamicForm
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @return the DynamicForm
*/
public abstract DynamicForm<T> getDynamicForm();
/**
* Abstract function to set the field in a view state
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
public abstract void setViewState();
/**
* Abstract function to set the field in a edit state
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
public abstract void setEditDtate();
/**
* Abstract function to set the field in a add state
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
public abstract void setAddState();
/**
* Abstract function that will be called on click of the save button is clicked
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
public abstract void saveField();
/**
* Abstract function that will be called on click of the add button is clicked
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
public abstract void addField();
/**
* Abstract function that will be called on click of the remove button is clicked
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
public abstract void removeField();
/**
* If the need arise for the field to have ValueChangeHandler added to it
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param handler - The Value Change Handler
*/
@Override
public HandlerRegistration addValueChangeHandler(ValueChangeHandler<T> handler) {
return null;
}
/**
* Function that will set a widget in the action container
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param widget - The widget to set
*/
protected void setActionPanel(Widget widget) {
actionPanel.clear();
actionPanel.add(widget);
}
/**
* Function that will add a widget in the action container
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param widget - The widget to add
*/
protected void addToActionPanel(Widget widget) {
actionPanel.add(widget);
}
/**
* Function that will remove a widget in the action container
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param widget - The widget to remove
*/
protected void removeFromActionPanel(Widget widget) {
actionPanel.remove(widget);
}
/**
* Function that will clear the action container
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
protected void clearActionPanel() {
actionPanel.clear();
}
/**
* Getter for the view panel
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @return the view panel
*/
protected FlowPanel getViewPanel() {
return this.viewPanel;
}
/**
* Getter for the dynamic panel
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @return the dynamic panel
*/
protected FlowPanel getDynamicFormPanel() {
return this.dynamicFormPanel;
}
/**
* Set the add button to the action container.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
protected void setAddButton() {
setActionPanel(addButton);
}
/**
* Set the view buttons to the action container.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
protected void setViewButtons() {
setActionPanel(viewButtons);
}
/**
* Set the edit button to the action container.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*/
protected void setEditButtons() {
setActionPanel(editButtons);
}
/**
* A setter for an inject object
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param object - The object to inject
*/
public void setInjectedObject(Object object) {
this.injectedObject = object;
}
/**
* Return the field as a widget
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @return the field as a widget
*/
@Override
public Widget getInputFieldWidget() {
return this.getWidget();
}
/**
* Set the message panel to visible and sets an error message
* on it. Also applies the error style.
*
* @param message String to display as message
*
* @author Alec Erasmus <[email protected]>
* @since 26 November 2012
*/
public void displayValidationError(String message) {
this.clearMessage();
messageCell.setText(message);
messageCell.setStyleName("messageErrorCell");
messageRow.setStyleName("messageRow");
messageTable.setStyleName("messageTable");
messagePanel.setStyleName("ssGWT-complexMessagePanel");
messageRow.add(messageCell);
messageTable.add(messageRow);
messagePanel.add(messageTable);
messagePanel.setVisible(true);
}
/**
* Set the message panel to visible and sets an info message
* on it. Also applies the info style.
*
* @param message String to display as message
*
* @author Alec Erasmus <[email protected]>
* @since 26 November 2012
*/
public void displayInfoMessage(String message) {
this.clearMessage();
messageCell.setText(message);
messageCell.setStyleName("messageInfoCell");
messageRow.setStyleName("messageRow");
messageTable.setStyleName("messageTable");
messagePanel.setStyleName("ssGWT-complexMessagePanel");
messageRow.add(messageCell);
messageTable.add(messageRow);
messagePanel.add(messageTable);
messagePanel.setVisible(true);
}
/**
* Clear the message panel of messages and sets it's
* visibility to false.
*
* @author Ashwin Arendse <[email protected]>
* @since 12 November 2012
*/
public void clearMessage() {
messagePanel.setVisible(false);
messageCell.setText("");
messagePanel.clear();
}
/**
* Function force implementation due to class inheritance
*/
@Override
@Deprecated
public Class<T> getReturnType() {
return null;
}
/**
* Function force implementation due to class inheritance
*/
@Deprecated
@Override
public boolean isRequired() {
return false;
}
/**
* Function force implementation due to class inheritance
*/
@Override
@Deprecated
public void setRequired(boolean required) {
}
/**
* Function force implementation due to class inheritance
*/
@Override
@Deprecated
public void setReadOnly(boolean readOnly) {
}
/**
* Function force implementation due to class inheritance
*/
@Override
@Deprecated
public boolean isReadOnly() {
return false;
}
/**
* Function force implementation due to class inheritance
*/
@Override
@Deprecated
public void setValue(T value, boolean fireEvents) {
}
/**
* Function force implementation due to class inheritance
*/
@Override
@Deprecated
public void setValue(T object, T value) {
}
/**
* Function force implementation due to class inheritance
*/
@Override
@Deprecated
public T getValue(T object) {
return null;
}
}
| true | true | public void constructor() {
//create view components
messagePanel = new FlowPanel();
messageTable = new FlowPanel();
messageRow = new FlowPanel();
messageCell = new Label();
messageContainer = new FlowPanel();
messageContainer.add(messagePanel);
messagePanel.setVisible(false);
mainPanel.add(messagePanel);
dynamicFormPanel.add(getDynamicForm());
dynamicFormPanel.setStyleName(displayInline);
viewPanel.add(getUiBinder());
viewPanel.setStyleName(displayInline);
viewPanel.setVisible(false);
dataPanel.add(dynamicFormPanel);
dataPanel.add(viewPanel);
dataPanel.setStyleName(displayInline);
viewButtons.add(editLabel);
editLabel.setStyleName(displayInline, true);
editLabel.setStyleName(languageInputClickLabels, true);
editLabel.setStyleName(complexLabelButton, true);
viewButtons.add(removeLabel);
removeLabel.setStyleName(displayInline, true);
removeLabel.setStyleName(languageInputClickLabels, true);
removeLabel.setStyleName(complexLabelButton, true);
viewButtons.setStyleName(displayInline, true);
editButtons.add(saveButton);
saveButton.setStyleName(complexSaveButton);
editButtons.add(undoButton);
undoButton.setStyleName(displayInline);
undoButton.setStyleName(complexUndoButton, true);
editButtons.setStyleName(displayInline);
addButton.setStyleName(complexAddButton);
actionPanel.add(addButton);
actionPanel.setStyleName(displayInline);
actionPanel.setStyleName(complexActionContainer, true);
mainPanel.add(dataPanel);
mainPanel.add(actionPanel);
/**
* Add click handler on editLabel
*/
editLabel.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
setEditDtate();
}
});
/**
* Add click handler on removeLabel
*/
removeLabel.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
removeField();
}
});
/**
* Add click handler on addButton
*/
addButton.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
addField();
}
});
/**
* Add click handler on saveButton
*/
saveButton.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
saveField();
}
});
/**
* Add click handler on undoButton
*/
undoButton.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
setViewState();
}
});
}
| public void constructor() {
//create view components
messagePanel = new FlowPanel();
messageTable = new FlowPanel();
messageRow = new FlowPanel();
messageCell = new Label();
messageContainer = new FlowPanel();
messageContainer.add(messagePanel);
messagePanel.setVisible(false);
mainPanel.add(messagePanel);
dynamicFormPanel.add(getDynamicForm());
dynamicFormPanel.setStyleName(displayInline);
viewPanel.add(getUiBinder());
viewPanel.setStyleName(displayInline);
viewPanel.setVisible(false);
dataPanel.add(dynamicFormPanel);
dataPanel.add(viewPanel);
dataPanel.setStyleName(displayInline);
viewButtons.add(editLabel);
editLabel.setStyleName(displayInline, true);
editLabel.setStyleName(languageInputClickLabels, true);
editLabel.setStyleName(complexLabelButton, true);
viewButtons.add(removeLabel);
removeLabel.setStyleName(displayInline, true);
removeLabel.setStyleName(languageInputClickLabels, true);
removeLabel.setStyleName(complexLabelButton, true);
viewButtons.setStyleName(displayInline, true);
editButtons.add(saveButton);
saveButton.setStyleName(complexSaveButton);
editButtons.add(undoButton);
undoButton.setStyleName(displayInline);
undoButton.setStyleName(complexUndoButton, true);
editButtons.setStyleName(displayInline);
addButton.setStyleName(complexAddButton);
actionPanel.add(addButton);
actionPanel.setStyleName(displayInline);
actionPanel.setStyleName(complexActionContainer, true);
mainPanel.add(dataPanel);
mainPanel.add(actionPanel);
/**
* Add click handler on editLabel
*/
editLabel.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
setEditDtate();
}
});
/**
* Add click handler on removeLabel
*/
removeLabel.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
removeField();
}
});
/**
* Add click handler on addButton
*/
addButton.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
addField();
}
});
/**
* Add click handler on saveButton
*/
saveButton.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
saveField();
}
});
/**
* Add click handler on undoButton
*/
undoButton.addClickHandler(new ClickHandler() {
/**
* Event cached on click of the component.
*
* @author Alec Erasmus <[email protected]>
* @since 22 November 2012
*
* @param event - The click event
*/
@Override
public void onClick(ClickEvent event) {
clearMessage();
setViewState();
}
});
}
|
diff --git a/src/main/java/me/eccentric_nz/TARDIS/listeners/TARDISSaveSignListener.java b/src/main/java/me/eccentric_nz/TARDIS/listeners/TARDISSaveSignListener.java
index d5ad5a66e..612297288 100644
--- a/src/main/java/me/eccentric_nz/TARDIS/listeners/TARDISSaveSignListener.java
+++ b/src/main/java/me/eccentric_nz/TARDIS/listeners/TARDISSaveSignListener.java
@@ -1,216 +1,216 @@
/*
* Copyright (C) 2013 eccentric_nz
*
* 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 me.eccentric_nz.TARDIS.listeners;
import java.util.HashMap;
import java.util.List;
import me.eccentric_nz.TARDIS.TARDIS;
import me.eccentric_nz.TARDIS.database.QueryFactory;
import me.eccentric_nz.TARDIS.database.ResultSetCurrentLocation;
import me.eccentric_nz.TARDIS.database.ResultSetTardis;
import me.eccentric_nz.TARDIS.database.ResultSetTravellers;
import me.eccentric_nz.TARDIS.enumeration.MESSAGE;
import me.eccentric_nz.TARDIS.travel.TARDISAreasInventory;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
/**
*
* @author eccentric_nz
*/
public class TARDISSaveSignListener implements Listener {
private final TARDIS plugin;
public TARDISSaveSignListener(TARDIS plugin) {
this.plugin = plugin;
}
/**
* Listens for player clicking inside an inventory. If the inventory is a
* TARDIS GUI, then the click is processed accordingly.
*
* @param event a player clicking an inventory slot
*/
@EventHandler(priority = EventPriority.NORMAL)
public void onSaveTerminalClick(InventoryClickEvent event) {
Inventory inv = event.getInventory();
String name = inv.getTitle();
if (name.equals("§4TARDIS saves")) {
event.setCancelled(true);
int slot = event.getRawSlot();
final Player player = (Player) event.getWhoClicked();
if (slot >= 0 && slot < 45) {
String playerNameStr = player.getName();
// get the TARDIS the player is in
HashMap<String, Object> wheres = new HashMap<String, Object>();
wheres.put("player", playerNameStr);
ResultSetTravellers rst = new ResultSetTravellers(plugin, wheres, false);
if (rst.resultSet()) {
int id = rst.getTardis_id();
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("tardis_id", id);
ResultSetCurrentLocation rsc = new ResultSetCurrentLocation(plugin, where);
Location current = null;
if (rsc.resultSet()) {
current = new Location(rsc.getWorld(), rsc.getX(), rsc.getY(), rsc.getZ());
}
ItemStack is = inv.getItem(slot);
if (is != null) {
ItemMeta im = is.getItemMeta();
List<String> lore = im.getLore();
Location save_dest = getLocation(lore);
if (save_dest != null) {
// check the player is allowed!
if (!plugin.getPluginRespect().getRespect(player, save_dest, true)) {
close(player);
return;
}
// get tardis artron level
HashMap<String, Object> wherel = new HashMap<String, Object>();
wherel.put("tardis_id", id);
- ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false);
+ ResultSetTardis rs = new ResultSetTardis(plugin, wherel, "", false);
if (!rs.resultSet()) {
close(player);
return;
}
int level = rs.getArtron_level();
int travel = plugin.getArtronConfig().getInt("travel");
if (level < travel) {
player.sendMessage(plugin.getPluginName() + ChatColor.RED + MESSAGE.NOT_ENOUGH_ENERGY.getText());
close(player);
return;
}
if (!plugin.getTardisArea().areaCheckInExisting(save_dest)) {
// save is in a TARDIS area, so check that the spot is not occupied
HashMap<String, Object> wheresave = new HashMap<String, Object>();
wheresave.put("world", lore.get(0));
wheresave.put("x", lore.get(1));
wheresave.put("y", lore.get(2));
wheresave.put("z", lore.get(3));
ResultSetCurrentLocation rsz = new ResultSetCurrentLocation(plugin, wheresave);
if (rsz.resultSet()) {
player.sendMessage(plugin.getPluginName() + "A TARDIS already occupies this parking spot! Try using the " + ChatColor.AQUA + "/tardistravel area [name]" + ChatColor.RESET + " command instead.");
close(player);
return;
}
}
if (!save_dest.equals(current)) {
HashMap<String, Object> set = new HashMap<String, Object>();
set.put("world", lore.get(0));
set.put("x", plugin.getUtils().parseInt(lore.get(1)));
set.put("y", plugin.getUtils().parseInt(lore.get(2)));
set.put("z", plugin.getUtils().parseInt(lore.get(3)));
int l_size = lore.size();
if (l_size >= 5) {
if (!lore.get(4).isEmpty() && !lore.get(4).equals("§6Current location")) {
set.put("direction", lore.get(4));
}
if (l_size > 5 && !lore.get(5).isEmpty() && lore.get(5).equals("true")) {
set.put("submarine", 1);
} else {
set.put("submarine", 0);
}
}
HashMap<String, Object> wheret = new HashMap<String, Object>();
wheret.put("tardis_id", id);
new QueryFactory(plugin).doUpdate("next", set, wheret);
plugin.getTrackerKeeper().getTrackHasDestination().put(id, plugin.getArtronConfig().getInt("random"));
if (plugin.getTrackerKeeper().getTrackRescue().containsKey(Integer.valueOf(id))) {
plugin.getTrackerKeeper().getTrackRescue().remove(Integer.valueOf(id));
}
close(player);
player.sendMessage(plugin.getPluginName() + im.getDisplayName() + " destination set. Please release the handbrake!");
} else if (!lore.contains("§6Current location")) {
lore.add("§6Current location");
im.setLore(lore);
is.setItemMeta(im);
}
} else {
close(player);
player.sendMessage(plugin.getPluginName() + im.getDisplayName() + " is not a valid destination!");
}
}
}
}
if (slot == 49) {
// load TARDIS areas
close(player);
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
TARDISAreasInventory sst = new TARDISAreasInventory(plugin, player);
ItemStack[] items = sst.getTerminal();
Inventory areainv = plugin.getServer().createInventory(player, 54, "§4TARDIS areas");
areainv.setContents(items);
player.openInventory(areainv);
}
}, 2L);
}
}
}
/**
* Converts an Item Stacks lore to a destination string.
*
* @param lore the lore to read
* @return the destination string
*/
private String getDestination(List<String> lore) {
return lore.get(0) + ":" + lore.get(1) + ":" + lore.get(2) + ":" + lore.get(3);
}
/**
* Converts an Item Stacks lore to a Location.
*
* @param lore the lore to read
* @return a Location
*/
private Location getLocation(List<String> lore) {
World w = plugin.getServer().getWorld(lore.get(0));
if (w == null) {
return null;
}
int x = plugin.getUtils().parseInt(lore.get(1));
int y = plugin.getUtils().parseInt(lore.get(2));
int z = plugin.getUtils().parseInt(lore.get(3));
return new Location(w, x, y, z);
}
/**
* Closes the inventory.
*
* @param p the player using the GUI
*/
private void close(final Player p) {
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
p.closeInventory();
}
}, 1L);
}
}
| true | true | public void onSaveTerminalClick(InventoryClickEvent event) {
Inventory inv = event.getInventory();
String name = inv.getTitle();
if (name.equals("§4TARDIS saves")) {
event.setCancelled(true);
int slot = event.getRawSlot();
final Player player = (Player) event.getWhoClicked();
if (slot >= 0 && slot < 45) {
String playerNameStr = player.getName();
// get the TARDIS the player is in
HashMap<String, Object> wheres = new HashMap<String, Object>();
wheres.put("player", playerNameStr);
ResultSetTravellers rst = new ResultSetTravellers(plugin, wheres, false);
if (rst.resultSet()) {
int id = rst.getTardis_id();
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("tardis_id", id);
ResultSetCurrentLocation rsc = new ResultSetCurrentLocation(plugin, where);
Location current = null;
if (rsc.resultSet()) {
current = new Location(rsc.getWorld(), rsc.getX(), rsc.getY(), rsc.getZ());
}
ItemStack is = inv.getItem(slot);
if (is != null) {
ItemMeta im = is.getItemMeta();
List<String> lore = im.getLore();
Location save_dest = getLocation(lore);
if (save_dest != null) {
// check the player is allowed!
if (!plugin.getPluginRespect().getRespect(player, save_dest, true)) {
close(player);
return;
}
// get tardis artron level
HashMap<String, Object> wherel = new HashMap<String, Object>();
wherel.put("tardis_id", id);
ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false);
if (!rs.resultSet()) {
close(player);
return;
}
int level = rs.getArtron_level();
int travel = plugin.getArtronConfig().getInt("travel");
if (level < travel) {
player.sendMessage(plugin.getPluginName() + ChatColor.RED + MESSAGE.NOT_ENOUGH_ENERGY.getText());
close(player);
return;
}
if (!plugin.getTardisArea().areaCheckInExisting(save_dest)) {
// save is in a TARDIS area, so check that the spot is not occupied
HashMap<String, Object> wheresave = new HashMap<String, Object>();
wheresave.put("world", lore.get(0));
wheresave.put("x", lore.get(1));
wheresave.put("y", lore.get(2));
wheresave.put("z", lore.get(3));
ResultSetCurrentLocation rsz = new ResultSetCurrentLocation(plugin, wheresave);
if (rsz.resultSet()) {
player.sendMessage(plugin.getPluginName() + "A TARDIS already occupies this parking spot! Try using the " + ChatColor.AQUA + "/tardistravel area [name]" + ChatColor.RESET + " command instead.");
close(player);
return;
}
}
if (!save_dest.equals(current)) {
HashMap<String, Object> set = new HashMap<String, Object>();
set.put("world", lore.get(0));
set.put("x", plugin.getUtils().parseInt(lore.get(1)));
set.put("y", plugin.getUtils().parseInt(lore.get(2)));
set.put("z", plugin.getUtils().parseInt(lore.get(3)));
int l_size = lore.size();
if (l_size >= 5) {
if (!lore.get(4).isEmpty() && !lore.get(4).equals("§6Current location")) {
set.put("direction", lore.get(4));
}
if (l_size > 5 && !lore.get(5).isEmpty() && lore.get(5).equals("true")) {
set.put("submarine", 1);
} else {
set.put("submarine", 0);
}
}
HashMap<String, Object> wheret = new HashMap<String, Object>();
wheret.put("tardis_id", id);
new QueryFactory(plugin).doUpdate("next", set, wheret);
plugin.getTrackerKeeper().getTrackHasDestination().put(id, plugin.getArtronConfig().getInt("random"));
if (plugin.getTrackerKeeper().getTrackRescue().containsKey(Integer.valueOf(id))) {
plugin.getTrackerKeeper().getTrackRescue().remove(Integer.valueOf(id));
}
close(player);
player.sendMessage(plugin.getPluginName() + im.getDisplayName() + " destination set. Please release the handbrake!");
} else if (!lore.contains("§6Current location")) {
lore.add("§6Current location");
im.setLore(lore);
is.setItemMeta(im);
}
} else {
close(player);
player.sendMessage(plugin.getPluginName() + im.getDisplayName() + " is not a valid destination!");
}
}
}
}
if (slot == 49) {
// load TARDIS areas
close(player);
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
TARDISAreasInventory sst = new TARDISAreasInventory(plugin, player);
ItemStack[] items = sst.getTerminal();
Inventory areainv = plugin.getServer().createInventory(player, 54, "§4TARDIS areas");
areainv.setContents(items);
player.openInventory(areainv);
}
}, 2L);
}
}
}
| public void onSaveTerminalClick(InventoryClickEvent event) {
Inventory inv = event.getInventory();
String name = inv.getTitle();
if (name.equals("§4TARDIS saves")) {
event.setCancelled(true);
int slot = event.getRawSlot();
final Player player = (Player) event.getWhoClicked();
if (slot >= 0 && slot < 45) {
String playerNameStr = player.getName();
// get the TARDIS the player is in
HashMap<String, Object> wheres = new HashMap<String, Object>();
wheres.put("player", playerNameStr);
ResultSetTravellers rst = new ResultSetTravellers(plugin, wheres, false);
if (rst.resultSet()) {
int id = rst.getTardis_id();
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("tardis_id", id);
ResultSetCurrentLocation rsc = new ResultSetCurrentLocation(plugin, where);
Location current = null;
if (rsc.resultSet()) {
current = new Location(rsc.getWorld(), rsc.getX(), rsc.getY(), rsc.getZ());
}
ItemStack is = inv.getItem(slot);
if (is != null) {
ItemMeta im = is.getItemMeta();
List<String> lore = im.getLore();
Location save_dest = getLocation(lore);
if (save_dest != null) {
// check the player is allowed!
if (!plugin.getPluginRespect().getRespect(player, save_dest, true)) {
close(player);
return;
}
// get tardis artron level
HashMap<String, Object> wherel = new HashMap<String, Object>();
wherel.put("tardis_id", id);
ResultSetTardis rs = new ResultSetTardis(plugin, wherel, "", false);
if (!rs.resultSet()) {
close(player);
return;
}
int level = rs.getArtron_level();
int travel = plugin.getArtronConfig().getInt("travel");
if (level < travel) {
player.sendMessage(plugin.getPluginName() + ChatColor.RED + MESSAGE.NOT_ENOUGH_ENERGY.getText());
close(player);
return;
}
if (!plugin.getTardisArea().areaCheckInExisting(save_dest)) {
// save is in a TARDIS area, so check that the spot is not occupied
HashMap<String, Object> wheresave = new HashMap<String, Object>();
wheresave.put("world", lore.get(0));
wheresave.put("x", lore.get(1));
wheresave.put("y", lore.get(2));
wheresave.put("z", lore.get(3));
ResultSetCurrentLocation rsz = new ResultSetCurrentLocation(plugin, wheresave);
if (rsz.resultSet()) {
player.sendMessage(plugin.getPluginName() + "A TARDIS already occupies this parking spot! Try using the " + ChatColor.AQUA + "/tardistravel area [name]" + ChatColor.RESET + " command instead.");
close(player);
return;
}
}
if (!save_dest.equals(current)) {
HashMap<String, Object> set = new HashMap<String, Object>();
set.put("world", lore.get(0));
set.put("x", plugin.getUtils().parseInt(lore.get(1)));
set.put("y", plugin.getUtils().parseInt(lore.get(2)));
set.put("z", plugin.getUtils().parseInt(lore.get(3)));
int l_size = lore.size();
if (l_size >= 5) {
if (!lore.get(4).isEmpty() && !lore.get(4).equals("§6Current location")) {
set.put("direction", lore.get(4));
}
if (l_size > 5 && !lore.get(5).isEmpty() && lore.get(5).equals("true")) {
set.put("submarine", 1);
} else {
set.put("submarine", 0);
}
}
HashMap<String, Object> wheret = new HashMap<String, Object>();
wheret.put("tardis_id", id);
new QueryFactory(plugin).doUpdate("next", set, wheret);
plugin.getTrackerKeeper().getTrackHasDestination().put(id, plugin.getArtronConfig().getInt("random"));
if (plugin.getTrackerKeeper().getTrackRescue().containsKey(Integer.valueOf(id))) {
plugin.getTrackerKeeper().getTrackRescue().remove(Integer.valueOf(id));
}
close(player);
player.sendMessage(plugin.getPluginName() + im.getDisplayName() + " destination set. Please release the handbrake!");
} else if (!lore.contains("§6Current location")) {
lore.add("§6Current location");
im.setLore(lore);
is.setItemMeta(im);
}
} else {
close(player);
player.sendMessage(plugin.getPluginName() + im.getDisplayName() + " is not a valid destination!");
}
}
}
}
if (slot == 49) {
// load TARDIS areas
close(player);
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
TARDISAreasInventory sst = new TARDISAreasInventory(plugin, player);
ItemStack[] items = sst.getTerminal();
Inventory areainv = plugin.getServer().createInventory(player, 54, "§4TARDIS areas");
areainv.setContents(items);
player.openInventory(areainv);
}
}, 2L);
}
}
}
|
diff --git a/src/org/olap4j/driver/xmla/XmlaOlap4jCatalog.java b/src/org/olap4j/driver/xmla/XmlaOlap4jCatalog.java
index 3e951c1..979df3d 100644
--- a/src/org/olap4j/driver/xmla/XmlaOlap4jCatalog.java
+++ b/src/org/olap4j/driver/xmla/XmlaOlap4jCatalog.java
@@ -1,120 +1,120 @@
/*
// $Id$
// This software is subject to the terms of the Eclipse Public License v1.0
// Agreement, available at the following URL:
// http://www.eclipse.org/legal/epl-v10.html.
// Copyright (C) 2007-2010 Julian Hyde
// All Rights Reserved.
// You must accept the terms of that agreement to use this software.
*/
package org.olap4j.driver.xmla;
import org.olap4j.OlapDatabaseMetaData;
import org.olap4j.OlapException;
import org.olap4j.impl.Named;
import org.olap4j.impl.Olap4jUtil;
import org.olap4j.metadata.*;
/**
* Implementation of {@link org.olap4j.metadata.Catalog}
* for XML/A providers.
*
* @author jhyde
* @version $Id$
* @since May 23, 2007
*/
class XmlaOlap4jCatalog implements Catalog, Named {
final XmlaOlap4jDatabaseMetaData olap4jDatabaseMetaData;
private final String name;
final DeferredNamedListImpl<XmlaOlap4jSchema> schemas;
private final XmlaOlap4jDatabase database;
XmlaOlap4jCatalog(
XmlaOlap4jDatabaseMetaData olap4jDatabaseMetaData,
XmlaOlap4jDatabase database,
String name)
{
this.database = database;
assert olap4jDatabaseMetaData != null;
assert name != null;
this.olap4jDatabaseMetaData = olap4jDatabaseMetaData;
this.name = name;
// Some servers don't support MDSCHEMA_MDSCHEMATA, so we will
// override the list class so it tries it first, and falls
// back to the MDSCHEMA_CUBES trick, where ask for the cubes,
// restricting results on the catalog, and while
// iterating on the cubes, take the schema name from this recordset.
//
// Many servers (SSAS for example) won't support the schema name column
// in the returned rowset. This has to be taken into account as well.
this.schemas =
new DeferredNamedListImpl<XmlaOlap4jSchema>(
XmlaOlap4jConnection.MetadataRequest.DBSCHEMA_SCHEMATA,
new XmlaOlap4jConnection.Context(
olap4jDatabaseMetaData.olap4jConnection,
olap4jDatabaseMetaData,
this,
null, null, null, null, null),
- new XmlaOlap4jConnection.SchemaHandler(),
+ new XmlaOlap4jConnection.CatalogSchemaHandler(this.name),
null)
{
@Override
protected void populateList(NamedList<XmlaOlap4jSchema> list)
throws OlapException
{
// First try DBSCHEMA_SCHEMATA
try {
super.populateList(list);
} catch (OlapException e) {
// Fallback to MDSCHEMA_CUBES trick
XmlaOlap4jConnection conn =
XmlaOlap4jCatalog.this
.olap4jDatabaseMetaData.olap4jConnection;
conn.populateList(
list,
new XmlaOlap4jConnection.Context(
conn,
conn.olap4jDatabaseMetaData,
XmlaOlap4jCatalog.this,
null, null, null, null, null),
XmlaOlap4jConnection.MetadataRequest
.MDSCHEMA_CUBES,
new XmlaOlap4jConnection.CatalogSchemaHandler(
XmlaOlap4jCatalog.this.name),
new Object[0]);
}
}
};
}
public int hashCode() {
return name.hashCode();
}
public boolean equals(Object obj) {
if (obj instanceof XmlaOlap4jCatalog) {
XmlaOlap4jCatalog that = (XmlaOlap4jCatalog) obj;
return this.name.equals(that.name);
}
return false;
}
public NamedList<Schema> getSchemas() throws OlapException {
return Olap4jUtil.cast(schemas);
}
public String getName() {
return name;
}
public OlapDatabaseMetaData getMetaData() {
return olap4jDatabaseMetaData;
}
public XmlaOlap4jDatabase getDatabase() {
return database;
}
}
// End XmlaOlap4jCatalog.java
| true | true | XmlaOlap4jCatalog(
XmlaOlap4jDatabaseMetaData olap4jDatabaseMetaData,
XmlaOlap4jDatabase database,
String name)
{
this.database = database;
assert olap4jDatabaseMetaData != null;
assert name != null;
this.olap4jDatabaseMetaData = olap4jDatabaseMetaData;
this.name = name;
// Some servers don't support MDSCHEMA_MDSCHEMATA, so we will
// override the list class so it tries it first, and falls
// back to the MDSCHEMA_CUBES trick, where ask for the cubes,
// restricting results on the catalog, and while
// iterating on the cubes, take the schema name from this recordset.
//
// Many servers (SSAS for example) won't support the schema name column
// in the returned rowset. This has to be taken into account as well.
this.schemas =
new DeferredNamedListImpl<XmlaOlap4jSchema>(
XmlaOlap4jConnection.MetadataRequest.DBSCHEMA_SCHEMATA,
new XmlaOlap4jConnection.Context(
olap4jDatabaseMetaData.olap4jConnection,
olap4jDatabaseMetaData,
this,
null, null, null, null, null),
new XmlaOlap4jConnection.SchemaHandler(),
null)
{
@Override
protected void populateList(NamedList<XmlaOlap4jSchema> list)
throws OlapException
{
// First try DBSCHEMA_SCHEMATA
try {
super.populateList(list);
} catch (OlapException e) {
// Fallback to MDSCHEMA_CUBES trick
XmlaOlap4jConnection conn =
XmlaOlap4jCatalog.this
.olap4jDatabaseMetaData.olap4jConnection;
conn.populateList(
list,
new XmlaOlap4jConnection.Context(
conn,
conn.olap4jDatabaseMetaData,
XmlaOlap4jCatalog.this,
null, null, null, null, null),
XmlaOlap4jConnection.MetadataRequest
.MDSCHEMA_CUBES,
new XmlaOlap4jConnection.CatalogSchemaHandler(
XmlaOlap4jCatalog.this.name),
new Object[0]);
}
}
};
}
| XmlaOlap4jCatalog(
XmlaOlap4jDatabaseMetaData olap4jDatabaseMetaData,
XmlaOlap4jDatabase database,
String name)
{
this.database = database;
assert olap4jDatabaseMetaData != null;
assert name != null;
this.olap4jDatabaseMetaData = olap4jDatabaseMetaData;
this.name = name;
// Some servers don't support MDSCHEMA_MDSCHEMATA, so we will
// override the list class so it tries it first, and falls
// back to the MDSCHEMA_CUBES trick, where ask for the cubes,
// restricting results on the catalog, and while
// iterating on the cubes, take the schema name from this recordset.
//
// Many servers (SSAS for example) won't support the schema name column
// in the returned rowset. This has to be taken into account as well.
this.schemas =
new DeferredNamedListImpl<XmlaOlap4jSchema>(
XmlaOlap4jConnection.MetadataRequest.DBSCHEMA_SCHEMATA,
new XmlaOlap4jConnection.Context(
olap4jDatabaseMetaData.olap4jConnection,
olap4jDatabaseMetaData,
this,
null, null, null, null, null),
new XmlaOlap4jConnection.CatalogSchemaHandler(this.name),
null)
{
@Override
protected void populateList(NamedList<XmlaOlap4jSchema> list)
throws OlapException
{
// First try DBSCHEMA_SCHEMATA
try {
super.populateList(list);
} catch (OlapException e) {
// Fallback to MDSCHEMA_CUBES trick
XmlaOlap4jConnection conn =
XmlaOlap4jCatalog.this
.olap4jDatabaseMetaData.olap4jConnection;
conn.populateList(
list,
new XmlaOlap4jConnection.Context(
conn,
conn.olap4jDatabaseMetaData,
XmlaOlap4jCatalog.this,
null, null, null, null, null),
XmlaOlap4jConnection.MetadataRequest
.MDSCHEMA_CUBES,
new XmlaOlap4jConnection.CatalogSchemaHandler(
XmlaOlap4jCatalog.this.name),
new Object[0]);
}
}
};
}
|
diff --git a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/unresolved/UnresolvedUnknownUsageInfo.java b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/unresolved/UnresolvedUnknownUsageInfo.java
index f5a49cfd..aa13da6b 100644
--- a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/unresolved/UnresolvedUnknownUsageInfo.java
+++ b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/unresolved/UnresolvedUnknownUsageInfo.java
@@ -1,1014 +1,1015 @@
package jp.ac.osaka_u.ist.sel.metricstool.main.data.target.unresolved;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import jp.ac.osaka_u.ist.sel.metricstool.main.Settings;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.CallableUnitInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ClassInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ClassInfoManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ClassReferenceInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.ClassTypeInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.EntityUsageInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.FieldInfoManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.FieldUsageInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.Members;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.MethodInfoManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetClassInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetFieldInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TargetInnerClassInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.TypeParameterInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.UnknownEntityUsageInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.UnknownTypeInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.external.ExternalClassInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.target.external.ExternalFieldInfo;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.DefaultMessagePrinter;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessagePrinter;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessageSource;
import jp.ac.osaka_u.ist.sel.metricstool.main.io.MessagePrinter.MESSAGE_TYPE;
import jp.ac.osaka_u.ist.sel.metricstool.main.security.MetricsToolSecurityManager;
import jp.ac.osaka_u.ist.sel.metricstool.main.util.LANGUAGE;
/**
* �������G���e�B�e�B�g�p��ۑ����邽�߂̃N���X�D �������G���e�B�e�B�g�p�Ƃ́C�p�b�P�[�W����N���X���̎Q�� ��\���D
*
* @author higo
*
*/
public final class UnresolvedUnknownUsageInfo extends UnresolvedEntityUsageInfo {
/**
* �������G���e�B�e�B�g�p�I�u�W�F�N�g���쐬����D
*
* @param availableNamespaces ���p�\�Ȗ��O���
* @param name �������G���e�B�e�B�g�p��
*/
public UnresolvedUnknownUsageInfo(final Set<AvailableNamespaceInfo> availableNamespaces,
final String[] name, final int fromLine, final int fromColumn, final int toLine,
final int toColumn) {
this.availableNamespaces = availableNamespaces;
this.name = name;
this.setFromLine(fromLine);
this.setFromColumn(fromColumn);
this.setToLine(toLine);
this.setToColumn(toColumn);
this.resolvedIndo = null;
}
/**
* �������G���e�B�e�B�g�p����������Ă��邩�ǂ�����Ԃ�
*
* @return ��������Ă���ꍇ�� true�C�����łȂ��ꍇ�� false
*/
@Override
public boolean alreadyResolved() {
return null != this.resolvedIndo;
}
/**
* �����ς݃G���e�B�e�B�g�p��Ԃ�
*
* @return �����ς݃G���e�B�e�B�g�p
* @throws ��������Ă��Ȃ��ꍇ�ɃX���[�����
*/
@Override
public EntityUsageInfo getResolvedEntityUsage() {
if (!this.alreadyResolved()) {
throw new NotResolvedException();
}
return this.resolvedIndo;
}
@Override
public EntityUsageInfo resolveEntityUsage(final TargetClassInfo usingClass,
final CallableUnitInfo usingMethod, final ClassInfoManager classInfoManager,
final FieldInfoManager fieldInfoManager, final MethodInfoManager methodInfoManager) {
// �s���ȌĂяo���łȂ������`�F�b�N
MetricsToolSecurityManager.getInstance().checkAccess();
if ((null == usingClass) || (null == usingMethod) || (null == classInfoManager)
|| (null == methodInfoManager)) {
throw new NullPointerException();
}
// ���ɉ����ς݂ł���ꍇ�́C�L���b�V����Ԃ�
if (this.alreadyResolved()) {
return this.getResolvedEntityUsage();
}
// �G���e�B�e�B�Q�Ɩ����擾
final String[] name = this.getName();
// �ʒu�����擾
final int fromLine = this.getFromLine();
final int fromColumn = this.getFromColumn();
final int toLine = this.getToLine();
final int toColumn = this.getToColumn();
// ���p�\�ȃC���X�^���X�t�B�[���h������G���e�B�e�B��������
{
// ���̃N���X�ŗ��p�\�ȃC���X�^���X�t�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFieldsOfThisClass = Members
.<TargetFieldInfo> getInstanceMembers(NameResolver
.getAvailableFields(usingClass));
for (final TargetFieldInfo availableFieldOfThisClass : availableFieldsOfThisClass) {
// ��v����t�B�[���h�������������ꍇ
if (name[0].equals(availableFieldOfThisClass.getName())) {
// usingMethod.addReferencee(availableFieldOfThisClass);
// availableFieldOfThisClass.addReferencer(usingMethod);
// �e�̌^��
final ClassTypeInfo usingClassType = new ClassTypeInfo(usingClass);
for (final TypeParameterInfo typeParameter : usingClass.getTypeParameters()) {
usingClassType.addTypeArgument(typeParameter);
}
// availableField.getType() ���玟��word(name[i])�𖼑O����
EntityUsageInfo entityUsage = new FieldUsageInfo(usingClassType,
availableFieldOfThisClass, true, fromLine, fromColumn, toLine, toColumn);
for (int i = 1; i < name.length; i++) {
// �e�� UnknownTypeInfo ��������C�ǂ����悤���Ȃ�
if (entityUsage.getType() instanceof UnknownTypeInfo) {
this.resolvedIndo = new UnknownEntityUsageInfo(fromLine, fromColumn,
toLine, toColumn);
return this.resolvedIndo;
// �e���N���X�^�̏ꍇ
} else if (entityUsage.getType() instanceof ClassTypeInfo) {
final ClassInfo ownerClass = ((ClassTypeInfo) entityUsage.getType())
.getReferencedClass();
// �e���ΏۃN���X(TargetClassInfo)�̏ꍇ
if (ownerClass instanceof TargetClassInfo) {
// �܂��͗��p�\�ȃt�B�[���h�ꗗ���擾
boolean found = false;
{
// ���p�\�ȃC���X�^���X�t�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFields = Members
.getInstanceMembers(NameResolver.getAvailableFields(
(TargetClassInfo) ownerClass, usingClass));
for (final TargetFieldInfo availableField : availableFields) {
// ��v����t�B�[���h�������������ꍇ
if (name[i].equals(availableField.getName())) {
// usingMethod.addReferencee(availableField);
// availableField.addReferencer(usingMethod);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
availableField, true, fromLine, fromColumn,
toLine, toColumn);
found = true;
break;
}
}
}
// ���p�\�ȃt�B�[���h��������Ȃ������ꍇ�́C�O���N���X�ł���e�N���X������͂��D
// ���̃N���X�̃t�B�[���h���g�p���Ă���Ƃ݂Ȃ�
{
if (!found) {
final ClassInfo referencedClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
final ExternalClassInfo externalSuperClass = NameResolver
.getExternalSuperClass((TargetClassInfo) referencedClass);
if (!(referencedClass instanceof TargetInnerClassInfo)
&& (null != externalSuperClass)) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], externalSuperClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
fieldInfo, true, fromLine, fromColumn, toLine,
toColumn);
} else {
assert false : "Can't resolve entity usage1 : "
+ this.toString();
}
}
}
// �e���O���N���X(ExternalClassInfo)�̏ꍇ
} else if (ownerClass instanceof ExternalClassInfo) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(name[i],
ownerClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(), fieldInfo,
true, fromLine, fromColumn, toLine, toColumn);
}
} else {
assert false : "Here shouldn't be reached!";
}
}
this.resolvedIndo = entityUsage;
return this.resolvedIndo;
}
}
}
// ���p�\�ȃX�^�e�B�b�N�t�B�[���h������G���e�B�e�B��������
{
// ���̃N���X�ŗ��p�\�ȃX�^�e�B�b�N�t�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFieldsOfThisClass = Members
.<TargetFieldInfo> getStaticMembers(NameResolver.getAvailableFields(usingClass));
for (final TargetFieldInfo availableFieldOfThisClass : availableFieldsOfThisClass) {
// ��v����t�B�[���h�������������ꍇ
if (name[0].equals(availableFieldOfThisClass.getName())) {
// usingMethod.addReferencee(availableFieldOfThisClass);
// availableFieldOfThisClass.addReferencer(usingMethod);
// �e�̌^��
final ClassTypeInfo usingClassType = new ClassTypeInfo(usingClass);
for (final TypeParameterInfo typeParameter : usingClass.getTypeParameters()) {
usingClassType.addTypeArgument(typeParameter);
}
// availableField.getType() ���玟��word(name[i])�𖼑O����
EntityUsageInfo entityUsage = new FieldUsageInfo(usingClassType,
availableFieldOfThisClass, true, fromLine, fromColumn, toLine, toColumn);
for (int i = 1; i < name.length; i++) {
// �e�� UnknownTypeInfo ��������C�ǂ����悤���Ȃ�
if (entityUsage.getType() instanceof UnknownTypeInfo) {
this.resolvedIndo = new UnknownEntityUsageInfo(fromLine, fromColumn,
toLine, toColumn);
return this.resolvedIndo;
// �e���N���X�^�̏ꍇ
} else if (entityUsage.getType() instanceof ClassTypeInfo) {
final ClassInfo ownerClass = ((ClassTypeInfo) entityUsage.getType())
.getReferencedClass();
// �e���ΏۃN���X(TargetClassInfo)�̏ꍇ
if (ownerClass instanceof TargetClassInfo) {
// �܂��͗��p�\�ȃt�B�[���h�ꗗ���擾
boolean found = false;
{
// ���p�\�ȃX�^�e�B�b�N�t�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFields = Members
.getStaticMembers(NameResolver.getAvailableFields(
(TargetClassInfo) ownerClass, usingClass));
for (final TargetFieldInfo availableField : availableFields) {
// ��v����t�B�[���h�������������ꍇ
if (name[i].equals(availableField.getName())) {
// usingMethod.addReferencee(availableField);
// availableField.addReferencer(usingMethod);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
availableField, true, fromLine, fromColumn,
toLine, toColumn);
found = true;
break;
}
}
}
// �X�^�e�B�b�N�t�B�[���h�Ō�����Ȃ������ꍇ�́C�C���i�[�N���X����T��
{
if (!found) {
// �C���i�[�N���X�ꗗ���擾
final SortedSet<TargetInnerClassInfo> innerClasses = NameResolver
.getAvailableDirectInnerClasses((TargetClassInfo) ownerClass);
for (final TargetInnerClassInfo innerClass : innerClasses) {
// ��v����N���X�������������ꍇ
if (name[i].equals(innerClass.getClassName())) {
// TODO ���p�W���\�z����R�[�h���K�v�H
final ClassTypeInfo referenceType = new ClassTypeInfo(
innerClass);
entityUsage = new ClassReferenceInfo(referenceType,
fromLine, fromColumn, toLine, toColumn);
found = true;
break;
}
}
}
}
// ���p�\�ȃt�B�[���h��������Ȃ������ꍇ�́C�O���N���X�ł���e�N���X������͂��D
// ���̃N���X�̃t�B�[���h���g�p���Ă���Ƃ݂Ȃ�
{
if (!found) {
final ClassInfo referencedClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
final ExternalClassInfo externalSuperClass = NameResolver
.getExternalSuperClass((TargetClassInfo) referencedClass);
if (!(referencedClass instanceof TargetInnerClassInfo)
&& (null != externalSuperClass)) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], externalSuperClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
fieldInfo, true, fromLine, fromColumn, toLine,
toColumn);
} else {
assert false : "Can't resolve entity usage2 : "
+ this.toString();
}
}
}
// �e���O���N���X(ExternalClassInfo)�̏ꍇ
} else if (ownerClass instanceof ExternalClassInfo) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(name[i],
ownerClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(), fieldInfo,
true, fromLine, fromColumn, toLine, toColumn);
}
} else {
assert false : "Here shouldn't be reached!";
}
}
this.resolvedIndo = entityUsage;
return this.resolvedIndo;
}
}
}
// �G���e�B�e�B�������S���薼�ł���ꍇ������
{
for (int length = 1; length <= name.length; length++) {
// �������閼�O(String[])���쐬
final String[] searchingName = new String[length];
System.arraycopy(name, 0, searchingName, 0, length);
final ClassInfo searchingClass = classInfoManager.getClassInfo(searchingName);
if (null != searchingClass) {
EntityUsageInfo entityUsage = new ClassReferenceInfo(new ClassTypeInfo(
searchingClass), fromLine, fromColumn, toLine, toColumn);
for (int i = length; i < name.length; i++) {
// �e�� UnknownTypeInfo ��������C�ǂ����悤���Ȃ�
if (entityUsage.getType() instanceof UnknownTypeInfo) {
this.resolvedIndo = new UnknownEntityUsageInfo(fromLine, fromColumn,
toLine, toColumn);
return this.resolvedIndo;
// �e���N���X�^�̏ꍇ
} else if (entityUsage.getType() instanceof ClassTypeInfo) {
final ClassInfo ownerClass = ((ClassTypeInfo) entityUsage.getType())
.getReferencedClass();
// �e���ΏۃN���X(TargetClassInfo)�̏ꍇ
if (ownerClass instanceof TargetClassInfo) {
// �܂��͗��p�\�ȃt�B�[���h�ꗗ���擾
boolean found = false;
{
// ���p�\�ȃt�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFields = Members
.getStaticMembers(NameResolver.getAvailableFields(
(TargetClassInfo) ownerClass, usingClass));
for (final TargetFieldInfo availableField : availableFields) {
// ��v����t�B�[���h�������������ꍇ
if (name[i].equals(availableField.getName())) {
// usingMethod.addReferencee(availableField);
// availableField.addReferencer(usingMethod);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
availableField, true, fromLine, fromColumn,
toLine, toColumn);
found = true;
break;
}
}
}
// �X�^�e�B�b�N�t�B�[���h�Ō�����Ȃ������ꍇ�́C�C���i�[�N���X����T��
{
if (!found) {
// �C���i�[�N���X�ꗗ���擾
final SortedSet<TargetInnerClassInfo> innerClasses = NameResolver
.getAvailableDirectInnerClasses((TargetClassInfo) ownerClass);
for (final TargetInnerClassInfo innerClass : innerClasses) {
// ��v����N���X�������������ꍇ
if (name[i].equals(innerClass.getClassName())) {
// TODO ���p�W���\�z����R�[�h���K�v�H
final ClassTypeInfo referenceType = new ClassTypeInfo(
innerClass);
entityUsage = new ClassReferenceInfo(referenceType,
fromLine, fromColumn, toLine, toColumn);
found = true;
break;
}
}
}
}
// ���p�\�ȃt�B�[���h��������Ȃ������ꍇ�́C�O���N���X�ł���e�N���X������͂��D
// ���̃N���X�̃t�B�[���h���g�p���Ă���Ƃ݂Ȃ�
{
if (!found) {
final ClassInfo referencedClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
final ExternalClassInfo externalSuperClass = NameResolver
.getExternalSuperClass((TargetClassInfo) referencedClass);
if (!(referencedClass instanceof TargetInnerClassInfo)
&& (null != externalSuperClass)) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], externalSuperClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
fieldInfo, true, fromLine, fromColumn, toLine,
toColumn);
} else {
assert false : "Can't resolve entity usage3 : "
+ this.toString();
}
}
}
// �e���O���N���X(ExternalClassInfo)�̏ꍇ
} else if (ownerClass instanceof ExternalClassInfo) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(name[i],
ownerClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(), fieldInfo,
true, fromLine, fromColumn, toLine, toColumn);
}
} else {
assert false : "Here shouldn't be reached!";
}
}
this.resolvedIndo = entityUsage;
return this.resolvedIndo;
}
}
}
// ���p�\�ȃN���X������G���e�B�e�B��������
{
// �����N���X�����猟��
{
final TargetClassInfo outestClass;
if (usingClass instanceof TargetInnerClassInfo) {
outestClass = NameResolver.getOuterstClass((TargetInnerClassInfo) usingClass);
} else {
outestClass = usingClass;
}
for (final TargetInnerClassInfo innerClassInfo : NameResolver
.getAvailableInnerClasses(outestClass)) {
// �N���X���ƎQ�Ɩ��̐擪���������ꍇ�́C���̃N���X�����Q�Ɛ�ł���ƌ��肷��
final String innerClassName = innerClassInfo.getClassName();
if (innerClassName.equals(name[0])) {
EntityUsageInfo entityUsage = new ClassReferenceInfo(new ClassTypeInfo(
innerClassInfo), fromLine, fromColumn, toLine, toColumn);
for (int i = 1; i < name.length; i++) {
// �e�� UnknownTypeInfo ��������C�ǂ����悤���Ȃ�
if (entityUsage.getType() instanceof UnknownTypeInfo) {
this.resolvedIndo = new UnknownEntityUsageInfo(fromLine,
fromColumn, toLine, toColumn);
return this.resolvedIndo;
// �e���N���X�^�̏ꍇ
} else if (entityUsage.getType() instanceof ClassTypeInfo) {
final ClassInfo ownerClass = ((ClassTypeInfo) entityUsage.getType())
.getReferencedClass();
// �e���ΏۃN���X(TargetClassInfo)�̏ꍇ
if (ownerClass instanceof TargetClassInfo) {
// �܂��͗��p�\�ȃt�B�[���h�ꗗ���擾
boolean found = false;
{
// ���p�\�ȃt�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFields = NameResolver
.getAvailableFields((TargetClassInfo) ownerClass,
usingClass);
for (final TargetFieldInfo availableField : availableFields) {
// ��v����t�B�[���h�������������ꍇ
if (name[i].equals(availableField.getName())) {
// usingMethod.addReferencee(availableField);
// availableField.addReferencer(usingMethod);
entityUsage = new FieldUsageInfo(entityUsage
.getType(), availableField, true, fromLine,
fromColumn, toLine, toColumn);
found = true;
break;
}
}
}
// �X�^�e�B�b�N�t�B�[���h�Ō�����Ȃ������ꍇ�́C�C���i�[�N���X����T��
{
if (!found) {
// �C���i�[�N���X�ꗗ���擾
final SortedSet<TargetInnerClassInfo> innerClasses = NameResolver
.getAvailableDirectInnerClasses((TargetClassInfo) ownerClass);
for (final TargetInnerClassInfo innerClass : innerClasses) {
// ��v����N���X�������������ꍇ
if (name[i].equals(innerClass.getClassName())) {
// TODO ���p�W���\�z����R�[�h���K�v�H
final ClassTypeInfo referenceType = new ClassTypeInfo(
innerClassInfo);
entityUsage = new ClassReferenceInfo(
referenceType, fromLine, fromColumn,
toLine, toColumn);
found = true;
break;
}
}
}
}
// ���p�\�ȃt�B�[���h��������Ȃ������ꍇ�́C�O���N���X�ł���e�N���X������͂��D
// ���̃N���X�̃t�B�[���h���g�p���Ă���Ƃ݂Ȃ�
{
if (!found) {
final ClassInfo referencedClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
final ExternalClassInfo externalSuperClass = NameResolver
.getExternalSuperClass((TargetClassInfo) referencedClass);
if (!(referencedClass instanceof TargetInnerClassInfo)
&& (null != externalSuperClass)) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], externalSuperClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage
.getType(), fieldInfo, true, fromLine,
fromColumn, toLine, toColumn);
} else {
assert false : "Can't resolve entity usage3.5 : "
+ this.toString();
}
}
}
// �e���O���N���X(ExternalClassInfo)�̏ꍇ
} else if (ownerClass instanceof ExternalClassInfo) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], ownerClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
fieldInfo, true, fromLine, fromColumn, toLine, toColumn);
}
} else {
assert false : "Here shouldn't be reached!";
}
}
this.resolvedIndo = entityUsage;
return this.resolvedIndo;
}
}
}
// ���p�\�Ȗ��O��Ԃ��猟��
{
for (final AvailableNamespaceInfo availableNamespace : this
.getAvailableNamespaces()) {
// ���O��Ԗ�.* �ƂȂ��Ă���ꍇ
if (availableNamespace.isAllClasses()) {
final String[] namespace = availableNamespace.getNamespace();
// ���O��Ԃ̉��ɂ���e�N���X�ɑ���
for (final ClassInfo classInfo : classInfoManager.getClassInfos(namespace)) {
final String className = classInfo.getClassName();
// �N���X���ƎQ�Ɩ��̐擪���������ꍇ�́C���̃N���X�����Q�Ɛ�ł���ƌ��肷��
if (className.equals(name[0])) {
EntityUsageInfo entityUsage = new ClassReferenceInfo(
new ClassTypeInfo(classInfo), fromLine, fromColumn, toLine,
toColumn);
for (int i = 1; i < name.length; i++) {
// �e�� UnknownTypeInfo ��������C�ǂ����悤���Ȃ�
if (entityUsage.getType() instanceof UnknownTypeInfo) {
this.resolvedIndo = new UnknownEntityUsageInfo(fromLine,
fromColumn, toLine, toColumn);
return this.resolvedIndo;
// �e���N���X�^�̏ꍇ
} else if (entityUsage.getType() instanceof ClassTypeInfo) {
final ClassInfo ownerClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
// �e���ΏۃN���X(TargetClassInfo)�̏ꍇ
if (ownerClass instanceof TargetClassInfo) {
// �܂��͗��p�\�ȃt�B�[���h�ꗗ���擾
boolean found = false;
{
// ���p�\�ȃt�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFields = NameResolver
.getAvailableFields(
(TargetClassInfo) ownerClass,
usingClass);
for (TargetFieldInfo availableField : availableFields) {
// ��v����t�B�[���h�������������ꍇ
if (name[i].equals(availableField.getName())) {
// usingMethod.addReferencee(availableField);
// availableField.addReferencer(usingMethod);
entityUsage = new FieldUsageInfo(
entityUsage.getType(),
availableField, true, fromLine,
fromColumn, toLine, toColumn);
found = true;
break;
}
}
}
// �X�^�e�B�b�N�t�B�[���h�Ō�����Ȃ������ꍇ�́C�C���i�[�N���X����T��
{
if (!found) {
// �C���i�[�N���X�ꗗ���擾
final SortedSet<TargetInnerClassInfo> innerClasses = NameResolver
.getAvailableDirectInnerClasses((TargetClassInfo) ownerClass);
for (final TargetInnerClassInfo innerClass : innerClasses) {
// ��v����N���X�������������ꍇ
if (name[i].equals(innerClass
.getClassName())) {
// TODO ���p�W���\�z����R�[�h���K�v�H
final ClassTypeInfo referenceType = new ClassTypeInfo(
innerClass);
entityUsage = new ClassReferenceInfo(
referenceType, fromLine,
fromColumn, toLine, toColumn);
found = true;
break;
}
}
}
}
// ���p�\�ȃt�B�[���h��������Ȃ������ꍇ�́C�O���N���X�ł���e�N���X������͂��D
// ���̃N���X�̃t�B�[���h���g�p���Ă���Ƃ݂Ȃ�
{
if (!found) {
final ClassInfo referencedClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
final ExternalClassInfo externalSuperClass = NameResolver
.getExternalSuperClass((TargetClassInfo) referencedClass);
if (!(referencedClass instanceof TargetInnerClassInfo)
&& (null != externalSuperClass)) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], externalSuperClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(
entityUsage.getType(), fieldInfo,
true, fromLine, fromColumn, toLine,
toColumn);
} else {
assert false : "Can't resolve entity usage4 : "
+ this.toString();
}
}
}
// �e���O���N���X(ExternalClassInfo)�̏ꍇ
} else if (ownerClass instanceof ExternalClassInfo) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], ownerClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
fieldInfo, true, fromLine, fromColumn, toLine,
toColumn);
}
} else {
assert false : "Here shouldn't be reached!";
}
}
this.resolvedIndo = entityUsage;
return this.resolvedIndo;
}
}
// ���O���.�N���X�� �ƂȂ��Ă���ꍇ
} else {
final String[] importName = availableNamespace.getImportName();
// �N���X���ƎQ�Ɩ��̐擪���������ꍇ�́C���̃N���X�����Q�Ɛ�ł���ƌ��肷��
if (importName[importName.length - 1].equals(name[0])) {
ClassInfo specifiedClassInfo = classInfoManager
.getClassInfo(importName);
if (null == specifiedClassInfo) {
specifiedClassInfo = new ExternalClassInfo(importName);
classInfoManager.add((ExternalClassInfo) specifiedClassInfo);
}
EntityUsageInfo entityUsage = new ClassReferenceInfo(new ClassTypeInfo(
specifiedClassInfo), fromLine, fromColumn, toLine, toColumn);
for (int i = 1; i < name.length; i++) {
// �e�� UnknownTypeInfo ��������C�ǂ����悤���Ȃ�
if (entityUsage.getType() instanceof UnknownTypeInfo) {
this.resolvedIndo = new UnknownEntityUsageInfo(fromLine,
fromColumn, toLine, toColumn);
return this.resolvedIndo;
// �e���N���X�^�̏ꍇ
} else if (entityUsage.getType() instanceof ClassTypeInfo) {
final ClassInfo ownerClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
// �e���ΏۃN���X(TargetClassInfo)�̏ꍇ
if (ownerClass instanceof TargetClassInfo) {
// �܂��͗��p�\�ȃt�B�[���h�ꗗ���擾
boolean found = false;
{
// ���p�\�ȃt�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFields = NameResolver
.getAvailableFields(
(TargetClassInfo) ownerClass,
usingClass);
for (final TargetFieldInfo availableField : availableFields) {
// ��v����t�B�[���h�������������ꍇ
if (name[i].equals(availableField.getName())) {
// usingMethod.addReferencee(availableField);
// availableField.addReferencer(usingMethod);
entityUsage = new FieldUsageInfo(entityUsage
.getType(), availableField, true,
fromLine, fromColumn, toLine, toColumn);
found = true;
break;
}
}
}
// �X�^�e�B�b�N�t�B�[���h�Ō�����Ȃ������ꍇ�́C�C���i�[�N���X����T��
{
if (!found) {
// �C���i�[�N���X�ꗗ���擾
final SortedSet<TargetInnerClassInfo> innerClasses = NameResolver
.getAvailableDirectInnerClasses((TargetClassInfo) ownerClass);
for (final TargetInnerClassInfo innerClass : innerClasses) {
// ��v����N���X�������������ꍇ
if (name[i].equals(innerClass.getClassName())) {
// TODO ���p�W���\�z����R�[�h���K�v�H
final ClassTypeInfo referenceType = new ClassTypeInfo(
innerClass);
entityUsage = new ClassReferenceInfo(
referenceType, fromLine,
fromColumn, toLine, toColumn);
found = true;
break;
}
}
}
}
// ���p�\�ȃt�B�[���h��������Ȃ������ꍇ�́C�O���N���X�ł���e�N���X������͂��D
// ���̃N���X�̃t�B�[���h���g�p���Ă���Ƃ݂Ȃ�
{
if (!found) {
final ClassInfo referencedClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
final ExternalClassInfo externalSuperClass = NameResolver
.getExternalSuperClass((TargetClassInfo) referencedClass);
if (!(referencedClass instanceof TargetInnerClassInfo)
&& (null != externalSuperClass)) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], externalSuperClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage
.getType(), fieldInfo, true, fromLine,
fromColumn, toLine, toColumn);
} else {
assert false : "Can't resolve entity usage5 : "
+ this.toString();
}
}
}
// �e���O���N���X(ExternalClassInfo)�̏ꍇ
} else if (ownerClass instanceof ExternalClassInfo) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], ownerClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
fieldInfo, true, fromLine, fromColumn, toLine,
toColumn);
}
} else {
assert false : "Here shouldn't be reached!";
}
}
this.resolvedIndo = entityUsage;
return this.resolvedIndo;
}
}
}
}
}
// java����̏ꍇ�́Cjava��javax�Ŏn�܂�C������3�ȏ��UnknownEntityUsageInfo��JDK���̃N���X�Ƃ݂Ȃ�
if (Settings.getLanguage().equals(LANGUAGE.JAVA)) {
if ((name[0].equals("java") || name[0].equals("javax")) && (3 <= name.length)) {
final ExternalClassInfo externalClass = new ExternalClassInfo(name);
final ClassTypeInfo externalClassType = new ClassTypeInfo(externalClass);
this.resolvedIndo = new ClassReferenceInfo(externalClassType, fromLine, fromColumn,
toLine, toColumn);
classInfoManager.add(externalClass);
+ return this.resolvedIndo;
}
}
err.println("Remain unresolved \"" + this.toString() + "\"" + " line:" + this.getFromLine()
+ " column:" + this.getFromColumn() + " on \""
+ usingClass.getFullQualifiedName(LANGUAGE.JAVA.getNamespaceDelimiter()));
// ������Ȃ������������s��
usingMethod.addUnresolvedUsage(this);
this.resolvedIndo = new UnknownEntityUsageInfo(fromLine, fromColumn, toLine, toColumn);
return this.resolvedIndo;
}
/**
* �������G���e�B�e�B�g�p����Ԃ��D
*
* @return �������G���e�B�e�B�g�p��
*/
public String[] getName() {
return this.name;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder(this.name[0]);
for (int i = 1; i < this.name.length; i++) {
sb.append(".");
sb.append(this.name[i]);
}
return sb.toString();
}
/**
* ���̖������G���e�B�e�B�g�p�����p���邱�Ƃ̂ł��閼�O��Ԃ�Ԃ��D
*
* @return ���̖������G���e�B�e�B�g�p�����p���邱�Ƃ̂ł��閼�O���
*/
public Set<AvailableNamespaceInfo> getAvailableNamespaces() {
return this.availableNamespaces;
}
/**
* ���̖������G���e�B�e�B�g�p�����p���邱�Ƃ̂ł��閼�O��Ԃ�ۑ����邽�߂̕ϐ�
*/
private final Set<AvailableNamespaceInfo> availableNamespaces;
/**
* ���̖������G���e�B�e�B�g�p����ۑ����邽�߂̕ϐ�
*/
private final String[] name;
/**
* �����ς݃G���e�B�e�B�g�p��ۑ����邽�߂̕ϐ�
*/
private EntityUsageInfo resolvedIndo;
/**
* �G���[���b�Z�[�W�o�͗p�̃v�����^
*/
private static final MessagePrinter err = new DefaultMessagePrinter(new MessageSource() {
public String getMessageSourceName() {
return "UnresolvedUnknownEntityUsage";
}
}, MESSAGE_TYPE.ERROR);
}
| true | true | public EntityUsageInfo resolveEntityUsage(final TargetClassInfo usingClass,
final CallableUnitInfo usingMethod, final ClassInfoManager classInfoManager,
final FieldInfoManager fieldInfoManager, final MethodInfoManager methodInfoManager) {
// �s���ȌĂяo���łȂ������`�F�b�N
MetricsToolSecurityManager.getInstance().checkAccess();
if ((null == usingClass) || (null == usingMethod) || (null == classInfoManager)
|| (null == methodInfoManager)) {
throw new NullPointerException();
}
// ���ɉ����ς݂ł���ꍇ�́C�L���b�V����Ԃ�
if (this.alreadyResolved()) {
return this.getResolvedEntityUsage();
}
// �G���e�B�e�B�Q�Ɩ����擾
final String[] name = this.getName();
// �ʒu�����擾
final int fromLine = this.getFromLine();
final int fromColumn = this.getFromColumn();
final int toLine = this.getToLine();
final int toColumn = this.getToColumn();
// ���p�\�ȃC���X�^���X�t�B�[���h������G���e�B�e�B��������
{
// ���̃N���X�ŗ��p�\�ȃC���X�^���X�t�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFieldsOfThisClass = Members
.<TargetFieldInfo> getInstanceMembers(NameResolver
.getAvailableFields(usingClass));
for (final TargetFieldInfo availableFieldOfThisClass : availableFieldsOfThisClass) {
// ��v����t�B�[���h�������������ꍇ
if (name[0].equals(availableFieldOfThisClass.getName())) {
// usingMethod.addReferencee(availableFieldOfThisClass);
// availableFieldOfThisClass.addReferencer(usingMethod);
// �e�̌^��
final ClassTypeInfo usingClassType = new ClassTypeInfo(usingClass);
for (final TypeParameterInfo typeParameter : usingClass.getTypeParameters()) {
usingClassType.addTypeArgument(typeParameter);
}
// availableField.getType() ���玟��word(name[i])�𖼑O����
EntityUsageInfo entityUsage = new FieldUsageInfo(usingClassType,
availableFieldOfThisClass, true, fromLine, fromColumn, toLine, toColumn);
for (int i = 1; i < name.length; i++) {
// �e�� UnknownTypeInfo ��������C�ǂ����悤���Ȃ�
if (entityUsage.getType() instanceof UnknownTypeInfo) {
this.resolvedIndo = new UnknownEntityUsageInfo(fromLine, fromColumn,
toLine, toColumn);
return this.resolvedIndo;
// �e���N���X�^�̏ꍇ
} else if (entityUsage.getType() instanceof ClassTypeInfo) {
final ClassInfo ownerClass = ((ClassTypeInfo) entityUsage.getType())
.getReferencedClass();
// �e���ΏۃN���X(TargetClassInfo)�̏ꍇ
if (ownerClass instanceof TargetClassInfo) {
// �܂��͗��p�\�ȃt�B�[���h�ꗗ���擾
boolean found = false;
{
// ���p�\�ȃC���X�^���X�t�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFields = Members
.getInstanceMembers(NameResolver.getAvailableFields(
(TargetClassInfo) ownerClass, usingClass));
for (final TargetFieldInfo availableField : availableFields) {
// ��v����t�B�[���h�������������ꍇ
if (name[i].equals(availableField.getName())) {
// usingMethod.addReferencee(availableField);
// availableField.addReferencer(usingMethod);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
availableField, true, fromLine, fromColumn,
toLine, toColumn);
found = true;
break;
}
}
}
// ���p�\�ȃt�B�[���h��������Ȃ������ꍇ�́C�O���N���X�ł���e�N���X������͂��D
// ���̃N���X�̃t�B�[���h���g�p���Ă���Ƃ݂Ȃ�
{
if (!found) {
final ClassInfo referencedClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
final ExternalClassInfo externalSuperClass = NameResolver
.getExternalSuperClass((TargetClassInfo) referencedClass);
if (!(referencedClass instanceof TargetInnerClassInfo)
&& (null != externalSuperClass)) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], externalSuperClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
fieldInfo, true, fromLine, fromColumn, toLine,
toColumn);
} else {
assert false : "Can't resolve entity usage1 : "
+ this.toString();
}
}
}
// �e���O���N���X(ExternalClassInfo)�̏ꍇ
} else if (ownerClass instanceof ExternalClassInfo) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(name[i],
ownerClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(), fieldInfo,
true, fromLine, fromColumn, toLine, toColumn);
}
} else {
assert false : "Here shouldn't be reached!";
}
}
this.resolvedIndo = entityUsage;
return this.resolvedIndo;
}
}
}
// ���p�\�ȃX�^�e�B�b�N�t�B�[���h������G���e�B�e�B��������
{
// ���̃N���X�ŗ��p�\�ȃX�^�e�B�b�N�t�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFieldsOfThisClass = Members
.<TargetFieldInfo> getStaticMembers(NameResolver.getAvailableFields(usingClass));
for (final TargetFieldInfo availableFieldOfThisClass : availableFieldsOfThisClass) {
// ��v����t�B�[���h�������������ꍇ
if (name[0].equals(availableFieldOfThisClass.getName())) {
// usingMethod.addReferencee(availableFieldOfThisClass);
// availableFieldOfThisClass.addReferencer(usingMethod);
// �e�̌^��
final ClassTypeInfo usingClassType = new ClassTypeInfo(usingClass);
for (final TypeParameterInfo typeParameter : usingClass.getTypeParameters()) {
usingClassType.addTypeArgument(typeParameter);
}
// availableField.getType() ���玟��word(name[i])�𖼑O����
EntityUsageInfo entityUsage = new FieldUsageInfo(usingClassType,
availableFieldOfThisClass, true, fromLine, fromColumn, toLine, toColumn);
for (int i = 1; i < name.length; i++) {
// �e�� UnknownTypeInfo ��������C�ǂ����悤���Ȃ�
if (entityUsage.getType() instanceof UnknownTypeInfo) {
this.resolvedIndo = new UnknownEntityUsageInfo(fromLine, fromColumn,
toLine, toColumn);
return this.resolvedIndo;
// �e���N���X�^�̏ꍇ
} else if (entityUsage.getType() instanceof ClassTypeInfo) {
final ClassInfo ownerClass = ((ClassTypeInfo) entityUsage.getType())
.getReferencedClass();
// �e���ΏۃN���X(TargetClassInfo)�̏ꍇ
if (ownerClass instanceof TargetClassInfo) {
// �܂��͗��p�\�ȃt�B�[���h�ꗗ���擾
boolean found = false;
{
// ���p�\�ȃX�^�e�B�b�N�t�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFields = Members
.getStaticMembers(NameResolver.getAvailableFields(
(TargetClassInfo) ownerClass, usingClass));
for (final TargetFieldInfo availableField : availableFields) {
// ��v����t�B�[���h�������������ꍇ
if (name[i].equals(availableField.getName())) {
// usingMethod.addReferencee(availableField);
// availableField.addReferencer(usingMethod);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
availableField, true, fromLine, fromColumn,
toLine, toColumn);
found = true;
break;
}
}
}
// �X�^�e�B�b�N�t�B�[���h�Ō�����Ȃ������ꍇ�́C�C���i�[�N���X����T��
{
if (!found) {
// �C���i�[�N���X�ꗗ���擾
final SortedSet<TargetInnerClassInfo> innerClasses = NameResolver
.getAvailableDirectInnerClasses((TargetClassInfo) ownerClass);
for (final TargetInnerClassInfo innerClass : innerClasses) {
// ��v����N���X�������������ꍇ
if (name[i].equals(innerClass.getClassName())) {
// TODO ���p�W���\�z����R�[�h���K�v�H
final ClassTypeInfo referenceType = new ClassTypeInfo(
innerClass);
entityUsage = new ClassReferenceInfo(referenceType,
fromLine, fromColumn, toLine, toColumn);
found = true;
break;
}
}
}
}
// ���p�\�ȃt�B�[���h��������Ȃ������ꍇ�́C�O���N���X�ł���e�N���X������͂��D
// ���̃N���X�̃t�B�[���h���g�p���Ă���Ƃ݂Ȃ�
{
if (!found) {
final ClassInfo referencedClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
final ExternalClassInfo externalSuperClass = NameResolver
.getExternalSuperClass((TargetClassInfo) referencedClass);
if (!(referencedClass instanceof TargetInnerClassInfo)
&& (null != externalSuperClass)) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], externalSuperClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
fieldInfo, true, fromLine, fromColumn, toLine,
toColumn);
} else {
assert false : "Can't resolve entity usage2 : "
+ this.toString();
}
}
}
// �e���O���N���X(ExternalClassInfo)�̏ꍇ
} else if (ownerClass instanceof ExternalClassInfo) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(name[i],
ownerClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(), fieldInfo,
true, fromLine, fromColumn, toLine, toColumn);
}
} else {
assert false : "Here shouldn't be reached!";
}
}
this.resolvedIndo = entityUsage;
return this.resolvedIndo;
}
}
}
// �G���e�B�e�B�������S���薼�ł���ꍇ������
{
for (int length = 1; length <= name.length; length++) {
// �������閼�O(String[])���쐬
final String[] searchingName = new String[length];
System.arraycopy(name, 0, searchingName, 0, length);
final ClassInfo searchingClass = classInfoManager.getClassInfo(searchingName);
if (null != searchingClass) {
EntityUsageInfo entityUsage = new ClassReferenceInfo(new ClassTypeInfo(
searchingClass), fromLine, fromColumn, toLine, toColumn);
for (int i = length; i < name.length; i++) {
// �e�� UnknownTypeInfo ��������C�ǂ����悤���Ȃ�
if (entityUsage.getType() instanceof UnknownTypeInfo) {
this.resolvedIndo = new UnknownEntityUsageInfo(fromLine, fromColumn,
toLine, toColumn);
return this.resolvedIndo;
// �e���N���X�^�̏ꍇ
} else if (entityUsage.getType() instanceof ClassTypeInfo) {
final ClassInfo ownerClass = ((ClassTypeInfo) entityUsage.getType())
.getReferencedClass();
// �e���ΏۃN���X(TargetClassInfo)�̏ꍇ
if (ownerClass instanceof TargetClassInfo) {
// �܂��͗��p�\�ȃt�B�[���h�ꗗ���擾
boolean found = false;
{
// ���p�\�ȃt�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFields = Members
.getStaticMembers(NameResolver.getAvailableFields(
(TargetClassInfo) ownerClass, usingClass));
for (final TargetFieldInfo availableField : availableFields) {
// ��v����t�B�[���h�������������ꍇ
if (name[i].equals(availableField.getName())) {
// usingMethod.addReferencee(availableField);
// availableField.addReferencer(usingMethod);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
availableField, true, fromLine, fromColumn,
toLine, toColumn);
found = true;
break;
}
}
}
// �X�^�e�B�b�N�t�B�[���h�Ō�����Ȃ������ꍇ�́C�C���i�[�N���X����T��
{
if (!found) {
// �C���i�[�N���X�ꗗ���擾
final SortedSet<TargetInnerClassInfo> innerClasses = NameResolver
.getAvailableDirectInnerClasses((TargetClassInfo) ownerClass);
for (final TargetInnerClassInfo innerClass : innerClasses) {
// ��v����N���X�������������ꍇ
if (name[i].equals(innerClass.getClassName())) {
// TODO ���p�W���\�z����R�[�h���K�v�H
final ClassTypeInfo referenceType = new ClassTypeInfo(
innerClass);
entityUsage = new ClassReferenceInfo(referenceType,
fromLine, fromColumn, toLine, toColumn);
found = true;
break;
}
}
}
}
// ���p�\�ȃt�B�[���h��������Ȃ������ꍇ�́C�O���N���X�ł���e�N���X������͂��D
// ���̃N���X�̃t�B�[���h���g�p���Ă���Ƃ݂Ȃ�
{
if (!found) {
final ClassInfo referencedClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
final ExternalClassInfo externalSuperClass = NameResolver
.getExternalSuperClass((TargetClassInfo) referencedClass);
if (!(referencedClass instanceof TargetInnerClassInfo)
&& (null != externalSuperClass)) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], externalSuperClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
fieldInfo, true, fromLine, fromColumn, toLine,
toColumn);
} else {
assert false : "Can't resolve entity usage3 : "
+ this.toString();
}
}
}
// �e���O���N���X(ExternalClassInfo)�̏ꍇ
} else if (ownerClass instanceof ExternalClassInfo) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(name[i],
ownerClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(), fieldInfo,
true, fromLine, fromColumn, toLine, toColumn);
}
} else {
assert false : "Here shouldn't be reached!";
}
}
this.resolvedIndo = entityUsage;
return this.resolvedIndo;
}
}
}
// ���p�\�ȃN���X������G���e�B�e�B��������
{
// �����N���X�����猟��
{
final TargetClassInfo outestClass;
if (usingClass instanceof TargetInnerClassInfo) {
outestClass = NameResolver.getOuterstClass((TargetInnerClassInfo) usingClass);
} else {
outestClass = usingClass;
}
for (final TargetInnerClassInfo innerClassInfo : NameResolver
.getAvailableInnerClasses(outestClass)) {
// �N���X���ƎQ�Ɩ��̐擪���������ꍇ�́C���̃N���X�����Q�Ɛ�ł���ƌ��肷��
final String innerClassName = innerClassInfo.getClassName();
if (innerClassName.equals(name[0])) {
EntityUsageInfo entityUsage = new ClassReferenceInfo(new ClassTypeInfo(
innerClassInfo), fromLine, fromColumn, toLine, toColumn);
for (int i = 1; i < name.length; i++) {
// �e�� UnknownTypeInfo ��������C�ǂ����悤���Ȃ�
if (entityUsage.getType() instanceof UnknownTypeInfo) {
this.resolvedIndo = new UnknownEntityUsageInfo(fromLine,
fromColumn, toLine, toColumn);
return this.resolvedIndo;
// �e���N���X�^�̏ꍇ
} else if (entityUsage.getType() instanceof ClassTypeInfo) {
final ClassInfo ownerClass = ((ClassTypeInfo) entityUsage.getType())
.getReferencedClass();
// �e���ΏۃN���X(TargetClassInfo)�̏ꍇ
if (ownerClass instanceof TargetClassInfo) {
// �܂��͗��p�\�ȃt�B�[���h�ꗗ���擾
boolean found = false;
{
// ���p�\�ȃt�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFields = NameResolver
.getAvailableFields((TargetClassInfo) ownerClass,
usingClass);
for (final TargetFieldInfo availableField : availableFields) {
// ��v����t�B�[���h�������������ꍇ
if (name[i].equals(availableField.getName())) {
// usingMethod.addReferencee(availableField);
// availableField.addReferencer(usingMethod);
entityUsage = new FieldUsageInfo(entityUsage
.getType(), availableField, true, fromLine,
fromColumn, toLine, toColumn);
found = true;
break;
}
}
}
// �X�^�e�B�b�N�t�B�[���h�Ō�����Ȃ������ꍇ�́C�C���i�[�N���X����T��
{
if (!found) {
// �C���i�[�N���X�ꗗ���擾
final SortedSet<TargetInnerClassInfo> innerClasses = NameResolver
.getAvailableDirectInnerClasses((TargetClassInfo) ownerClass);
for (final TargetInnerClassInfo innerClass : innerClasses) {
// ��v����N���X�������������ꍇ
if (name[i].equals(innerClass.getClassName())) {
// TODO ���p�W���\�z����R�[�h���K�v�H
final ClassTypeInfo referenceType = new ClassTypeInfo(
innerClassInfo);
entityUsage = new ClassReferenceInfo(
referenceType, fromLine, fromColumn,
toLine, toColumn);
found = true;
break;
}
}
}
}
// ���p�\�ȃt�B�[���h��������Ȃ������ꍇ�́C�O���N���X�ł���e�N���X������͂��D
// ���̃N���X�̃t�B�[���h���g�p���Ă���Ƃ݂Ȃ�
{
if (!found) {
final ClassInfo referencedClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
final ExternalClassInfo externalSuperClass = NameResolver
.getExternalSuperClass((TargetClassInfo) referencedClass);
if (!(referencedClass instanceof TargetInnerClassInfo)
&& (null != externalSuperClass)) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], externalSuperClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage
.getType(), fieldInfo, true, fromLine,
fromColumn, toLine, toColumn);
} else {
assert false : "Can't resolve entity usage3.5 : "
+ this.toString();
}
}
}
// �e���O���N���X(ExternalClassInfo)�̏ꍇ
} else if (ownerClass instanceof ExternalClassInfo) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], ownerClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
fieldInfo, true, fromLine, fromColumn, toLine, toColumn);
}
} else {
assert false : "Here shouldn't be reached!";
}
}
this.resolvedIndo = entityUsage;
return this.resolvedIndo;
}
}
}
// ���p�\�Ȗ��O��Ԃ��猟��
{
for (final AvailableNamespaceInfo availableNamespace : this
.getAvailableNamespaces()) {
// ���O��Ԗ�.* �ƂȂ��Ă���ꍇ
if (availableNamespace.isAllClasses()) {
final String[] namespace = availableNamespace.getNamespace();
// ���O��Ԃ̉��ɂ���e�N���X�ɑ���
for (final ClassInfo classInfo : classInfoManager.getClassInfos(namespace)) {
final String className = classInfo.getClassName();
// �N���X���ƎQ�Ɩ��̐擪���������ꍇ�́C���̃N���X�����Q�Ɛ�ł���ƌ��肷��
if (className.equals(name[0])) {
EntityUsageInfo entityUsage = new ClassReferenceInfo(
new ClassTypeInfo(classInfo), fromLine, fromColumn, toLine,
toColumn);
for (int i = 1; i < name.length; i++) {
// �e�� UnknownTypeInfo ��������C�ǂ����悤���Ȃ�
if (entityUsage.getType() instanceof UnknownTypeInfo) {
this.resolvedIndo = new UnknownEntityUsageInfo(fromLine,
fromColumn, toLine, toColumn);
return this.resolvedIndo;
// �e���N���X�^�̏ꍇ
} else if (entityUsage.getType() instanceof ClassTypeInfo) {
final ClassInfo ownerClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
// �e���ΏۃN���X(TargetClassInfo)�̏ꍇ
if (ownerClass instanceof TargetClassInfo) {
// �܂��͗��p�\�ȃt�B�[���h�ꗗ���擾
boolean found = false;
{
// ���p�\�ȃt�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFields = NameResolver
.getAvailableFields(
(TargetClassInfo) ownerClass,
usingClass);
for (TargetFieldInfo availableField : availableFields) {
// ��v����t�B�[���h�������������ꍇ
if (name[i].equals(availableField.getName())) {
// usingMethod.addReferencee(availableField);
// availableField.addReferencer(usingMethod);
entityUsage = new FieldUsageInfo(
entityUsage.getType(),
availableField, true, fromLine,
fromColumn, toLine, toColumn);
found = true;
break;
}
}
}
// �X�^�e�B�b�N�t�B�[���h�Ō�����Ȃ������ꍇ�́C�C���i�[�N���X����T��
{
if (!found) {
// �C���i�[�N���X�ꗗ���擾
final SortedSet<TargetInnerClassInfo> innerClasses = NameResolver
.getAvailableDirectInnerClasses((TargetClassInfo) ownerClass);
for (final TargetInnerClassInfo innerClass : innerClasses) {
// ��v����N���X�������������ꍇ
if (name[i].equals(innerClass
.getClassName())) {
// TODO ���p�W���\�z����R�[�h���K�v�H
final ClassTypeInfo referenceType = new ClassTypeInfo(
innerClass);
entityUsage = new ClassReferenceInfo(
referenceType, fromLine,
fromColumn, toLine, toColumn);
found = true;
break;
}
}
}
}
// ���p�\�ȃt�B�[���h��������Ȃ������ꍇ�́C�O���N���X�ł���e�N���X������͂��D
// ���̃N���X�̃t�B�[���h���g�p���Ă���Ƃ݂Ȃ�
{
if (!found) {
final ClassInfo referencedClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
final ExternalClassInfo externalSuperClass = NameResolver
.getExternalSuperClass((TargetClassInfo) referencedClass);
if (!(referencedClass instanceof TargetInnerClassInfo)
&& (null != externalSuperClass)) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], externalSuperClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(
entityUsage.getType(), fieldInfo,
true, fromLine, fromColumn, toLine,
toColumn);
} else {
assert false : "Can't resolve entity usage4 : "
+ this.toString();
}
}
}
// �e���O���N���X(ExternalClassInfo)�̏ꍇ
} else if (ownerClass instanceof ExternalClassInfo) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], ownerClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
fieldInfo, true, fromLine, fromColumn, toLine,
toColumn);
}
} else {
assert false : "Here shouldn't be reached!";
}
}
this.resolvedIndo = entityUsage;
return this.resolvedIndo;
}
}
// ���O���.�N���X�� �ƂȂ��Ă���ꍇ
} else {
final String[] importName = availableNamespace.getImportName();
// �N���X���ƎQ�Ɩ��̐擪���������ꍇ�́C���̃N���X�����Q�Ɛ�ł���ƌ��肷��
if (importName[importName.length - 1].equals(name[0])) {
ClassInfo specifiedClassInfo = classInfoManager
.getClassInfo(importName);
if (null == specifiedClassInfo) {
specifiedClassInfo = new ExternalClassInfo(importName);
classInfoManager.add((ExternalClassInfo) specifiedClassInfo);
}
EntityUsageInfo entityUsage = new ClassReferenceInfo(new ClassTypeInfo(
specifiedClassInfo), fromLine, fromColumn, toLine, toColumn);
for (int i = 1; i < name.length; i++) {
// �e�� UnknownTypeInfo ��������C�ǂ����悤���Ȃ�
if (entityUsage.getType() instanceof UnknownTypeInfo) {
this.resolvedIndo = new UnknownEntityUsageInfo(fromLine,
fromColumn, toLine, toColumn);
return this.resolvedIndo;
// �e���N���X�^�̏ꍇ
} else if (entityUsage.getType() instanceof ClassTypeInfo) {
final ClassInfo ownerClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
// �e���ΏۃN���X(TargetClassInfo)�̏ꍇ
if (ownerClass instanceof TargetClassInfo) {
// �܂��͗��p�\�ȃt�B�[���h�ꗗ���擾
boolean found = false;
{
// ���p�\�ȃt�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFields = NameResolver
.getAvailableFields(
(TargetClassInfo) ownerClass,
usingClass);
for (final TargetFieldInfo availableField : availableFields) {
// ��v����t�B�[���h�������������ꍇ
if (name[i].equals(availableField.getName())) {
// usingMethod.addReferencee(availableField);
// availableField.addReferencer(usingMethod);
entityUsage = new FieldUsageInfo(entityUsage
.getType(), availableField, true,
fromLine, fromColumn, toLine, toColumn);
found = true;
break;
}
}
}
// �X�^�e�B�b�N�t�B�[���h�Ō�����Ȃ������ꍇ�́C�C���i�[�N���X����T��
{
if (!found) {
// �C���i�[�N���X�ꗗ���擾
final SortedSet<TargetInnerClassInfo> innerClasses = NameResolver
.getAvailableDirectInnerClasses((TargetClassInfo) ownerClass);
for (final TargetInnerClassInfo innerClass : innerClasses) {
// ��v����N���X�������������ꍇ
if (name[i].equals(innerClass.getClassName())) {
// TODO ���p�W���\�z����R�[�h���K�v�H
final ClassTypeInfo referenceType = new ClassTypeInfo(
innerClass);
entityUsage = new ClassReferenceInfo(
referenceType, fromLine,
fromColumn, toLine, toColumn);
found = true;
break;
}
}
}
}
// ���p�\�ȃt�B�[���h��������Ȃ������ꍇ�́C�O���N���X�ł���e�N���X������͂��D
// ���̃N���X�̃t�B�[���h���g�p���Ă���Ƃ݂Ȃ�
{
if (!found) {
final ClassInfo referencedClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
final ExternalClassInfo externalSuperClass = NameResolver
.getExternalSuperClass((TargetClassInfo) referencedClass);
if (!(referencedClass instanceof TargetInnerClassInfo)
&& (null != externalSuperClass)) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], externalSuperClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage
.getType(), fieldInfo, true, fromLine,
fromColumn, toLine, toColumn);
} else {
assert false : "Can't resolve entity usage5 : "
+ this.toString();
}
}
}
// �e���O���N���X(ExternalClassInfo)�̏ꍇ
} else if (ownerClass instanceof ExternalClassInfo) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], ownerClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
fieldInfo, true, fromLine, fromColumn, toLine,
toColumn);
}
} else {
assert false : "Here shouldn't be reached!";
}
}
this.resolvedIndo = entityUsage;
return this.resolvedIndo;
}
}
}
}
}
// java����̏ꍇ�́Cjava��javax�Ŏn�܂�C������3�ȏ��UnknownEntityUsageInfo��JDK���̃N���X�Ƃ݂Ȃ�
if (Settings.getLanguage().equals(LANGUAGE.JAVA)) {
if ((name[0].equals("java") || name[0].equals("javax")) && (3 <= name.length)) {
final ExternalClassInfo externalClass = new ExternalClassInfo(name);
final ClassTypeInfo externalClassType = new ClassTypeInfo(externalClass);
this.resolvedIndo = new ClassReferenceInfo(externalClassType, fromLine, fromColumn,
toLine, toColumn);
classInfoManager.add(externalClass);
}
}
err.println("Remain unresolved \"" + this.toString() + "\"" + " line:" + this.getFromLine()
+ " column:" + this.getFromColumn() + " on \""
+ usingClass.getFullQualifiedName(LANGUAGE.JAVA.getNamespaceDelimiter()));
// ������Ȃ������������s��
usingMethod.addUnresolvedUsage(this);
this.resolvedIndo = new UnknownEntityUsageInfo(fromLine, fromColumn, toLine, toColumn);
return this.resolvedIndo;
}
| public EntityUsageInfo resolveEntityUsage(final TargetClassInfo usingClass,
final CallableUnitInfo usingMethod, final ClassInfoManager classInfoManager,
final FieldInfoManager fieldInfoManager, final MethodInfoManager methodInfoManager) {
// �s���ȌĂяo���łȂ������`�F�b�N
MetricsToolSecurityManager.getInstance().checkAccess();
if ((null == usingClass) || (null == usingMethod) || (null == classInfoManager)
|| (null == methodInfoManager)) {
throw new NullPointerException();
}
// ���ɉ����ς݂ł���ꍇ�́C�L���b�V����Ԃ�
if (this.alreadyResolved()) {
return this.getResolvedEntityUsage();
}
// �G���e�B�e�B�Q�Ɩ����擾
final String[] name = this.getName();
// �ʒu�����擾
final int fromLine = this.getFromLine();
final int fromColumn = this.getFromColumn();
final int toLine = this.getToLine();
final int toColumn = this.getToColumn();
// ���p�\�ȃC���X�^���X�t�B�[���h������G���e�B�e�B��������
{
// ���̃N���X�ŗ��p�\�ȃC���X�^���X�t�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFieldsOfThisClass = Members
.<TargetFieldInfo> getInstanceMembers(NameResolver
.getAvailableFields(usingClass));
for (final TargetFieldInfo availableFieldOfThisClass : availableFieldsOfThisClass) {
// ��v����t�B�[���h�������������ꍇ
if (name[0].equals(availableFieldOfThisClass.getName())) {
// usingMethod.addReferencee(availableFieldOfThisClass);
// availableFieldOfThisClass.addReferencer(usingMethod);
// �e�̌^��
final ClassTypeInfo usingClassType = new ClassTypeInfo(usingClass);
for (final TypeParameterInfo typeParameter : usingClass.getTypeParameters()) {
usingClassType.addTypeArgument(typeParameter);
}
// availableField.getType() ���玟��word(name[i])�𖼑O����
EntityUsageInfo entityUsage = new FieldUsageInfo(usingClassType,
availableFieldOfThisClass, true, fromLine, fromColumn, toLine, toColumn);
for (int i = 1; i < name.length; i++) {
// �e�� UnknownTypeInfo ��������C�ǂ����悤���Ȃ�
if (entityUsage.getType() instanceof UnknownTypeInfo) {
this.resolvedIndo = new UnknownEntityUsageInfo(fromLine, fromColumn,
toLine, toColumn);
return this.resolvedIndo;
// �e���N���X�^�̏ꍇ
} else if (entityUsage.getType() instanceof ClassTypeInfo) {
final ClassInfo ownerClass = ((ClassTypeInfo) entityUsage.getType())
.getReferencedClass();
// �e���ΏۃN���X(TargetClassInfo)�̏ꍇ
if (ownerClass instanceof TargetClassInfo) {
// �܂��͗��p�\�ȃt�B�[���h�ꗗ���擾
boolean found = false;
{
// ���p�\�ȃC���X�^���X�t�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFields = Members
.getInstanceMembers(NameResolver.getAvailableFields(
(TargetClassInfo) ownerClass, usingClass));
for (final TargetFieldInfo availableField : availableFields) {
// ��v����t�B�[���h�������������ꍇ
if (name[i].equals(availableField.getName())) {
// usingMethod.addReferencee(availableField);
// availableField.addReferencer(usingMethod);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
availableField, true, fromLine, fromColumn,
toLine, toColumn);
found = true;
break;
}
}
}
// ���p�\�ȃt�B�[���h��������Ȃ������ꍇ�́C�O���N���X�ł���e�N���X������͂��D
// ���̃N���X�̃t�B�[���h���g�p���Ă���Ƃ݂Ȃ�
{
if (!found) {
final ClassInfo referencedClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
final ExternalClassInfo externalSuperClass = NameResolver
.getExternalSuperClass((TargetClassInfo) referencedClass);
if (!(referencedClass instanceof TargetInnerClassInfo)
&& (null != externalSuperClass)) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], externalSuperClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
fieldInfo, true, fromLine, fromColumn, toLine,
toColumn);
} else {
assert false : "Can't resolve entity usage1 : "
+ this.toString();
}
}
}
// �e���O���N���X(ExternalClassInfo)�̏ꍇ
} else if (ownerClass instanceof ExternalClassInfo) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(name[i],
ownerClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(), fieldInfo,
true, fromLine, fromColumn, toLine, toColumn);
}
} else {
assert false : "Here shouldn't be reached!";
}
}
this.resolvedIndo = entityUsage;
return this.resolvedIndo;
}
}
}
// ���p�\�ȃX�^�e�B�b�N�t�B�[���h������G���e�B�e�B��������
{
// ���̃N���X�ŗ��p�\�ȃX�^�e�B�b�N�t�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFieldsOfThisClass = Members
.<TargetFieldInfo> getStaticMembers(NameResolver.getAvailableFields(usingClass));
for (final TargetFieldInfo availableFieldOfThisClass : availableFieldsOfThisClass) {
// ��v����t�B�[���h�������������ꍇ
if (name[0].equals(availableFieldOfThisClass.getName())) {
// usingMethod.addReferencee(availableFieldOfThisClass);
// availableFieldOfThisClass.addReferencer(usingMethod);
// �e�̌^��
final ClassTypeInfo usingClassType = new ClassTypeInfo(usingClass);
for (final TypeParameterInfo typeParameter : usingClass.getTypeParameters()) {
usingClassType.addTypeArgument(typeParameter);
}
// availableField.getType() ���玟��word(name[i])�𖼑O����
EntityUsageInfo entityUsage = new FieldUsageInfo(usingClassType,
availableFieldOfThisClass, true, fromLine, fromColumn, toLine, toColumn);
for (int i = 1; i < name.length; i++) {
// �e�� UnknownTypeInfo ��������C�ǂ����悤���Ȃ�
if (entityUsage.getType() instanceof UnknownTypeInfo) {
this.resolvedIndo = new UnknownEntityUsageInfo(fromLine, fromColumn,
toLine, toColumn);
return this.resolvedIndo;
// �e���N���X�^�̏ꍇ
} else if (entityUsage.getType() instanceof ClassTypeInfo) {
final ClassInfo ownerClass = ((ClassTypeInfo) entityUsage.getType())
.getReferencedClass();
// �e���ΏۃN���X(TargetClassInfo)�̏ꍇ
if (ownerClass instanceof TargetClassInfo) {
// �܂��͗��p�\�ȃt�B�[���h�ꗗ���擾
boolean found = false;
{
// ���p�\�ȃX�^�e�B�b�N�t�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFields = Members
.getStaticMembers(NameResolver.getAvailableFields(
(TargetClassInfo) ownerClass, usingClass));
for (final TargetFieldInfo availableField : availableFields) {
// ��v����t�B�[���h�������������ꍇ
if (name[i].equals(availableField.getName())) {
// usingMethod.addReferencee(availableField);
// availableField.addReferencer(usingMethod);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
availableField, true, fromLine, fromColumn,
toLine, toColumn);
found = true;
break;
}
}
}
// �X�^�e�B�b�N�t�B�[���h�Ō�����Ȃ������ꍇ�́C�C���i�[�N���X����T��
{
if (!found) {
// �C���i�[�N���X�ꗗ���擾
final SortedSet<TargetInnerClassInfo> innerClasses = NameResolver
.getAvailableDirectInnerClasses((TargetClassInfo) ownerClass);
for (final TargetInnerClassInfo innerClass : innerClasses) {
// ��v����N���X�������������ꍇ
if (name[i].equals(innerClass.getClassName())) {
// TODO ���p�W���\�z����R�[�h���K�v�H
final ClassTypeInfo referenceType = new ClassTypeInfo(
innerClass);
entityUsage = new ClassReferenceInfo(referenceType,
fromLine, fromColumn, toLine, toColumn);
found = true;
break;
}
}
}
}
// ���p�\�ȃt�B�[���h��������Ȃ������ꍇ�́C�O���N���X�ł���e�N���X������͂��D
// ���̃N���X�̃t�B�[���h���g�p���Ă���Ƃ݂Ȃ�
{
if (!found) {
final ClassInfo referencedClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
final ExternalClassInfo externalSuperClass = NameResolver
.getExternalSuperClass((TargetClassInfo) referencedClass);
if (!(referencedClass instanceof TargetInnerClassInfo)
&& (null != externalSuperClass)) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], externalSuperClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
fieldInfo, true, fromLine, fromColumn, toLine,
toColumn);
} else {
assert false : "Can't resolve entity usage2 : "
+ this.toString();
}
}
}
// �e���O���N���X(ExternalClassInfo)�̏ꍇ
} else if (ownerClass instanceof ExternalClassInfo) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(name[i],
ownerClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(), fieldInfo,
true, fromLine, fromColumn, toLine, toColumn);
}
} else {
assert false : "Here shouldn't be reached!";
}
}
this.resolvedIndo = entityUsage;
return this.resolvedIndo;
}
}
}
// �G���e�B�e�B�������S���薼�ł���ꍇ������
{
for (int length = 1; length <= name.length; length++) {
// �������閼�O(String[])���쐬
final String[] searchingName = new String[length];
System.arraycopy(name, 0, searchingName, 0, length);
final ClassInfo searchingClass = classInfoManager.getClassInfo(searchingName);
if (null != searchingClass) {
EntityUsageInfo entityUsage = new ClassReferenceInfo(new ClassTypeInfo(
searchingClass), fromLine, fromColumn, toLine, toColumn);
for (int i = length; i < name.length; i++) {
// �e�� UnknownTypeInfo ��������C�ǂ����悤���Ȃ�
if (entityUsage.getType() instanceof UnknownTypeInfo) {
this.resolvedIndo = new UnknownEntityUsageInfo(fromLine, fromColumn,
toLine, toColumn);
return this.resolvedIndo;
// �e���N���X�^�̏ꍇ
} else if (entityUsage.getType() instanceof ClassTypeInfo) {
final ClassInfo ownerClass = ((ClassTypeInfo) entityUsage.getType())
.getReferencedClass();
// �e���ΏۃN���X(TargetClassInfo)�̏ꍇ
if (ownerClass instanceof TargetClassInfo) {
// �܂��͗��p�\�ȃt�B�[���h�ꗗ���擾
boolean found = false;
{
// ���p�\�ȃt�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFields = Members
.getStaticMembers(NameResolver.getAvailableFields(
(TargetClassInfo) ownerClass, usingClass));
for (final TargetFieldInfo availableField : availableFields) {
// ��v����t�B�[���h�������������ꍇ
if (name[i].equals(availableField.getName())) {
// usingMethod.addReferencee(availableField);
// availableField.addReferencer(usingMethod);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
availableField, true, fromLine, fromColumn,
toLine, toColumn);
found = true;
break;
}
}
}
// �X�^�e�B�b�N�t�B�[���h�Ō�����Ȃ������ꍇ�́C�C���i�[�N���X����T��
{
if (!found) {
// �C���i�[�N���X�ꗗ���擾
final SortedSet<TargetInnerClassInfo> innerClasses = NameResolver
.getAvailableDirectInnerClasses((TargetClassInfo) ownerClass);
for (final TargetInnerClassInfo innerClass : innerClasses) {
// ��v����N���X�������������ꍇ
if (name[i].equals(innerClass.getClassName())) {
// TODO ���p�W���\�z����R�[�h���K�v�H
final ClassTypeInfo referenceType = new ClassTypeInfo(
innerClass);
entityUsage = new ClassReferenceInfo(referenceType,
fromLine, fromColumn, toLine, toColumn);
found = true;
break;
}
}
}
}
// ���p�\�ȃt�B�[���h��������Ȃ������ꍇ�́C�O���N���X�ł���e�N���X������͂��D
// ���̃N���X�̃t�B�[���h���g�p���Ă���Ƃ݂Ȃ�
{
if (!found) {
final ClassInfo referencedClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
final ExternalClassInfo externalSuperClass = NameResolver
.getExternalSuperClass((TargetClassInfo) referencedClass);
if (!(referencedClass instanceof TargetInnerClassInfo)
&& (null != externalSuperClass)) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], externalSuperClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
fieldInfo, true, fromLine, fromColumn, toLine,
toColumn);
} else {
assert false : "Can't resolve entity usage3 : "
+ this.toString();
}
}
}
// �e���O���N���X(ExternalClassInfo)�̏ꍇ
} else if (ownerClass instanceof ExternalClassInfo) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(name[i],
ownerClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(), fieldInfo,
true, fromLine, fromColumn, toLine, toColumn);
}
} else {
assert false : "Here shouldn't be reached!";
}
}
this.resolvedIndo = entityUsage;
return this.resolvedIndo;
}
}
}
// ���p�\�ȃN���X������G���e�B�e�B��������
{
// �����N���X�����猟��
{
final TargetClassInfo outestClass;
if (usingClass instanceof TargetInnerClassInfo) {
outestClass = NameResolver.getOuterstClass((TargetInnerClassInfo) usingClass);
} else {
outestClass = usingClass;
}
for (final TargetInnerClassInfo innerClassInfo : NameResolver
.getAvailableInnerClasses(outestClass)) {
// �N���X���ƎQ�Ɩ��̐擪���������ꍇ�́C���̃N���X�����Q�Ɛ�ł���ƌ��肷��
final String innerClassName = innerClassInfo.getClassName();
if (innerClassName.equals(name[0])) {
EntityUsageInfo entityUsage = new ClassReferenceInfo(new ClassTypeInfo(
innerClassInfo), fromLine, fromColumn, toLine, toColumn);
for (int i = 1; i < name.length; i++) {
// �e�� UnknownTypeInfo ��������C�ǂ����悤���Ȃ�
if (entityUsage.getType() instanceof UnknownTypeInfo) {
this.resolvedIndo = new UnknownEntityUsageInfo(fromLine,
fromColumn, toLine, toColumn);
return this.resolvedIndo;
// �e���N���X�^�̏ꍇ
} else if (entityUsage.getType() instanceof ClassTypeInfo) {
final ClassInfo ownerClass = ((ClassTypeInfo) entityUsage.getType())
.getReferencedClass();
// �e���ΏۃN���X(TargetClassInfo)�̏ꍇ
if (ownerClass instanceof TargetClassInfo) {
// �܂��͗��p�\�ȃt�B�[���h�ꗗ���擾
boolean found = false;
{
// ���p�\�ȃt�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFields = NameResolver
.getAvailableFields((TargetClassInfo) ownerClass,
usingClass);
for (final TargetFieldInfo availableField : availableFields) {
// ��v����t�B�[���h�������������ꍇ
if (name[i].equals(availableField.getName())) {
// usingMethod.addReferencee(availableField);
// availableField.addReferencer(usingMethod);
entityUsage = new FieldUsageInfo(entityUsage
.getType(), availableField, true, fromLine,
fromColumn, toLine, toColumn);
found = true;
break;
}
}
}
// �X�^�e�B�b�N�t�B�[���h�Ō�����Ȃ������ꍇ�́C�C���i�[�N���X����T��
{
if (!found) {
// �C���i�[�N���X�ꗗ���擾
final SortedSet<TargetInnerClassInfo> innerClasses = NameResolver
.getAvailableDirectInnerClasses((TargetClassInfo) ownerClass);
for (final TargetInnerClassInfo innerClass : innerClasses) {
// ��v����N���X�������������ꍇ
if (name[i].equals(innerClass.getClassName())) {
// TODO ���p�W���\�z����R�[�h���K�v�H
final ClassTypeInfo referenceType = new ClassTypeInfo(
innerClassInfo);
entityUsage = new ClassReferenceInfo(
referenceType, fromLine, fromColumn,
toLine, toColumn);
found = true;
break;
}
}
}
}
// ���p�\�ȃt�B�[���h��������Ȃ������ꍇ�́C�O���N���X�ł���e�N���X������͂��D
// ���̃N���X�̃t�B�[���h���g�p���Ă���Ƃ݂Ȃ�
{
if (!found) {
final ClassInfo referencedClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
final ExternalClassInfo externalSuperClass = NameResolver
.getExternalSuperClass((TargetClassInfo) referencedClass);
if (!(referencedClass instanceof TargetInnerClassInfo)
&& (null != externalSuperClass)) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], externalSuperClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage
.getType(), fieldInfo, true, fromLine,
fromColumn, toLine, toColumn);
} else {
assert false : "Can't resolve entity usage3.5 : "
+ this.toString();
}
}
}
// �e���O���N���X(ExternalClassInfo)�̏ꍇ
} else if (ownerClass instanceof ExternalClassInfo) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], ownerClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
fieldInfo, true, fromLine, fromColumn, toLine, toColumn);
}
} else {
assert false : "Here shouldn't be reached!";
}
}
this.resolvedIndo = entityUsage;
return this.resolvedIndo;
}
}
}
// ���p�\�Ȗ��O��Ԃ��猟��
{
for (final AvailableNamespaceInfo availableNamespace : this
.getAvailableNamespaces()) {
// ���O��Ԗ�.* �ƂȂ��Ă���ꍇ
if (availableNamespace.isAllClasses()) {
final String[] namespace = availableNamespace.getNamespace();
// ���O��Ԃ̉��ɂ���e�N���X�ɑ���
for (final ClassInfo classInfo : classInfoManager.getClassInfos(namespace)) {
final String className = classInfo.getClassName();
// �N���X���ƎQ�Ɩ��̐擪���������ꍇ�́C���̃N���X�����Q�Ɛ�ł���ƌ��肷��
if (className.equals(name[0])) {
EntityUsageInfo entityUsage = new ClassReferenceInfo(
new ClassTypeInfo(classInfo), fromLine, fromColumn, toLine,
toColumn);
for (int i = 1; i < name.length; i++) {
// �e�� UnknownTypeInfo ��������C�ǂ����悤���Ȃ�
if (entityUsage.getType() instanceof UnknownTypeInfo) {
this.resolvedIndo = new UnknownEntityUsageInfo(fromLine,
fromColumn, toLine, toColumn);
return this.resolvedIndo;
// �e���N���X�^�̏ꍇ
} else if (entityUsage.getType() instanceof ClassTypeInfo) {
final ClassInfo ownerClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
// �e���ΏۃN���X(TargetClassInfo)�̏ꍇ
if (ownerClass instanceof TargetClassInfo) {
// �܂��͗��p�\�ȃt�B�[���h�ꗗ���擾
boolean found = false;
{
// ���p�\�ȃt�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFields = NameResolver
.getAvailableFields(
(TargetClassInfo) ownerClass,
usingClass);
for (TargetFieldInfo availableField : availableFields) {
// ��v����t�B�[���h�������������ꍇ
if (name[i].equals(availableField.getName())) {
// usingMethod.addReferencee(availableField);
// availableField.addReferencer(usingMethod);
entityUsage = new FieldUsageInfo(
entityUsage.getType(),
availableField, true, fromLine,
fromColumn, toLine, toColumn);
found = true;
break;
}
}
}
// �X�^�e�B�b�N�t�B�[���h�Ō�����Ȃ������ꍇ�́C�C���i�[�N���X����T��
{
if (!found) {
// �C���i�[�N���X�ꗗ���擾
final SortedSet<TargetInnerClassInfo> innerClasses = NameResolver
.getAvailableDirectInnerClasses((TargetClassInfo) ownerClass);
for (final TargetInnerClassInfo innerClass : innerClasses) {
// ��v����N���X�������������ꍇ
if (name[i].equals(innerClass
.getClassName())) {
// TODO ���p�W���\�z����R�[�h���K�v�H
final ClassTypeInfo referenceType = new ClassTypeInfo(
innerClass);
entityUsage = new ClassReferenceInfo(
referenceType, fromLine,
fromColumn, toLine, toColumn);
found = true;
break;
}
}
}
}
// ���p�\�ȃt�B�[���h��������Ȃ������ꍇ�́C�O���N���X�ł���e�N���X������͂��D
// ���̃N���X�̃t�B�[���h���g�p���Ă���Ƃ݂Ȃ�
{
if (!found) {
final ClassInfo referencedClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
final ExternalClassInfo externalSuperClass = NameResolver
.getExternalSuperClass((TargetClassInfo) referencedClass);
if (!(referencedClass instanceof TargetInnerClassInfo)
&& (null != externalSuperClass)) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], externalSuperClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(
entityUsage.getType(), fieldInfo,
true, fromLine, fromColumn, toLine,
toColumn);
} else {
assert false : "Can't resolve entity usage4 : "
+ this.toString();
}
}
}
// �e���O���N���X(ExternalClassInfo)�̏ꍇ
} else if (ownerClass instanceof ExternalClassInfo) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], ownerClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
fieldInfo, true, fromLine, fromColumn, toLine,
toColumn);
}
} else {
assert false : "Here shouldn't be reached!";
}
}
this.resolvedIndo = entityUsage;
return this.resolvedIndo;
}
}
// ���O���.�N���X�� �ƂȂ��Ă���ꍇ
} else {
final String[] importName = availableNamespace.getImportName();
// �N���X���ƎQ�Ɩ��̐擪���������ꍇ�́C���̃N���X�����Q�Ɛ�ł���ƌ��肷��
if (importName[importName.length - 1].equals(name[0])) {
ClassInfo specifiedClassInfo = classInfoManager
.getClassInfo(importName);
if (null == specifiedClassInfo) {
specifiedClassInfo = new ExternalClassInfo(importName);
classInfoManager.add((ExternalClassInfo) specifiedClassInfo);
}
EntityUsageInfo entityUsage = new ClassReferenceInfo(new ClassTypeInfo(
specifiedClassInfo), fromLine, fromColumn, toLine, toColumn);
for (int i = 1; i < name.length; i++) {
// �e�� UnknownTypeInfo ��������C�ǂ����悤���Ȃ�
if (entityUsage.getType() instanceof UnknownTypeInfo) {
this.resolvedIndo = new UnknownEntityUsageInfo(fromLine,
fromColumn, toLine, toColumn);
return this.resolvedIndo;
// �e���N���X�^�̏ꍇ
} else if (entityUsage.getType() instanceof ClassTypeInfo) {
final ClassInfo ownerClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
// �e���ΏۃN���X(TargetClassInfo)�̏ꍇ
if (ownerClass instanceof TargetClassInfo) {
// �܂��͗��p�\�ȃt�B�[���h�ꗗ���擾
boolean found = false;
{
// ���p�\�ȃt�B�[���h�ꗗ���擾
final List<TargetFieldInfo> availableFields = NameResolver
.getAvailableFields(
(TargetClassInfo) ownerClass,
usingClass);
for (final TargetFieldInfo availableField : availableFields) {
// ��v����t�B�[���h�������������ꍇ
if (name[i].equals(availableField.getName())) {
// usingMethod.addReferencee(availableField);
// availableField.addReferencer(usingMethod);
entityUsage = new FieldUsageInfo(entityUsage
.getType(), availableField, true,
fromLine, fromColumn, toLine, toColumn);
found = true;
break;
}
}
}
// �X�^�e�B�b�N�t�B�[���h�Ō�����Ȃ������ꍇ�́C�C���i�[�N���X����T��
{
if (!found) {
// �C���i�[�N���X�ꗗ���擾
final SortedSet<TargetInnerClassInfo> innerClasses = NameResolver
.getAvailableDirectInnerClasses((TargetClassInfo) ownerClass);
for (final TargetInnerClassInfo innerClass : innerClasses) {
// ��v����N���X�������������ꍇ
if (name[i].equals(innerClass.getClassName())) {
// TODO ���p�W���\�z����R�[�h���K�v�H
final ClassTypeInfo referenceType = new ClassTypeInfo(
innerClass);
entityUsage = new ClassReferenceInfo(
referenceType, fromLine,
fromColumn, toLine, toColumn);
found = true;
break;
}
}
}
}
// ���p�\�ȃt�B�[���h��������Ȃ������ꍇ�́C�O���N���X�ł���e�N���X������͂��D
// ���̃N���X�̃t�B�[���h���g�p���Ă���Ƃ݂Ȃ�
{
if (!found) {
final ClassInfo referencedClass = ((ClassTypeInfo) entityUsage
.getType()).getReferencedClass();
final ExternalClassInfo externalSuperClass = NameResolver
.getExternalSuperClass((TargetClassInfo) referencedClass);
if (!(referencedClass instanceof TargetInnerClassInfo)
&& (null != externalSuperClass)) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], externalSuperClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage
.getType(), fieldInfo, true, fromLine,
fromColumn, toLine, toColumn);
} else {
assert false : "Can't resolve entity usage5 : "
+ this.toString();
}
}
}
// �e���O���N���X(ExternalClassInfo)�̏ꍇ
} else if (ownerClass instanceof ExternalClassInfo) {
final ExternalFieldInfo fieldInfo = new ExternalFieldInfo(
name[i], ownerClass);
// usingMethod.addReferencee(fieldInfo);
// fieldInfo.addReferencer(usingMethod);
fieldInfoManager.add(fieldInfo);
entityUsage = new FieldUsageInfo(entityUsage.getType(),
fieldInfo, true, fromLine, fromColumn, toLine,
toColumn);
}
} else {
assert false : "Here shouldn't be reached!";
}
}
this.resolvedIndo = entityUsage;
return this.resolvedIndo;
}
}
}
}
}
// java����̏ꍇ�́Cjava��javax�Ŏn�܂�C������3�ȏ��UnknownEntityUsageInfo��JDK���̃N���X�Ƃ݂Ȃ�
if (Settings.getLanguage().equals(LANGUAGE.JAVA)) {
if ((name[0].equals("java") || name[0].equals("javax")) && (3 <= name.length)) {
final ExternalClassInfo externalClass = new ExternalClassInfo(name);
final ClassTypeInfo externalClassType = new ClassTypeInfo(externalClass);
this.resolvedIndo = new ClassReferenceInfo(externalClassType, fromLine, fromColumn,
toLine, toColumn);
classInfoManager.add(externalClass);
return this.resolvedIndo;
}
}
err.println("Remain unresolved \"" + this.toString() + "\"" + " line:" + this.getFromLine()
+ " column:" + this.getFromColumn() + " on \""
+ usingClass.getFullQualifiedName(LANGUAGE.JAVA.getNamespaceDelimiter()));
// ������Ȃ������������s��
usingMethod.addUnresolvedUsage(this);
this.resolvedIndo = new UnknownEntityUsageInfo(fromLine, fromColumn, toLine, toColumn);
return this.resolvedIndo;
}
|
diff --git a/wings/src/java/org/wings/plaf/css/ContainerCG.java b/wings/src/java/org/wings/plaf/css/ContainerCG.java
index 1127f71..b8519c3 100644
--- a/wings/src/java/org/wings/plaf/css/ContainerCG.java
+++ b/wings/src/java/org/wings/plaf/css/ContainerCG.java
@@ -1,67 +1,69 @@
/*
* Copyright 2000,2005 wingS development team.
*
* This file is part of wingS (http://wingsframework.org).
*
* wingS 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.
*
* Please see COPYING for the complete licence.
*/
package org.wings.plaf.css;
import org.wings.*;
import org.wings.io.Device;
import org.wings.session.ScriptManager;
import org.wings.plaf.css.script.*;
public class ContainerCG extends AbstractComponentCG implements org.wings.plaf.PanelCG {
private static final long serialVersionUID = 1L;
public void writeInternal(final Device device, final SComponent component) throws java.io.IOException {
final SContainer container = (SContainer) component;
final SLayoutManager layout = container.getLayout();
SDimension preferredSize = container.getPreferredSize();
String height = preferredSize != null ? preferredSize.getHeight() : null;
boolean clientLayout = height != null && Utils.isMSIE(container) && !"auto".equals(height)
&& (layout instanceof SBorderLayout || layout instanceof SGridBagLayout || layout instanceof SCardLayout);
device.print("<table");
if (clientLayout) {
Utils.optAttribute(device, "layoutHeight", height);
- Utils.setPreferredSize(component, preferredSize.getWidth(), null);
+ if (!"px".equals(preferredSize.getHeightUnit()))
+ Utils.setPreferredSize(component, preferredSize.getWidth(), null);
}
Utils.writeAllAttributes(device, component);
Utils.writeEvents(device, component, null);
if (clientLayout) {
- Utils.setPreferredSize(component, preferredSize.getWidth(), height);
+ if (!"px".equals(preferredSize.getHeightUnit()))
+ Utils.setPreferredSize(component, preferredSize.getWidth(), height);
ScriptManager.getInstance().addScriptListener(new LayoutFillScript(component.getName()));
}
device.print(">");
// special case templateLayout and card layout. We open a TABLE cell for them.
final boolean writeTableData = layout instanceof STemplateLayout;
if (writeTableData) {
device.print("<tr><td");
Utils.printTableCellAlignment(device, component, SConstants.LEFT_ALIGN, SConstants.TOP_ALIGN);
device.print(">");
}
Utils.renderContainer(device, container);
if (writeTableData) {
device.print("</td></tr>");
}
device.print("</table>");
}
}
| false | true | public void writeInternal(final Device device, final SComponent component) throws java.io.IOException {
final SContainer container = (SContainer) component;
final SLayoutManager layout = container.getLayout();
SDimension preferredSize = container.getPreferredSize();
String height = preferredSize != null ? preferredSize.getHeight() : null;
boolean clientLayout = height != null && Utils.isMSIE(container) && !"auto".equals(height)
&& (layout instanceof SBorderLayout || layout instanceof SGridBagLayout || layout instanceof SCardLayout);
device.print("<table");
if (clientLayout) {
Utils.optAttribute(device, "layoutHeight", height);
Utils.setPreferredSize(component, preferredSize.getWidth(), null);
}
Utils.writeAllAttributes(device, component);
Utils.writeEvents(device, component, null);
if (clientLayout) {
Utils.setPreferredSize(component, preferredSize.getWidth(), height);
ScriptManager.getInstance().addScriptListener(new LayoutFillScript(component.getName()));
}
device.print(">");
// special case templateLayout and card layout. We open a TABLE cell for them.
final boolean writeTableData = layout instanceof STemplateLayout;
if (writeTableData) {
device.print("<tr><td");
Utils.printTableCellAlignment(device, component, SConstants.LEFT_ALIGN, SConstants.TOP_ALIGN);
device.print(">");
}
Utils.renderContainer(device, container);
if (writeTableData) {
device.print("</td></tr>");
}
device.print("</table>");
}
| public void writeInternal(final Device device, final SComponent component) throws java.io.IOException {
final SContainer container = (SContainer) component;
final SLayoutManager layout = container.getLayout();
SDimension preferredSize = container.getPreferredSize();
String height = preferredSize != null ? preferredSize.getHeight() : null;
boolean clientLayout = height != null && Utils.isMSIE(container) && !"auto".equals(height)
&& (layout instanceof SBorderLayout || layout instanceof SGridBagLayout || layout instanceof SCardLayout);
device.print("<table");
if (clientLayout) {
Utils.optAttribute(device, "layoutHeight", height);
if (!"px".equals(preferredSize.getHeightUnit()))
Utils.setPreferredSize(component, preferredSize.getWidth(), null);
}
Utils.writeAllAttributes(device, component);
Utils.writeEvents(device, component, null);
if (clientLayout) {
if (!"px".equals(preferredSize.getHeightUnit()))
Utils.setPreferredSize(component, preferredSize.getWidth(), height);
ScriptManager.getInstance().addScriptListener(new LayoutFillScript(component.getName()));
}
device.print(">");
// special case templateLayout and card layout. We open a TABLE cell for them.
final boolean writeTableData = layout instanceof STemplateLayout;
if (writeTableData) {
device.print("<tr><td");
Utils.printTableCellAlignment(device, component, SConstants.LEFT_ALIGN, SConstants.TOP_ALIGN);
device.print(">");
}
Utils.renderContainer(device, container);
if (writeTableData) {
device.print("</td></tr>");
}
device.print("</table>");
}
|
diff --git a/src/main/java/netweb/MkIndex.java b/src/main/java/netweb/MkIndex.java
index 64cb475a..f058e435 100644
--- a/src/main/java/netweb/MkIndex.java
+++ b/src/main/java/netweb/MkIndex.java
@@ -1,206 +1,206 @@
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
/** A simple HTML Link Checker.
* Sorta working, but not ready for prime time.
* Needs code simplification/elimination.
* Need to have a -depth N argument to limit depth of checking.
* Responses not adequate; need to check at least for 404-type errors!
* When all that is said and done, display in a Tree instead of a TextArea.
*
* @author Ian Darwin, Darwin Open Systems, www.darwinsys.com.
* Routine "readTag" stolen shamelessly from from
* Elliott Rusty Harold's "ImageSizer" program.
*/
public class LinkChecker extends Frame implements Runnable {
protected Thread t = null;
protected Runnable selfRef;
protected TextField textFldURL;
protected TextArea textWindow;
protected Panel p;
protected Button checkButton;
protected Button killButton;
public static void main(String[] args) {
LinkChecker lc = new LinkChecker();
if (args.length == 1)
lc.textFldURL.setText(args[0]);
lc.setSize(500, 400);
lc.setVisible(true);
}
/** Construct a LinkChecker */
public LinkChecker() {
super("LinkChecker");
selfRef = this;
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
setVisible(false);
dispose();
System.exit(0);
}
});
setLayout(new BorderLayout());
textFldURL = new TextField(40);
add("North", textFldURL);
textWindow = new TextArea(80, 40);
add("Center", textWindow);
add("South", p = new Panel());
p.add(checkButton = new Button("Check URL"));
checkButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (t!=null && t.isAlive())
return;
t = new Thread(selfRef);
t.start();
}
});
p.add(killButton = new Button("Stop"));
killButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (t == null || !t.isAlive())
return;
t.stop();
textWindow.append("-- Interrupted --");
}
});
}
public synchronized void run() {
textWindow.setText("");
checkOut(textFldURL.getText());
textWindow.append("-- All done --");
}
/** Start checking, given a URL by name. */
public void checkOut(String pageURL) {
String thisLine = null;
URL root = null;
if (pageURL == null) {
throw new IllegalArgumentException(
"checkOut(null) isn't very useful");
}
// Open the URL for reading
try {
root = new URL(pageURL);
BufferedReader inrdr = null;
char thisChar = 0;
String tag = null;
inrdr = new BufferedReader(new InputStreamReader(root.openStream()));
int i;
while ((i = inrdr.read()) != -1) {
thisChar = (char)i;
if (thisChar == '<') {
tag = readTag(inrdr);
// System.out.println("TAG: " + tag);
if (tag.toUpperCase().startsWith("<A ") ||
tag.toUpperCase().startsWith("<A\t")) {
String href = extractHREF(tag);
// Can't really validate these!
if (href.startsWith("mailto:"))
continue;
textWindow.append(href + " -- ");
// don't combine previous append with this one,
// since this one can throw an exception!
textWindow.append(checkLink(root, href) + "\n");
// If HTML, check it recursively
if (href.endsWith(".htm") ||
href.endsWith(".html")) {
if (href.indexOf(":") != -1)
checkOut(href);
else {
String newRef = root.getProtocol() +
"://" + root.getHost() + "/" + href;
System.out.println(newRef);
checkOut(newRef);
}
}
}
}
}
inrdr.close();
}
catch (MalformedURLException e) {
textWindow.append("Can't parse " + pageURL + "\n");
}
catch (IOException e) {
- textWindow.append("Error " + root + ":<" + e +">\n");
+ System.err.println("Error " + root + ":<" + e +">\n");
}
}
/** Check one link, given its DocumentBase and the tag */
public String checkLink(URL baseURL, String thisURL) {
URL linkURL;
try {
if (thisURL.indexOf(":") == -1) {
// it's not an absolute URL
linkURL = new URL(baseURL, thisURL);
} else {
linkURL = new URL(thisURL);
}
// Open it; if the open fails we'll likely throw an exception
URLConnection luf = linkURL.openConnection();
if (luf instanceof HttpURLConnection) {
HttpURLConnection huf = (HttpURLConnection)linkURL.openConnection();
String s = huf.getResponseCode() + " " + huf.getResponseMessage();
if (huf.getResponseCode() == -1)
return "Server error: bad HTTP response";
return s;
// } else if (luf instanceof FileURLConnection) {
// return "(File)";
} else
return "(non-HTTP)";
}
catch (MalformedURLException e) {
return "MALFORMED";
}
catch (IOException e) {
return "DEAD";
}
}
/** Read one tag. Adapted from code by Elliott Rusty Harold */
public String readTag(BufferedReader is) {
StringBuffer theTag = new StringBuffer("<");
int i = '<';
try {
while (i != '>' && (i = is.read()) != -1)
theTag.append((char)i);
}
catch (IOException e) {
System.err.println("I/O Error: " + e);
}
catch (Exception e) {
System.err.println(e);
}
return theTag.toString();
}
/** Extract the URL from <A HREF="http://foo/bar" ...>
* We presume that the HREF is the first tag.
*/
public String extractHREF(String tag) throws MalformedURLException {
String s1 = tag.toUpperCase();
int p1, p2, p3, p4;
p1 = s1.indexOf("HREF");
p2 = s1.indexOf ("=", p1);
p3 = s1.indexOf("\"", p2);
p4 = s1.indexOf("\"", p3+1);
if (p3 < 0 || p4 < 0)
throw new MalformedURLException(tag);
return tag.substring(p3+1, p4);
}
}
| true | true | public void checkOut(String pageURL) {
String thisLine = null;
URL root = null;
if (pageURL == null) {
throw new IllegalArgumentException(
"checkOut(null) isn't very useful");
}
// Open the URL for reading
try {
root = new URL(pageURL);
BufferedReader inrdr = null;
char thisChar = 0;
String tag = null;
inrdr = new BufferedReader(new InputStreamReader(root.openStream()));
int i;
while ((i = inrdr.read()) != -1) {
thisChar = (char)i;
if (thisChar == '<') {
tag = readTag(inrdr);
// System.out.println("TAG: " + tag);
if (tag.toUpperCase().startsWith("<A ") ||
tag.toUpperCase().startsWith("<A\t")) {
String href = extractHREF(tag);
// Can't really validate these!
if (href.startsWith("mailto:"))
continue;
textWindow.append(href + " -- ");
// don't combine previous append with this one,
// since this one can throw an exception!
textWindow.append(checkLink(root, href) + "\n");
// If HTML, check it recursively
if (href.endsWith(".htm") ||
href.endsWith(".html")) {
if (href.indexOf(":") != -1)
checkOut(href);
else {
String newRef = root.getProtocol() +
"://" + root.getHost() + "/" + href;
System.out.println(newRef);
checkOut(newRef);
}
}
}
}
}
inrdr.close();
}
catch (MalformedURLException e) {
textWindow.append("Can't parse " + pageURL + "\n");
}
catch (IOException e) {
textWindow.append("Error " + root + ":<" + e +">\n");
}
}
| public void checkOut(String pageURL) {
String thisLine = null;
URL root = null;
if (pageURL == null) {
throw new IllegalArgumentException(
"checkOut(null) isn't very useful");
}
// Open the URL for reading
try {
root = new URL(pageURL);
BufferedReader inrdr = null;
char thisChar = 0;
String tag = null;
inrdr = new BufferedReader(new InputStreamReader(root.openStream()));
int i;
while ((i = inrdr.read()) != -1) {
thisChar = (char)i;
if (thisChar == '<') {
tag = readTag(inrdr);
// System.out.println("TAG: " + tag);
if (tag.toUpperCase().startsWith("<A ") ||
tag.toUpperCase().startsWith("<A\t")) {
String href = extractHREF(tag);
// Can't really validate these!
if (href.startsWith("mailto:"))
continue;
textWindow.append(href + " -- ");
// don't combine previous append with this one,
// since this one can throw an exception!
textWindow.append(checkLink(root, href) + "\n");
// If HTML, check it recursively
if (href.endsWith(".htm") ||
href.endsWith(".html")) {
if (href.indexOf(":") != -1)
checkOut(href);
else {
String newRef = root.getProtocol() +
"://" + root.getHost() + "/" + href;
System.out.println(newRef);
checkOut(newRef);
}
}
}
}
}
inrdr.close();
}
catch (MalformedURLException e) {
textWindow.append("Can't parse " + pageURL + "\n");
}
catch (IOException e) {
System.err.println("Error " + root + ":<" + e +">\n");
}
}
|
diff --git a/src/multimil/Main.java b/src/multimil/Main.java
index a3d9bc7..56f6b9f 100644
--- a/src/multimil/Main.java
+++ b/src/multimil/Main.java
@@ -1,27 +1,27 @@
package multimil;
import java.io.*;
/**
* Main class for Multimil.
*
* @author angelstam
*/
public class Main
{
/**
* @param args
*/
public static void main(String[] args)
{
System.out.println("Multimil disassembler for SY6502.");
opHandler handler;
- if (args[0].equals("smooth"))
+ if (args.length > 0 && args[0].equals("smooth"))
handler = new opHandler("../codematrix",2);
else
handler = new opHandler("../codematrix",1);
handler.generateInstructions("../doc/multimil.bin");
}
}
| true | true | public static void main(String[] args)
{
System.out.println("Multimil disassembler for SY6502.");
opHandler handler;
if (args[0].equals("smooth"))
handler = new opHandler("../codematrix",2);
else
handler = new opHandler("../codematrix",1);
handler.generateInstructions("../doc/multimil.bin");
}
| public static void main(String[] args)
{
System.out.println("Multimil disassembler for SY6502.");
opHandler handler;
if (args.length > 0 && args[0].equals("smooth"))
handler = new opHandler("../codematrix",2);
else
handler = new opHandler("../codematrix",1);
handler.generateInstructions("../doc/multimil.bin");
}
|
diff --git a/src/gov/nih/nci/eagle/service/strategies/GeneralizedLinearModelFindingStrategy.java b/src/gov/nih/nci/eagle/service/strategies/GeneralizedLinearModelFindingStrategy.java
index 41ce5a7..a25a1aa 100644
--- a/src/gov/nih/nci/eagle/service/strategies/GeneralizedLinearModelFindingStrategy.java
+++ b/src/gov/nih/nci/eagle/service/strategies/GeneralizedLinearModelFindingStrategy.java
@@ -1,268 +1,269 @@
package gov.nih.nci.eagle.service.strategies;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jms.JMSException;
import org.apache.log4j.Logger;
import gov.nih.nci.caintegrator.analysis.messaging.GLMSampleGroup;
import gov.nih.nci.caintegrator.analysis.messaging.GeneralizedLinearModelRequest;
import gov.nih.nci.caintegrator.analysis.messaging.SampleGroup;
import gov.nih.nci.caintegrator.application.analysis.AnalysisServerClientManager;
import gov.nih.nci.caintegrator.application.cache.BusinessTierCache;
import gov.nih.nci.caintegrator.application.service.strategy.AsynchronousFindingStrategy;
import gov.nih.nci.caintegrator.dto.query.ClassComparisonQueryDTO;
import gov.nih.nci.caintegrator.dto.query.QueryDTO;
import gov.nih.nci.caintegrator.enumeration.ArrayPlatformType;
import gov.nih.nci.caintegrator.enumeration.CoVariateType;
import gov.nih.nci.caintegrator.enumeration.StatisticalMethodType;
import gov.nih.nci.caintegrator.exceptions.FindingsAnalysisException;
import gov.nih.nci.caintegrator.exceptions.FindingsQueryException;
import gov.nih.nci.caintegrator.exceptions.ValidationException;
import gov.nih.nci.caintegrator.service.findings.Finding;
import gov.nih.nci.caintegrator.service.findings.GeneralizedLinearModelFinding;
import gov.nih.nci.caintegrator.service.task.Task;
import gov.nih.nci.caintegrator.service.task.TaskResult;
import gov.nih.nci.caintegrator.util.ValidationUtility;
import gov.nih.nci.eagle.dto.de.CoVariateDE;
import gov.nih.nci.eagle.enumeration.SpecimenType;
import gov.nih.nci.eagle.query.dto.ClassComparisonQueryDTOImpl;
import gov.nih.nci.eagle.util.PatientGroupManager;
public class GeneralizedLinearModelFindingStrategy extends
AsynchronousFindingStrategy {
private static Logger logger = Logger.getLogger(GeneralizedLinearModelFindingStrategy.class);
private Collection<SampleGroup> sampleGroups = new ArrayList<SampleGroup>();
private List<CoVariateType> coVariateTypes = new ArrayList<CoVariateType>();
private GeneralizedLinearModelRequest glmRequest = null;
private AnalysisServerClientManager analysisServerClientManager;
private Map<ArrayPlatformType, String> dataFileMap;
private PatientGroupManager pgm = new PatientGroupManager();
/*
* (non-Javadoc)
*
* @see gov.nih.nci.caintegrator.service.findings.strategies.FindingStrategy#createQuery()
* This method validates that 2 groups were passed for generalized linear model as the statistical method
*/
public boolean createQuery() throws FindingsQueryException {
// because each layer is valid I am assured I will be getting a fulling
// populated query object
StatisticalMethodType statisticType = getQueryDTO()
.getStatisticTypeDE().getValueObject();
if (getQueryDTO().getComparisonGroups() != null) {
if(statisticType==StatisticalMethodType.GLM) {
if (getQueryDTO().getComparisonGroups().size() < 1 && getQueryDTO().getBaselineGroupMap().size()>0) {
throw new FindingsQueryException(
"Incorrect Number of queries passed for the Generalized Linear Model statistical type");
}
}
return true;
}
return false;
}
protected void executeStrategy() {
glmRequest = new GeneralizedLinearModelRequest(taskResult
.getTask().getCacheId(), taskResult.getTask().getId());
businessCacheManager.addToSessionCache(getTaskResult().getTask()
.getCacheId(), getTaskResult().getTask().getId(),
getTaskResult());
}
/*
*
*/
public boolean analyzeResultSet() throws FindingsAnalysisException {
StatisticalMethodType statisticType = getQueryDTO().getStatisticTypeDE().getValueObject();
try {
if(statisticType==StatisticalMethodType.GLM) {
// set statistical method
glmRequest.setStatisticalMethod(statisticType);
// Set sample groups
HashMap<String, List> comparisonGroupsMap = getQueryDTO().getComparisonGroupsMap();
HashMap<String, List> baselineGroupMap = getQueryDTO().getBaselineGroupMap();
GLMSampleGroup baseline = null;
for(String gname : baselineGroupMap.keySet()) {
List<String> groups = baselineGroupMap.get(gname);
baseline = new GLMSampleGroup(gname);
baseline.addAll(baselineGroupMap.get(gname));
for(String name : groups ) {
//add each patient
HashMap<String, String> annotationMap = new HashMap<String, String>();
//fetch the data about each patient
Map pm = pgm.getPatientInfo(name);
annotationMap.put("sex", pm.get("sex").toString());
annotationMap.put("age", pm.get("age").toString());
annotationMap.put("smoking_status", pm.get("smoking_status").toString());
baseline.addPatientData(name, annotationMap);
}
}
glmRequest.setBaselineGroup(baseline);
List<GLMSampleGroup> glmsgs = new ArrayList<GLMSampleGroup>();
for(String gname : comparisonGroupsMap.keySet()) {
List<String> groups = comparisonGroupsMap.get(gname);
GLMSampleGroup comparison = new GLMSampleGroup(gname);
comparison.addAll(comparisonGroupsMap.get(gname));
for(String name : groups ) {
HashMap<String, String> annotationMap = new HashMap<String, String>();
Map pm = pgm.getPatientInfo(name);
annotationMap.put("sex", pm.get("sex").toString());
annotationMap.put("age", pm.get("age").toString());
annotationMap.put("smoking_status", pm.get("smoking_status").toString());
comparison.addPatientData(name, annotationMap);
}
+ glmsgs.add(comparison);
}
glmRequest.setComparisonGroups(glmsgs);
// set Co-variates
List<CoVariateDE> coVariateDEs = getQueryDTO().getCoVariateDEs();
Object[] obj = coVariateDEs.toArray();
for(int i=0; i<obj.length;i++) {
CoVariateDE coVariateDE = (CoVariateDE)obj[i];
coVariateTypes.add(coVariateDE.getValueObject());
}
glmRequest.setCoVariateTypes(coVariateTypes);
// set Multiple Comparison Adjustment type
glmRequest.setMultiGrpComparisonAdjType(getQueryDTO().getMultiGroupComparisonAdjustmentTypeDE().getValueObject());
// set foldChange
glmRequest.setFoldChangeThreshold(getQueryDTO().getExprFoldChangeDE().getValueObject());
// set pvalue
glmRequest.setPValueThreshold(getQueryDTO().getStatisticalSignificanceDE().getValueObject());
// set arrayplat form, come back to this to figure out how to pass the platform
// glmRequest.setArrayPlatform(getQueryDTO().getArrayPlatformDE().getValueObjectAsArrayPlatformType());
// go the correct matrix to fetch data
glmRequest.setDataFileName(dataFileMap.get(getQueryDTO().getSpecimenTypeEnum().name()));
analysisServerClientManager.sendRequest(glmRequest);
return true;
}
}// end of try
catch(JMSException ex) {
logger.error(ex.getMessage());
throw new FindingsAnalysisException(ex.getMessage());
}
catch(Exception ex) {
logger.error("erro in glm", ex);
throw new FindingsAnalysisException("Error in setting glmRequest object");
}
return false;
}
public Finding getFinding() {
return (GeneralizedLinearModelFinding) taskResult;
}
public boolean validate(QueryDTO queryDTO) throws ValidationException {
boolean _valid = false;
if (queryDTO instanceof ClassComparisonQueryDTO) {
ClassComparisonQueryDTO classComparisonQueryDTO = (ClassComparisonQueryDTO) queryDTO;
try {
ValidationUtility.checkForNull(classComparisonQueryDTO
.getArrayPlatformDE());
ValidationUtility.checkForNull(classComparisonQueryDTO
.getComparisonGroups());
ValidationUtility.checkForNull(classComparisonQueryDTO
.getExprFoldChangeDE());
ValidationUtility.checkForNull(classComparisonQueryDTO
.getMultiGroupComparisonAdjustmentTypeDE());
ValidationUtility.checkForNull(classComparisonQueryDTO
.getQueryName());
ValidationUtility.checkForNull(classComparisonQueryDTO
.getStatisticalSignificanceDE());
ValidationUtility.checkForNull(classComparisonQueryDTO
.getStatisticTypeDE());
_valid = true;
} catch (ValidationException ex) {
logger.error(ex.getMessage());
throw ex;
}
}
return _valid;
}
private ClassComparisonQueryDTOImpl getQueryDTO() {
return (ClassComparisonQueryDTOImpl) taskResult.getTask().getQueryDTO();
}
public TaskResult retrieveTaskResult(Task task) {
TaskResult taskResult = (TaskResult) businessCacheManager
.getObjectFromSessionCache(task.getCacheId(), task.getId());
return taskResult;
}
public boolean canHandle(QueryDTO query) {
if(query instanceof ClassComparisonQueryDTO) {
ClassComparisonQueryDTO dto = (ClassComparisonQueryDTO)query;
return ( dto.getStatisticTypeDE().getValueObject().equals(StatisticalMethodType.GLM));
}
return false;
}
public AnalysisServerClientManager getAnalysisServerClientManager() {
return analysisServerClientManager;
}
public void setAnalysisServerClientManager(
AnalysisServerClientManager analysisServerClientManager) {
this.analysisServerClientManager = analysisServerClientManager;
}
public BusinessTierCache getBusinessCacheManager() {
return businessCacheManager;
}
public void setBusinessCacheManager(BusinessTierCache cacheManager) {
this.businessCacheManager = cacheManager;
}
public Map getDataFileMap() {
return dataFileMap;
}
public void setDataFileMap(Map dataFileMap) {
this.dataFileMap = dataFileMap;
}
}
| true | true | public boolean analyzeResultSet() throws FindingsAnalysisException {
StatisticalMethodType statisticType = getQueryDTO().getStatisticTypeDE().getValueObject();
try {
if(statisticType==StatisticalMethodType.GLM) {
// set statistical method
glmRequest.setStatisticalMethod(statisticType);
// Set sample groups
HashMap<String, List> comparisonGroupsMap = getQueryDTO().getComparisonGroupsMap();
HashMap<String, List> baselineGroupMap = getQueryDTO().getBaselineGroupMap();
GLMSampleGroup baseline = null;
for(String gname : baselineGroupMap.keySet()) {
List<String> groups = baselineGroupMap.get(gname);
baseline = new GLMSampleGroup(gname);
baseline.addAll(baselineGroupMap.get(gname));
for(String name : groups ) {
//add each patient
HashMap<String, String> annotationMap = new HashMap<String, String>();
//fetch the data about each patient
Map pm = pgm.getPatientInfo(name);
annotationMap.put("sex", pm.get("sex").toString());
annotationMap.put("age", pm.get("age").toString());
annotationMap.put("smoking_status", pm.get("smoking_status").toString());
baseline.addPatientData(name, annotationMap);
}
}
glmRequest.setBaselineGroup(baseline);
List<GLMSampleGroup> glmsgs = new ArrayList<GLMSampleGroup>();
for(String gname : comparisonGroupsMap.keySet()) {
List<String> groups = comparisonGroupsMap.get(gname);
GLMSampleGroup comparison = new GLMSampleGroup(gname);
comparison.addAll(comparisonGroupsMap.get(gname));
for(String name : groups ) {
HashMap<String, String> annotationMap = new HashMap<String, String>();
Map pm = pgm.getPatientInfo(name);
annotationMap.put("sex", pm.get("sex").toString());
annotationMap.put("age", pm.get("age").toString());
annotationMap.put("smoking_status", pm.get("smoking_status").toString());
comparison.addPatientData(name, annotationMap);
}
}
glmRequest.setComparisonGroups(glmsgs);
// set Co-variates
List<CoVariateDE> coVariateDEs = getQueryDTO().getCoVariateDEs();
Object[] obj = coVariateDEs.toArray();
for(int i=0; i<obj.length;i++) {
CoVariateDE coVariateDE = (CoVariateDE)obj[i];
coVariateTypes.add(coVariateDE.getValueObject());
}
glmRequest.setCoVariateTypes(coVariateTypes);
// set Multiple Comparison Adjustment type
glmRequest.setMultiGrpComparisonAdjType(getQueryDTO().getMultiGroupComparisonAdjustmentTypeDE().getValueObject());
// set foldChange
glmRequest.setFoldChangeThreshold(getQueryDTO().getExprFoldChangeDE().getValueObject());
// set pvalue
glmRequest.setPValueThreshold(getQueryDTO().getStatisticalSignificanceDE().getValueObject());
// set arrayplat form, come back to this to figure out how to pass the platform
// glmRequest.setArrayPlatform(getQueryDTO().getArrayPlatformDE().getValueObjectAsArrayPlatformType());
// go the correct matrix to fetch data
glmRequest.setDataFileName(dataFileMap.get(getQueryDTO().getSpecimenTypeEnum().name()));
analysisServerClientManager.sendRequest(glmRequest);
return true;
}
}// end of try
catch(JMSException ex) {
logger.error(ex.getMessage());
throw new FindingsAnalysisException(ex.getMessage());
}
catch(Exception ex) {
logger.error("erro in glm", ex);
throw new FindingsAnalysisException("Error in setting glmRequest object");
}
return false;
}
| public boolean analyzeResultSet() throws FindingsAnalysisException {
StatisticalMethodType statisticType = getQueryDTO().getStatisticTypeDE().getValueObject();
try {
if(statisticType==StatisticalMethodType.GLM) {
// set statistical method
glmRequest.setStatisticalMethod(statisticType);
// Set sample groups
HashMap<String, List> comparisonGroupsMap = getQueryDTO().getComparisonGroupsMap();
HashMap<String, List> baselineGroupMap = getQueryDTO().getBaselineGroupMap();
GLMSampleGroup baseline = null;
for(String gname : baselineGroupMap.keySet()) {
List<String> groups = baselineGroupMap.get(gname);
baseline = new GLMSampleGroup(gname);
baseline.addAll(baselineGroupMap.get(gname));
for(String name : groups ) {
//add each patient
HashMap<String, String> annotationMap = new HashMap<String, String>();
//fetch the data about each patient
Map pm = pgm.getPatientInfo(name);
annotationMap.put("sex", pm.get("sex").toString());
annotationMap.put("age", pm.get("age").toString());
annotationMap.put("smoking_status", pm.get("smoking_status").toString());
baseline.addPatientData(name, annotationMap);
}
}
glmRequest.setBaselineGroup(baseline);
List<GLMSampleGroup> glmsgs = new ArrayList<GLMSampleGroup>();
for(String gname : comparisonGroupsMap.keySet()) {
List<String> groups = comparisonGroupsMap.get(gname);
GLMSampleGroup comparison = new GLMSampleGroup(gname);
comparison.addAll(comparisonGroupsMap.get(gname));
for(String name : groups ) {
HashMap<String, String> annotationMap = new HashMap<String, String>();
Map pm = pgm.getPatientInfo(name);
annotationMap.put("sex", pm.get("sex").toString());
annotationMap.put("age", pm.get("age").toString());
annotationMap.put("smoking_status", pm.get("smoking_status").toString());
comparison.addPatientData(name, annotationMap);
}
glmsgs.add(comparison);
}
glmRequest.setComparisonGroups(glmsgs);
// set Co-variates
List<CoVariateDE> coVariateDEs = getQueryDTO().getCoVariateDEs();
Object[] obj = coVariateDEs.toArray();
for(int i=0; i<obj.length;i++) {
CoVariateDE coVariateDE = (CoVariateDE)obj[i];
coVariateTypes.add(coVariateDE.getValueObject());
}
glmRequest.setCoVariateTypes(coVariateTypes);
// set Multiple Comparison Adjustment type
glmRequest.setMultiGrpComparisonAdjType(getQueryDTO().getMultiGroupComparisonAdjustmentTypeDE().getValueObject());
// set foldChange
glmRequest.setFoldChangeThreshold(getQueryDTO().getExprFoldChangeDE().getValueObject());
// set pvalue
glmRequest.setPValueThreshold(getQueryDTO().getStatisticalSignificanceDE().getValueObject());
// set arrayplat form, come back to this to figure out how to pass the platform
// glmRequest.setArrayPlatform(getQueryDTO().getArrayPlatformDE().getValueObjectAsArrayPlatformType());
// go the correct matrix to fetch data
glmRequest.setDataFileName(dataFileMap.get(getQueryDTO().getSpecimenTypeEnum().name()));
analysisServerClientManager.sendRequest(glmRequest);
return true;
}
}// end of try
catch(JMSException ex) {
logger.error(ex.getMessage());
throw new FindingsAnalysisException(ex.getMessage());
}
catch(Exception ex) {
logger.error("erro in glm", ex);
throw new FindingsAnalysisException("Error in setting glmRequest object");
}
return false;
}
|
diff --git a/beanstalk-maven-plugin/src/main/java/br/com/ingenieux/mojo/beanstalk/cmd/env/waitfor/WaitForEnvironmentCommand.java b/beanstalk-maven-plugin/src/main/java/br/com/ingenieux/mojo/beanstalk/cmd/env/waitfor/WaitForEnvironmentCommand.java
index c7660fa..3a85822 100644
--- a/beanstalk-maven-plugin/src/main/java/br/com/ingenieux/mojo/beanstalk/cmd/env/waitfor/WaitForEnvironmentCommand.java
+++ b/beanstalk-maven-plugin/src/main/java/br/com/ingenieux/mojo/beanstalk/cmd/env/waitfor/WaitForEnvironmentCommand.java
@@ -1,216 +1,216 @@
package br.com.ingenieux.mojo.beanstalk.cmd.env.waitfor;
import br.com.ingenieux.mojo.beanstalk.AbstractBeanstalkMojo;
import br.com.ingenieux.mojo.beanstalk.cmd.BaseCommand;
import com.amazonaws.services.elasticbeanstalk.model.DescribeEnvironmentsRequest;
import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription;
import com.amazonaws.services.elasticbeanstalk.model.EventDescription;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2;
import org.apache.commons.lang.Validate;
import org.apache.maven.plugin.AbstractMojoExecutionException;
import org.apache.maven.plugin.MojoExecutionException;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import static org.apache.commons.lang.StringUtils.defaultString;
import static org.apache.commons.lang.StringUtils.isNotBlank;
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class WaitForEnvironmentCommand extends
BaseCommand<WaitForEnvironmentContext, EnvironmentDescription> {
static class EventDescriptionComparator implements
Comparator<EventDescription> {
@Override
public int compare(EventDescription o1, EventDescription o2) {
return o1.getEventDate().compareTo(o2.getEventDate());
}
}
/**
* Poll Interval
*/
public static final long POLL_INTERVAL = 15 * 1000;
/**
* Magic Constant for Mins to MSEC
*/
private static final long MINS_TO_MSEC = 60 * 1000;
/**
* Constructor
*
* @param parentMojo
* parent mojo
* @throws AbstractMojoExecutionException
*/
public WaitForEnvironmentCommand(AbstractBeanstalkMojo parentMojo)
throws MojoExecutionException {
super(parentMojo);
}
public Collection<EnvironmentDescription> lookupInternal(WaitForEnvironmentContext context) {
Predicate<EnvironmentDescription> envPredicate = getEnvironmentDescriptionPredicate(context);
DescribeEnvironmentsRequest req = new DescribeEnvironmentsRequest().withApplicationName(context.getApplicationName()).withIncludeDeleted(true);
final List<EnvironmentDescription> envs = parentMojo.getService().describeEnvironments(req).getEnvironments();
return Collections2.filter(envs, envPredicate);
}
protected Predicate<EnvironmentDescription> getEnvironmentDescriptionPredicate(WaitForEnvironmentContext context) {
// as well as those (which are used as predicate variables, thus being
// final)
final String environmentRef = context.getEnvironmentRef();
final String statusToWaitFor = defaultString(context.getStatusToWaitFor(), "!Terminated");
final String healthToWaitFor = context.getHealth();
// Sanity Check
Validate.isTrue(isNotBlank(environmentRef), "EnvironmentRef is blank or null", environmentRef);
// some argument juggling
final boolean negated = statusToWaitFor.startsWith("!");
// argument juggling
Predicate<EnvironmentDescription> envPredicate = null;
{
// start building predicates with the status one - "![status]" must
// be equal to status or not status
final int offset = negated ? 1 : 0;
final String vStatusToWaitFor = statusToWaitFor.substring(offset);
envPredicate = new Predicate<EnvironmentDescription>() {
public boolean apply(EnvironmentDescription t) {
boolean result = vStatusToWaitFor.equals(t.getStatus());
if (negated)
result = !result;
debug("testing status '%s' as equal as '%s' (negated? %s, offset: %d): %s",
vStatusToWaitFor, t.getStatus(), negated, offset,
result);
return result;
}
};
info("... with status %s set to '%s'", (negated ? "*NOT*" : " "), vStatusToWaitFor);
}
if (environmentRef.matches("e-\\p{Alnum}{10}")) {
envPredicate = Predicates.and(envPredicate, new Predicate<EnvironmentDescription>() {
@Override
public boolean apply(EnvironmentDescription t) {
return t.getEnvironmentId().equals(environmentRef);
}
});
info("... with environmentId equal to '%s'", environmentRef);
} else if (environmentRef.matches(".*\\Q.elasticbeanstalk.com\\E")) {
envPredicate = Predicates.and(envPredicate, new Predicate<EnvironmentDescription>() {
@Override
public boolean apply(EnvironmentDescription t) {
- return t.getCNAME().equals(environmentRef);
+ return defaultString(t.getCNAME()).equals(environmentRef);
}
});
info("... with cname set to '%s'", environmentRef);
} else {
envPredicate = Predicates.and(envPredicate, new Predicate<EnvironmentDescription>() {
@Override
public boolean apply(EnvironmentDescription t) {
return t.getEnvironmentName().equals(environmentRef);
}
});
info("... with environmentName set to '%s'", environmentRef);
}
{
if (isNotBlank(healthToWaitFor)) {
envPredicate = Predicates.and(envPredicate, new Predicate<EnvironmentDescription>() {
@Override
public boolean apply(EnvironmentDescription t) {
return t.getHealth().equals(healthToWaitFor);
}
});
info("... with health equal to '%s'", healthToWaitFor);
}
}
return envPredicate;
}
public EnvironmentDescription executeInternal(
WaitForEnvironmentContext context) throws Exception {
// Those are invariants
long timeoutMins = context.getTimeoutMins();
Date expiresAt = new Date(System.currentTimeMillis() + MINS_TO_MSEC
* timeoutMins);
Date lastMessageRecord = new Date();
parentMojo.getLog().info("Environment Lookup");
Predicate<EnvironmentDescription> envPredicate = getEnvironmentDescriptionPredicate(context);
do {
DescribeEnvironmentsRequest req = new DescribeEnvironmentsRequest().withApplicationName(context.getApplicationName()).withIncludeDeleted(true);
final List<EnvironmentDescription> envs = parentMojo.getService().describeEnvironments(req).getEnvironments();
Collection<EnvironmentDescription> validEnvironments = Collections2.filter(envs, envPredicate);
debug("There are %d environments", validEnvironments.size());
if (1 == validEnvironments.size()) {
EnvironmentDescription foundEnvironment = validEnvironments.iterator()
.next();
debug("Found environment %s", foundEnvironment);
return foundEnvironment;
} else {
debug("Found %d environments. No good. Ignoring.",
validEnvironments.size());
for (EnvironmentDescription d : validEnvironments)
debug(" ... %s", d);
}
sleepInterval(POLL_INTERVAL);
} while (!timedOutP(expiresAt));
throw new MojoExecutionException("Timed out");
}
boolean timedOutP(Date expiresAt) throws MojoExecutionException {
return expiresAt.before(new Date(System.currentTimeMillis()));
}
public void sleepInterval(long pollInterval) {
debug("Sleeping for %d seconds", pollInterval / 1000);
try {
Thread.sleep(pollInterval);
} catch (InterruptedException e) {
}
}
}
| true | true | protected Predicate<EnvironmentDescription> getEnvironmentDescriptionPredicate(WaitForEnvironmentContext context) {
// as well as those (which are used as predicate variables, thus being
// final)
final String environmentRef = context.getEnvironmentRef();
final String statusToWaitFor = defaultString(context.getStatusToWaitFor(), "!Terminated");
final String healthToWaitFor = context.getHealth();
// Sanity Check
Validate.isTrue(isNotBlank(environmentRef), "EnvironmentRef is blank or null", environmentRef);
// some argument juggling
final boolean negated = statusToWaitFor.startsWith("!");
// argument juggling
Predicate<EnvironmentDescription> envPredicate = null;
{
// start building predicates with the status one - "![status]" must
// be equal to status or not status
final int offset = negated ? 1 : 0;
final String vStatusToWaitFor = statusToWaitFor.substring(offset);
envPredicate = new Predicate<EnvironmentDescription>() {
public boolean apply(EnvironmentDescription t) {
boolean result = vStatusToWaitFor.equals(t.getStatus());
if (negated)
result = !result;
debug("testing status '%s' as equal as '%s' (negated? %s, offset: %d): %s",
vStatusToWaitFor, t.getStatus(), negated, offset,
result);
return result;
}
};
info("... with status %s set to '%s'", (negated ? "*NOT*" : " "), vStatusToWaitFor);
}
if (environmentRef.matches("e-\\p{Alnum}{10}")) {
envPredicate = Predicates.and(envPredicate, new Predicate<EnvironmentDescription>() {
@Override
public boolean apply(EnvironmentDescription t) {
return t.getEnvironmentId().equals(environmentRef);
}
});
info("... with environmentId equal to '%s'", environmentRef);
} else if (environmentRef.matches(".*\\Q.elasticbeanstalk.com\\E")) {
envPredicate = Predicates.and(envPredicate, new Predicate<EnvironmentDescription>() {
@Override
public boolean apply(EnvironmentDescription t) {
return t.getCNAME().equals(environmentRef);
}
});
info("... with cname set to '%s'", environmentRef);
} else {
envPredicate = Predicates.and(envPredicate, new Predicate<EnvironmentDescription>() {
@Override
public boolean apply(EnvironmentDescription t) {
return t.getEnvironmentName().equals(environmentRef);
}
});
info("... with environmentName set to '%s'", environmentRef);
}
{
if (isNotBlank(healthToWaitFor)) {
envPredicate = Predicates.and(envPredicate, new Predicate<EnvironmentDescription>() {
@Override
public boolean apply(EnvironmentDescription t) {
return t.getHealth().equals(healthToWaitFor);
}
});
info("... with health equal to '%s'", healthToWaitFor);
}
}
return envPredicate;
}
| protected Predicate<EnvironmentDescription> getEnvironmentDescriptionPredicate(WaitForEnvironmentContext context) {
// as well as those (which are used as predicate variables, thus being
// final)
final String environmentRef = context.getEnvironmentRef();
final String statusToWaitFor = defaultString(context.getStatusToWaitFor(), "!Terminated");
final String healthToWaitFor = context.getHealth();
// Sanity Check
Validate.isTrue(isNotBlank(environmentRef), "EnvironmentRef is blank or null", environmentRef);
// some argument juggling
final boolean negated = statusToWaitFor.startsWith("!");
// argument juggling
Predicate<EnvironmentDescription> envPredicate = null;
{
// start building predicates with the status one - "![status]" must
// be equal to status or not status
final int offset = negated ? 1 : 0;
final String vStatusToWaitFor = statusToWaitFor.substring(offset);
envPredicate = new Predicate<EnvironmentDescription>() {
public boolean apply(EnvironmentDescription t) {
boolean result = vStatusToWaitFor.equals(t.getStatus());
if (negated)
result = !result;
debug("testing status '%s' as equal as '%s' (negated? %s, offset: %d): %s",
vStatusToWaitFor, t.getStatus(), negated, offset,
result);
return result;
}
};
info("... with status %s set to '%s'", (negated ? "*NOT*" : " "), vStatusToWaitFor);
}
if (environmentRef.matches("e-\\p{Alnum}{10}")) {
envPredicate = Predicates.and(envPredicate, new Predicate<EnvironmentDescription>() {
@Override
public boolean apply(EnvironmentDescription t) {
return t.getEnvironmentId().equals(environmentRef);
}
});
info("... with environmentId equal to '%s'", environmentRef);
} else if (environmentRef.matches(".*\\Q.elasticbeanstalk.com\\E")) {
envPredicate = Predicates.and(envPredicate, new Predicate<EnvironmentDescription>() {
@Override
public boolean apply(EnvironmentDescription t) {
return defaultString(t.getCNAME()).equals(environmentRef);
}
});
info("... with cname set to '%s'", environmentRef);
} else {
envPredicate = Predicates.and(envPredicate, new Predicate<EnvironmentDescription>() {
@Override
public boolean apply(EnvironmentDescription t) {
return t.getEnvironmentName().equals(environmentRef);
}
});
info("... with environmentName set to '%s'", environmentRef);
}
{
if (isNotBlank(healthToWaitFor)) {
envPredicate = Predicates.and(envPredicate, new Predicate<EnvironmentDescription>() {
@Override
public boolean apply(EnvironmentDescription t) {
return t.getHealth().equals(healthToWaitFor);
}
});
info("... with health equal to '%s'", healthToWaitFor);
}
}
return envPredicate;
}
|
diff --git a/src/ee/ut/math/tvt/salessystem/ui/SalesSystemUI.java b/src/ee/ut/math/tvt/salessystem/ui/SalesSystemUI.java
index 3d5d5ea..759be96 100755
--- a/src/ee/ut/math/tvt/salessystem/ui/SalesSystemUI.java
+++ b/src/ee/ut/math/tvt/salessystem/ui/SalesSystemUI.java
@@ -1,149 +1,156 @@
package ee.ut.math.tvt.salessystem.ui;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.apache.log4j.Logger;
import com.jgoodies.looks.windows.WindowsLookAndFeel;
import ee.ut.math.tvt.BSS.comboBoxItem;
import ee.ut.math.tvt.salessystem.domain.controller.SalesDomainController;
import ee.ut.math.tvt.salessystem.ui.model.SalesSystemModel;
import ee.ut.math.tvt.salessystem.ui.tabs.HistoryTab;
import ee.ut.math.tvt.salessystem.ui.tabs.PurchaseTab;
import ee.ut.math.tvt.salessystem.ui.tabs.StockTab;
/**
* Graphical user interface of the sales system.
*/
public class SalesSystemUI extends JFrame {
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(SalesSystemUI.class);
private final SalesDomainController domainController;
// Warehouse model
private SalesSystemModel model;
// Instances of tab classes
private PurchaseTab purchaseTab;
private HistoryTab historyTab;
private StockTab stockTab;
/**
* Constructs sales system GUI.
* @param domainController Sales domain controller.
*/
public SalesSystemUI(SalesDomainController domainController) {
this.domainController = domainController;
this.model = new SalesSystemModel(domainController);
// Create singleton instances of the tab classes
historyTab = new HistoryTab(model);
stockTab = new StockTab(model);
purchaseTab = new PurchaseTab(domainController, model);
setTitle("Sales system");
// set L&F to the nice Windows style
try {
UIManager.setLookAndFeel(new WindowsLookAndFeel());
} catch (UnsupportedLookAndFeelException e1) {
log.warn(e1.getMessage());
}
drawWidgets();
// size & location
int width = 600;
int height = 400;
setSize(width, height);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((screen.width - width) / 2, (screen.height - height) / 2);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
private Component getComponent(String componentName, Component component) {
Component found = null;
if (component.getName() != null && component.getName().equals(componentName)) {
found = component;
} else {
for (Component child : ((Container) component).getComponents()) {
found = getComponent(componentName, child);
if (found != null)
break;
}
}
return found;
}
private void drawWidgets() {
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add("Point-of-sale", purchaseTab.draw());
tabbedPane.add("Warehouse", stockTab.draw());
tabbedPane.add("History", historyTab.draw());
tabbedPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (e.getSource() instanceof JTabbedPane) {
JTabbedPane tabPages = (JTabbedPane)e.getSource();
switch (tabPages.getSelectedIndex()) {
case 0:
- Component comp = getComponent("BarCodeComboBox",
- tabPages.getSelectedComponent());
+ Component comp = getComponent("BarCodeComboBox", tabPages.getSelectedComponent());
if ((comp != null) && (comp instanceof JComboBox)) {
JComboBox barCodeCB = (JComboBox) comp;
- long Id = ((comboBoxItem) barCodeCB.getSelectedItem()).getId().longValue();
+ Object itemOld = barCodeCB.getSelectedItem();
+ long Id = -1;
+ if (itemOld != null) {
+ Id = ((comboBoxItem) itemOld).getId().longValue();
+ }
barCodeCB.setModel(new DefaultComboBoxModel(model.getWarehouseTableModel().getProductList()));
+ if (Id == -1) {
+ barCodeCB.setSelectedIndex(-1);
+ break;
+ }
for (int i = 0; i < barCodeCB.getItemCount(); i++) {
if (Id == ((comboBoxItem) barCodeCB.getItemAt(i)).getId().longValue()) {
- barCodeCB.setSelectedIndex(i);
+ barCodeCB.setSelectedIndex(i);
break;
}
}
}
break;
default:
break;
}
log.debug("Tab: " + tabPages.getSelectedComponent().getName());
//System.out.println("Tab: change active");
}
}
});
getContentPane().add(tabbedPane);
}
}
| false | true | private void drawWidgets() {
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add("Point-of-sale", purchaseTab.draw());
tabbedPane.add("Warehouse", stockTab.draw());
tabbedPane.add("History", historyTab.draw());
tabbedPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (e.getSource() instanceof JTabbedPane) {
JTabbedPane tabPages = (JTabbedPane)e.getSource();
switch (tabPages.getSelectedIndex()) {
case 0:
Component comp = getComponent("BarCodeComboBox",
tabPages.getSelectedComponent());
if ((comp != null) && (comp instanceof JComboBox)) {
JComboBox barCodeCB = (JComboBox) comp;
long Id = ((comboBoxItem) barCodeCB.getSelectedItem()).getId().longValue();
barCodeCB.setModel(new DefaultComboBoxModel(model.getWarehouseTableModel().getProductList()));
for (int i = 0; i < barCodeCB.getItemCount(); i++) {
if (Id == ((comboBoxItem) barCodeCB.getItemAt(i)).getId().longValue()) {
barCodeCB.setSelectedIndex(i);
break;
}
}
}
break;
default:
break;
}
log.debug("Tab: " + tabPages.getSelectedComponent().getName());
//System.out.println("Tab: change active");
}
}
});
getContentPane().add(tabbedPane);
}
| private void drawWidgets() {
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add("Point-of-sale", purchaseTab.draw());
tabbedPane.add("Warehouse", stockTab.draw());
tabbedPane.add("History", historyTab.draw());
tabbedPane.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if (e.getSource() instanceof JTabbedPane) {
JTabbedPane tabPages = (JTabbedPane)e.getSource();
switch (tabPages.getSelectedIndex()) {
case 0:
Component comp = getComponent("BarCodeComboBox", tabPages.getSelectedComponent());
if ((comp != null) && (comp instanceof JComboBox)) {
JComboBox barCodeCB = (JComboBox) comp;
Object itemOld = barCodeCB.getSelectedItem();
long Id = -1;
if (itemOld != null) {
Id = ((comboBoxItem) itemOld).getId().longValue();
}
barCodeCB.setModel(new DefaultComboBoxModel(model.getWarehouseTableModel().getProductList()));
if (Id == -1) {
barCodeCB.setSelectedIndex(-1);
break;
}
for (int i = 0; i < barCodeCB.getItemCount(); i++) {
if (Id == ((comboBoxItem) barCodeCB.getItemAt(i)).getId().longValue()) {
barCodeCB.setSelectedIndex(i);
break;
}
}
}
break;
default:
break;
}
log.debug("Tab: " + tabPages.getSelectedComponent().getName());
//System.out.println("Tab: change active");
}
}
});
getContentPane().add(tabbedPane);
}
|
diff --git a/src/test/java/com/technophobia/webdriver/substeps/runner/WebdriverSubstepsPropertiesConfigurationTest.java b/src/test/java/com/technophobia/webdriver/substeps/runner/WebdriverSubstepsPropertiesConfigurationTest.java
index 75a3e28..73bb512 100644
--- a/src/test/java/com/technophobia/webdriver/substeps/runner/WebdriverSubstepsPropertiesConfigurationTest.java
+++ b/src/test/java/com/technophobia/webdriver/substeps/runner/WebdriverSubstepsPropertiesConfigurationTest.java
@@ -1,80 +1,76 @@
/*
* Copyright Technophobia Ltd 2012
*
* This file is part of Substeps.
*
* Substeps 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.
*
* Substeps 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 Substeps. If not, see <http://www.gnu.org/licenses/>.
*/
package com.technophobia.webdriver.substeps.runner;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.startsWith;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.junit.Assert;
import org.junit.Test;
/**
* @author imoore
*/
public class WebdriverSubstepsPropertiesConfigurationTest {
@Test
public void checkOverrides() {
System.setProperty("environment", "localhost");
Assert.assertFalse(WebdriverSubstepsPropertiesConfiguration.INSTANCE.closeVisualWebDriveronFail());
}
@Test
public void testRelativeURLResolvesToFileProtocol() throws SecurityException,
NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
InvocationTargetException {
- final Method determineBaseURLMethod = WebdriverSubstepsPropertiesConfiguration.class
- .getDeclaredMethod("determineBaseURL", String.class);
+ final WebdriverSubstepsPropertiesConfiguration config = WebdriverSubstepsPropertiesConfiguration.INSTANCE;
+ final Method determineBaseURLMethod = config.getClass().getDeclaredMethod("determineBaseURL", String.class);
determineBaseURLMethod.setAccessible(true);
- final String baseUrl = (String) determineBaseURLMethod.invoke(
- WebdriverSubstepsPropertiesConfiguration.class, "src/web");
+ final String baseUrl = (String) determineBaseURLMethod.invoke(config, "src/web");
Assert.assertThat(baseUrl, startsWith("file:/"));
- final String baseUrl2 = (String) determineBaseURLMethod.invoke(
- WebdriverSubstepsPropertiesConfiguration.class, "./src/web");
+ final String baseUrl2 = (String) determineBaseURLMethod.invoke(config, "./src/web");
final File current = new File(".");
Assert.assertThat(baseUrl2, is(current.toURI().toString() + "src/web"));
- final String baseUrl3 = (String) determineBaseURLMethod.invoke(
- WebdriverSubstepsPropertiesConfiguration.class, "http://blah-blah.com/src/web");
+ final String baseUrl3 = (String) determineBaseURLMethod.invoke(config, "http://blah-blah.com/src/web");
Assert.assertThat(baseUrl3, startsWith("http://"));
- final String baseUrl4 = (String) determineBaseURLMethod.invoke(
- WebdriverSubstepsPropertiesConfiguration.class, "file://some-path/whatever");
+ final String baseUrl4 = (String) determineBaseURLMethod.invoke(config, "file://some-path/whatever");
Assert.assertThat(baseUrl4, is("file://some-path/whatever"));
}
}
| false | true | public void testRelativeURLResolvesToFileProtocol() throws SecurityException,
NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
InvocationTargetException {
final Method determineBaseURLMethod = WebdriverSubstepsPropertiesConfiguration.class
.getDeclaredMethod("determineBaseURL", String.class);
determineBaseURLMethod.setAccessible(true);
final String baseUrl = (String) determineBaseURLMethod.invoke(
WebdriverSubstepsPropertiesConfiguration.class, "src/web");
Assert.assertThat(baseUrl, startsWith("file:/"));
final String baseUrl2 = (String) determineBaseURLMethod.invoke(
WebdriverSubstepsPropertiesConfiguration.class, "./src/web");
final File current = new File(".");
Assert.assertThat(baseUrl2, is(current.toURI().toString() + "src/web"));
final String baseUrl3 = (String) determineBaseURLMethod.invoke(
WebdriverSubstepsPropertiesConfiguration.class, "http://blah-blah.com/src/web");
Assert.assertThat(baseUrl3, startsWith("http://"));
final String baseUrl4 = (String) determineBaseURLMethod.invoke(
WebdriverSubstepsPropertiesConfiguration.class, "file://some-path/whatever");
Assert.assertThat(baseUrl4, is("file://some-path/whatever"));
}
| public void testRelativeURLResolvesToFileProtocol() throws SecurityException,
NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
InvocationTargetException {
final WebdriverSubstepsPropertiesConfiguration config = WebdriverSubstepsPropertiesConfiguration.INSTANCE;
final Method determineBaseURLMethod = config.getClass().getDeclaredMethod("determineBaseURL", String.class);
determineBaseURLMethod.setAccessible(true);
final String baseUrl = (String) determineBaseURLMethod.invoke(config, "src/web");
Assert.assertThat(baseUrl, startsWith("file:/"));
final String baseUrl2 = (String) determineBaseURLMethod.invoke(config, "./src/web");
final File current = new File(".");
Assert.assertThat(baseUrl2, is(current.toURI().toString() + "src/web"));
final String baseUrl3 = (String) determineBaseURLMethod.invoke(config, "http://blah-blah.com/src/web");
Assert.assertThat(baseUrl3, startsWith("http://"));
final String baseUrl4 = (String) determineBaseURLMethod.invoke(config, "file://some-path/whatever");
Assert.assertThat(baseUrl4, is("file://some-path/whatever"));
}
|
diff --git a/src/de/schildbach/wallet/WalletTransactionsFragment.java b/src/de/schildbach/wallet/WalletTransactionsFragment.java
index dc94340..d2edc47 100644
--- a/src/de/schildbach/wallet/WalletTransactionsFragment.java
+++ b/src/de/schildbach/wallet/WalletTransactionsFragment.java
@@ -1,340 +1,340 @@
/*
* Copyright 2010 the original author or authors.
*
* 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 de.schildbach.wallet;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.google.bitcoin.core.AbstractWalletEventListener;
import com.google.bitcoin.core.Address;
import com.google.bitcoin.core.ScriptException;
import com.google.bitcoin.core.Transaction;
import com.google.bitcoin.core.Utils;
import com.google.bitcoin.core.Wallet;
import com.google.bitcoin.core.WalletEventListener;
import de.schildbach.wallet.util.ViewPagerTabs;
import de.schildbach.wallet_test.R;
/**
* @author Andreas Schildbach
*/
public class WalletTransactionsFragment extends Fragment
{
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState)
{
final View view = inflater.inflate(R.layout.wallet_transactions_fragment, container, false);
final ViewPagerTabs pagerTabs = (ViewPagerTabs) view.findViewById(R.id.transactions_pager_tabs);
pagerTabs.addTabLabels(R.string.wallet_transactions_fragment_tab_received, R.string.wallet_transactions_fragment_tab_all,
R.string.wallet_transactions_fragment_tab_sent);
final PagerAdapter pagerAdapter = new PagerAdapter(getFragmentManager());
final ViewPager pager = (ViewPager) view.findViewById(R.id.transactions_pager);
pager.setAdapter(pagerAdapter);
pager.setOnPageChangeListener(pagerTabs);
pager.setCurrentItem(1);
pagerTabs.onPageScrolled(1, 0, 0); // should not be needed
return view;
}
private static class PagerAdapter extends FragmentStatePagerAdapter
{
public PagerAdapter(final FragmentManager fm)
{
super(fm);
}
@Override
public int getCount()
{
return 3;
}
@Override
public Fragment getItem(final int position)
{
return ListFragment.instance(position);
}
}
public static class ListFragment extends android.support.v4.app.ListFragment
{
private Application application;
private ArrayAdapter<Transaction> transactionsListAdapter;
private int mode;
private final Handler handler = new Handler();
private final static String KEY_MODE = "mode";
public static ListFragment instance(final int mode)
{
final ListFragment fragment = new ListFragment();
final Bundle args = new Bundle();
args.putInt(KEY_MODE, mode);
fragment.setArguments(args);
return fragment;
}
private final WalletEventListener walletEventListener = new AbstractWalletEventListener()
{
@Override
public void onChange()
{
getActivity().runOnUiThread(new Runnable()
{
public void run()
{
updateView();
}
});
}
};
private final ContentObserver contentObserver = new ContentObserver(handler)
{
@Override
public void onChange(final boolean selfChange)
{
transactionsListAdapter.notifyDataSetChanged();
}
};
private final OnItemClickListener itemClickListener = new OnItemClickListener()
{
public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id)
{
final Transaction tx = transactionsListAdapter.getItem(position);
System.out.println("clicked on tx " + tx);
final boolean sent = tx.sent(application.getWallet());
try
{
final Address address = sent ? tx.getOutputs().get(0).getScriptPubKey().getToAddress() : tx.getInputs().get(0).getFromAddress();
final FragmentTransaction ft = getFragmentManager().beginTransaction();
final Fragment prev = getFragmentManager().findFragmentByTag(EditAddressBookEntryFragment.FRAGMENT_TAG);
if (prev != null)
ft.remove(prev);
ft.addToBackStack(null);
final DialogFragment newFragment = EditAddressBookEntryFragment.instance(address.toString());
newFragment.show(ft, EditAddressBookEntryFragment.FRAGMENT_TAG);
}
catch (final ScriptException x)
{
// ignore click
x.printStackTrace();
}
}
};
@Override
public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.mode = getArguments().getInt(KEY_MODE);
application = (Application) getActivity().getApplication();
final Wallet wallet = application.getWallet();
transactionsListAdapter = new ArrayAdapter<Transaction>(getActivity(), 0)
{
final DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getActivity());
final DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(getActivity());
@Override
public View getView(final int position, View row, final ViewGroup parent)
{
if (row == null)
row = getLayoutInflater(null).inflate(R.layout.transaction_row, null);
final Transaction tx = getItem(position);
final boolean sent = tx.sent(wallet);
final boolean pending = wallet.isPending(tx);
final boolean dead = wallet.isDead(tx);
final int textColor;
if (dead)
textColor = Color.RED;
else if (pending)
textColor = Color.LTGRAY;
else
textColor = Color.BLACK;
String address = null;
String label = null;
try
{
if (sent)
address = tx.getOutputs().get(0).getScriptPubKey().getToAddress().toString();
else
address = tx.getInputs().get(0).getFromAddress().toString();
final Uri uri = AddressBookProvider.CONTENT_URI.buildUpon().appendPath(address).build();
final Cursor cursor = getActivity().managedQuery(uri, null, null, null, null);
- if (cursor.moveToFirst())
+ if (cursor != null && cursor.moveToFirst())
label = cursor.getString(cursor.getColumnIndexOrThrow(AddressBookProvider.KEY_LABEL));
}
catch (final ScriptException x)
{
x.printStackTrace();
}
final TextView rowTime = (TextView) row.findViewById(R.id.transaction_time);
final Date time = tx.getUpdateTime();
rowTime.setText(time != null ? DateUtils.isToday(time.getTime()) ? timeFormat.format(time) : dateFormat.format(time) : null);
rowTime.setTextColor(textColor);
final TextView rowTo = (TextView) row.findViewById(R.id.transaction_to);
rowTo.setVisibility(sent ? View.VISIBLE : View.INVISIBLE);
rowTo.setTextColor(textColor);
final TextView rowFrom = (TextView) row.findViewById(R.id.transaction_from);
rowFrom.setVisibility(sent ? View.INVISIBLE : View.VISIBLE);
rowFrom.setTextColor(textColor);
final TextView rowLabel = (TextView) row.findViewById(R.id.transaction_address);
rowLabel.setTextColor(textColor);
rowLabel.setText(label != null ? label : address);
final TextView rowValue = (TextView) row.findViewById(R.id.transaction_value);
rowValue.setTextColor(textColor);
try
{
rowValue.setText((sent ? "-" : "+") + "\u2009" /* thin space */+ Utils.bitcoinValueToFriendlyString(tx.amount(wallet)));
}
catch (final ScriptException x)
{
throw new RuntimeException(x);
}
return row;
}
};
setListAdapter(transactionsListAdapter);
wallet.addEventListener(walletEventListener);
getActivity().getContentResolver().registerContentObserver(AddressBookProvider.CONTENT_URI, true, contentObserver);
}
@Override
public void onActivityCreated(final Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
setEmptyText(getString(mode == 2 ? R.string.wallet_transactions_fragment_empty_text_sent
: R.string.wallet_transactions_fragment_empty_text_received));
}
@Override
public void onViewCreated(final View view, final Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
getListView().setOnItemClickListener(itemClickListener);
}
@Override
public void onResume()
{
super.onResume();
updateView();
}
@Override
public void onDestroy()
{
getActivity().getContentResolver().unregisterContentObserver(contentObserver);
application.getWallet().removeEventListener(walletEventListener);
super.onDestroy();
}
public void updateView()
{
final Wallet wallet = application.getWallet();
final List<Transaction> transactions = new ArrayList<Transaction>(wallet.getTransactions(true, false));
Collections.sort(transactions, new Comparator<Transaction>()
{
public int compare(final Transaction tx1, final Transaction tx2)
{
final boolean pending1 = wallet.isPending(tx1);
final boolean pending2 = wallet.isPending(tx2);
if (pending1 != pending2)
return pending1 ? -1 : 1;
final long time1 = tx1.getUpdateTime() != null ? tx1.getUpdateTime().getTime() : 0;
final long time2 = tx2.getUpdateTime() != null ? tx2.getUpdateTime().getTime() : 0;
if (time1 != time2)
return time1 > time2 ? -1 : 1;
return 0;
}
});
transactionsListAdapter.clear();
for (final Transaction tx : transactions)
{
final boolean sent = tx.sent(wallet);
if ((mode == 0 && !sent) || mode == 1 || (mode == 2 && sent))
transactionsListAdapter.add(tx);
}
}
}
}
| true | true | public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.mode = getArguments().getInt(KEY_MODE);
application = (Application) getActivity().getApplication();
final Wallet wallet = application.getWallet();
transactionsListAdapter = new ArrayAdapter<Transaction>(getActivity(), 0)
{
final DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getActivity());
final DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(getActivity());
@Override
public View getView(final int position, View row, final ViewGroup parent)
{
if (row == null)
row = getLayoutInflater(null).inflate(R.layout.transaction_row, null);
final Transaction tx = getItem(position);
final boolean sent = tx.sent(wallet);
final boolean pending = wallet.isPending(tx);
final boolean dead = wallet.isDead(tx);
final int textColor;
if (dead)
textColor = Color.RED;
else if (pending)
textColor = Color.LTGRAY;
else
textColor = Color.BLACK;
String address = null;
String label = null;
try
{
if (sent)
address = tx.getOutputs().get(0).getScriptPubKey().getToAddress().toString();
else
address = tx.getInputs().get(0).getFromAddress().toString();
final Uri uri = AddressBookProvider.CONTENT_URI.buildUpon().appendPath(address).build();
final Cursor cursor = getActivity().managedQuery(uri, null, null, null, null);
if (cursor.moveToFirst())
label = cursor.getString(cursor.getColumnIndexOrThrow(AddressBookProvider.KEY_LABEL));
}
catch (final ScriptException x)
{
x.printStackTrace();
}
final TextView rowTime = (TextView) row.findViewById(R.id.transaction_time);
final Date time = tx.getUpdateTime();
rowTime.setText(time != null ? DateUtils.isToday(time.getTime()) ? timeFormat.format(time) : dateFormat.format(time) : null);
rowTime.setTextColor(textColor);
final TextView rowTo = (TextView) row.findViewById(R.id.transaction_to);
rowTo.setVisibility(sent ? View.VISIBLE : View.INVISIBLE);
rowTo.setTextColor(textColor);
final TextView rowFrom = (TextView) row.findViewById(R.id.transaction_from);
rowFrom.setVisibility(sent ? View.INVISIBLE : View.VISIBLE);
rowFrom.setTextColor(textColor);
final TextView rowLabel = (TextView) row.findViewById(R.id.transaction_address);
rowLabel.setTextColor(textColor);
rowLabel.setText(label != null ? label : address);
final TextView rowValue = (TextView) row.findViewById(R.id.transaction_value);
rowValue.setTextColor(textColor);
try
{
rowValue.setText((sent ? "-" : "+") + "\u2009" /* thin space */+ Utils.bitcoinValueToFriendlyString(tx.amount(wallet)));
}
catch (final ScriptException x)
{
throw new RuntimeException(x);
}
return row;
}
};
setListAdapter(transactionsListAdapter);
wallet.addEventListener(walletEventListener);
getActivity().getContentResolver().registerContentObserver(AddressBookProvider.CONTENT_URI, true, contentObserver);
}
| public void onCreate(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.mode = getArguments().getInt(KEY_MODE);
application = (Application) getActivity().getApplication();
final Wallet wallet = application.getWallet();
transactionsListAdapter = new ArrayAdapter<Transaction>(getActivity(), 0)
{
final DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getActivity());
final DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(getActivity());
@Override
public View getView(final int position, View row, final ViewGroup parent)
{
if (row == null)
row = getLayoutInflater(null).inflate(R.layout.transaction_row, null);
final Transaction tx = getItem(position);
final boolean sent = tx.sent(wallet);
final boolean pending = wallet.isPending(tx);
final boolean dead = wallet.isDead(tx);
final int textColor;
if (dead)
textColor = Color.RED;
else if (pending)
textColor = Color.LTGRAY;
else
textColor = Color.BLACK;
String address = null;
String label = null;
try
{
if (sent)
address = tx.getOutputs().get(0).getScriptPubKey().getToAddress().toString();
else
address = tx.getInputs().get(0).getFromAddress().toString();
final Uri uri = AddressBookProvider.CONTENT_URI.buildUpon().appendPath(address).build();
final Cursor cursor = getActivity().managedQuery(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst())
label = cursor.getString(cursor.getColumnIndexOrThrow(AddressBookProvider.KEY_LABEL));
}
catch (final ScriptException x)
{
x.printStackTrace();
}
final TextView rowTime = (TextView) row.findViewById(R.id.transaction_time);
final Date time = tx.getUpdateTime();
rowTime.setText(time != null ? DateUtils.isToday(time.getTime()) ? timeFormat.format(time) : dateFormat.format(time) : null);
rowTime.setTextColor(textColor);
final TextView rowTo = (TextView) row.findViewById(R.id.transaction_to);
rowTo.setVisibility(sent ? View.VISIBLE : View.INVISIBLE);
rowTo.setTextColor(textColor);
final TextView rowFrom = (TextView) row.findViewById(R.id.transaction_from);
rowFrom.setVisibility(sent ? View.INVISIBLE : View.VISIBLE);
rowFrom.setTextColor(textColor);
final TextView rowLabel = (TextView) row.findViewById(R.id.transaction_address);
rowLabel.setTextColor(textColor);
rowLabel.setText(label != null ? label : address);
final TextView rowValue = (TextView) row.findViewById(R.id.transaction_value);
rowValue.setTextColor(textColor);
try
{
rowValue.setText((sent ? "-" : "+") + "\u2009" /* thin space */+ Utils.bitcoinValueToFriendlyString(tx.amount(wallet)));
}
catch (final ScriptException x)
{
throw new RuntimeException(x);
}
return row;
}
};
setListAdapter(transactionsListAdapter);
wallet.addEventListener(walletEventListener);
getActivity().getContentResolver().registerContentObserver(AddressBookProvider.CONTENT_URI, true, contentObserver);
}
|
diff --git a/ui/plugins/eu.esdihumboldt.hale.ui.common.editors/src/eu/esdihumboldt/hale/ui/common/editors/DefaultAttributeEditor.java b/ui/plugins/eu.esdihumboldt.hale.ui.common.editors/src/eu/esdihumboldt/hale/ui/common/editors/DefaultAttributeEditor.java
index 9fc92b7b4..e3a2b74a7 100644
--- a/ui/plugins/eu.esdihumboldt.hale.ui.common.editors/src/eu/esdihumboldt/hale/ui/common/editors/DefaultAttributeEditor.java
+++ b/ui/plugins/eu.esdihumboldt.hale.ui.common.editors/src/eu/esdihumboldt/hale/ui/common/editors/DefaultAttributeEditor.java
@@ -1,386 +1,386 @@
/*
* HUMBOLDT: A Framework for Data Harmonisation and Service Integration.
* EU Integrated Project #030962 01.10.2006 - 30.09.2010
*
* For more information on the project, please refer to the this web site:
* http://www.esdi-humboldt.eu
*
* LICENSE: For information on the license under which this program is
* available, please refer to http:/www.esdi-humboldt.eu/license.html#core
* (c) the HUMBOLDT Consortium, 2007 to 2011.
*/
package eu.esdihumboldt.hale.ui.common.editors;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import org.eclipse.jface.fieldassist.ControlDecoration;
import org.eclipse.jface.fieldassist.FieldDecoration;
import org.eclipse.jface.fieldassist.FieldDecorationRegistry;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.PlatformUI;
import org.springframework.core.convert.ConversionException;
import org.springframework.core.convert.ConversionService;
import de.fhg.igd.osgi.util.OsgiUtils;
import eu.esdihumboldt.hale.common.codelist.CodeList;
import eu.esdihumboldt.hale.common.codelist.CodeList.CodeEntry;
import eu.esdihumboldt.hale.common.schema.model.PropertyDefinition;
import eu.esdihumboldt.hale.common.schema.model.TypeDefinition;
import eu.esdihumboldt.hale.common.schema.model.constraint.type.Binding;
import eu.esdihumboldt.hale.common.schema.model.constraint.type.Enumeration;
import eu.esdihumboldt.hale.common.schema.model.constraint.type.ValidationConstraint;
import eu.esdihumboldt.hale.ui.codelist.internal.CodeListUIPlugin;
import eu.esdihumboldt.hale.ui.codelist.selector.CodeListSelectionDialog;
import eu.esdihumboldt.hale.ui.codelist.service.CodeListService;
import eu.esdihumboldt.hale.ui.common.definition.AbstractAttributeEditor;
import eu.esdihumboldt.util.validator.Validator;
/**
* A default attribute editor using binding, enumeration and validation
* constraints.
*
* @author Kai Schwierczek
*/
public class DefaultAttributeEditor extends AbstractAttributeEditor<Object> {
// XXX generic version instead?
private final PropertyDefinition property;
private final Class<?> binding;
private final Collection<String> enumerationValues;
private ArrayList<Object> values;
private final boolean otherValuesAllowed;
private final Validator validator;
private final ConversionService cs = OsgiUtils.getService(ConversionService.class);
private Composite composite;
private ComboViewer viewer;
private ControlDecoration decoration;
private String stringValue;
private Object objectValue;
private boolean validated = false;
private String validationResult;
private CodeList codeList;
private final String codeListNamespace;
private final String codeListName;
/**
* Creates an attribute editor for the given type.
*
* @param parent the parent composite
* @param property the property
*/
public DefaultAttributeEditor(Composite parent, PropertyDefinition property) {
this.property = property;
TypeDefinition type = property.getPropertyType();
binding = type.getConstraint(Binding.class).getBinding();
validator = type.getConstraint(ValidationConstraint.class).getValidator();
Enumeration<?> enumeration = type.getConstraint(Enumeration.class);
otherValuesAllowed = enumeration.isAllowOthers();
codeListNamespace = property.getParentType().getName().getNamespaceURI();
String propertyName = property.getName().getLocalPart();
codeListName = Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1) + "Value"; //$NON-NLS-1$
// add enumeration info
if (enumeration.getValues() != null) {
enumerationValues = new ArrayList<String>(enumeration.getValues().size());
// check values against validator and binding
for (Object o : enumeration.getValues())
if (validator.validate(o) == null) {
try {
String stringValue = cs.convert(o, String.class);
cs.convert(stringValue, binding);
enumerationValues.add(stringValue);
} catch (ConversionException ce) {
// value is either not convertable to string or the string value
// is not convertable to the target binding.
}
}
} else
enumerationValues = null;
composite = new Composite(parent, SWT.NONE);
composite.setLayout(GridLayoutFactory.swtDefaults().margins(0, 0).numColumns(2).create());
viewer = new ComboViewer(composite, (otherValuesAllowed ? SWT.NONE : SWT.READ_ONLY) | SWT.BORDER);
viewer.getControl().setLayoutData(GridDataFactory.fillDefaults().indent(5, 0).grab(true, false).create());
viewer.setContentProvider(ArrayContentProvider.getInstance());
viewer.setLabelProvider(new LabelProvider() {
@Override
public String getText(Object element) {
// XXX show more information out of the CodeEntry?
if (element instanceof CodeEntry)
return ((CodeEntry) element).getName();
else
return super.getText(element);
}
});
viewer.addPostSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if (!selection.isEmpty() && selection instanceof IStructuredSelection) {
Object selected = ((IStructuredSelection) selection).getFirstElement();
if (selected instanceof CodeEntry) {
CodeEntry entry = (CodeEntry) selected;
viewer.getCombo().setToolTipText(entry.getName() + ":\n\n" + entry.getDescription()); //$NON-NLS-1$
return;
}
}
viewer.getCombo().setToolTipText(null);
}
});
viewer.setInput(values);
if (otherValuesAllowed) {
viewer.getCombo().setText("");
stringValue = "";
}
// create decoration
decoration = new ControlDecoration(viewer.getControl(), SWT.LEFT | SWT.TOP, composite);
FieldDecoration fieldDecoration = FieldDecorationRegistry.getDefault().getFieldDecoration(
FieldDecorationRegistry.DEC_ERROR);
decoration.setImage(fieldDecoration.getImage());
decoration.hide();
viewer.getCombo().addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
String oldValue = stringValue;
String newValue = viewer.getCombo().getText();
if (viewer.getSelection() != null && !viewer.getSelection().isEmpty()
&& viewer.getSelection() instanceof IStructuredSelection) {
Object selection = ((IStructuredSelection) viewer.getSelection()).getFirstElement();
if (selection instanceof CodeEntry)
newValue = ((CodeEntry) selection).getIdentifier();
}
valueChanged(oldValue, newValue);
}
});
// set initial selection (triggers modify event -> gets validated
if (values != null && values.size() > 0)
viewer.setSelection(new StructuredSelection(values.iterator().next()));
// add code list selection button
final Image assignImage =
CodeListUIPlugin.getImageDescriptor("icons/assign_codelist.gif").createImage(); //$NON-NLS-1$
Button assign = new Button(composite, SWT.PUSH);
assign.setImage(assignImage);
assign.setToolTipText("Assign a code list"); //$NON-NLS-1$
assign.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
final Display display = Display.getCurrent();
CodeListSelectionDialog dialog = new CodeListSelectionDialog(display.getActiveShell(), codeList,
MessageFormat.format("Please select a code list to assign to {0}",
DefaultAttributeEditor.this.property.getDisplayName()));
if (dialog.open() == CodeListSelectionDialog.OK) {
CodeList newCodeList = dialog.getCodeList();
CodeListService codeListService =
(CodeListService) PlatformUI.getWorkbench().getService(CodeListService.class);
codeListService.assignAttributeCodeList(
DefaultAttributeEditor.this.property.getIdentifier(), newCodeList);
updateCodeList();
}
}
});
composite.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
assignImage.dispose();
}
});
// add code list info
updateCodeList();
// info on what inputs are valid
StringBuilder infoText = new StringBuilder();
// every string is convertible to string -> leave that out
if (!binding.equals(String.class))
infoText.append("Input must be convertable to ").append(binding).append('.');
// every input is valid -> leave that out
if (!validator.isAlwaysTrue()) {
if (infoText.length() > 0)
infoText.append('\n');
infoText.append(validator.getDescription());
}
if (infoText.length() > 0) {
Label inputInfo = new Label(composite, SWT.NONE);
- inputInfo.setLayoutData(GridDataFactory.fillDefaults().span(2, 1));
+ inputInfo.setLayoutData(GridDataFactory.fillDefaults().span(2, 1).create());
inputInfo.setText(infoText.toString());
}
}
private void updateCodeList() {
// TODO how to handle enumeration + code list?
values = new ArrayList<Object>();
if (enumerationValues != null)
values.addAll(enumerationValues);
CodeListService clService = (CodeListService) PlatformUI.getWorkbench().getService(CodeListService.class);
codeList = clService.findCodeListByAttribute(property.getIdentifier());
if (codeList == null)
codeList = clService.findCodeListByIdentifier(codeListNamespace, codeListName);
if (codeList != null) {
// XXX check values against validator and binding?
if (values.isEmpty())
values.addAll(codeList.getEntries());
}
values.trimToSize();
viewer.setInput(values);
}
/**
* Updates the local value, valid status and fires necessary events.
*
* @param oldValue the old value
* @param newValue the new value
*/
private void valueChanged(String oldValue, String newValue) {
// get old valid status
boolean wasValid = isValid();
// set new value
stringValue = newValue;
// validate it
validate();
// check whether valid status changed
boolean validChanged = false;
if (wasValid != isValid())
validChanged = true;
// fire events
fireValueChanged(VALUE, oldValue, newValue);
if (validChanged)
fireStateChanged(IS_VALID, wasValid, !wasValid);
}
/**
* Validates the current string value and sets validationResult.<br>
* Also sets object result if possible and updates the ControlDecoration.
*/
private void validate() {
validationResult = null;
validated = true;
// check binding first
try {
// for example boolean converter returns null for empty string...
objectValue = cs.convert(stringValue, binding);
if (objectValue == null)
validationResult = stringValue + " cannot be converted to " + binding.getSimpleName();
} catch (ConversionException ce) {
objectValue = null;
validationResult = stringValue + " cannot be converted to " + binding.getSimpleName();
}
// validators
if (validationResult == null)
validationResult = validator.validate(objectValue);
// show or hide decoration
if (validationResult != null) {
decoration.setDescriptionText(validationResult);
decoration.show();
} else
decoration.hide();
}
/**
* @see eu.esdihumboldt.hale.ui.common.definition.AttributeEditor#getControl()
*/
@Override
public Control getControl() {
return composite;
}
/**
* @see eu.esdihumboldt.hale.ui.common.definition.AttributeEditor#setValue(java.lang.Object)
*/
@Override
public void setValue(Object value) {
setAsText(cs.convert(value, String.class));
}
/**
* @see eu.esdihumboldt.hale.ui.common.definition.AttributeEditor#getValue()
*
* @throws IllegalStateException if the current input is not valid
*/
@Override
public Object getValue() {
if (isValid())
return objectValue;
else
throw new IllegalStateException();
}
/**
* @see eu.esdihumboldt.hale.ui.common.definition.AttributeEditor#setAsText(java.lang.String)
*/
@Override
public void setAsText(String text) {
// Simply set as string IF other values are allowed. Check against enumeration otherwise.
if (otherValuesAllowed || values.contains(text))
viewer.getCombo().setText(text);
}
/**
* @see eu.esdihumboldt.hale.ui.common.definition.AttributeEditor#getAsText()
*
* @throws IllegalStateException if the current input is not valid
*/
@Override
public String getAsText() {
if (isValid()) {
// return converted value, as that SHOULD be XML conform
// in contrast to input value where the converter maybe allows more.
return cs.convert(objectValue, String.class);
} else
throw new IllegalStateException();
}
/**
* @see eu.esdihumboldt.hale.ui.common.definition.AttributeEditor#isValid()
*/
@Override
public boolean isValid() {
if (!validated)
validate();
return validationResult == null;
}
}
| true | true | public DefaultAttributeEditor(Composite parent, PropertyDefinition property) {
this.property = property;
TypeDefinition type = property.getPropertyType();
binding = type.getConstraint(Binding.class).getBinding();
validator = type.getConstraint(ValidationConstraint.class).getValidator();
Enumeration<?> enumeration = type.getConstraint(Enumeration.class);
otherValuesAllowed = enumeration.isAllowOthers();
codeListNamespace = property.getParentType().getName().getNamespaceURI();
String propertyName = property.getName().getLocalPart();
codeListName = Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1) + "Value"; //$NON-NLS-1$
// add enumeration info
if (enumeration.getValues() != null) {
enumerationValues = new ArrayList<String>(enumeration.getValues().size());
// check values against validator and binding
for (Object o : enumeration.getValues())
if (validator.validate(o) == null) {
try {
String stringValue = cs.convert(o, String.class);
cs.convert(stringValue, binding);
enumerationValues.add(stringValue);
} catch (ConversionException ce) {
// value is either not convertable to string or the string value
// is not convertable to the target binding.
}
}
} else
enumerationValues = null;
composite = new Composite(parent, SWT.NONE);
composite.setLayout(GridLayoutFactory.swtDefaults().margins(0, 0).numColumns(2).create());
viewer = new ComboViewer(composite, (otherValuesAllowed ? SWT.NONE : SWT.READ_ONLY) | SWT.BORDER);
viewer.getControl().setLayoutData(GridDataFactory.fillDefaults().indent(5, 0).grab(true, false).create());
viewer.setContentProvider(ArrayContentProvider.getInstance());
viewer.setLabelProvider(new LabelProvider() {
@Override
public String getText(Object element) {
// XXX show more information out of the CodeEntry?
if (element instanceof CodeEntry)
return ((CodeEntry) element).getName();
else
return super.getText(element);
}
});
viewer.addPostSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if (!selection.isEmpty() && selection instanceof IStructuredSelection) {
Object selected = ((IStructuredSelection) selection).getFirstElement();
if (selected instanceof CodeEntry) {
CodeEntry entry = (CodeEntry) selected;
viewer.getCombo().setToolTipText(entry.getName() + ":\n\n" + entry.getDescription()); //$NON-NLS-1$
return;
}
}
viewer.getCombo().setToolTipText(null);
}
});
viewer.setInput(values);
if (otherValuesAllowed) {
viewer.getCombo().setText("");
stringValue = "";
}
// create decoration
decoration = new ControlDecoration(viewer.getControl(), SWT.LEFT | SWT.TOP, composite);
FieldDecoration fieldDecoration = FieldDecorationRegistry.getDefault().getFieldDecoration(
FieldDecorationRegistry.DEC_ERROR);
decoration.setImage(fieldDecoration.getImage());
decoration.hide();
viewer.getCombo().addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
String oldValue = stringValue;
String newValue = viewer.getCombo().getText();
if (viewer.getSelection() != null && !viewer.getSelection().isEmpty()
&& viewer.getSelection() instanceof IStructuredSelection) {
Object selection = ((IStructuredSelection) viewer.getSelection()).getFirstElement();
if (selection instanceof CodeEntry)
newValue = ((CodeEntry) selection).getIdentifier();
}
valueChanged(oldValue, newValue);
}
});
// set initial selection (triggers modify event -> gets validated
if (values != null && values.size() > 0)
viewer.setSelection(new StructuredSelection(values.iterator().next()));
// add code list selection button
final Image assignImage =
CodeListUIPlugin.getImageDescriptor("icons/assign_codelist.gif").createImage(); //$NON-NLS-1$
Button assign = new Button(composite, SWT.PUSH);
assign.setImage(assignImage);
assign.setToolTipText("Assign a code list"); //$NON-NLS-1$
assign.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
final Display display = Display.getCurrent();
CodeListSelectionDialog dialog = new CodeListSelectionDialog(display.getActiveShell(), codeList,
MessageFormat.format("Please select a code list to assign to {0}",
DefaultAttributeEditor.this.property.getDisplayName()));
if (dialog.open() == CodeListSelectionDialog.OK) {
CodeList newCodeList = dialog.getCodeList();
CodeListService codeListService =
(CodeListService) PlatformUI.getWorkbench().getService(CodeListService.class);
codeListService.assignAttributeCodeList(
DefaultAttributeEditor.this.property.getIdentifier(), newCodeList);
updateCodeList();
}
}
});
composite.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
assignImage.dispose();
}
});
// add code list info
updateCodeList();
// info on what inputs are valid
StringBuilder infoText = new StringBuilder();
// every string is convertible to string -> leave that out
if (!binding.equals(String.class))
infoText.append("Input must be convertable to ").append(binding).append('.');
// every input is valid -> leave that out
if (!validator.isAlwaysTrue()) {
if (infoText.length() > 0)
infoText.append('\n');
infoText.append(validator.getDescription());
}
if (infoText.length() > 0) {
Label inputInfo = new Label(composite, SWT.NONE);
inputInfo.setLayoutData(GridDataFactory.fillDefaults().span(2, 1));
inputInfo.setText(infoText.toString());
}
}
| public DefaultAttributeEditor(Composite parent, PropertyDefinition property) {
this.property = property;
TypeDefinition type = property.getPropertyType();
binding = type.getConstraint(Binding.class).getBinding();
validator = type.getConstraint(ValidationConstraint.class).getValidator();
Enumeration<?> enumeration = type.getConstraint(Enumeration.class);
otherValuesAllowed = enumeration.isAllowOthers();
codeListNamespace = property.getParentType().getName().getNamespaceURI();
String propertyName = property.getName().getLocalPart();
codeListName = Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1) + "Value"; //$NON-NLS-1$
// add enumeration info
if (enumeration.getValues() != null) {
enumerationValues = new ArrayList<String>(enumeration.getValues().size());
// check values against validator and binding
for (Object o : enumeration.getValues())
if (validator.validate(o) == null) {
try {
String stringValue = cs.convert(o, String.class);
cs.convert(stringValue, binding);
enumerationValues.add(stringValue);
} catch (ConversionException ce) {
// value is either not convertable to string or the string value
// is not convertable to the target binding.
}
}
} else
enumerationValues = null;
composite = new Composite(parent, SWT.NONE);
composite.setLayout(GridLayoutFactory.swtDefaults().margins(0, 0).numColumns(2).create());
viewer = new ComboViewer(composite, (otherValuesAllowed ? SWT.NONE : SWT.READ_ONLY) | SWT.BORDER);
viewer.getControl().setLayoutData(GridDataFactory.fillDefaults().indent(5, 0).grab(true, false).create());
viewer.setContentProvider(ArrayContentProvider.getInstance());
viewer.setLabelProvider(new LabelProvider() {
@Override
public String getText(Object element) {
// XXX show more information out of the CodeEntry?
if (element instanceof CodeEntry)
return ((CodeEntry) element).getName();
else
return super.getText(element);
}
});
viewer.addPostSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if (!selection.isEmpty() && selection instanceof IStructuredSelection) {
Object selected = ((IStructuredSelection) selection).getFirstElement();
if (selected instanceof CodeEntry) {
CodeEntry entry = (CodeEntry) selected;
viewer.getCombo().setToolTipText(entry.getName() + ":\n\n" + entry.getDescription()); //$NON-NLS-1$
return;
}
}
viewer.getCombo().setToolTipText(null);
}
});
viewer.setInput(values);
if (otherValuesAllowed) {
viewer.getCombo().setText("");
stringValue = "";
}
// create decoration
decoration = new ControlDecoration(viewer.getControl(), SWT.LEFT | SWT.TOP, composite);
FieldDecoration fieldDecoration = FieldDecorationRegistry.getDefault().getFieldDecoration(
FieldDecorationRegistry.DEC_ERROR);
decoration.setImage(fieldDecoration.getImage());
decoration.hide();
viewer.getCombo().addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
String oldValue = stringValue;
String newValue = viewer.getCombo().getText();
if (viewer.getSelection() != null && !viewer.getSelection().isEmpty()
&& viewer.getSelection() instanceof IStructuredSelection) {
Object selection = ((IStructuredSelection) viewer.getSelection()).getFirstElement();
if (selection instanceof CodeEntry)
newValue = ((CodeEntry) selection).getIdentifier();
}
valueChanged(oldValue, newValue);
}
});
// set initial selection (triggers modify event -> gets validated
if (values != null && values.size() > 0)
viewer.setSelection(new StructuredSelection(values.iterator().next()));
// add code list selection button
final Image assignImage =
CodeListUIPlugin.getImageDescriptor("icons/assign_codelist.gif").createImage(); //$NON-NLS-1$
Button assign = new Button(composite, SWT.PUSH);
assign.setImage(assignImage);
assign.setToolTipText("Assign a code list"); //$NON-NLS-1$
assign.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
final Display display = Display.getCurrent();
CodeListSelectionDialog dialog = new CodeListSelectionDialog(display.getActiveShell(), codeList,
MessageFormat.format("Please select a code list to assign to {0}",
DefaultAttributeEditor.this.property.getDisplayName()));
if (dialog.open() == CodeListSelectionDialog.OK) {
CodeList newCodeList = dialog.getCodeList();
CodeListService codeListService =
(CodeListService) PlatformUI.getWorkbench().getService(CodeListService.class);
codeListService.assignAttributeCodeList(
DefaultAttributeEditor.this.property.getIdentifier(), newCodeList);
updateCodeList();
}
}
});
composite.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
assignImage.dispose();
}
});
// add code list info
updateCodeList();
// info on what inputs are valid
StringBuilder infoText = new StringBuilder();
// every string is convertible to string -> leave that out
if (!binding.equals(String.class))
infoText.append("Input must be convertable to ").append(binding).append('.');
// every input is valid -> leave that out
if (!validator.isAlwaysTrue()) {
if (infoText.length() > 0)
infoText.append('\n');
infoText.append(validator.getDescription());
}
if (infoText.length() > 0) {
Label inputInfo = new Label(composite, SWT.NONE);
inputInfo.setLayoutData(GridDataFactory.fillDefaults().span(2, 1).create());
inputInfo.setText(infoText.toString());
}
}
|
diff --git a/src/freemail/Version.java b/src/freemail/Version.java
index c820464..6ce2221 100644
--- a/src/freemail/Version.java
+++ b/src/freemail/Version.java
@@ -1,47 +1,47 @@
/*
* Version.java
* This file is part of Freemail, copyright (C) 2006 Dave Baker
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
* USA
*
*/
package freemail;
public class Version {
/** The human readable version */
public static final String VERSION = "0.1";
/**
* The build number, used by the plugin auto-updater. This must always
* increase, and at least by one per build that is uploaded to the auto
* update system.
*/
public static final int BUILD_NO = 14;
/** Version number updated at build time using git describe */
public static final String GIT_REVISION = "@custom@";
public static String getVersionString() {
- if(VERSION.equals("v" + GIT_REVISION)) {
+ if(GIT_REVISION.equals("v" + VERSION)) {
//Presumably because this is a proper release,
//so don't include the redundant git info
return VERSION;
} else {
return VERSION + " (" + GIT_REVISION + ")";
}
}
}
| true | true | public static String getVersionString() {
if(VERSION.equals("v" + GIT_REVISION)) {
//Presumably because this is a proper release,
//so don't include the redundant git info
return VERSION;
} else {
return VERSION + " (" + GIT_REVISION + ")";
}
}
| public static String getVersionString() {
if(GIT_REVISION.equals("v" + VERSION)) {
//Presumably because this is a proper release,
//so don't include the redundant git info
return VERSION;
} else {
return VERSION + " (" + GIT_REVISION + ")";
}
}
|
diff --git a/src/test/java/novelang/model/implementation/PartTest.java b/src/test/java/novelang/model/implementation/PartTest.java
index 0923e650..ee044c34 100644
--- a/src/test/java/novelang/model/implementation/PartTest.java
+++ b/src/test/java/novelang/model/implementation/PartTest.java
@@ -1,85 +1,77 @@
/*
* Copyright (C) 2008 Laurent Caillette
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package novelang.model.implementation;
import java.io.File;
import java.io.IOException;
import org.apache.commons.lang.ClassUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import novelang.ScratchDirectoryFixture;
import novelang.TestResourceTools;
import novelang.TestResources;
import static novelang.model.common.NodeKind.*;
import novelang.model.common.Tree;
import novelang.parser.antlr.TreeHelper;
import static novelang.parser.antlr.TreeHelper.tree;
/**
* @author Laurent Caillette
*/
public class PartTest {
@Test
public void loadPartOk() throws IOException {
final Part part = new Part( sections1File ) ;
final Tree partTree = part.getTree();
Assert.assertNotNull( partTree ) ;
final Tree expected = tree( PART,
- tree( SECTION,
- tree( IDENTIFIER, tree( WORD, "Section1nlp" ) ),
- tree( PARAGRAPH_PLAIN, tree( WORD, "p00" ), tree( WORD, "w001" ) )
- ),
- tree( SECTION,
- tree( TITLE, tree( WORD, "section1" ), tree( WORD, "w11" ) ),
- tree( PARAGRAPH_PLAIN,
- tree( WORD, "p10" ),
- tree( WORD, "w101" ),
- tree( WORD, "w102" )
- )
- )
+ tree( SECTION, tree( IDENTIFIER, tree( WORD, "Section1nlp" ) ) ),
+ tree( PARAGRAPH_PLAIN, tree( WORD, "p00" ), tree( WORD, "w001" ) ),
+ tree( SECTION, tree( TITLE, tree( WORD, "section1" ), tree( WORD, "w11" ) ) ),
+ tree( PARAGRAPH_PLAIN, tree( WORD, "p10" ), tree( WORD, "w101" ), tree( WORD, "w102" ) )
) ;
TreeHelper.assertEquals( expected, partTree ) ;
Assert.assertFalse( part.getProblems().iterator().hasNext() ) ;
}
@Test
public void findIdentifiersOk() throws IOException {
final Part part = new Part( sections1File ) ;
part.getIdentifiers() ;
}
private File book1Directory ;
private File sections1File;
@Before
public void setUp() throws IOException {
final String testName = ClassUtils.getShortClassName( getClass() );
final ScratchDirectoryFixture scratchDirectoryFixture =
new ScratchDirectoryFixture( testName ) ;
book1Directory = scratchDirectoryFixture.getBook1Directory() ;
TestResourceTools.copyResourceToFile( getClass(), TestResources.SECTIONS_1, book1Directory ) ;
sections1File = new File( book1Directory, TestResources.SECTIONS_1 ) ;
}
}
| true | true | public void loadPartOk() throws IOException {
final Part part = new Part( sections1File ) ;
final Tree partTree = part.getTree();
Assert.assertNotNull( partTree ) ;
final Tree expected = tree( PART,
tree( SECTION,
tree( IDENTIFIER, tree( WORD, "Section1nlp" ) ),
tree( PARAGRAPH_PLAIN, tree( WORD, "p00" ), tree( WORD, "w001" ) )
),
tree( SECTION,
tree( TITLE, tree( WORD, "section1" ), tree( WORD, "w11" ) ),
tree( PARAGRAPH_PLAIN,
tree( WORD, "p10" ),
tree( WORD, "w101" ),
tree( WORD, "w102" )
)
)
) ;
TreeHelper.assertEquals( expected, partTree ) ;
Assert.assertFalse( part.getProblems().iterator().hasNext() ) ;
}
| public void loadPartOk() throws IOException {
final Part part = new Part( sections1File ) ;
final Tree partTree = part.getTree();
Assert.assertNotNull( partTree ) ;
final Tree expected = tree( PART,
tree( SECTION, tree( IDENTIFIER, tree( WORD, "Section1nlp" ) ) ),
tree( PARAGRAPH_PLAIN, tree( WORD, "p00" ), tree( WORD, "w001" ) ),
tree( SECTION, tree( TITLE, tree( WORD, "section1" ), tree( WORD, "w11" ) ) ),
tree( PARAGRAPH_PLAIN, tree( WORD, "p10" ), tree( WORD, "w101" ), tree( WORD, "w102" ) )
) ;
TreeHelper.assertEquals( expected, partTree ) ;
Assert.assertFalse( part.getProblems().iterator().hasNext() ) ;
}
|
diff --git a/src/main/java/tconstruct/tools/model/BattlesignTesr.java b/src/main/java/tconstruct/tools/model/BattlesignTesr.java
index 2bca9ddf4..a3077ba87 100644
--- a/src/main/java/tconstruct/tools/model/BattlesignTesr.java
+++ b/src/main/java/tconstruct/tools/model/BattlesignTesr.java
@@ -1,75 +1,75 @@
package tconstruct.tools.model;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumChatFormatting;
import org.lwjgl.opengl.GL11;
import tconstruct.tools.logic.BattlesignLogic;
public class BattlesignTesr extends TileEntitySpecialRenderer
{
public void renderTileEntityAt (BattlesignLogic te, double x, double y, double z, float something)
{
GL11.glPushMatrix();
GL11.glDisable(GL11.GL_LIGHTING);
float f = 0.016666668F * 0.6666667F;
GL11.glTranslated(x, y, z);
GL11.glScalef(f, -f, f);
- // GL11.glRotatef(180F, 0F, 0F, 1F);
FontRenderer fr = Minecraft.getMinecraft().fontRenderer;
switch (te.getWorldObj().getBlockMetadata(te.xCoord, te.yCoord, te.zCoord))
{
case 0:
GL11.glRotatef(-90F, 0F, 1F, 0F);
GL11.glTranslatef(5F, -96F, -37F);
break;
case 1:
GL11.glRotatef(90F, 0F, 1F, 0F);
GL11.glTranslatef(-85F, -96F, 53F);
break;
case 2:
GL11.glTranslatef(5F, -96F, 53F);
break;
case 3:
GL11.glRotatef(180F, 0F, 1F, 0F);
GL11.glTranslatef(-85F, -96F, -37F);
break;
}
String strings[] = te.getText();
if (strings != null && strings.length > 0)
{
float lum = calcLuminance(te.getWorldObj().getBlock(te.xCoord, te.yCoord, te.zCoord).colorMultiplier(te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord));
for (int i = 0; i < strings.length; i++)
{
fr.drawString((lum >= 35F ? EnumChatFormatting.BLACK : lum >= 31F ? EnumChatFormatting.GRAY : EnumChatFormatting.WHITE) + strings[i], -fr.getStringWidth(strings[i]) / 2 + 40, 10 * i, 0);
}
}
+ GL11.glEnable(GL11.GL_LIGHTING);
GL11.glPopMatrix();
}
private float calcLuminance (int rgb)
{
int r = (rgb & 0xff0000) >> 16;
int g = (rgb & 0xff00) >> 8;
int b = (rgb & 0xff);
return (r * 0.299f + g * 0.587f + b * 0.114f) / 3;
}
@Override
public void renderTileEntityAt (TileEntity te, double x, double y, double z, float something)
{
this.renderTileEntityAt((BattlesignLogic) te, x, y, z, something);
}
}
| false | true | public void renderTileEntityAt (BattlesignLogic te, double x, double y, double z, float something)
{
GL11.glPushMatrix();
GL11.glDisable(GL11.GL_LIGHTING);
float f = 0.016666668F * 0.6666667F;
GL11.glTranslated(x, y, z);
GL11.glScalef(f, -f, f);
// GL11.glRotatef(180F, 0F, 0F, 1F);
FontRenderer fr = Minecraft.getMinecraft().fontRenderer;
switch (te.getWorldObj().getBlockMetadata(te.xCoord, te.yCoord, te.zCoord))
{
case 0:
GL11.glRotatef(-90F, 0F, 1F, 0F);
GL11.glTranslatef(5F, -96F, -37F);
break;
case 1:
GL11.glRotatef(90F, 0F, 1F, 0F);
GL11.glTranslatef(-85F, -96F, 53F);
break;
case 2:
GL11.glTranslatef(5F, -96F, 53F);
break;
case 3:
GL11.glRotatef(180F, 0F, 1F, 0F);
GL11.glTranslatef(-85F, -96F, -37F);
break;
}
String strings[] = te.getText();
if (strings != null && strings.length > 0)
{
float lum = calcLuminance(te.getWorldObj().getBlock(te.xCoord, te.yCoord, te.zCoord).colorMultiplier(te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord));
for (int i = 0; i < strings.length; i++)
{
fr.drawString((lum >= 35F ? EnumChatFormatting.BLACK : lum >= 31F ? EnumChatFormatting.GRAY : EnumChatFormatting.WHITE) + strings[i], -fr.getStringWidth(strings[i]) / 2 + 40, 10 * i, 0);
}
}
GL11.glPopMatrix();
}
| public void renderTileEntityAt (BattlesignLogic te, double x, double y, double z, float something)
{
GL11.glPushMatrix();
GL11.glDisable(GL11.GL_LIGHTING);
float f = 0.016666668F * 0.6666667F;
GL11.glTranslated(x, y, z);
GL11.glScalef(f, -f, f);
FontRenderer fr = Minecraft.getMinecraft().fontRenderer;
switch (te.getWorldObj().getBlockMetadata(te.xCoord, te.yCoord, te.zCoord))
{
case 0:
GL11.glRotatef(-90F, 0F, 1F, 0F);
GL11.glTranslatef(5F, -96F, -37F);
break;
case 1:
GL11.glRotatef(90F, 0F, 1F, 0F);
GL11.glTranslatef(-85F, -96F, 53F);
break;
case 2:
GL11.glTranslatef(5F, -96F, 53F);
break;
case 3:
GL11.glRotatef(180F, 0F, 1F, 0F);
GL11.glTranslatef(-85F, -96F, -37F);
break;
}
String strings[] = te.getText();
if (strings != null && strings.length > 0)
{
float lum = calcLuminance(te.getWorldObj().getBlock(te.xCoord, te.yCoord, te.zCoord).colorMultiplier(te.getWorldObj(), te.xCoord, te.yCoord, te.zCoord));
for (int i = 0; i < strings.length; i++)
{
fr.drawString((lum >= 35F ? EnumChatFormatting.BLACK : lum >= 31F ? EnumChatFormatting.GRAY : EnumChatFormatting.WHITE) + strings[i], -fr.getStringWidth(strings[i]) / 2 + 40, 10 * i, 0);
}
}
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glPopMatrix();
}
|
diff --git a/src/com/android/volley/toolbox/BasicNetwork.java b/src/com/android/volley/toolbox/BasicNetwork.java
index be77a0d..282fd14 100644
--- a/src/com/android/volley/toolbox/BasicNetwork.java
+++ b/src/com/android/volley/toolbox/BasicNetwork.java
@@ -1,233 +1,231 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modified by Vinay S Shenoy on 19/5/13
*/
package com.android.volley.toolbox;
import android.os.SystemClock;
import com.android.volley.*;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.cookie.DateUtils;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* A network performing Volley requests over an {@link HttpStack}.
*/
public class BasicNetwork implements Network {
protected static final boolean DEBUG = VolleyLog.DEBUG;
private static int SLOW_REQUEST_THRESHOLD_MS = 3000;
private static int DEFAULT_POOL_SIZE = 4096;
protected final HttpStack mHttpStack;
protected final ByteArrayPool mPool;
/**
* @param httpStack HTTP stack to be used
*/
public BasicNetwork(HttpStack httpStack) {
// If a pool isn't passed in, then build a small default pool that will give us a lot of
// benefit and not use too much memory.
this(httpStack, new ByteArrayPool(DEFAULT_POOL_SIZE));
}
/**
* @param httpStack HTTP stack to be used
* @param pool a buffer pool that improves GC performance in copy operations
*/
public BasicNetwork(HttpStack httpStack, ByteArrayPool pool) {
mHttpStack = httpStack;
mPool = pool;
}
@Override
public NetworkResponse performRequest(Request<?> request) throws VolleyError {
long requestStart = SystemClock.elapsedRealtime();
while (true) {
HttpResponse httpResponse = null;
byte[] responseContents = null;
Map<String, String> responseHeaders = new HashMap<String, String>();
try {
// Gather headers.
Map<String, String> headers = new HashMap<String, String>();
addCacheHeaders(headers, request.getCacheEntry());
httpResponse = mHttpStack.performRequest(request, headers);
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
responseHeaders = convertHeaders(httpResponse.getAllHeaders());
// Handle cache validation.
if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED,
request.getCacheEntry().data, responseHeaders, true);
}
responseContents = entityToBytes(httpResponse.getEntity());
// if the request is slow, log it.
long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
logSlowRequests(requestLifetime, request, responseContents, statusLine);
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_NO_CONTENT) {
throw new IOException();
}
return new NetworkResponse(statusCode, responseContents, responseHeaders, false);
} catch (SocketTimeoutException e) {
attemptRetryOnException("socket", request, new TimeoutError());
} catch (ConnectTimeoutException e) {
attemptRetryOnException("connection", request, new TimeoutError());
} catch (MalformedURLException e) {
throw new RuntimeException("Bad URL " + request.getUrl(), e);
} catch (IOException e) {
int statusCode = 0;
NetworkResponse networkResponse = null;
if (httpResponse != null) {
statusCode = httpResponse.getStatusLine().getStatusCode();
} else {
throw new NoConnectionError(e);
}
VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
if (responseContents != null) {
networkResponse = new NetworkResponse(statusCode, responseContents,
responseHeaders, false);
if (statusCode == HttpStatus.SC_UNAUTHORIZED ||
statusCode == HttpStatus.SC_FORBIDDEN) {
attemptRetryOnException("auth",
request, new AuthFailureError(networkResponse));
- } else if(statusCode == HttpStatus.SC_BAD_REQUEST) {
- throw new BadRequestError(networkResponse);
} else {
// TODO: Only throw ServerError for 5xx status codes.
throw new ServerError(networkResponse);
}
} else {
throw new NetworkError(networkResponse);
}
}
}
}
/**
* Logs requests that took over SLOW_REQUEST_THRESHOLD_MS to complete.
*/
private void logSlowRequests(long requestLifetime, Request<?> request,
byte[] responseContents, StatusLine statusLine) {
if (DEBUG || requestLifetime > SLOW_REQUEST_THRESHOLD_MS) {
VolleyLog.d("HTTP response for request=<%s> [lifetime=%d], [size=%s], " +
"[rc=%d], [retryCount=%s]", request, requestLifetime,
responseContents != null ? responseContents.length : "null",
statusLine.getStatusCode(), request.getRetryPolicy().getCurrentRetryCount());
}
}
/**
* Attempts to prepare the request for a retry. If there are no more attempts remaining in the
* request's retry policy, a timeout exception is thrown.
* @param request The request to use.
*/
private static void attemptRetryOnException(String logPrefix, Request<?> request,
VolleyError exception) throws VolleyError {
RetryPolicy retryPolicy = request.getRetryPolicy();
int oldTimeout = request.getTimeoutMs();
try {
retryPolicy.retry(exception);
} catch (VolleyError e) {
request.addMarker(
String.format("%s-timeout-giveup [timeout=%s]", logPrefix, oldTimeout));
throw e;
}
request.addMarker(String.format("%s-retry [timeout=%s]", logPrefix, oldTimeout));
}
private void addCacheHeaders(Map<String, String> headers, Cache.Entry entry) {
// If there's no cache entry, we're done.
if (entry == null) {
return;
}
if (entry.etag != null) {
headers.put("If-None-Match", entry.etag);
}
if (entry.serverDate > 0) {
Date refTime = new Date(entry.serverDate);
headers.put("If-Modified-Since", DateUtils.formatDate(refTime));
}
}
protected void logError(String what, String url, long start) {
long now = SystemClock.elapsedRealtime();
VolleyLog.v("HTTP ERROR(%s) %d ms to fetch %s", what, (now - start), url);
}
/** Reads the contents of HttpEntity into a byte[]. */
private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
PoolingByteArrayOutputStream bytes =
new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
byte[] buffer = null;
try {
InputStream in = entity.getContent();
if (in == null) {
throw new ServerError();
}
buffer = mPool.getBuf(1024);
int count;
while ((count = in.read(buffer)) != -1) {
bytes.write(buffer, 0, count);
}
return bytes.toByteArray();
} finally {
try {
// Close the InputStream and release the resources by "consuming the content".
entity.consumeContent();
} catch (IOException e) {
// This can happen if there was an exception above that left the entity in
// an invalid state.
VolleyLog.v("Error occured when calling consumingContent");
}
mPool.returnBuf(buffer);
bytes.close();
}
}
/**
* Converts Headers[] to Map<String, String>.
*/
private static Map<String, String> convertHeaders(Header[] headers) {
Map<String, String> result = new HashMap<String, String>();
for (int i = 0; i < headers.length; i++) {
result.put(headers[i].getName(), headers[i].getValue());
}
return result;
}
}
| true | true | public NetworkResponse performRequest(Request<?> request) throws VolleyError {
long requestStart = SystemClock.elapsedRealtime();
while (true) {
HttpResponse httpResponse = null;
byte[] responseContents = null;
Map<String, String> responseHeaders = new HashMap<String, String>();
try {
// Gather headers.
Map<String, String> headers = new HashMap<String, String>();
addCacheHeaders(headers, request.getCacheEntry());
httpResponse = mHttpStack.performRequest(request, headers);
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
responseHeaders = convertHeaders(httpResponse.getAllHeaders());
// Handle cache validation.
if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED,
request.getCacheEntry().data, responseHeaders, true);
}
responseContents = entityToBytes(httpResponse.getEntity());
// if the request is slow, log it.
long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
logSlowRequests(requestLifetime, request, responseContents, statusLine);
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_NO_CONTENT) {
throw new IOException();
}
return new NetworkResponse(statusCode, responseContents, responseHeaders, false);
} catch (SocketTimeoutException e) {
attemptRetryOnException("socket", request, new TimeoutError());
} catch (ConnectTimeoutException e) {
attemptRetryOnException("connection", request, new TimeoutError());
} catch (MalformedURLException e) {
throw new RuntimeException("Bad URL " + request.getUrl(), e);
} catch (IOException e) {
int statusCode = 0;
NetworkResponse networkResponse = null;
if (httpResponse != null) {
statusCode = httpResponse.getStatusLine().getStatusCode();
} else {
throw new NoConnectionError(e);
}
VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
if (responseContents != null) {
networkResponse = new NetworkResponse(statusCode, responseContents,
responseHeaders, false);
if (statusCode == HttpStatus.SC_UNAUTHORIZED ||
statusCode == HttpStatus.SC_FORBIDDEN) {
attemptRetryOnException("auth",
request, new AuthFailureError(networkResponse));
} else if(statusCode == HttpStatus.SC_BAD_REQUEST) {
throw new BadRequestError(networkResponse);
} else {
// TODO: Only throw ServerError for 5xx status codes.
throw new ServerError(networkResponse);
}
} else {
throw new NetworkError(networkResponse);
}
}
}
}
| public NetworkResponse performRequest(Request<?> request) throws VolleyError {
long requestStart = SystemClock.elapsedRealtime();
while (true) {
HttpResponse httpResponse = null;
byte[] responseContents = null;
Map<String, String> responseHeaders = new HashMap<String, String>();
try {
// Gather headers.
Map<String, String> headers = new HashMap<String, String>();
addCacheHeaders(headers, request.getCacheEntry());
httpResponse = mHttpStack.performRequest(request, headers);
StatusLine statusLine = httpResponse.getStatusLine();
int statusCode = statusLine.getStatusCode();
responseHeaders = convertHeaders(httpResponse.getAllHeaders());
// Handle cache validation.
if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
return new NetworkResponse(HttpStatus.SC_NOT_MODIFIED,
request.getCacheEntry().data, responseHeaders, true);
}
responseContents = entityToBytes(httpResponse.getEntity());
// if the request is slow, log it.
long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
logSlowRequests(requestLifetime, request, responseContents, statusLine);
if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_NO_CONTENT) {
throw new IOException();
}
return new NetworkResponse(statusCode, responseContents, responseHeaders, false);
} catch (SocketTimeoutException e) {
attemptRetryOnException("socket", request, new TimeoutError());
} catch (ConnectTimeoutException e) {
attemptRetryOnException("connection", request, new TimeoutError());
} catch (MalformedURLException e) {
throw new RuntimeException("Bad URL " + request.getUrl(), e);
} catch (IOException e) {
int statusCode = 0;
NetworkResponse networkResponse = null;
if (httpResponse != null) {
statusCode = httpResponse.getStatusLine().getStatusCode();
} else {
throw new NoConnectionError(e);
}
VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
if (responseContents != null) {
networkResponse = new NetworkResponse(statusCode, responseContents,
responseHeaders, false);
if (statusCode == HttpStatus.SC_UNAUTHORIZED ||
statusCode == HttpStatus.SC_FORBIDDEN) {
attemptRetryOnException("auth",
request, new AuthFailureError(networkResponse));
} else {
// TODO: Only throw ServerError for 5xx status codes.
throw new ServerError(networkResponse);
}
} else {
throw new NetworkError(networkResponse);
}
}
}
}
|
diff --git a/src/main/java/org/apache/ibatis/builder/SqlSourceBuilder.java b/src/main/java/org/apache/ibatis/builder/SqlSourceBuilder.java
index b8c5fa8285..82baaf912c 100644
--- a/src/main/java/org/apache/ibatis/builder/SqlSourceBuilder.java
+++ b/src/main/java/org/apache/ibatis/builder/SqlSourceBuilder.java
@@ -1,134 +1,134 @@
/*
* 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.builder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.parsing.GenericTokenParser;
import org.apache.ibatis.parsing.TokenHandler;
import org.apache.ibatis.reflection.MetaClass;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
public class SqlSourceBuilder extends BaseBuilder {
private static final String parameterProperties = "javaType,jdbcType,mode,numericScale,resultMap,typeHandler,jdbcTypeName";
public SqlSourceBuilder(Configuration configuration) {
super(configuration);
}
public SqlSource parse(String originalSql, Class<?> parameterType, Map<String, Object> additionalParameters) {
ParameterMappingTokenHandler handler = new ParameterMappingTokenHandler(configuration, parameterType, additionalParameters);
GenericTokenParser parser = new GenericTokenParser("#{", "}", handler);
String sql = parser.parse(originalSql);
return new StaticSqlSource(configuration, sql, handler.getParameterMappings());
}
private static class ParameterMappingTokenHandler extends BaseBuilder implements TokenHandler {
private List<ParameterMapping> parameterMappings = new ArrayList<ParameterMapping>();
private Class<?> parameterType;
private MetaObject metaParameters;
public ParameterMappingTokenHandler(Configuration configuration, Class<?> parameterType, Map<String, Object> additionalParameters) {
super(configuration);
this.parameterType = parameterType;
this.metaParameters = configuration.newMetaObject(additionalParameters);
}
public List<ParameterMapping> getParameterMappings() {
return parameterMappings;
}
public String handleToken(String content) {
parameterMappings.add(buildParameterMapping(content));
return "?";
}
private ParameterMapping buildParameterMapping(String content) {
Map<String, String> propertiesMap = parseParameterMapping(content);
String property = propertiesMap.get("property");
Class<?> propertyType;
if (metaParameters.hasGetter(property)) { // issue #448 get type from additional params
propertyType = metaParameters.getGetterType(property);
} else if (typeHandlerRegistry.hasTypeHandler(parameterType)) {
propertyType = parameterType;
} else if (JdbcType.CURSOR.name().equals(propertiesMap.get("jdbcType"))) {
propertyType = java.sql.ResultSet.class;
} else if (property != null) {
MetaClass metaClass = MetaClass.forClass(parameterType);
if (metaClass.hasGetter(property)) {
propertyType = metaClass.getGetterType(property);
} else {
propertyType = Object.class;
}
} else {
propertyType = Object.class;
}
ParameterMapping.Builder builder = new ParameterMapping.Builder(configuration, property, propertyType);
- Class<?> javaType = null;
+ Class<?> javaType = propertyType;
String typeHandlerAlias = null;
for (Map.Entry<String, String> entry : propertiesMap.entrySet()) {
String name = entry.getKey();
String value = entry.getValue();
if ("javaType".equals(name)) {
javaType = resolveClass(value);
builder.javaType(javaType);
} else if ("jdbcType".equals(name)) {
builder.jdbcType(resolveJdbcType(value));
} else if ("mode".equals(name)) {
builder.mode(resolveParameterMode(value));
} else if ("numericScale".equals(name)) {
builder.numericScale(Integer.valueOf(value));
} else if ("resultMap".equals(name)) {
builder.resultMapId(value);
} else if ("typeHandler".equals(name)) {
typeHandlerAlias = value;
} else if ("jdbcTypeName".equals(name)) {
builder.jdbcTypeName(value);
} else if ("property".equals(name)) {
// Do Nothing
} else if ("expression".equals(name)) {
throw new BuilderException("Expression based parameters are not supported yet");
} else {
throw new BuilderException("An invalid property '" + name + "' was found in mapping #{" + content + "}. Valid properties are " + parameterProperties);
}
}
if (typeHandlerAlias != null) {
builder.typeHandler((TypeHandler<?>) resolveTypeHandler(javaType, typeHandlerAlias));
}
return builder.build();
}
private Map<String, String> parseParameterMapping(String content) {
try {
return ParameterExpressionParser.parse(content);
} catch (BuilderException ex) {
throw ex;
} catch (Exception ex) {
throw new BuilderException("Parsing error was found in mapping #{" + content + "}. Check syntax #{property|(expression), var1=value1, var2=value2, ...} ", ex);
}
}
}
}
| true | true | private ParameterMapping buildParameterMapping(String content) {
Map<String, String> propertiesMap = parseParameterMapping(content);
String property = propertiesMap.get("property");
Class<?> propertyType;
if (metaParameters.hasGetter(property)) { // issue #448 get type from additional params
propertyType = metaParameters.getGetterType(property);
} else if (typeHandlerRegistry.hasTypeHandler(parameterType)) {
propertyType = parameterType;
} else if (JdbcType.CURSOR.name().equals(propertiesMap.get("jdbcType"))) {
propertyType = java.sql.ResultSet.class;
} else if (property != null) {
MetaClass metaClass = MetaClass.forClass(parameterType);
if (metaClass.hasGetter(property)) {
propertyType = metaClass.getGetterType(property);
} else {
propertyType = Object.class;
}
} else {
propertyType = Object.class;
}
ParameterMapping.Builder builder = new ParameterMapping.Builder(configuration, property, propertyType);
Class<?> javaType = null;
String typeHandlerAlias = null;
for (Map.Entry<String, String> entry : propertiesMap.entrySet()) {
String name = entry.getKey();
String value = entry.getValue();
if ("javaType".equals(name)) {
javaType = resolveClass(value);
builder.javaType(javaType);
} else if ("jdbcType".equals(name)) {
builder.jdbcType(resolveJdbcType(value));
} else if ("mode".equals(name)) {
builder.mode(resolveParameterMode(value));
} else if ("numericScale".equals(name)) {
builder.numericScale(Integer.valueOf(value));
} else if ("resultMap".equals(name)) {
builder.resultMapId(value);
} else if ("typeHandler".equals(name)) {
typeHandlerAlias = value;
} else if ("jdbcTypeName".equals(name)) {
builder.jdbcTypeName(value);
} else if ("property".equals(name)) {
// Do Nothing
} else if ("expression".equals(name)) {
throw new BuilderException("Expression based parameters are not supported yet");
} else {
throw new BuilderException("An invalid property '" + name + "' was found in mapping #{" + content + "}. Valid properties are " + parameterProperties);
}
}
if (typeHandlerAlias != null) {
builder.typeHandler((TypeHandler<?>) resolveTypeHandler(javaType, typeHandlerAlias));
}
return builder.build();
}
| private ParameterMapping buildParameterMapping(String content) {
Map<String, String> propertiesMap = parseParameterMapping(content);
String property = propertiesMap.get("property");
Class<?> propertyType;
if (metaParameters.hasGetter(property)) { // issue #448 get type from additional params
propertyType = metaParameters.getGetterType(property);
} else if (typeHandlerRegistry.hasTypeHandler(parameterType)) {
propertyType = parameterType;
} else if (JdbcType.CURSOR.name().equals(propertiesMap.get("jdbcType"))) {
propertyType = java.sql.ResultSet.class;
} else if (property != null) {
MetaClass metaClass = MetaClass.forClass(parameterType);
if (metaClass.hasGetter(property)) {
propertyType = metaClass.getGetterType(property);
} else {
propertyType = Object.class;
}
} else {
propertyType = Object.class;
}
ParameterMapping.Builder builder = new ParameterMapping.Builder(configuration, property, propertyType);
Class<?> javaType = propertyType;
String typeHandlerAlias = null;
for (Map.Entry<String, String> entry : propertiesMap.entrySet()) {
String name = entry.getKey();
String value = entry.getValue();
if ("javaType".equals(name)) {
javaType = resolveClass(value);
builder.javaType(javaType);
} else if ("jdbcType".equals(name)) {
builder.jdbcType(resolveJdbcType(value));
} else if ("mode".equals(name)) {
builder.mode(resolveParameterMode(value));
} else if ("numericScale".equals(name)) {
builder.numericScale(Integer.valueOf(value));
} else if ("resultMap".equals(name)) {
builder.resultMapId(value);
} else if ("typeHandler".equals(name)) {
typeHandlerAlias = value;
} else if ("jdbcTypeName".equals(name)) {
builder.jdbcTypeName(value);
} else if ("property".equals(name)) {
// Do Nothing
} else if ("expression".equals(name)) {
throw new BuilderException("Expression based parameters are not supported yet");
} else {
throw new BuilderException("An invalid property '" + name + "' was found in mapping #{" + content + "}. Valid properties are " + parameterProperties);
}
}
if (typeHandlerAlias != null) {
builder.typeHandler((TypeHandler<?>) resolveTypeHandler(javaType, typeHandlerAlias));
}
return builder.build();
}
|
diff --git a/PetriNetReplayAnalysis/src/org/processmining/plugins/petrinet/addtransition/AddEndTransitionPlugin.java b/PetriNetReplayAnalysis/src/org/processmining/plugins/petrinet/addtransition/AddEndTransitionPlugin.java
index f69ca38..7149593 100644
--- a/PetriNetReplayAnalysis/src/org/processmining/plugins/petrinet/addtransition/AddEndTransitionPlugin.java
+++ b/PetriNetReplayAnalysis/src/org/processmining/plugins/petrinet/addtransition/AddEndTransitionPlugin.java
@@ -1,90 +1,90 @@
package org.processmining.plugins.petrinet.addtransition;
import org.processmining.contexts.uitopia.annotations.UITopiaVariant;
import org.processmining.framework.connections.ConnectionCannotBeObtained;
import org.processmining.framework.plugin.PluginContext;
import org.processmining.framework.plugin.annotations.Plugin;
import org.processmining.framework.plugin.annotations.PluginVariant;
import org.processmining.models.connections.petrinets.behavioral.InitialMarkingConnection;
import org.processmining.models.graphbased.directed.petrinet.Petrinet;
import org.processmining.models.graphbased.directed.petrinet.elements.ExpandableSubNet;
import org.processmining.models.graphbased.directed.petrinet.elements.Place;
import org.processmining.models.graphbased.directed.petrinet.elements.Transition;
import org.processmining.models.graphbased.directed.petrinet.impl.PetrinetFactory;
import org.processmining.models.semantics.petrinet.Marking;
@Plugin(name = "Add Artificial End Transition", parameterLabels = { "PetriNet","Name End Transition" }, returnLabels = { "PetriNet","Initial Marking" }, returnTypes = { Petrinet.class, Marking.class })
public class AddEndTransitionPlugin {
@PluginVariant(requiredParameterLabels = { 0 })
@UITopiaVariant(affiliation = "UNIPI", author = "GOs", email = "")
public Object addTransition(PluginContext context, Petrinet oldnet){
return this.addTransition(context, oldnet, "ArtificialEnd");
}
@PluginVariant(requiredParameterLabels = { 0,1 })
public Object addTransition(PluginContext context, Petrinet oldnet, String name){
name = name.replaceAll ("[ \\p{Punct}]", "");
Marking oldmarking=null;
try {
InitialMarkingConnection connection = context.getConnectionManager().getFirstConnection(
InitialMarkingConnection.class, context, oldnet);
oldmarking = connection.getObjectWithRole(InitialMarkingConnection.MARKING);
} catch (ConnectionCannotBeObtained ex) {
context.log("Petri net lacks initial marking");
System.out.println("**************** NO MARKING **************");
return null;
}
Petrinet net = PetrinetFactory.clonePetrinet(oldnet);
ExpandableSubNet subNet = null;
//cerca la piazza finale
for(Place p : net.getPlaces()){
//questa è il place finale
if(p.getGraph().getOutEdges(p).size()==0){
- Transition t = net.addTransition(name+"complete", subNet);
+ Transition t = net.addTransition(name+"+complete", subNet);
Place place = net.addPlace(name, subNet);
net.addArc(t, place, 1, subNet);
net.addArc(p, t, 1, subNet);
}
}
Marking newmarking = new Marking();
for (Place p :oldmarking.toList()){
for(Place pnew : net.getPlaces()){
if(p.getLabel()==pnew.getLabel()){
newmarking.add(pnew);
break;
}
}
}
context.addConnection(new InitialMarkingConnection(net, newmarking));
Object[] result = new Object[2];
result[0] = net;
result[1] = newmarking;
return result;
}
}
| true | true | public Object addTransition(PluginContext context, Petrinet oldnet, String name){
name = name.replaceAll ("[ \\p{Punct}]", "");
Marking oldmarking=null;
try {
InitialMarkingConnection connection = context.getConnectionManager().getFirstConnection(
InitialMarkingConnection.class, context, oldnet);
oldmarking = connection.getObjectWithRole(InitialMarkingConnection.MARKING);
} catch (ConnectionCannotBeObtained ex) {
context.log("Petri net lacks initial marking");
System.out.println("**************** NO MARKING **************");
return null;
}
Petrinet net = PetrinetFactory.clonePetrinet(oldnet);
ExpandableSubNet subNet = null;
//cerca la piazza finale
for(Place p : net.getPlaces()){
//questa è il place finale
if(p.getGraph().getOutEdges(p).size()==0){
Transition t = net.addTransition(name+"complete", subNet);
Place place = net.addPlace(name, subNet);
net.addArc(t, place, 1, subNet);
net.addArc(p, t, 1, subNet);
}
}
Marking newmarking = new Marking();
for (Place p :oldmarking.toList()){
for(Place pnew : net.getPlaces()){
if(p.getLabel()==pnew.getLabel()){
newmarking.add(pnew);
break;
}
}
}
context.addConnection(new InitialMarkingConnection(net, newmarking));
Object[] result = new Object[2];
result[0] = net;
result[1] = newmarking;
return result;
}
| public Object addTransition(PluginContext context, Petrinet oldnet, String name){
name = name.replaceAll ("[ \\p{Punct}]", "");
Marking oldmarking=null;
try {
InitialMarkingConnection connection = context.getConnectionManager().getFirstConnection(
InitialMarkingConnection.class, context, oldnet);
oldmarking = connection.getObjectWithRole(InitialMarkingConnection.MARKING);
} catch (ConnectionCannotBeObtained ex) {
context.log("Petri net lacks initial marking");
System.out.println("**************** NO MARKING **************");
return null;
}
Petrinet net = PetrinetFactory.clonePetrinet(oldnet);
ExpandableSubNet subNet = null;
//cerca la piazza finale
for(Place p : net.getPlaces()){
//questa è il place finale
if(p.getGraph().getOutEdges(p).size()==0){
Transition t = net.addTransition(name+"+complete", subNet);
Place place = net.addPlace(name, subNet);
net.addArc(t, place, 1, subNet);
net.addArc(p, t, 1, subNet);
}
}
Marking newmarking = new Marking();
for (Place p :oldmarking.toList()){
for(Place pnew : net.getPlaces()){
if(p.getLabel()==pnew.getLabel()){
newmarking.add(pnew);
break;
}
}
}
context.addConnection(new InitialMarkingConnection(net, newmarking));
Object[] result = new Object[2];
result[0] = net;
result[1] = newmarking;
return result;
}
|
diff --git a/core/src/main/java/org/apache/ftpserver/DataConnectionConfigurationFactory.java b/core/src/main/java/org/apache/ftpserver/DataConnectionConfigurationFactory.java
index f6ffe9b0..7743ab48 100644
--- a/core/src/main/java/org/apache/ftpserver/DataConnectionConfigurationFactory.java
+++ b/core/src/main/java/org/apache/ftpserver/DataConnectionConfigurationFactory.java
@@ -1,296 +1,296 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ftpserver;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.ftpserver.impl.DefaultDataConnectionConfiguration;
import org.apache.ftpserver.impl.PassivePorts;
import org.apache.ftpserver.ssl.SslConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Data connection factory
*
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
public class DataConnectionConfigurationFactory {
private Logger log = LoggerFactory.getLogger(DataConnectionConfigurationFactory.class);
// maximum idle time in seconds
private int idleTime = 300;
private SslConfiguration ssl;
private boolean activeEnabled = true;
private String activeLocalAddress;
private int activeLocalPort = 0;
private boolean activeIpCheck = false;
private String passiveAddress;
private String passiveExternalAddress;
private PassivePorts passivePorts = new PassivePorts(new int[] { 0 }, true);
private boolean implicitSsl;
/**
* Create a {@link DataConnectionConfiguration} instance based on the
* configuration on this factory
* @return The {@link DataConnectionConfiguration} instance
*/
public DataConnectionConfiguration createDataConnectionConfiguration() {
checkValidAddresses();
return new DefaultDataConnectionConfiguration(idleTime,
ssl, activeEnabled, activeIpCheck,
activeLocalAddress, activeLocalPort,
passiveAddress, passivePorts,
passiveExternalAddress, implicitSsl);
}
/*
* (Non-Javadoc)
* Checks if the configured addresses to be used in further data connections
* are valid.
*/
private void checkValidAddresses(){
try{
InetAddress.getByName(passiveAddress);
InetAddress.getByName(passiveExternalAddress);
}catch(UnknownHostException ex){
throw new FtpServerConfigurationException("Unknown host", ex);
}
}
/**
* Get the maximum idle time in seconds.
* @return The maximum idle time
*/
public int getIdleTime() {
return idleTime;
}
/**
* Set the maximum idle time in seconds.
* @param idleTime The maximum idle time
*/
public void setIdleTime(int idleTime) {
this.idleTime = idleTime;
}
/**
* Is PORT enabled?
* @return true if active data connections are enabled
*/
public boolean isActiveEnabled() {
return activeEnabled;
}
/**
* Set if active data connections are enabled
* @param activeEnabled true if active data connections are enabled
*/
public void setActiveEnabled(boolean activeEnabled) {
this.activeEnabled = activeEnabled;
}
/**
* Check the PORT IP?
* @return true if the client IP is verified against the PORT IP
*/
public boolean isActiveIpCheck() {
return activeIpCheck;
}
/**
* Check the PORT IP with the client IP?
* @param activeIpCheck true if the PORT IP should be verified
*/
public void setActiveIpCheck(boolean activeIpCheck) {
this.activeIpCheck = activeIpCheck;
}
/**
* Get the local address for active mode data transfer.
* @return The address used for active data connections
*/
public String getActiveLocalAddress() {
return activeLocalAddress;
}
/**
* Set the active data connection local host.
* @param activeLocalAddress The address for active connections
*/
public void setActiveLocalAddress(String activeLocalAddress) {
this.activeLocalAddress = activeLocalAddress;
}
/**
* Get the active local port number.
* @return The port used for active data connections
*/
public int getActiveLocalPort() {
return activeLocalPort;
}
/**
* Set the active data connection local port.
* @param activeLocalPort The active data connection local port
*/
public void setActiveLocalPort(int activeLocalPort) {
this.activeLocalPort = activeLocalPort;
}
/**
* Get passive host.
* @return The address used for passive data connections
*/
public String getPassiveAddress() {
return passiveAddress;
}
/**
* Set the passive server address.
* @param passiveAddress The address used for passive connections
*/
public void setPassiveAddress(String passiveAddress) {
this.passiveAddress = passiveAddress;
}
/**
* Get the passive address that will be returned to clients on the PASV
* command.
*
* @return The passive address to be returned to clients, null if not
* configured.
*/
public String getPassiveExternalAddress() {
return passiveExternalAddress;
}
/**
* Set the passive address that will be returned to clients on the PASV
* command.
*
* @param passiveExternalAddress The passive address to be returned to clients
*/
public void setPassiveExternalAddress(String passiveExternalAddress) {
this.passiveExternalAddress = passiveExternalAddress;
}
/**
* Get passive data port. Data port number zero (0) means that any available
* port will be used.
* @return A passive port to use
*/
public synchronized int requestPassivePort() {
int dataPort = -1;
int loopTimes = 2;
Thread currThread = Thread.currentThread();
while ((dataPort == -1) && (--loopTimes >= 0)
&& (!currThread.isInterrupted())) {
// search for a free port
dataPort = passivePorts.reserveNextPort();
// no available free port - wait for the release notification
if (dataPort == -1) {
try {
- log.info("We're waiting for a passive part, might be stuck");
+ log.info("We're waiting for a passive port, might be stuck");
wait();
} catch (InterruptedException ex) {
}
}
}
return dataPort;
}
/**
* Retrieve the passive ports configured for this data connection
*
* @return The String of passive ports
*/
public String getPassivePorts() {
return passivePorts.toString();
}
/**
* Set the passive ports to be used for data connections. Ports can be
* defined as single ports, closed or open ranges. Multiple definitions can
* be separated by commas, for example:
* <ul>
* <li>2300 : only use port 2300 as the passive port</li>
* <li>2300-2399 : use all ports in the range</li>
* <li>2300- : use all ports larger than 2300</li>
* <li>2300, 2305, 2400- : use 2300 or 2305 or any port larger than 2400</li>
* </ul>
*
* Defaults to using any available port
*
* @param passivePorts The passive ports string
*/
public void setPassivePorts(String passivePorts) {
this.passivePorts = new PassivePorts(passivePorts, true);
}
/**
* Release data port
* @param port The port to release
*/
public synchronized void releasePassivePort(final int port) {
passivePorts.releasePort(port);
notify();
}
/**
* Get the {@link SslConfiguration} to be used by data connections
* @return The {@link SslConfiguration} used by data connections
*/
public SslConfiguration getSslConfiguration() {
return ssl;
}
/**
* Set the {@link SslConfiguration} to be used by data connections
* @param ssl The {@link SslConfiguration}
*/
public void setSslConfiguration(SslConfiguration ssl) {
this.ssl = ssl;
}
/**
* @return True if ssl is mandatory for the data connection
*/
public boolean isImplicitSsl() {
return implicitSsl;
}
/**
* Set whether ssl is required for the data connection
* @param sslMandatory True if ssl is mandatory for the data connection
*/
public void setImplicitSsl(boolean implicitSsl) {
this.implicitSsl = implicitSsl;
}
}
| true | true | public synchronized int requestPassivePort() {
int dataPort = -1;
int loopTimes = 2;
Thread currThread = Thread.currentThread();
while ((dataPort == -1) && (--loopTimes >= 0)
&& (!currThread.isInterrupted())) {
// search for a free port
dataPort = passivePorts.reserveNextPort();
// no available free port - wait for the release notification
if (dataPort == -1) {
try {
log.info("We're waiting for a passive part, might be stuck");
wait();
} catch (InterruptedException ex) {
}
}
}
return dataPort;
}
| public synchronized int requestPassivePort() {
int dataPort = -1;
int loopTimes = 2;
Thread currThread = Thread.currentThread();
while ((dataPort == -1) && (--loopTimes >= 0)
&& (!currThread.isInterrupted())) {
// search for a free port
dataPort = passivePorts.reserveNextPort();
// no available free port - wait for the release notification
if (dataPort == -1) {
try {
log.info("We're waiting for a passive port, might be stuck");
wait();
} catch (InterruptedException ex) {
}
}
}
return dataPort;
}
|
diff --git a/wicketstuff-jquery-examples/src/main/java/org/wicketstuff/jquery/demo/Page4JGrowl.java b/wicketstuff-jquery-examples/src/main/java/org/wicketstuff/jquery/demo/Page4JGrowl.java
index 1ef90dde5..42bc6585d 100644
--- a/wicketstuff-jquery-examples/src/main/java/org/wicketstuff/jquery/demo/Page4JGrowl.java
+++ b/wicketstuff-jquery-examples/src/main/java/org/wicketstuff/jquery/demo/Page4JGrowl.java
@@ -1,44 +1,44 @@
package org.wicketstuff.jquery.demo;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.wicketstuff.jquery.Options;
import org.wicketstuff.jquery.jgrowl.JGrowlFeedbackPanel;
@SuppressWarnings("serial")
public class Page4JGrowl extends PageSupport {
public Page4JGrowl() {
final JGrowlFeedbackPanel feedback = new JGrowlFeedbackPanel("jgrowlFeedback");
add(feedback);
final Options errorOptions = new Options();
errorOptions.set("header", "Error");
errorOptions.set("theme", "error");
errorOptions.set("glue", "before");
feedback.setErrorMessageOptions(errorOptions);
final Options infoOptions = new Options();
infoOptions.set("header", "Info");
infoOptions.set("theme", "info");
infoOptions.set("glue", "after");
feedback.setInfoMessageOptions(infoOptions);
- final AjaxLink link = new AjaxLink("showButton") {
+ final AjaxLink<Void> link = new AjaxLink<Void>("showButton") {
@Override
public void onClick(final AjaxRequestTarget target) {
error("An ERROR message");
info("An INFO message");
target.addComponent(feedback);
}
};
add(link);
}
}
| true | true | public Page4JGrowl() {
final JGrowlFeedbackPanel feedback = new JGrowlFeedbackPanel("jgrowlFeedback");
add(feedback);
final Options errorOptions = new Options();
errorOptions.set("header", "Error");
errorOptions.set("theme", "error");
errorOptions.set("glue", "before");
feedback.setErrorMessageOptions(errorOptions);
final Options infoOptions = new Options();
infoOptions.set("header", "Info");
infoOptions.set("theme", "info");
infoOptions.set("glue", "after");
feedback.setInfoMessageOptions(infoOptions);
final AjaxLink link = new AjaxLink("showButton") {
@Override
public void onClick(final AjaxRequestTarget target) {
error("An ERROR message");
info("An INFO message");
target.addComponent(feedback);
}
};
add(link);
}
| public Page4JGrowl() {
final JGrowlFeedbackPanel feedback = new JGrowlFeedbackPanel("jgrowlFeedback");
add(feedback);
final Options errorOptions = new Options();
errorOptions.set("header", "Error");
errorOptions.set("theme", "error");
errorOptions.set("glue", "before");
feedback.setErrorMessageOptions(errorOptions);
final Options infoOptions = new Options();
infoOptions.set("header", "Info");
infoOptions.set("theme", "info");
infoOptions.set("glue", "after");
feedback.setInfoMessageOptions(infoOptions);
final AjaxLink<Void> link = new AjaxLink<Void>("showButton") {
@Override
public void onClick(final AjaxRequestTarget target) {
error("An ERROR message");
info("An INFO message");
target.addComponent(feedback);
}
};
add(link);
}
|
diff --git a/src/main/java/de/cismet/cids/custom/nas/PointNumberDownload.java b/src/main/java/de/cismet/cids/custom/nas/PointNumberDownload.java
index 20ff1f4c..301c5bf2 100644
--- a/src/main/java/de/cismet/cids/custom/nas/PointNumberDownload.java
+++ b/src/main/java/de/cismet/cids/custom/nas/PointNumberDownload.java
@@ -1,212 +1,212 @@
/***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.cismet.cids.custom.nas;
import org.apache.log4j.Logger;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import de.cismet.cids.custom.utils.pointnumberreservation.PointNumberReservation;
import de.cismet.cids.custom.utils.pointnumberreservation.PointNumberReservationRequest;
import de.cismet.tools.gui.downloadmanager.AbstractDownload;
/**
* DOCUMENT ME!
*
* @author daniel
* @version $Revision$, $Date$
*/
public class PointNumberDownload extends AbstractDownload {
//~ Static fields/initializers ---------------------------------------------
private static final Logger LOG = Logger.getLogger(PointNumberDownload.class);
private static final DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
private static final DateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd");
//~ Instance fields --------------------------------------------------------
boolean isFreigabeMode = false;
boolean downloadProtokoll = false;
private final StringBuilder contentBuilder = new StringBuilder();
private PointNumberReservationRequest content;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new PointNumberDownload object.
*
* @param content DOCUMENT ME!
* @param title DOCUMENT ME!
* @param directory DOCUMENT ME!
* @param filename DOCUMENT ME!
*/
public PointNumberDownload(final PointNumberReservationRequest content,
final String title,
final String directory,
final String filename) {
this.content = content;
this.title = title;
this.directory = directory;
if ((content != null) && content.isSuccessfull() && (content.getPointNumbers() != null)) {
for (final PointNumberReservation pnr : content.getPointNumbers()) {
if ((pnr.getAblaufDatum() == null) || pnr.getAblaufDatum().isEmpty()) {
isFreigabeMode = true;
break;
}
}
}
status = State.WAITING;
if ((content == null) || content.isSuccessfull()) {
determineDestinationFile(filename, ".txt");
} else {
downloadProtokoll = true;
determineDestinationFile(filename, ".xml");
}
}
//~ Methods ----------------------------------------------------------------
/**
* DOCUMENT ME!
*/
private void createFileBody() {
for (final PointNumberReservation pnr : content.getPointNumbers()) {
contentBuilder.append(pnr.getPunktnummern());
if (!isFreigabeMode) {
contentBuilder.append(" (");
try {
contentBuilder.append(dateFormat.format(dateParser.parse(pnr.getAblaufDatum())));
} catch (ParseException ex) {
LOG.info(
"Could not parse the expiration date of a reservation. Using the string representation return by server");
contentBuilder.append(pnr.getAblaufDatum());
}
contentBuilder.append(")");
}
contentBuilder.append(System.getProperty("line.separator"));
}
}
/**
* DOCUMENT ME!
*/
private void createFileHeader() {
String header = "Antragsnummer: " + content.getAntragsnummer() + " erstellt am: ";
final GregorianCalendar cal = new GregorianCalendar();
header += dateFormat.format(cal.getTime());
header += " Anzahl ";
if (isFreigabeMode) {
header += "freigegebener";
} else {
header += "reservierter";
}
header += " Punktnummern: " + content.getPointNumbers().size();
contentBuilder.append(header);
contentBuilder.append(System.getProperty("line.separator"));
if (isFreigabeMode) {
contentBuilder.append("freigegebene Punktnummern");
} else {
contentBuilder.append("reservierte Punktnummern (gültig bis)");
}
contentBuilder.append(System.getProperty("line.separator"));
contentBuilder.append(System.getProperty("line.separator"));
}
@Override
public void run() {
if (status != State.WAITING) {
return;
}
status = State.RUNNING;
stateChanged();
final String bytes;
if (downloadProtokoll) {
bytes = content.getProtokoll();
} else {
if (!isPointNumberBeanValid()) {
status = State.COMPLETED_WITH_ERROR;
stateChanged();
return;
}
createFileHeader();
createFileBody();
bytes = contentBuilder.toString();
}
if ((bytes == null) || (bytes.isEmpty())) {
log.info("Downloaded content seems to be empty..");
if (status == State.RUNNING) {
status = State.COMPLETED;
stateChanged();
}
return;
}
FileOutputStream out = null;
Writer w = null;
try {
out = new FileOutputStream(fileToSaveTo);
- w = new OutputStreamWriter(out, "UTF8");
+ w = new OutputStreamWriter(out, "UTF-8");
w.write(bytes);
w.flush();
} catch (final IOException ex) {
log.warn("Couldn't write downloaded content to file '" + fileToSaveTo + "'.", ex);
error(ex);
return;
} finally {
if (w != null) {
try {
w.close();
} catch (Exception e) {
}
}
}
if (status == State.RUNNING) {
status = State.COMPLETED;
stateChanged();
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
private boolean isPointNumberBeanValid() {
if (content == null) {
return false;
}
if ((content.getAntragsnummer() == null) || content.getAntragsnummer().isEmpty()) {
return false;
}
if ((content.getPointNumbers() == null) || content.getPointNumbers().isEmpty()) {
return false;
}
return true;
}
}
| true | true | public void run() {
if (status != State.WAITING) {
return;
}
status = State.RUNNING;
stateChanged();
final String bytes;
if (downloadProtokoll) {
bytes = content.getProtokoll();
} else {
if (!isPointNumberBeanValid()) {
status = State.COMPLETED_WITH_ERROR;
stateChanged();
return;
}
createFileHeader();
createFileBody();
bytes = contentBuilder.toString();
}
if ((bytes == null) || (bytes.isEmpty())) {
log.info("Downloaded content seems to be empty..");
if (status == State.RUNNING) {
status = State.COMPLETED;
stateChanged();
}
return;
}
FileOutputStream out = null;
Writer w = null;
try {
out = new FileOutputStream(fileToSaveTo);
w = new OutputStreamWriter(out, "UTF8");
w.write(bytes);
w.flush();
} catch (final IOException ex) {
log.warn("Couldn't write downloaded content to file '" + fileToSaveTo + "'.", ex);
error(ex);
return;
} finally {
if (w != null) {
try {
w.close();
} catch (Exception e) {
}
}
}
if (status == State.RUNNING) {
status = State.COMPLETED;
stateChanged();
}
}
| public void run() {
if (status != State.WAITING) {
return;
}
status = State.RUNNING;
stateChanged();
final String bytes;
if (downloadProtokoll) {
bytes = content.getProtokoll();
} else {
if (!isPointNumberBeanValid()) {
status = State.COMPLETED_WITH_ERROR;
stateChanged();
return;
}
createFileHeader();
createFileBody();
bytes = contentBuilder.toString();
}
if ((bytes == null) || (bytes.isEmpty())) {
log.info("Downloaded content seems to be empty..");
if (status == State.RUNNING) {
status = State.COMPLETED;
stateChanged();
}
return;
}
FileOutputStream out = null;
Writer w = null;
try {
out = new FileOutputStream(fileToSaveTo);
w = new OutputStreamWriter(out, "UTF-8");
w.write(bytes);
w.flush();
} catch (final IOException ex) {
log.warn("Couldn't write downloaded content to file '" + fileToSaveTo + "'.", ex);
error(ex);
return;
} finally {
if (w != null) {
try {
w.close();
} catch (Exception e) {
}
}
}
if (status == State.RUNNING) {
status = State.COMPLETED;
stateChanged();
}
}
|
diff --git a/CommandsEX/src/com/github/zathrus_writer/commandsex/commands/Command_cex_ownerstatus.java b/CommandsEX/src/com/github/zathrus_writer/commandsex/commands/Command_cex_ownerstatus.java
index 58f9306..282625f 100644
--- a/CommandsEX/src/com/github/zathrus_writer/commandsex/commands/Command_cex_ownerstatus.java
+++ b/CommandsEX/src/com/github/zathrus_writer/commandsex/commands/Command_cex_ownerstatus.java
@@ -1,101 +1,103 @@
package com.github.zathrus_writer.commandsex.commands;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.github.zathrus_writer.commandsex.CommandsEX;
import com.github.zathrus_writer.commandsex.helpers.Commands;
import com.github.zathrus_writer.commandsex.helpers.LogHelper;
public class Command_cex_ownerstatus {
/***
* OWNERSTATUS - displays wether the owner is online with optional other stuff...
* @author Kezz101
* @param sender
* @param args
* @return
*/
public static Boolean run(CommandSender sender, String alias, String[] args) {
// Command Variables
Player player = (Player)sender;
String ownerS = CommandsEX.getConf().getString("ServerOwner");
Player owner = Bukkit.getPlayer(ownerS);
String ownerStatus = "";
// Is the sender the owner?
if(player == owner) {
// If they ain't used any correct args
if(args.length != 1 || args[0]=="help" || args[0]=="check") {
// Tell them what they are
LogHelper.showInfo("ownerCheckStatus#####" + "[" + ownerStatus, sender);
// Then show them how to change it
LogHelper.showInfo("ownerChangeStatus", sender);
LogHelper.showInfo("ownerDefineDoNotDisturb", sender);
LogHelper.showInfo("ownerDefineAwayFromKeyboard", sender);
LogHelper.showInfo("ownerDefineBusy", sender);
LogHelper.showInfo("ownerDefineHere", sender);
// And finally show them the syntax
Commands.showCommandHelpAndUsage(sender, "cex_ownerstatus", alias);
return true;
}
// Set there new status
if(args[0].equalsIgnoreCase("here")) {
ownerStatus="";
} else if(args[0].equalsIgnoreCase("dnd")) {
ownerStatus="dnd";
} else if(args[0].equalsIgnoreCase("afk")) {
ownerStatus="afk";
} else if(args[0].equalsIgnoreCase("busy")) {
ownerStatus="busy";
+ } else {
+ return false;
}
// Finally show them what they changed it to
LogHelper.showInfo("ownerNewStatus#####" + "[" + ownerStatus, sender);
return true;
}
// Is owner is offline
if(owner == null) {
LogHelper.showInfo("[" + ownerS + " #####ownerOffline", sender, ChatColor.RED);
return true;
}
// If owner is dnd
if(ownerStatus.equalsIgnoreCase("dnd")) {
LogHelper.showInfo("[" + ownerS + " #####ownerDoNotDisturb", sender, ChatColor.DARK_RED);
return true;
}
// If owner is afk
if(ownerStatus.equalsIgnoreCase("afk")) {
LogHelper.showInfo("[" + ownerS + " #####ownerAwayFromKeyboard", sender, ChatColor.RED);
return true;
}
// Is owner is busy
if(ownerStatus.equalsIgnoreCase("busy")) {
LogHelper.showInfo("[" + ownerS + " #####ownerBusy", sender, ChatColor.RED);
return true;
}
// If they are just online
if(ownerStatus.equalsIgnoreCase("")) {
LogHelper.showInfo("[" + ownerS + " #####ownerOnline", sender, ChatColor.GREEN);
return true;
}
return true;
}
}
| true | true | public static Boolean run(CommandSender sender, String alias, String[] args) {
// Command Variables
Player player = (Player)sender;
String ownerS = CommandsEX.getConf().getString("ServerOwner");
Player owner = Bukkit.getPlayer(ownerS);
String ownerStatus = "";
// Is the sender the owner?
if(player == owner) {
// If they ain't used any correct args
if(args.length != 1 || args[0]=="help" || args[0]=="check") {
// Tell them what they are
LogHelper.showInfo("ownerCheckStatus#####" + "[" + ownerStatus, sender);
// Then show them how to change it
LogHelper.showInfo("ownerChangeStatus", sender);
LogHelper.showInfo("ownerDefineDoNotDisturb", sender);
LogHelper.showInfo("ownerDefineAwayFromKeyboard", sender);
LogHelper.showInfo("ownerDefineBusy", sender);
LogHelper.showInfo("ownerDefineHere", sender);
// And finally show them the syntax
Commands.showCommandHelpAndUsage(sender, "cex_ownerstatus", alias);
return true;
}
// Set there new status
if(args[0].equalsIgnoreCase("here")) {
ownerStatus="";
} else if(args[0].equalsIgnoreCase("dnd")) {
ownerStatus="dnd";
} else if(args[0].equalsIgnoreCase("afk")) {
ownerStatus="afk";
} else if(args[0].equalsIgnoreCase("busy")) {
ownerStatus="busy";
}
// Finally show them what they changed it to
LogHelper.showInfo("ownerNewStatus#####" + "[" + ownerStatus, sender);
return true;
}
// Is owner is offline
if(owner == null) {
LogHelper.showInfo("[" + ownerS + " #####ownerOffline", sender, ChatColor.RED);
return true;
}
// If owner is dnd
if(ownerStatus.equalsIgnoreCase("dnd")) {
LogHelper.showInfo("[" + ownerS + " #####ownerDoNotDisturb", sender, ChatColor.DARK_RED);
return true;
}
// If owner is afk
if(ownerStatus.equalsIgnoreCase("afk")) {
LogHelper.showInfo("[" + ownerS + " #####ownerAwayFromKeyboard", sender, ChatColor.RED);
return true;
}
// Is owner is busy
if(ownerStatus.equalsIgnoreCase("busy")) {
LogHelper.showInfo("[" + ownerS + " #####ownerBusy", sender, ChatColor.RED);
return true;
}
// If they are just online
if(ownerStatus.equalsIgnoreCase("")) {
LogHelper.showInfo("[" + ownerS + " #####ownerOnline", sender, ChatColor.GREEN);
return true;
}
return true;
}
| public static Boolean run(CommandSender sender, String alias, String[] args) {
// Command Variables
Player player = (Player)sender;
String ownerS = CommandsEX.getConf().getString("ServerOwner");
Player owner = Bukkit.getPlayer(ownerS);
String ownerStatus = "";
// Is the sender the owner?
if(player == owner) {
// If they ain't used any correct args
if(args.length != 1 || args[0]=="help" || args[0]=="check") {
// Tell them what they are
LogHelper.showInfo("ownerCheckStatus#####" + "[" + ownerStatus, sender);
// Then show them how to change it
LogHelper.showInfo("ownerChangeStatus", sender);
LogHelper.showInfo("ownerDefineDoNotDisturb", sender);
LogHelper.showInfo("ownerDefineAwayFromKeyboard", sender);
LogHelper.showInfo("ownerDefineBusy", sender);
LogHelper.showInfo("ownerDefineHere", sender);
// And finally show them the syntax
Commands.showCommandHelpAndUsage(sender, "cex_ownerstatus", alias);
return true;
}
// Set there new status
if(args[0].equalsIgnoreCase("here")) {
ownerStatus="";
} else if(args[0].equalsIgnoreCase("dnd")) {
ownerStatus="dnd";
} else if(args[0].equalsIgnoreCase("afk")) {
ownerStatus="afk";
} else if(args[0].equalsIgnoreCase("busy")) {
ownerStatus="busy";
} else {
return false;
}
// Finally show them what they changed it to
LogHelper.showInfo("ownerNewStatus#####" + "[" + ownerStatus, sender);
return true;
}
// Is owner is offline
if(owner == null) {
LogHelper.showInfo("[" + ownerS + " #####ownerOffline", sender, ChatColor.RED);
return true;
}
// If owner is dnd
if(ownerStatus.equalsIgnoreCase("dnd")) {
LogHelper.showInfo("[" + ownerS + " #####ownerDoNotDisturb", sender, ChatColor.DARK_RED);
return true;
}
// If owner is afk
if(ownerStatus.equalsIgnoreCase("afk")) {
LogHelper.showInfo("[" + ownerS + " #####ownerAwayFromKeyboard", sender, ChatColor.RED);
return true;
}
// Is owner is busy
if(ownerStatus.equalsIgnoreCase("busy")) {
LogHelper.showInfo("[" + ownerS + " #####ownerBusy", sender, ChatColor.RED);
return true;
}
// If they are just online
if(ownerStatus.equalsIgnoreCase("")) {
LogHelper.showInfo("[" + ownerS + " #####ownerOnline", sender, ChatColor.GREEN);
return true;
}
return true;
}
|
diff --git a/src/main/java/nodebox/client/NetworkView.java b/src/main/java/nodebox/client/NetworkView.java
index 9ca26f22..0a0f6139 100644
--- a/src/main/java/nodebox/client/NetworkView.java
+++ b/src/main/java/nodebox/client/NetworkView.java
@@ -1,1136 +1,1140 @@
package nodebox.client;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import nodebox.node.*;
import nodebox.ui.PaneView;
import nodebox.ui.Platform;
import nodebox.ui.Theme;
import org.python.google.common.base.Joiner;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
public class NetworkView extends JComponent implements PaneView, KeyListener, MouseListener, MouseWheelListener, MouseMotionListener {
public static final int GRID_CELL_SIZE = 48;
public static final int NODE_MARGIN = 6;
public static final int NODE_PADDING = 5;
public static final int NODE_WIDTH = GRID_CELL_SIZE * 3 - NODE_MARGIN * 2;
public static final int NODE_HEIGHT = GRID_CELL_SIZE - NODE_MARGIN * 2;
public static final int NODE_ICON_SIZE = 26;
public static final int GRID_OFFSET = 6;
public static final int PORT_WIDTH = 10;
public static final int PORT_HEIGHT = 3;
public static final int PORT_SPACING = 10;
public static final Dimension NODE_DIMENSION = new Dimension(NODE_WIDTH, NODE_HEIGHT);
public static final String SELECT_PROPERTY = "NetworkView.select";
public static final String HIGHLIGHT_PROPERTY = "highlight";
public static final String RENDER_PROPERTY = "render";
public static final String NETWORK_PROPERTY = "network";
private static Map<String, BufferedImage> nodeImageCache = new HashMap<String, BufferedImage>();
private static BufferedImage nodeGeneric;
public static final float MIN_ZOOM = 0.05f;
public static final float MAX_ZOOM = 1.0f;
public static final Map<String, Color> PORT_COLORS = Maps.newHashMap();
public static final Color DEFAULT_PORT_COLOR = Color.WHITE;
public static final Color NODE_BACKGROUND_COLOR = new Color(123, 154, 152);
public static final Color PORT_HOVER_COLOR = Color.YELLOW;
public static final Color TOOLTIP_BACKGROUND_COLOR = new Color(254, 255, 215);
public static final Color TOOLTIP_STROKE_COLOR = Color.DARK_GRAY;
public static final Color TOOLTIP_TEXT_COLOR = Color.DARK_GRAY;
public static final Color DRAG_SELECTION_COLOR = new Color(255, 255, 255, 100);
public static final BasicStroke DRAG_SELECTION_STROKE = new BasicStroke(1f);
public static final BasicStroke CONNECTION_STROKE = new BasicStroke(2);
private static Cursor defaultCursor, panCursor;
private final NodeBoxDocument document;
private JPopupMenu networkMenu;
private Point networkMenuLocation;
private JPopupMenu nodeMenu;
private Point nodeMenuLocation;
// View state
private double viewX, viewY, viewScale = 1;
private transient AffineTransform viewTransform = null;
private transient AffineTransform inverseViewTransform = null;
private Set<String> selectedNodes = new HashSet<String>();
// Interaction state
private boolean isDraggingNodes = false;
private boolean isSpacePressed = false;
private boolean isShiftPressed = false;
private boolean isDragSelecting = false;
private ImmutableMap<String, nodebox.graphics.Point> dragPositions = ImmutableMap.of();
private NodePort overInput;
private Node overOutput;
private Node connectionOutput;
private NodePort connectionInput;
private Point2D connectionPoint;
private boolean startDragging;
private Point2D dragStartPoint;
private Point2D dragCurrentPoint;
static {
Image panCursorImage;
try {
if (Platform.onWindows())
panCursorImage = ImageIO.read(new File("res/view-cursor-pan-32.png"));
else
panCursorImage = ImageIO.read(new File("res/view-cursor-pan.png"));
Toolkit toolkit = Toolkit.getDefaultToolkit();
panCursor = toolkit.createCustomCursor(panCursorImage, new Point(0, 0), "PanCursor");
defaultCursor = Cursor.getDefaultCursor();
nodeGeneric = ImageIO.read(new File("res/node-generic.png"));
} catch (IOException e) {
throw new RuntimeException(e);
}
PORT_COLORS.put(Port.TYPE_INT, new Color(116, 119, 121));
PORT_COLORS.put(Port.TYPE_FLOAT, new Color(116, 119, 121));
PORT_COLORS.put(Port.TYPE_STRING, new Color(92, 90, 91));
PORT_COLORS.put(Port.TYPE_BOOLEAN, new Color(92, 90, 91));
PORT_COLORS.put(Port.TYPE_POINT, new Color(119, 154, 173));
PORT_COLORS.put(Port.TYPE_COLOR, new Color(94, 85, 112));
PORT_COLORS.put("geometry", new Color(20, 20, 20));
PORT_COLORS.put("list", new Color(76, 137, 174));
PORT_COLORS.put("data", new Color(52, 85, 129));
}
/**
* Tries to find an image representation for the node.
* The image should be located near the library, and have the same name as the library.
* <p/>
* If this node has no image, the prototype is searched to find its image. If no image could be found,
* a generic image is returned.
*
* @param node the node
* @param nodeRepository the list of nodes to look for the icon
* @return an Image object.
*/
public static BufferedImage getImageForNode(Node node, NodeRepository nodeRepository) {
for (NodeLibrary library : nodeRepository.getLibraries()) {
BufferedImage img = findNodeImage(library, node);
if (img != null) {
return img;
}
}
if (node.getPrototype() != null) {
return getImageForNode(node.getPrototype(), nodeRepository);
} else {
return nodeGeneric;
}
}
public static BufferedImage findNodeImage(NodeLibrary library, Node node) {
if (node == null || node.getImage() == null || node.getImage().isEmpty()) return null;
if (!library.getRoot().hasChild(node)) return null;
File libraryFile = library.getFile();
if (libraryFile != null) {
File libraryDirectory = libraryFile.getParentFile();
if (libraryDirectory != null) {
File nodeImageFile = new File(libraryDirectory, node.getImage());
if (nodeImageFile.exists()) {
return readNodeImage(nodeImageFile);
}
}
}
return null;
}
public static BufferedImage readNodeImage(File nodeImageFile) {
String imagePath = nodeImageFile.getAbsolutePath();
if (nodeImageCache.containsKey(imagePath)) {
return nodeImageCache.get(imagePath);
} else {
try {
BufferedImage image = ImageIO.read(nodeImageFile);
nodeImageCache.put(imagePath, image);
return image;
} catch (IOException e) {
return null;
}
}
}
public NetworkView(NodeBoxDocument document) {
this.document = document;
setBackground(Theme.NETWORK_BACKGROUND_COLOR);
initEventHandlers();
initMenus();
}
private void initEventHandlers() {
setFocusable(true);
// This is disabled so we can detect the tab key.
setFocusTraversalKeysEnabled(false);
addKeyListener(this);
addMouseListener(this);
addMouseMotionListener(this);
addMouseWheelListener(this);
}
private void initMenus() {
networkMenu = new JPopupMenu();
networkMenu.add(new NewNodeAction());
networkMenu.add(new ResetViewAction());
networkMenu.add(new GoUpAction());
nodeMenu = new JPopupMenu();
nodeMenu.add(new SetRenderedAction());
nodeMenu.add(new RenameAction());
nodeMenu.add(new DeleteAction());
nodeMenu.add(new GroupIntoNetworkAction(null));
nodeMenu.add(new GoInAction());
}
public NodeBoxDocument getDocument() {
return document;
}
public Node getActiveNetwork() {
return document.getActiveNetwork();
}
//// Events ////
/**
* Refresh the nodes and connections cache.
*/
public void updateAll() {
updateNodes();
updateConnections();
}
public void updateNodes() {
repaint();
}
public void updateConnections() {
repaint();
}
public void updatePosition(Node node) {
updateConnections();
}
public void checkErrorAndRepaint() {
//if (!networkError && !activeNetwork.hasError()) return;
//networkError = activeNetwork.hasError();
repaint();
}
public void codeChanged(Node node, boolean changed) {
repaint();
}
//// Model queries ////
public Node getActiveNode() {
return document.getActiveNode();
}
private ImmutableList<Node> getNodes() {
return getDocument().getActiveNetwork().getChildren();
}
private ImmutableList<Node> getNodesReversed() {
return getNodes().reverse();
}
private Iterable<Connection> getConnections() {
return getDocument().getActiveNetwork().getConnections();
}
public static boolean isPublished(Node network, Node childNode, Port childPort) {
return network.hasPublishedInput(childNode.getName(), childPort.getName());
}
//// Painting the nodes ////
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
// Draw background
g2.setColor(Theme.NETWORK_BACKGROUND_COLOR);
g2.fill(g.getClipBounds());
// Paint the grid
// (The grid is not really affected by the view transform)
paintGrid(g2);
// Set the view transform
AffineTransform originalTransform = g2.getTransform();
g2.transform(getViewTransform());
paintNodes(g2);
paintConnections(g2);
paintCurrentConnection(g2);
paintPortTooltip(g2);
paintDragSelection(g2);
// Restore original transform
g2.setTransform(originalTransform);
}
private void paintGrid(Graphics2D g) {
g.setColor(Theme.NETWORK_GRID_COLOR);
int gridCellSize = (int) Math.round(GRID_CELL_SIZE * viewScale);
int gridOffset = (int) Math.round(GRID_OFFSET * viewScale);
if (gridCellSize < 10) return;
int transformOffsetX = (int) (viewX % gridCellSize);
int transformOffsetY = (int) (viewY % gridCellSize);
for (int y = -gridCellSize; y < getHeight() + gridCellSize; y += gridCellSize) {
g.drawLine(0, y - gridOffset + transformOffsetY, getWidth(), y - gridOffset + transformOffsetY);
}
for (int x = -gridCellSize; x < getWidth() + gridCellSize; x += gridCellSize) {
g.drawLine(x - gridOffset + transformOffsetX, 0, x - gridOffset + transformOffsetX, getHeight());
}
}
private void paintConnections(Graphics2D g) {
g.setColor(Theme.CONNECTION_DEFAULT_COLOR);
g.setStroke(CONNECTION_STROKE);
for (Connection connection : getConnections()) {
paintConnection(g, connection);
}
}
private void paintConnection(Graphics2D g, Connection connection) {
Node outputNode = findNodeWithName(connection.getOutputNode());
Node inputNode = findNodeWithName(connection.getInputNode());
Port inputPort = inputNode.getInput(connection.getInputPort());
g.setColor(portTypeColor(outputNode.getOutputType()));
Rectangle outputRect = nodeRect(outputNode);
Rectangle inputRect = nodeRect(inputNode);
paintConnectionLine(g, outputRect.x + 4, outputRect.y + outputRect.height + 1, inputRect.x + portOffset(inputNode, inputPort) + 4, inputRect.y - 4);
}
private void paintCurrentConnection(Graphics2D g) {
g.setColor(Theme.CONNECTION_DEFAULT_COLOR);
if (connectionOutput != null) {
Rectangle outputRect = nodeRect(connectionOutput);
g.setColor(portTypeColor(connectionOutput.getOutputType()));
paintConnectionLine(g, outputRect.x + 4, outputRect.y + outputRect.height + 1, (int) connectionPoint.getX(), (int) connectionPoint.getY());
}
}
private static void paintConnectionLine(Graphics2D g, int x0, int y0, int x1, int y1) {
double dy = Math.abs(y1 - y0);
if (dy < GRID_CELL_SIZE) {
g.drawLine(x0, y0, x1, y1);
} else {
double halfDx = Math.abs(x1 - x0) / 2;
GeneralPath p = new GeneralPath();
p.moveTo(x0, y0);
p.curveTo(x0, y0 + halfDx, x1, y1 - halfDx, x1, y1);
g.draw(p);
}
}
private void paintNodes(Graphics2D g) {
g.setColor(Theme.NETWORK_NODE_NAME_COLOR);
for (Node node : getNodes()) {
Port hoverInputPort = overInput != null && overInput.node == node.getName() ? findNodeWithName(overInput.node).getInput(overInput.port) : null;
BufferedImage icon = getImageForNode(node, getDocument().getNodeRepository());
paintNode(g, getActiveNetwork(), node, icon, isSelected(node), isRendered(node), connectionOutput, hoverInputPort, overOutput == node);
}
}
public static Color portTypeColor(String type) {
Color portColor = PORT_COLORS.get(type);
return portColor == null ? DEFAULT_PORT_COLOR : portColor;
}
private static String getShortenedName(String name, int startChars) {
nodebox.graphics.Text text = new nodebox.graphics.Text(name, nodebox.graphics.Point.ZERO);
text.setFontName(Theme.NETWORK_FONT.getFontName());
text.setFontSize(Theme.NETWORK_FONT.getSize());
int cells = Math.min(Math.max(3, 1 + (int) Math.ceil(text.getMetrics().getWidth() / (GRID_CELL_SIZE - 6))), 6);
if (cells > 3)
return getShortenedName(name.substring(0, startChars) + "…" + name.substring(name.length() - 3, name.length()), startChars - 1);
return name;
}
private void paintNode(Graphics2D g, Node network, Node node, BufferedImage icon, boolean selected, boolean rendered, Node connectionOutput, Port hoverInputPort, boolean hoverOutput) {
Rectangle r = nodeRect(node);
String outputType = node.getOutputType();
// Draw selection ring
if (selected) {
g.setColor(Color.WHITE);
g.fillRect(r.x, r.y, NODE_WIDTH, NODE_HEIGHT);
}
// Draw node
g.setColor(portTypeColor(outputType));
if (selected) {
g.fillRect(r.x + 2, r.y + 2, NODE_WIDTH - 4, NODE_HEIGHT - 4);
} else {
g.fillRect(r.x, r.y, NODE_WIDTH, NODE_HEIGHT);
}
// Draw render flag
if (rendered) {
g.setColor(Color.WHITE);
GeneralPath gp = new GeneralPath();
gp.moveTo(r.x + NODE_WIDTH - 2, r.y + NODE_HEIGHT - 20);
gp.lineTo(r.x + NODE_WIDTH - 2, r.y + NODE_HEIGHT - 2);
gp.lineTo(r.x + NODE_WIDTH - 20, r.y + NODE_HEIGHT - 2);
g.fill(gp);
}
// Draw input ports
g.setColor(Color.WHITE);
int portX = 0;
for (Port input : node.getInputs()) {
if (hoverInputPort == input) {
g.setColor(PORT_HOVER_COLOR);
} else {
g.setColor(portTypeColor(input.getType()));
}
// Highlight ports that match the dragged connection type
int portHeight = PORT_HEIGHT;
if (connectionOutput != null) {
- if (connectionOutput.getOutputType().equals(input.getType())) {
+ String connectionOutputType = connectionOutput.getOutputType();
+ String inputType = input.getType();
+ if (connectionOutputType.equals(inputType) || inputType.equals(Port.TYPE_LIST)) {
portHeight = PORT_HEIGHT * 2;
+ } else if (TypeConversions.canBeConverted(connectionOutputType, inputType)) {
+ portHeight = PORT_HEIGHT - 1;
} else {
portHeight = 1;
}
}
if (isPublished(network, node, input)) {
Point2D topLeft = inverseViewTransformPoint(new Point(4, 0));
g.setColor(portTypeColor(input.getType()));
g.setStroke(CONNECTION_STROKE);
paintConnectionLine(g, (int) topLeft.getX(), (int) topLeft.getY(), r.x + portX + 4, r.y - 2);
}
g.fillRect(r.x + portX, r.y - portHeight, PORT_WIDTH, portHeight);
portX += PORT_WIDTH + PORT_SPACING;
}
// Draw output port
if (hoverOutput && connectionOutput == null) {
g.setColor(PORT_HOVER_COLOR);
} else {
g.setColor(portTypeColor(outputType));
}
g.fillRect(r.x, r.y + NODE_HEIGHT, PORT_WIDTH, PORT_HEIGHT);
// Draw icon
g.drawImage(icon, r.x + NODE_PADDING, r.y + NODE_PADDING, NODE_ICON_SIZE, NODE_ICON_SIZE, null);
g.setColor(Color.WHITE);
g.setFont(Theme.NETWORK_FONT);
g.drawString(getShortenedName(node.getName(), 7), r.x + NODE_ICON_SIZE + NODE_PADDING * 2 + 2, r.y + 22);
}
private void paintPortTooltip(Graphics2D g) {
if (overInput != null) {
Node overInputNode = findNodeWithName(overInput.node);
Port overInputPort = overInputNode.getInput(overInput.port);
Rectangle r = inputPortRect(overInputNode, overInputPort);
Point2D pt = new Point2D.Double(r.getX(), r.getY() + 11);
String text = String.format("%s (%s)", overInput.port, overInputPort.getType());
paintTooltip(g, pt, text);
} else if (overOutput != null && connectionOutput == null) {
Rectangle r = outputPortRect(overOutput);
Point2D pt = new Point2D.Double(r.getX(), r.getY() + 11);
String text = String.format("output (%s)", overOutput.getOutputType());
paintTooltip(g, pt, text);
}
}
private static void paintTooltip(Graphics2D g, Point2D point, String text) {
FontMetrics fontMetrics = g.getFontMetrics();
int textWidth = fontMetrics.stringWidth(text);
int verticalOffset = 10;
Rectangle r = new Rectangle((int) point.getX(), (int) point.getY() + verticalOffset, textWidth, fontMetrics.getHeight());
r.grow(4, 3);
g.setColor(TOOLTIP_STROKE_COLOR);
g.drawRoundRect(r.x, r.y, r.width, r.height, 8, 8);
g.setColor(TOOLTIP_BACKGROUND_COLOR);
g.fillRoundRect(r.x, r.y, r.width, r.height, 8, 8);
g.setColor(TOOLTIP_TEXT_COLOR);
g.drawString(text, (float) point.getX(), (float) point.getY() + fontMetrics.getAscent() + verticalOffset);
}
private void paintDragSelection(Graphics2D g) {
if (isDragSelecting) {
Rectangle r = dragSelectRect();
g.setColor(DRAG_SELECTION_COLOR);
g.setStroke(DRAG_SELECTION_STROKE);
g.fill(r);
// To get a smooth line we need to subtract one from the width and height.
g.drawRect((int) r.getX(), (int) r.getY(), (int) r.getWidth() - 1, (int) r.getHeight() - 1);
}
}
private Rectangle dragSelectRect() {
int x0 = (int) dragStartPoint.getX();
int y0 = (int) dragStartPoint.getY();
int x1 = (int) dragCurrentPoint.getX();
int y1 = (int) dragCurrentPoint.getY();
int x = Math.min(x0, x1);
int y = Math.min(y0, y1);
int w = (int) Math.abs(dragCurrentPoint.getX() - dragStartPoint.getX());
int h = (int) Math.abs(dragCurrentPoint.getY() - dragStartPoint.getY());
return new Rectangle(x, y, w, h);
}
private static Rectangle nodeRect(Node node) {
return new Rectangle(nodePoint(node), NODE_DIMENSION);
}
private static Rectangle inputPortRect(Node node, Port port) {
Point pt = nodePoint(node);
Rectangle portRect = new Rectangle(pt.x + portOffset(node, port), pt.y - PORT_HEIGHT, PORT_WIDTH, PORT_HEIGHT);
growHitRectangle(portRect);
return portRect;
}
private static Rectangle outputPortRect(Node node) {
Point pt = nodePoint(node);
Rectangle portRect = new Rectangle(pt.x, pt.y + NODE_HEIGHT, PORT_WIDTH, PORT_HEIGHT);
growHitRectangle(portRect);
return portRect;
}
private static void growHitRectangle(Rectangle r) {
r.grow(2, 2);
}
private static Point nodePoint(Node node) {
int nodeX = ((int) node.getPosition().getX()) * GRID_CELL_SIZE;
int nodeY = ((int) node.getPosition().getY()) * GRID_CELL_SIZE;
return new Point(nodeX, nodeY);
}
private Point pointToGridPoint(Point e) {
Point2D pt = getInverseViewTransform().transform(e, null);
return new Point(
(int) Math.floor(pt.getX() / GRID_CELL_SIZE),
(int) Math.floor(pt.getY() / GRID_CELL_SIZE));
}
private static int portOffset(Node node, Port port) {
int portIndex = node.getInputs().indexOf(port);
return (PORT_WIDTH + PORT_SPACING) * portIndex;
}
//// View Transform ////
private void setViewTransform(double viewX, double viewY, double viewScale) {
this.viewX = viewX;
this.viewY = viewY;
this.viewScale = viewScale;
this.viewTransform = null;
this.inverseViewTransform = null;
}
private AffineTransform getViewTransform() {
if (viewTransform == null) {
viewTransform = new AffineTransform();
viewTransform.translate(viewX, viewY);
viewTransform.scale(viewScale, viewScale);
}
return viewTransform;
}
private AffineTransform getInverseViewTransform() {
if (inverseViewTransform == null) {
try {
inverseViewTransform = getViewTransform().createInverse();
} catch (NoninvertibleTransformException e) {
inverseViewTransform = new AffineTransform();
}
}
return inverseViewTransform;
}
private void resetViewTransform() {
setViewTransform(0, 0, 1);
repaint();
}
//// View queries ////
private Node findNodeWithName(String name) {
return getActiveNetwork().getChild(name);
}
public Node getNodeAt(Point2D point) {
for (Node node : getNodesReversed()) {
Rectangle r = nodeRect(node);
if (r.contains(point)) {
return node;
}
}
return null;
}
public Node getNodeAt(MouseEvent e) {
return getNodeAt(e.getPoint());
}
public Node getNodeWithOutputPortAt(Point2D point) {
for (Node node : getNodesReversed()) {
Rectangle r = outputPortRect(node);
if (r.contains(point)) {
return node;
}
}
return null;
}
public NodePort getInputPortAt(Point2D point) {
for (Node node : getNodesReversed()) {
for (Port port : node.getInputs()) {
Rectangle r = inputPortRect(node, port);
if (r.contains(point)) {
return NodePort.of(node.getName(), port.getName());
}
}
}
return null;
}
//// Selections ////
public boolean isRendered(Node node) {
return getActiveNetwork().getRenderedChild() == node;
}
public boolean isSelected(Node node) {
return (selectedNodes.contains(node.getName()));
}
public void select(Node node) {
selectedNodes.add(node.getName());
}
/**
* Select this node, and only this node.
* <p/>
* All other selected nodes will be deselected.
*
* @param node The node to select. If node is null, everything is deselected.
*/
public void singleSelect(Node node) {
if (selectedNodes.size() == 1 && selectedNodes.contains(node.getName())) return;
selectedNodes.clear();
if (node != null && getActiveNetwork().hasChild(node)) {
selectedNodes.add(node.getName());
firePropertyChange(SELECT_PROPERTY, null, selectedNodes);
document.setActiveNode(node);
}
repaint();
}
public void select(Iterable<Node> nodes) {
selectedNodes.clear();
for (Node node : nodes) {
selectedNodes.add(node.getName());
}
}
public void toggleSelection(Node node) {
checkNotNull(node);
if (selectedNodes.isEmpty()) {
singleSelect(node);
} else {
if (selectedNodes.contains(node.getName())) {
selectedNodes.remove(node.getName());
} else {
selectedNodes.add(node.getName());
}
firePropertyChange(SELECT_PROPERTY, null, selectedNodes);
repaint();
}
}
public void deselectAll() {
if (selectedNodes.isEmpty()) return;
selectedNodes.clear();
firePropertyChange(SELECT_PROPERTY, null, selectedNodes);
document.setActiveNode((Node) null);
repaint();
}
public Iterable<String> getSelectedNodeNames() {
return selectedNodes;
}
public Iterable<Node> getSelectedNodes() {
ImmutableList.Builder<Node> b = new ImmutableList.Builder<nodebox.node.Node>();
for (String name : getSelectedNodeNames()) {
b.add(findNodeWithName(name));
}
return b.build();
}
public void deleteSelection() {
document.removeNodes(getSelectedNodes());
}
//// Network navigation ////
private void goUp() {
if (getDocument().getActiveNetworkPath().equals("/")) return;
Iterable<String> it = Splitter.on("/").split(getDocument().getActiveNetworkPath());
int parts = Iterables.size(it);
String path = parts - 1 > 1 ? Joiner.on("/").join(Iterables.limit(it, parts - 1)) : "/";
getDocument().setActiveNetwork(path);
}
//// Input Events ////
public void keyTyped(KeyEvent e) {
switch (e.getKeyChar()) {
case KeyEvent.VK_BACK_SPACE:
getDocument().deleteSelection();
break;
}
}
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_SHIFT) {
isShiftPressed = true;
} else if (keyCode == KeyEvent.VK_SPACE) {
isSpacePressed = true;
setCursor(panCursor);
} else if (keyCode == KeyEvent.VK_UP) {
moveSelectedNodes(0, -1);
} else if (keyCode == KeyEvent.VK_RIGHT) {
moveSelectedNodes(1, 0);
} else if (keyCode == KeyEvent.VK_DOWN) {
moveSelectedNodes(0, 1);
} else if (keyCode == KeyEvent.VK_LEFT) {
moveSelectedNodes(-1, 0);
}
}
private void moveSelectedNodes(int dx, int dy) {
for (Node node : getSelectedNodes()) {
getDocument().setNodePosition(node, node.getPosition().moved(dx, dy));
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SHIFT) {
isShiftPressed = false;
} else if (e.getKeyCode() == KeyEvent.VK_SPACE) {
isSpacePressed = false;
setCursor(defaultCursor);
}
}
public boolean isSpacePressed() {
return isSpacePressed;
}
public void mouseClicked(MouseEvent e) {
Point2D pt = inverseViewTransformPoint(e.getPoint());
if (e.getButton() == MouseEvent.BUTTON1) {
if (e.getClickCount() == 1) {
Node clickedNode = getNodeAt(pt);
if (clickedNode == null) {
deselectAll();
} else {
if (isShiftPressed) {
toggleSelection(clickedNode);
} else {
singleSelect(clickedNode);
}
}
} else if (e.getClickCount() == 2) {
Node clickedNode = getNodeAt(pt);
if (clickedNode == null) {
Point gridPoint = pointToGridPoint(e.getPoint());
getDocument().showNodeSelectionDialog(gridPoint);
} else {
document.setRenderedNode(clickedNode);
}
}
}
}
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showPopup(e);
} else {
// If the space bar and mouse is pressed, we're getting ready to pan the view.
if (isSpacePressed) {
// When panning the view use the original mouse point, not the one affected by the view transform.
dragStartPoint = e.getPoint();
return;
}
Point2D pt = inverseViewTransformPoint(e.getPoint());
// Check if we're over an output port.
connectionOutput = getNodeWithOutputPortAt(pt);
if (connectionOutput != null) return;
// Check if we're over a connected input port.
connectionInput = getInputPortAt(pt);
if (connectionInput != null) {
// We're over a port, but is it connected?
Connection c = getActiveNetwork().getConnection(connectionInput.node, connectionInput.port);
// Disconnect it, but start a new connection on the same node immediately.
if (c != null) {
getDocument().disconnect(c);
connectionOutput = getActiveNetwork().getChild(c.getOutputNode());
connectionPoint = pt;
}
return;
}
// Check if we're pressing a node.
Node pressedNode = getNodeAt(pt);
if (pressedNode != null) {
// Don't immediately set "isDragging."
// We wait until we actually drag the first time to do the work.
startDragging = true;
return;
}
// We're creating a drag selection.
isDragSelecting = true;
dragStartPoint = pt;
}
}
public void mouseReleased(MouseEvent e) {
isDraggingNodes = false;
isDragSelecting = false;
if (connectionOutput != null && connectionInput != null) {
getDocument().connect(connectionOutput.getName(), connectionInput.node, connectionInput.port);
}
connectionOutput = null;
if (e.isPopupTrigger()) {
showPopup(e);
}
repaint();
}
public void mouseEntered(MouseEvent e) {
grabFocus();
}
public void mouseExited(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
Point2D pt = inverseViewTransformPoint(e.getPoint());
// Panning the view has the first priority.
if (isSpacePressed) {
// When panning the view use the original mouse point, not the one affected by the view transform.
Point2D offset = minPoint(e.getPoint(), dragStartPoint);
setViewTransform(viewX + offset.getX(), viewY + offset.getY(), viewScale);
dragStartPoint = e.getPoint();
repaint();
return;
}
if (connectionOutput != null) {
repaint();
connectionInput = getInputPortAt(pt);
connectionPoint = pt;
overOutput = getNodeWithOutputPortAt(pt);
overInput = getInputPortAt(pt);
}
if (startDragging) {
startDragging = false;
Node pressedNode = getNodeAt(pt);
if (pressedNode != null) {
if (selectedNodes.isEmpty() || !selectedNodes.contains(pressedNode.getName())) {
singleSelect(pressedNode);
}
isDraggingNodes = true;
dragPositions = selectedNodePositions();
dragStartPoint = pt;
} else {
isDraggingNodes = false;
}
}
if (isDraggingNodes) {
Point2D offset = minPoint(pt, dragStartPoint);
int gridX = (int) Math.round(offset.getX() / GRID_CELL_SIZE);
int gridY = (int) Math.round(offset.getY() / (float) GRID_CELL_SIZE);
for (String name : selectedNodes) {
nodebox.graphics.Point originalPosition = dragPositions.get(name);
nodebox.graphics.Point newPosition = originalPosition.moved(gridX, gridY);
getDocument().setNodePosition(findNodeWithName(name), newPosition);
}
}
if (isDragSelecting) {
dragCurrentPoint = pt;
Rectangle r = dragSelectRect();
selectedNodes.clear();
for (Node node : getNodes()) {
if (r.intersects(nodeRect(node))) {
selectedNodes.add(node.getName());
}
}
repaint();
}
}
public void mouseMoved(MouseEvent e) {
Point2D pt = inverseViewTransformPoint(e.getPoint());
overOutput = getNodeWithOutputPortAt(pt);
overInput = getInputPortAt(pt);
// It is probably very inefficient to repaint the view every time the mouse moves.
repaint();
}
public void mouseWheelMoved(MouseWheelEvent e) {
double scaleDelta = 1F - e.getWheelRotation() / 10F;
double newViewScale = viewScale * scaleDelta;
if (newViewScale < MIN_ZOOM) {
scaleDelta = MIN_ZOOM / viewScale;
} else if (newViewScale > MAX_ZOOM) {
scaleDelta = MAX_ZOOM / viewScale;
}
double vx = viewX - (e.getX() - viewX) * (scaleDelta - 1);
double vy = viewY - (e.getY() - viewY) * (scaleDelta - 1);
setViewTransform(vx, vy, viewScale * scaleDelta);
repaint();
}
private void showPopup(MouseEvent e) {
Point pt = e.getPoint();
NodePort nodePort = getInputPortAt(inverseViewTransformPoint(pt));
if (nodePort != null) {
JPopupMenu pMenu = new JPopupMenu();
pMenu.add(new PublishAction(nodePort));
if (findNodeWithName(nodePort.getNode()).hasPublishedInput(nodePort.getPort()))
pMenu.add(new GoToPortAction(nodePort));
pMenu.show(this, e.getX(), e.getY());
} else {
Node pressedNode = getNodeAt(inverseViewTransformPoint(pt));
if (pressedNode != null) {
nodeMenuLocation = pt;
nodeMenu.show(this, e.getX(), e.getY());
} else {
networkMenuLocation = pt;
networkMenu.show(this, e.getX(), e.getY());
}
}
}
private ImmutableMap<String, nodebox.graphics.Point> selectedNodePositions() {
ImmutableMap.Builder<String, nodebox.graphics.Point> b = ImmutableMap.builder();
for (String nodeName : selectedNodes) {
b.put(nodeName, findNodeWithName(nodeName).getPosition());
}
return b.build();
}
private Point2D inverseViewTransformPoint(Point p) {
Point2D pt = new Point2D.Double(p.getX(), p.getY());
return getInverseViewTransform().transform(pt, null);
}
private Point2D minPoint(Point2D a, Point2D b) {
return new Point2D.Double(a.getX() - b.getX(), a.getY() - b.getY());
}
private class NewNodeAction extends AbstractAction {
private NewNodeAction() {
super("New Node");
}
public void actionPerformed(ActionEvent e) {
Point gridPoint = pointToGridPoint(networkMenuLocation);
getDocument().showNodeSelectionDialog(gridPoint);
}
}
private class ResetViewAction extends AbstractAction {
private ResetViewAction() {
super("Reset View");
}
public void actionPerformed(ActionEvent e) {
resetViewTransform();
}
}
private class GoUpAction extends AbstractAction {
private GoUpAction() {
super("Go Up");
}
public void actionPerformed(ActionEvent e) {
goUp();
}
}
private class PublishAction extends AbstractAction {
private NodePort nodePort;
private PublishAction(NodePort nodePort) {
super(getActiveNetwork().hasPublishedInput(nodePort.getNode(), nodePort.getPort()) ? "Unpublish" : "Publish");
this.nodePort = nodePort;
}
public void actionPerformed(ActionEvent e) {
if (getActiveNetwork().hasPublishedInput(nodePort.getNode(), nodePort.getPort())) {
unpublish();
} else {
publish();
}
}
private void unpublish() {
Port port = getActiveNetwork().getPortByChildReference(nodePort.getNode(), nodePort.getPort());
getDocument().unpublish(port.getName());
}
private void publish() {
String s = JOptionPane.showInputDialog(NetworkView.this, "Publish as:", nodePort.getPort());
if (s == null || s.length() == 0)
return;
getDocument().publish(nodePort.getNode(), nodePort.getPort(), s);
}
}
private class GoToPortAction extends AbstractAction {
private NodePort nodePort;
private GoToPortAction(NodePort nodePort) {
super("Go to Port");
this.nodePort = nodePort;
}
public void actionPerformed(ActionEvent e) {
getDocument().setActiveNetwork(Node.path(getDocument().getActiveNetworkPath(), nodePort.getNode()));
// todo: visually indicate the origin port.
// Node node = findNodeWithName(nodePort.getNode());
// Port publishedPort = node.getInput(nodePort.getPort());
// publishedPort.getChildNodeName()
// publishedPort.getChildPortName()
}
}
private class SetRenderedAction extends AbstractAction {
private SetRenderedAction() {
super("Set Rendered");
}
public void actionPerformed(ActionEvent e) {
Node node = getNodeAt(inverseViewTransformPoint(nodeMenuLocation));
document.setRenderedNode(node);
}
}
private class RenameAction extends AbstractAction {
private RenameAction() {
super("Rename");
}
public void actionPerformed(ActionEvent e) {
Node node = getNodeAt(inverseViewTransformPoint(nodeMenuLocation));
String s = JOptionPane.showInputDialog(NetworkView.this, "New name:", node.getName());
if (s == null || s.length() == 0)
return;
try {
getDocument().setNodeName(node, s);
} catch (InvalidNameException ex) {
JOptionPane.showMessageDialog(NetworkView.this, "The given name is not valid.\n" + ex.getMessage(), Application.NAME, JOptionPane.ERROR_MESSAGE);
}
}
}
private class DeleteAction extends AbstractAction {
private DeleteAction() {
super("Delete");
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0));
}
public void actionPerformed(ActionEvent e) {
deleteSelection();
}
}
private class GoInAction extends AbstractAction {
private GoInAction() {
super("Edit Children");
}
public void actionPerformed(ActionEvent e) {
Node node = getNodeAt(inverseViewTransformPoint(nodeMenuLocation));
String childPath = Node.path(getDocument().getActiveNetworkPath(), node.getName());
getDocument().setActiveNetwork(childPath);
}
}
private class GroupIntoNetworkAction extends AbstractAction {
private Point gridPoint;
private GroupIntoNetworkAction(Point gridPoint) {
super("Group into Network");
this.gridPoint = gridPoint;
}
public void actionPerformed(ActionEvent e) {
nodebox.graphics.Point position;
if (gridPoint == null)
position = getNodeAt(inverseViewTransformPoint(nodeMenuLocation)).getPosition();
else
position = new nodebox.graphics.Point(gridPoint);
getDocument().groupIntoNetwork(position);
}
}
}
| false | true | private void paintNode(Graphics2D g, Node network, Node node, BufferedImage icon, boolean selected, boolean rendered, Node connectionOutput, Port hoverInputPort, boolean hoverOutput) {
Rectangle r = nodeRect(node);
String outputType = node.getOutputType();
// Draw selection ring
if (selected) {
g.setColor(Color.WHITE);
g.fillRect(r.x, r.y, NODE_WIDTH, NODE_HEIGHT);
}
// Draw node
g.setColor(portTypeColor(outputType));
if (selected) {
g.fillRect(r.x + 2, r.y + 2, NODE_WIDTH - 4, NODE_HEIGHT - 4);
} else {
g.fillRect(r.x, r.y, NODE_WIDTH, NODE_HEIGHT);
}
// Draw render flag
if (rendered) {
g.setColor(Color.WHITE);
GeneralPath gp = new GeneralPath();
gp.moveTo(r.x + NODE_WIDTH - 2, r.y + NODE_HEIGHT - 20);
gp.lineTo(r.x + NODE_WIDTH - 2, r.y + NODE_HEIGHT - 2);
gp.lineTo(r.x + NODE_WIDTH - 20, r.y + NODE_HEIGHT - 2);
g.fill(gp);
}
// Draw input ports
g.setColor(Color.WHITE);
int portX = 0;
for (Port input : node.getInputs()) {
if (hoverInputPort == input) {
g.setColor(PORT_HOVER_COLOR);
} else {
g.setColor(portTypeColor(input.getType()));
}
// Highlight ports that match the dragged connection type
int portHeight = PORT_HEIGHT;
if (connectionOutput != null) {
if (connectionOutput.getOutputType().equals(input.getType())) {
portHeight = PORT_HEIGHT * 2;
} else {
portHeight = 1;
}
}
if (isPublished(network, node, input)) {
Point2D topLeft = inverseViewTransformPoint(new Point(4, 0));
g.setColor(portTypeColor(input.getType()));
g.setStroke(CONNECTION_STROKE);
paintConnectionLine(g, (int) topLeft.getX(), (int) topLeft.getY(), r.x + portX + 4, r.y - 2);
}
g.fillRect(r.x + portX, r.y - portHeight, PORT_WIDTH, portHeight);
portX += PORT_WIDTH + PORT_SPACING;
}
// Draw output port
if (hoverOutput && connectionOutput == null) {
g.setColor(PORT_HOVER_COLOR);
} else {
g.setColor(portTypeColor(outputType));
}
g.fillRect(r.x, r.y + NODE_HEIGHT, PORT_WIDTH, PORT_HEIGHT);
// Draw icon
g.drawImage(icon, r.x + NODE_PADDING, r.y + NODE_PADDING, NODE_ICON_SIZE, NODE_ICON_SIZE, null);
g.setColor(Color.WHITE);
g.setFont(Theme.NETWORK_FONT);
g.drawString(getShortenedName(node.getName(), 7), r.x + NODE_ICON_SIZE + NODE_PADDING * 2 + 2, r.y + 22);
}
| private void paintNode(Graphics2D g, Node network, Node node, BufferedImage icon, boolean selected, boolean rendered, Node connectionOutput, Port hoverInputPort, boolean hoverOutput) {
Rectangle r = nodeRect(node);
String outputType = node.getOutputType();
// Draw selection ring
if (selected) {
g.setColor(Color.WHITE);
g.fillRect(r.x, r.y, NODE_WIDTH, NODE_HEIGHT);
}
// Draw node
g.setColor(portTypeColor(outputType));
if (selected) {
g.fillRect(r.x + 2, r.y + 2, NODE_WIDTH - 4, NODE_HEIGHT - 4);
} else {
g.fillRect(r.x, r.y, NODE_WIDTH, NODE_HEIGHT);
}
// Draw render flag
if (rendered) {
g.setColor(Color.WHITE);
GeneralPath gp = new GeneralPath();
gp.moveTo(r.x + NODE_WIDTH - 2, r.y + NODE_HEIGHT - 20);
gp.lineTo(r.x + NODE_WIDTH - 2, r.y + NODE_HEIGHT - 2);
gp.lineTo(r.x + NODE_WIDTH - 20, r.y + NODE_HEIGHT - 2);
g.fill(gp);
}
// Draw input ports
g.setColor(Color.WHITE);
int portX = 0;
for (Port input : node.getInputs()) {
if (hoverInputPort == input) {
g.setColor(PORT_HOVER_COLOR);
} else {
g.setColor(portTypeColor(input.getType()));
}
// Highlight ports that match the dragged connection type
int portHeight = PORT_HEIGHT;
if (connectionOutput != null) {
String connectionOutputType = connectionOutput.getOutputType();
String inputType = input.getType();
if (connectionOutputType.equals(inputType) || inputType.equals(Port.TYPE_LIST)) {
portHeight = PORT_HEIGHT * 2;
} else if (TypeConversions.canBeConverted(connectionOutputType, inputType)) {
portHeight = PORT_HEIGHT - 1;
} else {
portHeight = 1;
}
}
if (isPublished(network, node, input)) {
Point2D topLeft = inverseViewTransformPoint(new Point(4, 0));
g.setColor(portTypeColor(input.getType()));
g.setStroke(CONNECTION_STROKE);
paintConnectionLine(g, (int) topLeft.getX(), (int) topLeft.getY(), r.x + portX + 4, r.y - 2);
}
g.fillRect(r.x + portX, r.y - portHeight, PORT_WIDTH, portHeight);
portX += PORT_WIDTH + PORT_SPACING;
}
// Draw output port
if (hoverOutput && connectionOutput == null) {
g.setColor(PORT_HOVER_COLOR);
} else {
g.setColor(portTypeColor(outputType));
}
g.fillRect(r.x, r.y + NODE_HEIGHT, PORT_WIDTH, PORT_HEIGHT);
// Draw icon
g.drawImage(icon, r.x + NODE_PADDING, r.y + NODE_PADDING, NODE_ICON_SIZE, NODE_ICON_SIZE, null);
g.setColor(Color.WHITE);
g.setFont(Theme.NETWORK_FONT);
g.drawString(getShortenedName(node.getName(), 7), r.x + NODE_ICON_SIZE + NODE_PADDING * 2 + 2, r.y + 22);
}
|
diff --git a/sventon/src/main/java/de/berlios/sventon/web/command/ConfigCommandValidator.java b/sventon/src/main/java/de/berlios/sventon/web/command/ConfigCommandValidator.java
index cd7f3c0a..c7675f15 100644
--- a/sventon/src/main/java/de/berlios/sventon/web/command/ConfigCommandValidator.java
+++ b/sventon/src/main/java/de/berlios/sventon/web/command/ConfigCommandValidator.java
@@ -1,135 +1,135 @@
/*
* ====================================================================
* Copyright (c) 2005-2008 sventon project. All rights reserved.
*
* This software is licensed as described in the file LICENSE, which
* you should have received as part of this distribution. The terms
* are also available at http://sventon.berlios.de.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
* ====================================================================
*/
package de.berlios.sventon.web.command;
import de.berlios.sventon.appl.Instance;
import de.berlios.sventon.appl.InstanceConfiguration;
import de.berlios.sventon.repository.RepositoryFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.io.SVNRepository;
/**
* ConfigCommandValidator.
*
* @author [email protected]
* @author [email protected]
*/
public final class ConfigCommandValidator implements Validator {
/**
* Logger for this class and subclasses
*/
private final Log logger = LogFactory.getLog(getClass());
/**
* Controls whether repository connection should be tested or not.
*/
private boolean testConnection = true;
/**
* The repository factory.
*/
private RepositoryFactory repositoryFactory;
/**
* Constructor.
*/
public ConfigCommandValidator() {
}
/**
* Constructor for testing purposes.
*
* @param testConnection If <tt>false</tt> repository
* connection will not be tested.
*/
protected ConfigCommandValidator(final boolean testConnection) {
this.testConnection = testConnection;
}
/**
* {@inheritDoc}
*/
public boolean supports(final Class clazz) {
return clazz.equals(ConfigCommand.class);
}
/**
* Sets the repository factory instance.
*
* @param repositoryFactory Factory.
*/
public void setRepositoryFactory(final RepositoryFactory repositoryFactory) {
this.repositoryFactory = repositoryFactory;
}
/**
* {@inheritDoc}
*/
public void validate(final Object obj, final Errors errors) {
final ConfigCommand command = (ConfigCommand) obj;
// Validate 'repository instance name'
final String instanceName = command.getName();
if (instanceName != null) {
if (!Instance.isValidName(instanceName)) {
final String msg = "Name must be in lower case a-z and/or 0-9";
logger.warn(msg);
errors.rejectValue("name", "config.error.illegal-name", msg);
}
}
// Validate 'repositoryUrl', 'username' and 'password'
final String repositoryUrl = command.getRepositoryUrl();
if (repositoryUrl != null) {
final String trimmedURL = repositoryUrl.trim();
SVNURL url = null;
try {
url = SVNURL.parseURIDecoded(trimmedURL);
} catch (SVNException ex) {
final String msg = "Invalid repository URL!";
logger.warn(msg);
errors.rejectValue("repositoryUrl", "config.error.illegal-url", msg);
}
if (url != null && testConnection) {
logger.info("Testing repository connection");
final InstanceConfiguration configuration = new InstanceConfiguration(instanceName);
configuration.setRepositoryUrl(trimmedURL);
configuration.setUid(command.isEnableAccessControl() ?
command.getConnectionTestUid() : command.getUid());
configuration.setPwd(command.isEnableAccessControl() ?
command.getConnectionTestPwd() : command.getPwd());
SVNRepository repository = null;
try {
repository = repositoryFactory.getRepository(configuration.getSVNURL(), configuration.getUid(), configuration.getPwd());
repository.testConnection();
} catch (SVNException e) {
logger.warn("Unable to connect to repository", e);
errors.rejectValue("repositoryUrl", "config.error.connection-error",
- "Unable to connect to repository. Check URL, user name and password.");
+ "Unable to connect to repository [" + trimmedURL + "]. Check URL, user name and password.");
} finally {
if (repository != null) {
repository.closeSession();
}
}
}
}
}
}
| true | true | public void validate(final Object obj, final Errors errors) {
final ConfigCommand command = (ConfigCommand) obj;
// Validate 'repository instance name'
final String instanceName = command.getName();
if (instanceName != null) {
if (!Instance.isValidName(instanceName)) {
final String msg = "Name must be in lower case a-z and/or 0-9";
logger.warn(msg);
errors.rejectValue("name", "config.error.illegal-name", msg);
}
}
// Validate 'repositoryUrl', 'username' and 'password'
final String repositoryUrl = command.getRepositoryUrl();
if (repositoryUrl != null) {
final String trimmedURL = repositoryUrl.trim();
SVNURL url = null;
try {
url = SVNURL.parseURIDecoded(trimmedURL);
} catch (SVNException ex) {
final String msg = "Invalid repository URL!";
logger.warn(msg);
errors.rejectValue("repositoryUrl", "config.error.illegal-url", msg);
}
if (url != null && testConnection) {
logger.info("Testing repository connection");
final InstanceConfiguration configuration = new InstanceConfiguration(instanceName);
configuration.setRepositoryUrl(trimmedURL);
configuration.setUid(command.isEnableAccessControl() ?
command.getConnectionTestUid() : command.getUid());
configuration.setPwd(command.isEnableAccessControl() ?
command.getConnectionTestPwd() : command.getPwd());
SVNRepository repository = null;
try {
repository = repositoryFactory.getRepository(configuration.getSVNURL(), configuration.getUid(), configuration.getPwd());
repository.testConnection();
} catch (SVNException e) {
logger.warn("Unable to connect to repository", e);
errors.rejectValue("repositoryUrl", "config.error.connection-error",
"Unable to connect to repository. Check URL, user name and password.");
} finally {
if (repository != null) {
repository.closeSession();
}
}
}
}
}
| public void validate(final Object obj, final Errors errors) {
final ConfigCommand command = (ConfigCommand) obj;
// Validate 'repository instance name'
final String instanceName = command.getName();
if (instanceName != null) {
if (!Instance.isValidName(instanceName)) {
final String msg = "Name must be in lower case a-z and/or 0-9";
logger.warn(msg);
errors.rejectValue("name", "config.error.illegal-name", msg);
}
}
// Validate 'repositoryUrl', 'username' and 'password'
final String repositoryUrl = command.getRepositoryUrl();
if (repositoryUrl != null) {
final String trimmedURL = repositoryUrl.trim();
SVNURL url = null;
try {
url = SVNURL.parseURIDecoded(trimmedURL);
} catch (SVNException ex) {
final String msg = "Invalid repository URL!";
logger.warn(msg);
errors.rejectValue("repositoryUrl", "config.error.illegal-url", msg);
}
if (url != null && testConnection) {
logger.info("Testing repository connection");
final InstanceConfiguration configuration = new InstanceConfiguration(instanceName);
configuration.setRepositoryUrl(trimmedURL);
configuration.setUid(command.isEnableAccessControl() ?
command.getConnectionTestUid() : command.getUid());
configuration.setPwd(command.isEnableAccessControl() ?
command.getConnectionTestPwd() : command.getPwd());
SVNRepository repository = null;
try {
repository = repositoryFactory.getRepository(configuration.getSVNURL(), configuration.getUid(), configuration.getPwd());
repository.testConnection();
} catch (SVNException e) {
logger.warn("Unable to connect to repository", e);
errors.rejectValue("repositoryUrl", "config.error.connection-error",
"Unable to connect to repository [" + trimmedURL + "]. Check URL, user name and password.");
} finally {
if (repository != null) {
repository.closeSession();
}
}
}
}
}
|
diff --git a/source/de/tuclausthal/submissioninterface/servlets/view/ShowLectureStudentView.java b/source/de/tuclausthal/submissioninterface/servlets/view/ShowLectureStudentView.java
index a64c6ea..09f2d3a 100644
--- a/source/de/tuclausthal/submissioninterface/servlets/view/ShowLectureStudentView.java
+++ b/source/de/tuclausthal/submissioninterface/servlets/view/ShowLectureStudentView.java
@@ -1,92 +1,91 @@
/*
* Copyright 2009 Sven Strickroth <[email protected]>
*
* This file is part of the SubmissionInterface.
*
* SubmissionInterface is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* SubmissionInterface 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 SubmissionInterface. If not, see <http://www.gnu.org/licenses/>.
*/
package de.tuclausthal.submissioninterface.servlets.view;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import de.tuclausthal.submissioninterface.authfilter.SessionAdapter;
import de.tuclausthal.submissioninterface.persistence.dao.DAOFactory;
import de.tuclausthal.submissioninterface.persistence.dao.ParticipationDAOIf;
import de.tuclausthal.submissioninterface.persistence.datamodel.Lecture;
import de.tuclausthal.submissioninterface.persistence.datamodel.Participation;
import de.tuclausthal.submissioninterface.persistence.datamodel.ParticipationRole;
import de.tuclausthal.submissioninterface.persistence.datamodel.Submission;
import de.tuclausthal.submissioninterface.persistence.datamodel.Task;
import de.tuclausthal.submissioninterface.template.Template;
import de.tuclausthal.submissioninterface.template.TemplateFactory;
import de.tuclausthal.submissioninterface.util.Util;
/**
* View-Servlet for displaying a lecture in student view
* @author Sven Strickroth
*/
public class ShowLectureStudentView extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Template template = TemplateFactory.getTemplate(request, response);
PrintWriter out = response.getWriter();
Participation participation = (Participation) request.getAttribute("participation");
Lecture lecture = participation.getLecture();
SessionAdapter sessionAdapter = new SessionAdapter(request);
- ParticipationDAOIf participationDAO = DAOFactory.ParticipationDAOIf();
// list all tasks for a lecture
template.printTemplateHeader(lecture);
// todo: wenn keine abrufbaren tasks da sind, nichts anzeigen
Iterator<Task> taskIterator = lecture.getTasks().iterator();
if (taskIterator.hasNext()) {
out.println("<table class=border>");
out.println("<tr>");
out.println("<th>Aufgabe</th>");
out.println("<th>Max. Punkte</th>");
out.println("<th>Meine Punkte</th>");
out.println("</tr>");
while (taskIterator.hasNext()) {
Task task = taskIterator.next();
if (task.getStart().before(Util.correctTimezone(new Date())) || participation.getRoleType().compareTo(ParticipationRole.TUTOR) >= 0) {
out.println("<tr>");
out.println("<td><a href=\"" + response.encodeURL("ShowTask?taskid=" + task.getTaskid()) + "\">" + Util.mknohtml(task.getTitle()) + "</a></td>");
out.println("<td class=points>" + task.getMaxPoints() + "</td>");
Submission submission = DAOFactory.SubmissionDAOIf().getSubmission(task, sessionAdapter.getUser());
- if (submission != null && submission.getPoints() != null && submission.getTask().getShowPoints().after(Util.correctTimezone(new Date()))) {
+ if (submission != null && submission.getPoints() != null && submission.getTask().getShowPoints().before(Util.correctTimezone(new Date()))) {
out.println("<td class=points>" + submission.getPoints().getPoints() + "</td>");
} else {
out.println("<td class=points>n/a</td>");
}
out.println("</tr>");
}
}
out.println("</table>");
} else {
out.println("<div class=mid>keine Aufgaben gefunden.</div>");
}
template.printTemplateFooter();
}
}
| false | true | public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Template template = TemplateFactory.getTemplate(request, response);
PrintWriter out = response.getWriter();
Participation participation = (Participation) request.getAttribute("participation");
Lecture lecture = participation.getLecture();
SessionAdapter sessionAdapter = new SessionAdapter(request);
ParticipationDAOIf participationDAO = DAOFactory.ParticipationDAOIf();
// list all tasks for a lecture
template.printTemplateHeader(lecture);
// todo: wenn keine abrufbaren tasks da sind, nichts anzeigen
Iterator<Task> taskIterator = lecture.getTasks().iterator();
if (taskIterator.hasNext()) {
out.println("<table class=border>");
out.println("<tr>");
out.println("<th>Aufgabe</th>");
out.println("<th>Max. Punkte</th>");
out.println("<th>Meine Punkte</th>");
out.println("</tr>");
while (taskIterator.hasNext()) {
Task task = taskIterator.next();
if (task.getStart().before(Util.correctTimezone(new Date())) || participation.getRoleType().compareTo(ParticipationRole.TUTOR) >= 0) {
out.println("<tr>");
out.println("<td><a href=\"" + response.encodeURL("ShowTask?taskid=" + task.getTaskid()) + "\">" + Util.mknohtml(task.getTitle()) + "</a></td>");
out.println("<td class=points>" + task.getMaxPoints() + "</td>");
Submission submission = DAOFactory.SubmissionDAOIf().getSubmission(task, sessionAdapter.getUser());
if (submission != null && submission.getPoints() != null && submission.getTask().getShowPoints().after(Util.correctTimezone(new Date()))) {
out.println("<td class=points>" + submission.getPoints().getPoints() + "</td>");
} else {
out.println("<td class=points>n/a</td>");
}
out.println("</tr>");
}
}
out.println("</table>");
} else {
out.println("<div class=mid>keine Aufgaben gefunden.</div>");
}
template.printTemplateFooter();
}
| public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Template template = TemplateFactory.getTemplate(request, response);
PrintWriter out = response.getWriter();
Participation participation = (Participation) request.getAttribute("participation");
Lecture lecture = participation.getLecture();
SessionAdapter sessionAdapter = new SessionAdapter(request);
// list all tasks for a lecture
template.printTemplateHeader(lecture);
// todo: wenn keine abrufbaren tasks da sind, nichts anzeigen
Iterator<Task> taskIterator = lecture.getTasks().iterator();
if (taskIterator.hasNext()) {
out.println("<table class=border>");
out.println("<tr>");
out.println("<th>Aufgabe</th>");
out.println("<th>Max. Punkte</th>");
out.println("<th>Meine Punkte</th>");
out.println("</tr>");
while (taskIterator.hasNext()) {
Task task = taskIterator.next();
if (task.getStart().before(Util.correctTimezone(new Date())) || participation.getRoleType().compareTo(ParticipationRole.TUTOR) >= 0) {
out.println("<tr>");
out.println("<td><a href=\"" + response.encodeURL("ShowTask?taskid=" + task.getTaskid()) + "\">" + Util.mknohtml(task.getTitle()) + "</a></td>");
out.println("<td class=points>" + task.getMaxPoints() + "</td>");
Submission submission = DAOFactory.SubmissionDAOIf().getSubmission(task, sessionAdapter.getUser());
if (submission != null && submission.getPoints() != null && submission.getTask().getShowPoints().before(Util.correctTimezone(new Date()))) {
out.println("<td class=points>" + submission.getPoints().getPoints() + "</td>");
} else {
out.println("<td class=points>n/a</td>");
}
out.println("</tr>");
}
}
out.println("</table>");
} else {
out.println("<div class=mid>keine Aufgaben gefunden.</div>");
}
template.printTemplateFooter();
}
|
diff --git a/dspace/src/org/dspace/browse/Browse.java b/dspace/src/org/dspace/browse/Browse.java
index 744fd2f67..3a3f0e651 100644
--- a/dspace/src/org/dspace/browse/Browse.java
+++ b/dspace/src/org/dspace/browse/Browse.java
@@ -1,2234 +1,2234 @@
/*
* Browse.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* 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
* 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.dspace.browse;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.WeakHashMap;
import org.apache.log4j.Logger;
import org.dspace.content.Collection;
import org.dspace.content.Community;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.content.ItemComparator;
import org.dspace.content.ItemIterator;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.storage.rdbms.DatabaseManager;
import org.dspace.storage.rdbms.TableRow;
/**
* API for Browsing Items in DSpace by title, author, or date. Browses only
* return archived Items.
*
* @author Peter Breton
* @version $Revision$
*/
public class Browse
{
// Browse types
static final int AUTHORS_BROWSE = 0;
static final int ITEMS_BY_TITLE_BROWSE = 1;
static final int ITEMS_BY_AUTHOR_BROWSE = 2;
static final int ITEMS_BY_DATE_BROWSE = 3;
static final int SUBJECTS_BROWSE = 4;
static final int ITEMS_BY_SUBJECT_BROWSE = 5;
/** Log4j log */
private static Logger log = Logger.getLogger(Browse.class);
/**
* Constructor
*/
private Browse()
{
}
/**
* Return distinct Authors in the given scope. Author refers to a Dublin
* Core field with element <em>contributor</em> and qualifier
* <em>author</em>.
*
* <p>
* Results are returned in alphabetical order.
* </p>
*
* @param scope
* The BrowseScope
* @return A BrowseInfo object, the results of the browse
* @exception SQLException
* If a database error occurs
*/
public static BrowseInfo getAuthors(BrowseScope scope) throws SQLException
{
scope.setBrowseType(AUTHORS_BROWSE);
scope.setAscending(true);
scope.setSortByTitle(null);
return doBrowse(scope);
}
/**
* Return distinct Subjects in the given scope. Subjects refers to a Dublin
* Core field with element <em>subject</em> and qualifier
* <em>*</em>.
*
* <p>
* Results are returned in alphabetical order.
* </p>
*
* @param scope
* The BrowseScope
* @return A BrowseInfo object, the results of the browse
* @exception SQLException
* If a database error occurs
*/
public static BrowseInfo getSubjects(BrowseScope scope) throws SQLException
{
scope.setBrowseType(SUBJECTS_BROWSE);
scope.setAscending(true);
scope.setSortByTitle(null);
return doBrowse(scope);
}
/**
* Return Items indexed by title in the given scope. Title refers to a
* Dublin Core field with element <em>title</em> and no qualifier.
*
* <p>
* Results are returned in alphabetical order; that is, the Item with the
* title which is first in alphabetical order will be returned first.
* </p>
*
* @param scope
* The BrowseScope
* @return A BrowseInfo object, the results of the browse
* @exception SQLException
* If a database error occurs
*/
public static BrowseInfo getItemsByTitle(BrowseScope scope)
throws SQLException
{
scope.setBrowseType(ITEMS_BY_TITLE_BROWSE);
scope.setAscending(true);
scope.setSortByTitle(null);
return doBrowse(scope);
}
/**
* Return Items indexed by date in the given scope. Date refers to a Dublin
* Core field with element <em>date</em> and qualifier <em>issued</em>.
*
* <p>
* If oldestfirst is true, the dates returned are the ones after the focus,
* ordered from earliest to latest. Otherwise the dates are the ones before
* the focus, and ordered from latest to earliest. For example:
* </p>
*
* <p>
* For example, if the focus is <em>1995</em>, and oldestfirst is true,
* the results might look like this:
* </p>
*
* <code>1993, 1994, 1995 (the focus), 1996, 1997.....</code>
*
* <p>
* While if the focus is <em>1995</em>, and oldestfirst is false, the
* results would be:
* </p>
*
* <code>1997, 1996, 1995 (the focus), 1994, 1993 .....</code>
*
* @param scope
* The BrowseScope
* @param oldestfirst
* If true, the dates returned are the ones after focus, ordered
* from earliest to latest; otherwise the dates are the ones
* before focus, ordered from latest to earliest.
* @return A BrowseInfo object, the results of the browse
* @exception SQLException
* If a database error occurs
*/
public static BrowseInfo getItemsByDate(BrowseScope scope,
boolean oldestfirst) throws SQLException
{
scope.setBrowseType(ITEMS_BY_DATE_BROWSE);
scope.setAscending(oldestfirst);
scope.setSortByTitle(null);
return doBrowse(scope);
}
/**
* <p>
* Return Items in the given scope by the author (exact match). The focus of
* the BrowseScope is the author to use; using a BrowseScope without a focus
* causes an IllegalArgumentException to be thrown.
* </p>
*
* <p>
* Author refers to a Dublin Core field with element <em>contributor</em>
* and qualifier <em>author</em>.
* </p>
*
* @param scope
* The BrowseScope
* @param sortByTitle
* If true, the returned items are sorted by title; otherwise
* they are sorted by date issued.
* @return A BrowseInfo object, the results of the browse
* @exception SQLException
* If a database error occurs
*/
public static BrowseInfo getItemsByAuthor(BrowseScope scope,
boolean sortByTitle) throws SQLException
{
if (!scope.hasFocus())
{
throw new IllegalArgumentException(
"Must specify an author for getItemsByAuthor");
}
if (!(scope.getFocus() instanceof String))
{
throw new IllegalArgumentException(
"The focus for getItemsByAuthor must be a String");
}
scope.setBrowseType(ITEMS_BY_AUTHOR_BROWSE);
scope.setAscending(true);
scope.setSortByTitle(sortByTitle ? Boolean.TRUE : Boolean.FALSE);
scope.setTotalAll();
return doBrowse(scope);
}
/**
* <p>
* Return Items in the given scope by the subject (exact match). The focus of
* the BrowseScope is the subject to use; using a BrowseScope without a focus
* causes an IllegalArgumentException to be thrown.
* </p>
*
* <p>
* Subject refers to a Dublin Core field with element <em>subject</em>
* and qualifier <em>*</em>.
* </p>
*
* @param scope
* The BrowseScope
* @param sortByTitle
* If true, the returned items are sorted by title; otherwise
* they are sorted by date issued.
* @return A BrowseInfo object, the results of the browse
* @exception SQLException
* If a database error occurs
*/
public static BrowseInfo getItemsBySubject(BrowseScope scope,
boolean sortByTitle) throws SQLException
{
if (!scope.hasFocus())
{
throw new IllegalArgumentException(
"Must specify a subject for getItemsBySubject");
}
if (!(scope.getFocus() instanceof String))
{
throw new IllegalArgumentException(
"The focus for getItemsBySubject must be a String");
}
scope.setBrowseType(ITEMS_BY_SUBJECT_BROWSE);
scope.setAscending(true);
scope.setSortByTitle(sortByTitle ? Boolean.TRUE : Boolean.FALSE);
scope.setTotalAll();
return doBrowse(scope);
}
/**
* Returns the last items submitted to DSpace in the given scope.
*
* @param scope
* The Browse Scope
* @return A List of Items submitted
* @exception SQLException
* If a database error occurs
*/
public static List getLastSubmitted(BrowseScope scope) throws SQLException
{
Context context = scope.getContext();
String sql = getLastSubmittedQuery(scope);
if (log.isDebugEnabled())
{
log.debug("SQL for last submitted is \"" + sql + "\"");
}
List results = DatabaseManager.query(context, sql).toList();
return getLastSubmittedResults(context, results);
}
/**
* Return the SQL used to determine the last submitted Items for scope.
*
* @param scope
* @return String query string
*/
private static String getLastSubmittedQuery(BrowseScope scope)
{
String table = getLastSubmittedTable(scope);
String query = "SELECT * FROM " + table
+ getScopeClause(scope, "where")
+ " ORDER BY date_accessioned DESC";
if (!scope.hasNoLimit())
{
if ("oracle".equals(ConfigurationManager.getProperty("db.name")))
{
// Oracle version of LIMIT...OFFSET - must use a sub-query and
// ROWNUM
query = "SELECT * FROM (" + query + ") WHERE ROWNUM <="
+ scope.getTotal();
}
else
{
// postgres, use LIMIT
query = query + " LIMIT " + scope.getTotal();
}
}
return query;
}
/**
* Return the name of the Browse index table to query for last submitted
* items in the given scope.
*
* @param scope
* @return name of table
*/
private static String getLastSubmittedTable(BrowseScope scope)
{
if (scope.isCommunityScope())
{
return "CommunityItemsByDateAccession";
}
else if (scope.isCollectionScope())
{
return "CollectionItemsByDateAccession";
}
return "ItemsByDateAccessioned";
}
/**
* Transform the query results into a List of Items.
*
* @param context
* @param results
* @return list of items
* @throws SQLException
*/
private static List getLastSubmittedResults(Context context, List results)
throws SQLException
{
if ((results == null) || (results.isEmpty()))
{
return Collections.EMPTY_LIST;
}
List items = new ArrayList();
// FIXME This seems like a very common need, so might
// be factored out at some point.
for (Iterator iterator = results.iterator(); iterator.hasNext();)
{
TableRow row = (TableRow) iterator.next();
Item item = Item.find(context, row.getIntColumn("item_id"));
items.add(item);
}
return items;
}
////////////////////////////////////////
// Index maintainence methods
////////////////////////////////////////
/**
* This method should be called whenever an item is removed.
*
* @param context
* The current DSpace context
* @param id
* The id of the item which has been removed
* @exception SQLException
* If a database error occurs
*/
public static void itemRemoved(Context context, int id) throws SQLException
{
String sql = "delete from {0} where item_id = " + id;
String[] browseTables = BrowseTables.tables();
for (int i = 0; i < browseTables.length; i++)
{
String query = MessageFormat.format(sql,
new String[] { browseTables[i] });
DatabaseManager.updateQuery(context, query);
}
}
/**
* This method should be called whenever an item has changed. Changes
* include:
*
* <ul>
* <li>DC values are added, removed, or modified
* <li>the value of the in_archive flag changes
* </ul>
*
* @param context -
* The database context
* @param item -
* The item which has been added
* @exception SQLException -
* If a database error occurs
*/
public static void itemChanged(Context context, Item item)
throws SQLException
{
// This is a bit heavy-weight, but without knowing what
// changed, it's easiest just to replace the values
// en masse.
itemRemoved(context, item.getID());
if (!item.isArchived())
{
return;
}
itemAdded(context, item);
}
/**
* This method should be called whenever an item is added.
*
* @param context
* The current DSpace context
* @param item
* The item which has been added
* @exception SQLException
* If a database error occurs
*/
public static void itemAdded(Context context, Item item)
throws SQLException
{
// add all parent communities to communities2item table
Community[] parents = item.getCommunities();
for (int j = 0; j < parents.length; j++)
{
TableRow row = DatabaseManager.create(context, "Communities2Item");
row.setColumn("item_id", item.getID());
row.setColumn("community_id", parents[j].getID());
DatabaseManager.update(context, row);
}
// get the metadata fields to index in the title and date tables
// get the date, title and author fields
String dateField = ConfigurationManager.getProperty("webui.browse.index.date");
if (dateField == null)
{
dateField = "dc.date.issued";
}
String titleField = ConfigurationManager.getProperty("webui.browse.index.title");
if (titleField == null)
{
titleField = "dc.title";
}
String authorField = ConfigurationManager.getProperty("webui.browse.index.author");
if (authorField == null)
{
authorField = "dc.contributor.*";
}
String subjectField = ConfigurationManager.getProperty("webui.browse.index.subject");
if (subjectField == null)
{
subjectField = "dc.subject.*";
}
// get the DC values for each of these fields
DCValue[] titleArray = getMetadataField(item, titleField);
DCValue[] dateArray = getMetadataField(item, dateField);
DCValue[] authorArray = getMetadataField(item, authorField);
DCValue[] subjectArray = getMetadataField(item, subjectField);
// now build the data map
Map table2dc = new HashMap();
table2dc.put("ItemsByTitle", titleArray);
table2dc.put("ItemsByAuthor", authorArray);
table2dc.put("ItemsByDate", dateArray);
table2dc.put("ItemsByDateAccessioned", item.getDC("date",
"accessioned", Item.ANY));
table2dc.put("ItemsBySubject", subjectArray);
for (Iterator iterator = table2dc.keySet().iterator(); iterator
.hasNext();)
{
String table = (String) iterator.next();
DCValue[] dc = (DCValue[]) table2dc.get(table);
for (int i = 0; i < dc.length; i++)
{
TableRow row = DatabaseManager.create(context, table);
row.setColumn("item_id", item.getID());
String value = dc[i].value;
if ("ItemsByDateAccessioned".equals(table))
{
row.setColumn("date_accessioned", value);
}
else if ("ItemsByDate".equals(table))
{
row.setColumn("date_issued", value);
}
else if ("ItemsByAuthor".equals(table))
{
// author name, and normalized sorting name
// (which for now is simple lower-case)
row.setColumn("author", value);
row.setColumn("sort_author", value.toLowerCase());
}
else if ("ItemsByTitle".equals(table))
{
String title = NormalizedTitle.normalize(value,
dc[i].language);
row.setColumn("title", value);
row.setColumn("sort_title", title.toLowerCase());
}
else if ("ItemsBySubject".equals(table))
{
row.setColumn("subject", value);
row.setColumn("sort_subject", value.toLowerCase());
}
DatabaseManager.update(context, row);
}
}
}
/**
* Index all items in DSpace. This method may be resource-intensive.
*
* @param context
* Current DSpace context
* @return The number of items indexed.
* @exception SQLException
* If a database error occurs
*/
public static int indexAll(Context context) throws SQLException
{
indexRemoveAll(context);
int count = 0;
ItemIterator iterator = Item.findAll(context);
while (iterator.hasNext())
{
itemAdded(context, iterator.next());
count++;
}
return count;
}
/**
* Remove all items in DSpace from the Browse index.
*
* @param context
* Current DSpace context
* @return The number of items removed.
* @exception SQLException
* If a database error occurs
*/
public static int indexRemoveAll(Context context) throws SQLException
{
int total = 0;
String[] browseTables = BrowseTables.tables();
for (int i = 0; i < browseTables.length; i++)
{
String sql = "delete from " + browseTables[i];
total += DatabaseManager.updateQuery(context, sql);
}
return total;
}
////////////////////////////////////////
// Other methods
////////////////////////////////////////
/**
* Return the normalized form of title.
*
* @param title
* @param lang
* @return title
*/
public static String getNormalizedTitle(String title, String lang)
{
return NormalizedTitle.normalize(title, lang);
}
////////////////////////////////////////
// Private methods
////////////////////////////////////////
private static DCValue[] getMetadataField(Item item, String md)
{
StringTokenizer dcf = new StringTokenizer(md, ".");
String[] tokens = { "", "", "" };
int i = 0;
while(dcf.hasMoreTokens())
{
tokens[i] = dcf.nextToken().toLowerCase().trim();
i++;
}
String schema = tokens[0];
String element = tokens[1];
String qualifier = tokens[2];
DCValue[] values;
if ("*".equals(qualifier))
{
values = item.getMetadata(schema, element, Item.ANY, Item.ANY);
}
else if ("".equals(qualifier))
{
values = item.getMetadata(schema, element, null, Item.ANY);
}
else
{
values = item.getMetadata(schema, element, qualifier, Item.ANY);
}
return values;
}
/**
* Workhorse method for browse functionality.
*
* @param scope
* @return BrowseInfo
* @throws SQLException
*/
private static BrowseInfo doBrowse(BrowseScope scope) throws SQLException
{
// Check for a cached browse
BrowseInfo cachedInfo = BrowseCache.get(scope);
if (cachedInfo != null)
{
return cachedInfo;
}
// Run the Browse queries
// If the focus is an Item, this returns the value
String itemValue = getItemValue(scope);
List results = new ArrayList();
results.addAll(getResultsBeforeFocus(scope, itemValue));
int beforeFocus = results.size();
results.addAll(getResultsAfterFocus(scope, itemValue, beforeFocus));
// Find out the total in the index, and the number of
// matches for the query
int total = countTotalInIndex(scope, results.size());
int matches = countMatches(scope, itemValue, total, results.size());
if (log.isDebugEnabled())
{
log.debug("Number of matches " + matches);
}
int position = getPosition(total, matches, beforeFocus);
sortResults(scope, results);
BrowseInfo info = new BrowseInfo(results, position, total,
beforeFocus);
logInfo(info);
BrowseCache.add(scope, info);
return info;
}
/**
* If focus refers to an Item, return a value for the item (its title,
* author, accession date, etc). Otherwise return null.
*
* In general, the queries for these values look like this: select
* max(date_issued) from ItemsByDate where item_id = 7;
*
* The max operator ensures that only one value is returned.
*
* If limiting to a community or collection, we add a clause like:
* community_id = 7 collection_id = 201
*
* @param scope
* @return desired value for the item
* @throws SQLException
*/
protected static String getItemValue(BrowseScope scope) throws SQLException
{
if (!scope.focusIsItem())
{
return null;
}
PreparedStatement statement = null;
ResultSet results = null;
try
{
String tablename = BrowseTables.getTable(scope);
String column = BrowseTables.getValueColumn(scope);
String itemValueQuery = new StringBuffer().append("select ")
.append("max(").append(column).append(") from ").append(
tablename).append(" where ").append(" item_id = ")
.append(scope.getFocusItemId()).append(
getScopeClause(scope, "and")).toString();
statement = createStatement(scope, itemValueQuery);
results = statement.executeQuery();
String itemValue = results.next() ? results.getString(1) : null;
if (log.isDebugEnabled())
{
log.debug("Subquery value is " + itemValue);
}
return itemValue;
}
finally
{
if (statement != null)
{
statement.close();
}
if (results != null)
{
results.close();
}
}
}
/**
* Run a database query and return results before the focus.
*
* @param scope
* The Browse Scope
* @param itemValue
* If the focus is an Item, this is its value in the index (its
* title, author, etc).
* @return list of Item results
* @throws SQLException
*/
protected static List getResultsBeforeFocus(BrowseScope scope,
String itemValue) throws SQLException
{
// Starting from beginning of index
if (!scope.hasFocus())
{
return Collections.EMPTY_LIST;
}
// No previous results desired
if (scope.getNumberBefore() == 0)
{
return Collections.EMPTY_LIST;
}
// ItemsByAuthor. Since this is an exact match, it
// does not make sense to return values before the
// query.
if (scope.getBrowseType() == ITEMS_BY_AUTHOR_BROWSE
|| scope.getBrowseType() == ITEMS_BY_SUBJECT_BROWSE)
{
return Collections.EMPTY_LIST;
}
PreparedStatement statement = createSql(scope, itemValue, false, false);
List qresults = DatabaseManager.queryPrepared(statement).toList();
int numberDesired = scope.getNumberBefore();
List results = getResults(scope, qresults, numberDesired);
if (!results.isEmpty())
{
Collections.reverse(results);
}
return results;
}
/**
* Run a database query and return results after the focus.
*
* @param scope
* The Browse Scope
* @param itemValue
* If the focus is an Item, this is its value in the index (its
* title, author, etc).
* @param count
* @return list of results after the focus
* @throws SQLException
*/
protected static List getResultsAfterFocus(BrowseScope scope,
String itemValue, int count) throws SQLException
{
// No results desired
if (scope.getTotal() == 0)
{
return Collections.EMPTY_LIST;
}
PreparedStatement statement = createSql(scope, itemValue, true, false);
List qresults = DatabaseManager.queryPrepared(statement).toList();
// The number of results we want is either -1 (everything)
// or the total, less the number already retrieved.
int numberDesired = -1;
if (!scope.hasNoLimit())
{
numberDesired = Math.max(scope.getTotal() - count, 0);
}
return getResults(scope, qresults, numberDesired);
}
/*
* Return the total number of values in an index.
*
* <p> We total Authors with SQL like: select count(distinct author) from
* ItemsByAuthor; ItemsByAuthor with: select count(*) from ItemsByAuthor
* where author = ?; and every other index with: select count(*) from
* ItemsByTitle; </p>
*
* <p> If limiting to a community or collection, we add a clause like:
* community_id = 7 collection_id = 201 </p>
*/
protected static int countTotalInIndex(BrowseScope scope,
int numberOfResults) throws SQLException
{
int browseType = scope.getBrowseType();
// When finding Items by Author, it often happens that
// we find every single Item (eg, the Author only published
// 2 works, and we asked for 15), and so can skip the
// query.
if ((browseType == ITEMS_BY_AUTHOR_BROWSE)
&& (scope.hasNoLimit() || (scope.getTotal() > numberOfResults)))
{
return numberOfResults;
}
PreparedStatement statement = null;
Object obj = scope.getScope();
try
{
String table = BrowseTables.getTable(scope);
StringBuffer buffer = new StringBuffer().append("select count(")
.append(getTargetColumns(scope)).append(") from ").append(
table);
boolean hasWhere = false;
if (browseType == ITEMS_BY_AUTHOR_BROWSE)
{
hasWhere = true;
buffer.append(" where sort_author = ?");
}
if (browseType == ITEMS_BY_SUBJECT_BROWSE)
{
hasWhere = true;
buffer.append(" where sort_subject = ?");
}
String connector = hasWhere ? "and" : "where";
String sql = buffer.append(getScopeClause(scope, connector))
.toString();
if (log.isDebugEnabled())
{
log.debug("Total sql: \"" + sql + "\"");
}
statement = createStatement(scope, sql);
if (browseType == ITEMS_BY_AUTHOR_BROWSE)
{
statement.setString(1, (String) scope.getFocus());
}
if (browseType == ITEMS_BY_SUBJECT_BROWSE)
{
statement.setString(1, (String) scope.getFocus());
}
return getIntValue(statement);
}
finally
{
if (statement != null)
{
statement.close();
}
}
}
/**
* Return the number of matches for the browse scope.
*
* @param scope
* @param itemValue
* item value we're looking for
* @param totalInIndex
* FIXME ??
* @param numberOfResults
* FIXME ??
* @return number of matches
* @throws SQLException
*/
protected static int countMatches(BrowseScope scope, String itemValue,
int totalInIndex, int numberOfResults) throws SQLException
{
// Matched everything
if (numberOfResults == totalInIndex)
{
return totalInIndex;
}
// Scope matches everything in the index
// Note that this only works when the scope is all of DSpace,
// since the Community and Collection index tables
// include Items in other Communities/Collections
if ((!scope.hasFocus()) && scope.isAllDSpaceScope())
{
return totalInIndex;
}
PreparedStatement statement = null;
try {
statement = createSql(scope, itemValue, true, true);
return getIntValue(statement);
}
finally {
if(statement != null) {
try {
statement.close();
}
catch(SQLException e) {
log.error("Problem releasing statement", e);
}
}
}
}
private static int getPosition(int total, int matches, int beforeFocus)
{
// Matched everything, so position is at start (0)
if (total == matches)
{
return 0;
}
return total - matches - beforeFocus;
}
/**
* Sort the results returned from the browse if necessary. The list of
* results is sorted in-place.
*
* @param scope
* @param results
*/
private static void sortResults(BrowseScope scope, List results)
{
// Currently we only sort ItemsByAuthor, Advisor, Subjects browses
if ((scope.getBrowseType() != ITEMS_BY_AUTHOR_BROWSE)
&& (scope.getBrowseType() != ITEMS_BY_SUBJECT_BROWSE))
{
return;
}
ItemComparator ic = scope.getSortByTitle().booleanValue() ? new ItemComparator(
"title", null, Item.ANY, true)
: new ItemComparator("date", "issued", Item.ANY, true);
Collections.sort(results, ic);
}
/**
* Transform the results of the query (TableRow objects_ into a List of
* Strings (for getAuthors()) or Items (for all the other browses).
*
* @param scope
* The Browse Scope
* @param results
* The results of the query
* @param max
* The maximum number of results to return
* @return FIXME ??
* @throws SQLException
*/
private static List getResults(BrowseScope scope, List results, int max)
throws SQLException
{
if (results == null)
{
return Collections.EMPTY_LIST;
}
List theResults = new ArrayList();
boolean hasLimit = !scope.hasNoLimit();
boolean isAuthorsBrowse = scope.getBrowseType() == AUTHORS_BROWSE;
boolean isSubjectsBrowse = scope.getBrowseType() == SUBJECTS_BROWSE;
for (Iterator iterator = results.iterator(); iterator.hasNext();)
{
TableRow row = (TableRow) iterator.next();
Object theValue = null;
if (isAuthorsBrowse)
theValue = (Object) row.getStringColumn("author");
else if (isSubjectsBrowse)
theValue = (Object) row.getStringColumn("subject");
else
theValue = (Object) new Integer(row.getIntColumn("item_id"));
// Should not happen
if (theValue == null)
{
continue;
}
// Exceeded limit
if (hasLimit && (theResults.size() >= max))
{
break;
}
theResults.add(theValue);
if (log.isDebugEnabled())
{
log.debug("Adding result " + theValue);
}
}
return (isAuthorsBrowse||isSubjectsBrowse)
? theResults : toItems(scope.getContext(), theResults);
}
/**
* Create a PreparedStatement to run the correct query for scope.
*
* @param scope
* The Browse scope
* @param subqueryValue
* If the focus is an item, this is its value in the browse index
* (its title, author, date, etc). Otherwise null.
* @param after
* If true, create SQL to find the items after the focus.
* Otherwise create SQL to find the items before the focus.
* @param isCount
* If true, create SQL to count the number of matches for the
* query. Otherwise just the query.
* @return a prepared statement
* @throws SQLException
*/
private static PreparedStatement createSql(BrowseScope scope,
String subqueryValue, boolean after, boolean isCount)
throws SQLException
{
String sqli = createSqlInternal(scope, subqueryValue, isCount);
String sql = formatSql(scope, sqli, subqueryValue, after);
PreparedStatement statement = createStatement(scope, sql);
// Browses without a focus have no parameters to bind
if (scope.hasFocus())
{
String value = subqueryValue;
if (value == null && scope.getFocus() instanceof String)
{
value = (String)scope.getFocus();
}
statement.setString(1, value);
// Binds the parameter in the subquery clause
if (subqueryValue != null)
{
statement.setString(2, value);
}
}
if (log.isDebugEnabled())
{
log.debug("Created SQL \"" + sql + "\"");
}
return statement;
}
/**
* Create a SQL string to run the correct query.
*
* @param scope
* @param itemValue
* FIXME ??
* @param isCount
* @return
*/
private static String createSqlInternal(BrowseScope scope,
String itemValue, boolean isCount)
{
String tablename = BrowseTables.getTable(scope);
String column = BrowseTables.getValueColumn(scope);
int browseType = scope.getBrowseType();
StringBuffer sqlb = new StringBuffer();
sqlb.append("select ");
sqlb.append(isCount ? "count(" : "");
sqlb.append(getTargetColumns(scope));
/**
* This next bit adds another column to the query, so authors don't show
* up lower-case
*/
if ((browseType == AUTHORS_BROWSE) && !isCount)
{
sqlb.append(",sort_author");
}
if ((browseType == SUBJECTS_BROWSE) && !isCount)
{
sqlb.append(",sort_subject");
}
sqlb.append(isCount ? ")" : "");
sqlb.append(" from (SELECT DISTINCT * ");
sqlb.append(" from ");
sqlb.append(tablename);
- sqlb.append(" ) as distinct_view");
+ sqlb.append(" ) distinct_view");
// If the browse uses items (or item ids) instead of String values
// make a subquery.
// We use a separate query to make sure the subquery works correctly
// when item values are the same. (this is transactionally
// safe because we set the isolation level).
// If we're NOT searching from the start, add some clauses
boolean addedWhereClause = false;
if (scope.hasFocus())
{
String subquery = null;
if (scope.focusIsItem())
{
subquery = new StringBuffer().append(" or ( ").append(column)
.append(" = ? and item_id {0} ").append(
scope.getFocusItemId()).append(")").toString();
}
if (log.isDebugEnabled())
{
log.debug("Subquery is \"" + subquery + "\"");
}
sqlb.append(" where ").append("(").append(column).append(" {1} ")
.append("?").append(scope.focusIsItem() ? subquery : "")
.append(")");
addedWhereClause = true;
}
String connector = addedWhereClause ? " and " : " where ";
sqlb.append(getScopeClause(scope, connector));
// For counting, skip the "order by" and "limit" clauses
if (isCount)
{
return sqlb.toString();
}
// Add an order by clause -- a parameter
sqlb
.append(" order by ")
.append(column)
.append("{2}")
.append(
((scope.focusIsString() && (scope.getBrowseType() != ITEMS_BY_DATE_BROWSE))
|| (scope.getBrowseType() == AUTHORS_BROWSE) || (scope
.getBrowseType() == SUBJECTS_BROWSE)) ? ""
: ", item_id{2}");
String myquery = sqlb.toString();
// A limit on the total returned (Postgres extension)
if (!scope.hasNoLimit())
{
if ("oracle".equals(ConfigurationManager.getProperty("db.name")))
{
myquery = "SELECT * FROM (" + myquery
+ ") WHERE ROWNUM <= {3} ";
}
else
{
// postgres uses LIMIT
myquery = myquery + " LIMIT {3} ";
}
}
return myquery;
}
/**
* Format SQL according to the browse type.
*
* @param scope
* @param sql
* @param subqueryValue
* FIXME ??
* @param after
* @return
*
*
*/
private static String formatSql(BrowseScope scope, String sql,
String subqueryValue, boolean after)
{
boolean before = !after;
int browseType = scope.getBrowseType();
boolean ascending = scope.getAscending();
int numberDesired = before ? scope.getNumberBefore() : scope.getTotal();
// Search operator
// Normal case: before is less than, after is greater than or equal
String beforeOperator = "<";
String afterOperator = ">=";
// For authors, only equality is relevant
if (browseType == ITEMS_BY_AUTHOR_BROWSE)
{
afterOperator = "=";
}
if (browseType == ITEMS_BY_SUBJECT_BROWSE)
{
afterOperator = "=";
}
// Subqueries add a clause which checks for the item specifically,
// so we do not check for equality here
if (subqueryValue != null)
{
beforeOperator = "<";
afterOperator = ">";
}
if (!ascending)
{
beforeOperator = ">";
afterOperator = "<=";
}
if (browseType == ITEMS_BY_DATE_BROWSE)
{
if (!ascending)
{
beforeOperator = ">";
afterOperator = "<";
}
else
{
beforeOperator = "<";
afterOperator = ">";
}
}
String beforeSubqueryOperator = "<";
String afterSubqueryOperator = ">=";
// For authors, only equality is relevant
if (browseType == ITEMS_BY_AUTHOR_BROWSE
|| browseType == ITEMS_BY_SUBJECT_BROWSE)
{
afterSubqueryOperator = "=";
}
if (!ascending)
{
beforeSubqueryOperator = ">";
afterSubqueryOperator = "<=";
}
String order = before ? " desc" : "";
if (!ascending)
{
order = before ? "" : " desc";
}
// Note that it's OK to have unused arguments in the array;
// see the javadoc of java.text.MessageFormat
// for the whole story.
List args = new ArrayList();
args.add(before ? beforeSubqueryOperator : afterSubqueryOperator);
args.add(before ? beforeOperator : afterOperator);
args.add(order);
args.add(new Integer(numberDesired));
return MessageFormat.format(sql, args.toArray());
}
/**
* Log a message about the results of a browse.
*
* @param info
*/
private static void logInfo(BrowseInfo info)
{
if (!log.isDebugEnabled())
{
return;
}
log.debug("Number of Results: " + info.getResultCount()
+ " Overall position: " + info.getOverallPosition() + " Total "
+ info.getTotal() + " Offset " + info.getOffset());
int lastIndex = (info.getOverallPosition() + info.getResultCount());
boolean noresults = (info.getTotal() == 0)
|| (info.getResultCount() == 0);
if (noresults)
{
log.debug("Got no results");
}
log.debug("Got results: " + info.getOverallPosition() + " to "
+ lastIndex + " out of " + info.getTotal());
}
/**
* Return the name or names of the column(s) to query for a browse.
*
* @param scope
* The current browse scope
* @return The name or names of the columns to query
*/
private static String getTargetColumns(BrowseScope scope)
{
int browseType = scope.getBrowseType();
if (browseType == AUTHORS_BROWSE)
return "distinct author";
else if (browseType == SUBJECTS_BROWSE)
return "distinct subject";
else
return "*";
}
/**
* <p>
* Return a scoping clause.
* </p>
*
* <p>
* If scope is ALLDSPACE_SCOPE, return the empty string.
* </p>
*
* <p>
* Otherwise, the SQL clause which is generated looks like:
* </p>
* CONNECTOR community_id = 7 CONNECTOR collection_id = 203
*
* <p>
* CONNECTOR may be empty, or it may be a SQL keyword like <em>where</em>,
* <em>and</em>, and so forth.
* </p>
*
* @param scope
* @param connector
* FIXME ??
* @return
*/
static String getScopeClause(BrowseScope scope, String connector)
{
if (scope.isAllDSpaceScope())
{
return "";
}
boolean isCommunity = scope.isCommunityScope();
Object obj = scope.getScope();
int id = (isCommunity) ? ((Community) obj).getID() : ((Collection) obj)
.getID();
String column = (isCommunity) ? "community_id" : "collection_id";
return new StringBuffer().append(" ").append(connector).append(" ")
.append(column).append(" = ").append(id).toString();
}
/**
* Create a PreparedStatement with the given sql.
*
* @param scope
* The current Browse scope
* @param sql
* SQL query
* @return A PreparedStatement with the given SQL
* @exception SQLException
* If a database error occurs
*/
private static PreparedStatement createStatement(BrowseScope scope,
String sql) throws SQLException
{
Connection connection = scope.getContext().getDBConnection();
return connection.prepareStatement(sql);
}
/**
* Return a single int value from the PreparedStatement.
*
* @param statement
* A PreparedStatement for a query which returns a single value
* of INTEGER type.
* @return The integer value from the query.
* @exception SQLException
* If a database error occurs
*/
private static int getIntValue(PreparedStatement statement)
throws SQLException
{
ResultSet results = null;
try
{
results = statement.executeQuery();
return results.next() ? results.getInt(1) : (-1);
}
finally
{
if (results != null)
{
results.close();
}
}
}
/**
* Convert a list of item ids to full Items.
*
* @param context
* The current DSpace context
* @param ids
* A list of item ids. Each member of the list is an Integer.
* @return A list of Items with the given ids.
* @exception SQLException
* If a database error occurs
*/
private static List toItems(Context context, List ids) throws SQLException
{
// FIXME Again, this is probably a more general need
List results = new ArrayList();
for (Iterator iterator = ids.iterator(); iterator.hasNext();)
{
Integer id = (Integer) iterator.next();
Item item = Item.find(context, id.intValue());
if (item != null)
{
results.add(item);
}
}
return results;
}
}
class NormalizedTitle
{
private static String[] STOP_WORDS = new String[] { "A", "An", "The" };
/**
* Returns a normalized String corresponding to TITLE.
*
* @param title
* @param lang
* @return
*/
public static String normalize(String title, String lang)
{
if (lang == null)
{
return title;
}
return (lang.startsWith("en")) ? normalizeEnglish(title) : title;
}
/**
* Returns a normalized String corresponding to TITLE. The normalization is
* effected by:
* + first removing leading spaces, if any + then removing the first
* leading occurences of "a", "an" and "the" (in any case). + removing any
* whitespace following an occurence of a stop word
*
* This simple strategy is only expected to be used for English words.
*
* @param oldtitle
* @return
*/
public static String normalizeEnglish(String oldtitle)
{
// Corner cases
if (oldtitle == null)
{
return null;
}
if (oldtitle.length() == 0)
{
return oldtitle;
}
// lower case, stupid! (sorry, just a rant about bad contractors)
String title = oldtitle.toLowerCase();
// State variables
// First find leading whitespace, if any
int startAt = firstWhitespace(title);
boolean modified = (startAt != 0);
boolean usedStopWord = false;
String stop = null;
// Examine each stop word
for (int i = 0; i < STOP_WORDS.length; i++)
{
stop = STOP_WORDS[i];
int stoplen = stop.length();
// The title must start with the stop word (skipping white space
// and ignoring case).
boolean found = title.toLowerCase().startsWith(stop.toLowerCase(),
startAt)
&& ( // The title must be longer than whitespace plus the
// stop word
title.length() >= (startAt + stoplen + 1)) &&
// The stop word must be followed by white space
Character.isWhitespace(title.charAt(startAt + stoplen));
if (found)
{
modified = true;
usedStopWord = true;
startAt += stoplen;
// Strip leading whitespace again, if any
int firstw = firstWhitespace(title, startAt);
if (firstw != 0)
{
startAt = firstw;
}
// Only process a single stop word
break;
}
}
// If we didn't change anything, just return the title as-is
if (!modified)
{
return title;
}
// If we just stripped white space, return a substring
if (!usedStopWord)
{
return title.substring(startAt);
}
// Otherwise, return the substring with the stop word appended
return new StringBuffer(title.substring(startAt)).append(", ").append(
stop).toString();
}
/**
* Return the index of the first non-whitespace character in the String.
*
* @param title
* @return
*/
private static int firstWhitespace(String title)
{
return firstWhitespace(title, 0);
}
/**
* Return the index of the first non-whitespace character in the character
* array.
*
* @param title
* @return
*/
private static int firstWhitespace(char[] title)
{
return firstWhitespace(title, 0);
}
/**
* Return the index of the first non-whitespace character in the String,
* starting at position STARTAT.
*
* @param title
* @param startAt
* @return
*/
private static int firstWhitespace(String title, int startAt)
{
return firstWhitespace(title.toCharArray(), startAt);
}
/**
* Return the index of the first letter or number in the character array,
* starting at position STARTAT.
*
* @param title
* @param startAt
* @return
*/
private static int firstWhitespace(char[] title, int startAt)
{
int first = 0;
for (int j = startAt; j < title.length; j++)
{
//if (Character.isWhitespace(title[j]))
// Actually, let's skip anything that's not a letter or number
if (!Character.isLetterOrDigit(title[j]))
{
first = j + 1;
continue;
}
break;
}
return first;
}
}
class BrowseCache
{
private static Map tableMax = new HashMap();
private static Map tableSize = new HashMap();
/** log4j object */
private static Logger log = Logger.getLogger(BrowseCache.class);
private static Map cache = new WeakHashMap();
// Everything in the cache is held via Weak References, and is
// subject to being gc-ed at any time.
// The dateCache holds normal references, so anything in it
// will stay around.
private static SortedMap dateCache = new TreeMap();
private static final int CACHE_MAXIMUM = 30;
/**
* Look for cached Browse data corresponding to KEY.
*
* @param key
* @return
*/
public static BrowseInfo get(BrowseScope key)
{
if (log.isDebugEnabled())
{
log
.debug("Checking browse cache with " + cache.size()
+ " objects");
}
BrowseInfo cachedInfo = (BrowseInfo) cache.get(key);
try
{
// Index has never been calculated
if (getMaximum(key) == -1)
{
updateIndexData(key);
}
if (cachedInfo == null)
{
if (log.isDebugEnabled())
{
log.debug("Not in browse cache");
}
return null;
}
// If we found an object, make sure that the browse indexes
// have not changed.
//
// The granularity for this is quite large;
// any change to the index and we will calculate from scratch.,
// Thus, the cache works well when few changes are made, or
// when changes are spaced widely apart.
if (indexHasChanged(key))
{
if (log.isDebugEnabled())
{
log.debug("Index has changed");
}
cache.remove(key);
return null;
}
}
catch (SQLException sqle)
{
if (log.isDebugEnabled())
{
log.debug("Caught SQLException: " + sqle, sqle);
}
return null;
}
// Cached object
if (log.isDebugEnabled())
{
log.debug("Using cached browse");
}
cachedInfo.setCached(true);
return cachedInfo;
}
/**
* Return true if an index has changed
*
* @param key
* @return
* @throws SQLException
*/
public static boolean indexHasChanged(BrowseScope key) throws SQLException
{
Context context = null;
try
{
context = new Context();
TableRow results = countAndMax(context, key);
long count = -1;
int max = -1;
if (results != null)
{
// use getIntColumn for Oracle count data
if ("oracle".equals(ConfigurationManager.getProperty("db.name")))
{
count = results.getIntColumn("count");
}
else //getLongColumn works for postgres
{
count = results.getLongColumn("count");
}
max = results.getIntColumn("max");
}
context.complete();
// Same?
if ((count == getCount(key)) && (max == getMaximum(key)))
{
return false;
}
// Update 'em
setMaximum(key, max);
setCount(key, count);
// The index has in fact changed
return true;
}
catch (SQLException sqle)
{
if (context != null)
{
context.abort();
}
throw sqle;
}
}
/**
* Compute and save the values for the number of values in the index, and
* the maximum such value.
*
* @param key
*/
public static void updateIndexData(BrowseScope key)
{
Context context = null;
try
{
context = new Context();
TableRow results = countAndMax(context, key);
long count = -1;
int max = -1;
if (results != null)
{
//use getIntColumn for Oracle count data
if ("oracle".equals(ConfigurationManager.getProperty("db.name")))
{
count = results.getIntColumn("count");
}
else //getLongColumn works for postgres
{
count = results.getLongColumn("count");
}
max = results.getIntColumn("max");
}
context.complete();
setMaximum(key, max);
setCount(key, count);
}
catch (Exception e)
{
if (context != null)
{
context.abort();
}
e.printStackTrace();
}
}
/**
* Retrieve the values for count and max
*
* @param context
* @param scope
* @return
* @throws SQLException
*/
public static TableRow countAndMax(Context context, BrowseScope scope)
throws SQLException
{
// The basic idea here is that we'll check an indexes
// maximum id and its count: if the maximum id has changed,
// then there are new values, and if the count has changed,
// then some items may have been removed. We assume that
// values never change.
String sql = new StringBuffer().append(
"select count({0}) as count, max({0}) as max from ").append(
BrowseTables.getTable(scope)).append(
Browse.getScopeClause(scope, "where")).toString();
// Format it to use the correct columns
String countColumn = BrowseTables.getIndexColumn(scope);
Object[] args = new Object[] { countColumn, countColumn };
String SQL = MessageFormat.format(sql, args);
// Run the query
if (log.isDebugEnabled())
{
log.debug("Running SQL to check whether index has changed: \""
+ SQL + "\"");
}
return DatabaseManager.querySingle(context, SQL);
}
/**
* Add info to cache, using key.
*
* @param key
* @param info
*/
public static void add(BrowseScope key, BrowseInfo info)
{
// Don't bother caching browses with no results, they are
// fairly cheap to calculate
if (info.getResultCount() == 0)
{
return;
}
// Add the info to the cache
// Since the object is passed in to us (and thus the caller
// may change it), we make a copy.
cache.put(key.clone(), info);
// Make sure the date cache is current
cleanDateCache();
// Save a new entry into the date cache
dateCache.put(new java.util.Date(), key);
}
/**
* Remove entries from the date cache
*/
private static void cleanDateCache()
{
synchronized (dateCache)
{
// Plenty of room!
if (dateCache.size() < CACHE_MAXIMUM)
{
return;
}
// Remove the oldest object
dateCache.remove(dateCache.firstKey());
}
}
/**
* Return the maximum value
*
* @param scope
* @return
*/
private static int getMaximum(BrowseScope scope)
{
String table = BrowseTables.getTable(scope);
Integer value = (Integer) tableMax.get(table);
return (value == null) ? (-1) : value.intValue();
}
private static long getCount(BrowseScope scope)
{
String table = BrowseTables.getTable(scope);
Long value = (Long) tableSize.get(table);
return (value == null) ? (-1) : value.longValue();
}
private static void setMaximum(BrowseScope scope, int max)
{
String table = BrowseTables.getTable(scope);
tableMax.put(table, new Integer(max));
}
private static void setCount(BrowseScope scope, long count)
{
String table = BrowseTables.getTable(scope);
tableSize.put(table, new Long(count));
}
}
// Encapsulates browse table info:
// * Each scope and browsetype has a corresponding table or view
// * Each browse table or view has a value column
// * Some of the browse tables are true tables, others are views.
// The index maintenance code needs to know the true tables.
// The true tables have index columns, which can be used for caching
class BrowseTables
{
private static final String[] BROWSE_TABLES = new String[] {
"Communities2Item", "ItemsByAuthor", "ItemsByDate",
"ItemsByDateAccessioned", "ItemsByTitle", "ItemsBySubject" };
/**
* Return the browse tables. This only returns true tables, views are
* ignored.
*
* @return
*/
public static String[] tables()
{
return BROWSE_TABLES;
}
/**
* Return the browse table or view for scope.
*
* @param scope
* @return
*/
public static String getTable(BrowseScope scope)
{
int browseType = scope.getBrowseType();
boolean isCommunity = scope.isCommunityScope();
boolean isCollection = scope.isCollectionScope();
if ((browseType == Browse.AUTHORS_BROWSE)
|| (browseType == Browse.ITEMS_BY_AUTHOR_BROWSE))
{
if (isCommunity)
{
return "CommunityItemsByAuthor";
}
if (isCollection)
{
return "CollectionItemsByAuthor";
}
return "ItemsByAuthor";
}
if (browseType == Browse.ITEMS_BY_TITLE_BROWSE)
{
if (isCommunity)
{
return "CommunityItemsByTitle";
}
if (isCollection)
{
return "CollectionItemsByTitle";
}
return "ItemsByTitle";
}
if (browseType == Browse.ITEMS_BY_DATE_BROWSE)
{
if (isCommunity)
{
return "CommunityItemsByDate";
}
if (isCollection)
{
return "CollectionItemsByDate";
}
return "ItemsByDate";
}
if ((browseType == Browse.SUBJECTS_BROWSE)
|| (browseType == Browse.ITEMS_BY_SUBJECT_BROWSE))
{
if (isCommunity)
{
return "CommunityItemsBySubject";
}
if (isCollection)
{
return "CollectionItemsBySubject";
}
return "ItemsBySubject";
}
throw new IllegalArgumentException(
"No table for browse and scope combination");
}
/**
* Return the name of the column that holds the index.
*
* @param scope
* @return
*/
public static String getIndexColumn(BrowseScope scope)
{
int browseType = scope.getBrowseType();
if (browseType == Browse.AUTHORS_BROWSE)
{
return "items_by_author_id";
}
if (browseType == Browse.ITEMS_BY_AUTHOR_BROWSE)
{
return "items_by_author_id";
}
if (browseType == Browse.ITEMS_BY_DATE_BROWSE)
{
return "items_by_date_id";
}
if (browseType == Browse.ITEMS_BY_TITLE_BROWSE)
{
return "items_by_title_id";
}
if (browseType == Browse.SUBJECTS_BROWSE)
{
return "items_by_subject_id";
}
if (browseType == Browse.ITEMS_BY_SUBJECT_BROWSE)
{
return "items_by_subject_id";
}
throw new IllegalArgumentException("Unknown browse type: " + browseType);
}
/**
* Return the name of the column that holds the Browse value (the title,
* author, date, etc).
*
* @param scope
* @return
*/
public static String getValueColumn(BrowseScope scope)
{
int browseType = scope.getBrowseType();
if (browseType == Browse.AUTHORS_BROWSE)
{
return "sort_author";
}
if (browseType == Browse.ITEMS_BY_AUTHOR_BROWSE)
{
return "sort_author";
}
if (browseType == Browse.ITEMS_BY_DATE_BROWSE)
{
return "date_issued";
}
// Note that we use the normalized form of the title
if (browseType == Browse.ITEMS_BY_TITLE_BROWSE)
{
return "sort_title";
}
if (browseType == Browse.SUBJECTS_BROWSE)
{
return "sort_subject";
}
if (browseType == Browse.ITEMS_BY_SUBJECT_BROWSE)
{
return "sort_subject";
}
throw new IllegalArgumentException("Unknown browse type: " + browseType);
}
}
| true | true | private static String createSqlInternal(BrowseScope scope,
String itemValue, boolean isCount)
{
String tablename = BrowseTables.getTable(scope);
String column = BrowseTables.getValueColumn(scope);
int browseType = scope.getBrowseType();
StringBuffer sqlb = new StringBuffer();
sqlb.append("select ");
sqlb.append(isCount ? "count(" : "");
sqlb.append(getTargetColumns(scope));
/**
* This next bit adds another column to the query, so authors don't show
* up lower-case
*/
if ((browseType == AUTHORS_BROWSE) && !isCount)
{
sqlb.append(",sort_author");
}
if ((browseType == SUBJECTS_BROWSE) && !isCount)
{
sqlb.append(",sort_subject");
}
sqlb.append(isCount ? ")" : "");
sqlb.append(" from (SELECT DISTINCT * ");
sqlb.append(" from ");
sqlb.append(tablename);
sqlb.append(" ) as distinct_view");
// If the browse uses items (or item ids) instead of String values
// make a subquery.
// We use a separate query to make sure the subquery works correctly
// when item values are the same. (this is transactionally
// safe because we set the isolation level).
// If we're NOT searching from the start, add some clauses
boolean addedWhereClause = false;
if (scope.hasFocus())
{
String subquery = null;
if (scope.focusIsItem())
{
subquery = new StringBuffer().append(" or ( ").append(column)
.append(" = ? and item_id {0} ").append(
scope.getFocusItemId()).append(")").toString();
}
if (log.isDebugEnabled())
{
log.debug("Subquery is \"" + subquery + "\"");
}
sqlb.append(" where ").append("(").append(column).append(" {1} ")
.append("?").append(scope.focusIsItem() ? subquery : "")
.append(")");
addedWhereClause = true;
}
String connector = addedWhereClause ? " and " : " where ";
sqlb.append(getScopeClause(scope, connector));
// For counting, skip the "order by" and "limit" clauses
if (isCount)
{
return sqlb.toString();
}
// Add an order by clause -- a parameter
sqlb
.append(" order by ")
.append(column)
.append("{2}")
.append(
((scope.focusIsString() && (scope.getBrowseType() != ITEMS_BY_DATE_BROWSE))
|| (scope.getBrowseType() == AUTHORS_BROWSE) || (scope
.getBrowseType() == SUBJECTS_BROWSE)) ? ""
: ", item_id{2}");
String myquery = sqlb.toString();
// A limit on the total returned (Postgres extension)
if (!scope.hasNoLimit())
{
if ("oracle".equals(ConfigurationManager.getProperty("db.name")))
{
myquery = "SELECT * FROM (" + myquery
+ ") WHERE ROWNUM <= {3} ";
}
else
{
// postgres uses LIMIT
myquery = myquery + " LIMIT {3} ";
}
}
return myquery;
}
| private static String createSqlInternal(BrowseScope scope,
String itemValue, boolean isCount)
{
String tablename = BrowseTables.getTable(scope);
String column = BrowseTables.getValueColumn(scope);
int browseType = scope.getBrowseType();
StringBuffer sqlb = new StringBuffer();
sqlb.append("select ");
sqlb.append(isCount ? "count(" : "");
sqlb.append(getTargetColumns(scope));
/**
* This next bit adds another column to the query, so authors don't show
* up lower-case
*/
if ((browseType == AUTHORS_BROWSE) && !isCount)
{
sqlb.append(",sort_author");
}
if ((browseType == SUBJECTS_BROWSE) && !isCount)
{
sqlb.append(",sort_subject");
}
sqlb.append(isCount ? ")" : "");
sqlb.append(" from (SELECT DISTINCT * ");
sqlb.append(" from ");
sqlb.append(tablename);
sqlb.append(" ) distinct_view");
// If the browse uses items (or item ids) instead of String values
// make a subquery.
// We use a separate query to make sure the subquery works correctly
// when item values are the same. (this is transactionally
// safe because we set the isolation level).
// If we're NOT searching from the start, add some clauses
boolean addedWhereClause = false;
if (scope.hasFocus())
{
String subquery = null;
if (scope.focusIsItem())
{
subquery = new StringBuffer().append(" or ( ").append(column)
.append(" = ? and item_id {0} ").append(
scope.getFocusItemId()).append(")").toString();
}
if (log.isDebugEnabled())
{
log.debug("Subquery is \"" + subquery + "\"");
}
sqlb.append(" where ").append("(").append(column).append(" {1} ")
.append("?").append(scope.focusIsItem() ? subquery : "")
.append(")");
addedWhereClause = true;
}
String connector = addedWhereClause ? " and " : " where ";
sqlb.append(getScopeClause(scope, connector));
// For counting, skip the "order by" and "limit" clauses
if (isCount)
{
return sqlb.toString();
}
// Add an order by clause -- a parameter
sqlb
.append(" order by ")
.append(column)
.append("{2}")
.append(
((scope.focusIsString() && (scope.getBrowseType() != ITEMS_BY_DATE_BROWSE))
|| (scope.getBrowseType() == AUTHORS_BROWSE) || (scope
.getBrowseType() == SUBJECTS_BROWSE)) ? ""
: ", item_id{2}");
String myquery = sqlb.toString();
// A limit on the total returned (Postgres extension)
if (!scope.hasNoLimit())
{
if ("oracle".equals(ConfigurationManager.getProperty("db.name")))
{
myquery = "SELECT * FROM (" + myquery
+ ") WHERE ROWNUM <= {3} ";
}
else
{
// postgres uses LIMIT
myquery = myquery + " LIMIT {3} ";
}
}
return myquery;
}
|
diff --git a/splat/src/main/uk/ac/starlink/splat/vo/SSAMetadataFrame.java b/splat/src/main/uk/ac/starlink/splat/vo/SSAMetadataFrame.java
index d0dde5040..d70ebacf8 100644
--- a/splat/src/main/uk/ac/starlink/splat/vo/SSAMetadataFrame.java
+++ b/splat/src/main/uk/ac/starlink/splat/vo/SSAMetadataFrame.java
@@ -1,790 +1,790 @@
/*
* Copyright (C) 2001-2005 Central Laboratory of the Research Councils
* Copyright (C) 2008 Science and Technology Facilities Council
*
* History:
* 23-FEB-2012 (Margarida Castro Neves [email protected])
* Original version.
*/
package uk.ac.starlink.splat.vo;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import uk.ac.starlink.splat.iface.HelpFrame;
import uk.ac.starlink.splat.iface.images.ImageHolder;
import uk.ac.starlink.splat.util.SplatCommunicator;
import uk.ac.starlink.splat.util.Transmitter;
import uk.ac.starlink.splat.util.Utilities;
import uk.ac.starlink.util.gui.BasicFileChooser;
import uk.ac.starlink.util.gui.BasicFileFilter;
import uk.ac.starlink.util.gui.ErrorDialog;
import uk.ac.starlink.splat.vo.SSAQueryBrowser.LocalAction;
import uk.ac.starlink.splat.vo.SSAQueryBrowser.MetadataInputParameter;
import uk.ac.starlink.splat.vo.SSAQueryBrowser.ResolverAction;
/**
* Class SSAMetadataServerFrame
*
* This class supports displaying metadata parameters that can be used for a SSA query,
* selecting parameters and modifying their values.
*
* @author Margarida Castro Neves
*/
public class SSAMetadataFrame extends JFrame implements ActionListener
{
/**
* Panel for the central region.
*/
protected JPanel centrePanel = new JPanel();
/**
* File chooser for storing and restoring server lists.
*/
protected BasicFileChooser fileChooser = null;
// used to trigger a new server metadata query by SSAQueryBrowser
private PropertyChangeSupport queryMetadata;
private static JTable metadataTable;
private static MetadataTableModel metadataTableModel;
/** The list of all input parameters read from the servers as a hash map */
private HashMap<String, MetadataInputParameter> metaParam=null;
// the metadata table
private static final int NRCOLS = 5; // the number of columns in the table
// the table indexes
private static final int SELECTED_INDEX = 0;
private static final int NR_SERVERS_INDEX = 1;
private static final int NAME_INDEX = 2;
private static final int VALUE_INDEX = 3;
private static final int DESCRIPTION_INDEX = 4;
// total number of servers that returned parameters
int nrServers;
// the table headers
String[] headers;
String[] headersToolTips;
// cell renderer for the parameter name column
ParamCellRenderer paramRenderer=null;
/**
* Constructor:
*/
//public SSAMetadataFrame( HashMap<String, MetadataInputParameter> metaParam , int nrServers)
public SSAMetadataFrame( HashMap<String, MetadataInputParameter> metaParam )
{
this.metaParam = metaParam;
//this.nrServers = nrServers;
initUI();
initMetadataTable();
initMenus();
initFrame();
queryMetadata = new PropertyChangeSupport(this);
} //initFrame
/**
* Constructor: creates an empty table
*/
public SSAMetadataFrame( )
{
metaParam = null;
// nrServers = 0;
initUI();
initMetadataTable();
initMenus();
initFrame();
queryMetadata = new PropertyChangeSupport(this);
} //initFrame
/**
* Initialize the metadata table
*/
public void initMetadataTable()
{
// the table headers
headers = new String[NRCOLS];
headers[SELECTED_INDEX] = "Use";
headers[NR_SERVERS_INDEX] = "Nr servers";
headers[NAME_INDEX] = "Name";
headers[VALUE_INDEX] = "Value";
headers[DESCRIPTION_INDEX] = "Description";
// the tooltip Texts for the headers
headersToolTips = new String[NRCOLS];
headersToolTips[SELECTED_INDEX] = "Select for Query";
headersToolTips[NR_SERVERS_INDEX] = "Nr servers supporting this parameter";
headersToolTips[NAME_INDEX] = "Parameter name";
headersToolTips[VALUE_INDEX] = "Parameter value";
headersToolTips[DESCRIPTION_INDEX] = "Description";
// Table of metadata parameters goes into a scrollpane in the center of
// window (along with a set of buttons, see initUI).
// set the model and change the appearance
// the table data
if (metaParam != null)
{
String[][] paramList = getParamList();
metadataTableModel = new MetadataTableModel(paramList, headers);
} else
metadataTableModel = new MetadataTableModel(headers);
metadataTable.setModel( metadataTableModel );
metadataTable.setShowGrid(true);
metadataTable.setGridColor(Color.lightGray);
metadataTable.getTableHeader().setReorderingAllowed(false);
paramRenderer = new ParamCellRenderer(); // set cell renderer for description column
adjustColumns();
}
/**
* updateMetadata( HashMap<String, MetadataInputParameter> metaParam )
* updates the metadata table information after a "refresh"
*
* @param metaParam
*/
public void updateMetadata(HashMap<String, MetadataInputParameter> metaParam )
{
metadataTableModel = new MetadataTableModel(headers);
metadataTable.setModel(metadataTableModel );
adjustColumns();
}
/**
* Transform the metadata Hash into a two-dimensional String array (an array of rows).
* The rows will be sorted by number of servers supporting the parameter
*
* @return the metadata array
*/
public String[][] getParamList()
{
// Iterate through metaParam, add the entries, populate the table
Collection<MetadataInputParameter> mp = metaParam.values();
String[][] metadataList = new String[mp.size()][NRCOLS];
Iterator<MetadataInputParameter> it = mp.iterator();
int row=0;
while (it.hasNext()) {
MetadataInputParameter mip = it.next();
metadataList[row][NR_SERVERS_INDEX] = Integer.toString(mip.getCounter());//+"/"+Integer.toString(nrServers); // nr supporting servers
metadataList[row][NAME_INDEX] = mip.getName().replace("INPUT:", ""); // name
metadataList[row][VALUE_INDEX] = mip.getValue(); // value (default value or "")
String unit = mip.getUnit();
String desc = mip.getDescription();
desc = desc.replaceAll("\n+", "<br>");
desc = desc.replaceAll("\t+", " ");
desc = desc.replaceAll("\\s+", " ");
if (unit != null && unit.length() >0) {
desc = desc + " ("+unit+")"; // description (unit)
}
metadataList[row][DESCRIPTION_INDEX] = desc; // description
row++;
} // while
Arrays.sort(metadataList, new SupportedComparator());
return metadataList;
}
/**
* comparator to sort the parameter list by the nr of servers that support a parameter
*/
class SupportedComparator implements Comparator<String[]>
{
public int compare(String[] object1, String[] object2) {
// compare the frequency counter
return ( Integer.parseInt(object2[NR_SERVERS_INDEX]) - Integer.parseInt(object1[NR_SERVERS_INDEX]) );
}
}
/**
* adjust column sizes, renderers and editors
*/
private void adjustColumns() {
JCheckBox cb = new JCheckBox();
JTextField tf = new JTextField();
metadataTable.getColumnModel().getColumn(SELECTED_INDEX).setCellEditor(new DefaultCellEditor(cb));
metadataTable.getColumnModel().getColumn(SELECTED_INDEX).setMaxWidth(30);
metadataTable.getColumnModel().getColumn(SELECTED_INDEX).setMinWidth(30);
metadataTable.getColumnModel().getColumn(NR_SERVERS_INDEX).setMaxWidth(60);
metadataTable.getColumnModel().getColumn(NAME_INDEX).setMinWidth(150);
metadataTable.getColumnModel().getColumn(VALUE_INDEX).setMinWidth(150);
metadataTable.getColumnModel().getColumn(VALUE_INDEX).setCellEditor(new DefaultCellEditor(tf));
metadataTable.getColumnModel().getColumn(NAME_INDEX).setCellRenderer(paramRenderer);
metadataTable.getColumnModel().getColumn (DESCRIPTION_INDEX).setMaxWidth(0);
// Remove the description column. Its contents will not be removed. They'll be displayed as tooltip text in the NAME_INDEX column.
metadataTable.removeColumn(metadataTable.getColumnModel().getColumn (DESCRIPTION_INDEX));
}
/**
* Retrieve parameter names and values from table and returns a query substring
* Only the parameters on selected rows, and having non-empty values will be added to the table
*/
public String getParamsQueryString()
{
String query="";
// iterate through all rows
for (int i=0; i< metadataTable.getRowCount(); i++)
{
if (rowChecked( i ))
{
String val = getTableData(i,VALUE_INDEX).toString().trim();
if (val != null && val.length() > 0) {
String name = getTableData(i,NAME_INDEX).toString().trim();
query += "&"+name+"="+val;
}
}
}
return query;
}
/**
* retrieves table content at cell position row, col
*
* @param row
* @param col
* @return
*/
private Object getTableData(int row, int col )
{
return metadataTable.getModel().getValueAt(row, col);
}
/**
* retrieves the state of the checkbox row (parameter selected)
*
* @param row
* @return - true if it is checked, false if unchecked
*/
private boolean rowChecked(int row)
{
Boolean val = (Boolean) metadataTable.getModel().getValueAt(row, SELECTED_INDEX);
if (Boolean.TRUE.equals(val))
return true;
else return false;
}
/**
* changes content to newValue at cell position row, col
*
* @param newValue
* @param row
* @param col
*/
private void setTableData(String newValue, int row, int col )
{
metadataTable.getModel().setValueAt(newValue, row, col);
}
/**
* Initialise the main part of the user interface.
*/
protected void initUI()
{
getContentPane().setLayout( new BorderLayout() );
metadataTable = new JTable( );
JScrollPane scroller = new JScrollPane( metadataTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
// metadataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
centrePanel.setLayout( new BorderLayout() );
centrePanel.add( scroller, BorderLayout.CENTER );
getContentPane().add( centrePanel, BorderLayout.CENTER );
centrePanel.setBorder( BorderFactory.createTitledBorder( "Optional Parameters" ) );
}
/**
* Initialise frame properties (disposal, title, menus etc.).
*/
protected void initFrame()
{
setTitle( Utilities.getTitle( "Select SSAP Parameters" ));
setDefaultCloseOperation( JFrame.HIDE_ON_CLOSE );
setSize( new Dimension( 425, 500 ) );
setVisible( true );
}
/**
* Initialise the menu bar, action bar and related actions.
*/
protected void initMenus()
{
// get the icons
// Get icons.
ImageIcon closeImage = new ImageIcon( ImageHolder.class.getResource( "close.gif" ) );
ImageIcon saveImage = new ImageIcon( ImageHolder.class.getResource( "savefile.gif" ) );
ImageIcon readImage = new ImageIcon( ImageHolder.class.getResource( "openfile.gif" ) );
// ImageIcon helpImage = new ImageIcon( ImageHolder.class.getResource( "help.gif" ) );
ImageIcon updateImage = new ImageIcon( ImageHolder.class.getResource("ssapservers.gif") );
ImageIcon resetImage = new ImageIcon( ImageHolder.class.getResource("reset.gif") );
// The Menu bar
// Add the menuBar.
JMenuBar menuBar = new JMenuBar();
setJMenuBar( menuBar );
// Create the File menu.
JMenu fileMenu = new JMenu( "File" );
fileMenu.setMnemonic( KeyEvent.VK_F );
menuBar.add( fileMenu );
JMenuItem saveFile = new JMenuItem("(S)ave Param List to File", saveImage);
saveFile.setMnemonic( KeyEvent.VK_S );
saveFile.addActionListener(this);
saveFile.setActionCommand( "save" );
fileMenu.add(saveFile);
JMenuItem readFile = new JMenuItem("Read Param List from (F)ile", readImage);
fileMenu.add(readFile);
readFile.setMnemonic( KeyEvent.VK_F );
readFile.addActionListener(this);
readFile.setActionCommand( "restore" );
JMenuItem loadFile = new JMenuItem("(U)pdate Params from servers", updateImage);
fileMenu.add(loadFile);
loadFile.setMnemonic( KeyEvent.VK_U );
loadFile.addActionListener(this);
loadFile.setActionCommand( "load" );
JMenuItem resetFile = new JMenuItem("(R)eset all values", resetImage);
fileMenu.add(loadFile);
resetFile.setMnemonic( KeyEvent.VK_R );
resetFile.addActionListener(this);
resetFile.setActionCommand( "reset" );
// Create the Help menu.
HelpFrame.createButtonHelpMenu( "ssa-window", "Help on window", menuBar, null );
// The Buttons bar
// the action buttons
JPanel buttonsPanel = new JPanel( new GridLayout(1,5) );
// Add action to save the parameter list into a file
JButton saveButton = new JButton( "Save" , saveImage );
saveButton.setActionCommand( "save" );
saveButton.setToolTipText( "Save parameter list to a file" );
saveButton.addActionListener( this );
buttonsPanel.add( saveButton );
// Add action to save the parameter list into a file
JButton restoreButton = new JButton( "Read" , readImage);
restoreButton.setActionCommand( "restore" );
restoreButton.setToolTipText( "Restore parameter list from a file" );
restoreButton.addActionListener( this );
buttonsPanel.add( restoreButton );
// Add action to query the servers for parameters
JButton queryButton = new JButton( "Update" , updateImage);
- queryButton.setActionCommand( "load" );
+ queryButton.setActionCommand( "refresh" );
queryButton.setToolTipText( "Query the servers for a current list of parameters" );
queryButton.addActionListener( this );
buttonsPanel.add( queryButton );
// Add action to do reset the form
JButton resetButton = new JButton( "Reset", resetImage );
resetButton.setActionCommand( "reset" );
resetButton.setToolTipText( "Clear all fields" );
resetButton.addActionListener( this );
buttonsPanel.add( resetButton );
// Add an action to close the window.
JButton closeButton = new JButton( "Close", closeImage );
//centrePanel.add( closeButton );
closeButton.addActionListener( this );
closeButton.setActionCommand( "close" );
closeButton.setToolTipText( "Close window" );
buttonsPanel.add( closeButton);
centrePanel.add( buttonsPanel, BorderLayout.SOUTH);
} // initMenus
/**
* Register new Property Change Listener
*/
public void addPropertyChangeListener(PropertyChangeListener l)
{
queryMetadata.addPropertyChangeListener(l);
}
/**
* action performed
* process the actions when a button is clicked
*/
public void actionPerformed(ActionEvent e) {
Object command = e.getActionCommand();
if ( command.equals( "save" ) ) // save table values to a file
{
saveMetadataToFile();
}
if ( command.equals( "load" ) ) // read saved table values from a file
{
readMetadataFromFile();
}
if ( command.equals( "refresh" ) ) // add new server to list
{
queryMetadata.firePropertyChange("refresh", false, true);
}
if ( command.equals( "reset" ) ) // reset text fields
{
resetFields();
}
if ( command.equals( "close" ) ) // close window
{
closeWindow();
}
} // actionPerformed
/**
* Close (hide) the window.
*/
private void closeWindow()
{
this.setVisible( false );
}
/**
* Open (show) the window.
*/
public void openWindow()
{
this.setVisible( true );
}
/**
* Reset all fields
*/
private void resetFields()
{
for (int i=0; i< metadataTable.getRowCount(); i++) {
String val = getTableData(i,VALUE_INDEX).toString().trim();
if (val != null && val.length() > 0) {
setTableData("", i,VALUE_INDEX);
}
}
} //resetFields
/**
* Initialise the file chooser to have the necessary filters.
*/
protected void initFileChooser()
{
if ( fileChooser == null ) {
fileChooser = new BasicFileChooser( false );
fileChooser.setMultiSelectionEnabled( false );
// Add a filter for XML files.
BasicFileFilter csvFileFilter =
new BasicFileFilter( "csv", "CSV files" );
fileChooser.addChoosableFileFilter( csvFileFilter );
// But allow all files as well.
fileChooser.addChoosableFileFilter
( fileChooser.getAcceptAllFileFilter() );
}
} //initFileChooser
/**
* Restore metadata that has been previously written to a
* CSV file. The file name is obtained interactively.
*/
public void readMetadataFromFile()
{
initFileChooser();
int result = fileChooser.showOpenDialog( this );
if ( result == JFileChooser.APPROVE_OPTION )
{
File file = fileChooser.getSelectedFile();
try {
readTable( file );
}
catch (Exception e) {
ErrorDialog.showError( this, e );
}
}
} // readMetadataFromFile
/**
* Interactively gets a file name and save current metadata table to it in CSV format
* a VOTable.
*/
public void saveMetadataToFile()
{
if ( metadataTable == null || metadataTable.getRowCount() == 0 ) {
JOptionPane.showMessageDialog( this,
"There are no parameters to save",
"No parameters", JOptionPane.ERROR_MESSAGE );
return;
}
initFileChooser();
int result = fileChooser.showSaveDialog( this );
if ( result == JFileChooser.APPROVE_OPTION ) {
File file = fileChooser.getSelectedFile();
try {
saveTable( file );
}
catch (Exception e) {
ErrorDialog.showError( this, e );
}
}
} // readMetadataFromFile
/**
* saveTable(file)
* saves the metadata table to a file in csv format
*
* @param paramFile - file where to save the table
* @throws IOException
*/
private void saveTable(File paramFile) throws IOException
{
BufferedWriter tableWriter = new BufferedWriter(new FileWriter(paramFile));
for ( int row=0; row< metadataTable.getRowCount(); row++) {
tableWriter.append(metadataTable.getValueAt(row, NR_SERVERS_INDEX).toString());
tableWriter.append(';');
tableWriter.append(metadataTable.getValueAt(row, NAME_INDEX).toString());
tableWriter.append(';');
tableWriter.append(metadataTable.getValueAt(row, VALUE_INDEX).toString());
tableWriter.append(';');
tableWriter.append(metadataTable.getValueAt(row, DESCRIPTION_INDEX).toString());
tableWriter.append('\n');
}
tableWriter.flush();
tableWriter.close();
} //saveTable()
/**
* readTable( File paramFile)
* reads the metadata table previously saved with saveTable() from a file in csv format
*
* @param paramFile - the csv file to be read
* @throws IOException
* @throws FileNotFoundException
*/
private void readTable(File paramFile) throws IOException, FileNotFoundException
{
MetadataTableModel newmodel = new MetadataTableModel(headers);
BufferedReader CSVFile = new BufferedReader(new FileReader(paramFile));
String tableRow = CSVFile.readLine();
while (tableRow != null) {
String [] paramRow = new String [NRCOLS];
paramRow = tableRow.split(";", NRCOLS);
newmodel.addRow(paramRow);
tableRow = CSVFile.readLine();
}
// Close the file once all data has been read.
CSVFile.close();
// set the new model
metadataTable.setModel(newmodel);
adjustColumns(); // adjust column sizes in the new model
} //readTable()
/**
* Adds a new row to the table
* @param mip the metadata parameter that will be added to the table
*/
public void addRow (MetadataInputParameter mip) {
String [] paramRow = new String [NRCOLS];
paramRow[NR_SERVERS_INDEX] = Integer.toString(mip.getCounter());//+"/"+Integer.toString(nrServers); // nr supporting servers
paramRow[NAME_INDEX] = mip.getName().replace("INPUT:", ""); // name
paramRow[VALUE_INDEX] = mip.getValue(); // value (default value or "")
String unit = mip.getUnit();
String desc = mip.getDescription();
if (desc != null)
{
// remove newline, tabs, and multiple spaces
desc = desc.replaceAll("\n+", " ");
desc = desc.replaceAll("\t+", " ");
desc = desc.replaceAll("\\s+", " ");
// insert linebreaks for multi-lined tooltip
int linelength=100;
int sum=0;
String [] words = desc.split( " " );
desc="";
for (int i=0; i<words.length; i++ ) {
sum+=words[i].length()+1;
if (sum > linelength) {
desc+="<br>"+words[i]+" ";
sum=words[i].length();
} else {
desc+=words[i]+" ";
}
}
}
if (unit != null && unit.length() >0) {
desc = desc + " ("+unit+")"; // description (unit)
}
paramRow[DESCRIPTION_INDEX] = desc; // description
MetadataTableModel mtm = (MetadataTableModel) metadataTable.getModel();
mtm.addRow( paramRow );
} //addRow
/**
* Set number of servers to the respective column in the table
* @param counter the nr of servers supporting the parameter
* @param name the name of the parameter
*/
public void setNrServers(int counter, String name) {
// boolean found=false;
int row=0;
String paramName = name.replace("INPUT:", "");
MetadataTableModel mtm = (MetadataTableModel) metadataTable.getModel();
while (row<mtm.getRowCount() )
{
if ( mtm.getValueAt(row, NAME_INDEX).toString().equalsIgnoreCase(paramName)) {
mtm.setValueAt(counter, row, NR_SERVERS_INDEX);
return;
}
row++;
}
}//setnrServers
/**
* the cell renderer for the parameter name column ( show description as toolTipText )
*
*/
class ParamCellRenderer extends JLabel implements TableCellRenderer
{
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
setText(value.toString());
setToolTipText("<html><p>"+table.getModel().getValueAt(row, DESCRIPTION_INDEX).toString()+"</p></html>");
if (isSelected)
setBackground(table.getSelectionBackground());
return this;
}
} //ParamCellRenderer
/**
* MetadataTableModel
* defines the model of the metadata table
*/
class MetadataTableModel extends DefaultTableModel
{
// creates a metadataTableModel with headers and data
public MetadataTableModel( String [][] data, String [] headers ) {
super(data, headers);
}
// creates a metadataTableModel with headers and no data rows
public MetadataTableModel( String [] headers ) {
super(headers, 0);
}
@Override
public boolean isCellEditable(int row, int column) {
return (column == VALUE_INDEX || column == SELECTED_INDEX ); // the Values column is editable
}
@Override
public Class getColumnClass(int column) {
if (column == SELECTED_INDEX )
return Boolean.class;
return String.class;
}
} //MetadataTableModel
} //SSAMetadataFrame
| true | true | protected void initMenus()
{
// get the icons
// Get icons.
ImageIcon closeImage = new ImageIcon( ImageHolder.class.getResource( "close.gif" ) );
ImageIcon saveImage = new ImageIcon( ImageHolder.class.getResource( "savefile.gif" ) );
ImageIcon readImage = new ImageIcon( ImageHolder.class.getResource( "openfile.gif" ) );
// ImageIcon helpImage = new ImageIcon( ImageHolder.class.getResource( "help.gif" ) );
ImageIcon updateImage = new ImageIcon( ImageHolder.class.getResource("ssapservers.gif") );
ImageIcon resetImage = new ImageIcon( ImageHolder.class.getResource("reset.gif") );
// The Menu bar
// Add the menuBar.
JMenuBar menuBar = new JMenuBar();
setJMenuBar( menuBar );
// Create the File menu.
JMenu fileMenu = new JMenu( "File" );
fileMenu.setMnemonic( KeyEvent.VK_F );
menuBar.add( fileMenu );
JMenuItem saveFile = new JMenuItem("(S)ave Param List to File", saveImage);
saveFile.setMnemonic( KeyEvent.VK_S );
saveFile.addActionListener(this);
saveFile.setActionCommand( "save" );
fileMenu.add(saveFile);
JMenuItem readFile = new JMenuItem("Read Param List from (F)ile", readImage);
fileMenu.add(readFile);
readFile.setMnemonic( KeyEvent.VK_F );
readFile.addActionListener(this);
readFile.setActionCommand( "restore" );
JMenuItem loadFile = new JMenuItem("(U)pdate Params from servers", updateImage);
fileMenu.add(loadFile);
loadFile.setMnemonic( KeyEvent.VK_U );
loadFile.addActionListener(this);
loadFile.setActionCommand( "load" );
JMenuItem resetFile = new JMenuItem("(R)eset all values", resetImage);
fileMenu.add(loadFile);
resetFile.setMnemonic( KeyEvent.VK_R );
resetFile.addActionListener(this);
resetFile.setActionCommand( "reset" );
// Create the Help menu.
HelpFrame.createButtonHelpMenu( "ssa-window", "Help on window", menuBar, null );
// The Buttons bar
// the action buttons
JPanel buttonsPanel = new JPanel( new GridLayout(1,5) );
// Add action to save the parameter list into a file
JButton saveButton = new JButton( "Save" , saveImage );
saveButton.setActionCommand( "save" );
saveButton.setToolTipText( "Save parameter list to a file" );
saveButton.addActionListener( this );
buttonsPanel.add( saveButton );
// Add action to save the parameter list into a file
JButton restoreButton = new JButton( "Read" , readImage);
restoreButton.setActionCommand( "restore" );
restoreButton.setToolTipText( "Restore parameter list from a file" );
restoreButton.addActionListener( this );
buttonsPanel.add( restoreButton );
// Add action to query the servers for parameters
JButton queryButton = new JButton( "Update" , updateImage);
queryButton.setActionCommand( "load" );
queryButton.setToolTipText( "Query the servers for a current list of parameters" );
queryButton.addActionListener( this );
buttonsPanel.add( queryButton );
// Add action to do reset the form
JButton resetButton = new JButton( "Reset", resetImage );
resetButton.setActionCommand( "reset" );
resetButton.setToolTipText( "Clear all fields" );
resetButton.addActionListener( this );
buttonsPanel.add( resetButton );
// Add an action to close the window.
JButton closeButton = new JButton( "Close", closeImage );
//centrePanel.add( closeButton );
closeButton.addActionListener( this );
closeButton.setActionCommand( "close" );
closeButton.setToolTipText( "Close window" );
buttonsPanel.add( closeButton);
centrePanel.add( buttonsPanel, BorderLayout.SOUTH);
} // initMenus
| protected void initMenus()
{
// get the icons
// Get icons.
ImageIcon closeImage = new ImageIcon( ImageHolder.class.getResource( "close.gif" ) );
ImageIcon saveImage = new ImageIcon( ImageHolder.class.getResource( "savefile.gif" ) );
ImageIcon readImage = new ImageIcon( ImageHolder.class.getResource( "openfile.gif" ) );
// ImageIcon helpImage = new ImageIcon( ImageHolder.class.getResource( "help.gif" ) );
ImageIcon updateImage = new ImageIcon( ImageHolder.class.getResource("ssapservers.gif") );
ImageIcon resetImage = new ImageIcon( ImageHolder.class.getResource("reset.gif") );
// The Menu bar
// Add the menuBar.
JMenuBar menuBar = new JMenuBar();
setJMenuBar( menuBar );
// Create the File menu.
JMenu fileMenu = new JMenu( "File" );
fileMenu.setMnemonic( KeyEvent.VK_F );
menuBar.add( fileMenu );
JMenuItem saveFile = new JMenuItem("(S)ave Param List to File", saveImage);
saveFile.setMnemonic( KeyEvent.VK_S );
saveFile.addActionListener(this);
saveFile.setActionCommand( "save" );
fileMenu.add(saveFile);
JMenuItem readFile = new JMenuItem("Read Param List from (F)ile", readImage);
fileMenu.add(readFile);
readFile.setMnemonic( KeyEvent.VK_F );
readFile.addActionListener(this);
readFile.setActionCommand( "restore" );
JMenuItem loadFile = new JMenuItem("(U)pdate Params from servers", updateImage);
fileMenu.add(loadFile);
loadFile.setMnemonic( KeyEvent.VK_U );
loadFile.addActionListener(this);
loadFile.setActionCommand( "load" );
JMenuItem resetFile = new JMenuItem("(R)eset all values", resetImage);
fileMenu.add(loadFile);
resetFile.setMnemonic( KeyEvent.VK_R );
resetFile.addActionListener(this);
resetFile.setActionCommand( "reset" );
// Create the Help menu.
HelpFrame.createButtonHelpMenu( "ssa-window", "Help on window", menuBar, null );
// The Buttons bar
// the action buttons
JPanel buttonsPanel = new JPanel( new GridLayout(1,5) );
// Add action to save the parameter list into a file
JButton saveButton = new JButton( "Save" , saveImage );
saveButton.setActionCommand( "save" );
saveButton.setToolTipText( "Save parameter list to a file" );
saveButton.addActionListener( this );
buttonsPanel.add( saveButton );
// Add action to save the parameter list into a file
JButton restoreButton = new JButton( "Read" , readImage);
restoreButton.setActionCommand( "restore" );
restoreButton.setToolTipText( "Restore parameter list from a file" );
restoreButton.addActionListener( this );
buttonsPanel.add( restoreButton );
// Add action to query the servers for parameters
JButton queryButton = new JButton( "Update" , updateImage);
queryButton.setActionCommand( "refresh" );
queryButton.setToolTipText( "Query the servers for a current list of parameters" );
queryButton.addActionListener( this );
buttonsPanel.add( queryButton );
// Add action to do reset the form
JButton resetButton = new JButton( "Reset", resetImage );
resetButton.setActionCommand( "reset" );
resetButton.setToolTipText( "Clear all fields" );
resetButton.addActionListener( this );
buttonsPanel.add( resetButton );
// Add an action to close the window.
JButton closeButton = new JButton( "Close", closeImage );
//centrePanel.add( closeButton );
closeButton.addActionListener( this );
closeButton.setActionCommand( "close" );
closeButton.setToolTipText( "Close window" );
buttonsPanel.add( closeButton);
centrePanel.add( buttonsPanel, BorderLayout.SOUTH);
} // initMenus
|
diff --git a/src/com/android/settings/wifi/WifiDialog.java b/src/com/android/settings/wifi/WifiDialog.java
index 7f69967c4..203499e89 100644
--- a/src/com/android/settings/wifi/WifiDialog.java
+++ b/src/com/android/settings/wifi/WifiDialog.java
@@ -1,362 +1,362 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings.wifi;
import com.android.settings.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.net.NetworkInfo.DetailedState;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.AuthAlgorithm;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiInfo;
import android.os.Bundle;
import android.security.Credentials;
import android.security.KeyStore;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.format.Formatter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.Spinner;
import android.widget.TextView;
class WifiDialog extends AlertDialog implements View.OnClickListener,
TextWatcher, AdapterView.OnItemSelectedListener {
private static final String KEYSTORE_SPACE = "keystore://";
static final int BUTTON_SUBMIT = DialogInterface.BUTTON_POSITIVE;
static final int BUTTON_FORGET = DialogInterface.BUTTON_NEUTRAL;
final boolean edit;
private final DialogInterface.OnClickListener mListener;
private final AccessPoint mAccessPoint;
private View mView;
private TextView mSsid;
private int mSecurity;
private TextView mPassword;
private Spinner mEapMethod;
private Spinner mEapCaCert;
private Spinner mEapUserCert;
private TextView mEapIdentity;
private TextView mEapAnonymous;
static boolean requireKeyStore(WifiConfiguration config) {
String values[] = {config.ca_cert.value(), config.client_cert.value(),
config.private_key.value()};
for (String value : values) {
if (value != null && value.startsWith(KEYSTORE_SPACE)) {
return true;
}
}
return false;
}
WifiDialog(Context context, DialogInterface.OnClickListener listener,
AccessPoint accessPoint, boolean edit) {
super(context);
this.edit = edit;
mListener = listener;
mAccessPoint = accessPoint;
mSecurity = (accessPoint == null) ? AccessPoint.SECURITY_NONE : accessPoint.security;
}
WifiConfiguration getConfig() {
if (mAccessPoint != null && mAccessPoint.networkId != -1 && !edit) {
return null;
}
WifiConfiguration config = new WifiConfiguration();
if (mAccessPoint == null) {
config.SSID = mSsid.getText().toString();
// If the user adds a network manually, assume that it is hidden.
config.hiddenSSID = true;
} else if (mAccessPoint.networkId == -1) {
config.SSID = mAccessPoint.ssid;
} else {
config.networkId = mAccessPoint.networkId;
}
switch (mSecurity) {
case AccessPoint.SECURITY_NONE:
config.allowedKeyManagement.set(KeyMgmt.NONE);
return config;
case AccessPoint.SECURITY_WEP:
config.allowedKeyManagement.set(KeyMgmt.NONE);
config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
if (mPassword.length() != 0) {
int length = mPassword.length();
String password = mPassword.getText().toString();
// WEP-40, WEP-104, and 256-bit WEP (WEP-232?)
if ((length == 10 || length == 26 || length == 58) &&
password.matches("[0-9A-Fa-f]*")) {
config.wepKeys[0] = password;
} else {
config.wepKeys[0] = '"' + password + '"';
}
}
return config;
case AccessPoint.SECURITY_PSK:
config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
if (mPassword.length() != 0) {
String password = mPassword.getText().toString();
if (password.matches("[0-9A-Fa-f]{64}")) {
config.preSharedKey = password;
} else {
config.preSharedKey = '"' + password + '"';
}
}
return config;
case AccessPoint.SECURITY_EAP:
config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
config.eap.setValue((String) mEapMethod.getSelectedItem());
config.ca_cert.setValue((mEapCaCert.getSelectedItemPosition() == 0) ? "" :
KEYSTORE_SPACE + Credentials.CA_CERTIFICATE +
(String) mEapCaCert.getSelectedItem());
config.client_cert.setValue((mEapUserCert.getSelectedItemPosition() == 0) ? "" :
KEYSTORE_SPACE + Credentials.USER_CERTIFICATE +
(String) mEapUserCert.getSelectedItem());
config.private_key.setValue((mEapUserCert.getSelectedItemPosition() == 0) ? "" :
- KEYSTORE_SPACE + Credentials.PRIVATE_KEY +
+ KEYSTORE_SPACE + Credentials.USER_PRIVATE_KEY +
(String) mEapUserCert.getSelectedItem());
config.identity.setValue((mEapIdentity.length() == 0) ? "" :
mEapIdentity.getText().toString());
config.anonymous_identity.setValue((mEapAnonymous.length() == 0) ? "" :
mEapAnonymous.getText().toString());
if (mPassword.length() != 0) {
config.password.setValue(mPassword.getText().toString());
}
return config;
}
return null;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
mView = getLayoutInflater().inflate(R.layout.wifi_dialog, null);
setView(mView);
setInverseBackgroundForced(true);
Context context = getContext();
Resources resources = context.getResources();
if (mAccessPoint == null) {
setTitle(R.string.wifi_add_network);
mView.findViewById(R.id.type).setVisibility(View.VISIBLE);
mSsid = (TextView) mView.findViewById(R.id.ssid);
mSsid.addTextChangedListener(this);
((Spinner) mView.findViewById(R.id.security)).setOnItemSelectedListener(this);
setButton(BUTTON_SUBMIT, context.getString(R.string.wifi_save), mListener);
} else {
setTitle(mAccessPoint.ssid);
ViewGroup group = (ViewGroup) mView.findViewById(R.id.info);
DetailedState state = mAccessPoint.getState();
if (state != null) {
addRow(group, R.string.wifi_status, Summary.get(getContext(), state));
}
String[] type = resources.getStringArray(R.array.wifi_security);
addRow(group, R.string.wifi_security, type[mAccessPoint.security]);
int level = mAccessPoint.getLevel();
if (level != -1) {
String[] signal = resources.getStringArray(R.array.wifi_signal);
addRow(group, R.string.wifi_signal, signal[level]);
}
WifiInfo info = mAccessPoint.getInfo();
if (info != null) {
addRow(group, R.string.wifi_speed, info.getLinkSpeed() + WifiInfo.LINK_SPEED_UNITS);
// TODO: fix the ip address for IPv6.
int address = info.getIpAddress();
if (address != 0) {
addRow(group, R.string.wifi_ip_address, Formatter.formatIpAddress(address));
}
}
if (mAccessPoint.networkId == -1 || edit) {
showSecurityFields();
}
if (edit) {
setButton(BUTTON_SUBMIT, context.getString(R.string.wifi_save), mListener);
} else {
if (state == null && level != -1) {
setButton(BUTTON_SUBMIT, context.getString(R.string.wifi_connect), mListener);
}
if (mAccessPoint.networkId != -1) {
setButton(BUTTON_FORGET, context.getString(R.string.wifi_forget), mListener);
}
}
}
setButton(DialogInterface.BUTTON_NEGATIVE,
context.getString(R.string.wifi_cancel), mListener);
super.onCreate(savedInstanceState);
if (getButton(BUTTON_SUBMIT) != null) {
validate();
}
}
private void addRow(ViewGroup group, int name, String value) {
View row = getLayoutInflater().inflate(R.layout.wifi_dialog_row, group, false);
((TextView) row.findViewById(R.id.name)).setText(name);
((TextView) row.findViewById(R.id.value)).setText(value);
group.addView(row);
}
private void validate() {
// TODO: make sure this is complete.
if ((mSsid != null && mSsid.length() == 0) ||
((mAccessPoint == null || mAccessPoint.networkId == -1) &&
((mSecurity == AccessPoint.SECURITY_WEP && mPassword.length() == 0) ||
(mSecurity == AccessPoint.SECURITY_PSK && mPassword.length() < 8)))) {
getButton(BUTTON_SUBMIT).setEnabled(false);
} else {
getButton(BUTTON_SUBMIT).setEnabled(true);
}
}
public void onClick(View view) {
mPassword.setInputType(
InputType.TYPE_CLASS_TEXT | (((CheckBox) view).isChecked() ?
InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD :
InputType.TYPE_TEXT_VARIATION_PASSWORD));
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable editable) {
validate();
}
public void onItemSelected(AdapterView parent, View view, int position, long id) {
mSecurity = position;
showSecurityFields();
validate();
}
public void onNothingSelected(AdapterView parent) {
}
private void showSecurityFields() {
if (mSecurity == AccessPoint.SECURITY_NONE) {
mView.findViewById(R.id.fields).setVisibility(View.GONE);
return;
}
mView.findViewById(R.id.fields).setVisibility(View.VISIBLE);
if (mPassword == null) {
mPassword = (TextView) mView.findViewById(R.id.password);
mPassword.addTextChangedListener(this);
((CheckBox) mView.findViewById(R.id.show_password)).setOnClickListener(this);
if (mAccessPoint != null && mAccessPoint.networkId != -1) {
mPassword.setHint(R.string.wifi_unchanged);
}
}
if (mSecurity != AccessPoint.SECURITY_EAP) {
mView.findViewById(R.id.eap).setVisibility(View.GONE);
return;
}
mView.findViewById(R.id.eap).setVisibility(View.VISIBLE);
if (mEapMethod == null) {
mEapMethod = (Spinner) mView.findViewById(R.id.method);
mEapCaCert = (Spinner) mView.findViewById(R.id.ca_cert);
mEapUserCert = (Spinner) mView.findViewById(R.id.user_cert);
mEapIdentity = (TextView) mView.findViewById(R.id.identity);
mEapAnonymous = (TextView) mView.findViewById(R.id.anonymous);
loadCertificates(mEapCaCert, Credentials.CA_CERTIFICATE);
loadCertificates(mEapUserCert, Credentials.USER_PRIVATE_KEY);
if (mAccessPoint != null && mAccessPoint.networkId != -1) {
WifiConfiguration config = mAccessPoint.getConfig();
setSelection(mEapMethod, config.eap.value());
setCertificate(mEapCaCert, Credentials.CA_CERTIFICATE,
config.ca_cert.value());
setCertificate(mEapUserCert, Credentials.USER_PRIVATE_KEY,
config.private_key.value());
mEapIdentity.setText(config.identity.value());
mEapAnonymous.setText(config.anonymous_identity.value());
}
}
}
private void loadCertificates(Spinner spinner, String prefix) {
String[] certs = KeyStore.getInstance().saw(prefix);
Context context = getContext();
String unspecified = context.getString(R.string.wifi_unspecified);
if (certs == null || certs.length == 0) {
certs = new String[] {unspecified};
} else {
String[] array = new String[certs.length + 1];
array[0] = unspecified;
System.arraycopy(certs, 0, array, 1, certs.length);
certs = array;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
context, android.R.layout.simple_spinner_item, certs);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
private void setCertificate(Spinner spinner, String prefix, String cert) {
prefix = KEYSTORE_SPACE + prefix;
if (cert != null && cert.startsWith(prefix)) {
setSelection(spinner, cert.substring(prefix.length()));
}
}
private void setSelection(Spinner spinner, String value) {
if (value != null) {
ArrayAdapter<String> adapter = (ArrayAdapter<String>) spinner.getAdapter();
for (int i = adapter.getCount() - 1; i >= 0; --i) {
if (value.equals(adapter.getItem(i))) {
spinner.setSelection(i);
break;
}
}
}
}
}
| true | true | WifiConfiguration getConfig() {
if (mAccessPoint != null && mAccessPoint.networkId != -1 && !edit) {
return null;
}
WifiConfiguration config = new WifiConfiguration();
if (mAccessPoint == null) {
config.SSID = mSsid.getText().toString();
// If the user adds a network manually, assume that it is hidden.
config.hiddenSSID = true;
} else if (mAccessPoint.networkId == -1) {
config.SSID = mAccessPoint.ssid;
} else {
config.networkId = mAccessPoint.networkId;
}
switch (mSecurity) {
case AccessPoint.SECURITY_NONE:
config.allowedKeyManagement.set(KeyMgmt.NONE);
return config;
case AccessPoint.SECURITY_WEP:
config.allowedKeyManagement.set(KeyMgmt.NONE);
config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
if (mPassword.length() != 0) {
int length = mPassword.length();
String password = mPassword.getText().toString();
// WEP-40, WEP-104, and 256-bit WEP (WEP-232?)
if ((length == 10 || length == 26 || length == 58) &&
password.matches("[0-9A-Fa-f]*")) {
config.wepKeys[0] = password;
} else {
config.wepKeys[0] = '"' + password + '"';
}
}
return config;
case AccessPoint.SECURITY_PSK:
config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
if (mPassword.length() != 0) {
String password = mPassword.getText().toString();
if (password.matches("[0-9A-Fa-f]{64}")) {
config.preSharedKey = password;
} else {
config.preSharedKey = '"' + password + '"';
}
}
return config;
case AccessPoint.SECURITY_EAP:
config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
config.eap.setValue((String) mEapMethod.getSelectedItem());
config.ca_cert.setValue((mEapCaCert.getSelectedItemPosition() == 0) ? "" :
KEYSTORE_SPACE + Credentials.CA_CERTIFICATE +
(String) mEapCaCert.getSelectedItem());
config.client_cert.setValue((mEapUserCert.getSelectedItemPosition() == 0) ? "" :
KEYSTORE_SPACE + Credentials.USER_CERTIFICATE +
(String) mEapUserCert.getSelectedItem());
config.private_key.setValue((mEapUserCert.getSelectedItemPosition() == 0) ? "" :
KEYSTORE_SPACE + Credentials.PRIVATE_KEY +
(String) mEapUserCert.getSelectedItem());
config.identity.setValue((mEapIdentity.length() == 0) ? "" :
mEapIdentity.getText().toString());
config.anonymous_identity.setValue((mEapAnonymous.length() == 0) ? "" :
mEapAnonymous.getText().toString());
if (mPassword.length() != 0) {
config.password.setValue(mPassword.getText().toString());
}
return config;
}
return null;
}
| WifiConfiguration getConfig() {
if (mAccessPoint != null && mAccessPoint.networkId != -1 && !edit) {
return null;
}
WifiConfiguration config = new WifiConfiguration();
if (mAccessPoint == null) {
config.SSID = mSsid.getText().toString();
// If the user adds a network manually, assume that it is hidden.
config.hiddenSSID = true;
} else if (mAccessPoint.networkId == -1) {
config.SSID = mAccessPoint.ssid;
} else {
config.networkId = mAccessPoint.networkId;
}
switch (mSecurity) {
case AccessPoint.SECURITY_NONE:
config.allowedKeyManagement.set(KeyMgmt.NONE);
return config;
case AccessPoint.SECURITY_WEP:
config.allowedKeyManagement.set(KeyMgmt.NONE);
config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
if (mPassword.length() != 0) {
int length = mPassword.length();
String password = mPassword.getText().toString();
// WEP-40, WEP-104, and 256-bit WEP (WEP-232?)
if ((length == 10 || length == 26 || length == 58) &&
password.matches("[0-9A-Fa-f]*")) {
config.wepKeys[0] = password;
} else {
config.wepKeys[0] = '"' + password + '"';
}
}
return config;
case AccessPoint.SECURITY_PSK:
config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
if (mPassword.length() != 0) {
String password = mPassword.getText().toString();
if (password.matches("[0-9A-Fa-f]{64}")) {
config.preSharedKey = password;
} else {
config.preSharedKey = '"' + password + '"';
}
}
return config;
case AccessPoint.SECURITY_EAP:
config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
config.eap.setValue((String) mEapMethod.getSelectedItem());
config.ca_cert.setValue((mEapCaCert.getSelectedItemPosition() == 0) ? "" :
KEYSTORE_SPACE + Credentials.CA_CERTIFICATE +
(String) mEapCaCert.getSelectedItem());
config.client_cert.setValue((mEapUserCert.getSelectedItemPosition() == 0) ? "" :
KEYSTORE_SPACE + Credentials.USER_CERTIFICATE +
(String) mEapUserCert.getSelectedItem());
config.private_key.setValue((mEapUserCert.getSelectedItemPosition() == 0) ? "" :
KEYSTORE_SPACE + Credentials.USER_PRIVATE_KEY +
(String) mEapUserCert.getSelectedItem());
config.identity.setValue((mEapIdentity.length() == 0) ? "" :
mEapIdentity.getText().toString());
config.anonymous_identity.setValue((mEapAnonymous.length() == 0) ? "" :
mEapAnonymous.getText().toString());
if (mPassword.length() != 0) {
config.password.setValue(mPassword.getText().toString());
}
return config;
}
return null;
}
|
diff --git a/sventon/dev/java/src/de/berlios/sventon/web/ctrl/ShowLogController.java b/sventon/dev/java/src/de/berlios/sventon/web/ctrl/ShowLogController.java
index 36a696c9..99144275 100644
--- a/sventon/dev/java/src/de/berlios/sventon/web/ctrl/ShowLogController.java
+++ b/sventon/dev/java/src/de/berlios/sventon/web/ctrl/ShowLogController.java
@@ -1,131 +1,132 @@
/*
* ====================================================================
* Copyright (c) 2005-2006 Sventon Project. All rights reserved.
*
* This software is licensed as described in the file LICENSE, which
* you should have received as part of this distribution. The terms
* are also available at http://sventon.berlios.de.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
* ====================================================================
*/
package de.berlios.sventon.web.ctrl;
import de.berlios.sventon.web.command.SVNBaseCommand;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.RequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.tmatesoft.svn.core.SVNLogEntry;
import org.tmatesoft.svn.core.SVNLogEntryPath;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.wc.SVNRevision;
import static org.tmatesoft.svn.core.wc.SVNRevision.HEAD;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
/**
* ShowLogController. For showing logs. Note, this currently does not work for
* protocol http/https. <p/> The log entries will be paged if the number of
* entries exceeds max page siz, {@link #pageSize}. Paged log entries are
* stored in the user HTTP session using key <code>sventon.logEntryPages</code>.
* The type of this object is <code>List<List<SVNLogEntry>></code>.
*
* @author [email protected]
*/
public class ShowLogController extends AbstractSVNTemplateController implements Controller {
/**
* Max entries per page, default set to 50.
*/
private int pageSize = 50;
/**
* Set page size, this is the max number of log entires shown at a time
*
* @param pageSize Page size.
*/
public void setPageSize(final int pageSize) {
this.pageSize = pageSize;
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
protected ModelAndView svnHandle(final SVNRepository repository, final SVNBaseCommand svnCommand,
final SVNRevision revision, final HttpServletRequest request,
final HttpServletResponse response, final BindException exception) throws Exception {
String path = svnCommand.getPath();
final String nextPathParam = RequestUtils.getStringParameter(request, "nextPath", null);
final String nextRevParam = RequestUtils.getStringParameter(request, "nextRevision", null);
- final String[] targetPaths;
+ final String targetPath;
final long revNumber;
if (!path.startsWith("/")) {
path = "/" + path;
}
if (nextPathParam == null || nextRevParam == null) {
- targetPaths = new String[]{path};
+ targetPath = path;
revNumber = revision == HEAD ? getHeadRevision(repository) : revision.getNumber();
} else {
- targetPaths = new String[]{nextPathParam};
+ targetPath = nextPathParam;
if ("HEAD".equals(nextRevParam)) {
revNumber = getHeadRevision(repository);
} else {
try {
revNumber = Long.parseLong(nextRevParam);
} catch (final NumberFormatException nfe) {
exception.reject("log.command.invalidpath", "Invalid revision/path combination for logs");
return prepareExceptionModelAndView(exception, svnCommand);
}
}
}
final List<LogEntryBundle> logEntryBundles = new ArrayList<LogEntryBundle>();
logger.debug("Assembling logs data");
// TODO: Safer parsing would be nice.
- final List<SVNLogEntry> logEntries = getRepositoryService().getRevisions(repository, revNumber, 0, pageSize);
+ final List<SVNLogEntry> logEntries =
+ getRepositoryService().getRevisions(repository, revNumber, 0, targetPath, pageSize);
final SVNNodeKind nodeKind = repository.checkPath(path, revision.getNumber());
- String pathAtRevision = targetPaths[0];
+ String pathAtRevision = targetPath;
for (SVNLogEntry logEntry : logEntries) {
logEntryBundles.add(new LogEntryBundle(logEntry, pathAtRevision));
final Map<String, SVNLogEntryPath> allChangedPaths = logEntry.getChangedPaths();
final Set<String> changedPaths = allChangedPaths.keySet();
for (String entryPath : changedPaths) {
int i = StringUtils.indexOfDifference(entryPath, pathAtRevision);
if (i == -1) { // Same path
final SVNLogEntryPath logEntryPath = allChangedPaths.get(entryPath);
if (logEntryPath.getCopyPath() != null) {
pathAtRevision = logEntryPath.getCopyPath();
}
} else if (entryPath.length() == i) { // Part path, can be a branch
final SVNLogEntryPath logEntryPath = allChangedPaths.get(entryPath);
if (logEntryPath.getCopyPath() != null) {
pathAtRevision = logEntryPath.getCopyPath() + pathAtRevision.substring(i);
}
}
}
}
logger.debug("Create model");
final Map<String, Object> model = new HashMap<String, Object>();
model.put("logEntriesPage", logEntryBundles);
model.put("pageSize", pageSize);
model.put("isFile", nodeKind == SVNNodeKind.FILE);
model.put("morePages", logEntryBundles.size() == pageSize);
return new ModelAndView("showlog", model);
}
}
| false | true | protected ModelAndView svnHandle(final SVNRepository repository, final SVNBaseCommand svnCommand,
final SVNRevision revision, final HttpServletRequest request,
final HttpServletResponse response, final BindException exception) throws Exception {
String path = svnCommand.getPath();
final String nextPathParam = RequestUtils.getStringParameter(request, "nextPath", null);
final String nextRevParam = RequestUtils.getStringParameter(request, "nextRevision", null);
final String[] targetPaths;
final long revNumber;
if (!path.startsWith("/")) {
path = "/" + path;
}
if (nextPathParam == null || nextRevParam == null) {
targetPaths = new String[]{path};
revNumber = revision == HEAD ? getHeadRevision(repository) : revision.getNumber();
} else {
targetPaths = new String[]{nextPathParam};
if ("HEAD".equals(nextRevParam)) {
revNumber = getHeadRevision(repository);
} else {
try {
revNumber = Long.parseLong(nextRevParam);
} catch (final NumberFormatException nfe) {
exception.reject("log.command.invalidpath", "Invalid revision/path combination for logs");
return prepareExceptionModelAndView(exception, svnCommand);
}
}
}
final List<LogEntryBundle> logEntryBundles = new ArrayList<LogEntryBundle>();
logger.debug("Assembling logs data");
// TODO: Safer parsing would be nice.
final List<SVNLogEntry> logEntries = getRepositoryService().getRevisions(repository, revNumber, 0, pageSize);
final SVNNodeKind nodeKind = repository.checkPath(path, revision.getNumber());
String pathAtRevision = targetPaths[0];
for (SVNLogEntry logEntry : logEntries) {
logEntryBundles.add(new LogEntryBundle(logEntry, pathAtRevision));
final Map<String, SVNLogEntryPath> allChangedPaths = logEntry.getChangedPaths();
final Set<String> changedPaths = allChangedPaths.keySet();
for (String entryPath : changedPaths) {
int i = StringUtils.indexOfDifference(entryPath, pathAtRevision);
if (i == -1) { // Same path
final SVNLogEntryPath logEntryPath = allChangedPaths.get(entryPath);
if (logEntryPath.getCopyPath() != null) {
pathAtRevision = logEntryPath.getCopyPath();
}
} else if (entryPath.length() == i) { // Part path, can be a branch
final SVNLogEntryPath logEntryPath = allChangedPaths.get(entryPath);
if (logEntryPath.getCopyPath() != null) {
pathAtRevision = logEntryPath.getCopyPath() + pathAtRevision.substring(i);
}
}
}
}
logger.debug("Create model");
final Map<String, Object> model = new HashMap<String, Object>();
model.put("logEntriesPage", logEntryBundles);
model.put("pageSize", pageSize);
model.put("isFile", nodeKind == SVNNodeKind.FILE);
model.put("morePages", logEntryBundles.size() == pageSize);
return new ModelAndView("showlog", model);
}
| protected ModelAndView svnHandle(final SVNRepository repository, final SVNBaseCommand svnCommand,
final SVNRevision revision, final HttpServletRequest request,
final HttpServletResponse response, final BindException exception) throws Exception {
String path = svnCommand.getPath();
final String nextPathParam = RequestUtils.getStringParameter(request, "nextPath", null);
final String nextRevParam = RequestUtils.getStringParameter(request, "nextRevision", null);
final String targetPath;
final long revNumber;
if (!path.startsWith("/")) {
path = "/" + path;
}
if (nextPathParam == null || nextRevParam == null) {
targetPath = path;
revNumber = revision == HEAD ? getHeadRevision(repository) : revision.getNumber();
} else {
targetPath = nextPathParam;
if ("HEAD".equals(nextRevParam)) {
revNumber = getHeadRevision(repository);
} else {
try {
revNumber = Long.parseLong(nextRevParam);
} catch (final NumberFormatException nfe) {
exception.reject("log.command.invalidpath", "Invalid revision/path combination for logs");
return prepareExceptionModelAndView(exception, svnCommand);
}
}
}
final List<LogEntryBundle> logEntryBundles = new ArrayList<LogEntryBundle>();
logger.debug("Assembling logs data");
// TODO: Safer parsing would be nice.
final List<SVNLogEntry> logEntries =
getRepositoryService().getRevisions(repository, revNumber, 0, targetPath, pageSize);
final SVNNodeKind nodeKind = repository.checkPath(path, revision.getNumber());
String pathAtRevision = targetPath;
for (SVNLogEntry logEntry : logEntries) {
logEntryBundles.add(new LogEntryBundle(logEntry, pathAtRevision));
final Map<String, SVNLogEntryPath> allChangedPaths = logEntry.getChangedPaths();
final Set<String> changedPaths = allChangedPaths.keySet();
for (String entryPath : changedPaths) {
int i = StringUtils.indexOfDifference(entryPath, pathAtRevision);
if (i == -1) { // Same path
final SVNLogEntryPath logEntryPath = allChangedPaths.get(entryPath);
if (logEntryPath.getCopyPath() != null) {
pathAtRevision = logEntryPath.getCopyPath();
}
} else if (entryPath.length() == i) { // Part path, can be a branch
final SVNLogEntryPath logEntryPath = allChangedPaths.get(entryPath);
if (logEntryPath.getCopyPath() != null) {
pathAtRevision = logEntryPath.getCopyPath() + pathAtRevision.substring(i);
}
}
}
}
logger.debug("Create model");
final Map<String, Object> model = new HashMap<String, Object>();
model.put("logEntriesPage", logEntryBundles);
model.put("pageSize", pageSize);
model.put("isFile", nodeKind == SVNNodeKind.FILE);
model.put("morePages", logEntryBundles.size() == pageSize);
return new ModelAndView("showlog", model);
}
|
diff --git a/MSMExplorer/src/edu/stanford/folding/msmexplorer/util/ui/VisualizationSettingsDialog.java b/MSMExplorer/src/edu/stanford/folding/msmexplorer/util/ui/VisualizationSettingsDialog.java
index 09da988..0099269 100644
--- a/MSMExplorer/src/edu/stanford/folding/msmexplorer/util/ui/VisualizationSettingsDialog.java
+++ b/MSMExplorer/src/edu/stanford/folding/msmexplorer/util/ui/VisualizationSettingsDialog.java
@@ -1,1002 +1,1008 @@
/*
* Copyright (C) 2012 Stanford University
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package edu.stanford.folding.msmexplorer.util.ui;
import edu.stanford.folding.msmexplorer.MSMConstants;
import edu.stanford.folding.msmexplorer.MSMExplorer;
import edu.stanford.folding.msmexplorer.util.AggForceDirectedLayout;
import edu.stanford.folding.msmexplorer.util.FlexDataColorAction;
import edu.stanford.folding.msmexplorer.util.render.SelfRefEdgeRenderer;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTabbedPane;
import javax.swing.JToggleButton;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import prefuse.action.Action;
import prefuse.Constants;
import prefuse.Visualization;
import prefuse.action.ActionList;
import prefuse.action.EncoderAction;
import prefuse.action.assignment.DataColorAction;
import prefuse.action.assignment.DataShapeAction;
import prefuse.action.assignment.DataSizeAction;
import prefuse.action.filter.VisibilityFilter;
import prefuse.data.Graph;
import prefuse.data.Table;
import prefuse.data.column.Column;
import prefuse.data.expression.BooleanLiteral;
import prefuse.data.expression.ColumnExpression;
import prefuse.render.ImageFactory;
import prefuse.render.LabelRenderer;
import prefuse.render.PolygonRenderer;
import prefuse.render.ShapeRenderer;
import prefuse.util.ColorLib;
import prefuse.util.FontLib;
import prefuse.util.ui.JRangeSlider;
import prefuse.visual.VisualItem;
/**
* A general visualization properties settings dialog
* designed for MSMExplorer. If you're trying to use this for
* something else, you'll have to be careful with all of the
* action and group names...
*
* @author brycecr
*/
public class VisualizationSettingsDialog extends JDialog implements MSMConstants {
// Visualization we're modifying. Action and group names depend
// on what was registered with this visualization object
private final Visualization m_vis;
private final LabelRenderer m_lr;
private final ShapeRenderer m_sr;
private final SelfRefEdgeRenderer m_er;
private final PolygonRenderer m_pr;
//copied from AxisSettingsDialog...maybe there's a clean way to share this?
private static final Integer[] FONTSIZES = {4,6,8,10,12,14,16,28,20,24,28,32,26,40,48,50,56,64,72,
84,96,110,130,150,170,200,240,280,320,360,400,450,500};
//Shaperender node shapes and corresponding labels in the JComboBox
private static final int[] SHAPES = {Constants.SHAPE_CROSS,
Constants.SHAPE_DIAMOND, Constants.SHAPE_ELLIPSE, Constants.SHAPE_HEXAGON,
Constants.SHAPE_RECTANGLE, Constants.SHAPE_STAR, Constants.SHAPE_TRIANGLE_UP,
Constants.SHAPE_TRIANGLE_DOWN};
private static final String[] SHAPES_LABELS = {"Cross", "Diamond",
"Circle", "Hexagon", "Rectangle", "Star", "Up Triangle", "Down Triangle"};
//LabelRenderer image positions and corresponding labels in JComboBox
private static final int[] IMAGEPOS = {Constants.LEFT, Constants.RIGHT,
Constants.TOP, Constants.BOTTOM};
private static final String[] IMAGEPOS_LABELS = {"Left", "Right", "Top", "Bottom"};
private static final String[] PALETTE_LABELS = {"Interpolated", "Category", "Cool",
"Hot", "Grayscale", "HSB"};
private static final String[] SCALE_LABELS = {"Linear", "Log", "Square Root", "Quantile"};
private static final Integer[] SCALE_TYPES = {Constants.LINEAR_SCALE, Constants.LOG_SCALE,
Constants.SQRT_SCALE, Constants.QUANTILE_SCALE};
private Action filter = null;
public VisualizationSettingsDialog(final Frame f, Visualization vis, LabelRenderer lr,
ShapeRenderer sr, SelfRefEdgeRenderer er, PolygonRenderer pr) {
//Init instance members
super(f);
m_vis = vis;
m_lr = lr;
m_sr = sr;
m_er = er;
m_pr = pr;
//Pane for options related to different renderers.
JTabbedPane pane = new JTabbedPane();
//main layout box
//Box main = new Box(BoxLayout.Y_AXIS);
/* ----------------------- GENERAL PANE ----------------------- */
//General pane (displayed above the tabbed pane,
//but could be it's own tab as well...
JPanel node_Panel = new JPanel();
pane.addTab("Gen. Node", node_Panel);
node_Panel.setLayout(new BoxLayout(node_Panel, BoxLayout.Y_AXIS));
//Slider sets range for automatically interpolated node size
final DataSizeAction nodeSizeAction = (DataSizeAction)m_vis.getAction("nodeSize");
int small = (int)nodeSizeAction.getMinimumSize();
int large = (int)nodeSizeAction.getMaximumSize();
if (small < 1) {
small = 1;
}
if (large < 1) {
large = 1;
}
+ if (small > large) {
+ small = large;
+ }
final JRangeSlider nodeSizeSlider = new JRangeSlider(1, 2000,
small, large, JRangeSlider.HORIZONTAL);
nodeSizeSlider.addChangeListener( new ChangeListener() {
public void stateChanged(ChangeEvent ce) {
int lowVal = nodeSizeSlider.getLowValue();
int highVal = nodeSizeSlider.getHighValue();
if (lowVal < 1) {
lowVal = 1;
}
if (highVal < 1) {
highVal = 1;
}
+ if (lowVal > highVal) {
+ highVal=lowVal;
+ }
if (m_lr.getImageField() == null) {
nodeSizeAction.setMaximumSize(highVal);
nodeSizeAction.setMinimumSize(lowVal);
} else {
double scale = 1.0d / m_vis.getDisplay(0).getScale();
double highDub = highVal / 100.0;
if (highDub < lowVal) {
highDub = lowVal;
}
nodeSizeAction.setMinimumSize(lowVal);
nodeSizeAction.setMaximumSize(highDub);
//ineffecient, perhaps, but forces the resolution to be re-evaluated.
//a better ImageFactory should cache the original images
//instead of just the scaled ones
m_lr.setImageFactory(new ImageFactory());
m_lr.getImageFactory().setMaxImageDimensions((int) (150.0d * highDub), (int) (150.0d * highDub));
m_lr.getImageFactory().preloadImages(m_vis.getGroup(NODES).tuples(), "image");
m_lr.setImageField("image");
}
m_vis.run("nodeSize");
m_vis.run("aggLayout");
m_vis.run("animate");
m_vis.repaint();
}
});
final Table nt = ((Graph)m_vis.getGroup(GRAPH)).getNodeTable();
int numCols = nt.getColumnCount();
//just the numerical type fields. It doesn't make sense to scale
//nodes based on an ordinal range, so we restrict to a numerical types
final Vector<String> numericalFields = new Vector<String>(5);
//all data fields (except visualization backing junk)
final Vector<String> fields = new Vector<String>(5);
//we start at Label to skip all the backing data
for (int i = nt.getColumnNumber(LABEL); i < numCols; ++i) {
if (isNumerical(nt.getColumn(i))) {
numericalFields.add(nt.getColumnName(i));
}
fields.add(nt.getColumnName(i));
}
final JComboBox nodeSizeActionField = new JComboBox(numericalFields);
nodeSizeActionField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
nodeSizeAction.setDataField((String)nodeSizeActionField.getSelectedItem());
m_vis.run("nodeSize");
m_vis.repaint();
}
});
nodeSizeActionField.setSelectedItem(nodeSizeAction.getDataField());
final JComboBox nodeSizeScaleField = new JComboBox(SCALE_LABELS);
nodeSizeScaleField.addActionListener( new ScaleComboxActionListener(nodeSizeScaleField,
nodeSizeAction, m_vis.getAction("nodeSize")));
nodeSizeScaleField.setSelectedIndex(Arrays.binarySearch(SCALE_TYPES, nodeSizeAction.getScale()));
final FlexDataColorAction nodeColorAction = (FlexDataColorAction)m_vis.getAction("nodeFill");
final JComboBox nodeColorActionField = new JComboBox(fields);
nodeColorActionField.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int dataType = Constants.ORDINAL;
String col = (String)nodeColorActionField.getSelectedItem();
if (isNumerical(nt.getColumn(col))) {
dataType = Constants.NUMERICAL;
}
nodeColorAction.setDataField(col);
nodeColorAction.setDataType(dataType);
m_vis.run("nodeFill");
m_vis.repaint();
}
});
nodeColorActionField.setSelectedItem(nodeColorAction.getDataField());
JComboBox nodeColorScaleField = new JComboBox(SCALE_LABELS);
nodeColorScaleField.addActionListener( new ScaleComboxActionListener(nodeColorScaleField,
nodeColorAction, m_vis.getAction("nodeFill")));
nodeColorScaleField.setSelectedIndex(Arrays.binarySearch(SCALE_TYPES, nodeColorAction.getScale()));
int[] palette = nodeColorAction.getPalette();
final JComboBox presetPalettes = new JComboBox(PALETTE_LABELS);
final JButton startColorButton = new JButton("Start Color", new
ColorSwatch(new Color(palette[palette.length-1])));
startColorButton.addActionListener( new PaletteColorButtonActionListener(f, startColorButton,
nodeColorAction, PaletteColorButtonActionListener.START, presetPalettes));
final JButton endColorButton = new JButton("End Color",
new ColorSwatch(new Color(palette[0])));
endColorButton.addActionListener( new PaletteColorButtonActionListener(f, endColorButton,
nodeColorAction, PaletteColorButtonActionListener.END, presetPalettes));
final JButton showColorChooser = new JButton("Node Color", new ColorSwatch(new Color(nodeColorAction.getPalette()[0])));
showColorChooser.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
Color newFill = JColorChooser.showDialog(f, "Choose Node Color", new Color(nodeColorAction.getDefaultColor()));
if (newFill != null) {
int[] palette = {newFill.getRGB()};
nodeColorAction.setPalette(palette);
((ColorSwatch)showColorChooser.getIcon()).setColor(newFill);
((ColorSwatch)startColorButton.getIcon()).setColor(newFill);
((ColorSwatch)endColorButton.getIcon()).setColor(newFill);
showColorChooser.repaint();
startColorButton.repaint();
endColorButton.repaint();
}
} catch (Exception e) {
Logger.getLogger(MSMExplorer.class.getName()).log(Level.SEVERE, null, e);
}
}
});
showColorChooser.setToolTipText("Open a dialog to select a new node color.");
presetPalettes.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int[] palette;
switch (presetPalettes.getSelectedIndex()) {
case 0:
palette = ColorLib.getInterpolatedPalette(((ColorSwatch)
startColorButton.getIcon()).getColor().getRGB(),
((ColorSwatch)endColorButton.getIcon()).getColor().getRGB());
break;
case 1:
palette = ColorLib.getCategoryPalette(12);
break;
case 2:
palette = ColorLib.getCoolPalette();
break;
case 3:
palette = ColorLib.getHotPalette();
break;
case 4:
palette = ColorLib.getGrayscalePalette();
break;
case 5:
palette = ColorLib.getHSBPalette();
break;
default:
return;
}
nodeColorAction.setPalette(palette);
m_vis.run("nodeFill");
m_vis.repaint();
}
});
final ActionList draw = (ActionList) m_vis.getAction("draw");
filter = null;
for (int i = 0; i < draw.size(); ++i) {
if (draw.get(i) instanceof VisibilityFilter) {
filter = draw.get(i);
}
}
final JToggleButton nodeFilterButton = new JToggleButton("Only TPT Visible", filter != null);
nodeFilterButton.addActionListener( new ActionListener() {
public void actionPerformed (ActionEvent ae) {
if (filter != null) {
draw.remove(filter);
}
VisibilityFilter vf = new VisibilityFilter(m_vis, GRAPH, new BooleanLiteral(true));
if (nodeFilterButton.isSelected()) {
vf = new VisibilityFilter(m_vis, GRAPH, new ColumnExpression("inTPT"));
}
draw.add(vf);
m_vis.run("draw");
m_vis.run("animate");
m_vis.repaint();
}
});
JPanel gen_node = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
gen_node.setBorder(BorderFactory.createTitledBorder("Gen. Node Appearance"));
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 3;
c.gridx = 1;
c.gridy = 0;
gen_node.add(showColorChooser, c);
JPanel gen_nodeAction = new JPanel(new GridBagLayout());
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
gen_nodeAction.setBorder(BorderFactory.createTitledBorder("Node Data Actions"));
c.gridx = 0;
c.gridy = 0;
gen_nodeAction.add(new JLabel("Node Size Field: "), c);
c.gridwidth = 1;
c.gridx = 1;
gen_nodeAction.add(nodeSizeActionField, c);
c.gridx = 2;
gen_nodeAction.add(new JLabel("Scale Type: ", JLabel.RIGHT), c);
c.gridx = 3;
gen_nodeAction.add(nodeSizeScaleField, c);
c.gridx = 0;
c.gridy = 1;
gen_nodeAction.add(new JLabel("Node Size Range: "), c);
c.gridx = 1;
c.gridwidth = 3;
gen_nodeAction.add(nodeSizeSlider, c);
c.insets = new Insets(20,0,0,0);
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 2;
gen_nodeAction.add(new JLabel("Node Color Field"), c);
c.gridx = 1;
gen_nodeAction.add(nodeColorActionField, c);
c.gridx = 2;
gen_nodeAction.add(new JLabel("Scale Type: ", JLabel.RIGHT), c);
c.gridx = 3;
gen_nodeAction.add(nodeColorScaleField, c);
c.gridx = 0;
c.gridy = 3;
c.insets = new Insets(0,0,0,0);
gen_nodeAction.add(new JLabel("Color Palette: ", JLabel.RIGHT), c);
c.gridx = 1;
gen_nodeAction.add(startColorButton, c);
c.gridx = 2;
gen_nodeAction.add(endColorButton, c);
c.gridx = 3;
gen_nodeAction.add(presetPalettes, c);
if (((Graph)m_vis.getGroup(GRAPH)).getNodeTable().getColumnNumber("inTPT") >= 0) {
c.gridy = 4;
c.gridx = 1;
c.gridwidth = 2;
c.insets = new Insets(10,0,0,0);
gen_nodeAction.add(nodeFilterButton, c);
}
gen_node.setOpaque(false);
gen_nodeAction.setOpaque(false);
node_Panel.add(gen_node);
node_Panel.add(gen_nodeAction);
node_Panel.setOpaque(false);
/* ----------------------- LABEL PANE ----------------------- */
JPanel lr_Panel = new JPanel();
lr_Panel.setLayout(new GridLayout(0,2));
pane.addTab("Label", lr_Panel);
final JSpinner lr_Rounded = new JSpinner(new SpinnerNumberModel(8, 0, 1000000000, 1));
lr_Rounded.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ce) {
m_lr.setRoundedCorner((Integer)lr_Rounded.getValue(), (Integer)lr_Rounded.getValue());
m_vis.run("nodeFill");
m_vis.repaint();
}
});
lr_Panel.add(new JLabel("Rounding Radius: ", JLabel.RIGHT));
lr_Panel.add(lr_Rounded);
final JComboBox lr_fontSize = new JComboBox(FONTSIZES);
lr_fontSize.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
m_vis.setValue(NODES, null, VisualItem.FONT, FontLib.getFont("Tahoma", (Integer)lr_fontSize.getSelectedItem()));
m_vis.run("nodeFill");
m_vis.repaint();
}
});
lr_fontSize.setSelectedItem(((VisualItem)m_vis.getVisualGroup(NODES).tuples().next()).getFont().getSize());
lr_Panel.add(new JLabel("Label Font Size: ", JLabel.RIGHT));
lr_Panel.add(lr_fontSize);
final JComboBox lr_imagePos = new JComboBox(IMAGEPOS_LABELS);
lr_imagePos.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
m_lr.setImagePosition(IMAGEPOS[lr_imagePos.getSelectedIndex()]);
m_vis.run("nodeFill");
m_vis.repaint();
}
});
lr_Panel.add(new JLabel("Image Position: ", JLabel.RIGHT));
lr_Panel.add(lr_imagePos);
final JToggleButton lr_showLabel = new JToggleButton("Images Only", m_lr.getTextField() == null);
lr_showLabel.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (m_lr.getImageField() != null) {
if (lr_showLabel.isSelected()) {
m_lr.setTextField(null);
} else {
m_lr.setTextField(LABEL);
}
m_vis.run("nodeFill");
m_vis.repaint();
} else {
//if no images are visble, we don't want
//to make nodes disappear, so refuse
//to select
lr_showLabel.setSelected(false);
}
}
});
lr_Panel.add(lr_showLabel);
final JButton lr_showLabelColorChooser = new JButton("Text Color", new ColorSwatch(
new Color(((VisualItem)m_vis.getGroup(NODES).tuples().next()).getTextColor())));
lr_showLabelColorChooser.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
FlexDataColorAction fill = (FlexDataColorAction)((ActionList)m_vis.getAction("animate")).get(2);
Color newFill = JColorChooser.showDialog(f, "Choose Node Color", new Color(fill.getDefaultColor()));
if (newFill != null) {
m_vis.setValue(NODES, null, VisualItem.TEXTCOLOR, newFill.getRGB());
((ColorSwatch)lr_showLabelColorChooser.getIcon()).setColor(newFill);
}
} catch (Exception e) {
Logger.getLogger(MSMExplorer.class.getName()).log(Level.SEVERE, null, e);
}
}
});
lr_showLabelColorChooser.setToolTipText("Open a dialog to select a new label text color.");
lr_Panel.add(lr_showLabelColorChooser);
lr_Panel.add(Box.createVerticalGlue());
lr_Panel.setOpaque(false);
/* ------------------ SHAPE PANE --------------------- */
JPanel sr_Panel = new JPanel(new GridBagLayout());
pane.addTab("Shape", sr_Panel);
final JComboBox shapeComboBox = new JComboBox(SHAPES_LABELS);
shapeComboBox.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
m_vis.setValue(NODES, null, VisualItem.SHAPE, SHAPES[shapeComboBox.getSelectedIndex()]);
m_vis.run("nodeFill");
m_vis.repaint();
}
});
final JComboBox shapeActionField = new JComboBox(fields);
shapeActionField.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
ActionList draw = (ActionList)m_vis.getAction("draw");
DataShapeAction dataShapeAction = null;
assert draw.size() > 1;
if (draw.get(draw.size() - 1) instanceof DataShapeAction) {
dataShapeAction = (DataShapeAction)draw.get(draw.size() - 1);
} else if (draw.get(draw.size() - 2) instanceof DataShapeAction) {
dataShapeAction = (DataShapeAction)draw.get(draw.size() - 2);
}
if (dataShapeAction != null) {
dataShapeAction.setDataField((String)shapeActionField.getSelectedItem());
} else {
dataShapeAction = new DataShapeAction(NODES, (String)shapeActionField.getSelectedItem());
dataShapeAction.setVisualization(m_vis);
draw.add(dataShapeAction);
}
m_vis.run("draw");
m_vis.repaint();
}
});
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2;
sr_Panel.add(new JLabel("Node Shape: "), c);
c.gridx = 2;
sr_Panel.add(shapeComboBox, c);
c.insets = new Insets(10,0,0,0);
c.gridx = 0;
c.gridy = 1;
sr_Panel.add(new JLabel("Node Shape Field:"), c);
c.gridx = 2;
c.gridy = 1;
sr_Panel.add(shapeActionField, c);
sr_Panel.setOpaque(false);
/* -------------------- EDGE PANE --------------------- */
JPanel er_Panel = new JPanel(new GridBagLayout());
pane.addTab("Edge", er_Panel);
final JToggleButton showSelfEdges = new JToggleButton("Show Self Edges", m_er.getRenderSelfEdges());
showSelfEdges.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
m_er.setRenderSelfEdges(showSelfEdges.isSelected());
m_vis.run("animate");
m_vis.repaint();
}
});
final ActionList animate = (ActionList)m_vis.getAction("animate");
final FlexDataColorAction edgeArrowColorAction = (FlexDataColorAction)animate.get(1);
final FlexDataColorAction edgeColorAction = (FlexDataColorAction)animate.get(2);
edgeColorAction.setDataType(Constants.NUMERICAL);
edgeArrowColorAction.setDataType(Constants.NUMERICAL);
final Table et = ((Graph)m_vis.getGroup(GRAPH)).getEdgeTable();
final Vector<String> etFields = new Vector<String>(5);
final Vector<String> etNumFields = new Vector<String>(5);
for (int i = et.getColumnNumber(TPROB); i < et.getColumnCount(); ++i) {
if (isNumerical(et.getColumn(i))) {
etNumFields.add(et.getColumnName(i));
}
etFields.add(et.getColumnName(i));
}
final JComboBox edgeColorScaleField = new JComboBox(SCALE_LABELS);
final JComboBox edgeColorField = new JComboBox(etFields);
edgeColorField.setSelectedItem(edgeColorAction.getDataField());
edgeColorField.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int dataType = Constants.ORDINAL;
String col = (String)edgeColorField.getSelectedItem();
if (isNumerical(et.getColumn(col))) {
dataType = Constants.NUMERICAL;
edgeColorAction.setBinCount(10);
edgeColorAction.setScale(SCALE_TYPES[edgeColorScaleField.getSelectedIndex()]);
}
edgeColorAction.setDataField(col);
edgeColorAction.setDataType(dataType);
edgeArrowColorAction.setDataField(col);
edgeArrowColorAction.setDataType(dataType);
m_vis.run("animate");
m_vis.repaint();
}
});
edgeColorScaleField.setSelectedIndex(Arrays.binarySearch(SCALE_TYPES, nodeColorAction.getScale()));
edgeColorScaleField.addActionListener( new ScaleComboxActionListener(edgeColorScaleField,
new ArrayList<EncoderAction>(2){{add(edgeColorAction);add(edgeArrowColorAction);}},
m_vis.getAction("animate")));
final JComboBox edgePresetPalettes = new JComboBox(PALETTE_LABELS);
int[] er_palette = edgeColorAction.getPalette();
final JButton edgeStartColorButton = new JButton("Start Color", new
ColorSwatch(new Color(er_palette[0])));
edgeStartColorButton.addActionListener( new PaletteColorButtonActionListener(f, edgeStartColorButton,
new ArrayList<FlexDataColorAction>() {{add(edgeColorAction); add(edgeArrowColorAction);}},
PaletteColorButtonActionListener.START, edgePresetPalettes));
final JButton edgeEndColorButton = new JButton("End Color", new
ColorSwatch(new Color(er_palette[er_palette.length-1])));
edgeEndColorButton.addActionListener( new PaletteColorButtonActionListener(f, edgeEndColorButton,
new ArrayList<FlexDataColorAction>() {{add(edgeColorAction); add(edgeArrowColorAction);}},
PaletteColorButtonActionListener.END, edgePresetPalettes));
edgePresetPalettes.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int[] palette;
switch (edgePresetPalettes.getSelectedIndex()) {
case 0:
palette = ColorLib.getInterpolatedPalette(((ColorSwatch)
edgeStartColorButton.getIcon()).getColor().getRGB(),
((ColorSwatch)edgeEndColorButton.getIcon()).getColor().getRGB());
break;
case 1:
palette = ColorLib.getCategoryPalette(12);
break;
case 2:
palette = ColorLib.getCoolPalette();
break;
case 3:
palette = ColorLib.getHotPalette();
break;
case 4:
palette = ColorLib.getGrayscalePalette();
break;
case 5:
palette = ColorLib.getHSBPalette();
break;
default:
return;
}
edgeColorAction.setPalette(palette);
edgeArrowColorAction.setPalette(palette);
m_vis.run("animate");
m_vis.repaint();
}
});
final DataSizeAction edgeWeightAction = (DataSizeAction)animate.get(0);
int smallw = (int)edgeWeightAction.getMinimumSize();
int largew = (int)edgeWeightAction.getMaximumSize();
smallw = (smallw > 0) ? smallw : 1;
largew = (largew > 0) ? largew : 1;
final JRangeSlider edgeWeightSlider = new JRangeSlider(1, 100000, smallw, largew, Constants.ORIENT_TOP_BOTTOM);
edgeWeightSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JRangeSlider slider = (JRangeSlider) e.getSource();
edgeWeightAction.setMinimumSize((double)slider.getLowValue()/5.0d);
edgeWeightAction.setMaximumSize((double)slider.getHighValue()/5.0d);
m_vis.run("animate");
m_vis.repaint();
}
});
edgeWeightSlider.setToolTipText("Set the range for edge thickness.");
final JComboBox edgeWeightField = new JComboBox(etNumFields);
edgeWeightField.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
double lowVal = edgeWeightSlider.getLowValue();
double highVal = edgeWeightSlider.getHighValue();
if (lowVal < 1) {
lowVal = 1;
}
if (highVal < 1) {
highVal = 1;
}
edgeWeightAction.setDataField((String)edgeWeightField.getSelectedItem());
edgeWeightAction.setMinimumSize(lowVal);
edgeWeightAction.setMaximumSize(highVal);
m_vis.run("animate");
m_vis.repaint();
}
});
final JComboBox edgeWeightScaleField = new JComboBox(SCALE_LABELS);
edgeWeightScaleField.addActionListener( new ScaleComboxActionListener(edgeWeightScaleField,
edgeWeightAction, m_vis.getAction("animate")));
edgeWeightScaleField.setSelectedIndex(Arrays.binarySearch(SCALE_TYPES, nodeColorAction.getScale()));
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 2;
c.gridx = 1;
c.gridy = 0;
er_Panel.add(showSelfEdges, c);
c.insets = new Insets(10,0,0,0);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
er_Panel.add(new JLabel("Edge Color Field: "), c);
c.gridx = 1;
er_Panel.add(edgeColorField, c);
c.gridx = 2;
er_Panel.add(new JLabel("Scale Type: ", JLabel.RIGHT), c);
c.gridx = 3;
er_Panel.add(edgeColorScaleField, c);
c.insets = new Insets(0,0,0,0);
c.gridx = 1;
c.gridy = 2;
er_Panel.add(edgeStartColorButton, c);
c.gridx = 2;
er_Panel.add(edgeEndColorButton, c);
c.gridx = 3;
er_Panel.add(edgePresetPalettes, c);
c.insets = new Insets(20,0,0,0);
c.gridx = 0;
c.gridy = 3;
er_Panel.add(new JLabel("Edge Weight Field: "), c);
c.gridx = 1;
er_Panel.add(edgeWeightField, c);
c.gridx = 2;
er_Panel.add(new JLabel("Scale Type: ", JLabel.RIGHT), c);
c.gridx = 3;
er_Panel.add(edgeWeightScaleField, c);
c.insets = new Insets(0,0,0,0);
c.gridy = 4;
c.gridx = 0;
er_Panel.add(new JLabel("Weight Range: "), c);
c.gridx = 1;
c.gridwidth = 3;
er_Panel.add(edgeWeightSlider, c);
er_Panel.setOpaque(false);
/* --------------------- AGG PANE ----------------------- */
if (m_pr != null) {
assert m_pr != null;
JPanel pr_Panel = new JPanel( new GridBagLayout());
pane.addTab("Agg.", pr_Panel);
final JSpinner aggCurve = new JSpinner(new SpinnerNumberModel(m_pr.getCurveSlack(), 0.0d, 10.0d, .02d));
aggCurve.addChangeListener( new ChangeListener() {
public void stateChanged(ChangeEvent ce) {
m_pr.setCurveSlack(((Double)aggCurve.getValue()).floatValue());
m_vis.run("aggLayout");
m_vis.repaint();
}
});
aggCurve.setPreferredSize(new Dimension(100, 30));
final JComboBox pr_presetPalettes = new JComboBox(PALETTE_LABELS);
final FlexDataColorAction aggrColorAction;
if (draw.get(draw.size() - 1) instanceof FlexDataColorAction) {
aggrColorAction = (FlexDataColorAction)draw.get(draw.size() - 1);
} else if (draw.get(draw.size() - 2) instanceof FlexDataColorAction) {
aggrColorAction = (FlexDataColorAction)draw.get(draw.size() - 2);
} else {
assert 1 == 0;
aggrColorAction = null;
}
int[] aggrPalette = aggrColorAction.getPalette();
final JButton aggrStartColorButton = new JButton("Start Color", new ColorSwatch(new Color(aggrPalette[0])));
aggrStartColorButton.addActionListener( new PaletteColorButtonActionListener(f, aggrStartColorButton,
aggrColorAction, PaletteColorButtonActionListener.START, pr_presetPalettes));
final JButton aggrEndColorButton = new JButton("End Color", new ColorSwatch(new Color(aggrPalette[aggrPalette.length-1])));
aggrEndColorButton.addActionListener( new PaletteColorButtonActionListener(f, aggrEndColorButton,
aggrColorAction, PaletteColorButtonActionListener.END, pr_presetPalettes));
ActionList lll = ((ActionList) m_vis.getAction("lll"));
final AggForceDirectedLayout afdl = ((AggForceDirectedLayout)lll.get(0));
final JToggleButton aggrLayoutMode = new JToggleButton("Agg-Lump Layout", afdl.isAggLump());
aggrLayoutMode.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
afdl.setAggLump(aggrLayoutMode.isSelected());
m_vis.run("lll");
}
});
pr_presetPalettes.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int[] palette;
switch (pr_presetPalettes.getSelectedIndex()) {
case 0:
Color start = ((ColorSwatch)aggrStartColorButton.getIcon()).getColor();
Color end = ((ColorSwatch)aggrEndColorButton.getIcon()).getColor();
palette = ColorLib.getInterpolatedPalette(start.getRGB(), end.getRGB());
break;
case 1:
palette = ColorLib.getCategoryPalette(50, 0.95f, .15f, .9f, .5f);
break;
case 2:
palette = ColorLib.getCoolPalette();
break;
case 3:
palette = ColorLib.getHotPalette();
break;
case 4:
palette = ColorLib.getGrayscalePalette();
break;
case 5:
palette = ColorLib.getHSBPalette();
break;
default:
return;
}
//This bit of crunchiness sets the alpha at value 128
//redundant for category palette but it's hard to argue
//that's a big issue...
for (int i = 0; i < palette.length; ++i) {
palette[i] = (palette[i] | 0x80000000) & 0x80ffffff;
}
aggrColorAction.setPalette(palette);
m_vis.run("draw");
m_vis.repaint();
}
});
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
pr_Panel.add(new JLabel("Aggregate Curve Slack: "), c);
c.gridx = 1;
pr_Panel.add(aggCurve, c);
c.insets = new Insets(10,0,0,0);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
pr_Panel.add(aggrStartColorButton, c);
c.gridx = 1;
pr_Panel.add(aggrEndColorButton, c);
c.gridx = 2;
pr_Panel.add(pr_presetPalettes, c);
c.gridy = 2;
c.gridx = 0;
c.gridwidth = 2;
pr_Panel.add(aggrLayoutMode, c);
pr_Panel.setOpaque(false);
}
pane.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT); //unfortunately doesn't seem to affect OSX...
add(pane);
pack();
}
public void showDialog() {
setLocationByPlatform(true);
setVisible(true);
}
private boolean isNumerical(Column c) {
Class<?> cls = c.getColumnType();
if (cls == double.class || cls == int.class || cls == float.class ||
cls == long.class) {
return true;
}
return false;
}
/**
* An ActionListener that backs buttons that select the start
* and end colors for palettes for FlexDataColorActions.
*/
private class PaletteColorButtonActionListener implements ActionListener {
//Constants denoting which end of the palette this button sets
//the start or the beginning...
public static final int START = 0;
public static final int END = 0;
private int m_end;
private Frame m_frame;
private JButton m_colorButton;
private FlexDataColorAction[] m_actions = new FlexDataColorAction[0];
private JComboBox m_presetPalette;
public PaletteColorButtonActionListener(Frame f, JButton colorButton, final FlexDataColorAction action, int end, JComboBox presetPalette) {
this(f, colorButton, new ArrayList<FlexDataColorAction>() {{add(action);}}, end, presetPalette);
}
/**
* Initializes ActionListener with gui elements, actions, and an end of the spectrum.
*
* @param f parent component (can be NULL)
* @param colorButton the button this action is being assigned to. If button has ColorSwatch object as its icon, it will be updated on color change
* @param actions an ArrayList of all the actions to set the new palette for. All should use identical palettes.
* @param end which end of the spectrum does this button set? Values must come from static constants in this class
* @param presetPalette JComboBox that has palette presets so that adjusting the color on this button sets to "Interpolated" (can be NULL)
*/
public PaletteColorButtonActionListener(Frame f, JButton colorButton, ArrayList<FlexDataColorAction> actions, int end, JComboBox presetPalette) {
//Can't construct if any of these are the case...
if (colorButton == null || actions == null || actions.isEmpty() || (end != START && end != END)) {
Logger.getLogger(MSMExplorer.class.getName()).log(Level.SEVERE, null, new Exception("Bad ColorButtonAction params"));
return;
}
m_frame = f;
m_colorButton = colorButton;
m_actions = actions.toArray(m_actions);
m_presetPalette = presetPalette;
}
/**
* Implements actionPerformed. Opens a color chooser dialog
* to select a new color for the actions in m_actions.
* Assigns that action to all the actions in m_actions
* at the end specified by m_end and updates gui components
* button color and presetPalette to reflect the change.
*
* @param ae ActionEvent that initiated this call
*/
public void actionPerformed(ActionEvent ae) {
try {
Color newColor = JColorChooser.showDialog(m_frame, "Choose Node Color",
new Color(m_actions[0].getDefaultColor()));
if (newColor != null) {
int[] oldPalette = m_actions[0].getPalette();
int[] newPalette;
if (m_end == START) {
newPalette = ColorLib.getInterpolatedPalette(newColor.getRGB(), oldPalette[oldPalette.length-1]);
} else if (m_end == END) {
newPalette = ColorLib.getInterpolatedPalette(oldPalette[0], newColor.getRGB());
} else {
assert 5 == 3;
return;
}
for (int i = 0; i < m_actions.length; ++i) {
m_actions[i].setPalette(newPalette);
}
Icon icn = m_colorButton.getIcon();
if (icn instanceof ColorSwatch) {
((ColorSwatch)icn).setColor(newColor);
}
if (m_presetPalette != null) {
m_presetPalette.setSelectedItem("Interpolated");
}
}
} catch (Exception e) {
Logger.getLogger(MSMExplorer.class.getName()).log(Level.SEVERE, null, e);
}
}
}
/**
* A simple ActionListener that manages actions for JComboBoxes that
* choose scale types for Data___Actions (anything that responds to getScale and setScale)
*/
private class ScaleComboxActionListener implements ActionListener {
private Action[] m_actions = new Action[0];
private EncoderAction[] m_sizeActions = new EncoderAction[0];
private JComboBox m_field;
public ScaleComboxActionListener(JComboBox field, EncoderAction sizeAction, final Action action) {
this(field, sizeAction, new ArrayList<Action>(1){{add(action);}});
}
public ScaleComboxActionListener(JComboBox field, final EncoderAction sizeAction, ArrayList<Action> actions) {
this(field, new ArrayList<EncoderAction>(1){{add(sizeAction);}}, actions);
}
public ScaleComboxActionListener(JComboBox field, ArrayList<EncoderAction> sizeActions, final Action action) {
this(field, sizeActions, new ArrayList<Action>(1){{add(action);}});
}
public ScaleComboxActionListener(JComboBox field, ArrayList<EncoderAction> sizeActions, ArrayList<Action> actions) {
m_actions = actions.toArray(m_actions);
m_sizeActions = sizeActions.toArray(m_sizeActions);
m_field = field;
}
public void actionPerformed(ActionEvent ae) {
for (int i = 0; i < m_sizeActions.length; ++i) {
EncoderAction m_sizeAction = m_sizeActions[i];
if (m_sizeAction instanceof FlexDataColorAction) {
((FlexDataColorAction)m_sizeAction).setScale(SCALE_TYPES[m_field.getSelectedIndex()]);
} else if (m_sizeAction instanceof DataColorAction) {
((DataColorAction)m_sizeAction).setScale(SCALE_TYPES[m_field.getSelectedIndex()]);
} else if (m_sizeAction instanceof DataSizeAction) {
((DataSizeAction)m_sizeAction).setScale(SCALE_TYPES[m_field.getSelectedIndex()]);
}
}
for (int i = 0; i < m_actions.length; ++i) {
m_actions[i].run();
}
m_vis.repaint();
}
}
}
| false | true | public VisualizationSettingsDialog(final Frame f, Visualization vis, LabelRenderer lr,
ShapeRenderer sr, SelfRefEdgeRenderer er, PolygonRenderer pr) {
//Init instance members
super(f);
m_vis = vis;
m_lr = lr;
m_sr = sr;
m_er = er;
m_pr = pr;
//Pane for options related to different renderers.
JTabbedPane pane = new JTabbedPane();
//main layout box
//Box main = new Box(BoxLayout.Y_AXIS);
/* ----------------------- GENERAL PANE ----------------------- */
//General pane (displayed above the tabbed pane,
//but could be it's own tab as well...
JPanel node_Panel = new JPanel();
pane.addTab("Gen. Node", node_Panel);
node_Panel.setLayout(new BoxLayout(node_Panel, BoxLayout.Y_AXIS));
//Slider sets range for automatically interpolated node size
final DataSizeAction nodeSizeAction = (DataSizeAction)m_vis.getAction("nodeSize");
int small = (int)nodeSizeAction.getMinimumSize();
int large = (int)nodeSizeAction.getMaximumSize();
if (small < 1) {
small = 1;
}
if (large < 1) {
large = 1;
}
final JRangeSlider nodeSizeSlider = new JRangeSlider(1, 2000,
small, large, JRangeSlider.HORIZONTAL);
nodeSizeSlider.addChangeListener( new ChangeListener() {
public void stateChanged(ChangeEvent ce) {
int lowVal = nodeSizeSlider.getLowValue();
int highVal = nodeSizeSlider.getHighValue();
if (lowVal < 1) {
lowVal = 1;
}
if (highVal < 1) {
highVal = 1;
}
if (m_lr.getImageField() == null) {
nodeSizeAction.setMaximumSize(highVal);
nodeSizeAction.setMinimumSize(lowVal);
} else {
double scale = 1.0d / m_vis.getDisplay(0).getScale();
double highDub = highVal / 100.0;
if (highDub < lowVal) {
highDub = lowVal;
}
nodeSizeAction.setMinimumSize(lowVal);
nodeSizeAction.setMaximumSize(highDub);
//ineffecient, perhaps, but forces the resolution to be re-evaluated.
//a better ImageFactory should cache the original images
//instead of just the scaled ones
m_lr.setImageFactory(new ImageFactory());
m_lr.getImageFactory().setMaxImageDimensions((int) (150.0d * highDub), (int) (150.0d * highDub));
m_lr.getImageFactory().preloadImages(m_vis.getGroup(NODES).tuples(), "image");
m_lr.setImageField("image");
}
m_vis.run("nodeSize");
m_vis.run("aggLayout");
m_vis.run("animate");
m_vis.repaint();
}
});
final Table nt = ((Graph)m_vis.getGroup(GRAPH)).getNodeTable();
int numCols = nt.getColumnCount();
//just the numerical type fields. It doesn't make sense to scale
//nodes based on an ordinal range, so we restrict to a numerical types
final Vector<String> numericalFields = new Vector<String>(5);
//all data fields (except visualization backing junk)
final Vector<String> fields = new Vector<String>(5);
//we start at Label to skip all the backing data
for (int i = nt.getColumnNumber(LABEL); i < numCols; ++i) {
if (isNumerical(nt.getColumn(i))) {
numericalFields.add(nt.getColumnName(i));
}
fields.add(nt.getColumnName(i));
}
final JComboBox nodeSizeActionField = new JComboBox(numericalFields);
nodeSizeActionField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
nodeSizeAction.setDataField((String)nodeSizeActionField.getSelectedItem());
m_vis.run("nodeSize");
m_vis.repaint();
}
});
nodeSizeActionField.setSelectedItem(nodeSizeAction.getDataField());
final JComboBox nodeSizeScaleField = new JComboBox(SCALE_LABELS);
nodeSizeScaleField.addActionListener( new ScaleComboxActionListener(nodeSizeScaleField,
nodeSizeAction, m_vis.getAction("nodeSize")));
nodeSizeScaleField.setSelectedIndex(Arrays.binarySearch(SCALE_TYPES, nodeSizeAction.getScale()));
final FlexDataColorAction nodeColorAction = (FlexDataColorAction)m_vis.getAction("nodeFill");
final JComboBox nodeColorActionField = new JComboBox(fields);
nodeColorActionField.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int dataType = Constants.ORDINAL;
String col = (String)nodeColorActionField.getSelectedItem();
if (isNumerical(nt.getColumn(col))) {
dataType = Constants.NUMERICAL;
}
nodeColorAction.setDataField(col);
nodeColorAction.setDataType(dataType);
m_vis.run("nodeFill");
m_vis.repaint();
}
});
nodeColorActionField.setSelectedItem(nodeColorAction.getDataField());
JComboBox nodeColorScaleField = new JComboBox(SCALE_LABELS);
nodeColorScaleField.addActionListener( new ScaleComboxActionListener(nodeColorScaleField,
nodeColorAction, m_vis.getAction("nodeFill")));
nodeColorScaleField.setSelectedIndex(Arrays.binarySearch(SCALE_TYPES, nodeColorAction.getScale()));
int[] palette = nodeColorAction.getPalette();
final JComboBox presetPalettes = new JComboBox(PALETTE_LABELS);
final JButton startColorButton = new JButton("Start Color", new
ColorSwatch(new Color(palette[palette.length-1])));
startColorButton.addActionListener( new PaletteColorButtonActionListener(f, startColorButton,
nodeColorAction, PaletteColorButtonActionListener.START, presetPalettes));
final JButton endColorButton = new JButton("End Color",
new ColorSwatch(new Color(palette[0])));
endColorButton.addActionListener( new PaletteColorButtonActionListener(f, endColorButton,
nodeColorAction, PaletteColorButtonActionListener.END, presetPalettes));
final JButton showColorChooser = new JButton("Node Color", new ColorSwatch(new Color(nodeColorAction.getPalette()[0])));
showColorChooser.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
Color newFill = JColorChooser.showDialog(f, "Choose Node Color", new Color(nodeColorAction.getDefaultColor()));
if (newFill != null) {
int[] palette = {newFill.getRGB()};
nodeColorAction.setPalette(palette);
((ColorSwatch)showColorChooser.getIcon()).setColor(newFill);
((ColorSwatch)startColorButton.getIcon()).setColor(newFill);
((ColorSwatch)endColorButton.getIcon()).setColor(newFill);
showColorChooser.repaint();
startColorButton.repaint();
endColorButton.repaint();
}
} catch (Exception e) {
Logger.getLogger(MSMExplorer.class.getName()).log(Level.SEVERE, null, e);
}
}
});
showColorChooser.setToolTipText("Open a dialog to select a new node color.");
presetPalettes.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int[] palette;
switch (presetPalettes.getSelectedIndex()) {
case 0:
palette = ColorLib.getInterpolatedPalette(((ColorSwatch)
startColorButton.getIcon()).getColor().getRGB(),
((ColorSwatch)endColorButton.getIcon()).getColor().getRGB());
break;
case 1:
palette = ColorLib.getCategoryPalette(12);
break;
case 2:
palette = ColorLib.getCoolPalette();
break;
case 3:
palette = ColorLib.getHotPalette();
break;
case 4:
palette = ColorLib.getGrayscalePalette();
break;
case 5:
palette = ColorLib.getHSBPalette();
break;
default:
return;
}
nodeColorAction.setPalette(palette);
m_vis.run("nodeFill");
m_vis.repaint();
}
});
final ActionList draw = (ActionList) m_vis.getAction("draw");
filter = null;
for (int i = 0; i < draw.size(); ++i) {
if (draw.get(i) instanceof VisibilityFilter) {
filter = draw.get(i);
}
}
final JToggleButton nodeFilterButton = new JToggleButton("Only TPT Visible", filter != null);
nodeFilterButton.addActionListener( new ActionListener() {
public void actionPerformed (ActionEvent ae) {
if (filter != null) {
draw.remove(filter);
}
VisibilityFilter vf = new VisibilityFilter(m_vis, GRAPH, new BooleanLiteral(true));
if (nodeFilterButton.isSelected()) {
vf = new VisibilityFilter(m_vis, GRAPH, new ColumnExpression("inTPT"));
}
draw.add(vf);
m_vis.run("draw");
m_vis.run("animate");
m_vis.repaint();
}
});
JPanel gen_node = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
gen_node.setBorder(BorderFactory.createTitledBorder("Gen. Node Appearance"));
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 3;
c.gridx = 1;
c.gridy = 0;
gen_node.add(showColorChooser, c);
JPanel gen_nodeAction = new JPanel(new GridBagLayout());
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
gen_nodeAction.setBorder(BorderFactory.createTitledBorder("Node Data Actions"));
c.gridx = 0;
c.gridy = 0;
gen_nodeAction.add(new JLabel("Node Size Field: "), c);
c.gridwidth = 1;
c.gridx = 1;
gen_nodeAction.add(nodeSizeActionField, c);
c.gridx = 2;
gen_nodeAction.add(new JLabel("Scale Type: ", JLabel.RIGHT), c);
c.gridx = 3;
gen_nodeAction.add(nodeSizeScaleField, c);
c.gridx = 0;
c.gridy = 1;
gen_nodeAction.add(new JLabel("Node Size Range: "), c);
c.gridx = 1;
c.gridwidth = 3;
gen_nodeAction.add(nodeSizeSlider, c);
c.insets = new Insets(20,0,0,0);
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 2;
gen_nodeAction.add(new JLabel("Node Color Field"), c);
c.gridx = 1;
gen_nodeAction.add(nodeColorActionField, c);
c.gridx = 2;
gen_nodeAction.add(new JLabel("Scale Type: ", JLabel.RIGHT), c);
c.gridx = 3;
gen_nodeAction.add(nodeColorScaleField, c);
c.gridx = 0;
c.gridy = 3;
c.insets = new Insets(0,0,0,0);
gen_nodeAction.add(new JLabel("Color Palette: ", JLabel.RIGHT), c);
c.gridx = 1;
gen_nodeAction.add(startColorButton, c);
c.gridx = 2;
gen_nodeAction.add(endColorButton, c);
c.gridx = 3;
gen_nodeAction.add(presetPalettes, c);
if (((Graph)m_vis.getGroup(GRAPH)).getNodeTable().getColumnNumber("inTPT") >= 0) {
c.gridy = 4;
c.gridx = 1;
c.gridwidth = 2;
c.insets = new Insets(10,0,0,0);
gen_nodeAction.add(nodeFilterButton, c);
}
gen_node.setOpaque(false);
gen_nodeAction.setOpaque(false);
node_Panel.add(gen_node);
node_Panel.add(gen_nodeAction);
node_Panel.setOpaque(false);
/* ----------------------- LABEL PANE ----------------------- */
JPanel lr_Panel = new JPanel();
lr_Panel.setLayout(new GridLayout(0,2));
pane.addTab("Label", lr_Panel);
final JSpinner lr_Rounded = new JSpinner(new SpinnerNumberModel(8, 0, 1000000000, 1));
lr_Rounded.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ce) {
m_lr.setRoundedCorner((Integer)lr_Rounded.getValue(), (Integer)lr_Rounded.getValue());
m_vis.run("nodeFill");
m_vis.repaint();
}
});
lr_Panel.add(new JLabel("Rounding Radius: ", JLabel.RIGHT));
lr_Panel.add(lr_Rounded);
final JComboBox lr_fontSize = new JComboBox(FONTSIZES);
lr_fontSize.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
m_vis.setValue(NODES, null, VisualItem.FONT, FontLib.getFont("Tahoma", (Integer)lr_fontSize.getSelectedItem()));
m_vis.run("nodeFill");
m_vis.repaint();
}
});
lr_fontSize.setSelectedItem(((VisualItem)m_vis.getVisualGroup(NODES).tuples().next()).getFont().getSize());
lr_Panel.add(new JLabel("Label Font Size: ", JLabel.RIGHT));
lr_Panel.add(lr_fontSize);
final JComboBox lr_imagePos = new JComboBox(IMAGEPOS_LABELS);
lr_imagePos.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
m_lr.setImagePosition(IMAGEPOS[lr_imagePos.getSelectedIndex()]);
m_vis.run("nodeFill");
m_vis.repaint();
}
});
lr_Panel.add(new JLabel("Image Position: ", JLabel.RIGHT));
lr_Panel.add(lr_imagePos);
final JToggleButton lr_showLabel = new JToggleButton("Images Only", m_lr.getTextField() == null);
lr_showLabel.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (m_lr.getImageField() != null) {
if (lr_showLabel.isSelected()) {
m_lr.setTextField(null);
} else {
m_lr.setTextField(LABEL);
}
m_vis.run("nodeFill");
m_vis.repaint();
} else {
//if no images are visble, we don't want
//to make nodes disappear, so refuse
//to select
lr_showLabel.setSelected(false);
}
}
});
lr_Panel.add(lr_showLabel);
final JButton lr_showLabelColorChooser = new JButton("Text Color", new ColorSwatch(
new Color(((VisualItem)m_vis.getGroup(NODES).tuples().next()).getTextColor())));
lr_showLabelColorChooser.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
FlexDataColorAction fill = (FlexDataColorAction)((ActionList)m_vis.getAction("animate")).get(2);
Color newFill = JColorChooser.showDialog(f, "Choose Node Color", new Color(fill.getDefaultColor()));
if (newFill != null) {
m_vis.setValue(NODES, null, VisualItem.TEXTCOLOR, newFill.getRGB());
((ColorSwatch)lr_showLabelColorChooser.getIcon()).setColor(newFill);
}
} catch (Exception e) {
Logger.getLogger(MSMExplorer.class.getName()).log(Level.SEVERE, null, e);
}
}
});
lr_showLabelColorChooser.setToolTipText("Open a dialog to select a new label text color.");
lr_Panel.add(lr_showLabelColorChooser);
lr_Panel.add(Box.createVerticalGlue());
lr_Panel.setOpaque(false);
/* ------------------ SHAPE PANE --------------------- */
JPanel sr_Panel = new JPanel(new GridBagLayout());
pane.addTab("Shape", sr_Panel);
final JComboBox shapeComboBox = new JComboBox(SHAPES_LABELS);
shapeComboBox.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
m_vis.setValue(NODES, null, VisualItem.SHAPE, SHAPES[shapeComboBox.getSelectedIndex()]);
m_vis.run("nodeFill");
m_vis.repaint();
}
});
final JComboBox shapeActionField = new JComboBox(fields);
shapeActionField.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
ActionList draw = (ActionList)m_vis.getAction("draw");
DataShapeAction dataShapeAction = null;
assert draw.size() > 1;
if (draw.get(draw.size() - 1) instanceof DataShapeAction) {
dataShapeAction = (DataShapeAction)draw.get(draw.size() - 1);
} else if (draw.get(draw.size() - 2) instanceof DataShapeAction) {
dataShapeAction = (DataShapeAction)draw.get(draw.size() - 2);
}
if (dataShapeAction != null) {
dataShapeAction.setDataField((String)shapeActionField.getSelectedItem());
} else {
dataShapeAction = new DataShapeAction(NODES, (String)shapeActionField.getSelectedItem());
dataShapeAction.setVisualization(m_vis);
draw.add(dataShapeAction);
}
m_vis.run("draw");
m_vis.repaint();
}
});
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2;
sr_Panel.add(new JLabel("Node Shape: "), c);
c.gridx = 2;
sr_Panel.add(shapeComboBox, c);
c.insets = new Insets(10,0,0,0);
c.gridx = 0;
c.gridy = 1;
sr_Panel.add(new JLabel("Node Shape Field:"), c);
c.gridx = 2;
c.gridy = 1;
sr_Panel.add(shapeActionField, c);
sr_Panel.setOpaque(false);
/* -------------------- EDGE PANE --------------------- */
JPanel er_Panel = new JPanel(new GridBagLayout());
pane.addTab("Edge", er_Panel);
final JToggleButton showSelfEdges = new JToggleButton("Show Self Edges", m_er.getRenderSelfEdges());
showSelfEdges.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
m_er.setRenderSelfEdges(showSelfEdges.isSelected());
m_vis.run("animate");
m_vis.repaint();
}
});
final ActionList animate = (ActionList)m_vis.getAction("animate");
final FlexDataColorAction edgeArrowColorAction = (FlexDataColorAction)animate.get(1);
final FlexDataColorAction edgeColorAction = (FlexDataColorAction)animate.get(2);
edgeColorAction.setDataType(Constants.NUMERICAL);
edgeArrowColorAction.setDataType(Constants.NUMERICAL);
final Table et = ((Graph)m_vis.getGroup(GRAPH)).getEdgeTable();
final Vector<String> etFields = new Vector<String>(5);
final Vector<String> etNumFields = new Vector<String>(5);
for (int i = et.getColumnNumber(TPROB); i < et.getColumnCount(); ++i) {
if (isNumerical(et.getColumn(i))) {
etNumFields.add(et.getColumnName(i));
}
etFields.add(et.getColumnName(i));
}
final JComboBox edgeColorScaleField = new JComboBox(SCALE_LABELS);
final JComboBox edgeColorField = new JComboBox(etFields);
edgeColorField.setSelectedItem(edgeColorAction.getDataField());
edgeColorField.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int dataType = Constants.ORDINAL;
String col = (String)edgeColorField.getSelectedItem();
if (isNumerical(et.getColumn(col))) {
dataType = Constants.NUMERICAL;
edgeColorAction.setBinCount(10);
edgeColorAction.setScale(SCALE_TYPES[edgeColorScaleField.getSelectedIndex()]);
}
edgeColorAction.setDataField(col);
edgeColorAction.setDataType(dataType);
edgeArrowColorAction.setDataField(col);
edgeArrowColorAction.setDataType(dataType);
m_vis.run("animate");
m_vis.repaint();
}
});
edgeColorScaleField.setSelectedIndex(Arrays.binarySearch(SCALE_TYPES, nodeColorAction.getScale()));
edgeColorScaleField.addActionListener( new ScaleComboxActionListener(edgeColorScaleField,
new ArrayList<EncoderAction>(2){{add(edgeColorAction);add(edgeArrowColorAction);}},
m_vis.getAction("animate")));
final JComboBox edgePresetPalettes = new JComboBox(PALETTE_LABELS);
int[] er_palette = edgeColorAction.getPalette();
final JButton edgeStartColorButton = new JButton("Start Color", new
ColorSwatch(new Color(er_palette[0])));
edgeStartColorButton.addActionListener( new PaletteColorButtonActionListener(f, edgeStartColorButton,
new ArrayList<FlexDataColorAction>() {{add(edgeColorAction); add(edgeArrowColorAction);}},
PaletteColorButtonActionListener.START, edgePresetPalettes));
final JButton edgeEndColorButton = new JButton("End Color", new
ColorSwatch(new Color(er_palette[er_palette.length-1])));
edgeEndColorButton.addActionListener( new PaletteColorButtonActionListener(f, edgeEndColorButton,
new ArrayList<FlexDataColorAction>() {{add(edgeColorAction); add(edgeArrowColorAction);}},
PaletteColorButtonActionListener.END, edgePresetPalettes));
edgePresetPalettes.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int[] palette;
switch (edgePresetPalettes.getSelectedIndex()) {
case 0:
palette = ColorLib.getInterpolatedPalette(((ColorSwatch)
edgeStartColorButton.getIcon()).getColor().getRGB(),
((ColorSwatch)edgeEndColorButton.getIcon()).getColor().getRGB());
break;
case 1:
palette = ColorLib.getCategoryPalette(12);
break;
case 2:
palette = ColorLib.getCoolPalette();
break;
case 3:
palette = ColorLib.getHotPalette();
break;
case 4:
palette = ColorLib.getGrayscalePalette();
break;
case 5:
palette = ColorLib.getHSBPalette();
break;
default:
return;
}
edgeColorAction.setPalette(palette);
edgeArrowColorAction.setPalette(palette);
m_vis.run("animate");
m_vis.repaint();
}
});
final DataSizeAction edgeWeightAction = (DataSizeAction)animate.get(0);
int smallw = (int)edgeWeightAction.getMinimumSize();
int largew = (int)edgeWeightAction.getMaximumSize();
smallw = (smallw > 0) ? smallw : 1;
largew = (largew > 0) ? largew : 1;
final JRangeSlider edgeWeightSlider = new JRangeSlider(1, 100000, smallw, largew, Constants.ORIENT_TOP_BOTTOM);
edgeWeightSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JRangeSlider slider = (JRangeSlider) e.getSource();
edgeWeightAction.setMinimumSize((double)slider.getLowValue()/5.0d);
edgeWeightAction.setMaximumSize((double)slider.getHighValue()/5.0d);
m_vis.run("animate");
m_vis.repaint();
}
});
edgeWeightSlider.setToolTipText("Set the range for edge thickness.");
final JComboBox edgeWeightField = new JComboBox(etNumFields);
edgeWeightField.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
double lowVal = edgeWeightSlider.getLowValue();
double highVal = edgeWeightSlider.getHighValue();
if (lowVal < 1) {
lowVal = 1;
}
if (highVal < 1) {
highVal = 1;
}
edgeWeightAction.setDataField((String)edgeWeightField.getSelectedItem());
edgeWeightAction.setMinimumSize(lowVal);
edgeWeightAction.setMaximumSize(highVal);
m_vis.run("animate");
m_vis.repaint();
}
});
final JComboBox edgeWeightScaleField = new JComboBox(SCALE_LABELS);
edgeWeightScaleField.addActionListener( new ScaleComboxActionListener(edgeWeightScaleField,
edgeWeightAction, m_vis.getAction("animate")));
edgeWeightScaleField.setSelectedIndex(Arrays.binarySearch(SCALE_TYPES, nodeColorAction.getScale()));
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 2;
c.gridx = 1;
c.gridy = 0;
er_Panel.add(showSelfEdges, c);
c.insets = new Insets(10,0,0,0);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
er_Panel.add(new JLabel("Edge Color Field: "), c);
c.gridx = 1;
er_Panel.add(edgeColorField, c);
c.gridx = 2;
er_Panel.add(new JLabel("Scale Type: ", JLabel.RIGHT), c);
c.gridx = 3;
er_Panel.add(edgeColorScaleField, c);
c.insets = new Insets(0,0,0,0);
c.gridx = 1;
c.gridy = 2;
er_Panel.add(edgeStartColorButton, c);
c.gridx = 2;
er_Panel.add(edgeEndColorButton, c);
c.gridx = 3;
er_Panel.add(edgePresetPalettes, c);
c.insets = new Insets(20,0,0,0);
c.gridx = 0;
c.gridy = 3;
er_Panel.add(new JLabel("Edge Weight Field: "), c);
c.gridx = 1;
er_Panel.add(edgeWeightField, c);
c.gridx = 2;
er_Panel.add(new JLabel("Scale Type: ", JLabel.RIGHT), c);
c.gridx = 3;
er_Panel.add(edgeWeightScaleField, c);
c.insets = new Insets(0,0,0,0);
c.gridy = 4;
c.gridx = 0;
er_Panel.add(new JLabel("Weight Range: "), c);
c.gridx = 1;
c.gridwidth = 3;
er_Panel.add(edgeWeightSlider, c);
er_Panel.setOpaque(false);
/* --------------------- AGG PANE ----------------------- */
if (m_pr != null) {
assert m_pr != null;
JPanel pr_Panel = new JPanel( new GridBagLayout());
pane.addTab("Agg.", pr_Panel);
final JSpinner aggCurve = new JSpinner(new SpinnerNumberModel(m_pr.getCurveSlack(), 0.0d, 10.0d, .02d));
aggCurve.addChangeListener( new ChangeListener() {
public void stateChanged(ChangeEvent ce) {
m_pr.setCurveSlack(((Double)aggCurve.getValue()).floatValue());
m_vis.run("aggLayout");
m_vis.repaint();
}
});
aggCurve.setPreferredSize(new Dimension(100, 30));
final JComboBox pr_presetPalettes = new JComboBox(PALETTE_LABELS);
final FlexDataColorAction aggrColorAction;
if (draw.get(draw.size() - 1) instanceof FlexDataColorAction) {
aggrColorAction = (FlexDataColorAction)draw.get(draw.size() - 1);
} else if (draw.get(draw.size() - 2) instanceof FlexDataColorAction) {
aggrColorAction = (FlexDataColorAction)draw.get(draw.size() - 2);
} else {
assert 1 == 0;
aggrColorAction = null;
}
int[] aggrPalette = aggrColorAction.getPalette();
final JButton aggrStartColorButton = new JButton("Start Color", new ColorSwatch(new Color(aggrPalette[0])));
aggrStartColorButton.addActionListener( new PaletteColorButtonActionListener(f, aggrStartColorButton,
aggrColorAction, PaletteColorButtonActionListener.START, pr_presetPalettes));
final JButton aggrEndColorButton = new JButton("End Color", new ColorSwatch(new Color(aggrPalette[aggrPalette.length-1])));
aggrEndColorButton.addActionListener( new PaletteColorButtonActionListener(f, aggrEndColorButton,
aggrColorAction, PaletteColorButtonActionListener.END, pr_presetPalettes));
ActionList lll = ((ActionList) m_vis.getAction("lll"));
final AggForceDirectedLayout afdl = ((AggForceDirectedLayout)lll.get(0));
final JToggleButton aggrLayoutMode = new JToggleButton("Agg-Lump Layout", afdl.isAggLump());
aggrLayoutMode.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
afdl.setAggLump(aggrLayoutMode.isSelected());
m_vis.run("lll");
}
});
pr_presetPalettes.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int[] palette;
switch (pr_presetPalettes.getSelectedIndex()) {
case 0:
Color start = ((ColorSwatch)aggrStartColorButton.getIcon()).getColor();
Color end = ((ColorSwatch)aggrEndColorButton.getIcon()).getColor();
palette = ColorLib.getInterpolatedPalette(start.getRGB(), end.getRGB());
break;
case 1:
palette = ColorLib.getCategoryPalette(50, 0.95f, .15f, .9f, .5f);
break;
case 2:
palette = ColorLib.getCoolPalette();
break;
case 3:
palette = ColorLib.getHotPalette();
break;
case 4:
palette = ColorLib.getGrayscalePalette();
break;
case 5:
palette = ColorLib.getHSBPalette();
break;
default:
return;
}
//This bit of crunchiness sets the alpha at value 128
//redundant for category palette but it's hard to argue
//that's a big issue...
for (int i = 0; i < palette.length; ++i) {
palette[i] = (palette[i] | 0x80000000) & 0x80ffffff;
}
aggrColorAction.setPalette(palette);
m_vis.run("draw");
m_vis.repaint();
}
});
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
pr_Panel.add(new JLabel("Aggregate Curve Slack: "), c);
c.gridx = 1;
pr_Panel.add(aggCurve, c);
c.insets = new Insets(10,0,0,0);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
pr_Panel.add(aggrStartColorButton, c);
c.gridx = 1;
pr_Panel.add(aggrEndColorButton, c);
c.gridx = 2;
pr_Panel.add(pr_presetPalettes, c);
c.gridy = 2;
c.gridx = 0;
c.gridwidth = 2;
pr_Panel.add(aggrLayoutMode, c);
pr_Panel.setOpaque(false);
}
pane.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT); //unfortunately doesn't seem to affect OSX...
add(pane);
pack();
}
| public VisualizationSettingsDialog(final Frame f, Visualization vis, LabelRenderer lr,
ShapeRenderer sr, SelfRefEdgeRenderer er, PolygonRenderer pr) {
//Init instance members
super(f);
m_vis = vis;
m_lr = lr;
m_sr = sr;
m_er = er;
m_pr = pr;
//Pane for options related to different renderers.
JTabbedPane pane = new JTabbedPane();
//main layout box
//Box main = new Box(BoxLayout.Y_AXIS);
/* ----------------------- GENERAL PANE ----------------------- */
//General pane (displayed above the tabbed pane,
//but could be it's own tab as well...
JPanel node_Panel = new JPanel();
pane.addTab("Gen. Node", node_Panel);
node_Panel.setLayout(new BoxLayout(node_Panel, BoxLayout.Y_AXIS));
//Slider sets range for automatically interpolated node size
final DataSizeAction nodeSizeAction = (DataSizeAction)m_vis.getAction("nodeSize");
int small = (int)nodeSizeAction.getMinimumSize();
int large = (int)nodeSizeAction.getMaximumSize();
if (small < 1) {
small = 1;
}
if (large < 1) {
large = 1;
}
if (small > large) {
small = large;
}
final JRangeSlider nodeSizeSlider = new JRangeSlider(1, 2000,
small, large, JRangeSlider.HORIZONTAL);
nodeSizeSlider.addChangeListener( new ChangeListener() {
public void stateChanged(ChangeEvent ce) {
int lowVal = nodeSizeSlider.getLowValue();
int highVal = nodeSizeSlider.getHighValue();
if (lowVal < 1) {
lowVal = 1;
}
if (highVal < 1) {
highVal = 1;
}
if (lowVal > highVal) {
highVal=lowVal;
}
if (m_lr.getImageField() == null) {
nodeSizeAction.setMaximumSize(highVal);
nodeSizeAction.setMinimumSize(lowVal);
} else {
double scale = 1.0d / m_vis.getDisplay(0).getScale();
double highDub = highVal / 100.0;
if (highDub < lowVal) {
highDub = lowVal;
}
nodeSizeAction.setMinimumSize(lowVal);
nodeSizeAction.setMaximumSize(highDub);
//ineffecient, perhaps, but forces the resolution to be re-evaluated.
//a better ImageFactory should cache the original images
//instead of just the scaled ones
m_lr.setImageFactory(new ImageFactory());
m_lr.getImageFactory().setMaxImageDimensions((int) (150.0d * highDub), (int) (150.0d * highDub));
m_lr.getImageFactory().preloadImages(m_vis.getGroup(NODES).tuples(), "image");
m_lr.setImageField("image");
}
m_vis.run("nodeSize");
m_vis.run("aggLayout");
m_vis.run("animate");
m_vis.repaint();
}
});
final Table nt = ((Graph)m_vis.getGroup(GRAPH)).getNodeTable();
int numCols = nt.getColumnCount();
//just the numerical type fields. It doesn't make sense to scale
//nodes based on an ordinal range, so we restrict to a numerical types
final Vector<String> numericalFields = new Vector<String>(5);
//all data fields (except visualization backing junk)
final Vector<String> fields = new Vector<String>(5);
//we start at Label to skip all the backing data
for (int i = nt.getColumnNumber(LABEL); i < numCols; ++i) {
if (isNumerical(nt.getColumn(i))) {
numericalFields.add(nt.getColumnName(i));
}
fields.add(nt.getColumnName(i));
}
final JComboBox nodeSizeActionField = new JComboBox(numericalFields);
nodeSizeActionField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
nodeSizeAction.setDataField((String)nodeSizeActionField.getSelectedItem());
m_vis.run("nodeSize");
m_vis.repaint();
}
});
nodeSizeActionField.setSelectedItem(nodeSizeAction.getDataField());
final JComboBox nodeSizeScaleField = new JComboBox(SCALE_LABELS);
nodeSizeScaleField.addActionListener( new ScaleComboxActionListener(nodeSizeScaleField,
nodeSizeAction, m_vis.getAction("nodeSize")));
nodeSizeScaleField.setSelectedIndex(Arrays.binarySearch(SCALE_TYPES, nodeSizeAction.getScale()));
final FlexDataColorAction nodeColorAction = (FlexDataColorAction)m_vis.getAction("nodeFill");
final JComboBox nodeColorActionField = new JComboBox(fields);
nodeColorActionField.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int dataType = Constants.ORDINAL;
String col = (String)nodeColorActionField.getSelectedItem();
if (isNumerical(nt.getColumn(col))) {
dataType = Constants.NUMERICAL;
}
nodeColorAction.setDataField(col);
nodeColorAction.setDataType(dataType);
m_vis.run("nodeFill");
m_vis.repaint();
}
});
nodeColorActionField.setSelectedItem(nodeColorAction.getDataField());
JComboBox nodeColorScaleField = new JComboBox(SCALE_LABELS);
nodeColorScaleField.addActionListener( new ScaleComboxActionListener(nodeColorScaleField,
nodeColorAction, m_vis.getAction("nodeFill")));
nodeColorScaleField.setSelectedIndex(Arrays.binarySearch(SCALE_TYPES, nodeColorAction.getScale()));
int[] palette = nodeColorAction.getPalette();
final JComboBox presetPalettes = new JComboBox(PALETTE_LABELS);
final JButton startColorButton = new JButton("Start Color", new
ColorSwatch(new Color(palette[palette.length-1])));
startColorButton.addActionListener( new PaletteColorButtonActionListener(f, startColorButton,
nodeColorAction, PaletteColorButtonActionListener.START, presetPalettes));
final JButton endColorButton = new JButton("End Color",
new ColorSwatch(new Color(palette[0])));
endColorButton.addActionListener( new PaletteColorButtonActionListener(f, endColorButton,
nodeColorAction, PaletteColorButtonActionListener.END, presetPalettes));
final JButton showColorChooser = new JButton("Node Color", new ColorSwatch(new Color(nodeColorAction.getPalette()[0])));
showColorChooser.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
Color newFill = JColorChooser.showDialog(f, "Choose Node Color", new Color(nodeColorAction.getDefaultColor()));
if (newFill != null) {
int[] palette = {newFill.getRGB()};
nodeColorAction.setPalette(palette);
((ColorSwatch)showColorChooser.getIcon()).setColor(newFill);
((ColorSwatch)startColorButton.getIcon()).setColor(newFill);
((ColorSwatch)endColorButton.getIcon()).setColor(newFill);
showColorChooser.repaint();
startColorButton.repaint();
endColorButton.repaint();
}
} catch (Exception e) {
Logger.getLogger(MSMExplorer.class.getName()).log(Level.SEVERE, null, e);
}
}
});
showColorChooser.setToolTipText("Open a dialog to select a new node color.");
presetPalettes.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int[] palette;
switch (presetPalettes.getSelectedIndex()) {
case 0:
palette = ColorLib.getInterpolatedPalette(((ColorSwatch)
startColorButton.getIcon()).getColor().getRGB(),
((ColorSwatch)endColorButton.getIcon()).getColor().getRGB());
break;
case 1:
palette = ColorLib.getCategoryPalette(12);
break;
case 2:
palette = ColorLib.getCoolPalette();
break;
case 3:
palette = ColorLib.getHotPalette();
break;
case 4:
palette = ColorLib.getGrayscalePalette();
break;
case 5:
palette = ColorLib.getHSBPalette();
break;
default:
return;
}
nodeColorAction.setPalette(palette);
m_vis.run("nodeFill");
m_vis.repaint();
}
});
final ActionList draw = (ActionList) m_vis.getAction("draw");
filter = null;
for (int i = 0; i < draw.size(); ++i) {
if (draw.get(i) instanceof VisibilityFilter) {
filter = draw.get(i);
}
}
final JToggleButton nodeFilterButton = new JToggleButton("Only TPT Visible", filter != null);
nodeFilterButton.addActionListener( new ActionListener() {
public void actionPerformed (ActionEvent ae) {
if (filter != null) {
draw.remove(filter);
}
VisibilityFilter vf = new VisibilityFilter(m_vis, GRAPH, new BooleanLiteral(true));
if (nodeFilterButton.isSelected()) {
vf = new VisibilityFilter(m_vis, GRAPH, new ColumnExpression("inTPT"));
}
draw.add(vf);
m_vis.run("draw");
m_vis.run("animate");
m_vis.repaint();
}
});
JPanel gen_node = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
gen_node.setBorder(BorderFactory.createTitledBorder("Gen. Node Appearance"));
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 3;
c.gridx = 1;
c.gridy = 0;
gen_node.add(showColorChooser, c);
JPanel gen_nodeAction = new JPanel(new GridBagLayout());
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
gen_nodeAction.setBorder(BorderFactory.createTitledBorder("Node Data Actions"));
c.gridx = 0;
c.gridy = 0;
gen_nodeAction.add(new JLabel("Node Size Field: "), c);
c.gridwidth = 1;
c.gridx = 1;
gen_nodeAction.add(nodeSizeActionField, c);
c.gridx = 2;
gen_nodeAction.add(new JLabel("Scale Type: ", JLabel.RIGHT), c);
c.gridx = 3;
gen_nodeAction.add(nodeSizeScaleField, c);
c.gridx = 0;
c.gridy = 1;
gen_nodeAction.add(new JLabel("Node Size Range: "), c);
c.gridx = 1;
c.gridwidth = 3;
gen_nodeAction.add(nodeSizeSlider, c);
c.insets = new Insets(20,0,0,0);
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 2;
gen_nodeAction.add(new JLabel("Node Color Field"), c);
c.gridx = 1;
gen_nodeAction.add(nodeColorActionField, c);
c.gridx = 2;
gen_nodeAction.add(new JLabel("Scale Type: ", JLabel.RIGHT), c);
c.gridx = 3;
gen_nodeAction.add(nodeColorScaleField, c);
c.gridx = 0;
c.gridy = 3;
c.insets = new Insets(0,0,0,0);
gen_nodeAction.add(new JLabel("Color Palette: ", JLabel.RIGHT), c);
c.gridx = 1;
gen_nodeAction.add(startColorButton, c);
c.gridx = 2;
gen_nodeAction.add(endColorButton, c);
c.gridx = 3;
gen_nodeAction.add(presetPalettes, c);
if (((Graph)m_vis.getGroup(GRAPH)).getNodeTable().getColumnNumber("inTPT") >= 0) {
c.gridy = 4;
c.gridx = 1;
c.gridwidth = 2;
c.insets = new Insets(10,0,0,0);
gen_nodeAction.add(nodeFilterButton, c);
}
gen_node.setOpaque(false);
gen_nodeAction.setOpaque(false);
node_Panel.add(gen_node);
node_Panel.add(gen_nodeAction);
node_Panel.setOpaque(false);
/* ----------------------- LABEL PANE ----------------------- */
JPanel lr_Panel = new JPanel();
lr_Panel.setLayout(new GridLayout(0,2));
pane.addTab("Label", lr_Panel);
final JSpinner lr_Rounded = new JSpinner(new SpinnerNumberModel(8, 0, 1000000000, 1));
lr_Rounded.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ce) {
m_lr.setRoundedCorner((Integer)lr_Rounded.getValue(), (Integer)lr_Rounded.getValue());
m_vis.run("nodeFill");
m_vis.repaint();
}
});
lr_Panel.add(new JLabel("Rounding Radius: ", JLabel.RIGHT));
lr_Panel.add(lr_Rounded);
final JComboBox lr_fontSize = new JComboBox(FONTSIZES);
lr_fontSize.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
m_vis.setValue(NODES, null, VisualItem.FONT, FontLib.getFont("Tahoma", (Integer)lr_fontSize.getSelectedItem()));
m_vis.run("nodeFill");
m_vis.repaint();
}
});
lr_fontSize.setSelectedItem(((VisualItem)m_vis.getVisualGroup(NODES).tuples().next()).getFont().getSize());
lr_Panel.add(new JLabel("Label Font Size: ", JLabel.RIGHT));
lr_Panel.add(lr_fontSize);
final JComboBox lr_imagePos = new JComboBox(IMAGEPOS_LABELS);
lr_imagePos.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
m_lr.setImagePosition(IMAGEPOS[lr_imagePos.getSelectedIndex()]);
m_vis.run("nodeFill");
m_vis.repaint();
}
});
lr_Panel.add(new JLabel("Image Position: ", JLabel.RIGHT));
lr_Panel.add(lr_imagePos);
final JToggleButton lr_showLabel = new JToggleButton("Images Only", m_lr.getTextField() == null);
lr_showLabel.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (m_lr.getImageField() != null) {
if (lr_showLabel.isSelected()) {
m_lr.setTextField(null);
} else {
m_lr.setTextField(LABEL);
}
m_vis.run("nodeFill");
m_vis.repaint();
} else {
//if no images are visble, we don't want
//to make nodes disappear, so refuse
//to select
lr_showLabel.setSelected(false);
}
}
});
lr_Panel.add(lr_showLabel);
final JButton lr_showLabelColorChooser = new JButton("Text Color", new ColorSwatch(
new Color(((VisualItem)m_vis.getGroup(NODES).tuples().next()).getTextColor())));
lr_showLabelColorChooser.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
FlexDataColorAction fill = (FlexDataColorAction)((ActionList)m_vis.getAction("animate")).get(2);
Color newFill = JColorChooser.showDialog(f, "Choose Node Color", new Color(fill.getDefaultColor()));
if (newFill != null) {
m_vis.setValue(NODES, null, VisualItem.TEXTCOLOR, newFill.getRGB());
((ColorSwatch)lr_showLabelColorChooser.getIcon()).setColor(newFill);
}
} catch (Exception e) {
Logger.getLogger(MSMExplorer.class.getName()).log(Level.SEVERE, null, e);
}
}
});
lr_showLabelColorChooser.setToolTipText("Open a dialog to select a new label text color.");
lr_Panel.add(lr_showLabelColorChooser);
lr_Panel.add(Box.createVerticalGlue());
lr_Panel.setOpaque(false);
/* ------------------ SHAPE PANE --------------------- */
JPanel sr_Panel = new JPanel(new GridBagLayout());
pane.addTab("Shape", sr_Panel);
final JComboBox shapeComboBox = new JComboBox(SHAPES_LABELS);
shapeComboBox.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
m_vis.setValue(NODES, null, VisualItem.SHAPE, SHAPES[shapeComboBox.getSelectedIndex()]);
m_vis.run("nodeFill");
m_vis.repaint();
}
});
final JComboBox shapeActionField = new JComboBox(fields);
shapeActionField.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
ActionList draw = (ActionList)m_vis.getAction("draw");
DataShapeAction dataShapeAction = null;
assert draw.size() > 1;
if (draw.get(draw.size() - 1) instanceof DataShapeAction) {
dataShapeAction = (DataShapeAction)draw.get(draw.size() - 1);
} else if (draw.get(draw.size() - 2) instanceof DataShapeAction) {
dataShapeAction = (DataShapeAction)draw.get(draw.size() - 2);
}
if (dataShapeAction != null) {
dataShapeAction.setDataField((String)shapeActionField.getSelectedItem());
} else {
dataShapeAction = new DataShapeAction(NODES, (String)shapeActionField.getSelectedItem());
dataShapeAction.setVisualization(m_vis);
draw.add(dataShapeAction);
}
m_vis.run("draw");
m_vis.repaint();
}
});
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2;
sr_Panel.add(new JLabel("Node Shape: "), c);
c.gridx = 2;
sr_Panel.add(shapeComboBox, c);
c.insets = new Insets(10,0,0,0);
c.gridx = 0;
c.gridy = 1;
sr_Panel.add(new JLabel("Node Shape Field:"), c);
c.gridx = 2;
c.gridy = 1;
sr_Panel.add(shapeActionField, c);
sr_Panel.setOpaque(false);
/* -------------------- EDGE PANE --------------------- */
JPanel er_Panel = new JPanel(new GridBagLayout());
pane.addTab("Edge", er_Panel);
final JToggleButton showSelfEdges = new JToggleButton("Show Self Edges", m_er.getRenderSelfEdges());
showSelfEdges.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
m_er.setRenderSelfEdges(showSelfEdges.isSelected());
m_vis.run("animate");
m_vis.repaint();
}
});
final ActionList animate = (ActionList)m_vis.getAction("animate");
final FlexDataColorAction edgeArrowColorAction = (FlexDataColorAction)animate.get(1);
final FlexDataColorAction edgeColorAction = (FlexDataColorAction)animate.get(2);
edgeColorAction.setDataType(Constants.NUMERICAL);
edgeArrowColorAction.setDataType(Constants.NUMERICAL);
final Table et = ((Graph)m_vis.getGroup(GRAPH)).getEdgeTable();
final Vector<String> etFields = new Vector<String>(5);
final Vector<String> etNumFields = new Vector<String>(5);
for (int i = et.getColumnNumber(TPROB); i < et.getColumnCount(); ++i) {
if (isNumerical(et.getColumn(i))) {
etNumFields.add(et.getColumnName(i));
}
etFields.add(et.getColumnName(i));
}
final JComboBox edgeColorScaleField = new JComboBox(SCALE_LABELS);
final JComboBox edgeColorField = new JComboBox(etFields);
edgeColorField.setSelectedItem(edgeColorAction.getDataField());
edgeColorField.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int dataType = Constants.ORDINAL;
String col = (String)edgeColorField.getSelectedItem();
if (isNumerical(et.getColumn(col))) {
dataType = Constants.NUMERICAL;
edgeColorAction.setBinCount(10);
edgeColorAction.setScale(SCALE_TYPES[edgeColorScaleField.getSelectedIndex()]);
}
edgeColorAction.setDataField(col);
edgeColorAction.setDataType(dataType);
edgeArrowColorAction.setDataField(col);
edgeArrowColorAction.setDataType(dataType);
m_vis.run("animate");
m_vis.repaint();
}
});
edgeColorScaleField.setSelectedIndex(Arrays.binarySearch(SCALE_TYPES, nodeColorAction.getScale()));
edgeColorScaleField.addActionListener( new ScaleComboxActionListener(edgeColorScaleField,
new ArrayList<EncoderAction>(2){{add(edgeColorAction);add(edgeArrowColorAction);}},
m_vis.getAction("animate")));
final JComboBox edgePresetPalettes = new JComboBox(PALETTE_LABELS);
int[] er_palette = edgeColorAction.getPalette();
final JButton edgeStartColorButton = new JButton("Start Color", new
ColorSwatch(new Color(er_palette[0])));
edgeStartColorButton.addActionListener( new PaletteColorButtonActionListener(f, edgeStartColorButton,
new ArrayList<FlexDataColorAction>() {{add(edgeColorAction); add(edgeArrowColorAction);}},
PaletteColorButtonActionListener.START, edgePresetPalettes));
final JButton edgeEndColorButton = new JButton("End Color", new
ColorSwatch(new Color(er_palette[er_palette.length-1])));
edgeEndColorButton.addActionListener( new PaletteColorButtonActionListener(f, edgeEndColorButton,
new ArrayList<FlexDataColorAction>() {{add(edgeColorAction); add(edgeArrowColorAction);}},
PaletteColorButtonActionListener.END, edgePresetPalettes));
edgePresetPalettes.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int[] palette;
switch (edgePresetPalettes.getSelectedIndex()) {
case 0:
palette = ColorLib.getInterpolatedPalette(((ColorSwatch)
edgeStartColorButton.getIcon()).getColor().getRGB(),
((ColorSwatch)edgeEndColorButton.getIcon()).getColor().getRGB());
break;
case 1:
palette = ColorLib.getCategoryPalette(12);
break;
case 2:
palette = ColorLib.getCoolPalette();
break;
case 3:
palette = ColorLib.getHotPalette();
break;
case 4:
palette = ColorLib.getGrayscalePalette();
break;
case 5:
palette = ColorLib.getHSBPalette();
break;
default:
return;
}
edgeColorAction.setPalette(palette);
edgeArrowColorAction.setPalette(palette);
m_vis.run("animate");
m_vis.repaint();
}
});
final DataSizeAction edgeWeightAction = (DataSizeAction)animate.get(0);
int smallw = (int)edgeWeightAction.getMinimumSize();
int largew = (int)edgeWeightAction.getMaximumSize();
smallw = (smallw > 0) ? smallw : 1;
largew = (largew > 0) ? largew : 1;
final JRangeSlider edgeWeightSlider = new JRangeSlider(1, 100000, smallw, largew, Constants.ORIENT_TOP_BOTTOM);
edgeWeightSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JRangeSlider slider = (JRangeSlider) e.getSource();
edgeWeightAction.setMinimumSize((double)slider.getLowValue()/5.0d);
edgeWeightAction.setMaximumSize((double)slider.getHighValue()/5.0d);
m_vis.run("animate");
m_vis.repaint();
}
});
edgeWeightSlider.setToolTipText("Set the range for edge thickness.");
final JComboBox edgeWeightField = new JComboBox(etNumFields);
edgeWeightField.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
double lowVal = edgeWeightSlider.getLowValue();
double highVal = edgeWeightSlider.getHighValue();
if (lowVal < 1) {
lowVal = 1;
}
if (highVal < 1) {
highVal = 1;
}
edgeWeightAction.setDataField((String)edgeWeightField.getSelectedItem());
edgeWeightAction.setMinimumSize(lowVal);
edgeWeightAction.setMaximumSize(highVal);
m_vis.run("animate");
m_vis.repaint();
}
});
final JComboBox edgeWeightScaleField = new JComboBox(SCALE_LABELS);
edgeWeightScaleField.addActionListener( new ScaleComboxActionListener(edgeWeightScaleField,
edgeWeightAction, m_vis.getAction("animate")));
edgeWeightScaleField.setSelectedIndex(Arrays.binarySearch(SCALE_TYPES, nodeColorAction.getScale()));
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 2;
c.gridx = 1;
c.gridy = 0;
er_Panel.add(showSelfEdges, c);
c.insets = new Insets(10,0,0,0);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
er_Panel.add(new JLabel("Edge Color Field: "), c);
c.gridx = 1;
er_Panel.add(edgeColorField, c);
c.gridx = 2;
er_Panel.add(new JLabel("Scale Type: ", JLabel.RIGHT), c);
c.gridx = 3;
er_Panel.add(edgeColorScaleField, c);
c.insets = new Insets(0,0,0,0);
c.gridx = 1;
c.gridy = 2;
er_Panel.add(edgeStartColorButton, c);
c.gridx = 2;
er_Panel.add(edgeEndColorButton, c);
c.gridx = 3;
er_Panel.add(edgePresetPalettes, c);
c.insets = new Insets(20,0,0,0);
c.gridx = 0;
c.gridy = 3;
er_Panel.add(new JLabel("Edge Weight Field: "), c);
c.gridx = 1;
er_Panel.add(edgeWeightField, c);
c.gridx = 2;
er_Panel.add(new JLabel("Scale Type: ", JLabel.RIGHT), c);
c.gridx = 3;
er_Panel.add(edgeWeightScaleField, c);
c.insets = new Insets(0,0,0,0);
c.gridy = 4;
c.gridx = 0;
er_Panel.add(new JLabel("Weight Range: "), c);
c.gridx = 1;
c.gridwidth = 3;
er_Panel.add(edgeWeightSlider, c);
er_Panel.setOpaque(false);
/* --------------------- AGG PANE ----------------------- */
if (m_pr != null) {
assert m_pr != null;
JPanel pr_Panel = new JPanel( new GridBagLayout());
pane.addTab("Agg.", pr_Panel);
final JSpinner aggCurve = new JSpinner(new SpinnerNumberModel(m_pr.getCurveSlack(), 0.0d, 10.0d, .02d));
aggCurve.addChangeListener( new ChangeListener() {
public void stateChanged(ChangeEvent ce) {
m_pr.setCurveSlack(((Double)aggCurve.getValue()).floatValue());
m_vis.run("aggLayout");
m_vis.repaint();
}
});
aggCurve.setPreferredSize(new Dimension(100, 30));
final JComboBox pr_presetPalettes = new JComboBox(PALETTE_LABELS);
final FlexDataColorAction aggrColorAction;
if (draw.get(draw.size() - 1) instanceof FlexDataColorAction) {
aggrColorAction = (FlexDataColorAction)draw.get(draw.size() - 1);
} else if (draw.get(draw.size() - 2) instanceof FlexDataColorAction) {
aggrColorAction = (FlexDataColorAction)draw.get(draw.size() - 2);
} else {
assert 1 == 0;
aggrColorAction = null;
}
int[] aggrPalette = aggrColorAction.getPalette();
final JButton aggrStartColorButton = new JButton("Start Color", new ColorSwatch(new Color(aggrPalette[0])));
aggrStartColorButton.addActionListener( new PaletteColorButtonActionListener(f, aggrStartColorButton,
aggrColorAction, PaletteColorButtonActionListener.START, pr_presetPalettes));
final JButton aggrEndColorButton = new JButton("End Color", new ColorSwatch(new Color(aggrPalette[aggrPalette.length-1])));
aggrEndColorButton.addActionListener( new PaletteColorButtonActionListener(f, aggrEndColorButton,
aggrColorAction, PaletteColorButtonActionListener.END, pr_presetPalettes));
ActionList lll = ((ActionList) m_vis.getAction("lll"));
final AggForceDirectedLayout afdl = ((AggForceDirectedLayout)lll.get(0));
final JToggleButton aggrLayoutMode = new JToggleButton("Agg-Lump Layout", afdl.isAggLump());
aggrLayoutMode.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
afdl.setAggLump(aggrLayoutMode.isSelected());
m_vis.run("lll");
}
});
pr_presetPalettes.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int[] palette;
switch (pr_presetPalettes.getSelectedIndex()) {
case 0:
Color start = ((ColorSwatch)aggrStartColorButton.getIcon()).getColor();
Color end = ((ColorSwatch)aggrEndColorButton.getIcon()).getColor();
palette = ColorLib.getInterpolatedPalette(start.getRGB(), end.getRGB());
break;
case 1:
palette = ColorLib.getCategoryPalette(50, 0.95f, .15f, .9f, .5f);
break;
case 2:
palette = ColorLib.getCoolPalette();
break;
case 3:
palette = ColorLib.getHotPalette();
break;
case 4:
palette = ColorLib.getGrayscalePalette();
break;
case 5:
palette = ColorLib.getHSBPalette();
break;
default:
return;
}
//This bit of crunchiness sets the alpha at value 128
//redundant for category palette but it's hard to argue
//that's a big issue...
for (int i = 0; i < palette.length; ++i) {
palette[i] = (palette[i] | 0x80000000) & 0x80ffffff;
}
aggrColorAction.setPalette(palette);
m_vis.run("draw");
m_vis.repaint();
}
});
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
pr_Panel.add(new JLabel("Aggregate Curve Slack: "), c);
c.gridx = 1;
pr_Panel.add(aggCurve, c);
c.insets = new Insets(10,0,0,0);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
pr_Panel.add(aggrStartColorButton, c);
c.gridx = 1;
pr_Panel.add(aggrEndColorButton, c);
c.gridx = 2;
pr_Panel.add(pr_presetPalettes, c);
c.gridy = 2;
c.gridx = 0;
c.gridwidth = 2;
pr_Panel.add(aggrLayoutMode, c);
pr_Panel.setOpaque(false);
}
pane.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT); //unfortunately doesn't seem to affect OSX...
add(pane);
pack();
}
|
diff --git a/jminix/src/main/java/org/jminix/console/resource/AbstractTemplateResource.java b/jminix/src/main/java/org/jminix/console/resource/AbstractTemplateResource.java
index 669b84e..056b6d9 100644
--- a/jminix/src/main/java/org/jminix/console/resource/AbstractTemplateResource.java
+++ b/jminix/src/main/java/org/jminix/console/resource/AbstractTemplateResource.java
@@ -1,302 +1,302 @@
/*
* Copyright 2009 Laurent Bovet, Swiss Post IT <[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.jminix.console.resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanServerConnection;
import net.sf.json.JSONSerializer;
import org.apache.velocity.Template;
import org.apache.velocity.app.VelocityEngine;
import org.restlet.Context;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.ext.velocity.TemplateRepresentation;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.ResourceException;
import org.restlet.resource.StringRepresentation;
import org.restlet.resource.Variant;
import org.jminix.server.ServerConnectionProvider;
import org.jminix.type.HtmlContent;
public abstract class AbstractTemplateResource extends Resource
{
public String a;
private final static String VELOCITY_ENGINE_CONTEX_KEY = "template.resource.velocity.engine";
public AbstractTemplateResource(Context context, Request request, Response response)
{
super(context, request, response);
getVariants().add(new Variant(MediaType.TEXT_HTML));
getVariants().add(new Variant(MediaType.TEXT_PLAIN));
getVariants().add(new Variant(MediaType.APPLICATION_JSON));
VelocityEngine ve =
(VelocityEngine) context.getAttributes().get(VELOCITY_ENGINE_CONTEX_KEY);
if (ve == null)
{
ve = new VelocityEngine();
Properties p = new Properties();
p.setProperty("resource.loader", "class");
p.setProperty("class.resource.loader.description",
"Velocity Classpath Resource Loader");
p.setProperty("class.resource.loader.class",
"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
p.setProperty("runtime.log.logsystem.log4j.logger", "common.jmx.velocity");
try
{
ve.init(p);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
context.getAttributes().put(VELOCITY_ENGINE_CONTEX_KEY, ve);
}
}
protected abstract String getTemplateName();
protected abstract Map<String, Object> getModel();
@Override
public Representation represent(Variant variant) throws ResourceException
{
// To avoid IE caching causing conflicts between JSON and HTML representations in ajax
// console
Form responseHeaders =
(Form) getResponse().getAttributes().get("org.restlet.http.headers");
if (responseHeaders == null)
{
responseHeaders = new Form();
getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
}
responseHeaders.add("Cache-Control", "no-store, no-cache, must-revalidate");
responseHeaders.add("Cache-Control", "post-check=0, pre-check=0");
responseHeaders.add("Pragma", "no-cache");
responseHeaders.add("Expires", "0");
if (MediaType.TEXT_HTML.equals(variant.getMediaType()))
{
Map<String, Object> enrichedModel = new HashMap<String, Object>(getModel());
String templateName = getTemplateName();
if(enrichedModel.get("value") instanceof HtmlContent) {
templateName = "html-attribute";
}
Template template;
try
{
VelocityEngine ve =
(VelocityEngine) getContext().getAttributes().get(
VELOCITY_ENGINE_CONTEX_KEY);
template = ve.getTemplate("jminix/templates/" + templateName + ".vm");
}
catch (Exception e)
{
throw new RuntimeException(e);
}
String skin = getRequest().getResourceRef().getQueryAsForm().getValues("skin");
if(skin==null) {
skin="default";
}
String desc = getRequest().getResourceRef().getQueryAsForm().getValues("desc");
if(desc==null) {
desc="on";
}
enrichedModel.put("query", getQueryString());
enrichedModel.put("ok", "1".equals(getRequest().getResourceRef().getQueryAsForm().getValues("ok")));
enrichedModel.put("margin", "embedded".equals(skin) ? 0 : 5);
enrichedModel.put("skin", skin);
enrichedModel.put("desc", desc);
enrichedModel.put("encoder", new EncoderBean());
enrichedModel.put("request", getRequest());
return new TemplateRepresentation(template, enrichedModel, MediaType.TEXT_HTML);
}
else if (MediaType.TEXT_PLAIN.equals(variant.getMediaType()))
{
Map<String, Object> enrichedModel = new HashMap<String, Object>(getModel());
Template template;
try
{
VelocityEngine ve = new VelocityEngine();
Properties p = new Properties();
p.setProperty("resource.loader", "class");
p.setProperty("class.resource.loader.description",
"Velocity Classpath Resource Loader");
p.setProperty("class.resource.loader.class",
"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
ve.init(p);
template =
ve.getTemplate("jminix/templates/"
+ getTemplateName() + "-plain.vm");
}
catch (Exception e)
{
throw new RuntimeException(e);
}
enrichedModel.put("encoder", new EncoderBean());
enrichedModel.put("request", getRequest());
return new TemplateRepresentation(template, enrichedModel, MediaType.TEXT_PLAIN);
}
else if (MediaType.APPLICATION_JSON.equals(variant.getMediaType()))
{
// Translate known models, needs a refactoring to embed that in each resource...
HashMap<String, Object> result = new HashMap<String, Object>();
result.put("label", getRequest().getOriginalRef().getLastSegment(true));
String beforeLast =
getRequest().getOriginalRef().getSegments().size() > 2 ? getRequest()
.getResourceRef().getSegments().get(
getRequest().getOriginalRef().getSegments().size() - 3) : null;
boolean leaf = "attributes".equals(beforeLast) || "operations".equals(beforeLast);
if (getModel().containsKey("items") && !leaf)
{
Object items = getModel().get("items");
Collection<Object> itemCollection = null;
if (items instanceof Collection)
{
itemCollection = (Collection<Object>) items;
}
else
{
itemCollection = Arrays.asList(items);
}
List<Map<String, String>> children = new ArrayList<Map<String, String>>();
for (Object item : itemCollection)
{
HashMap<String, String> ref = new HashMap<String, String>();
if (item instanceof MBeanAttributeInfo)
{
ref.put("$ref", new EncoderBean().encode(escape(((MBeanAttributeInfo) item).getName())) + "/");
}
else if (item instanceof Map && ((Map) item).containsKey("declaration"))
{
ref.put("$ref", ((Map) item).get("declaration").toString());
}
else
{
ref.put("$ref", escape(item.toString()) + "/");
}
children.add(ref);
}
result.put("children", children);
}
else
{
if (getModel().containsKey("value"))
{
if(getModel().get("value") instanceof HtmlContent) {
result.put("value", "...");
} else {
result.put("value", getModel().get("value").toString());
}
}
else if (getModel().containsKey("items"))
{
Object items = getModel().get("items");
String value = null;
if(items.getClass().isArray()) {
- value = Arrays.deepToString((Object[])items);
+ value = Arrays.deepToString(Arrays.asList(items).toArray());
} else {
value = items.toString();
}
result.put("value", value);
}
}
// Hack because root must be a list for dojo tree...
if ("servers".equals(getRequest().getOriginalRef().getLastSegment(true)))
{
return new StringRepresentation(JSONSerializer.toJSON(new Object[]{result})
.toString());
}
else
{
return new StringRepresentation(JSONSerializer.toJSON(result).toString());
}
}
else
{
return null;
}
}
protected ServerConnectionProvider getServerProvider()
{
return (ServerConnectionProvider) getContext().getAttributes().get(
"serverProvider");
}
protected MBeanServerConnection getServer()
{
return getServerProvider().getConnection(getRequest().getAttributes().get("server").toString());
}
protected String getQueryString() {
String query = getRequest().getResourceRef().getQuery();
return query!=null ? "?"+query : "";
}
protected String escape(String value) {
return value.replaceAll("/", "¦");
}
protected String unescape(String value) {
return value.replaceAll("¦", "/");
}
}
| true | true | public Representation represent(Variant variant) throws ResourceException
{
// To avoid IE caching causing conflicts between JSON and HTML representations in ajax
// console
Form responseHeaders =
(Form) getResponse().getAttributes().get("org.restlet.http.headers");
if (responseHeaders == null)
{
responseHeaders = new Form();
getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
}
responseHeaders.add("Cache-Control", "no-store, no-cache, must-revalidate");
responseHeaders.add("Cache-Control", "post-check=0, pre-check=0");
responseHeaders.add("Pragma", "no-cache");
responseHeaders.add("Expires", "0");
if (MediaType.TEXT_HTML.equals(variant.getMediaType()))
{
Map<String, Object> enrichedModel = new HashMap<String, Object>(getModel());
String templateName = getTemplateName();
if(enrichedModel.get("value") instanceof HtmlContent) {
templateName = "html-attribute";
}
Template template;
try
{
VelocityEngine ve =
(VelocityEngine) getContext().getAttributes().get(
VELOCITY_ENGINE_CONTEX_KEY);
template = ve.getTemplate("jminix/templates/" + templateName + ".vm");
}
catch (Exception e)
{
throw new RuntimeException(e);
}
String skin = getRequest().getResourceRef().getQueryAsForm().getValues("skin");
if(skin==null) {
skin="default";
}
String desc = getRequest().getResourceRef().getQueryAsForm().getValues("desc");
if(desc==null) {
desc="on";
}
enrichedModel.put("query", getQueryString());
enrichedModel.put("ok", "1".equals(getRequest().getResourceRef().getQueryAsForm().getValues("ok")));
enrichedModel.put("margin", "embedded".equals(skin) ? 0 : 5);
enrichedModel.put("skin", skin);
enrichedModel.put("desc", desc);
enrichedModel.put("encoder", new EncoderBean());
enrichedModel.put("request", getRequest());
return new TemplateRepresentation(template, enrichedModel, MediaType.TEXT_HTML);
}
else if (MediaType.TEXT_PLAIN.equals(variant.getMediaType()))
{
Map<String, Object> enrichedModel = new HashMap<String, Object>(getModel());
Template template;
try
{
VelocityEngine ve = new VelocityEngine();
Properties p = new Properties();
p.setProperty("resource.loader", "class");
p.setProperty("class.resource.loader.description",
"Velocity Classpath Resource Loader");
p.setProperty("class.resource.loader.class",
"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
ve.init(p);
template =
ve.getTemplate("jminix/templates/"
+ getTemplateName() + "-plain.vm");
}
catch (Exception e)
{
throw new RuntimeException(e);
}
enrichedModel.put("encoder", new EncoderBean());
enrichedModel.put("request", getRequest());
return new TemplateRepresentation(template, enrichedModel, MediaType.TEXT_PLAIN);
}
else if (MediaType.APPLICATION_JSON.equals(variant.getMediaType()))
{
// Translate known models, needs a refactoring to embed that in each resource...
HashMap<String, Object> result = new HashMap<String, Object>();
result.put("label", getRequest().getOriginalRef().getLastSegment(true));
String beforeLast =
getRequest().getOriginalRef().getSegments().size() > 2 ? getRequest()
.getResourceRef().getSegments().get(
getRequest().getOriginalRef().getSegments().size() - 3) : null;
boolean leaf = "attributes".equals(beforeLast) || "operations".equals(beforeLast);
if (getModel().containsKey("items") && !leaf)
{
Object items = getModel().get("items");
Collection<Object> itemCollection = null;
if (items instanceof Collection)
{
itemCollection = (Collection<Object>) items;
}
else
{
itemCollection = Arrays.asList(items);
}
List<Map<String, String>> children = new ArrayList<Map<String, String>>();
for (Object item : itemCollection)
{
HashMap<String, String> ref = new HashMap<String, String>();
if (item instanceof MBeanAttributeInfo)
{
ref.put("$ref", new EncoderBean().encode(escape(((MBeanAttributeInfo) item).getName())) + "/");
}
else if (item instanceof Map && ((Map) item).containsKey("declaration"))
{
ref.put("$ref", ((Map) item).get("declaration").toString());
}
else
{
ref.put("$ref", escape(item.toString()) + "/");
}
children.add(ref);
}
result.put("children", children);
}
else
{
if (getModel().containsKey("value"))
{
if(getModel().get("value") instanceof HtmlContent) {
result.put("value", "...");
} else {
result.put("value", getModel().get("value").toString());
}
}
else if (getModel().containsKey("items"))
{
Object items = getModel().get("items");
String value = null;
if(items.getClass().isArray()) {
value = Arrays.deepToString((Object[])items);
} else {
value = items.toString();
}
result.put("value", value);
}
}
// Hack because root must be a list for dojo tree...
if ("servers".equals(getRequest().getOriginalRef().getLastSegment(true)))
{
return new StringRepresentation(JSONSerializer.toJSON(new Object[]{result})
.toString());
}
else
{
return new StringRepresentation(JSONSerializer.toJSON(result).toString());
}
}
else
{
return null;
}
}
| public Representation represent(Variant variant) throws ResourceException
{
// To avoid IE caching causing conflicts between JSON and HTML representations in ajax
// console
Form responseHeaders =
(Form) getResponse().getAttributes().get("org.restlet.http.headers");
if (responseHeaders == null)
{
responseHeaders = new Form();
getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
}
responseHeaders.add("Cache-Control", "no-store, no-cache, must-revalidate");
responseHeaders.add("Cache-Control", "post-check=0, pre-check=0");
responseHeaders.add("Pragma", "no-cache");
responseHeaders.add("Expires", "0");
if (MediaType.TEXT_HTML.equals(variant.getMediaType()))
{
Map<String, Object> enrichedModel = new HashMap<String, Object>(getModel());
String templateName = getTemplateName();
if(enrichedModel.get("value") instanceof HtmlContent) {
templateName = "html-attribute";
}
Template template;
try
{
VelocityEngine ve =
(VelocityEngine) getContext().getAttributes().get(
VELOCITY_ENGINE_CONTEX_KEY);
template = ve.getTemplate("jminix/templates/" + templateName + ".vm");
}
catch (Exception e)
{
throw new RuntimeException(e);
}
String skin = getRequest().getResourceRef().getQueryAsForm().getValues("skin");
if(skin==null) {
skin="default";
}
String desc = getRequest().getResourceRef().getQueryAsForm().getValues("desc");
if(desc==null) {
desc="on";
}
enrichedModel.put("query", getQueryString());
enrichedModel.put("ok", "1".equals(getRequest().getResourceRef().getQueryAsForm().getValues("ok")));
enrichedModel.put("margin", "embedded".equals(skin) ? 0 : 5);
enrichedModel.put("skin", skin);
enrichedModel.put("desc", desc);
enrichedModel.put("encoder", new EncoderBean());
enrichedModel.put("request", getRequest());
return new TemplateRepresentation(template, enrichedModel, MediaType.TEXT_HTML);
}
else if (MediaType.TEXT_PLAIN.equals(variant.getMediaType()))
{
Map<String, Object> enrichedModel = new HashMap<String, Object>(getModel());
Template template;
try
{
VelocityEngine ve = new VelocityEngine();
Properties p = new Properties();
p.setProperty("resource.loader", "class");
p.setProperty("class.resource.loader.description",
"Velocity Classpath Resource Loader");
p.setProperty("class.resource.loader.class",
"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
ve.init(p);
template =
ve.getTemplate("jminix/templates/"
+ getTemplateName() + "-plain.vm");
}
catch (Exception e)
{
throw new RuntimeException(e);
}
enrichedModel.put("encoder", new EncoderBean());
enrichedModel.put("request", getRequest());
return new TemplateRepresentation(template, enrichedModel, MediaType.TEXT_PLAIN);
}
else if (MediaType.APPLICATION_JSON.equals(variant.getMediaType()))
{
// Translate known models, needs a refactoring to embed that in each resource...
HashMap<String, Object> result = new HashMap<String, Object>();
result.put("label", getRequest().getOriginalRef().getLastSegment(true));
String beforeLast =
getRequest().getOriginalRef().getSegments().size() > 2 ? getRequest()
.getResourceRef().getSegments().get(
getRequest().getOriginalRef().getSegments().size() - 3) : null;
boolean leaf = "attributes".equals(beforeLast) || "operations".equals(beforeLast);
if (getModel().containsKey("items") && !leaf)
{
Object items = getModel().get("items");
Collection<Object> itemCollection = null;
if (items instanceof Collection)
{
itemCollection = (Collection<Object>) items;
}
else
{
itemCollection = Arrays.asList(items);
}
List<Map<String, String>> children = new ArrayList<Map<String, String>>();
for (Object item : itemCollection)
{
HashMap<String, String> ref = new HashMap<String, String>();
if (item instanceof MBeanAttributeInfo)
{
ref.put("$ref", new EncoderBean().encode(escape(((MBeanAttributeInfo) item).getName())) + "/");
}
else if (item instanceof Map && ((Map) item).containsKey("declaration"))
{
ref.put("$ref", ((Map) item).get("declaration").toString());
}
else
{
ref.put("$ref", escape(item.toString()) + "/");
}
children.add(ref);
}
result.put("children", children);
}
else
{
if (getModel().containsKey("value"))
{
if(getModel().get("value") instanceof HtmlContent) {
result.put("value", "...");
} else {
result.put("value", getModel().get("value").toString());
}
}
else if (getModel().containsKey("items"))
{
Object items = getModel().get("items");
String value = null;
if(items.getClass().isArray()) {
value = Arrays.deepToString(Arrays.asList(items).toArray());
} else {
value = items.toString();
}
result.put("value", value);
}
}
// Hack because root must be a list for dojo tree...
if ("servers".equals(getRequest().getOriginalRef().getLastSegment(true)))
{
return new StringRepresentation(JSONSerializer.toJSON(new Object[]{result})
.toString());
}
else
{
return new StringRepresentation(JSONSerializer.toJSON(result).toString());
}
}
else
{
return null;
}
}
|
diff --git a/ecologylab/generic/ReflectionTools.java b/ecologylab/generic/ReflectionTools.java
index e00e5397..4c3cde2e 100644
--- a/ecologylab/generic/ReflectionTools.java
+++ b/ecologylab/generic/ReflectionTools.java
@@ -1,235 +1,237 @@
package ecologylab.generic;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* Utility routines for working with reflection.
*
* @author andruid
*/
public class ReflectionTools extends Debug
{
/**
* Get the Field object with name fieldName, in thatClass.
*
* @param thatClass
* @param fieldName
*
* @return The Field object in thatClass, or null if there is none accessible.
*/
public static Field getField(Class thatClass, String fieldName)
{
Field result = null;
try
{
result = thatClass.getField(fieldName);
} catch (SecurityException e)
{
} catch (NoSuchFieldException e)
{
}
return result;
}
/**
* Get the Field object with name fieldName, in thatClass.
*
* @param thatClass
* @param fieldName
*
* @return The Field object in thatClass, or null if there is none accessible.
*/
public static Field getDeclaredField(Class thatClass, String fieldName)
{
Field result = null;
try
{
result = thatClass.getDeclaredField(fieldName);
} catch (SecurityException e)
{
} catch (NoSuchFieldException e)
{
}
return result;
}
public static final Object BAD_ACCESS = new Object();
/**
* Return the value of the Field in the Object, or BAD_ACCESS if it can't be accessed.
*
* @param that
* @param field
* @return
*/
public static Object getFieldValue(Object that, Field field)
{
Object result = null;
try
{
result = field.get(that);
} catch (IllegalArgumentException e)
{
result = BAD_ACCESS;
e.printStackTrace();
} catch (IllegalAccessException e)
{
result = BAD_ACCESS;
e.printStackTrace();
}
return result;
}
/**
* Set a reference type Field to a value.
*
* @param that Object that the field is in.
* @param field Reference type field within that object.
* @param value Value to set the reference field to.
*
* @return true if the set succeeds.
*/
public static boolean setFieldValue(Object that, Field field, Object value)
{
boolean result = false;
try
{
field.set(that, value);
result = true;
} catch (IllegalArgumentException e)
{
e.printStackTrace();
} catch (IllegalAccessException e)
{
e.printStackTrace();
}
return true;
}
/**
* Wraps the no argument getInstance() method.
* Checks to see if the class object passed in is null, or if
* any exceptions are thrown by newInstance().
*
* @param thatClass
* @return An instance of an object of the specified class, or null if the Class object was null or
* an InstantiationException or IllegalAccessException was thrown in the attempt to instantiate.
*/
public static<T> T getInstance(Class<T> thatClass)
{
T result = null;
if (thatClass != null)
{
try
{
result = thatClass.newInstance();
} catch (InstantiationException e)
{
e.printStackTrace();
} catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
return result;
}
/**
* Wraps the no argument getInstance() method.
* Checks to see if the class object passed in is null, or if
* any exceptions are thrown by newInstance().
*
* @param thatClass
* @return An instance of an object of the specified class, or null if the Class object was null or
* an InstantiationException or IllegalAccessException was thrown in the attempt to instantiate.
*/
public static<T> T getInstance(Class<T> thatClass, Class[] parameterTypes, Object[] args)
{
T result = null;
if (thatClass != null)
{
try
{
Constructor<T> constructor = thatClass.getDeclaredConstructor(parameterTypes);
if (constructor != null)
result = constructor.newInstance(args);
} catch (SecurityException e1)
{
e1.printStackTrace();
} catch (NoSuchMethodException e1)
{
e1.printStackTrace();
} catch (IllegalArgumentException e)
{
e.printStackTrace();
} catch (InstantiationException e)
{
e.printStackTrace();
} catch (IllegalAccessException e)
{
e.printStackTrace();
} catch (InvocationTargetException e)
{
+ Throwable cause = e.getCause();
+ cause.printStackTrace();
e.printStackTrace();
}
}
return result;
}
/**
* Find a Method object if there is one in the context class, or return null if not.
*
* @param context Class to find the Method in.
* @param name Name of the method.
* @param types Array of Class objects indicating parameter types.
*
* @return The associated Method object, or null if non is accessible.
*/
public static Method getMethod(Class context, String name, Class[] types)
{
Method result = null;
try
{
result = context.getMethod(name, types);
} catch (SecurityException e)
{
} catch (NoSuchMethodException e)
{
}
return result;
}
/**
* See if the Field has the annotation in its declaration.
*
* @param field
* @param annotationClass
* @return
*/
public static boolean isAnnotationPresent(Field field, Class annotationClass)
{
return field.isAnnotationPresent(annotationClass);
}
/**
* Get the parameterized type tokens that the generic Field was declared with.
*
* @param reflectType
* @return
*/
public static Type[] getParameterizedTypeTokens(Field field)
{
Type[] result = null;
Type reflectType = field.getGenericType();
if (reflectType instanceof ParameterizedType)
{
ParameterizedType pType = (ParameterizedType) reflectType;
result = pType.getActualTypeArguments();
}
return result;
}
}
| true | true | public static<T> T getInstance(Class<T> thatClass, Class[] parameterTypes, Object[] args)
{
T result = null;
if (thatClass != null)
{
try
{
Constructor<T> constructor = thatClass.getDeclaredConstructor(parameterTypes);
if (constructor != null)
result = constructor.newInstance(args);
} catch (SecurityException e1)
{
e1.printStackTrace();
} catch (NoSuchMethodException e1)
{
e1.printStackTrace();
} catch (IllegalArgumentException e)
{
e.printStackTrace();
} catch (InstantiationException e)
{
e.printStackTrace();
} catch (IllegalAccessException e)
{
e.printStackTrace();
} catch (InvocationTargetException e)
{
e.printStackTrace();
}
}
return result;
}
| public static<T> T getInstance(Class<T> thatClass, Class[] parameterTypes, Object[] args)
{
T result = null;
if (thatClass != null)
{
try
{
Constructor<T> constructor = thatClass.getDeclaredConstructor(parameterTypes);
if (constructor != null)
result = constructor.newInstance(args);
} catch (SecurityException e1)
{
e1.printStackTrace();
} catch (NoSuchMethodException e1)
{
e1.printStackTrace();
} catch (IllegalArgumentException e)
{
e.printStackTrace();
} catch (InstantiationException e)
{
e.printStackTrace();
} catch (IllegalAccessException e)
{
e.printStackTrace();
} catch (InvocationTargetException e)
{
Throwable cause = e.getCause();
cause.printStackTrace();
e.printStackTrace();
}
}
return result;
}
|
diff --git a/src/gov/nist/javax/sip/parser/Pipeline.java b/src/gov/nist/javax/sip/parser/Pipeline.java
index d94bd6b1..66a080c6 100755
--- a/src/gov/nist/javax/sip/parser/Pipeline.java
+++ b/src/gov/nist/javax/sip/parser/Pipeline.java
@@ -1,201 +1,202 @@
/*
* Conditions Of Use
*
* This software was developed by employees of the National Institute of
* Standards and Technology (NIST), an agency of the Federal Government.
* Pursuant to title 15 Untied States Code Section 105, works of NIST
* employees are not subject to copyright protection in the United States
* and are considered to be in the public domain. As a result, a formal
* license is not needed to use the software.
*
* This software is provided by NIST as a service and is expressly
* provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY. NIST does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
* Permission to use this software is contingent upon your acceptance
* of the terms of this agreement
*
* .
*
*/
package gov.nist.javax.sip.parser;
import gov.nist.core.InternalErrorHandler;
import gov.nist.javax.sip.stack.SIPStackTimerTask;
import gov.nist.javax.sip.stack.timers.SipTimer;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.NoSuchElementException;
/**
* Input class for the pipelined parser. Buffer all bytes read from the socket
* and make them available to the message parser.
*
* @author M. Ranganathan (Contains a bug fix contributed by Rob Daugherty (
* Lucent Technologies) )
*
*/
public class Pipeline extends InputStream {
private LinkedList buffList;
private Buffer currentBuffer;
private boolean isClosed;
private SipTimer timer;
private InputStream pipe;
private int readTimeout;
private SIPStackTimerTask myTimerTask;
class MyTimer extends SIPStackTimerTask {
Pipeline pipeline;
private boolean isCancelled;
protected MyTimer(Pipeline pipeline) {
this.pipeline = pipeline;
}
public void runTask() {
if (this.isCancelled) {
this.pipeline = null;
return;
}
try {
pipeline.close();
} catch (IOException ex) {
InternalErrorHandler.handleException(ex);
}
}
@Override
public void cleanUpBeforeCancel() {
this.isCancelled = true;
this.pipeline = null;
super.cleanUpBeforeCancel();
}
}
class Buffer {
byte[] bytes;
int length;
int ptr;
public Buffer(byte[] bytes, int length) {
ptr = 0;
this.length = length;
this.bytes = bytes;
}
public int getNextByte() {
return (int) bytes[ptr++] & 0xFF;
}
}
public void startTimer() {
if (this.readTimeout == -1)
return;
// TODO make this a tunable number. For now 4 seconds
// between reads seems reasonable upper limit.
this.myTimerTask = new MyTimer(this);
this.timer.schedule(this.myTimerTask, this.readTimeout);
}
public void stopTimer() {
if (this.readTimeout == -1)
return;
if (this.myTimerTask != null)
this.timer.cancel(myTimerTask);
}
public Pipeline(InputStream pipe, int readTimeout, SipTimer timer) {
// pipe is the Socket stream
// this is recorded here to implement a timeout.
this.timer = timer;
this.pipe = pipe;
buffList = new LinkedList();
this.readTimeout = readTimeout;
}
public void write(byte[] bytes, int start, int length) throws IOException {
if (this.isClosed)
throw new IOException("Closed!!");
Buffer buff = new Buffer(bytes, length);
buff.ptr = start;
synchronized (this.buffList) {
buffList.add(buff);
buffList.notifyAll();
}
}
public void write(byte[] bytes) throws IOException {
if (this.isClosed)
throw new IOException("Closed!!");
Buffer buff = new Buffer(bytes, bytes.length);
synchronized (this.buffList) {
buffList.add(buff);
buffList.notifyAll();
}
}
public void close() throws IOException {
this.isClosed = true;
synchronized (this.buffList) {
this.buffList.notifyAll();
}
// JvB: added
this.pipe.close();
}
public int read() throws IOException {
// if (this.isClosed) return -1;
synchronized (this.buffList) {
if (currentBuffer != null
&& currentBuffer.ptr < currentBuffer.length) {
int retval = currentBuffer.getNextByte();
if (currentBuffer.ptr == currentBuffer.length)
this.currentBuffer = null;
return retval;
}
// Bug fix contributed by Rob Daugherty.
if (this.isClosed && this.buffList.isEmpty())
return -1;
try {
// wait till something is posted.
while (this.buffList.isEmpty()) {
this.buffList.wait();
- if (this.isClosed)
+ // jeand : Issue 314 : return -1 only is the buffer is empty
+ if (this.buffList.isEmpty() && this.isClosed)
return -1;
}
currentBuffer = (Buffer) this.buffList.removeFirst();
int retval = currentBuffer.getNextByte();
if (currentBuffer.ptr == currentBuffer.length)
this.currentBuffer = null;
return retval;
} catch (InterruptedException ex) {
throw new IOException(ex.getMessage());
} catch (NoSuchElementException ex) {
ex.printStackTrace();
throw new IOException(ex.getMessage());
}
}
}
}
| true | true | public int read() throws IOException {
// if (this.isClosed) return -1;
synchronized (this.buffList) {
if (currentBuffer != null
&& currentBuffer.ptr < currentBuffer.length) {
int retval = currentBuffer.getNextByte();
if (currentBuffer.ptr == currentBuffer.length)
this.currentBuffer = null;
return retval;
}
// Bug fix contributed by Rob Daugherty.
if (this.isClosed && this.buffList.isEmpty())
return -1;
try {
// wait till something is posted.
while (this.buffList.isEmpty()) {
this.buffList.wait();
if (this.isClosed)
return -1;
}
currentBuffer = (Buffer) this.buffList.removeFirst();
int retval = currentBuffer.getNextByte();
if (currentBuffer.ptr == currentBuffer.length)
this.currentBuffer = null;
return retval;
} catch (InterruptedException ex) {
throw new IOException(ex.getMessage());
} catch (NoSuchElementException ex) {
ex.printStackTrace();
throw new IOException(ex.getMessage());
}
}
}
| public int read() throws IOException {
// if (this.isClosed) return -1;
synchronized (this.buffList) {
if (currentBuffer != null
&& currentBuffer.ptr < currentBuffer.length) {
int retval = currentBuffer.getNextByte();
if (currentBuffer.ptr == currentBuffer.length)
this.currentBuffer = null;
return retval;
}
// Bug fix contributed by Rob Daugherty.
if (this.isClosed && this.buffList.isEmpty())
return -1;
try {
// wait till something is posted.
while (this.buffList.isEmpty()) {
this.buffList.wait();
// jeand : Issue 314 : return -1 only is the buffer is empty
if (this.buffList.isEmpty() && this.isClosed)
return -1;
}
currentBuffer = (Buffer) this.buffList.removeFirst();
int retval = currentBuffer.getNextByte();
if (currentBuffer.ptr == currentBuffer.length)
this.currentBuffer = null;
return retval;
} catch (InterruptedException ex) {
throw new IOException(ex.getMessage());
} catch (NoSuchElementException ex) {
ex.printStackTrace();
throw new IOException(ex.getMessage());
}
}
}
|
diff --git a/library/src/com/orm/StringUtil.java b/library/src/com/orm/StringUtil.java
index effb501..40fabf4 100644
--- a/library/src/com/orm/StringUtil.java
+++ b/library/src/com/orm/StringUtil.java
@@ -1,38 +1,38 @@
package com.orm;
public class StringUtil {
public static String toSQLName(String javaNotation) {
if(javaNotation.equalsIgnoreCase("_id"))
return "_id";
StringBuilder sb = new StringBuilder();
char[] buf = javaNotation.toCharArray();
for (int i = 0; i < buf.length; i++) {
char prevChar = (i > 0) ? buf[i - 1] : 0;
char c = buf[i];
char nextChar = (i < buf.length - 1) ? buf[i + 1] : 0;
boolean isFirstChar = (i == 0);
- if (isFirstChar || Character.isLowerCase(c)) {
+ if (isFirstChar || Character.isLowerCase(c) || Character.isDigit(c)) {
sb.append(Character.toUpperCase(c));
} else if (Character.isUpperCase(c)) {
if (Character.isLetterOrDigit(prevChar)) {
if (Character.isLowerCase(prevChar)) {
sb.append('_').append(Character.toUpperCase(c));
} else if (nextChar > 0 && Character.isLowerCase(nextChar)) {
sb.append('_').append(Character.toUpperCase(c));
} else {
sb.append(c);
}
}
else {
sb.append(c);
}
}
}
return sb.toString();
}
}
| true | true | public static String toSQLName(String javaNotation) {
if(javaNotation.equalsIgnoreCase("_id"))
return "_id";
StringBuilder sb = new StringBuilder();
char[] buf = javaNotation.toCharArray();
for (int i = 0; i < buf.length; i++) {
char prevChar = (i > 0) ? buf[i - 1] : 0;
char c = buf[i];
char nextChar = (i < buf.length - 1) ? buf[i + 1] : 0;
boolean isFirstChar = (i == 0);
if (isFirstChar || Character.isLowerCase(c)) {
sb.append(Character.toUpperCase(c));
} else if (Character.isUpperCase(c)) {
if (Character.isLetterOrDigit(prevChar)) {
if (Character.isLowerCase(prevChar)) {
sb.append('_').append(Character.toUpperCase(c));
} else if (nextChar > 0 && Character.isLowerCase(nextChar)) {
sb.append('_').append(Character.toUpperCase(c));
} else {
sb.append(c);
}
}
else {
sb.append(c);
}
}
}
return sb.toString();
}
| public static String toSQLName(String javaNotation) {
if(javaNotation.equalsIgnoreCase("_id"))
return "_id";
StringBuilder sb = new StringBuilder();
char[] buf = javaNotation.toCharArray();
for (int i = 0; i < buf.length; i++) {
char prevChar = (i > 0) ? buf[i - 1] : 0;
char c = buf[i];
char nextChar = (i < buf.length - 1) ? buf[i + 1] : 0;
boolean isFirstChar = (i == 0);
if (isFirstChar || Character.isLowerCase(c) || Character.isDigit(c)) {
sb.append(Character.toUpperCase(c));
} else if (Character.isUpperCase(c)) {
if (Character.isLetterOrDigit(prevChar)) {
if (Character.isLowerCase(prevChar)) {
sb.append('_').append(Character.toUpperCase(c));
} else if (nextChar > 0 && Character.isLowerCase(nextChar)) {
sb.append('_').append(Character.toUpperCase(c));
} else {
sb.append(c);
}
}
else {
sb.append(c);
}
}
}
return sb.toString();
}
|
diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/DefaultStepFactoryBean.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/DefaultStepFactoryBean.java
index cc5d1be5a..f497ff8eb 100644
--- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/DefaultStepFactoryBean.java
+++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/DefaultStepFactoryBean.java
@@ -1,215 +1,215 @@
/*
* Copyright 2006-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.batch.core.step;
import org.springframework.batch.core.BatchListener;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepListener;
import org.springframework.batch.core.listener.MulticasterBatchListener;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemStream;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.repeat.exception.ExceptionHandler;
import org.springframework.batch.repeat.policy.SimpleCompletionPolicy;
import org.springframework.batch.repeat.support.RepeatTemplate;
import org.springframework.batch.repeat.support.TaskExecutorRepeatTemplate;
import org.springframework.core.task.TaskExecutor;
/**
* Most common configuration options for simple steps should be found here. Use
* this factory bean instead of creating a {@link Step} implementation manually.
*
* @author Dave Syer
*
*/
public class DefaultStepFactoryBean extends AbstractStepFactoryBean {
private int commitInterval = 0;
private ItemStream[] streams = new ItemStream[0];
private BatchListener[] listeners = new BatchListener[0];
private MulticasterBatchListener listener = new MulticasterBatchListener();
private TaskExecutor taskExecutor;
private ItemHandler itemHandler;
private RepeatTemplate stepOperations;
private ExceptionHandler exceptionHandler;
/**
* Set the commit interval.
*
* @param commitInterval
*/
public void setCommitInterval(int commitInterval) {
this.commitInterval = commitInterval;
}
/**
* The streams to inject into the {@link Step}. Any instance of
* {@link ItemStream} can be used, and will then receive callbacks at the
* appropriate stage in the step.
*
* @param streams an array of listeners
*/
public void setStreams(ItemStream[] streams) {
this.streams = streams;
}
/**
* The listeners to inject into the {@link Step}. Any instance of
* {@link BatchListener} can be used, and will then receive callbacks at the
* appropriate stage in the step.
*
* @param listeners an array of listeners
*/
public void setListeners(BatchListener[] listeners) {
this.listeners = listeners;
}
/**
* Protected getter for the step operations to make them available in
* subclasses.
* @return the step operations
*/
protected RepeatTemplate getStepOperations() {
return stepOperations;
}
/**
* Public setter for the SimpleLimitExceptionHandler.
* @param exceptionHandler the exceptionHandler to set
*/
public void setExceptionHandler(ExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
}
/**
* Protected getter for the {@link ExceptionHandler}.
* @return the {@link ExceptionHandler}
*/
protected ExceptionHandler getExceptionHandler() {
return exceptionHandler;
}
/**
* Public setter for the {@link TaskExecutor}. If this is set, then it will
* be used to execute the chunk processing inside the {@link Step}.
*
* @param taskExecutor the taskExecutor to set
*/
public void setTaskExecutor(TaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
/**
* Public getter for the ItemProcessor.
* @return the itemProcessor
*/
protected ItemHandler getItemHandler() {
return itemHandler;
}
/**
* Public setter for the ItemProcessor.
* @param itemHandler the itemProcessor to set
*/
protected void setItemHandler(ItemHandler itemHandler) {
this.itemHandler = itemHandler;
}
/**
* @param step
*
*/
protected void applyConfiguration(ItemOrientedStep step) {
super.applyConfiguration(step);
step.setStreams(streams);
for (int i = 0; i < listeners.length; i++) {
BatchListener listener = listeners[i];
if (listener instanceof StepListener) {
step.registerStepListener((StepListener) listener);
}
else {
this.listener.register(listener);
}
}
ItemReader itemReader = getItemReader();
ItemWriter itemWriter = getItemWriter();
// Since we are going to wrap these things with listener callbacks we
// need to register them here because the step will not know we did
// that.
if (itemReader instanceof ItemStream) {
step.registerStream((ItemStream) itemReader);
}
if (itemReader instanceof StepListener) {
step.registerStepListener((StepListener) itemReader);
}
if (itemWriter instanceof ItemStream) {
step.registerStream((ItemStream) itemWriter);
}
if (itemWriter instanceof StepListener) {
step.registerStepListener((StepListener) itemWriter);
}
BatchListenerFactoryHelper helper = new BatchListenerFactoryHelper();
if (commitInterval > 0) {
RepeatTemplate chunkOperations = new RepeatTemplate();
chunkOperations.setCompletionPolicy(new SimpleCompletionPolicy(commitInterval));
helper.addChunkListeners(chunkOperations, listeners);
step.setChunkOperations(chunkOperations);
}
StepListener[] stepListeners = helper.getStepListeners(listeners);
itemReader = helper.getItemReader(itemReader, listeners);
itemWriter = helper.getItemWriter(itemWriter, listeners);
// In case they are used by subclasses:
setItemReader(itemReader);
setItemWriter(itemWriter);
step.setStepListeners(stepListeners);
stepOperations = new RepeatTemplate();
if (taskExecutor != null) {
TaskExecutorRepeatTemplate repeatTemplate = new TaskExecutorRepeatTemplate();
repeatTemplate.setTaskExecutor(taskExecutor);
stepOperations = repeatTemplate;
}
step.setStepOperations(stepOperations);
- ItemSkipPolicyItemHandler itemHandler = new ItemSkipPolicyItemHandler(itemReader, itemWriter);
+ ItemHandler itemHandler = new SimpleItemHandler(itemReader, itemWriter);
setItemHandler(itemHandler);
step.setItemHandler(itemHandler);
}
}
| true | true | protected void applyConfiguration(ItemOrientedStep step) {
super.applyConfiguration(step);
step.setStreams(streams);
for (int i = 0; i < listeners.length; i++) {
BatchListener listener = listeners[i];
if (listener instanceof StepListener) {
step.registerStepListener((StepListener) listener);
}
else {
this.listener.register(listener);
}
}
ItemReader itemReader = getItemReader();
ItemWriter itemWriter = getItemWriter();
// Since we are going to wrap these things with listener callbacks we
// need to register them here because the step will not know we did
// that.
if (itemReader instanceof ItemStream) {
step.registerStream((ItemStream) itemReader);
}
if (itemReader instanceof StepListener) {
step.registerStepListener((StepListener) itemReader);
}
if (itemWriter instanceof ItemStream) {
step.registerStream((ItemStream) itemWriter);
}
if (itemWriter instanceof StepListener) {
step.registerStepListener((StepListener) itemWriter);
}
BatchListenerFactoryHelper helper = new BatchListenerFactoryHelper();
if (commitInterval > 0) {
RepeatTemplate chunkOperations = new RepeatTemplate();
chunkOperations.setCompletionPolicy(new SimpleCompletionPolicy(commitInterval));
helper.addChunkListeners(chunkOperations, listeners);
step.setChunkOperations(chunkOperations);
}
StepListener[] stepListeners = helper.getStepListeners(listeners);
itemReader = helper.getItemReader(itemReader, listeners);
itemWriter = helper.getItemWriter(itemWriter, listeners);
// In case they are used by subclasses:
setItemReader(itemReader);
setItemWriter(itemWriter);
step.setStepListeners(stepListeners);
stepOperations = new RepeatTemplate();
if (taskExecutor != null) {
TaskExecutorRepeatTemplate repeatTemplate = new TaskExecutorRepeatTemplate();
repeatTemplate.setTaskExecutor(taskExecutor);
stepOperations = repeatTemplate;
}
step.setStepOperations(stepOperations);
ItemSkipPolicyItemHandler itemHandler = new ItemSkipPolicyItemHandler(itemReader, itemWriter);
setItemHandler(itemHandler);
step.setItemHandler(itemHandler);
}
| protected void applyConfiguration(ItemOrientedStep step) {
super.applyConfiguration(step);
step.setStreams(streams);
for (int i = 0; i < listeners.length; i++) {
BatchListener listener = listeners[i];
if (listener instanceof StepListener) {
step.registerStepListener((StepListener) listener);
}
else {
this.listener.register(listener);
}
}
ItemReader itemReader = getItemReader();
ItemWriter itemWriter = getItemWriter();
// Since we are going to wrap these things with listener callbacks we
// need to register them here because the step will not know we did
// that.
if (itemReader instanceof ItemStream) {
step.registerStream((ItemStream) itemReader);
}
if (itemReader instanceof StepListener) {
step.registerStepListener((StepListener) itemReader);
}
if (itemWriter instanceof ItemStream) {
step.registerStream((ItemStream) itemWriter);
}
if (itemWriter instanceof StepListener) {
step.registerStepListener((StepListener) itemWriter);
}
BatchListenerFactoryHelper helper = new BatchListenerFactoryHelper();
if (commitInterval > 0) {
RepeatTemplate chunkOperations = new RepeatTemplate();
chunkOperations.setCompletionPolicy(new SimpleCompletionPolicy(commitInterval));
helper.addChunkListeners(chunkOperations, listeners);
step.setChunkOperations(chunkOperations);
}
StepListener[] stepListeners = helper.getStepListeners(listeners);
itemReader = helper.getItemReader(itemReader, listeners);
itemWriter = helper.getItemWriter(itemWriter, listeners);
// In case they are used by subclasses:
setItemReader(itemReader);
setItemWriter(itemWriter);
step.setStepListeners(stepListeners);
stepOperations = new RepeatTemplate();
if (taskExecutor != null) {
TaskExecutorRepeatTemplate repeatTemplate = new TaskExecutorRepeatTemplate();
repeatTemplate.setTaskExecutor(taskExecutor);
stepOperations = repeatTemplate;
}
step.setStepOperations(stepOperations);
ItemHandler itemHandler = new SimpleItemHandler(itemReader, itemWriter);
setItemHandler(itemHandler);
step.setItemHandler(itemHandler);
}
|
diff --git a/src/main/java/org/sonatype/jettytestsuite/proxy/UnstableFileServerServlet.java b/src/main/java/org/sonatype/jettytestsuite/proxy/UnstableFileServerServlet.java
index 7af3a5b..7928ba6 100644
--- a/src/main/java/org/sonatype/jettytestsuite/proxy/UnstableFileServerServlet.java
+++ b/src/main/java/org/sonatype/jettytestsuite/proxy/UnstableFileServerServlet.java
@@ -1,43 +1,44 @@
package org.sonatype.jettytestsuite.proxy;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UnstableFileServerServlet
extends FileServerServlet
{
private static final long serialVersionUID = -6940218205740360901L;
private int numberOfTries;
private final int returnCode;
public UnstableFileServerServlet( int numberOfTries, int returnCode, File content )
{
super( content );
this.numberOfTries = numberOfTries;
this.returnCode = returnCode;
}
@Override
public void service( HttpServletRequest req, HttpServletResponse res )
throws ServletException, IOException
{
if ( numberOfTries > 0 )
{
+ numberOfTries--;
res.sendError( returnCode );
return;
}
else
{
super.service( req, res );
}
}
}
| true | true | public void service( HttpServletRequest req, HttpServletResponse res )
throws ServletException, IOException
{
if ( numberOfTries > 0 )
{
res.sendError( returnCode );
return;
}
else
{
super.service( req, res );
}
}
| public void service( HttpServletRequest req, HttpServletResponse res )
throws ServletException, IOException
{
if ( numberOfTries > 0 )
{
numberOfTries--;
res.sendError( returnCode );
return;
}
else
{
super.service( req, res );
}
}
|
diff --git a/source/RMG/jing/rxnSys/RateBasedPDepVT.java b/source/RMG/jing/rxnSys/RateBasedPDepVT.java
index 1caf40b0..28c8395b 100644
--- a/source/RMG/jing/rxnSys/RateBasedPDepVT.java
+++ b/source/RMG/jing/rxnSys/RateBasedPDepVT.java
@@ -1,90 +1,91 @@
////////////////////////////////////////////////////////////////////////////////
//
// RMG - Reaction Mechanism Generator
//
// Copyright (c) 2002-2009 Prof. William H. Green ([email protected]) and the
// RMG Team ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////
package jing.rxnSys;
import jing.rxn.*;
import jing.chem.*;
import java.util.*;
import jing.param.*;
//## package jing::rxnSys
//----------------------------------------------------------------------------
// jing\rxnSys\RateBasedPDepVT.java
//----------------------------------------------------------------------------
//## class RateBasedPDepVT
public class RateBasedPDepVT extends RateBasedVT {
// Constructors
//## operation RateBasedPDepVT(double)
public RateBasedPDepVT(double p_tolerance) {
//#[ operation RateBasedPDepVT(double)
super(p_tolerance);
//#]
}
public RateBasedPDepVT() {
}
//## operation isModelValid(ReactionSystem)
public boolean isModelValid(ReactionSystem p_reactionSystem) {
// Check if all the unreacted species has their fluxes under the system min flux
if (!super.isModelValid(p_reactionSystem))
return false;
// check if all the networks has their leak fluxes under the system min flux
PresentStatus ps = p_reactionSystem.getPresentStatus();
calculateRmin(ps);
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel) p_reactionSystem.getReactionModel();
double[] leakFlux = PDepNetwork.getSpeciesLeakFluxes(ps, cerm);
- for (int i = 1; i <= cerm.getMaxSpeciesID(); i++) {
- if (leakFlux[i] > Rmin) {
- System.out.println("Exceeded largest permitted flux for convergence (tolerance="+tolerance+"): " + Rmin);
+ for (Iterator iter = cerm.getUnreactedSpeciesSet().iterator(); iter.hasNext(); ) {
+ Species us = (Species) iter.next();
+ if (leakFlux[us.getID()] > Rmin) {
+ System.out.println("Leak flux exceeded largest permitted flux for convergence (tolerance="+tolerance+"): " + Rmin);
return false;
}
}
return true;
//#]
}
}
/*********************************************************************
File Path : RMG\RMG\jing\rxnSys\RateBasedPDepVT.java
*********************************************************************/
| true | true | public boolean isModelValid(ReactionSystem p_reactionSystem) {
// Check if all the unreacted species has their fluxes under the system min flux
if (!super.isModelValid(p_reactionSystem))
return false;
// check if all the networks has their leak fluxes under the system min flux
PresentStatus ps = p_reactionSystem.getPresentStatus();
calculateRmin(ps);
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel) p_reactionSystem.getReactionModel();
double[] leakFlux = PDepNetwork.getSpeciesLeakFluxes(ps, cerm);
for (int i = 1; i <= cerm.getMaxSpeciesID(); i++) {
if (leakFlux[i] > Rmin) {
System.out.println("Exceeded largest permitted flux for convergence (tolerance="+tolerance+"): " + Rmin);
return false;
}
}
return true;
//#]
}
| public boolean isModelValid(ReactionSystem p_reactionSystem) {
// Check if all the unreacted species has their fluxes under the system min flux
if (!super.isModelValid(p_reactionSystem))
return false;
// check if all the networks has their leak fluxes under the system min flux
PresentStatus ps = p_reactionSystem.getPresentStatus();
calculateRmin(ps);
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel) p_reactionSystem.getReactionModel();
double[] leakFlux = PDepNetwork.getSpeciesLeakFluxes(ps, cerm);
for (Iterator iter = cerm.getUnreactedSpeciesSet().iterator(); iter.hasNext(); ) {
Species us = (Species) iter.next();
if (leakFlux[us.getID()] > Rmin) {
System.out.println("Leak flux exceeded largest permitted flux for convergence (tolerance="+tolerance+"): " + Rmin);
return false;
}
}
return true;
//#]
}
|
diff --git a/cilia-workbench-designer/src/fr/liglab/adele/cilia/workbench/designer/parser/ciliajar/MediatorComponent.java b/cilia-workbench-designer/src/fr/liglab/adele/cilia/workbench/designer/parser/ciliajar/MediatorComponent.java
index ea39870..1510fdf 100644
--- a/cilia-workbench-designer/src/fr/liglab/adele/cilia/workbench/designer/parser/ciliajar/MediatorComponent.java
+++ b/cilia-workbench-designer/src/fr/liglab/adele/cilia/workbench/designer/parser/ciliajar/MediatorComponent.java
@@ -1,261 +1,261 @@
/**
* Copyright Universite Joseph Fourier (www.ujf-grenoble.fr)
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.liglab.adele.cilia.workbench.designer.parser.ciliajar;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.w3c.dom.Node;
import fr.liglab.adele.cilia.workbench.common.cilia.CiliaConstants;
import fr.liglab.adele.cilia.workbench.common.cilia.CiliaException;
import fr.liglab.adele.cilia.workbench.common.identifiable.NameNamespaceID;
import fr.liglab.adele.cilia.workbench.common.marker.CiliaError;
import fr.liglab.adele.cilia.workbench.common.marker.CiliaFlag;
import fr.liglab.adele.cilia.workbench.common.marker.IdentifiableUtils;
import fr.liglab.adele.cilia.workbench.common.reflection.ReflectionUtil;
import fr.liglab.adele.cilia.workbench.common.xml.XMLHelpers;
import fr.liglab.adele.cilia.workbench.designer.parser.spec.ComponentPart;
import fr.liglab.adele.cilia.workbench.designer.parser.spec.MediatorSpec;
import fr.liglab.adele.cilia.workbench.designer.service.jarreposervice.JarRepoService;
/**
*
* @author Etienne Gandrille
*/
public class MediatorComponent extends Element {
private final SuperMediator spec;
private String schedulerName;
private String schedulerNamespace;
private String processorName;
private String processorNamespace;
private String dispatcherName;
private String dispatcherNamespace;
private List<Port> ports = new ArrayList<Port>();
private List<Property> properties = new ArrayList<Property>();
public MediatorComponent(Node node) throws CiliaException {
super(node);
String defNs = CiliaConstants.getDefaultNamespace();
String specName = null;
String specNamespace = null;
Map<String, String> attrMap = XMLHelpers.findAttributesValues(node);
for (String attr : attrMap.keySet()) {
if (attr.equalsIgnoreCase("spec-name"))
specName = attrMap.get(attr);
else if (attr.equalsIgnoreCase("spec-namespace"))
specNamespace = attrMap.get(attr);
else if (!attr.equalsIgnoreCase("name") && !attr.equalsIgnoreCase("namespace"))
properties.add(new Property(attr, attrMap.get(attr)));
}
if (specName != null)
spec = new SuperMediator(specName, specNamespace);
else
spec = null;
Node schedulerNode = XMLHelpers.findChild(node, "scheduler");
if (schedulerNode != null) {
ReflectionUtil.setAttribute(schedulerNode, "name", this, "schedulerName");
ReflectionUtil.setAttribute(schedulerNode, "namespace", this, "schedulerNamespace", defNs);
}
Node processorNode = XMLHelpers.findChild(node, "processor");
if (processorNode != null) {
ReflectionUtil.setAttribute(processorNode, "name", this, "processorName");
ReflectionUtil.setAttribute(processorNode, "namespace", this, "processorNamespace", defNs);
}
Node dispatcherNode = XMLHelpers.findChild(node, "dispatcher");
if (dispatcherNode != null) {
ReflectionUtil.setAttribute(dispatcherNode, "name", this, "dispatcherName");
ReflectionUtil.setAttribute(dispatcherNode, "namespace", this, "dispatcherNamespace", defNs);
}
Node portsNode = XMLHelpers.findChild(node, "ports");
if (portsNode != null) {
Node[] inPorts = XMLHelpers.findChildren(portsNode, "in-port");
for (Node inPort : inPorts)
ports.add(new InPort(inPort));
Node[] outPorts = XMLHelpers.findChildren(portsNode, "out-port");
for (Node outPort : outPorts)
ports.add(new OutPort(outPort));
}
}
public List<Port> getPorts() {
return ports;
}
public List<Port> getInPorts() {
List<Port> retval = new ArrayList<Port>();
for (Port p : ports)
if (p.isInPort())
retval.add(p);
return retval;
}
public List<Port> getOutPorts() {
List<Port> retval = new ArrayList<Port>();
for (Port p : ports)
if (p.isOutPort())
retval.add(p);
return retval;
}
public SuperMediator getSpec() {
return spec;
}
public NameNamespaceID getSchedulerNameNamespace() {
return new NameNamespaceID(schedulerName, schedulerNamespace);
}
public NameNamespaceID getProcessorNameNamespace() {
return new NameNamespaceID(processorName, processorNamespace);
}
public NameNamespaceID getDispatcherNameNamespace() {
return new NameNamespaceID(dispatcherName, dispatcherNamespace);
}
public List<Property> getProperties() {
return properties;
}
public Property getProperty(String key) {
for (Property p : getProperties())
if (p.getKey().equalsIgnoreCase(key))
return p;
return null;
}
@Override
public CiliaFlag[] getErrorsAndWarnings() {
CiliaFlag[] tab = super.getErrorsAndWarnings();
List<CiliaFlag> flagsTab = new ArrayList<CiliaFlag>();
for (CiliaFlag f : tab)
flagsTab.add(f);
CiliaFlag e1 = CiliaError.checkStringNotNullOrEmpty(this, schedulerName, "scheduler name");
CiliaFlag e2 = CiliaError.checkStringNotNullOrEmpty(this, processorName, "processor name");
CiliaFlag e3 = CiliaError.checkStringNotNullOrEmpty(this, dispatcherName, "dispatcher name");
CiliaFlag e4 = null;
CiliaFlag e5 = null;
CiliaFlag e6 = null;
CiliaFlag e7 = null;
// ports
if (getInPorts().size() == 0)
e4 = new CiliaError("Mediator doesn't have an in port", this);
if (getOutPorts().size() == 0)
e5 = new CiliaError("Mediator doesn't have an out port", this);
flagsTab.addAll(IdentifiableUtils.getErrorsNonUniqueId(this, getInPorts()));
flagsTab.addAll(IdentifiableUtils.getErrorsNonUniqueId(this, getOutPorts()));
// properties
flagsTab.addAll(IdentifiableUtils.getErrorsNonUniqueId(this, properties));
// Spec
if (getSpec() != null && getSpec().getMediatorSpec() != null) {
MediatorSpec mediatorSpec = getSpec().getMediatorSpec();
// In ports
if (!IdentifiableUtils.isSameListId(mediatorSpec.getInPorts(), getInPorts()))
e6 = new CiliaError("In ports list doesn't respect the specification", getSpec());
// Out ports
if (!IdentifiableUtils.isSameListId(mediatorSpec.getOutPorts(), getOutPorts()))
e7 = new CiliaError("Out ports list doesn't respect the specification", getSpec());
// Properties
for (fr.liglab.adele.cilia.workbench.designer.parser.spec.Property mediaProp : mediatorSpec.getProperties()) {
String specKey = mediaProp.getKey();
String specValue = mediaProp.getValue();
Property curProp = getProperty(specKey);
if (curProp == null)
flagsTab.add(new CiliaError("Mediator must have \"" + specKey + "\" property defined with value \""
- + specValue + "\" to respect its specification", this));
+ + specValue + "\" to respect its specification", getSpec()));
else if (!curProp.getValue().equalsIgnoreCase(specValue))
flagsTab.add(new CiliaError("Mediator must have \"" + specKey + "\" property defined with value \""
- + specValue + "\" to respect its specification", this));
+ + specValue + "\" to respect its specification", getSpec()));
}
}
return CiliaFlag.generateTab(flagsTab, e1, e2, e3, e4, e5, e6, e7);
}
public static List<CiliaFlag> checkSPDParameters(JarRepoService repo, MediatorComponent mediator) {
List<CiliaFlag> flagsTab = new ArrayList<CiliaFlag>();
if (mediator.getSpec() != null && mediator.getSpec().getMediatorSpec() != null) {
MediatorSpec mediatorSpec = mediator.getSpec().getMediatorSpec();
// Scheduler parameters
Scheduler scheduler = repo.getScheduler(mediator.getSchedulerNameNamespace());
if (scheduler != null)
flagsTab.addAll(checkParameters(mediator, mediatorSpec.getScheduler(), scheduler, "scheduler"));
// Processor parameters
Processor processor = repo.getProcessor(mediator.getProcessorNameNamespace());
if (processor != null)
flagsTab.addAll(checkParameters(mediator, mediatorSpec.getProcessor(), processor, "processor"));
// Dispatcher parameters
Dispatcher dispatcher = repo.getDispatcher(mediator.getDispatcherNameNamespace());
if (dispatcher != null)
flagsTab.addAll(checkParameters(mediator, mediatorSpec.getDispatcher(), dispatcher, "dispatcher"));
}
return flagsTab;
}
private static List<CiliaFlag> checkParameters(MediatorComponent mediator, ComponentPart spec, SPDElement implem,
String elementTypeName) {
List<CiliaFlag> retval = new ArrayList<CiliaFlag>();
if (spec == null)
return retval;
for (fr.liglab.adele.cilia.workbench.designer.parser.spec.Parameter param : spec.getParameters()) {
String paramName = param.getName();
boolean found = false;
for (Iterator<Parameter> iterator = implem.getParameters().iterator(); iterator.hasNext() && !found;) {
if (iterator.next().getName().equalsIgnoreCase(paramName))
found = true;
}
if (!found)
retval.add(new CiliaError(elementTypeName + " must have a parameter named " + paramName
+ " to respect its specification", mediator.getSpec()));
}
return retval;
}
}
| false | true | public CiliaFlag[] getErrorsAndWarnings() {
CiliaFlag[] tab = super.getErrorsAndWarnings();
List<CiliaFlag> flagsTab = new ArrayList<CiliaFlag>();
for (CiliaFlag f : tab)
flagsTab.add(f);
CiliaFlag e1 = CiliaError.checkStringNotNullOrEmpty(this, schedulerName, "scheduler name");
CiliaFlag e2 = CiliaError.checkStringNotNullOrEmpty(this, processorName, "processor name");
CiliaFlag e3 = CiliaError.checkStringNotNullOrEmpty(this, dispatcherName, "dispatcher name");
CiliaFlag e4 = null;
CiliaFlag e5 = null;
CiliaFlag e6 = null;
CiliaFlag e7 = null;
// ports
if (getInPorts().size() == 0)
e4 = new CiliaError("Mediator doesn't have an in port", this);
if (getOutPorts().size() == 0)
e5 = new CiliaError("Mediator doesn't have an out port", this);
flagsTab.addAll(IdentifiableUtils.getErrorsNonUniqueId(this, getInPorts()));
flagsTab.addAll(IdentifiableUtils.getErrorsNonUniqueId(this, getOutPorts()));
// properties
flagsTab.addAll(IdentifiableUtils.getErrorsNonUniqueId(this, properties));
// Spec
if (getSpec() != null && getSpec().getMediatorSpec() != null) {
MediatorSpec mediatorSpec = getSpec().getMediatorSpec();
// In ports
if (!IdentifiableUtils.isSameListId(mediatorSpec.getInPorts(), getInPorts()))
e6 = new CiliaError("In ports list doesn't respect the specification", getSpec());
// Out ports
if (!IdentifiableUtils.isSameListId(mediatorSpec.getOutPorts(), getOutPorts()))
e7 = new CiliaError("Out ports list doesn't respect the specification", getSpec());
// Properties
for (fr.liglab.adele.cilia.workbench.designer.parser.spec.Property mediaProp : mediatorSpec.getProperties()) {
String specKey = mediaProp.getKey();
String specValue = mediaProp.getValue();
Property curProp = getProperty(specKey);
if (curProp == null)
flagsTab.add(new CiliaError("Mediator must have \"" + specKey + "\" property defined with value \""
+ specValue + "\" to respect its specification", this));
else if (!curProp.getValue().equalsIgnoreCase(specValue))
flagsTab.add(new CiliaError("Mediator must have \"" + specKey + "\" property defined with value \""
+ specValue + "\" to respect its specification", this));
}
}
return CiliaFlag.generateTab(flagsTab, e1, e2, e3, e4, e5, e6, e7);
}
| public CiliaFlag[] getErrorsAndWarnings() {
CiliaFlag[] tab = super.getErrorsAndWarnings();
List<CiliaFlag> flagsTab = new ArrayList<CiliaFlag>();
for (CiliaFlag f : tab)
flagsTab.add(f);
CiliaFlag e1 = CiliaError.checkStringNotNullOrEmpty(this, schedulerName, "scheduler name");
CiliaFlag e2 = CiliaError.checkStringNotNullOrEmpty(this, processorName, "processor name");
CiliaFlag e3 = CiliaError.checkStringNotNullOrEmpty(this, dispatcherName, "dispatcher name");
CiliaFlag e4 = null;
CiliaFlag e5 = null;
CiliaFlag e6 = null;
CiliaFlag e7 = null;
// ports
if (getInPorts().size() == 0)
e4 = new CiliaError("Mediator doesn't have an in port", this);
if (getOutPorts().size() == 0)
e5 = new CiliaError("Mediator doesn't have an out port", this);
flagsTab.addAll(IdentifiableUtils.getErrorsNonUniqueId(this, getInPorts()));
flagsTab.addAll(IdentifiableUtils.getErrorsNonUniqueId(this, getOutPorts()));
// properties
flagsTab.addAll(IdentifiableUtils.getErrorsNonUniqueId(this, properties));
// Spec
if (getSpec() != null && getSpec().getMediatorSpec() != null) {
MediatorSpec mediatorSpec = getSpec().getMediatorSpec();
// In ports
if (!IdentifiableUtils.isSameListId(mediatorSpec.getInPorts(), getInPorts()))
e6 = new CiliaError("In ports list doesn't respect the specification", getSpec());
// Out ports
if (!IdentifiableUtils.isSameListId(mediatorSpec.getOutPorts(), getOutPorts()))
e7 = new CiliaError("Out ports list doesn't respect the specification", getSpec());
// Properties
for (fr.liglab.adele.cilia.workbench.designer.parser.spec.Property mediaProp : mediatorSpec.getProperties()) {
String specKey = mediaProp.getKey();
String specValue = mediaProp.getValue();
Property curProp = getProperty(specKey);
if (curProp == null)
flagsTab.add(new CiliaError("Mediator must have \"" + specKey + "\" property defined with value \""
+ specValue + "\" to respect its specification", getSpec()));
else if (!curProp.getValue().equalsIgnoreCase(specValue))
flagsTab.add(new CiliaError("Mediator must have \"" + specKey + "\" property defined with value \""
+ specValue + "\" to respect its specification", getSpec()));
}
}
return CiliaFlag.generateTab(flagsTab, e1, e2, e3, e4, e5, e6, e7);
}
|
diff --git a/src/info/jeppes/ZoneCore/ZoneConfig.java b/src/info/jeppes/ZoneCore/ZoneConfig.java
index 9f9f903..bdb7611 100644
--- a/src/info/jeppes/ZoneCore/ZoneConfig.java
+++ b/src/info/jeppes/ZoneCore/ZoneConfig.java
@@ -1,157 +1,159 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package info.jeppes.ZoneCore;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
/**
*
* @author Jeppe
*/
public class ZoneConfig extends AsynchronizedYamlConfiguration{
private final Plugin plugin;
private File file;
private String name;
public ZoneConfig(Plugin plugin, File file){
this(plugin,file,true);
}
public ZoneConfig(Plugin plugin, File file, boolean loadDefaults){
this.plugin = plugin;
this.file = file;
this.name = file.getName();
if(!file.exists()){
try {
//Create directory if doesn't exist
- new File(file.getPath()).mkdirs();
+ if(file.getParentFile() != null){
+ file.getParentFile().mkdirs();
+ }
//create file
file.createNewFile();
} catch (IOException ex) {
Logger.getLogger(ZoneConfig.class.getName()).log(Level.SEVERE, null, ex);
}
}
try {
load(file);
} catch (FileNotFoundException ex) {
Logger.getLogger(ZoneConfig.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException | InvalidConfigurationException ex) {
Logger.getLogger(ZoneConfig.class.getName()).log(Level.SEVERE, null, ex);
}
if(loadDefaults){
loadDefaults(plugin);
}
}
public String getFileName(){
return name;
}
@Override
public String getName(){
return getFileName();
}
public final boolean loadDefaults(Plugin plugin){
return this.loadDefaults(plugin, file.getName());
}
public final boolean loadDefaults(Plugin plugin, String fileName){
if(plugin == null){
return false;
}
InputStream defConfigStream = plugin.getResource(fileName);
if (defConfigStream != null) {
YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream);
loadDefaults(plugin,defConfig);
return true;
}
return false;
}
public final boolean loadDefaults(Plugin plugin, YamlConfiguration config){
setDefaults(config);
options().copyDefaults(true);
schedualSave();
return true;
}
public void writeYML(String root, Object x){
writeYML(this,file,root,x);
}
public static void writeYML(YamlConfiguration config, File configFile, String root, Object x){
config.set(root, x);
try {
config.save(configFile);
} catch (IOException ex) {
Logger.getLogger(ZoneConfig.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void deleteYML(String root){
deleteYML(this,file,root);
}
public static void deleteYML(YamlConfiguration config, File configFile, String root){
config.set(root, null);
try {
config.save(configFile);
} catch (IOException ex) {
Logger.getLogger(ZoneConfig.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void writeYMLASync(String root, Object x){
writeYMLASync(this,file,root,x);
}
public void writeYMLASync(final YamlConfiguration config, final File configFile, final String root, final Object x){
Bukkit.getScheduler().scheduleAsyncDelayedTask(plugin, new Runnable(){
@Override
public void run() {
try {
config.set(root, x);
config.save(configFile);
} catch (IOException ex) {
Logger.getLogger(ZoneConfig.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
public void deleteYMLASync(String root){
deleteYMLASync(this,file,root);
}
public void deleteYMLASync(final YamlConfiguration config, final File configFile, final String root){
Bukkit.getScheduler().scheduleAsyncDelayedTask(plugin, new Runnable(){
@Override
public void run() {
try {
config.set(root, null);
config.save(configFile);
} catch (IOException ex) {
Logger.getLogger(ZoneConfig.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
@Override
public boolean save(){
try {
save(file);
} catch (IOException ex) {
Logger.getLogger(ZoneConfig.class.getName()).log(Level.SEVERE, null, ex);
return false;
}
return true;
}
@Override
public String toString(){
return "ZoneConfig[File name=\""+this.getName()+"\" path:\""+this.file.getPath()+"\"]";
}
}
| true | true | public ZoneConfig(Plugin plugin, File file, boolean loadDefaults){
this.plugin = plugin;
this.file = file;
this.name = file.getName();
if(!file.exists()){
try {
//Create directory if doesn't exist
new File(file.getPath()).mkdirs();
//create file
file.createNewFile();
} catch (IOException ex) {
Logger.getLogger(ZoneConfig.class.getName()).log(Level.SEVERE, null, ex);
}
}
try {
load(file);
} catch (FileNotFoundException ex) {
Logger.getLogger(ZoneConfig.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException | InvalidConfigurationException ex) {
Logger.getLogger(ZoneConfig.class.getName()).log(Level.SEVERE, null, ex);
}
if(loadDefaults){
loadDefaults(plugin);
}
}
| public ZoneConfig(Plugin plugin, File file, boolean loadDefaults){
this.plugin = plugin;
this.file = file;
this.name = file.getName();
if(!file.exists()){
try {
//Create directory if doesn't exist
if(file.getParentFile() != null){
file.getParentFile().mkdirs();
}
//create file
file.createNewFile();
} catch (IOException ex) {
Logger.getLogger(ZoneConfig.class.getName()).log(Level.SEVERE, null, ex);
}
}
try {
load(file);
} catch (FileNotFoundException ex) {
Logger.getLogger(ZoneConfig.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException | InvalidConfigurationException ex) {
Logger.getLogger(ZoneConfig.class.getName()).log(Level.SEVERE, null, ex);
}
if(loadDefaults){
loadDefaults(plugin);
}
}
|
diff --git a/src/main/java/edu/rit/asksg/domain/Twilio.java b/src/main/java/edu/rit/asksg/domain/Twilio.java
index 9062c4d..e3bfd79 100755
--- a/src/main/java/edu/rit/asksg/domain/Twilio.java
+++ b/src/main/java/edu/rit/asksg/domain/Twilio.java
@@ -1,108 +1,108 @@
package edu.rit.asksg.domain;
import com.google.common.base.Optional;
import com.sun.org.apache.xpath.internal.operations.Bool;
import com.twilio.sdk.TwilioRestClient;
import com.twilio.sdk.TwilioRestException;
import com.twilio.sdk.resource.factory.SmsFactory;
import com.twilio.sdk.resource.instance.Sms;
import edu.rit.asksg.dataio.ContentProvider;
import edu.rit.asksg.domain.config.ProviderConfig;
import edu.rit.asksg.domain.config.TwilioConfig;
import edu.rit.asksg.service.ConversationService;
import edu.rit.asksg.service.IdentityService;
import flexjson.JSON;
import org.joda.time.LocalDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.entity.RooJpaEntity;
import org.springframework.roo.addon.json.RooJson;
import org.springframework.roo.addon.tostring.RooToString;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RooJavaBean
@RooToString
@RooJpaEntity
@RooJson
public class Twilio extends Service implements ContentProvider {
private transient static final Logger logger = LoggerFactory.getLogger(Twilio.class);
@JSON(include = false)
@Override
public List<Conversation> getNewContent() {
logger.debug("Twilio does not support fetching new content.");
return new ArrayList<Conversation>();
}
@JSON(include = false)
@Override
public List<Conversation> getContentSince(LocalDateTime datetime) {
return new ArrayList<Conversation>();
}
@Override
public boolean postContent(Message message) {
final TwilioConfig config = (TwilioConfig) this.getConfig();
TwilioRestClient twc = new TwilioRestClient(config.getUsername(), config.getAuthenticationToken());
Map<String, String> vars = new HashMap<String, String>();
vars.put("Body", message.getContent());
vars.put("From", config.getPhoneNumber());
vars.put("To", message.getConversation().getRecipient());
SmsFactory smsFactory = twc.getAccount().getSmsFactory();
try {
Sms sms = smsFactory.create(vars);
//TODO: Twilio can use a callback to POST information to if sending fails
} catch (TwilioRestException e) {
logger.error(e.getLocalizedMessage(), e);
return false;
}
return true;
}
@Override
public boolean authenticate() {
return false;
}
@Override
public boolean isAuthenticated() {
return false;
}
public void handleMessage(String smsSid, String accountSid, String from, String to, String body) {
Message message = new Message();
message.setContent(body);
Identity identity = getIdentityService().findOrCreate(from);
message.setIdentity(identity);
- LocalDateTime now = LocalDateTime.now();
+ LocalDateTime now = LocalDateTime.now().plusHours(4);
message.setCreated(now);
message.setModified(now);
Conversation conv = getConversationService().findConversationByRecipientSince(from, now.minusWeeks(1));
if (conv == null) {
logger.debug("Twilio: Creating new conversation for message received from " + from);
conv = new Conversation(message);
conv.setExternalId(smsSid);
conv.setCreated(now);
conv.setSubject(body);
}
conv.getMessages().add(message);
conv.setModified(now);
conv.setService(this);
message.setConversation(conv);
getConversationService().saveConversation(conv);
}
}
| true | true | public void handleMessage(String smsSid, String accountSid, String from, String to, String body) {
Message message = new Message();
message.setContent(body);
Identity identity = getIdentityService().findOrCreate(from);
message.setIdentity(identity);
LocalDateTime now = LocalDateTime.now();
message.setCreated(now);
message.setModified(now);
Conversation conv = getConversationService().findConversationByRecipientSince(from, now.minusWeeks(1));
if (conv == null) {
logger.debug("Twilio: Creating new conversation for message received from " + from);
conv = new Conversation(message);
conv.setExternalId(smsSid);
conv.setCreated(now);
conv.setSubject(body);
}
conv.getMessages().add(message);
conv.setModified(now);
conv.setService(this);
message.setConversation(conv);
getConversationService().saveConversation(conv);
}
| public void handleMessage(String smsSid, String accountSid, String from, String to, String body) {
Message message = new Message();
message.setContent(body);
Identity identity = getIdentityService().findOrCreate(from);
message.setIdentity(identity);
LocalDateTime now = LocalDateTime.now().plusHours(4);
message.setCreated(now);
message.setModified(now);
Conversation conv = getConversationService().findConversationByRecipientSince(from, now.minusWeeks(1));
if (conv == null) {
logger.debug("Twilio: Creating new conversation for message received from " + from);
conv = new Conversation(message);
conv.setExternalId(smsSid);
conv.setCreated(now);
conv.setSubject(body);
}
conv.getMessages().add(message);
conv.setModified(now);
conv.setService(this);
message.setConversation(conv);
getConversationService().saveConversation(conv);
}
|
diff --git a/src/main/java/com/mike724/email/Email.java b/src/main/java/com/mike724/email/Email.java
index 24d3b99..db5f2dd 100644
--- a/src/main/java/com/mike724/email/Email.java
+++ b/src/main/java/com/mike724/email/Email.java
@@ -1,96 +1,96 @@
/*
This file is part of Email.
Email 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.
Email 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 Email. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mike724.email;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import org.mcstats.MetricsLite;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
public class Email extends JavaPlugin {
public EmailManager emails;
public EmailTransfer mailman;
@Override
public void onDisable() {
this.getLogger().info("Disabled successfully");
}
@Override
public void onEnable() {
if (!this.getDataFolder().exists()) {
this.getDataFolder().mkdir();
}
FileConfiguration config = this.getConfig();
config.options().copyHeader(true);
config.options().copyDefaults(true);
this.saveConfig();
Logger log = this.getLogger();
boolean enableEmailSending = config.getBoolean("email.enable");
if (enableEmailSending) {
String typeString = config.getString("email.type");
List<Map<?, ?>> maps = config.getMapList("providers."+typeString);
if(maps == null || maps.isEmpty()) {
log.severe("Unknown email provider! Disabling");
this.getServer().getPluginManager().disablePlugin(this);
return;
}
HashMap<String, String> props = new HashMap<String, String>();
for(Map<?, ?> map : maps) {
//This part is a bit messy/hacky. Sorry. :)
//Nothing should go wrong if the key is a string
- //The value should be either a string or int, but toString() will take care if that
+ //The value should be either a string or int, but toString() will take care of that
@SuppressWarnings("unchecked")
String key = ((Set<String>)map.keySet()).iterator().next();
props.put(key, map.get(key).toString());
}
EmailProvider type = new EmailProvider(typeString, props);
String user = config.getString("email.user");
String pass = config.getString("email.password");
if (user == null || pass == null) {
log.severe("Issue with email configuration section, please fill out everything.");
this.getServer().getPluginManager().disablePlugin(this);
return;
}
mailman = new EmailTransfer(this, type, user, pass);
} else {
mailman = null;
}
emails = new EmailManager(this);
//Enable plugin metrics
try {
MetricsLite metrics = new MetricsLite(this);
metrics.start();
} catch (IOException e) {
e.printStackTrace();
}
this.getCommand("email").setExecutor(new EmailCommands(this));
this.getLogger().info("Enabled successfully");
}
}
| true | true | public void onEnable() {
if (!this.getDataFolder().exists()) {
this.getDataFolder().mkdir();
}
FileConfiguration config = this.getConfig();
config.options().copyHeader(true);
config.options().copyDefaults(true);
this.saveConfig();
Logger log = this.getLogger();
boolean enableEmailSending = config.getBoolean("email.enable");
if (enableEmailSending) {
String typeString = config.getString("email.type");
List<Map<?, ?>> maps = config.getMapList("providers."+typeString);
if(maps == null || maps.isEmpty()) {
log.severe("Unknown email provider! Disabling");
this.getServer().getPluginManager().disablePlugin(this);
return;
}
HashMap<String, String> props = new HashMap<String, String>();
for(Map<?, ?> map : maps) {
//This part is a bit messy/hacky. Sorry. :)
//Nothing should go wrong if the key is a string
//The value should be either a string or int, but toString() will take care if that
@SuppressWarnings("unchecked")
String key = ((Set<String>)map.keySet()).iterator().next();
props.put(key, map.get(key).toString());
}
EmailProvider type = new EmailProvider(typeString, props);
String user = config.getString("email.user");
String pass = config.getString("email.password");
if (user == null || pass == null) {
log.severe("Issue with email configuration section, please fill out everything.");
this.getServer().getPluginManager().disablePlugin(this);
return;
}
mailman = new EmailTransfer(this, type, user, pass);
} else {
mailman = null;
}
emails = new EmailManager(this);
//Enable plugin metrics
try {
MetricsLite metrics = new MetricsLite(this);
metrics.start();
} catch (IOException e) {
e.printStackTrace();
}
this.getCommand("email").setExecutor(new EmailCommands(this));
this.getLogger().info("Enabled successfully");
}
| public void onEnable() {
if (!this.getDataFolder().exists()) {
this.getDataFolder().mkdir();
}
FileConfiguration config = this.getConfig();
config.options().copyHeader(true);
config.options().copyDefaults(true);
this.saveConfig();
Logger log = this.getLogger();
boolean enableEmailSending = config.getBoolean("email.enable");
if (enableEmailSending) {
String typeString = config.getString("email.type");
List<Map<?, ?>> maps = config.getMapList("providers."+typeString);
if(maps == null || maps.isEmpty()) {
log.severe("Unknown email provider! Disabling");
this.getServer().getPluginManager().disablePlugin(this);
return;
}
HashMap<String, String> props = new HashMap<String, String>();
for(Map<?, ?> map : maps) {
//This part is a bit messy/hacky. Sorry. :)
//Nothing should go wrong if the key is a string
//The value should be either a string or int, but toString() will take care of that
@SuppressWarnings("unchecked")
String key = ((Set<String>)map.keySet()).iterator().next();
props.put(key, map.get(key).toString());
}
EmailProvider type = new EmailProvider(typeString, props);
String user = config.getString("email.user");
String pass = config.getString("email.password");
if (user == null || pass == null) {
log.severe("Issue with email configuration section, please fill out everything.");
this.getServer().getPluginManager().disablePlugin(this);
return;
}
mailman = new EmailTransfer(this, type, user, pass);
} else {
mailman = null;
}
emails = new EmailManager(this);
//Enable plugin metrics
try {
MetricsLite metrics = new MetricsLite(this);
metrics.start();
} catch (IOException e) {
e.printStackTrace();
}
this.getCommand("email").setExecutor(new EmailCommands(this));
this.getLogger().info("Enabled successfully");
}
|
diff --git a/src/web/org/openmrs/web/taglib/ForEachEncounterTag.java b/src/web/org/openmrs/web/taglib/ForEachEncounterTag.java
index ac886dda..4bebddb4 100644
--- a/src/web/org/openmrs/web/taglib/ForEachEncounterTag.java
+++ b/src/web/org/openmrs/web/taglib/ForEachEncounterTag.java
@@ -1,200 +1,200 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.taglib;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.apache.commons.collections.comparators.ReverseComparator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Encounter;
public class ForEachEncounterTag extends BodyTagSupport {
public static final long serialVersionUID = 1L;
private final Log log = LogFactory.getLog(getClass());
int count = 0;
List<Encounter> matchingEncs = null;
// Properties accessible through tag attributes
private Collection<Encounter> encounters;
private Integer type;
private Integer num = null;
private String sortBy;
private Boolean descending = Boolean.FALSE;
private String var;
public int doStartTag() {
if (encounters == null || encounters.isEmpty()) {
- log.error("ForEachEncounterTag skipping body due to encounters param = " + encounters);
+ log.error("ForEachEncounterTag skipping body due to 'encounters' param = " + encounters);
return SKIP_BODY;
}
- // First retrieve all encounters matching the passed concept id, if provided.
+ // First retrieve all encounters matching the passed encounter type id, if provided.
// If not provided, return all encounters
matchingEncs = new ArrayList<Encounter>();
for (Iterator<Encounter> i=encounters.iterator(); i.hasNext();) {
Encounter e = i.next();
if (type == null || e.getEncounterType().getEncounterTypeId().intValue() == type.intValue()) {
matchingEncs.add(e);
}
}
log.debug("ForEachEncounterTag found " + matchingEncs.size() + " encounters matching type = " + type);
// Next, sort the encounters
if (sortBy == null || sortBy.equals("")) {
sortBy = "encounterDatetime";
}
Comparator comp = new BeanComparator(sortBy, (descending ? new ReverseComparator(new ComparableComparator()) : new ComparableComparator()));
Collections.sort(matchingEncs, comp);
// Return appropriate number of results
if (matchingEncs.isEmpty()) {
return SKIP_BODY;
} else {
pageContext.setAttribute(var, matchingEncs.get(count++));
return EVAL_BODY_BUFFERED;
}
}
/**
* @see javax.servlet.jsp.tagext.IterationTag#doAfterBody()
*/
public int doAfterBody() throws JspException {
if(matchingEncs.size() > count && (num == null || count < num.intValue())) {
pageContext.setAttribute("count", count);
pageContext.setAttribute(var, matchingEncs.get(count++));
return EVAL_BODY_BUFFERED;
} else {
return SKIP_BODY;
}
}
/**
* @see javax.servlet.jsp.tagext.Tag#doEndTag()
*/
public int doEndTag() throws JspException {
try {
if (count > 0 && bodyContent != null) {
count = 0;
bodyContent.writeOut(bodyContent.getEnclosingWriter());
}
num = null;
}
catch(java.io.IOException e) {
throw new JspTagException("IO Error: " + e.getMessage());
}
return EVAL_PAGE;
}
/**
* @return the descending
*/
public boolean isDescending() {
return descending;
}
/**
* @param descending the descending to set
*/
public void setDescending(boolean descending) {
this.descending = descending;
}
/**
* @return the encounters
*/
public Collection<Encounter> getEncounters() {
return encounters;
}
/**
* @param encounters the encounters to set
*/
public void setEncounters(Collection<Encounter> encounters) {
this.encounters = encounters;
}
/**
* @return the num
*/
public Integer getNum() {
return num;
}
/**
* @param num the num to set
*/
public void setNum(Integer num) {
if (num != 0)
this.num = num;
else
num = null;
}
/**
* @return the sortBy
*/
public String getSortBy() {
return sortBy;
}
/**
* @param sortBy the sortBy to set
*/
public void setSortBy(String sortBy) {
this.sortBy = sortBy;
}
/**
* @return the type
*/
public Integer getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(Integer type) {
this.type = type;
}
/**
* @return the var
*/
public String getVar() {
return var;
}
/**
* @param var the var to set
*/
public void setVar(String var) {
this.var = var;
}
}
| false | true | public int doStartTag() {
if (encounters == null || encounters.isEmpty()) {
log.error("ForEachEncounterTag skipping body due to encounters param = " + encounters);
return SKIP_BODY;
}
// First retrieve all encounters matching the passed concept id, if provided.
// If not provided, return all encounters
matchingEncs = new ArrayList<Encounter>();
for (Iterator<Encounter> i=encounters.iterator(); i.hasNext();) {
Encounter e = i.next();
if (type == null || e.getEncounterType().getEncounterTypeId().intValue() == type.intValue()) {
matchingEncs.add(e);
}
}
log.debug("ForEachEncounterTag found " + matchingEncs.size() + " encounters matching type = " + type);
// Next, sort the encounters
if (sortBy == null || sortBy.equals("")) {
sortBy = "encounterDatetime";
}
Comparator comp = new BeanComparator(sortBy, (descending ? new ReverseComparator(new ComparableComparator()) : new ComparableComparator()));
Collections.sort(matchingEncs, comp);
// Return appropriate number of results
if (matchingEncs.isEmpty()) {
return SKIP_BODY;
} else {
pageContext.setAttribute(var, matchingEncs.get(count++));
return EVAL_BODY_BUFFERED;
}
}
| public int doStartTag() {
if (encounters == null || encounters.isEmpty()) {
log.error("ForEachEncounterTag skipping body due to 'encounters' param = " + encounters);
return SKIP_BODY;
}
// First retrieve all encounters matching the passed encounter type id, if provided.
// If not provided, return all encounters
matchingEncs = new ArrayList<Encounter>();
for (Iterator<Encounter> i=encounters.iterator(); i.hasNext();) {
Encounter e = i.next();
if (type == null || e.getEncounterType().getEncounterTypeId().intValue() == type.intValue()) {
matchingEncs.add(e);
}
}
log.debug("ForEachEncounterTag found " + matchingEncs.size() + " encounters matching type = " + type);
// Next, sort the encounters
if (sortBy == null || sortBy.equals("")) {
sortBy = "encounterDatetime";
}
Comparator comp = new BeanComparator(sortBy, (descending ? new ReverseComparator(new ComparableComparator()) : new ComparableComparator()));
Collections.sort(matchingEncs, comp);
// Return appropriate number of results
if (matchingEncs.isEmpty()) {
return SKIP_BODY;
} else {
pageContext.setAttribute(var, matchingEncs.get(count++));
return EVAL_BODY_BUFFERED;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.