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/org.eclipse.mylyn.tasks.tests/src/org/eclipse/mylyn/tasks/tests/WebRepositoryConnectorTest.java b/org.eclipse.mylyn.tasks.tests/src/org/eclipse/mylyn/tasks/tests/WebRepositoryConnectorTest.java
index 7160b7020..b53b6e312 100644
--- a/org.eclipse.mylyn.tasks.tests/src/org/eclipse/mylyn/tasks/tests/WebRepositoryConnectorTest.java
+++ b/org.eclipse.mylyn.tasks.tests/src/org/eclipse/mylyn/tasks/tests/WebRepositoryConnectorTest.java
@@ -1,96 +1,108 @@
/*******************************************************************************
* Copyright (c) 2006 - 2006 Mylar eclipse.org project 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:
* Mylar project committers - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.tasks.tests;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.extensions.ActiveTestSuite;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.mylar.internal.tasks.core.WebTask;
import org.eclipse.mylar.internal.tasks.web.WebRepositoryConnector;
import org.eclipse.mylar.tasks.core.AbstractQueryHit;
import org.eclipse.mylar.tasks.core.AbstractRepositoryConnector;
import org.eclipse.mylar.tasks.core.QueryHitCollector;
import org.eclipse.mylar.tasks.core.RepositoryTemplate;
import org.eclipse.mylar.tasks.core.TaskRepository;
import org.eclipse.mylar.tasks.ui.TasksUiPlugin;
/**
* @author Eugene Kuleshov
*/
public class WebRepositoryConnectorTest extends TestCase {
private final RepositoryTemplate template;
public WebRepositoryConnectorTest(RepositoryTemplate template) {
super("testRepositoryTemplate");
this.template = template;
}
public void testRepositoryTemplate() throws Exception {
IProgressMonitor monitor = new NullProgressMonitor();
MultiStatus queryStatus = new MultiStatus(TasksUiPlugin.PLUGIN_ID, IStatus.OK, "Query result", null);
final List<AbstractQueryHit> hits = new ArrayList<AbstractQueryHit>();
QueryHitCollector collector = new QueryHitCollector(TasksUiPlugin.getTaskListManager().getTaskList()) {
@Override
public void addMatch(AbstractQueryHit hit) {
hits.add(hit);
}
};
Map<String, String> params = new HashMap<String, String>();
Map<String, String> attributes = new HashMap<String, String>(template.getAttributes());
for(Map.Entry<String, String> e : attributes.entrySet()) {
String key = e.getKey();
- if(key.startsWith(WebRepositoryConnector.PARAM_PREFIX)) {
+// if(key.startsWith(WebRepositoryConnector.PARAM_PREFIX)) {
params.put(key, e.getValue());
- }
+// }
}
TaskRepository repository = new TaskRepository(WebTask.REPOSITORY_TYPE, template.repositoryUrl, params);
- repository.setAuthenticationCredentials("user", "pwd");
+ if(repository.getUrl().equals("http://demo.otrs.org")) {
+ // HACK: OTRS repository require auth
+ repository.setAuthenticationCredentials("skywalker", "skywalker");
+// } else {
+// repository.setAuthenticationCredentials("user", "pwd");
+ }
String taskQueryUrl = WebRepositoryConnector.evaluateParams(template.taskQueryUrl, repository);
- String buffer = WebRepositoryConnector.fetchResource(taskQueryUrl, null, null, null);
+ String buffer = WebRepositoryConnector.fetchResource(taskQueryUrl, params, repository);
+ assertTrue("Unable to fetch resource\n" + taskQueryUrl, buffer != null && buffer.length() > 0);
String regexp = WebRepositoryConnector.evaluateParams(template.getAttribute(WebRepositoryConnector.PROPERTY_QUERY_REGEXP), repository);
IStatus resultingStatus = WebRepositoryConnector.performQuery(buffer, regexp, null, monitor, collector, repository);
assertTrue("Query failed\n"+taskQueryUrl+"\n"+regexp+"\n"+resultingStatus.toString(), queryStatus.isOK());
- assertTrue("Expected non-empty query result\n"+taskQueryUrl+"\n"+regexp, hits.size()>0);
+ try {
+ assertTrue("Expected non-empty query result\n" + taskQueryUrl + "\n" + regexp, hits.size() > 0);
+ } catch (Exception e) {
+ System.err.println(taskQueryUrl);
+ System.err.println(buffer);
+ System.err.println("--------------------------------------------------------");
+ }
}
public String getName() {
return template.label;
}
public static TestSuite suite() {
TestSuite suite = new ActiveTestSuite(WebRepositoryConnectorTest.class.getName());
AbstractRepositoryConnector repositoryConnector = TasksUiPlugin.getRepositoryManager().getRepositoryConnector(WebTask.REPOSITORY_TYPE);
for (RepositoryTemplate template : repositoryConnector.getTemplates()) {
suite.addTest(new WebRepositoryConnectorTest(template));
}
return suite;
}
}
| false | true | public void testRepositoryTemplate() throws Exception {
IProgressMonitor monitor = new NullProgressMonitor();
MultiStatus queryStatus = new MultiStatus(TasksUiPlugin.PLUGIN_ID, IStatus.OK, "Query result", null);
final List<AbstractQueryHit> hits = new ArrayList<AbstractQueryHit>();
QueryHitCollector collector = new QueryHitCollector(TasksUiPlugin.getTaskListManager().getTaskList()) {
@Override
public void addMatch(AbstractQueryHit hit) {
hits.add(hit);
}
};
Map<String, String> params = new HashMap<String, String>();
Map<String, String> attributes = new HashMap<String, String>(template.getAttributes());
for(Map.Entry<String, String> e : attributes.entrySet()) {
String key = e.getKey();
if(key.startsWith(WebRepositoryConnector.PARAM_PREFIX)) {
params.put(key, e.getValue());
}
}
TaskRepository repository = new TaskRepository(WebTask.REPOSITORY_TYPE, template.repositoryUrl, params);
repository.setAuthenticationCredentials("user", "pwd");
String taskQueryUrl = WebRepositoryConnector.evaluateParams(template.taskQueryUrl, repository);
String buffer = WebRepositoryConnector.fetchResource(taskQueryUrl, null, null, null);
String regexp = WebRepositoryConnector.evaluateParams(template.getAttribute(WebRepositoryConnector.PROPERTY_QUERY_REGEXP), repository);
IStatus resultingStatus = WebRepositoryConnector.performQuery(buffer, regexp, null, monitor, collector, repository);
assertTrue("Query failed\n"+taskQueryUrl+"\n"+regexp+"\n"+resultingStatus.toString(), queryStatus.isOK());
assertTrue("Expected non-empty query result\n"+taskQueryUrl+"\n"+regexp, hits.size()>0);
}
| public void testRepositoryTemplate() throws Exception {
IProgressMonitor monitor = new NullProgressMonitor();
MultiStatus queryStatus = new MultiStatus(TasksUiPlugin.PLUGIN_ID, IStatus.OK, "Query result", null);
final List<AbstractQueryHit> hits = new ArrayList<AbstractQueryHit>();
QueryHitCollector collector = new QueryHitCollector(TasksUiPlugin.getTaskListManager().getTaskList()) {
@Override
public void addMatch(AbstractQueryHit hit) {
hits.add(hit);
}
};
Map<String, String> params = new HashMap<String, String>();
Map<String, String> attributes = new HashMap<String, String>(template.getAttributes());
for(Map.Entry<String, String> e : attributes.entrySet()) {
String key = e.getKey();
// if(key.startsWith(WebRepositoryConnector.PARAM_PREFIX)) {
params.put(key, e.getValue());
// }
}
TaskRepository repository = new TaskRepository(WebTask.REPOSITORY_TYPE, template.repositoryUrl, params);
if(repository.getUrl().equals("http://demo.otrs.org")) {
// HACK: OTRS repository require auth
repository.setAuthenticationCredentials("skywalker", "skywalker");
// } else {
// repository.setAuthenticationCredentials("user", "pwd");
}
String taskQueryUrl = WebRepositoryConnector.evaluateParams(template.taskQueryUrl, repository);
String buffer = WebRepositoryConnector.fetchResource(taskQueryUrl, params, repository);
assertTrue("Unable to fetch resource\n" + taskQueryUrl, buffer != null && buffer.length() > 0);
String regexp = WebRepositoryConnector.evaluateParams(template.getAttribute(WebRepositoryConnector.PROPERTY_QUERY_REGEXP), repository);
IStatus resultingStatus = WebRepositoryConnector.performQuery(buffer, regexp, null, monitor, collector, repository);
assertTrue("Query failed\n"+taskQueryUrl+"\n"+regexp+"\n"+resultingStatus.toString(), queryStatus.isOK());
try {
assertTrue("Expected non-empty query result\n" + taskQueryUrl + "\n" + regexp, hits.size() > 0);
} catch (Exception e) {
System.err.println(taskQueryUrl);
System.err.println(buffer);
System.err.println("--------------------------------------------------------");
}
}
|
diff --git a/SeriesGuide/src/com/battlelancer/seriesguide/util/SimpleCrypto.java b/SeriesGuide/src/com/battlelancer/seriesguide/util/SimpleCrypto.java
index 0af1b69b7..4417c62e7 100644
--- a/SeriesGuide/src/com/battlelancer/seriesguide/util/SimpleCrypto.java
+++ b/SeriesGuide/src/com/battlelancer/seriesguide/util/SimpleCrypto.java
@@ -1,102 +1,106 @@
package com.battlelancer.seriesguide.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* Usage:
*
* <pre>
* String crypto = SimpleCrypto.encrypt(cleartext)
* ...
* String cleartext = SimpleCrypto.decrypt(crypto)
* </pre>
*
* @author ferenc.hechler, modified by Uwe Trottmann for SeriesGuide
*/
public class SimpleCrypto {
private static final String KEY_SECURE = "com.battlelancer.seriesguide.secure";
public static String encrypt(String cleartext, Context context) throws Exception {
byte[] rawKey = getRawKey(context);
byte[] result = encrypt(rawKey, cleartext.getBytes());
return toHex(result);
}
public static String decrypt(String encrypted, Context context) throws Exception {
byte[] rawKey = getRawKey(context);
byte[] enc = toByte(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
}
private static byte[] getRawKey(Context context) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
- SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
+ SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context
+ .getApplicationContext());
String seed = prefs.getString(KEY_SECURE, null);
+ byte[] seedBytes;
if (seed == null) {
- seed = toHex(sr.generateSeed(128));
+ seedBytes = sr.generateSeed(16);
+ seed = toHex(seedBytes);
prefs.edit().putString(KEY_SECURE, seed).commit();
} else {
- sr.setSeed(toByte(seed));
+ seedBytes = toByte(seed);
}
+ sr.setSeed(seedBytes);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static String toHex(String txt) {
return toHex(txt.getBytes());
}
public static String fromHex(String hex) {
return new String(toByte(hex));
}
public static byte[] toByte(String hexString) {
int len = hexString.length() / 2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue();
return result;
}
public static String toHex(byte[] b) {
String result = "";
for (int i = 0; i < b.length; i++) {
result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return result;
}
}
| false | true | private static byte[] getRawKey(Context context) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String seed = prefs.getString(KEY_SECURE, null);
if (seed == null) {
seed = toHex(sr.generateSeed(128));
prefs.edit().putString(KEY_SECURE, seed).commit();
} else {
sr.setSeed(toByte(seed));
}
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
| private static byte[] getRawKey(Context context) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context
.getApplicationContext());
String seed = prefs.getString(KEY_SECURE, null);
byte[] seedBytes;
if (seed == null) {
seedBytes = sr.generateSeed(16);
seed = toHex(seedBytes);
prefs.edit().putString(KEY_SECURE, seed).commit();
} else {
seedBytes = toByte(seed);
}
sr.setSeed(seedBytes);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
|
diff --git a/chronicle/src/test/java/com/higherfrequencytrading/chronicle/examples/ExampleRewriteMain.java b/chronicle/src/test/java/com/higherfrequencytrading/chronicle/examples/ExampleRewriteMain.java
index 0f27c58..603d8a3 100644
--- a/chronicle/src/test/java/com/higherfrequencytrading/chronicle/examples/ExampleRewriteMain.java
+++ b/chronicle/src/test/java/com/higherfrequencytrading/chronicle/examples/ExampleRewriteMain.java
@@ -1,97 +1,96 @@
/*
* Copyright 2013 Peter Lawrey
*
* 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.higherfrequencytrading.chronicle.examples;
import com.higherfrequencytrading.chronicle.Excerpt;
import com.higherfrequencytrading.chronicle.impl.IndexedChronicle;
import com.higherfrequencytrading.chronicle.tools.ChronicleTools;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
/**
* @author peter.lawrey
* 50.0% took 0.3 µs, 90.0% took 0.4 µs, 99.0% took 33.5 µs, 99.9% took 66.9 µs, 99.99% took 119.7 µs, worst took 183 µs
*/
public class ExampleRewriteMain {
public static void main(String... ignored) throws IOException {
final String basePath = System.getProperty("java.io.tmpdir") + File.separator + "test";
ChronicleTools.deleteOnExit(basePath);
final int[] consolidates = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
final int warmup = 500000;
final int repeats = 1000000;
//Write
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
final IndexedChronicle chronicle = new IndexedChronicle(basePath);
chronicle.useUnsafe(true); // for benchmarks.
final Excerpt excerpt = chronicle.createExcerpt();
for (int i = -warmup; i < repeats; i++) {
doSomeThinking();
excerpt.startExcerpt(8 + 4 + 4 * consolidates.length);
excerpt.writeLong(System.nanoTime());
excerpt.writeUnsignedShort(consolidates.length);
for (final int consolidate : consolidates) {
excerpt.writeStopBit(consolidate);
}
excerpt.finish();
}
chronicle.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void doSomeThinking() {
// real programs do some work between messages
// this has an impact on the worst case latencies.
Thread.yield();
}
});
t.start();
//Read
final IndexedChronicle chronicle = new IndexedChronicle(basePath);
chronicle.useUnsafe(true); // for benchmarks.
final Excerpt excerpt = chronicle.createExcerpt();
int[] times = new int[repeats];
for (int count = -warmup; count < repeats; count++) {
do {
/* busy wait */
} while (!excerpt.nextIndex());
final long timestamp = excerpt.readLong();
long time = System.nanoTime() - timestamp;
if (count >= 0)
times[count] = (int) time;
final int nbConsolidates = excerpt.readUnsignedShort();
assert nbConsolidates == consolidates.length;
for (int i = 0; i < nbConsolidates; i++) {
excerpt.readStopBit();
}
excerpt.finish();
- count++;
}
Arrays.sort(times);
for (double perc : new double[]{50, 90, 99, 99.9, 99.99}) {
System.out.printf("%s%% took %.1f µs, ", perc, times[((int) (repeats * perc / 100))] / 1000.0);
}
System.out.printf("worst took %d µs%n", times[times.length - 1] / 1000);
chronicle.close();
}
}
| true | true | public static void main(String... ignored) throws IOException {
final String basePath = System.getProperty("java.io.tmpdir") + File.separator + "test";
ChronicleTools.deleteOnExit(basePath);
final int[] consolidates = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
final int warmup = 500000;
final int repeats = 1000000;
//Write
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
final IndexedChronicle chronicle = new IndexedChronicle(basePath);
chronicle.useUnsafe(true); // for benchmarks.
final Excerpt excerpt = chronicle.createExcerpt();
for (int i = -warmup; i < repeats; i++) {
doSomeThinking();
excerpt.startExcerpt(8 + 4 + 4 * consolidates.length);
excerpt.writeLong(System.nanoTime());
excerpt.writeUnsignedShort(consolidates.length);
for (final int consolidate : consolidates) {
excerpt.writeStopBit(consolidate);
}
excerpt.finish();
}
chronicle.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void doSomeThinking() {
// real programs do some work between messages
// this has an impact on the worst case latencies.
Thread.yield();
}
});
t.start();
//Read
final IndexedChronicle chronicle = new IndexedChronicle(basePath);
chronicle.useUnsafe(true); // for benchmarks.
final Excerpt excerpt = chronicle.createExcerpt();
int[] times = new int[repeats];
for (int count = -warmup; count < repeats; count++) {
do {
/* busy wait */
} while (!excerpt.nextIndex());
final long timestamp = excerpt.readLong();
long time = System.nanoTime() - timestamp;
if (count >= 0)
times[count] = (int) time;
final int nbConsolidates = excerpt.readUnsignedShort();
assert nbConsolidates == consolidates.length;
for (int i = 0; i < nbConsolidates; i++) {
excerpt.readStopBit();
}
excerpt.finish();
count++;
}
Arrays.sort(times);
for (double perc : new double[]{50, 90, 99, 99.9, 99.99}) {
System.out.printf("%s%% took %.1f µs, ", perc, times[((int) (repeats * perc / 100))] / 1000.0);
}
System.out.printf("worst took %d µs%n", times[times.length - 1] / 1000);
chronicle.close();
}
| public static void main(String... ignored) throws IOException {
final String basePath = System.getProperty("java.io.tmpdir") + File.separator + "test";
ChronicleTools.deleteOnExit(basePath);
final int[] consolidates = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
final int warmup = 500000;
final int repeats = 1000000;
//Write
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
final IndexedChronicle chronicle = new IndexedChronicle(basePath);
chronicle.useUnsafe(true); // for benchmarks.
final Excerpt excerpt = chronicle.createExcerpt();
for (int i = -warmup; i < repeats; i++) {
doSomeThinking();
excerpt.startExcerpt(8 + 4 + 4 * consolidates.length);
excerpt.writeLong(System.nanoTime());
excerpt.writeUnsignedShort(consolidates.length);
for (final int consolidate : consolidates) {
excerpt.writeStopBit(consolidate);
}
excerpt.finish();
}
chronicle.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void doSomeThinking() {
// real programs do some work between messages
// this has an impact on the worst case latencies.
Thread.yield();
}
});
t.start();
//Read
final IndexedChronicle chronicle = new IndexedChronicle(basePath);
chronicle.useUnsafe(true); // for benchmarks.
final Excerpt excerpt = chronicle.createExcerpt();
int[] times = new int[repeats];
for (int count = -warmup; count < repeats; count++) {
do {
/* busy wait */
} while (!excerpt.nextIndex());
final long timestamp = excerpt.readLong();
long time = System.nanoTime() - timestamp;
if (count >= 0)
times[count] = (int) time;
final int nbConsolidates = excerpt.readUnsignedShort();
assert nbConsolidates == consolidates.length;
for (int i = 0; i < nbConsolidates; i++) {
excerpt.readStopBit();
}
excerpt.finish();
}
Arrays.sort(times);
for (double perc : new double[]{50, 90, 99, 99.9, 99.99}) {
System.out.printf("%s%% took %.1f µs, ", perc, times[((int) (repeats * perc / 100))] / 1000.0);
}
System.out.printf("worst took %d µs%n", times[times.length - 1] / 1000);
chronicle.close();
}
|
diff --git a/plugins/org.eclipse.m2m.atl.core.ant/src_ant/org/eclipse/m2m/atl/core/ant/tasks/ATLModelTransformationTask.java b/plugins/org.eclipse.m2m.atl.core.ant/src_ant/org/eclipse/m2m/atl/core/ant/tasks/ATLModelTransformationTask.java
index 2a4fbf3f..d1e8839b 100644
--- a/plugins/org.eclipse.m2m.atl.core.ant/src_ant/org/eclipse/m2m/atl/core/ant/tasks/ATLModelTransformationTask.java
+++ b/plugins/org.eclipse.m2m.atl.core.ant/src_ant/org/eclipse/m2m/atl/core/ant/tasks/ATLModelTransformationTask.java
@@ -1,245 +1,245 @@
/*******************************************************************************
* Copyright (c) 2008, 2009 Obeo.
* 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:
* Obeo - Ant tooling
*******************************************************************************/
package org.eclipse.m2m.atl.core.ant.tasks;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.tools.ant.BuildException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.m2m.atl.common.ATLExecutionException;
import org.eclipse.m2m.atl.core.ATLCoreException;
import org.eclipse.m2m.atl.core.IModel;
import org.eclipse.m2m.atl.core.IReferenceModel;
import org.eclipse.m2m.atl.core.ModelFactory;
import org.eclipse.m2m.atl.core.ant.AtlBuildListener;
import org.eclipse.m2m.atl.core.ant.Messages;
import org.eclipse.m2m.atl.core.ant.tasks.nested.InModel;
import org.eclipse.m2m.atl.core.ant.tasks.nested.Library;
import org.eclipse.m2m.atl.core.ant.tasks.nested.OutModel;
import org.eclipse.m2m.atl.core.ant.tasks.nested.Param;
import org.eclipse.m2m.atl.core.ant.tasks.nested.Superimpose;
import org.eclipse.m2m.atl.core.launch.ILauncher;
import org.eclipse.m2m.atl.core.service.LauncherService;
/**
* Launches an ATL transformation, using the launcher specified as property in the ant project.
*
* @author <a href="mailto:[email protected]">William Piers</a>
*/
public class ATLModelTransformationTask extends AbstractAtlTask {
protected boolean isRefiningTraceMode;
protected File asmPath;
protected List<InModel> inModels = new ArrayList<InModel>();
protected List<OutModel> outModels = new ArrayList<OutModel>();
protected List<InModel> inoutModels = new ArrayList<InModel>();
protected List<Library> libraries = new ArrayList<Library>();
protected Map<String, Object> options = new HashMap<String, Object>();
protected List<Superimpose> superimposeModules = new ArrayList<Superimpose>();
public void setRefining(boolean isRefining) {
this.isRefiningTraceMode = isRefining;
}
public void setPath(File path) {
this.asmPath = path;
}
/**
* Adds an input model to the task.
*
* @param model
* the given model
*/
public void addConfiguredInModel(InModel model) {
inModels.add(model);
}
/**
* Adds an output model to the task.
*
* @param model
* the given model
*/
public void addConfiguredOutModel(OutModel model) {
Map<String, Object> modelOptions = new HashMap<String, Object>();
modelOptions.put(OPTION_MODEL_NAME, model.getName());
modelOptions.put(OPTION_MODEL_PATH, model.getPath());
modelOptions.put(OPTION_NEW_MODEL, true);
if (model.getFactory() != null) {
newModel(model.getFactory(), model.getModel(), model.getMetamodel(), modelOptions);
} else {
newModel(getDefaultModelFactory(), model.getModel(), model.getMetamodel(), modelOptions);
}
outModels.add(model);
}
/**
* Adds an input/output model to the task.
*
* @param model
* the given model
*/
public void addConfiguredInoutModel(InModel model) {
inoutModels.add(model);
}
/**
* Adds a library to the task.
*
* @param library
* the given library
*/
public void addConfiguredLibrary(Library library) {
libraries.add(library);
}
/**
* Adds a superimposition module to the task.
*
* @param superimpose
* the given superimposition module
*/
public void addConfiguredSuperimpose(Superimpose superimpose) {
this.superimposeModules.add(superimpose);
}
/**
* Adds an option to the task.
*
* @param option
* the given option
*/
public void addConfiguredOption(Param option) {
options.put(option.getName(), option.getValue());
}
/**
* {@inheritDoc}
*
* @see org.eclipse.m2m.atl.core.ant.tasks.AbstractAtlTask#execute()
*/
@Override
public void execute() throws BuildException {
log(Messages.getString("ATLModelTransformationTask.MSG", asmPath.toString(), getLauncherName())); //$NON-NLS-1$
ILauncher launcherInstance = getLauncher();
launcherInstance.initialize(options);
if (asmPath == null) {
error(Messages.getString("ATLModelTransformationTask.UNSPECIFIED_MODULE")); //$NON-NLS-1$
}
for (InModel model : inModels) {
launcherInstance.addInModel(getModelByName(model.getModel()), model.getName(),
getMetamodelName(model.getModel()));
}
for (InModel model : inoutModels) {
launcherInstance.addInOutModel(getModelByName(model.getModel()), model.getName(),
getMetamodelName(model.getModel()));
}
for (OutModel model : outModels) {
launcherInstance.addOutModel(getModelByName(model.getModel()), model.getName(), model
.getMetamodel());
}
for (Library library : libraries) {
launcherInstance.addLibrary(library.getName(), getInputStreamFromPath(library.getPath()));
}
try {
if (isRefiningTraceMode) {
ModelFactory factory = AtlBuildListener.getModelFactory(launcherInstance
.getDefaultModelFactoryName());
IReferenceModel refiningTraceMetamodel = factory
.getBuiltInResource(LauncherService.REFINING_TRACE_METAMODEL + ".ecore"); //$NON-NLS-1$
getProject().addReference(LauncherService.REFINING_TRACE_METAMODEL, refiningTraceMetamodel);
Map<String, Object> modelOptions = new HashMap<String, Object>();
modelOptions.put(OPTION_MODEL_PATH, "temp"); //$NON-NLS-1$
modelOptions.put(OPTION_MODEL_NAME, LauncherService.REFINING_TRACE_MODEL);
modelOptions.put(OPTION_NEW_MODEL, true);
IModel refiningTraceModel = newModel(factory, LauncherService.REFINING_TRACE_MODEL,
LauncherService.REFINING_TRACE_METAMODEL, options);
launcherInstance.addOutModel(refiningTraceModel, LauncherService.REFINING_TRACE_MODEL,
LauncherService.REFINING_TRACE_METAMODEL);
}
} catch (ATLCoreException e) {
error(Messages.getString("ATLModelTransformationTask.UNABLE_TO_LOAD_REFINING")); //$NON-NLS-1$
}
InputStream[] moduleInputStreams = new InputStream[superimposeModules.size() + 1];
- int i = 0;
+ int i = 1;
moduleInputStreams[0] = getInputStreamFromPath(asmPath);
for (Superimpose superimposedModule : superimposeModules) {
moduleInputStreams[i++] = getInputStreamFromPath(superimposedModule.getPath());
}
Object transformationResult = null;
long startTime = System.currentTimeMillis();
try {
transformationResult = launcherInstance.launch(ILauncher.RUN_MODE, new NullProgressMonitor(),
options, (Object[])moduleInputStreams);
} catch (ATLExecutionException e) {
error(e.getMessage(), e);
}
long endTime = System.currentTimeMillis();
double executionTime = (endTime - startTime) / 1000.;
getProject().addReference(RESULT_REFERENCE, transformationResult);
log(Messages.getString("ATLModelTransformationTask.EXECUTION_TIME", executionTime)); //$NON-NLS-1$
super.execute();
}
private IModel getModelByName(String name) {
IModel res = (IModel)getProject().getReference(name);
if (res == null) {
error(Messages.getString("ATLModelTransformationTask.MODEL_NOT_FOUND", name)); //$NON-NLS-1$
}
return res;
}
private String getMetamodelName(String modelName) {
IReferenceModel res = getModelByName(modelName).getReferenceModel();
for (Iterator<?> iterator = getProject().getReferences().entrySet().iterator(); iterator.hasNext();) {
Entry<?, ?> entry = (Entry<?, ?>)iterator.next();
if (entry.getValue().equals(res)) {
return (String)entry.getKey();
}
}
return null;
}
private InputStream getInputStreamFromPath(File path) {
try {
return new FileInputStream(path);
} catch (IOException e) {
error(Messages.getString("ATLModelTransformationTask.FILE_NOT_FOUND", path), e); //$NON-NLS-1$
}
return null;
}
}
| true | true | public void execute() throws BuildException {
log(Messages.getString("ATLModelTransformationTask.MSG", asmPath.toString(), getLauncherName())); //$NON-NLS-1$
ILauncher launcherInstance = getLauncher();
launcherInstance.initialize(options);
if (asmPath == null) {
error(Messages.getString("ATLModelTransformationTask.UNSPECIFIED_MODULE")); //$NON-NLS-1$
}
for (InModel model : inModels) {
launcherInstance.addInModel(getModelByName(model.getModel()), model.getName(),
getMetamodelName(model.getModel()));
}
for (InModel model : inoutModels) {
launcherInstance.addInOutModel(getModelByName(model.getModel()), model.getName(),
getMetamodelName(model.getModel()));
}
for (OutModel model : outModels) {
launcherInstance.addOutModel(getModelByName(model.getModel()), model.getName(), model
.getMetamodel());
}
for (Library library : libraries) {
launcherInstance.addLibrary(library.getName(), getInputStreamFromPath(library.getPath()));
}
try {
if (isRefiningTraceMode) {
ModelFactory factory = AtlBuildListener.getModelFactory(launcherInstance
.getDefaultModelFactoryName());
IReferenceModel refiningTraceMetamodel = factory
.getBuiltInResource(LauncherService.REFINING_TRACE_METAMODEL + ".ecore"); //$NON-NLS-1$
getProject().addReference(LauncherService.REFINING_TRACE_METAMODEL, refiningTraceMetamodel);
Map<String, Object> modelOptions = new HashMap<String, Object>();
modelOptions.put(OPTION_MODEL_PATH, "temp"); //$NON-NLS-1$
modelOptions.put(OPTION_MODEL_NAME, LauncherService.REFINING_TRACE_MODEL);
modelOptions.put(OPTION_NEW_MODEL, true);
IModel refiningTraceModel = newModel(factory, LauncherService.REFINING_TRACE_MODEL,
LauncherService.REFINING_TRACE_METAMODEL, options);
launcherInstance.addOutModel(refiningTraceModel, LauncherService.REFINING_TRACE_MODEL,
LauncherService.REFINING_TRACE_METAMODEL);
}
} catch (ATLCoreException e) {
error(Messages.getString("ATLModelTransformationTask.UNABLE_TO_LOAD_REFINING")); //$NON-NLS-1$
}
InputStream[] moduleInputStreams = new InputStream[superimposeModules.size() + 1];
int i = 0;
moduleInputStreams[0] = getInputStreamFromPath(asmPath);
for (Superimpose superimposedModule : superimposeModules) {
moduleInputStreams[i++] = getInputStreamFromPath(superimposedModule.getPath());
}
Object transformationResult = null;
long startTime = System.currentTimeMillis();
try {
transformationResult = launcherInstance.launch(ILauncher.RUN_MODE, new NullProgressMonitor(),
options, (Object[])moduleInputStreams);
} catch (ATLExecutionException e) {
error(e.getMessage(), e);
}
long endTime = System.currentTimeMillis();
double executionTime = (endTime - startTime) / 1000.;
getProject().addReference(RESULT_REFERENCE, transformationResult);
log(Messages.getString("ATLModelTransformationTask.EXECUTION_TIME", executionTime)); //$NON-NLS-1$
super.execute();
}
| public void execute() throws BuildException {
log(Messages.getString("ATLModelTransformationTask.MSG", asmPath.toString(), getLauncherName())); //$NON-NLS-1$
ILauncher launcherInstance = getLauncher();
launcherInstance.initialize(options);
if (asmPath == null) {
error(Messages.getString("ATLModelTransformationTask.UNSPECIFIED_MODULE")); //$NON-NLS-1$
}
for (InModel model : inModels) {
launcherInstance.addInModel(getModelByName(model.getModel()), model.getName(),
getMetamodelName(model.getModel()));
}
for (InModel model : inoutModels) {
launcherInstance.addInOutModel(getModelByName(model.getModel()), model.getName(),
getMetamodelName(model.getModel()));
}
for (OutModel model : outModels) {
launcherInstance.addOutModel(getModelByName(model.getModel()), model.getName(), model
.getMetamodel());
}
for (Library library : libraries) {
launcherInstance.addLibrary(library.getName(), getInputStreamFromPath(library.getPath()));
}
try {
if (isRefiningTraceMode) {
ModelFactory factory = AtlBuildListener.getModelFactory(launcherInstance
.getDefaultModelFactoryName());
IReferenceModel refiningTraceMetamodel = factory
.getBuiltInResource(LauncherService.REFINING_TRACE_METAMODEL + ".ecore"); //$NON-NLS-1$
getProject().addReference(LauncherService.REFINING_TRACE_METAMODEL, refiningTraceMetamodel);
Map<String, Object> modelOptions = new HashMap<String, Object>();
modelOptions.put(OPTION_MODEL_PATH, "temp"); //$NON-NLS-1$
modelOptions.put(OPTION_MODEL_NAME, LauncherService.REFINING_TRACE_MODEL);
modelOptions.put(OPTION_NEW_MODEL, true);
IModel refiningTraceModel = newModel(factory, LauncherService.REFINING_TRACE_MODEL,
LauncherService.REFINING_TRACE_METAMODEL, options);
launcherInstance.addOutModel(refiningTraceModel, LauncherService.REFINING_TRACE_MODEL,
LauncherService.REFINING_TRACE_METAMODEL);
}
} catch (ATLCoreException e) {
error(Messages.getString("ATLModelTransformationTask.UNABLE_TO_LOAD_REFINING")); //$NON-NLS-1$
}
InputStream[] moduleInputStreams = new InputStream[superimposeModules.size() + 1];
int i = 1;
moduleInputStreams[0] = getInputStreamFromPath(asmPath);
for (Superimpose superimposedModule : superimposeModules) {
moduleInputStreams[i++] = getInputStreamFromPath(superimposedModule.getPath());
}
Object transformationResult = null;
long startTime = System.currentTimeMillis();
try {
transformationResult = launcherInstance.launch(ILauncher.RUN_MODE, new NullProgressMonitor(),
options, (Object[])moduleInputStreams);
} catch (ATLExecutionException e) {
error(e.getMessage(), e);
}
long endTime = System.currentTimeMillis();
double executionTime = (endTime - startTime) / 1000.;
getProject().addReference(RESULT_REFERENCE, transformationResult);
log(Messages.getString("ATLModelTransformationTask.EXECUTION_TIME", executionTime)); //$NON-NLS-1$
super.execute();
}
|
diff --git a/src/rajawali/BaseObject3D.java b/src/rajawali/BaseObject3D.java
index 7b304059..f141d359 100644
--- a/src/rajawali/BaseObject3D.java
+++ b/src/rajawali/BaseObject3D.java
@@ -1,817 +1,820 @@
package rajawali;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import java.util.ArrayList;
import java.util.Stack;
import rajawali.bounds.BoundingBox;
import rajawali.lights.ALight;
import rajawali.materials.AMaterial;
import rajawali.materials.ColorPickerMaterial;
import rajawali.materials.TextureInfo;
import rajawali.materials.TextureManager.TextureType;
import rajawali.math.Number3D;
import rajawali.util.ObjectColorPicker.ColorPickerInfo;
import rajawali.util.RajLog;
import rajawali.visitors.INode;
import rajawali.visitors.INodeVisitor;
import android.graphics.Color;
import android.opengl.GLES20;
import android.opengl.GLU;
import android.opengl.Matrix;
/**
* This is the main object that all other 3D objects inherit from.
*
* @author dennis.ippel
*
*/
public class BaseObject3D extends ATransformable3D implements Comparable<BaseObject3D>, INode {
protected float[] mMVPMatrix = new float[16];
protected float[] mMMatrix = new float[16];
protected float[] mProjMatrix;
protected float[] mScalematrix = new float[16];
protected float[] mTranslateMatrix = new float[16];
protected float[] mRotateMatrix = new float[16];
protected float[] mRotateMatrixTmp = new float[16];
protected float[] mTmpMatrix = new float[16];
protected AMaterial mMaterial;
protected Stack<ALight> mLights;
protected Geometry3D mGeometry;
protected ArrayList<BaseObject3D> mChildren;
protected String mName;
protected boolean mDoubleSided = false;
protected boolean mBackSided = false;
protected boolean mTransparent = false;
protected boolean mForcedDepth = false;
protected boolean mHasCubemapTexture = false;
protected boolean mIsVisible = true;
protected boolean mShowBoundingVolume = false;
protected int mDrawingMode = GLES20.GL_TRIANGLES;
protected int mElementsBufferType = GLES20.GL_UNSIGNED_INT;
protected boolean mIsContainerOnly = true;
protected int mPickingColor;
protected boolean mIsPickingEnabled = false;
protected float[] mPickingColorArray;
protected boolean mFrustumTest = false;
protected boolean mIsInFrustum;
protected boolean mRenderChildrenAsBatch = false;
protected boolean mIsPartOfBatch = false;
protected boolean mManageMaterial = true;
protected boolean mEnableBlending = false;
protected int mBlendFuncSFactor;
protected int mBlendFuncDFactor;
protected boolean mEnableDepthTest = true;
protected boolean mEnableDepthMask = true;
public BaseObject3D() {
super();
mChildren = new ArrayList<BaseObject3D>();
mGeometry = new Geometry3D();
mLights = new Stack<ALight>();
}
public BaseObject3D(String name) {
this();
mName = name;
}
/**
* Creates a BaseObject3D from a serialized file. A serialized file can be a BaseObject3D but also a
* VertexAnimationObject3D.
*
* A serialized file can be created by the MeshExporter class. Example: <code>
Cube cube = new Cube(2);
MeshExporter exporter = new MeshExporter(cube);
exporter.export("myobject.ser", ExportType.SERIALIZED);
</code> This saves the serialized file to
* the SD card.
*
* @param ser
*/
public BaseObject3D(SerializedObject3D ser) {
this();
setData(ser);
}
/**
* Passes the data to the Geometry3D instance. Vertex Buffer Objects (VBOs) will be created.
*
* @param vertexBufferInfo
* The handle to the vertex buffer
* @param normalBufferInfo
* The handle to the normal buffer
* @param textureCoords
* A float array containing texture coordinates
* @param colors
* A float array containing color values (rgba)
* @param indices
* An integer array containing face indices
*/
public void setData(BufferInfo vertexBufferInfo, BufferInfo normalBufferInfo, float[] textureCoords,
float[] colors, int[] indices) {
mGeometry.setData(vertexBufferInfo, normalBufferInfo, textureCoords, colors, indices);
mIsContainerOnly = false;
mElementsBufferType = mGeometry.areOnlyShortBuffersSupported() ? GLES20.GL_UNSIGNED_SHORT
: GLES20.GL_UNSIGNED_INT;
}
/**
* Passes the data to the Geometry3D instance. Vertex Buffer Objects (VBOs) will be created.
*
* @param vertices
* A float array containing vertex data
* @param normals
* A float array containing normal data
* @param textureCoords
* A float array containing texture coordinates
* @param colors
* A float array containing color values (rgba)
* @param indices
* An integer array containing face indices
*/
public void setData(float[] vertices, float[] normals, float[] textureCoords, float[] colors, int[] indices) {
setData(vertices, GLES20.GL_STATIC_DRAW, normals, GLES20.GL_STATIC_DRAW, textureCoords, GLES20.GL_STATIC_DRAW,
colors, GLES20.GL_STATIC_DRAW, indices, GLES20.GL_STATIC_DRAW);
}
/**
* Passes serialized data to the Geometry3D instance. Vertex Buffer Objects (VBOs) will be created.
*
* A serialized file can be created by the MeshExporter class. Example: <code>
Cube cube = new Cube(2);
MeshExporter exporter = new MeshExporter(cube);
exporter.export("myobject.ser", ExportType.SERIALIZED);
</code> This saves the serialized file to
* the SD card.
*
* @param ser
*/
public void setData(SerializedObject3D ser) {
setData(ser.getVertices(), ser.getNormals(), ser.getTextureCoords(), ser.getColors(), ser.getIndices());
}
public void setData(float[] vertices, int verticesUsage, float[] normals, int normalsUsage, float[] textureCoords,
int textureCoordsUsage,
float[] colors, int colorsUsage, int[] indices, int indicesUsage) {
mGeometry.setData(vertices, verticesUsage, normals, normalsUsage, textureCoords, textureCoordsUsage, colors,
colorsUsage, indices, indicesUsage);
mIsContainerOnly = false;
mElementsBufferType = mGeometry.areOnlyShortBuffersSupported() ? GLES20.GL_UNSIGNED_SHORT
: GLES20.GL_UNSIGNED_INT;
}
/**
* Executed before the rendering process starts
*/
protected void preRender() {
mGeometry.validateBuffers();
}
public void render(Camera camera, float[] projMatrix, float[] vMatrix, ColorPickerInfo pickerInfo) {
render(camera, projMatrix, vMatrix, null, pickerInfo);
}
/**
* Renders the object
*
* @param camera
* The camera
* @param projMatrix
* The projection matrix
* @param vMatrix
* The view matrix
* @param parentMatrix
* This object's parent matrix
* @param pickerInfo
* The current color picker info. This is only used when an object is touched.
*/
public void render(Camera camera, float[] projMatrix, float[] vMatrix, final float[] parentMatrix,
ColorPickerInfo pickerInfo) {
if (!mIsVisible)
return;
preRender();
// -- move view matrix transformation first
Matrix.setIdentityM(mMMatrix, 0);
Matrix.setIdentityM(mScalematrix, 0);
Matrix.scaleM(mScalematrix, 0, mScale.x, mScale.y, mScale.z);
Matrix.setIdentityM(mRotateMatrix, 0);
setOrientation();
if (mLookAt == null) {
mOrientation.toRotationMatrix(mRotateMatrix);
} else {
System.arraycopy(mLookAtMatrix, 0, mRotateMatrix, 0, 16);
}
Matrix.translateM(mMMatrix, 0, -mPosition.x, mPosition.y, mPosition.z);
Matrix.setIdentityM(mTmpMatrix, 0);
Matrix.multiplyMM(mTmpMatrix, 0, mMMatrix, 0, mScalematrix, 0);
Matrix.multiplyMM(mMMatrix, 0, mTmpMatrix, 0, mRotateMatrix, 0);
if (parentMatrix != null) {
Matrix.multiplyMM(mTmpMatrix, 0, parentMatrix, 0, mMMatrix, 0);
System.arraycopy(mTmpMatrix, 0, mMMatrix, 0, 16);
}
Matrix.multiplyMM(mMVPMatrix, 0, vMatrix, 0, mMMatrix, 0);
Matrix.multiplyMM(mMVPMatrix, 0, projMatrix, 0, mMVPMatrix, 0);
mIsInFrustum = true; // only if mFrustrumTest == true it check frustum
if (mFrustumTest && mGeometry.hasBoundingBox()) {
BoundingBox bbox = mGeometry.getBoundingBox();
bbox.transform(mMMatrix);
if (!camera.mFrustum.boundsInFrustum(bbox)) {
mIsInFrustum = false;
}
}
if (!mIsContainerOnly && mIsInFrustum) {
mProjMatrix = projMatrix;
if (!mDoubleSided) {
GLES20.glEnable(GLES20.GL_CULL_FACE);
- if (mBackSided)
+ if (mBackSided) {
GLES20.glCullFace(GLES20.GL_FRONT);
- else
+ GLES20.glFrontFace(GLES20.GL_CW);
+ } else {
GLES20.glCullFace(GLES20.GL_BACK);
+ GLES20.glFrontFace(GLES20.GL_CCW);
+ }
}
if (mEnableBlending && !(pickerInfo != null && mIsPickingEnabled)) {
GLES20.glEnable(GLES20.GL_BLEND);
GLES20.glBlendFunc(mBlendFuncSFactor, mBlendFuncDFactor);
} else {
GLES20.glDisable(GLES20.GL_BLEND);
}
if (mEnableDepthTest)
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
else
GLES20.glDisable(GLES20.GL_DEPTH_TEST);
GLES20.glDepthMask(mEnableDepthMask);
if (pickerInfo != null && mIsPickingEnabled) {
ColorPickerMaterial pickerMat = pickerInfo.getPicker().getMaterial();
pickerMat.setPickingColor(mPickingColorArray);
pickerMat.useProgram();
pickerMat.setCamera(camera);
pickerMat.setVertices(mGeometry.getVertexBufferInfo().bufferHandle);
} else {
if (!mIsPartOfBatch) {
if (mMaterial == null) {
RajLog.e("[" + this.getClass().getName()
+ "] This object can't renderer because there's no material attached to it.");
throw new RuntimeException(
"This object can't renderer because there's no material attached to it.");
}
mMaterial.useProgram();
setShaderParams(camera);
mMaterial.bindTextures();
mMaterial.setTextureCoords(mGeometry.getTexCoordBufferInfo().bufferHandle, mHasCubemapTexture);
mMaterial.setNormals(mGeometry.getNormalBufferInfo().bufferHandle);
mMaterial.setCamera(camera);
mMaterial.setVertices(mGeometry.getVertexBufferInfo().bufferHandle);
}
if (mMaterial.getUseColor())
mMaterial.setColors(mGeometry.getColorBufferInfo().bufferHandle);
}
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
if (pickerInfo == null)
{
mMaterial.setMVPMatrix(mMVPMatrix);
mMaterial.setModelMatrix(mMMatrix);
mMaterial.setViewMatrix(vMatrix);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, mGeometry.getIndexBufferInfo().bufferHandle);
fix.android.opengl.GLES20.glDrawElements(mDrawingMode, mGeometry.getNumIndices(), mElementsBufferType,
0);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0);
if (!mIsPartOfBatch && !mRenderChildrenAsBatch) {
mMaterial.unbindTextures();
}
} else if (pickerInfo != null && mIsPickingEnabled) {
ColorPickerMaterial pickerMat = pickerInfo.getPicker().getMaterial();
pickerMat.setMVPMatrix(mMVPMatrix);
pickerMat.setModelMatrix(mMMatrix);
pickerMat.setViewMatrix(vMatrix);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, mGeometry.getIndexBufferInfo().bufferHandle);
fix.android.opengl.GLES20.glDrawElements(mDrawingMode, mGeometry.getNumIndices(), mElementsBufferType,
0);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0);
pickerMat.unbindTextures();
}
GLES20.glDisable(GLES20.GL_CULL_FACE);
GLES20.glDisable(GLES20.GL_BLEND);
GLES20.glDisable(GLES20.GL_DEPTH_TEST);
}
if (mShowBoundingVolume) {
if (mGeometry.hasBoundingBox())
mGeometry.getBoundingBox().drawBoundingVolume(camera, projMatrix, vMatrix, mMMatrix);
if (mGeometry.hasBoundingSphere())
mGeometry.getBoundingSphere().drawBoundingVolume(camera, projMatrix, vMatrix, mMMatrix);
}
// Draw children without frustum test
for (int i = 0, j = mChildren.size(); i < j; i++)
mChildren.get(i).render(camera, projMatrix, vMatrix, mMMatrix, pickerInfo);
if (mRenderChildrenAsBatch) {
mMaterial.unbindTextures();
}
}
/**
* Optimized version of Matrix.rotateM(). Apparently the native version does a lot of float[] allocations.
*
* @see http://groups.google.com/group/android-developers/browse_thread/thread/b30dd2a437cfb076?pli=1
*
* @param m
* The matrix
* @param mOffset
* Matrix offset
* @param a
* The angle
* @param x
* x axis
* @param y
* y axis
* @param z
* z axis
*/
protected void rotateM(float[] m, int mOffset, float a, float x, float y, float z) {
Matrix.setIdentityM(mRotateMatrixTmp, 0);
Matrix.setRotateM(mRotateMatrixTmp, 0, a, x, y, z);
System.arraycopy(m, 0, mTmpMatrix, 0, 16);
Matrix.multiplyMM(m, mOffset, mTmpMatrix, mOffset, mRotateMatrixTmp, 0);
}
/**
* This is where the parameters for the shaders are set. It is called every frame.
*
* @param camera
*/
protected void setShaderParams(Camera camera) {
mMaterial.setLightParams();
};
/**
* Adds a texture to this object
*
* @parameter textureInfo
*/
public void addTexture(TextureInfo textureInfo) {
if (mMaterial == null) {
RajLog.e("[" + getClass().getName() + "] Material is null. Please add a material before adding a texture.");
throw new RuntimeException("Material is null. Please add a material first.");
}
if (mLights.size() > 0 && textureInfo.getTextureType() != TextureType.SPHERE_MAP) {
mMaterial.setUseColor(false);
}
mMaterial.addTexture(textureInfo);
}
public void removeTexture(TextureInfo textureInfo) {
mMaterial.removeTexture(textureInfo);
}
protected void checkGlError(String op) {
int error;
while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) {
RajLog.e(op + ": glError " + error + " in class " + this.getClass().getName());
throw new RuntimeException(op + ": glError " + error);
}
}
/**
* The reload method is called whenever the OpenGL context needs to be re-created. When the OpenGL context was lost,
* the vertex, uv coord, index etc data needs to be re-uploaded.
*/
public void reload() {
if (!mIsContainerOnly) {
if (mManageMaterial)
mMaterial.reload();
mGeometry.reload();
}
for (int i = 0, j = mChildren.size(); i < j; i++)
mChildren.get(i).reload();
if (mGeometry.hasBoundingBox() && mGeometry.getBoundingBox().getVisual() != null)
mGeometry.getBoundingBox().getVisual().reload();
if (mGeometry.hasBoundingSphere() && mGeometry.getBoundingSphere().getVisual() != null)
mGeometry.getBoundingSphere().getVisual().reload();
}
public void isContainer(boolean isContainer) {
mIsContainerOnly = isContainer;
}
public boolean isContainer() {
return mIsContainerOnly;
}
/**
* Maps screen coordinates to object coordinates
*
* @param x
* @param y
* @param viewportWidth
* @param viewportHeight
* @param eyeZ
*/
public void setScreenCoordinates(float x, float y, int viewportWidth, int viewportHeight, float eyeZ) {
float[] r1 = new float[16];
int[] viewport = new int[] { 0, 0, viewportWidth, viewportHeight };
float[] modelMatrix = new float[16];
Matrix.setIdentityM(modelMatrix, 0);
GLU.gluUnProject(x, viewportHeight - y, 0.0f, modelMatrix, 0, mProjMatrix, 0, viewport, 0, r1, 0);
setPosition(r1[0] * eyeZ, r1[1] * -eyeZ, 0);
}
public float[] getModelMatrix() {
return mMMatrix;
}
public boolean isDoubleSided() {
return mDoubleSided;
}
public boolean isBackSided() {
return mBackSided;
}
public boolean isVisible() {
return mIsVisible;
}
public void setDoubleSided(boolean doubleSided) {
this.mDoubleSided = doubleSided;
}
public void setBackSided(boolean backSided) {
this.mBackSided = backSided;
}
public boolean isTransparent() {
return mTransparent;
}
/**
* Use this together with the alpha channel when calling BaseObject3D.setColor(): 0xaarrggbb. So for 50% transparent
* red, set transparent to true and call: * <code>setColor(0x7fff0000);</code>
*
* @param transparent
*/
public void setTransparent(boolean value) {
this.mTransparent = value;
mEnableBlending = value;
setBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
mEnableDepthMask = !value;
}
public void setLights(Stack<ALight> lights) {
mLights = lights;
for (int i = 0; i < mChildren.size(); ++i)
mChildren.get(i).setLights(lights);
if (mMaterial != null)
mMaterial.setLights(mLights);
}
/**
* Adds a light to this object.
*
* @param light
*/
public void addLight(ALight light) {
mLights.add(light);
for (int i = 0; i < mChildren.size(); ++i)
mChildren.get(i).setLights(mLights);
if (mMaterial != null)
mMaterial.setLights(mLights);
}
/**
* @deprecated Use addLight() instead
* @param light
*/
@Deprecated
public void setLight(ALight light) {
addLight(light);
}
/**
* @deprecated use getLight(int index) instead
* @return
*/
@Deprecated
public ALight getLight() {
return mLights.get(0);
}
public ALight getLight(int index) {
return mLights.get(index);
}
public int getDrawingMode() {
return mDrawingMode;
}
/**
* Sets the OpenGL drawing mode. GLES20.GL_TRIANGLES is the default. Other values can be GL_LINES, GL_LINE_LOOP,
* GL_LINE_LOOP, GL_TRIANGLE_FAN, GL_TRIANGLE_STRIP
*
*
* @param drawingMode
*/
public void setDrawingMode(int drawingMode) {
this.mDrawingMode = drawingMode;
}
/**
* Compares one object's depth to another object's depth
*/
public int compareTo(BaseObject3D another) {
if (mForcedDepth)
return -1;
if (mPosition.z < another.getZ())
return 1;
else if (mPosition.z > another.getZ())
return -1;
else
return 0;
}
public void addChild(BaseObject3D child) {
mChildren.add(child);
if (mRenderChildrenAsBatch)
child.setPartOfBatch(true);
}
public boolean removeChild(BaseObject3D child) {
return mChildren.remove(child);
}
public int getNumChildren() {
return mChildren.size();
}
public BaseObject3D getChildAt(int index) {
return mChildren.get(index);
}
public BaseObject3D getChildByName(String name) {
for (int i = 0, j = mChildren.size(); i < j; i++)
if (mChildren.get(i).getName().equals(name))
return mChildren.get(i);
return null;
}
public Geometry3D getGeometry() {
return mGeometry;
}
public void setMaterial(AMaterial material) {
setMaterial(material, true);
material.setLights(mLights);
}
public AMaterial getMaterial() {
return mMaterial;
}
public void setMaterial(AMaterial material, boolean copyTextures) {
if (mMaterial != null && copyTextures)
mMaterial.copyTexturesTo(material);
else if (mMaterial != null && !copyTextures)
mMaterial.getTextureInfoList().clear();
mMaterial = null;
mMaterial = material;
}
public void setName(String name) {
mName = name;
}
public String getName() {
return mName;
}
public boolean isForcedDepth() {
return mForcedDepth;
}
public void setForcedDepth(boolean forcedDepth) {
this.mForcedDepth = forcedDepth;
}
public ArrayList<TextureInfo> getTextureInfoList() {
ArrayList<TextureInfo> ti = mMaterial.getTextureInfoList();
for (int i = 0, j = mChildren.size(); i < j; i++)
ti.addAll(mChildren.get(i).getTextureInfoList());
return ti;
}
public SerializedObject3D toSerializedObject3D() {
SerializedObject3D ser = new SerializedObject3D(
mGeometry.getVertices() != null ? mGeometry.getVertices().capacity() : 0,
mGeometry.getNormals() != null ? mGeometry.getNormals().capacity() : 0,
mGeometry.getTextureCoords() != null ? mGeometry.getTextureCoords().capacity() : 0,
mGeometry.getColors() != null ? mGeometry.getColors().capacity() : 0,
mGeometry.getIndices() != null ? mGeometry.getIndices().capacity() : 0);
int i;
if (mGeometry.getVertices() != null)
for (i = 0; i < mGeometry.getVertices().capacity(); i++)
ser.getVertices()[i] = mGeometry.getVertices().get(i);
if (mGeometry.getNormals() != null)
for (i = 0; i < mGeometry.getNormals().capacity(); i++)
ser.getNormals()[i] = mGeometry.getNormals().get(i);
if (mGeometry.getTextureCoords() != null)
for (i = 0; i < mGeometry.getTextureCoords().capacity(); i++)
ser.getTextureCoords()[i] = mGeometry.getTextureCoords().get(i);
if (mGeometry.getColors() != null)
for (i = 0; i < mGeometry.getColors().capacity(); i++)
ser.getColors()[i] = mGeometry.getColors().get(i);
if (!mGeometry.areOnlyShortBuffersSupported()) {
IntBuffer buff = (IntBuffer) mGeometry.getIndices();
for (i = 0; i < mGeometry.getIndices().capacity(); i++)
ser.getIndices()[i] = buff.get(i);
} else {
ShortBuffer buff = (ShortBuffer) mGeometry.getIndices();
for (i = 0; i < mGeometry.getIndices().capacity(); i++)
ser.getIndices()[i] = buff.get(i);
}
return ser;
}
protected void cloneTo(BaseObject3D clone, boolean copyMaterial) {
clone.getGeometry().copyFromGeometry3D(mGeometry);
clone.isContainer(mIsContainerOnly);
if (copyMaterial)
clone.setMaterial(mMaterial, false);
clone.mElementsBufferType = mGeometry.areOnlyShortBuffersSupported() ? GLES20.GL_UNSIGNED_SHORT
: GLES20.GL_UNSIGNED_INT;
clone.mTransparent = this.mTransparent;
clone.mEnableBlending = this.mEnableBlending;
clone.mBlendFuncSFactor = this.mBlendFuncSFactor;
clone.mBlendFuncDFactor = this.mBlendFuncDFactor;
clone.mEnableDepthTest = this.mEnableDepthTest;
clone.mEnableDepthMask = this.mEnableDepthMask;
}
public BaseObject3D clone(boolean copyMaterial) {
BaseObject3D clone = new BaseObject3D();
cloneTo(clone, copyMaterial);
return clone;
}
public BaseObject3D clone() {
return clone(true);
}
public void setVisible(boolean visible) {
mIsVisible = visible;
}
public void setColor(int color) {
setColor(color, false);
}
public void setColor(int color, boolean createNewBuffer) {
mGeometry.setColor(Color.red(color) / 255f, Color.green(color) / 255f, Color.blue(color) / 255f,
Color.alpha(color) / 255f, createNewBuffer);
if (mMaterial != null) {
mMaterial.setUseColor(true);
}
}
public void setColor(Number3D color) {
setColor(Color.rgb((int) (color.x * 255), (int) (color.y * 255), (int) (color.z * 255)));
}
public int getPickingColor() {
return mPickingColor;
}
public void setPickingColor(int pickingColor) {
if (mPickingColorArray == null)
mPickingColorArray = new float[4];
this.mPickingColor = pickingColor;
mPickingColorArray[0] = Color.red(pickingColor) / 255f;
mPickingColorArray[1] = Color.green(pickingColor) / 255f;
mPickingColorArray[2] = Color.blue(pickingColor) / 255f;
mPickingColorArray[3] = Color.alpha(pickingColor) / 255f;
mIsPickingEnabled = true;
}
public void setShowBoundingVolume(boolean showBoundingVolume) {
this.mShowBoundingVolume = showBoundingVolume;
}
public float[] getRotationMatrix() {
return mRotateMatrix;
}
public void setFrustumTest(boolean value) {
mFrustumTest = value;
}
public void accept(INodeVisitor visitor) {
visitor.apply(this);
}
public boolean isInFrustum() {
return mIsInFrustum;
}
public boolean getRenderChildrenAsBatch()
{
return mRenderChildrenAsBatch;
}
public void setRenderChildrenAsBatch(boolean renderChildrenAsBatch)
{
this.mRenderChildrenAsBatch = renderChildrenAsBatch;
}
public boolean isPartOfBatch()
{
return mIsPartOfBatch;
}
public void setPartOfBatch(boolean isPartOfBatch)
{
this.mIsPartOfBatch = isPartOfBatch;
}
public boolean getManageMaterial()
{
return mManageMaterial;
}
public void setManageMaterial(boolean manageMaterial)
{
this.mManageMaterial = manageMaterial;
}
public void setBlendingEnabled(boolean value) {
mEnableBlending = value;
}
public boolean isBlendingEnabled() {
return mEnableBlending;
}
public void setBlendFunc(int sFactor, int dFactor) {
mBlendFuncSFactor = sFactor;
mBlendFuncDFactor = dFactor;
}
public void setDepthTestEnabled(boolean value) {
mEnableDepthTest = value;
}
public boolean isDepthTestEnabled() {
return mEnableDepthTest;
}
public void setDepthMaskEnabled(boolean value) {
mEnableDepthMask = value;
}
public boolean isDepthMaskEnabled() {
return mEnableDepthMask;
}
public void destroy() {
if (mLights != null)
mLights.clear();
if (mGeometry != null)
mGeometry.destroy();
if (mMaterial != null)
mMaterial.destroy();
mLights = null;
mMaterial = null;
mGeometry = null;
for (int i = 0, j = mChildren.size(); i < j; i++)
mChildren.get(i).destroy();
mChildren.clear();
}
}
| false | true | public void render(Camera camera, float[] projMatrix, float[] vMatrix, final float[] parentMatrix,
ColorPickerInfo pickerInfo) {
if (!mIsVisible)
return;
preRender();
// -- move view matrix transformation first
Matrix.setIdentityM(mMMatrix, 0);
Matrix.setIdentityM(mScalematrix, 0);
Matrix.scaleM(mScalematrix, 0, mScale.x, mScale.y, mScale.z);
Matrix.setIdentityM(mRotateMatrix, 0);
setOrientation();
if (mLookAt == null) {
mOrientation.toRotationMatrix(mRotateMatrix);
} else {
System.arraycopy(mLookAtMatrix, 0, mRotateMatrix, 0, 16);
}
Matrix.translateM(mMMatrix, 0, -mPosition.x, mPosition.y, mPosition.z);
Matrix.setIdentityM(mTmpMatrix, 0);
Matrix.multiplyMM(mTmpMatrix, 0, mMMatrix, 0, mScalematrix, 0);
Matrix.multiplyMM(mMMatrix, 0, mTmpMatrix, 0, mRotateMatrix, 0);
if (parentMatrix != null) {
Matrix.multiplyMM(mTmpMatrix, 0, parentMatrix, 0, mMMatrix, 0);
System.arraycopy(mTmpMatrix, 0, mMMatrix, 0, 16);
}
Matrix.multiplyMM(mMVPMatrix, 0, vMatrix, 0, mMMatrix, 0);
Matrix.multiplyMM(mMVPMatrix, 0, projMatrix, 0, mMVPMatrix, 0);
mIsInFrustum = true; // only if mFrustrumTest == true it check frustum
if (mFrustumTest && mGeometry.hasBoundingBox()) {
BoundingBox bbox = mGeometry.getBoundingBox();
bbox.transform(mMMatrix);
if (!camera.mFrustum.boundsInFrustum(bbox)) {
mIsInFrustum = false;
}
}
if (!mIsContainerOnly && mIsInFrustum) {
mProjMatrix = projMatrix;
if (!mDoubleSided) {
GLES20.glEnable(GLES20.GL_CULL_FACE);
if (mBackSided)
GLES20.glCullFace(GLES20.GL_FRONT);
else
GLES20.glCullFace(GLES20.GL_BACK);
}
if (mEnableBlending && !(pickerInfo != null && mIsPickingEnabled)) {
GLES20.glEnable(GLES20.GL_BLEND);
GLES20.glBlendFunc(mBlendFuncSFactor, mBlendFuncDFactor);
} else {
GLES20.glDisable(GLES20.GL_BLEND);
}
if (mEnableDepthTest)
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
else
GLES20.glDisable(GLES20.GL_DEPTH_TEST);
GLES20.glDepthMask(mEnableDepthMask);
if (pickerInfo != null && mIsPickingEnabled) {
ColorPickerMaterial pickerMat = pickerInfo.getPicker().getMaterial();
pickerMat.setPickingColor(mPickingColorArray);
pickerMat.useProgram();
pickerMat.setCamera(camera);
pickerMat.setVertices(mGeometry.getVertexBufferInfo().bufferHandle);
} else {
if (!mIsPartOfBatch) {
if (mMaterial == null) {
RajLog.e("[" + this.getClass().getName()
+ "] This object can't renderer because there's no material attached to it.");
throw new RuntimeException(
"This object can't renderer because there's no material attached to it.");
}
mMaterial.useProgram();
setShaderParams(camera);
mMaterial.bindTextures();
mMaterial.setTextureCoords(mGeometry.getTexCoordBufferInfo().bufferHandle, mHasCubemapTexture);
mMaterial.setNormals(mGeometry.getNormalBufferInfo().bufferHandle);
mMaterial.setCamera(camera);
mMaterial.setVertices(mGeometry.getVertexBufferInfo().bufferHandle);
}
if (mMaterial.getUseColor())
mMaterial.setColors(mGeometry.getColorBufferInfo().bufferHandle);
}
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
if (pickerInfo == null)
{
mMaterial.setMVPMatrix(mMVPMatrix);
mMaterial.setModelMatrix(mMMatrix);
mMaterial.setViewMatrix(vMatrix);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, mGeometry.getIndexBufferInfo().bufferHandle);
fix.android.opengl.GLES20.glDrawElements(mDrawingMode, mGeometry.getNumIndices(), mElementsBufferType,
0);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0);
if (!mIsPartOfBatch && !mRenderChildrenAsBatch) {
mMaterial.unbindTextures();
}
} else if (pickerInfo != null && mIsPickingEnabled) {
ColorPickerMaterial pickerMat = pickerInfo.getPicker().getMaterial();
pickerMat.setMVPMatrix(mMVPMatrix);
pickerMat.setModelMatrix(mMMatrix);
pickerMat.setViewMatrix(vMatrix);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, mGeometry.getIndexBufferInfo().bufferHandle);
fix.android.opengl.GLES20.glDrawElements(mDrawingMode, mGeometry.getNumIndices(), mElementsBufferType,
0);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0);
pickerMat.unbindTextures();
}
GLES20.glDisable(GLES20.GL_CULL_FACE);
GLES20.glDisable(GLES20.GL_BLEND);
GLES20.glDisable(GLES20.GL_DEPTH_TEST);
}
if (mShowBoundingVolume) {
if (mGeometry.hasBoundingBox())
mGeometry.getBoundingBox().drawBoundingVolume(camera, projMatrix, vMatrix, mMMatrix);
if (mGeometry.hasBoundingSphere())
mGeometry.getBoundingSphere().drawBoundingVolume(camera, projMatrix, vMatrix, mMMatrix);
}
// Draw children without frustum test
for (int i = 0, j = mChildren.size(); i < j; i++)
mChildren.get(i).render(camera, projMatrix, vMatrix, mMMatrix, pickerInfo);
if (mRenderChildrenAsBatch) {
mMaterial.unbindTextures();
}
}
| public void render(Camera camera, float[] projMatrix, float[] vMatrix, final float[] parentMatrix,
ColorPickerInfo pickerInfo) {
if (!mIsVisible)
return;
preRender();
// -- move view matrix transformation first
Matrix.setIdentityM(mMMatrix, 0);
Matrix.setIdentityM(mScalematrix, 0);
Matrix.scaleM(mScalematrix, 0, mScale.x, mScale.y, mScale.z);
Matrix.setIdentityM(mRotateMatrix, 0);
setOrientation();
if (mLookAt == null) {
mOrientation.toRotationMatrix(mRotateMatrix);
} else {
System.arraycopy(mLookAtMatrix, 0, mRotateMatrix, 0, 16);
}
Matrix.translateM(mMMatrix, 0, -mPosition.x, mPosition.y, mPosition.z);
Matrix.setIdentityM(mTmpMatrix, 0);
Matrix.multiplyMM(mTmpMatrix, 0, mMMatrix, 0, mScalematrix, 0);
Matrix.multiplyMM(mMMatrix, 0, mTmpMatrix, 0, mRotateMatrix, 0);
if (parentMatrix != null) {
Matrix.multiplyMM(mTmpMatrix, 0, parentMatrix, 0, mMMatrix, 0);
System.arraycopy(mTmpMatrix, 0, mMMatrix, 0, 16);
}
Matrix.multiplyMM(mMVPMatrix, 0, vMatrix, 0, mMMatrix, 0);
Matrix.multiplyMM(mMVPMatrix, 0, projMatrix, 0, mMVPMatrix, 0);
mIsInFrustum = true; // only if mFrustrumTest == true it check frustum
if (mFrustumTest && mGeometry.hasBoundingBox()) {
BoundingBox bbox = mGeometry.getBoundingBox();
bbox.transform(mMMatrix);
if (!camera.mFrustum.boundsInFrustum(bbox)) {
mIsInFrustum = false;
}
}
if (!mIsContainerOnly && mIsInFrustum) {
mProjMatrix = projMatrix;
if (!mDoubleSided) {
GLES20.glEnable(GLES20.GL_CULL_FACE);
if (mBackSided) {
GLES20.glCullFace(GLES20.GL_FRONT);
GLES20.glFrontFace(GLES20.GL_CW);
} else {
GLES20.glCullFace(GLES20.GL_BACK);
GLES20.glFrontFace(GLES20.GL_CCW);
}
}
if (mEnableBlending && !(pickerInfo != null && mIsPickingEnabled)) {
GLES20.glEnable(GLES20.GL_BLEND);
GLES20.glBlendFunc(mBlendFuncSFactor, mBlendFuncDFactor);
} else {
GLES20.glDisable(GLES20.GL_BLEND);
}
if (mEnableDepthTest)
GLES20.glEnable(GLES20.GL_DEPTH_TEST);
else
GLES20.glDisable(GLES20.GL_DEPTH_TEST);
GLES20.glDepthMask(mEnableDepthMask);
if (pickerInfo != null && mIsPickingEnabled) {
ColorPickerMaterial pickerMat = pickerInfo.getPicker().getMaterial();
pickerMat.setPickingColor(mPickingColorArray);
pickerMat.useProgram();
pickerMat.setCamera(camera);
pickerMat.setVertices(mGeometry.getVertexBufferInfo().bufferHandle);
} else {
if (!mIsPartOfBatch) {
if (mMaterial == null) {
RajLog.e("[" + this.getClass().getName()
+ "] This object can't renderer because there's no material attached to it.");
throw new RuntimeException(
"This object can't renderer because there's no material attached to it.");
}
mMaterial.useProgram();
setShaderParams(camera);
mMaterial.bindTextures();
mMaterial.setTextureCoords(mGeometry.getTexCoordBufferInfo().bufferHandle, mHasCubemapTexture);
mMaterial.setNormals(mGeometry.getNormalBufferInfo().bufferHandle);
mMaterial.setCamera(camera);
mMaterial.setVertices(mGeometry.getVertexBufferInfo().bufferHandle);
}
if (mMaterial.getUseColor())
mMaterial.setColors(mGeometry.getColorBufferInfo().bufferHandle);
}
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, 0);
if (pickerInfo == null)
{
mMaterial.setMVPMatrix(mMVPMatrix);
mMaterial.setModelMatrix(mMMatrix);
mMaterial.setViewMatrix(vMatrix);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, mGeometry.getIndexBufferInfo().bufferHandle);
fix.android.opengl.GLES20.glDrawElements(mDrawingMode, mGeometry.getNumIndices(), mElementsBufferType,
0);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0);
if (!mIsPartOfBatch && !mRenderChildrenAsBatch) {
mMaterial.unbindTextures();
}
} else if (pickerInfo != null && mIsPickingEnabled) {
ColorPickerMaterial pickerMat = pickerInfo.getPicker().getMaterial();
pickerMat.setMVPMatrix(mMVPMatrix);
pickerMat.setModelMatrix(mMMatrix);
pickerMat.setViewMatrix(vMatrix);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, mGeometry.getIndexBufferInfo().bufferHandle);
fix.android.opengl.GLES20.glDrawElements(mDrawingMode, mGeometry.getNumIndices(), mElementsBufferType,
0);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, 0);
pickerMat.unbindTextures();
}
GLES20.glDisable(GLES20.GL_CULL_FACE);
GLES20.glDisable(GLES20.GL_BLEND);
GLES20.glDisable(GLES20.GL_DEPTH_TEST);
}
if (mShowBoundingVolume) {
if (mGeometry.hasBoundingBox())
mGeometry.getBoundingBox().drawBoundingVolume(camera, projMatrix, vMatrix, mMMatrix);
if (mGeometry.hasBoundingSphere())
mGeometry.getBoundingSphere().drawBoundingVolume(camera, projMatrix, vMatrix, mMMatrix);
}
// Draw children without frustum test
for (int i = 0, j = mChildren.size(); i < j; i++)
mChildren.get(i).render(camera, projMatrix, vMatrix, mMMatrix, pickerInfo);
if (mRenderChildrenAsBatch) {
mMaterial.unbindTextures();
}
}
|
diff --git a/src/imp/model/SQLAudit.java b/src/imp/model/SQLAudit.java
index 9763a68..ff6f25f 100644
--- a/src/imp/model/SQLAudit.java
+++ b/src/imp/model/SQLAudit.java
@@ -1,113 +1,116 @@
/**
*
*/
package imp.model;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.SQLException;
import com.mysql.jdbc.Driver;
import imp.core.IPObject;
import imp.core.serverType;
/**
* @author Ransom Roberson
* @date 11.06.13
*/
public class SQLAudit {
private IPObject target;
private String JDBC_DRIVER;
private String DB_URL;
private String USER;
private String PASS;
private String PORT;
private serverType type;
/**
* This constructor will setup the sql scanning parameters
*
* @param target
* IPObject of target server
* @param type
* serverType enum to declare what kind of scan we're performing
*/
public SQLAudit(IPObject target, serverType type) {
Config cfg = new Config();
this.target = target;
this.type = type;
if (type == imp.core.serverType.MYSQL) {
USER = cfg.getProperty("mysql.user");
PASS = cfg.getProperty("mysql.pass");
PORT = cfg.getProperty("mysql.port");
JDBC_DRIVER = "com.mysql.jdbc.Driver";
DB_URL = "jdbc:mysql://" + target.toString() + ":" + PORT;
} else if (type == imp.core.serverType.MSSQL) {
USER = cfg.getProperty("mssql.user");
PASS = cfg.getProperty("mssql.pass");
PORT = cfg.getProperty("mssql.port");
JDBC_DRIVER = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
DB_URL = "jdbc:microsoft:sqlserver://" + target.toString() + ":" + PORT;
} else {
// Scan both
}
this.run();
}
/**
* Attempts to connect to the database
*/
private void run() {
try {
Class.forName(JDBC_DRIVER);
} catch (Exception e) {
System.out.println("Could not create JDBC driver");
e.printStackTrace();
return;
}
System.out.println("Starting connection...");
Connection con = null;
try {
DriverManager.setLoginTimeout(2);
con = DriverManager.getConnection(DB_URL, USER, PORT);
} catch (SQLException e) {
- System.out.println("Connection failed.");
- target.scanned = false;
- target.vulnderable = false;
- target.reachable = false;
+ if (e.getMessage().contains("is not allowed to connect to this"))
+ {
+ System.out.println("Connection failed. You do not have authorization from this host to access this server.");
+ target.scanned = true;
+ target.vulnderable = false;
+ target.reachable = true;
+ }
return;
}
if (con != null) {
System.out.println("Connection established.");
target.scanned = true;
target.vulnderable = false;
target.serverType = this.type;
target.reachable = true;
} else {
System.out.println("Connection failed.");
target.scanned = true;
target.vulnderable = false;
target.reachable = false;
return;
}
try {
con.close();
} catch (SQLException e) {
System.out.println("Couldn't close connection.");
}
}
public IPObject get() {
return target;
}
}
| true | true | private void run() {
try {
Class.forName(JDBC_DRIVER);
} catch (Exception e) {
System.out.println("Could not create JDBC driver");
e.printStackTrace();
return;
}
System.out.println("Starting connection...");
Connection con = null;
try {
DriverManager.setLoginTimeout(2);
con = DriverManager.getConnection(DB_URL, USER, PORT);
} catch (SQLException e) {
System.out.println("Connection failed.");
target.scanned = false;
target.vulnderable = false;
target.reachable = false;
return;
}
if (con != null) {
System.out.println("Connection established.");
target.scanned = true;
target.vulnderable = false;
target.serverType = this.type;
target.reachable = true;
} else {
System.out.println("Connection failed.");
target.scanned = true;
target.vulnderable = false;
target.reachable = false;
return;
}
try {
con.close();
} catch (SQLException e) {
System.out.println("Couldn't close connection.");
}
}
| private void run() {
try {
Class.forName(JDBC_DRIVER);
} catch (Exception e) {
System.out.println("Could not create JDBC driver");
e.printStackTrace();
return;
}
System.out.println("Starting connection...");
Connection con = null;
try {
DriverManager.setLoginTimeout(2);
con = DriverManager.getConnection(DB_URL, USER, PORT);
} catch (SQLException e) {
if (e.getMessage().contains("is not allowed to connect to this"))
{
System.out.println("Connection failed. You do not have authorization from this host to access this server.");
target.scanned = true;
target.vulnderable = false;
target.reachable = true;
}
return;
}
if (con != null) {
System.out.println("Connection established.");
target.scanned = true;
target.vulnderable = false;
target.serverType = this.type;
target.reachable = true;
} else {
System.out.println("Connection failed.");
target.scanned = true;
target.vulnderable = false;
target.reachable = false;
return;
}
try {
con.close();
} catch (SQLException e) {
System.out.println("Couldn't close connection.");
}
}
|
diff --git a/vufind/cron/src/org/epub/Reindex.java b/vufind/cron/src/org/epub/Reindex.java
index 3bff4c48..b47726e5 100644
--- a/vufind/cron/src/org/epub/Reindex.java
+++ b/vufind/cron/src/org/epub/Reindex.java
@@ -1,75 +1,75 @@
package org.epub;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import org.apache.log4j.Logger;
import org.ini4j.Ini;
import org.ini4j.Profile.Section;
import org.vufind.CronLogEntry;
import org.vufind.CronProcessLogEntry;
import org.vufind.IProcessHandler;
import org.vufind.Util;
public class Reindex implements IProcessHandler {
private String vufindUrl;
@Override
public void doCronProcess(String servername, Ini configIni, Section processSettings, Connection vufindConn, Connection econtentConn, CronLogEntry cronEntry, Logger logger) {
CronProcessLogEntry processLog = new CronProcessLogEntry(cronEntry.getLogEntryId(), "Reindex eContent");
processLog.saveToDatabase(vufindConn, logger);
logger.info("Reindexing eContent");
//Load configuration
if (!loadConfig(configIni, processSettings, logger)){
return;
}
try {
//TODO: Drop existing records from Solr index.
//Reindexing all records
- PreparedStatement eContentRecordStmt = econtentConn.prepareStatement("SELECT id from econtent_record");
+ PreparedStatement eContentRecordStmt = econtentConn.prepareStatement("SELECT id from econtent_record where status ='active' ");
ResultSet eContentRecordRS = eContentRecordStmt.executeQuery();
while (eContentRecordRS.next()){
long startTime = new Date().getTime();
String econtentRecordId = eContentRecordRS.getString("id");
try {
- URL updateIndexURL = new URL(vufindUrl + "/EcontentRecord/" + econtentRecordId + "/Reindex");
+ URL updateIndexURL = new URL(vufindUrl + "/EcontentRecord/" + econtentRecordId + "/Reindex?quick=true");
Object updateIndexDataRaw = updateIndexURL.getContent();
if (updateIndexDataRaw instanceof InputStream) {
String updateIndexResponse = Util.convertStreamToString((InputStream) updateIndexDataRaw);
long endTime = new Date().getTime();
logger.info("Indexing record " + econtentRecordId + " elapsed " + (endTime - startTime) + " response: " + updateIndexResponse);
processLog.incUpdated();
}
} catch (Exception e) {
logger.info("Unable to reindex record " + econtentRecordId, e);
}
}
processLog.setFinished();
processLog.saveToDatabase(vufindConn, logger);
} catch (SQLException ex) {
// handle any errors
logger.error("Error establishing connection to database ", ex);
return;
}
}
private boolean loadConfig(Ini configIni, Section processSettings, Logger logger) {
vufindUrl = configIni.get("Site", "url");
if (vufindUrl == null || vufindUrl.length() == 0) {
logger.error("Unable to get URL for VuFind in General settings. Please add a vufindUrl key.");
return false;
}
return true;
}
}
| false | true | public void doCronProcess(String servername, Ini configIni, Section processSettings, Connection vufindConn, Connection econtentConn, CronLogEntry cronEntry, Logger logger) {
CronProcessLogEntry processLog = new CronProcessLogEntry(cronEntry.getLogEntryId(), "Reindex eContent");
processLog.saveToDatabase(vufindConn, logger);
logger.info("Reindexing eContent");
//Load configuration
if (!loadConfig(configIni, processSettings, logger)){
return;
}
try {
//TODO: Drop existing records from Solr index.
//Reindexing all records
PreparedStatement eContentRecordStmt = econtentConn.prepareStatement("SELECT id from econtent_record");
ResultSet eContentRecordRS = eContentRecordStmt.executeQuery();
while (eContentRecordRS.next()){
long startTime = new Date().getTime();
String econtentRecordId = eContentRecordRS.getString("id");
try {
URL updateIndexURL = new URL(vufindUrl + "/EcontentRecord/" + econtentRecordId + "/Reindex");
Object updateIndexDataRaw = updateIndexURL.getContent();
if (updateIndexDataRaw instanceof InputStream) {
String updateIndexResponse = Util.convertStreamToString((InputStream) updateIndexDataRaw);
long endTime = new Date().getTime();
logger.info("Indexing record " + econtentRecordId + " elapsed " + (endTime - startTime) + " response: " + updateIndexResponse);
processLog.incUpdated();
}
} catch (Exception e) {
logger.info("Unable to reindex record " + econtentRecordId, e);
}
}
processLog.setFinished();
processLog.saveToDatabase(vufindConn, logger);
} catch (SQLException ex) {
// handle any errors
logger.error("Error establishing connection to database ", ex);
return;
}
}
| public void doCronProcess(String servername, Ini configIni, Section processSettings, Connection vufindConn, Connection econtentConn, CronLogEntry cronEntry, Logger logger) {
CronProcessLogEntry processLog = new CronProcessLogEntry(cronEntry.getLogEntryId(), "Reindex eContent");
processLog.saveToDatabase(vufindConn, logger);
logger.info("Reindexing eContent");
//Load configuration
if (!loadConfig(configIni, processSettings, logger)){
return;
}
try {
//TODO: Drop existing records from Solr index.
//Reindexing all records
PreparedStatement eContentRecordStmt = econtentConn.prepareStatement("SELECT id from econtent_record where status ='active' ");
ResultSet eContentRecordRS = eContentRecordStmt.executeQuery();
while (eContentRecordRS.next()){
long startTime = new Date().getTime();
String econtentRecordId = eContentRecordRS.getString("id");
try {
URL updateIndexURL = new URL(vufindUrl + "/EcontentRecord/" + econtentRecordId + "/Reindex?quick=true");
Object updateIndexDataRaw = updateIndexURL.getContent();
if (updateIndexDataRaw instanceof InputStream) {
String updateIndexResponse = Util.convertStreamToString((InputStream) updateIndexDataRaw);
long endTime = new Date().getTime();
logger.info("Indexing record " + econtentRecordId + " elapsed " + (endTime - startTime) + " response: " + updateIndexResponse);
processLog.incUpdated();
}
} catch (Exception e) {
logger.info("Unable to reindex record " + econtentRecordId, e);
}
}
processLog.setFinished();
processLog.saveToDatabase(vufindConn, logger);
} catch (SQLException ex) {
// handle any errors
logger.error("Error establishing connection to database ", ex);
return;
}
}
|
diff --git a/jar/src/main/java/org/mobicents/tools/sip/balancer/NodeRegisterImpl.java b/jar/src/main/java/org/mobicents/tools/sip/balancer/NodeRegisterImpl.java
index a082b6c..1c0ed11 100644
--- a/jar/src/main/java/org/mobicents/tools/sip/balancer/NodeRegisterImpl.java
+++ b/jar/src/main/java/org/mobicents/tools/sip/balancer/NodeRegisterImpl.java
@@ -1,417 +1,418 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.mobicents.tools.sip.balancer;
import java.net.InetAddress;
import java.rmi.AlreadyBoundException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* <p>
* This is the placeholder for maintening information about alive nodes and
* the relation between a Call-Id and its attributed node.
* </p>
*
* @author M. Ranganathan
* @author baranowb
* @author <A HREF="mailto:[email protected]">Jean Deruelle</A>
*
*/
public class NodeRegisterImpl implements NodeRegister {
private static Logger logger = Logger.getLogger(NodeRegisterImpl.class.getCanonicalName());
public static final int POINTER_START = 0;
private long nodeInfoExpirationTaskInterval = 5000;
private long nodeExpiration = 5100;
private Registry registry;
private Timer taskTimer = new Timer();
private TimerTask nodeExpirationTask = null;
private InetAddress serverAddress = null;
public NodeRegisterImpl(InetAddress serverAddress) throws RemoteException {
super();
this.serverAddress = serverAddress;
}
/**
* {@inheritDoc}
*/
public CopyOnWriteArrayList<SIPNode> getNodes() {
return BalancerContext.balancerContext.nodes;
}
/**
* {@inheritDoc}
*/
public boolean startRegistry(int rmiRegistryPort) {
if(logger.isLoggable(Level.INFO)) {
logger.info("Node registry starting...");
}
try {
BalancerContext.balancerContext.nodes = new CopyOnWriteArrayList<SIPNode>();;
BalancerContext.balancerContext.jvmRouteToSipNode = new ConcurrentHashMap<String, SIPNode>();
register(serverAddress, rmiRegistryPort);
this.nodeExpirationTask = new NodeExpirationTimerTask();
this.taskTimer.scheduleAtFixedRate(this.nodeExpirationTask,
this.nodeInfoExpirationTaskInterval,
this.nodeInfoExpirationTaskInterval);
if(logger.isLoggable(Level.INFO)) {
logger.info("Node expiration task created");
logger.info("Node registry started");
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Unexpected exception while starting the registry", e);
return false;
}
return true;
}
/**
* {@inheritDoc}
*/
public boolean stopRegistry() {
if(logger.isLoggable(Level.INFO)) {
logger.info("Stopping node registry...");
}
boolean isDeregistered = deregister(serverAddress);
boolean taskCancelled = nodeExpirationTask.cancel();
if(logger.isLoggable(Level.INFO)) {
logger.info("Node Expiration Task cancelled " + taskCancelled);
}
BalancerContext.balancerContext.nodes.clear();
BalancerContext.balancerContext.nodes = null;
if(logger.isLoggable(Level.INFO)) {
logger.info("Node registry stopped.");
}
return isDeregistered;
}
// ********* CLASS TO BE EXPOSED VIA RMI
private class RegisterRMIStub extends UnicastRemoteObject implements NodeRegisterRMIStub {
protected RegisterRMIStub() throws RemoteException {
super();
}
/*
* (non-Javadoc)
* @see org.mobicents.tools.sip.balancer.NodeRegisterRMIStub#handlePing(java.util.ArrayList)
*/
public void handlePing(ArrayList<SIPNode> ping) throws RemoteException {
handlePingInRegister(ping);
}
/*
* (non-Javadoc)
* @see org.mobicents.tools.sip.balancer.NodeRegisterRMIStub#forceRemoval(java.util.ArrayList)
*/
public void forceRemoval(ArrayList<SIPNode> ping)
throws RemoteException {
forceRemovalInRegister(ping);
}
public void switchover(String fromJvmRoute, String toJvmRoute) throws RemoteException {
jvmRouteSwitchover(fromJvmRoute, toJvmRoute);
}
}
// ***** SOME PRIVATE HELPERS
private void register(InetAddress serverAddress, int rmiRegistryPort) {
try {
registry = LocateRegistry.createRegistry(rmiRegistryPort);
registry.bind("SIPBalancer", new RegisterRMIStub());
} catch (RemoteException e) {
throw new RuntimeException("Failed to bind due to:", e);
} catch (AlreadyBoundException e) {
throw new RuntimeException("Failed to bind due to:", e);
}
}
private boolean deregister(InetAddress serverAddress) {
try {
registry.unbind("SIPBalancer");
return UnicastRemoteObject.unexportObject(registry, false);
} catch (RemoteException e) {
throw new RuntimeException("Failed to unbind due to", e);
} catch (NotBoundException e) {
throw new RuntimeException("Failed to unbind due to", e);
}
}
// ***** NODE MGMT METHODS
/**
* {@inheritDoc}
*/
public void unStickSessionFromNode(String callID) {
if(logger.isLoggable(Level.FINEST)) {
logger.finest("unsticked CallId " + callID + " from node " + null);
}
}
/**
* {@inheritDoc}
*/
public SIPNode stickSessionToNode(String callID, SIPNode sipNode) {
if(logger.isLoggable(Level.FINEST)) {
logger.finest("sticking CallId " + callID + " to node " + null);
}
return null;
}
/**
* {@inheritDoc}
*/
public SIPNode getGluedNode(String callID) {
if(logger.isLoggable(Level.FINEST)) {
logger.finest("glueued node " + null + " for CallId " + callID);
}
return null;
}
/**
* {@inheritDoc}
*/
public boolean isSIPNodePresent(String host, int port, String transport) {
if(getNode(host, port, transport) != null) {
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
public SIPNode getNode(String host, int port, String transport) {
for (SIPNode node : BalancerContext.balancerContext.nodes) {
if(logger.isLoggable(Level.FINEST)) {
logger.finest("node to check against " + node);
}
if(node.getIp().equals(host)) {
Integer nodePort = (Integer) node.getProperties().get(transport + "Port");
if(nodePort != null) {
if(nodePort == port) {
return node;
}
}
}
}
if(logger.isLoggable(Level.FINEST)) {
logger.finest("checking if the node is still alive for " + host + ":" + port + "/" + transport + " : false");
}
return null;
}
class NodeExpirationTimerTask extends TimerTask {
public void run() {
if(logger.isLoggable(Level.FINEST)) {
logger.finest("NodeExpirationTimerTask Running");
}
for (SIPNode node : BalancerContext.balancerContext.nodes) {
long expirationTime = node.getTimeStamp() + nodeExpiration;
if (expirationTime < System
.currentTimeMillis()) {
BalancerContext.balancerContext.nodes.remove(node);
BalancerContext.balancerContext.balancerAlgorithm.nodeRemoved(node);
if(logger.isLoggable(Level.INFO)) {
logger.info("NodeExpirationTimerTask Run NSync["
+ node + "] removed. Last timestamp: " + node.getTimeStamp() +
", current: " + System.currentTimeMillis()
+ " diff=" + ((double)System.currentTimeMillis()-node.getTimeStamp() ) +
"ms and tolerance=" + nodeExpiration + " ms");
}
} else {
if(logger.isLoggable(Level.FINEST)) {
logger.finest("node time stamp : " + expirationTime + " , current time : "
+ System.currentTimeMillis());
}
}
}
if(logger.isLoggable(Level.FINEST)) {
logger.finest("NodeExpirationTimerTask Done");
}
}
}
/**
* {@inheritDoc}
*/
public void handlePingInRegister(ArrayList<SIPNode> ping) {
for (SIPNode pingNode : ping) {
+ pingNode.updateTimerStamp();
if(pingNode.getProperties().get("jvmRoute") != null) {
// Let it leak, we will have 10-100 nodes, not a big deal if it leaks.
// We need info about inactive nodes to do the failover
BalancerContext.balancerContext.jvmRouteToSipNode.put(
(String)pingNode.getProperties().get("jvmRoute"), pingNode);
}
if(BalancerContext.balancerContext.nodes.size() < 1) {
BalancerContext.balancerContext.nodes.add(pingNode);
BalancerContext.balancerContext.balancerAlgorithm.nodeAdded(pingNode);
if(logger.isLoggable(Level.INFO)) {
logger.info("NodeExpirationTimerTask Run NSync["
+ pingNode + "] added");
}
return ;
}
SIPNode nodePresent = null;
Iterator<SIPNode> nodesIterator = BalancerContext.balancerContext.nodes.iterator();
while (nodesIterator.hasNext() && nodePresent == null) {
SIPNode node = (SIPNode) nodesIterator.next();
if (node.equals(pingNode)) {
nodePresent = node;
}
}
// adding done afterwards to avoid ConcurrentModificationException when adding the node while going through the iterator
if(nodePresent != null) {
nodePresent.updateTimerStamp();
if(logger.isLoggable(Level.FINE)) {
logger.fine("Ping " + nodePresent.getTimeStamp());
}
} else {
BalancerContext.balancerContext.nodes.add(pingNode);
BalancerContext.balancerContext.balancerAlgorithm.nodeAdded(pingNode);
pingNode.updateTimerStamp();
if(logger.isLoggable(Level.INFO)) {
logger.info("NodeExpirationTimerTask Run NSync["
+ pingNode + "] added");
}
}
}
}
/**
* {@inheritDoc}
*/
public void forceRemovalInRegister(ArrayList<SIPNode> ping) {
for (SIPNode pingNode : ping) {
if(BalancerContext.balancerContext.nodes.size() < 1) {
BalancerContext.balancerContext.nodes.remove(pingNode);
BalancerContext.balancerContext.balancerAlgorithm.nodeRemoved(pingNode);
if(logger.isLoggable(Level.INFO)) {
logger.info("NodeExpirationTimerTask Run NSync["
+ pingNode + "] forcibly removed due to a clean shutdown of a node");
}
return ;
}
boolean nodePresent = false;
Iterator<SIPNode> nodesIterator = BalancerContext.balancerContext.nodes.iterator();
while (nodesIterator.hasNext() && !nodePresent) {
SIPNode node = (SIPNode) nodesIterator.next();
if (node.equals(pingNode)) {
nodePresent = true;
}
}
// removal done afterwards to avoid ConcurrentModificationException when removing the node while goign through the iterator
if(nodePresent) {
BalancerContext.balancerContext.nodes.remove(pingNode);
BalancerContext.balancerContext.balancerAlgorithm.nodeRemoved(pingNode);
if(logger.isLoggable(Level.INFO)) {
logger.info("NodeExpirationTimerTask Run NSync["
+ pingNode + "] forcibly removed due to a clean shutdown of a node. Numbers of nodes present in the balancer : "
+ BalancerContext.balancerContext.nodes.size());
}
}
}
}
/**
* {@inheritDoc}
*/
public InetAddress getAddress() {
return this.serverAddress;
}
/**
* {@inheritDoc}
*/
public long getNodeExpiration() {
return this.nodeExpiration;
}
/**
* {@inheritDoc}
*/
public long getNodeExpirationTaskInterval() {
return this.nodeInfoExpirationTaskInterval;
}
/**
* {@inheritDoc}
*/
public void setNodeExpiration(long value) throws IllegalArgumentException {
if (value < 15)
throw new IllegalArgumentException("Value cant be less than 15");
this.nodeExpiration = value;
}
/**
* {@inheritDoc}
*/
public void setNodeExpirationTaskInterval(long value) {
if (value < 15)
throw new IllegalArgumentException("Value cant be less than 15");
this.nodeInfoExpirationTaskInterval = value;
}
public SIPNode[] getAllNodes() {
return BalancerContext.balancerContext.nodes.toArray(new SIPNode[]{});
}
public SIPNode getNextNode() throws IndexOutOfBoundsException {
// TODO Auto-generated method stub
return null;
}
public void jvmRouteSwitchover(String fromJvmRoute, String toJvmRoute) {
BalancerContext.balancerContext.balancerAlgorithm.jvmRouteSwitchover(fromJvmRoute, toJvmRoute);
}
}
| true | true | public void handlePingInRegister(ArrayList<SIPNode> ping) {
for (SIPNode pingNode : ping) {
if(pingNode.getProperties().get("jvmRoute") != null) {
// Let it leak, we will have 10-100 nodes, not a big deal if it leaks.
// We need info about inactive nodes to do the failover
BalancerContext.balancerContext.jvmRouteToSipNode.put(
(String)pingNode.getProperties().get("jvmRoute"), pingNode);
}
if(BalancerContext.balancerContext.nodes.size() < 1) {
BalancerContext.balancerContext.nodes.add(pingNode);
BalancerContext.balancerContext.balancerAlgorithm.nodeAdded(pingNode);
if(logger.isLoggable(Level.INFO)) {
logger.info("NodeExpirationTimerTask Run NSync["
+ pingNode + "] added");
}
return ;
}
SIPNode nodePresent = null;
Iterator<SIPNode> nodesIterator = BalancerContext.balancerContext.nodes.iterator();
while (nodesIterator.hasNext() && nodePresent == null) {
SIPNode node = (SIPNode) nodesIterator.next();
if (node.equals(pingNode)) {
nodePresent = node;
}
}
// adding done afterwards to avoid ConcurrentModificationException when adding the node while going through the iterator
if(nodePresent != null) {
nodePresent.updateTimerStamp();
if(logger.isLoggable(Level.FINE)) {
logger.fine("Ping " + nodePresent.getTimeStamp());
}
} else {
BalancerContext.balancerContext.nodes.add(pingNode);
BalancerContext.balancerContext.balancerAlgorithm.nodeAdded(pingNode);
pingNode.updateTimerStamp();
if(logger.isLoggable(Level.INFO)) {
logger.info("NodeExpirationTimerTask Run NSync["
+ pingNode + "] added");
}
}
}
}
| public void handlePingInRegister(ArrayList<SIPNode> ping) {
for (SIPNode pingNode : ping) {
pingNode.updateTimerStamp();
if(pingNode.getProperties().get("jvmRoute") != null) {
// Let it leak, we will have 10-100 nodes, not a big deal if it leaks.
// We need info about inactive nodes to do the failover
BalancerContext.balancerContext.jvmRouteToSipNode.put(
(String)pingNode.getProperties().get("jvmRoute"), pingNode);
}
if(BalancerContext.balancerContext.nodes.size() < 1) {
BalancerContext.balancerContext.nodes.add(pingNode);
BalancerContext.balancerContext.balancerAlgorithm.nodeAdded(pingNode);
if(logger.isLoggable(Level.INFO)) {
logger.info("NodeExpirationTimerTask Run NSync["
+ pingNode + "] added");
}
return ;
}
SIPNode nodePresent = null;
Iterator<SIPNode> nodesIterator = BalancerContext.balancerContext.nodes.iterator();
while (nodesIterator.hasNext() && nodePresent == null) {
SIPNode node = (SIPNode) nodesIterator.next();
if (node.equals(pingNode)) {
nodePresent = node;
}
}
// adding done afterwards to avoid ConcurrentModificationException when adding the node while going through the iterator
if(nodePresent != null) {
nodePresent.updateTimerStamp();
if(logger.isLoggable(Level.FINE)) {
logger.fine("Ping " + nodePresent.getTimeStamp());
}
} else {
BalancerContext.balancerContext.nodes.add(pingNode);
BalancerContext.balancerContext.balancerAlgorithm.nodeAdded(pingNode);
pingNode.updateTimerStamp();
if(logger.isLoggable(Level.INFO)) {
logger.info("NodeExpirationTimerTask Run NSync["
+ pingNode + "] added");
}
}
}
}
|
diff --git a/org.eclipse.mylyn.trac.tests/src/org/eclipse/mylyn/trac/tests/core/TracTaskDataHandlerXmlRpcTest.java b/org.eclipse.mylyn.trac.tests/src/org/eclipse/mylyn/trac/tests/core/TracTaskDataHandlerXmlRpcTest.java
index 7c7c8a8b4..45300a543 100644
--- a/org.eclipse.mylyn.trac.tests/src/org/eclipse/mylyn/trac/tests/core/TracTaskDataHandlerXmlRpcTest.java
+++ b/org.eclipse.mylyn.trac.tests/src/org/eclipse/mylyn/trac/tests/core/TracTaskDataHandlerXmlRpcTest.java
@@ -1,399 +1,407 @@
/*******************************************************************************
* Copyright (c) 2006, 2009 Steffen Pingel 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:
* Steffen Pingel - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.trac.tests.core;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import junit.framework.TestCase;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.mylyn.commons.net.AuthenticationCredentials;
import org.eclipse.mylyn.commons.net.AuthenticationType;
import org.eclipse.mylyn.internal.tasks.core.TaskTask;
import org.eclipse.mylyn.internal.tasks.core.data.TextTaskAttachmentSource;
import org.eclipse.mylyn.internal.tasks.core.sync.SynchronizationSession;
import org.eclipse.mylyn.internal.trac.core.TracAttribute;
import org.eclipse.mylyn.internal.trac.core.TracAttributeMapper;
import org.eclipse.mylyn.internal.trac.core.TracCorePlugin;
import org.eclipse.mylyn.internal.trac.core.TracRepositoryConnector;
import org.eclipse.mylyn.internal.trac.core.TracTaskDataHandler;
import org.eclipse.mylyn.internal.trac.core.TracTaskMapper;
import org.eclipse.mylyn.internal.trac.core.client.ITracClient;
import org.eclipse.mylyn.internal.trac.core.model.TracTicket;
import org.eclipse.mylyn.internal.trac.core.model.TracTicket.Key;
import org.eclipse.mylyn.internal.trac.core.util.TracUtil;
import org.eclipse.mylyn.tasks.core.ITask;
import org.eclipse.mylyn.tasks.core.ITaskAttachment;
import org.eclipse.mylyn.tasks.core.RepositoryStatus;
import org.eclipse.mylyn.tasks.core.TaskMapping;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.core.data.AbstractTaskAttachmentHandler;
import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
import org.eclipse.mylyn.tasks.core.data.TaskData;
import org.eclipse.mylyn.tasks.core.data.TaskMapper;
import org.eclipse.mylyn.tasks.core.data.TaskOperation;
import org.eclipse.mylyn.tasks.core.data.TaskRelation;
import org.eclipse.mylyn.tasks.ui.TasksUi;
import org.eclipse.mylyn.trac.tests.support.TracFixture;
import org.eclipse.mylyn.trac.tests.support.TracTestConstants;
import org.eclipse.mylyn.trac.tests.support.TracTestUtil;
import org.eclipse.mylyn.trac.tests.support.XmlRpcServer.TestData;
/**
* @author Steffen Pingel
*/
public class TracTaskDataHandlerXmlRpcTest extends TestCase {
private TracRepositoryConnector connector;
private TaskRepository repository;
private TestData data;
private TracTaskDataHandler taskDataHandler;
private ITracClient client;
public TracTaskDataHandlerXmlRpcTest() {
}
@Override
protected void setUp() throws Exception {
super.setUp();
data = TracFixture.init010();
connector = (TracRepositoryConnector) TasksUi.getRepositoryConnector(TracCorePlugin.CONNECTOR_KIND);
taskDataHandler = connector.getTaskDataHandler();
repository = TracFixture.current().singleRepository(connector);
client = connector.getClientManager().getTracClient(repository);
}
private SynchronizationSession createSession(ITask... tasks) {
SynchronizationSession session = new SynchronizationSession();
session.setNeedsPerformQueries(true);
session.setTaskRepository(repository);
session.setFullSynchronization(true);
session.setTasks(new HashSet<ITask>(Arrays.asList(tasks)));
return session;
}
public void testMarkStaleTasks() throws Exception {
SynchronizationSession session;
TracTicket ticket = TracTestUtil.createTicket(client, "markStaleTasks");
ITask task = TracTestUtil.createTask(repository, ticket.getId() + "");
long lastModified = TracUtil.toTracTime(task.getModificationDate());
// an empty set should not cause contact to the repository
repository.setSynchronizationTimeStamp(null);
session = createSession(task);
connector.preSynchronization(session, null);
assertTrue(session.needsPerformQueries());
assertNull(repository.getSynchronizationTimeStamp());
repository.setSynchronizationTimeStamp(null);
session = createSession(task);
connector.preSynchronization(session, null);
assertTrue(session.needsPerformQueries());
assertEquals(Collections.singleton(task), session.getStaleTasks());
// always returns the ticket because time comparison mode is >=
repository.setSynchronizationTimeStamp(lastModified + "");
session = createSession(task);
connector.preSynchronization(session, null);
// TODO this was fixed so it returns false now but only if the
// query returns a single task
assertFalse(session.needsPerformQueries());
assertEquals(Collections.emptySet(), session.getStaleTasks());
repository.setSynchronizationTimeStamp((lastModified + 1) + "");
session = createSession(task);
connector.preSynchronization(session, null);
assertFalse(session.needsPerformQueries());
assertEquals(Collections.emptySet(), session.getStaleTasks());
- // change ticket making sure it gets a new change time
- Thread.sleep(1500);
- ticket.putBuiltinValue(Key.DESCRIPTION, lastModified + "");
- client.updateTicket(ticket, "comment", null);
+ // try changing ticket 3x to make sure it gets a new change time
+ for (int i = 0; i < 3; i++) {
+ ticket.putBuiltinValue(Key.DESCRIPTION, lastModified + "");
+ client.updateTicket(ticket, "comment", null);
+ TracTicket updateTicket = client.getTicket(ticket.getId(), null);
+ if (updateTicket.getLastChanged().getTime() > lastModified) {
+ break;
+ } else if (i == 2) {
+ fail("Failed to update ticket modification time for ticket: " + ticket.getId());
+ }
+ Thread.sleep(1500);
+ }
repository.setSynchronizationTimeStamp((lastModified + 1) + "");
session = createSession(task);
connector.preSynchronization(session, null);
assertTrue(session.needsPerformQueries());
assertEquals(Collections.singleton(task), session.getStaleTasks());
}
public void testMarkStaleTasksNoTimeStamp() throws Exception {
SynchronizationSession session;
ITask task = TracTestUtil.createTask(repository, data.offlineHandlerTicketId + "");
session = createSession(task);
repository.setSynchronizationTimeStamp(null);
connector.preSynchronization(session, null);
assertTrue(session.needsPerformQueries());
assertEquals(Collections.singleton(task), session.getStaleTasks());
session = createSession(task);
repository.setSynchronizationTimeStamp("");
connector.preSynchronization(session, null);
assertTrue(session.needsPerformQueries());
assertEquals(Collections.singleton(task), session.getStaleTasks());
session = createSession(task);
repository.setSynchronizationTimeStamp("0");
connector.preSynchronization(session, null);
assertTrue(session.needsPerformQueries());
assertEquals(Collections.singleton(task), session.getStaleTasks());
session = createSession(task);
repository.setSynchronizationTimeStamp("abc");
connector.preSynchronization(session, null);
assertTrue(session.needsPerformQueries());
assertEquals(Collections.singleton(task), session.getStaleTasks());
}
public void testNonNumericTaskId() {
try {
connector.getTaskData(repository, "abc", null);
fail("Expected CoreException");
} catch (CoreException e) {
}
}
public void testAttachmentChangesLastModifiedDate() throws Exception {
AbstractTaskAttachmentHandler attachmentHandler = connector.getTaskAttachmentHandler();
ITask task = TracTestUtil.createTask(repository, data.attachmentTicketId + "");
Date lastModified = task.getModificationDate();
// XXX the test case fails when comment == null
attachmentHandler.postContent(repository, task, new TextTaskAttachmentSource("abc"), "comment", null, null);
task = TracTestUtil.createTask(repository, data.attachmentTicketId + "");
Date newLastModified = task.getModificationDate();
assertTrue("Expected " + newLastModified + " to be more recent than " + lastModified,
newLastModified.after(lastModified));
}
public void testAttachmentUrlEncoding() throws Exception {
AbstractTaskAttachmentHandler attachmentHandler = connector.getTaskAttachmentHandler();
TracTicket ticket = TracTestUtil.createTicket(client, "attachment url test");
ITask task = TracTestUtil.createTask(repository, ticket.getId() + "");
attachmentHandler.postContent(repository, task, new TextTaskAttachmentSource("abc") {
@Override
public String getName() {
return "https%3A%2F%2Fbugs.eclipse.org%2Fbugs.xml.zip";
}
}, "comment", null, null);
task = TracTestUtil.createTask(repository, ticket.getId() + "");
List<ITaskAttachment> attachments = TracTestUtil.getTaskAttachments(task);
assertEquals(1, attachments.size());
assertEquals(repository.getUrl() + "/attachment/ticket/" + ticket.getId()
+ "/https%253A%252F%252Fbugs.eclipse.org%252Fbugs.xml.zip", attachments.get(0).getUrl());
}
public void testPostTaskDataInvalidCredentials() throws Exception {
ITask task = TracTestUtil.createTask(repository, data.offlineHandlerTicketId + "");
TaskData taskData = TasksUi.getTaskDataManager().getTaskData(task);
taskData.getRoot().getMappedAttribute(TaskAttribute.COMMENT_NEW).setValue("new comment");
repository.setCredentials(AuthenticationType.REPOSITORY, new AuthenticationCredentials("foo", "bar"), false);
try {
taskDataHandler.postTaskData(repository, taskData, null, null);
} catch (CoreException expected) {
assertEquals(RepositoryStatus.ERROR_REPOSITORY_LOGIN, expected.getStatus().getCode());
}
assertEquals("new comment", taskData.getRoot().getMappedAttribute(TaskAttribute.COMMENT_NEW).getValue());
}
public void testCanInitializeTaskData() throws Exception {
ITask task = new TaskTask(TracCorePlugin.CONNECTOR_KIND, "", "");
assertFalse(taskDataHandler.canInitializeSubTaskData(repository, task));
task.setAttribute(TracRepositoryConnector.TASK_KEY_SUPPORTS_SUBTASKS, Boolean.TRUE.toString());
assertTrue(taskDataHandler.canInitializeSubTaskData(repository, task));
task = TracTestUtil.createTask(repository, data.offlineHandlerTicketId + "");
TaskData taskData = taskDataHandler.getTaskData(repository, data.offlineHandlerTicketId + "", null);
assertFalse(taskDataHandler.canInitializeSubTaskData(repository, task));
taskData.getRoot().createAttribute(TracTaskDataHandler.ATTRIBUTE_BLOCKED_BY);
connector.updateTaskFromTaskData(repository, task, taskData);
assertTrue(taskDataHandler.canInitializeSubTaskData(repository, task));
task.setAttribute(TracRepositoryConnector.TASK_KEY_SUPPORTS_SUBTASKS, Boolean.FALSE.toString());
connector.updateTaskFromTaskData(repository, task, taskData);
assertTrue(taskDataHandler.canInitializeSubTaskData(repository, task));
}
public void testInitializeSubTaskDataInvalidParent() throws Exception {
TaskData parentTaskData = taskDataHandler.getTaskData(repository, data.offlineHandlerTicketId + "",
new NullProgressMonitor());
try {
taskDataHandler.initializeSubTaskData(repository, parentTaskData, parentTaskData, null);
fail("expected CoreException");
} catch (CoreException expected) {
}
}
public void testInitializeSubTaskData() throws Exception {
TaskData parentTaskData = taskDataHandler.getTaskData(repository, data.offlineHandlerTicketId + "", null);
TaskMapper parentTaskMapper = new TracTaskMapper(parentTaskData, null);
parentTaskMapper.setSummary("abc");
parentTaskMapper.setDescription("def");
String component = parentTaskData.getRoot()
.getMappedAttribute(TracAttribute.COMPONENT.getTracKey())
.getOptions()
.get(0);
parentTaskMapper.setComponent(component);
parentTaskData.getRoot().createAttribute(TracTaskDataHandler.ATTRIBUTE_BLOCKED_BY);
TaskData subTaskData = new TaskData(parentTaskData.getAttributeMapper(), TracCorePlugin.CONNECTOR_KIND, "", "");
subTaskData.getRoot().createAttribute(TracTaskDataHandler.ATTRIBUTE_BLOCKING);
taskDataHandler.initializeSubTaskData(repository, subTaskData, parentTaskData, new NullProgressMonitor());
TaskMapper subTaskMapper = new TracTaskMapper(subTaskData, null);
assertEquals("", subTaskMapper.getSummary());
assertEquals("", subTaskMapper.getDescription());
assertEquals(component, subTaskMapper.getComponent());
TaskAttribute attribute = subTaskData.getRoot().getMappedAttribute(TracTaskDataHandler.ATTRIBUTE_BLOCKING);
assertEquals(parentTaskData.getTaskId(), attribute.getValue());
attribute = parentTaskData.getRoot().getMappedAttribute(TracTaskDataHandler.ATTRIBUTE_BLOCKED_BY);
assertEquals("", attribute.getValue());
}
public void testGetSubTaskIds() throws Exception {
TaskData taskData = new TaskData(new TracAttributeMapper(new TaskRepository("", ""), client),
TracCorePlugin.CONNECTOR_KIND, "", "");
TaskAttribute blockedBy = taskData.getRoot().createAttribute(TracTaskDataHandler.ATTRIBUTE_BLOCKED_BY);
Collection<String> subTaskIds;
blockedBy.setValue("123 456");
subTaskIds = getSubTaskIds(taskData);
assertEquals(2, subTaskIds.size());
assertTrue(subTaskIds.contains("123"));
assertTrue(subTaskIds.contains("456"));
blockedBy.setValue("7,8");
subTaskIds = getSubTaskIds(taskData);
assertEquals(2, subTaskIds.size());
assertTrue(subTaskIds.contains("7"));
assertTrue(subTaskIds.contains("8"));
blockedBy.setValue(" 7 , 8, ");
subTaskIds = getSubTaskIds(taskData);
assertEquals(2, subTaskIds.size());
assertTrue(subTaskIds.contains("7"));
assertTrue(subTaskIds.contains("8"));
blockedBy.setValue("7");
subTaskIds = getSubTaskIds(taskData);
assertEquals(1, subTaskIds.size());
assertTrue(subTaskIds.contains("7"));
blockedBy.setValue("");
subTaskIds = getSubTaskIds(taskData);
assertEquals(0, subTaskIds.size());
blockedBy.setValue(" ");
subTaskIds = getSubTaskIds(taskData);
assertEquals(0, subTaskIds.size());
}
private Collection<String> getSubTaskIds(TaskData taskData) {
List<String> subTaskIds = new ArrayList<String>();
Collection<TaskRelation> relations = connector.getTaskRelations(taskData);
for (TaskRelation taskRelation : relations) {
subTaskIds.add(taskRelation.getTaskId());
}
return subTaskIds;
}
public void testInitializeTaskData() throws Exception {
TaskData taskData = new TaskData(taskDataHandler.getAttributeMapper(repository), TracCorePlugin.CONNECTOR_KIND,
"", "");
TaskMapping mapping = new TaskMapping() {
@Override
public String getDescription() {
return "description";
}
@Override
public String getSummary() {
return "summary";
}
};
taskDataHandler.initializeTaskData(repository, taskData, mapping, new NullProgressMonitor());
// initializeTaskData() should ignore the initialization data
TaskMapper mapper = new TracTaskMapper(taskData, null);
assertEquals(null, mapper.getResolution());
assertEquals("", mapper.getSummary());
assertEquals("", mapper.getDescription());
// check for default values
assertEquals("Defect", mapper.getTaskKind());
assertEquals("major", mapper.getPriority());
// empty attributes should not exist
assertNull(taskData.getRoot().getAttribute(TracAttribute.SEVERITY.getTracKey()));
}
public void testOperations() throws Exception {
boolean hasReassign = TracTestConstants.TEST_TRAC_011_URL.equals(repository.getRepositoryUrl());
TaskData taskData = taskDataHandler.getTaskData(repository, "1", new NullProgressMonitor());
List<TaskAttribute> operations = taskData.getAttributeMapper().getAttributesByType(taskData,
TaskAttribute.TYPE_OPERATION);
assertEquals((hasReassign ? 5 : 4), operations.size());
TaskOperation operation = taskData.getAttributeMapper().getTaskOperation(operations.get(0));
assertEquals(TaskAttribute.OPERATION, operation.getTaskAttribute().getId());
operation = taskData.getAttributeMapper().getTaskOperation(operations.get(1));
assertEquals("leave", operation.getOperationId());
assertNotNull(operation.getLabel());
operation = taskData.getAttributeMapper().getTaskOperation(operations.get(2));
assertEquals("resolve", operation.getOperationId());
assertNotNull(operation.getLabel());
String associatedId = operation.getTaskAttribute().getMetaData().getValue(
TaskAttribute.META_ASSOCIATED_ATTRIBUTE_ID);
assertNotNull(associatedId);
if (hasReassign) {
operation = taskData.getAttributeMapper().getTaskOperation(operations.get(3));
assertEquals("reassign", operation.getOperationId());
assertNotNull(operation.getLabel());
operation = taskData.getAttributeMapper().getTaskOperation(operations.get(4));
assertEquals("accept", operation.getOperationId());
assertNotNull(operation.getLabel());
} else {
operation = taskData.getAttributeMapper().getTaskOperation(operations.get(3));
assertEquals("accept", operation.getOperationId());
assertNotNull(operation.getLabel());
}
}
public void testPostTaskDataUnsetResolution() throws Exception {
TracTicket ticket = TracTestUtil.createTicket(client, "postTaskDataUnsetResolution");
TaskData taskData = taskDataHandler.getTaskData(repository, ticket.getId() + "", new NullProgressMonitor());
TaskAttribute attribute = taskData.getRoot().getMappedAttribute(TaskAttribute.RESOLUTION);
attribute.setValue("fixed");
taskDataHandler.postTaskData(repository, taskData, null, new NullProgressMonitor());
// should not set resolution unless resolve operation is selected
taskData = taskDataHandler.getTaskData(repository, ticket.getId() + "", new NullProgressMonitor());
attribute = taskData.getRoot().getMappedAttribute(TaskAttribute.RESOLUTION);
assertEquals("", attribute.getValue());
}
}
| true | true | public void testMarkStaleTasks() throws Exception {
SynchronizationSession session;
TracTicket ticket = TracTestUtil.createTicket(client, "markStaleTasks");
ITask task = TracTestUtil.createTask(repository, ticket.getId() + "");
long lastModified = TracUtil.toTracTime(task.getModificationDate());
// an empty set should not cause contact to the repository
repository.setSynchronizationTimeStamp(null);
session = createSession(task);
connector.preSynchronization(session, null);
assertTrue(session.needsPerformQueries());
assertNull(repository.getSynchronizationTimeStamp());
repository.setSynchronizationTimeStamp(null);
session = createSession(task);
connector.preSynchronization(session, null);
assertTrue(session.needsPerformQueries());
assertEquals(Collections.singleton(task), session.getStaleTasks());
// always returns the ticket because time comparison mode is >=
repository.setSynchronizationTimeStamp(lastModified + "");
session = createSession(task);
connector.preSynchronization(session, null);
// TODO this was fixed so it returns false now but only if the
// query returns a single task
assertFalse(session.needsPerformQueries());
assertEquals(Collections.emptySet(), session.getStaleTasks());
repository.setSynchronizationTimeStamp((lastModified + 1) + "");
session = createSession(task);
connector.preSynchronization(session, null);
assertFalse(session.needsPerformQueries());
assertEquals(Collections.emptySet(), session.getStaleTasks());
// change ticket making sure it gets a new change time
Thread.sleep(1500);
ticket.putBuiltinValue(Key.DESCRIPTION, lastModified + "");
client.updateTicket(ticket, "comment", null);
repository.setSynchronizationTimeStamp((lastModified + 1) + "");
session = createSession(task);
connector.preSynchronization(session, null);
assertTrue(session.needsPerformQueries());
assertEquals(Collections.singleton(task), session.getStaleTasks());
}
| public void testMarkStaleTasks() throws Exception {
SynchronizationSession session;
TracTicket ticket = TracTestUtil.createTicket(client, "markStaleTasks");
ITask task = TracTestUtil.createTask(repository, ticket.getId() + "");
long lastModified = TracUtil.toTracTime(task.getModificationDate());
// an empty set should not cause contact to the repository
repository.setSynchronizationTimeStamp(null);
session = createSession(task);
connector.preSynchronization(session, null);
assertTrue(session.needsPerformQueries());
assertNull(repository.getSynchronizationTimeStamp());
repository.setSynchronizationTimeStamp(null);
session = createSession(task);
connector.preSynchronization(session, null);
assertTrue(session.needsPerformQueries());
assertEquals(Collections.singleton(task), session.getStaleTasks());
// always returns the ticket because time comparison mode is >=
repository.setSynchronizationTimeStamp(lastModified + "");
session = createSession(task);
connector.preSynchronization(session, null);
// TODO this was fixed so it returns false now but only if the
// query returns a single task
assertFalse(session.needsPerformQueries());
assertEquals(Collections.emptySet(), session.getStaleTasks());
repository.setSynchronizationTimeStamp((lastModified + 1) + "");
session = createSession(task);
connector.preSynchronization(session, null);
assertFalse(session.needsPerformQueries());
assertEquals(Collections.emptySet(), session.getStaleTasks());
// try changing ticket 3x to make sure it gets a new change time
for (int i = 0; i < 3; i++) {
ticket.putBuiltinValue(Key.DESCRIPTION, lastModified + "");
client.updateTicket(ticket, "comment", null);
TracTicket updateTicket = client.getTicket(ticket.getId(), null);
if (updateTicket.getLastChanged().getTime() > lastModified) {
break;
} else if (i == 2) {
fail("Failed to update ticket modification time for ticket: " + ticket.getId());
}
Thread.sleep(1500);
}
repository.setSynchronizationTimeStamp((lastModified + 1) + "");
session = createSession(task);
connector.preSynchronization(session, null);
assertTrue(session.needsPerformQueries());
assertEquals(Collections.singleton(task), session.getStaleTasks());
}
|
diff --git a/hazelcast/src/main/java/com/hazelcast/impl/concurrentmap/MapSystemLogFactory.java b/hazelcast/src/main/java/com/hazelcast/impl/concurrentmap/MapSystemLogFactory.java
index cb382a04..0ee0bc7e 100644
--- a/hazelcast/src/main/java/com/hazelcast/impl/concurrentmap/MapSystemLogFactory.java
+++ b/hazelcast/src/main/java/com/hazelcast/impl/concurrentmap/MapSystemLogFactory.java
@@ -1,136 +1,138 @@
/*
* Copyright (c) 2008-2012, Hazel Bilisim Ltd. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.impl.concurrentmap;
import com.hazelcast.core.Member;
import com.hazelcast.impl.*;
import com.hazelcast.impl.base.DistributedLock;
import com.hazelcast.impl.base.SystemLog;
import com.hazelcast.impl.partition.MigratingPartition;
import com.hazelcast.impl.partition.PartitionInfo;
import com.hazelcast.nio.Address;
import com.hazelcast.nio.Connection;
import com.hazelcast.nio.Data;
import java.util.HashSet;
import java.util.Set;
public class MapSystemLogFactory {
public static SystemLog newScheduleRequest(DistributedLock lock, int size) {
return new RequestScheduled(lock, size);
}
public static SystemLog newRedoLog(Node node, Request request) {
final Set<Member> members = new HashSet<Member>(node.getClusterImpl().getMembers());
final Data key = request.key;
final Address target = request.target;
PartitionInfo partitionInfo = null;
PartitionManager pm = node.concurrentMapManager.getPartitionManager();
if (key != null) {
partitionInfo = new PartitionInfo(pm.getPartition(node.concurrentMapManager.getPartitionId(key)));
}
boolean targetConnected = false;
if (target != null && node.getThisAddress().equals(target)) {
Connection targetConnection = node.connectionManager.getConnection(target);
targetConnected = (targetConnection != null && targetConnection.live());
}
return new RedoLog(key, request.operation, target, targetConnected,
members, partitionInfo, request.redoCount, pm.getMigratingPartition());
}
static class RedoLog extends SystemLog {
final Data key;
final ClusterOperation operation;
final Address target;
final boolean targetConnected;
final Set<Member> members;
final PartitionInfo partition;
final MigratingPartition migratingPartition;
final int redoCount;
RedoLog(Data key, ClusterOperation operation,
Address target,
boolean targetConnected,
Set<Member> members,
PartitionInfo partition,
int redoCount, MigratingPartition migratingPartition) {
this.key = key;
this.operation = operation;
this.target = target;
this.targetConnected = targetConnected;
this.members = members;
this.partition = partition;
this.redoCount = redoCount;
this.migratingPartition = migratingPartition;
}
private boolean contains(Address address) {
for (Member member : members) {
MemberImpl m = (MemberImpl) member;
if (m.getAddress().equals(address)) {
return true;
}
}
return false;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("RedoLog{");
sb.append("key=" + key +
", operation=" + operation +
", target=" + target +
", targetConnected=" + targetConnected +
", redoCount=" + redoCount +
", migrating=" + migratingPartition + "\n" +
"partition=" + partition +
"\n");
- for (int i = 0; i < PartitionInfo.MAX_REPLICA_COUNT; i++) {
- Address replicaAddress = partition.getReplicaAddress(i);
- if (replicaAddress != null && !contains(replicaAddress)) {
- sb.append(replicaAddress + " not a member!\n");
+ if (partition != null) {
+ for (int i = 0; i < PartitionInfo.MAX_REPLICA_COUNT; i++) {
+ Address replicaAddress = partition.getReplicaAddress(i);
+ if (replicaAddress != null && !contains(replicaAddress)) {
+ sb.append(replicaAddress + " not a member!\n");
+ }
}
}
sb.append("}");
return sb.toString();
}
}
static class RequestScheduled extends SystemLog {
private final DistributedLock lock;
private final int size;
public RequestScheduled(DistributedLock lock, int size) {
this.lock = lock;
this.size = size;
}
@Override
public String toString() {
DistributedLock l = lock;
StringBuilder sb = new StringBuilder("Scheduled[size=");
sb.append(size).append("]");
if (l != null) {
sb.append(" {");
sb.append(l.toString());
sb.append("}");
}
return sb.toString();
}
}
}
| true | true | public String toString() {
StringBuilder sb = new StringBuilder("RedoLog{");
sb.append("key=" + key +
", operation=" + operation +
", target=" + target +
", targetConnected=" + targetConnected +
", redoCount=" + redoCount +
", migrating=" + migratingPartition + "\n" +
"partition=" + partition +
"\n");
for (int i = 0; i < PartitionInfo.MAX_REPLICA_COUNT; i++) {
Address replicaAddress = partition.getReplicaAddress(i);
if (replicaAddress != null && !contains(replicaAddress)) {
sb.append(replicaAddress + " not a member!\n");
}
}
sb.append("}");
return sb.toString();
}
| public String toString() {
StringBuilder sb = new StringBuilder("RedoLog{");
sb.append("key=" + key +
", operation=" + operation +
", target=" + target +
", targetConnected=" + targetConnected +
", redoCount=" + redoCount +
", migrating=" + migratingPartition + "\n" +
"partition=" + partition +
"\n");
if (partition != null) {
for (int i = 0; i < PartitionInfo.MAX_REPLICA_COUNT; i++) {
Address replicaAddress = partition.getReplicaAddress(i);
if (replicaAddress != null && !contains(replicaAddress)) {
sb.append(replicaAddress + " not a member!\n");
}
}
}
sb.append("}");
return sb.toString();
}
|
diff --git a/course_manager_mobile/src/cz/kinst/jakub/coursemanager/AssignmentDetail.java b/course_manager_mobile/src/cz/kinst/jakub/coursemanager/AssignmentDetail.java
index 9eee8e1..83c3d82 100644
--- a/course_manager_mobile/src/cz/kinst/jakub/coursemanager/AssignmentDetail.java
+++ b/course_manager_mobile/src/cz/kinst/jakub/coursemanager/AssignmentDetail.java
@@ -1,114 +1,114 @@
package cz.kinst.jakub.coursemanager;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import cz.kinst.jakub.coursemanager.utils.Utils;
/**
* Activity showing detail of an assignment. Provides buttons for solving or
* correcting
*
* @author Jakub Kinst
*
*/
public class AssignmentDetail extends CMActivity {
/**
* UID for serialization
*/
private static final long serialVersionUID = -9168204116934753181L;
/**
* Assignment Id
*/
private int aid;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.aid = getIntent().getExtras().getInt("aid");
setContentView(R.layout.assignment_detail);
reload();
}
@Override
protected void onResume() {
reload();
super.onResume();
}
@Override
protected JSONObject reloadWork() throws JSONException {
ArrayList<NameValuePair> args = new ArrayList<NameValuePair>();
args.add(new BasicNameValuePair("aid", String.valueOf(this.aid)));
return courseManagerCon.getAction("assignment", "show", args,
new ArrayList<NameValuePair>());
}
@Override
public void gotData(JSONObject data) throws JSONException {
JSONObject assignment = data.getJSONObject("assignment");
TextView name = (TextView) findViewById(R.id.name);
TextView date = (TextView) findViewById(R.id.date);
JSONObject course = data.getJSONObject("activeCourse");
setTitle(course.getString("name") + " > "
+ getText(R.string.assignment));
TextView timelimit = (TextView) findViewById(R.id.timelimit);
TextView description = (TextView) findViewById(R.id.description);
int limit = assignment.getInt("timelimit");
timelimit.setText(getText(R.string.time_limit) + ": " + limit + " "
+ getText(R.string.minutes));
name.setText(assignment.getString("name"));
description.setText(assignment.getString("description"));
Date assignDate = Utils.getDateFromDBString(assignment
.getString("assigndate"));
Date dueDate = Utils.getDateFromDBString(assignment
.getString("duedate"));
DateFormat df = DateFormat.getInstance();
date.setText(df.format(assignDate) + " - " + df.format(dueDate));
Button solveButton = (Button) findViewById(R.id.solveButton);
- if (data.getBoolean("canSolve")) {
+ if (data.getBoolean("canSolve") && !data.getBoolean("isTeacher")) {
solveButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(AssignmentDetail.this,
AssignmentSolve.class).putExtra("cm",
courseManagerCon).putExtra("aid", aid));
}
});
} else {
solveButton.setVisibility(View.GONE);
}
Button correctButton = (Button) findViewById(R.id.correctButton);
if (data.getBoolean("isTeacher")
&& 1 != assignment.getInt("autocorrect")) {
correctButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(AssignmentDetail.this,
AssignmentCorrect.class).putExtra("cm",
courseManagerCon).putExtra("aid", aid));
}
});
} else {
correctButton.setVisibility(View.GONE);
}
}
}
| true | true | public void gotData(JSONObject data) throws JSONException {
JSONObject assignment = data.getJSONObject("assignment");
TextView name = (TextView) findViewById(R.id.name);
TextView date = (TextView) findViewById(R.id.date);
JSONObject course = data.getJSONObject("activeCourse");
setTitle(course.getString("name") + " > "
+ getText(R.string.assignment));
TextView timelimit = (TextView) findViewById(R.id.timelimit);
TextView description = (TextView) findViewById(R.id.description);
int limit = assignment.getInt("timelimit");
timelimit.setText(getText(R.string.time_limit) + ": " + limit + " "
+ getText(R.string.minutes));
name.setText(assignment.getString("name"));
description.setText(assignment.getString("description"));
Date assignDate = Utils.getDateFromDBString(assignment
.getString("assigndate"));
Date dueDate = Utils.getDateFromDBString(assignment
.getString("duedate"));
DateFormat df = DateFormat.getInstance();
date.setText(df.format(assignDate) + " - " + df.format(dueDate));
Button solveButton = (Button) findViewById(R.id.solveButton);
if (data.getBoolean("canSolve")) {
solveButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(AssignmentDetail.this,
AssignmentSolve.class).putExtra("cm",
courseManagerCon).putExtra("aid", aid));
}
});
} else {
solveButton.setVisibility(View.GONE);
}
Button correctButton = (Button) findViewById(R.id.correctButton);
if (data.getBoolean("isTeacher")
&& 1 != assignment.getInt("autocorrect")) {
correctButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(AssignmentDetail.this,
AssignmentCorrect.class).putExtra("cm",
courseManagerCon).putExtra("aid", aid));
}
});
} else {
correctButton.setVisibility(View.GONE);
}
}
| public void gotData(JSONObject data) throws JSONException {
JSONObject assignment = data.getJSONObject("assignment");
TextView name = (TextView) findViewById(R.id.name);
TextView date = (TextView) findViewById(R.id.date);
JSONObject course = data.getJSONObject("activeCourse");
setTitle(course.getString("name") + " > "
+ getText(R.string.assignment));
TextView timelimit = (TextView) findViewById(R.id.timelimit);
TextView description = (TextView) findViewById(R.id.description);
int limit = assignment.getInt("timelimit");
timelimit.setText(getText(R.string.time_limit) + ": " + limit + " "
+ getText(R.string.minutes));
name.setText(assignment.getString("name"));
description.setText(assignment.getString("description"));
Date assignDate = Utils.getDateFromDBString(assignment
.getString("assigndate"));
Date dueDate = Utils.getDateFromDBString(assignment
.getString("duedate"));
DateFormat df = DateFormat.getInstance();
date.setText(df.format(assignDate) + " - " + df.format(dueDate));
Button solveButton = (Button) findViewById(R.id.solveButton);
if (data.getBoolean("canSolve") && !data.getBoolean("isTeacher")) {
solveButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(AssignmentDetail.this,
AssignmentSolve.class).putExtra("cm",
courseManagerCon).putExtra("aid", aid));
}
});
} else {
solveButton.setVisibility(View.GONE);
}
Button correctButton = (Button) findViewById(R.id.correctButton);
if (data.getBoolean("isTeacher")
&& 1 != assignment.getInt("autocorrect")) {
correctButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(AssignmentDetail.this,
AssignmentCorrect.class).putExtra("cm",
courseManagerCon).putExtra("aid", aid));
}
});
} else {
correctButton.setVisibility(View.GONE);
}
}
|
diff --git a/Model/src/java/fr/cg95/cvq/dao/request/xml/LocalReferentialDAO.java b/Model/src/java/fr/cg95/cvq/dao/request/xml/LocalReferentialDAO.java
index 0941c2c1a..cf99f4ad2 100644
--- a/Model/src/java/fr/cg95/cvq/dao/request/xml/LocalReferentialDAO.java
+++ b/Model/src/java/fr/cg95/cvq/dao/request/xml/LocalReferentialDAO.java
@@ -1,149 +1,151 @@
package fr.cg95.cvq.dao.request.xml;
import fr.cg95.cvq.business.authority.LocalAuthorityResource.Type;
import fr.cg95.cvq.business.request.LocalReferentialType;
import fr.cg95.cvq.dao.request.ILocalReferentialDAO;
import fr.cg95.cvq.exception.CvqException;
import fr.cg95.cvq.service.authority.ILocalAuthorityRegistry;
import fr.cg95.cvq.service.request.IRequestServiceRegistry;
import fr.cg95.cvq.service.request.LocalReferential;
import fr.cg95.cvq.util.translation.ITranslationService;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.WordUtils;
import org.apache.log4j.Logger;
/**
* Implementation of ILocalReferentialDAO using XML files.
* @author julien
*/
public class LocalReferentialDAO implements ILocalReferentialDAO {
private IRequestServiceRegistry requestServiceRegistry;
private ILocalAuthorityRegistry localAuthorityRegistry;
private ITranslationService translationService;
private static Logger logger = Logger.getLogger(LocalReferentialDAO.class);
public void setLocalAuthorityRegistry(ILocalAuthorityRegistry localAuthorityRegistry) {
this.localAuthorityRegistry = localAuthorityRegistry;
}
public void setRequestServiceRegistry(IRequestServiceRegistry requestServiceRegistry) {
this.requestServiceRegistry = requestServiceRegistry;
}
public void setTranslationService(ITranslationService translationService) {
this.translationService = translationService;
}
@Override
public Set<LocalReferentialType> listByRequestType(final String requestTypeLabel) {
File file = getOrCreateLocalReferentialFile(requestTypeLabel);
if (file == null) {
return null;
}
try {
return LocalReferentialXml.xmlToModel(file);
} catch (CvqException e) {
return null;
}
}
@Override
public LocalReferentialType getByRequestTypeAndName(final String requestTypeLabel, final String typeName) {
final Set<LocalReferentialType> lrts = listByRequestType(requestTypeLabel);
if (lrts == null) {
return null;
}
for (final LocalReferentialType lrt : lrts) {
if (lrt.getName().equals(typeName)) {
return lrt;
}
}
return null;
}
@Override
public void save(final String requestTypeLabel, final LocalReferentialType lrt) throws CvqException {
File file = getOrCreateLocalReferentialFile(requestTypeLabel);
if (file != null) {
LocalReferentialXml.modelToXml(lrt, file);
}
}
/**
* @param requestTypeLabel
* @return The file containing the local refererential for the given request type, or null if it’s does not have one
*/
private File getOrCreateLocalReferentialFile(final String requestTypeLabel) {
final String fileName = requestServiceRegistry.getRequestService(requestTypeLabel).getLocalReferentialFilename();
+ if (fileName == null)
+ return null;
final File file = getLocalReferentialFile(fileName);
if (file != null && file.exists()) {
return file;
} else {
logger.debug("No local referential file found, creating an empty one.");
if (!file.exists())
try {
file.createNewFile();
} catch (IOException e) {
logger.error("Failed to create the new local referential " + file.getName());
return null;
}
final Set<LocalReferentialType> lrts = generateEmptyLocalReferential(requestTypeLabel);
if (!lrts.isEmpty()) {
try {
LocalReferentialXml.modelToXml(lrts, file);
logger.debug("Local referential skeleton saved in file: "+ file.getAbsolutePath());
return file;
} catch (CvqException ex) {
logger.error("Failed to save the generated local referential");
}
}
logger.debug("No local referential for this request type");
return null;
}
}
/**
* @param requestTypeLabel
* @return The File associated to the given requestTypeLabel, or null if this request type does not have a local referential
*/
private File getLocalReferentialFile(final String fileName) {
if (fileName != null) {
return localAuthorityRegistry.getLocalAuthorityResourceFile(Type.LOCAL_REFERENTIAL, fileName, false);
}
return null;
}
private Set<LocalReferentialType> generateEmptyLocalReferential(String requestTypeLabel) {
final Set<LocalReferentialType> lrts = new LinkedHashSet<LocalReferentialType>();
try {
final Class<?> clazz = requestServiceRegistry.getRequestService(requestTypeLabel).getSkeletonRequest()
.getSpecificData().getClass();
final String prefix = translationService.generateInitialism(requestTypeLabel);
for (Field field : clazz.getDeclaredFields()) {
// logger.debug("inspecting field " + field.getName());
// HACK Due to Java’s type erasure we can’t retrieve local referentials fields (type List<LocalReferentialData>)
// So we look for fields of type List<?> annotated with the validation annotation @LocalReferential
if (field.getType().isAssignableFrom(List.class) && field.getAnnotation(LocalReferential.class) != null) {
// logger.debug("LocalReferentialFound: " + field.getName());
final LocalReferentialType lrt;
lrt = new LocalReferentialType();
lrt.setName(WordUtils.capitalize(field.getName()));
lrt.setLabel(translationService.translate(prefix+".property."+field.getName()+".label"));
lrts.add(lrt);
}
}
} catch (CvqException ex) {
}
return lrts;
}
}
| true | true | private File getOrCreateLocalReferentialFile(final String requestTypeLabel) {
final String fileName = requestServiceRegistry.getRequestService(requestTypeLabel).getLocalReferentialFilename();
final File file = getLocalReferentialFile(fileName);
if (file != null && file.exists()) {
return file;
} else {
logger.debug("No local referential file found, creating an empty one.");
if (!file.exists())
try {
file.createNewFile();
} catch (IOException e) {
logger.error("Failed to create the new local referential " + file.getName());
return null;
}
final Set<LocalReferentialType> lrts = generateEmptyLocalReferential(requestTypeLabel);
if (!lrts.isEmpty()) {
try {
LocalReferentialXml.modelToXml(lrts, file);
logger.debug("Local referential skeleton saved in file: "+ file.getAbsolutePath());
return file;
} catch (CvqException ex) {
logger.error("Failed to save the generated local referential");
}
}
logger.debug("No local referential for this request type");
return null;
}
}
| private File getOrCreateLocalReferentialFile(final String requestTypeLabel) {
final String fileName = requestServiceRegistry.getRequestService(requestTypeLabel).getLocalReferentialFilename();
if (fileName == null)
return null;
final File file = getLocalReferentialFile(fileName);
if (file != null && file.exists()) {
return file;
} else {
logger.debug("No local referential file found, creating an empty one.");
if (!file.exists())
try {
file.createNewFile();
} catch (IOException e) {
logger.error("Failed to create the new local referential " + file.getName());
return null;
}
final Set<LocalReferentialType> lrts = generateEmptyLocalReferential(requestTypeLabel);
if (!lrts.isEmpty()) {
try {
LocalReferentialXml.modelToXml(lrts, file);
logger.debug("Local referential skeleton saved in file: "+ file.getAbsolutePath());
return file;
} catch (CvqException ex) {
logger.error("Failed to save the generated local referential");
}
}
logger.debug("No local referential for this request type");
return null;
}
}
|
diff --git a/org.emftext.runtime.ui/src/org/emftext/runtime/ui/EMFTextEditorCompletionProcessor.java b/org.emftext.runtime.ui/src/org/emftext/runtime/ui/EMFTextEditorCompletionProcessor.java
index 505ee54d8..e630d8857 100644
--- a/org.emftext.runtime.ui/src/org/emftext/runtime/ui/EMFTextEditorCompletionProcessor.java
+++ b/org.emftext.runtime.ui/src/org/emftext/runtime/ui/EMFTextEditorCompletionProcessor.java
@@ -1,193 +1,196 @@
package org.emftext.runtime.ui;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.contentassist.CompletionProposal;
import org.eclipse.jface.text.contentassist.ContextInformation;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.text.contentassist.IContextInformationValidator;
import org.emftext.runtime.resource.ILocationMap;
import org.emftext.runtime.resource.IReferenceMapping;
import org.emftext.runtime.resource.IReferenceResolverSwitch;
import org.emftext.runtime.resource.IResolveResult;
import org.emftext.runtime.resource.ITextResource;
import org.emftext.runtime.resource.impl.ResolveResult;
import org.emftext.runtime.ui.editor.EMFTextEditor;
public class EMFTextEditorCompletionProcessor implements
IContentAssistProcessor {
private static final ICompletionProposal[] EMPTY_PROPOSAL_ARRAY = new ICompletionProposal[0];
private EMFTextEditor editor;
public EMFTextEditorCompletionProcessor(EMFTextEditor editor) {
this.editor = editor;
}
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
int documentOffset) {
long startTime = System.currentTimeMillis();
Resource resource = editor.getResource();
ITextResource textResource = (ITextResource) resource;
ILocationMap locationMap = textResource.getLocationMap();
EList<EObject> contents = resource.getContents();
if (contents == null) {
return EMPTY_PROPOSAL_ARRAY;
}
+ if (contents.size() == 0) {
+ return EMPTY_PROPOSAL_ARRAY;
+ }
List<EObject> elementsAtChar = locationMap.getElementsAt(contents.get(0), documentOffset);
sortElements(elementsAtChar);
if (elementsAtChar.size() < 2) {
return EMPTY_PROPOSAL_ARRAY;
}
EObject elementAtChar = elementsAtChar.get(0);
EObject containerAtChar = elementsAtChar.get(1);
int start = locationMap.getCharStart(elementAtChar);
// figure out prefix (is between start and documentOffset)
String prefix;
try {
prefix = viewer.getDocument().get(start, documentOffset - start);
} catch (BadLocationException e) {
e.printStackTrace();
return EMPTY_PROPOSAL_ARRAY;
}
//TODO @mseifert: the prefix somehow has to go through the appropriate token resolver,
// otherwise we have different kind of identifiers in the reference resolvers
IReferenceResolverSwitch resolverSwitch = textResource.getReferenceResolverSwitch();
IResolveResult resolved = new ResolveResult(true);
resolverSwitch.resolve(prefix, containerAtChar, null, 0, true, resolved);
if (!resolved.wasResolvedMultiple()) {
return EMPTY_PROPOSAL_ARRAY;
}
List<IReferenceMapping> mappings = new ArrayList<IReferenceMapping>(resolved.getMappings());
// sort identifiers alphabetically
sortAlphabetically(mappings);
removeDuplicates(mappings);
ICompletionProposal[] proposals = createProposals(documentOffset, prefix,
mappings);
System.out.println("computeCompletionProposals() took " + (System.currentTimeMillis() - startTime) + "ms");
return proposals;
}
private void removeDuplicates(List<IReferenceMapping> mappings) {
for (int i = 0; i < mappings.size(); i++) {
IReferenceMapping mapping_i = mappings.get(i);
String identifier_i = mapping_i.getIdentifier();
for (int j = i + 1; j < mappings.size(); j++) {
IReferenceMapping mapping_j = mappings.get(j);
String identifier_j = mapping_j.getIdentifier();
if (identifier_i != null && identifier_i.equals(identifier_j)) {
mappings.remove(j);
j--;
}
}
}
}
private ICompletionProposal[] createProposals(int documentOffset,
String prefix, Collection<IReferenceMapping> mappings) {
ICompletionProposal[] result = new ICompletionProposal[mappings.size()];
int i = 0;
for (IReferenceMapping next : mappings) {
String proposal = next.getIdentifier();
assert proposal != null;
IContextInformation info = new ContextInformation(proposal,
proposal);
String insertString = proposal.substring(prefix.length());
result[i++] = new CompletionProposal(insertString, documentOffset,
0, insertString.length(), null, proposal, info,
proposal);
}
return result;
}
private void sortAlphabetically(List<IReferenceMapping> mappings) {
Collections.sort(mappings, new Comparator<IReferenceMapping>() {
public int compare(IReferenceMapping o1, IReferenceMapping o2) {
return o1.getIdentifier().compareTo(o2.getIdentifier());
}
});
}
private void sortElements(List<EObject> elementsAtChar) {
shiftProxiesToHead(elementsAtChar);
shiftContainersToEnd(elementsAtChar);
}
private void shiftProxiesToHead(List<EObject> elementsAtChar) {
// shift the proxy elements to the head of the list
Collections.sort(elementsAtChar, new Comparator<EObject>() {
public int compare(EObject objectA, EObject objectB) {
boolean aIsProxy = objectA.eIsProxy();
boolean bIsProxy = objectB.eIsProxy();
return aIsProxy == bIsProxy ? 0 : (aIsProxy ? -1 : 1);
}
});
}
private void shiftContainersToEnd(List<EObject> elementsAtChar) {
// shift the containers to the end of the list
Collections.sort(elementsAtChar, new Comparator<EObject>() {
public int compare(EObject objectA, EObject objectB) {
boolean aContainsB = contains(objectA, objectB);
boolean bContainsA = contains(objectB, objectA);
if (!aContainsB && !bContainsA) {
return 0;
}
if (aContainsB) {
return 1;
}
if (bContainsA) {
return -1;
}
return 0;
}
private boolean contains(EObject objectA, EObject objectB) {
TreeIterator<EObject> it = objectA.eAllContents();
while (it.hasNext()) {
if (it.next() == objectB) {
return true;
}
}
return false;
}
});
}
public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) {
return new IContextInformation[0];
}
public char[] getCompletionProposalAutoActivationCharacters() {
return null;
}
public char[] getContextInformationAutoActivationCharacters() {
return null;
}
public IContextInformationValidator getContextInformationValidator() {
return null;
}
public String getErrorMessage() {
return null;
}
}
| true | true | public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
int documentOffset) {
long startTime = System.currentTimeMillis();
Resource resource = editor.getResource();
ITextResource textResource = (ITextResource) resource;
ILocationMap locationMap = textResource.getLocationMap();
EList<EObject> contents = resource.getContents();
if (contents == null) {
return EMPTY_PROPOSAL_ARRAY;
}
List<EObject> elementsAtChar = locationMap.getElementsAt(contents.get(0), documentOffset);
sortElements(elementsAtChar);
if (elementsAtChar.size() < 2) {
return EMPTY_PROPOSAL_ARRAY;
}
EObject elementAtChar = elementsAtChar.get(0);
EObject containerAtChar = elementsAtChar.get(1);
int start = locationMap.getCharStart(elementAtChar);
// figure out prefix (is between start and documentOffset)
String prefix;
try {
prefix = viewer.getDocument().get(start, documentOffset - start);
} catch (BadLocationException e) {
e.printStackTrace();
return EMPTY_PROPOSAL_ARRAY;
}
//TODO @mseifert: the prefix somehow has to go through the appropriate token resolver,
// otherwise we have different kind of identifiers in the reference resolvers
IReferenceResolverSwitch resolverSwitch = textResource.getReferenceResolverSwitch();
IResolveResult resolved = new ResolveResult(true);
resolverSwitch.resolve(prefix, containerAtChar, null, 0, true, resolved);
if (!resolved.wasResolvedMultiple()) {
return EMPTY_PROPOSAL_ARRAY;
}
List<IReferenceMapping> mappings = new ArrayList<IReferenceMapping>(resolved.getMappings());
// sort identifiers alphabetically
sortAlphabetically(mappings);
removeDuplicates(mappings);
ICompletionProposal[] proposals = createProposals(documentOffset, prefix,
mappings);
System.out.println("computeCompletionProposals() took " + (System.currentTimeMillis() - startTime) + "ms");
return proposals;
}
| public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer,
int documentOffset) {
long startTime = System.currentTimeMillis();
Resource resource = editor.getResource();
ITextResource textResource = (ITextResource) resource;
ILocationMap locationMap = textResource.getLocationMap();
EList<EObject> contents = resource.getContents();
if (contents == null) {
return EMPTY_PROPOSAL_ARRAY;
}
if (contents.size() == 0) {
return EMPTY_PROPOSAL_ARRAY;
}
List<EObject> elementsAtChar = locationMap.getElementsAt(contents.get(0), documentOffset);
sortElements(elementsAtChar);
if (elementsAtChar.size() < 2) {
return EMPTY_PROPOSAL_ARRAY;
}
EObject elementAtChar = elementsAtChar.get(0);
EObject containerAtChar = elementsAtChar.get(1);
int start = locationMap.getCharStart(elementAtChar);
// figure out prefix (is between start and documentOffset)
String prefix;
try {
prefix = viewer.getDocument().get(start, documentOffset - start);
} catch (BadLocationException e) {
e.printStackTrace();
return EMPTY_PROPOSAL_ARRAY;
}
//TODO @mseifert: the prefix somehow has to go through the appropriate token resolver,
// otherwise we have different kind of identifiers in the reference resolvers
IReferenceResolverSwitch resolverSwitch = textResource.getReferenceResolverSwitch();
IResolveResult resolved = new ResolveResult(true);
resolverSwitch.resolve(prefix, containerAtChar, null, 0, true, resolved);
if (!resolved.wasResolvedMultiple()) {
return EMPTY_PROPOSAL_ARRAY;
}
List<IReferenceMapping> mappings = new ArrayList<IReferenceMapping>(resolved.getMappings());
// sort identifiers alphabetically
sortAlphabetically(mappings);
removeDuplicates(mappings);
ICompletionProposal[] proposals = createProposals(documentOffset, prefix,
mappings);
System.out.println("computeCompletionProposals() took " + (System.currentTimeMillis() - startTime) + "ms");
return proposals;
}
|
diff --git a/piratebay-downloader-gui/src/main/java/com/ags/pirate/PirateGui.java b/piratebay-downloader-gui/src/main/java/com/ags/pirate/PirateGui.java
index a3543e4..1bbf1dd 100644
--- a/piratebay-downloader-gui/src/main/java/com/ags/pirate/PirateGui.java
+++ b/piratebay-downloader-gui/src/main/java/com/ags/pirate/PirateGui.java
@@ -1,139 +1,140 @@
package com.ags.pirate;
import com.ags.pirate.common.configuration.Configuration;
import com.ags.pirate.common.model.Serie;
import com.ags.pirate.common.model.Torrent;
import com.ags.pirate.gui.event.SerieSelectedEvent;
import com.ags.pirate.gui.event.TorrentFoundEvent;
import com.ags.pirate.gui.fal.ColorProvider;
import com.ags.pirate.gui.info.InfoView;
import com.ags.pirate.gui.listener.SerieSelectedListener;
import com.ags.pirate.gui.listener.TorrentFoundListener;
import com.ags.pirate.gui.serie.SeriesView;
import com.ags.pirate.gui.torrent.TorrentView;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import java.awt.*;
import java.util.List;
/**
* Application with Swing as GUI.
*
* @author Angel
* @since 17/11/13
*/
public class PirateGui {
public static final int WIDTH = 800;
public static final int HEIGHT = 500;
private static Logger LOGGER = LoggerFactory.getLogger(PirateGui.class);
private JFrame frame;
private InfoView infoView;
private SeriesView seriesView;
private TorrentView torrentView;
private void execute() {
this.createComponents();
this.applyLookAndFeel();
this.createListeners();
this.displayComponents();
}
private void createComponents() {
//Create and set up the window.
frame = new JFrame("PirateBay downloader "+ Configuration.getInstance().getProjectVersion());
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MigLayout layout = new MigLayout("", "[0:0,grow 25,fill]0[0:0,grow 75,fill]", "[]0[]");
frame.getContentPane().setLayout(layout);
+ frame.getContentPane().setBackground(ColorProvider.getMainBackgroundColor());
//info panel
infoView = new InfoView();
infoView.setMinimumSize(new Dimension(0,30));
frame.add(infoView, BorderLayout.SOUTH);
//series list
seriesView = new SeriesView();
frame.add(seriesView, BorderLayout.WEST);
//torrent list
torrentView = new TorrentView();
torrentView.setMinimumSize(new Dimension(WIDTH,HEIGHT));
frame.add(torrentView, BorderLayout.EAST);
}
/**
* this could be moved to the components itself but doing this way we centralize
* all the feel and look properties.
*/
private void applyLookAndFeel() {
/** series list **/
seriesView.applyFeelAndLook();
/** info texts **/
infoView.applyFeelAndLook();
/** torrent list **/
torrentView.applyFeelAndLook();
}
private void createListeners() {
seriesView.setSerieSelectedListener(new SerieSelectedListener() {
@Override
public void actionPerformed(final SerieSelectedEvent event) {
searchTorrents(event.getSerieSelected());
}
});
torrentView.setTorrentsFoundListener(new TorrentFoundListener() {
@Override
public void actionPerformed(TorrentFoundEvent event) {
updateInfoPanel(event.getCount());
}
});
}
private void displayComponents() {
//Display the window.
frame.pack();
frame.setVisible(true);
}
private void searchTorrents(final Serie serie) {
seriesView.setEnabled(false);
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
torrentView.searchTorrent(serie);
} finally {
frame.pack();
seriesView.setEnabled(true);
}
}
};
new Thread(runnable).start();
infoView.updateInfoText(new ImageIcon(getClass().getResource("1-1.gif")), "Searching torrents for " + serie.getTitle());
frame.pack();
}
private void updateInfoPanel(int size) {
infoView.updateInfoText(null, "Found " + size + " torrent(s)");
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new PirateGui().execute();
}
});
}
}
| true | true | private void createComponents() {
//Create and set up the window.
frame = new JFrame("PirateBay downloader "+ Configuration.getInstance().getProjectVersion());
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MigLayout layout = new MigLayout("", "[0:0,grow 25,fill]0[0:0,grow 75,fill]", "[]0[]");
frame.getContentPane().setLayout(layout);
//info panel
infoView = new InfoView();
infoView.setMinimumSize(new Dimension(0,30));
frame.add(infoView, BorderLayout.SOUTH);
//series list
seriesView = new SeriesView();
frame.add(seriesView, BorderLayout.WEST);
//torrent list
torrentView = new TorrentView();
torrentView.setMinimumSize(new Dimension(WIDTH,HEIGHT));
frame.add(torrentView, BorderLayout.EAST);
}
| private void createComponents() {
//Create and set up the window.
frame = new JFrame("PirateBay downloader "+ Configuration.getInstance().getProjectVersion());
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MigLayout layout = new MigLayout("", "[0:0,grow 25,fill]0[0:0,grow 75,fill]", "[]0[]");
frame.getContentPane().setLayout(layout);
frame.getContentPane().setBackground(ColorProvider.getMainBackgroundColor());
//info panel
infoView = new InfoView();
infoView.setMinimumSize(new Dimension(0,30));
frame.add(infoView, BorderLayout.SOUTH);
//series list
seriesView = new SeriesView();
frame.add(seriesView, BorderLayout.WEST);
//torrent list
torrentView = new TorrentView();
torrentView.setMinimumSize(new Dimension(WIDTH,HEIGHT));
frame.add(torrentView, BorderLayout.EAST);
}
|
diff --git a/src/com/github/triplesolitaire/Lane.java b/src/com/github/triplesolitaire/Lane.java
index bf80a96..e52b6d5 100644
--- a/src/com/github/triplesolitaire/Lane.java
+++ b/src/com/github/triplesolitaire/Lane.java
@@ -1,248 +1,248 @@
package com.github.triplesolitaire;
import java.util.List;
import android.content.ClipData;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.DragEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnDragListener;
import android.widget.RelativeLayout;
public class Lane extends RelativeLayout implements OnDragListener
{
private class OnStartDragListener implements OnTouchListener
{
private final int cascadeIndex;
public OnStartDragListener(final int cascadeIndex)
{
this.cascadeIndex = cascadeIndex;
}
@Override
public boolean onTouch(final View v, final MotionEvent event)
{
if (event.getAction() != MotionEvent.ACTION_DOWN)
return false;
Log.d(TAG, laneId + ": Starting drag at " + cascadeIndex);
final String cascadeData = gameState.buildCascadeString(laneId - 1,
cascadeSize - cascadeIndex);
final ClipData dragData = ClipData.newPlainText(
(cascadeIndex + 1 != cascadeSize ? "MULTI" : "")
+ cascadeData, cascadeData);
currentDragIndex = cascadeIndex;
v.startDrag(dragData, new View.DragShadowBuilder(v), laneId, 0);
return true;
}
}
/**
* Logging tag
*/
private static final String TAG = "TripleSolitaireActivity";
private int cascadeSize;
private int currentDragIndex = -1;
private GameState gameState;
private int laneId;
private OnClickListener onCardFlipListener;
private int stackSize;
public Lane(final Context context, final AttributeSet attrs)
{
super(context, attrs);
final Card laneBase = new Card(context, R.drawable.lane);
laneBase.setId(0);
laneBase.setOnDragListener(this);
addView(laneBase);
}
public void addCascade(final List<String> cascadeToAdd)
{
final int card_vert_overlap_dim = getResources().getDimensionPixelSize(
R.dimen.card_vert_overlap_dim);
// Create the cascade
for (int h = 0; h < cascadeToAdd.size(); h++)
{
final int cascadeId = h + cascadeSize + stackSize + 1;
final Card cascadeCard = new Card(getContext(), getResources()
.getIdentifier(cascadeToAdd.get(h), "drawable",
getContext().getPackageName()));
cascadeCard.setId(cascadeId);
final RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_TOP, cascadeId - 1);
lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
- if (stackSize + cascadeSize > 0)
+ if (stackSize + cascadeSize + h != 0)
lp.setMargins(0, card_vert_overlap_dim, 0, 0);
cascadeCard.setOnTouchListener(new OnStartDragListener(h
+ cascadeSize));
addView(cascadeCard, lp);
}
if (cascadeSize == 0 && !cascadeToAdd.isEmpty())
if (stackSize > 0)
{
// Remove the onCardFlipListener from the top card on the stack
// if
// there is a cascade now
final Card topStack = (Card) findViewById(stackSize);
topStack.setOnClickListener(null);
}
else
{
// Remove the onDragListener from the base of the stack if
// there is a cascade now
final Card laneBase = (Card) findViewById(0);
laneBase.setOnDragListener(null);
}
if (cascadeSize > 0)
{
final Card oldTopCascade = (Card) findViewById(stackSize
+ cascadeSize);
oldTopCascade.setOnDragListener(null);
}
if (!cascadeToAdd.isEmpty())
{
final Card newTopCascade = (Card) findViewById(getChildCount() - 1);
newTopCascade.setOnDragListener(this);
}
cascadeSize += cascadeToAdd.size();
}
public void decrementCascadeSize(final int removeCount)
{
for (int h = 0; h < removeCount; h++)
{
removeViewAt(getChildCount() - 1);
cascadeSize -= 1;
}
if (stackSize + cascadeSize == 0)
{
final Card laneBase = (Card) findViewById(0);
laneBase.setOnDragListener(this);
}
else if (cascadeSize == 0)
{
final Card topStack = (Card) findViewById(stackSize);
topStack.setOnClickListener(onCardFlipListener);
}
else
{
final Card topCascade = (Card) findViewById(stackSize + cascadeSize);
topCascade.setOnDragListener(this);
}
}
public void flipOverTopStack(final String card)
{
final Card toFlip = (Card) findViewById(stackSize);
toFlip.setBackgroundResource(getResources().getIdentifier(card,
"drawable", getContext().getPackageName()));
toFlip.invalidate();
toFlip.setOnClickListener(null);
toFlip.setOnDragListener(this);
toFlip.setOnTouchListener(new OnStartDragListener(0));
stackSize -= 1;
cascadeSize += 1;
}
@Override
public boolean onDrag(final View v, final DragEvent event)
{
final boolean isMyCascade = laneId == (Integer) event.getLocalState();
if (event.getAction() == DragEvent.ACTION_DRAG_STARTED)
{
String card = event.getClipDescription().getLabel().toString();
if (isMyCascade)
{
Log.d(TAG, laneId + ": Drag started of mine of " + card + ": "
+ event);
return false;
}
// Take off MULTI prefix - we accept all cascades based on the top
// card alone
if (card.startsWith("MULTI"))
card = card.substring(5, card.indexOf(';'));
final boolean acceptDrop = cascadeSize == 0 ? gameState
.acceptLaneDrop(card) : gameState.acceptCascadeDrop(
laneId - 1, card);
if (acceptDrop)
Log.d(TAG, laneId + ": Acceptable drag of " + card + " onto "
+ gameState.getCascadeTop(laneId - 1));
return acceptDrop;
}
else if (event.getAction() == DragEvent.ACTION_DROP)
{
final String card = event.getClipData().getItemAt(0).getText()
.toString();
Log.d(TAG, laneId + ": Drop of " + card);
final int from = (Integer) event.getLocalState();
if (from == 0)
gameState.dropFromWasteToCascade(laneId - 1);
else if (from < 0)
gameState
.dropFromFoundationToCascade(laneId - 1, -1 * from - 1);
else
gameState.dropFromCascadeToCascade(laneId - 1, from - 1, card);
}
else if (event.getAction() == DragEvent.ACTION_DRAG_ENDED
&& isMyCascade)
{
Log.d(TAG, laneId + ": Drag ended of mine: " + event.getResult());
if (!event.getResult() && currentDragIndex + 1 == cascadeSize)
gameState.attemptAutoMoveFromCascadeToFoundation(laneId - 1);
currentDragIndex = -1;
}
return true;
}
public void setGameState(final GameState gameState)
{
this.gameState = gameState;
}
public void setLaneId(final int laneId)
{
this.laneId = laneId;
}
public void setOnCardFlipListener(final OnClickListener onCardFlipListener)
{
this.onCardFlipListener = onCardFlipListener;
}
public void setStackSize(final int newStackSize)
{
// Remove the existing views
removeViews(1, getChildCount() - 1);
cascadeSize = 0;
if (stackSize == 0 && newStackSize > 0)
{
final Card laneBase = (Card) findViewById(0);
laneBase.setOnDragListener(null);
}
stackSize = newStackSize;
final int card_vert_overlap_dim = getResources().getDimensionPixelSize(
R.dimen.card_vert_overlap_dim);
// Create the stack
for (int stackId = 1; stackId <= stackSize; stackId++)
{
final Card stackCard = new Card(getContext(), R.drawable.back);
stackCard.setId(stackId);
final RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_TOP, stackId - 1);
lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
if (stackId != 1)
lp.setMargins(0, card_vert_overlap_dim, 0, 0);
if (cascadeSize == 0 && stackId == stackSize)
stackCard.setOnClickListener(onCardFlipListener);
addView(stackCard, stackId, lp);
}
}
}
| true | true | public void addCascade(final List<String> cascadeToAdd)
{
final int card_vert_overlap_dim = getResources().getDimensionPixelSize(
R.dimen.card_vert_overlap_dim);
// Create the cascade
for (int h = 0; h < cascadeToAdd.size(); h++)
{
final int cascadeId = h + cascadeSize + stackSize + 1;
final Card cascadeCard = new Card(getContext(), getResources()
.getIdentifier(cascadeToAdd.get(h), "drawable",
getContext().getPackageName()));
cascadeCard.setId(cascadeId);
final RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_TOP, cascadeId - 1);
lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
if (stackSize + cascadeSize > 0)
lp.setMargins(0, card_vert_overlap_dim, 0, 0);
cascadeCard.setOnTouchListener(new OnStartDragListener(h
+ cascadeSize));
addView(cascadeCard, lp);
}
if (cascadeSize == 0 && !cascadeToAdd.isEmpty())
if (stackSize > 0)
{
// Remove the onCardFlipListener from the top card on the stack
// if
// there is a cascade now
final Card topStack = (Card) findViewById(stackSize);
topStack.setOnClickListener(null);
}
else
{
// Remove the onDragListener from the base of the stack if
// there is a cascade now
final Card laneBase = (Card) findViewById(0);
laneBase.setOnDragListener(null);
}
if (cascadeSize > 0)
{
final Card oldTopCascade = (Card) findViewById(stackSize
+ cascadeSize);
oldTopCascade.setOnDragListener(null);
}
if (!cascadeToAdd.isEmpty())
{
final Card newTopCascade = (Card) findViewById(getChildCount() - 1);
newTopCascade.setOnDragListener(this);
}
cascadeSize += cascadeToAdd.size();
}
| public void addCascade(final List<String> cascadeToAdd)
{
final int card_vert_overlap_dim = getResources().getDimensionPixelSize(
R.dimen.card_vert_overlap_dim);
// Create the cascade
for (int h = 0; h < cascadeToAdd.size(); h++)
{
final int cascadeId = h + cascadeSize + stackSize + 1;
final Card cascadeCard = new Card(getContext(), getResources()
.getIdentifier(cascadeToAdd.get(h), "drawable",
getContext().getPackageName()));
cascadeCard.setId(cascadeId);
final RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_TOP, cascadeId - 1);
lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
if (stackSize + cascadeSize + h != 0)
lp.setMargins(0, card_vert_overlap_dim, 0, 0);
cascadeCard.setOnTouchListener(new OnStartDragListener(h
+ cascadeSize));
addView(cascadeCard, lp);
}
if (cascadeSize == 0 && !cascadeToAdd.isEmpty())
if (stackSize > 0)
{
// Remove the onCardFlipListener from the top card on the stack
// if
// there is a cascade now
final Card topStack = (Card) findViewById(stackSize);
topStack.setOnClickListener(null);
}
else
{
// Remove the onDragListener from the base of the stack if
// there is a cascade now
final Card laneBase = (Card) findViewById(0);
laneBase.setOnDragListener(null);
}
if (cascadeSize > 0)
{
final Card oldTopCascade = (Card) findViewById(stackSize
+ cascadeSize);
oldTopCascade.setOnDragListener(null);
}
if (!cascadeToAdd.isEmpty())
{
final Card newTopCascade = (Card) findViewById(getChildCount() - 1);
newTopCascade.setOnDragListener(this);
}
cascadeSize += cascadeToAdd.size();
}
|
diff --git a/jtidy/src/main/org/w3c/tidy/Lexer.java b/jtidy/src/main/org/w3c/tidy/Lexer.java
index 969ba97..f68966b 100644
--- a/jtidy/src/main/org/w3c/tidy/Lexer.java
+++ b/jtidy/src/main/org/w3c/tidy/Lexer.java
@@ -1,3472 +1,3472 @@
/**
* Java HTML Tidy - JTidy
* HTML parser and pretty printer
*
* Copyright (c) 1998-2000 World Wide Web Consortium (Massachusetts
* Institute of Technology, Institut National de Recherche en
* Informatique et en Automatique, Keio University). All Rights
* Reserved.
*
* Contributing Author(s):
*
* Dave Raggett <[email protected]>
* Andy Quick <[email protected]> (translation to Java)
* Gary L Peskin <[email protected]> (Java development)
* Sami Lempinen <[email protected]> (release management)
* Fabrizio Giustina <fgiust at users.sourceforge.net>
*
* The contributing author(s) would like to thank all those who
* helped with testing, bug fixes, and patience. This wouldn't
* have been possible without all of you.
*
* COPYRIGHT NOTICE:
*
* This software and documentation is provided "as is," and
* the copyright holders and contributing author(s) make no
* representations or warranties, express or implied, including
* but not limited to, warranties of merchantability or fitness
* for any particular purpose or that the use of the software or
* documentation will not infringe any third party patents,
* copyrights, trademarks or other rights.
*
* The copyright holders and contributing author(s) will not be
* liable for any direct, indirect, special or consequential damages
* arising out of any use of the software or documentation, even if
* advised of the possibility of such damage.
*
* Permission is hereby granted to use, copy, modify, and distribute
* this source code, or portions hereof, documentation and executables,
* for any purpose, without fee, subject to the following restrictions:
*
* 1. The origin of this source code must not be misrepresented.
* 2. Altered versions must be plainly marked as such and must
* not be misrepresented as being the original source.
* 3. This Copyright notice may not be removed or altered from any
* source or altered source distribution.
*
* The copyright holders and contributing author(s) specifically
* permit, without fee, and encourage the use of this source code
* as a component for supporting the Hypertext Markup Language in
* commercial products. If you use this source code in a product,
* acknowledgment is not required but would be appreciated.
*
*/
package org.w3c.tidy;
import java.io.PrintWriter;
import java.util.Stack;
import java.util.Vector;
/**
* Lexer for html parser.
* <p>
* Given a file stream fp it returns a sequence of tokens. GetToken(fp) gets the next token UngetToken(fp) provides one
* level undo The tags include an attribute list: - linked list of attribute/value nodes - each node has 2
* null-terminated strings. - entities are replaced in attribute values white space is compacted if not in preformatted
* mode If not in preformatted mode then leading white space is discarded and subsequent white space sequences
* compacted to single space chars. If XmlTags is no then Tag names are folded to upper case and attribute names to
* lower case. Not yet done: - Doctype subset and marked sections
* </p>
* @author Dave Raggett <a href="mailto:[email protected]">[email protected]</a>
* @author Andy Quick <a href="mailto:[email protected]">[email protected]</a> (translation to Java)
* @version $Revision $ ($Author $)
*/
public class Lexer
{
public static final short IgnoreWhitespace = 0;
public static final short MixedContent = 1;
public static final short Preformatted = 2;
public static final short IgnoreMarkup = 3;
/* the 3 URIs for the XHTML 1.0 DTDs */
private static final String voyager_loose = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";
private static final String voyager_strict = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";
private static final String voyager_frameset = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd";
private static final String XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
private static Lexer.W3CVersionInfo[] W3CVersion =
{
new W3CVersionInfo("HTML 4.01", "XHTML 1.0 Strict", voyager_strict, Dict.VERS_HTML40_STRICT),
new W3CVersionInfo(
"HTML 4.01 Transitional",
"XHTML 1.0 Transitional",
voyager_loose,
Dict.VERS_HTML40_LOOSE),
new W3CVersionInfo("HTML 4.01 Frameset", "XHTML 1.0 Frameset", voyager_frameset, Dict.VERS_FRAMES),
new W3CVersionInfo("HTML 4.0", "XHTML 1.0 Strict", voyager_strict, Dict.VERS_HTML40_STRICT),
new W3CVersionInfo(
"HTML 4.0 Transitional",
"XHTML 1.0 Transitional",
voyager_loose,
Dict.VERS_HTML40_LOOSE),
new W3CVersionInfo("HTML 4.0 Frameset", "XHTML 1.0 Frameset", voyager_frameset, Dict.VERS_FRAMES),
new W3CVersionInfo("HTML 3.2", "XHTML 1.0 Transitional", voyager_loose, Dict.VERS_HTML32),
new W3CVersionInfo("HTML 2.0", "XHTML 1.0 Strict", voyager_strict, Dict.VERS_HTML20)};
/* lexer char types */
private static final short DIGIT = 1;
private static final short LETTER = 2;
private static final short NAMECHAR = 4;
private static final short WHITE = 8;
private static final short NEWLINE = 16;
private static final short LOWERCASE = 32;
private static final short UPPERCASE = 64;
/* lexer GetToken states */
private static final short LEX_CONTENT = 0;
private static final short LEX_GT = 1;
private static final short LEX_ENDTAG = 2;
private static final short LEX_STARTTAG = 3;
private static final short LEX_COMMENT = 4;
private static final short LEX_DOCTYPE = 5;
private static final short LEX_PROCINSTR = 6;
private static final short LEX_ENDCOMMENT = 7;
private static final short LEX_CDATA = 8;
private static final short LEX_SECTION = 9;
private static final short LEX_ASP = 10;
private static final short LEX_JSTE = 11;
private static final short LEX_PHP = 12;
/**
* used to classify chars for lexical purposes.
*/
private static short[] lexmap = new short[128];
/**
* file stream.
*/
public StreamIn in;
/**
* error output stream.
*/
public PrintWriter errout;
/**
* for accessibility errors.
*/
public short badAccess;
/**
* for bad style errors.
*/
public short badLayout;
/**
* for bad char encodings.
*/
public short badChars;
/**
* for mismatched/mispositioned form tags.
*/
public short badForm;
/**
* count of warnings in this document.
*/
public short warnings;
/**
* count of errors.
*/
public short errors;
/**
* lines seen.
*/
public int lines;
/**
* at start of current token.
*/
public int columns;
/**
* used to collapse contiguous white space.
*/
public boolean waswhite;
/**
* true after token has been pushed back.
*/
public boolean pushed;
/**
* when space is moved after end tag.
*/
public boolean insertspace;
/**
* Netscape compatibility.
*/
public boolean excludeBlocks;
/**
* true if moved out of table.
*/
public boolean exiled;
/**
* true if xmlns attribute on html element.
*/
public boolean isvoyager;
/**
* bit vector of HTML versions.
*/
public short versions;
/**
* version as given by doctype (if any).
*/
public int doctype;
/**
* e.g. if html or PUBLIC is missing.
*/
public boolean badDoctype;
/**
* start of current node.
*/
public int txtstart;
/**
* end of current node.
*/
public int txtend;
/**
* state of lexer's finite state machine.
*/
public short state;
public Node token;
/**
* lexer character buffer parse tree nodes span onto this buffer which contains the concatenated text contents of
* all of the elements. lexsize must be reset for each file. Byte buffer of UTF-8 chars.
*/
public byte[] lexbuf;
/**
* allocated.
*/
public int lexlength;
/**
* used.
*/
public int lexsize;
/**
* Inline stack for compatibility with Mosaic. For deferring text node.
*/
public Node inode;
/**
* for inferring inline tags.
*/
public int insert;
public Stack istack;
/**
* start of frame.
*/
public int istackbase;
/**
* used for cleaning up presentation markup.
*/
public Style styles;
public Configuration configuration;
protected int seenBodyEndTag; /* used by parser */
private Vector nodeList;
public Lexer(StreamIn in, Configuration configuration)
{
this.in = in;
this.lines = 1;
this.columns = 1;
this.state = LEX_CONTENT;
this.badAccess = 0;
this.badLayout = 0;
this.badChars = 0;
this.badForm = 0;
this.warnings = 0;
this.errors = 0;
this.waswhite = false;
this.pushed = false;
this.insertspace = false;
this.exiled = false;
this.isvoyager = false;
this.versions = Dict.VERS_EVERYTHING;
this.doctype = Dict.VERS_UNKNOWN;
this.badDoctype = false;
this.txtstart = 0;
this.txtend = 0;
this.token = null;
this.lexbuf = null;
this.lexlength = 0;
this.lexsize = 0;
this.inode = null;
this.insert = -1;
this.istack = new Stack();
this.istackbase = 0;
this.styles = null;
this.configuration = configuration;
this.seenBodyEndTag = 0;
this.nodeList = new Vector();
}
public Node newNode()
{
Node node = new Node();
this.nodeList.addElement(node);
return node;
}
public Node newNode(short type, byte[] textarray, int start, int end)
{
Node node = new Node(type, textarray, start, end);
this.nodeList.addElement(node);
return node;
}
public Node newNode(short type, byte[] textarray, int start, int end, String element)
{
Node node = new Node(type, textarray, start, end, element, this.configuration.tt);
this.nodeList.addElement(node);
return node;
}
public Node cloneNode(Node node)
{
Node cnode = (Node) node.clone();
this.nodeList.addElement(cnode);
for (AttVal att = cnode.attributes; att != null; att = att.next)
{
if (att.asp != null)
{
this.nodeList.addElement(att.asp);
}
if (att.php != null)
{
this.nodeList.addElement(att.php);
}
}
return cnode;
}
public AttVal cloneAttributes(AttVal attrs)
{
AttVal cattrs = (AttVal) attrs.clone();
for (AttVal att = cattrs; att != null; att = att.next)
{
if (att.asp != null)
{
this.nodeList.addElement(att.asp);
}
if (att.php != null)
{
this.nodeList.addElement(att.php);
}
}
return cattrs;
}
protected void updateNodeTextArrays(byte[] oldtextarray, byte[] newtextarray)
{
Node node;
for (int i = 0; i < this.nodeList.size(); i++)
{
node = (Node) (this.nodeList.elementAt(i));
if (node.textarray == oldtextarray)
{
node.textarray = newtextarray;
}
}
}
/**
* Used for creating preformatted text from Word2000.
*/
public Node newLineNode()
{
Node node = newNode();
node.textarray = this.lexbuf;
node.start = this.lexsize;
addCharToLexer('\n');
node.end = this.lexsize;
return node;
}
/**
* Should always be able convert to/from UTF-8, so encoding exceptions are converted to an Error to avoid adding
* throws declarations in lots of methods.
*/
public static byte[] getBytes(String str)
{
try
{
return str.getBytes("UTF8");
}
catch (java.io.UnsupportedEncodingException e)
{
throw new Error("string to UTF-8 conversion failed: " + e.getMessage());
}
}
public static String getString(byte[] bytes, int offset, int length)
{
try
{
return new String(bytes, offset, length, "UTF8");
}
catch (java.io.UnsupportedEncodingException e)
{
throw new Error("UTF-8 to string conversion failed: " + e.getMessage());
}
}
public boolean endOfInput()
{
return this.in.isEndOfStream();
}
public void addByte(int c)
{
if (this.lexsize + 1 >= this.lexlength)
{
while (this.lexsize + 1 >= this.lexlength)
{
if (this.lexlength == 0)
{
this.lexlength = 8192;
}
else
{
this.lexlength = this.lexlength * 2;
}
}
byte[] temp = this.lexbuf;
this.lexbuf = new byte[this.lexlength];
if (temp != null)
{
System.arraycopy(temp, 0, this.lexbuf, 0, temp.length);
updateNodeTextArrays(temp, this.lexbuf);
}
}
this.lexbuf[this.lexsize++] = (byte) c;
this.lexbuf[this.lexsize] = (byte) '\0'; /* debug */
}
public void changeChar(byte c)
{
if (this.lexsize > 0)
{
this.lexbuf[this.lexsize - 1] = c;
}
}
/**
* store char c as UTF-8 encoded byte stream
*/
public void addCharToLexer(int c)
{
if (c < 128)
{
addByte(c);
}
else if (c <= 0x7FF)
{
addByte(0xC0 | (c >> 6));
addByte(0x80 | (c & 0x3F));
}
else if (c <= 0xFFFF)
{
addByte(0xE0 | (c >> 12));
addByte(0x80 | ((c >> 6) & 0x3F));
addByte(0x80 | (c & 0x3F));
}
else if (c <= 0x1FFFFF)
{
addByte(0xF0 | (c >> 18));
addByte(0x80 | ((c >> 12) & 0x3F));
addByte(0x80 | ((c >> 6) & 0x3F));
addByte(0x80 | (c & 0x3F));
}
else
{
addByte(0xF8 | (c >> 24));
addByte(0x80 | ((c >> 18) & 0x3F));
addByte(0x80 | ((c >> 12) & 0x3F));
addByte(0x80 | ((c >> 6) & 0x3F));
addByte(0x80 | (c & 0x3F));
}
}
public void addStringToLexer(String str)
{
for (int i = 0; i < str.length(); i++)
{
addCharToLexer(str.charAt(i));
}
}
/**
* No longer attempts to insert missing ';' for unknown enitities unless one was present already, since this gives
* unexpected results. For example: <a href="something.htm?foo&bar&fred"> was tidied to: <a
* href="something.htm?foo&bar;&fred;"> rather than: <a href="something.htm?foo&bar&fred"> My
* thanks for Maurice Buxton for spotting this.
*/
public void parseEntity(short mode)
{
short map;
int start;
boolean first = true;
boolean semicolon = false;
boolean numeric = false;
int c, ch, startcol;
String str;
start = this.lexsize - 1; /* to start at "&" */
startcol = this.in.curcol - 1;
while (true)
{
c = this.in.readChar();
if (c == StreamIn.EndOfStream)
{
break;
}
if (c == ';')
{
semicolon = true;
break;
}
if (first && c == '#')
{
addCharToLexer(c);
first = false;
numeric = true;
continue;
}
first = false;
map = MAP((char) c);
// AQ: Added flag for numeric entities so that numeric entities with missing semi-colons are recognized.
// Eg. "rep..." is recognized as "rep"
if (numeric && ((c == 'x') || ((map & DIGIT) != 0)))
{
addCharToLexer(c);
continue;
}
if (!numeric && ((map & NAMECHAR) != 0))
{
addCharToLexer(c);
continue;
}
// otherwise put it back
this.in.ungetChar(c);
break;
}
str = getString(this.lexbuf, start, this.lexsize - start);
ch = EntityTable.getDefaultEntityTable().entityCode(str);
// deal with unrecognized entities
if (ch <= 0)
{
// set error position just before offending chararcter
this.lines = this.in.curline;
this.columns = startcol;
if (this.lexsize > start + 1)
{
Report.entityError(this, Report.UNKNOWN_ENTITY, str, ch);
if (semicolon)
{
addCharToLexer(';');
}
}
else
{
// naked &
Report.entityError(this, Report.UNESCAPED_AMPERSAND, str, ch);
}
}
else
{
// issue warning if not terminated by ';'
if (c != ';')
{
// set error position just before offending chararcter
this.lines = this.in.curline;
this.columns = startcol;
Report.entityError(this, Report.MISSING_SEMICOLON, str, c);
}
this.lexsize = start;
if (ch == 160 && (mode & Preformatted) != 0)
{
ch = ' ';
}
addCharToLexer(ch);
if (ch == '&' && !this.configuration.QuoteAmpersand)
{
addCharToLexer('a');
addCharToLexer('m');
addCharToLexer('p');
addCharToLexer(';');
}
}
}
public char parseTagName()
{
short map;
int c;
/* fold case of first char in buffer */
c = this.lexbuf[this.txtstart];
map = MAP((char) c);
if (!this.configuration.XmlTags && (map & UPPERCASE) != 0)
{
c += ('a' - 'A');
this.lexbuf[this.txtstart] = (byte) c;
}
while (true)
{
c = this.in.readChar();
if (c == StreamIn.EndOfStream)
{
break;
}
map = MAP((char) c);
if ((map & NAMECHAR) == 0)
{
break;
}
// fold case of subsequent chars
if (!this.configuration.XmlTags && (map & UPPERCASE) != 0)
{
c += ('a' - 'A');
}
addCharToLexer(c);
}
this.txtend = this.lexsize;
return (char) c;
}
public void addStringLiteral(String str)
{
for (int i = 0; i < str.length(); i++)
{
addCharToLexer(str.charAt(i));
}
}
/**
* choose what version to use for new doctype
* @param root
* @return
*/
public short HTMLVersion()
{
short versions;
versions = this.versions;
if ((versions & Dict.VERS_HTML20) != 0)
{
return Dict.VERS_HTML20;
}
if ((versions & Dict.VERS_HTML32) != 0)
{
return Dict.VERS_HTML32;
}
if ((versions & Dict.VERS_HTML40_STRICT) != 0)
{
return Dict.VERS_HTML40_STRICT;
}
if ((versions & Dict.VERS_HTML40_LOOSE) != 0)
{
return Dict.VERS_HTML40_LOOSE;
}
if ((versions & Dict.VERS_FRAMES) != 0)
{
return Dict.VERS_FRAMES;
}
return Dict.VERS_UNKNOWN;
}
public String HTMLVersionName()
{
short guessed;
int j;
guessed = apparentVersion();
for (j = 0; j < W3CVersion.length; ++j)
{
if (guessed == W3CVersion[j].code)
{
if (this.isvoyager)
{
return W3CVersion[j].voyagerName;
}
return W3CVersion[j].name;
}
}
return null;
}
/* add meta element for Tidy */
public boolean addGenerator(Node root)
{
AttVal attval;
Node node;
Node head = root.findHEAD(this.configuration.tt);
if (head != null)
{
for (node = head.content; node != null; node = node.next)
{
if (node.tag == this.configuration.tt.tagMeta)
{
attval = node.getAttrByName("name");
if (attval != null && attval.value != null && Lexer.wstrcasecmp(attval.value, "generator") == 0)
{
attval = node.getAttrByName("content");
if (attval != null
&& attval.value != null
&& attval.value.length() >= 9
&& Lexer.wstrcasecmp(attval.value.substring(0, 9), "HTML Tidy") == 0)
{
return false;
}
}
}
}
node = this.inferredTag("meta");
node.addAttribute("content", "HTML Tidy, see www.w3.org");
node.addAttribute("name", "generator");
Node.insertNodeAtStart(head, node);
return true;
}
return false;
}
/* return true if substring s is in p and isn't all in upper case */
/* this is used to check the case of SYSTEM, PUBLIC, DTD and EN */
/* len is how many chars to check in p */
private static boolean findBadSubString(String s, String p, int len)
{
int n = s.length();
int i = 0;
String ps;
while (n < len)
{
ps = p.substring(i, i + n);
if (wstrcasecmp(s, ps) == 0)
{
return (!ps.equals(s.substring(0, n)));
}
++i;
--len;
}
return false;
}
public boolean checkDocTypeKeyWords(Node doctype)
{
int len = doctype.end - doctype.start;
String s = getString(this.lexbuf, doctype.start, len);
return !(
findBadSubString("SYSTEM", s, len)
|| findBadSubString("PUBLIC", s, len)
|| findBadSubString("//DTD", s, len)
|| findBadSubString("//W3C", s, len)
|| findBadSubString("//EN", s, len));
}
/* examine <!DOCTYPE> to identify version */
public short findGivenVersion(Node doctype)
{
String p, s;
int i, j;
int len;
String str1;
String str2;
/* if root tag for doctype isn't html give up now */
str1 = getString(this.lexbuf, doctype.start, 5);
if (wstrcasecmp(str1, "html ") != 0)
{
return 0;
}
if (!checkDocTypeKeyWords(doctype))
{
Report.warning(this, doctype, null, Report.DTYPE_NOT_UPPER_CASE);
}
/* give up if all we are given is the system id for the doctype */
str1 = getString(this.lexbuf, doctype.start + 5, 7);
if (wstrcasecmp(str1, "SYSTEM ") == 0)
{
/* but at least ensure the case is correct */
if (!str1.substring(0, 6).equals("SYSTEM"))
{
System.arraycopy(getBytes("SYSTEM"), 0, this.lexbuf, doctype.start + 5, 6);
}
return 0; /* unrecognized */
}
if (wstrcasecmp(str1, "PUBLIC ") == 0)
{
if (!str1.substring(0, 6).equals("PUBLIC"))
{
System.arraycopy(getBytes("PUBLIC "), 0, this.lexbuf, doctype.start + 5, 6);
}
}
else
{
this.badDoctype = true;
}
for (i = doctype.start; i < doctype.end; ++i)
{
if (this.lexbuf[i] == (byte) '"')
{
str1 = getString(this.lexbuf, i + 1, 12);
str2 = getString(this.lexbuf, i + 1, 13);
if (str1.equals("-//W3C//DTD "))
{
/* compute length of identifier e.g. "HTML 4.0 Transitional" */
for (j = i + 13; j < doctype.end && this.lexbuf[j] != (byte) '/'; ++j);
len = j - i - 13;
p = getString(this.lexbuf, i + 13, len);
for (j = 1; j < W3CVersion.length; ++j)
{
s = W3CVersion[j].name;
if (len == s.length() && s.equals(p))
{
return W3CVersion[j].code;
}
}
/* else unrecognized version */
}
else if (str2.equals("-//IETF//DTD "))
{
/* compute length of identifier e.g. "HTML 2.0" */
for (j = i + 14; j < doctype.end && this.lexbuf[j] != (byte) '/'; ++j);
len = j - i - 14;
p = getString(this.lexbuf, i + 14, len);
s = W3CVersion[0].name;
if (len == s.length() && s.equals(p))
{
return W3CVersion[0].code;
}
/* else unrecognized version */
}
break;
}
}
return 0;
}
public void fixHTMLNameSpace(Node root, String profile)
{
Node node;
AttVal attr;
for (node = root.content; node != null && node.tag != this.configuration.tt.tagHtml; node = node.next);
if (node != null)
{
for (attr = node.attributes; attr != null; attr = attr.next)
{
if (attr.attribute.equals("xmlns"))
{
break;
}
}
if (attr != null)
{
if (!attr.value.equals(profile))
{
Report.warning(this, node, null, Report.INCONSISTENT_NAMESPACE);
attr.value = profile;
}
}
else
{
attr = new AttVal(node.attributes, null, '"', "xmlns", profile);
attr.dict = AttributeTable.getDefaultAttributeTable().findAttribute(attr);
node.attributes = attr;
}
}
}
public boolean setXHTMLDocType(Node root)
{
String fpi = " ";
String sysid = "";
String namespace = XHTML_NAMESPACE;
Node doctype;
doctype = root.findDocType();
if (this.configuration.docTypeMode == Configuration.DOCTYPE_OMIT)
{
if (doctype != null)
{
Node.discardElement(doctype);
}
return true;
}
if (this.configuration.docTypeMode == Configuration.DOCTYPE_AUTO)
{
/* see what flavor of XHTML this document matches */
if ((this.versions & Dict.VERS_HTML40_STRICT) != 0)
{ /* use XHTML strict */
fpi = "-//W3C//DTD XHTML 1.0 Strict//EN";
sysid = voyager_strict;
}
else if ((this.versions & Dict.VERS_LOOSE) != 0)
{
fpi = "-//W3C//DTD XHTML 1.0 Transitional//EN";
sysid = voyager_loose;
}
else if ((this.versions & Dict.VERS_FRAMES) != 0)
{ /* use XHTML frames */
fpi = "-//W3C//DTD XHTML 1.0 Frameset//EN";
sysid = voyager_frameset;
}
else
{
// lets assume XHTML transitional
fpi = "-//W3C//DTD XHTML 1.0 Transitional//EN";
sysid = voyager_loose;
}
}
else if (this.configuration.docTypeMode == Configuration.DOCTYPE_STRICT)
{
fpi = "-//W3C//DTD XHTML 1.0 Strict//EN";
sysid = voyager_strict;
}
else if (this.configuration.docTypeMode == Configuration.DOCTYPE_LOOSE)
{
fpi = "-//W3C//DTD XHTML 1.0 Transitional//EN";
sysid = voyager_loose;
}
fixHTMLNameSpace(root, namespace);
if (doctype == null)
{
doctype = newNode(Node.DocTypeTag, this.lexbuf, 0, 0);
doctype.next = root.content;
doctype.parent = root;
doctype.prev = null;
root.content = doctype;
}
if (this.configuration.docTypeMode == Configuration.DOCTYPE_USER && this.configuration.docTypeStr != null)
{
fpi = this.configuration.docTypeStr;
sysid = "";
}
this.txtstart = this.lexsize;
this.txtend = this.lexsize;
/* add public identifier */
addStringLiteral("html PUBLIC ");
/* check if the fpi is quoted or not */
if (fpi.charAt(0) == '"')
{
addStringLiteral(fpi);
}
else
{
addStringLiteral("\"");
addStringLiteral(fpi);
addStringLiteral("\"");
}
if (sysid.length() + 6 >= this.configuration.wraplen)
{
addStringLiteral("\n\"");
}
else
{
addStringLiteral("\n \"");
}
/* add system identifier */
addStringLiteral(sysid);
addStringLiteral("\"");
this.txtend = this.lexsize;
doctype.start = this.txtstart;
doctype.end = this.txtend;
return false;
}
public short apparentVersion()
{
switch (this.doctype)
{
case Dict.VERS_UNKNOWN :
return HTMLVersion();
case Dict.VERS_HTML20 :
if ((this.versions & Dict.VERS_HTML20) != 0)
{
return Dict.VERS_HTML20;
}
break;
case Dict.VERS_HTML32 :
if ((this.versions & Dict.VERS_HTML32) != 0)
{
return Dict.VERS_HTML32;
}
break; /* to replace old version by new */
case Dict.VERS_HTML40_STRICT :
if ((this.versions & Dict.VERS_HTML40_STRICT) != 0)
{
return Dict.VERS_HTML40_STRICT;
}
break;
case Dict.VERS_HTML40_LOOSE :
if ((this.versions & Dict.VERS_HTML40_LOOSE) != 0)
{
return Dict.VERS_HTML40_LOOSE;
}
break; /* to replace old version by new */
case Dict.VERS_FRAMES :
if ((this.versions & Dict.VERS_FRAMES) != 0)
{
return Dict.VERS_FRAMES;
}
break;
}
Report.warning(this, null, null, Report.INCONSISTENT_VERSION);
return this.HTMLVersion();
}
/* fixup doctype if missing */
public boolean fixDocType(Node root)
{
Node doctype;
int guessed = Dict.VERS_HTML40_STRICT, i;
if (this.badDoctype)
{
Report.warning(this, null, null, Report.MALFORMED_DOCTYPE);
}
if (this.configuration.XmlOut)
{
return true;
}
doctype = root.findDocType();
if (this.configuration.docTypeMode == Configuration.DOCTYPE_OMIT)
{
if (doctype != null)
{
Node.discardElement(doctype);
}
return true;
}
if (this.configuration.docTypeMode == Configuration.DOCTYPE_STRICT)
{
Node.discardElement(doctype);
doctype = null;
guessed = Dict.VERS_HTML40_STRICT;
}
else if (this.configuration.docTypeMode == Configuration.DOCTYPE_LOOSE)
{
Node.discardElement(doctype);
doctype = null;
guessed = Dict.VERS_HTML40_LOOSE;
}
else if (this.configuration.docTypeMode == Configuration.DOCTYPE_AUTO)
{
if (doctype != null)
{
if (this.doctype == Dict.VERS_UNKNOWN)
{
return false;
}
switch (this.doctype)
{
case Dict.VERS_UNKNOWN :
return false;
case Dict.VERS_HTML20 :
if ((this.versions & Dict.VERS_HTML20) != 0)
{
return true;
}
break; /* to replace old version by new */
case Dict.VERS_HTML32 :
if ((this.versions & Dict.VERS_HTML32) != 0)
{
return true;
}
break; /* to replace old version by new */
case Dict.VERS_HTML40_STRICT :
if ((this.versions & Dict.VERS_HTML40_STRICT) != 0)
{
return true;
}
break; /* to replace old version by new */
case Dict.VERS_HTML40_LOOSE :
if ((this.versions & Dict.VERS_HTML40_LOOSE) != 0)
{
return true;
}
break; /* to replace old version by new */
case Dict.VERS_FRAMES :
if ((this.versions & Dict.VERS_FRAMES) != 0)
{
return true;
}
break; /* to replace old version by new */
}
/* INCONSISTENT_VERSION warning is now issued by ApparentVersion() */
}
/* choose new doctype */
guessed = HTMLVersion();
}
if (guessed == Dict.VERS_UNKNOWN)
{
return false;
}
/* for XML use the Voyager system identifier */
if (this.configuration.XmlOut || this.configuration.XmlTags || this.isvoyager)
{
if (doctype != null)
{
Node.discardElement(doctype);
}
for (i = 0; i < W3CVersion.length; ++i)
{
if (guessed == W3CVersion[i].code)
{
fixHTMLNameSpace(root, W3CVersion[i].profile);
break;
}
}
return true;
}
if (doctype == null)
{
doctype = newNode(Node.DocTypeTag, this.lexbuf, 0, 0);
doctype.next = root.content;
doctype.parent = root;
doctype.prev = null;
root.content = doctype;
}
this.txtstart = this.lexsize;
this.txtend = this.lexsize;
/* use the appropriate public identifier */
addStringLiteral("html PUBLIC ");
if (this.configuration.docTypeMode == Configuration.DOCTYPE_USER && this.configuration.docTypeStr != null)
{
addStringLiteral(this.configuration.docTypeStr);
}
else if (guessed == Dict.VERS_HTML20)
{
addStringLiteral("\"-//IETF//DTD HTML 2.0//EN\"");
}
else
{
addStringLiteral("\"-//W3C//DTD ");
for (i = 0; i < W3CVersion.length; ++i)
{
if (guessed == W3CVersion[i].code)
{
addStringLiteral(W3CVersion[i].name);
break;
}
}
addStringLiteral("//EN\"");
}
this.txtend = this.lexsize;
doctype.start = this.txtstart;
doctype.end = this.txtend;
return true;
}
/* ensure XML document starts with <?XML version="1.0"?> */
public boolean fixXMLPI(Node root)
{
Node xml;
int s;
if (root.content != null && root.content.type == Node.ProcInsTag)
{
s = root.content.start;
if (this.lexbuf[s] == (byte) 'x' && this.lexbuf[s + 1] == (byte) 'm' && this.lexbuf[s + 2] == (byte) 'l')
{
return true;
}
}
xml = newNode(Node.ProcInsTag, this.lexbuf, 0, 0);
xml.next = root.content;
if (root.content != null)
{
root.content.prev = xml;
xml.next = root.content;
}
root.content = xml;
this.txtstart = this.lexsize;
this.txtend = this.lexsize;
addStringLiteral("xml version=\"1.0\"");
if (this.configuration.CharEncoding == Configuration.LATIN1)
{
addStringLiteral(" encoding=\"ISO-8859-1\"");
}
this.txtend = this.lexsize;
xml.start = this.txtstart;
xml.end = this.txtend;
return false;
}
public Node inferredTag(String name)
{
Node node;
node = newNode(Node.StartTag, this.lexbuf, this.txtstart, this.txtend, name);
node.implicit = true;
return node;
}
public static boolean expectsContent(Node node)
{
if (node.type != Node.StartTag)
{
return false;
}
/* unknown element? */
if (node.tag == null)
{
return true;
}
if ((node.tag.model & Dict.CM_EMPTY) != 0)
{
return false;
}
return true;
}
/*
* create a text node for the contents of a CDATA element like style or script which ends with </foo> for some foo.
*/
public Node getCDATA(Node container)
{
int c, lastc, start, len, i;
String str;
boolean endtag = false;
this.lines = this.in.curline;
this.columns = this.in.curcol;
this.waswhite = false;
this.txtstart = this.lexsize;
this.txtend = this.lexsize;
lastc = '\0';
start = -1;
while (true)
{
c = this.in.readChar();
if (c == StreamIn.EndOfStream)
{
break;
}
/* treat \r\n as \n and \r as \n */
if (c == '/' && lastc == '<')
{
if (endtag)
{
this.lines = this.in.curline;
this.columns = this.in.curcol - 3;
Report.warning(this, null, null, Report.BAD_CDATA_CONTENT);
}
start = this.lexsize + 1; /* to first letter */
endtag = true;
}
else if (c == '>' && start >= 0)
{
len = this.lexsize - start;
if (len == container.element.length())
{
str = getString(this.lexbuf, start, len);
if (Lexer.wstrcasecmp(str, container.element) == 0)
{
this.txtend = start - 2;
break;
}
}
this.lines = this.in.curline;
this.columns = this.in.curcol - 3;
Report.warning(this, null, null, Report.BAD_CDATA_CONTENT);
/* if javascript insert backslash before / */
if (ParserImpl.isJavaScript(container))
{
for (i = this.lexsize; i > start - 1; --i)
{
this.lexbuf[i] = this.lexbuf[i - 1];
}
this.lexbuf[start - 1] = (byte) '\\';
this.lexsize++;
}
start = -1;
}
else if (c == '\r')
{
c = this.in.readChar();
if (c != '\n')
{
this.in.ungetChar(c);
}
c = '\n';
}
addCharToLexer(c);
this.txtend = this.lexsize;
lastc = c;
}
if (c == StreamIn.EndOfStream)
{
Report.warning(this, container, null, Report.MISSING_ENDTAG_FOR);
}
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
return null;
}
public void ungetToken()
{
this.pushed = true;
}
/*
* modes for GetToken() MixedContent -- for elements which don't accept PCDATA Preformatted -- white space
* preserved as is IgnoreMarkup -- for CDATA elements such as script, style
*/
public Node getToken(short mode)
{
short map;
int c = 0;
int badcomment = 0;
MutableBoolean isempty = new MutableBoolean();
AttVal attributes;
if (this.pushed)
{
/* duplicate inlines in preference to pushed text nodes when appropriate */
if (this.token.type != Node.TextNode || (this.insert == -1 && this.inode == null))
{
this.pushed = false;
return this.token;
}
}
// at start of block elements, unclosed inline
if (this.insert != -1 || this.inode != null)
{
return insertedToken();
}
this.lines = this.in.curline;
this.columns = this.in.curcol;
this.waswhite = false;
this.txtstart = this.lexsize;
this.txtend = this.lexsize;
while (true)
{
c = this.in.readChar();
if (c == StreamIn.EndOfStream)
{
break;
}
// fix for [427846]
// if (lexer->insertspace && !(mode & IgnoreWhitespace))
- if (this.insertspace && !((mode & IgnoreWhitespace) == 0))
+ if (this.insertspace && !((mode & IgnoreWhitespace) != 0))
{
addCharToLexer(' ');
this.waswhite = true;
this.insertspace = false;
}
/* treat \r\n as \n and \r as \n */
if (c == '\r')
{
c = this.in.readChar();
if (c != '\n')
{
this.in.ungetChar(c);
}
c = '\n';
}
addCharToLexer(c);
switch (this.state)
{
case LEX_CONTENT : /* element content */
map = MAP((char) c);
/*
* Discard white space if appropriate. Its cheaper to do this here rather than in parser methods
* for elements that don't have mixed content.
*/
if (((map & WHITE) != 0) && (mode == IgnoreWhitespace) && this.lexsize == this.txtstart + 1)
{
--this.lexsize;
this.waswhite = false;
this.lines = this.in.curline;
this.columns = this.in.curcol;
continue;
}
if (c == '<')
{
this.state = LEX_GT;
continue;
}
if ((map & WHITE) != 0)
{
/* was previous char white? */
if (this.waswhite)
{
if (mode != Preformatted && mode != IgnoreMarkup)
{
--this.lexsize;
this.lines = this.in.curline;
this.columns = this.in.curcol;
}
}
else
{
// prev char wasn't white
this.waswhite = true;
if (mode != Preformatted && mode != IgnoreMarkup && c != ' ')
{
changeChar((byte) ' ');
}
}
continue;
}
else if (c == '&' && mode != IgnoreMarkup)
{
parseEntity(mode);
}
/* this is needed to avoid trimming trailing whitespace */
if (mode == IgnoreWhitespace)
{
mode = MixedContent;
}
this.waswhite = false;
continue;
case LEX_GT : /* < */
/* check for endtag */
if (c == '/')
{
c = this.in.readChar();
if (c == StreamIn.EndOfStream)
{
this.in.ungetChar(c);
continue;
}
addCharToLexer(c);
map = MAP((char) c);
if ((map & LETTER) != 0)
{
this.lexsize -= 3;
this.txtend = this.lexsize;
this.in.ungetChar(c);
this.state = LEX_ENDTAG;
this.lexbuf[this.lexsize] = (byte) '\0'; /* debug */
this.in.curcol -= 2;
/* if some text before the </ return it now */
if (this.txtend > this.txtstart)
{
/* trim space char before end tag */
if (mode == IgnoreWhitespace && this.lexbuf[this.lexsize - 1] == (byte) ' ')
{
this.lexsize -= 1;
this.txtend = this.lexsize;
}
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
continue; /* no text so keep going */
}
/* otherwise treat as CDATA */
this.waswhite = false;
this.state = LEX_CONTENT;
continue;
}
if (mode == IgnoreMarkup)
{
/* otherwise treat as CDATA */
this.waswhite = false;
this.state = LEX_CONTENT;
continue;
}
/*
* look out for comments, doctype or marked sections this isn't quite right, but its getting there
* ...
*/
if (c == '!')
{
c = this.in.readChar();
if (c == '-')
{
c = this.in.readChar();
if (c == '-')
{
this.state = LEX_COMMENT; /* comment */
this.lexsize -= 2;
this.txtend = this.lexsize;
/* if some text before < return it now */
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
this.txtstart = this.lexsize;
continue;
}
Report.warning(this, null, null, Report.MALFORMED_COMMENT);
}
else if (c == 'd' || c == 'D')
{
this.state = LEX_DOCTYPE; /* doctype */
this.lexsize -= 2;
this.txtend = this.lexsize;
mode = IgnoreWhitespace;
/* skip until white space or '>' */
for (;;)
{
c = this.in.readChar();
if (c == StreamIn.EndOfStream || c == '>')
{
this.in.ungetChar(c);
break;
}
map = MAP((char) c);
if ((map & WHITE) == 0)
{
continue;
}
/* and skip to end of whitespace */
for (;;)
{
c = this.in.readChar();
if (c == StreamIn.EndOfStream || c == '>')
{
this.in.ungetChar(c);
break;
}
map = MAP((char) c);
if ((map & WHITE) != 0)
{
continue;
}
this.in.ungetChar(c);
break;
}
break;
}
/* if some text before < return it now */
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
this.txtstart = this.lexsize;
continue;
}
else if (c == '[')
{
/* Word 2000 embeds <![if ...]> ... <![endif]> sequences */
this.lexsize -= 2;
this.state = LEX_SECTION;
this.txtend = this.lexsize;
/* if some text before < return it now */
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
this.txtstart = this.lexsize;
continue;
}
/* otherwise swallow chars up to and including next '>' */
while (true)
{
c = this.in.readChar();
if (c == '>')
{
break;
}
if (c == -1)
{
this.in.ungetChar(c);
break;
}
}
this.lexsize -= 2;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
continue;
}
/*
* processing instructions
*/
if (c == '?')
{
this.lexsize -= 2;
this.state = LEX_PROCINSTR;
this.txtend = this.lexsize;
/* if some text before < return it now */
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
this.txtstart = this.lexsize;
continue;
}
/* Microsoft ASP's e.g. <% ... server-code ... %> */
if (c == '%')
{
this.lexsize -= 2;
this.state = LEX_ASP;
this.txtend = this.lexsize;
/* if some text before < return it now */
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
this.txtstart = this.lexsize;
continue;
}
/* Netscapes JSTE e.g. <# ... server-code ... #> */
if (c == '#')
{
this.lexsize -= 2;
this.state = LEX_JSTE;
this.txtend = this.lexsize;
/* if some text before < return it now */
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
this.txtstart = this.lexsize;
continue;
}
map = MAP((char) c);
/* check for start tag */
if ((map & LETTER) != 0)
{
this.in.ungetChar(c); /* push back letter */
this.lexsize -= 2; /* discard " <" + letter */
this.txtend = this.lexsize;
this.state = LEX_STARTTAG; /* ready to read tag name */
/* if some text before < return it now */
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
continue; /* no text so keep going */
}
/* otherwise treat as CDATA */
this.state = LEX_CONTENT;
this.waswhite = false;
continue;
case LEX_ENDTAG : /* </letter */
this.txtstart = this.lexsize - 1;
this.in.curcol += 2;
c = parseTagName();
this.token = newNode(Node.EndTag, /* create endtag token */
this.lexbuf,
this.txtstart,
this.txtend,
getString(this.lexbuf, this.txtstart, this.txtend - this.txtstart));
this.lexsize = this.txtstart;
this.txtend = this.txtstart;
/* skip to '>' */
while (c != '>')
{
c = this.in.readChar();
if (c == StreamIn.EndOfStream)
{
break;
}
}
if (c == StreamIn.EndOfStream)
{
this.in.ungetChar(c);
continue;
}
this.state = LEX_CONTENT;
this.waswhite = false;
return this.token; /* the endtag token */
case LEX_STARTTAG : /* first letter of tagname */
this.txtstart = this.lexsize - 1; /* set txtstart to first letter */
c = parseTagName();
isempty.value = false;
attributes = null;
this.token =
newNode(
(isempty.value ? Node.StartEndTag : Node.StartTag),
this.lexbuf,
this.txtstart,
this.txtend,
getString(this.lexbuf, this.txtstart, this.txtend - this.txtstart));
/* parse attributes, consuming closing ">" */
if (c != '>')
{
if (c == '/')
{
this.in.ungetChar(c);
}
attributes = parseAttrs(isempty);
}
if (isempty.value)
{
this.token.type = Node.StartEndTag;
}
this.token.attributes = attributes;
this.lexsize = this.txtstart;
this.txtend = this.txtstart;
/* swallow newline following start tag */
/* special check needed for CRLF sequence */
/* this doesn't apply to empty elements */
if (expectsContent(this.token) || this.token.tag == this.configuration.tt.tagBr)
{
c = this.in.readChar();
if (c == '\r')
{
c = this.in.readChar();
if (c != '\n')
{
this.in.ungetChar(c);
}
}
else if (c != '\n' && c != '\f')
{
this.in.ungetChar(c);
}
this.waswhite = true; /* to swallow leading whitespace */
}
else
{
this.waswhite = false;
}
this.state = LEX_CONTENT;
if (this.token.tag == null)
{
Report.error(this, null, this.token, Report.UNKNOWN_ELEMENT);
}
else if (!this.configuration.XmlTags)
{
this.versions &= this.token.tag.versions;
if ((this.token.tag.versions & Dict.VERS_PROPRIETARY) != 0)
{
if (!this.configuration.MakeClean
&& (this.token.tag == this.configuration.tt.tagNobr
|| this.token.tag == this.configuration.tt.tagWbr))
{
Report.warning(this, null, this.token, Report.PROPRIETARY_ELEMENT);
}
}
if (this.token.tag.chkattrs != null)
{
this.token.checkUniqueAttributes(this);
this.token.tag.chkattrs.check(this, this.token);
}
else
{
this.token.checkAttributes(this);
}
}
return this.token; /* return start tag */
case LEX_COMMENT : /* seen <!-- so look for --> */
if (c != '-')
{
continue;
}
c = this.in.readChar();
addCharToLexer(c);
if (c != '-')
{
continue;
}
end_comment : while (true)
{
c = this.in.readChar();
if (c == '>')
{
if (badcomment != 0)
{
Report.warning(this, null, null, Report.MALFORMED_COMMENT);
}
this.txtend = this.lexsize - 2; // AQ 8Jul2000
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.CommentTag, this.lexbuf, this.txtstart, this.txtend);
/* now look for a line break */
c = this.in.readChar();
if (c == '\r')
{
c = this.in.readChar();
if (c != '\n')
{
this.token.linebreak = true;
}
}
if (c == '\n')
{
this.token.linebreak = true;
}
else
{
this.in.ungetChar(c);
}
return this.token;
}
/* note position of first such error in the comment */
if (badcomment == 0)
{
this.lines = this.in.curline;
this.columns = this.in.curcol - 3;
}
badcomment++;
if (this.configuration.FixComments)
{
this.lexbuf[this.lexsize - 2] = (byte) '=';
}
addCharToLexer(c);
/* if '-' then look for '>' to end the comment */
if (c != '-')
{
break end_comment;
}
}
/* otherwise continue to look for --> */
this.lexbuf[this.lexsize - 2] = (byte) '=';
continue;
case LEX_DOCTYPE : /* seen <!d so look for '> ' munging whitespace */
map = MAP((char) c);
if ((map & WHITE) != 0)
{
if (this.waswhite)
{
this.lexsize -= 1;
}
this.waswhite = true;
}
else
{
this.waswhite = false;
}
if (c != '>')
{
continue;
}
this.lexsize -= 1;
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.DocTypeTag, this.lexbuf, this.txtstart, this.txtend);
/* make a note of the version named by the doctype */
this.doctype = findGivenVersion(this.token);
return this.token;
case LEX_PROCINSTR : /* seen <? so look for '> ' */
/* check for PHP preprocessor instructions <?php ... ?> */
if (this.lexsize - this.txtstart == 3)
{
if ((getString(this.lexbuf, this.txtstart, 3)).equals("php"))
{
this.state = LEX_PHP;
continue;
}
}
if (this.configuration.XmlPIs) /* insist on ?> as terminator */
{
if (c != '?')
{
continue;
}
/* now look for '>' */
c = this.in.readChar();
if (c == StreamIn.EndOfStream)
{
Report.warning(this, null, null, Report.UNEXPECTED_END_OF_FILE);
this.in.ungetChar(c);
continue;
}
addCharToLexer(c);
}
if (c != '>')
{
continue;
}
this.lexsize -= 1;
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.ProcInsTag, this.lexbuf, this.txtstart, this.txtend);
return this.token;
case LEX_ASP : /* seen <% so look for "%> " */
if (c != '%')
{
continue;
}
/* now look for '>' */
c = this.in.readChar();
if (c != '>')
{
this.in.ungetChar(c);
continue;
}
this.lexsize -= 1;
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.AspTag, this.lexbuf, this.txtstart, this.txtend);
return this.token;
case LEX_JSTE : /* seen <# so look for "#> " */
if (c != '#')
{
continue;
}
/* now look for '>' */
c = this.in.readChar();
if (c != '>')
{
this.in.ungetChar(c);
continue;
}
this.lexsize -= 1;
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.JsteTag, this.lexbuf, this.txtstart, this.txtend);
return this.token;
case LEX_PHP : /* seen " <?php" so look for "?> " */
if (c != '?')
{
continue;
}
/* now look for '>' */
c = this.in.readChar();
if (c != '>')
{
this.in.ungetChar(c);
continue;
}
this.lexsize -= 1;
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.PhpTag, this.lexbuf, this.txtstart, this.txtend);
return this.token;
case LEX_SECTION : /* seen " <![" so look for "]> " */
if (c == '[')
{
if (this.lexsize == (this.txtstart + 6)
&& (getString(this.lexbuf, this.txtstart, 6)).equals("CDATA["))
{
this.state = LEX_CDATA;
this.lexsize -= 6;
continue;
}
}
if (c != ']')
{
continue;
}
/* now look for '>' */
c = this.in.readChar();
if (c != '>')
{
this.in.ungetChar(c);
continue;
}
this.lexsize -= 1;
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.SectionTag, this.lexbuf, this.txtstart, this.txtend);
return this.token;
case LEX_CDATA : /* seen " <![CDATA[" so look for "]]> " */
if (c != ']')
{
continue;
}
/* now look for ']' */
c = this.in.readChar();
if (c != ']')
{
this.in.ungetChar(c);
continue;
}
/* now look for '>' */
c = this.in.readChar();
if (c != '>')
{
this.in.ungetChar(c);
continue;
}
this.lexsize -= 1;
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.CDATATag, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
}
if (this.state == LEX_CONTENT) /* text string */
{
this.txtend = this.lexsize;
if (this.txtend > this.txtstart)
{
this.in.ungetChar(c);
if (this.lexbuf[this.lexsize - 1] == (byte) ' ')
{
this.lexsize -= 1;
this.txtend = this.lexsize;
}
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
}
else if (this.state == LEX_COMMENT) /* comment */
{
if (c == StreamIn.EndOfStream)
{
Report.warning(this, null, null, Report.MALFORMED_COMMENT);
}
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.CommentTag, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
return null;
}
/*
* parser for ASP within start tags Some people use ASP for to customize attributes Tidy isn't really well suited
* to dealing with ASP This is a workaround for attributes, but won't deal with the case where the ASP is used to
* tailor the attribute value. Here is an example of a work around for using ASP in attribute values: href="
* <%=rsSchool.Fields("ID").Value%> " where the ASP that generates the attribute value is masked from Tidy by the
* quotemarks.
*/
public Node parseAsp()
{
int c;
Node asp = null;
this.txtstart = this.lexsize;
for (;;)
{
c = this.in.readChar();
addCharToLexer(c);
if (c != '%')
{
continue;
}
c = this.in.readChar();
addCharToLexer(c);
if (c == '>')
{
break;
}
}
this.lexsize -= 2;
this.txtend = this.lexsize;
if (this.txtend > this.txtstart)
{
asp = newNode(Node.AspTag, this.lexbuf, this.txtstart, this.txtend);
}
this.txtstart = this.txtend;
return asp;
}
/*
* PHP is like ASP but is based upon XML processing instructions, e.g. <?php ... ?>
*/
public Node parsePhp()
{
int c;
Node php = null;
this.txtstart = this.lexsize;
for (;;)
{
c = this.in.readChar();
addCharToLexer(c);
if (c != '?')
{
continue;
}
c = this.in.readChar();
addCharToLexer(c);
if (c == '>')
{
break;
}
}
this.lexsize -= 2;
this.txtend = this.lexsize;
if (this.txtend > this.txtstart)
{
php = newNode(Node.PhpTag, this.lexbuf, this.txtstart, this.txtend);
}
this.txtstart = this.txtend;
return php;
}
/* consumes the '>' terminating start tags */
public String parseAttribute(MutableBoolean isempty, MutableObject asp, MutableObject php)
{
int start = 0;
// int len = 0; Removed by BUGFIX for 126265
short map;
String attr;
int c = 0;
asp.setObject(null); /* clear asp pointer */
php.setObject(null); /* clear php pointer */
/* skip white space before the attribute */
for (;;)
{
c = this.in.readChar();
if (c == '/')
{
c = this.in.readChar();
if (c == '>')
{
isempty.value = true;
return null;
}
this.in.ungetChar(c);
c = '/';
break;
}
if (c == '>')
{
return null;
}
if (c == '<')
{
c = this.in.readChar();
if (c == '%')
{
asp.setObject(parseAsp());
return null;
}
else if (c == '?')
{
php.setObject(parsePhp());
return null;
}
this.in.ungetChar(c);
Report.attrError(this, this.token, null, Report.UNEXPECTED_GT);
return null;
}
if (c == '"' || c == '\'')
{
Report.attrError(this, this.token, null, Report.UNEXPECTED_QUOTEMARK);
continue;
}
if (c == StreamIn.EndOfStream)
{
Report.attrError(this, this.token, null, Report.UNEXPECTED_END_OF_FILE);
this.in.ungetChar(c);
return null;
}
map = MAP((char) c);
if ((map & WHITE) == 0)
{
break;
}
}
start = this.lexsize;
for (;;)
{
/* but push back '=' for parseValue() */
if (c == '=' || c == '>')
{
this.in.ungetChar(c);
break;
}
if (c == '<' || c == StreamIn.EndOfStream)
{
this.in.ungetChar(c);
break;
}
map = MAP((char) c);
if ((map & WHITE) != 0)
{
break;
}
/* what should be done about non-namechar characters? */
/* currently these are incorporated into the attr name */
if (!this.configuration.XmlTags && (map & UPPERCASE) != 0)
{
c += ('a' - 'A');
}
// ++len; Removed by BUGFIX for 126265
addCharToLexer(c);
c = this.in.readChar();
}
// Following line added by GLP to fix BUG 126265. This is a temporary comment
// and should be removed when Tidy is fixed.
int len = this.lexsize - start;
attr = (len > 0 ? getString(this.lexbuf, start, len) : null);
this.lexsize = start;
return attr;
}
/**
* invoked when < is seen in place of attribute value but terminates on whitespace if not ASP, PHP or Tango this
* routine recognizes ' and " quoted strings.
*/
public int parseServerInstruction()
{
int c, map, delim = '"';
boolean isrule = false;
c = this.in.readChar();
addCharToLexer(c);
/* check for ASP, PHP or Tango */
if (c == '%' || c == '?' || c == '@')
{
isrule = true;
}
for (;;)
{
c = this.in.readChar();
if (c == StreamIn.EndOfStream)
{
break;
}
if (c == '>')
{
if (isrule)
{
addCharToLexer(c);
}
else
{
this.in.ungetChar(c);
}
break;
}
/* if not recognized as ASP, PHP or Tango */
/* then also finish value on whitespace */
if (!isrule)
{
map = MAP((char) c);
if ((map & WHITE) != 0)
{
break;
}
}
addCharToLexer(c);
if (c == '"')
{
do
{
c = this.in.readChar();
if (endOfInput()) /* #427840 - fix by Terry Teague 30 Jun 01 */
{
Report.attrError(this, this.token, null, Report.UNEXPECTED_END_OF_FILE);
this.in.ungetChar(c);
return 0;
}
if (c == '>') /* #427840 - fix by Terry Teague 30 Jun 01 */
{
this.in.ungetChar(c);
Report.attrError(this, this.token, null, Report.UNEXPECTED_GT);
return 0;
}
addCharToLexer(c);
}
while (c != '"');
delim = '\'';
continue;
}
if (c == '\'')
{
do
{
c = this.in.readChar();
if (endOfInput()) /* #427840 - fix by Terry Teague 30 Jun 01 */
{
Report.attrError(this, this.token, null, Report.UNEXPECTED_END_OF_FILE);
this.in.ungetChar(c);
return 0;
}
if (c == '>') /* #427840 - fix by Terry Teague 30 Jun 01 */
{
this.in.ungetChar(c);
Report.attrError(this, this.token, null, Report.UNEXPECTED_GT);
return 0;
}
addCharToLexer(c);
}
while (c != '\'');
}
}
return delim;
}
/* values start with "=" or " = " etc. */
/* doesn't consume the ">" at end of start tag */
public String parseValue(String name, boolean foldCase, MutableBoolean isempty, MutableInteger pdelim)
{
int len = 0;
int start;
short map;
boolean seen_gt = false;
boolean munge = true;
int c = 0;
int lastc, delim, quotewarning;
String value;
delim = 0;
pdelim.value = '"';
/*
* Henry Zrepa reports that some folk are using the embed element with script attributes where newlines are
* significant and must be preserved
*/
if (this.configuration.LiteralAttribs)
{
munge = false;
}
/* skip white space before the '=' */
for (;;)
{
c = this.in.readChar();
if (c == StreamIn.EndOfStream)
{
this.in.ungetChar(c);
break;
}
map = MAP((char) c);
if ((map & WHITE) == 0)
{
break;
}
}
/*
* c should be '=' if there is a value other legal possibilities are white space, '/' and '>'
*/
if (c != '=')
{
this.in.ungetChar(c);
return null;
}
/* skip white space after '=' */
for (;;)
{
c = this.in.readChar();
if (c == StreamIn.EndOfStream)
{
this.in.ungetChar(c);
break;
}
map = MAP((char) c);
if ((map & WHITE) == 0)
{
break;
}
}
/* check for quote marks */
if (c == '"' || c == '\'')
{
delim = c;
}
else if (c == '<')
{
start = this.lexsize;
addCharToLexer(c);
pdelim.value = parseServerInstruction();
len = this.lexsize - start;
this.lexsize = start;
return (len > 0 ? getString(this.lexbuf, start, len) : null);
}
else
{
this.in.ungetChar(c);
}
/*
* and read the value string check for quote mark if needed
*/
quotewarning = 0;
start = this.lexsize;
c = '\0';
for (;;)
{
lastc = c; /* track last character */
c = this.in.readChar();
if (c == StreamIn.EndOfStream)
{
Report.attrError(this, this.token, null, Report.UNEXPECTED_END_OF_FILE);
this.in.ungetChar(c);
break;
}
if (delim == (char) 0)
{
if (c == '>')
{
this.in.ungetChar(c);
break;
}
if (c == '"' || c == '\'')
{
Report.attrError(this, this.token, null, Report.UNEXPECTED_QUOTEMARK);
break;
}
if (c == '<')
{
/* this.in.ungetChar(c); */
Report.attrError(this, this.token, null, Report.UNEXPECTED_GT);
/* break; */
}
/*
* For cases like <br clear=all/> need to avoid treating /> as part of the attribute value, however
* care is needed to avoid so treating <a href=http://www.acme.com /> in this way, which would map the
* <a> tag to <a href="http://www.acme.com"/>
*/
if (c == '/')
{
/* peek ahead in case of /> */
c = this.in.readChar();
if (c == '>' && !AttributeTable.getDefaultAttributeTable().isUrl(name))
{
isempty.value = true;
this.in.ungetChar(c);
break;
}
/* unget peeked char */
this.in.ungetChar(c);
c = '/';
}
}
else
{
// delim is '\'' or '"'
if (c == delim)
{
break;
}
/* treat CRLF, CR and LF as single line break */
if (c == '\r')
{
c = this.in.readChar();
if (c != '\n')
{
this.in.ungetChar(c);
}
c = '\n';
}
if (c == '\n' || c == '<' || c == '>')
{
++quotewarning;
}
if (c == '>')
{
seen_gt = true;
}
}
if (c == '&')
{
addCharToLexer(c);
parseEntity((short) 0);
continue;
}
/*
* kludge for JavaScript attribute values with line continuations in string literals
*/
if (c == '\\')
{
c = this.in.readChar();
if (c != '\n')
{
this.in.ungetChar(c);
c = '\\';
}
}
map = MAP((char) c);
if ((map & WHITE) != 0)
{
if (delim == (char) 0)
{
break;
}
if (munge)
{
c = ' ';
if (lastc == ' ')
{
continue;
}
}
}
else if (foldCase && (map & UPPERCASE) != 0)
{
c += ('a' - 'A');
}
addCharToLexer(c);
}
if (quotewarning > 10 && seen_gt && munge)
{
/*
* there is almost certainly a missing trailling quote mark as we have see too many newlines, < or >
* characters. an exception is made for Javascript attributes and the javascript URL scheme which may
* legitimately include < and >
*/
if (!AttributeTable.getDefaultAttributeTable().isScript(name)
&& !(AttributeTable.getDefaultAttributeTable().isUrl(name)
&& (getString(this.lexbuf, start, 11)).equals("javascript:")))
{
Report.error(this, null, null, Report.SUSPECTED_MISSING_QUOTE);
}
}
len = this.lexsize - start;
this.lexsize = start;
if (len > 0 || delim != 0)
{
value = getString(this.lexbuf, start, len);
}
else
{
value = null;
}
/* note delimiter if given */
if (delim != 0)
{
pdelim.value = delim;
}
else
{
pdelim.value = '"';
}
return value;
}
/* attr must be non-null */
public static boolean isValidAttrName(String attr)
{
short map;
char c;
int i;
/* first character should be a letter */
c = attr.charAt(0);
map = MAP(c);
if (!((map & LETTER) != 0))
{
return false;
}
/* remaining characters should be namechars */
for (i = 1; i < attr.length(); i++)
{
c = attr.charAt(i);
map = MAP(c);
if ((map & NAMECHAR) != 0)
{
continue;
}
return false;
}
return true;
}
/* swallows closing '>' */
public AttVal parseAttrs(MutableBoolean isempty)
{
AttVal av, list;
String attribute, value;
MutableInteger delim = new MutableInteger();
MutableObject asp = new MutableObject();
MutableObject php = new MutableObject();
list = null;
for (; !endOfInput();)
{
attribute = parseAttribute(isempty, asp, php);
if (attribute == null)
{
/* check if attributes are created by ASP markup */
if (asp.getObject() != null)
{
av = new AttVal(list, null, (Node) asp.getObject(), null, '\0', null, null);
list = av;
continue;
}
/* check if attributes are created by PHP markup */
if (php.getObject() != null)
{
av = new AttVal(list, null, null, (Node) php.getObject(), '\0', null, null);
list = av;
continue;
}
break;
}
value = parseValue(attribute, false, isempty, delim);
if (attribute != null && isValidAttrName(attribute))
{
av = new AttVal(list, null, null, null, delim.value, attribute, value);
av.dict = AttributeTable.getDefaultAttributeTable().findAttribute(av);
list = av;
}
else
{
av = new AttVal(null, null, null, null, 0, attribute, value);
Report.attrError(this, this.token, value, Report.BAD_ATTRIBUTE_VALUE);
}
}
return list;
}
/*
* push a copy of an inline node onto stack but don't push if implicit or OBJECT or APPLET (implicit tags are ones
* generated from the istack) One issue arises with pushing inlines when the tag is already pushed. For instance:
* <p><em> text <p><em> more text Shouldn't be mapped to <p><em> text </em></p><p><em><em> more text </em>
* </em>
*/
public void pushInline(Node node)
{
IStack is;
if (node.implicit)
{
return;
}
if (node.tag == null)
{
return;
}
if ((node.tag.model & Dict.CM_INLINE) == 0)
{
return;
}
if ((node.tag.model & Dict.CM_OBJECT) != 0)
{
return;
}
if (node.tag != this.configuration.tt.tagFont && isPushed(node))
{
return;
}
// make sure there is enough space for the stack
is = new IStack();
is.tag = node.tag;
is.element = node.element;
if (node.attributes != null)
{
is.attributes = cloneAttributes(node.attributes);
}
this.istack.push(is);
}
/* pop inline stack */
public void popInline(Node node)
{
IStack is;
if (node != null)
{
if (node.tag == null)
{
return;
}
if ((node.tag.model & Dict.CM_INLINE) == 0)
{
return;
}
if ((node.tag.model & Dict.CM_OBJECT) != 0)
{
return;
}
// if node is </a> then pop until we find an <a>
if (node.tag == this.configuration.tt.tagA)
{
while (this.istack.size() > 0)
{
is = (IStack) this.istack.pop();
if (is.tag == this.configuration.tt.tagA)
{
break;
}
}
if (this.insert >= this.istack.size())
{
this.insert = -1;
}
return;
}
}
if (this.istack.size() > 0)
{
is = (IStack) this.istack.pop();
if (this.insert >= this.istack.size())
{
this.insert = -1;
}
}
}
public boolean isPushed(Node node)
{
int i;
IStack is;
for (i = this.istack.size() - 1; i >= 0; --i)
{
is = (IStack) this.istack.elementAt(i);
if (is.tag == node.tag)
{
return true;
}
}
return false;
}
/*
* This has the effect of inserting "missing" inline elements around the contents of blocklevel elements such as P,
* TD, TH, DIV, PRE etc. This procedure is called at the start of ParseBlock. when the inline stack is not empty,
* as will be the case in: <i><h1> italic heading </h1></i> which is then treated as equivalent to <h1><i>
* italic heading </i></h1> This is implemented by setting the lexer into a mode where it gets tokens from the
* inline stack rather than from the input stream.
*/
public int inlineDup(Node node)
{
int n;
n = this.istack.size() - this.istackbase;
if (n > 0)
{
this.insert = this.istackbase;
this.inode = node;
}
return n;
}
public Node insertedToken()
{
Node node;
IStack is;
int n;
// this will only be null if inode != null
if (this.insert == -1)
{
node = this.inode;
this.inode = null;
return node;
}
// is this is the "latest" node then update
// the position, otherwise use current values
if (this.inode == null)
{
this.lines = this.in.curline;
this.columns = this.in.curcol;
}
node = newNode(Node.StartTag, this.lexbuf, this.txtstart, this.txtend);
// GLP: Bugfix 126261. Remove when this change
// is fixed in istack.c in the original Tidy
node.implicit = true;
is = (IStack) this.istack.elementAt(this.insert);
node.element = is.element;
node.tag = is.tag;
if (is.attributes != null)
{
node.attributes = cloneAttributes(is.attributes);
}
// advance lexer to next item on the stack
n = this.insert;
// and recover state if we have reached the end
if (++n < this.istack.size())
{
this.insert = n;
}
else
{
this.insert = -1;
}
return node;
}
/* AQ: Try this for speed optimization */
public static int wstrcasecmp(String s1, String s2)
{
return (s1.equalsIgnoreCase(s2) ? 0 : 1);
}
public static int wstrcaselexcmp(String s1, String s2)
{
char c;
int i = 0;
while (i < s1.length() && i < s2.length())
{
c = s1.charAt(i);
if (toLower(c) != toLower(s2.charAt(i)))
{
break;
}
i += 1;
}
if (i == s1.length() && i == s2.length())
{
return 0;
}
else if (i == s1.length())
{
return -1;
}
else if (i == s2.length())
{
return 1;
}
else
{
return (s1.charAt(i) > s2.charAt(i) ? 1 : -1);
}
}
public static boolean wsubstr(String s1, String s2)
{
int i;
int len1 = s1.length();
int len2 = s2.length();
for (i = 0; i <= len1 - len2; ++i)
{
if (s2.equalsIgnoreCase(s1.substring(i)))
{
return true;
}
}
return false;
}
public boolean canPrune(Node element)
{
if (element.type == Node.TextNode)
{
return true;
}
if (element.content != null)
{
return false;
}
if (element.tag == this.configuration.tt.tagA && element.attributes != null)
{
return false;
}
if (element.tag == this.configuration.tt.tagP && !this.configuration.DropEmptyParas)
{
return false;
}
if (element.tag == null)
{
return false;
}
if ((element.tag.model & Dict.CM_ROW) != 0)
{
return false;
}
if (element.tag == this.configuration.tt.tagApplet)
{
return false;
}
if (element.tag == this.configuration.tt.tagObject)
{
return false;
}
if (element.attributes != null
&& (element.getAttrByName("id") != null || element.getAttrByName("name") != null))
{
return false;
}
return true;
}
/* duplicate name attribute as an id */
public void fixId(Node node)
{
AttVal name = node.getAttrByName("name");
AttVal id = node.getAttrByName("id");
if (name != null)
{
if (id != null)
{
if (!id.value.equals(name.value))
{
Report.attrError(this, node, "name", Report.ID_NAME_MISMATCH);
}
}
else if (this.configuration.XmlOut)
{
node.addAttribute("id", name.value);
}
}
}
/**
* defer duplicates when entering a table or other element where the inlines shouldn't be duplicated.
*/
public void deferDup()
{
this.insert = -1;
this.inode = null;
}
private static void mapStr(String str, short code)
{
int j;
for (int i = 0; i < str.length(); i++)
{
j = str.charAt(i);
lexmap[j] |= code;
}
}
static {
mapStr("\r\n\f", (short) (NEWLINE | WHITE));
mapStr(" \t", WHITE);
mapStr("-.:_", NAMECHAR);
mapStr("0123456789", (short) (DIGIT | NAMECHAR));
mapStr("abcdefghijklmnopqrstuvwxyz", (short) (LOWERCASE | LETTER | NAMECHAR));
mapStr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", (short) (UPPERCASE | LETTER | NAMECHAR));
}
private static short MAP(char c)
{
return (c < 128 ? lexmap[c] : 0);
}
private static boolean isWhite(char c)
{
short m = MAP(c);
return (m & WHITE) != 0;
}
private static boolean isDigit(char c)
{
short m;
m = MAP(c);
return (m & DIGIT) != 0;
}
private static boolean isLetter(char c)
{
short m;
m = MAP(c);
return (m & LETTER) != 0;
}
private static char toLower(char c)
{
short m = MAP(c);
if ((m & UPPERCASE) != 0)
{
c = (char) (c + 'a' - 'A');
}
return c;
}
private static char toUpper(char c)
{
short m = MAP(c);
if ((m & LOWERCASE) != 0)
{
c = (char) (c + 'A' - 'a');
}
return c;
}
public static char foldCase(char c, boolean tocaps, boolean xmlTags)
{
short m;
if (!xmlTags)
{
m = MAP(c);
if (tocaps)
{
if ((m & LOWERCASE) != 0)
{
c = (char) (c + 'A' - 'a');
}
}
else
{
// force to lower case
if ((m & UPPERCASE) != 0)
{
c = (char) (c + 'a' - 'A');
}
}
}
return c;
}
private static class W3CVersionInfo
{
String name;
String voyagerName;
String profile;
short code;
public W3CVersionInfo(String name, String voyagerName, String profile, short code)
{
this.name = name;
this.voyagerName = voyagerName;
this.profile = profile;
this.code = code;
}
}
}
| true | true | public Node getToken(short mode)
{
short map;
int c = 0;
int badcomment = 0;
MutableBoolean isempty = new MutableBoolean();
AttVal attributes;
if (this.pushed)
{
/* duplicate inlines in preference to pushed text nodes when appropriate */
if (this.token.type != Node.TextNode || (this.insert == -1 && this.inode == null))
{
this.pushed = false;
return this.token;
}
}
// at start of block elements, unclosed inline
if (this.insert != -1 || this.inode != null)
{
return insertedToken();
}
this.lines = this.in.curline;
this.columns = this.in.curcol;
this.waswhite = false;
this.txtstart = this.lexsize;
this.txtend = this.lexsize;
while (true)
{
c = this.in.readChar();
if (c == StreamIn.EndOfStream)
{
break;
}
// fix for [427846]
// if (lexer->insertspace && !(mode & IgnoreWhitespace))
if (this.insertspace && !((mode & IgnoreWhitespace) == 0))
{
addCharToLexer(' ');
this.waswhite = true;
this.insertspace = false;
}
/* treat \r\n as \n and \r as \n */
if (c == '\r')
{
c = this.in.readChar();
if (c != '\n')
{
this.in.ungetChar(c);
}
c = '\n';
}
addCharToLexer(c);
switch (this.state)
{
case LEX_CONTENT : /* element content */
map = MAP((char) c);
/*
* Discard white space if appropriate. Its cheaper to do this here rather than in parser methods
* for elements that don't have mixed content.
*/
if (((map & WHITE) != 0) && (mode == IgnoreWhitespace) && this.lexsize == this.txtstart + 1)
{
--this.lexsize;
this.waswhite = false;
this.lines = this.in.curline;
this.columns = this.in.curcol;
continue;
}
if (c == '<')
{
this.state = LEX_GT;
continue;
}
if ((map & WHITE) != 0)
{
/* was previous char white? */
if (this.waswhite)
{
if (mode != Preformatted && mode != IgnoreMarkup)
{
--this.lexsize;
this.lines = this.in.curline;
this.columns = this.in.curcol;
}
}
else
{
// prev char wasn't white
this.waswhite = true;
if (mode != Preformatted && mode != IgnoreMarkup && c != ' ')
{
changeChar((byte) ' ');
}
}
continue;
}
else if (c == '&' && mode != IgnoreMarkup)
{
parseEntity(mode);
}
/* this is needed to avoid trimming trailing whitespace */
if (mode == IgnoreWhitespace)
{
mode = MixedContent;
}
this.waswhite = false;
continue;
case LEX_GT : /* < */
/* check for endtag */
if (c == '/')
{
c = this.in.readChar();
if (c == StreamIn.EndOfStream)
{
this.in.ungetChar(c);
continue;
}
addCharToLexer(c);
map = MAP((char) c);
if ((map & LETTER) != 0)
{
this.lexsize -= 3;
this.txtend = this.lexsize;
this.in.ungetChar(c);
this.state = LEX_ENDTAG;
this.lexbuf[this.lexsize] = (byte) '\0'; /* debug */
this.in.curcol -= 2;
/* if some text before the </ return it now */
if (this.txtend > this.txtstart)
{
/* trim space char before end tag */
if (mode == IgnoreWhitespace && this.lexbuf[this.lexsize - 1] == (byte) ' ')
{
this.lexsize -= 1;
this.txtend = this.lexsize;
}
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
continue; /* no text so keep going */
}
/* otherwise treat as CDATA */
this.waswhite = false;
this.state = LEX_CONTENT;
continue;
}
if (mode == IgnoreMarkup)
{
/* otherwise treat as CDATA */
this.waswhite = false;
this.state = LEX_CONTENT;
continue;
}
/*
* look out for comments, doctype or marked sections this isn't quite right, but its getting there
* ...
*/
if (c == '!')
{
c = this.in.readChar();
if (c == '-')
{
c = this.in.readChar();
if (c == '-')
{
this.state = LEX_COMMENT; /* comment */
this.lexsize -= 2;
this.txtend = this.lexsize;
/* if some text before < return it now */
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
this.txtstart = this.lexsize;
continue;
}
Report.warning(this, null, null, Report.MALFORMED_COMMENT);
}
else if (c == 'd' || c == 'D')
{
this.state = LEX_DOCTYPE; /* doctype */
this.lexsize -= 2;
this.txtend = this.lexsize;
mode = IgnoreWhitespace;
/* skip until white space or '>' */
for (;;)
{
c = this.in.readChar();
if (c == StreamIn.EndOfStream || c == '>')
{
this.in.ungetChar(c);
break;
}
map = MAP((char) c);
if ((map & WHITE) == 0)
{
continue;
}
/* and skip to end of whitespace */
for (;;)
{
c = this.in.readChar();
if (c == StreamIn.EndOfStream || c == '>')
{
this.in.ungetChar(c);
break;
}
map = MAP((char) c);
if ((map & WHITE) != 0)
{
continue;
}
this.in.ungetChar(c);
break;
}
break;
}
/* if some text before < return it now */
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
this.txtstart = this.lexsize;
continue;
}
else if (c == '[')
{
/* Word 2000 embeds <![if ...]> ... <![endif]> sequences */
this.lexsize -= 2;
this.state = LEX_SECTION;
this.txtend = this.lexsize;
/* if some text before < return it now */
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
this.txtstart = this.lexsize;
continue;
}
/* otherwise swallow chars up to and including next '>' */
while (true)
{
c = this.in.readChar();
if (c == '>')
{
break;
}
if (c == -1)
{
this.in.ungetChar(c);
break;
}
}
this.lexsize -= 2;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
continue;
}
/*
* processing instructions
*/
if (c == '?')
{
this.lexsize -= 2;
this.state = LEX_PROCINSTR;
this.txtend = this.lexsize;
/* if some text before < return it now */
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
this.txtstart = this.lexsize;
continue;
}
/* Microsoft ASP's e.g. <% ... server-code ... %> */
if (c == '%')
{
this.lexsize -= 2;
this.state = LEX_ASP;
this.txtend = this.lexsize;
/* if some text before < return it now */
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
this.txtstart = this.lexsize;
continue;
}
/* Netscapes JSTE e.g. <# ... server-code ... #> */
if (c == '#')
{
this.lexsize -= 2;
this.state = LEX_JSTE;
this.txtend = this.lexsize;
/* if some text before < return it now */
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
this.txtstart = this.lexsize;
continue;
}
map = MAP((char) c);
/* check for start tag */
if ((map & LETTER) != 0)
{
this.in.ungetChar(c); /* push back letter */
this.lexsize -= 2; /* discard " <" + letter */
this.txtend = this.lexsize;
this.state = LEX_STARTTAG; /* ready to read tag name */
/* if some text before < return it now */
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
continue; /* no text so keep going */
}
/* otherwise treat as CDATA */
this.state = LEX_CONTENT;
this.waswhite = false;
continue;
case LEX_ENDTAG : /* </letter */
this.txtstart = this.lexsize - 1;
this.in.curcol += 2;
c = parseTagName();
this.token = newNode(Node.EndTag, /* create endtag token */
this.lexbuf,
this.txtstart,
this.txtend,
getString(this.lexbuf, this.txtstart, this.txtend - this.txtstart));
this.lexsize = this.txtstart;
this.txtend = this.txtstart;
/* skip to '>' */
while (c != '>')
{
c = this.in.readChar();
if (c == StreamIn.EndOfStream)
{
break;
}
}
if (c == StreamIn.EndOfStream)
{
this.in.ungetChar(c);
continue;
}
this.state = LEX_CONTENT;
this.waswhite = false;
return this.token; /* the endtag token */
case LEX_STARTTAG : /* first letter of tagname */
this.txtstart = this.lexsize - 1; /* set txtstart to first letter */
c = parseTagName();
isempty.value = false;
attributes = null;
this.token =
newNode(
(isempty.value ? Node.StartEndTag : Node.StartTag),
this.lexbuf,
this.txtstart,
this.txtend,
getString(this.lexbuf, this.txtstart, this.txtend - this.txtstart));
/* parse attributes, consuming closing ">" */
if (c != '>')
{
if (c == '/')
{
this.in.ungetChar(c);
}
attributes = parseAttrs(isempty);
}
if (isempty.value)
{
this.token.type = Node.StartEndTag;
}
this.token.attributes = attributes;
this.lexsize = this.txtstart;
this.txtend = this.txtstart;
/* swallow newline following start tag */
/* special check needed for CRLF sequence */
/* this doesn't apply to empty elements */
if (expectsContent(this.token) || this.token.tag == this.configuration.tt.tagBr)
{
c = this.in.readChar();
if (c == '\r')
{
c = this.in.readChar();
if (c != '\n')
{
this.in.ungetChar(c);
}
}
else if (c != '\n' && c != '\f')
{
this.in.ungetChar(c);
}
this.waswhite = true; /* to swallow leading whitespace */
}
else
{
this.waswhite = false;
}
this.state = LEX_CONTENT;
if (this.token.tag == null)
{
Report.error(this, null, this.token, Report.UNKNOWN_ELEMENT);
}
else if (!this.configuration.XmlTags)
{
this.versions &= this.token.tag.versions;
if ((this.token.tag.versions & Dict.VERS_PROPRIETARY) != 0)
{
if (!this.configuration.MakeClean
&& (this.token.tag == this.configuration.tt.tagNobr
|| this.token.tag == this.configuration.tt.tagWbr))
{
Report.warning(this, null, this.token, Report.PROPRIETARY_ELEMENT);
}
}
if (this.token.tag.chkattrs != null)
{
this.token.checkUniqueAttributes(this);
this.token.tag.chkattrs.check(this, this.token);
}
else
{
this.token.checkAttributes(this);
}
}
return this.token; /* return start tag */
case LEX_COMMENT : /* seen <!-- so look for --> */
if (c != '-')
{
continue;
}
c = this.in.readChar();
addCharToLexer(c);
if (c != '-')
{
continue;
}
end_comment : while (true)
{
c = this.in.readChar();
if (c == '>')
{
if (badcomment != 0)
{
Report.warning(this, null, null, Report.MALFORMED_COMMENT);
}
this.txtend = this.lexsize - 2; // AQ 8Jul2000
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.CommentTag, this.lexbuf, this.txtstart, this.txtend);
/* now look for a line break */
c = this.in.readChar();
if (c == '\r')
{
c = this.in.readChar();
if (c != '\n')
{
this.token.linebreak = true;
}
}
if (c == '\n')
{
this.token.linebreak = true;
}
else
{
this.in.ungetChar(c);
}
return this.token;
}
/* note position of first such error in the comment */
if (badcomment == 0)
{
this.lines = this.in.curline;
this.columns = this.in.curcol - 3;
}
badcomment++;
if (this.configuration.FixComments)
{
this.lexbuf[this.lexsize - 2] = (byte) '=';
}
addCharToLexer(c);
/* if '-' then look for '>' to end the comment */
if (c != '-')
{
break end_comment;
}
}
/* otherwise continue to look for --> */
this.lexbuf[this.lexsize - 2] = (byte) '=';
continue;
case LEX_DOCTYPE : /* seen <!d so look for '> ' munging whitespace */
map = MAP((char) c);
if ((map & WHITE) != 0)
{
if (this.waswhite)
{
this.lexsize -= 1;
}
this.waswhite = true;
}
else
{
this.waswhite = false;
}
if (c != '>')
{
continue;
}
this.lexsize -= 1;
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.DocTypeTag, this.lexbuf, this.txtstart, this.txtend);
/* make a note of the version named by the doctype */
this.doctype = findGivenVersion(this.token);
return this.token;
case LEX_PROCINSTR : /* seen <? so look for '> ' */
/* check for PHP preprocessor instructions <?php ... ?> */
if (this.lexsize - this.txtstart == 3)
{
if ((getString(this.lexbuf, this.txtstart, 3)).equals("php"))
{
this.state = LEX_PHP;
continue;
}
}
if (this.configuration.XmlPIs) /* insist on ?> as terminator */
{
if (c != '?')
{
continue;
}
/* now look for '>' */
c = this.in.readChar();
if (c == StreamIn.EndOfStream)
{
Report.warning(this, null, null, Report.UNEXPECTED_END_OF_FILE);
this.in.ungetChar(c);
continue;
}
addCharToLexer(c);
}
if (c != '>')
{
continue;
}
this.lexsize -= 1;
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.ProcInsTag, this.lexbuf, this.txtstart, this.txtend);
return this.token;
case LEX_ASP : /* seen <% so look for "%> " */
if (c != '%')
{
continue;
}
/* now look for '>' */
c = this.in.readChar();
if (c != '>')
{
this.in.ungetChar(c);
continue;
}
this.lexsize -= 1;
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.AspTag, this.lexbuf, this.txtstart, this.txtend);
return this.token;
case LEX_JSTE : /* seen <# so look for "#> " */
if (c != '#')
{
continue;
}
/* now look for '>' */
c = this.in.readChar();
if (c != '>')
{
this.in.ungetChar(c);
continue;
}
this.lexsize -= 1;
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.JsteTag, this.lexbuf, this.txtstart, this.txtend);
return this.token;
case LEX_PHP : /* seen " <?php" so look for "?> " */
if (c != '?')
{
continue;
}
/* now look for '>' */
c = this.in.readChar();
if (c != '>')
{
this.in.ungetChar(c);
continue;
}
this.lexsize -= 1;
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.PhpTag, this.lexbuf, this.txtstart, this.txtend);
return this.token;
case LEX_SECTION : /* seen " <![" so look for "]> " */
if (c == '[')
{
if (this.lexsize == (this.txtstart + 6)
&& (getString(this.lexbuf, this.txtstart, 6)).equals("CDATA["))
{
this.state = LEX_CDATA;
this.lexsize -= 6;
continue;
}
}
if (c != ']')
{
continue;
}
/* now look for '>' */
c = this.in.readChar();
if (c != '>')
{
this.in.ungetChar(c);
continue;
}
this.lexsize -= 1;
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.SectionTag, this.lexbuf, this.txtstart, this.txtend);
return this.token;
case LEX_CDATA : /* seen " <![CDATA[" so look for "]]> " */
if (c != ']')
{
continue;
}
/* now look for ']' */
c = this.in.readChar();
if (c != ']')
{
this.in.ungetChar(c);
continue;
}
/* now look for '>' */
c = this.in.readChar();
if (c != '>')
{
this.in.ungetChar(c);
continue;
}
this.lexsize -= 1;
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.CDATATag, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
}
if (this.state == LEX_CONTENT) /* text string */
{
this.txtend = this.lexsize;
if (this.txtend > this.txtstart)
{
this.in.ungetChar(c);
if (this.lexbuf[this.lexsize - 1] == (byte) ' ')
{
this.lexsize -= 1;
this.txtend = this.lexsize;
}
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
}
else if (this.state == LEX_COMMENT) /* comment */
{
if (c == StreamIn.EndOfStream)
{
Report.warning(this, null, null, Report.MALFORMED_COMMENT);
}
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.CommentTag, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
return null;
}
| public Node getToken(short mode)
{
short map;
int c = 0;
int badcomment = 0;
MutableBoolean isempty = new MutableBoolean();
AttVal attributes;
if (this.pushed)
{
/* duplicate inlines in preference to pushed text nodes when appropriate */
if (this.token.type != Node.TextNode || (this.insert == -1 && this.inode == null))
{
this.pushed = false;
return this.token;
}
}
// at start of block elements, unclosed inline
if (this.insert != -1 || this.inode != null)
{
return insertedToken();
}
this.lines = this.in.curline;
this.columns = this.in.curcol;
this.waswhite = false;
this.txtstart = this.lexsize;
this.txtend = this.lexsize;
while (true)
{
c = this.in.readChar();
if (c == StreamIn.EndOfStream)
{
break;
}
// fix for [427846]
// if (lexer->insertspace && !(mode & IgnoreWhitespace))
if (this.insertspace && !((mode & IgnoreWhitespace) != 0))
{
addCharToLexer(' ');
this.waswhite = true;
this.insertspace = false;
}
/* treat \r\n as \n and \r as \n */
if (c == '\r')
{
c = this.in.readChar();
if (c != '\n')
{
this.in.ungetChar(c);
}
c = '\n';
}
addCharToLexer(c);
switch (this.state)
{
case LEX_CONTENT : /* element content */
map = MAP((char) c);
/*
* Discard white space if appropriate. Its cheaper to do this here rather than in parser methods
* for elements that don't have mixed content.
*/
if (((map & WHITE) != 0) && (mode == IgnoreWhitespace) && this.lexsize == this.txtstart + 1)
{
--this.lexsize;
this.waswhite = false;
this.lines = this.in.curline;
this.columns = this.in.curcol;
continue;
}
if (c == '<')
{
this.state = LEX_GT;
continue;
}
if ((map & WHITE) != 0)
{
/* was previous char white? */
if (this.waswhite)
{
if (mode != Preformatted && mode != IgnoreMarkup)
{
--this.lexsize;
this.lines = this.in.curline;
this.columns = this.in.curcol;
}
}
else
{
// prev char wasn't white
this.waswhite = true;
if (mode != Preformatted && mode != IgnoreMarkup && c != ' ')
{
changeChar((byte) ' ');
}
}
continue;
}
else if (c == '&' && mode != IgnoreMarkup)
{
parseEntity(mode);
}
/* this is needed to avoid trimming trailing whitespace */
if (mode == IgnoreWhitespace)
{
mode = MixedContent;
}
this.waswhite = false;
continue;
case LEX_GT : /* < */
/* check for endtag */
if (c == '/')
{
c = this.in.readChar();
if (c == StreamIn.EndOfStream)
{
this.in.ungetChar(c);
continue;
}
addCharToLexer(c);
map = MAP((char) c);
if ((map & LETTER) != 0)
{
this.lexsize -= 3;
this.txtend = this.lexsize;
this.in.ungetChar(c);
this.state = LEX_ENDTAG;
this.lexbuf[this.lexsize] = (byte) '\0'; /* debug */
this.in.curcol -= 2;
/* if some text before the </ return it now */
if (this.txtend > this.txtstart)
{
/* trim space char before end tag */
if (mode == IgnoreWhitespace && this.lexbuf[this.lexsize - 1] == (byte) ' ')
{
this.lexsize -= 1;
this.txtend = this.lexsize;
}
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
continue; /* no text so keep going */
}
/* otherwise treat as CDATA */
this.waswhite = false;
this.state = LEX_CONTENT;
continue;
}
if (mode == IgnoreMarkup)
{
/* otherwise treat as CDATA */
this.waswhite = false;
this.state = LEX_CONTENT;
continue;
}
/*
* look out for comments, doctype or marked sections this isn't quite right, but its getting there
* ...
*/
if (c == '!')
{
c = this.in.readChar();
if (c == '-')
{
c = this.in.readChar();
if (c == '-')
{
this.state = LEX_COMMENT; /* comment */
this.lexsize -= 2;
this.txtend = this.lexsize;
/* if some text before < return it now */
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
this.txtstart = this.lexsize;
continue;
}
Report.warning(this, null, null, Report.MALFORMED_COMMENT);
}
else if (c == 'd' || c == 'D')
{
this.state = LEX_DOCTYPE; /* doctype */
this.lexsize -= 2;
this.txtend = this.lexsize;
mode = IgnoreWhitespace;
/* skip until white space or '>' */
for (;;)
{
c = this.in.readChar();
if (c == StreamIn.EndOfStream || c == '>')
{
this.in.ungetChar(c);
break;
}
map = MAP((char) c);
if ((map & WHITE) == 0)
{
continue;
}
/* and skip to end of whitespace */
for (;;)
{
c = this.in.readChar();
if (c == StreamIn.EndOfStream || c == '>')
{
this.in.ungetChar(c);
break;
}
map = MAP((char) c);
if ((map & WHITE) != 0)
{
continue;
}
this.in.ungetChar(c);
break;
}
break;
}
/* if some text before < return it now */
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
this.txtstart = this.lexsize;
continue;
}
else if (c == '[')
{
/* Word 2000 embeds <![if ...]> ... <![endif]> sequences */
this.lexsize -= 2;
this.state = LEX_SECTION;
this.txtend = this.lexsize;
/* if some text before < return it now */
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
this.txtstart = this.lexsize;
continue;
}
/* otherwise swallow chars up to and including next '>' */
while (true)
{
c = this.in.readChar();
if (c == '>')
{
break;
}
if (c == -1)
{
this.in.ungetChar(c);
break;
}
}
this.lexsize -= 2;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
continue;
}
/*
* processing instructions
*/
if (c == '?')
{
this.lexsize -= 2;
this.state = LEX_PROCINSTR;
this.txtend = this.lexsize;
/* if some text before < return it now */
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
this.txtstart = this.lexsize;
continue;
}
/* Microsoft ASP's e.g. <% ... server-code ... %> */
if (c == '%')
{
this.lexsize -= 2;
this.state = LEX_ASP;
this.txtend = this.lexsize;
/* if some text before < return it now */
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
this.txtstart = this.lexsize;
continue;
}
/* Netscapes JSTE e.g. <# ... server-code ... #> */
if (c == '#')
{
this.lexsize -= 2;
this.state = LEX_JSTE;
this.txtend = this.lexsize;
/* if some text before < return it now */
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
this.txtstart = this.lexsize;
continue;
}
map = MAP((char) c);
/* check for start tag */
if ((map & LETTER) != 0)
{
this.in.ungetChar(c); /* push back letter */
this.lexsize -= 2; /* discard " <" + letter */
this.txtend = this.lexsize;
this.state = LEX_STARTTAG; /* ready to read tag name */
/* if some text before < return it now */
if (this.txtend > this.txtstart)
{
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
continue; /* no text so keep going */
}
/* otherwise treat as CDATA */
this.state = LEX_CONTENT;
this.waswhite = false;
continue;
case LEX_ENDTAG : /* </letter */
this.txtstart = this.lexsize - 1;
this.in.curcol += 2;
c = parseTagName();
this.token = newNode(Node.EndTag, /* create endtag token */
this.lexbuf,
this.txtstart,
this.txtend,
getString(this.lexbuf, this.txtstart, this.txtend - this.txtstart));
this.lexsize = this.txtstart;
this.txtend = this.txtstart;
/* skip to '>' */
while (c != '>')
{
c = this.in.readChar();
if (c == StreamIn.EndOfStream)
{
break;
}
}
if (c == StreamIn.EndOfStream)
{
this.in.ungetChar(c);
continue;
}
this.state = LEX_CONTENT;
this.waswhite = false;
return this.token; /* the endtag token */
case LEX_STARTTAG : /* first letter of tagname */
this.txtstart = this.lexsize - 1; /* set txtstart to first letter */
c = parseTagName();
isempty.value = false;
attributes = null;
this.token =
newNode(
(isempty.value ? Node.StartEndTag : Node.StartTag),
this.lexbuf,
this.txtstart,
this.txtend,
getString(this.lexbuf, this.txtstart, this.txtend - this.txtstart));
/* parse attributes, consuming closing ">" */
if (c != '>')
{
if (c == '/')
{
this.in.ungetChar(c);
}
attributes = parseAttrs(isempty);
}
if (isempty.value)
{
this.token.type = Node.StartEndTag;
}
this.token.attributes = attributes;
this.lexsize = this.txtstart;
this.txtend = this.txtstart;
/* swallow newline following start tag */
/* special check needed for CRLF sequence */
/* this doesn't apply to empty elements */
if (expectsContent(this.token) || this.token.tag == this.configuration.tt.tagBr)
{
c = this.in.readChar();
if (c == '\r')
{
c = this.in.readChar();
if (c != '\n')
{
this.in.ungetChar(c);
}
}
else if (c != '\n' && c != '\f')
{
this.in.ungetChar(c);
}
this.waswhite = true; /* to swallow leading whitespace */
}
else
{
this.waswhite = false;
}
this.state = LEX_CONTENT;
if (this.token.tag == null)
{
Report.error(this, null, this.token, Report.UNKNOWN_ELEMENT);
}
else if (!this.configuration.XmlTags)
{
this.versions &= this.token.tag.versions;
if ((this.token.tag.versions & Dict.VERS_PROPRIETARY) != 0)
{
if (!this.configuration.MakeClean
&& (this.token.tag == this.configuration.tt.tagNobr
|| this.token.tag == this.configuration.tt.tagWbr))
{
Report.warning(this, null, this.token, Report.PROPRIETARY_ELEMENT);
}
}
if (this.token.tag.chkattrs != null)
{
this.token.checkUniqueAttributes(this);
this.token.tag.chkattrs.check(this, this.token);
}
else
{
this.token.checkAttributes(this);
}
}
return this.token; /* return start tag */
case LEX_COMMENT : /* seen <!-- so look for --> */
if (c != '-')
{
continue;
}
c = this.in.readChar();
addCharToLexer(c);
if (c != '-')
{
continue;
}
end_comment : while (true)
{
c = this.in.readChar();
if (c == '>')
{
if (badcomment != 0)
{
Report.warning(this, null, null, Report.MALFORMED_COMMENT);
}
this.txtend = this.lexsize - 2; // AQ 8Jul2000
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.CommentTag, this.lexbuf, this.txtstart, this.txtend);
/* now look for a line break */
c = this.in.readChar();
if (c == '\r')
{
c = this.in.readChar();
if (c != '\n')
{
this.token.linebreak = true;
}
}
if (c == '\n')
{
this.token.linebreak = true;
}
else
{
this.in.ungetChar(c);
}
return this.token;
}
/* note position of first such error in the comment */
if (badcomment == 0)
{
this.lines = this.in.curline;
this.columns = this.in.curcol - 3;
}
badcomment++;
if (this.configuration.FixComments)
{
this.lexbuf[this.lexsize - 2] = (byte) '=';
}
addCharToLexer(c);
/* if '-' then look for '>' to end the comment */
if (c != '-')
{
break end_comment;
}
}
/* otherwise continue to look for --> */
this.lexbuf[this.lexsize - 2] = (byte) '=';
continue;
case LEX_DOCTYPE : /* seen <!d so look for '> ' munging whitespace */
map = MAP((char) c);
if ((map & WHITE) != 0)
{
if (this.waswhite)
{
this.lexsize -= 1;
}
this.waswhite = true;
}
else
{
this.waswhite = false;
}
if (c != '>')
{
continue;
}
this.lexsize -= 1;
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.DocTypeTag, this.lexbuf, this.txtstart, this.txtend);
/* make a note of the version named by the doctype */
this.doctype = findGivenVersion(this.token);
return this.token;
case LEX_PROCINSTR : /* seen <? so look for '> ' */
/* check for PHP preprocessor instructions <?php ... ?> */
if (this.lexsize - this.txtstart == 3)
{
if ((getString(this.lexbuf, this.txtstart, 3)).equals("php"))
{
this.state = LEX_PHP;
continue;
}
}
if (this.configuration.XmlPIs) /* insist on ?> as terminator */
{
if (c != '?')
{
continue;
}
/* now look for '>' */
c = this.in.readChar();
if (c == StreamIn.EndOfStream)
{
Report.warning(this, null, null, Report.UNEXPECTED_END_OF_FILE);
this.in.ungetChar(c);
continue;
}
addCharToLexer(c);
}
if (c != '>')
{
continue;
}
this.lexsize -= 1;
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.ProcInsTag, this.lexbuf, this.txtstart, this.txtend);
return this.token;
case LEX_ASP : /* seen <% so look for "%> " */
if (c != '%')
{
continue;
}
/* now look for '>' */
c = this.in.readChar();
if (c != '>')
{
this.in.ungetChar(c);
continue;
}
this.lexsize -= 1;
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.AspTag, this.lexbuf, this.txtstart, this.txtend);
return this.token;
case LEX_JSTE : /* seen <# so look for "#> " */
if (c != '#')
{
continue;
}
/* now look for '>' */
c = this.in.readChar();
if (c != '>')
{
this.in.ungetChar(c);
continue;
}
this.lexsize -= 1;
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.JsteTag, this.lexbuf, this.txtstart, this.txtend);
return this.token;
case LEX_PHP : /* seen " <?php" so look for "?> " */
if (c != '?')
{
continue;
}
/* now look for '>' */
c = this.in.readChar();
if (c != '>')
{
this.in.ungetChar(c);
continue;
}
this.lexsize -= 1;
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.PhpTag, this.lexbuf, this.txtstart, this.txtend);
return this.token;
case LEX_SECTION : /* seen " <![" so look for "]> " */
if (c == '[')
{
if (this.lexsize == (this.txtstart + 6)
&& (getString(this.lexbuf, this.txtstart, 6)).equals("CDATA["))
{
this.state = LEX_CDATA;
this.lexsize -= 6;
continue;
}
}
if (c != ']')
{
continue;
}
/* now look for '>' */
c = this.in.readChar();
if (c != '>')
{
this.in.ungetChar(c);
continue;
}
this.lexsize -= 1;
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.SectionTag, this.lexbuf, this.txtstart, this.txtend);
return this.token;
case LEX_CDATA : /* seen " <![CDATA[" so look for "]]> " */
if (c != ']')
{
continue;
}
/* now look for ']' */
c = this.in.readChar();
if (c != ']')
{
this.in.ungetChar(c);
continue;
}
/* now look for '>' */
c = this.in.readChar();
if (c != '>')
{
this.in.ungetChar(c);
continue;
}
this.lexsize -= 1;
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.CDATATag, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
}
if (this.state == LEX_CONTENT) /* text string */
{
this.txtend = this.lexsize;
if (this.txtend > this.txtstart)
{
this.in.ungetChar(c);
if (this.lexbuf[this.lexsize - 1] == (byte) ' ')
{
this.lexsize -= 1;
this.txtend = this.lexsize;
}
this.token = newNode(Node.TextNode, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
}
else if (this.state == LEX_COMMENT) /* comment */
{
if (c == StreamIn.EndOfStream)
{
Report.warning(this, null, null, Report.MALFORMED_COMMENT);
}
this.txtend = this.lexsize;
this.lexbuf[this.lexsize] = (byte) '\0';
this.state = LEX_CONTENT;
this.waswhite = false;
this.token = newNode(Node.CommentTag, this.lexbuf, this.txtstart, this.txtend);
return this.token;
}
return null;
}
|
diff --git a/common/crazypants/enderio/conduit/liquid/LiquidConduitRenderer.java b/common/crazypants/enderio/conduit/liquid/LiquidConduitRenderer.java
index b0bbb31d3..78b89518c 100644
--- a/common/crazypants/enderio/conduit/liquid/LiquidConduitRenderer.java
+++ b/common/crazypants/enderio/conduit/liquid/LiquidConduitRenderer.java
@@ -1,175 +1,181 @@
package crazypants.enderio.conduit.liquid;
import static crazypants.render.CubeRenderer.setupVertices;
import java.util.List;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.util.Icon;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.fluids.FluidStack;
import crazypants.enderio.conduit.IConduit;
import crazypants.enderio.conduit.IConduitBundle;
import crazypants.enderio.conduit.geom.CollidableComponent;
import crazypants.enderio.conduit.render.ConduitBundleRenderer;
import crazypants.enderio.conduit.render.DefaultConduitRenderer;
import crazypants.render.BoundingBox;
import crazypants.render.RenderUtil;
import crazypants.vecmath.Vector2d;
import crazypants.vecmath.Vector3d;
import crazypants.vecmath.Vector3f;
public class LiquidConduitRenderer extends DefaultConduitRenderer {
private float downRatio;
private float flatRatio;
private float upRatio;
@Override
public boolean isRendererForConduit(IConduit conduit) {
if(conduit instanceof ILiquidConduit) {
return true;
}
return false;
}
@Override
public void renderEntity(ConduitBundleRenderer conduitBundleRenderer, IConduitBundle te, IConduit conduit, double x, double y, double z, float partialTick,
float worldLight) {
calculateRatios((ILiquidConduit) conduit);
super.renderEntity(conduitBundleRenderer, te, conduit, x, y, z, partialTick, worldLight);
}
@Override
protected void renderConduit(Icon tex, IConduit conduit, CollidableComponent component, float brightness) {
if(isNSEWUP(component.dir)) {
ILiquidConduit lc = (ILiquidConduit) conduit;
FluidStack fluid = lc.getFluidType();
if(fluid != null) {
renderFluidOutline(component, fluid);
}
BoundingBox[] cubes = toCubes(component.bound);
for (BoundingBox cube : cubes) {
drawSection(cube, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV(), component.dir, false);
}
} else {
drawSection(component.bound, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV(), component.dir, true);
}
}
private void renderFluidOutline(CollidableComponent component, FluidStack fluid) {
//TODO: Should cache these vertices as relatively heavy weight to calc each frame
Icon texture = fluid.getFluid().getStillIcon();
+ if(texture == null) {
+ texture = fluid.getFluid().getIcon();
+ if(texture == null) {
+ return;
+ }
+ }
BoundingBox bbb = component.bound;
for (ForgeDirection face : ForgeDirection.VALID_DIRECTIONS) {
if(face != component.dir && face != component.dir.getOpposite()) {
Tessellator tes = Tessellator.instance;
tes.setNormal(face.offsetX, face.offsetY, face.offsetZ);
float scaleFactor = 14f / 16f;
Vector2d uv = new Vector2d();
List<ForgeDirection> edges = RenderUtil.getEdgesForFace(face);
for (ForgeDirection edge : edges) {
if(edge != component.dir && edge != component.dir.getOpposite()) {
float xLen = 1 - Math.abs(edge.offsetX) * scaleFactor;
float yLen = 1 - Math.abs(edge.offsetY) * scaleFactor;
float zLen = 1 - Math.abs(edge.offsetZ) * scaleFactor;
BoundingBox bb = bbb.scale(xLen, yLen, zLen);
List<Vector3f> corners = bb.getCornersForFace(face);
for (Vector3f unitCorn : corners) {
Vector3d corner = new Vector3d(unitCorn);
corner.x += (float) (edge.offsetX * 0.5 * bbb.sizeX()) - (Math.signum(edge.offsetX) * xLen / 2f * bbb.sizeX()) * 2f;
corner.y += (float) (edge.offsetY * 0.5 * bbb.sizeY()) - (Math.signum(edge.offsetY) * yLen / 2f * bbb.sizeY()) * 2f;
corner.z += (float) (edge.offsetZ * 0.5 * bbb.sizeZ()) - (Math.signum(edge.offsetZ) * zLen / 2f * bbb.sizeZ()) * 2f;
RenderUtil.getUvForCorner(uv, corner, 0, 0, 0, face, texture);
tes.addVertexWithUV(corner.x, corner.y, corner.z, uv.x, uv.y);
}
}
}
}
}
}
@Override
protected void renderTransmission(Icon tex, CollidableComponent component, float brightness) {
BoundingBox[] cubes = toCubes(component.bound);
for (BoundingBox cube : cubes) {
drawSection(cube, tex.getMinU(), tex.getMaxU(), tex.getMinV(), tex.getMaxV(), component.dir, true);
}
}
@Override
protected void setVerticesForTransmission(BoundingBox bound, ForgeDirection id) {
float yScale = getRatioForConnection(id);
float xs = id.offsetX == 0 ? 0.9f : 1;
float ys = id.offsetY == 0 ? Math.min(yScale, 0.9f) : yScale;
float zs = id.offsetZ == 0 ? 0.9f : 1;
float sizeY = bound.sizeY();
bound = bound.scale(xs, ys, zs);
float transY = (bound.sizeY() - sizeY) / 2;
Vector3d translation = new Vector3d(0, transY, 0);
setupVertices(bound.translate(translation));
}
private void calculateRatios(ILiquidConduit conduit) {
ConduitTank tank = conduit.getTank();
int totalAmount = tank.getFluidAmount();
int upCapacity = 0;
if(conduit.containsConduitConnection(ForgeDirection.UP) || conduit.containsExternalConnection(ForgeDirection.UP)) {
upCapacity = ILiquidConduit.VOLUME_PER_CONNECTION;
}
int downCapacity = 0;
if(conduit.containsConduitConnection(ForgeDirection.DOWN) || conduit.containsExternalConnection(ForgeDirection.DOWN)) {
downCapacity = ILiquidConduit.VOLUME_PER_CONNECTION;
}
int flatCapacity = tank.getCapacity() - upCapacity - downCapacity;
int usedCapacity = 0;
if(downCapacity > 0) {
int inDown = Math.min(totalAmount, downCapacity);
usedCapacity += inDown;
downRatio = (float) inDown / downCapacity;
}
if(flatCapacity > 0 && usedCapacity < totalAmount) {
int inFlat = Math.min(flatCapacity, totalAmount - usedCapacity);
usedCapacity += inFlat;
flatRatio = (float) inFlat / flatCapacity;
} else {
flatRatio = 0;
}
if(upCapacity > 0 && usedCapacity < totalAmount) {
int inUp = Math.min(upCapacity, totalAmount - usedCapacity);
upRatio = (float) inUp / upCapacity;
} else {
upRatio = 0;
}
}
private float getRatioForConnection(ForgeDirection id) {
if(id == ForgeDirection.UP) {
return upRatio;
}
if(id == ForgeDirection.DOWN) {
return downRatio;
}
return flatRatio;
}
}
| true | true | private void renderFluidOutline(CollidableComponent component, FluidStack fluid) {
//TODO: Should cache these vertices as relatively heavy weight to calc each frame
Icon texture = fluid.getFluid().getStillIcon();
BoundingBox bbb = component.bound;
for (ForgeDirection face : ForgeDirection.VALID_DIRECTIONS) {
if(face != component.dir && face != component.dir.getOpposite()) {
Tessellator tes = Tessellator.instance;
tes.setNormal(face.offsetX, face.offsetY, face.offsetZ);
float scaleFactor = 14f / 16f;
Vector2d uv = new Vector2d();
List<ForgeDirection> edges = RenderUtil.getEdgesForFace(face);
for (ForgeDirection edge : edges) {
if(edge != component.dir && edge != component.dir.getOpposite()) {
float xLen = 1 - Math.abs(edge.offsetX) * scaleFactor;
float yLen = 1 - Math.abs(edge.offsetY) * scaleFactor;
float zLen = 1 - Math.abs(edge.offsetZ) * scaleFactor;
BoundingBox bb = bbb.scale(xLen, yLen, zLen);
List<Vector3f> corners = bb.getCornersForFace(face);
for (Vector3f unitCorn : corners) {
Vector3d corner = new Vector3d(unitCorn);
corner.x += (float) (edge.offsetX * 0.5 * bbb.sizeX()) - (Math.signum(edge.offsetX) * xLen / 2f * bbb.sizeX()) * 2f;
corner.y += (float) (edge.offsetY * 0.5 * bbb.sizeY()) - (Math.signum(edge.offsetY) * yLen / 2f * bbb.sizeY()) * 2f;
corner.z += (float) (edge.offsetZ * 0.5 * bbb.sizeZ()) - (Math.signum(edge.offsetZ) * zLen / 2f * bbb.sizeZ()) * 2f;
RenderUtil.getUvForCorner(uv, corner, 0, 0, 0, face, texture);
tes.addVertexWithUV(corner.x, corner.y, corner.z, uv.x, uv.y);
}
}
}
}
}
}
| private void renderFluidOutline(CollidableComponent component, FluidStack fluid) {
//TODO: Should cache these vertices as relatively heavy weight to calc each frame
Icon texture = fluid.getFluid().getStillIcon();
if(texture == null) {
texture = fluid.getFluid().getIcon();
if(texture == null) {
return;
}
}
BoundingBox bbb = component.bound;
for (ForgeDirection face : ForgeDirection.VALID_DIRECTIONS) {
if(face != component.dir && face != component.dir.getOpposite()) {
Tessellator tes = Tessellator.instance;
tes.setNormal(face.offsetX, face.offsetY, face.offsetZ);
float scaleFactor = 14f / 16f;
Vector2d uv = new Vector2d();
List<ForgeDirection> edges = RenderUtil.getEdgesForFace(face);
for (ForgeDirection edge : edges) {
if(edge != component.dir && edge != component.dir.getOpposite()) {
float xLen = 1 - Math.abs(edge.offsetX) * scaleFactor;
float yLen = 1 - Math.abs(edge.offsetY) * scaleFactor;
float zLen = 1 - Math.abs(edge.offsetZ) * scaleFactor;
BoundingBox bb = bbb.scale(xLen, yLen, zLen);
List<Vector3f> corners = bb.getCornersForFace(face);
for (Vector3f unitCorn : corners) {
Vector3d corner = new Vector3d(unitCorn);
corner.x += (float) (edge.offsetX * 0.5 * bbb.sizeX()) - (Math.signum(edge.offsetX) * xLen / 2f * bbb.sizeX()) * 2f;
corner.y += (float) (edge.offsetY * 0.5 * bbb.sizeY()) - (Math.signum(edge.offsetY) * yLen / 2f * bbb.sizeY()) * 2f;
corner.z += (float) (edge.offsetZ * 0.5 * bbb.sizeZ()) - (Math.signum(edge.offsetZ) * zLen / 2f * bbb.sizeZ()) * 2f;
RenderUtil.getUvForCorner(uv, corner, 0, 0, 0, face, texture);
tes.addVertexWithUV(corner.x, corner.y, corner.z, uv.x, uv.y);
}
}
}
}
}
}
|
diff --git a/hibernate-ogm-core/src/main/java/org/hibernate/ogm/type/descriptor/BasicGridBinder.java b/hibernate-ogm-core/src/main/java/org/hibernate/ogm/type/descriptor/BasicGridBinder.java
index 9a53d6d84..900a79315 100644
--- a/hibernate-ogm-core/src/main/java/org/hibernate/ogm/type/descriptor/BasicGridBinder.java
+++ b/hibernate-ogm-core/src/main/java/org/hibernate/ogm/type/descriptor/BasicGridBinder.java
@@ -1,93 +1,93 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* JBoss, Home of Professional Open Source
* Copyright 2010-2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.hibernate.ogm.type.descriptor;
import java.sql.SQLException;
import java.util.Arrays;
import org.hibernate.engine.jdbc.LobCreator;
import org.hibernate.engine.jdbc.NonContextualLobCreator;
import org.hibernate.ogm.datastore.spi.Tuple;
import org.hibernate.ogm.util.impl.Log;
import org.hibernate.ogm.util.impl.LoggerFactory;
import org.hibernate.type.descriptor.WrapperOptions;
import org.hibernate.type.descriptor.java.JavaTypeDescriptor;
import org.hibernate.type.descriptor.sql.SqlTypeDescriptor;
/**
* @author Emmanuel Bernard
*/
public abstract class BasicGridBinder<X> implements GridValueBinder<X>{
private static final Log log = LoggerFactory.make();
private final JavaTypeDescriptor<X> javaDescriptor;
private final GridTypeDescriptor gridDescriptor;
private static final WrapperOptions DEFAULT_OPTIONS = new WrapperOptions() {
@Override
public boolean useStreamForLobBinding() {
return false;
}
@Override
public LobCreator getLobCreator() {
return NonContextualLobCreator.INSTANCE;
}
@Override
public SqlTypeDescriptor remapSqlTypeDescriptor(SqlTypeDescriptor sqlTypeDescriptor) {
//OGM dialect don't remap types yet
return sqlTypeDescriptor;
}
};
public BasicGridBinder(JavaTypeDescriptor<X> javaDescriptor, GridTypeDescriptor gridDescriptor) {
this.javaDescriptor = javaDescriptor;
this.gridDescriptor = gridDescriptor;
}
@Override
public void bind(Tuple resultset, X value, String[] names) {
if ( value == null ) {
for ( String name : names ) {
- log.tracef( "binding [null] to parameter [$s]", name );
+ log.tracef( "binding [null] to parameter [%1$s]", name );
resultset.put( name, null );
}
}
else {
if ( log.isTraceEnabled() ) {
- log.tracef( "binding [$s] to parameter(s) $s", javaDescriptor.extractLoggableRepresentation( value ), Arrays.toString( names ) );
+ log.tracef( "binding [%2$s] to parameter(s) %1$s", javaDescriptor.extractLoggableRepresentation( value ), Arrays.toString( names ) );
}
doBind( resultset, value, names, DEFAULT_OPTIONS );
}
}
/**
* Perform the binding. Safe to assume that value is not null.
*
* @param st The prepared statement
* @param value The value to bind (not null).
* @param index The index at which to bind
* @param options The binding options
*
* @throws SQLException Indicates a problem binding to the prepared statement.
*/
protected abstract void doBind(Tuple resultset, X value, String[] names, WrapperOptions options);
}
| false | true | public void bind(Tuple resultset, X value, String[] names) {
if ( value == null ) {
for ( String name : names ) {
log.tracef( "binding [null] to parameter [$s]", name );
resultset.put( name, null );
}
}
else {
if ( log.isTraceEnabled() ) {
log.tracef( "binding [$s] to parameter(s) $s", javaDescriptor.extractLoggableRepresentation( value ), Arrays.toString( names ) );
}
doBind( resultset, value, names, DEFAULT_OPTIONS );
}
}
| public void bind(Tuple resultset, X value, String[] names) {
if ( value == null ) {
for ( String name : names ) {
log.tracef( "binding [null] to parameter [%1$s]", name );
resultset.put( name, null );
}
}
else {
if ( log.isTraceEnabled() ) {
log.tracef( "binding [%2$s] to parameter(s) %1$s", javaDescriptor.extractLoggableRepresentation( value ), Arrays.toString( names ) );
}
doBind( resultset, value, names, DEFAULT_OPTIONS );
}
}
|
diff --git a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/RetriableFileCopyCommand.java b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/RetriableFileCopyCommand.java
index 227df08d11..9148630d08 100644
--- a/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/RetriableFileCopyCommand.java
+++ b/hadoop-tools/hadoop-distcp/src/main/java/org/apache/hadoop/tools/mapred/RetriableFileCopyCommand.java
@@ -1,247 +1,248 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.tools.mapred;
import org.apache.hadoop.tools.util.RetriableCommand;
import org.apache.hadoop.tools.util.ThrottledInputStream;
import org.apache.hadoop.tools.util.DistCpUtils;
import org.apache.hadoop.tools.DistCpOptions.*;
import org.apache.hadoop.tools.DistCpConstants;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.*;
import java.util.EnumSet;
/**
* This class extends RetriableCommand to implement the copy of files,
* with retries on failure.
*/
public class RetriableFileCopyCommand extends RetriableCommand {
private static Log LOG = LogFactory.getLog(RetriableFileCopyCommand.class);
private static int BUFFER_SIZE = 8 * 1024;
/**
* Constructor, taking a description of the action.
* @param description Verbose description of the copy operation.
*/
public RetriableFileCopyCommand(String description) {
super(description);
}
/**
* Implementation of RetriableCommand::doExecute().
* This is the actual copy-implementation.
* @param arguments Argument-list to the command.
* @return Number of bytes copied.
* @throws Exception: CopyReadException, if there are read-failures. All other
* failures are IOExceptions.
*/
@SuppressWarnings("unchecked")
@Override
protected Object doExecute(Object... arguments) throws Exception {
assert arguments.length == 4 : "Unexpected argument list.";
FileStatus source = (FileStatus)arguments[0];
assert !source.isDirectory() : "Unexpected file-status. Expected file.";
Path target = (Path)arguments[1];
Mapper.Context context = (Mapper.Context)arguments[2];
EnumSet<FileAttribute> fileAttributes
= (EnumSet<FileAttribute>)arguments[3];
return doCopy(source, target, context, fileAttributes);
}
private long doCopy(FileStatus sourceFileStatus, Path target,
Mapper.Context context,
EnumSet<FileAttribute> fileAttributes)
throws IOException {
Path tmpTargetPath = getTmpFile(target, context);
final Configuration configuration = context.getConfiguration();
FileSystem targetFS = target.getFileSystem(configuration);
try {
if (LOG.isDebugEnabled()) {
LOG.debug("Copying " + sourceFileStatus.getPath() + " to " + target);
LOG.debug("Tmp-file path: " + tmpTargetPath);
}
FileSystem sourceFS = sourceFileStatus.getPath().getFileSystem(
configuration);
long bytesRead = copyToTmpFile(tmpTargetPath, targetFS, sourceFileStatus,
context, fileAttributes);
compareFileLengths(sourceFileStatus, tmpTargetPath, configuration, bytesRead);
//At this point, src&dest lengths are same. if length==0, we skip checksum
- if (bytesRead != 0)
- compareCheckSums(sourceFS, sourceFileStatus.getPath(), targetFS, tmpTargetPath);
+ if (bytesRead != 0) {
+ compareCheckSums(sourceFS, sourceFileStatus.getPath(), targetFS, tmpTargetPath);
+ }
promoteTmpToTarget(tmpTargetPath, target, targetFS);
return bytesRead;
} finally {
if (targetFS.exists(tmpTargetPath))
targetFS.delete(tmpTargetPath, false);
}
}
private long copyToTmpFile(Path tmpTargetPath, FileSystem targetFS,
FileStatus sourceFileStatus, Mapper.Context context,
EnumSet<FileAttribute> fileAttributes)
throws IOException {
OutputStream outStream = new BufferedOutputStream(targetFS.create(
tmpTargetPath, true, BUFFER_SIZE,
getReplicationFactor(fileAttributes, sourceFileStatus, targetFS, tmpTargetPath),
getBlockSize(fileAttributes, sourceFileStatus, targetFS, tmpTargetPath), context));
return copyBytes(sourceFileStatus, outStream, BUFFER_SIZE, true, context);
}
private void compareFileLengths(FileStatus sourceFileStatus, Path target,
Configuration configuration, long bytesRead)
throws IOException {
final Path sourcePath = sourceFileStatus.getPath();
FileSystem fs = sourcePath.getFileSystem(configuration);
if (fs.getFileStatus(sourcePath).getLen() != bytesRead)
throw new IOException("Mismatch in length of source:" + sourcePath
+ " and target:" + target);
}
private void compareCheckSums(FileSystem sourceFS, Path source,
FileSystem targetFS, Path target)
throws IOException {
if (!DistCpUtils.checksumsAreEqual(sourceFS, source, targetFS, target))
throw new IOException("Check-sum mismatch between "
+ source + " and " + target);
}
//If target file exists and unable to delete target - fail
//If target doesn't exist and unable to create parent folder - fail
//If target is successfully deleted and parent exists, if rename fails - fail
private void promoteTmpToTarget(Path tmpTarget, Path target, FileSystem fs)
throws IOException {
if ((fs.exists(target) && !fs.delete(target, false))
|| (!fs.exists(target.getParent()) && !fs.mkdirs(target.getParent()))
|| !fs.rename(tmpTarget, target)) {
throw new IOException("Failed to promote tmp-file:" + tmpTarget
+ " to: " + target);
}
}
private Path getTmpFile(Path target, Mapper.Context context) {
Path targetWorkPath = new Path(context.getConfiguration().
get(DistCpConstants.CONF_LABEL_TARGET_WORK_PATH));
Path root = target.equals(targetWorkPath)? targetWorkPath.getParent() : targetWorkPath;
LOG.info("Creating temp file: " +
new Path(root, ".distcp.tmp." + context.getTaskAttemptID().toString()));
return new Path(root, ".distcp.tmp." + context.getTaskAttemptID().toString());
}
private long copyBytes(FileStatus sourceFileStatus, OutputStream outStream,
int bufferSize, boolean mustCloseStream,
Mapper.Context context) throws IOException {
Path source = sourceFileStatus.getPath();
byte buf[] = new byte[bufferSize];
ThrottledInputStream inStream = null;
long totalBytesRead = 0;
try {
inStream = getInputStream(source, context.getConfiguration());
int bytesRead = readBytes(inStream, buf);
while (bytesRead >= 0) {
totalBytesRead += bytesRead;
outStream.write(buf, 0, bytesRead);
updateContextStatus(totalBytesRead, context, sourceFileStatus);
bytesRead = inStream.read(buf);
}
} finally {
if (mustCloseStream)
IOUtils.cleanup(LOG, outStream, inStream);
}
return totalBytesRead;
}
private void updateContextStatus(long totalBytesRead, Mapper.Context context,
FileStatus sourceFileStatus) {
StringBuilder message = new StringBuilder(DistCpUtils.getFormatter()
.format(totalBytesRead * 100.0f / sourceFileStatus.getLen()));
message.append("% ")
.append(description).append(" [")
.append(DistCpUtils.getStringDescriptionFor(totalBytesRead))
.append('/')
.append(DistCpUtils.getStringDescriptionFor(sourceFileStatus.getLen()))
.append(']');
context.setStatus(message.toString());
}
private static int readBytes(InputStream inStream, byte buf[])
throws IOException {
try {
return inStream.read(buf);
}
catch (IOException e) {
throw new CopyReadException(e);
}
}
private static ThrottledInputStream getInputStream(Path path, Configuration conf)
throws IOException {
try {
FileSystem fs = path.getFileSystem(conf);
long bandwidthMB = conf.getInt(DistCpConstants.CONF_LABEL_BANDWIDTH_MB,
DistCpConstants.DEFAULT_BANDWIDTH_MB);
return new ThrottledInputStream(new BufferedInputStream(fs.open(path)),
bandwidthMB * 1024 * 1024);
}
catch (IOException e) {
throw new CopyReadException(e);
}
}
private static short getReplicationFactor(
EnumSet<FileAttribute> fileAttributes,
FileStatus sourceFile, FileSystem targetFS, Path tmpTargetPath) {
return fileAttributes.contains(FileAttribute.REPLICATION)?
sourceFile.getReplication() : targetFS.getDefaultReplication(tmpTargetPath);
}
private static long getBlockSize(
EnumSet<FileAttribute> fileAttributes,
FileStatus sourceFile, FileSystem targetFS, Path tmpTargetPath) {
return fileAttributes.contains(FileAttribute.BLOCKSIZE)?
sourceFile.getBlockSize() : targetFS.getDefaultBlockSize(tmpTargetPath);
}
/**
* Special subclass of IOException. This is used to distinguish read-operation
* failures from other kinds of IOExceptions.
* The failure to read from source is dealt with specially, in the CopyMapper.
* Such failures may be skipped if the DistCpOptions indicate so.
* Write failures are intolerable, and amount to CopyMapper failure.
*/
public static class CopyReadException extends IOException {
public CopyReadException(Throwable rootCause) {
super(rootCause);
}
}
}
| true | true | private long doCopy(FileStatus sourceFileStatus, Path target,
Mapper.Context context,
EnumSet<FileAttribute> fileAttributes)
throws IOException {
Path tmpTargetPath = getTmpFile(target, context);
final Configuration configuration = context.getConfiguration();
FileSystem targetFS = target.getFileSystem(configuration);
try {
if (LOG.isDebugEnabled()) {
LOG.debug("Copying " + sourceFileStatus.getPath() + " to " + target);
LOG.debug("Tmp-file path: " + tmpTargetPath);
}
FileSystem sourceFS = sourceFileStatus.getPath().getFileSystem(
configuration);
long bytesRead = copyToTmpFile(tmpTargetPath, targetFS, sourceFileStatus,
context, fileAttributes);
compareFileLengths(sourceFileStatus, tmpTargetPath, configuration, bytesRead);
//At this point, src&dest lengths are same. if length==0, we skip checksum
if (bytesRead != 0)
compareCheckSums(sourceFS, sourceFileStatus.getPath(), targetFS, tmpTargetPath);
promoteTmpToTarget(tmpTargetPath, target, targetFS);
return bytesRead;
} finally {
if (targetFS.exists(tmpTargetPath))
targetFS.delete(tmpTargetPath, false);
}
}
| private long doCopy(FileStatus sourceFileStatus, Path target,
Mapper.Context context,
EnumSet<FileAttribute> fileAttributes)
throws IOException {
Path tmpTargetPath = getTmpFile(target, context);
final Configuration configuration = context.getConfiguration();
FileSystem targetFS = target.getFileSystem(configuration);
try {
if (LOG.isDebugEnabled()) {
LOG.debug("Copying " + sourceFileStatus.getPath() + " to " + target);
LOG.debug("Tmp-file path: " + tmpTargetPath);
}
FileSystem sourceFS = sourceFileStatus.getPath().getFileSystem(
configuration);
long bytesRead = copyToTmpFile(tmpTargetPath, targetFS, sourceFileStatus,
context, fileAttributes);
compareFileLengths(sourceFileStatus, tmpTargetPath, configuration, bytesRead);
//At this point, src&dest lengths are same. if length==0, we skip checksum
if (bytesRead != 0) {
compareCheckSums(sourceFS, sourceFileStatus.getPath(), targetFS, tmpTargetPath);
}
promoteTmpToTarget(tmpTargetPath, target, targetFS);
return bytesRead;
} finally {
if (targetFS.exists(tmpTargetPath))
targetFS.delete(tmpTargetPath, false);
}
}
|
diff --git a/iwsn/wsn-federator/src/main/java/de/uniluebeck/itm/tr/wsn/federator/FederatorSessionManagement.java b/iwsn/wsn-federator/src/main/java/de/uniluebeck/itm/tr/wsn/federator/FederatorSessionManagement.java
index f83eb35d..a8949c8e 100644
--- a/iwsn/wsn-federator/src/main/java/de/uniluebeck/itm/tr/wsn/federator/FederatorSessionManagement.java
+++ b/iwsn/wsn-federator/src/main/java/de/uniluebeck/itm/tr/wsn/federator/FederatorSessionManagement.java
@@ -1,426 +1,426 @@
/**********************************************************************************************************************
* Copyright (c) 2010, Institute of Telematics, University of Luebeck *
* 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 University of Luebeck 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 de.uniluebeck.itm.tr.wsn.federator;
import com.google.common.collect.BiMap;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import de.uniluebeck.itm.tr.util.ExecutorUtils;
import de.uniluebeck.itm.tr.util.SecureIdGenerator;
import de.uniluebeck.itm.tr.util.TimedCache;
import de.uniluebeck.itm.tr.util.UrlUtils;
import eu.wisebed.testbed.api.wsn.Constants;
import eu.wisebed.testbed.api.wsn.SessionManagementHelper;
import eu.wisebed.testbed.api.wsn.SessionManagementPreconditions;
import eu.wisebed.testbed.api.wsn.WSNServiceHelper;
import eu.wisebed.testbed.api.wsn.v211.ExperimentNotRunningException_Exception;
import eu.wisebed.testbed.api.wsn.v211.SecretReservationKey;
import eu.wisebed.testbed.api.wsn.v211.SessionManagement;
import eu.wisebed.testbed.api.wsn.v211.UnknownReservationIdException_Exception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
import java.util.*;
import java.util.concurrent.*;
@WebService(serviceName = "SessionManagementService", targetNamespace = Constants.NAMESPACE_SESSION_MANAGEMENT_SERVICE,
portName = "SessionManagementPort", endpointInterface = Constants.ENDPOINT_INTERFACE_SESSION_MANGEMENT_SERVICE)
public class FederatorSessionManagement implements SessionManagement {
/**
* The logger instance for this Session Management federator instance.
*/
private static final Logger log = LoggerFactory.getLogger(FederatorSessionManagement.class);
/**
* The {@link java.util.concurrent.ExecutorService} instance that is used to run jobs in parallel.
*/
private final ExecutorService executorService = Executors.newCachedThreadPool(
new ThreadFactoryBuilder().setNameFormat("FederatorSessionManagement-Thread %d").build()
);
/**
* Session Management Service sessionManagementEndpoint URL <-> Set<URN Prefixes>
*/
private final BiMap<String, Set<String>> sessionManagementEndpointUrlPrefixSet;
/**
*
*/
private final String endpointUrlBase;
/**
* The Reservation System sessionManagementEndpoint URL. Usually this would be a federated reservation system that
* serves all URN prefixes that are federated by this Session Management federator.
*/
private final String reservationEndpointUrl;
/**
* wsnInstanceHash (see {@link eu.wisebed.testbed.api.wsn.SessionManagementHelper#calculateWSNInstanceHash(java.util.List)}
* ) -> Federating WSN API instance
*/
private final TimedCache<String, FederatorWSN> instanceCache = new TimedCache<String, FederatorWSN>();
/**
*
*/
private final SecureIdGenerator secureIdGenerator = new SecureIdGenerator();
/**
*
*/
private final String sessionManagementEndpointUrl;
/**
*
*/
private Endpoint sessionManagementEndpoint;
/**
*
*/
private SessionManagementPreconditions preconditions;
public FederatorSessionManagement(BiMap<String, Set<String>> sessionManagementEndpointUrlPrefixSet,
String endpointUrlBase, String path, String reservationEndpointUrl) {
this.sessionManagementEndpointUrlPrefixSet = sessionManagementEndpointUrlPrefixSet;
this.endpointUrlBase = endpointUrlBase.endsWith("/") ? endpointUrlBase : endpointUrlBase + "/";
this.sessionManagementEndpointUrl = endpointUrlBase + (path.startsWith("/") ? path.substring(1) : path);
this.reservationEndpointUrl = reservationEndpointUrl;
this.preconditions = new SessionManagementPreconditions();
for (Set<String> endpointPrefixSet : sessionManagementEndpointUrlPrefixSet.values()) {
this.preconditions.addServedUrnPrefixes(endpointPrefixSet.toArray(new String[endpointPrefixSet.size()]));
}
}
public void start() throws Exception {
String bindAllInterfacesUrl = UrlUtils.convertHostToZeros(sessionManagementEndpointUrl);
log.debug("Starting Session Management federator...");
log.debug("Endpoint URL: {}", sessionManagementEndpointUrl);
log.debug("Binding URL: {}", bindAllInterfacesUrl);
sessionManagementEndpoint = Endpoint.publish(bindAllInterfacesUrl, this);
log.info("Successfully started Session Management federator on {}", bindAllInterfacesUrl);
}
public void stop() throws Exception {
if (sessionManagementEndpoint != null) {
sessionManagementEndpoint.stop();
log.info("Stopped Session Management federator on {}", sessionManagementEndpointUrl);
}
ExecutorUtils.shutdown(executorService, 5, TimeUnit.SECONDS);
}
private static class GetInstanceCallable implements Callable<GetInstanceCallable.Result> {
private static class Result {
public String federatedWSNInstanceEndpointUrl;
public List<SecretReservationKey> secretReservationKey;
public String controller;
private Result(List<SecretReservationKey> secretReservationKey, String controller,
String federatedWSNInstanceEndpointUrl) {
this.secretReservationKey = secretReservationKey;
this.controller = controller;
this.federatedWSNInstanceEndpointUrl = federatedWSNInstanceEndpointUrl;
}
}
private String federatedSessionManagementEndpointUrl;
private List<SecretReservationKey> secretReservationKey;
private String controller;
public GetInstanceCallable(String federatedSessionManagementEndpointUrl,
List<SecretReservationKey> secretReservationKey, String controller) {
this.federatedSessionManagementEndpointUrl = federatedSessionManagementEndpointUrl;
this.secretReservationKey = secretReservationKey;
this.controller = controller;
}
@Override
public GetInstanceCallable.Result call() throws Exception {
SessionManagement service = WSNServiceHelper
.getSessionManagementService(federatedSessionManagementEndpointUrl);
String federatedWSNInstanceEndpointUrl = service.getInstance(secretReservationKey, controller);
return new GetInstanceCallable.Result(secretReservationKey, controller, federatedWSNInstanceEndpointUrl);
}
}
@Override
public String getInstance(
@WebParam(name = "secretReservationKeys", targetNamespace = "")
List<SecretReservationKey> secretReservationKeys,
@WebParam(name = "controller", targetNamespace = "")
String controller)
throws ExperimentNotRunningException_Exception, UnknownReservationIdException_Exception {
preconditions.checkGetInstanceArguments(secretReservationKeys, controller);
final String wsnInstanceHash = SessionManagementHelper.calculateWSNInstanceHash(secretReservationKeys);
// check if instance already exists and return it if that's the case
FederatorWSN existingWSNFederatorInstance = instanceCache.get(wsnInstanceHash);
if (existingWSNFederatorInstance != null) {
String msg = "Found existing federating WSN API instance for secretReservationKeys {} with "
+ "wsnInstanceHash {}. Returning its' sessionManagementEndpoint URL: {}";
log.debug(msg, new Object[]{
secretReservationKeys, wsnInstanceHash,
existingWSNFederatorInstance.getWsnEndpointUrl()
}
);
log.debug("Adding controller to the set of controllers: {}", controller);
existingWSNFederatorInstance.addController(controller);
return existingWSNFederatorInstance.getWsnEndpointUrl();
}
// create a WSN API instance under a generated secret URL and remember
// to which set of secret URLs of federated
// WSN API instances it maps
String wsnEndpointUrl = endpointUrlBase + secureIdGenerator.getNextId() + "/wsn";
String controllerEndpointUrl = endpointUrlBase + secureIdGenerator.getNextId() + "/controller";
FederatorWSN federatorWSN = new FederatorWSN(wsnEndpointUrl, controllerEndpointUrl);
try {
federatorWSN.start();
// add controller to set of upstream controllers so that output is
// sent upwards
federatorWSN.addController(controller);
} catch (Exception e) {
// TODO throw generic but declared exception
throw WSNServiceHelper
.createExperimentNotRunningException("The federator service could not be started.", e);
}
// delegate calls to the relevant federated Session Management API
// endpoints (fork)
final List<Future<GetInstanceCallable.Result>> futures = new ArrayList<Future<GetInstanceCallable.Result>>();
final Map<String, List<SecretReservationKey>> serviceMapping = getServiceMapping(secretReservationKeys);
for (Map.Entry<String, List<SecretReservationKey>> entry : serviceMapping.entrySet()) {
String sessionManagementEndpointUrl = entry.getKey();
GetInstanceCallable getInstanceCallable = new GetInstanceCallable(
- sessionManagementEndpointUrl, secretReservationKeys, controllerEndpointUrl
+ sessionManagementEndpointUrl, entry.getValue(), controllerEndpointUrl
);
log.debug("Calling getInstance on {}", entry.getKey());
futures.add(executorService.submit(getInstanceCallable));
}
// collect call results (join)
for (Future<GetInstanceCallable.Result> future : futures) {
try {
GetInstanceCallable.Result result = future.get();
Set<String> federatedUrnPrefixSet = convertToUrnPrefixSet(result.secretReservationKey);
federatorWSN.addFederatedWSNEndpoint(result.federatedWSNInstanceEndpointUrl, federatedUrnPrefixSet);
} catch (InterruptedException e) {
// if one delegate call fails also fail
log.error("" + e, e);
// TODO use more generic error message
throw WSNServiceHelper.createExperimentNotRunningException(e.getMessage(), e);
} catch (ExecutionException e) {
// if one delegate call fails also fail
log.error("" + e, e);
// TODO use more generic error message
throw WSNServiceHelper.createExperimentNotRunningException(e.getMessage(), e);
}
}
instanceCache.put(wsnInstanceHash, federatorWSN);
// return the instantiated WSN API instance sessionManagementEndpoint
// URL
return federatorWSN.getWsnEndpointUrl();
}
/**
* Calculates the set of URN prefixes that are "buried" inside {@code secretReservationKeys}.
*
* @param secretReservationKeys the list of {@link eu.wisebed.testbed.api.wsn.v211.SecretReservationKey} instances
*
* @return the set of URN prefixes that are "buried" inside {@code secretReservationKeys}
*/
private Set<String> convertToUrnPrefixSet(List<SecretReservationKey> secretReservationKeys) {
Set<String> retSet = new HashSet<String>(secretReservationKeys.size());
for (SecretReservationKey secretReservationKey : secretReservationKeys) {
retSet.add(secretReservationKey.getUrnPrefix());
}
return retSet;
}
/**
* Checks for a given list of {@link eu.wisebed.testbed.api.wsn.v211.SecretReservationKey} instances which federated
* Session Management endpoints are responsible for which set of URN prefixes.
*
* @param secretReservationKeys the list of {@link eu.wisebed.testbed.api.wsn.v211.SecretReservationKey} instances as
* passed in as parameter e.g. to {@link de.uniluebeck.itm.tr.wsn.federator.FederatorSessionManagement#getInstance(java.util.List,
* String)}
*
* @return a mapping between the Session Management sessionManagementEndpoint URL and the subset of URN prefixes they
* serve
*/
private Map<String, List<SecretReservationKey>> getServiceMapping(
List<SecretReservationKey> secretReservationKeys) {
HashMap<String, List<SecretReservationKey>> map = new HashMap<String, List<SecretReservationKey>>();
for (Map.Entry<String, Set<String>> entry : sessionManagementEndpointUrlPrefixSet.entrySet()) {
for (String urnPrefix : entry.getValue()) {
for (SecretReservationKey srk : secretReservationKeys) {
if (urnPrefix.equals(srk.getUrnPrefix())) {
List<SecretReservationKey> secretReservationKeyList = map.get(entry.getKey());
if (secretReservationKeyList == null) {
secretReservationKeyList = new ArrayList<SecretReservationKey>();
map.put(entry.getKey(), secretReservationKeyList);
}
secretReservationKeyList.add(srk);
}
}
}
}
return map;
}
@Override
public void free(
@WebParam(name = "secretReservationKeys", targetNamespace = "")
List<SecretReservationKey> secretReservationKeys)
throws ExperimentNotRunningException_Exception, UnknownReservationIdException_Exception {
preconditions.checkFreeArguments(secretReservationKeys);
// check if instance still exists and if not simply exit
String wsnInstanceHash = SessionManagementHelper.calculateWSNInstanceHash(secretReservationKeys);
FederatorWSN federatorWSN = instanceCache.remove(wsnInstanceHash);
if (federatorWSN == null) {
log.warn("Trying to free a not existing instance for keys {} with a hash of {}.", secretReservationKeys,
wsnInstanceHash
);
return;
}
// free the WSN API instance created by this implementation
try {
log.debug("Stopping FederatorWSN instance on URL {}", federatorWSN.getWsnEndpointUrl());
federatorWSN.stop();
} catch (Exception e) {
log.error("" + e, e);
}
// call free on all relevant federated Session Management API endpoints
// (asynchronously)
// only fork, but no join since return values are irrelevant for us
Map<String, List<SecretReservationKey>> serviceMapping = getServiceMapping(secretReservationKeys);
for (Map.Entry<String, List<SecretReservationKey>> entry : serviceMapping.entrySet()) {
String federatedSessionManagementEndpointUrl = entry.getKey();
List<SecretReservationKey> secretReservationKeysToFree = entry.getValue();
executorService
.submit(new FreeRunnable(federatedSessionManagementEndpointUrl, secretReservationKeysToFree));
}
}
private static class FreeRunnable implements Runnable {
String sessionManagementEndpointUrl;
List<SecretReservationKey> secretReservationKeys;
private FreeRunnable(String sessionManagementEndpointUrl, List<SecretReservationKey> secretReservationKeys) {
this.sessionManagementEndpointUrl = sessionManagementEndpointUrl;
this.secretReservationKeys = secretReservationKeys;
}
@Override
public void run() {
try {
log
.debug("Freeing WSN instance on {} for keys {}", sessionManagementEndpointUrl,
secretReservationKeys
);
WSNServiceHelper.getSessionManagementService(sessionManagementEndpointUrl).free(secretReservationKeys);
} catch (ExperimentNotRunningException_Exception e) {
log.warn("" + e, e);
} catch (UnknownReservationIdException_Exception e) {
log.warn("" + e, e);
}
}
}
@Override
public String getNetwork() {
// call all federated Session Management API endpoints and collect their
// network information (fork)
// wait for all calls to return (join)
// merge results into one WiseML document
// TODO check if there's something like an XPath expression that does
// this job for us
return null; // TODO implement
}
}
| true | true | public String getInstance(
@WebParam(name = "secretReservationKeys", targetNamespace = "")
List<SecretReservationKey> secretReservationKeys,
@WebParam(name = "controller", targetNamespace = "")
String controller)
throws ExperimentNotRunningException_Exception, UnknownReservationIdException_Exception {
preconditions.checkGetInstanceArguments(secretReservationKeys, controller);
final String wsnInstanceHash = SessionManagementHelper.calculateWSNInstanceHash(secretReservationKeys);
// check if instance already exists and return it if that's the case
FederatorWSN existingWSNFederatorInstance = instanceCache.get(wsnInstanceHash);
if (existingWSNFederatorInstance != null) {
String msg = "Found existing federating WSN API instance for secretReservationKeys {} with "
+ "wsnInstanceHash {}. Returning its' sessionManagementEndpoint URL: {}";
log.debug(msg, new Object[]{
secretReservationKeys, wsnInstanceHash,
existingWSNFederatorInstance.getWsnEndpointUrl()
}
);
log.debug("Adding controller to the set of controllers: {}", controller);
existingWSNFederatorInstance.addController(controller);
return existingWSNFederatorInstance.getWsnEndpointUrl();
}
// create a WSN API instance under a generated secret URL and remember
// to which set of secret URLs of federated
// WSN API instances it maps
String wsnEndpointUrl = endpointUrlBase + secureIdGenerator.getNextId() + "/wsn";
String controllerEndpointUrl = endpointUrlBase + secureIdGenerator.getNextId() + "/controller";
FederatorWSN federatorWSN = new FederatorWSN(wsnEndpointUrl, controllerEndpointUrl);
try {
federatorWSN.start();
// add controller to set of upstream controllers so that output is
// sent upwards
federatorWSN.addController(controller);
} catch (Exception e) {
// TODO throw generic but declared exception
throw WSNServiceHelper
.createExperimentNotRunningException("The federator service could not be started.", e);
}
// delegate calls to the relevant federated Session Management API
// endpoints (fork)
final List<Future<GetInstanceCallable.Result>> futures = new ArrayList<Future<GetInstanceCallable.Result>>();
final Map<String, List<SecretReservationKey>> serviceMapping = getServiceMapping(secretReservationKeys);
for (Map.Entry<String, List<SecretReservationKey>> entry : serviceMapping.entrySet()) {
String sessionManagementEndpointUrl = entry.getKey();
GetInstanceCallable getInstanceCallable = new GetInstanceCallable(
sessionManagementEndpointUrl, secretReservationKeys, controllerEndpointUrl
);
log.debug("Calling getInstance on {}", entry.getKey());
futures.add(executorService.submit(getInstanceCallable));
}
// collect call results (join)
for (Future<GetInstanceCallable.Result> future : futures) {
try {
GetInstanceCallable.Result result = future.get();
Set<String> federatedUrnPrefixSet = convertToUrnPrefixSet(result.secretReservationKey);
federatorWSN.addFederatedWSNEndpoint(result.federatedWSNInstanceEndpointUrl, federatedUrnPrefixSet);
} catch (InterruptedException e) {
// if one delegate call fails also fail
log.error("" + e, e);
// TODO use more generic error message
throw WSNServiceHelper.createExperimentNotRunningException(e.getMessage(), e);
} catch (ExecutionException e) {
// if one delegate call fails also fail
log.error("" + e, e);
// TODO use more generic error message
throw WSNServiceHelper.createExperimentNotRunningException(e.getMessage(), e);
}
}
instanceCache.put(wsnInstanceHash, federatorWSN);
// return the instantiated WSN API instance sessionManagementEndpoint
// URL
return federatorWSN.getWsnEndpointUrl();
}
| public String getInstance(
@WebParam(name = "secretReservationKeys", targetNamespace = "")
List<SecretReservationKey> secretReservationKeys,
@WebParam(name = "controller", targetNamespace = "")
String controller)
throws ExperimentNotRunningException_Exception, UnknownReservationIdException_Exception {
preconditions.checkGetInstanceArguments(secretReservationKeys, controller);
final String wsnInstanceHash = SessionManagementHelper.calculateWSNInstanceHash(secretReservationKeys);
// check if instance already exists and return it if that's the case
FederatorWSN existingWSNFederatorInstance = instanceCache.get(wsnInstanceHash);
if (existingWSNFederatorInstance != null) {
String msg = "Found existing federating WSN API instance for secretReservationKeys {} with "
+ "wsnInstanceHash {}. Returning its' sessionManagementEndpoint URL: {}";
log.debug(msg, new Object[]{
secretReservationKeys, wsnInstanceHash,
existingWSNFederatorInstance.getWsnEndpointUrl()
}
);
log.debug("Adding controller to the set of controllers: {}", controller);
existingWSNFederatorInstance.addController(controller);
return existingWSNFederatorInstance.getWsnEndpointUrl();
}
// create a WSN API instance under a generated secret URL and remember
// to which set of secret URLs of federated
// WSN API instances it maps
String wsnEndpointUrl = endpointUrlBase + secureIdGenerator.getNextId() + "/wsn";
String controllerEndpointUrl = endpointUrlBase + secureIdGenerator.getNextId() + "/controller";
FederatorWSN federatorWSN = new FederatorWSN(wsnEndpointUrl, controllerEndpointUrl);
try {
federatorWSN.start();
// add controller to set of upstream controllers so that output is
// sent upwards
federatorWSN.addController(controller);
} catch (Exception e) {
// TODO throw generic but declared exception
throw WSNServiceHelper
.createExperimentNotRunningException("The federator service could not be started.", e);
}
// delegate calls to the relevant federated Session Management API
// endpoints (fork)
final List<Future<GetInstanceCallable.Result>> futures = new ArrayList<Future<GetInstanceCallable.Result>>();
final Map<String, List<SecretReservationKey>> serviceMapping = getServiceMapping(secretReservationKeys);
for (Map.Entry<String, List<SecretReservationKey>> entry : serviceMapping.entrySet()) {
String sessionManagementEndpointUrl = entry.getKey();
GetInstanceCallable getInstanceCallable = new GetInstanceCallable(
sessionManagementEndpointUrl, entry.getValue(), controllerEndpointUrl
);
log.debug("Calling getInstance on {}", entry.getKey());
futures.add(executorService.submit(getInstanceCallable));
}
// collect call results (join)
for (Future<GetInstanceCallable.Result> future : futures) {
try {
GetInstanceCallable.Result result = future.get();
Set<String> federatedUrnPrefixSet = convertToUrnPrefixSet(result.secretReservationKey);
federatorWSN.addFederatedWSNEndpoint(result.federatedWSNInstanceEndpointUrl, federatedUrnPrefixSet);
} catch (InterruptedException e) {
// if one delegate call fails also fail
log.error("" + e, e);
// TODO use more generic error message
throw WSNServiceHelper.createExperimentNotRunningException(e.getMessage(), e);
} catch (ExecutionException e) {
// if one delegate call fails also fail
log.error("" + e, e);
// TODO use more generic error message
throw WSNServiceHelper.createExperimentNotRunningException(e.getMessage(), e);
}
}
instanceCache.put(wsnInstanceHash, federatorWSN);
// return the instantiated WSN API instance sessionManagementEndpoint
// URL
return federatorWSN.getWsnEndpointUrl();
}
|
diff --git a/drools-analytics/src/test/java/org/drools/analytics/AnalyzerTest.java b/drools-analytics/src/test/java/org/drools/analytics/AnalyzerTest.java
index 2eb197c1a..05dbc38d6 100644
--- a/drools-analytics/src/test/java/org/drools/analytics/AnalyzerTest.java
+++ b/drools-analytics/src/test/java/org/drools/analytics/AnalyzerTest.java
@@ -1,77 +1,78 @@
package org.drools.analytics;
import java.io.InputStreamReader;
import org.drools.RuleBase;
import org.drools.analytics.dao.AnalyticsResult;
import org.drools.analytics.report.components.AnalyticsMessageBase;
import org.drools.compiler.DrlParser;
import org.drools.lang.descr.PackageDescr;
import junit.framework.TestCase;
public class AnalyzerTest extends TestCase {
public void testAnalyzer() throws Exception {
Analyzer anal = new Analyzer();
DrlParser p = new DrlParser();
InputStreamReader reader = new InputStreamReader(this.getClass().getResourceAsStream("Misc3.drl"));
PackageDescr pkg = p.parse(reader);
assertFalse(p.hasErrors());
anal.addPackageDescr(pkg);
anal.fireAnalysis();
AnalyticsResult result = anal.getResult();
assertNotNull(result);
assertEquals(0, result.getBySeverity(AnalyticsMessageBase.Severity.ERROR).size());
assertEquals(17, result.getBySeverity(AnalyticsMessageBase.Severity.WARNING).size());
assertEquals(1, result.getBySeverity(AnalyticsMessageBase.Severity.NOTE).size());
//check it again
anal = new Analyzer();
p = new DrlParser();
reader = new InputStreamReader(this.getClass().getResourceAsStream("Misc3.drl"));
pkg = p.parse(reader);
assertFalse(p.hasErrors());
anal.addPackageDescr(pkg);
anal.fireAnalysis();
result = anal.getResult();
assertNotNull(result);
assertEquals(0, result.getBySeverity(AnalyticsMessageBase.Severity.ERROR).size());
+ // These row has a problem
assertEquals( 17, result.getBySeverity(AnalyticsMessageBase.Severity.WARNING).size());
assertEquals(1, result.getBySeverity(AnalyticsMessageBase.Severity.NOTE).size());
}
public void testCacheKnowledgeBase() throws Exception {
Analyzer anal = new Analyzer();
DrlParser p = new DrlParser();
InputStreamReader reader = new InputStreamReader(this.getClass().getResourceAsStream("Misc3.drl"));
PackageDescr pkg = p.parse(reader);
assertFalse(p.hasErrors());
anal.addPackageDescr(pkg);
anal.fireAnalysis();
RuleBase original = Analyzer.analysisKnowledgeBase;
Analyzer anal2 = new Analyzer();
assertSame(original, Analyzer.analysisKnowledgeBase);
anal2.reloadAnalysisKnowledgeBase();
assertNotSame(original, Analyzer.analysisKnowledgeBase);
}
}
| true | true | public void testAnalyzer() throws Exception {
Analyzer anal = new Analyzer();
DrlParser p = new DrlParser();
InputStreamReader reader = new InputStreamReader(this.getClass().getResourceAsStream("Misc3.drl"));
PackageDescr pkg = p.parse(reader);
assertFalse(p.hasErrors());
anal.addPackageDescr(pkg);
anal.fireAnalysis();
AnalyticsResult result = anal.getResult();
assertNotNull(result);
assertEquals(0, result.getBySeverity(AnalyticsMessageBase.Severity.ERROR).size());
assertEquals(17, result.getBySeverity(AnalyticsMessageBase.Severity.WARNING).size());
assertEquals(1, result.getBySeverity(AnalyticsMessageBase.Severity.NOTE).size());
//check it again
anal = new Analyzer();
p = new DrlParser();
reader = new InputStreamReader(this.getClass().getResourceAsStream("Misc3.drl"));
pkg = p.parse(reader);
assertFalse(p.hasErrors());
anal.addPackageDescr(pkg);
anal.fireAnalysis();
result = anal.getResult();
assertNotNull(result);
assertEquals(0, result.getBySeverity(AnalyticsMessageBase.Severity.ERROR).size());
assertEquals( 17, result.getBySeverity(AnalyticsMessageBase.Severity.WARNING).size());
assertEquals(1, result.getBySeverity(AnalyticsMessageBase.Severity.NOTE).size());
}
| public void testAnalyzer() throws Exception {
Analyzer anal = new Analyzer();
DrlParser p = new DrlParser();
InputStreamReader reader = new InputStreamReader(this.getClass().getResourceAsStream("Misc3.drl"));
PackageDescr pkg = p.parse(reader);
assertFalse(p.hasErrors());
anal.addPackageDescr(pkg);
anal.fireAnalysis();
AnalyticsResult result = anal.getResult();
assertNotNull(result);
assertEquals(0, result.getBySeverity(AnalyticsMessageBase.Severity.ERROR).size());
assertEquals(17, result.getBySeverity(AnalyticsMessageBase.Severity.WARNING).size());
assertEquals(1, result.getBySeverity(AnalyticsMessageBase.Severity.NOTE).size());
//check it again
anal = new Analyzer();
p = new DrlParser();
reader = new InputStreamReader(this.getClass().getResourceAsStream("Misc3.drl"));
pkg = p.parse(reader);
assertFalse(p.hasErrors());
anal.addPackageDescr(pkg);
anal.fireAnalysis();
result = anal.getResult();
assertNotNull(result);
assertEquals(0, result.getBySeverity(AnalyticsMessageBase.Severity.ERROR).size());
// These row has a problem
assertEquals( 17, result.getBySeverity(AnalyticsMessageBase.Severity.WARNING).size());
assertEquals(1, result.getBySeverity(AnalyticsMessageBase.Severity.NOTE).size());
}
|
diff --git a/onebusaway-transit-data-federation/src/main/java/org/onebusaway/transit_data_federation/impl/transit_graph/BlockConfigurationEntryImpl.java b/onebusaway-transit-data-federation/src/main/java/org/onebusaway/transit_data_federation/impl/transit_graph/BlockConfigurationEntryImpl.java
index 1f6460e6..af171ae8 100644
--- a/onebusaway-transit-data-federation/src/main/java/org/onebusaway/transit_data_federation/impl/transit_graph/BlockConfigurationEntryImpl.java
+++ b/onebusaway-transit-data-federation/src/main/java/org/onebusaway/transit_data_federation/impl/transit_graph/BlockConfigurationEntryImpl.java
@@ -1,371 +1,372 @@
/**
* Copyright (C) 2011 Brian Ferris <[email protected]>
* Copyright (C) 2011 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 org.onebusaway.transit_data_federation.impl.transit_graph;
import java.io.Serializable;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
import org.onebusaway.transit_data_federation.services.transit_graph.BlockConfigurationEntry;
import org.onebusaway.transit_data_federation.services.transit_graph.BlockEntry;
import org.onebusaway.transit_data_federation.services.transit_graph.BlockStopTimeEntry;
import org.onebusaway.transit_data_federation.services.transit_graph.BlockTripEntry;
import org.onebusaway.transit_data_federation.services.transit_graph.FrequencyEntry;
import org.onebusaway.transit_data_federation.services.transit_graph.ServiceIdActivation;
import org.onebusaway.transit_data_federation.services.transit_graph.StopTimeEntry;
import org.onebusaway.transit_data_federation.services.transit_graph.TripEntry;
public class BlockConfigurationEntryImpl implements BlockConfigurationEntry,
Serializable {
private static final long serialVersionUID = 1L;
private final BlockEntry block;
private final ServiceIdActivation serviceIds;
private final List<BlockTripEntry> trips;
private final double totalBlockDistance;
private final BlockStopTimeList blockStopTimes = new BlockStopTimeList();
private final int[] tripIndices;
private final int[] accumulatedStopTimeIndices;
/**
* We make this one field non-final because it makes it easier to add
* Frequency information after the fact.
*/
private List<FrequencyEntry> frequencies;
private BlockConfigurationEntryImpl(Builder builder) {
this.block = builder.block;
this.serviceIds = builder.serviceIds;
this.trips = builder.computeBlockTrips(this);
this.frequencies = builder.frequencies;
this.totalBlockDistance = builder.computeTotalBlockDistance();
this.tripIndices = builder.computeTripIndices();
this.accumulatedStopTimeIndices = builder.computeAccumulatedStopTimeIndices();
}
public static Builder builder() {
return new Builder();
}
public void setFrequencies(List<FrequencyEntry> frequencies) {
this.frequencies = frequencies;
}
/****
* {@link BlockConfigurationEntry} Interface
****/
@Override
public BlockEntry getBlock() {
return block;
}
@Override
public ServiceIdActivation getServiceIds() {
return serviceIds;
}
@Override
public List<BlockTripEntry> getTrips() {
return trips;
}
@Override
public List<FrequencyEntry> getFrequencies() {
return frequencies;
}
@Override
public List<BlockStopTimeEntry> getStopTimes() {
return blockStopTimes;
}
@Override
public double getTotalBlockDistance() {
return totalBlockDistance;
}
@Override
public int getArrivalTimeForIndex(int index) {
StopTimeEntry stopTime = getStopTimeForIndex(index);
return stopTime.getArrivalTime();
}
@Override
public int getDepartureTimeForIndex(int index) {
StopTimeEntry stopTime = getStopTimeForIndex(index);
return stopTime.getDepartureTime();
}
@Override
public double getDistanceAlongBlockForIndex(int index) {
int tripIndex = tripIndices[index];
BlockTripEntry blockTrip = trips.get(tripIndex);
TripEntry trip = blockTrip.getTrip();
List<StopTimeEntry> stopTimes = trip.getStopTimes();
int stopTimeIndex = index - accumulatedStopTimeIndices[tripIndex];
StopTimeEntry stopTime = stopTimes.get(stopTimeIndex);
return blockTrip.getDistanceAlongBlock() + stopTime.getShapeDistTraveled();
}
@Override
public String toString() {
return "BlockConfiguration [block=" + block.getId() + " serviceIds="
+ serviceIds + "]";
}
public static class Builder {
private BlockEntry block;
private ServiceIdActivation serviceIds;
private List<TripEntry> trips;
private List<FrequencyEntry> frequencies;
private double[] tripGapDistances;
private Builder() {
}
public void setBlock(BlockEntry block) {
this.block = block;
}
public void setServiceIds(ServiceIdActivation serviceIds) {
this.serviceIds = serviceIds;
}
public List<TripEntry> getTrips() {
return trips;
}
public void setTrips(List<TripEntry> trips) {
this.trips = trips;
}
public List<FrequencyEntry> getFrequencies() {
return frequencies;
}
public void setFrequencies(List<FrequencyEntry> frequencies) {
this.frequencies = frequencies;
}
public void setTripGapDistances(double[] tripGapDistances) {
this.tripGapDistances = tripGapDistances;
}
public BlockConfigurationEntry create() {
return new BlockConfigurationEntryImpl(this);
}
private double computeTotalBlockDistance() {
double distance = 0;
for (int i = 0; i < trips.size(); i++) {
TripEntry trip = trips.get(i);
distance += trip.getTotalTripDistance() + tripGapDistances[i];
}
return distance;
}
private int[] computeTripIndices() {
int n = 0;
for (TripEntry trip : trips)
n += trip.getStopTimes().size();
int[] tripIndices = new int[n];
int index = 0;
for (int tripIndex = 0; tripIndex < trips.size(); tripIndex++) {
TripEntry trip = trips.get(tripIndex);
for (int i = 0; i < trip.getStopTimes().size(); i++)
tripIndices[index++] = tripIndex;
}
return tripIndices;
}
private int[] computeAccumulatedStopTimeIndices() {
int[] accumulatedStopTimeIndices = new int[trips.size()];
int n = 0;
for (int i = 0; i < trips.size(); i++) {
accumulatedStopTimeIndices[i] = n;
n += trips.get(i).getStopTimes().size();
}
return accumulatedStopTimeIndices;
}
private List<BlockTripEntry> computeBlockTrips(
BlockConfigurationEntryImpl blockConfiguration) {
ArrayList<BlockTripEntry> blockTrips = new ArrayList<BlockTripEntry>();
short accumulatedStopTimeIndex = 0;
int accumulatedSlackTime = 0;
double distanceAlongBlock = 0;
BlockTripEntryImpl prevTrip = null;
StopTimeEntry prevTripStopTime = null;
double prevTripAvgVelocity = 0;
for (short i = 0; i < trips.size(); i++) {
TripEntry tripEntry = trips.get(i);
List<StopTimeEntry> stopTimes = tripEntry.getStopTimes();
/**
* See if there is any slack time in the schedule in the transition
* between the two trips. We take the distance between the last stop of
* the previous trip and the first stop of the next trip, along with the
* average travel velocity from the previous trip, and compute the
* estimated travel time. Any time that's left over is slack.
*/
if (prevTripStopTime != null) {
StopTimeEntry nextStopTime = stopTimes.get(0);
int slackTime = nextStopTime.getArrivalTime()
- prevTripStopTime.getDepartureTime();
double distance = (distanceAlongBlock - (prevTrip.getDistanceAlongBlock() + prevTripStopTime.getShapeDistTraveled()))
+ nextStopTime.getShapeDistTraveled();
if (prevTripAvgVelocity > 0) {
int timeToTravel = (int) (distance / prevTripAvgVelocity);
slackTime -= Math.min(timeToTravel, slackTime);
}
accumulatedSlackTime += slackTime;
}
BlockTripEntryImpl blockTripEntry = new BlockTripEntryImpl();
blockTripEntry.setTrip(tripEntry);
blockTripEntry.setBlockConfiguration(blockConfiguration);
blockTripEntry.setSequence(i);
blockTripEntry.setAccumulatedStopTimeIndex(accumulatedStopTimeIndex);
blockTripEntry.setAccumulatedSlackTime(accumulatedSlackTime);
blockTripEntry.setDistanceAlongBlock(distanceAlongBlock);
if (prevTrip != null) {
prevTrip.setNextTrip(blockTripEntry);
blockTripEntry.setPreviousTrip(prevTrip);
}
blockTrips.add(blockTripEntry);
accumulatedStopTimeIndex += stopTimes.size();
if (accumulatedSlackTime < 0)
throw new IllegalStateException(
"I didn't think this was possible, but the number of stop times in a particular block exceeded "
+ Short.MAX_VALUE
- + " causing a wrap-around in the accumulated stop time index");
+ + " causing a wrap-around in the accumulated stop time index: blockId="
+ + blockConfiguration.getBlock().getId());
for (StopTimeEntry stopTime : stopTimes)
accumulatedSlackTime += stopTime.getSlackTime();
prevTripAvgVelocity = computeAverageTripTravelVelocity(stopTimes);
distanceAlongBlock += tripEntry.getTotalTripDistance()
+ tripGapDistances[i];
prevTrip = blockTripEntry;
prevTripStopTime = stopTimes.get(stopTimes.size() - 1);
}
blockTrips.trimToSize();
return blockTrips;
}
private double computeAverageTripTravelVelocity(
List<StopTimeEntry> stopTimes) {
int accumulatedTravelTime = 0;
double accumulatedTravelDistance = 0;
StopTimeEntry prevStopTime = null;
for (StopTimeEntry stopTime : stopTimes) {
if (prevStopTime != null) {
accumulatedTravelTime += stopTime.getArrivalTime()
- prevStopTime.getDepartureTime();
accumulatedTravelDistance += stopTime.getShapeDistTraveled()
- prevStopTime.getShapeDistTraveled();
}
prevStopTime = stopTime;
}
if (accumulatedTravelTime == 0)
return 0;
return accumulatedTravelDistance / accumulatedTravelTime;
}
}
/*****
* Private Methods
****/
private StopTimeEntry getStopTimeForIndex(int index) {
int tripIndex = tripIndices[index];
BlockTripEntry blockTrip = trips.get(tripIndex);
TripEntry trip = blockTrip.getTrip();
List<StopTimeEntry> stopTimes = trip.getStopTimes();
int stopTimeIndex = index - accumulatedStopTimeIndices[tripIndex];
StopTimeEntry stopTime = stopTimes.get(stopTimeIndex);
return stopTime;
}
private class BlockStopTimeList extends AbstractList<BlockStopTimeEntry>
implements Serializable {
private static final long serialVersionUID = 1L;
@Override
public int size() {
return tripIndices.length;
}
@Override
public BlockStopTimeEntry get(int index) {
int tripIndex = tripIndices[index];
BlockTripEntry blockTrip = trips.get(tripIndex);
TripEntry trip = blockTrip.getTrip();
List<StopTimeEntry> stopTimes = trip.getStopTimes();
int stopTimeIndex = index - accumulatedStopTimeIndices[tripIndex];
StopTimeEntry stopTime = stopTimes.get(stopTimeIndex);
boolean hasNextStop = index + 1 < tripIndices.length;
return new BlockStopTimeEntryImpl(stopTime, index, blockTrip, hasNextStop);
}
}
}
| true | true | private List<BlockTripEntry> computeBlockTrips(
BlockConfigurationEntryImpl blockConfiguration) {
ArrayList<BlockTripEntry> blockTrips = new ArrayList<BlockTripEntry>();
short accumulatedStopTimeIndex = 0;
int accumulatedSlackTime = 0;
double distanceAlongBlock = 0;
BlockTripEntryImpl prevTrip = null;
StopTimeEntry prevTripStopTime = null;
double prevTripAvgVelocity = 0;
for (short i = 0; i < trips.size(); i++) {
TripEntry tripEntry = trips.get(i);
List<StopTimeEntry> stopTimes = tripEntry.getStopTimes();
/**
* See if there is any slack time in the schedule in the transition
* between the two trips. We take the distance between the last stop of
* the previous trip and the first stop of the next trip, along with the
* average travel velocity from the previous trip, and compute the
* estimated travel time. Any time that's left over is slack.
*/
if (prevTripStopTime != null) {
StopTimeEntry nextStopTime = stopTimes.get(0);
int slackTime = nextStopTime.getArrivalTime()
- prevTripStopTime.getDepartureTime();
double distance = (distanceAlongBlock - (prevTrip.getDistanceAlongBlock() + prevTripStopTime.getShapeDistTraveled()))
+ nextStopTime.getShapeDistTraveled();
if (prevTripAvgVelocity > 0) {
int timeToTravel = (int) (distance / prevTripAvgVelocity);
slackTime -= Math.min(timeToTravel, slackTime);
}
accumulatedSlackTime += slackTime;
}
BlockTripEntryImpl blockTripEntry = new BlockTripEntryImpl();
blockTripEntry.setTrip(tripEntry);
blockTripEntry.setBlockConfiguration(blockConfiguration);
blockTripEntry.setSequence(i);
blockTripEntry.setAccumulatedStopTimeIndex(accumulatedStopTimeIndex);
blockTripEntry.setAccumulatedSlackTime(accumulatedSlackTime);
blockTripEntry.setDistanceAlongBlock(distanceAlongBlock);
if (prevTrip != null) {
prevTrip.setNextTrip(blockTripEntry);
blockTripEntry.setPreviousTrip(prevTrip);
}
blockTrips.add(blockTripEntry);
accumulatedStopTimeIndex += stopTimes.size();
if (accumulatedSlackTime < 0)
throw new IllegalStateException(
"I didn't think this was possible, but the number of stop times in a particular block exceeded "
+ Short.MAX_VALUE
+ " causing a wrap-around in the accumulated stop time index");
for (StopTimeEntry stopTime : stopTimes)
accumulatedSlackTime += stopTime.getSlackTime();
prevTripAvgVelocity = computeAverageTripTravelVelocity(stopTimes);
distanceAlongBlock += tripEntry.getTotalTripDistance()
+ tripGapDistances[i];
prevTrip = blockTripEntry;
prevTripStopTime = stopTimes.get(stopTimes.size() - 1);
}
blockTrips.trimToSize();
return blockTrips;
}
| private List<BlockTripEntry> computeBlockTrips(
BlockConfigurationEntryImpl blockConfiguration) {
ArrayList<BlockTripEntry> blockTrips = new ArrayList<BlockTripEntry>();
short accumulatedStopTimeIndex = 0;
int accumulatedSlackTime = 0;
double distanceAlongBlock = 0;
BlockTripEntryImpl prevTrip = null;
StopTimeEntry prevTripStopTime = null;
double prevTripAvgVelocity = 0;
for (short i = 0; i < trips.size(); i++) {
TripEntry tripEntry = trips.get(i);
List<StopTimeEntry> stopTimes = tripEntry.getStopTimes();
/**
* See if there is any slack time in the schedule in the transition
* between the two trips. We take the distance between the last stop of
* the previous trip and the first stop of the next trip, along with the
* average travel velocity from the previous trip, and compute the
* estimated travel time. Any time that's left over is slack.
*/
if (prevTripStopTime != null) {
StopTimeEntry nextStopTime = stopTimes.get(0);
int slackTime = nextStopTime.getArrivalTime()
- prevTripStopTime.getDepartureTime();
double distance = (distanceAlongBlock - (prevTrip.getDistanceAlongBlock() + prevTripStopTime.getShapeDistTraveled()))
+ nextStopTime.getShapeDistTraveled();
if (prevTripAvgVelocity > 0) {
int timeToTravel = (int) (distance / prevTripAvgVelocity);
slackTime -= Math.min(timeToTravel, slackTime);
}
accumulatedSlackTime += slackTime;
}
BlockTripEntryImpl blockTripEntry = new BlockTripEntryImpl();
blockTripEntry.setTrip(tripEntry);
blockTripEntry.setBlockConfiguration(blockConfiguration);
blockTripEntry.setSequence(i);
blockTripEntry.setAccumulatedStopTimeIndex(accumulatedStopTimeIndex);
blockTripEntry.setAccumulatedSlackTime(accumulatedSlackTime);
blockTripEntry.setDistanceAlongBlock(distanceAlongBlock);
if (prevTrip != null) {
prevTrip.setNextTrip(blockTripEntry);
blockTripEntry.setPreviousTrip(prevTrip);
}
blockTrips.add(blockTripEntry);
accumulatedStopTimeIndex += stopTimes.size();
if (accumulatedSlackTime < 0)
throw new IllegalStateException(
"I didn't think this was possible, but the number of stop times in a particular block exceeded "
+ Short.MAX_VALUE
+ " causing a wrap-around in the accumulated stop time index: blockId="
+ blockConfiguration.getBlock().getId());
for (StopTimeEntry stopTime : stopTimes)
accumulatedSlackTime += stopTime.getSlackTime();
prevTripAvgVelocity = computeAverageTripTravelVelocity(stopTimes);
distanceAlongBlock += tripEntry.getTotalTripDistance()
+ tripGapDistances[i];
prevTrip = blockTripEntry;
prevTripStopTime = stopTimes.get(stopTimes.size() - 1);
}
blockTrips.trimToSize();
return blockTrips;
}
|
diff --git a/core/src/visad/trunk/Irregular3DSet.java b/core/src/visad/trunk/Irregular3DSet.java
index 3207e405c..e63f62e31 100644
--- a/core/src/visad/trunk/Irregular3DSet.java
+++ b/core/src/visad/trunk/Irregular3DSet.java
@@ -1,2997 +1,3018 @@
//
// Irregular3DSet.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 2002 Bill Hibbard, Curtis Rueden, Tom
Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and
Tommy Jasmin.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA
*/
package visad;
/**
Irregular3DSet represents a finite set of samples of R^3.<P>
No Irregular3DSet with ManifoldDimension = 1. Use
Gridded3DSet with ManifoldDimension = 1 instead.<P>
*/
public class Irregular3DSet extends IrregularSet {
private float LowX, HiX, LowY, HiY, LowZ, HiZ;
/** a 3-D irregular set with null errors, CoordinateSystem
and Units are defaults from type; topology is computed
by the constructor */
public Irregular3DSet(MathType type, float[][] samples)
throws VisADException {
this(type, samples, null, null, null, null, true);
}
/** a 3-D irregular set; samples array is organized
float[3][number_of_samples]; no geometric constraint on
samples; if delan is non-null it defines the topology of
samples (which may have manifold dimension 2 or 3), else
the constructor computes a topology with manifold dimension
3; note that Gridded3DSet can be used for an irregular set
with domain dimension 3 and manifold dimension 1;
coordinate_system and units must be compatible with
defaults for type, or may be null; errors may be null */
public Irregular3DSet(MathType type, float[][] samples,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, Delaunay delan)
throws VisADException {
this(type, samples, coord_sys, units, errors, delan, true);
}
public Irregular3DSet(MathType type, float[][] samples,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, Delaunay delan,
boolean copy) throws VisADException {
/* ManifoldDimension might not be equal to samples.length
if a 2D triangulation has been specified */
super(type, samples, (delan == null) ? samples.length
: delan.Tri[0].length-1,
coord_sys, units, errors, delan, copy);
LowX = Low[0];
HiX = Hi[0];
LowY = Low[1];
HiY = Hi[1];
LowZ = Low[2];
HiZ = Hi[2];
oldToNew = null;
newToOld = null;
}
/** construct Irregular3DSet using sort from existing
Irregular1DSet */
public Irregular3DSet(MathType type, float[][] samples,
int[] new2old, int[] old2new) throws VisADException {
this(type, samples, new2old, old2new, null, null, null, true);
}
/** construct Irregular3DSet using sort from existing
Irregular1DSet */
public Irregular3DSet(MathType type, float[][] samples,
int[] new2old, int[] old2new,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors) throws VisADException {
this(type, samples, new2old, old2new, coord_sys, units, errors, true);
}
public Irregular3DSet(MathType type, float[][] samples,
int[] new2old, int[] old2new,
CoordinateSystem coord_sys, Unit[] units,
ErrorEstimate[] errors, boolean copy)
throws VisADException {
super(type, samples, 1, coord_sys, units, errors, null, copy);
if (Length != new2old.length || Length != old2new.length) {
throw new SetException("Irregular3DSet: sort lengths do not match");
}
newToOld = new int[Length];
oldToNew = new int[Length];
System.arraycopy(new2old, 0, newToOld, 0, Length);
System.arraycopy(old2new, 0, oldToNew, 0, Length);
LowX = Low[0];
HiX = Hi[0];
LowY = Low[1];
HiY = Hi[1];
LowZ = Low[2];
HiZ = Hi[2];
Delan = null;
}
public Set makeSpatial(SetType type, float[][] samples) throws VisADException {
if (samples.length == 3) {
if (ManifoldDimension == 1) {
return new Irregular3DSet(type, samples, newToOld, oldToNew,
null, null, null, false);
}
else {
if (Delan.Tri == null || Delan.Tri.length == 0) return null;
return new Irregular3DSet(type, samples, null, null, null,
Delan, false);
}
}
else {
throw new SetException("Irregular3DSet.makeSpatial: bad samples length");
}
}
/** convert an array of 1-D indices to an array of values in
R^DomainDimension */
public float[][] indexToValue(int[] index) throws VisADException {
float[][] value = new float[3][index.length];
for (int i=0; i<index.length; i++) {
if ( (index[i] >= 0) && (index[i] < Length) ) {
value[0][i] = Samples[0][index[i]];
value[1][i] = Samples[1][index[i]];
value[2][i] = Samples[2][index[i]];
}
else {
value[0][i] = value[1][i] = value[2][i] = Float.NaN;
}
}
return value;
}
/** valueToTri returns an array of containing triangles given
an array of points in R^DomainDimension */
public int[] valueToTri(float[][] value) throws VisADException {
if (ManifoldDimension != 3) {
throw new SetException("Irregular3DSet.valueToTri: " +
"ManifoldDimension must be 3, not " +
ManifoldDimension);
}
int length = value[0].length;
if (length != value[1].length || length != value[2].length) {
throw new SetException("Irregular3DSet.valueToTri: lengths " +
"don't match");
}
boolean nonConvex = Delan.getNonConvex();
float[] PA = new float[3];
float[] PB = new float[3];
float[] PC = new float[3];
float[] PD = new float[3];
float[] BAxCB = new float[3];
float[] CBxDC = new float[3];
float[] DCxAD = new float[3];
float[] ADxBA = new float[3];
float sum_BAxCB;
float sum_CBxDC;
float sum_DCxAD;
float sum_ADxBA;
boolean[] fail_tri = new boolean[Delan.Tri.length];
for ( int kk = 0; kk < fail_tri.length; kk++ ) {
fail_tri[kk] = false;
}
int [] fail_list = null;
int fail_length = 0;
int[] tri = new int[length];
int curtri = 0;
// System.out.println("length = " + length + " Delan.Tri.length = " +
// Delan.Tri.length);
for (int i=0; i<length; i++) {
// System.out.println("\nvalue["+i+"] = ("+value[0][i]+", "+value[1][i]+", "+value[2][i]+")");
// Return -1 if iteration loop fails
tri[i] = -1;
boolean foundit = false;
if (curtri < 0) curtri = 0;
int itnum;
for (itnum=0; (itnum<Delan.Tri.length) && !foundit; itnum++) {
// define data
int t0 = Delan.Tri[curtri][0];
int t1 = Delan.Tri[curtri][1];
int t2 = Delan.Tri[curtri][2];
int t3 = Delan.Tri[curtri][3];
float Ax = Samples[0][t0];
float Ay = Samples[1][t0];
float Az = Samples[2][t0];
float Bx = Samples[0][t1];
float By = Samples[1][t1];
float Bz = Samples[2][t1];
float Cx = Samples[0][t2];
float Cy = Samples[1][t2];
float Cz = Samples[2][t2];
float Dx = Samples[0][t3];
float Dy = Samples[1][t3];
float Dz = Samples[2][t3];
float Px = value[0][i];
float Py = value[1][i];
float Pz = value[2][i];
PA[0] = Px-Ax;
PA[1] = Py-Ay;
PA[2] = Pz-Az;
PB[0] = Px-Bx;
PB[1] = Py-By;
PB[2] = Pz-Bz;
PC[0] = Px-Cx;
PC[1] = Py-Cy;
PC[2] = Pz-Cz;
PD[0] = Px-Dx;
PD[1] = Py-Dy;
PD[2] = Pz-Dz;
BAxCB[0] = (By-Ay)*(Cz-Bz)-(Bz-Az)*(Cy-By);
BAxCB[1] = (Bz-Az)*(Cx-Bx)-(Bx-Ax)*(Cz-Bz);
BAxCB[2] = (Bx-Ax)*(Cy-By)-(By-Ay)*(Cx-Bx);
sum_BAxCB = Math.abs(BAxCB[0]) + Math.abs(BAxCB[1]) +
Math.abs(BAxCB[2]);
CBxDC[0] = (Cy-By)*(Dz-Cz)-(Cz-Bz)*(Dy-Cy);
CBxDC[1] = (Cz-Bz)*(Dx-Cx)-(Cx-Bx)*(Dz-Cz);
CBxDC[2] = (Cx-Bx)*(Dy-Cy)-(Cy-By)*(Dx-Cx);
sum_CBxDC = Math.abs(CBxDC[0]) + Math.abs(CBxDC[1]) +
Math.abs(CBxDC[2]);
DCxAD[0] = (Dy-Cy)*(Az-Dz)-(Dz-Cz)*(Ay-Dy);
DCxAD[1] = (Dz-Cz)*(Ax-Dx)-(Dx-Cx)*(Az-Dz);
DCxAD[2] = (Dx-Cx)*(Ay-Dy)-(Dy-Cy)*(Ax-Dx);
sum_DCxAD = Math.abs(DCxAD[0]) + Math.abs(DCxAD[1]) +
Math.abs(DCxAD[2]);
ADxBA[0] = (Ay-Dy)*(Bz-Az)-(Az-Dz)*(By-Ay);
ADxBA[1] = (Az-Dz)*(Bx-Ax)-(Ax-Dx)*(Bz-Az);
ADxBA[2] = (Ax-Dx)*(By-Ay)-(Ay-Dy)*(Bx-Ax);
sum_ADxBA = Math.abs(ADxBA[0]) + Math.abs(ADxBA[1]) +
Math.abs(ADxBA[2]);
// test whether point is contained in current triangle
float tval1 = BAxCB[0]*PA[0] + BAxCB[1]*PA[1] + BAxCB[2]*PA[2];
float tval2 = CBxDC[0]*PB[0] + CBxDC[1]*PB[1] + CBxDC[2]*PB[2];
float tval3 = DCxAD[0]*PC[0] + DCxAD[1]*PC[1] + DCxAD[2]*PC[2];
float tval4 = ADxBA[0]*PD[0] + ADxBA[1]*PD[1] + ADxBA[2]*PD[2];
// System.out.println("Px-Ax: "+(Px-Ax)+" Py-Ay: "+(Py-Ay)+" Pz-Az: "+(Pz-Az));
// System.out.println("Px-Bx: "+(Px-Bx)+" Py-By: "+(Py-By)+" Pz-Bz: "+(Pz-Bz));
// System.out.println("Px-Cx: "+(Px-Cx)+" Py-Cy: "+(Py-Cy)+" Pz-Cz: "+(Pz-Cz));
// System.out.println("Px-Dx: "+(Px-Dx)+" Py-Dy: "+(Py-Dy)+" Pz-Dz: "+(Pz-Dz));
// System.out.println("sum_BAxCB: "+sum_BAxCB+" sum_CBxDC: "+sum_CBxDC+" sum_DCxAD "+sum_DCxAD+" sum_ADxBA "+sum_ADxBA);
// System.out.println("curtri: "+curtri+" tval1: "+tval1+" tval2: "+tval2+" tval3: "+tval3+" tval4: "+tval4);
boolean test1 = ((tval1 == 0.0f) || ( (tval1 > 0) == (
BAxCB[0]*(Dx-Ax)
+ BAxCB[1]*(Dy-Ay)
+ BAxCB[2]*(Dz-Az) > 0) )) && (sum_BAxCB != 0);
boolean test2 = ((tval2 == 0.0f) || ( (tval2 > 0) == (
CBxDC[0]*(Ax-Bx)
+ CBxDC[1]*(Ay-By)
+ CBxDC[2]*(Az-Bz) > 0) )) && (sum_CBxDC != 0);
boolean test3 = ((tval3 == 0.0f) || ( (tval3 > 0) == (
DCxAD[0]*(Bx-Cx)
+ DCxAD[1]*(By-Cy)
+ DCxAD[2]*(Bz-Cz) > 0) )) && (sum_DCxAD != 0);
boolean test4 = ((tval4 == 0.0f) || ( (tval4 > 0) == (
ADxBA[0]*(Cx-Dx)
+ ADxBA[1]*(Cy-Dy)
+ ADxBA[2]*(Cz-Dz) > 0) )) && (sum_ADxBA != 0);
// System.out.println("i: "+i+" curtri: "+curtri+" test1: "+test1+" test2: "+test2+" test3: "+test3+" test4: "+test4);
// figure out which triangle to go to next
if (!test1 || !test2 || !test3 || !test4) {
// record failed tri
fail_tri[curtri] = true;
// add to list of failed tris for efficient reset
if (fail_list == null) {
fail_list = new int[4];
fail_length = 0;
}
else if (fail_length >= fail_list.length) {
int[] new_fail_list = new int[2 * fail_list.length];
System.arraycopy(fail_list, 0, new_fail_list, 0, fail_list.length);
fail_list = new_fail_list;
}
fail_list[fail_length] = curtri;
fail_length++;
int t = -1;
boolean fail = true;
if (!test1 && fail) {
t = Delan.Walk[curtri][0];
if (t != -1) fail = fail_tri[t];
}
if (!test2 && fail) {
t = Delan.Walk[curtri][1];
if (t != -1) fail = fail_tri[t];
}
if (!test3 && fail) {
t = Delan.Walk[curtri][2];
if (t != -1) fail = fail_tri[t];
}
if (!test4 && fail) {
t = Delan.Walk[curtri][3];
if (t != -1) fail = fail_tri[t];
}
if (!fail || t == -1) {
curtri = t;
}
if (fail) curtri = -1;
if (nonConvex) {
// to deal with non-convex Set, but very slow
if (curtri == -1) {
for (int jj=0; jj<fail_tri.length; jj++) {
if (!fail_tri[jj]) {
curtri = jj;
break;
}
}
}
}
}
else {
foundit = true;
}
// Return -1 if outside of the convex hull
if (curtri < 0) {
// System.out.println("outside of the convex hull " + i);
foundit = true;
}
if (foundit) {
tri[i] = curtri;
}
} // end for (itnum=0; (itnum<Delan.Tri.length) && !foundit; itnum++)
// reset all fail_tri to false
if (fail_list != null) {
for (int ii=0; ii<fail_length; ii++) {
fail_tri[fail_list[ii]] = false;
}
fail_list = null;
}
} // end for (int i=0; i<length; i++)
return tri;
}
/** convert an array of values in R^DomainDimension to an array of
1-D indices */
public int[] valueToIndex(float[][] value) throws VisADException {
if (value.length < DomainDimension) {
throw new SetException("Irregular3DSet.valueToIndex: value dimension " +
value.length + " not equal to Domain dimension " +
DomainDimension);
}
int[] tri = valueToTri(value);
int[] index = new int[tri.length];
for (int i=0; i<tri.length; i++) {
if (tri[i] < 0) {
index[i] = -1;
}
else {
// current values
float x = value[0][i];
float y = value[1][i];
float z = value[2][i];
// triangle indices
int t = tri[i];
int t0 = Delan.Tri[t][0];
int t1 = Delan.Tri[t][1];
int t2 = Delan.Tri[t][2];
int t3 = Delan.Tri[t][3];
// partial distances
float D00 = Samples[0][t0] - x;
float D01 = Samples[1][t0] - y;
float D02 = Samples[2][t0] - z;
float D10 = Samples[0][t1] - x;
float D11 = Samples[1][t1] - y;
float D12 = Samples[2][t1] - z;
float D20 = Samples[0][t2] - x;
float D21 = Samples[1][t2] - y;
float D22 = Samples[2][t2] - z;
float D30 = Samples[0][t3] - x;
float D31 = Samples[1][t3] - y;
float D32 = Samples[2][t3] - z;
// distances squared
float Dsq0 = D00*D00 + D01*D01 + D02*D02;
float Dsq1 = D10*D10 + D11*D11 + D12*D12;
float Dsq2 = D20*D20 + D21*D21 + D22*D22;
float Dsq3 = D30*D30 + D31*D31 + D32*D32;
// find the minimum distance
float min = Math.min(Dsq0, Dsq1);
min = Math.min(min, Dsq2);
min = Math.min(min, Dsq3);
if (min == Dsq0) index[i] = t0;
else if (min == Dsq1) index[i] = t1;
else if (min == Dsq2) index[i] = t2;
else index[i] = t3;
}
}
return index;
}
/** for each of an array of values in R^DomainDimension, compute an array
of 1-D indices and an array of weights, to be used for interpolation;
indices[i] and weights[i] are null if no interpolation is possible */
public void valueToInterp(float[][] value, int[][] indices,
float[][] weights) throws VisADException {
if (value.length < DomainDimension) {
throw new SetException("Irregular3DSet.valueToInterp: value dimension " +
value.length + " not equal to Domain dimension " +
DomainDimension);
}
int length = value[0].length; // number of values
if ( (indices.length < length) || (weights.length < length) ) {
throw new SetException("Irregular3DSet.valueToInterp:"
+" lengths don't match");
}
// System.out.println("value: "+value[0][0]+", "+value[1][0]+", "+value[2][0]);
int[] tri = valueToTri(value);
for (int i=0; i<tri.length; i++) {
if (tri[i] < 0) {
indices[i] = null;
weights[i] = null;
}
else {
// indices and weights sub-arrays
int[] ival = new int[4];
float[] wval = new float[4];
// current values
float x = value[0][i];
float y = value[1][i];
float z = value[2][i];
// triangle indices
int t = tri[i];
int t0 = Delan.Tri[t][0];
int t1 = Delan.Tri[t][1];
int t2 = Delan.Tri[t][2];
int t3 = Delan.Tri[t][3];
ival[0] = t0;
ival[1] = t1;
ival[2] = t2;
ival[3] = t3;
// triangle vertices
float x0 = Samples[0][t0];
float y0 = Samples[1][t0];
float z0 = Samples[2][t0];
float x1 = Samples[0][t1];
float y1 = Samples[1][t1];
float z1 = Samples[2][t1];
float x2 = Samples[0][t2];
float y2 = Samples[1][t2];
float z2 = Samples[2][t2];
float x3 = Samples[0][t3];
float y3 = Samples[1][t3];
float z3 = Samples[2][t3];
// perpendicular lines
float C0x = (y3-y1)*(z2-z1) - (z3-z1)*(y2-y1);
float C0y = (z3-z1)*(x2-x1) - (x3-x1)*(z2-z1);
float C0z = (x3-x1)*(y2-y1) - (y3-y1)*(x2-x1);
float C1x = (y3-y0)*(z2-z0) - (z3-z0)*(y2-y0);
float C1y = (z3-z0)*(x2-x0) - (x3-x0)*(z2-z0);
float C1z = (x3-x0)*(y2-y0) - (y3-y0)*(x2-x0);
float C2x = (y3-y0)*(z1-z0) - (z3-z0)*(y1-y0);
float C2y = (z3-z0)*(x1-x0) - (x3-x0)*(z1-z0);
float C2z = (x3-x0)*(y1-y0) - (y3-y0)*(x1-x0);
float C3x = (y2-y0)*(z1-z0) - (z2-z0)*(y1-y0);
float C3y = (z2-z0)*(x1-x0) - (x2-x0)*(z1-z0);
float C3z = (x2-x0)*(y1-y0) - (y2-y0)*(x1-x0);
// weights
wval[0] = ( ( (x - x1)*C0x) + ( (y - y1)*C0y) + ( (z - z1)*C0z) )
/ ( ((x0 - x1)*C0x) + ((y0 - y1)*C0y) + ((z0 - z1)*C0z) );
wval[1] = ( ( (x - x0)*C1x) + ( (y - y0)*C1y) + ( (z - z0)*C1z) )
/ ( ((x1 - x0)*C1x) + ((y1 - y0)*C1y) + ((z1 - z0)*C1z) );
wval[2] = ( ( (x - x0)*C2x) + ( (y - y0)*C2y) + ( (z - z0)*C2z) )
/ ( ((x2 - x0)*C2x) + ((y2 - y0)*C2y) + ((z2 - z0)*C2z) );
wval[3] = ( ( (x - x0)*C3x) + ( (y - y0)*C3y) + ( (z - z0)*C3z) )
/ ( ((x3 - x0)*C3x) + ((y3 - y0)*C3y) + ((z3 - z0)*C3z) );
// fill in arrays
indices[i] = ival;
weights[i] = wval;
}
}
}
/** return basic lines in array[0], fill-ins in array[1]
and labels in array[2] */
public VisADGeometryArray[][] makeIsoLines(float[] intervals,
float lowlimit, float highlimit, float base,
float[] fieldValues, byte[][] color_values,
boolean[] swap, boolean dash,
boolean fill, ScalarMap[] smap,
double scale_ratio, double label_size,
float[][][] f_array) throws VisADException {
if (ManifoldDimension != 2) {
throw new DisplayException("Irregular3DSet.makeIsoLines: " +
"ManifoldDimension must be 2, not " +
ManifoldDimension);
}
// WLH 21 May 99
if (intervals == null) return null;
int[][] Tri = Delan.Tri;
float[][] samples = getSamples(false);
int npolygons = Tri.length;
int nvertex = Delan.Vertices.length;
if (npolygons < 1 || nvertex < 3) return null;
// estimate number of vertices
int maxv = 2 * 2 * Length;
int color_length = (color_values != null) ? color_values.length : 0;
byte[][] color_levels = null;
if (color_length > 0) {
if (color_length > 3) color_length = 3; // no alpha for lines
color_levels = new byte[color_length][maxv];
}
float[] vx = new float[maxv];
float[] vy = new float[maxv];
float[] vz = new float[maxv];
int numv = 0;
for (int jj=0; jj<npolygons; jj++) {
int va = Tri[jj][0];
int vb = Tri[jj][1];
int vc = Tri[jj][2];
float ga = fieldValues[va];
// test for missing
if (ga != ga) continue;
float gb = fieldValues[vb];
// test for missing
if (gb != gb) continue;
float gc = fieldValues[vc];
// test for missing
if (gc != gc) continue;
byte[] auxa = null;
byte[] auxb = null;
byte[] auxc = null;
if (color_length > 0) {
auxa = new byte[color_length];
auxb = new byte[color_length];
auxc = new byte[color_length];
for (int i=0; i<color_length; i++) {
auxa[i] = color_values[i][va];
auxb[i] = color_values[i][vb];
auxc[i] = color_values[i][vc];
}
}
float gn = ga < gb ? ga : gb;
gn = gc < gn ? gc : gn;
float gx = ga > gb ? ga : gb;
gx = gc > gx ? gc : gx;
for (int il=0; il<intervals.length; il++) {
float gg = intervals[il];
if (numv+8 >= maxv) {
// allocate more space
maxv = 2 * maxv;
byte[][] t = color_levels;
color_levels = new byte[color_length][maxv];
for (int i=0; i<color_length; i++) {
System.arraycopy(t[i], 0, color_levels[i], 0, numv);
}
float[] tx = vx;
float[] ty = vy;
float[] tz = vz;
vx = new float[maxv];
vy = new float[maxv];
vz = new float[maxv];
System.arraycopy(tx, 0, vx, 0, numv);
System.arraycopy(ty, 0, vy, 0, numv);
System.arraycopy(tz, 0, vz, 0, numv);
}
float gba, gca, gcb;
float ratioba, ratioca, ratiocb;
int ii;
int t;
// make sure gg is within contouring limits
if (gg < gn) continue;
if (gg > gx) break;
if (gg < lowlimit) continue;
if (gg > highlimit) break;
// compute orientation of lines inside box
ii = 0;
if (gg > ga) ii = 1;
if (gg > gb) ii += 2;
if (gg > gc) ii += 4;
if (ii > 3) ii = 7 - ii;
if (ii <= 0) continue;
switch (ii) {
case 1:
gba = gb-ga;
gca = gc-ga;
ratioba = (gg-ga)/gba;
ratioca = (gg-ga)/gca;
if (color_length > 0) {
for (int i=0; i<color_length; i++) {
t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioba * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) );
color_levels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioca * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) );
color_levels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
color_levels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba;
color_levels[i][numv+1] = auxa[i] + (auxc[i]-auxa[i]) * ratioca;
*/
}
}
vx[numv] = samples[0][va] + (samples[0][vb]-samples[0][va]) * ratioba;
vy[numv] = samples[1][va] + (samples[1][vb]-samples[1][va]) * ratioba;
vz[numv] = samples[2][va] + (samples[2][vb]-samples[2][va]) * ratioba;
numv++;
vx[numv] = samples[0][va] + (samples[0][vc]-samples[0][va]) * ratioca;
vy[numv] = samples[1][va] + (samples[1][vc]-samples[1][va]) * ratioca;
vz[numv] = samples[2][va] + (samples[2][vc]-samples[2][va]) * ratioca;
numv++;
break;
case 2:
gba = gb-ga;
gcb = gc-gb;
ratioba = (gg-ga)/gba;
ratiocb = (gg-gb)/gcb;
if (color_length > 0) {
for (int i=0; i<color_length; i++) {
t = (int) ( (1.0f - ratioba) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioba * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) );
color_levels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
t = (int) ( (1.0f - ratiocb) * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) +
ratiocb * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) );
color_levels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
color_levels[i][numv] = auxa[i] + (auxb[i]-auxa[i]) * ratioba;
color_levels[i][numv+1] = auxb[i] + (auxc[i]-auxb[i]) * ratiocb;
*/
}
}
vx[numv] = samples[0][va] + (samples[0][vb]-samples[0][va]) * ratioba;
vy[numv] = samples[1][va] + (samples[1][vb]-samples[1][va]) * ratioba;
vz[numv] = samples[2][va] + (samples[2][vb]-samples[2][va]) * ratioba;
numv++;
vx[numv] = samples[0][vb] + (samples[0][vc]-samples[0][vb]) * ratiocb;
vy[numv] = samples[1][vb] + (samples[1][vc]-samples[1][vb]) * ratiocb;
vz[numv] = samples[2][vb] + (samples[2][vc]-samples[2][vb]) * ratiocb;
numv++;
break;
case 3:
gca = gc-ga;
gcb = gc-gb;
ratioca = (gg-ga)/gca;
ratiocb = (gg-gb)/gcb;
if (color_length > 0) {
for (int i=0; i<color_length; i++) {
t = (int) ( (1.0f - ratioca) * ((auxa[i] < 0) ?
((float) auxa[i]) + 256.0f : ((float) auxa[i]) ) +
ratioca * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) );
color_levels[i][numv] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
t = (int) ( (1.0f - ratiocb) * ((auxb[i] < 0) ?
((float) auxb[i]) + 256.0f : ((float) auxb[i]) ) +
ratiocb * ((auxc[i] < 0) ?
((float) auxc[i]) + 256.0f : ((float) auxc[i]) ) );
color_levels[i][numv+1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
color_levels[i][numv] = auxa[i] + (auxc[i]-auxa[i]) * ratioca;
color_levels[i][numv+1] = auxb[i] + (auxc[i]-auxb[i]) * ratiocb;
*/
}
}
vx[numv] = samples[0][va] + (samples[0][vc]-samples[0][va]) * ratioca;
vy[numv] = samples[1][va] + (samples[1][vc]-samples[1][va]) * ratioca;
vz[numv] = samples[2][va] + (samples[2][vc]-samples[2][va]) * ratioca;
numv++;
vx[numv] = samples[0][vb] + (samples[0][vc]-samples[0][vb]) * ratiocb;
vy[numv] = samples[1][vb] + (samples[1][vc]-samples[1][vb]) * ratiocb;
vz[numv] = samples[2][vb] + (samples[2][vc]-samples[2][vb]) * ratiocb;
numv++;
break;
} // end switch (ii)
} // end for (int il=0; il<numc && numv+8<mav; il++, gg += interval)
} // end for (int jj=0; jj<npolygons; jj++)
VisADLineArray[][] arrays = new VisADLineArray[3][1];
arrays[0][0] = new VisADLineArray();
float[][] coordinates = new float[3][numv];
System.arraycopy(vx, 0, coordinates[0], 0, numv);
System.arraycopy(vy, 0, coordinates[1], 0, numv);
System.arraycopy(vz, 0, coordinates[2], 0, numv);
vx = null;
vy = null;
vz = null;
byte[][] colors = null;
if (color_length > 0) {
colors = new byte[3][numv];
System.arraycopy(color_levels[0], 0, colors[0], 0, numv);
System.arraycopy(color_levels[1], 0, colors[1], 0, numv);
System.arraycopy(color_levels[2], 0, colors[2], 0, numv);
/* MEM_WLH
colors = new byte[3][numv];
for (int i=0; i<3; i++) {
for (int j=0; j<numv; j++) {
int k = (int) (color_levels[i][j] * 255.0);
k = (k < 0) ? 0 : (k > 255) ? 255 : k;
colors[i][j] = (byte) ((k < 128) ? k : k - 256);
}
}
*/
color_levels = null;
}
setGeometryArray(arrays[0][0], coordinates, 3, colors);
arrays[1][0] = null;
arrays[2][0] = null;
return arrays;
}
public VisADGeometryArray makeIsoSurface(float isolevel,
float[] fieldValues, byte[][] color_values, boolean indexed)
throws VisADException {
if (ManifoldDimension != 3) {
throw new DisplayException("Irregular3DSet.main_isosurf: " +
"ManifoldDimension must be 3, not " +
ManifoldDimension);
}
float[][] fieldVertices = new float[3][];
byte[][] color_levels = null;
if (color_values != null) {
color_levels = new byte[color_values.length][];
/* MEM_WLH
cfloat = new float[color_values.length][];
for (int i = 0; i< color_levels.length; i++) {
if (color_values[i] != null) {
cfloat[i] = new float[color_values[i].length];
for (int j=0; j<color_values[i].length; j++) {
int k = color_values[i][j];
if (k < 0) k += 256;
cfloat[i][j] = (k / 255.0f);
}
}
}
*/
}
int[][][] polyToVert = new int[1][][];
int[][][] vertToPoly = new int[1][][];
makeIsosurface(isolevel, fieldValues, color_values, fieldVertices,
color_levels, polyToVert, vertToPoly);
/* MEM_WLH
byte[][] c = null;
if (color_levels != null) {
c = new byte[color_levels.length][];
for (int i = 0; i< color_levels.length; i++) {
if (color_levels[i] != null) {
c[i] = new byte[color_levels[i].length];
for (int j=0; j<color_levels[i].length; j++) {
int k = (int) (color_levels[i][j] * 255.0);
k = (k < 0) ? 0 : (k > 255) ? 255 : k;
c[i][j] = (byte) ((k < 128) ? k : k - 256);
}
}
}
// FREE
color_levels = null;
}
*/
int nvertex = vertToPoly[0].length;
int npolygons = polyToVert[0].length;
float[] NX = new float[nvertex];
float[] NY = new float[nvertex];
float[] NZ = new float[nvertex];
if (nvertex == 0 || npolygons == 0) return null;
// with make_normals
float[] NxA = new float[npolygons];
float[] NxB = new float[npolygons];
float[] NyA = new float[npolygons];
float[] NyB = new float[npolygons];
float[] NzA = new float[npolygons];
float[] NzB = new float[npolygons];
float[] Pnx = new float[npolygons];
float[] Pny = new float[npolygons];
float[] Pnz = new float[npolygons];
make_normals(fieldVertices[0], fieldVertices[1], fieldVertices[2],
NX, NY, NZ, nvertex, npolygons, Pnx, Pny, Pnz,
NxA, NxB, NyA, NyB, NzA, NzB, vertToPoly[0], polyToVert[0]);
// take the garbage out
NxA = NxB = NyA = NyB = NzA = NzB = Pnx = Pny = Pnz = null;
// with poly_triangle_stripe
float[] normals = new float[3 * nvertex];
int j = 0;
for (int i=0; i<nvertex; i++) {
normals[j++] = (float) NX[i];
normals[j++] = (float) NY[i];
normals[j++] = (float) NZ[i];
}
// take the garbage out
NX = NY = NZ = null;
int[] stripe = new int[6 * npolygons];
int size_stripe =
poly_triangle_stripe(stripe, nvertex, npolygons,
vertToPoly[0], polyToVert[0]);
// take the garbage out
vertToPoly = null;
polyToVert = null;
if (indexed) {
VisADIndexedTriangleStripArray array =
new VisADIndexedTriangleStripArray();
// set up indices
array.indexCount = size_stripe;
array.indices = new int[size_stripe];
System.arraycopy(stripe, 0, array.indices, 0, size_stripe);
array.stripVertexCounts = new int[1];
array.stripVertexCounts[0] = size_stripe;
// take the garbage out
stripe = null;
// set coordinates and colors
setGeometryArray(array, fieldVertices, 4, color_levels);
// take the garbage out
fieldVertices = null;
color_levels = null;
// array.vertexFormat |= NORMALS;
array.normals = normals;
return array;
}
else { // if (!indexed)
VisADTriangleStripArray array = new VisADTriangleStripArray();
array.stripVertexCounts = new int[] {size_stripe};
array.vertexCount = size_stripe;
array.normals = new float[3 * size_stripe];
int k = 0;
for (int i=0; i<3*size_stripe; i+=3) {
j = 3 * stripe[k];
array.normals[i] = normals[j];
array.normals[i+1] = normals[j+1];
array.normals[i+2] = normals[j+2];
k++;
}
normals = null;
array.coordinates = new float[3 * size_stripe];
k = 0;
for (int i=0; i<3*size_stripe; i+=3) {
j = stripe[k];
array.coordinates[i] = fieldVertices[0][j];
array.coordinates[i+1] = fieldVertices[1][j];
array.coordinates[i+2] = fieldVertices[2][j];
k++;
}
fieldVertices = null;
if (color_levels != null) {
int color_length = color_levels.length;
array.colors = new byte[color_length * size_stripe];
k = 0;
if (color_length == 4) {
for (int i=0; i<color_length*size_stripe; i+=color_length) {
j = stripe[k];
array.colors[i] = color_levels[0][j];
array.colors[i+1] = color_levels[1][j];
array.colors[i+2] = color_levels[2][j];
array.colors[i+3] = color_levels[3][j];
k++;
}
}
else { // if (color_length == 3)
for (int i=0; i<color_length*size_stripe; i+=color_length) {
j = stripe[k];
array.colors[i] = color_levels[0][j];
array.colors[i+1] = color_levels[1][j];
array.colors[i+2] = color_levels[2][j];
k++;
}
}
}
color_levels = null;
stripe = null;
return array;
}
}
/** compute an Isosurface through the Irregular3DSet
given an array of fieldValues at each sample,
an isolevel at which to form the surface, and
other values (e.g., colors) at each sample in
auxValues;
return vertex locations in fieldVertices[3][nvertex];
return values of auxValues at vertices in auxLevels;
return pointers from vertices to polys in
vertToPoly[1][nvertex][nverts[i]];
return pointers from polys to vertices in
polyToVert[1][npolygons][4]; */
private void makeIsosurface(float isolevel, float[] fieldValues,
byte[][] auxValues, float[][] fieldVertices,
byte[][] auxLevels, int[][][] polyToVert,
int[][][] vertToPoly) throws VisADException {
boolean DEBUG = false;
if (ManifoldDimension != 3) {
throw new DisplayException("Irregular3DSet.makeIsosurface: " +
"ManifoldDimension must be 3, not " +
ManifoldDimension);
}
if (fieldValues.length != Length) {
throw new DisplayException("Irregular3DSet.makeIsosurface: "
+"fieldValues length does't match");
}
if (Double.isNaN(isolevel)) {
throw new DisplayException("Irregular3DSet.makeIsosurface: "
+"isolevel cannot be missing");
}
if (fieldVertices.length != 3 || polyToVert.length != 1
|| vertToPoly.length != 1) {
throw new DisplayException("Irregular3DSet.makeIsosurface: return value"
+ " arrays not correctly initialized " +
fieldVertices.length + " " + polyToVert.length +
" " + vertToPoly.length);
}
int naux = (auxValues != null) ? auxValues.length : 0;
if (naux > 0) {
if (auxLevels == null || auxLevels.length != naux) {
throw new DisplayException("Irregular3DSet.makeIsosurface: "
+"auxLevels length doesn't match");
}
for (int i=0; i<naux; i++) {
if (auxValues[i].length != Length) {
throw new DisplayException("Irregular3DSet.makeIsosurface: "
+"auxValues lengths don't match");
}
}
}
else {
if (auxLevels != null) {
throw new DisplayException("Irregular3DSet.makeIsosurface: "
+"auxValues null but auxLevels not null");
}
}
if (DEBUG) {
System.out.println("isolevel = " + isolevel + "\n");
System.out.println("fieldValues " + fieldValues.length);
for (int i=0; i<fieldValues.length; i++) {
System.out.println(" " + i + " -> " + fieldValues[i]);
}
System.out.println(Delan.sampleString(Samples));
}
int trilength = Delan.Tri.length;
// temporary storage of polyToVert structure
int[][] polys = new int[trilength][4];
// pointers from global edge number to nvertex
int[] globalToVertex = new int[Delan.NumEdges];
for (int i=0; i<Delan.NumEdges; i++) globalToVertex[i] = -1;
// global edges temporary storage array
float[][] edgeInterp = new float[DomainDimension][Delan.NumEdges];
for (int i=0; i<Delan.NumEdges; i++) edgeInterp[0][i] = Float.NaN;
// global edges temporary storage array for aux levels
byte[][] auxInterp = (naux > 0) ? new byte[naux][Delan.NumEdges] : null;
int t;
int nvertex = 0;
int npolygons = 0;
for (int i=0; i<trilength; i++) {
int v0 = Delan.Tri[i][0];
int v1 = Delan.Tri[i][1];
int v2 = Delan.Tri[i][2];
int v3 = Delan.Tri[i][3];
float f0 = (float) fieldValues[v0];
float f1 = (float) fieldValues[v1];
float f2 = (float) fieldValues[v2];
float f3 = (float) fieldValues[v3];
int e0, e1, e2, e3, e4, e5;
// compute tetrahedron signature
// vector from v0 to v3
float vx = Samples[0][v3] - Samples[0][v0];
float vy = Samples[1][v3] - Samples[1][v0];
float vz = Samples[2][v3] - Samples[2][v0];
// cross product (v2 - v0) x (v1 - v0)
float sx = Samples[0][v2] - Samples[0][v0];
float sy = Samples[1][v2] - Samples[1][v0];
float sz = Samples[2][v2] - Samples[2][v0];
float tx = Samples[0][v1] - Samples[0][v0];
float ty = Samples[1][v1] - Samples[1][v0];
float tz = Samples[2][v1] - Samples[2][v0];
float cx = sy * tz - sz * ty;
float cy = sz * tx - sx * tz;
float cz = sx * ty - sy * tx;
// signature is sign of v (dot) c
float sig = vx * cx + vy * cy + vz * cz;
// 8 possibilities
int index = ((f0 > isolevel) ? 1 : 0)
+ ((f1 > isolevel) ? 2 : 0)
+ ((f2 > isolevel) ? 4 : 0)
+ ((f3 > isolevel) ? 8 : 0);
// apply signature to index
if (sig < 0.0f) index = 15 - index;
switch (index) {
case 0:
case 15: // plane does not intersect this tetrahedron
break;
case 1:
case 14: // plane slices a triangle
// define edge values needed
e0 = Delan.Edges[i][0];
e1 = Delan.Edges[i][1];
e2 = Delan.Edges[i][2];
// fill in edge interpolation values if they haven't been found
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e0])) {
*/
// test for missing
if (edgeInterp[0][e0] != edgeInterp[0][e0]) {
float a = (isolevel - f1)/(f0 - f1);
if (a < 0) a = -a;
edgeInterp[0][e0] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v1];
edgeInterp[1][e0] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v1];
edgeInterp[2][e0] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v1];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) );
auxInterp[j][e0] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e0] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v1];
*/
}
globalToVertex[e0] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e1])) {
*/
// test for missing
if (edgeInterp[0][e1] != edgeInterp[0][e1]) {
float a = (isolevel - f2)/(f0 - f2);
if (a < 0) a = -a;
edgeInterp[0][e1] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v2];
edgeInterp[1][e1] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v2];
edgeInterp[2][e1] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e1] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e1] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e2])) {
*/
// test for missing
if (edgeInterp[0][e2] != edgeInterp[0][e2]) {
float a = (isolevel - f3)/(f0 - f3);
if (a < 0) a = -a;
edgeInterp[0][e2] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v3];
edgeInterp[1][e2] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v3];
edgeInterp[2][e2] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e2] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e2] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e2] = nvertex;
nvertex++;
}
// fill in the polys and vertToPoly arrays
polys[npolygons][0] = e0;
if (index == 1) {
polys[npolygons][1] = e1;
polys[npolygons][2] = e2;
}
else { // index == 14
polys[npolygons][1] = e2;
polys[npolygons][2] = e1;
}
polys[npolygons][3] = -1;
// on to the next tetrahedron
npolygons++;
break;
case 2:
case 13: // plane slices a triangle
// define edge values needed
e0 = Delan.Edges[i][0];
e3 = Delan.Edges[i][3];
e4 = Delan.Edges[i][4];
// fill in edge interpolation values if they haven't been found
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e0])) {
*/
// test for missing
if (edgeInterp[0][e0] != edgeInterp[0][e0]) {
float a = (isolevel - f1)/(f0 - f1);
if (a < 0) a = -a;
edgeInterp[0][e0] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v1];
edgeInterp[1][e0] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v1];
edgeInterp[2][e0] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v1];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) );
auxInterp[j][e0] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e0] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v1];
*/
}
globalToVertex[e0] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e3])) {
*/
// test for missing
if (edgeInterp[0][e3] != edgeInterp[0][e3]) {
float a = (isolevel - f2)/(f1 - f2);
if (a < 0) a = -a;
edgeInterp[0][e3] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v2];
edgeInterp[1][e3] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v2];
edgeInterp[2][e3] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e3] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e3] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e3] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e4])) {
*/
// test for missing
if (edgeInterp[0][e4] != edgeInterp[0][e4]) {
float a = (isolevel - f3)/(f1 - f3);
if (a < 0) a = -a;
edgeInterp[0][e4] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v3];
edgeInterp[1][e4] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v3];
edgeInterp[2][e4] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e4] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e4] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e4] = nvertex;
nvertex++;
}
// fill in the polys array
polys[npolygons][0] = e0;
if (index == 2) {
polys[npolygons][1] = e4;
polys[npolygons][2] = e3;
}
else { // index == 13
polys[npolygons][1] = e3;
polys[npolygons][2] = e4;
}
polys[npolygons][3] = -1;
// on to the next tetrahedron
npolygons++;
break;
case 3:
case 12: // plane slices a quadrilateral
// define edge values needed
e1 = Delan.Edges[i][1];
e2 = Delan.Edges[i][2];
e3 = Delan.Edges[i][3];
e4 = Delan.Edges[i][4];
// fill in edge interpolation values if they haven't been found
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e1])) {
*/
// test for missing
if (edgeInterp[0][e1] != edgeInterp[0][e1]) {
float a = (isolevel - f2)/(f0 - f2);
if (a < 0) a = -a;
edgeInterp[0][e1] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v2];
edgeInterp[1][e1] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v2];
edgeInterp[2][e1] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e1] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e1] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e2])) {
*/
// test for missing
if (edgeInterp[0][e2] != edgeInterp[0][e2]) {
float a = (isolevel - f3)/(f0 - f3);
if (a < 0) a = -a;
edgeInterp[0][e2] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v3];
edgeInterp[1][e2] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v3];
edgeInterp[2][e2] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e2] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e2] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e2] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e4])) {
*/
// test for missing
if (edgeInterp[0][e4] != edgeInterp[0][e4]) {
float a = (isolevel - f3)/(f1 - f3);
if (a < 0) a = -a;
edgeInterp[0][e4] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v3];
edgeInterp[1][e4] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v3];
edgeInterp[2][e4] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e4] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e4] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e4] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e3])) {
*/
// test for missing
if (edgeInterp[0][e3] != edgeInterp[0][e3]) {
float a = (isolevel - f2)/(f1 - f2);
if (a < 0) a = -a;
edgeInterp[0][e3] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v2];
edgeInterp[1][e3] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v2];
edgeInterp[2][e3] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e3] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e3] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e3] = nvertex;
nvertex++;
}
// fill in the polys array
polys[npolygons][0] = e1;
if (index == 3) {
polys[npolygons][1] = e2;
polys[npolygons][2] = e4;
polys[npolygons][3] = e3;
}
else { // index == 12
polys[npolygons][1] = e3;
polys[npolygons][2] = e4;
polys[npolygons][3] = e2;
}
// on to the next tetrahedron
npolygons++;
break;
case 4:
case 11: // plane slices a triangle
// define edge values needed
e1 = Delan.Edges[i][1];
e3 = Delan.Edges[i][3];
e5 = Delan.Edges[i][5];
// fill in edge interpolation values if they haven't been found
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e1])) {
*/
// test for missing
if (edgeInterp[0][e1] != edgeInterp[0][e1]) {
float a = (isolevel - f2)/(f0 - f2);
if (a < 0) a = -a;
edgeInterp[0][e1] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v2];
edgeInterp[1][e1] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v2];
edgeInterp[2][e1] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e1] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e1] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e3])) {
*/
// test for missing
if (edgeInterp[0][e3] != edgeInterp[0][e3]) {
float a = (isolevel - f2)/(f1 - f2);
if (a < 0) a = -a;
edgeInterp[0][e3] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v2];
edgeInterp[1][e3] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v2];
edgeInterp[2][e3] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e3] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e3] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e3] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e5])) {
*/
// test for missing
if (edgeInterp[0][e5] != edgeInterp[0][e5]) {
float a = (isolevel - f3)/(f2 - f3);
if (a < 0) a = -a;
edgeInterp[0][e5] = (float) a*Samples[0][v2] + (1-a)*Samples[0][v3];
edgeInterp[1][e5] = (float) a*Samples[1][v2] + (1-a)*Samples[1][v3];
edgeInterp[2][e5] = (float) a*Samples[2][v2] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e5] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e5] = (float) a*auxValues[j][v2] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e5] = nvertex;
nvertex++;
}
// fill in the polys array
polys[npolygons][0] = e1;
if (index == 4) {
polys[npolygons][1] = e3;
polys[npolygons][2] = e5;
}
else { // index == 11
polys[npolygons][1] = e5;
polys[npolygons][2] = e3;
}
polys[npolygons][3] = -1;
// on to the next tetrahedron
npolygons++;
break;
case 5:
case 10: // plane slices a quadrilateral
// define edge values needed
e0 = Delan.Edges[i][0];
e2 = Delan.Edges[i][2];
e3 = Delan.Edges[i][3];
e5 = Delan.Edges[i][5];
// fill in edge interpolation values if they haven't been found
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e0])) {
*/
// test for missing
if (edgeInterp[0][e0] != edgeInterp[0][e0]) {
float a = (isolevel - f1)/(f0 - f1);
if (a < 0) a = -a;
edgeInterp[0][e0] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v1];
edgeInterp[1][e0] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v1];
edgeInterp[2][e0] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v1];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) );
auxInterp[j][e0] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e0] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v1];
*/
}
globalToVertex[e0] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e2])) {
*/
// test for missing
if (edgeInterp[0][e2] != edgeInterp[0][e2]) {
float a = (isolevel - f3)/(f0 - f3);
if (a < 0) a = -a;
edgeInterp[0][e2] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v3];
edgeInterp[1][e2] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v3];
edgeInterp[2][e2] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e2] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e2] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e2] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e5])) {
*/
// test for missing
if (edgeInterp[0][e5] != edgeInterp[0][e5]) {
float a = (isolevel - f3)/(f2 - f3);
if (a < 0) a = -a;
edgeInterp[0][e5] = (float) a*Samples[0][v2] + (1-a)*Samples[0][v3];
edgeInterp[1][e5] = (float) a*Samples[1][v2] + (1-a)*Samples[1][v3];
edgeInterp[2][e5] = (float) a*Samples[2][v2] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e5] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e5] = (float) a*auxValues[j][v2] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e5] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e3])) {
*/
// test for missing
if (edgeInterp[0][e3] != edgeInterp[0][e3]) {
float a = (isolevel - f2)/(f1 - f2);
if (a < 0) a = -a;
edgeInterp[0][e3] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v2];
edgeInterp[1][e3] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v2];
edgeInterp[2][e3] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e3] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e3] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e3] = nvertex;
nvertex++;
}
// fill in the polys array
polys[npolygons][0] = e0;
if (index == 5) {
polys[npolygons][1] = e3;
polys[npolygons][2] = e5;
polys[npolygons][3] = e2;
}
else { // index == 10
polys[npolygons][1] = e2;
polys[npolygons][2] = e5;
polys[npolygons][3] = e3;
}
// on to the next tetrahedron
npolygons++;
break;
case 6:
case 9: // plane slices a quadrilateral
// define edge values needed
e0 = Delan.Edges[i][0];
e1 = Delan.Edges[i][1];
e4 = Delan.Edges[i][4];
e5 = Delan.Edges[i][5];
// fill in edge interpolation values if they haven't been found
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e0])) {
*/
// test for missing
if (edgeInterp[0][e0] != edgeInterp[0][e0]) {
float a = (isolevel - f1)/(f0 - f1);
if (a < 0) a = -a;
edgeInterp[0][e0] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v1];
edgeInterp[1][e0] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v1];
edgeInterp[2][e0] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v1];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) );
auxInterp[j][e0] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e0] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v1];
*/
}
globalToVertex[e0] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e1])) {
*/
// test for missing
if (edgeInterp[0][e1] != edgeInterp[0][e1]) {
float a = (isolevel - f2)/(f0 - f2);
if (a < 0) a = -a;
edgeInterp[0][e1] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v2];
edgeInterp[1][e1] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v2];
edgeInterp[2][e1] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e1] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e1] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e5])) {
*/
// test for missing
if (edgeInterp[0][e5] != edgeInterp[0][e5]) {
float a = (isolevel - f3)/(f2 - f3);
if (a < 0) a = -a;
edgeInterp[0][e5] = (float) a*Samples[0][v2] + (1-a)*Samples[0][v3];
edgeInterp[1][e5] = (float) a*Samples[1][v2] + (1-a)*Samples[1][v3];
edgeInterp[2][e5] = (float) a*Samples[2][v2] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e5] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e5] = (float) a*auxValues[j][v2] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e5] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e4])) {
*/
// test for missing
if (edgeInterp[0][e4] != edgeInterp[0][e4]) {
float a = (isolevel - f3)/(f1 - f3);
if (a < 0) a = -a;
edgeInterp[0][e4] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v3];
edgeInterp[1][e4] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v3];
edgeInterp[2][e4] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e4] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e4] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e4] = nvertex;
nvertex++;
}
// fill in the polys array
polys[npolygons][0] = e0;
if (index == 6) {
polys[npolygons][1] = e4;
polys[npolygons][2] = e5;
polys[npolygons][3] = e1;
}
else { // index == 9
polys[npolygons][1] = e1;
polys[npolygons][2] = e5;
polys[npolygons][3] = e4;
}
// on to the next tetrahedron
npolygons++;
break;
case 7:
case 8: // plane slices a triangle
// interpolate between 3:0, 3:1, 3:2 for tri edges, same as case 8
// define edge values needed
e2 = Delan.Edges[i][2];
e4 = Delan.Edges[i][4];
e5 = Delan.Edges[i][5];
// fill in edge interpolation values if they haven't been found
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e2])) {
*/
// test for missing
if (edgeInterp[0][e2] != edgeInterp[0][e2]) {
float a = (isolevel - f3)/(f0 - f3);
if (a < 0) a = -a;
edgeInterp[0][e2] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v3];
edgeInterp[1][e2] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v3];
edgeInterp[2][e2] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e2] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e2] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e2] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e4])) {
*/
// test for missing
if (edgeInterp[0][e4] != edgeInterp[0][e4]) {
float a = (isolevel - f3)/(f1 - f3);
if (a < 0) a = -a;
edgeInterp[0][e4] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v3];
edgeInterp[1][e4] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v3];
edgeInterp[2][e4] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e4] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e4] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e4] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e5])) {
*/
// test for missing
if (edgeInterp[0][e5] != edgeInterp[0][e5]) {
float a = (isolevel - f3)/(f2 - f3);
if (a < 0) a = -a;
edgeInterp[0][e5] = (float) a*Samples[0][v2] + (1-a)*Samples[0][v3];
edgeInterp[1][e5] = (float) a*Samples[1][v2] + (1-a)*Samples[1][v3];
edgeInterp[2][e5] = (float) a*Samples[2][v2] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e5] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e5] = (float) a*auxValues[j][v2] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e5] = nvertex;
nvertex++;
}
// fill in the polys array
polys[npolygons][0] = e2;
if (index == 7) {
polys[npolygons][1] = e4;
polys[npolygons][2] = e5;
}
else { // index == 8
polys[npolygons][1] = e5;
polys[npolygons][2] = e4;
}
polys[npolygons][3] = -1;
// on to the next tetrahedron
npolygons++;
break;
} // end switch (index)
} // end for (int i=0; i<trilength; i++)
if (DEBUG) {
System.out.println("\npolys (polys -> global edges) " + npolygons + "\n");
for (int i=0; i<npolygons; i++) {
String s = " " + i + " -> ";
for (int j=0; j<4; j++) {
s = s + " " + polys[i][j];
}
System.out.println(s + "\n");
}
}
// transform polys array into polyToVert array
polyToVert[0] = new int[npolygons][];
for (int i=0; i<npolygons; i++) {
int n = polys[i][3] < 0 ? 3 : 4;
polyToVert[0][i] = new int[n];
for (int j=0; j<n; j++) polyToVert[0][i][j] = globalToVertex[polys[i][j]];
}
if (DEBUG) {
System.out.println("\npolyToVert (polys -> vertices) " + npolygons + "\n");
for (int i=0; i<npolygons; i++) {
String s = " " + i + " -> ";
for (int j=0; j<polyToVert[0][i].length; j++) {
s = s + " " + polyToVert[0][i][j];
}
System.out.println(s + "\n");
}
}
// build nverts helper array
int[] nverts = new int[nvertex];
for (int i=0; i<nvertex; i++) nverts[i] = 0;
for (int i=0; i<npolygons; i++) {
nverts[polyToVert[0][i][0]]++;
nverts[polyToVert[0][i][1]]++;
nverts[polyToVert[0][i][2]]++;
if (polyToVert[0][i].length > 3) nverts[polyToVert[0][i][3]]++;
}
// initialize vertToPoly array
vertToPoly[0] = new int[nvertex][];
for (int i=0; i<nvertex; i++) {
vertToPoly[0][i] = new int[nverts[i]];
}
// fill in vertToPoly array
for (int i=0; i<nvertex; i++) nverts[i] = 0;
for (int i=0; i<npolygons; i++) {
int a = polyToVert[0][i][0];
int b = polyToVert[0][i][1];
int c = polyToVert[0][i][2];
vertToPoly[0][a][nverts[a]++] = i;
vertToPoly[0][b][nverts[b]++] = i;
vertToPoly[0][c][nverts[c]++] = i;
if (polyToVert[0][i].length > 3) {
int d = polyToVert[0][i][3];
if (d != -1) vertToPoly[0][d][nverts[d]++] = i;
}
}
if (DEBUG) {
System.out.println("\nvertToPoly (vertices -> polys) " + nvertex + "\n");
for (int i=0; i<nvertex; i++) {
String s = " " + i + " -> ";
for (int j=0; j<vertToPoly[0][i].length; j++) {
s = s + " " + vertToPoly[0][i][j];
}
System.out.println(s + "\n");
}
}
// set up fieldVertices and auxLevels
fieldVertices[0] = new float[nvertex];
fieldVertices[1] = new float[nvertex];
fieldVertices[2] = new float[nvertex];
for (int j=0; j<naux; j++) {
auxLevels[j] = new byte[nvertex];
}
for (int i=0; i<Delan.NumEdges; i++) {
int k = globalToVertex[i];
if (k >= 0) {
fieldVertices[0][k] = edgeInterp[0][i];
fieldVertices[1][k] = edgeInterp[1][i];
fieldVertices[2][k] = edgeInterp[2][i];
for (int j=0; j<naux; j++) {
auxLevels[j][k] = auxInterp[j][i];
}
}
}
if (DEBUG) {
System.out.println("\nfieldVertices " + nvertex + "\n");
for (int i=0; i<nvertex; i++) {
String s = " " + i + " -> ";
for (int j=0; j<3; j++) {
s = s + " " + fieldVertices[j][i];
}
System.out.println(s + "\n");
}
}
}
/*
make_normals and poly_triangle_stripe altered according to:
Pol_f_Vert[9*i + 8] --> vertToPoly[i].length
Pol_f_Vert[9*i + off] --> vertToPoly[i][off]
Vert_f_Pol[7*i + 6] --> polyToVert[i].length
Vert_f_Pol[7*i + off] --> polyToVert[i][off]
*/
/* from Contour3D.java, used by make_normals */
static final float EPS_0 = (float) 1.0e-5;
/* copied from Contour3D.java */
private static void make_normals(float[] VX, float[] VY, float[] VZ,
float[] NX, float[] NY, float[] NZ, int nvertex,
int npolygons, float[] Pnx, float[] Pny, float[] Pnz,
float[] NxA, float[] NxB, float[] NyA, float[] NyB,
float[] NzA, float[] NzB,
int[][] vertToPoly, int[][] polyToVert)
/* WLH 25 Oct 97
int[] Pol_f_Vert, int[] Vert_f_Pol )
*/
throws VisADException {
int i, k, n;
int i1, i2, ix, iy, iz, ixb, iyb, izb;
int max_vert_per_pol, swap_flag;
float x, y, z, a, minimum_area, len;
int iv[] = new int[3];
if (nvertex <= 0) return;
for (i = 0; i < nvertex; i++) {
NX[i] = 0;
NY[i] = 0;
NZ[i] = 0;
}
// WLH 12 Nov 2001
// minimum_area = (float) ((1.e-4 > EPS_0) ? 1.e-4 : EPS_0);
minimum_area = Float.MIN_VALUE;
/* Calculate maximum number of vertices per polygon */
/* WLH 25 Oct 97
k = 6;
n = 7*npolygons;
*/
k = 0;
while ( true ) {
/* WLH 25 Oct 97
for (i=k+7; i<n; i+=7)
if (Vert_f_Pol[i] > Vert_f_Pol[k]) break;
*/
for (i=k+1; i<npolygons; i++)
if (polyToVert[i].length > polyToVert[k].length) break;
/* WLH 25 Oct 97
if (i >= n) break;
*/
if (i >= npolygons) break;
k = i;
}
/* WLH 25 Oct 97
max_vert_per_pol = Vert_f_Pol[k];
*/
max_vert_per_pol = polyToVert[k].length;
/* Calculate the Normals vector components for each Polygon */
for ( i=0; i<npolygons; i++) { /* Vectorized */
/* WLH 25 Oct 97
if (Vert_f_Pol[6+i*7]>0) {
NxA[i] = VX[Vert_f_Pol[1+i*7]] - VX[Vert_f_Pol[0+i*7]];
NyA[i] = VY[Vert_f_Pol[1+i*7]] - VY[Vert_f_Pol[0+i*7]];
NzA[i] = VZ[Vert_f_Pol[1+i*7]] - VZ[Vert_f_Pol[0+i*7]];
}
*/
if (polyToVert[i].length>0) {
int j1 = polyToVert[i][1];
int j0 = polyToVert[i][0];
NxA[i] = VX[j1] - VX[j0];
NyA[i] = VY[j1] - VY[j0];
NzA[i] = VZ[j1] - VZ[j0];
}
}
swap_flag = 0;
for ( k = 2; k < max_vert_per_pol; k++ ) {
if (swap_flag==0) {
/*$dir no_recurrence */ /* Vectorized */
for ( i=0; i<npolygons; i++ ) {
/* WLH 25 Oct 97
if ( Vert_f_Pol[k+i*7] >= 0 ) {
NxB[i] = VX[Vert_f_Pol[k+i*7]] - VX[Vert_f_Pol[0+i*7]];
NyB[i] = VY[Vert_f_Pol[k+i*7]] - VY[Vert_f_Pol[0+i*7]];
NzB[i] = VZ[Vert_f_Pol[k+i*7]] - VZ[Vert_f_Pol[0+i*7]];
*/
if ( k < polyToVert[i].length ) {
int jk = polyToVert[i][k];
int j0 = polyToVert[i][0];
NxB[i] = VX[jk] - VX[j0];
NyB[i] = VY[jk] - VY[j0];
NzB[i] = VZ[jk] - VZ[j0];
Pnx[i] = NyA[i]*NzB[i] - NzA[i]*NyB[i];
Pny[i] = NzA[i]*NxB[i] - NxA[i]*NzB[i];
Pnz[i] = NxA[i]*NyB[i] - NyA[i]*NxB[i];
NxA[i] = Pnx[i]*Pnx[i] + Pny[i]*Pny[i] + Pnz[i]*Pnz[i];
if (NxA[i] > minimum_area) {
Pnx[i] /= NxA[i];
Pny[i] /= NxA[i];
Pnz[i] /= NxA[i];
}
}
}
}
else { /* swap_flag!=0 */
/*$dir no_recurrence */ /* Vectorized */
for (i=0; i<npolygons; i++) {
/* WLH 25 Oct 97
if ( Vert_f_Pol[k+i*7] >= 0 ) {
NxA[i] = VX[Vert_f_Pol[k+i*7]] - VX[Vert_f_Pol[0+i*7]];
NyA[i] = VY[Vert_f_Pol[k+i*7]] - VY[Vert_f_Pol[0+i*7]];
NzA[i] = VZ[Vert_f_Pol[k+i*7]] - VZ[Vert_f_Pol[0+i*7]];
*/
if ( k < polyToVert[i].length ) {
int jk = polyToVert[i][k];
int j0 = polyToVert[i][0];
NxA[i] = VX[jk] - VX[j0];
NyA[i] = VY[jk] - VY[j0];
NzA[i] = VZ[jk] - VZ[j0];
Pnx[i] = NyB[i]*NzA[i] - NzB[i]*NyA[i];
Pny[i] = NzB[i]*NxA[i] - NxB[i]*NzA[i];
Pnz[i] = NxB[i]*NyA[i] - NyB[i]*NxA[i];
NxB[i] = Pnx[i]*Pnx[i] + Pny[i]*Pny[i] + Pnz[i]*Pnz[i];
if (NxB[i] > minimum_area) {
Pnx[i] /= NxB[i];
Pny[i] /= NxB[i];
Pnz[i] /= NxB[i];
}
}
} // end for (i=0; i<npolygons; i++)
} // end swap_flag!=0
/* This Loop <CAN'T> be Vectorized */
for ( i=0; i<npolygons; i++ ) {
/* WLH 25 Oct 97
if (Vert_f_Pol[k+i*7] >= 0) {
iv[0] = Vert_f_Pol[0+i*7];
iv[1] = Vert_f_Pol[(k-1)+i*7];
iv[2] = Vert_f_Pol[k+i*7];
*/
if (k < polyToVert[i].length) {
iv[0] = polyToVert[i][0];
iv[1] = polyToVert[i][k-1];
iv[2] = polyToVert[i][k];
x = Pnx[i]; y = Pny[i]; z = Pnz[i];
/*
System.out.println("vertices: " + iv[0] + " " + iv[1] + " " + iv[2]);
System.out.println(" normal: " + x + " " + y + " " + z + "\n");
*/
// Update the origin vertex
NX[iv[0]] += x; NY[iv[0]] += y; NZ[iv[0]] += z;
// Update the vertex that defines the first vector
NX[iv[1]] += x; NY[iv[1]] += y; NZ[iv[1]] += z;
// Update the vertex that defines the second vector
NX[iv[2]] += x; NY[iv[2]] += y; NZ[iv[2]] += z;
}
} // end for ( i=0; i<npolygons; i++ )
swap_flag = ( (swap_flag != 0) ? 0 : 1 );
} // end for ( k = 2; k < max_vert_per_pol; k++ )
/* Normalize the Normals */
for ( i=0; i<nvertex; i++ ) { /* Vectorized */
len = (float) Math.sqrt(NX[i]*NX[i] + NY[i]*NY[i] + NZ[i]*NZ[i]);
if (len > EPS_0) {
NX[i] /= len;
NY[i] /= len;
NZ[i] /= len;
}
}
}
/* from Contour3D.java, used by poly_triangle_stripe */
static final int NTAB[] =
{ 0,1,2, 1,2,0, 2,0,1,
0,1,3,2, 1,2,0,3, 2,3,1,0, 3,0,2,1,
0,1,4,2,3, 1,2,0,3,4, 2,3,1,4,0, 3,4,2,0,1, 4,0,3,1,2,
0,1,5,2,4,3, 1,2,0,3,5,4, 2,3,1,4,0,5, 3,4,2,5,1,0, 4,5,3,0,2,1,
5,0,4,1,3,2
};
/* from Contour3D.java, used by poly_triangle_stripe */
static final int ITAB[] =
{ 0,2,1, 1,0,2, 2,1,0,
0,3,1,2, 1,0,2,3, 2,1,3,0, 3,2,0,1,
0,4,1,3,2, 1,0,2,4,3, 2,1,3,0,4, 3,2,4,1,0, 4,3,0,2,1,
0,5,1,4,2,3, 1,0,2,5,3,4, 2,1,3,0,4,5, 3,2,4,1,5,0, 4,3,5,2,0,1,
5,4,0,3,1,2
};
/* from Contour3D.java, used by poly_triangle_stripe */
static final int STAB[] = { 0, 9, 25, 50 };
/* copied from Contour3D.java */
static int poly_triangle_stripe( int[] Tri_Stripe,
int nvertex, int npolygons,
int[][] vertToPoly, int[][] polyToVert)
/* WLH 25 Oct 97
int[] Pol_f_Vert, int[] Vert_f_Pol )
*/
throws VisADException {
int i, j, k, m, ii, npol, cpol, idx, off, Nvt,
vA, vB, ivA, ivB, iST, last_pol;
boolean f_line_conection = false;
boolean[] vet_pol = new boolean[npolygons];
last_pol = 0;
npol = 0;
iST = 0;
ivB = 0;
for (i=0; i<npolygons; i++) vet_pol[i] = true; /* Vectorized */
while (true)
{
/* find_unselected_pol(cpol); */
for (cpol=last_pol; cpol<npolygons; cpol++) {
if ( vet_pol[cpol] ) break;
}
if (cpol == npolygons) {
cpol = -1;
}
else {
last_pol = cpol;
}
/* end find_unselected_pol(cpol); */
if (cpol < 0) break;
-/* update_polygon */
+/* ypdate_polygon */
+// System.out.println("1 vet_pol[" + cpol + "] = false");
vet_pol[cpol] = false;
/* end update_polygon */
/* get_vertices_of_pol(cpol,Vt,Nvt); { */
/* WLH 25 Oct 97
Nvt = Vert_f_Pol[(j=cpol*7)+6];
off = j;
*/
Nvt = polyToVert[cpol].length;
/* } */
/* end get_vertices_of_pol(cpol,Vt,Nvt); { */
for (ivA=0; ivA<Nvt; ivA++) {
ivB = (((ivA+1)==Nvt) ? 0:(ivA+1));
/* get_pol_vert(Vt[ivA],Vt[ivB],npol) { */
npol = -1;
/* WLH 25 Oct 97
if (Vert_f_Pol[ivA+off]>=0 && Vert_f_Pol[ivB+off]>=0) {
i=Vert_f_Pol[ivA+off]*9;
k=i+Pol_f_Vert [i+8];
j=Vert_f_Pol[ivB+off]*9;
m=j+Pol_f_Vert [j+8];
while (i>0 && j>0 && i<k && j <m ) {
if (Pol_f_Vert [i] == Pol_f_Vert [j] &&
vet_pol[Pol_f_Vert[i]] ) {
npol=Pol_f_Vert [i];
break;
}
else if (Pol_f_Vert [i] < Pol_f_Vert [j])
i++;
else
j++;
}
}
*/
if (ivA < polyToVert[cpol].length && ivB < polyToVert[cpol].length) {
i=polyToVert[cpol][ivA];
int ilim = vertToPoly[i].length;
k = 0;
j=polyToVert[cpol][ivB];
int jlim = vertToPoly[j].length;
m = 0;
// while (0<k && k<ilim && 0<m && m<jlim) {
while (0<i && k<ilim && 0<j && m<jlim) {
if (vertToPoly[i][k] == vertToPoly[j][m] &&
vet_pol[vertToPoly[i][k]] ) {
npol=vertToPoly[i][k];
break;
}
else if (vertToPoly[i][k] < vertToPoly[j][m])
k++;
else
m++;
}
}
/* } */
/* end get_pol_vert(Vt[ivA],Vt[ivB],npol) { */
if (npol >= 0) break;
}
/* insert polygon alone */
if (npol < 0)
{ /*ptT = NTAB + STAB[Nvt-3];*/
idx = STAB[Nvt-3];
if (iST > 0)
{ Tri_Stripe[iST] = Tri_Stripe[iST-1]; iST++;
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx]+off];
*/
+// System.out.println("1 Tri_Stripe[" + iST + "] from poly " + cpol);
Tri_Stripe[iST++] = polyToVert[cpol][NTAB[idx]];
}
else f_line_conection = true; /* WLH 3-9-95 added */
for (ii=0; ii< ((Nvt < 6) ? Nvt:6); ii++) {
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx++]+off];
*/
+// System.out.println("2 Tri_Stripe[" + iST + "] from poly " + cpol);
Tri_Stripe[iST++] = polyToVert[cpol][NTAB[idx++]];
}
continue;
}
if (( (ivB != 0) && ivA==(ivB-1)) || ( !(ivB != 0) && ivA==Nvt-1)) {
/* ptT = ITAB + STAB[Nvt-3] + (ivB+1)*Nvt; */
idx = STAB[Nvt-3] + (ivB+1)*Nvt;
if (f_line_conection)
{ Tri_Stripe[iST] = Tri_Stripe[iST-1]; iST++;
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[ITAB[idx-1]+off];
*/
+// System.out.println("3 Tri_Stripe[" + iST + "] from poly " + cpol);
Tri_Stripe[iST++] = polyToVert[cpol][ITAB[idx-1]];
f_line_conection = false;
}
for (ii=0; ii<((Nvt < 6) ? Nvt:6); ii++) {
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[ITAB[--idx]+off];
*/
+// System.out.println("4 Tri_Stripe[" + iST + "] from poly " + cpol);
Tri_Stripe[iST++] = polyToVert[cpol][ITAB[--idx]];
}
}
else {
/* ptT = NTAB + STAB[Nvt-3] + (ivB+1)*Nvt; */
idx = STAB[Nvt-3] + (ivB+1)*Nvt;
if (f_line_conection)
{ Tri_Stripe[iST] = Tri_Stripe[iST-1]; iST++;
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx-1]+off];
*/
+// System.out.println("5 Tri_Stripe[" + iST + "] from poly " + cpol);
Tri_Stripe[iST++] = polyToVert[cpol][NTAB[idx-1]];
f_line_conection = false;
}
for (ii=0; ii<((Nvt < 6) ? Nvt:6); ii++) {
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[--idx]+off];
*/
+// System.out.println("6 Tri_Stripe[" + iST + "] from poly " + cpol);
Tri_Stripe[iST++] = polyToVert[cpol][NTAB[--idx]];
}
}
vB = Tri_Stripe[iST-1];
vA = Tri_Stripe[iST-2];
cpol = npol;
while (true)
{
/* get_vertices_of_pol(cpol,Vt,Nvt) { */
/* WLH 25 Oct 97
Nvt = Vert_f_Pol [(j=cpol*7)+6];
off = j;
*/
Nvt = polyToVert[cpol].length;
/* } */
/* update_polygon(cpol) */
+// System.out.println("2 vet_pol[" + cpol + "] = false");
vet_pol[cpol] = false;
/* WLH 25 Oct 97
for (ivA=0; ivA<Nvt && Vert_f_Pol[ivA+off]!=vA; ivA++);
for (ivB=0; ivB<Nvt && Vert_f_Pol[ivB+off]!=vB; ivB++);
*/
for (ivA=0; ivA<Nvt && polyToVert[cpol][ivA]!=vA; ivA++);
for (ivB=0; ivB<Nvt && polyToVert[cpol][ivB]!=vB; ivB++);
if (( (ivB != 0) && ivA==(ivB-1)) || (!(ivB != 0) && ivA==Nvt-1)) {
/* ptT = NTAB + STAB[Nvt-3] + ivA*Nvt + 2; */
idx = STAB[Nvt-3] + ivA*Nvt + 2;
for (ii=2; ii<((Nvt < 6) ? Nvt:6); ii++) {
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx++]+off];
*/
+// System.out.println("7 Tri_Stripe[" + iST + "] from poly " + cpol);
Tri_Stripe[iST++] = polyToVert[cpol][NTAB[idx++]];
}
}
else {
/* ptT = ITAB + STAB[Nvt-3] + ivA*Nvt + 2; */
idx = STAB[Nvt-3] + ivA*Nvt + 2;
for (ii=2; ii<((Nvt < 6) ? Nvt:6); ii++) {
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[ITAB[idx++]+off];
*/
+// System.out.println("8 Tri_Stripe[" + iST + "] from poly " + cpol);
Tri_Stripe[iST++] = polyToVert[cpol][ITAB[idx++]];
}
}
vB = Tri_Stripe[iST-1];
vA = Tri_Stripe[iST-2];
/* get_pol_vert(vA,vB,cpol) { */
cpol = -1;
/* WLH 25 Oct 97
if (vA>=0 && vB>=0) {
i=vA*9;
k=i+Pol_f_Vert [i+8];
j=vB*9;
m=j+Pol_f_Vert [j+8];
while (i>0 && j>0 && i<k && j<m) {
if (Pol_f_Vert [i] == Pol_f_Vert [j] &&
vet_pol[Pol_f_Vert[i]] ) {
cpol=Pol_f_Vert[i];
break;
}
else if (Pol_f_Vert [i] < Pol_f_Vert [j])
i++;
else
j++;
}
}
*/
if (vA>=0 && vB>=0) {
int ilim = vertToPoly[vA].length;
k = 0;
int jlim = vertToPoly[vB].length;
m = 0;
// while (0<k && k<ilim && 0<m && m<jlim) {
while (0<vA && k<ilim && 0<vB && m<jlim) {
if (vertToPoly[vA][k] == vertToPoly[vB][m] &&
vet_pol[vertToPoly[vA][k]] ) {
cpol=vertToPoly[vA][k];
break;
}
else if (vertToPoly[vA][k] < vertToPoly[vB][m])
k++;
else
m++;
}
}
/* } */
if (cpol < 0) {
vA = Tri_Stripe[iST-3];
/* get_pol_vert(vA,vB,cpol) { */
cpol = -1;
/* WLH 25 Oct 97
if (vA>=0 && vB>=0) {
i=vA*9;
k=i+Pol_f_Vert [i+8];
j=vB*9;
m=j+Pol_f_Vert [j+8];
while (i>0 && j>0 && i<k && j<m) {
if (Pol_f_Vert [i] == Pol_f_Vert [j] &&
vet_pol[Pol_f_Vert[i]] ) {
cpol=Pol_f_Vert[i];
break;
}
else if (Pol_f_Vert [i] < Pol_f_Vert [j])
i++;
else
j++;
}
}
*/
if (vA>=0 && vB>=0) {
int ilim = vertToPoly[vA].length;
k = 0;
int jlim = vertToPoly[vB].length;
m = 0;
// while (0<k && k<ilim && 0<m && m<jlim) {
while (0<vA && k<ilim && 0<vB && m<jlim) {
if (vertToPoly[vA][k] == vertToPoly[vB][m] &&
vet_pol[vertToPoly[vA][k]] ) {
cpol=vertToPoly[vA][k];
break;
}
else if (vertToPoly[vA][k] < vertToPoly[vB][m])
k++;
else
m++;
}
}
/* } */
if (cpol < 0) {
f_line_conection = true;
break;
}
else {
+// System.out.println("9 Tri_Stripe[" + iST + "] where cpol = " + cpol);
+ // WLH 5 May 2004 - fix bug vintage 1990 or 91
+ if (iST > 0) {
+ Tri_Stripe[iST] = Tri_Stripe[iST-1];
+ iST++;
+ }
Tri_Stripe[iST++] = vA;
i = vA;
vA = vB;
vB = i;
}
}
}
}
return iST;
}
/** create a 2-D GeometryArray from this Set and color_values */
public VisADGeometryArray make2DGeometry(byte[][] color_values,
boolean indexed) throws VisADException {
if (DomainDimension != 3) {
throw new SetException("Irregular3DSet.make2DGeometry: " +
"DomainDimension must be 3, not " +
DomainDimension);
}
if (ManifoldDimension != 2) {
throw new SetException("Irregular3DSet.make2DGeometry: " +
"ManifoldDimension must be 2, not " +
ManifoldDimension);
}
int npolygons = Delan.Tri.length;
int nvertex = Delan.Vertices.length;
if (npolygons < 1 || nvertex < 3) return null;
// make sure all triangles have the same signature
// i.e., winding direction
int[][] Tri = Delan.Tri;
int[][] Walk = Delan.Walk;
int dim = Tri[0].length - 1;
int[][] tri = new int[npolygons][];
int[] poly_stack = new int[npolygons];
int[] walk_stack = new int[npolygons];
int sp; // stack pointer
for (int ii=0; ii<npolygons; ii++) {
// find an un-adjusted triangle
if (tri[ii] == null) {
// initialize its signature
tri[ii] = new int[3];
tri[ii][0] = Tri[ii][0];
tri[ii][1] = Tri[ii][1];
tri[ii][2] = Tri[ii][2];
// first stack entry, for recursive search of triangles
// via Walk array
sp = 0;
walk_stack[sp] = 0;
poly_stack[sp] = ii;
while (true) {
// find neighbor triangle via Walk
int i = poly_stack[sp];
int w = walk_stack[sp];
int j = Walk[i][w];
if (j >= 0 && tri[j] == null) {
// compare signatures of neighbors
int v1 = Tri[i][w];
int v2 = Tri[i][(w + 1) % 3];
int i1 = -1;
int i2 = -1;
int j1 = -1;
int j2 = -1;
for (int k=0; k<3; k++) {
if (tri[i][k] == v1) i1 = k;
if (tri[i][k] == v2) i2 = k;
if (Tri[j][k] == v1) j1 = k;
if (Tri[j][k] == v2) j2 = k;
}
tri[j] = new int[3];
tri[j][0] = Tri[j][0];
if ( ( (((i1 + 1) % 3) == i2) && (((j1 + 1) % 3) == j2) ) ||
( (((i2 + 1) % 3) == i1) && (((j2 + 1) % 3) == j1) ) ) {
tri[j][1] = Tri[j][2];
tri[j][2] = Tri[j][1];
}
else {
tri[j][1] = Tri[j][1];
tri[j][2] = Tri[j][2];
}
// add j to stack
sp++;
walk_stack[sp] = 0;
poly_stack[sp] = j;
}
else { // (j < 0 || tri[j] != null)
while (true) {
walk_stack[sp]++;
if (walk_stack[sp] < 3) {
break;
}
else {
sp--;
if (sp < 0) break;
}
} // end while (true)
} // end if (j < 0 || tri[j] != null)
if (sp < 0) break;
} // end while (true)
} // end if (tri[ii] == null)
} // end for (int ii=0; ii<npolygons; ii++)
float[][] samples = getSamples(false);
float[] NxA = new float[npolygons];
float[] NxB = new float[npolygons];
float[] NyA = new float[npolygons];
float[] NyB = new float[npolygons];
float[] NzA = new float[npolygons];
float[] NzB = new float[npolygons];
float[] Pnx = new float[npolygons];
float[] Pny = new float[npolygons];
float[] Pnz = new float[npolygons];
float[] NX = new float[nvertex];
float[] NY = new float[nvertex];
float[] NZ = new float[nvertex];
make_normals(samples[0], samples[1], samples[2],
NX, NY, NZ, nvertex, npolygons, Pnx, Pny, Pnz,
NxA, NxB, NyA, NyB, NzA, NzB, Delan.Vertices, tri);
// NxA, NxB, NyA, NyB, NzA, NzB, Delan.Vertices, Delan.Tri);
// take the garbage out
NxA = NxB = NyA = NyB = NzA = NzB = Pnx = Pny = Pnz = null;
float[] normals = new float[3 * nvertex];
int j = 0;
for (int i=0; i<nvertex; i++) {
normals[j++] = (float) NX[i];
normals[j++] = (float) NY[i];
normals[j++] = (float) NZ[i];
}
// take the garbage out
NX = NY = NZ = null;
// temporary array to hold maximum possible polytriangle strip
int[] stripe = new int[6 * npolygons];
int size_stripe =
poly_triangle_stripe(stripe, nvertex, npolygons,
Delan.Vertices, Delan.Tri);
if (indexed) {
VisADIndexedTriangleStripArray array =
new VisADIndexedTriangleStripArray();
// array.vertexFormat |= NORMALS;
array.normals = normals;
// take the garbage out
normals = null;
// set up indices
array.indexCount = size_stripe;
array.indices = new int[size_stripe];
System.arraycopy(stripe, 0, array.indices, 0, size_stripe);
array.stripVertexCounts = new int[1];
array.stripVertexCounts[0] = size_stripe;
// take the garbage out
stripe = null;
// set coordinates and colors
setGeometryArray(array, samples, 4, color_values);
// take the garbage out
samples = null;
return array;
}
else { // if (!indexed)
VisADTriangleStripArray array = new VisADTriangleStripArray();
array.stripVertexCounts = new int[] {size_stripe};
array.vertexCount = size_stripe;
array.normals = new float[3 * size_stripe];
int k = 0;
for (int i=0; i<3*size_stripe; i+=3) {
j = 3 * stripe[k];
array.normals[i] = normals[j];
array.normals[i+1] = normals[j+1];
array.normals[i+2] = normals[j+2];
k++;
}
normals = null;
array.coordinates = new float[3 * size_stripe];
k = 0;
for (int i=0; i<3*size_stripe; i+=3) {
j = stripe[k];
array.coordinates[i] = samples[0][j];
array.coordinates[i+1] = samples[1][j];
array.coordinates[i+2] = samples[2][j];
+/*
+System.out.println("strip[" + k + "] = (" + array.coordinates[i] + ", " +
+ array.coordinates[i+1] + ", " +
+ array.coordinates[i+2] + ")");
+*/
k++;
}
samples = null;
if (color_values != null) {
int color_length = color_values.length;
array.colors = new byte[color_length * size_stripe];
k = 0;
if (color_length == 4) {
for (int i=0; i<color_length*size_stripe; i+=color_length) {
j = stripe[k];
array.colors[i] = color_values[0][j];
array.colors[i+1] = color_values[1][j];
array.colors[i+2] = color_values[2][j];
array.colors[i+3] = color_values[3][j];
k++;
}
}
else { // if (color_length == 3)
for (int i=0; i<color_length*size_stripe; i+=color_length) {
j = stripe[k];
array.colors[i] = color_values[0][j];
array.colors[i+1] = color_values[1][j];
array.colors[i+2] = color_values[2][j];
k++;
}
}
}
color_values = null;
stripe = null;
return array;
} // end if (!indexed)
}
public Object cloneButType(MathType type) throws VisADException {
if (ManifoldDimension == 1) {
return new Irregular3DSet(type, Samples, newToOld, oldToNew,
DomainCoordinateSystem, SetUnits, SetErrors);
}
else {
return new Irregular3DSet(type, Samples, DomainCoordinateSystem,
SetUnits, SetErrors, Delan);
}
}
/* run 'java visad.Irregular3DSet' to test the Irregular3DSet class */
public static void main(String[] argv) throws VisADException {
float[][] samp = { {179, 232, 183, 244, 106, 344, 166, 304, 286},
{ 86, 231, 152, 123, 183, 153, 308, 325, 89},
{121, 301, 346, 352, 123, 125, 187, 101, 142} };
RealType test1 = RealType.getRealType("x");
RealType test2 = RealType.getRealType("y");
RealType test3 = RealType.getRealType("z");
RealType[] t_array = {test1, test2, test3};
RealTupleType t_tuple = new RealTupleType(t_array);
Irregular3DSet iSet3D = new Irregular3DSet(t_tuple, samp);
// print out Samples information
System.out.println("Samples:");
for (int i=0; i<iSet3D.Samples[0].length; i++) {
System.out.println("#"+i+":\t"+iSet3D.Samples[0][i]+", "
+iSet3D.Samples[1][i]+", "
+iSet3D.Samples[2][i]);
}
System.out.println(iSet3D.Delan.Tri.length
+" tetrahedrons in tetrahedralization.");
// test valueToIndex function
System.out.println("\nvalueToIndex test:");
float[][] value = { {189, 221, 319, 215, 196},
{166, 161, 158, 139, 285},
{207, 300, 127, 287, 194} };
int[] index = iSet3D.valueToIndex(value);
for (int i=0; i<index.length; i++) {
System.out.println(value[0][i]+", "+value[1][i]+", "
+value[2][i]+"\t--> #"+index[i]);
}
// test valueToInterp function
System.out.println("\nvalueToInterp test:");
int[][] indices = new int[value[0].length][];
float[][] weights = new float[value[0].length][];
iSet3D.valueToInterp(value, indices, weights);
for (int i=0; i<value[0].length; i++) {
System.out.println(value[0][i]+", "+value[1][i]+", "
+value[2][i]+"\t--> ["
+indices[i][0]+", "
+indices[i][1]+", "
+indices[i][2]+", "
+indices[i][3]+"]\tweight total: "
+(weights[i][0]+weights[i][1]
+weights[i][2]+weights[i][3]));
}
// test makeIsosurface function
System.out.println("\nmakeIsosurface test:");
float[] field = {100, 300, 320, 250, 80, 70, 135, 110, 105};
float[][] slice = new float[3][];
int[][][] polyvert = new int[1][][];
int[][][] vertpoly = new int[1][][];
iSet3D.makeIsosurface(288, field, null, slice, null, polyvert, vertpoly);
for (int i=0; i<slice[0].length; i++) {
for (int j=0; j<3; j++) {
slice[j][i] = (float) Math.round(1000*slice[j][i]) / 1000;
}
}
System.out.println("polygons:");
for (int i=0; i<polyvert[0].length; i++) {
System.out.print("#"+i+":");
/* WLH 25 Oct 97
for (int j=0; j<4; j++) {
if (polyvert[0][i][j] != -1) {
if (j == 1) {
if (polyvert[0][i][3] == -1) {
System.out.print("(tri)");
}
else {
System.out.print("(quad)");
}
}
System.out.println("\t"+slice[0][polyvert[0][i][j]]
+", "+slice[1][polyvert[0][i][j]]
+", "+slice[2][polyvert[0][i][j]]);
}
}
*/
for (int j=0; j<polyvert[0][i].length; j++) {
if (j == 1) {
if (polyvert[0][i].length == 3) {
System.out.print("(tri)");
}
else {
System.out.print("(quad)");
}
}
System.out.println("\t"+slice[0][polyvert[0][i][j]]
+", "+slice[1][polyvert[0][i][j]]
+", "+slice[2][polyvert[0][i][j]]);
}
}
System.out.println();
for (int i=0; i<polyvert[0].length; i++) {
int a = polyvert[0][i][0];
int b = polyvert[0][i][1];
int c = polyvert[0][i][2];
int d = polyvert[0][i].length==4 ? polyvert[0][i][3] : -1;
boolean found = false;
for (int j=0; j<vertpoly[0][a].length; j++) {
if (vertpoly[0][a][j] == i) found = true;
}
if (!found) {
System.out.println("vertToPoly array corrupted at triangle #"
+i+" vertex #0!");
}
found = false;
for (int j=0; j<vertpoly[0][b].length; j++) {
if (vertpoly[0][b][j] == i) found = true;
}
if (!found) {
System.out.println("vertToPoly array corrupted at triangle #"
+i+" vertex #1!");
}
found = false;
for (int j=0; j<vertpoly[0][c].length; j++) {
if (vertpoly[0][c][j] == i) found = true;
}
if (!found) {
System.out.println("vertToPoly array corrupted at triangle #"
+i+" vertex #2!");
}
found = false;
if (d != -1) {
for (int j=0; j<vertpoly[0][d].length; j++) {
if (vertpoly[0][d][j] == i) found = true;
}
if (!found) {
System.out.println("vertToPoly array corrupted at triangle #"
+i+" vertex #3!");
}
}
}
}
/* Here's the output:
iris 45% java visad.Irregular3DSet
Samples:
#0: 179.0, 86.0, 121.0
#1: 232.0, 231.0, 301.0
#2: 183.0, 152.0, 346.0
#3: 244.0, 123.0, 352.0
#4: 106.0, 183.0, 123.0
#5: 344.0, 153.0, 125.0
#6: 166.0, 308.0, 187.0
#7: 304.0, 325.0, 101.0
#8: 286.0, 89.0, 142.0
15 tetrahedrons in tetrahedralization.
valueToIndex test:
189.0, 166.0, 207.0 --> #0
221.0, 161.0, 300.0 --> #2
319.0, 158.0, 127.0 --> #5
215.0, 139.0, 287.0 --> #2
196.0, 285.0, 194.0 --> #6
valueToInterp test:
189.0, 166.0, 207.0 --> [0, 1, 2, 4] weight total: 1.0
221.0, 161.0, 300.0 --> [1, 2, 3, 8] weight total: 1.0
319.0, 158.0, 127.0 --> [4, 5, 6, 8] weight total: 0.9999999999999999
215.0, 139.0, 287.0 --> [1, 2, 3, 8] weight total: 1.0
196.0, 285.0, 194.0 --> [1, 5, 6, 7] weight total: 1.0
makeIsosurface test:
polygons:
#0: 237.843, 226.93, 291.817
(tri) 227.2, 236.6, 292.709
236.547, 236.937, 288.368
#1: 228.82, 222.3, 290.2
(quad) 182.418, 142.4, 313.273
225.127, 228.382, 291.291
172.733, 156.133, 316.267
#2: 225.127, 228.382, 291.291
(tri) 227.2, 236.6, 292.709
235.323, 222.262, 291.215
#3: 228.82, 222.3, 290.2
(quad) 182.418, 142.4, 313.273
235.323, 222.262, 291.215
198.33, 142.623, 315.637
#4: 234.88, 205.08, 313.24
(tri) 237.843, 226.93, 291.817
235.323, 222.262, 291.215
#5: 182.418, 142.4, 313.273
(tri) 210.886, 138.743, 348.743
198.33, 142.623, 315.637
#6: 234.88, 205.08, 313.24
(quad) 235.323, 222.262, 291.215
210.886, 138.743, 348.743
198.33, 142.623, 315.637
#7: 225.127, 228.382, 291.291
(quad) 227.2, 236.6, 292.709
172.733, 156.133, 316.267
180.059, 178.984, 318.497
#8: 234.88, 205.08, 313.24
(tri) 237.843, 226.93, 291.817
236.547, 236.937, 288.368
#9: 228.82, 222.3, 290.2
(tri) 225.127, 228.382, 291.291
235.323, 222.262, 291.215
#10: 237.843, 226.93, 291.817
(tri) 227.2, 236.6, 292.709
235.323, 222.262, 291.215
iris 46%
*/
}
| false | true | private void makeIsosurface(float isolevel, float[] fieldValues,
byte[][] auxValues, float[][] fieldVertices,
byte[][] auxLevels, int[][][] polyToVert,
int[][][] vertToPoly) throws VisADException {
boolean DEBUG = false;
if (ManifoldDimension != 3) {
throw new DisplayException("Irregular3DSet.makeIsosurface: " +
"ManifoldDimension must be 3, not " +
ManifoldDimension);
}
if (fieldValues.length != Length) {
throw new DisplayException("Irregular3DSet.makeIsosurface: "
+"fieldValues length does't match");
}
if (Double.isNaN(isolevel)) {
throw new DisplayException("Irregular3DSet.makeIsosurface: "
+"isolevel cannot be missing");
}
if (fieldVertices.length != 3 || polyToVert.length != 1
|| vertToPoly.length != 1) {
throw new DisplayException("Irregular3DSet.makeIsosurface: return value"
+ " arrays not correctly initialized " +
fieldVertices.length + " " + polyToVert.length +
" " + vertToPoly.length);
}
int naux = (auxValues != null) ? auxValues.length : 0;
if (naux > 0) {
if (auxLevels == null || auxLevels.length != naux) {
throw new DisplayException("Irregular3DSet.makeIsosurface: "
+"auxLevels length doesn't match");
}
for (int i=0; i<naux; i++) {
if (auxValues[i].length != Length) {
throw new DisplayException("Irregular3DSet.makeIsosurface: "
+"auxValues lengths don't match");
}
}
}
else {
if (auxLevels != null) {
throw new DisplayException("Irregular3DSet.makeIsosurface: "
+"auxValues null but auxLevels not null");
}
}
if (DEBUG) {
System.out.println("isolevel = " + isolevel + "\n");
System.out.println("fieldValues " + fieldValues.length);
for (int i=0; i<fieldValues.length; i++) {
System.out.println(" " + i + " -> " + fieldValues[i]);
}
System.out.println(Delan.sampleString(Samples));
}
int trilength = Delan.Tri.length;
// temporary storage of polyToVert structure
int[][] polys = new int[trilength][4];
// pointers from global edge number to nvertex
int[] globalToVertex = new int[Delan.NumEdges];
for (int i=0; i<Delan.NumEdges; i++) globalToVertex[i] = -1;
// global edges temporary storage array
float[][] edgeInterp = new float[DomainDimension][Delan.NumEdges];
for (int i=0; i<Delan.NumEdges; i++) edgeInterp[0][i] = Float.NaN;
// global edges temporary storage array for aux levels
byte[][] auxInterp = (naux > 0) ? new byte[naux][Delan.NumEdges] : null;
int t;
int nvertex = 0;
int npolygons = 0;
for (int i=0; i<trilength; i++) {
int v0 = Delan.Tri[i][0];
int v1 = Delan.Tri[i][1];
int v2 = Delan.Tri[i][2];
int v3 = Delan.Tri[i][3];
float f0 = (float) fieldValues[v0];
float f1 = (float) fieldValues[v1];
float f2 = (float) fieldValues[v2];
float f3 = (float) fieldValues[v3];
int e0, e1, e2, e3, e4, e5;
// compute tetrahedron signature
// vector from v0 to v3
float vx = Samples[0][v3] - Samples[0][v0];
float vy = Samples[1][v3] - Samples[1][v0];
float vz = Samples[2][v3] - Samples[2][v0];
// cross product (v2 - v0) x (v1 - v0)
float sx = Samples[0][v2] - Samples[0][v0];
float sy = Samples[1][v2] - Samples[1][v0];
float sz = Samples[2][v2] - Samples[2][v0];
float tx = Samples[0][v1] - Samples[0][v0];
float ty = Samples[1][v1] - Samples[1][v0];
float tz = Samples[2][v1] - Samples[2][v0];
float cx = sy * tz - sz * ty;
float cy = sz * tx - sx * tz;
float cz = sx * ty - sy * tx;
// signature is sign of v (dot) c
float sig = vx * cx + vy * cy + vz * cz;
// 8 possibilities
int index = ((f0 > isolevel) ? 1 : 0)
+ ((f1 > isolevel) ? 2 : 0)
+ ((f2 > isolevel) ? 4 : 0)
+ ((f3 > isolevel) ? 8 : 0);
// apply signature to index
if (sig < 0.0f) index = 15 - index;
switch (index) {
case 0:
case 15: // plane does not intersect this tetrahedron
break;
case 1:
case 14: // plane slices a triangle
// define edge values needed
e0 = Delan.Edges[i][0];
e1 = Delan.Edges[i][1];
e2 = Delan.Edges[i][2];
// fill in edge interpolation values if they haven't been found
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e0])) {
*/
// test for missing
if (edgeInterp[0][e0] != edgeInterp[0][e0]) {
float a = (isolevel - f1)/(f0 - f1);
if (a < 0) a = -a;
edgeInterp[0][e0] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v1];
edgeInterp[1][e0] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v1];
edgeInterp[2][e0] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v1];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) );
auxInterp[j][e0] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e0] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v1];
*/
}
globalToVertex[e0] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e1])) {
*/
// test for missing
if (edgeInterp[0][e1] != edgeInterp[0][e1]) {
float a = (isolevel - f2)/(f0 - f2);
if (a < 0) a = -a;
edgeInterp[0][e1] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v2];
edgeInterp[1][e1] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v2];
edgeInterp[2][e1] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e1] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e1] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e2])) {
*/
// test for missing
if (edgeInterp[0][e2] != edgeInterp[0][e2]) {
float a = (isolevel - f3)/(f0 - f3);
if (a < 0) a = -a;
edgeInterp[0][e2] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v3];
edgeInterp[1][e2] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v3];
edgeInterp[2][e2] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e2] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e2] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e2] = nvertex;
nvertex++;
}
// fill in the polys and vertToPoly arrays
polys[npolygons][0] = e0;
if (index == 1) {
polys[npolygons][1] = e1;
polys[npolygons][2] = e2;
}
else { // index == 14
polys[npolygons][1] = e2;
polys[npolygons][2] = e1;
}
polys[npolygons][3] = -1;
// on to the next tetrahedron
npolygons++;
break;
case 2:
case 13: // plane slices a triangle
// define edge values needed
e0 = Delan.Edges[i][0];
e3 = Delan.Edges[i][3];
e4 = Delan.Edges[i][4];
// fill in edge interpolation values if they haven't been found
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e0])) {
*/
// test for missing
if (edgeInterp[0][e0] != edgeInterp[0][e0]) {
float a = (isolevel - f1)/(f0 - f1);
if (a < 0) a = -a;
edgeInterp[0][e0] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v1];
edgeInterp[1][e0] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v1];
edgeInterp[2][e0] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v1];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) );
auxInterp[j][e0] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e0] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v1];
*/
}
globalToVertex[e0] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e3])) {
*/
// test for missing
if (edgeInterp[0][e3] != edgeInterp[0][e3]) {
float a = (isolevel - f2)/(f1 - f2);
if (a < 0) a = -a;
edgeInterp[0][e3] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v2];
edgeInterp[1][e3] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v2];
edgeInterp[2][e3] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e3] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e3] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e3] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e4])) {
*/
// test for missing
if (edgeInterp[0][e4] != edgeInterp[0][e4]) {
float a = (isolevel - f3)/(f1 - f3);
if (a < 0) a = -a;
edgeInterp[0][e4] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v3];
edgeInterp[1][e4] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v3];
edgeInterp[2][e4] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e4] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e4] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e4] = nvertex;
nvertex++;
}
// fill in the polys array
polys[npolygons][0] = e0;
if (index == 2) {
polys[npolygons][1] = e4;
polys[npolygons][2] = e3;
}
else { // index == 13
polys[npolygons][1] = e3;
polys[npolygons][2] = e4;
}
polys[npolygons][3] = -1;
// on to the next tetrahedron
npolygons++;
break;
case 3:
case 12: // plane slices a quadrilateral
// define edge values needed
e1 = Delan.Edges[i][1];
e2 = Delan.Edges[i][2];
e3 = Delan.Edges[i][3];
e4 = Delan.Edges[i][4];
// fill in edge interpolation values if they haven't been found
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e1])) {
*/
// test for missing
if (edgeInterp[0][e1] != edgeInterp[0][e1]) {
float a = (isolevel - f2)/(f0 - f2);
if (a < 0) a = -a;
edgeInterp[0][e1] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v2];
edgeInterp[1][e1] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v2];
edgeInterp[2][e1] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e1] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e1] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e2])) {
*/
// test for missing
if (edgeInterp[0][e2] != edgeInterp[0][e2]) {
float a = (isolevel - f3)/(f0 - f3);
if (a < 0) a = -a;
edgeInterp[0][e2] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v3];
edgeInterp[1][e2] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v3];
edgeInterp[2][e2] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e2] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e2] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e2] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e4])) {
*/
// test for missing
if (edgeInterp[0][e4] != edgeInterp[0][e4]) {
float a = (isolevel - f3)/(f1 - f3);
if (a < 0) a = -a;
edgeInterp[0][e4] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v3];
edgeInterp[1][e4] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v3];
edgeInterp[2][e4] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e4] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e4] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e4] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e3])) {
*/
// test for missing
if (edgeInterp[0][e3] != edgeInterp[0][e3]) {
float a = (isolevel - f2)/(f1 - f2);
if (a < 0) a = -a;
edgeInterp[0][e3] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v2];
edgeInterp[1][e3] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v2];
edgeInterp[2][e3] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e3] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e3] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e3] = nvertex;
nvertex++;
}
// fill in the polys array
polys[npolygons][0] = e1;
if (index == 3) {
polys[npolygons][1] = e2;
polys[npolygons][2] = e4;
polys[npolygons][3] = e3;
}
else { // index == 12
polys[npolygons][1] = e3;
polys[npolygons][2] = e4;
polys[npolygons][3] = e2;
}
// on to the next tetrahedron
npolygons++;
break;
case 4:
case 11: // plane slices a triangle
// define edge values needed
e1 = Delan.Edges[i][1];
e3 = Delan.Edges[i][3];
e5 = Delan.Edges[i][5];
// fill in edge interpolation values if they haven't been found
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e1])) {
*/
// test for missing
if (edgeInterp[0][e1] != edgeInterp[0][e1]) {
float a = (isolevel - f2)/(f0 - f2);
if (a < 0) a = -a;
edgeInterp[0][e1] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v2];
edgeInterp[1][e1] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v2];
edgeInterp[2][e1] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e1] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e1] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e3])) {
*/
// test for missing
if (edgeInterp[0][e3] != edgeInterp[0][e3]) {
float a = (isolevel - f2)/(f1 - f2);
if (a < 0) a = -a;
edgeInterp[0][e3] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v2];
edgeInterp[1][e3] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v2];
edgeInterp[2][e3] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e3] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e3] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e3] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e5])) {
*/
// test for missing
if (edgeInterp[0][e5] != edgeInterp[0][e5]) {
float a = (isolevel - f3)/(f2 - f3);
if (a < 0) a = -a;
edgeInterp[0][e5] = (float) a*Samples[0][v2] + (1-a)*Samples[0][v3];
edgeInterp[1][e5] = (float) a*Samples[1][v2] + (1-a)*Samples[1][v3];
edgeInterp[2][e5] = (float) a*Samples[2][v2] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e5] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e5] = (float) a*auxValues[j][v2] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e5] = nvertex;
nvertex++;
}
// fill in the polys array
polys[npolygons][0] = e1;
if (index == 4) {
polys[npolygons][1] = e3;
polys[npolygons][2] = e5;
}
else { // index == 11
polys[npolygons][1] = e5;
polys[npolygons][2] = e3;
}
polys[npolygons][3] = -1;
// on to the next tetrahedron
npolygons++;
break;
case 5:
case 10: // plane slices a quadrilateral
// define edge values needed
e0 = Delan.Edges[i][0];
e2 = Delan.Edges[i][2];
e3 = Delan.Edges[i][3];
e5 = Delan.Edges[i][5];
// fill in edge interpolation values if they haven't been found
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e0])) {
*/
// test for missing
if (edgeInterp[0][e0] != edgeInterp[0][e0]) {
float a = (isolevel - f1)/(f0 - f1);
if (a < 0) a = -a;
edgeInterp[0][e0] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v1];
edgeInterp[1][e0] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v1];
edgeInterp[2][e0] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v1];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) );
auxInterp[j][e0] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e0] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v1];
*/
}
globalToVertex[e0] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e2])) {
*/
// test for missing
if (edgeInterp[0][e2] != edgeInterp[0][e2]) {
float a = (isolevel - f3)/(f0 - f3);
if (a < 0) a = -a;
edgeInterp[0][e2] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v3];
edgeInterp[1][e2] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v3];
edgeInterp[2][e2] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e2] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e2] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e2] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e5])) {
*/
// test for missing
if (edgeInterp[0][e5] != edgeInterp[0][e5]) {
float a = (isolevel - f3)/(f2 - f3);
if (a < 0) a = -a;
edgeInterp[0][e5] = (float) a*Samples[0][v2] + (1-a)*Samples[0][v3];
edgeInterp[1][e5] = (float) a*Samples[1][v2] + (1-a)*Samples[1][v3];
edgeInterp[2][e5] = (float) a*Samples[2][v2] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e5] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e5] = (float) a*auxValues[j][v2] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e5] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e3])) {
*/
// test for missing
if (edgeInterp[0][e3] != edgeInterp[0][e3]) {
float a = (isolevel - f2)/(f1 - f2);
if (a < 0) a = -a;
edgeInterp[0][e3] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v2];
edgeInterp[1][e3] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v2];
edgeInterp[2][e3] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e3] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e3] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e3] = nvertex;
nvertex++;
}
// fill in the polys array
polys[npolygons][0] = e0;
if (index == 5) {
polys[npolygons][1] = e3;
polys[npolygons][2] = e5;
polys[npolygons][3] = e2;
}
else { // index == 10
polys[npolygons][1] = e2;
polys[npolygons][2] = e5;
polys[npolygons][3] = e3;
}
// on to the next tetrahedron
npolygons++;
break;
case 6:
case 9: // plane slices a quadrilateral
// define edge values needed
e0 = Delan.Edges[i][0];
e1 = Delan.Edges[i][1];
e4 = Delan.Edges[i][4];
e5 = Delan.Edges[i][5];
// fill in edge interpolation values if they haven't been found
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e0])) {
*/
// test for missing
if (edgeInterp[0][e0] != edgeInterp[0][e0]) {
float a = (isolevel - f1)/(f0 - f1);
if (a < 0) a = -a;
edgeInterp[0][e0] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v1];
edgeInterp[1][e0] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v1];
edgeInterp[2][e0] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v1];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) );
auxInterp[j][e0] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e0] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v1];
*/
}
globalToVertex[e0] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e1])) {
*/
// test for missing
if (edgeInterp[0][e1] != edgeInterp[0][e1]) {
float a = (isolevel - f2)/(f0 - f2);
if (a < 0) a = -a;
edgeInterp[0][e1] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v2];
edgeInterp[1][e1] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v2];
edgeInterp[2][e1] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e1] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e1] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e5])) {
*/
// test for missing
if (edgeInterp[0][e5] != edgeInterp[0][e5]) {
float a = (isolevel - f3)/(f2 - f3);
if (a < 0) a = -a;
edgeInterp[0][e5] = (float) a*Samples[0][v2] + (1-a)*Samples[0][v3];
edgeInterp[1][e5] = (float) a*Samples[1][v2] + (1-a)*Samples[1][v3];
edgeInterp[2][e5] = (float) a*Samples[2][v2] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e5] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e5] = (float) a*auxValues[j][v2] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e5] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e4])) {
*/
// test for missing
if (edgeInterp[0][e4] != edgeInterp[0][e4]) {
float a = (isolevel - f3)/(f1 - f3);
if (a < 0) a = -a;
edgeInterp[0][e4] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v3];
edgeInterp[1][e4] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v3];
edgeInterp[2][e4] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e4] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e4] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e4] = nvertex;
nvertex++;
}
// fill in the polys array
polys[npolygons][0] = e0;
if (index == 6) {
polys[npolygons][1] = e4;
polys[npolygons][2] = e5;
polys[npolygons][3] = e1;
}
else { // index == 9
polys[npolygons][1] = e1;
polys[npolygons][2] = e5;
polys[npolygons][3] = e4;
}
// on to the next tetrahedron
npolygons++;
break;
case 7:
case 8: // plane slices a triangle
// interpolate between 3:0, 3:1, 3:2 for tri edges, same as case 8
// define edge values needed
e2 = Delan.Edges[i][2];
e4 = Delan.Edges[i][4];
e5 = Delan.Edges[i][5];
// fill in edge interpolation values if they haven't been found
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e2])) {
*/
// test for missing
if (edgeInterp[0][e2] != edgeInterp[0][e2]) {
float a = (isolevel - f3)/(f0 - f3);
if (a < 0) a = -a;
edgeInterp[0][e2] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v3];
edgeInterp[1][e2] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v3];
edgeInterp[2][e2] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e2] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e2] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e2] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e4])) {
*/
// test for missing
if (edgeInterp[0][e4] != edgeInterp[0][e4]) {
float a = (isolevel - f3)/(f1 - f3);
if (a < 0) a = -a;
edgeInterp[0][e4] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v3];
edgeInterp[1][e4] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v3];
edgeInterp[2][e4] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e4] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e4] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e4] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e5])) {
*/
// test for missing
if (edgeInterp[0][e5] != edgeInterp[0][e5]) {
float a = (isolevel - f3)/(f2 - f3);
if (a < 0) a = -a;
edgeInterp[0][e5] = (float) a*Samples[0][v2] + (1-a)*Samples[0][v3];
edgeInterp[1][e5] = (float) a*Samples[1][v2] + (1-a)*Samples[1][v3];
edgeInterp[2][e5] = (float) a*Samples[2][v2] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e5] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e5] = (float) a*auxValues[j][v2] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e5] = nvertex;
nvertex++;
}
// fill in the polys array
polys[npolygons][0] = e2;
if (index == 7) {
polys[npolygons][1] = e4;
polys[npolygons][2] = e5;
}
else { // index == 8
polys[npolygons][1] = e5;
polys[npolygons][2] = e4;
}
polys[npolygons][3] = -1;
// on to the next tetrahedron
npolygons++;
break;
} // end switch (index)
} // end for (int i=0; i<trilength; i++)
if (DEBUG) {
System.out.println("\npolys (polys -> global edges) " + npolygons + "\n");
for (int i=0; i<npolygons; i++) {
String s = " " + i + " -> ";
for (int j=0; j<4; j++) {
s = s + " " + polys[i][j];
}
System.out.println(s + "\n");
}
}
// transform polys array into polyToVert array
polyToVert[0] = new int[npolygons][];
for (int i=0; i<npolygons; i++) {
int n = polys[i][3] < 0 ? 3 : 4;
polyToVert[0][i] = new int[n];
for (int j=0; j<n; j++) polyToVert[0][i][j] = globalToVertex[polys[i][j]];
}
if (DEBUG) {
System.out.println("\npolyToVert (polys -> vertices) " + npolygons + "\n");
for (int i=0; i<npolygons; i++) {
String s = " " + i + " -> ";
for (int j=0; j<polyToVert[0][i].length; j++) {
s = s + " " + polyToVert[0][i][j];
}
System.out.println(s + "\n");
}
}
// build nverts helper array
int[] nverts = new int[nvertex];
for (int i=0; i<nvertex; i++) nverts[i] = 0;
for (int i=0; i<npolygons; i++) {
nverts[polyToVert[0][i][0]]++;
nverts[polyToVert[0][i][1]]++;
nverts[polyToVert[0][i][2]]++;
if (polyToVert[0][i].length > 3) nverts[polyToVert[0][i][3]]++;
}
// initialize vertToPoly array
vertToPoly[0] = new int[nvertex][];
for (int i=0; i<nvertex; i++) {
vertToPoly[0][i] = new int[nverts[i]];
}
// fill in vertToPoly array
for (int i=0; i<nvertex; i++) nverts[i] = 0;
for (int i=0; i<npolygons; i++) {
int a = polyToVert[0][i][0];
int b = polyToVert[0][i][1];
int c = polyToVert[0][i][2];
vertToPoly[0][a][nverts[a]++] = i;
vertToPoly[0][b][nverts[b]++] = i;
vertToPoly[0][c][nverts[c]++] = i;
if (polyToVert[0][i].length > 3) {
int d = polyToVert[0][i][3];
if (d != -1) vertToPoly[0][d][nverts[d]++] = i;
}
}
if (DEBUG) {
System.out.println("\nvertToPoly (vertices -> polys) " + nvertex + "\n");
for (int i=0; i<nvertex; i++) {
String s = " " + i + " -> ";
for (int j=0; j<vertToPoly[0][i].length; j++) {
s = s + " " + vertToPoly[0][i][j];
}
System.out.println(s + "\n");
}
}
// set up fieldVertices and auxLevels
fieldVertices[0] = new float[nvertex];
fieldVertices[1] = new float[nvertex];
fieldVertices[2] = new float[nvertex];
for (int j=0; j<naux; j++) {
auxLevels[j] = new byte[nvertex];
}
for (int i=0; i<Delan.NumEdges; i++) {
int k = globalToVertex[i];
if (k >= 0) {
fieldVertices[0][k] = edgeInterp[0][i];
fieldVertices[1][k] = edgeInterp[1][i];
fieldVertices[2][k] = edgeInterp[2][i];
for (int j=0; j<naux; j++) {
auxLevels[j][k] = auxInterp[j][i];
}
}
}
if (DEBUG) {
System.out.println("\nfieldVertices " + nvertex + "\n");
for (int i=0; i<nvertex; i++) {
String s = " " + i + " -> ";
for (int j=0; j<3; j++) {
s = s + " " + fieldVertices[j][i];
}
System.out.println(s + "\n");
}
}
}
/*
make_normals and poly_triangle_stripe altered according to:
Pol_f_Vert[9*i + 8] --> vertToPoly[i].length
Pol_f_Vert[9*i + off] --> vertToPoly[i][off]
Vert_f_Pol[7*i + 6] --> polyToVert[i].length
Vert_f_Pol[7*i + off] --> polyToVert[i][off]
*/
/* from Contour3D.java, used by make_normals */
static final float EPS_0 = (float) 1.0e-5;
/* copied from Contour3D.java */
private static void make_normals(float[] VX, float[] VY, float[] VZ,
float[] NX, float[] NY, float[] NZ, int nvertex,
int npolygons, float[] Pnx, float[] Pny, float[] Pnz,
float[] NxA, float[] NxB, float[] NyA, float[] NyB,
float[] NzA, float[] NzB,
int[][] vertToPoly, int[][] polyToVert)
/* WLH 25 Oct 97
int[] Pol_f_Vert, int[] Vert_f_Pol )
*/
throws VisADException {
int i, k, n;
int i1, i2, ix, iy, iz, ixb, iyb, izb;
int max_vert_per_pol, swap_flag;
float x, y, z, a, minimum_area, len;
int iv[] = new int[3];
if (nvertex <= 0) return;
for (i = 0; i < nvertex; i++) {
NX[i] = 0;
NY[i] = 0;
NZ[i] = 0;
}
// WLH 12 Nov 2001
// minimum_area = (float) ((1.e-4 > EPS_0) ? 1.e-4 : EPS_0);
minimum_area = Float.MIN_VALUE;
/* Calculate maximum number of vertices per polygon */
/* WLH 25 Oct 97
k = 6;
n = 7*npolygons;
*/
k = 0;
while ( true ) {
/* WLH 25 Oct 97
for (i=k+7; i<n; i+=7)
if (Vert_f_Pol[i] > Vert_f_Pol[k]) break;
*/
for (i=k+1; i<npolygons; i++)
if (polyToVert[i].length > polyToVert[k].length) break;
/* WLH 25 Oct 97
if (i >= n) break;
*/
if (i >= npolygons) break;
k = i;
}
/* WLH 25 Oct 97
max_vert_per_pol = Vert_f_Pol[k];
*/
max_vert_per_pol = polyToVert[k].length;
/* Calculate the Normals vector components for each Polygon */
for ( i=0; i<npolygons; i++) { /* Vectorized */
/* WLH 25 Oct 97
if (Vert_f_Pol[6+i*7]>0) {
NxA[i] = VX[Vert_f_Pol[1+i*7]] - VX[Vert_f_Pol[0+i*7]];
NyA[i] = VY[Vert_f_Pol[1+i*7]] - VY[Vert_f_Pol[0+i*7]];
NzA[i] = VZ[Vert_f_Pol[1+i*7]] - VZ[Vert_f_Pol[0+i*7]];
}
*/
if (polyToVert[i].length>0) {
int j1 = polyToVert[i][1];
int j0 = polyToVert[i][0];
NxA[i] = VX[j1] - VX[j0];
NyA[i] = VY[j1] - VY[j0];
NzA[i] = VZ[j1] - VZ[j0];
}
}
swap_flag = 0;
for ( k = 2; k < max_vert_per_pol; k++ ) {
if (swap_flag==0) {
/*$dir no_recurrence */ /* Vectorized */
for ( i=0; i<npolygons; i++ ) {
/* WLH 25 Oct 97
if ( Vert_f_Pol[k+i*7] >= 0 ) {
NxB[i] = VX[Vert_f_Pol[k+i*7]] - VX[Vert_f_Pol[0+i*7]];
NyB[i] = VY[Vert_f_Pol[k+i*7]] - VY[Vert_f_Pol[0+i*7]];
NzB[i] = VZ[Vert_f_Pol[k+i*7]] - VZ[Vert_f_Pol[0+i*7]];
*/
if ( k < polyToVert[i].length ) {
int jk = polyToVert[i][k];
int j0 = polyToVert[i][0];
NxB[i] = VX[jk] - VX[j0];
NyB[i] = VY[jk] - VY[j0];
NzB[i] = VZ[jk] - VZ[j0];
Pnx[i] = NyA[i]*NzB[i] - NzA[i]*NyB[i];
Pny[i] = NzA[i]*NxB[i] - NxA[i]*NzB[i];
Pnz[i] = NxA[i]*NyB[i] - NyA[i]*NxB[i];
NxA[i] = Pnx[i]*Pnx[i] + Pny[i]*Pny[i] + Pnz[i]*Pnz[i];
if (NxA[i] > minimum_area) {
Pnx[i] /= NxA[i];
Pny[i] /= NxA[i];
Pnz[i] /= NxA[i];
}
}
}
}
else { /* swap_flag!=0 */
/*$dir no_recurrence */ /* Vectorized */
for (i=0; i<npolygons; i++) {
/* WLH 25 Oct 97
if ( Vert_f_Pol[k+i*7] >= 0 ) {
NxA[i] = VX[Vert_f_Pol[k+i*7]] - VX[Vert_f_Pol[0+i*7]];
NyA[i] = VY[Vert_f_Pol[k+i*7]] - VY[Vert_f_Pol[0+i*7]];
NzA[i] = VZ[Vert_f_Pol[k+i*7]] - VZ[Vert_f_Pol[0+i*7]];
*/
if ( k < polyToVert[i].length ) {
int jk = polyToVert[i][k];
int j0 = polyToVert[i][0];
NxA[i] = VX[jk] - VX[j0];
NyA[i] = VY[jk] - VY[j0];
NzA[i] = VZ[jk] - VZ[j0];
Pnx[i] = NyB[i]*NzA[i] - NzB[i]*NyA[i];
Pny[i] = NzB[i]*NxA[i] - NxB[i]*NzA[i];
Pnz[i] = NxB[i]*NyA[i] - NyB[i]*NxA[i];
NxB[i] = Pnx[i]*Pnx[i] + Pny[i]*Pny[i] + Pnz[i]*Pnz[i];
if (NxB[i] > minimum_area) {
Pnx[i] /= NxB[i];
Pny[i] /= NxB[i];
Pnz[i] /= NxB[i];
}
}
} // end for (i=0; i<npolygons; i++)
} // end swap_flag!=0
/* This Loop <CAN'T> be Vectorized */
for ( i=0; i<npolygons; i++ ) {
/* WLH 25 Oct 97
if (Vert_f_Pol[k+i*7] >= 0) {
iv[0] = Vert_f_Pol[0+i*7];
iv[1] = Vert_f_Pol[(k-1)+i*7];
iv[2] = Vert_f_Pol[k+i*7];
*/
if (k < polyToVert[i].length) {
iv[0] = polyToVert[i][0];
iv[1] = polyToVert[i][k-1];
iv[2] = polyToVert[i][k];
x = Pnx[i]; y = Pny[i]; z = Pnz[i];
/*
System.out.println("vertices: " + iv[0] + " " + iv[1] + " " + iv[2]);
System.out.println(" normal: " + x + " " + y + " " + z + "\n");
*/
// Update the origin vertex
NX[iv[0]] += x; NY[iv[0]] += y; NZ[iv[0]] += z;
// Update the vertex that defines the first vector
NX[iv[1]] += x; NY[iv[1]] += y; NZ[iv[1]] += z;
// Update the vertex that defines the second vector
NX[iv[2]] += x; NY[iv[2]] += y; NZ[iv[2]] += z;
}
} // end for ( i=0; i<npolygons; i++ )
swap_flag = ( (swap_flag != 0) ? 0 : 1 );
} // end for ( k = 2; k < max_vert_per_pol; k++ )
/* Normalize the Normals */
for ( i=0; i<nvertex; i++ ) { /* Vectorized */
len = (float) Math.sqrt(NX[i]*NX[i] + NY[i]*NY[i] + NZ[i]*NZ[i]);
if (len > EPS_0) {
NX[i] /= len;
NY[i] /= len;
NZ[i] /= len;
}
}
}
/* from Contour3D.java, used by poly_triangle_stripe */
static final int NTAB[] =
{ 0,1,2, 1,2,0, 2,0,1,
0,1,3,2, 1,2,0,3, 2,3,1,0, 3,0,2,1,
0,1,4,2,3, 1,2,0,3,4, 2,3,1,4,0, 3,4,2,0,1, 4,0,3,1,2,
0,1,5,2,4,3, 1,2,0,3,5,4, 2,3,1,4,0,5, 3,4,2,5,1,0, 4,5,3,0,2,1,
5,0,4,1,3,2
};
/* from Contour3D.java, used by poly_triangle_stripe */
static final int ITAB[] =
{ 0,2,1, 1,0,2, 2,1,0,
0,3,1,2, 1,0,2,3, 2,1,3,0, 3,2,0,1,
0,4,1,3,2, 1,0,2,4,3, 2,1,3,0,4, 3,2,4,1,0, 4,3,0,2,1,
0,5,1,4,2,3, 1,0,2,5,3,4, 2,1,3,0,4,5, 3,2,4,1,5,0, 4,3,5,2,0,1,
5,4,0,3,1,2
};
/* from Contour3D.java, used by poly_triangle_stripe */
static final int STAB[] = { 0, 9, 25, 50 };
/* copied from Contour3D.java */
static int poly_triangle_stripe( int[] Tri_Stripe,
int nvertex, int npolygons,
int[][] vertToPoly, int[][] polyToVert)
/* WLH 25 Oct 97
int[] Pol_f_Vert, int[] Vert_f_Pol )
*/
throws VisADException {
int i, j, k, m, ii, npol, cpol, idx, off, Nvt,
vA, vB, ivA, ivB, iST, last_pol;
boolean f_line_conection = false;
boolean[] vet_pol = new boolean[npolygons];
last_pol = 0;
npol = 0;
iST = 0;
ivB = 0;
for (i=0; i<npolygons; i++) vet_pol[i] = true; /* Vectorized */
while (true)
{
/* find_unselected_pol(cpol); */
for (cpol=last_pol; cpol<npolygons; cpol++) {
if ( vet_pol[cpol] ) break;
}
if (cpol == npolygons) {
cpol = -1;
}
else {
last_pol = cpol;
}
/* end find_unselected_pol(cpol); */
if (cpol < 0) break;
/* update_polygon */
vet_pol[cpol] = false;
/* end update_polygon */
/* get_vertices_of_pol(cpol,Vt,Nvt); { */
/* WLH 25 Oct 97
Nvt = Vert_f_Pol[(j=cpol*7)+6];
off = j;
*/
Nvt = polyToVert[cpol].length;
/* } */
/* end get_vertices_of_pol(cpol,Vt,Nvt); { */
for (ivA=0; ivA<Nvt; ivA++) {
ivB = (((ivA+1)==Nvt) ? 0:(ivA+1));
/* get_pol_vert(Vt[ivA],Vt[ivB],npol) { */
npol = -1;
/* WLH 25 Oct 97
if (Vert_f_Pol[ivA+off]>=0 && Vert_f_Pol[ivB+off]>=0) {
i=Vert_f_Pol[ivA+off]*9;
k=i+Pol_f_Vert [i+8];
j=Vert_f_Pol[ivB+off]*9;
m=j+Pol_f_Vert [j+8];
while (i>0 && j>0 && i<k && j <m ) {
if (Pol_f_Vert [i] == Pol_f_Vert [j] &&
vet_pol[Pol_f_Vert[i]] ) {
npol=Pol_f_Vert [i];
break;
}
else if (Pol_f_Vert [i] < Pol_f_Vert [j])
i++;
else
j++;
}
}
*/
if (ivA < polyToVert[cpol].length && ivB < polyToVert[cpol].length) {
i=polyToVert[cpol][ivA];
int ilim = vertToPoly[i].length;
k = 0;
j=polyToVert[cpol][ivB];
int jlim = vertToPoly[j].length;
m = 0;
// while (0<k && k<ilim && 0<m && m<jlim) {
while (0<i && k<ilim && 0<j && m<jlim) {
if (vertToPoly[i][k] == vertToPoly[j][m] &&
vet_pol[vertToPoly[i][k]] ) {
npol=vertToPoly[i][k];
break;
}
else if (vertToPoly[i][k] < vertToPoly[j][m])
k++;
else
m++;
}
}
/* } */
/* end get_pol_vert(Vt[ivA],Vt[ivB],npol) { */
if (npol >= 0) break;
}
/* insert polygon alone */
if (npol < 0)
{ /*ptT = NTAB + STAB[Nvt-3];*/
idx = STAB[Nvt-3];
if (iST > 0)
{ Tri_Stripe[iST] = Tri_Stripe[iST-1]; iST++;
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx]+off];
*/
Tri_Stripe[iST++] = polyToVert[cpol][NTAB[idx]];
}
else f_line_conection = true; /* WLH 3-9-95 added */
for (ii=0; ii< ((Nvt < 6) ? Nvt:6); ii++) {
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx++]+off];
*/
Tri_Stripe[iST++] = polyToVert[cpol][NTAB[idx++]];
}
continue;
}
if (( (ivB != 0) && ivA==(ivB-1)) || ( !(ivB != 0) && ivA==Nvt-1)) {
/* ptT = ITAB + STAB[Nvt-3] + (ivB+1)*Nvt; */
idx = STAB[Nvt-3] + (ivB+1)*Nvt;
if (f_line_conection)
{ Tri_Stripe[iST] = Tri_Stripe[iST-1]; iST++;
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[ITAB[idx-1]+off];
*/
Tri_Stripe[iST++] = polyToVert[cpol][ITAB[idx-1]];
f_line_conection = false;
}
for (ii=0; ii<((Nvt < 6) ? Nvt:6); ii++) {
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[ITAB[--idx]+off];
*/
Tri_Stripe[iST++] = polyToVert[cpol][ITAB[--idx]];
}
}
else {
/* ptT = NTAB + STAB[Nvt-3] + (ivB+1)*Nvt; */
idx = STAB[Nvt-3] + (ivB+1)*Nvt;
if (f_line_conection)
{ Tri_Stripe[iST] = Tri_Stripe[iST-1]; iST++;
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx-1]+off];
*/
Tri_Stripe[iST++] = polyToVert[cpol][NTAB[idx-1]];
f_line_conection = false;
}
for (ii=0; ii<((Nvt < 6) ? Nvt:6); ii++) {
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[--idx]+off];
*/
Tri_Stripe[iST++] = polyToVert[cpol][NTAB[--idx]];
}
}
vB = Tri_Stripe[iST-1];
vA = Tri_Stripe[iST-2];
cpol = npol;
while (true)
{
/* get_vertices_of_pol(cpol,Vt,Nvt) { */
/* WLH 25 Oct 97
Nvt = Vert_f_Pol [(j=cpol*7)+6];
off = j;
*/
Nvt = polyToVert[cpol].length;
/* } */
/* update_polygon(cpol) */
vet_pol[cpol] = false;
/* WLH 25 Oct 97
for (ivA=0; ivA<Nvt && Vert_f_Pol[ivA+off]!=vA; ivA++);
for (ivB=0; ivB<Nvt && Vert_f_Pol[ivB+off]!=vB; ivB++);
*/
for (ivA=0; ivA<Nvt && polyToVert[cpol][ivA]!=vA; ivA++);
for (ivB=0; ivB<Nvt && polyToVert[cpol][ivB]!=vB; ivB++);
if (( (ivB != 0) && ivA==(ivB-1)) || (!(ivB != 0) && ivA==Nvt-1)) {
/* ptT = NTAB + STAB[Nvt-3] + ivA*Nvt + 2; */
idx = STAB[Nvt-3] + ivA*Nvt + 2;
for (ii=2; ii<((Nvt < 6) ? Nvt:6); ii++) {
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx++]+off];
*/
Tri_Stripe[iST++] = polyToVert[cpol][NTAB[idx++]];
}
}
else {
/* ptT = ITAB + STAB[Nvt-3] + ivA*Nvt + 2; */
idx = STAB[Nvt-3] + ivA*Nvt + 2;
for (ii=2; ii<((Nvt < 6) ? Nvt:6); ii++) {
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[ITAB[idx++]+off];
*/
Tri_Stripe[iST++] = polyToVert[cpol][ITAB[idx++]];
}
}
vB = Tri_Stripe[iST-1];
vA = Tri_Stripe[iST-2];
/* get_pol_vert(vA,vB,cpol) { */
cpol = -1;
/* WLH 25 Oct 97
if (vA>=0 && vB>=0) {
i=vA*9;
k=i+Pol_f_Vert [i+8];
j=vB*9;
m=j+Pol_f_Vert [j+8];
while (i>0 && j>0 && i<k && j<m) {
if (Pol_f_Vert [i] == Pol_f_Vert [j] &&
vet_pol[Pol_f_Vert[i]] ) {
cpol=Pol_f_Vert[i];
break;
}
else if (Pol_f_Vert [i] < Pol_f_Vert [j])
i++;
else
j++;
}
}
*/
if (vA>=0 && vB>=0) {
int ilim = vertToPoly[vA].length;
k = 0;
int jlim = vertToPoly[vB].length;
m = 0;
// while (0<k && k<ilim && 0<m && m<jlim) {
while (0<vA && k<ilim && 0<vB && m<jlim) {
if (vertToPoly[vA][k] == vertToPoly[vB][m] &&
vet_pol[vertToPoly[vA][k]] ) {
cpol=vertToPoly[vA][k];
break;
}
else if (vertToPoly[vA][k] < vertToPoly[vB][m])
k++;
else
m++;
}
}
/* } */
if (cpol < 0) {
vA = Tri_Stripe[iST-3];
/* get_pol_vert(vA,vB,cpol) { */
cpol = -1;
/* WLH 25 Oct 97
if (vA>=0 && vB>=0) {
i=vA*9;
k=i+Pol_f_Vert [i+8];
j=vB*9;
m=j+Pol_f_Vert [j+8];
while (i>0 && j>0 && i<k && j<m) {
if (Pol_f_Vert [i] == Pol_f_Vert [j] &&
vet_pol[Pol_f_Vert[i]] ) {
cpol=Pol_f_Vert[i];
break;
}
else if (Pol_f_Vert [i] < Pol_f_Vert [j])
i++;
else
j++;
}
}
*/
if (vA>=0 && vB>=0) {
int ilim = vertToPoly[vA].length;
k = 0;
int jlim = vertToPoly[vB].length;
m = 0;
// while (0<k && k<ilim && 0<m && m<jlim) {
while (0<vA && k<ilim && 0<vB && m<jlim) {
if (vertToPoly[vA][k] == vertToPoly[vB][m] &&
vet_pol[vertToPoly[vA][k]] ) {
cpol=vertToPoly[vA][k];
break;
}
else if (vertToPoly[vA][k] < vertToPoly[vB][m])
k++;
else
m++;
}
}
/* } */
if (cpol < 0) {
f_line_conection = true;
break;
}
else {
Tri_Stripe[iST++] = vA;
i = vA;
vA = vB;
vB = i;
}
}
}
}
return iST;
}
/** create a 2-D GeometryArray from this Set and color_values */
public VisADGeometryArray make2DGeometry(byte[][] color_values,
boolean indexed) throws VisADException {
if (DomainDimension != 3) {
throw new SetException("Irregular3DSet.make2DGeometry: " +
"DomainDimension must be 3, not " +
DomainDimension);
}
if (ManifoldDimension != 2) {
throw new SetException("Irregular3DSet.make2DGeometry: " +
"ManifoldDimension must be 2, not " +
ManifoldDimension);
}
int npolygons = Delan.Tri.length;
int nvertex = Delan.Vertices.length;
if (npolygons < 1 || nvertex < 3) return null;
// make sure all triangles have the same signature
// i.e., winding direction
int[][] Tri = Delan.Tri;
int[][] Walk = Delan.Walk;
int dim = Tri[0].length - 1;
int[][] tri = new int[npolygons][];
int[] poly_stack = new int[npolygons];
int[] walk_stack = new int[npolygons];
int sp; // stack pointer
for (int ii=0; ii<npolygons; ii++) {
// find an un-adjusted triangle
if (tri[ii] == null) {
// initialize its signature
tri[ii] = new int[3];
tri[ii][0] = Tri[ii][0];
tri[ii][1] = Tri[ii][1];
tri[ii][2] = Tri[ii][2];
// first stack entry, for recursive search of triangles
// via Walk array
sp = 0;
walk_stack[sp] = 0;
poly_stack[sp] = ii;
while (true) {
// find neighbor triangle via Walk
int i = poly_stack[sp];
int w = walk_stack[sp];
int j = Walk[i][w];
if (j >= 0 && tri[j] == null) {
// compare signatures of neighbors
int v1 = Tri[i][w];
int v2 = Tri[i][(w + 1) % 3];
int i1 = -1;
int i2 = -1;
int j1 = -1;
int j2 = -1;
for (int k=0; k<3; k++) {
if (tri[i][k] == v1) i1 = k;
if (tri[i][k] == v2) i2 = k;
if (Tri[j][k] == v1) j1 = k;
if (Tri[j][k] == v2) j2 = k;
}
tri[j] = new int[3];
tri[j][0] = Tri[j][0];
if ( ( (((i1 + 1) % 3) == i2) && (((j1 + 1) % 3) == j2) ) ||
( (((i2 + 1) % 3) == i1) && (((j2 + 1) % 3) == j1) ) ) {
tri[j][1] = Tri[j][2];
tri[j][2] = Tri[j][1];
}
else {
tri[j][1] = Tri[j][1];
tri[j][2] = Tri[j][2];
}
// add j to stack
sp++;
walk_stack[sp] = 0;
poly_stack[sp] = j;
}
else { // (j < 0 || tri[j] != null)
while (true) {
walk_stack[sp]++;
if (walk_stack[sp] < 3) {
break;
}
else {
sp--;
if (sp < 0) break;
}
} // end while (true)
} // end if (j < 0 || tri[j] != null)
if (sp < 0) break;
} // end while (true)
} // end if (tri[ii] == null)
} // end for (int ii=0; ii<npolygons; ii++)
float[][] samples = getSamples(false);
float[] NxA = new float[npolygons];
float[] NxB = new float[npolygons];
float[] NyA = new float[npolygons];
float[] NyB = new float[npolygons];
float[] NzA = new float[npolygons];
float[] NzB = new float[npolygons];
float[] Pnx = new float[npolygons];
float[] Pny = new float[npolygons];
float[] Pnz = new float[npolygons];
float[] NX = new float[nvertex];
float[] NY = new float[nvertex];
float[] NZ = new float[nvertex];
make_normals(samples[0], samples[1], samples[2],
NX, NY, NZ, nvertex, npolygons, Pnx, Pny, Pnz,
NxA, NxB, NyA, NyB, NzA, NzB, Delan.Vertices, tri);
// NxA, NxB, NyA, NyB, NzA, NzB, Delan.Vertices, Delan.Tri);
// take the garbage out
NxA = NxB = NyA = NyB = NzA = NzB = Pnx = Pny = Pnz = null;
float[] normals = new float[3 * nvertex];
int j = 0;
for (int i=0; i<nvertex; i++) {
normals[j++] = (float) NX[i];
normals[j++] = (float) NY[i];
normals[j++] = (float) NZ[i];
}
// take the garbage out
NX = NY = NZ = null;
// temporary array to hold maximum possible polytriangle strip
int[] stripe = new int[6 * npolygons];
int size_stripe =
poly_triangle_stripe(stripe, nvertex, npolygons,
Delan.Vertices, Delan.Tri);
if (indexed) {
VisADIndexedTriangleStripArray array =
new VisADIndexedTriangleStripArray();
// array.vertexFormat |= NORMALS;
array.normals = normals;
// take the garbage out
normals = null;
// set up indices
array.indexCount = size_stripe;
array.indices = new int[size_stripe];
System.arraycopy(stripe, 0, array.indices, 0, size_stripe);
array.stripVertexCounts = new int[1];
array.stripVertexCounts[0] = size_stripe;
// take the garbage out
stripe = null;
// set coordinates and colors
setGeometryArray(array, samples, 4, color_values);
// take the garbage out
samples = null;
return array;
}
else { // if (!indexed)
VisADTriangleStripArray array = new VisADTriangleStripArray();
array.stripVertexCounts = new int[] {size_stripe};
array.vertexCount = size_stripe;
array.normals = new float[3 * size_stripe];
int k = 0;
for (int i=0; i<3*size_stripe; i+=3) {
j = 3 * stripe[k];
array.normals[i] = normals[j];
array.normals[i+1] = normals[j+1];
array.normals[i+2] = normals[j+2];
k++;
}
normals = null;
array.coordinates = new float[3 * size_stripe];
k = 0;
for (int i=0; i<3*size_stripe; i+=3) {
j = stripe[k];
array.coordinates[i] = samples[0][j];
array.coordinates[i+1] = samples[1][j];
array.coordinates[i+2] = samples[2][j];
k++;
}
samples = null;
if (color_values != null) {
int color_length = color_values.length;
array.colors = new byte[color_length * size_stripe];
k = 0;
if (color_length == 4) {
for (int i=0; i<color_length*size_stripe; i+=color_length) {
j = stripe[k];
array.colors[i] = color_values[0][j];
array.colors[i+1] = color_values[1][j];
array.colors[i+2] = color_values[2][j];
array.colors[i+3] = color_values[3][j];
k++;
}
}
else { // if (color_length == 3)
for (int i=0; i<color_length*size_stripe; i+=color_length) {
j = stripe[k];
array.colors[i] = color_values[0][j];
array.colors[i+1] = color_values[1][j];
array.colors[i+2] = color_values[2][j];
k++;
}
}
}
color_values = null;
stripe = null;
return array;
} // end if (!indexed)
}
public Object cloneButType(MathType type) throws VisADException {
if (ManifoldDimension == 1) {
return new Irregular3DSet(type, Samples, newToOld, oldToNew,
DomainCoordinateSystem, SetUnits, SetErrors);
}
else {
return new Irregular3DSet(type, Samples, DomainCoordinateSystem,
SetUnits, SetErrors, Delan);
}
}
/* run 'java visad.Irregular3DSet' to test the Irregular3DSet class */
public static void main(String[] argv) throws VisADException {
float[][] samp = { {179, 232, 183, 244, 106, 344, 166, 304, 286},
{ 86, 231, 152, 123, 183, 153, 308, 325, 89},
{121, 301, 346, 352, 123, 125, 187, 101, 142} };
RealType test1 = RealType.getRealType("x");
RealType test2 = RealType.getRealType("y");
RealType test3 = RealType.getRealType("z");
RealType[] t_array = {test1, test2, test3};
RealTupleType t_tuple = new RealTupleType(t_array);
Irregular3DSet iSet3D = new Irregular3DSet(t_tuple, samp);
// print out Samples information
System.out.println("Samples:");
for (int i=0; i<iSet3D.Samples[0].length; i++) {
System.out.println("#"+i+":\t"+iSet3D.Samples[0][i]+", "
+iSet3D.Samples[1][i]+", "
+iSet3D.Samples[2][i]);
}
System.out.println(iSet3D.Delan.Tri.length
+" tetrahedrons in tetrahedralization.");
// test valueToIndex function
System.out.println("\nvalueToIndex test:");
float[][] value = { {189, 221, 319, 215, 196},
{166, 161, 158, 139, 285},
{207, 300, 127, 287, 194} };
int[] index = iSet3D.valueToIndex(value);
for (int i=0; i<index.length; i++) {
System.out.println(value[0][i]+", "+value[1][i]+", "
+value[2][i]+"\t--> #"+index[i]);
}
// test valueToInterp function
System.out.println("\nvalueToInterp test:");
int[][] indices = new int[value[0].length][];
float[][] weights = new float[value[0].length][];
iSet3D.valueToInterp(value, indices, weights);
for (int i=0; i<value[0].length; i++) {
System.out.println(value[0][i]+", "+value[1][i]+", "
+value[2][i]+"\t--> ["
+indices[i][0]+", "
+indices[i][1]+", "
+indices[i][2]+", "
+indices[i][3]+"]\tweight total: "
+(weights[i][0]+weights[i][1]
+weights[i][2]+weights[i][3]));
}
// test makeIsosurface function
System.out.println("\nmakeIsosurface test:");
float[] field = {100, 300, 320, 250, 80, 70, 135, 110, 105};
float[][] slice = new float[3][];
int[][][] polyvert = new int[1][][];
int[][][] vertpoly = new int[1][][];
iSet3D.makeIsosurface(288, field, null, slice, null, polyvert, vertpoly);
for (int i=0; i<slice[0].length; i++) {
for (int j=0; j<3; j++) {
slice[j][i] = (float) Math.round(1000*slice[j][i]) / 1000;
}
}
System.out.println("polygons:");
for (int i=0; i<polyvert[0].length; i++) {
System.out.print("#"+i+":");
/* WLH 25 Oct 97
for (int j=0; j<4; j++) {
if (polyvert[0][i][j] != -1) {
if (j == 1) {
if (polyvert[0][i][3] == -1) {
System.out.print("(tri)");
}
else {
System.out.print("(quad)");
}
}
System.out.println("\t"+slice[0][polyvert[0][i][j]]
+", "+slice[1][polyvert[0][i][j]]
+", "+slice[2][polyvert[0][i][j]]);
}
}
*/
for (int j=0; j<polyvert[0][i].length; j++) {
if (j == 1) {
if (polyvert[0][i].length == 3) {
System.out.print("(tri)");
}
else {
System.out.print("(quad)");
}
}
System.out.println("\t"+slice[0][polyvert[0][i][j]]
+", "+slice[1][polyvert[0][i][j]]
+", "+slice[2][polyvert[0][i][j]]);
}
}
System.out.println();
for (int i=0; i<polyvert[0].length; i++) {
int a = polyvert[0][i][0];
int b = polyvert[0][i][1];
int c = polyvert[0][i][2];
int d = polyvert[0][i].length==4 ? polyvert[0][i][3] : -1;
boolean found = false;
for (int j=0; j<vertpoly[0][a].length; j++) {
if (vertpoly[0][a][j] == i) found = true;
}
if (!found) {
System.out.println("vertToPoly array corrupted at triangle #"
+i+" vertex #0!");
}
found = false;
for (int j=0; j<vertpoly[0][b].length; j++) {
if (vertpoly[0][b][j] == i) found = true;
}
if (!found) {
System.out.println("vertToPoly array corrupted at triangle #"
+i+" vertex #1!");
}
found = false;
for (int j=0; j<vertpoly[0][c].length; j++) {
if (vertpoly[0][c][j] == i) found = true;
}
if (!found) {
System.out.println("vertToPoly array corrupted at triangle #"
+i+" vertex #2!");
}
found = false;
if (d != -1) {
for (int j=0; j<vertpoly[0][d].length; j++) {
if (vertpoly[0][d][j] == i) found = true;
}
if (!found) {
System.out.println("vertToPoly array corrupted at triangle #"
+i+" vertex #3!");
}
}
}
}
/* Here's the output:
iris 45% java visad.Irregular3DSet
Samples:
#0: 179.0, 86.0, 121.0
#1: 232.0, 231.0, 301.0
#2: 183.0, 152.0, 346.0
#3: 244.0, 123.0, 352.0
#4: 106.0, 183.0, 123.0
#5: 344.0, 153.0, 125.0
#6: 166.0, 308.0, 187.0
#7: 304.0, 325.0, 101.0
#8: 286.0, 89.0, 142.0
15 tetrahedrons in tetrahedralization.
valueToIndex test:
189.0, 166.0, 207.0 --> #0
221.0, 161.0, 300.0 --> #2
319.0, 158.0, 127.0 --> #5
215.0, 139.0, 287.0 --> #2
196.0, 285.0, 194.0 --> #6
valueToInterp test:
189.0, 166.0, 207.0 --> [0, 1, 2, 4] weight total: 1.0
221.0, 161.0, 300.0 --> [1, 2, 3, 8] weight total: 1.0
319.0, 158.0, 127.0 --> [4, 5, 6, 8] weight total: 0.9999999999999999
215.0, 139.0, 287.0 --> [1, 2, 3, 8] weight total: 1.0
196.0, 285.0, 194.0 --> [1, 5, 6, 7] weight total: 1.0
makeIsosurface test:
polygons:
#0: 237.843, 226.93, 291.817
(tri) 227.2, 236.6, 292.709
236.547, 236.937, 288.368
#1: 228.82, 222.3, 290.2
(quad) 182.418, 142.4, 313.273
225.127, 228.382, 291.291
172.733, 156.133, 316.267
#2: 225.127, 228.382, 291.291
(tri) 227.2, 236.6, 292.709
235.323, 222.262, 291.215
#3: 228.82, 222.3, 290.2
(quad) 182.418, 142.4, 313.273
235.323, 222.262, 291.215
198.33, 142.623, 315.637
#4: 234.88, 205.08, 313.24
(tri) 237.843, 226.93, 291.817
235.323, 222.262, 291.215
#5: 182.418, 142.4, 313.273
(tri) 210.886, 138.743, 348.743
198.33, 142.623, 315.637
#6: 234.88, 205.08, 313.24
(quad) 235.323, 222.262, 291.215
210.886, 138.743, 348.743
198.33, 142.623, 315.637
#7: 225.127, 228.382, 291.291
(quad) 227.2, 236.6, 292.709
172.733, 156.133, 316.267
180.059, 178.984, 318.497
#8: 234.88, 205.08, 313.24
(tri) 237.843, 226.93, 291.817
236.547, 236.937, 288.368
#9: 228.82, 222.3, 290.2
(tri) 225.127, 228.382, 291.291
235.323, 222.262, 291.215
#10: 237.843, 226.93, 291.817
(tri) 227.2, 236.6, 292.709
235.323, 222.262, 291.215
iris 46%
*/
}
| private void makeIsosurface(float isolevel, float[] fieldValues,
byte[][] auxValues, float[][] fieldVertices,
byte[][] auxLevels, int[][][] polyToVert,
int[][][] vertToPoly) throws VisADException {
boolean DEBUG = false;
if (ManifoldDimension != 3) {
throw new DisplayException("Irregular3DSet.makeIsosurface: " +
"ManifoldDimension must be 3, not " +
ManifoldDimension);
}
if (fieldValues.length != Length) {
throw new DisplayException("Irregular3DSet.makeIsosurface: "
+"fieldValues length does't match");
}
if (Double.isNaN(isolevel)) {
throw new DisplayException("Irregular3DSet.makeIsosurface: "
+"isolevel cannot be missing");
}
if (fieldVertices.length != 3 || polyToVert.length != 1
|| vertToPoly.length != 1) {
throw new DisplayException("Irregular3DSet.makeIsosurface: return value"
+ " arrays not correctly initialized " +
fieldVertices.length + " " + polyToVert.length +
" " + vertToPoly.length);
}
int naux = (auxValues != null) ? auxValues.length : 0;
if (naux > 0) {
if (auxLevels == null || auxLevels.length != naux) {
throw new DisplayException("Irregular3DSet.makeIsosurface: "
+"auxLevels length doesn't match");
}
for (int i=0; i<naux; i++) {
if (auxValues[i].length != Length) {
throw new DisplayException("Irregular3DSet.makeIsosurface: "
+"auxValues lengths don't match");
}
}
}
else {
if (auxLevels != null) {
throw new DisplayException("Irregular3DSet.makeIsosurface: "
+"auxValues null but auxLevels not null");
}
}
if (DEBUG) {
System.out.println("isolevel = " + isolevel + "\n");
System.out.println("fieldValues " + fieldValues.length);
for (int i=0; i<fieldValues.length; i++) {
System.out.println(" " + i + " -> " + fieldValues[i]);
}
System.out.println(Delan.sampleString(Samples));
}
int trilength = Delan.Tri.length;
// temporary storage of polyToVert structure
int[][] polys = new int[trilength][4];
// pointers from global edge number to nvertex
int[] globalToVertex = new int[Delan.NumEdges];
for (int i=0; i<Delan.NumEdges; i++) globalToVertex[i] = -1;
// global edges temporary storage array
float[][] edgeInterp = new float[DomainDimension][Delan.NumEdges];
for (int i=0; i<Delan.NumEdges; i++) edgeInterp[0][i] = Float.NaN;
// global edges temporary storage array for aux levels
byte[][] auxInterp = (naux > 0) ? new byte[naux][Delan.NumEdges] : null;
int t;
int nvertex = 0;
int npolygons = 0;
for (int i=0; i<trilength; i++) {
int v0 = Delan.Tri[i][0];
int v1 = Delan.Tri[i][1];
int v2 = Delan.Tri[i][2];
int v3 = Delan.Tri[i][3];
float f0 = (float) fieldValues[v0];
float f1 = (float) fieldValues[v1];
float f2 = (float) fieldValues[v2];
float f3 = (float) fieldValues[v3];
int e0, e1, e2, e3, e4, e5;
// compute tetrahedron signature
// vector from v0 to v3
float vx = Samples[0][v3] - Samples[0][v0];
float vy = Samples[1][v3] - Samples[1][v0];
float vz = Samples[2][v3] - Samples[2][v0];
// cross product (v2 - v0) x (v1 - v0)
float sx = Samples[0][v2] - Samples[0][v0];
float sy = Samples[1][v2] - Samples[1][v0];
float sz = Samples[2][v2] - Samples[2][v0];
float tx = Samples[0][v1] - Samples[0][v0];
float ty = Samples[1][v1] - Samples[1][v0];
float tz = Samples[2][v1] - Samples[2][v0];
float cx = sy * tz - sz * ty;
float cy = sz * tx - sx * tz;
float cz = sx * ty - sy * tx;
// signature is sign of v (dot) c
float sig = vx * cx + vy * cy + vz * cz;
// 8 possibilities
int index = ((f0 > isolevel) ? 1 : 0)
+ ((f1 > isolevel) ? 2 : 0)
+ ((f2 > isolevel) ? 4 : 0)
+ ((f3 > isolevel) ? 8 : 0);
// apply signature to index
if (sig < 0.0f) index = 15 - index;
switch (index) {
case 0:
case 15: // plane does not intersect this tetrahedron
break;
case 1:
case 14: // plane slices a triangle
// define edge values needed
e0 = Delan.Edges[i][0];
e1 = Delan.Edges[i][1];
e2 = Delan.Edges[i][2];
// fill in edge interpolation values if they haven't been found
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e0])) {
*/
// test for missing
if (edgeInterp[0][e0] != edgeInterp[0][e0]) {
float a = (isolevel - f1)/(f0 - f1);
if (a < 0) a = -a;
edgeInterp[0][e0] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v1];
edgeInterp[1][e0] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v1];
edgeInterp[2][e0] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v1];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) );
auxInterp[j][e0] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e0] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v1];
*/
}
globalToVertex[e0] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e1])) {
*/
// test for missing
if (edgeInterp[0][e1] != edgeInterp[0][e1]) {
float a = (isolevel - f2)/(f0 - f2);
if (a < 0) a = -a;
edgeInterp[0][e1] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v2];
edgeInterp[1][e1] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v2];
edgeInterp[2][e1] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e1] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e1] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e2])) {
*/
// test for missing
if (edgeInterp[0][e2] != edgeInterp[0][e2]) {
float a = (isolevel - f3)/(f0 - f3);
if (a < 0) a = -a;
edgeInterp[0][e2] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v3];
edgeInterp[1][e2] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v3];
edgeInterp[2][e2] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e2] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e2] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e2] = nvertex;
nvertex++;
}
// fill in the polys and vertToPoly arrays
polys[npolygons][0] = e0;
if (index == 1) {
polys[npolygons][1] = e1;
polys[npolygons][2] = e2;
}
else { // index == 14
polys[npolygons][1] = e2;
polys[npolygons][2] = e1;
}
polys[npolygons][3] = -1;
// on to the next tetrahedron
npolygons++;
break;
case 2:
case 13: // plane slices a triangle
// define edge values needed
e0 = Delan.Edges[i][0];
e3 = Delan.Edges[i][3];
e4 = Delan.Edges[i][4];
// fill in edge interpolation values if they haven't been found
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e0])) {
*/
// test for missing
if (edgeInterp[0][e0] != edgeInterp[0][e0]) {
float a = (isolevel - f1)/(f0 - f1);
if (a < 0) a = -a;
edgeInterp[0][e0] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v1];
edgeInterp[1][e0] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v1];
edgeInterp[2][e0] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v1];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) );
auxInterp[j][e0] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e0] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v1];
*/
}
globalToVertex[e0] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e3])) {
*/
// test for missing
if (edgeInterp[0][e3] != edgeInterp[0][e3]) {
float a = (isolevel - f2)/(f1 - f2);
if (a < 0) a = -a;
edgeInterp[0][e3] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v2];
edgeInterp[1][e3] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v2];
edgeInterp[2][e3] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e3] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e3] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e3] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e4])) {
*/
// test for missing
if (edgeInterp[0][e4] != edgeInterp[0][e4]) {
float a = (isolevel - f3)/(f1 - f3);
if (a < 0) a = -a;
edgeInterp[0][e4] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v3];
edgeInterp[1][e4] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v3];
edgeInterp[2][e4] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e4] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e4] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e4] = nvertex;
nvertex++;
}
// fill in the polys array
polys[npolygons][0] = e0;
if (index == 2) {
polys[npolygons][1] = e4;
polys[npolygons][2] = e3;
}
else { // index == 13
polys[npolygons][1] = e3;
polys[npolygons][2] = e4;
}
polys[npolygons][3] = -1;
// on to the next tetrahedron
npolygons++;
break;
case 3:
case 12: // plane slices a quadrilateral
// define edge values needed
e1 = Delan.Edges[i][1];
e2 = Delan.Edges[i][2];
e3 = Delan.Edges[i][3];
e4 = Delan.Edges[i][4];
// fill in edge interpolation values if they haven't been found
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e1])) {
*/
// test for missing
if (edgeInterp[0][e1] != edgeInterp[0][e1]) {
float a = (isolevel - f2)/(f0 - f2);
if (a < 0) a = -a;
edgeInterp[0][e1] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v2];
edgeInterp[1][e1] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v2];
edgeInterp[2][e1] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e1] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e1] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e2])) {
*/
// test for missing
if (edgeInterp[0][e2] != edgeInterp[0][e2]) {
float a = (isolevel - f3)/(f0 - f3);
if (a < 0) a = -a;
edgeInterp[0][e2] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v3];
edgeInterp[1][e2] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v3];
edgeInterp[2][e2] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e2] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e2] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e2] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e4])) {
*/
// test for missing
if (edgeInterp[0][e4] != edgeInterp[0][e4]) {
float a = (isolevel - f3)/(f1 - f3);
if (a < 0) a = -a;
edgeInterp[0][e4] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v3];
edgeInterp[1][e4] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v3];
edgeInterp[2][e4] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e4] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e4] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e4] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e3])) {
*/
// test for missing
if (edgeInterp[0][e3] != edgeInterp[0][e3]) {
float a = (isolevel - f2)/(f1 - f2);
if (a < 0) a = -a;
edgeInterp[0][e3] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v2];
edgeInterp[1][e3] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v2];
edgeInterp[2][e3] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e3] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e3] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e3] = nvertex;
nvertex++;
}
// fill in the polys array
polys[npolygons][0] = e1;
if (index == 3) {
polys[npolygons][1] = e2;
polys[npolygons][2] = e4;
polys[npolygons][3] = e3;
}
else { // index == 12
polys[npolygons][1] = e3;
polys[npolygons][2] = e4;
polys[npolygons][3] = e2;
}
// on to the next tetrahedron
npolygons++;
break;
case 4:
case 11: // plane slices a triangle
// define edge values needed
e1 = Delan.Edges[i][1];
e3 = Delan.Edges[i][3];
e5 = Delan.Edges[i][5];
// fill in edge interpolation values if they haven't been found
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e1])) {
*/
// test for missing
if (edgeInterp[0][e1] != edgeInterp[0][e1]) {
float a = (isolevel - f2)/(f0 - f2);
if (a < 0) a = -a;
edgeInterp[0][e1] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v2];
edgeInterp[1][e1] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v2];
edgeInterp[2][e1] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e1] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e1] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e3])) {
*/
// test for missing
if (edgeInterp[0][e3] != edgeInterp[0][e3]) {
float a = (isolevel - f2)/(f1 - f2);
if (a < 0) a = -a;
edgeInterp[0][e3] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v2];
edgeInterp[1][e3] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v2];
edgeInterp[2][e3] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e3] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e3] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e3] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e5])) {
*/
// test for missing
if (edgeInterp[0][e5] != edgeInterp[0][e5]) {
float a = (isolevel - f3)/(f2 - f3);
if (a < 0) a = -a;
edgeInterp[0][e5] = (float) a*Samples[0][v2] + (1-a)*Samples[0][v3];
edgeInterp[1][e5] = (float) a*Samples[1][v2] + (1-a)*Samples[1][v3];
edgeInterp[2][e5] = (float) a*Samples[2][v2] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e5] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e5] = (float) a*auxValues[j][v2] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e5] = nvertex;
nvertex++;
}
// fill in the polys array
polys[npolygons][0] = e1;
if (index == 4) {
polys[npolygons][1] = e3;
polys[npolygons][2] = e5;
}
else { // index == 11
polys[npolygons][1] = e5;
polys[npolygons][2] = e3;
}
polys[npolygons][3] = -1;
// on to the next tetrahedron
npolygons++;
break;
case 5:
case 10: // plane slices a quadrilateral
// define edge values needed
e0 = Delan.Edges[i][0];
e2 = Delan.Edges[i][2];
e3 = Delan.Edges[i][3];
e5 = Delan.Edges[i][5];
// fill in edge interpolation values if they haven't been found
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e0])) {
*/
// test for missing
if (edgeInterp[0][e0] != edgeInterp[0][e0]) {
float a = (isolevel - f1)/(f0 - f1);
if (a < 0) a = -a;
edgeInterp[0][e0] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v1];
edgeInterp[1][e0] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v1];
edgeInterp[2][e0] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v1];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) );
auxInterp[j][e0] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e0] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v1];
*/
}
globalToVertex[e0] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e2])) {
*/
// test for missing
if (edgeInterp[0][e2] != edgeInterp[0][e2]) {
float a = (isolevel - f3)/(f0 - f3);
if (a < 0) a = -a;
edgeInterp[0][e2] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v3];
edgeInterp[1][e2] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v3];
edgeInterp[2][e2] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e2] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e2] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e2] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e5])) {
*/
// test for missing
if (edgeInterp[0][e5] != edgeInterp[0][e5]) {
float a = (isolevel - f3)/(f2 - f3);
if (a < 0) a = -a;
edgeInterp[0][e5] = (float) a*Samples[0][v2] + (1-a)*Samples[0][v3];
edgeInterp[1][e5] = (float) a*Samples[1][v2] + (1-a)*Samples[1][v3];
edgeInterp[2][e5] = (float) a*Samples[2][v2] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e5] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e5] = (float) a*auxValues[j][v2] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e5] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e3])) {
*/
// test for missing
if (edgeInterp[0][e3] != edgeInterp[0][e3]) {
float a = (isolevel - f2)/(f1 - f2);
if (a < 0) a = -a;
edgeInterp[0][e3] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v2];
edgeInterp[1][e3] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v2];
edgeInterp[2][e3] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e3] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e3] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e3] = nvertex;
nvertex++;
}
// fill in the polys array
polys[npolygons][0] = e0;
if (index == 5) {
polys[npolygons][1] = e3;
polys[npolygons][2] = e5;
polys[npolygons][3] = e2;
}
else { // index == 10
polys[npolygons][1] = e2;
polys[npolygons][2] = e5;
polys[npolygons][3] = e3;
}
// on to the next tetrahedron
npolygons++;
break;
case 6:
case 9: // plane slices a quadrilateral
// define edge values needed
e0 = Delan.Edges[i][0];
e1 = Delan.Edges[i][1];
e4 = Delan.Edges[i][4];
e5 = Delan.Edges[i][5];
// fill in edge interpolation values if they haven't been found
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e0])) {
*/
// test for missing
if (edgeInterp[0][e0] != edgeInterp[0][e0]) {
float a = (isolevel - f1)/(f0 - f1);
if (a < 0) a = -a;
edgeInterp[0][e0] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v1];
edgeInterp[1][e0] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v1];
edgeInterp[2][e0] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v1];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) );
auxInterp[j][e0] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e0] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v1];
*/
}
globalToVertex[e0] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e1])) {
*/
// test for missing
if (edgeInterp[0][e1] != edgeInterp[0][e1]) {
float a = (isolevel - f2)/(f0 - f2);
if (a < 0) a = -a;
edgeInterp[0][e1] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v2];
edgeInterp[1][e1] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v2];
edgeInterp[2][e1] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v2];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) );
auxInterp[j][e1] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e1] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v2];
*/
}
globalToVertex[e1] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e5])) {
*/
// test for missing
if (edgeInterp[0][e5] != edgeInterp[0][e5]) {
float a = (isolevel - f3)/(f2 - f3);
if (a < 0) a = -a;
edgeInterp[0][e5] = (float) a*Samples[0][v2] + (1-a)*Samples[0][v3];
edgeInterp[1][e5] = (float) a*Samples[1][v2] + (1-a)*Samples[1][v3];
edgeInterp[2][e5] = (float) a*Samples[2][v2] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e5] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e5] = (float) a*auxValues[j][v2] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e5] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e4])) {
*/
// test for missing
if (edgeInterp[0][e4] != edgeInterp[0][e4]) {
float a = (isolevel - f3)/(f1 - f3);
if (a < 0) a = -a;
edgeInterp[0][e4] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v3];
edgeInterp[1][e4] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v3];
edgeInterp[2][e4] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e4] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e4] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e4] = nvertex;
nvertex++;
}
// fill in the polys array
polys[npolygons][0] = e0;
if (index == 6) {
polys[npolygons][1] = e4;
polys[npolygons][2] = e5;
polys[npolygons][3] = e1;
}
else { // index == 9
polys[npolygons][1] = e1;
polys[npolygons][2] = e5;
polys[npolygons][3] = e4;
}
// on to the next tetrahedron
npolygons++;
break;
case 7:
case 8: // plane slices a triangle
// interpolate between 3:0, 3:1, 3:2 for tri edges, same as case 8
// define edge values needed
e2 = Delan.Edges[i][2];
e4 = Delan.Edges[i][4];
e5 = Delan.Edges[i][5];
// fill in edge interpolation values if they haven't been found
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e2])) {
*/
// test for missing
if (edgeInterp[0][e2] != edgeInterp[0][e2]) {
float a = (isolevel - f3)/(f0 - f3);
if (a < 0) a = -a;
edgeInterp[0][e2] = (float) a*Samples[0][v0] + (1-a)*Samples[0][v3];
edgeInterp[1][e2] = (float) a*Samples[1][v0] + (1-a)*Samples[1][v3];
edgeInterp[2][e2] = (float) a*Samples[2][v0] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v0] < 0) ?
((float) auxValues[j][v0]) + 256.0f :
((float) auxValues[j][v0]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e2] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e2] = (float) a*auxValues[j][v0] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e2] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e4])) {
*/
// test for missing
if (edgeInterp[0][e4] != edgeInterp[0][e4]) {
float a = (isolevel - f3)/(f1 - f3);
if (a < 0) a = -a;
edgeInterp[0][e4] = (float) a*Samples[0][v1] + (1-a)*Samples[0][v3];
edgeInterp[1][e4] = (float) a*Samples[1][v1] + (1-a)*Samples[1][v3];
edgeInterp[2][e4] = (float) a*Samples[2][v1] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v1] < 0) ?
((float) auxValues[j][v1]) + 256.0f :
((float) auxValues[j][v1]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e4] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e4] = (float) a*auxValues[j][v1] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e4] = nvertex;
nvertex++;
}
/* WLH 25 Oct 97
if (Double.isNaN(edgeInterp[0][e5])) {
*/
// test for missing
if (edgeInterp[0][e5] != edgeInterp[0][e5]) {
float a = (isolevel - f3)/(f2 - f3);
if (a < 0) a = -a;
edgeInterp[0][e5] = (float) a*Samples[0][v2] + (1-a)*Samples[0][v3];
edgeInterp[1][e5] = (float) a*Samples[1][v2] + (1-a)*Samples[1][v3];
edgeInterp[2][e5] = (float) a*Samples[2][v2] + (1-a)*Samples[2][v3];
for (int j=0; j<naux; j++) {
t = (int) ( a * ((auxValues[j][v2] < 0) ?
((float) auxValues[j][v2]) + 256.0f :
((float) auxValues[j][v2]) ) +
(1.0f - a) * ((auxValues[j][v3] < 0) ?
((float) auxValues[j][v3]) + 256.0f :
((float) auxValues[j][v3]) ) );
auxInterp[j][e5] = (byte)
( (t < 0) ? 0 : ((t > 255) ? -1 : ((t < 128) ? t : t - 256) ) );
/* MEM_WLH
auxInterp[j][e5] = (float) a*auxValues[j][v2] + (1-a)*auxValues[j][v3];
*/
}
globalToVertex[e5] = nvertex;
nvertex++;
}
// fill in the polys array
polys[npolygons][0] = e2;
if (index == 7) {
polys[npolygons][1] = e4;
polys[npolygons][2] = e5;
}
else { // index == 8
polys[npolygons][1] = e5;
polys[npolygons][2] = e4;
}
polys[npolygons][3] = -1;
// on to the next tetrahedron
npolygons++;
break;
} // end switch (index)
} // end for (int i=0; i<trilength; i++)
if (DEBUG) {
System.out.println("\npolys (polys -> global edges) " + npolygons + "\n");
for (int i=0; i<npolygons; i++) {
String s = " " + i + " -> ";
for (int j=0; j<4; j++) {
s = s + " " + polys[i][j];
}
System.out.println(s + "\n");
}
}
// transform polys array into polyToVert array
polyToVert[0] = new int[npolygons][];
for (int i=0; i<npolygons; i++) {
int n = polys[i][3] < 0 ? 3 : 4;
polyToVert[0][i] = new int[n];
for (int j=0; j<n; j++) polyToVert[0][i][j] = globalToVertex[polys[i][j]];
}
if (DEBUG) {
System.out.println("\npolyToVert (polys -> vertices) " + npolygons + "\n");
for (int i=0; i<npolygons; i++) {
String s = " " + i + " -> ";
for (int j=0; j<polyToVert[0][i].length; j++) {
s = s + " " + polyToVert[0][i][j];
}
System.out.println(s + "\n");
}
}
// build nverts helper array
int[] nverts = new int[nvertex];
for (int i=0; i<nvertex; i++) nverts[i] = 0;
for (int i=0; i<npolygons; i++) {
nverts[polyToVert[0][i][0]]++;
nverts[polyToVert[0][i][1]]++;
nverts[polyToVert[0][i][2]]++;
if (polyToVert[0][i].length > 3) nverts[polyToVert[0][i][3]]++;
}
// initialize vertToPoly array
vertToPoly[0] = new int[nvertex][];
for (int i=0; i<nvertex; i++) {
vertToPoly[0][i] = new int[nverts[i]];
}
// fill in vertToPoly array
for (int i=0; i<nvertex; i++) nverts[i] = 0;
for (int i=0; i<npolygons; i++) {
int a = polyToVert[0][i][0];
int b = polyToVert[0][i][1];
int c = polyToVert[0][i][2];
vertToPoly[0][a][nverts[a]++] = i;
vertToPoly[0][b][nverts[b]++] = i;
vertToPoly[0][c][nverts[c]++] = i;
if (polyToVert[0][i].length > 3) {
int d = polyToVert[0][i][3];
if (d != -1) vertToPoly[0][d][nverts[d]++] = i;
}
}
if (DEBUG) {
System.out.println("\nvertToPoly (vertices -> polys) " + nvertex + "\n");
for (int i=0; i<nvertex; i++) {
String s = " " + i + " -> ";
for (int j=0; j<vertToPoly[0][i].length; j++) {
s = s + " " + vertToPoly[0][i][j];
}
System.out.println(s + "\n");
}
}
// set up fieldVertices and auxLevels
fieldVertices[0] = new float[nvertex];
fieldVertices[1] = new float[nvertex];
fieldVertices[2] = new float[nvertex];
for (int j=0; j<naux; j++) {
auxLevels[j] = new byte[nvertex];
}
for (int i=0; i<Delan.NumEdges; i++) {
int k = globalToVertex[i];
if (k >= 0) {
fieldVertices[0][k] = edgeInterp[0][i];
fieldVertices[1][k] = edgeInterp[1][i];
fieldVertices[2][k] = edgeInterp[2][i];
for (int j=0; j<naux; j++) {
auxLevels[j][k] = auxInterp[j][i];
}
}
}
if (DEBUG) {
System.out.println("\nfieldVertices " + nvertex + "\n");
for (int i=0; i<nvertex; i++) {
String s = " " + i + " -> ";
for (int j=0; j<3; j++) {
s = s + " " + fieldVertices[j][i];
}
System.out.println(s + "\n");
}
}
}
/*
make_normals and poly_triangle_stripe altered according to:
Pol_f_Vert[9*i + 8] --> vertToPoly[i].length
Pol_f_Vert[9*i + off] --> vertToPoly[i][off]
Vert_f_Pol[7*i + 6] --> polyToVert[i].length
Vert_f_Pol[7*i + off] --> polyToVert[i][off]
*/
/* from Contour3D.java, used by make_normals */
static final float EPS_0 = (float) 1.0e-5;
/* copied from Contour3D.java */
private static void make_normals(float[] VX, float[] VY, float[] VZ,
float[] NX, float[] NY, float[] NZ, int nvertex,
int npolygons, float[] Pnx, float[] Pny, float[] Pnz,
float[] NxA, float[] NxB, float[] NyA, float[] NyB,
float[] NzA, float[] NzB,
int[][] vertToPoly, int[][] polyToVert)
/* WLH 25 Oct 97
int[] Pol_f_Vert, int[] Vert_f_Pol )
*/
throws VisADException {
int i, k, n;
int i1, i2, ix, iy, iz, ixb, iyb, izb;
int max_vert_per_pol, swap_flag;
float x, y, z, a, minimum_area, len;
int iv[] = new int[3];
if (nvertex <= 0) return;
for (i = 0; i < nvertex; i++) {
NX[i] = 0;
NY[i] = 0;
NZ[i] = 0;
}
// WLH 12 Nov 2001
// minimum_area = (float) ((1.e-4 > EPS_0) ? 1.e-4 : EPS_0);
minimum_area = Float.MIN_VALUE;
/* Calculate maximum number of vertices per polygon */
/* WLH 25 Oct 97
k = 6;
n = 7*npolygons;
*/
k = 0;
while ( true ) {
/* WLH 25 Oct 97
for (i=k+7; i<n; i+=7)
if (Vert_f_Pol[i] > Vert_f_Pol[k]) break;
*/
for (i=k+1; i<npolygons; i++)
if (polyToVert[i].length > polyToVert[k].length) break;
/* WLH 25 Oct 97
if (i >= n) break;
*/
if (i >= npolygons) break;
k = i;
}
/* WLH 25 Oct 97
max_vert_per_pol = Vert_f_Pol[k];
*/
max_vert_per_pol = polyToVert[k].length;
/* Calculate the Normals vector components for each Polygon */
for ( i=0; i<npolygons; i++) { /* Vectorized */
/* WLH 25 Oct 97
if (Vert_f_Pol[6+i*7]>0) {
NxA[i] = VX[Vert_f_Pol[1+i*7]] - VX[Vert_f_Pol[0+i*7]];
NyA[i] = VY[Vert_f_Pol[1+i*7]] - VY[Vert_f_Pol[0+i*7]];
NzA[i] = VZ[Vert_f_Pol[1+i*7]] - VZ[Vert_f_Pol[0+i*7]];
}
*/
if (polyToVert[i].length>0) {
int j1 = polyToVert[i][1];
int j0 = polyToVert[i][0];
NxA[i] = VX[j1] - VX[j0];
NyA[i] = VY[j1] - VY[j0];
NzA[i] = VZ[j1] - VZ[j0];
}
}
swap_flag = 0;
for ( k = 2; k < max_vert_per_pol; k++ ) {
if (swap_flag==0) {
/*$dir no_recurrence */ /* Vectorized */
for ( i=0; i<npolygons; i++ ) {
/* WLH 25 Oct 97
if ( Vert_f_Pol[k+i*7] >= 0 ) {
NxB[i] = VX[Vert_f_Pol[k+i*7]] - VX[Vert_f_Pol[0+i*7]];
NyB[i] = VY[Vert_f_Pol[k+i*7]] - VY[Vert_f_Pol[0+i*7]];
NzB[i] = VZ[Vert_f_Pol[k+i*7]] - VZ[Vert_f_Pol[0+i*7]];
*/
if ( k < polyToVert[i].length ) {
int jk = polyToVert[i][k];
int j0 = polyToVert[i][0];
NxB[i] = VX[jk] - VX[j0];
NyB[i] = VY[jk] - VY[j0];
NzB[i] = VZ[jk] - VZ[j0];
Pnx[i] = NyA[i]*NzB[i] - NzA[i]*NyB[i];
Pny[i] = NzA[i]*NxB[i] - NxA[i]*NzB[i];
Pnz[i] = NxA[i]*NyB[i] - NyA[i]*NxB[i];
NxA[i] = Pnx[i]*Pnx[i] + Pny[i]*Pny[i] + Pnz[i]*Pnz[i];
if (NxA[i] > minimum_area) {
Pnx[i] /= NxA[i];
Pny[i] /= NxA[i];
Pnz[i] /= NxA[i];
}
}
}
}
else { /* swap_flag!=0 */
/*$dir no_recurrence */ /* Vectorized */
for (i=0; i<npolygons; i++) {
/* WLH 25 Oct 97
if ( Vert_f_Pol[k+i*7] >= 0 ) {
NxA[i] = VX[Vert_f_Pol[k+i*7]] - VX[Vert_f_Pol[0+i*7]];
NyA[i] = VY[Vert_f_Pol[k+i*7]] - VY[Vert_f_Pol[0+i*7]];
NzA[i] = VZ[Vert_f_Pol[k+i*7]] - VZ[Vert_f_Pol[0+i*7]];
*/
if ( k < polyToVert[i].length ) {
int jk = polyToVert[i][k];
int j0 = polyToVert[i][0];
NxA[i] = VX[jk] - VX[j0];
NyA[i] = VY[jk] - VY[j0];
NzA[i] = VZ[jk] - VZ[j0];
Pnx[i] = NyB[i]*NzA[i] - NzB[i]*NyA[i];
Pny[i] = NzB[i]*NxA[i] - NxB[i]*NzA[i];
Pnz[i] = NxB[i]*NyA[i] - NyB[i]*NxA[i];
NxB[i] = Pnx[i]*Pnx[i] + Pny[i]*Pny[i] + Pnz[i]*Pnz[i];
if (NxB[i] > minimum_area) {
Pnx[i] /= NxB[i];
Pny[i] /= NxB[i];
Pnz[i] /= NxB[i];
}
}
} // end for (i=0; i<npolygons; i++)
} // end swap_flag!=0
/* This Loop <CAN'T> be Vectorized */
for ( i=0; i<npolygons; i++ ) {
/* WLH 25 Oct 97
if (Vert_f_Pol[k+i*7] >= 0) {
iv[0] = Vert_f_Pol[0+i*7];
iv[1] = Vert_f_Pol[(k-1)+i*7];
iv[2] = Vert_f_Pol[k+i*7];
*/
if (k < polyToVert[i].length) {
iv[0] = polyToVert[i][0];
iv[1] = polyToVert[i][k-1];
iv[2] = polyToVert[i][k];
x = Pnx[i]; y = Pny[i]; z = Pnz[i];
/*
System.out.println("vertices: " + iv[0] + " " + iv[1] + " " + iv[2]);
System.out.println(" normal: " + x + " " + y + " " + z + "\n");
*/
// Update the origin vertex
NX[iv[0]] += x; NY[iv[0]] += y; NZ[iv[0]] += z;
// Update the vertex that defines the first vector
NX[iv[1]] += x; NY[iv[1]] += y; NZ[iv[1]] += z;
// Update the vertex that defines the second vector
NX[iv[2]] += x; NY[iv[2]] += y; NZ[iv[2]] += z;
}
} // end for ( i=0; i<npolygons; i++ )
swap_flag = ( (swap_flag != 0) ? 0 : 1 );
} // end for ( k = 2; k < max_vert_per_pol; k++ )
/* Normalize the Normals */
for ( i=0; i<nvertex; i++ ) { /* Vectorized */
len = (float) Math.sqrt(NX[i]*NX[i] + NY[i]*NY[i] + NZ[i]*NZ[i]);
if (len > EPS_0) {
NX[i] /= len;
NY[i] /= len;
NZ[i] /= len;
}
}
}
/* from Contour3D.java, used by poly_triangle_stripe */
static final int NTAB[] =
{ 0,1,2, 1,2,0, 2,0,1,
0,1,3,2, 1,2,0,3, 2,3,1,0, 3,0,2,1,
0,1,4,2,3, 1,2,0,3,4, 2,3,1,4,0, 3,4,2,0,1, 4,0,3,1,2,
0,1,5,2,4,3, 1,2,0,3,5,4, 2,3,1,4,0,5, 3,4,2,5,1,0, 4,5,3,0,2,1,
5,0,4,1,3,2
};
/* from Contour3D.java, used by poly_triangle_stripe */
static final int ITAB[] =
{ 0,2,1, 1,0,2, 2,1,0,
0,3,1,2, 1,0,2,3, 2,1,3,0, 3,2,0,1,
0,4,1,3,2, 1,0,2,4,3, 2,1,3,0,4, 3,2,4,1,0, 4,3,0,2,1,
0,5,1,4,2,3, 1,0,2,5,3,4, 2,1,3,0,4,5, 3,2,4,1,5,0, 4,3,5,2,0,1,
5,4,0,3,1,2
};
/* from Contour3D.java, used by poly_triangle_stripe */
static final int STAB[] = { 0, 9, 25, 50 };
/* copied from Contour3D.java */
static int poly_triangle_stripe( int[] Tri_Stripe,
int nvertex, int npolygons,
int[][] vertToPoly, int[][] polyToVert)
/* WLH 25 Oct 97
int[] Pol_f_Vert, int[] Vert_f_Pol )
*/
throws VisADException {
int i, j, k, m, ii, npol, cpol, idx, off, Nvt,
vA, vB, ivA, ivB, iST, last_pol;
boolean f_line_conection = false;
boolean[] vet_pol = new boolean[npolygons];
last_pol = 0;
npol = 0;
iST = 0;
ivB = 0;
for (i=0; i<npolygons; i++) vet_pol[i] = true; /* Vectorized */
while (true)
{
/* find_unselected_pol(cpol); */
for (cpol=last_pol; cpol<npolygons; cpol++) {
if ( vet_pol[cpol] ) break;
}
if (cpol == npolygons) {
cpol = -1;
}
else {
last_pol = cpol;
}
/* end find_unselected_pol(cpol); */
if (cpol < 0) break;
/* ypdate_polygon */
// System.out.println("1 vet_pol[" + cpol + "] = false");
vet_pol[cpol] = false;
/* end update_polygon */
/* get_vertices_of_pol(cpol,Vt,Nvt); { */
/* WLH 25 Oct 97
Nvt = Vert_f_Pol[(j=cpol*7)+6];
off = j;
*/
Nvt = polyToVert[cpol].length;
/* } */
/* end get_vertices_of_pol(cpol,Vt,Nvt); { */
for (ivA=0; ivA<Nvt; ivA++) {
ivB = (((ivA+1)==Nvt) ? 0:(ivA+1));
/* get_pol_vert(Vt[ivA],Vt[ivB],npol) { */
npol = -1;
/* WLH 25 Oct 97
if (Vert_f_Pol[ivA+off]>=0 && Vert_f_Pol[ivB+off]>=0) {
i=Vert_f_Pol[ivA+off]*9;
k=i+Pol_f_Vert [i+8];
j=Vert_f_Pol[ivB+off]*9;
m=j+Pol_f_Vert [j+8];
while (i>0 && j>0 && i<k && j <m ) {
if (Pol_f_Vert [i] == Pol_f_Vert [j] &&
vet_pol[Pol_f_Vert[i]] ) {
npol=Pol_f_Vert [i];
break;
}
else if (Pol_f_Vert [i] < Pol_f_Vert [j])
i++;
else
j++;
}
}
*/
if (ivA < polyToVert[cpol].length && ivB < polyToVert[cpol].length) {
i=polyToVert[cpol][ivA];
int ilim = vertToPoly[i].length;
k = 0;
j=polyToVert[cpol][ivB];
int jlim = vertToPoly[j].length;
m = 0;
// while (0<k && k<ilim && 0<m && m<jlim) {
while (0<i && k<ilim && 0<j && m<jlim) {
if (vertToPoly[i][k] == vertToPoly[j][m] &&
vet_pol[vertToPoly[i][k]] ) {
npol=vertToPoly[i][k];
break;
}
else if (vertToPoly[i][k] < vertToPoly[j][m])
k++;
else
m++;
}
}
/* } */
/* end get_pol_vert(Vt[ivA],Vt[ivB],npol) { */
if (npol >= 0) break;
}
/* insert polygon alone */
if (npol < 0)
{ /*ptT = NTAB + STAB[Nvt-3];*/
idx = STAB[Nvt-3];
if (iST > 0)
{ Tri_Stripe[iST] = Tri_Stripe[iST-1]; iST++;
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx]+off];
*/
// System.out.println("1 Tri_Stripe[" + iST + "] from poly " + cpol);
Tri_Stripe[iST++] = polyToVert[cpol][NTAB[idx]];
}
else f_line_conection = true; /* WLH 3-9-95 added */
for (ii=0; ii< ((Nvt < 6) ? Nvt:6); ii++) {
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx++]+off];
*/
// System.out.println("2 Tri_Stripe[" + iST + "] from poly " + cpol);
Tri_Stripe[iST++] = polyToVert[cpol][NTAB[idx++]];
}
continue;
}
if (( (ivB != 0) && ivA==(ivB-1)) || ( !(ivB != 0) && ivA==Nvt-1)) {
/* ptT = ITAB + STAB[Nvt-3] + (ivB+1)*Nvt; */
idx = STAB[Nvt-3] + (ivB+1)*Nvt;
if (f_line_conection)
{ Tri_Stripe[iST] = Tri_Stripe[iST-1]; iST++;
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[ITAB[idx-1]+off];
*/
// System.out.println("3 Tri_Stripe[" + iST + "] from poly " + cpol);
Tri_Stripe[iST++] = polyToVert[cpol][ITAB[idx-1]];
f_line_conection = false;
}
for (ii=0; ii<((Nvt < 6) ? Nvt:6); ii++) {
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[ITAB[--idx]+off];
*/
// System.out.println("4 Tri_Stripe[" + iST + "] from poly " + cpol);
Tri_Stripe[iST++] = polyToVert[cpol][ITAB[--idx]];
}
}
else {
/* ptT = NTAB + STAB[Nvt-3] + (ivB+1)*Nvt; */
idx = STAB[Nvt-3] + (ivB+1)*Nvt;
if (f_line_conection)
{ Tri_Stripe[iST] = Tri_Stripe[iST-1]; iST++;
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx-1]+off];
*/
// System.out.println("5 Tri_Stripe[" + iST + "] from poly " + cpol);
Tri_Stripe[iST++] = polyToVert[cpol][NTAB[idx-1]];
f_line_conection = false;
}
for (ii=0; ii<((Nvt < 6) ? Nvt:6); ii++) {
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[--idx]+off];
*/
// System.out.println("6 Tri_Stripe[" + iST + "] from poly " + cpol);
Tri_Stripe[iST++] = polyToVert[cpol][NTAB[--idx]];
}
}
vB = Tri_Stripe[iST-1];
vA = Tri_Stripe[iST-2];
cpol = npol;
while (true)
{
/* get_vertices_of_pol(cpol,Vt,Nvt) { */
/* WLH 25 Oct 97
Nvt = Vert_f_Pol [(j=cpol*7)+6];
off = j;
*/
Nvt = polyToVert[cpol].length;
/* } */
/* update_polygon(cpol) */
// System.out.println("2 vet_pol[" + cpol + "] = false");
vet_pol[cpol] = false;
/* WLH 25 Oct 97
for (ivA=0; ivA<Nvt && Vert_f_Pol[ivA+off]!=vA; ivA++);
for (ivB=0; ivB<Nvt && Vert_f_Pol[ivB+off]!=vB; ivB++);
*/
for (ivA=0; ivA<Nvt && polyToVert[cpol][ivA]!=vA; ivA++);
for (ivB=0; ivB<Nvt && polyToVert[cpol][ivB]!=vB; ivB++);
if (( (ivB != 0) && ivA==(ivB-1)) || (!(ivB != 0) && ivA==Nvt-1)) {
/* ptT = NTAB + STAB[Nvt-3] + ivA*Nvt + 2; */
idx = STAB[Nvt-3] + ivA*Nvt + 2;
for (ii=2; ii<((Nvt < 6) ? Nvt:6); ii++) {
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[NTAB[idx++]+off];
*/
// System.out.println("7 Tri_Stripe[" + iST + "] from poly " + cpol);
Tri_Stripe[iST++] = polyToVert[cpol][NTAB[idx++]];
}
}
else {
/* ptT = ITAB + STAB[Nvt-3] + ivA*Nvt + 2; */
idx = STAB[Nvt-3] + ivA*Nvt + 2;
for (ii=2; ii<((Nvt < 6) ? Nvt:6); ii++) {
/* WLH 25 Oct 97
Tri_Stripe[iST++] = Vert_f_Pol[ITAB[idx++]+off];
*/
// System.out.println("8 Tri_Stripe[" + iST + "] from poly " + cpol);
Tri_Stripe[iST++] = polyToVert[cpol][ITAB[idx++]];
}
}
vB = Tri_Stripe[iST-1];
vA = Tri_Stripe[iST-2];
/* get_pol_vert(vA,vB,cpol) { */
cpol = -1;
/* WLH 25 Oct 97
if (vA>=0 && vB>=0) {
i=vA*9;
k=i+Pol_f_Vert [i+8];
j=vB*9;
m=j+Pol_f_Vert [j+8];
while (i>0 && j>0 && i<k && j<m) {
if (Pol_f_Vert [i] == Pol_f_Vert [j] &&
vet_pol[Pol_f_Vert[i]] ) {
cpol=Pol_f_Vert[i];
break;
}
else if (Pol_f_Vert [i] < Pol_f_Vert [j])
i++;
else
j++;
}
}
*/
if (vA>=0 && vB>=0) {
int ilim = vertToPoly[vA].length;
k = 0;
int jlim = vertToPoly[vB].length;
m = 0;
// while (0<k && k<ilim && 0<m && m<jlim) {
while (0<vA && k<ilim && 0<vB && m<jlim) {
if (vertToPoly[vA][k] == vertToPoly[vB][m] &&
vet_pol[vertToPoly[vA][k]] ) {
cpol=vertToPoly[vA][k];
break;
}
else if (vertToPoly[vA][k] < vertToPoly[vB][m])
k++;
else
m++;
}
}
/* } */
if (cpol < 0) {
vA = Tri_Stripe[iST-3];
/* get_pol_vert(vA,vB,cpol) { */
cpol = -1;
/* WLH 25 Oct 97
if (vA>=0 && vB>=0) {
i=vA*9;
k=i+Pol_f_Vert [i+8];
j=vB*9;
m=j+Pol_f_Vert [j+8];
while (i>0 && j>0 && i<k && j<m) {
if (Pol_f_Vert [i] == Pol_f_Vert [j] &&
vet_pol[Pol_f_Vert[i]] ) {
cpol=Pol_f_Vert[i];
break;
}
else if (Pol_f_Vert [i] < Pol_f_Vert [j])
i++;
else
j++;
}
}
*/
if (vA>=0 && vB>=0) {
int ilim = vertToPoly[vA].length;
k = 0;
int jlim = vertToPoly[vB].length;
m = 0;
// while (0<k && k<ilim && 0<m && m<jlim) {
while (0<vA && k<ilim && 0<vB && m<jlim) {
if (vertToPoly[vA][k] == vertToPoly[vB][m] &&
vet_pol[vertToPoly[vA][k]] ) {
cpol=vertToPoly[vA][k];
break;
}
else if (vertToPoly[vA][k] < vertToPoly[vB][m])
k++;
else
m++;
}
}
/* } */
if (cpol < 0) {
f_line_conection = true;
break;
}
else {
// System.out.println("9 Tri_Stripe[" + iST + "] where cpol = " + cpol);
// WLH 5 May 2004 - fix bug vintage 1990 or 91
if (iST > 0) {
Tri_Stripe[iST] = Tri_Stripe[iST-1];
iST++;
}
Tri_Stripe[iST++] = vA;
i = vA;
vA = vB;
vB = i;
}
}
}
}
return iST;
}
/** create a 2-D GeometryArray from this Set and color_values */
public VisADGeometryArray make2DGeometry(byte[][] color_values,
boolean indexed) throws VisADException {
if (DomainDimension != 3) {
throw new SetException("Irregular3DSet.make2DGeometry: " +
"DomainDimension must be 3, not " +
DomainDimension);
}
if (ManifoldDimension != 2) {
throw new SetException("Irregular3DSet.make2DGeometry: " +
"ManifoldDimension must be 2, not " +
ManifoldDimension);
}
int npolygons = Delan.Tri.length;
int nvertex = Delan.Vertices.length;
if (npolygons < 1 || nvertex < 3) return null;
// make sure all triangles have the same signature
// i.e., winding direction
int[][] Tri = Delan.Tri;
int[][] Walk = Delan.Walk;
int dim = Tri[0].length - 1;
int[][] tri = new int[npolygons][];
int[] poly_stack = new int[npolygons];
int[] walk_stack = new int[npolygons];
int sp; // stack pointer
for (int ii=0; ii<npolygons; ii++) {
// find an un-adjusted triangle
if (tri[ii] == null) {
// initialize its signature
tri[ii] = new int[3];
tri[ii][0] = Tri[ii][0];
tri[ii][1] = Tri[ii][1];
tri[ii][2] = Tri[ii][2];
// first stack entry, for recursive search of triangles
// via Walk array
sp = 0;
walk_stack[sp] = 0;
poly_stack[sp] = ii;
while (true) {
// find neighbor triangle via Walk
int i = poly_stack[sp];
int w = walk_stack[sp];
int j = Walk[i][w];
if (j >= 0 && tri[j] == null) {
// compare signatures of neighbors
int v1 = Tri[i][w];
int v2 = Tri[i][(w + 1) % 3];
int i1 = -1;
int i2 = -1;
int j1 = -1;
int j2 = -1;
for (int k=0; k<3; k++) {
if (tri[i][k] == v1) i1 = k;
if (tri[i][k] == v2) i2 = k;
if (Tri[j][k] == v1) j1 = k;
if (Tri[j][k] == v2) j2 = k;
}
tri[j] = new int[3];
tri[j][0] = Tri[j][0];
if ( ( (((i1 + 1) % 3) == i2) && (((j1 + 1) % 3) == j2) ) ||
( (((i2 + 1) % 3) == i1) && (((j2 + 1) % 3) == j1) ) ) {
tri[j][1] = Tri[j][2];
tri[j][2] = Tri[j][1];
}
else {
tri[j][1] = Tri[j][1];
tri[j][2] = Tri[j][2];
}
// add j to stack
sp++;
walk_stack[sp] = 0;
poly_stack[sp] = j;
}
else { // (j < 0 || tri[j] != null)
while (true) {
walk_stack[sp]++;
if (walk_stack[sp] < 3) {
break;
}
else {
sp--;
if (sp < 0) break;
}
} // end while (true)
} // end if (j < 0 || tri[j] != null)
if (sp < 0) break;
} // end while (true)
} // end if (tri[ii] == null)
} // end for (int ii=0; ii<npolygons; ii++)
float[][] samples = getSamples(false);
float[] NxA = new float[npolygons];
float[] NxB = new float[npolygons];
float[] NyA = new float[npolygons];
float[] NyB = new float[npolygons];
float[] NzA = new float[npolygons];
float[] NzB = new float[npolygons];
float[] Pnx = new float[npolygons];
float[] Pny = new float[npolygons];
float[] Pnz = new float[npolygons];
float[] NX = new float[nvertex];
float[] NY = new float[nvertex];
float[] NZ = new float[nvertex];
make_normals(samples[0], samples[1], samples[2],
NX, NY, NZ, nvertex, npolygons, Pnx, Pny, Pnz,
NxA, NxB, NyA, NyB, NzA, NzB, Delan.Vertices, tri);
// NxA, NxB, NyA, NyB, NzA, NzB, Delan.Vertices, Delan.Tri);
// take the garbage out
NxA = NxB = NyA = NyB = NzA = NzB = Pnx = Pny = Pnz = null;
float[] normals = new float[3 * nvertex];
int j = 0;
for (int i=0; i<nvertex; i++) {
normals[j++] = (float) NX[i];
normals[j++] = (float) NY[i];
normals[j++] = (float) NZ[i];
}
// take the garbage out
NX = NY = NZ = null;
// temporary array to hold maximum possible polytriangle strip
int[] stripe = new int[6 * npolygons];
int size_stripe =
poly_triangle_stripe(stripe, nvertex, npolygons,
Delan.Vertices, Delan.Tri);
if (indexed) {
VisADIndexedTriangleStripArray array =
new VisADIndexedTriangleStripArray();
// array.vertexFormat |= NORMALS;
array.normals = normals;
// take the garbage out
normals = null;
// set up indices
array.indexCount = size_stripe;
array.indices = new int[size_stripe];
System.arraycopy(stripe, 0, array.indices, 0, size_stripe);
array.stripVertexCounts = new int[1];
array.stripVertexCounts[0] = size_stripe;
// take the garbage out
stripe = null;
// set coordinates and colors
setGeometryArray(array, samples, 4, color_values);
// take the garbage out
samples = null;
return array;
}
else { // if (!indexed)
VisADTriangleStripArray array = new VisADTriangleStripArray();
array.stripVertexCounts = new int[] {size_stripe};
array.vertexCount = size_stripe;
array.normals = new float[3 * size_stripe];
int k = 0;
for (int i=0; i<3*size_stripe; i+=3) {
j = 3 * stripe[k];
array.normals[i] = normals[j];
array.normals[i+1] = normals[j+1];
array.normals[i+2] = normals[j+2];
k++;
}
normals = null;
array.coordinates = new float[3 * size_stripe];
k = 0;
for (int i=0; i<3*size_stripe; i+=3) {
j = stripe[k];
array.coordinates[i] = samples[0][j];
array.coordinates[i+1] = samples[1][j];
array.coordinates[i+2] = samples[2][j];
/*
System.out.println("strip[" + k + "] = (" + array.coordinates[i] + ", " +
array.coordinates[i+1] + ", " +
array.coordinates[i+2] + ")");
*/
k++;
}
samples = null;
if (color_values != null) {
int color_length = color_values.length;
array.colors = new byte[color_length * size_stripe];
k = 0;
if (color_length == 4) {
for (int i=0; i<color_length*size_stripe; i+=color_length) {
j = stripe[k];
array.colors[i] = color_values[0][j];
array.colors[i+1] = color_values[1][j];
array.colors[i+2] = color_values[2][j];
array.colors[i+3] = color_values[3][j];
k++;
}
}
else { // if (color_length == 3)
for (int i=0; i<color_length*size_stripe; i+=color_length) {
j = stripe[k];
array.colors[i] = color_values[0][j];
array.colors[i+1] = color_values[1][j];
array.colors[i+2] = color_values[2][j];
k++;
}
}
}
color_values = null;
stripe = null;
return array;
} // end if (!indexed)
}
public Object cloneButType(MathType type) throws VisADException {
if (ManifoldDimension == 1) {
return new Irregular3DSet(type, Samples, newToOld, oldToNew,
DomainCoordinateSystem, SetUnits, SetErrors);
}
else {
return new Irregular3DSet(type, Samples, DomainCoordinateSystem,
SetUnits, SetErrors, Delan);
}
}
/* run 'java visad.Irregular3DSet' to test the Irregular3DSet class */
public static void main(String[] argv) throws VisADException {
float[][] samp = { {179, 232, 183, 244, 106, 344, 166, 304, 286},
{ 86, 231, 152, 123, 183, 153, 308, 325, 89},
{121, 301, 346, 352, 123, 125, 187, 101, 142} };
RealType test1 = RealType.getRealType("x");
RealType test2 = RealType.getRealType("y");
RealType test3 = RealType.getRealType("z");
RealType[] t_array = {test1, test2, test3};
RealTupleType t_tuple = new RealTupleType(t_array);
Irregular3DSet iSet3D = new Irregular3DSet(t_tuple, samp);
// print out Samples information
System.out.println("Samples:");
for (int i=0; i<iSet3D.Samples[0].length; i++) {
System.out.println("#"+i+":\t"+iSet3D.Samples[0][i]+", "
+iSet3D.Samples[1][i]+", "
+iSet3D.Samples[2][i]);
}
System.out.println(iSet3D.Delan.Tri.length
+" tetrahedrons in tetrahedralization.");
// test valueToIndex function
System.out.println("\nvalueToIndex test:");
float[][] value = { {189, 221, 319, 215, 196},
{166, 161, 158, 139, 285},
{207, 300, 127, 287, 194} };
int[] index = iSet3D.valueToIndex(value);
for (int i=0; i<index.length; i++) {
System.out.println(value[0][i]+", "+value[1][i]+", "
+value[2][i]+"\t--> #"+index[i]);
}
// test valueToInterp function
System.out.println("\nvalueToInterp test:");
int[][] indices = new int[value[0].length][];
float[][] weights = new float[value[0].length][];
iSet3D.valueToInterp(value, indices, weights);
for (int i=0; i<value[0].length; i++) {
System.out.println(value[0][i]+", "+value[1][i]+", "
+value[2][i]+"\t--> ["
+indices[i][0]+", "
+indices[i][1]+", "
+indices[i][2]+", "
+indices[i][3]+"]\tweight total: "
+(weights[i][0]+weights[i][1]
+weights[i][2]+weights[i][3]));
}
// test makeIsosurface function
System.out.println("\nmakeIsosurface test:");
float[] field = {100, 300, 320, 250, 80, 70, 135, 110, 105};
float[][] slice = new float[3][];
int[][][] polyvert = new int[1][][];
int[][][] vertpoly = new int[1][][];
iSet3D.makeIsosurface(288, field, null, slice, null, polyvert, vertpoly);
for (int i=0; i<slice[0].length; i++) {
for (int j=0; j<3; j++) {
slice[j][i] = (float) Math.round(1000*slice[j][i]) / 1000;
}
}
System.out.println("polygons:");
for (int i=0; i<polyvert[0].length; i++) {
System.out.print("#"+i+":");
/* WLH 25 Oct 97
for (int j=0; j<4; j++) {
if (polyvert[0][i][j] != -1) {
if (j == 1) {
if (polyvert[0][i][3] == -1) {
System.out.print("(tri)");
}
else {
System.out.print("(quad)");
}
}
System.out.println("\t"+slice[0][polyvert[0][i][j]]
+", "+slice[1][polyvert[0][i][j]]
+", "+slice[2][polyvert[0][i][j]]);
}
}
*/
for (int j=0; j<polyvert[0][i].length; j++) {
if (j == 1) {
if (polyvert[0][i].length == 3) {
System.out.print("(tri)");
}
else {
System.out.print("(quad)");
}
}
System.out.println("\t"+slice[0][polyvert[0][i][j]]
+", "+slice[1][polyvert[0][i][j]]
+", "+slice[2][polyvert[0][i][j]]);
}
}
System.out.println();
for (int i=0; i<polyvert[0].length; i++) {
int a = polyvert[0][i][0];
int b = polyvert[0][i][1];
int c = polyvert[0][i][2];
int d = polyvert[0][i].length==4 ? polyvert[0][i][3] : -1;
boolean found = false;
for (int j=0; j<vertpoly[0][a].length; j++) {
if (vertpoly[0][a][j] == i) found = true;
}
if (!found) {
System.out.println("vertToPoly array corrupted at triangle #"
+i+" vertex #0!");
}
found = false;
for (int j=0; j<vertpoly[0][b].length; j++) {
if (vertpoly[0][b][j] == i) found = true;
}
if (!found) {
System.out.println("vertToPoly array corrupted at triangle #"
+i+" vertex #1!");
}
found = false;
for (int j=0; j<vertpoly[0][c].length; j++) {
if (vertpoly[0][c][j] == i) found = true;
}
if (!found) {
System.out.println("vertToPoly array corrupted at triangle #"
+i+" vertex #2!");
}
found = false;
if (d != -1) {
for (int j=0; j<vertpoly[0][d].length; j++) {
if (vertpoly[0][d][j] == i) found = true;
}
if (!found) {
System.out.println("vertToPoly array corrupted at triangle #"
+i+" vertex #3!");
}
}
}
}
/* Here's the output:
iris 45% java visad.Irregular3DSet
Samples:
#0: 179.0, 86.0, 121.0
#1: 232.0, 231.0, 301.0
#2: 183.0, 152.0, 346.0
#3: 244.0, 123.0, 352.0
#4: 106.0, 183.0, 123.0
#5: 344.0, 153.0, 125.0
#6: 166.0, 308.0, 187.0
#7: 304.0, 325.0, 101.0
#8: 286.0, 89.0, 142.0
15 tetrahedrons in tetrahedralization.
valueToIndex test:
189.0, 166.0, 207.0 --> #0
221.0, 161.0, 300.0 --> #2
319.0, 158.0, 127.0 --> #5
215.0, 139.0, 287.0 --> #2
196.0, 285.0, 194.0 --> #6
valueToInterp test:
189.0, 166.0, 207.0 --> [0, 1, 2, 4] weight total: 1.0
221.0, 161.0, 300.0 --> [1, 2, 3, 8] weight total: 1.0
319.0, 158.0, 127.0 --> [4, 5, 6, 8] weight total: 0.9999999999999999
215.0, 139.0, 287.0 --> [1, 2, 3, 8] weight total: 1.0
196.0, 285.0, 194.0 --> [1, 5, 6, 7] weight total: 1.0
makeIsosurface test:
polygons:
#0: 237.843, 226.93, 291.817
(tri) 227.2, 236.6, 292.709
236.547, 236.937, 288.368
#1: 228.82, 222.3, 290.2
(quad) 182.418, 142.4, 313.273
225.127, 228.382, 291.291
172.733, 156.133, 316.267
#2: 225.127, 228.382, 291.291
(tri) 227.2, 236.6, 292.709
235.323, 222.262, 291.215
#3: 228.82, 222.3, 290.2
(quad) 182.418, 142.4, 313.273
235.323, 222.262, 291.215
198.33, 142.623, 315.637
#4: 234.88, 205.08, 313.24
(tri) 237.843, 226.93, 291.817
235.323, 222.262, 291.215
#5: 182.418, 142.4, 313.273
(tri) 210.886, 138.743, 348.743
198.33, 142.623, 315.637
#6: 234.88, 205.08, 313.24
(quad) 235.323, 222.262, 291.215
210.886, 138.743, 348.743
198.33, 142.623, 315.637
#7: 225.127, 228.382, 291.291
(quad) 227.2, 236.6, 292.709
172.733, 156.133, 316.267
180.059, 178.984, 318.497
#8: 234.88, 205.08, 313.24
(tri) 237.843, 226.93, 291.817
236.547, 236.937, 288.368
#9: 228.82, 222.3, 290.2
(tri) 225.127, 228.382, 291.291
235.323, 222.262, 291.215
#10: 237.843, 226.93, 291.817
(tri) 227.2, 236.6, 292.709
235.323, 222.262, 291.215
iris 46%
*/
}
|
diff --git a/syncronizer/src/org/sync/MainEntry.java b/syncronizer/src/org/sync/MainEntry.java
index 69f61e4..dcd58d1 100644
--- a/syncronizer/src/org/sync/MainEntry.java
+++ b/syncronizer/src/org/sync/MainEntry.java
@@ -1,229 +1,234 @@
/*****************************************************************************
This file is part of Git-Starteam.
Git-Starteam 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.
Git-Starteam 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 Git-Starteam. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package org.sync;
import java.io.Console;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.starbase.starteam.Project;
import com.starbase.starteam.Server;
import com.starbase.starteam.View;
import com.starbase.starteam.vts.comm.NetMonitor;
import jargs.gnu.CmdLineParser;
import jargs.gnu.CmdLineParser.IllegalOptionValueException;
import jargs.gnu.CmdLineParser.UnknownOptionException;
public class MainEntry {
/**
* @param args
*/
public static void main(String[] args) {
CmdLineParser parser = new CmdLineParser();
CmdLineParser.Option selectHost = parser.addStringOption('h', "host");
CmdLineParser.Option selectPort = parser.addIntegerOption('P', "port");
CmdLineParser.Option selectProject = parser.addStringOption('p', "project");
CmdLineParser.Option selectView = parser.addStringOption('v', "view");
CmdLineParser.Option selectTimeBasedImport = parser.addBooleanOption('T', "time-based");
CmdLineParser.Option selectLabelBasedImport = parser.addBooleanOption('L', "label-based");
CmdLineParser.Option selectTime = parser.addStringOption('t', "time");
CmdLineParser.Option selectFolder = parser.addStringOption('f', "folder");
CmdLineParser.Option selectDomain = parser.addStringOption('d', "domain");
CmdLineParser.Option isExpandKeywords = parser.addBooleanOption('k', "keyword");
CmdLineParser.Option selectUser = parser.addStringOption('U', "user");
CmdLineParser.Option isResume = parser.addBooleanOption('R', "resume");
CmdLineParser.Option selectHead = parser.addStringOption('H', "head");
CmdLineParser.Option selectPath = parser.addStringOption('X', "path-to-program");
CmdLineParser.Option isCreateRepo = parser.addBooleanOption('c', "create-new-repo");
CmdLineParser.Option selectPassword = parser.addStringOption("password");
CmdLineParser.Option dumpToFile = parser.addStringOption('D', "dump");
CmdLineParser.Option selectWorkingFolder = parser.addStringOption('W', "working-folder");
CmdLineParser.Option isVerbose = parser.addBooleanOption("verbose");
CmdLineParser.Option isCheckpoint = parser.addBooleanOption("checkpoint");
try {
parser.parse(args);
} catch (IllegalOptionValueException e) {
System.err.println(e.getMessage());
printHelp();
System.exit(1);
} catch (UnknownOptionException e) {
System.err.println(e.getMessage());
printHelp();
System.exit(2);
}
String host = (String) parser.getOptionValue(selectHost);
Integer port = (Integer) parser.getOptionValue(selectPort);
String project = (String) parser.getOptionValue(selectProject);
String view = (String) parser.getOptionValue(selectView);
String time = (String) parser.getOptionValue(selectTime);
Boolean timeBased = (Boolean) parser.getOptionValue(selectTimeBasedImport);
Boolean labelBased = (Boolean) parser.getOptionValue(selectLabelBasedImport);
String folder = (String) parser.getOptionValue(selectFolder);
String domain = (String) parser.getOptionValue(selectDomain);
Boolean keyword = (Boolean) parser.getOptionValue(isExpandKeywords);
String user = (String) parser.getOptionValue(selectUser);
Boolean resume = (Boolean) parser.getOptionValue(isResume);
String head = (String) parser.getOptionValue(selectHead);
String pathToProgram = (String) parser.getOptionValue(selectPath);
Boolean createNewRepo = (Boolean) parser.getOptionValue(isCreateRepo);
String password = (String) parser.getOptionValue(selectPassword);
String dumpTo = (String) parser.getOptionValue(dumpToFile);
String workingFolder = (String) parser.getOptionValue(selectWorkingFolder);
Boolean verboseFlag = (Boolean) parser.getOptionValue(isVerbose);
boolean verbose = verboseFlag != null && verboseFlag;
Boolean checkpointFlag = (Boolean) parser.getOptionValue(isCheckpoint);
boolean createCheckpoints = checkpointFlag != null && checkpointFlag;
if(host == null || port == null || project == null || view == null) {
printHelp();
System.exit(3);
}
if(null != folder && !folder.endsWith("/")) {
folder = folder + "/";
}
Date date = null;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if(null != time) {
if(!((null != timeBased && timeBased) ||
(null != labelBased && labelBased))) {
System.out.println("-t option can only be used with -T or -L options.");
System.exit(3);
}
try {
date = dateFormat.parse(time);
} catch (Exception ex) {
System.out.println(ex.getMessage());
System.exit(3);
}
}
if(null == domain) {
domain = "cie.com";
}
RepositoryHelperFactory.getFactory().setPreferedPath(pathToProgram);
RepositoryHelperFactory.getFactory().setCreateRepo((null != createNewRepo));
if(null != workingFolder) {
RepositoryHelperFactory.getFactory().setWorkingFolder(workingFolder);
}
Server starteam = new Server(host, port);
starteam.connect();
Console con = System.console();
- if(null == user) {
+ if(null != con && null == user) {
user = con.readLine("Username:");
}
- if(null == password) {
- password = new String(con.readPassword("Password:"));
+ if(null != con && null == password) {
+ char[] passwordChars = con.readPassword("Password:");
+ if(null != passwordChars) {
+ password = new String(passwordChars);
+ } else {
+ password = null;
+ }
}
int userid = starteam.logOn(user, password);
if(userid > 0) {
// try to reconnect at 15 second intervals for 1 hour
starteam.setAutoReconnectEnabled(true);
starteam.setAutoReconnectAttempts(60 * 60 / 15);
starteam.setAutoReconnectWait(15);
boolean projectFound = false;
for(Project p : starteam.getProjects()) {
if(p.getName().equalsIgnoreCase(project)) {
projectFound = true;
if(null == keyword) {
p.setExpandKeywords(false);
} else {
p.setExpandKeywords(true);
}
GitImporter importer = new GitImporter(starteam, p);
try {
if(null != head) {
importer.setHeadName(head);
}
if(null != resume) {
importer.setResume(resume);
}
if(null != dumpTo) {
importer.setDumpFile(new File(dumpTo));
}
importer.setVerbose(verbose);
importer.setCreateCheckpoints(createCheckpoints);
boolean viewFound = false;
for(View v : p.getViews()) {
if(v.getName().equalsIgnoreCase(view)) {
viewFound = true;
NetMonitor.onFile(new java.io.File("netmon.out"));
if(null != timeBased && timeBased) {
importer.generateDayByDayImport(v, date, folder, domain);
} else if (null != labelBased && labelBased) {
importer.generateByLabelImport(v, date, folder, domain);
} else {
importer.generateFastImportStream(v, folder, domain);
}
break;
} else if(verbose) {
System.err.println("Not view: " + v.getName());
}
}
if (!viewFound) {
System.err.println("View not found: " + view);
}
} finally {
importer.dispose();
}
break;
} else if(verbose) {
System.err.println("Not project: " + p.getName());
}
}
if (!projectFound) {
System.err.println("Project not found: " + project);
}
} else {
System.err.println("Could not log in user: " + user);
}
}
public static void printHelp() {
System.out.println("-h <host>\t\tDefine on which host the server is hosted");
System.out.println("-P <port>\t\tDefine the port used to connect to the starteam server");
System.out.println("-p <project>\t\tSelect the project to import from");
System.out.println("-v <view>\t\tSelect the view used for importation");
System.out.println("-d <domain>\t\tSelect the email domain (format like gmail.com) of the user");
System.out.println("[-t <time>]\t\tSelect the time (format like \"2012-07-11 23:59:59\") to import from");
System.out.println("[-f <folder>]\t\tSelect the folder (format like Src/apps/vlc2android/) to import from");
System.out.println("[-T]\t\t\tDo a day by day importation of the starteam view");
System.out.println("[-L]\t\t\tDo a label by label importation of the starteam view");
System.out.println("[-k]\t\t\tSet to enable keyword expansion in text files");
System.out.println("[-U <user>]\t\tPreselect the user login");
System.out.println("[-R]\t\t\tResume the file history importation for branch view");
System.out.println("[-H <head>]\t\tSelect the name of the head to use");
System.out.println("[-X <path to git>]\tSelect the path to the git executable");
System.out.println("[-c]\t\t\tCreate a new repository if one does not exist");
System.out.println("[-W <folder>]\t\tSelect where the repository is located");
System.out.println("[--password]\t\tStarTeam password");
System.out.println("[-D <dump file prefix>]\tDump fast-import data to files");
System.out.println("[--checkpoint]\t\tCreate git fast-import checkpoints after each label");
System.out.println("[--verbose]\t\tVerbose output");
System.out.println("java org.sync.MainEntry -h localhost -P 23456 -p Alpha -v MAIN -d email.com -U you");
}
}
| false | true | public static void main(String[] args) {
CmdLineParser parser = new CmdLineParser();
CmdLineParser.Option selectHost = parser.addStringOption('h', "host");
CmdLineParser.Option selectPort = parser.addIntegerOption('P', "port");
CmdLineParser.Option selectProject = parser.addStringOption('p', "project");
CmdLineParser.Option selectView = parser.addStringOption('v', "view");
CmdLineParser.Option selectTimeBasedImport = parser.addBooleanOption('T', "time-based");
CmdLineParser.Option selectLabelBasedImport = parser.addBooleanOption('L', "label-based");
CmdLineParser.Option selectTime = parser.addStringOption('t', "time");
CmdLineParser.Option selectFolder = parser.addStringOption('f', "folder");
CmdLineParser.Option selectDomain = parser.addStringOption('d', "domain");
CmdLineParser.Option isExpandKeywords = parser.addBooleanOption('k', "keyword");
CmdLineParser.Option selectUser = parser.addStringOption('U', "user");
CmdLineParser.Option isResume = parser.addBooleanOption('R', "resume");
CmdLineParser.Option selectHead = parser.addStringOption('H', "head");
CmdLineParser.Option selectPath = parser.addStringOption('X', "path-to-program");
CmdLineParser.Option isCreateRepo = parser.addBooleanOption('c', "create-new-repo");
CmdLineParser.Option selectPassword = parser.addStringOption("password");
CmdLineParser.Option dumpToFile = parser.addStringOption('D', "dump");
CmdLineParser.Option selectWorkingFolder = parser.addStringOption('W', "working-folder");
CmdLineParser.Option isVerbose = parser.addBooleanOption("verbose");
CmdLineParser.Option isCheckpoint = parser.addBooleanOption("checkpoint");
try {
parser.parse(args);
} catch (IllegalOptionValueException e) {
System.err.println(e.getMessage());
printHelp();
System.exit(1);
} catch (UnknownOptionException e) {
System.err.println(e.getMessage());
printHelp();
System.exit(2);
}
String host = (String) parser.getOptionValue(selectHost);
Integer port = (Integer) parser.getOptionValue(selectPort);
String project = (String) parser.getOptionValue(selectProject);
String view = (String) parser.getOptionValue(selectView);
String time = (String) parser.getOptionValue(selectTime);
Boolean timeBased = (Boolean) parser.getOptionValue(selectTimeBasedImport);
Boolean labelBased = (Boolean) parser.getOptionValue(selectLabelBasedImport);
String folder = (String) parser.getOptionValue(selectFolder);
String domain = (String) parser.getOptionValue(selectDomain);
Boolean keyword = (Boolean) parser.getOptionValue(isExpandKeywords);
String user = (String) parser.getOptionValue(selectUser);
Boolean resume = (Boolean) parser.getOptionValue(isResume);
String head = (String) parser.getOptionValue(selectHead);
String pathToProgram = (String) parser.getOptionValue(selectPath);
Boolean createNewRepo = (Boolean) parser.getOptionValue(isCreateRepo);
String password = (String) parser.getOptionValue(selectPassword);
String dumpTo = (String) parser.getOptionValue(dumpToFile);
String workingFolder = (String) parser.getOptionValue(selectWorkingFolder);
Boolean verboseFlag = (Boolean) parser.getOptionValue(isVerbose);
boolean verbose = verboseFlag != null && verboseFlag;
Boolean checkpointFlag = (Boolean) parser.getOptionValue(isCheckpoint);
boolean createCheckpoints = checkpointFlag != null && checkpointFlag;
if(host == null || port == null || project == null || view == null) {
printHelp();
System.exit(3);
}
if(null != folder && !folder.endsWith("/")) {
folder = folder + "/";
}
Date date = null;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if(null != time) {
if(!((null != timeBased && timeBased) ||
(null != labelBased && labelBased))) {
System.out.println("-t option can only be used with -T or -L options.");
System.exit(3);
}
try {
date = dateFormat.parse(time);
} catch (Exception ex) {
System.out.println(ex.getMessage());
System.exit(3);
}
}
if(null == domain) {
domain = "cie.com";
}
RepositoryHelperFactory.getFactory().setPreferedPath(pathToProgram);
RepositoryHelperFactory.getFactory().setCreateRepo((null != createNewRepo));
if(null != workingFolder) {
RepositoryHelperFactory.getFactory().setWorkingFolder(workingFolder);
}
Server starteam = new Server(host, port);
starteam.connect();
Console con = System.console();
if(null == user) {
user = con.readLine("Username:");
}
if(null == password) {
password = new String(con.readPassword("Password:"));
}
int userid = starteam.logOn(user, password);
if(userid > 0) {
// try to reconnect at 15 second intervals for 1 hour
starteam.setAutoReconnectEnabled(true);
starteam.setAutoReconnectAttempts(60 * 60 / 15);
starteam.setAutoReconnectWait(15);
boolean projectFound = false;
for(Project p : starteam.getProjects()) {
if(p.getName().equalsIgnoreCase(project)) {
projectFound = true;
if(null == keyword) {
p.setExpandKeywords(false);
} else {
p.setExpandKeywords(true);
}
GitImporter importer = new GitImporter(starteam, p);
try {
if(null != head) {
importer.setHeadName(head);
}
if(null != resume) {
importer.setResume(resume);
}
if(null != dumpTo) {
importer.setDumpFile(new File(dumpTo));
}
importer.setVerbose(verbose);
importer.setCreateCheckpoints(createCheckpoints);
boolean viewFound = false;
for(View v : p.getViews()) {
if(v.getName().equalsIgnoreCase(view)) {
viewFound = true;
NetMonitor.onFile(new java.io.File("netmon.out"));
if(null != timeBased && timeBased) {
importer.generateDayByDayImport(v, date, folder, domain);
} else if (null != labelBased && labelBased) {
importer.generateByLabelImport(v, date, folder, domain);
} else {
importer.generateFastImportStream(v, folder, domain);
}
break;
} else if(verbose) {
System.err.println("Not view: " + v.getName());
}
}
if (!viewFound) {
System.err.println("View not found: " + view);
}
} finally {
importer.dispose();
}
break;
} else if(verbose) {
System.err.println("Not project: " + p.getName());
}
}
if (!projectFound) {
System.err.println("Project not found: " + project);
}
} else {
System.err.println("Could not log in user: " + user);
}
}
| public static void main(String[] args) {
CmdLineParser parser = new CmdLineParser();
CmdLineParser.Option selectHost = parser.addStringOption('h', "host");
CmdLineParser.Option selectPort = parser.addIntegerOption('P', "port");
CmdLineParser.Option selectProject = parser.addStringOption('p', "project");
CmdLineParser.Option selectView = parser.addStringOption('v', "view");
CmdLineParser.Option selectTimeBasedImport = parser.addBooleanOption('T', "time-based");
CmdLineParser.Option selectLabelBasedImport = parser.addBooleanOption('L', "label-based");
CmdLineParser.Option selectTime = parser.addStringOption('t', "time");
CmdLineParser.Option selectFolder = parser.addStringOption('f', "folder");
CmdLineParser.Option selectDomain = parser.addStringOption('d', "domain");
CmdLineParser.Option isExpandKeywords = parser.addBooleanOption('k', "keyword");
CmdLineParser.Option selectUser = parser.addStringOption('U', "user");
CmdLineParser.Option isResume = parser.addBooleanOption('R', "resume");
CmdLineParser.Option selectHead = parser.addStringOption('H', "head");
CmdLineParser.Option selectPath = parser.addStringOption('X', "path-to-program");
CmdLineParser.Option isCreateRepo = parser.addBooleanOption('c', "create-new-repo");
CmdLineParser.Option selectPassword = parser.addStringOption("password");
CmdLineParser.Option dumpToFile = parser.addStringOption('D', "dump");
CmdLineParser.Option selectWorkingFolder = parser.addStringOption('W', "working-folder");
CmdLineParser.Option isVerbose = parser.addBooleanOption("verbose");
CmdLineParser.Option isCheckpoint = parser.addBooleanOption("checkpoint");
try {
parser.parse(args);
} catch (IllegalOptionValueException e) {
System.err.println(e.getMessage());
printHelp();
System.exit(1);
} catch (UnknownOptionException e) {
System.err.println(e.getMessage());
printHelp();
System.exit(2);
}
String host = (String) parser.getOptionValue(selectHost);
Integer port = (Integer) parser.getOptionValue(selectPort);
String project = (String) parser.getOptionValue(selectProject);
String view = (String) parser.getOptionValue(selectView);
String time = (String) parser.getOptionValue(selectTime);
Boolean timeBased = (Boolean) parser.getOptionValue(selectTimeBasedImport);
Boolean labelBased = (Boolean) parser.getOptionValue(selectLabelBasedImport);
String folder = (String) parser.getOptionValue(selectFolder);
String domain = (String) parser.getOptionValue(selectDomain);
Boolean keyword = (Boolean) parser.getOptionValue(isExpandKeywords);
String user = (String) parser.getOptionValue(selectUser);
Boolean resume = (Boolean) parser.getOptionValue(isResume);
String head = (String) parser.getOptionValue(selectHead);
String pathToProgram = (String) parser.getOptionValue(selectPath);
Boolean createNewRepo = (Boolean) parser.getOptionValue(isCreateRepo);
String password = (String) parser.getOptionValue(selectPassword);
String dumpTo = (String) parser.getOptionValue(dumpToFile);
String workingFolder = (String) parser.getOptionValue(selectWorkingFolder);
Boolean verboseFlag = (Boolean) parser.getOptionValue(isVerbose);
boolean verbose = verboseFlag != null && verboseFlag;
Boolean checkpointFlag = (Boolean) parser.getOptionValue(isCheckpoint);
boolean createCheckpoints = checkpointFlag != null && checkpointFlag;
if(host == null || port == null || project == null || view == null) {
printHelp();
System.exit(3);
}
if(null != folder && !folder.endsWith("/")) {
folder = folder + "/";
}
Date date = null;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if(null != time) {
if(!((null != timeBased && timeBased) ||
(null != labelBased && labelBased))) {
System.out.println("-t option can only be used with -T or -L options.");
System.exit(3);
}
try {
date = dateFormat.parse(time);
} catch (Exception ex) {
System.out.println(ex.getMessage());
System.exit(3);
}
}
if(null == domain) {
domain = "cie.com";
}
RepositoryHelperFactory.getFactory().setPreferedPath(pathToProgram);
RepositoryHelperFactory.getFactory().setCreateRepo((null != createNewRepo));
if(null != workingFolder) {
RepositoryHelperFactory.getFactory().setWorkingFolder(workingFolder);
}
Server starteam = new Server(host, port);
starteam.connect();
Console con = System.console();
if(null != con && null == user) {
user = con.readLine("Username:");
}
if(null != con && null == password) {
char[] passwordChars = con.readPassword("Password:");
if(null != passwordChars) {
password = new String(passwordChars);
} else {
password = null;
}
}
int userid = starteam.logOn(user, password);
if(userid > 0) {
// try to reconnect at 15 second intervals for 1 hour
starteam.setAutoReconnectEnabled(true);
starteam.setAutoReconnectAttempts(60 * 60 / 15);
starteam.setAutoReconnectWait(15);
boolean projectFound = false;
for(Project p : starteam.getProjects()) {
if(p.getName().equalsIgnoreCase(project)) {
projectFound = true;
if(null == keyword) {
p.setExpandKeywords(false);
} else {
p.setExpandKeywords(true);
}
GitImporter importer = new GitImporter(starteam, p);
try {
if(null != head) {
importer.setHeadName(head);
}
if(null != resume) {
importer.setResume(resume);
}
if(null != dumpTo) {
importer.setDumpFile(new File(dumpTo));
}
importer.setVerbose(verbose);
importer.setCreateCheckpoints(createCheckpoints);
boolean viewFound = false;
for(View v : p.getViews()) {
if(v.getName().equalsIgnoreCase(view)) {
viewFound = true;
NetMonitor.onFile(new java.io.File("netmon.out"));
if(null != timeBased && timeBased) {
importer.generateDayByDayImport(v, date, folder, domain);
} else if (null != labelBased && labelBased) {
importer.generateByLabelImport(v, date, folder, domain);
} else {
importer.generateFastImportStream(v, folder, domain);
}
break;
} else if(verbose) {
System.err.println("Not view: " + v.getName());
}
}
if (!viewFound) {
System.err.println("View not found: " + view);
}
} finally {
importer.dispose();
}
break;
} else if(verbose) {
System.err.println("Not project: " + p.getName());
}
}
if (!projectFound) {
System.err.println("Project not found: " + project);
}
} else {
System.err.println("Could not log in user: " + user);
}
}
|
diff --git a/src/main/java/pl/psnc/dl/wf4ever/rosrs/ZippedResearchObjectResource.java b/src/main/java/pl/psnc/dl/wf4ever/rosrs/ZippedResearchObjectResource.java
index 30dafcc5..d867bf68 100644
--- a/src/main/java/pl/psnc/dl/wf4ever/rosrs/ZippedResearchObjectResource.java
+++ b/src/main/java/pl/psnc/dl/wf4ever/rosrs/ZippedResearchObjectResource.java
@@ -1,60 +1,60 @@
package pl.psnc.dl.wf4ever.rosrs;
import java.io.InputStream;
import java.net.URI;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import pl.psnc.dl.wf4ever.common.ResearchObject;
import pl.psnc.dl.wf4ever.dlibra.DigitalLibraryException;
import pl.psnc.dl.wf4ever.dlibra.NotFoundException;
import com.sun.jersey.core.header.ContentDisposition;
/**
* A REST API resource corresponding to a zipped RO.
*
* @author Piotr Hołubowicz
*
*/
@Path("zippedROs/{ro_id}/")
public class ZippedResearchObjectResource {
/** URI info. */
@Context
UriInfo uriInfo;
/**
* Returns zip archive with contents of RO version.
*
* @param researchObjectId
* RO identifier - defined by the user
* @return 200 OK
* @throws DigitalLibraryException
* could not get the RO frol dLibra
* @throws NotFoundException
* could not get the RO frol dLibra
*/
@GET
@Produces({ "application/zip", "multipart/related" })
public Response getZippedRO(@PathParam("ro_id") String researchObjectId)
throws DigitalLibraryException, NotFoundException {
- URI uri = uriInfo.getAbsolutePath().resolve("../../ROs/" + researchObjectId);
+ URI uri = URI.create(uriInfo.getAbsolutePath().toString().replaceFirst("zippedROs", "ROs"));
ResearchObject researchObject = ResearchObject.findByUri(uri);
if (researchObject == null) {
researchObject = new ResearchObject(uri);
}
InputStream body = ROSRService.DL.get().getZippedResearchObject(researchObject);
//TODO add all named graphs from SMS that start with the base URI
ContentDisposition cd = ContentDisposition.type("application/zip").fileName(researchObjectId + ".zip").build();
return ResearchObjectResource.addLinkHeaders(Response.ok(body), uriInfo, researchObjectId)
.header("Content-disposition", cd).build();
}
}
| true | true | public Response getZippedRO(@PathParam("ro_id") String researchObjectId)
throws DigitalLibraryException, NotFoundException {
URI uri = uriInfo.getAbsolutePath().resolve("../../ROs/" + researchObjectId);
ResearchObject researchObject = ResearchObject.findByUri(uri);
if (researchObject == null) {
researchObject = new ResearchObject(uri);
}
InputStream body = ROSRService.DL.get().getZippedResearchObject(researchObject);
//TODO add all named graphs from SMS that start with the base URI
ContentDisposition cd = ContentDisposition.type("application/zip").fileName(researchObjectId + ".zip").build();
return ResearchObjectResource.addLinkHeaders(Response.ok(body), uriInfo, researchObjectId)
.header("Content-disposition", cd).build();
}
| public Response getZippedRO(@PathParam("ro_id") String researchObjectId)
throws DigitalLibraryException, NotFoundException {
URI uri = URI.create(uriInfo.getAbsolutePath().toString().replaceFirst("zippedROs", "ROs"));
ResearchObject researchObject = ResearchObject.findByUri(uri);
if (researchObject == null) {
researchObject = new ResearchObject(uri);
}
InputStream body = ROSRService.DL.get().getZippedResearchObject(researchObject);
//TODO add all named graphs from SMS that start with the base URI
ContentDisposition cd = ContentDisposition.type("application/zip").fileName(researchObjectId + ".zip").build();
return ResearchObjectResource.addLinkHeaders(Response.ok(body), uriInfo, researchObjectId)
.header("Content-disposition", cd).build();
}
|
diff --git a/src/test/java/org/encog/neural/activation/TestActivationGaussian.java b/src/test/java/org/encog/neural/activation/TestActivationGaussian.java
index 4a30070ed..3fa23de44 100644
--- a/src/test/java/org/encog/neural/activation/TestActivationGaussian.java
+++ b/src/test/java/org/encog/neural/activation/TestActivationGaussian.java
@@ -1,55 +1,55 @@
/*
* Encog(tm) Core Unit Tests v3.0 - Java Version
* http://www.heatonresearch.com/encog/
* http://code.google.com/p/encog-java/
* Copyright 2008-2011 Heaton Research, 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.neural.activation;
import junit.framework.TestCase;
import org.encog.engine.network.activation.ActivationGaussian;
import org.junit.Assert;
import org.junit.Test;
public class TestActivationGaussian extends TestCase {
@Test
public void testGaussian() throws Throwable
{
ActivationGaussian activation = new ActivationGaussian(0.0,1.0);
- Assert.assertFalse(activation.hasDerivative());
+ Assert.assertFalse(!activation.hasDerivative());
ActivationGaussian clone = (ActivationGaussian)activation.clone();
Assert.assertNotNull(clone);
double[] input = { 0.0 };
activation.activationFunction(input,0,input.length);
Assert.assertEquals(1.0,input[0],0.1);
input[0] = activation.derivativeFunction(input[0],input[0]);
Assert.assertEquals(0,(int)(input[0]*100),0.1);
}
}
| true | true | public void testGaussian() throws Throwable
{
ActivationGaussian activation = new ActivationGaussian(0.0,1.0);
Assert.assertFalse(activation.hasDerivative());
ActivationGaussian clone = (ActivationGaussian)activation.clone();
Assert.assertNotNull(clone);
double[] input = { 0.0 };
activation.activationFunction(input,0,input.length);
Assert.assertEquals(1.0,input[0],0.1);
input[0] = activation.derivativeFunction(input[0],input[0]);
Assert.assertEquals(0,(int)(input[0]*100),0.1);
}
| public void testGaussian() throws Throwable
{
ActivationGaussian activation = new ActivationGaussian(0.0,1.0);
Assert.assertFalse(!activation.hasDerivative());
ActivationGaussian clone = (ActivationGaussian)activation.clone();
Assert.assertNotNull(clone);
double[] input = { 0.0 };
activation.activationFunction(input,0,input.length);
Assert.assertEquals(1.0,input[0],0.1);
input[0] = activation.derivativeFunction(input[0],input[0]);
Assert.assertEquals(0,(int)(input[0]*100),0.1);
}
|
diff --git a/filters/net.sf.okapi.filters.rtf/src/net/sf/okapi/filters/rtf/RTFFilter.java b/filters/net.sf.okapi.filters.rtf/src/net/sf/okapi/filters/rtf/RTFFilter.java
index 8443ee5f1..0a6a3f02d 100644
--- a/filters/net.sf.okapi.filters.rtf/src/net/sf/okapi/filters/rtf/RTFFilter.java
+++ b/filters/net.sf.okapi.filters.rtf/src/net/sf/okapi/filters/rtf/RTFFilter.java
@@ -1,1337 +1,1338 @@
/*===========================================================================
Copyright (C) 2008-2009 by the Okapi Framework contributors
-----------------------------------------------------------------------------
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
See also the full LGPL text here: http://www.gnu.org/copyleft/lesser.html
===========================================================================*/
package net.sf.okapi.filters.rtf;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
import java.util.logging.Logger;
import net.sf.okapi.common.Event;
import net.sf.okapi.common.EventType;
import net.sf.okapi.common.IParameters;
import net.sf.okapi.common.Util;
import net.sf.okapi.common.exceptions.OkapiIllegalFilterOperationException;
import net.sf.okapi.common.exceptions.OkapiIOException;
import net.sf.okapi.common.exceptions.OkapiUnsupportedEncodingException;
import net.sf.okapi.common.filters.FilterConfiguration;
import net.sf.okapi.common.filters.IFilter;
import net.sf.okapi.common.filterwriter.GenericFilterWriter;
import net.sf.okapi.common.filterwriter.IFilterWriter;
import net.sf.okapi.common.resource.Ending;
import net.sf.okapi.common.resource.RawDocument;
import net.sf.okapi.common.resource.StartDocument;
import net.sf.okapi.common.resource.TextFragment;
import net.sf.okapi.common.resource.TextUnit;
import net.sf.okapi.common.resource.TextFragment.TagType;
import net.sf.okapi.common.skeleton.GenericSkeletonWriter;
import net.sf.okapi.common.skeleton.ISkeletonWriter;
public class RTFFilter implements IFilter {
public static final int TOKEN_CHAR = 0;
public static final int TOKEN_STARTGROUP = 1;
public static final int TOKEN_ENDGROUP = 2;
public static final int TOKEN_ENDINPUT = 3;
public static final int TOKEN_CTRLWORD = 4;
// Do not use 0. Reserved for parsing
public static final int CW_ANSI = 1;
public static final int CW_F = 2;
public static final int CW_U = 3;
public static final int CW_ANSICPG = 4;
public static final int CW_LQUOTE = 5;
public static final int CW_RQUOTE = 6;
public static final int CW_LDBLQUOTE = 7;
public static final int CW_RDBLQUOTE = 8;
public static final int CW_BULLET = 9;
public static final int CW_ENDASH = 10;
public static final int CW_EMDASH = 11;
public static final int CW_ZWJ = 12;
public static final int CW_ZWNJ = 13;
public static final int CW_LTRMARK = 14;
public static final int CW_RTLMARK = 15;
public static final int CW_UC = 16;
public static final int CW_CPG = 17;
public static final int CW_FONTTBL = 18;
public static final int CW_FCHARSET = 19;
public static final int CW_PAR = 20;
public static final int CW_PAGE = 21;
public static final int CW_STYLESHEET = 22;
public static final int CW_COLORTBL = 23;
public static final int CW_SPECIAL = 24;
public static final int CW_FOOTNOTE = 25;
public static final int CW_TAB = 26;
public static final int CW_V = 27;
public static final int CW_XE = 28;
public static final int CW_CCHS = 29;
public static final int CW_PICT = 30;
public static final int CW_SHPTXT = 31;
public static final int CW_LINE = 32;
public static final int CW_INDEXSEP = 33;
public static final int CW_ULDB = 34;
public static final int CW_TITLE = 35;
public static final int CW_TROWD = 36;
public static final int CW_CELL = 37;
public static final int CW_BKMKSTART = 38;
public static final int CW_ROW = 39;
public static final int CW_UL = 40;
public static final int CW_PARD = 41;
public static final int CW_NONSHPPICT = 42;
public static final int CW_INFO = 43;
public static final int CW_CS = 44;
public static final int CW_DELETED = 45;
public static final int CW_PLAIN = 46;
public static final int CW_BKMKEND = 47;
public static final int CW_ANNOTATION = 48;
public static final int CW_MAC = 49;
public static final int CW_PC = 50;
public static final int CW_PCA = 51;
private final Logger logger = Logger.getLogger(getClass().getName());
private BufferedReader reader;
private boolean canceled;
private String srcLang;
private String trgLang;
private String passedEncoding;
private Hashtable<Integer, String> winCharsets;
private Hashtable<Integer, String> winCodepages;
private Hashtable<String, Integer> controlWords;
private Hashtable<Integer, RTFFont> fonts;
private char chCurrent;
private char chPrevTextChar;
private int value;
private Stack<RTFContext> ctxStack;
private int inFontTable;
private String defaultEncoding;
private boolean setCharset0ToDefault;
private StringBuilder word;
private boolean reParse;
private char chReParseChar;
private int skip;
private int code;
private int group;
private int noReset;
private byte byteData;
private char uChar;
int internalStyle;
int doNotTranslateStyle;
private CharsetDecoder currentCSDec;
private int currentDBCSCodepage;
private String currentCSName;
private ByteBuffer byteBuffer;
private LinkedList<Event> queue;
private boolean hasNext;
private String docName;
private int tuId;
private int otherId;
public RTFFilter () {
winCharsets = new Hashtable<Integer, String>();
winCharsets.put(0, "windows-1252");
winCharsets.put(1, Charset.defaultCharset().name());
winCharsets.put(2, "symbol");
winCharsets.put(3, "invalid-fcharset");
winCharsets.put(77, "MacRoman");
winCharsets.put(128, "Shift_JIS"); // Japanese, DBCS
winCharsets.put(129, "windows949"); // Korean
winCharsets.put(130, "johab"); // Korean, DBCS
winCharsets.put(134, "gb2312");
winCharsets.put(136, "Big5");
winCharsets.put(161, "windows-1253"); // Greek
winCharsets.put(162, "windows-1254"); // Turkish
winCharsets.put(163, "windows-1258"); // Vietnamese
winCharsets.put(177, "windows-1255"); // Hebrew
winCharsets.put(178, "windows-1256"); // Arabic
winCharsets.put(179, "windows-1256"); // Arabic Traditional
winCharsets.put(180, "arabic-user"); // Arabic User
winCharsets.put(181, "hebrew-user"); // hebrew User
winCharsets.put(186, "windows-1257"); // Baltic
winCharsets.put(204, "windows-1251"); // Russian
winCharsets.put(222, "windows-874"); // Thai
winCharsets.put(238, "windows-1250"); // Eastern European
winCharsets.put(254, "ibm437"); // PC-437
winCharsets.put(255, "oem"); // OEM
winCodepages = new Hashtable<Integer, String>();
winCodepages.put(437, "IBM437");
winCodepages.put(850, "IBM850");
winCodepages.put(852, "IBM852");
winCodepages.put(1250, "windows-1250");
winCodepages.put(1251, "windows-1251");
winCodepages.put(1252, "windows-1252");
winCodepages.put(1253, "windows-1253");
winCodepages.put(1254, "windows-1254");
winCodepages.put(1255, "windows-1255");
winCodepages.put(1256, "windows-1256");
winCodepages.put(1257, "windows-1257");
winCodepages.put(1258, "windows-1258");
/*
708 Arabic (ASMO 708)
709 Arabic (ASMO 449+, BCON V4)
710 Arabic (transparent Arabic)
711 Arabic (Nafitha Enhanced)
720 Arabic (transparent ASMO)
819 Windows 3.1 (United States and Western Europe)
860 Portuguese
862 Hebrew
863 French Canadian
864 Arabic
865 Norwegian
866 Soviet Union
874 Thai
932 Japanese
936 Simplified Chinese
949 Korean
950 Traditional Chinese
1361 Johab
*/
controlWords = new Hashtable<String, Integer>();
controlWords.put("par", CW_PAR);
controlWords.put("pard", CW_PARD);
controlWords.put("f", CW_F);
controlWords.put("u", CW_U);
controlWords.put("plain", CW_PLAIN);
controlWords.put("page", CW_PAGE);
controlWords.put("lquote", CW_LQUOTE);
controlWords.put("rquote", CW_RQUOTE);
controlWords.put("cell", CW_CELL);
controlWords.put("trowd", CW_TROWD);
controlWords.put("tab", CW_TAB);
controlWords.put("endash", CW_ENDASH);
controlWords.put("emdash", CW_EMDASH);
controlWords.put("ldblquote", CW_LDBLQUOTE);
controlWords.put("rdblquote", CW_RDBLQUOTE);
controlWords.put("v", CW_V);
controlWords.put("xe", CW_XE);
controlWords.put("cchs", CW_CCHS);
controlWords.put("bkmkstart", CW_BKMKSTART);
controlWords.put("row",CW_ROW);
controlWords.put("uc", CW_UC);
controlWords.put("*", CW_SPECIAL);
controlWords.put("pict", CW_PICT);
controlWords.put(":", CW_INDEXSEP);
controlWords.put("shptxt", CW_SHPTXT);
controlWords.put("fcharset", CW_FCHARSET);
controlWords.put("footnote", CW_FOOTNOTE);
controlWords.put("uldb", CW_ULDB);
controlWords.put("ul", CW_UL);
controlWords.put("bullet", CW_BULLET);
controlWords.put("ltrmark", CW_LTRMARK);
controlWords.put("rtlmark", CW_RTLMARK);
controlWords.put("line",CW_LINE);
controlWords.put("zwj", CW_ZWJ);
controlWords.put("zwnj", CW_ZWNJ);
controlWords.put("cpg", CW_CPG);
controlWords.put("ansi", CW_ANSI);
controlWords.put("fonttbl", CW_FONTTBL);
controlWords.put("stylesheet", CW_STYLESHEET);
controlWords.put("colortbl", CW_COLORTBL);
controlWords.put("info", CW_INFO);
controlWords.put("title", CW_TITLE);
controlWords.put("nonshppict", CW_NONSHPPICT);
controlWords.put("ansicpg", CW_ANSICPG);
controlWords.put("cs", CW_CS);
controlWords.put("deleted", CW_DELETED);
controlWords.put("bkmkend", CW_BKMKEND);
controlWords.put("annotation", CW_ANNOTATION);
controlWords.put("mac", CW_MAC);
controlWords.put("pc", CW_PC);
controlWords.put("pca", CW_PCA);
}
public void cancel () {
canceled = true;
}
public void close () {
try {
if ( reader != null ) {
reader.close();
reader = null;
}
hasNext = false;
}
catch ( IOException e ) {
throw new OkapiIOException(e);
}
}
public String getName () {
return "okf_rtf";
}
public String getMimeType () {
return "text/rtf"; //TODO: check
}
public List<FilterConfiguration> getConfigurations () {
List<FilterConfiguration> list = new ArrayList<FilterConfiguration>();
list.add(new FilterConfiguration(getName(),
"text/rtf",
getClass().getName(),
"RTF",
"Configuration for Rich Text Format (RTF) files."));
return list;
}
public IParameters getParameters () {
return null;
}
public boolean hasNext () {
return hasNext;
}
public Event next () {
// Check for cancellation first
if ( canceled ) {
queue.clear();
queue.add(new Event(EventType.CANCELED));
hasNext = false;
}
// Parse next if nothing in the queue
if ( queue.size() == 0 ) {
parseNext();
}
// Return the head of the queue
if ( queue.peek().getEventType() == EventType.END_DOCUMENT ) {
hasNext = false;
}
return queue.poll();
}
public void parseNext () {
TextUnit textUnit = new TextUnit(String.valueOf(++tuId));
if ( !getSegment(textUnit) ) {
// Send the end-document event
queue.add(new Event(EventType.END_DOCUMENT,
new Ending(String.valueOf(++otherId))));
}
else {
queue.add(new Event(EventType.TEXT_UNIT, textUnit));
}
}
public void open (RawDocument input) {
open(input, true);
}
public void open (RawDocument input,
boolean generateSkeleton)
{
try {
passedEncoding = input.getEncoding();
srcLang = input.getSourceLanguage();
trgLang = input.getTargetLanguage();
if ( input.getInputURI() != null ) {
docName = input.getInputURI().getPath();
}
reset(passedEncoding);
reader = new BufferedReader(
new InputStreamReader(input.getStream(), passedEncoding));
StartDocument startDoc = new StartDocument(String.valueOf(++otherId));
startDoc.setName(docName);
startDoc.setEncoding(passedEncoding, false);
startDoc.setLanguage(srcLang);
startDoc.setFilterParameters(getParameters());
startDoc.setFilterWriter(createFilterWriter());
startDoc.setType("text/rtf");
startDoc.setMimeType("text/rtf");
startDoc.setMultilingual(true);
startDoc.setLineBreak(Util.LINEBREAK_DOS);
queue.add(new Event(EventType.START_DOCUMENT, startDoc));
}
catch ( UnsupportedEncodingException e ) {
throw new OkapiUnsupportedEncodingException(e);
}
}
public void setParameters (IParameters params) {
}
public ISkeletonWriter createSkeletonWriter() {
return new GenericSkeletonWriter();
}
public IFilterWriter createFilterWriter () {
return new GenericFilterWriter(createSkeletonWriter());
}
private void reset (String defaultEncoding) {
close();
canceled = false;
chCurrent = (char)0;
reParse = false;
chReParseChar = (char)0;
group = 0;
skip = 0;
byteData = (byte)0;
code = 0;
word = new StringBuilder();
value = 0;
chPrevTextChar = (char)0;
uChar = (char)0;
byteBuffer = ByteBuffer.allocate(10);
fonts = new Hashtable<Integer, RTFFont>();
inFontTable = 0;
noReset = 0;
internalStyle = 6;
doNotTranslateStyle = 8;
RTFContext ctx = new RTFContext();
ctx.uniCount = 1;
ctx.inText = true;
ctx.font = 0;
this.defaultEncoding = defaultEncoding;
ctx.encoding = defaultEncoding;
ctxStack = new Stack<RTFContext>();
ctxStack.push(ctx);
loadEncoding(ctx.encoding);
hasNext = true;
tuId = 0;
otherId = 0;
queue = new LinkedList<Event>();
}
public boolean getSegment (TextUnit tu) {
int nState = 0;
String sTmp = "";
String sCode = "";
int nGrp = 0;
int nStyle = 0;
int nCode = 0;
TextFragment srcFrag = tu.setSourceContent(new TextFragment());
TextFragment trgFrag = new TextFragment();
TextFragment currentFrag = null;
while ( true ) {
switch ( getNextToken() ) {
case TOKEN_ENDINPUT:
return false;
case TOKEN_CHAR:
if ( !ctxStack.peek().inText ) {
if ( nStyle > 0 ) {
// Get style name
sTmp += chCurrent;
}
}
switch ( nState ) {
case 0: // Wait for { in {0>
if ( chCurrent == '{' ) nState = 1;
break;
case 1: // Wait for 0 in {0>
if ( chCurrent == '0' ) nState = 2;
else if ( chCurrent != '{' ) nState = 0;
break;
case 2: // Wait for > in {0>
if ( chCurrent == '>' ) {
nState = 3;
currentFrag = srcFrag;
}
else if ( chCurrent == '{' ) nState = 1; // Is {0{
else nState = 0; // Is {0x
break;
case 3: // After {0>, wait for <}n*{>
if ( chCurrent == '<' ) {
sTmp = "";
nState = 4;
}
else {
if ( nGrp > 0 ) sCode += chCurrent;
else srcFrag.append(chCurrent);
}
break;
case 4: // After < in <}n*{>
if ( chCurrent == '}' ) nState = 5;
else if ( chCurrent == '<' )
{
if ( nGrp > 0 ) sCode += chCurrent;
else srcFrag.append(chCurrent);
}
else {
if ( nGrp > 0 ) {
sCode += '<';
sCode += chCurrent;
}
else {
srcFrag.append('<');
srcFrag.append(chCurrent);
}
nState = 3;
}
break;
case 5: // After <} in <}n*{>
if ( chCurrent == '{' ) nState = 6;
else if ( !Character.isDigit(chCurrent) ) {
if ( nGrp > 0 ) {
sCode += "<}";
sCode += sTmp;
sCode += chCurrent;
}
else {
srcFrag.append("<}");
srcFrag.append(sTmp);
srcFrag.append(chCurrent);
}
nState = 3;
}
else { // Else: number, keep waiting (and preserve text)
sTmp += chCurrent;
}
break;
case 6: // After <}n*{ in <}n*{>
if ( chCurrent == '>' ) {
currentFrag = trgFrag; // Starting target text
nState = 7;
}
else {
throw new OkapiIllegalFilterOperationException("Expecting: '>' while parsing Trados markup.");
}
break;
case 7: // After <}n*{> wait for <0}
if ( chCurrent == '<' ) nState = 8;
else {
if ( nGrp > 0 ) sCode += chCurrent;
else trgFrag.append(chCurrent);
}
break;
case 8: // After < in <0}
if ( chCurrent == '0' ) nState = 9;
else if ( chCurrent == '<' ) {
// 2 sequential <, stay in the state
if ( nGrp > 0 ) sCode += chCurrent;
else trgFrag.append(chCurrent);
}
else {
if ( nGrp > 0 ) {
sCode += '<';
sCode += chCurrent;
}
else {
trgFrag.append('<');
trgFrag.append(chCurrent);
}
nState = 7;
}
break;
case 9: // After <0 in <0}
if ( chCurrent == '}' ) {
// Segment is done
if ( !trgFrag.isEmpty() ) {
tu.setTargetContent(trgLang, trgFrag);
}
return true;
}
else if ( chCurrent == '<' ) {
// <0< sequence
if ( nGrp > 0 ) sCode += "<0";
else trgFrag.append("<0");
nState = 8;
}
else {
if ( nGrp > 0 ) {
sCode += '<';
sCode += chCurrent;
}
else {
trgFrag.append('<');
trgFrag.append(chCurrent);
}
nState = 8;
}
break;
}
break; // End of case TOKEN_CHAR:
case TOKEN_STARTGROUP:
break;
case TOKEN_ENDGROUP:
if ( nStyle > 0 ) {
if ( nStyle < ctxStack.size()+1 ) {
// Is it the tw4winInternal style?
if ( "tw4winInternal;".compareTo(sTmp) == 0 ) {
internalStyle = nCode;
}
else if ( "DO_NOT_TRANSLATE;".compareTo(sTmp) == 0 ) {
doNotTranslateStyle = nCode;
}
}
else {
nStyle = 0;
}
break;
}
if ( nGrp > 0 ) {
if ( nGrp == ctxStack.size()+1 ) {
if ( currentFrag != null ) {
addInlineCode(currentFrag, sCode);
}
nGrp = 0;
}
break;
}
break;
case TOKEN_CTRLWORD:
switch ( code ) {
case CW_V:
ctxStack.peek().inText = (value == 0);
break;
case CW_CS:
if ( nStyle > 0 ) {
nCode = value;
sTmp = "";
break;
}
if ( value == internalStyle ) {
sCode = "";
nGrp = ctxStack.size();
break;
}
// Else: not in source or target
break;
case CW_STYLESHEET:
nStyle = ctxStack.size();
break;
}
break; // End of case TOKEN_CTRLWORD:
default:
// Should never get here
break;
} // End of switch ( getNextToken() )
} // End of while
}
/**
* Tries to guess if an in-line code is an opening/closing XML/HTML tag.
* @param data The text of the in-line code.
* @return The guessed TagType for the given in-line code.
*/
private void addInlineCode (TextFragment frag,
String data)
{
// By default we assume it's a place-holder
String type = null;
TagType tagType = TagType.PLACEHOLDER;
int last = data.length()-1;
int extra = 0;
// Long enough to be an XML/HTML tag?
if ( last > 1 ) {
// Starts with the proper character?
if ( data.charAt(0) == '<' ) {
// Ends with the proper character?
if ( data.charAt(last) == '>' ) {
// Has no more than one tag?
if ( data.indexOf('<', 1) == -1 ) {
// Is like "</...>", but not "</>", so that's a closing tag
if (( data.charAt(1) == '/' ) && ( last > 2 )) {
tagType = TagType.CLOSING;
extra = 1;
}
else if ( data.charAt(last-1) != '/' ) {
// Is like "<...>, that's an opening tag
tagType = TagType.OPENING;
}
// Else it's likely a empty tag, or it can also be something
// non XML/HTML, so it's a place-holder
}
}
}
}
// Set the type of opening and closing tags
if ( tagType != TagType.PLACEHOLDER ) {
int n = data.indexOf(' ');
if ( n > -1 ) type = data.substring(1+extra, n);
else type = data.substring(1+extra, last);
}
// Add the guessed in-line code
frag.append(tagType, type, data);
}
/**
* Gets the text content until a specified condition is reached.
* @param cwCode the control word to stop on. Use -1 for either CW_PAR or CW_LINE.
* @param errorCwCode the control word to stop on and return an error. Use 0 for none.
* @return 0: OK, 1: error, 2: stop was due to no more text
*/
public int getTextUntil (StringBuilder text,
int cwCode,
int errorCwCode)
{
text.setLength(0);
//boolean bParOrLine = false;
while ( true ) {
switch ( getNextToken() ) {
case TOKEN_ENDINPUT:
// Not found, EOF
if ( text.length() > 0 ) return 0;
// Else: no more text: end-of-input
return 2;
case TOKEN_CHAR:
if ( ctxStack.peek().inText ) {
text.append(chCurrent);
}
break;
case TOKEN_STARTGROUP:
case TOKEN_ENDGROUP:
break;
case TOKEN_CTRLWORD:
if ( cwCode == -1 ) {
if (( code == CW_PAR ) || ( code == CW_LINE )) {
//bParOrLine = true;
return 0;
}
}
else if ( code == cwCode ) {
if (( code == CW_PAR ) || ( code == CW_LINE )) {
//bParOrLine = true;
}
return 0;
}
if ( code == errorCwCode ) {
return 1;
}
break;
}
} // End of while
}
private int readChar () {
try {
int nRes = reader.read();
if ( nRes == -1 ) {
chCurrent = (char)0;
return TOKEN_ENDINPUT;
}
// Else get the character
chCurrent = (char)nRes;
return TOKEN_CHAR;
}
catch ( IOException e ) {
throw new OkapiIOException(e);
}
}
private int getNextToken () {
int nRes;
boolean waitingSecondByte = false;
while ( true ) {
// Get the next character
if ( reParse ) { // Re-used last parsed char if available
// Use the last parsed character
nRes = TOKEN_CHAR;
chCurrent = chReParseChar;
chReParseChar = (char)0;
reParse = false;
}
else { // Or read a new one
nRes = readChar();
}
switch ( nRes ) {
case TOKEN_CHAR:
switch ( chCurrent ) {
case '{':
group++;
if ( inFontTable > 0 ) inFontTable++;
if ( noReset > 0 ) noReset++;
ctxStack.push(new RTFContext(ctxStack.peek()));
return TOKEN_STARTGROUP;
case '}':
group--;
if ( inFontTable > 0 ) inFontTable--;
if ( noReset > 0 ) noReset--;
if ( ctxStack.size() > 1 ) {
ctxStack.pop();
loadEncoding(ctxStack.peek().encoding);
}
return TOKEN_ENDGROUP;
case '\r':
case '\n':
// Skip
continue;
case '\\':
nRes = parseAfterBackSlash();
// -1: it's a 'hh conversion to do, otherwise return it
if (( nRes != -1 ) && ( skip == 0 )) return nRes;
if ( nRes != -1 ) {
// Skip only: has to be uDDD
continue;
}
if ( waitingSecondByte ) {
// We were waiting for the second byte
waitingSecondByte = false;
// Convert the DBCS char into Unicode
//TODO: verify that byte-order works
byteBuffer.put(1, byteData);
CharBuffer charBuf;
try {
charBuf = currentCSDec.decode(byteBuffer);
chCurrent = charBuf.get(0);
}
catch (CharacterCodingException e) {
logger.warning(e.getLocalizedMessage());
chCurrent = '?';
}
}
else {
if ( skip == 0 ) { // Avoid conversion when skipping
if ( isLeadByte(byteData) ) {
waitingSecondByte = true;
// It's a lead byte. Store it and get the next byte
byteBuffer.clear();
byteBuffer.put(0, byteData);
break;
}
else { // SBCS
byteBuffer.clear();
byteBuffer.put(0, byteData);
CharBuffer charBuf;
try {
charBuf = currentCSDec.decode(byteBuffer);
chCurrent = charBuf.get(0);
}
catch (CharacterCodingException e) {
logger.warning(e.getLocalizedMessage());
chCurrent = '?';
}
}
}
}
// Fall thru to process the character
default:
if ( skip > 0 ) {
skip--;
if ( skip > 0 ) continue;
// Else, no more char to skip: fall thru and
// return char of uDDD
chCurrent = uChar;
}
if ( waitingSecondByte ) {
// We were waiting for the second byte
waitingSecondByte = false;
// Convert the DBCS char into Unicode
byteBuffer.put(1, byteData);
CharBuffer charBuf;
try {
charBuf = currentCSDec.decode(byteBuffer);
chCurrent = charBuf.get(0);
}
catch (CharacterCodingException e) {
logger.warning(e.getLocalizedMessage());
chCurrent = '?';
}
}
// Text: chCurrent has the Unicode value
chPrevTextChar = chCurrent;
return TOKEN_CHAR;
}
break;
case TOKEN_ENDINPUT:
if ( group > 0 ) {
// Missing '{'
logger.warning(String.format("Missing '{' = %d.", group));
}
else if ( group < 0 ) {
// Extra '}'
logger.warning(String.format("Extra '}' = %d.", group));
}
return nRes;
default:
return nRes;
}
}
}
private boolean isLeadByte (byte byteValue) {
switch ( currentDBCSCodepage ) {
// Make sure to cast to (byte) to get the signed value!
case 932: // Shift-JIS
if (( byteValue >= (byte)0x81 ) && ( byteValue <= (byte)0x9F )) return true;
if (( byteValue >= (byte)0xE0 ) && ( byteValue <= (byte)0xEE )) return true;
if (( byteValue >= (byte)0xFA ) && ( byteValue <= (byte)0xFC )) return true;
break;
case 936: // Chinese Simplified
if (( byteValue >= (byte)0xA1 ) && ( byteValue <= (byte)0xA9 )) return true;
if (( byteValue >= (byte)0xB0 ) && ( byteValue <= (byte)0xF7 )) return true;
break;
case 949: // Korean
if (( byteValue >= (byte)0x81 ) && ( byteValue <= (byte)0xC8 )) return true;
if (( byteValue >= (byte)0xCA ) && ( byteValue <= (byte)0xFD )) return true;
break;
case 950: // Chinese Traditional
if (( byteValue >= (byte)0xA1 ) && ( byteValue <= (byte)0xC6 )) return true;
if (( byteValue >= (byte)0xC9 ) && ( byteValue <= (byte)0xF9 )) return true;
break;
}
// All other encoding: No lead bytes
return false;
}
private int parseAfterBackSlash () {
boolean inHexa = false;
int count = 0;
String sBuf = "";
while ( true ) {
if ( readChar() == TOKEN_CHAR ) {
if ( inHexa ) {
sBuf += chCurrent;
if ( (++count) == 2 ) {
byteData = (byte)(Integer.parseInt(sBuf, 16));
return(-1); // Byte to process
}
continue;
}
else {
switch ( chCurrent ) {
case '\'':
inHexa = true;
break;
case '\r':
case '\n':
// equal to a \par
code = CW_PAR;
return TOKEN_CTRLWORD;
case '\\':
case '{':
case '}':
// Escaped characters
return TOKEN_CHAR;
case '~':
case '|':
case '-':
case '_':
case ':':
return parseControlSymbol();
case '*':
default:
return parseControlWord();
}
}
}
else {
// Unexpected end of input
throw new OkapiIllegalFilterOperationException("Unexcpected end of input.");
}
}
}
private int parseControlWord () {
int nRes;
int nState = 0;
String sBuf = "";
word.setLength(0);
word.append(chCurrent);
value = 1; // Default value
while ( true ) {
if ( (nRes = readChar()) == TOKEN_CHAR ) {
switch ( nState ) {
case 0: // Normal
switch ( chCurrent ) {
case ' ':
return getControlWord();
case '\r':
case '\n':
// According RTF spec 1.6 CR/LF should be ignored
//continue;
// According RTF spec 1.9 CR/LF should be ignored
// ... when "found in clear text segments"
return getControlWord();
default:
// keep adding to the word
if ( Character.isLetter(chCurrent) ) {
word.append(chCurrent);
continue;
}
// End by a value
if ( Character.isDigit(chCurrent) || ( chCurrent == '-' )) {
// Value
nState = 1;
sBuf = String.valueOf(chCurrent);
continue;
}
// End by a no-alpha char
reParse = true;
chReParseChar = chCurrent;
break;
} // End switch m_chCurrent
return getControlWord();
case 1: // Get a value
if ( Character.isDigit(chCurrent) ) {
sBuf += chCurrent;
}
else {
// End of value
if ( chCurrent != ' ' ) {
reParse = true;
chReParseChar = chCurrent;
}
value = Integer.parseInt(sBuf);
return getControlWord();
}
break;
}
}
else if ( nRes == TOKEN_ENDINPUT ) {
return getControlWord();
}
else {
// Unexpected end of input
throw new OkapiIllegalFilterOperationException("Unexcpected end of input.");
}
}
}
private int getControlWord () {
if ( controlWords.containsKey(word.toString()) ) {
code = controlWords.get(word.toString());
}
else {
code = -1;
}
return processControlWord();
}
private int processControlWord () {
RTFFont tmpFont;
switch ( code ) {
case CW_U:
// If the value is negative it's a RTF weird typing casting issue:
// make it positive by using the complement
if ( chCurrent < 0 ) chCurrent = (char)(65536+value);
else chCurrent = (char)value;
skip = ctxStack.peek().uniCount;
uChar = chCurrent; // Preserve char while skipping
return TOKEN_CHAR;
case CW_UC:
ctxStack.peek().uniCount = value;
break;
case CW_FONTTBL:
inFontTable = 1;
ctxStack.peek().inText = false;
break;
case CW_FCHARSET:
if ( inFontTable > 0 ) {
int nFont = ctxStack.peek().font;
if ( fonts.containsKey(nFont) ) {
tmpFont = fonts.get(nFont);
if ( setCharset0ToDefault && ( value == 0 )) {
tmpFont.encoding = defaultEncoding;
}
else {
// Else: Look at table
if ( winCharsets.containsKey(value) ) {
tmpFont.encoding = winCharsets.get(value);
}
else {
tmpFont.encoding = defaultEncoding;
}
}
}
// Else: should not happen (\fcharset is always after \f)
}
// Else: should not happen (\fcharset is always in font table)
break;
case CW_PARD: // Reset properties
// TODO?
break;
case CW_F:
if ( inFontTable > 0 ) {
// Define font
ctxStack.peek().font = value;
if ( !fonts.containsKey(value) ) {
tmpFont = new RTFFont();
fonts.put(value, tmpFont);
}
}
else {
// Switch font
ctxStack.peek().font = value;
// Search font definition
if ( fonts.containsKey(value) ) {
// Switch to the encoding of the font
tmpFont = fonts.get(value);
// Check if the encoding is set, if not, use the default encoding
if ( tmpFont.encoding == null ) {
tmpFont.encoding = defaultEncoding;
}
// Set the current encoding in the stack
ctxStack.peek().encoding = tmpFont.encoding;
// Load the new encoding if needed
loadEncoding(tmpFont.encoding);
}
else {
// Font undefined: Switch to the default encoding
logger.warning(String.format("The font '%d' is undefined. The encoding '%s' is used by default instead.",
value, defaultEncoding));
loadEncoding(defaultEncoding);
}
}
break;
case CW_TAB:
chCurrent = '\t';
return TOKEN_CHAR;
case CW_BULLET:
chCurrent = '\u2022';
return TOKEN_CHAR;
case CW_LQUOTE:
chCurrent = '\u2018';
return TOKEN_CHAR;
case CW_RQUOTE:
chCurrent = '\u2019';
return TOKEN_CHAR;
case CW_LDBLQUOTE:
chCurrent = '\u201c';
return TOKEN_CHAR;
case CW_RDBLQUOTE:
chCurrent = '\u201d';
return TOKEN_CHAR;
case CW_ENDASH:
chCurrent = '\u2013';
return TOKEN_CHAR;
case CW_EMDASH:
chCurrent = '\u2014';
return TOKEN_CHAR;
case CW_ZWJ:
chCurrent = '\u200d';
return TOKEN_CHAR;
case CW_ZWNJ:
chCurrent = '\u200c';
return TOKEN_CHAR;
case CW_LTRMARK:
chCurrent = '\u200e';
return TOKEN_CHAR;
case CW_RTLMARK:
chCurrent = '\u200f';
return TOKEN_CHAR;
case CW_CCHS:
if ( setCharset0ToDefault && ( value == 0 )) {
ctxStack.peek().encoding = defaultEncoding;
}
else {
// Else: Look up
if ( winCharsets.containsKey(value) ) {
ctxStack.peek().encoding = winCharsets.get(value);
}
else {
ctxStack.peek().encoding = defaultEncoding;
}
}
loadEncoding(ctxStack.peek().encoding);
break;
case CW_CPG:
case CW_ANSICPG:
String name = winCodepages.get(value);
if ( name == null ) {
logger.warning(String.format("The codepage '%d' is undefined. The encoding '%s' is used by default instead.",
value, defaultEncoding));
ctxStack.peek().encoding = defaultEncoding;
}
else {
ctxStack.peek().encoding = name;
}
loadEncoding(ctxStack.peek().encoding);
break;
case CW_ANSI:
if ( setCharset0ToDefault ) {
ctxStack.peek().encoding = defaultEncoding;
}
else {
ctxStack.peek().encoding = "windows-1252";
}
loadEncoding(ctxStack.peek().encoding);
break;
case CW_MAC:
ctxStack.peek().encoding = "MacRoman";
loadEncoding(ctxStack.peek().encoding);
break;
case CW_PC:
ctxStack.peek().encoding = "ibm437";
loadEncoding(ctxStack.peek().encoding);
break;
case CW_PCA:
ctxStack.peek().encoding = "ibm850";
loadEncoding(ctxStack.peek().encoding);
break;
case CW_FOOTNOTE:
if ( "#+!>@".indexOf(chPrevTextChar) != -1 ) {
ctxStack.peek().inText = false;
}
break;
case CW_V:
ctxStack.peek().inText = (value == 0);
break;
case CW_XE:
case CW_SHPTXT:
ctxStack.peek().inText = true;
break;
case CW_SPECIAL:
case CW_PICT:
case CW_STYLESHEET:
case CW_COLORTBL:
case CW_INFO:
ctxStack.peek().inText = false;
break;
case CW_ANNOTATION:
noReset = 1;
ctxStack.peek().inText = false;
break;
case CW_DELETED:
ctxStack.peek().inText = (value == 0);
break;
case CW_PLAIN:
// Reset to default
if ( noReset == 0 ) {
ctxStack.peek().inText = true;
}
break;
}
return TOKEN_CTRLWORD;
}
private void loadEncoding (String encodingName) {
if ( currentCSDec != null ) {
if ( currentCSName.compareTo(encodingName) == 0 )
return; // Same encoding: No change needed
}
// check for special cases
if (( "symbol".compareTo(encodingName) == 0 )
|| ( "oem".compareTo(encodingName) == 0 )
|| ( "arabic-user".compareTo(encodingName) == 0 )
|| ( "hebrew-user".compareTo(encodingName) == 0 ))
{
logger.warning(String.format("The encoding '%s' is unsupported. The encoding '%s' is used by default instead.",
encodingName, defaultEncoding));
encodingName = defaultEncoding;
}
// Load the new encoding
currentCSDec = Charset.forName(encodingName).newDecoder();
currentCSName = encodingName;
if ( currentCSName.compareTo("Shift_JIS") == 0 ) {
currentDBCSCodepage = 932;
}
else if ( currentCSName.compareTo("windows949") == 0 ) {
currentDBCSCodepage = 949;
}
//TODO: Other DBCS encoding
else {
currentDBCSCodepage = 0; // Not DBCS
}
}
private int parseControlSymbol () {
switch ( chCurrent ) {
- case '~':
- //??? Prev char problem?
+ case '~': // Non-breaking space
chCurrent = '\u00a0';
return TOKEN_CHAR;
- case '|':
- case '-':
- case '_':
+ case '_': // Non-Breaking hyphen
+ chCurrent = '\u2011';
+ return TOKEN_CHAR;
+ case '|': // Formula character
+ case '-': // Non-required hyphen (Soft-hyphen?? U+00AD?)
return TOKEN_CTRLWORD;
default: // Should not get here
throw new OkapiIllegalFilterOperationException(String.format("Unknown control symbol '%c'", chCurrent));
}
}
}
| false | true | public boolean getSegment (TextUnit tu) {
int nState = 0;
String sTmp = "";
String sCode = "";
int nGrp = 0;
int nStyle = 0;
int nCode = 0;
TextFragment srcFrag = tu.setSourceContent(new TextFragment());
TextFragment trgFrag = new TextFragment();
TextFragment currentFrag = null;
while ( true ) {
switch ( getNextToken() ) {
case TOKEN_ENDINPUT:
return false;
case TOKEN_CHAR:
if ( !ctxStack.peek().inText ) {
if ( nStyle > 0 ) {
// Get style name
sTmp += chCurrent;
}
}
switch ( nState ) {
case 0: // Wait for { in {0>
if ( chCurrent == '{' ) nState = 1;
break;
case 1: // Wait for 0 in {0>
if ( chCurrent == '0' ) nState = 2;
else if ( chCurrent != '{' ) nState = 0;
break;
case 2: // Wait for > in {0>
if ( chCurrent == '>' ) {
nState = 3;
currentFrag = srcFrag;
}
else if ( chCurrent == '{' ) nState = 1; // Is {0{
else nState = 0; // Is {0x
break;
case 3: // After {0>, wait for <}n*{>
if ( chCurrent == '<' ) {
sTmp = "";
nState = 4;
}
else {
if ( nGrp > 0 ) sCode += chCurrent;
else srcFrag.append(chCurrent);
}
break;
case 4: // After < in <}n*{>
if ( chCurrent == '}' ) nState = 5;
else if ( chCurrent == '<' )
{
if ( nGrp > 0 ) sCode += chCurrent;
else srcFrag.append(chCurrent);
}
else {
if ( nGrp > 0 ) {
sCode += '<';
sCode += chCurrent;
}
else {
srcFrag.append('<');
srcFrag.append(chCurrent);
}
nState = 3;
}
break;
case 5: // After <} in <}n*{>
if ( chCurrent == '{' ) nState = 6;
else if ( !Character.isDigit(chCurrent) ) {
if ( nGrp > 0 ) {
sCode += "<}";
sCode += sTmp;
sCode += chCurrent;
}
else {
srcFrag.append("<}");
srcFrag.append(sTmp);
srcFrag.append(chCurrent);
}
nState = 3;
}
else { // Else: number, keep waiting (and preserve text)
sTmp += chCurrent;
}
break;
case 6: // After <}n*{ in <}n*{>
if ( chCurrent == '>' ) {
currentFrag = trgFrag; // Starting target text
nState = 7;
}
else {
throw new OkapiIllegalFilterOperationException("Expecting: '>' while parsing Trados markup.");
}
break;
case 7: // After <}n*{> wait for <0}
if ( chCurrent == '<' ) nState = 8;
else {
if ( nGrp > 0 ) sCode += chCurrent;
else trgFrag.append(chCurrent);
}
break;
case 8: // After < in <0}
if ( chCurrent == '0' ) nState = 9;
else if ( chCurrent == '<' ) {
// 2 sequential <, stay in the state
if ( nGrp > 0 ) sCode += chCurrent;
else trgFrag.append(chCurrent);
}
else {
if ( nGrp > 0 ) {
sCode += '<';
sCode += chCurrent;
}
else {
trgFrag.append('<');
trgFrag.append(chCurrent);
}
nState = 7;
}
break;
case 9: // After <0 in <0}
if ( chCurrent == '}' ) {
// Segment is done
if ( !trgFrag.isEmpty() ) {
tu.setTargetContent(trgLang, trgFrag);
}
return true;
}
else if ( chCurrent == '<' ) {
// <0< sequence
if ( nGrp > 0 ) sCode += "<0";
else trgFrag.append("<0");
nState = 8;
}
else {
if ( nGrp > 0 ) {
sCode += '<';
sCode += chCurrent;
}
else {
trgFrag.append('<');
trgFrag.append(chCurrent);
}
nState = 8;
}
break;
}
break; // End of case TOKEN_CHAR:
case TOKEN_STARTGROUP:
break;
case TOKEN_ENDGROUP:
if ( nStyle > 0 ) {
if ( nStyle < ctxStack.size()+1 ) {
// Is it the tw4winInternal style?
if ( "tw4winInternal;".compareTo(sTmp) == 0 ) {
internalStyle = nCode;
}
else if ( "DO_NOT_TRANSLATE;".compareTo(sTmp) == 0 ) {
doNotTranslateStyle = nCode;
}
}
else {
nStyle = 0;
}
break;
}
if ( nGrp > 0 ) {
if ( nGrp == ctxStack.size()+1 ) {
if ( currentFrag != null ) {
addInlineCode(currentFrag, sCode);
}
nGrp = 0;
}
break;
}
break;
case TOKEN_CTRLWORD:
switch ( code ) {
case CW_V:
ctxStack.peek().inText = (value == 0);
break;
case CW_CS:
if ( nStyle > 0 ) {
nCode = value;
sTmp = "";
break;
}
if ( value == internalStyle ) {
sCode = "";
nGrp = ctxStack.size();
break;
}
// Else: not in source or target
break;
case CW_STYLESHEET:
nStyle = ctxStack.size();
break;
}
break; // End of case TOKEN_CTRLWORD:
default:
// Should never get here
break;
} // End of switch ( getNextToken() )
} // End of while
}
/**
* Tries to guess if an in-line code is an opening/closing XML/HTML tag.
* @param data The text of the in-line code.
* @return The guessed TagType for the given in-line code.
*/
private void addInlineCode (TextFragment frag,
String data)
{
// By default we assume it's a place-holder
String type = null;
TagType tagType = TagType.PLACEHOLDER;
int last = data.length()-1;
int extra = 0;
// Long enough to be an XML/HTML tag?
if ( last > 1 ) {
// Starts with the proper character?
if ( data.charAt(0) == '<' ) {
// Ends with the proper character?
if ( data.charAt(last) == '>' ) {
// Has no more than one tag?
if ( data.indexOf('<', 1) == -1 ) {
// Is like "</...>", but not "</>", so that's a closing tag
if (( data.charAt(1) == '/' ) && ( last > 2 )) {
tagType = TagType.CLOSING;
extra = 1;
}
else if ( data.charAt(last-1) != '/' ) {
// Is like "<...>, that's an opening tag
tagType = TagType.OPENING;
}
// Else it's likely a empty tag, or it can also be something
// non XML/HTML, so it's a place-holder
}
}
}
}
// Set the type of opening and closing tags
if ( tagType != TagType.PLACEHOLDER ) {
int n = data.indexOf(' ');
if ( n > -1 ) type = data.substring(1+extra, n);
else type = data.substring(1+extra, last);
}
// Add the guessed in-line code
frag.append(tagType, type, data);
}
/**
* Gets the text content until a specified condition is reached.
* @param cwCode the control word to stop on. Use -1 for either CW_PAR or CW_LINE.
* @param errorCwCode the control word to stop on and return an error. Use 0 for none.
* @return 0: OK, 1: error, 2: stop was due to no more text
*/
public int getTextUntil (StringBuilder text,
int cwCode,
int errorCwCode)
{
text.setLength(0);
//boolean bParOrLine = false;
while ( true ) {
switch ( getNextToken() ) {
case TOKEN_ENDINPUT:
// Not found, EOF
if ( text.length() > 0 ) return 0;
// Else: no more text: end-of-input
return 2;
case TOKEN_CHAR:
if ( ctxStack.peek().inText ) {
text.append(chCurrent);
}
break;
case TOKEN_STARTGROUP:
case TOKEN_ENDGROUP:
break;
case TOKEN_CTRLWORD:
if ( cwCode == -1 ) {
if (( code == CW_PAR ) || ( code == CW_LINE )) {
//bParOrLine = true;
return 0;
}
}
else if ( code == cwCode ) {
if (( code == CW_PAR ) || ( code == CW_LINE )) {
//bParOrLine = true;
}
return 0;
}
if ( code == errorCwCode ) {
return 1;
}
break;
}
} // End of while
}
private int readChar () {
try {
int nRes = reader.read();
if ( nRes == -1 ) {
chCurrent = (char)0;
return TOKEN_ENDINPUT;
}
// Else get the character
chCurrent = (char)nRes;
return TOKEN_CHAR;
}
catch ( IOException e ) {
throw new OkapiIOException(e);
}
}
private int getNextToken () {
int nRes;
boolean waitingSecondByte = false;
while ( true ) {
// Get the next character
if ( reParse ) { // Re-used last parsed char if available
// Use the last parsed character
nRes = TOKEN_CHAR;
chCurrent = chReParseChar;
chReParseChar = (char)0;
reParse = false;
}
else { // Or read a new one
nRes = readChar();
}
switch ( nRes ) {
case TOKEN_CHAR:
switch ( chCurrent ) {
case '{':
group++;
if ( inFontTable > 0 ) inFontTable++;
if ( noReset > 0 ) noReset++;
ctxStack.push(new RTFContext(ctxStack.peek()));
return TOKEN_STARTGROUP;
case '}':
group--;
if ( inFontTable > 0 ) inFontTable--;
if ( noReset > 0 ) noReset--;
if ( ctxStack.size() > 1 ) {
ctxStack.pop();
loadEncoding(ctxStack.peek().encoding);
}
return TOKEN_ENDGROUP;
case '\r':
case '\n':
// Skip
continue;
case '\\':
nRes = parseAfterBackSlash();
// -1: it's a 'hh conversion to do, otherwise return it
if (( nRes != -1 ) && ( skip == 0 )) return nRes;
if ( nRes != -1 ) {
// Skip only: has to be uDDD
continue;
}
if ( waitingSecondByte ) {
// We were waiting for the second byte
waitingSecondByte = false;
// Convert the DBCS char into Unicode
//TODO: verify that byte-order works
byteBuffer.put(1, byteData);
CharBuffer charBuf;
try {
charBuf = currentCSDec.decode(byteBuffer);
chCurrent = charBuf.get(0);
}
catch (CharacterCodingException e) {
logger.warning(e.getLocalizedMessage());
chCurrent = '?';
}
}
else {
if ( skip == 0 ) { // Avoid conversion when skipping
if ( isLeadByte(byteData) ) {
waitingSecondByte = true;
// It's a lead byte. Store it and get the next byte
byteBuffer.clear();
byteBuffer.put(0, byteData);
break;
}
else { // SBCS
byteBuffer.clear();
byteBuffer.put(0, byteData);
CharBuffer charBuf;
try {
charBuf = currentCSDec.decode(byteBuffer);
chCurrent = charBuf.get(0);
}
catch (CharacterCodingException e) {
logger.warning(e.getLocalizedMessage());
chCurrent = '?';
}
}
}
}
// Fall thru to process the character
default:
if ( skip > 0 ) {
skip--;
if ( skip > 0 ) continue;
// Else, no more char to skip: fall thru and
// return char of uDDD
chCurrent = uChar;
}
if ( waitingSecondByte ) {
// We were waiting for the second byte
waitingSecondByte = false;
// Convert the DBCS char into Unicode
byteBuffer.put(1, byteData);
CharBuffer charBuf;
try {
charBuf = currentCSDec.decode(byteBuffer);
chCurrent = charBuf.get(0);
}
catch (CharacterCodingException e) {
logger.warning(e.getLocalizedMessage());
chCurrent = '?';
}
}
// Text: chCurrent has the Unicode value
chPrevTextChar = chCurrent;
return TOKEN_CHAR;
}
break;
case TOKEN_ENDINPUT:
if ( group > 0 ) {
// Missing '{'
logger.warning(String.format("Missing '{' = %d.", group));
}
else if ( group < 0 ) {
// Extra '}'
logger.warning(String.format("Extra '}' = %d.", group));
}
return nRes;
default:
return nRes;
}
}
}
private boolean isLeadByte (byte byteValue) {
switch ( currentDBCSCodepage ) {
// Make sure to cast to (byte) to get the signed value!
case 932: // Shift-JIS
if (( byteValue >= (byte)0x81 ) && ( byteValue <= (byte)0x9F )) return true;
if (( byteValue >= (byte)0xE0 ) && ( byteValue <= (byte)0xEE )) return true;
if (( byteValue >= (byte)0xFA ) && ( byteValue <= (byte)0xFC )) return true;
break;
case 936: // Chinese Simplified
if (( byteValue >= (byte)0xA1 ) && ( byteValue <= (byte)0xA9 )) return true;
if (( byteValue >= (byte)0xB0 ) && ( byteValue <= (byte)0xF7 )) return true;
break;
case 949: // Korean
if (( byteValue >= (byte)0x81 ) && ( byteValue <= (byte)0xC8 )) return true;
if (( byteValue >= (byte)0xCA ) && ( byteValue <= (byte)0xFD )) return true;
break;
case 950: // Chinese Traditional
if (( byteValue >= (byte)0xA1 ) && ( byteValue <= (byte)0xC6 )) return true;
if (( byteValue >= (byte)0xC9 ) && ( byteValue <= (byte)0xF9 )) return true;
break;
}
// All other encoding: No lead bytes
return false;
}
private int parseAfterBackSlash () {
boolean inHexa = false;
int count = 0;
String sBuf = "";
while ( true ) {
if ( readChar() == TOKEN_CHAR ) {
if ( inHexa ) {
sBuf += chCurrent;
if ( (++count) == 2 ) {
byteData = (byte)(Integer.parseInt(sBuf, 16));
return(-1); // Byte to process
}
continue;
}
else {
switch ( chCurrent ) {
case '\'':
inHexa = true;
break;
case '\r':
case '\n':
// equal to a \par
code = CW_PAR;
return TOKEN_CTRLWORD;
case '\\':
case '{':
case '}':
// Escaped characters
return TOKEN_CHAR;
case '~':
case '|':
case '-':
case '_':
case ':':
return parseControlSymbol();
case '*':
default:
return parseControlWord();
}
}
}
else {
// Unexpected end of input
throw new OkapiIllegalFilterOperationException("Unexcpected end of input.");
}
}
}
private int parseControlWord () {
int nRes;
int nState = 0;
String sBuf = "";
word.setLength(0);
word.append(chCurrent);
value = 1; // Default value
while ( true ) {
if ( (nRes = readChar()) == TOKEN_CHAR ) {
switch ( nState ) {
case 0: // Normal
switch ( chCurrent ) {
case ' ':
return getControlWord();
case '\r':
case '\n':
// According RTF spec 1.6 CR/LF should be ignored
//continue;
// According RTF spec 1.9 CR/LF should be ignored
// ... when "found in clear text segments"
return getControlWord();
default:
// keep adding to the word
if ( Character.isLetter(chCurrent) ) {
word.append(chCurrent);
continue;
}
// End by a value
if ( Character.isDigit(chCurrent) || ( chCurrent == '-' )) {
// Value
nState = 1;
sBuf = String.valueOf(chCurrent);
continue;
}
// End by a no-alpha char
reParse = true;
chReParseChar = chCurrent;
break;
} // End switch m_chCurrent
return getControlWord();
case 1: // Get a value
if ( Character.isDigit(chCurrent) ) {
sBuf += chCurrent;
}
else {
// End of value
if ( chCurrent != ' ' ) {
reParse = true;
chReParseChar = chCurrent;
}
value = Integer.parseInt(sBuf);
return getControlWord();
}
break;
}
}
else if ( nRes == TOKEN_ENDINPUT ) {
return getControlWord();
}
else {
// Unexpected end of input
throw new OkapiIllegalFilterOperationException("Unexcpected end of input.");
}
}
}
private int getControlWord () {
if ( controlWords.containsKey(word.toString()) ) {
code = controlWords.get(word.toString());
}
else {
code = -1;
}
return processControlWord();
}
private int processControlWord () {
RTFFont tmpFont;
switch ( code ) {
case CW_U:
// If the value is negative it's a RTF weird typing casting issue:
// make it positive by using the complement
if ( chCurrent < 0 ) chCurrent = (char)(65536+value);
else chCurrent = (char)value;
skip = ctxStack.peek().uniCount;
uChar = chCurrent; // Preserve char while skipping
return TOKEN_CHAR;
case CW_UC:
ctxStack.peek().uniCount = value;
break;
case CW_FONTTBL:
inFontTable = 1;
ctxStack.peek().inText = false;
break;
case CW_FCHARSET:
if ( inFontTable > 0 ) {
int nFont = ctxStack.peek().font;
if ( fonts.containsKey(nFont) ) {
tmpFont = fonts.get(nFont);
if ( setCharset0ToDefault && ( value == 0 )) {
tmpFont.encoding = defaultEncoding;
}
else {
// Else: Look at table
if ( winCharsets.containsKey(value) ) {
tmpFont.encoding = winCharsets.get(value);
}
else {
tmpFont.encoding = defaultEncoding;
}
}
}
// Else: should not happen (\fcharset is always after \f)
}
// Else: should not happen (\fcharset is always in font table)
break;
case CW_PARD: // Reset properties
// TODO?
break;
case CW_F:
if ( inFontTable > 0 ) {
// Define font
ctxStack.peek().font = value;
if ( !fonts.containsKey(value) ) {
tmpFont = new RTFFont();
fonts.put(value, tmpFont);
}
}
else {
// Switch font
ctxStack.peek().font = value;
// Search font definition
if ( fonts.containsKey(value) ) {
// Switch to the encoding of the font
tmpFont = fonts.get(value);
// Check if the encoding is set, if not, use the default encoding
if ( tmpFont.encoding == null ) {
tmpFont.encoding = defaultEncoding;
}
// Set the current encoding in the stack
ctxStack.peek().encoding = tmpFont.encoding;
// Load the new encoding if needed
loadEncoding(tmpFont.encoding);
}
else {
// Font undefined: Switch to the default encoding
logger.warning(String.format("The font '%d' is undefined. The encoding '%s' is used by default instead.",
value, defaultEncoding));
loadEncoding(defaultEncoding);
}
}
break;
case CW_TAB:
chCurrent = '\t';
return TOKEN_CHAR;
case CW_BULLET:
chCurrent = '\u2022';
return TOKEN_CHAR;
case CW_LQUOTE:
chCurrent = '\u2018';
return TOKEN_CHAR;
case CW_RQUOTE:
chCurrent = '\u2019';
return TOKEN_CHAR;
case CW_LDBLQUOTE:
chCurrent = '\u201c';
return TOKEN_CHAR;
case CW_RDBLQUOTE:
chCurrent = '\u201d';
return TOKEN_CHAR;
case CW_ENDASH:
chCurrent = '\u2013';
return TOKEN_CHAR;
case CW_EMDASH:
chCurrent = '\u2014';
return TOKEN_CHAR;
case CW_ZWJ:
chCurrent = '\u200d';
return TOKEN_CHAR;
case CW_ZWNJ:
chCurrent = '\u200c';
return TOKEN_CHAR;
case CW_LTRMARK:
chCurrent = '\u200e';
return TOKEN_CHAR;
case CW_RTLMARK:
chCurrent = '\u200f';
return TOKEN_CHAR;
case CW_CCHS:
if ( setCharset0ToDefault && ( value == 0 )) {
ctxStack.peek().encoding = defaultEncoding;
}
else {
// Else: Look up
if ( winCharsets.containsKey(value) ) {
ctxStack.peek().encoding = winCharsets.get(value);
}
else {
ctxStack.peek().encoding = defaultEncoding;
}
}
loadEncoding(ctxStack.peek().encoding);
break;
case CW_CPG:
case CW_ANSICPG:
String name = winCodepages.get(value);
if ( name == null ) {
logger.warning(String.format("The codepage '%d' is undefined. The encoding '%s' is used by default instead.",
value, defaultEncoding));
ctxStack.peek().encoding = defaultEncoding;
}
else {
ctxStack.peek().encoding = name;
}
loadEncoding(ctxStack.peek().encoding);
break;
case CW_ANSI:
if ( setCharset0ToDefault ) {
ctxStack.peek().encoding = defaultEncoding;
}
else {
ctxStack.peek().encoding = "windows-1252";
}
loadEncoding(ctxStack.peek().encoding);
break;
case CW_MAC:
ctxStack.peek().encoding = "MacRoman";
loadEncoding(ctxStack.peek().encoding);
break;
case CW_PC:
ctxStack.peek().encoding = "ibm437";
loadEncoding(ctxStack.peek().encoding);
break;
case CW_PCA:
ctxStack.peek().encoding = "ibm850";
loadEncoding(ctxStack.peek().encoding);
break;
case CW_FOOTNOTE:
if ( "#+!>@".indexOf(chPrevTextChar) != -1 ) {
ctxStack.peek().inText = false;
}
break;
case CW_V:
ctxStack.peek().inText = (value == 0);
break;
case CW_XE:
case CW_SHPTXT:
ctxStack.peek().inText = true;
break;
case CW_SPECIAL:
case CW_PICT:
case CW_STYLESHEET:
case CW_COLORTBL:
case CW_INFO:
ctxStack.peek().inText = false;
break;
case CW_ANNOTATION:
noReset = 1;
ctxStack.peek().inText = false;
break;
case CW_DELETED:
ctxStack.peek().inText = (value == 0);
break;
case CW_PLAIN:
// Reset to default
if ( noReset == 0 ) {
ctxStack.peek().inText = true;
}
break;
}
return TOKEN_CTRLWORD;
}
private void loadEncoding (String encodingName) {
if ( currentCSDec != null ) {
if ( currentCSName.compareTo(encodingName) == 0 )
return; // Same encoding: No change needed
}
// check for special cases
if (( "symbol".compareTo(encodingName) == 0 )
|| ( "oem".compareTo(encodingName) == 0 )
|| ( "arabic-user".compareTo(encodingName) == 0 )
|| ( "hebrew-user".compareTo(encodingName) == 0 ))
{
logger.warning(String.format("The encoding '%s' is unsupported. The encoding '%s' is used by default instead.",
encodingName, defaultEncoding));
encodingName = defaultEncoding;
}
// Load the new encoding
currentCSDec = Charset.forName(encodingName).newDecoder();
currentCSName = encodingName;
if ( currentCSName.compareTo("Shift_JIS") == 0 ) {
currentDBCSCodepage = 932;
}
else if ( currentCSName.compareTo("windows949") == 0 ) {
currentDBCSCodepage = 949;
}
//TODO: Other DBCS encoding
else {
currentDBCSCodepage = 0; // Not DBCS
}
}
private int parseControlSymbol () {
switch ( chCurrent ) {
case '~':
//??? Prev char problem?
chCurrent = '\u00a0';
return TOKEN_CHAR;
case '|':
case '-':
case '_':
return TOKEN_CTRLWORD;
default: // Should not get here
throw new OkapiIllegalFilterOperationException(String.format("Unknown control symbol '%c'", chCurrent));
}
}
}
| public boolean getSegment (TextUnit tu) {
int nState = 0;
String sTmp = "";
String sCode = "";
int nGrp = 0;
int nStyle = 0;
int nCode = 0;
TextFragment srcFrag = tu.setSourceContent(new TextFragment());
TextFragment trgFrag = new TextFragment();
TextFragment currentFrag = null;
while ( true ) {
switch ( getNextToken() ) {
case TOKEN_ENDINPUT:
return false;
case TOKEN_CHAR:
if ( !ctxStack.peek().inText ) {
if ( nStyle > 0 ) {
// Get style name
sTmp += chCurrent;
}
}
switch ( nState ) {
case 0: // Wait for { in {0>
if ( chCurrent == '{' ) nState = 1;
break;
case 1: // Wait for 0 in {0>
if ( chCurrent == '0' ) nState = 2;
else if ( chCurrent != '{' ) nState = 0;
break;
case 2: // Wait for > in {0>
if ( chCurrent == '>' ) {
nState = 3;
currentFrag = srcFrag;
}
else if ( chCurrent == '{' ) nState = 1; // Is {0{
else nState = 0; // Is {0x
break;
case 3: // After {0>, wait for <}n*{>
if ( chCurrent == '<' ) {
sTmp = "";
nState = 4;
}
else {
if ( nGrp > 0 ) sCode += chCurrent;
else srcFrag.append(chCurrent);
}
break;
case 4: // After < in <}n*{>
if ( chCurrent == '}' ) nState = 5;
else if ( chCurrent == '<' )
{
if ( nGrp > 0 ) sCode += chCurrent;
else srcFrag.append(chCurrent);
}
else {
if ( nGrp > 0 ) {
sCode += '<';
sCode += chCurrent;
}
else {
srcFrag.append('<');
srcFrag.append(chCurrent);
}
nState = 3;
}
break;
case 5: // After <} in <}n*{>
if ( chCurrent == '{' ) nState = 6;
else if ( !Character.isDigit(chCurrent) ) {
if ( nGrp > 0 ) {
sCode += "<}";
sCode += sTmp;
sCode += chCurrent;
}
else {
srcFrag.append("<}");
srcFrag.append(sTmp);
srcFrag.append(chCurrent);
}
nState = 3;
}
else { // Else: number, keep waiting (and preserve text)
sTmp += chCurrent;
}
break;
case 6: // After <}n*{ in <}n*{>
if ( chCurrent == '>' ) {
currentFrag = trgFrag; // Starting target text
nState = 7;
}
else {
throw new OkapiIllegalFilterOperationException("Expecting: '>' while parsing Trados markup.");
}
break;
case 7: // After <}n*{> wait for <0}
if ( chCurrent == '<' ) nState = 8;
else {
if ( nGrp > 0 ) sCode += chCurrent;
else trgFrag.append(chCurrent);
}
break;
case 8: // After < in <0}
if ( chCurrent == '0' ) nState = 9;
else if ( chCurrent == '<' ) {
// 2 sequential <, stay in the state
if ( nGrp > 0 ) sCode += chCurrent;
else trgFrag.append(chCurrent);
}
else {
if ( nGrp > 0 ) {
sCode += '<';
sCode += chCurrent;
}
else {
trgFrag.append('<');
trgFrag.append(chCurrent);
}
nState = 7;
}
break;
case 9: // After <0 in <0}
if ( chCurrent == '}' ) {
// Segment is done
if ( !trgFrag.isEmpty() ) {
tu.setTargetContent(trgLang, trgFrag);
}
return true;
}
else if ( chCurrent == '<' ) {
// <0< sequence
if ( nGrp > 0 ) sCode += "<0";
else trgFrag.append("<0");
nState = 8;
}
else {
if ( nGrp > 0 ) {
sCode += '<';
sCode += chCurrent;
}
else {
trgFrag.append('<');
trgFrag.append(chCurrent);
}
nState = 8;
}
break;
}
break; // End of case TOKEN_CHAR:
case TOKEN_STARTGROUP:
break;
case TOKEN_ENDGROUP:
if ( nStyle > 0 ) {
if ( nStyle < ctxStack.size()+1 ) {
// Is it the tw4winInternal style?
if ( "tw4winInternal;".compareTo(sTmp) == 0 ) {
internalStyle = nCode;
}
else if ( "DO_NOT_TRANSLATE;".compareTo(sTmp) == 0 ) {
doNotTranslateStyle = nCode;
}
}
else {
nStyle = 0;
}
break;
}
if ( nGrp > 0 ) {
if ( nGrp == ctxStack.size()+1 ) {
if ( currentFrag != null ) {
addInlineCode(currentFrag, sCode);
}
nGrp = 0;
}
break;
}
break;
case TOKEN_CTRLWORD:
switch ( code ) {
case CW_V:
ctxStack.peek().inText = (value == 0);
break;
case CW_CS:
if ( nStyle > 0 ) {
nCode = value;
sTmp = "";
break;
}
if ( value == internalStyle ) {
sCode = "";
nGrp = ctxStack.size();
break;
}
// Else: not in source or target
break;
case CW_STYLESHEET:
nStyle = ctxStack.size();
break;
}
break; // End of case TOKEN_CTRLWORD:
default:
// Should never get here
break;
} // End of switch ( getNextToken() )
} // End of while
}
/**
* Tries to guess if an in-line code is an opening/closing XML/HTML tag.
* @param data The text of the in-line code.
* @return The guessed TagType for the given in-line code.
*/
private void addInlineCode (TextFragment frag,
String data)
{
// By default we assume it's a place-holder
String type = null;
TagType tagType = TagType.PLACEHOLDER;
int last = data.length()-1;
int extra = 0;
// Long enough to be an XML/HTML tag?
if ( last > 1 ) {
// Starts with the proper character?
if ( data.charAt(0) == '<' ) {
// Ends with the proper character?
if ( data.charAt(last) == '>' ) {
// Has no more than one tag?
if ( data.indexOf('<', 1) == -1 ) {
// Is like "</...>", but not "</>", so that's a closing tag
if (( data.charAt(1) == '/' ) && ( last > 2 )) {
tagType = TagType.CLOSING;
extra = 1;
}
else if ( data.charAt(last-1) != '/' ) {
// Is like "<...>, that's an opening tag
tagType = TagType.OPENING;
}
// Else it's likely a empty tag, or it can also be something
// non XML/HTML, so it's a place-holder
}
}
}
}
// Set the type of opening and closing tags
if ( tagType != TagType.PLACEHOLDER ) {
int n = data.indexOf(' ');
if ( n > -1 ) type = data.substring(1+extra, n);
else type = data.substring(1+extra, last);
}
// Add the guessed in-line code
frag.append(tagType, type, data);
}
/**
* Gets the text content until a specified condition is reached.
* @param cwCode the control word to stop on. Use -1 for either CW_PAR or CW_LINE.
* @param errorCwCode the control word to stop on and return an error. Use 0 for none.
* @return 0: OK, 1: error, 2: stop was due to no more text
*/
public int getTextUntil (StringBuilder text,
int cwCode,
int errorCwCode)
{
text.setLength(0);
//boolean bParOrLine = false;
while ( true ) {
switch ( getNextToken() ) {
case TOKEN_ENDINPUT:
// Not found, EOF
if ( text.length() > 0 ) return 0;
// Else: no more text: end-of-input
return 2;
case TOKEN_CHAR:
if ( ctxStack.peek().inText ) {
text.append(chCurrent);
}
break;
case TOKEN_STARTGROUP:
case TOKEN_ENDGROUP:
break;
case TOKEN_CTRLWORD:
if ( cwCode == -1 ) {
if (( code == CW_PAR ) || ( code == CW_LINE )) {
//bParOrLine = true;
return 0;
}
}
else if ( code == cwCode ) {
if (( code == CW_PAR ) || ( code == CW_LINE )) {
//bParOrLine = true;
}
return 0;
}
if ( code == errorCwCode ) {
return 1;
}
break;
}
} // End of while
}
private int readChar () {
try {
int nRes = reader.read();
if ( nRes == -1 ) {
chCurrent = (char)0;
return TOKEN_ENDINPUT;
}
// Else get the character
chCurrent = (char)nRes;
return TOKEN_CHAR;
}
catch ( IOException e ) {
throw new OkapiIOException(e);
}
}
private int getNextToken () {
int nRes;
boolean waitingSecondByte = false;
while ( true ) {
// Get the next character
if ( reParse ) { // Re-used last parsed char if available
// Use the last parsed character
nRes = TOKEN_CHAR;
chCurrent = chReParseChar;
chReParseChar = (char)0;
reParse = false;
}
else { // Or read a new one
nRes = readChar();
}
switch ( nRes ) {
case TOKEN_CHAR:
switch ( chCurrent ) {
case '{':
group++;
if ( inFontTable > 0 ) inFontTable++;
if ( noReset > 0 ) noReset++;
ctxStack.push(new RTFContext(ctxStack.peek()));
return TOKEN_STARTGROUP;
case '}':
group--;
if ( inFontTable > 0 ) inFontTable--;
if ( noReset > 0 ) noReset--;
if ( ctxStack.size() > 1 ) {
ctxStack.pop();
loadEncoding(ctxStack.peek().encoding);
}
return TOKEN_ENDGROUP;
case '\r':
case '\n':
// Skip
continue;
case '\\':
nRes = parseAfterBackSlash();
// -1: it's a 'hh conversion to do, otherwise return it
if (( nRes != -1 ) && ( skip == 0 )) return nRes;
if ( nRes != -1 ) {
// Skip only: has to be uDDD
continue;
}
if ( waitingSecondByte ) {
// We were waiting for the second byte
waitingSecondByte = false;
// Convert the DBCS char into Unicode
//TODO: verify that byte-order works
byteBuffer.put(1, byteData);
CharBuffer charBuf;
try {
charBuf = currentCSDec.decode(byteBuffer);
chCurrent = charBuf.get(0);
}
catch (CharacterCodingException e) {
logger.warning(e.getLocalizedMessage());
chCurrent = '?';
}
}
else {
if ( skip == 0 ) { // Avoid conversion when skipping
if ( isLeadByte(byteData) ) {
waitingSecondByte = true;
// It's a lead byte. Store it and get the next byte
byteBuffer.clear();
byteBuffer.put(0, byteData);
break;
}
else { // SBCS
byteBuffer.clear();
byteBuffer.put(0, byteData);
CharBuffer charBuf;
try {
charBuf = currentCSDec.decode(byteBuffer);
chCurrent = charBuf.get(0);
}
catch (CharacterCodingException e) {
logger.warning(e.getLocalizedMessage());
chCurrent = '?';
}
}
}
}
// Fall thru to process the character
default:
if ( skip > 0 ) {
skip--;
if ( skip > 0 ) continue;
// Else, no more char to skip: fall thru and
// return char of uDDD
chCurrent = uChar;
}
if ( waitingSecondByte ) {
// We were waiting for the second byte
waitingSecondByte = false;
// Convert the DBCS char into Unicode
byteBuffer.put(1, byteData);
CharBuffer charBuf;
try {
charBuf = currentCSDec.decode(byteBuffer);
chCurrent = charBuf.get(0);
}
catch (CharacterCodingException e) {
logger.warning(e.getLocalizedMessage());
chCurrent = '?';
}
}
// Text: chCurrent has the Unicode value
chPrevTextChar = chCurrent;
return TOKEN_CHAR;
}
break;
case TOKEN_ENDINPUT:
if ( group > 0 ) {
// Missing '{'
logger.warning(String.format("Missing '{' = %d.", group));
}
else if ( group < 0 ) {
// Extra '}'
logger.warning(String.format("Extra '}' = %d.", group));
}
return nRes;
default:
return nRes;
}
}
}
private boolean isLeadByte (byte byteValue) {
switch ( currentDBCSCodepage ) {
// Make sure to cast to (byte) to get the signed value!
case 932: // Shift-JIS
if (( byteValue >= (byte)0x81 ) && ( byteValue <= (byte)0x9F )) return true;
if (( byteValue >= (byte)0xE0 ) && ( byteValue <= (byte)0xEE )) return true;
if (( byteValue >= (byte)0xFA ) && ( byteValue <= (byte)0xFC )) return true;
break;
case 936: // Chinese Simplified
if (( byteValue >= (byte)0xA1 ) && ( byteValue <= (byte)0xA9 )) return true;
if (( byteValue >= (byte)0xB0 ) && ( byteValue <= (byte)0xF7 )) return true;
break;
case 949: // Korean
if (( byteValue >= (byte)0x81 ) && ( byteValue <= (byte)0xC8 )) return true;
if (( byteValue >= (byte)0xCA ) && ( byteValue <= (byte)0xFD )) return true;
break;
case 950: // Chinese Traditional
if (( byteValue >= (byte)0xA1 ) && ( byteValue <= (byte)0xC6 )) return true;
if (( byteValue >= (byte)0xC9 ) && ( byteValue <= (byte)0xF9 )) return true;
break;
}
// All other encoding: No lead bytes
return false;
}
private int parseAfterBackSlash () {
boolean inHexa = false;
int count = 0;
String sBuf = "";
while ( true ) {
if ( readChar() == TOKEN_CHAR ) {
if ( inHexa ) {
sBuf += chCurrent;
if ( (++count) == 2 ) {
byteData = (byte)(Integer.parseInt(sBuf, 16));
return(-1); // Byte to process
}
continue;
}
else {
switch ( chCurrent ) {
case '\'':
inHexa = true;
break;
case '\r':
case '\n':
// equal to a \par
code = CW_PAR;
return TOKEN_CTRLWORD;
case '\\':
case '{':
case '}':
// Escaped characters
return TOKEN_CHAR;
case '~':
case '|':
case '-':
case '_':
case ':':
return parseControlSymbol();
case '*':
default:
return parseControlWord();
}
}
}
else {
// Unexpected end of input
throw new OkapiIllegalFilterOperationException("Unexcpected end of input.");
}
}
}
private int parseControlWord () {
int nRes;
int nState = 0;
String sBuf = "";
word.setLength(0);
word.append(chCurrent);
value = 1; // Default value
while ( true ) {
if ( (nRes = readChar()) == TOKEN_CHAR ) {
switch ( nState ) {
case 0: // Normal
switch ( chCurrent ) {
case ' ':
return getControlWord();
case '\r':
case '\n':
// According RTF spec 1.6 CR/LF should be ignored
//continue;
// According RTF spec 1.9 CR/LF should be ignored
// ... when "found in clear text segments"
return getControlWord();
default:
// keep adding to the word
if ( Character.isLetter(chCurrent) ) {
word.append(chCurrent);
continue;
}
// End by a value
if ( Character.isDigit(chCurrent) || ( chCurrent == '-' )) {
// Value
nState = 1;
sBuf = String.valueOf(chCurrent);
continue;
}
// End by a no-alpha char
reParse = true;
chReParseChar = chCurrent;
break;
} // End switch m_chCurrent
return getControlWord();
case 1: // Get a value
if ( Character.isDigit(chCurrent) ) {
sBuf += chCurrent;
}
else {
// End of value
if ( chCurrent != ' ' ) {
reParse = true;
chReParseChar = chCurrent;
}
value = Integer.parseInt(sBuf);
return getControlWord();
}
break;
}
}
else if ( nRes == TOKEN_ENDINPUT ) {
return getControlWord();
}
else {
// Unexpected end of input
throw new OkapiIllegalFilterOperationException("Unexcpected end of input.");
}
}
}
private int getControlWord () {
if ( controlWords.containsKey(word.toString()) ) {
code = controlWords.get(word.toString());
}
else {
code = -1;
}
return processControlWord();
}
private int processControlWord () {
RTFFont tmpFont;
switch ( code ) {
case CW_U:
// If the value is negative it's a RTF weird typing casting issue:
// make it positive by using the complement
if ( chCurrent < 0 ) chCurrent = (char)(65536+value);
else chCurrent = (char)value;
skip = ctxStack.peek().uniCount;
uChar = chCurrent; // Preserve char while skipping
return TOKEN_CHAR;
case CW_UC:
ctxStack.peek().uniCount = value;
break;
case CW_FONTTBL:
inFontTable = 1;
ctxStack.peek().inText = false;
break;
case CW_FCHARSET:
if ( inFontTable > 0 ) {
int nFont = ctxStack.peek().font;
if ( fonts.containsKey(nFont) ) {
tmpFont = fonts.get(nFont);
if ( setCharset0ToDefault && ( value == 0 )) {
tmpFont.encoding = defaultEncoding;
}
else {
// Else: Look at table
if ( winCharsets.containsKey(value) ) {
tmpFont.encoding = winCharsets.get(value);
}
else {
tmpFont.encoding = defaultEncoding;
}
}
}
// Else: should not happen (\fcharset is always after \f)
}
// Else: should not happen (\fcharset is always in font table)
break;
case CW_PARD: // Reset properties
// TODO?
break;
case CW_F:
if ( inFontTable > 0 ) {
// Define font
ctxStack.peek().font = value;
if ( !fonts.containsKey(value) ) {
tmpFont = new RTFFont();
fonts.put(value, tmpFont);
}
}
else {
// Switch font
ctxStack.peek().font = value;
// Search font definition
if ( fonts.containsKey(value) ) {
// Switch to the encoding of the font
tmpFont = fonts.get(value);
// Check if the encoding is set, if not, use the default encoding
if ( tmpFont.encoding == null ) {
tmpFont.encoding = defaultEncoding;
}
// Set the current encoding in the stack
ctxStack.peek().encoding = tmpFont.encoding;
// Load the new encoding if needed
loadEncoding(tmpFont.encoding);
}
else {
// Font undefined: Switch to the default encoding
logger.warning(String.format("The font '%d' is undefined. The encoding '%s' is used by default instead.",
value, defaultEncoding));
loadEncoding(defaultEncoding);
}
}
break;
case CW_TAB:
chCurrent = '\t';
return TOKEN_CHAR;
case CW_BULLET:
chCurrent = '\u2022';
return TOKEN_CHAR;
case CW_LQUOTE:
chCurrent = '\u2018';
return TOKEN_CHAR;
case CW_RQUOTE:
chCurrent = '\u2019';
return TOKEN_CHAR;
case CW_LDBLQUOTE:
chCurrent = '\u201c';
return TOKEN_CHAR;
case CW_RDBLQUOTE:
chCurrent = '\u201d';
return TOKEN_CHAR;
case CW_ENDASH:
chCurrent = '\u2013';
return TOKEN_CHAR;
case CW_EMDASH:
chCurrent = '\u2014';
return TOKEN_CHAR;
case CW_ZWJ:
chCurrent = '\u200d';
return TOKEN_CHAR;
case CW_ZWNJ:
chCurrent = '\u200c';
return TOKEN_CHAR;
case CW_LTRMARK:
chCurrent = '\u200e';
return TOKEN_CHAR;
case CW_RTLMARK:
chCurrent = '\u200f';
return TOKEN_CHAR;
case CW_CCHS:
if ( setCharset0ToDefault && ( value == 0 )) {
ctxStack.peek().encoding = defaultEncoding;
}
else {
// Else: Look up
if ( winCharsets.containsKey(value) ) {
ctxStack.peek().encoding = winCharsets.get(value);
}
else {
ctxStack.peek().encoding = defaultEncoding;
}
}
loadEncoding(ctxStack.peek().encoding);
break;
case CW_CPG:
case CW_ANSICPG:
String name = winCodepages.get(value);
if ( name == null ) {
logger.warning(String.format("The codepage '%d' is undefined. The encoding '%s' is used by default instead.",
value, defaultEncoding));
ctxStack.peek().encoding = defaultEncoding;
}
else {
ctxStack.peek().encoding = name;
}
loadEncoding(ctxStack.peek().encoding);
break;
case CW_ANSI:
if ( setCharset0ToDefault ) {
ctxStack.peek().encoding = defaultEncoding;
}
else {
ctxStack.peek().encoding = "windows-1252";
}
loadEncoding(ctxStack.peek().encoding);
break;
case CW_MAC:
ctxStack.peek().encoding = "MacRoman";
loadEncoding(ctxStack.peek().encoding);
break;
case CW_PC:
ctxStack.peek().encoding = "ibm437";
loadEncoding(ctxStack.peek().encoding);
break;
case CW_PCA:
ctxStack.peek().encoding = "ibm850";
loadEncoding(ctxStack.peek().encoding);
break;
case CW_FOOTNOTE:
if ( "#+!>@".indexOf(chPrevTextChar) != -1 ) {
ctxStack.peek().inText = false;
}
break;
case CW_V:
ctxStack.peek().inText = (value == 0);
break;
case CW_XE:
case CW_SHPTXT:
ctxStack.peek().inText = true;
break;
case CW_SPECIAL:
case CW_PICT:
case CW_STYLESHEET:
case CW_COLORTBL:
case CW_INFO:
ctxStack.peek().inText = false;
break;
case CW_ANNOTATION:
noReset = 1;
ctxStack.peek().inText = false;
break;
case CW_DELETED:
ctxStack.peek().inText = (value == 0);
break;
case CW_PLAIN:
// Reset to default
if ( noReset == 0 ) {
ctxStack.peek().inText = true;
}
break;
}
return TOKEN_CTRLWORD;
}
private void loadEncoding (String encodingName) {
if ( currentCSDec != null ) {
if ( currentCSName.compareTo(encodingName) == 0 )
return; // Same encoding: No change needed
}
// check for special cases
if (( "symbol".compareTo(encodingName) == 0 )
|| ( "oem".compareTo(encodingName) == 0 )
|| ( "arabic-user".compareTo(encodingName) == 0 )
|| ( "hebrew-user".compareTo(encodingName) == 0 ))
{
logger.warning(String.format("The encoding '%s' is unsupported. The encoding '%s' is used by default instead.",
encodingName, defaultEncoding));
encodingName = defaultEncoding;
}
// Load the new encoding
currentCSDec = Charset.forName(encodingName).newDecoder();
currentCSName = encodingName;
if ( currentCSName.compareTo("Shift_JIS") == 0 ) {
currentDBCSCodepage = 932;
}
else if ( currentCSName.compareTo("windows949") == 0 ) {
currentDBCSCodepage = 949;
}
//TODO: Other DBCS encoding
else {
currentDBCSCodepage = 0; // Not DBCS
}
}
private int parseControlSymbol () {
switch ( chCurrent ) {
case '~': // Non-breaking space
chCurrent = '\u00a0';
return TOKEN_CHAR;
case '_': // Non-Breaking hyphen
chCurrent = '\u2011';
return TOKEN_CHAR;
case '|': // Formula character
case '-': // Non-required hyphen (Soft-hyphen?? U+00AD?)
return TOKEN_CTRLWORD;
default: // Should not get here
throw new OkapiIllegalFilterOperationException(String.format("Unknown control symbol '%c'", chCurrent));
}
}
}
|
diff --git a/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/properties/tabbed/ReviewExtraTabPropertySection.java b/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/properties/tabbed/ReviewExtraTabPropertySection.java
index 7b43f8f..730b309 100644
--- a/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/properties/tabbed/ReviewExtraTabPropertySection.java
+++ b/org.eclipse.mylyn.reviews.r4e.ui/src/org/eclipse/mylyn/reviews/r4e/ui/internal/properties/tabbed/ReviewExtraTabPropertySection.java
@@ -1,779 +1,785 @@
/*******************************************************************************
* Copyright (c) 2011 Ericsson Research Canada
*
* 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
*
* Description:
*
* This class implements the tabbed property section for the additional properties
* for the Review model element.
*
* Contributors:
* Sebastien Dubois - Created for Mylyn Review R4E project
*
******************************************************************************/
package org.eclipse.mylyn.reviews.r4e.ui.internal.properties.tabbed;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.eclipse.mylyn.reviews.r4e.core.model.R4EMeetingData;
import org.eclipse.mylyn.reviews.r4e.core.model.R4EParticipant;
import org.eclipse.mylyn.reviews.r4e.core.model.R4EReview;
import org.eclipse.mylyn.reviews.r4e.core.model.R4EReviewPhase;
import org.eclipse.mylyn.reviews.r4e.core.model.R4EReviewState;
import org.eclipse.mylyn.reviews.r4e.core.model.serial.impl.OutOfSyncException;
import org.eclipse.mylyn.reviews.r4e.core.model.serial.impl.ResourceHandlingException;
import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUIModelController;
import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUIReviewBasic;
import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUIReviewExtended;
import org.eclipse.mylyn.reviews.r4e.ui.internal.model.R4EUIReviewGroup;
import org.eclipse.mylyn.reviews.r4e.ui.internal.utils.EditableListWidget;
import org.eclipse.mylyn.reviews.r4e.ui.internal.utils.IEditableListListener;
import org.eclipse.mylyn.reviews.r4e.ui.internal.utils.MailServicesProxy;
import org.eclipse.mylyn.reviews.r4e.ui.internal.utils.R4EUIConstants;
import org.eclipse.mylyn.reviews.r4e.ui.internal.utils.UIUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.events.ExpansionAdapter;
import org.eclipse.ui.forms.events.ExpansionEvent;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.views.properties.tabbed.ITabbedPropertyConstants;
import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetPage;
import org.eclipse.ui.views.properties.tabbed.TabbedPropertySheetWidgetFactory;
/**
* @author lmcdubo
* @version $Revision: 1.0 $
*/
public class ReviewExtraTabPropertySection extends ModelElementTabPropertySection implements IEditableListListener {
// ------------------------------------------------------------------------
// Constants
// ------------------------------------------------------------------------
/**
* Field DECISION_SECTION_LABEL. (value is ""Decision information"")
*/
private static final String DECISION_SECTION_LABEL = "Decision Information";
/**
* Field REVIEW_MEETING_REFRESH_TOOLTIP. (value is ""Refresh meetinmg information for mail server"")
*/
private static final String REVIEW_MEETING_REFRESH_TOOLTIP = "Refresh meetinmg information for mail server";
// ------------------------------------------------------------------------
// Member variables
// ------------------------------------------------------------------------
/**
* Field fProjectCombo.
*/
protected CCombo fProjectCombo = null;
/**
* Field FComponents.
*/
protected EditableListWidget fComponents = null;
/**
* Field FEntryCriteriaText.
*/
protected Text fEntryCriteriaText = null;
/**
* Field FObjectivesText.
*/
protected Text fObjectivesText = null;
/**
* Field FReferenceMaterialText.
*/
protected Text fReferenceMaterialText = null;
/**
* Field fExitDecision.
*/
protected CCombo fExitDecisionCombo = null;
/**
* Field fDecisionUsersList.
*/
protected EditableListWidget fDecisionUsersList = null;
/**
* Field fDecisionUsersListLabel.
*/
protected CLabel fDecisionUsersListLabel = null;
/**
* Field fDecisionTimeSpentText.
*/
protected Text fDecisionTimeSpentText = null;
/**
* Field fDecisionTimeSpentLabel.
*/
protected CLabel fDecisionTimeSpentLabel = null;
/**
* Field fMeetingComposite.
*/
private Composite fMeetingComposite = null;
/**
* Field fMeetingUpdateButton.
*/
private Button fMeetingUpdateButton = null;
/**
* Field fMeetingRefreshButton.
*/
private Button fMeetingRefreshButton = null;
/**
* Field fMeetingSubjectLabel.
*/
protected CLabel fMeetingSubjectLabel = null;
/**
* Field fMeetingStartTimeLabel.
*/
protected CLabel fMeetingStartTimeLabel = null;
/**
* Field fMeetingEndTimeLabel.
*/
protected CLabel fMeetingDurationLabel = null;
/**
* Field fMeetingLocationLabel.
*/
protected CLabel fMeetingLocationLabel = null;
// ------------------------------------------------------------------------
// Methods
// ------------------------------------------------------------------------
/**
* Method createControls.
*
* @param parent
* Composite
* @param aTabbedPropertySheetPage
* TabbedPropertySheetPage
* @see org.eclipse.ui.views.properties.tabbed.ISection#createControls(Composite, TabbedPropertySheetPage)
*/
@Override
public void createControls(Composite parent, TabbedPropertySheetPage aTabbedPropertySheetPage) {
super.createControls(parent.getParent(), aTabbedPropertySheetPage);
final TabbedPropertySheetWidgetFactory widgetFactory = aTabbedPropertySheetPage.getWidgetFactory();
FormData data = null;
final Composite mainForm = widgetFactory.createFlatFormComposite(parent);
//Project
fProjectCombo = widgetFactory.createCCombo(mainForm, SWT.READ_ONLY);
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(mainForm, ITabbedPropertyConstants.VSPACE);
fProjectCombo.setToolTipText(R4EUIConstants.REVIEW_PROJECT_TOOLTIP);
fProjectCombo.setLayoutData(data);
fProjectCombo.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
if (!fRefreshInProgress) {
try {
final String currentUser = R4EUIModelController.getReviewer();
final R4EReview modelReview = ((R4EUIReviewBasic) fProperties.getElement()).getReview();
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelReview, currentUser);
modelReview.setProject(fProjectCombo.getText());
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
}
}
refresh();
}
public void widgetDefaultSelected(SelectionEvent e) { // $codepro.audit.disable emptyMethod
//No implementation needed
}
});
final CLabel projectLabel = widgetFactory.createCLabel(mainForm, R4EUIConstants.PROJECT_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fProjectCombo, -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fProjectCombo, 0, SWT.TOP);
projectLabel.setToolTipText(R4EUIConstants.REVIEW_PROJECT_TOOLTIP);
projectLabel.setLayoutData(data);
//Components (Read-only)
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(fProjectCombo, ITabbedPropertyConstants.VSPACE);
fComponents = new EditableListWidget(widgetFactory, mainForm, data, this, 1, CCombo.class, null);
fComponents.setToolTipText(R4EUIConstants.REVIEW_COMPONENTS_TOOLTIP);
final CLabel componentsLabel = widgetFactory.createCLabel(mainForm, R4EUIConstants.COMPONENTS_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fComponents.getComposite(), -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fComponents.getComposite(), 0, SWT.TOP);
componentsLabel.setToolTipText(R4EUIConstants.REVIEW_COMPONENTS_TOOLTIP);
componentsLabel.setLayoutData(data);
//Entry Criteria
fEntryCriteriaText = widgetFactory.createText(mainForm, "", SWT.BORDER);
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(fComponents.getComposite(), ITabbedPropertyConstants.VSPACE);
fEntryCriteriaText.setToolTipText(R4EUIConstants.REVIEW_ENTRY_CRITERIA_TOOLTIP);
fEntryCriteriaText.setLayoutData(data);
final CLabel entryCriteriaLabel = widgetFactory.createCLabel(mainForm, R4EUIConstants.ENTRY_CRITERIA_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fEntryCriteriaText, -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fEntryCriteriaText, 0, SWT.TOP);
entryCriteriaLabel.setToolTipText(R4EUIConstants.REVIEW_ENTRY_CRITERIA_TOOLTIP);
entryCriteriaLabel.setLayoutData(data);
fEntryCriteriaText.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
if (!fRefreshInProgress) {
try {
final String currentUser = R4EUIModelController.getReviewer();
final R4EReview modelReview = ((R4EUIReviewBasic) fProperties.getElement()).getReview();
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelReview, currentUser);
modelReview.setEntryCriteria(fEntryCriteriaText.getText());
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
}
}
}
public void focusGained(FocusEvent e) { // $codepro.audit.disable emptyMethod
//Nothing to do
}
});
UIUtils.addTabbedPropertiesTextResizeListener(fEntryCriteriaText);
//Objectives
fObjectivesText = widgetFactory.createText(mainForm, "", SWT.BORDER);
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(fEntryCriteriaText, ITabbedPropertyConstants.VSPACE);
fObjectivesText.setToolTipText(R4EUIConstants.REVIEW_OBJECTIVES_TOOLTIP);
fObjectivesText.setLayoutData(data);
fObjectivesText.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
if (!fRefreshInProgress) {
try {
final String currentUser = R4EUIModelController.getReviewer();
final R4EReview modelReview = ((R4EUIReviewBasic) fProperties.getElement()).getReview();
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelReview, currentUser);
modelReview.setObjectives(fObjectivesText.getText());
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
}
}
}
public void focusGained(FocusEvent e) { // $codepro.audit.disable emptyMethod
//Nothing to do
}
});
UIUtils.addTabbedPropertiesTextResizeListener(fObjectivesText);
final CLabel objectivesLabel = widgetFactory.createCLabel(mainForm, R4EUIConstants.OBJECTIVES_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fObjectivesText, -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fObjectivesText, 0, SWT.TOP);
objectivesLabel.setToolTipText(R4EUIConstants.REVIEW_OBJECTIVES_TOOLTIP);
objectivesLabel.setLayoutData(data);
//Reference Material
fReferenceMaterialText = widgetFactory.createText(mainForm, "", SWT.BORDER);
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(fObjectivesText, ITabbedPropertyConstants.VSPACE);
fReferenceMaterialText.setToolTipText(R4EUIConstants.REVIEW_REFERENCE_MATERIAL_TOOLTIP);
fReferenceMaterialText.setLayoutData(data);
fReferenceMaterialText.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
if (!fRefreshInProgress) {
try {
final String currentUser = R4EUIModelController.getReviewer();
final R4EReview modelReview = ((R4EUIReviewBasic) fProperties.getElement()).getReview();
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelReview, currentUser);
modelReview.setReferenceMaterial(fReferenceMaterialText.getText());
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
}
}
}
public void focusGained(FocusEvent e) { // $codepro.audit.disable emptyMethod
//Nothing to do
}
});
UIUtils.addTabbedPropertiesTextResizeListener(fReferenceMaterialText);
final CLabel referenceMaterialLabel = widgetFactory.createCLabel(mainForm,
R4EUIConstants.REFERENCE_MATERIAL_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fReferenceMaterialText, -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fReferenceMaterialText, 0, SWT.TOP);
referenceMaterialLabel.setToolTipText(R4EUIConstants.REVIEW_REFERENCE_MATERIAL_TOOLTIP);
referenceMaterialLabel.setLayoutData(data);
//Decision section
final ExpandableComposite decisionSection = widgetFactory.createExpandableComposite(mainForm,
ExpandableComposite.TWISTIE | ExpandableComposite.EXPANDED);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(fReferenceMaterialText, ITabbedPropertyConstants.VSPACE);
data.bottom = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
decisionSection.setLayoutData(data);
decisionSection.setText(DECISION_SECTION_LABEL);
decisionSection.addExpansionListener(new ExpansionAdapter() {
@Override
public void expansionStateChanged(ExpansionEvent e) {
mainForm.layout();
}
});
decisionSection.setLayout(new GridLayout(1, false));
final Composite decisionSectionClient = widgetFactory.createComposite(decisionSection);
decisionSectionClient.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));
decisionSectionClient.setLayout(new GridLayout(4, false));
decisionSection.setClient(decisionSectionClient);
//Scheduled Meetings
final CLabel meetingInfoLabel = widgetFactory.createCLabel(decisionSectionClient,
R4EUIConstants.DECISION_MEETING_LABEL);
meetingInfoLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_TOOLTIP);
meetingInfoLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
//Meeting composite
fMeetingComposite = widgetFactory.createComposite(decisionSectionClient, SWT.BORDER);
GridData textGridData = new GridData(GridData.FILL, GridData.FILL, true, true);
textGridData.horizontalSpan = 3;
fMeetingComposite.setLayoutData(textGridData);
fMeetingComposite.setLayout(new GridLayout(4, false));
//Meeting Subject
final CLabel meetingSubjectLabel = widgetFactory.createCLabel(fMeetingComposite, R4EUIConstants.SUBJECT_LABEL);
meetingSubjectLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_SUBJECT_TOOLTIP);
meetingSubjectLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fMeetingSubjectLabel = widgetFactory.createCLabel(fMeetingComposite, null);
textGridData = new GridData(GridData.FILL, GridData.FILL, false, false);
textGridData.horizontalSpan = 2;
fMeetingSubjectLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_SUBJECT_TOOLTIP);
fMeetingSubjectLabel.setLayoutData(textGridData);
//Meeting update button
fMeetingUpdateButton = widgetFactory.createButton(fMeetingComposite, R4EUIConstants.UPDATE_LABEL, SWT.PUSH);
fMeetingUpdateButton.setToolTipText(R4EUIConstants.REVIEW_MEETING_UPDATE_TOOLTIP);
fMeetingUpdateButton.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fMeetingUpdateButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
try {
MailServicesProxy.sendMeetingRequest();
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
} finally {
R4EUIModelController.setDialogOpen(false);
}
}
public void widgetDefaultSelected(SelectionEvent e) {
//Nothing to do
}
});
//Meeting Start Time
final CLabel meetingStartTimeLabel = widgetFactory.createCLabel(fMeetingComposite,
R4EUIConstants.START_TIME_LABEL);
meetingStartTimeLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_TIME_TOOLTIP);
meetingStartTimeLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fMeetingStartTimeLabel = widgetFactory.createCLabel(fMeetingComposite, "");
textGridData = new GridData(GridData.FILL, GridData.FILL, false, false);
textGridData.horizontalSpan = 2;
fMeetingStartTimeLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_TIME_TOOLTIP);
fMeetingStartTimeLabel.setLayoutData(textGridData);
//Meeting refresh button
fMeetingRefreshButton = widgetFactory.createButton(fMeetingComposite, R4EUIConstants.REFRESH_LABEL, SWT.PUSH);
fMeetingRefreshButton.setToolTipText(REVIEW_MEETING_REFRESH_TOOLTIP);
fMeetingRefreshButton.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fMeetingRefreshButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
try {
((R4EUIReviewBasic) fProperties.getElement()).refreshMeetingData();
} catch (OutOfSyncException ex) {
UIUtils.displaySyncErrorDialog(ex);
} catch (ResourceHandlingException ex) {
UIUtils.displayResourceErrorDialog(ex);
}
}
public void widgetDefaultSelected(SelectionEvent e) {
//Nothing to do
}
});
//Meeting Duration
final CLabel meetingDurationLabel = widgetFactory.createCLabel(fMeetingComposite, R4EUIConstants.DURATION_LABEL);
meetingDurationLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_DURATION_TOOLTIP);
meetingDurationLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fMeetingDurationLabel = widgetFactory.createCLabel(fMeetingComposite, "");
textGridData = new GridData(GridData.FILL, GridData.FILL, false, false);
textGridData.horizontalSpan = 2;
fMeetingDurationLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_DURATION_TOOLTIP);
fMeetingDurationLabel.setLayoutData(textGridData);
widgetFactory.createCLabel(fMeetingComposite, ""); //dummy label for alignment purposes
//Meeting Location
final CLabel meetingLocationLabel = widgetFactory.createCLabel(fMeetingComposite, R4EUIConstants.LOCATION_LABEL);
meetingLocationLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_LOCATION_TOOLTIP);
meetingLocationLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fMeetingLocationLabel = widgetFactory.createCLabel(fMeetingComposite, "");
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 2;
fMeetingLocationLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_LOCATION_TOOLTIP);
fMeetingLocationLabel.setLayoutData(textGridData);
widgetFactory.createCLabel(fMeetingComposite, ""); //dummy label for alignment purposes
//Exit Decision
final CLabel exitDecisionLabel = widgetFactory.createCLabel(decisionSectionClient,
R4EUIConstants.EXIT_DECISION_LABEL);
exitDecisionLabel.setToolTipText(R4EUIConstants.REVIEW_EXIT_DECISION_TOOLTIP);
exitDecisionLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fExitDecisionCombo = widgetFactory.createCCombo(decisionSectionClient, SWT.READ_ONLY);
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fExitDecisionCombo.setToolTipText(R4EUIConstants.REVIEW_EXIT_DECISION_TOOLTIP);
fExitDecisionCombo.setLayoutData(textGridData);
fExitDecisionCombo.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
if (!fRefreshInProgress) {
try {
final String currentUser = R4EUIModelController.getReviewer();
final R4EReview modelReview = ((R4EUIReviewBasic) fProperties.getElement()).getReview();
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelReview, currentUser);
modelReview.setDecision(R4EUIReviewBasic.getDecisionValueFromString(fExitDecisionCombo.getText()));
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
}
}
refresh();
}
public void widgetDefaultSelected(SelectionEvent e) { // $codepro.audit.disable emptyMethod
//No implementation needed
}
});
//Decision Participants
fDecisionUsersListLabel = widgetFactory.createCLabel(decisionSectionClient,
R4EUIConstants.DECISION_PARTICIPANTS_LABEL);
fDecisionUsersListLabel.setToolTipText(R4EUIConstants.REVIEW_EXIT_DECISION_PARTICIPANTS_TOOLTIP);
fDecisionUsersListLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
List<String> participants = null;
if (null != R4EUIModelController.getActiveReview()) {
participants = R4EUIModelController.getActiveReview().getParticipantIDs();
} else {
participants = new ArrayList<String>();
}
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fDecisionUsersList = new EditableListWidget(widgetFactory, decisionSectionClient, textGridData, this, 2,
CCombo.class, participants.toArray(new String[participants.size()]));
fDecisionUsersList.setToolTipText(R4EUIConstants.REVIEW_EXIT_DECISION_PARTICIPANTS_TOOLTIP);
//Decision Time Spent
fDecisionTimeSpentLabel = widgetFactory.createCLabel(decisionSectionClient,
R4EUIConstants.DECISION_TIME_SPENT_LABEL);
fDecisionTimeSpentLabel.setToolTipText(R4EUIConstants.REVIEW_EXIT_DECISION_TIME_SPENT_TOOLTIP);
fDecisionTimeSpentLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fDecisionTimeSpentText = widgetFactory.createText(decisionSectionClient, "");
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fDecisionTimeSpentText.setToolTipText(R4EUIConstants.REVIEW_EXIT_DECISION_TIME_SPENT_TOOLTIP);
fDecisionTimeSpentText.setLayoutData(textGridData);
fDecisionTimeSpentText.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
if (!fRefreshInProgress) {
+ Integer timeSpent;
+ try {
+ timeSpent = Integer.valueOf(fDecisionTimeSpentText.getText());
+ } catch (NumberFormatException e1) {
+ //Set field to 0
+ timeSpent = 0;
+ }
try {
final String currentUser = R4EUIModelController.getReviewer();
final R4EReview modelReview = ((R4EUIReviewExtended) fProperties.getElement()).getReview();
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelReview, currentUser);
- modelReview.getDecision().setSpentTime(
- Integer.valueOf(fDecisionTimeSpentText.getText()).intValue());
+ modelReview.getDecision().setSpentTime(timeSpent.intValue());
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
}
}
}
public void focusGained(FocusEvent e) { // $codepro.audit.disable emptyMethod
//Nothing to do
}
});
}
/**
* Method refresh.
*
* @see org.eclipse.ui.views.properties.tabbed.ISection#refresh()
*/
@Override
public void refresh() {
fRefreshInProgress = true;
final R4EReview modelReview = ((R4EUIReviewBasic) fProperties.getElement()).getReview();
final String[] availableProjects = (String[]) ((R4EUIReviewGroup) ((R4EUIReviewBasic) fProperties.getElement()).getParent()).getGroup()
.getAvailableProjects()
.toArray();
fProjectCombo.setItems(availableProjects);
final String project = modelReview.getProject();
for (int i = 0; i < availableProjects.length; i++) {
if (project.equals(availableProjects[i])) {
fProjectCombo.select(i);
break;
}
}
fComponents.setEditableValues((String[]) ((R4EUIReviewGroup) ((R4EUIReviewBasic) fProperties.getElement()).getParent()).getGroup()
.getAvailableComponents()
.toArray());
final String[] components = (String[]) modelReview.getComponents().toArray();
fComponents.clearAll();
Item item = null;
String component = null;
for (int i = 0; i < components.length; i++) {
component = components[i];
if (i >= fComponents.getItemCount()) {
item = fComponents.addItem();
} else {
item = fComponents.getItem(i);
if (null == item) {
item = fComponents.addItem();
}
}
item.setText(component);
}
fEntryCriteriaText.setText(modelReview.getEntryCriteria());
fObjectivesText.setText(modelReview.getObjectives());
fReferenceMaterialText.setText(modelReview.getReferenceMaterial());
final R4EMeetingData meetingData = modelReview.getActiveMeeting();
if (null != meetingData) {
fMeetingSubjectLabel.setText(meetingData.getSubject());
final SimpleDateFormat dateFormat = new SimpleDateFormat(R4EUIConstants.SIMPLE_DATE_FORMAT_MINUTES);
fMeetingStartTimeLabel.setText(dateFormat.format(new Date(meetingData.getStartTime())));
fMeetingDurationLabel.setText(Integer.toString(meetingData.getDuration()));
fMeetingLocationLabel.setText(meetingData.getLocation());
} else {
fMeetingSubjectLabel.setText("");
fMeetingStartTimeLabel.setText("");
fMeetingDurationLabel.setText("");
fMeetingLocationLabel.setText("");
}
fExitDecisionCombo.setItems(R4EUIReviewBasic.getExitDecisionValues());
if (null != modelReview.getDecision()) {
fExitDecisionCombo.select((null == modelReview.getDecision().getValue()) ? 0 : modelReview.getDecision()
.getValue()
.getValue());
} else {
fExitDecisionCombo.setText("");
}
if (fProperties.getElement() instanceof R4EUIReviewExtended) {
final List<R4EParticipant> participants = ((R4EUIReviewBasic) fProperties.getElement()).getParticipants();
item = null;
final int numParticipants = participants.size();
fDecisionUsersList.clearAll();
for (int i = 0; i < numParticipants; i++) {
if (participants.get(i).isIsPartOfDecision()) {
if (i >= fDecisionUsersList.getItemCount()) {
item = fDecisionUsersList.addItem();
} else {
item = fDecisionUsersList.getItem(i);
if (null == item) {
item = fDecisionUsersList.addItem();
}
}
item.setText(participants.get(i).getId());
}
}
if (null != modelReview.getDecision()) {
fDecisionTimeSpentText.setText(Integer.valueOf(modelReview.getDecision().getSpentTime()).toString());
} else {
fDecisionTimeSpentText.setText("");
}
}
setEnabledFields();
fRefreshInProgress = false;
}
/**
* Method setEnabledFields.
*/
@Override
protected void setEnabledFields() {
if (R4EUIModelController.isDialogOpen()
|| (!((R4EUIReviewBasic) fProperties.getElement()).isOpen())
|| ((R4EReviewState) ((R4EUIReviewBasic) fProperties.getElement()).getReview().getState()).getState()
.equals(R4EReviewPhase.R4E_REVIEW_PHASE_COMPLETED)) {
fProjectCombo.setEnabled(false);
fComponents.setEnabled(false);
fEntryCriteriaText.setEnabled(false);
fObjectivesText.setEnabled(false);
fReferenceMaterialText.setEnabled(false);
fExitDecisionCombo.setEnabled(false);
fMeetingUpdateButton.setEnabled(false);
fMeetingRefreshButton.setEnabled(false);
if (fProperties.getElement() instanceof R4EUIReviewExtended) {
fDecisionUsersList.setEnabled(false);
fDecisionTimeSpentText.setEnabled(false);
fDecisionUsersListLabel.setVisible(true);
fDecisionUsersList.setVisible(true);
fDecisionTimeSpentText.setVisible(true);
fDecisionTimeSpentLabel.setVisible(true);
} else {
fDecisionUsersListLabel.setVisible(false);
fDecisionUsersList.setVisible(false);
fDecisionTimeSpentText.setVisible(false);
fDecisionTimeSpentLabel.setVisible(false);
}
} else {
fProjectCombo.setEnabled(true);
fComponents.setEnabled(true);
fEntryCriteriaText.setEnabled(true);
fObjectivesText.setEnabled(true);
fReferenceMaterialText.setEnabled(true);
fMeetingUpdateButton.setEnabled(true);
fMeetingRefreshButton.setEnabled(true);
if (fProperties.getElement() instanceof R4EUIReviewExtended) {
final R4EUIReviewExtended uiReview = (R4EUIReviewExtended) fProperties.getElement();
if (uiReview.isDecisionDateEnabled()) {
fDecisionUsersList.setEnabled(true);
fDecisionTimeSpentText.setEnabled(true);
fExitDecisionCombo.setEnabled(true);
} else {
fDecisionUsersList.setEnabled(false);
fDecisionTimeSpentText.setEnabled(false);
fExitDecisionCombo.setEnabled(false);
}
fDecisionUsersListLabel.setVisible(true);
fDecisionUsersList.setVisible(true);
fDecisionTimeSpentText.setVisible(true);
fDecisionTimeSpentLabel.setVisible(true);
} else {
fDecisionUsersListLabel.setVisible(false);
fDecisionUsersList.setVisible(false);
fDecisionTimeSpentText.setVisible(false);
fDecisionTimeSpentLabel.setVisible(false);
if (((R4EUIReviewBasic) fProperties.getElement()).isExitDecisionEnabled()) {
fExitDecisionCombo.setEnabled(true);
} else {
fExitDecisionCombo.setEnabled(false);
}
}
}
}
/**
* Method itemsUpdated.
*
* @param aItems
* Item[]
* @param aInstanceId
* int
* @see org.eclipse.mylyn.reviews.r4e.ui.internal.utils.IEditableListListener#itemsUpdated(Item[], int)
*/
public void itemsUpdated(Item[] aItems, int aInstanceId) {
try {
final R4EReview modelReview = ((R4EUIReviewBasic) fProperties.getElement()).getReview();
final String currentUser = R4EUIModelController.getReviewer();
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelReview, currentUser);
if (1 == aInstanceId) {
//Update components
modelReview.getComponents().clear();
for (Item item : aItems) {
modelReview.getComponents().add(item.getText());
}
} else { //aInstanceId == 2
for (Item item : aItems) {
R4EParticipant participant = (R4EParticipant) modelReview.getUsersMap().get(item.getText());
if (null != participant) {
participant.setIsPartOfDecision(true);
}
}
}
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
refresh();
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
}
}
}
| false | true | public void createControls(Composite parent, TabbedPropertySheetPage aTabbedPropertySheetPage) {
super.createControls(parent.getParent(), aTabbedPropertySheetPage);
final TabbedPropertySheetWidgetFactory widgetFactory = aTabbedPropertySheetPage.getWidgetFactory();
FormData data = null;
final Composite mainForm = widgetFactory.createFlatFormComposite(parent);
//Project
fProjectCombo = widgetFactory.createCCombo(mainForm, SWT.READ_ONLY);
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(mainForm, ITabbedPropertyConstants.VSPACE);
fProjectCombo.setToolTipText(R4EUIConstants.REVIEW_PROJECT_TOOLTIP);
fProjectCombo.setLayoutData(data);
fProjectCombo.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
if (!fRefreshInProgress) {
try {
final String currentUser = R4EUIModelController.getReviewer();
final R4EReview modelReview = ((R4EUIReviewBasic) fProperties.getElement()).getReview();
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelReview, currentUser);
modelReview.setProject(fProjectCombo.getText());
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
}
}
refresh();
}
public void widgetDefaultSelected(SelectionEvent e) { // $codepro.audit.disable emptyMethod
//No implementation needed
}
});
final CLabel projectLabel = widgetFactory.createCLabel(mainForm, R4EUIConstants.PROJECT_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fProjectCombo, -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fProjectCombo, 0, SWT.TOP);
projectLabel.setToolTipText(R4EUIConstants.REVIEW_PROJECT_TOOLTIP);
projectLabel.setLayoutData(data);
//Components (Read-only)
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(fProjectCombo, ITabbedPropertyConstants.VSPACE);
fComponents = new EditableListWidget(widgetFactory, mainForm, data, this, 1, CCombo.class, null);
fComponents.setToolTipText(R4EUIConstants.REVIEW_COMPONENTS_TOOLTIP);
final CLabel componentsLabel = widgetFactory.createCLabel(mainForm, R4EUIConstants.COMPONENTS_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fComponents.getComposite(), -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fComponents.getComposite(), 0, SWT.TOP);
componentsLabel.setToolTipText(R4EUIConstants.REVIEW_COMPONENTS_TOOLTIP);
componentsLabel.setLayoutData(data);
//Entry Criteria
fEntryCriteriaText = widgetFactory.createText(mainForm, "", SWT.BORDER);
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(fComponents.getComposite(), ITabbedPropertyConstants.VSPACE);
fEntryCriteriaText.setToolTipText(R4EUIConstants.REVIEW_ENTRY_CRITERIA_TOOLTIP);
fEntryCriteriaText.setLayoutData(data);
final CLabel entryCriteriaLabel = widgetFactory.createCLabel(mainForm, R4EUIConstants.ENTRY_CRITERIA_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fEntryCriteriaText, -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fEntryCriteriaText, 0, SWT.TOP);
entryCriteriaLabel.setToolTipText(R4EUIConstants.REVIEW_ENTRY_CRITERIA_TOOLTIP);
entryCriteriaLabel.setLayoutData(data);
fEntryCriteriaText.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
if (!fRefreshInProgress) {
try {
final String currentUser = R4EUIModelController.getReviewer();
final R4EReview modelReview = ((R4EUIReviewBasic) fProperties.getElement()).getReview();
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelReview, currentUser);
modelReview.setEntryCriteria(fEntryCriteriaText.getText());
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
}
}
}
public void focusGained(FocusEvent e) { // $codepro.audit.disable emptyMethod
//Nothing to do
}
});
UIUtils.addTabbedPropertiesTextResizeListener(fEntryCriteriaText);
//Objectives
fObjectivesText = widgetFactory.createText(mainForm, "", SWT.BORDER);
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(fEntryCriteriaText, ITabbedPropertyConstants.VSPACE);
fObjectivesText.setToolTipText(R4EUIConstants.REVIEW_OBJECTIVES_TOOLTIP);
fObjectivesText.setLayoutData(data);
fObjectivesText.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
if (!fRefreshInProgress) {
try {
final String currentUser = R4EUIModelController.getReviewer();
final R4EReview modelReview = ((R4EUIReviewBasic) fProperties.getElement()).getReview();
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelReview, currentUser);
modelReview.setObjectives(fObjectivesText.getText());
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
}
}
}
public void focusGained(FocusEvent e) { // $codepro.audit.disable emptyMethod
//Nothing to do
}
});
UIUtils.addTabbedPropertiesTextResizeListener(fObjectivesText);
final CLabel objectivesLabel = widgetFactory.createCLabel(mainForm, R4EUIConstants.OBJECTIVES_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fObjectivesText, -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fObjectivesText, 0, SWT.TOP);
objectivesLabel.setToolTipText(R4EUIConstants.REVIEW_OBJECTIVES_TOOLTIP);
objectivesLabel.setLayoutData(data);
//Reference Material
fReferenceMaterialText = widgetFactory.createText(mainForm, "", SWT.BORDER);
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(fObjectivesText, ITabbedPropertyConstants.VSPACE);
fReferenceMaterialText.setToolTipText(R4EUIConstants.REVIEW_REFERENCE_MATERIAL_TOOLTIP);
fReferenceMaterialText.setLayoutData(data);
fReferenceMaterialText.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
if (!fRefreshInProgress) {
try {
final String currentUser = R4EUIModelController.getReviewer();
final R4EReview modelReview = ((R4EUIReviewBasic) fProperties.getElement()).getReview();
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelReview, currentUser);
modelReview.setReferenceMaterial(fReferenceMaterialText.getText());
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
}
}
}
public void focusGained(FocusEvent e) { // $codepro.audit.disable emptyMethod
//Nothing to do
}
});
UIUtils.addTabbedPropertiesTextResizeListener(fReferenceMaterialText);
final CLabel referenceMaterialLabel = widgetFactory.createCLabel(mainForm,
R4EUIConstants.REFERENCE_MATERIAL_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fReferenceMaterialText, -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fReferenceMaterialText, 0, SWT.TOP);
referenceMaterialLabel.setToolTipText(R4EUIConstants.REVIEW_REFERENCE_MATERIAL_TOOLTIP);
referenceMaterialLabel.setLayoutData(data);
//Decision section
final ExpandableComposite decisionSection = widgetFactory.createExpandableComposite(mainForm,
ExpandableComposite.TWISTIE | ExpandableComposite.EXPANDED);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(fReferenceMaterialText, ITabbedPropertyConstants.VSPACE);
data.bottom = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
decisionSection.setLayoutData(data);
decisionSection.setText(DECISION_SECTION_LABEL);
decisionSection.addExpansionListener(new ExpansionAdapter() {
@Override
public void expansionStateChanged(ExpansionEvent e) {
mainForm.layout();
}
});
decisionSection.setLayout(new GridLayout(1, false));
final Composite decisionSectionClient = widgetFactory.createComposite(decisionSection);
decisionSectionClient.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));
decisionSectionClient.setLayout(new GridLayout(4, false));
decisionSection.setClient(decisionSectionClient);
//Scheduled Meetings
final CLabel meetingInfoLabel = widgetFactory.createCLabel(decisionSectionClient,
R4EUIConstants.DECISION_MEETING_LABEL);
meetingInfoLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_TOOLTIP);
meetingInfoLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
//Meeting composite
fMeetingComposite = widgetFactory.createComposite(decisionSectionClient, SWT.BORDER);
GridData textGridData = new GridData(GridData.FILL, GridData.FILL, true, true);
textGridData.horizontalSpan = 3;
fMeetingComposite.setLayoutData(textGridData);
fMeetingComposite.setLayout(new GridLayout(4, false));
//Meeting Subject
final CLabel meetingSubjectLabel = widgetFactory.createCLabel(fMeetingComposite, R4EUIConstants.SUBJECT_LABEL);
meetingSubjectLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_SUBJECT_TOOLTIP);
meetingSubjectLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fMeetingSubjectLabel = widgetFactory.createCLabel(fMeetingComposite, null);
textGridData = new GridData(GridData.FILL, GridData.FILL, false, false);
textGridData.horizontalSpan = 2;
fMeetingSubjectLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_SUBJECT_TOOLTIP);
fMeetingSubjectLabel.setLayoutData(textGridData);
//Meeting update button
fMeetingUpdateButton = widgetFactory.createButton(fMeetingComposite, R4EUIConstants.UPDATE_LABEL, SWT.PUSH);
fMeetingUpdateButton.setToolTipText(R4EUIConstants.REVIEW_MEETING_UPDATE_TOOLTIP);
fMeetingUpdateButton.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fMeetingUpdateButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
try {
MailServicesProxy.sendMeetingRequest();
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
} finally {
R4EUIModelController.setDialogOpen(false);
}
}
public void widgetDefaultSelected(SelectionEvent e) {
//Nothing to do
}
});
//Meeting Start Time
final CLabel meetingStartTimeLabel = widgetFactory.createCLabel(fMeetingComposite,
R4EUIConstants.START_TIME_LABEL);
meetingStartTimeLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_TIME_TOOLTIP);
meetingStartTimeLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fMeetingStartTimeLabel = widgetFactory.createCLabel(fMeetingComposite, "");
textGridData = new GridData(GridData.FILL, GridData.FILL, false, false);
textGridData.horizontalSpan = 2;
fMeetingStartTimeLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_TIME_TOOLTIP);
fMeetingStartTimeLabel.setLayoutData(textGridData);
//Meeting refresh button
fMeetingRefreshButton = widgetFactory.createButton(fMeetingComposite, R4EUIConstants.REFRESH_LABEL, SWT.PUSH);
fMeetingRefreshButton.setToolTipText(REVIEW_MEETING_REFRESH_TOOLTIP);
fMeetingRefreshButton.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fMeetingRefreshButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
try {
((R4EUIReviewBasic) fProperties.getElement()).refreshMeetingData();
} catch (OutOfSyncException ex) {
UIUtils.displaySyncErrorDialog(ex);
} catch (ResourceHandlingException ex) {
UIUtils.displayResourceErrorDialog(ex);
}
}
public void widgetDefaultSelected(SelectionEvent e) {
//Nothing to do
}
});
//Meeting Duration
final CLabel meetingDurationLabel = widgetFactory.createCLabel(fMeetingComposite, R4EUIConstants.DURATION_LABEL);
meetingDurationLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_DURATION_TOOLTIP);
meetingDurationLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fMeetingDurationLabel = widgetFactory.createCLabel(fMeetingComposite, "");
textGridData = new GridData(GridData.FILL, GridData.FILL, false, false);
textGridData.horizontalSpan = 2;
fMeetingDurationLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_DURATION_TOOLTIP);
fMeetingDurationLabel.setLayoutData(textGridData);
widgetFactory.createCLabel(fMeetingComposite, ""); //dummy label for alignment purposes
//Meeting Location
final CLabel meetingLocationLabel = widgetFactory.createCLabel(fMeetingComposite, R4EUIConstants.LOCATION_LABEL);
meetingLocationLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_LOCATION_TOOLTIP);
meetingLocationLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fMeetingLocationLabel = widgetFactory.createCLabel(fMeetingComposite, "");
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 2;
fMeetingLocationLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_LOCATION_TOOLTIP);
fMeetingLocationLabel.setLayoutData(textGridData);
widgetFactory.createCLabel(fMeetingComposite, ""); //dummy label for alignment purposes
//Exit Decision
final CLabel exitDecisionLabel = widgetFactory.createCLabel(decisionSectionClient,
R4EUIConstants.EXIT_DECISION_LABEL);
exitDecisionLabel.setToolTipText(R4EUIConstants.REVIEW_EXIT_DECISION_TOOLTIP);
exitDecisionLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fExitDecisionCombo = widgetFactory.createCCombo(decisionSectionClient, SWT.READ_ONLY);
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fExitDecisionCombo.setToolTipText(R4EUIConstants.REVIEW_EXIT_DECISION_TOOLTIP);
fExitDecisionCombo.setLayoutData(textGridData);
fExitDecisionCombo.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
if (!fRefreshInProgress) {
try {
final String currentUser = R4EUIModelController.getReviewer();
final R4EReview modelReview = ((R4EUIReviewBasic) fProperties.getElement()).getReview();
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelReview, currentUser);
modelReview.setDecision(R4EUIReviewBasic.getDecisionValueFromString(fExitDecisionCombo.getText()));
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
}
}
refresh();
}
public void widgetDefaultSelected(SelectionEvent e) { // $codepro.audit.disable emptyMethod
//No implementation needed
}
});
//Decision Participants
fDecisionUsersListLabel = widgetFactory.createCLabel(decisionSectionClient,
R4EUIConstants.DECISION_PARTICIPANTS_LABEL);
fDecisionUsersListLabel.setToolTipText(R4EUIConstants.REVIEW_EXIT_DECISION_PARTICIPANTS_TOOLTIP);
fDecisionUsersListLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
List<String> participants = null;
if (null != R4EUIModelController.getActiveReview()) {
participants = R4EUIModelController.getActiveReview().getParticipantIDs();
} else {
participants = new ArrayList<String>();
}
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fDecisionUsersList = new EditableListWidget(widgetFactory, decisionSectionClient, textGridData, this, 2,
CCombo.class, participants.toArray(new String[participants.size()]));
fDecisionUsersList.setToolTipText(R4EUIConstants.REVIEW_EXIT_DECISION_PARTICIPANTS_TOOLTIP);
//Decision Time Spent
fDecisionTimeSpentLabel = widgetFactory.createCLabel(decisionSectionClient,
R4EUIConstants.DECISION_TIME_SPENT_LABEL);
fDecisionTimeSpentLabel.setToolTipText(R4EUIConstants.REVIEW_EXIT_DECISION_TIME_SPENT_TOOLTIP);
fDecisionTimeSpentLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fDecisionTimeSpentText = widgetFactory.createText(decisionSectionClient, "");
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fDecisionTimeSpentText.setToolTipText(R4EUIConstants.REVIEW_EXIT_DECISION_TIME_SPENT_TOOLTIP);
fDecisionTimeSpentText.setLayoutData(textGridData);
fDecisionTimeSpentText.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
if (!fRefreshInProgress) {
try {
final String currentUser = R4EUIModelController.getReviewer();
final R4EReview modelReview = ((R4EUIReviewExtended) fProperties.getElement()).getReview();
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelReview, currentUser);
modelReview.getDecision().setSpentTime(
Integer.valueOf(fDecisionTimeSpentText.getText()).intValue());
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
}
}
}
public void focusGained(FocusEvent e) { // $codepro.audit.disable emptyMethod
//Nothing to do
}
});
}
| public void createControls(Composite parent, TabbedPropertySheetPage aTabbedPropertySheetPage) {
super.createControls(parent.getParent(), aTabbedPropertySheetPage);
final TabbedPropertySheetWidgetFactory widgetFactory = aTabbedPropertySheetPage.getWidgetFactory();
FormData data = null;
final Composite mainForm = widgetFactory.createFlatFormComposite(parent);
//Project
fProjectCombo = widgetFactory.createCCombo(mainForm, SWT.READ_ONLY);
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(mainForm, ITabbedPropertyConstants.VSPACE);
fProjectCombo.setToolTipText(R4EUIConstants.REVIEW_PROJECT_TOOLTIP);
fProjectCombo.setLayoutData(data);
fProjectCombo.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
if (!fRefreshInProgress) {
try {
final String currentUser = R4EUIModelController.getReviewer();
final R4EReview modelReview = ((R4EUIReviewBasic) fProperties.getElement()).getReview();
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelReview, currentUser);
modelReview.setProject(fProjectCombo.getText());
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
}
}
refresh();
}
public void widgetDefaultSelected(SelectionEvent e) { // $codepro.audit.disable emptyMethod
//No implementation needed
}
});
final CLabel projectLabel = widgetFactory.createCLabel(mainForm, R4EUIConstants.PROJECT_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fProjectCombo, -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fProjectCombo, 0, SWT.TOP);
projectLabel.setToolTipText(R4EUIConstants.REVIEW_PROJECT_TOOLTIP);
projectLabel.setLayoutData(data);
//Components (Read-only)
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(fProjectCombo, ITabbedPropertyConstants.VSPACE);
fComponents = new EditableListWidget(widgetFactory, mainForm, data, this, 1, CCombo.class, null);
fComponents.setToolTipText(R4EUIConstants.REVIEW_COMPONENTS_TOOLTIP);
final CLabel componentsLabel = widgetFactory.createCLabel(mainForm, R4EUIConstants.COMPONENTS_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fComponents.getComposite(), -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fComponents.getComposite(), 0, SWT.TOP);
componentsLabel.setToolTipText(R4EUIConstants.REVIEW_COMPONENTS_TOOLTIP);
componentsLabel.setLayoutData(data);
//Entry Criteria
fEntryCriteriaText = widgetFactory.createText(mainForm, "", SWT.BORDER);
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(fComponents.getComposite(), ITabbedPropertyConstants.VSPACE);
fEntryCriteriaText.setToolTipText(R4EUIConstants.REVIEW_ENTRY_CRITERIA_TOOLTIP);
fEntryCriteriaText.setLayoutData(data);
final CLabel entryCriteriaLabel = widgetFactory.createCLabel(mainForm, R4EUIConstants.ENTRY_CRITERIA_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fEntryCriteriaText, -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fEntryCriteriaText, 0, SWT.TOP);
entryCriteriaLabel.setToolTipText(R4EUIConstants.REVIEW_ENTRY_CRITERIA_TOOLTIP);
entryCriteriaLabel.setLayoutData(data);
fEntryCriteriaText.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
if (!fRefreshInProgress) {
try {
final String currentUser = R4EUIModelController.getReviewer();
final R4EReview modelReview = ((R4EUIReviewBasic) fProperties.getElement()).getReview();
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelReview, currentUser);
modelReview.setEntryCriteria(fEntryCriteriaText.getText());
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
}
}
}
public void focusGained(FocusEvent e) { // $codepro.audit.disable emptyMethod
//Nothing to do
}
});
UIUtils.addTabbedPropertiesTextResizeListener(fEntryCriteriaText);
//Objectives
fObjectivesText = widgetFactory.createText(mainForm, "", SWT.BORDER);
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(fEntryCriteriaText, ITabbedPropertyConstants.VSPACE);
fObjectivesText.setToolTipText(R4EUIConstants.REVIEW_OBJECTIVES_TOOLTIP);
fObjectivesText.setLayoutData(data);
fObjectivesText.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
if (!fRefreshInProgress) {
try {
final String currentUser = R4EUIModelController.getReviewer();
final R4EReview modelReview = ((R4EUIReviewBasic) fProperties.getElement()).getReview();
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelReview, currentUser);
modelReview.setObjectives(fObjectivesText.getText());
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
}
}
}
public void focusGained(FocusEvent e) { // $codepro.audit.disable emptyMethod
//Nothing to do
}
});
UIUtils.addTabbedPropertiesTextResizeListener(fObjectivesText);
final CLabel objectivesLabel = widgetFactory.createCLabel(mainForm, R4EUIConstants.OBJECTIVES_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fObjectivesText, -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fObjectivesText, 0, SWT.TOP);
objectivesLabel.setToolTipText(R4EUIConstants.REVIEW_OBJECTIVES_TOOLTIP);
objectivesLabel.setLayoutData(data);
//Reference Material
fReferenceMaterialText = widgetFactory.createText(mainForm, "", SWT.BORDER);
data = new FormData();
data.left = new FormAttachment(0, R4EUIConstants.TABBED_PROPERTY_LABEL_WIDTH);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(fObjectivesText, ITabbedPropertyConstants.VSPACE);
fReferenceMaterialText.setToolTipText(R4EUIConstants.REVIEW_REFERENCE_MATERIAL_TOOLTIP);
fReferenceMaterialText.setLayoutData(data);
fReferenceMaterialText.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
if (!fRefreshInProgress) {
try {
final String currentUser = R4EUIModelController.getReviewer();
final R4EReview modelReview = ((R4EUIReviewBasic) fProperties.getElement()).getReview();
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelReview, currentUser);
modelReview.setReferenceMaterial(fReferenceMaterialText.getText());
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
}
}
}
public void focusGained(FocusEvent e) { // $codepro.audit.disable emptyMethod
//Nothing to do
}
});
UIUtils.addTabbedPropertiesTextResizeListener(fReferenceMaterialText);
final CLabel referenceMaterialLabel = widgetFactory.createCLabel(mainForm,
R4EUIConstants.REFERENCE_MATERIAL_LABEL);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(fReferenceMaterialText, -ITabbedPropertyConstants.HSPACE);
data.top = new FormAttachment(fReferenceMaterialText, 0, SWT.TOP);
referenceMaterialLabel.setToolTipText(R4EUIConstants.REVIEW_REFERENCE_MATERIAL_TOOLTIP);
referenceMaterialLabel.setLayoutData(data);
//Decision section
final ExpandableComposite decisionSection = widgetFactory.createExpandableComposite(mainForm,
ExpandableComposite.TWISTIE | ExpandableComposite.EXPANDED);
data = new FormData();
data.left = new FormAttachment(0, 0);
data.right = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
data.top = new FormAttachment(fReferenceMaterialText, ITabbedPropertyConstants.VSPACE);
data.bottom = new FormAttachment(100, 0); // $codepro.audit.disable numericLiterals
decisionSection.setLayoutData(data);
decisionSection.setText(DECISION_SECTION_LABEL);
decisionSection.addExpansionListener(new ExpansionAdapter() {
@Override
public void expansionStateChanged(ExpansionEvent e) {
mainForm.layout();
}
});
decisionSection.setLayout(new GridLayout(1, false));
final Composite decisionSectionClient = widgetFactory.createComposite(decisionSection);
decisionSectionClient.setLayoutData(new GridData(GridData.FILL, GridData.FILL, true, true));
decisionSectionClient.setLayout(new GridLayout(4, false));
decisionSection.setClient(decisionSectionClient);
//Scheduled Meetings
final CLabel meetingInfoLabel = widgetFactory.createCLabel(decisionSectionClient,
R4EUIConstants.DECISION_MEETING_LABEL);
meetingInfoLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_TOOLTIP);
meetingInfoLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
//Meeting composite
fMeetingComposite = widgetFactory.createComposite(decisionSectionClient, SWT.BORDER);
GridData textGridData = new GridData(GridData.FILL, GridData.FILL, true, true);
textGridData.horizontalSpan = 3;
fMeetingComposite.setLayoutData(textGridData);
fMeetingComposite.setLayout(new GridLayout(4, false));
//Meeting Subject
final CLabel meetingSubjectLabel = widgetFactory.createCLabel(fMeetingComposite, R4EUIConstants.SUBJECT_LABEL);
meetingSubjectLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_SUBJECT_TOOLTIP);
meetingSubjectLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fMeetingSubjectLabel = widgetFactory.createCLabel(fMeetingComposite, null);
textGridData = new GridData(GridData.FILL, GridData.FILL, false, false);
textGridData.horizontalSpan = 2;
fMeetingSubjectLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_SUBJECT_TOOLTIP);
fMeetingSubjectLabel.setLayoutData(textGridData);
//Meeting update button
fMeetingUpdateButton = widgetFactory.createButton(fMeetingComposite, R4EUIConstants.UPDATE_LABEL, SWT.PUSH);
fMeetingUpdateButton.setToolTipText(R4EUIConstants.REVIEW_MEETING_UPDATE_TOOLTIP);
fMeetingUpdateButton.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fMeetingUpdateButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
try {
MailServicesProxy.sendMeetingRequest();
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
} finally {
R4EUIModelController.setDialogOpen(false);
}
}
public void widgetDefaultSelected(SelectionEvent e) {
//Nothing to do
}
});
//Meeting Start Time
final CLabel meetingStartTimeLabel = widgetFactory.createCLabel(fMeetingComposite,
R4EUIConstants.START_TIME_LABEL);
meetingStartTimeLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_TIME_TOOLTIP);
meetingStartTimeLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fMeetingStartTimeLabel = widgetFactory.createCLabel(fMeetingComposite, "");
textGridData = new GridData(GridData.FILL, GridData.FILL, false, false);
textGridData.horizontalSpan = 2;
fMeetingStartTimeLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_TIME_TOOLTIP);
fMeetingStartTimeLabel.setLayoutData(textGridData);
//Meeting refresh button
fMeetingRefreshButton = widgetFactory.createButton(fMeetingComposite, R4EUIConstants.REFRESH_LABEL, SWT.PUSH);
fMeetingRefreshButton.setToolTipText(REVIEW_MEETING_REFRESH_TOOLTIP);
fMeetingRefreshButton.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fMeetingRefreshButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
try {
((R4EUIReviewBasic) fProperties.getElement()).refreshMeetingData();
} catch (OutOfSyncException ex) {
UIUtils.displaySyncErrorDialog(ex);
} catch (ResourceHandlingException ex) {
UIUtils.displayResourceErrorDialog(ex);
}
}
public void widgetDefaultSelected(SelectionEvent e) {
//Nothing to do
}
});
//Meeting Duration
final CLabel meetingDurationLabel = widgetFactory.createCLabel(fMeetingComposite, R4EUIConstants.DURATION_LABEL);
meetingDurationLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_DURATION_TOOLTIP);
meetingDurationLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fMeetingDurationLabel = widgetFactory.createCLabel(fMeetingComposite, "");
textGridData = new GridData(GridData.FILL, GridData.FILL, false, false);
textGridData.horizontalSpan = 2;
fMeetingDurationLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_DURATION_TOOLTIP);
fMeetingDurationLabel.setLayoutData(textGridData);
widgetFactory.createCLabel(fMeetingComposite, ""); //dummy label for alignment purposes
//Meeting Location
final CLabel meetingLocationLabel = widgetFactory.createCLabel(fMeetingComposite, R4EUIConstants.LOCATION_LABEL);
meetingLocationLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_LOCATION_TOOLTIP);
meetingLocationLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fMeetingLocationLabel = widgetFactory.createCLabel(fMeetingComposite, "");
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 2;
fMeetingLocationLabel.setToolTipText(R4EUIConstants.REVIEW_MEETING_LOCATION_TOOLTIP);
fMeetingLocationLabel.setLayoutData(textGridData);
widgetFactory.createCLabel(fMeetingComposite, ""); //dummy label for alignment purposes
//Exit Decision
final CLabel exitDecisionLabel = widgetFactory.createCLabel(decisionSectionClient,
R4EUIConstants.EXIT_DECISION_LABEL);
exitDecisionLabel.setToolTipText(R4EUIConstants.REVIEW_EXIT_DECISION_TOOLTIP);
exitDecisionLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fExitDecisionCombo = widgetFactory.createCCombo(decisionSectionClient, SWT.READ_ONLY);
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fExitDecisionCombo.setToolTipText(R4EUIConstants.REVIEW_EXIT_DECISION_TOOLTIP);
fExitDecisionCombo.setLayoutData(textGridData);
fExitDecisionCombo.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
if (!fRefreshInProgress) {
try {
final String currentUser = R4EUIModelController.getReviewer();
final R4EReview modelReview = ((R4EUIReviewBasic) fProperties.getElement()).getReview();
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelReview, currentUser);
modelReview.setDecision(R4EUIReviewBasic.getDecisionValueFromString(fExitDecisionCombo.getText()));
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
}
}
refresh();
}
public void widgetDefaultSelected(SelectionEvent e) { // $codepro.audit.disable emptyMethod
//No implementation needed
}
});
//Decision Participants
fDecisionUsersListLabel = widgetFactory.createCLabel(decisionSectionClient,
R4EUIConstants.DECISION_PARTICIPANTS_LABEL);
fDecisionUsersListLabel.setToolTipText(R4EUIConstants.REVIEW_EXIT_DECISION_PARTICIPANTS_TOOLTIP);
fDecisionUsersListLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
List<String> participants = null;
if (null != R4EUIModelController.getActiveReview()) {
participants = R4EUIModelController.getActiveReview().getParticipantIDs();
} else {
participants = new ArrayList<String>();
}
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fDecisionUsersList = new EditableListWidget(widgetFactory, decisionSectionClient, textGridData, this, 2,
CCombo.class, participants.toArray(new String[participants.size()]));
fDecisionUsersList.setToolTipText(R4EUIConstants.REVIEW_EXIT_DECISION_PARTICIPANTS_TOOLTIP);
//Decision Time Spent
fDecisionTimeSpentLabel = widgetFactory.createCLabel(decisionSectionClient,
R4EUIConstants.DECISION_TIME_SPENT_LABEL);
fDecisionTimeSpentLabel.setToolTipText(R4EUIConstants.REVIEW_EXIT_DECISION_TIME_SPENT_TOOLTIP);
fDecisionTimeSpentLabel.setLayoutData(new GridData(GridData.BEGINNING, GridData.BEGINNING, false, false));
fDecisionTimeSpentText = widgetFactory.createText(decisionSectionClient, "");
textGridData = new GridData(GridData.FILL, GridData.FILL, true, false);
textGridData.horizontalSpan = 3;
fDecisionTimeSpentText.setToolTipText(R4EUIConstants.REVIEW_EXIT_DECISION_TIME_SPENT_TOOLTIP);
fDecisionTimeSpentText.setLayoutData(textGridData);
fDecisionTimeSpentText.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
if (!fRefreshInProgress) {
Integer timeSpent;
try {
timeSpent = Integer.valueOf(fDecisionTimeSpentText.getText());
} catch (NumberFormatException e1) {
//Set field to 0
timeSpent = 0;
}
try {
final String currentUser = R4EUIModelController.getReviewer();
final R4EReview modelReview = ((R4EUIReviewExtended) fProperties.getElement()).getReview();
final Long bookNum = R4EUIModelController.FResourceUpdater.checkOut(modelReview, currentUser);
modelReview.getDecision().setSpentTime(timeSpent.intValue());
R4EUIModelController.FResourceUpdater.checkIn(bookNum);
} catch (ResourceHandlingException e1) {
UIUtils.displayResourceErrorDialog(e1);
} catch (OutOfSyncException e1) {
UIUtils.displaySyncErrorDialog(e1);
}
}
}
public void focusGained(FocusEvent e) { // $codepro.audit.disable emptyMethod
//Nothing to do
}
});
}
|
diff --git a/src/java/plantgame/models/Store.java b/src/java/plantgame/models/Store.java
index 3a2deef..de95b6e 100644
--- a/src/java/plantgame/models/Store.java
+++ b/src/java/plantgame/models/Store.java
@@ -1,211 +1,211 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package plantgame.models;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
import plantgame.utils.Constants;
import plantgame.utils.GameItemsEnum;
/**
*
* @author tyler
*/
public class Store implements Runnable{
//StoreItem will be an internal class to Store that holds an item type
//and the number of that item which the store contains
private class StoreItem{
//numberOfItem: number of items in stock
public int numberOfItem;
public GameItemsEnum itemType;
public int maxNumberOfItem;
public StoreItem(GameItemsEnum e, int num){
// num: ITEM_NUMBER_STORE_START
numberOfItem = num;
itemType = e;
// maxNumberOfItem: MAX_NUMBER_OF_ITEM_IN_STORE
maxNumberOfItem = e.getMaxNumber();
}
}
//Private class extending TimerTask. This will be used by the addItemsToStoreTimer
//object to add items to the store.
private class StoreDeliver extends TimerTask{
public StoreDeliver(){
super();
}
@Override
public void run(){
for(GameItemsEnum item : GameItemsEnum.values()){
addItemToStore(item.getName(), Constants.NUMBER_OF_ITEM_TO_ADD_TO_STORE);
//DEBUG
System.out.println("Store:StoreDeliver adding "+item.getName());
}
}
}
private static Store store = null;
private HashMap<String, StoreItem> storeItems;
//The constructor creates the storeItems hashmap which can be used to
//look up a StoreItem object by its name
private Store(){
storeItems = new HashMap<String, StoreItem>();
for (GameItemsEnum item : GameItemsEnum.values()){
StoreItem newStoreItem = new StoreItem(item, Constants.ITEM_NUMBER_STORE_START);
storeItems.put(item.getName(), newStoreItem);
}
}
@Override
public void run(){
//DEBUG
System.out.println("Store creating thread for deliveries.");
//Create a timer object which will execute
Timer addItemsToStoreTimer = new Timer();
addItemsToStoreTimer.scheduleAtFixedRate(new StoreDeliver(), Constants.STORE_FIRST_DELIVERY_DELAY, Constants.STORE_INTER_DELIVERY_DELAY);
}
//Store will be a singleton since it will be shared among all players in the
//game
//This will also start the store thread
public static Store getInstance (){
//DEBUG
System.out.println("Store returning an instance of the store.");
if (store == null){
store = new Store();
//DEBUG
System.out.println("Store starting thread.");
//Start the thread
(new Thread(store)).start();
}
return store;
}
//method for adding items to store. Should be synchronized
public synchronized void addItemToStore(String itemName, int numberToAdd){
//DEBUG
System.out.println("Store adding "+numberToAdd+" "+itemName+" to the store.");
//First get the StoreItem
StoreItem item = storeItems.get(itemName);
//Add the numberToAdd items to the store's inventory
item.numberOfItem = item.numberOfItem+numberToAdd;
//Then determine if the store hold too many of that item
//and if so decrease the number to the max number that the store
//can hold
if (item.numberOfItem > item.maxNumberOfItem){
item.numberOfItem = item.maxNumberOfItem;
}
//DEBUG
System.out.println("Store now has "+item.numberOfItem+" of "+item.itemType.getName());
}
//Method for getting the number of items in stock for a particular item
public int getNumberOfItemInStock(String itemName){
return storeItems.get(itemName).numberOfItem;
//storeItems.get(itemName): return a StoreItem object
}
//method for removing items from store. Should be synchronized
//The actual purchasing of items will be done here
//since this method is synchronized
public synchronized String purchaseItems(int[] selectedItems, User user){
//DEBUG
System.out.println("Store User's name is "+user.getUserName());
//DEBUG
if (user.getItems() == null){
System.out.println("Store the User's items are null");
}
else{
for (GameItemsEnum item : GameItemsEnum.values()){
if (user.getItems().containsKey(item.getName()) ){
System.out.println("Store The user has "+item.getName());
}
else{
System.out.println("Store The user does not have "+item.getName());
}
}
}
int index = 0;
HashMap<String, StoreItem> storeItemsCopy = new HashMap<String,StoreItem>(this.storeItems);
HashMap<String, UserItem> userItemsCopy = new HashMap<String, UserItem>(user.getItems());
- int total = 0;
+ double total = 0;
StoreItem storeItem;
UserItem userItem;
//Check that there are enough items in the store
for (GameItemsEnum item: GameItemsEnum.values()){
- total = total+selectedItems[index]*this.getItemPrice(item.getName());
+ total = total+(double)selectedItems[index]*this.getItemPrice(item.getName());
if (this.getNumberOfItemInStock(item.getName()) < selectedItems[index]){
return Constants.NOT_ENOUGH_ITEMS_IN_STORE;
}
else{
//DEBUG
System.out.println("Store purchasing "+item.getName());
//Remove items from copy of store's items
storeItem = storeItemsCopy.get(item.getName());
storeItem.numberOfItem=storeItem.numberOfItem-selectedItems[index];
//Add items to copy of user's stock
userItem = userItemsCopy.get(item.getName());
userItem.setNumberOfItem(userItem.getNumberOfItem()+selectedItems[index]);
}
index++;
}
if (total > user.getMoney()){
return Constants.NOT_ENOUGH_MONEY;
}
//At this point it has been verified that the store has enough items and
//the user has enough money for the purchase
//Subtract user's money
user.setMoney(user.getMoney()-total);
//set store's stock to the copy of the store's stock
this.storeItems = storeItemsCopy;
//set user's stock to the copy of the user's stock
user.setItems(userItemsCopy);
return Constants.PURCHASE_COMPLETE;
}
//method for getting price of an item
public int getItemPrice(String itemName){
StoreItem s = storeItems.get(itemName);
return s.itemType.getPrice(s.numberOfItem);
}
//Convenience method for getting an item's price without having
//to actually get a store object
public static int getItemPriceStatic(String itemName){
Store s = Store.getInstance();
return s.getItemPrice(itemName);
}
}
| false | true | public synchronized String purchaseItems(int[] selectedItems, User user){
//DEBUG
System.out.println("Store User's name is "+user.getUserName());
//DEBUG
if (user.getItems() == null){
System.out.println("Store the User's items are null");
}
else{
for (GameItemsEnum item : GameItemsEnum.values()){
if (user.getItems().containsKey(item.getName()) ){
System.out.println("Store The user has "+item.getName());
}
else{
System.out.println("Store The user does not have "+item.getName());
}
}
}
int index = 0;
HashMap<String, StoreItem> storeItemsCopy = new HashMap<String,StoreItem>(this.storeItems);
HashMap<String, UserItem> userItemsCopy = new HashMap<String, UserItem>(user.getItems());
int total = 0;
StoreItem storeItem;
UserItem userItem;
//Check that there are enough items in the store
for (GameItemsEnum item: GameItemsEnum.values()){
total = total+selectedItems[index]*this.getItemPrice(item.getName());
if (this.getNumberOfItemInStock(item.getName()) < selectedItems[index]){
return Constants.NOT_ENOUGH_ITEMS_IN_STORE;
}
else{
//DEBUG
System.out.println("Store purchasing "+item.getName());
//Remove items from copy of store's items
storeItem = storeItemsCopy.get(item.getName());
storeItem.numberOfItem=storeItem.numberOfItem-selectedItems[index];
//Add items to copy of user's stock
userItem = userItemsCopy.get(item.getName());
userItem.setNumberOfItem(userItem.getNumberOfItem()+selectedItems[index]);
}
index++;
}
if (total > user.getMoney()){
return Constants.NOT_ENOUGH_MONEY;
}
//At this point it has been verified that the store has enough items and
//the user has enough money for the purchase
//Subtract user's money
user.setMoney(user.getMoney()-total);
//set store's stock to the copy of the store's stock
this.storeItems = storeItemsCopy;
//set user's stock to the copy of the user's stock
user.setItems(userItemsCopy);
return Constants.PURCHASE_COMPLETE;
}
| public synchronized String purchaseItems(int[] selectedItems, User user){
//DEBUG
System.out.println("Store User's name is "+user.getUserName());
//DEBUG
if (user.getItems() == null){
System.out.println("Store the User's items are null");
}
else{
for (GameItemsEnum item : GameItemsEnum.values()){
if (user.getItems().containsKey(item.getName()) ){
System.out.println("Store The user has "+item.getName());
}
else{
System.out.println("Store The user does not have "+item.getName());
}
}
}
int index = 0;
HashMap<String, StoreItem> storeItemsCopy = new HashMap<String,StoreItem>(this.storeItems);
HashMap<String, UserItem> userItemsCopy = new HashMap<String, UserItem>(user.getItems());
double total = 0;
StoreItem storeItem;
UserItem userItem;
//Check that there are enough items in the store
for (GameItemsEnum item: GameItemsEnum.values()){
total = total+(double)selectedItems[index]*this.getItemPrice(item.getName());
if (this.getNumberOfItemInStock(item.getName()) < selectedItems[index]){
return Constants.NOT_ENOUGH_ITEMS_IN_STORE;
}
else{
//DEBUG
System.out.println("Store purchasing "+item.getName());
//Remove items from copy of store's items
storeItem = storeItemsCopy.get(item.getName());
storeItem.numberOfItem=storeItem.numberOfItem-selectedItems[index];
//Add items to copy of user's stock
userItem = userItemsCopy.get(item.getName());
userItem.setNumberOfItem(userItem.getNumberOfItem()+selectedItems[index]);
}
index++;
}
if (total > user.getMoney()){
return Constants.NOT_ENOUGH_MONEY;
}
//At this point it has been verified that the store has enough items and
//the user has enough money for the purchase
//Subtract user's money
user.setMoney(user.getMoney()-total);
//set store's stock to the copy of the store's stock
this.storeItems = storeItemsCopy;
//set user's stock to the copy of the user's stock
user.setItems(userItemsCopy);
return Constants.PURCHASE_COMPLETE;
}
|
diff --git a/src/main/java/com/steamedpears/comp3004/models/Card.java b/src/main/java/com/steamedpears/comp3004/models/Card.java
index b000552..fa002c2 100644
--- a/src/main/java/com/steamedpears/comp3004/models/Card.java
+++ b/src/main/java/com/steamedpears/comp3004/models/Card.java
@@ -1,151 +1,151 @@
package com.steamedpears.comp3004.models;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.steamedpears.comp3004.SevenWonders;
import javax.swing.*;
import java.awt.Image;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.steamedpears.comp3004.models.Asset.*;
public class Card {
//constants/////////////////////////////////////////////////////
public static final String PLAYER_LEFT = "left";
public static final String PLAYER_RIGHT = "right";
public static final String PLAYER_SELF = "self";
public static final String PROP_CARD_NAME = "name";
public static final String PROP_CARD_COLOR = "guild";
public static final String PROP_CARD_IMAGE = "image";
public static final String PROP_CARD_COST = "cost";
public static final String PROP_CARD_MIN_PLAYERS = "players";
public static final String PROP_CARD_AGE = "age";
public static final String PROP_CARD_BASE_ASSETS = "baseAssets";
public static final String PROP_CARD_MULTIPLIER_ASSETS = "multiplierAssets";
public static final String PROP_CARD_MULTIPLIER_TARGETS = "multiplierTargets";
public static final String PROP_CARD_DISCOUNTS_ASSETS = "discountsAssets";
public static final String PROP_CARD_DISCOUNTS_TARGETS = "discountsTargets";
public static final String PROP_CARD_CHOICE = "isChoice";
public static final String PROP_CARD_FREE_FOR = "freeFor";
//static methods////////////////////////////////////////////////
public static List<Card> parseDeck(JsonArray deck){
List<Card> cards = new ArrayList<Card>();
for(JsonElement element: deck){
cards.add(new Card(element.getAsJsonObject()));
}
return cards;
}
public static List<List<Card>> generateRandomDeck(List<Card> cards, int numPlayers){
//TODO: implement this
return null;
}
//instance variables////////////////////////////////////////////
private String color;
private String name;
private Image image;
private int minPlayers;
private int age;
//The base amount of assets this card yields
private Map<String, Integer> baseAssets;
//If multiplierAssets is not null, multiply the values in baseAssets
//by the number of occurences of these assets in multiplierTargets (a combination of self, left, and right)
private Set<String> multiplierAssets;
private Set<String> multiplierTargets;
//The building the card is free to play for
private String freeFor;
//the cost of playing this card
private Map<String, Integer> cost;
//the resources this card makes discounted
private Set<String> discountsAssets;
//the players to which this card's discountsAssets applies to
private Set<String> discountsTargets;
//if true, the player may choose only *one* of the keys of baseAssets
private boolean isChoice;
private String id;
//constructor///////////////////////////////////////////////////
public Card(JsonObject obj){
this.name = obj.has(PROP_CARD_NAME) ? obj.getAsJsonPrimitive(PROP_CARD_NAME).getAsString() : "";
this.color = obj.has(PROP_CARD_COLOR) ? obj.getAsJsonPrimitive(PROP_CARD_COLOR).getAsString() : "";
this.cost = convertJSONToAssetMap(obj, PROP_CARD_COST);
this.minPlayers = obj.has(PROP_CARD_MIN_PLAYERS) ? obj.getAsJsonPrimitive(PROP_CARD_MIN_PLAYERS).getAsInt() : 0;
this.age = obj.has(PROP_CARD_AGE) ? obj.getAsJsonPrimitive(PROP_CARD_AGE).getAsInt() : 0;
+ this.id = this.getName().replace(" ","")+"_"+this.age+"_"+this.minPlayers;
this.image = new ImageIcon(SevenWonders.PATH_IMG+getId()+".png").getImage();
//figure out what this card actually does
this.baseAssets = convertJSONToAssetMap(obj,PROP_CARD_BASE_ASSETS);
this.multiplierAssets = convertJSArrayToSet(obj,PROP_CARD_MULTIPLIER_ASSETS);
this.multiplierTargets = convertJSArrayToSet(obj,PROP_CARD_MULTIPLIER_TARGETS);
this.discountsAssets = convertJSArrayToSet(obj,PROP_CARD_DISCOUNTS_ASSETS);
this.discountsTargets = convertJSArrayToSet(obj,PROP_CARD_DISCOUNTS_TARGETS);
this.isChoice = obj.has(PROP_CARD_CHOICE) && obj.getAsJsonPrimitive(PROP_CARD_CHOICE).getAsBoolean();
this.freeFor = obj.has(PROP_CARD_FREE_FOR) ? obj.getAsJsonPrimitive(PROP_CARD_FREE_FOR).getAsString() : "";
- this.id = this.getName().replace(" ","")+"_"+this.age+"_"+this.minPlayers;
}
//getters////////////////////////////////////////////////////////
public String getName(){
return name;
}
public String getColor(){
return color;
}
public Image getImage(){
return image;
}
public int getMinPlayers(){
return minPlayers;
}
public int getAge(){
return age;
}
public String getFreeFor(){
return freeFor;
}
public Map<String, Integer> getCost(){
return cost;
}
public Set<String> getDiscountsAssets(){
return discountsAssets;
}
public Set<String> getDiscountsTargets(){
return discountsTargets;
}
public Map<String, Integer> getAssets(Player player){
//TODO: compute the assets this card yields if played by this player
return null;
}
public Set<String> getAssetsOptional(Player player){
//TODO: compute the list of assets this card yields if it isChoice
return null;
}
public String getId(){
return this.id;
}
@Override
public int hashCode(){
return getId().hashCode();
}
}
| false | true | public Card(JsonObject obj){
this.name = obj.has(PROP_CARD_NAME) ? obj.getAsJsonPrimitive(PROP_CARD_NAME).getAsString() : "";
this.color = obj.has(PROP_CARD_COLOR) ? obj.getAsJsonPrimitive(PROP_CARD_COLOR).getAsString() : "";
this.cost = convertJSONToAssetMap(obj, PROP_CARD_COST);
this.minPlayers = obj.has(PROP_CARD_MIN_PLAYERS) ? obj.getAsJsonPrimitive(PROP_CARD_MIN_PLAYERS).getAsInt() : 0;
this.age = obj.has(PROP_CARD_AGE) ? obj.getAsJsonPrimitive(PROP_CARD_AGE).getAsInt() : 0;
this.image = new ImageIcon(SevenWonders.PATH_IMG+getId()+".png").getImage();
//figure out what this card actually does
this.baseAssets = convertJSONToAssetMap(obj,PROP_CARD_BASE_ASSETS);
this.multiplierAssets = convertJSArrayToSet(obj,PROP_CARD_MULTIPLIER_ASSETS);
this.multiplierTargets = convertJSArrayToSet(obj,PROP_CARD_MULTIPLIER_TARGETS);
this.discountsAssets = convertJSArrayToSet(obj,PROP_CARD_DISCOUNTS_ASSETS);
this.discountsTargets = convertJSArrayToSet(obj,PROP_CARD_DISCOUNTS_TARGETS);
this.isChoice = obj.has(PROP_CARD_CHOICE) && obj.getAsJsonPrimitive(PROP_CARD_CHOICE).getAsBoolean();
this.freeFor = obj.has(PROP_CARD_FREE_FOR) ? obj.getAsJsonPrimitive(PROP_CARD_FREE_FOR).getAsString() : "";
this.id = this.getName().replace(" ","")+"_"+this.age+"_"+this.minPlayers;
}
| public Card(JsonObject obj){
this.name = obj.has(PROP_CARD_NAME) ? obj.getAsJsonPrimitive(PROP_CARD_NAME).getAsString() : "";
this.color = obj.has(PROP_CARD_COLOR) ? obj.getAsJsonPrimitive(PROP_CARD_COLOR).getAsString() : "";
this.cost = convertJSONToAssetMap(obj, PROP_CARD_COST);
this.minPlayers = obj.has(PROP_CARD_MIN_PLAYERS) ? obj.getAsJsonPrimitive(PROP_CARD_MIN_PLAYERS).getAsInt() : 0;
this.age = obj.has(PROP_CARD_AGE) ? obj.getAsJsonPrimitive(PROP_CARD_AGE).getAsInt() : 0;
this.id = this.getName().replace(" ","")+"_"+this.age+"_"+this.minPlayers;
this.image = new ImageIcon(SevenWonders.PATH_IMG+getId()+".png").getImage();
//figure out what this card actually does
this.baseAssets = convertJSONToAssetMap(obj,PROP_CARD_BASE_ASSETS);
this.multiplierAssets = convertJSArrayToSet(obj,PROP_CARD_MULTIPLIER_ASSETS);
this.multiplierTargets = convertJSArrayToSet(obj,PROP_CARD_MULTIPLIER_TARGETS);
this.discountsAssets = convertJSArrayToSet(obj,PROP_CARD_DISCOUNTS_ASSETS);
this.discountsTargets = convertJSArrayToSet(obj,PROP_CARD_DISCOUNTS_TARGETS);
this.isChoice = obj.has(PROP_CARD_CHOICE) && obj.getAsJsonPrimitive(PROP_CARD_CHOICE).getAsBoolean();
this.freeFor = obj.has(PROP_CARD_FREE_FOR) ? obj.getAsJsonPrimitive(PROP_CARD_FREE_FOR).getAsString() : "";
}
|
diff --git a/solr/core/src/java/org/apache/solr/schema/IndexSchema.java b/solr/core/src/java/org/apache/solr/schema/IndexSchema.java
index 55276a2863..6f778cbd0f 100644
--- a/solr/core/src/java/org/apache/solr/schema/IndexSchema.java
+++ b/solr/core/src/java/org/apache/solr/schema/IndexSchema.java
@@ -1,1464 +1,1468 @@
/*
* 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.schema;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.AnalyzerWrapper;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.index.StorableField;
import org.apache.lucene.index.StoredDocument;
import org.apache.lucene.search.similarities.Similarity;
import org.apache.lucene.util.Version;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.request.LocalSolrQueryRequest;
import org.apache.solr.response.SchemaXmlWriter;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.util.DOMUtil;
import org.apache.solr.core.SolrConfig;
import org.apache.solr.core.Config;
import org.apache.solr.core.SolrResourceLoader;
import org.apache.solr.search.similarities.DefaultSimilarityFactory;
import org.apache.solr.util.plugin.SolrCoreAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Pattern;
/**
* <code>IndexSchema</code> contains information about the valid fields in an index
* and the types of those fields.
*
*
*/
public class IndexSchema {
public static final String COPY_FIELD = "copyField";
public static final String COPY_FIELDS = COPY_FIELD + "s";
public static final String DEFAULT_OPERATOR = "defaultOperator";
public static final String DEFAULT_SCHEMA_FILE = "schema.xml";
public static final String DEFAULT_SEARCH_FIELD = "defaultSearchField";
public static final String DESTINATION = "dest";
public static final String DYNAMIC_FIELD = "dynamicField";
public static final String DYNAMIC_FIELDS = DYNAMIC_FIELD + "s";
public static final String FIELD = "field";
public static final String FIELDS = FIELD + "s";
public static final String FIELD_TYPE = "fieldType";
public static final String FIELD_TYPES = FIELD_TYPE + "s";
public static final String INTERNAL_POLY_FIELD_PREFIX = "*" + FieldType.POLY_FIELD_SEPARATOR;
public static final String LUCENE_MATCH_VERSION_PARAM = "luceneMatchVersion";
public static final String NAME = "name";
public static final String REQUIRED = "required";
public static final String SCHEMA = "schema";
public static final String SIMILARITY = "similarity";
public static final String SLASH = "/";
public static final String SOLR_QUERY_PARSER = "solrQueryParser";
public static final String SOURCE = "source";
public static final String TYPE = "type";
public static final String TYPES = "types";
public static final String UNIQUE_KEY = "uniqueKey";
public static final String VERSION = "version";
private static final String AT = "@";
private static final String DESTINATION_DYNAMIC_BASE = "destDynamicBase";
private static final String MAX_CHARS = "maxChars";
private static final String SOURCE_DYNAMIC_BASE = "sourceDynamicBase";
private static final String SOURCE_EXPLICIT_FIELDS = "sourceExplicitFields";
private static final String TEXT_FUNCTION = "text()";
private static final String XPATH_OR = " | ";
final static Logger log = LoggerFactory.getLogger(IndexSchema.class);
protected final SolrConfig solrConfig;
protected String resourceName;
protected String name;
protected float version;
protected final SolrResourceLoader loader;
protected Map<String,SchemaField> fields = new HashMap<String,SchemaField>();
protected Map<String,FieldType> fieldTypes = new HashMap<String,FieldType>();
protected List<SchemaField> fieldsWithDefaultValue = new ArrayList<SchemaField>();
protected Collection<SchemaField> requiredFields = new HashSet<SchemaField>();
protected volatile DynamicField[] dynamicFields;
public DynamicField[] getDynamicFields() { return dynamicFields; }
private Analyzer analyzer;
private Analyzer queryAnalyzer;
protected List<SchemaAware> schemaAware = new ArrayList<SchemaAware>();
protected String defaultSearchFieldName=null;
protected String queryParserDefaultOperator = "OR";
protected boolean isExplicitQueryParserDefaultOperator = false;
protected Map<String, List<CopyField>> copyFieldsMap = new HashMap<String, List<CopyField>>();
public Map<String,List<CopyField>> getCopyFieldsMap() { return Collections.unmodifiableMap(copyFieldsMap); }
protected DynamicCopy[] dynamicCopyFields;
public DynamicCopy[] getDynamicCopyFields() { return dynamicCopyFields; }
/**
* keys are all fields copied to, count is num of copyField
* directives that target them.
*/
protected Map<SchemaField, Integer> copyFieldTargetCounts = new HashMap<SchemaField, Integer>();
/**
* Constructs a schema using the specified resource name and stream.
* @see SolrResourceLoader#openSchema
* By default, this follows the normal config path directory searching rules.
* @see SolrResourceLoader#openResource
*/
public IndexSchema(SolrConfig solrConfig, String name, InputSource is) {
assert null != solrConfig : "SolrConfig should never be null";
assert null != name : "schema resource name should never be null";
assert null != is : "schema InputSource should never be null";
this.solrConfig = solrConfig;
this.resourceName = name;
loader = solrConfig.getResourceLoader();
try {
readSchema(is);
loader.inform(loader);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* @since solr 1.4
*/
public SolrResourceLoader getResourceLoader() {
return loader;
}
/** Gets the name of the resource used to instantiate this schema. */
public String getResourceName() {
return resourceName;
}
/** Sets the name of the resource used to instantiate this schema. */
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
/** Gets the name of the schema as specified in the schema resource. */
public String getSchemaName() {
return name;
}
/** The Default Lucene Match Version for this IndexSchema */
public Version getDefaultLuceneMatchVersion() {
return solrConfig.luceneMatchVersion;
}
public float getVersion() {
return version;
}
/**
* Provides direct access to the Map containing all explicit
* (ie: non-dynamic) fields in the index, keyed on field name.
*
* <p>
* Modifying this Map (or any item in it) will affect the real schema
* </p>
*
* <p>
* NOTE: this function is not thread safe. However, it is safe to use within the standard
* <code>inform( SolrCore core )</code> function for <code>SolrCoreAware</code> classes.
* Outside <code>inform</code>, this could potentially throw a ConcurrentModificationException
* </p>
*/
public Map<String,SchemaField> getFields() { return fields; }
/**
* Provides direct access to the Map containing all Field Types
* in the index, keyed on field type name.
*
* <p>
* Modifying this Map (or any item in it) will affect the real schema. However if you
* make any modifications, be sure to call {@link IndexSchema#refreshAnalyzers()} to
* update the Analyzers for the registered fields.
* </p>
*
* <p>
* NOTE: this function is not thread safe. However, it is safe to use within the standard
* <code>inform( SolrCore core )</code> function for <code>SolrCoreAware</code> classes.
* Outside <code>inform</code>, this could potentially throw a ConcurrentModificationException
* </p>
*/
public Map<String,FieldType> getFieldTypes() { return fieldTypes; }
/**
* Provides direct access to the List containing all fields with a default value
*/
public List<SchemaField> getFieldsWithDefaultValue() { return fieldsWithDefaultValue; }
/**
* Provides direct access to the List containing all required fields. This
* list contains all fields with default values.
*/
public Collection<SchemaField> getRequiredFields() { return requiredFields; }
protected Similarity similarity;
/**
* Returns the Similarity used for this index
*/
public Similarity getSimilarity() {
if (null == similarity) {
similarity = similarityFactory.getSimilarity();
}
return similarity;
}
protected SimilarityFactory similarityFactory;
protected boolean isExplicitSimilarity = false;
/** Returns the SimilarityFactory that constructed the Similarity for this index */
public SimilarityFactory getSimilarityFactory() { return similarityFactory; }
/**
* Returns the Analyzer used when indexing documents for this index
*
* <p>
* This Analyzer is field (and dynamic field) name aware, and delegates to
* a field specific Analyzer based on the field type.
* </p>
*/
public Analyzer getAnalyzer() { return analyzer; }
/**
* Returns the Analyzer used when searching this index
*
* <p>
* This Analyzer is field (and dynamic field) name aware, and delegates to
* a field specific Analyzer based on the field type.
* </p>
*/
public Analyzer getQueryAnalyzer() { return queryAnalyzer; }
/**
* Name of the default search field specified in the schema file.
* <br/><b>Note:</b>Avoid calling this, try to use this method so that the 'df' param is consulted as an override:
* {@link org.apache.solr.search.QueryParsing#getDefaultField(IndexSchema, String)}
*/
public String getDefaultSearchFieldName() {
return defaultSearchFieldName;
}
/**
* default operator ("AND" or "OR") for QueryParser
*/
public String getQueryParserDefaultOperator() {
return queryParserDefaultOperator;
}
protected SchemaField uniqueKeyField;
/**
* Unique Key field specified in the schema file
* @return null if this schema has no unique key field
*/
public SchemaField getUniqueKeyField() { return uniqueKeyField; }
private String uniqueKeyFieldName;
private FieldType uniqueKeyFieldType;
/**
* The raw (field type encoded) value of the Unique Key field for
* the specified Document
* @return null if this schema has no unique key field
* @see #printableUniqueKey
*/
public IndexableField getUniqueKeyField(org.apache.lucene.document.Document doc) {
return doc.getField(uniqueKeyFieldName); // this should return null if name is null
}
/**
* The printable value of the Unique Key field for
* the specified Document
* @return null if this schema has no unique key field
*/
public String printableUniqueKey(StoredDocument doc) {
StorableField f = doc.getField(uniqueKeyFieldName);
return f==null ? null : uniqueKeyFieldType.toExternal(f);
}
private SchemaField getIndexedField(String fname) {
SchemaField f = getFields().get(fname);
if (f==null) {
throw new RuntimeException("unknown field '" + fname + "'");
}
if (!f.indexed()) {
throw new RuntimeException("'"+fname+"' is not an indexed field:" + f);
}
return f;
}
/**
* This will re-create the Analyzers. If you make any modifications to
* the Field map ({@link IndexSchema#getFields()}, this function is required
* to synch the internally cached field analyzers.
*
* @since solr 1.3
*/
public void refreshAnalyzers() {
analyzer = new SolrIndexAnalyzer();
queryAnalyzer = new SolrQueryAnalyzer();
}
/**
* Writes the schema in schema.xml format to the given writer
*/
void persist(Writer writer) throws IOException {
final SolrQueryResponse response = new SolrQueryResponse();
response.add(IndexSchema.SCHEMA, getNamedPropertyValues());
final NamedList args = new NamedList(Arrays.<Object>asList("indent", "on"));
final LocalSolrQueryRequest req = new LocalSolrQueryRequest(null, args);
final SchemaXmlWriter schemaXmlWriter = new SchemaXmlWriter(writer, req, response);
schemaXmlWriter.setEmitManagedSchemaDoNotEditWarning(true);
schemaXmlWriter.writeResponse();
schemaXmlWriter.close();
}
public boolean isMutable() {
return false;
}
private class SolrIndexAnalyzer extends AnalyzerWrapper {
protected final HashMap<String, Analyzer> analyzers;
SolrIndexAnalyzer() {
analyzers = analyzerCache();
}
protected HashMap<String, Analyzer> analyzerCache() {
HashMap<String, Analyzer> cache = new HashMap<String, Analyzer>();
for (SchemaField f : getFields().values()) {
Analyzer analyzer = f.getType().getAnalyzer();
cache.put(f.getName(), analyzer);
}
return cache;
}
@Override
protected Analyzer getWrappedAnalyzer(String fieldName) {
Analyzer analyzer = analyzers.get(fieldName);
return analyzer != null ? analyzer : getDynamicFieldType(fieldName).getAnalyzer();
}
@Override
protected TokenStreamComponents wrapComponents(String fieldName, TokenStreamComponents components) {
return components;
}
}
private class SolrQueryAnalyzer extends SolrIndexAnalyzer {
@Override
protected HashMap<String, Analyzer> analyzerCache() {
HashMap<String, Analyzer> cache = new HashMap<String, Analyzer>();
for (SchemaField f : getFields().values()) {
Analyzer analyzer = f.getType().getQueryAnalyzer();
cache.put(f.getName(), analyzer);
}
return cache;
}
@Override
protected Analyzer getWrappedAnalyzer(String fieldName) {
Analyzer analyzer = analyzers.get(fieldName);
return analyzer != null ? analyzer : getDynamicFieldType(fieldName).getQueryAnalyzer();
}
}
protected void readSchema(InputSource is) {
log.info("Reading Solr Schema from " + resourceName);
try {
// pass the config resource loader to avoid building an empty one for no reason:
// in the current case though, the stream is valid so we wont load the resource by name
Config schemaConf = new Config(loader, SCHEMA, is, SLASH+SCHEMA+SLASH);
Document document = schemaConf.getDocument();
final XPath xpath = schemaConf.getXPath();
String expression = stepsToPath(SCHEMA, AT + NAME);
Node nd = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
StringBuilder sb = new StringBuilder();
+ // Another case where the initialization from the test harness is different than the "real world"
sb.append("[");
- sb.append(loader.getCoreProperties().getProperty(NAME));
- sb.append("] ");
+ if (loader.getCoreProperties() != null) {
+ sb.append(loader.getCoreProperties().getProperty(NAME));
+ } else {
+ sb.append("null");
+ }
if (nd==null) {
sb.append("schema has no name!");
log.warn(sb.toString());
} else {
name = nd.getNodeValue();
sb.append("Schema ");
sb.append(NAME);
sb.append("=");
sb.append(name);
log.info(sb.toString());
}
// /schema/@version
expression = stepsToPath(SCHEMA, AT + VERSION);
version = schemaConf.getFloat(expression, 1.0f);
// load the Field Types
final FieldTypePluginLoader typeLoader = new FieldTypePluginLoader(this, fieldTypes, schemaAware);
// /schema/types/fieldtype | /schema/types/fieldType
expression = stepsToPath(SCHEMA, TYPES, FIELD_TYPE.toLowerCase(Locale.ROOT)) // backcompat(?)
+ XPATH_OR + stepsToPath(SCHEMA, TYPES, FIELD_TYPE);
NodeList nodes = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);
typeLoader.load(loader, nodes);
// load the fields
Map<String,Boolean> explicitRequiredProp = loadFields(document, xpath);
expression = stepsToPath(SCHEMA, SIMILARITY); // /schema/similarity
Node node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
similarityFactory = readSimilarity(loader, node);
if (similarityFactory == null) {
similarityFactory = new DefaultSimilarityFactory();
} else {
isExplicitSimilarity = true;
}
if ( ! (similarityFactory instanceof SolrCoreAware)) {
// if the sim factory isn't SolrCoreAware (and hence schema aware),
// then we are responsible for erroring if a field type is trying to specify a sim.
for (FieldType ft : fieldTypes.values()) {
if (null != ft.getSimilarity()) {
String msg = "FieldType '" + ft.getTypeName()
+ "' is configured with a similarity, but the global similarity does not support it: "
+ similarityFactory.getClass();
log.error(msg);
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
}
}
// /schema/defaultSearchField/@text()
expression = stepsToPath(SCHEMA, DEFAULT_SEARCH_FIELD, TEXT_FUNCTION);
node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
if (node==null) {
log.debug("no default search field specified in schema.");
} else {
defaultSearchFieldName=node.getNodeValue().trim();
// throw exception if specified, but not found or not indexed
if (defaultSearchFieldName!=null) {
SchemaField defaultSearchField = getFields().get(defaultSearchFieldName);
if ((defaultSearchField == null) || !defaultSearchField.indexed()) {
String msg = "default search field '" + defaultSearchFieldName + "' not defined or not indexed" ;
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
}
log.info("default search field in schema is "+defaultSearchFieldName);
}
// /schema/solrQueryParser/@defaultOperator
expression = stepsToPath(SCHEMA, SOLR_QUERY_PARSER, AT + DEFAULT_OPERATOR);
node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
if (node==null) {
log.debug("using default query parser operator (OR)");
} else {
isExplicitQueryParserDefaultOperator = true;
queryParserDefaultOperator=node.getNodeValue().trim();
log.info("query parser default operator is "+queryParserDefaultOperator);
}
// /schema/uniqueKey/text()
expression = stepsToPath(SCHEMA, UNIQUE_KEY, TEXT_FUNCTION);
node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
if (node==null) {
log.warn("no " + UNIQUE_KEY + " specified in schema.");
} else {
uniqueKeyField=getIndexedField(node.getNodeValue().trim());
if (null != uniqueKeyField.getDefaultValue()) {
String msg = UNIQUE_KEY + " field ("+uniqueKeyFieldName+
") can not be configured with a default value ("+
uniqueKeyField.getDefaultValue()+")";
log.error(msg);
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
if (!uniqueKeyField.stored()) {
log.warn(UNIQUE_KEY + " is not stored - distributed search and MoreLikeThis will not work");
}
if (uniqueKeyField.multiValued()) {
String msg = UNIQUE_KEY + " field ("+uniqueKeyFieldName+
") can not be configured to be multivalued";
log.error(msg);
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
uniqueKeyFieldName=uniqueKeyField.getName();
uniqueKeyFieldType=uniqueKeyField.getType();
log.info("unique key field: "+uniqueKeyFieldName);
// Unless the uniqueKeyField is marked 'required=false' then make sure it exists
if( Boolean.FALSE != explicitRequiredProp.get( uniqueKeyFieldName ) ) {
uniqueKeyField.required = true;
requiredFields.add(uniqueKeyField);
}
}
/////////////// parse out copyField commands ///////////////
// Map<String,ArrayList<SchemaField>> cfields = new HashMap<String,ArrayList<SchemaField>>();
// expression = "/schema/copyField";
dynamicCopyFields = new DynamicCopy[] {};
expression = "//" + COPY_FIELD;
nodes = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);
for (int i=0; i<nodes.getLength(); i++) {
node = nodes.item(i);
NamedNodeMap attrs = node.getAttributes();
String source = DOMUtil.getAttr(attrs, SOURCE, COPY_FIELD + " definition");
String dest = DOMUtil.getAttr(attrs, DESTINATION, COPY_FIELD + " definition");
String maxChars = DOMUtil.getAttr(attrs, MAX_CHARS);
int maxCharsInt = CopyField.UNLIMITED;
if (maxChars != null) {
try {
maxCharsInt = Integer.parseInt(maxChars);
} catch (NumberFormatException e) {
log.warn("Couldn't parse " + MAX_CHARS + " attribute for " + COPY_FIELD + " from "
+ source + " to " + dest + " as integer. The whole field will be copied.");
}
}
if (dest.equals(uniqueKeyFieldName)) {
String msg = UNIQUE_KEY + " field ("+uniqueKeyFieldName+
") can not be the " + DESTINATION + " of a " + COPY_FIELD + "(" + SOURCE + "=" +source+")";
log.error(msg);
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
registerCopyField(source, dest, maxCharsInt);
}
for (Map.Entry<SchemaField, Integer> entry : copyFieldTargetCounts.entrySet()) {
if (entry.getValue() > 1 && !entry.getKey().multiValued()) {
log.warn("Field " + entry.getKey().name + " is not multivalued "+
"and destination for multiple " + COPY_FIELDS + " ("+
entry.getValue()+")");
}
}
//Run the callbacks on SchemaAware now that everything else is done
for (SchemaAware aware : schemaAware) {
aware.inform(this);
}
} catch (SolrException e) {
throw e;
} catch(Exception e) {
// unexpected exception...
throw new SolrException(ErrorCode.SERVER_ERROR, "Schema Parsing Failed: " + e.getMessage(), e);
}
// create the field analyzers
refreshAnalyzers();
}
/**
* Loads fields and dynamic fields.
*
* @return a map from field name to explicit required value
*/
protected synchronized Map<String,Boolean> loadFields(Document document, XPath xpath) throws XPathExpressionException {
// Hang on to the fields that say if they are required -- this lets us set a reasonable default for the unique key
Map<String,Boolean> explicitRequiredProp = new HashMap<String,Boolean>();
ArrayList<DynamicField> dFields = new ArrayList<DynamicField>();
// /schema/fields/field | /schema/fields/dynamicField
String expression = stepsToPath(SCHEMA, FIELDS, FIELD)
+ XPATH_OR + stepsToPath(SCHEMA, FIELDS, DYNAMIC_FIELD);
NodeList nodes = (NodeList)xpath.evaluate(expression, document, XPathConstants.NODESET);
for (int i=0; i<nodes.getLength(); i++) {
Node node = nodes.item(i);
NamedNodeMap attrs = node.getAttributes();
String name = DOMUtil.getAttr(attrs, NAME, "field definition");
log.trace("reading field def "+name);
String type = DOMUtil.getAttr(attrs, TYPE, "field " + name);
FieldType ft = fieldTypes.get(type);
if (ft==null) {
throw new SolrException
(ErrorCode.BAD_REQUEST, "Unknown " + FIELD_TYPE + " '" + type + "' specified on field " + name);
}
Map<String,String> args = DOMUtil.toMapExcept(attrs, NAME, TYPE);
if (null != args.get(REQUIRED)) {
explicitRequiredProp.put(name, Boolean.valueOf(args.get(REQUIRED)));
}
SchemaField f = SchemaField.create(name,ft,args);
if (node.getNodeName().equals(FIELD)) {
SchemaField old = fields.put(f.getName(),f);
if( old != null ) {
String msg = "[schema.xml] Duplicate field definition for '"
+ f.getName() + "' [[["+old.toString()+"]]] and [[["+f.toString()+"]]]";
throw new SolrException(ErrorCode.SERVER_ERROR, msg );
}
log.debug("field defined: " + f);
if( f.getDefaultValue() != null ) {
log.debug(name+" contains default value: " + f.getDefaultValue());
fieldsWithDefaultValue.add( f );
}
if (f.isRequired()) {
log.debug(name+" is required in this schema");
requiredFields.add(f);
}
} else if (node.getNodeName().equals(DYNAMIC_FIELD)) {
if (isValidFieldGlob(name)) {
// make sure nothing else has the same path
addDynamicField(dFields, f);
} else {
String msg = "Dynamic field name '" + name
+ "' should have either a leading or a trailing asterisk, and no others.";
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
} else {
// we should never get here
throw new RuntimeException("Unknown field type");
}
}
//fields with default values are by definition required
//add them to required fields, and we only have to loop once
// in DocumentBuilder.getDoc()
requiredFields.addAll(fieldsWithDefaultValue);
// OK, now sort the dynamic fields largest to smallest size so we don't get
// any false matches. We want to act like a compiler tool and try and match
// the largest string possible.
Collections.sort(dFields);
log.trace("Dynamic Field Ordering:" + dFields);
// stuff it in a normal array for faster access
dynamicFields = dFields.toArray(new DynamicField[dFields.size()]);
return explicitRequiredProp;
}
/**
* Converts a sequence of path steps into a rooted path, by inserting slashes in front of each step.
* @param steps The steps to join with slashes to form a path
* @return a rooted path: a leading slash followed by the given steps joined with slashes
*/
private String stepsToPath(String... steps) {
StringBuilder builder = new StringBuilder();
for (String step : steps) { builder.append(SLASH).append(step); }
return builder.toString();
}
/** Returns true if the given name has exactly one asterisk either at the start or end of the name */
private static boolean isValidFieldGlob(String name) {
if (name.startsWith("*") || name.endsWith("*")) {
int count = 0;
for (int pos = 0 ; pos < name.length() && -1 != (pos = name.indexOf('*', pos)) ; ++pos) ++count;
if (1 == count) return true;
}
return false;
}
private void addDynamicField(List<DynamicField> dFields, SchemaField f) {
if (isDuplicateDynField(dFields, f)) {
String msg = "[schema.xml] Duplicate DynamicField definition for '" + f.getName() + "'";
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
} else {
addDynamicFieldNoDupCheck(dFields, f);
}
}
/**
* Register one or more new Dynamic Fields with the Schema.
* @param fields The sequence of {@link org.apache.solr.schema.SchemaField}
*/
public void registerDynamicFields(SchemaField... fields) {
List<DynamicField> dynFields = new ArrayList<DynamicField>(Arrays.asList(dynamicFields));
for (SchemaField field : fields) {
if (isDuplicateDynField(dynFields, field)) {
log.debug("dynamic field already exists: dynamic field: [" + field.getName() + "]");
} else {
log.debug("dynamic field creation for schema field: " + field.getName());
addDynamicFieldNoDupCheck(dynFields, field);
}
}
Collections.sort(dynFields);
dynamicFields = dynFields.toArray(new DynamicField[dynFields.size()]);
}
private void addDynamicFieldNoDupCheck(List<DynamicField> dFields, SchemaField f) {
dFields.add(new DynamicField(f));
log.debug("dynamic field defined: " + f);
}
private boolean isDuplicateDynField(List<DynamicField> dFields, SchemaField f) {
for (DynamicField df : dFields) {
if (df.getRegex().equals(f.name)) return true;
}
return false;
}
public void registerCopyField( String source, String dest ) {
registerCopyField(source, dest, CopyField.UNLIMITED);
}
/**
* <p>
* NOTE: this function is not thread safe. However, it is safe to use within the standard
* <code>inform( SolrCore core )</code> function for <code>SolrCoreAware</code> classes.
* Outside <code>inform</code>, this could potentially throw a ConcurrentModificationException
* </p>
*
* @see SolrCoreAware
*/
public void registerCopyField(String source, String dest, int maxChars) {
log.debug(COPY_FIELD + " " + SOURCE + "='" + source + "' " + DESTINATION + "='" + dest
+ "' " + MAX_CHARS + "=" + maxChars);
DynamicField destDynamicField = null;
SchemaField destSchemaField = fields.get(dest);
SchemaField sourceSchemaField = fields.get(source);
DynamicField sourceDynamicBase = null;
DynamicField destDynamicBase = null;
boolean sourceIsDynamicFieldReference = false;
boolean sourceIsExplicitFieldGlob = false;
final String invalidGlobMessage = "is an invalid glob: either it contains more than one asterisk,"
+ " or the asterisk occurs neither at the start nor at the end.";
final boolean sourceIsGlob = isValidFieldGlob(source);
if (source.contains("*") && ! sourceIsGlob) {
String msg = "copyField source :'" + source + "' " + invalidGlobMessage;
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
if (dest.contains("*") && ! isValidFieldGlob(dest)) {
String msg = "copyField dest :'" + dest + "' " + invalidGlobMessage;
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
if (null == sourceSchemaField && sourceIsGlob) {
Pattern pattern = Pattern.compile(source.replace("*", ".*")); // glob->regex
for (String field : fields.keySet()) {
if (pattern.matcher(field).matches()) {
sourceIsExplicitFieldGlob = true;
break;
}
}
}
if (null == destSchemaField || (null == sourceSchemaField && ! sourceIsExplicitFieldGlob)) {
// Go through dynamicFields array only once, collecting info for both source and dest fields, if needed
for (DynamicField dynamicField : dynamicFields) {
if (null == sourceSchemaField && ! sourceIsDynamicFieldReference && ! sourceIsExplicitFieldGlob) {
if (dynamicField.matches(source)) {
sourceIsDynamicFieldReference = true;
if ( ! source.equals(dynamicField.getRegex())) {
sourceDynamicBase = dynamicField;
}
}
}
if (null == destSchemaField) {
if (dest.equals(dynamicField.getRegex())) {
destDynamicField = dynamicField;
destSchemaField = dynamicField.prototype;
} else if (dynamicField.matches(dest)) {
destSchemaField = dynamicField.makeSchemaField(dest);
destDynamicField = new DynamicField(destSchemaField);
destDynamicBase = dynamicField;
}
}
if (null != destSchemaField
&& (null != sourceSchemaField || sourceIsDynamicFieldReference || sourceIsExplicitFieldGlob)) {
break;
}
}
}
if (null == sourceSchemaField && ! sourceIsGlob && ! sourceIsDynamicFieldReference) {
String msg = "copyField source :'" + source + "' is not a glob and doesn't match any explicit field or dynamicField.";
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
if (null == destSchemaField) {
String msg = "copyField dest :'" + dest + "' is not an explicit field and doesn't match a dynamicField.";
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
if (sourceIsDynamicFieldReference || sourceIsGlob) {
if (null != destDynamicField) { // source: glob or no-asterisk dynamic field ref; dest: dynamic field ref
registerDynamicCopyField(new DynamicCopy(source, destDynamicField, maxChars, sourceDynamicBase, destDynamicBase));
incrementCopyFieldTargetCount(destSchemaField);
} else { // source: glob or no-asterisk dynamic field ref; dest: explicit field
destDynamicField = new DynamicField(destSchemaField);
registerDynamicCopyField(new DynamicCopy(source, destDynamicField, maxChars, sourceDynamicBase, null));
incrementCopyFieldTargetCount(destSchemaField);
}
} else {
if (null != destDynamicField) { // source: explicit field; dest: dynamic field reference
if (destDynamicField.pattern instanceof DynamicReplacement.DynamicPattern.NameEquals) {
// Dynamic dest with no asterisk is acceptable
registerDynamicCopyField(new DynamicCopy(source, destDynamicField, maxChars, sourceDynamicBase, destDynamicBase));
incrementCopyFieldTargetCount(destSchemaField);
} else {
String msg = "copyField only supports a dynamic destination with an asterisk "
+ "if the source also has an asterisk";
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
} else { // source & dest: explicit fields
List<CopyField> copyFieldList = copyFieldsMap.get(source);
if (copyFieldList == null) {
copyFieldList = new ArrayList<CopyField>();
copyFieldsMap.put(source, copyFieldList);
}
copyFieldList.add(new CopyField(sourceSchemaField, destSchemaField, maxChars));
incrementCopyFieldTargetCount(destSchemaField);
}
}
}
private void incrementCopyFieldTargetCount(SchemaField dest) {
copyFieldTargetCounts.put(dest, copyFieldTargetCounts.containsKey(dest) ? copyFieldTargetCounts.get(dest) + 1 : 1);
}
private void registerDynamicCopyField( DynamicCopy dcopy ) {
if( dynamicCopyFields == null ) {
dynamicCopyFields = new DynamicCopy[] {dcopy};
}
else {
DynamicCopy[] temp = new DynamicCopy[dynamicCopyFields.length+1];
System.arraycopy(dynamicCopyFields,0,temp,0,dynamicCopyFields.length);
temp[temp.length -1] = dcopy;
dynamicCopyFields = temp;
}
log.trace("Dynamic Copy Field:" + dcopy);
}
static SimilarityFactory readSimilarity(SolrResourceLoader loader, Node node) {
if (node==null) {
return null;
} else {
SimilarityFactory similarityFactory;
final String classArg = ((Element) node).getAttribute(SimilarityFactory.CLASS_NAME);
final Object obj = loader.newInstance(classArg, Object.class, "search.similarities.");
if (obj instanceof SimilarityFactory) {
// configure a factory, get a similarity back
final NamedList<Object> namedList = DOMUtil.childNodesToNamedList(node);
namedList.add(SimilarityFactory.CLASS_NAME, classArg);
SolrParams params = SolrParams.toSolrParams(namedList);
similarityFactory = (SimilarityFactory)obj;
similarityFactory.init(params);
} else {
// just like always, assume it's a Similarity and get a ClassCastException - reasonable error handling
similarityFactory = new SimilarityFactory() {
@Override
public Similarity getSimilarity() {
return (Similarity) obj;
}
};
}
return similarityFactory;
}
}
public static abstract class DynamicReplacement implements Comparable<DynamicReplacement> {
abstract protected static class DynamicPattern {
protected final String regex;
protected final String fixedStr;
protected DynamicPattern(String regex, String fixedStr) { this.regex = regex; this.fixedStr = fixedStr; }
static DynamicPattern createPattern(String regex) {
if (regex.startsWith("*")) { return new NameEndsWith(regex); }
else if (regex.endsWith("*")) { return new NameStartsWith(regex); }
else { return new NameEquals(regex);
}
}
/** Returns true if the given name matches this pattern */
abstract boolean matches(String name);
/** Returns the remainder of the given name after removing this pattern's fixed string component */
abstract String remainder(String name);
/** Returns the result of combining this pattern's fixed string component with the given replacement */
abstract String subst(String replacement);
/** Returns the length of the original regex, including the asterisk, if any. */
public int length() { return regex.length(); }
private static class NameStartsWith extends DynamicPattern {
NameStartsWith(String regex) { super(regex, regex.substring(0, regex.length() - 1)); }
boolean matches(String name) { return name.startsWith(fixedStr); }
String remainder(String name) { return name.substring(fixedStr.length()); }
String subst(String replacement) { return fixedStr + replacement; }
}
private static class NameEndsWith extends DynamicPattern {
NameEndsWith(String regex) { super(regex, regex.substring(1)); }
boolean matches(String name) { return name.endsWith(fixedStr); }
String remainder(String name) { return name.substring(0, name.length() - fixedStr.length()); }
String subst(String replacement) { return replacement + fixedStr; }
}
private static class NameEquals extends DynamicPattern {
NameEquals(String regex) { super(regex, regex); }
boolean matches(String name) { return regex.equals(name); }
String remainder(String name) { return ""; }
String subst(String replacement) { return fixedStr; }
}
}
protected DynamicPattern pattern;
public boolean matches(String name) { return pattern.matches(name); }
protected DynamicReplacement(String regex) {
pattern = DynamicPattern.createPattern(regex);
}
/**
* Sort order is based on length of regex. Longest comes first.
* @param other The object to compare to.
* @return a negative integer, zero, or a positive integer
* as this object is less than, equal to, or greater than
* the specified object.
*/
@Override
public int compareTo(DynamicReplacement other) {
return other.pattern.length() - pattern.length();
}
/** Returns the regex used to create this instance's pattern */
public String getRegex() {
return pattern.regex;
}
}
public final static class DynamicField extends DynamicReplacement {
private final SchemaField prototype;
public SchemaField getPrototype() { return prototype; }
DynamicField(SchemaField prototype) {
super(prototype.name);
this.prototype=prototype;
}
SchemaField makeSchemaField(String name) {
// could have a cache instead of returning a new one each time, but it might
// not be worth it.
// Actually, a higher level cache could be worth it to avoid too many
// .startsWith() and .endsWith() comparisons. it depends on how many
// dynamic fields there are.
return new SchemaField(prototype, name);
}
@Override
public String toString() {
return prototype.toString();
}
}
public static class DynamicCopy extends DynamicReplacement {
private final DynamicField destination;
private final int maxChars;
public int getMaxChars() { return maxChars; }
final DynamicField sourceDynamicBase;
public DynamicField getSourceDynamicBase() { return sourceDynamicBase; }
final DynamicField destDynamicBase;
public DynamicField getDestDynamicBase() { return destDynamicBase; }
DynamicCopy(String sourceRegex, DynamicField destination, int maxChars,
DynamicField sourceDynamicBase, DynamicField destDynamicBase) {
super(sourceRegex);
this.destination = destination;
this.maxChars = maxChars;
this.sourceDynamicBase = sourceDynamicBase;
this.destDynamicBase = destDynamicBase;
}
public String getDestFieldName() { return destination.getRegex(); }
/**
* Generates a destination field name based on this source pattern,
* by substituting the remainder of this source pattern into the
* the given destination pattern.
*/
public SchemaField getTargetField(String sourceField) {
String remainder = pattern.remainder(sourceField);
String targetFieldName = destination.pattern.subst(remainder);
return destination.makeSchemaField(targetFieldName);
}
@Override
public String toString() {
return destination.prototype.toString();
}
}
public SchemaField[] getDynamicFieldPrototypes() {
SchemaField[] df = new SchemaField[dynamicFields.length];
for (int i=0;i<dynamicFields.length;i++) {
df[i] = dynamicFields[i].prototype;
}
return df;
}
public String getDynamicPattern(String fieldName) {
for (DynamicField df : dynamicFields) {
if (df.matches(fieldName)) return df.getRegex();
}
return null;
}
/**
* Does the schema explicitly define the specified field, i.e. not as a result
* of a copyField declaration? We consider it explicitly defined if it matches
* a field name or a dynamicField name.
* @return true if explicitly declared in the schema.
*/
public boolean hasExplicitField(String fieldName) {
if (fields.containsKey(fieldName)) {
return true;
}
for (DynamicField df : dynamicFields) {
if (fieldName.equals(df.getRegex())) return true;
}
return false;
}
/**
* Is the specified field dynamic or not.
* @return true if the specified field is dynamic
*/
public boolean isDynamicField(String fieldName) {
if(fields.containsKey(fieldName)) {
return false;
}
for (DynamicField df : dynamicFields) {
if (df.matches(fieldName)) return true;
}
return false;
}
/**
* Returns the SchemaField that should be used for the specified field name, or
* null if none exists.
*
* @param fieldName may be an explicitly defined field or a name that
* matches a dynamic field.
* @see #getFieldType
* @see #getField(String)
* @return The {@link org.apache.solr.schema.SchemaField}
*/
public SchemaField getFieldOrNull(String fieldName) {
SchemaField f = fields.get(fieldName);
if (f != null) return f;
for (DynamicField df : dynamicFields) {
if (df.matches(fieldName)) return df.makeSchemaField(fieldName);
}
return f;
}
/**
* Returns the SchemaField that should be used for the specified field name
*
* @param fieldName may be an explicitly defined field or a name that
* matches a dynamic field.
* @throws SolrException if no such field exists
* @see #getFieldType
* @see #getFieldOrNull(String)
* @return The {@link SchemaField}
*/
public SchemaField getField(String fieldName) {
SchemaField f = getFieldOrNull(fieldName);
if (f != null) return f;
// Hmmm, default field could also be implemented with a dynamic field of "*".
// It would have to be special-cased and only used if nothing else matched.
/*** REMOVED -YCS
if (defaultFieldType != null) return new SchemaField(fieldName,defaultFieldType);
***/
throw new SolrException(ErrorCode.BAD_REQUEST,"undefined field: \""+fieldName+"\"");
}
/**
* Returns the FieldType for the specified field name.
*
* <p>
* This method exists because it can be more efficient then
* {@link #getField} for dynamic fields if a full SchemaField isn't needed.
* </p>
*
* @param fieldName may be an explicitly created field, or a name that
* excercises a dynamic field.
* @throws SolrException if no such field exists
* @see #getField(String)
* @see #getFieldTypeNoEx
*/
public FieldType getFieldType(String fieldName) {
SchemaField f = fields.get(fieldName);
if (f != null) return f.getType();
return getDynamicFieldType(fieldName);
}
/**
* Given the name of a {@link org.apache.solr.schema.FieldType} (not to be confused with {@link #getFieldType(String)} which
* takes in the name of a field), return the {@link org.apache.solr.schema.FieldType}.
* @param fieldTypeName The name of the {@link org.apache.solr.schema.FieldType}
* @return The {@link org.apache.solr.schema.FieldType} or null.
*/
public FieldType getFieldTypeByName(String fieldTypeName){
return fieldTypes.get(fieldTypeName);
}
/**
* Returns the FieldType for the specified field name.
*
* <p>
* This method exists because it can be more efficient then
* {@link #getField} for dynamic fields if a full SchemaField isn't needed.
* </p>
*
* @param fieldName may be an explicitly created field, or a name that
* exercises a dynamic field.
* @return null if field is not defined.
* @see #getField(String)
* @see #getFieldTypeNoEx
*/
public FieldType getFieldTypeNoEx(String fieldName) {
SchemaField f = fields.get(fieldName);
if (f != null) return f.getType();
return dynFieldType(fieldName);
}
/**
* Returns the FieldType of the best matching dynamic field for
* the specified field name
*
* @param fieldName may be an explicitly created field, or a name that
* exercises a dynamic field.
* @throws SolrException if no such field exists
* @see #getField(String)
* @see #getFieldTypeNoEx
*/
public FieldType getDynamicFieldType(String fieldName) {
for (DynamicField df : dynamicFields) {
if (df.matches(fieldName)) return df.prototype.getType();
}
throw new SolrException(ErrorCode.BAD_REQUEST,"undefined field "+fieldName);
}
private FieldType dynFieldType(String fieldName) {
for (DynamicField df : dynamicFields) {
if (df.matches(fieldName)) return df.prototype.getType();
}
return null;
};
/**
* Get all copy fields, both the static and the dynamic ones.
* @return Array of fields copied into this field
*/
public List<String> getCopySources(String destField) {
SchemaField f = getField(destField);
if (!isCopyFieldTarget(f)) {
return Collections.emptyList();
}
List<String> fieldNames = new ArrayList<String>();
for (Map.Entry<String, List<CopyField>> cfs : copyFieldsMap.entrySet()) {
for (CopyField copyField : cfs.getValue()) {
if (copyField.getDestination().getName().equals(destField)) {
fieldNames.add(copyField.getSource().getName());
}
}
}
for (DynamicCopy dynamicCopy : dynamicCopyFields) {
if (dynamicCopy.getDestFieldName().equals(destField)) {
fieldNames.add(dynamicCopy.getRegex());
}
}
return fieldNames;
}
/**
* Get all copy fields for a specified source field, both static
* and dynamic ones.
* @return List of CopyFields to copy to.
* @since solr 1.4
*/
// This is useful when we need the maxSize param of each CopyField
public List<CopyField> getCopyFieldsList(final String sourceField){
final List<CopyField> result = new ArrayList<CopyField>();
for (DynamicCopy dynamicCopy : dynamicCopyFields) {
if (dynamicCopy.matches(sourceField)) {
result.add(new CopyField(getField(sourceField), dynamicCopy.getTargetField(sourceField), dynamicCopy.maxChars));
}
}
List<CopyField> fixedCopyFields = copyFieldsMap.get(sourceField);
if (null != fixedCopyFields) {
result.addAll(fixedCopyFields);
}
return result;
}
/**
* Check if a field is used as the destination of a copyField operation
*
* @since solr 1.3
*/
public boolean isCopyFieldTarget( SchemaField f ) {
return copyFieldTargetCounts.containsKey( f );
}
/**
* Get a map of property name -> value for the whole schema.
*/
public SimpleOrderedMap<Object> getNamedPropertyValues() {
SimpleOrderedMap<Object> topLevel = new SimpleOrderedMap<Object>();
topLevel.add(NAME, getSchemaName());
topLevel.add(VERSION, getVersion());
if (null != uniqueKeyFieldName) {
topLevel.add(UNIQUE_KEY, uniqueKeyFieldName);
}
if (null != defaultSearchFieldName) {
topLevel.add(DEFAULT_SEARCH_FIELD, defaultSearchFieldName);
}
if (isExplicitQueryParserDefaultOperator) {
SimpleOrderedMap<Object> solrQueryParserProperties = new SimpleOrderedMap<Object>();
solrQueryParserProperties.add(DEFAULT_OPERATOR, queryParserDefaultOperator);
topLevel.add(SOLR_QUERY_PARSER, solrQueryParserProperties);
}
if (isExplicitSimilarity) {
topLevel.add(SIMILARITY, similarityFactory.getNamedPropertyValues());
}
List<SimpleOrderedMap<Object>> fieldTypeProperties = new ArrayList<SimpleOrderedMap<Object>>();
SortedMap<String,FieldType> sortedFieldTypes = new TreeMap<String,FieldType>(fieldTypes);
for (FieldType fieldType : sortedFieldTypes.values()) {
fieldTypeProperties.add(fieldType.getNamedPropertyValues(false));
}
topLevel.add(FIELD_TYPES, fieldTypeProperties);
List<SimpleOrderedMap<Object>> fieldProperties = new ArrayList<SimpleOrderedMap<Object>>();
SortedSet<String> fieldNames = new TreeSet<String>(fields.keySet());
for (String fieldName : fieldNames) {
fieldProperties.add(fields.get(fieldName).getNamedPropertyValues(false));
}
topLevel.add(FIELDS, fieldProperties);
List<SimpleOrderedMap<Object>> dynamicFieldProperties = new ArrayList<SimpleOrderedMap<Object>>();
for (IndexSchema.DynamicField dynamicField : dynamicFields) {
if ( ! dynamicField.getRegex().startsWith(INTERNAL_POLY_FIELD_PREFIX)) { // omit internal polyfields
dynamicFieldProperties.add(dynamicField.getPrototype().getNamedPropertyValues(false));
}
}
topLevel.add(DYNAMIC_FIELDS, dynamicFieldProperties);
topLevel.add(COPY_FIELDS, getCopyFieldProperties(false, null, null));
return topLevel;
}
/**
* Returns a list of copyField directives, with optional details and optionally restricting to those
* directives that contain the requested source and/or destination field names.
*
* @param showDetails If true, source and destination dynamic bases, and explicit fields matched by source globs,
* will be added to dynamic copyField directives where appropriate
* @param requestedSourceFields If not null, output is restricted to those copyField directives
* with the requested source field names
* @param requestedDestinationFields If not null, output is restricted to those copyField directives
* with the requested destination field names
* @return a list of copyField directives
*/
public List<SimpleOrderedMap<Object>> getCopyFieldProperties
(boolean showDetails, Set<String> requestedSourceFields, Set<String> requestedDestinationFields) {
List<SimpleOrderedMap<Object>> copyFieldProperties = new ArrayList<SimpleOrderedMap<Object>>();
SortedMap<String,List<CopyField>> sortedCopyFields = new TreeMap<String,List<CopyField>>(copyFieldsMap);
for (List<CopyField> copyFields : sortedCopyFields.values()) {
Collections.sort(copyFields, new Comparator<CopyField>() {
@Override
public int compare(CopyField cf1, CopyField cf2) {
// sources are all be the same, just sorting by destination here
return cf1.getDestination().getName().compareTo(cf2.getDestination().getName());
}
});
for (CopyField copyField : copyFields) {
final String source = copyField.getSource().getName();
final String destination = copyField.getDestination().getName();
if ( (null == requestedSourceFields || requestedSourceFields.contains(source))
&& (null == requestedDestinationFields || requestedDestinationFields.contains(destination))) {
SimpleOrderedMap<Object> props = new SimpleOrderedMap<Object>();
props.add(SOURCE, source);
props.add(DESTINATION, destination);
if (0 != copyField.getMaxChars()) {
props.add(MAX_CHARS, copyField.getMaxChars());
}
copyFieldProperties.add(props);
}
}
}
for (IndexSchema.DynamicCopy dynamicCopy : dynamicCopyFields) {
final String source = dynamicCopy.getRegex();
final String destination = dynamicCopy.getDestFieldName();
if ( (null == requestedSourceFields || requestedSourceFields.contains(source))
&& (null == requestedDestinationFields || requestedDestinationFields.contains(destination))) {
SimpleOrderedMap<Object> dynamicCopyProps = new SimpleOrderedMap<Object>();
dynamicCopyProps.add(SOURCE, dynamicCopy.getRegex());
if (showDetails) {
IndexSchema.DynamicField sourceDynamicBase = dynamicCopy.getSourceDynamicBase();
if (null != sourceDynamicBase) {
dynamicCopyProps.add(SOURCE_DYNAMIC_BASE, sourceDynamicBase.getRegex());
} else if (source.contains("*")) {
List<String> sourceExplicitFields = new ArrayList<String>();
Pattern pattern = Pattern.compile(source.replace("*", ".*")); // glob->regex
for (String field : fields.keySet()) {
if (pattern.matcher(field).matches()) {
sourceExplicitFields.add(field);
}
}
if (sourceExplicitFields.size() > 0) {
Collections.sort(sourceExplicitFields);
dynamicCopyProps.add(SOURCE_EXPLICIT_FIELDS, sourceExplicitFields);
}
}
}
dynamicCopyProps.add(DESTINATION, dynamicCopy.getDestFieldName());
if (showDetails) {
IndexSchema.DynamicField destDynamicBase = dynamicCopy.getDestDynamicBase();
if (null != destDynamicBase) {
dynamicCopyProps.add(DESTINATION_DYNAMIC_BASE, destDynamicBase.getRegex());
}
}
if (0 != dynamicCopy.getMaxChars()) {
dynamicCopyProps.add(MAX_CHARS, dynamicCopy.getMaxChars());
}
copyFieldProperties.add(dynamicCopyProps);
}
}
return copyFieldProperties;
}
protected IndexSchema(final SolrConfig solrConfig, final SolrResourceLoader loader) {
this.solrConfig = solrConfig;
this.loader = loader;
}
/**
* Copies this schema, adds the given field to the copy, then persists the new schema.
*
* @param newField the SchemaField to add
* @return a new IndexSchema based on this schema with newField added
* @see #newField(String, String, Map)
*/
public IndexSchema addField(SchemaField newField) {
String msg = "This IndexSchema is not mutable.";
log.error(msg);
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
/**
* Copies this schema, adds the given fields to the copy, then persists the new schema.
*
* @param newFields the SchemaFields to add
* @return a new IndexSchema based on this schema with newFields added
* @see #newField(String, String, Map)
*/
public IndexSchema addFields(Collection<SchemaField> newFields) {
String msg = "This IndexSchema is not mutable.";
log.error(msg);
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
/**
* Returns a SchemaField if the given fieldName does not already
* exist in this schema, and does not match any dynamic fields
* in this schema. The resulting SchemaField can be used in a call
* to {@link #addField(SchemaField)}.
*
* @param fieldName the name of the field to add
* @param fieldType the field type for the new field
* @param options the options to use when creating the SchemaField
* @return The created SchemaField
* @see #addField(SchemaField)
*/
public SchemaField newField(String fieldName, String fieldType, Map<String,?> options) {
String msg = "This IndexSchema is not mutable.";
log.error(msg);
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
}
| false | true | protected void readSchema(InputSource is) {
log.info("Reading Solr Schema from " + resourceName);
try {
// pass the config resource loader to avoid building an empty one for no reason:
// in the current case though, the stream is valid so we wont load the resource by name
Config schemaConf = new Config(loader, SCHEMA, is, SLASH+SCHEMA+SLASH);
Document document = schemaConf.getDocument();
final XPath xpath = schemaConf.getXPath();
String expression = stepsToPath(SCHEMA, AT + NAME);
Node nd = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append(loader.getCoreProperties().getProperty(NAME));
sb.append("] ");
if (nd==null) {
sb.append("schema has no name!");
log.warn(sb.toString());
} else {
name = nd.getNodeValue();
sb.append("Schema ");
sb.append(NAME);
sb.append("=");
sb.append(name);
log.info(sb.toString());
}
// /schema/@version
expression = stepsToPath(SCHEMA, AT + VERSION);
version = schemaConf.getFloat(expression, 1.0f);
// load the Field Types
final FieldTypePluginLoader typeLoader = new FieldTypePluginLoader(this, fieldTypes, schemaAware);
// /schema/types/fieldtype | /schema/types/fieldType
expression = stepsToPath(SCHEMA, TYPES, FIELD_TYPE.toLowerCase(Locale.ROOT)) // backcompat(?)
+ XPATH_OR + stepsToPath(SCHEMA, TYPES, FIELD_TYPE);
NodeList nodes = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);
typeLoader.load(loader, nodes);
// load the fields
Map<String,Boolean> explicitRequiredProp = loadFields(document, xpath);
expression = stepsToPath(SCHEMA, SIMILARITY); // /schema/similarity
Node node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
similarityFactory = readSimilarity(loader, node);
if (similarityFactory == null) {
similarityFactory = new DefaultSimilarityFactory();
} else {
isExplicitSimilarity = true;
}
if ( ! (similarityFactory instanceof SolrCoreAware)) {
// if the sim factory isn't SolrCoreAware (and hence schema aware),
// then we are responsible for erroring if a field type is trying to specify a sim.
for (FieldType ft : fieldTypes.values()) {
if (null != ft.getSimilarity()) {
String msg = "FieldType '" + ft.getTypeName()
+ "' is configured with a similarity, but the global similarity does not support it: "
+ similarityFactory.getClass();
log.error(msg);
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
}
}
// /schema/defaultSearchField/@text()
expression = stepsToPath(SCHEMA, DEFAULT_SEARCH_FIELD, TEXT_FUNCTION);
node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
if (node==null) {
log.debug("no default search field specified in schema.");
} else {
defaultSearchFieldName=node.getNodeValue().trim();
// throw exception if specified, but not found or not indexed
if (defaultSearchFieldName!=null) {
SchemaField defaultSearchField = getFields().get(defaultSearchFieldName);
if ((defaultSearchField == null) || !defaultSearchField.indexed()) {
String msg = "default search field '" + defaultSearchFieldName + "' not defined or not indexed" ;
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
}
log.info("default search field in schema is "+defaultSearchFieldName);
}
// /schema/solrQueryParser/@defaultOperator
expression = stepsToPath(SCHEMA, SOLR_QUERY_PARSER, AT + DEFAULT_OPERATOR);
node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
if (node==null) {
log.debug("using default query parser operator (OR)");
} else {
isExplicitQueryParserDefaultOperator = true;
queryParserDefaultOperator=node.getNodeValue().trim();
log.info("query parser default operator is "+queryParserDefaultOperator);
}
// /schema/uniqueKey/text()
expression = stepsToPath(SCHEMA, UNIQUE_KEY, TEXT_FUNCTION);
node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
if (node==null) {
log.warn("no " + UNIQUE_KEY + " specified in schema.");
} else {
uniqueKeyField=getIndexedField(node.getNodeValue().trim());
if (null != uniqueKeyField.getDefaultValue()) {
String msg = UNIQUE_KEY + " field ("+uniqueKeyFieldName+
") can not be configured with a default value ("+
uniqueKeyField.getDefaultValue()+")";
log.error(msg);
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
if (!uniqueKeyField.stored()) {
log.warn(UNIQUE_KEY + " is not stored - distributed search and MoreLikeThis will not work");
}
if (uniqueKeyField.multiValued()) {
String msg = UNIQUE_KEY + " field ("+uniqueKeyFieldName+
") can not be configured to be multivalued";
log.error(msg);
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
uniqueKeyFieldName=uniqueKeyField.getName();
uniqueKeyFieldType=uniqueKeyField.getType();
log.info("unique key field: "+uniqueKeyFieldName);
// Unless the uniqueKeyField is marked 'required=false' then make sure it exists
if( Boolean.FALSE != explicitRequiredProp.get( uniqueKeyFieldName ) ) {
uniqueKeyField.required = true;
requiredFields.add(uniqueKeyField);
}
}
/////////////// parse out copyField commands ///////////////
// Map<String,ArrayList<SchemaField>> cfields = new HashMap<String,ArrayList<SchemaField>>();
// expression = "/schema/copyField";
dynamicCopyFields = new DynamicCopy[] {};
expression = "//" + COPY_FIELD;
nodes = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);
for (int i=0; i<nodes.getLength(); i++) {
node = nodes.item(i);
NamedNodeMap attrs = node.getAttributes();
String source = DOMUtil.getAttr(attrs, SOURCE, COPY_FIELD + " definition");
String dest = DOMUtil.getAttr(attrs, DESTINATION, COPY_FIELD + " definition");
String maxChars = DOMUtil.getAttr(attrs, MAX_CHARS);
int maxCharsInt = CopyField.UNLIMITED;
if (maxChars != null) {
try {
maxCharsInt = Integer.parseInt(maxChars);
} catch (NumberFormatException e) {
log.warn("Couldn't parse " + MAX_CHARS + " attribute for " + COPY_FIELD + " from "
+ source + " to " + dest + " as integer. The whole field will be copied.");
}
}
if (dest.equals(uniqueKeyFieldName)) {
String msg = UNIQUE_KEY + " field ("+uniqueKeyFieldName+
") can not be the " + DESTINATION + " of a " + COPY_FIELD + "(" + SOURCE + "=" +source+")";
log.error(msg);
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
registerCopyField(source, dest, maxCharsInt);
}
for (Map.Entry<SchemaField, Integer> entry : copyFieldTargetCounts.entrySet()) {
if (entry.getValue() > 1 && !entry.getKey().multiValued()) {
log.warn("Field " + entry.getKey().name + " is not multivalued "+
"and destination for multiple " + COPY_FIELDS + " ("+
entry.getValue()+")");
}
}
//Run the callbacks on SchemaAware now that everything else is done
for (SchemaAware aware : schemaAware) {
aware.inform(this);
}
} catch (SolrException e) {
throw e;
} catch(Exception e) {
// unexpected exception...
throw new SolrException(ErrorCode.SERVER_ERROR, "Schema Parsing Failed: " + e.getMessage(), e);
}
// create the field analyzers
refreshAnalyzers();
}
| protected void readSchema(InputSource is) {
log.info("Reading Solr Schema from " + resourceName);
try {
// pass the config resource loader to avoid building an empty one for no reason:
// in the current case though, the stream is valid so we wont load the resource by name
Config schemaConf = new Config(loader, SCHEMA, is, SLASH+SCHEMA+SLASH);
Document document = schemaConf.getDocument();
final XPath xpath = schemaConf.getXPath();
String expression = stepsToPath(SCHEMA, AT + NAME);
Node nd = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
StringBuilder sb = new StringBuilder();
// Another case where the initialization from the test harness is different than the "real world"
sb.append("[");
if (loader.getCoreProperties() != null) {
sb.append(loader.getCoreProperties().getProperty(NAME));
} else {
sb.append("null");
}
if (nd==null) {
sb.append("schema has no name!");
log.warn(sb.toString());
} else {
name = nd.getNodeValue();
sb.append("Schema ");
sb.append(NAME);
sb.append("=");
sb.append(name);
log.info(sb.toString());
}
// /schema/@version
expression = stepsToPath(SCHEMA, AT + VERSION);
version = schemaConf.getFloat(expression, 1.0f);
// load the Field Types
final FieldTypePluginLoader typeLoader = new FieldTypePluginLoader(this, fieldTypes, schemaAware);
// /schema/types/fieldtype | /schema/types/fieldType
expression = stepsToPath(SCHEMA, TYPES, FIELD_TYPE.toLowerCase(Locale.ROOT)) // backcompat(?)
+ XPATH_OR + stepsToPath(SCHEMA, TYPES, FIELD_TYPE);
NodeList nodes = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);
typeLoader.load(loader, nodes);
// load the fields
Map<String,Boolean> explicitRequiredProp = loadFields(document, xpath);
expression = stepsToPath(SCHEMA, SIMILARITY); // /schema/similarity
Node node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
similarityFactory = readSimilarity(loader, node);
if (similarityFactory == null) {
similarityFactory = new DefaultSimilarityFactory();
} else {
isExplicitSimilarity = true;
}
if ( ! (similarityFactory instanceof SolrCoreAware)) {
// if the sim factory isn't SolrCoreAware (and hence schema aware),
// then we are responsible for erroring if a field type is trying to specify a sim.
for (FieldType ft : fieldTypes.values()) {
if (null != ft.getSimilarity()) {
String msg = "FieldType '" + ft.getTypeName()
+ "' is configured with a similarity, but the global similarity does not support it: "
+ similarityFactory.getClass();
log.error(msg);
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
}
}
// /schema/defaultSearchField/@text()
expression = stepsToPath(SCHEMA, DEFAULT_SEARCH_FIELD, TEXT_FUNCTION);
node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
if (node==null) {
log.debug("no default search field specified in schema.");
} else {
defaultSearchFieldName=node.getNodeValue().trim();
// throw exception if specified, but not found or not indexed
if (defaultSearchFieldName!=null) {
SchemaField defaultSearchField = getFields().get(defaultSearchFieldName);
if ((defaultSearchField == null) || !defaultSearchField.indexed()) {
String msg = "default search field '" + defaultSearchFieldName + "' not defined or not indexed" ;
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
}
log.info("default search field in schema is "+defaultSearchFieldName);
}
// /schema/solrQueryParser/@defaultOperator
expression = stepsToPath(SCHEMA, SOLR_QUERY_PARSER, AT + DEFAULT_OPERATOR);
node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
if (node==null) {
log.debug("using default query parser operator (OR)");
} else {
isExplicitQueryParserDefaultOperator = true;
queryParserDefaultOperator=node.getNodeValue().trim();
log.info("query parser default operator is "+queryParserDefaultOperator);
}
// /schema/uniqueKey/text()
expression = stepsToPath(SCHEMA, UNIQUE_KEY, TEXT_FUNCTION);
node = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
if (node==null) {
log.warn("no " + UNIQUE_KEY + " specified in schema.");
} else {
uniqueKeyField=getIndexedField(node.getNodeValue().trim());
if (null != uniqueKeyField.getDefaultValue()) {
String msg = UNIQUE_KEY + " field ("+uniqueKeyFieldName+
") can not be configured with a default value ("+
uniqueKeyField.getDefaultValue()+")";
log.error(msg);
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
if (!uniqueKeyField.stored()) {
log.warn(UNIQUE_KEY + " is not stored - distributed search and MoreLikeThis will not work");
}
if (uniqueKeyField.multiValued()) {
String msg = UNIQUE_KEY + " field ("+uniqueKeyFieldName+
") can not be configured to be multivalued";
log.error(msg);
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
uniqueKeyFieldName=uniqueKeyField.getName();
uniqueKeyFieldType=uniqueKeyField.getType();
log.info("unique key field: "+uniqueKeyFieldName);
// Unless the uniqueKeyField is marked 'required=false' then make sure it exists
if( Boolean.FALSE != explicitRequiredProp.get( uniqueKeyFieldName ) ) {
uniqueKeyField.required = true;
requiredFields.add(uniqueKeyField);
}
}
/////////////// parse out copyField commands ///////////////
// Map<String,ArrayList<SchemaField>> cfields = new HashMap<String,ArrayList<SchemaField>>();
// expression = "/schema/copyField";
dynamicCopyFields = new DynamicCopy[] {};
expression = "//" + COPY_FIELD;
nodes = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);
for (int i=0; i<nodes.getLength(); i++) {
node = nodes.item(i);
NamedNodeMap attrs = node.getAttributes();
String source = DOMUtil.getAttr(attrs, SOURCE, COPY_FIELD + " definition");
String dest = DOMUtil.getAttr(attrs, DESTINATION, COPY_FIELD + " definition");
String maxChars = DOMUtil.getAttr(attrs, MAX_CHARS);
int maxCharsInt = CopyField.UNLIMITED;
if (maxChars != null) {
try {
maxCharsInt = Integer.parseInt(maxChars);
} catch (NumberFormatException e) {
log.warn("Couldn't parse " + MAX_CHARS + " attribute for " + COPY_FIELD + " from "
+ source + " to " + dest + " as integer. The whole field will be copied.");
}
}
if (dest.equals(uniqueKeyFieldName)) {
String msg = UNIQUE_KEY + " field ("+uniqueKeyFieldName+
") can not be the " + DESTINATION + " of a " + COPY_FIELD + "(" + SOURCE + "=" +source+")";
log.error(msg);
throw new SolrException(ErrorCode.SERVER_ERROR, msg);
}
registerCopyField(source, dest, maxCharsInt);
}
for (Map.Entry<SchemaField, Integer> entry : copyFieldTargetCounts.entrySet()) {
if (entry.getValue() > 1 && !entry.getKey().multiValued()) {
log.warn("Field " + entry.getKey().name + " is not multivalued "+
"and destination for multiple " + COPY_FIELDS + " ("+
entry.getValue()+")");
}
}
//Run the callbacks on SchemaAware now that everything else is done
for (SchemaAware aware : schemaAware) {
aware.inform(this);
}
} catch (SolrException e) {
throw e;
} catch(Exception e) {
// unexpected exception...
throw new SolrException(ErrorCode.SERVER_ERROR, "Schema Parsing Failed: " + e.getMessage(), e);
}
// create the field analyzers
refreshAnalyzers();
}
|
diff --git a/src/main/java/nl/surfnet/bod/web/manager/DashboardController.java b/src/main/java/nl/surfnet/bod/web/manager/DashboardController.java
index bfc9fbe46..055f88864 100644
--- a/src/main/java/nl/surfnet/bod/web/manager/DashboardController.java
+++ b/src/main/java/nl/surfnet/bod/web/manager/DashboardController.java
@@ -1,84 +1,84 @@
/**
* The owner of the original code is SURFnet BV.
*
* Portions created by the original owner are Copyright (C) 2011-2012 the
* original owner. All Rights Reserved.
*
* Portions created by other contributors are Copyright (C) the contributor.
* All Rights Reserved.
*
* Contributor(s):
* (Contributors insert name & email here)
*
* This file is part of the SURFnet7 Bandwidth on Demand software.
*
* The SURFnet7 Bandwidth on Demand software is free software: you can
* redistribute it and/or modify it under the terms of the BSD license
* included with this distribution.
*
* If the BSD license cannot be found with this distribution, it is available
* at the following location <http://www.opensource.org/licenses/BSD-3-Clause>
*/
package nl.surfnet.bod.web.manager;
import java.util.Collection;
import nl.surfnet.bod.domain.PhysicalResourceGroup;
import nl.surfnet.bod.service.PhysicalResourceGroupService;
import nl.surfnet.bod.util.Environment;
import nl.surfnet.bod.web.WebUtils;
import nl.surfnet.bod.web.security.Security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller("managerDashboardController")
@RequestMapping("/manager")
public class DashboardController {
@Autowired
private PhysicalResourceGroupService physicalResourceGroupService;
@Autowired
private Environment environment;
@RequestMapping(method = RequestMethod.GET)
public String index(RedirectAttributes model) {
Collection<PhysicalResourceGroup> groups = physicalResourceGroupService
.findAllForManager(Security.getUserDetails());
for (PhysicalResourceGroup group : groups) {
if (!group.isActive()) {
WebUtils.addInfoMessage(model, createNewActivationLinkForm(new Object[] {
environment.getExternalBodUrl() + ActivationEmailController.ACTIVATION_MANAGER_PATH,
group.getId().toString() }));
return "redirect:manager/physicalresourcegroups/edit?id=" + group.getId();
}
}
- return "index";
+ return "manager/index";
}
/**
* Creates a form which posts to the activationEmailController to send the
* activationEmail again. We don't use the
* {@link WebUtils#addInfoMessage(org.springframework.ui.Model, String, String...)}
* method here, since this places markup around the parameters which will
* created an invalid post url.
*
* @param args
* @return
*/
String createNewActivationLinkForm(Object... args) {
return String.format("Your Physical Resource group is not activated yet, please do so now. "
+ "<form style=\"display: inline\" id=\"activateFrom\" action=\"%s\" method=\"POST\""
+ "enctype=\"application/x-www-form-urlencoded\">"
+ "<input id=\"id\" name=\"id\" type=\"hidden\" value=\"%s\"><input class=\"btn primary\""
+ "value=\"Send email\" type=\"submit\"></div></form>", args);
}
}
| true | true | public String index(RedirectAttributes model) {
Collection<PhysicalResourceGroup> groups = physicalResourceGroupService
.findAllForManager(Security.getUserDetails());
for (PhysicalResourceGroup group : groups) {
if (!group.isActive()) {
WebUtils.addInfoMessage(model, createNewActivationLinkForm(new Object[] {
environment.getExternalBodUrl() + ActivationEmailController.ACTIVATION_MANAGER_PATH,
group.getId().toString() }));
return "redirect:manager/physicalresourcegroups/edit?id=" + group.getId();
}
}
return "index";
}
| public String index(RedirectAttributes model) {
Collection<PhysicalResourceGroup> groups = physicalResourceGroupService
.findAllForManager(Security.getUserDetails());
for (PhysicalResourceGroup group : groups) {
if (!group.isActive()) {
WebUtils.addInfoMessage(model, createNewActivationLinkForm(new Object[] {
environment.getExternalBodUrl() + ActivationEmailController.ACTIVATION_MANAGER_PATH,
group.getId().toString() }));
return "redirect:manager/physicalresourcegroups/edit?id=" + group.getId();
}
}
return "manager/index";
}
|
diff --git a/core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java b/core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java
index b10a1d9f5..5bb2f2787 100644
--- a/core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java
+++ b/core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java
@@ -1,152 +1,152 @@
package hudson.node_monitors;
import hudson.model.Computer;
import hudson.model.Descriptor;
import hudson.model.Hudson;
import hudson.triggers.Trigger;
import hudson.triggers.SafeTimerTask;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Convenient base class for common {@link NodeMonitor} implementation
* where the "monitoring" consists of executing something periodically on every node
* and taking some action based on its result.
*
* <p>
* "T" represents the the result of the monitoring.
*
* @author Kohsuke Kawaguchi
*/
public abstract class AbstractNodeMonitorDescriptor<T> extends Descriptor<NodeMonitor> {
protected AbstractNodeMonitorDescriptor(Class<? extends NodeMonitor> clazz) {
this(clazz,HOUR);
}
protected AbstractNodeMonitorDescriptor(Class<? extends NodeMonitor> clazz, long interval) {
super(clazz);
// check every hour
Trigger.timer.scheduleAtFixedRate(new SafeTimerTask() {
public void doRun() {
triggerUpdate();
}
}, interval, interval);
}
/**
* Represents the last record of the update
*/
private volatile Record record = null;
/**
* Represents the update activity in progress.
*/
private volatile Record inProgress = null;
/**
* Performs monitoring of the given computer object.
* This method is invoked periodically to perform the monitoring of the computer.
*
* @return
* Application-specific value that represents the observed monitoring value
* on the given node. This value will be returned from the {@link #get(Computer)} method.
* If null is returned, it will be interpreted as "no observed value." This is
* convenient way of abandoning the observation on a particular computer,
* whereas {@link IOException} is useful for indicating a hard error that needs to be
* corrected.
*/
protected abstract T monitor(Computer c) throws IOException,InterruptedException;
/**
* Obtains the monitoring result.
*/
public T get(Computer c) {
if(record==null) {
// if this is the first time, schedule the check now
if(inProgress==null) {
synchronized(this) {
if(inProgress==null)
new Record().start();
}
}
return null;
}
return record.data.get(c);
}
/**
* @see NodeMonitor#triggerUpdate()
*/
/*package*/ Thread triggerUpdate() {
Record t = new Record();
t.start();
return t;
}
/**
* Thread that monitors nodes, as well as the data structure to record
* the result.
*/
private final class Record extends Thread {
/**
* Last computed monitoring result.
*/
private final Map<Computer,T> data = new HashMap<Computer,T>();
/**
* When was {@link #data} last updated?
*/
private Date lastUpdated;
public Record() {
super("Monitoring thread for "+getDisplayName()+" started on "+new Date());
synchronized(AbstractNodeMonitorDescriptor.this) {
if(inProgress!=null) {
// maybe it got stuck?
LOGGER.warning("Previous "+getDisplayName()+" monitoring activity still in progress. Interrupting");
inProgress.interrupt();
}
inProgress = this;
}
}
public void run() {
try {
long startTime = System.currentTimeMillis();
for( Computer c : Hudson.getInstance().getComputers() ) {
try {
if(c.isOffline())
data.put(c,null);
else
data.put(c,monitor(c));
} catch (IOException e) {
- LOGGER.log(Level.WARNING, "Failed to monitor "+c+" for "+getDisplayName(), e);
+ LOGGER.log(Level.WARNING, "Failed to monitor "+c.getDisplayName()+" for "+getDisplayName(), e);
}
}
lastUpdated = new Date();
synchronized(AbstractNodeMonitorDescriptor.this) {
assert inProgress==this;
inProgress = null;
record = this;
}
LOGGER.info("Node monitoring "+getDisplayName()+" completed in "+(System.currentTimeMillis()-startTime)+"ms");
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING,"Node monitoring "+getDisplayName()+" aborted.",e);
}
}
}
private final Logger LOGGER = Logger.getLogger(getClass().getName());
private static final long HOUR = 1000*60*60L;
}
| true | true | public void run() {
try {
long startTime = System.currentTimeMillis();
for( Computer c : Hudson.getInstance().getComputers() ) {
try {
if(c.isOffline())
data.put(c,null);
else
data.put(c,monitor(c));
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to monitor "+c+" for "+getDisplayName(), e);
}
}
lastUpdated = new Date();
synchronized(AbstractNodeMonitorDescriptor.this) {
assert inProgress==this;
inProgress = null;
record = this;
}
LOGGER.info("Node monitoring "+getDisplayName()+" completed in "+(System.currentTimeMillis()-startTime)+"ms");
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING,"Node monitoring "+getDisplayName()+" aborted.",e);
}
}
| public void run() {
try {
long startTime = System.currentTimeMillis();
for( Computer c : Hudson.getInstance().getComputers() ) {
try {
if(c.isOffline())
data.put(c,null);
else
data.put(c,monitor(c));
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to monitor "+c.getDisplayName()+" for "+getDisplayName(), e);
}
}
lastUpdated = new Date();
synchronized(AbstractNodeMonitorDescriptor.this) {
assert inProgress==this;
inProgress = null;
record = this;
}
LOGGER.info("Node monitoring "+getDisplayName()+" completed in "+(System.currentTimeMillis()-startTime)+"ms");
} catch (InterruptedException e) {
LOGGER.log(Level.WARNING,"Node monitoring "+getDisplayName()+" aborted.",e);
}
}
|
diff --git a/agile-apps/agile-app-docs/src/main/java/org/headsupdev/agile/app/docs/DocumentRenderer.java b/agile-apps/agile-app-docs/src/main/java/org/headsupdev/agile/app/docs/DocumentRenderer.java
index 759f5e41..8dca29ba 100644
--- a/agile-apps/agile-app-docs/src/main/java/org/headsupdev/agile/app/docs/DocumentRenderer.java
+++ b/agile-apps/agile-app-docs/src/main/java/org/headsupdev/agile/app/docs/DocumentRenderer.java
@@ -1,197 +1,198 @@
/*
* HeadsUp Agile
* Copyright 2009-2012 Heads Up Development Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.headsupdev.agile.app.docs;
import org.headsupdev.agile.api.Project;
import org.headsupdev.agile.api.LinkProvider;
import org.headsupdev.agile.web.components.MarkedUpTextModel;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
import java.io.*;
import java.util.Enumeration;
import java.util.Map;
import java.util.StringTokenizer;
/**
* This is a helper for rendering document objects.
*
* @author Andrew Williams
* @version $Id$
* @since 1.0
*/
public class DocumentRenderer
{
public static String markupLinks( String in, final Project project,
final Map<String,LinkProvider> linkProviders )
{
try
{
final StringWriter text = new StringWriter();
HTMLEditorKit.ParserCallback callback = new HTMLEditorKit.ParserCallback ()
{
boolean inlink = false;
@Override
public void handleStartTag( HTML.Tag t, MutableAttributeSet a, int pos )
{
if ( t.equals( HTML.Tag.A ) )
{
inlink = true;
}
text.append( "<" );
text.append( t.toString() );
Enumeration attEnum = a.getAttributeNames();
while ( attEnum.hasMoreElements() )
{
Object att = attEnum.nextElement();
if ( !( att instanceof HTML.Attribute ) )
{
continue;
}
text.append( ' ' );
text.append( att.toString() );
text.append( "=\"" );
if ( a.getAttribute( att ) != null )
{
text.append( a.getAttribute( att ).toString() );
}
text.append( "\"" );
}
text.append( ">" );
}
@Override
public void handleEndTag( HTML.Tag t, int pos )
{
if ( t.equals( HTML.Tag.A ) )
{
inlink = false;
}
text.append( "</" );
text.append( t.toString() );
text.append( ">" );
}
@Override
public void handleSimpleTag( HTML.Tag t, MutableAttributeSet a, int pos )
{
text.append( "<" );
text.append( t.toString() );
Enumeration attEnum = a.getAttributeNames();
while ( attEnum.hasMoreElements() )
{
Object att = attEnum.nextElement();
if ( !( att instanceof HTML.Attribute ) )
{
continue;
}
text.append( ' ' );
text.append( att.toString() );
text.append( "=\"" );
if ( a.getAttribute( att ) != null )
{
text.append( a.getAttribute( att ).toString() );
}
text.append( "\"" );
}
text.append( " />" );
}
@Override
public void handleText( char[] data, int pos )
{
StringTokenizer tokens = new StringTokenizer( new String( data ), " ", true );
while ( tokens.hasMoreElements() )
{
String token = (String) tokens.nextElement();
/* weird that the parser should return these brackets... */
if ( token.startsWith( ">" ) )
{
if ( token.length() == 1 )
{
+ text.write( ">" );
continue;
}
else
{
token = token.substring( 1 );
}
}
if ( token.indexOf( ':' ) > -1 )
{
if ( !inlink )
{
String link = MarkedUpTextModel.markUp( token, project );
if ( link == null )
{
text.write( escapeString( token ) );
}
else
{
text.write( link );
}
}
else
{
text.write( escapeString( token ) );
}
}
else
{
text.write( escapeString( token ) );
}
}
}
@Override
public void handleEndOfLineString( String eol )
{
text.append( eol );
}
};
new ParserDelegator().parse( new StringReader( in ), callback, false );
return text.toString();
}
catch ( IOException e )
{
return "(unable to parse document)";
}
}
protected static String escapeString( String in )
{
String out = in.replace( "&", "&" ).replace( "<", "<" ).replace( ">", ">" );
return out.replace( "\"", """ );
}
}
| true | true | public static String markupLinks( String in, final Project project,
final Map<String,LinkProvider> linkProviders )
{
try
{
final StringWriter text = new StringWriter();
HTMLEditorKit.ParserCallback callback = new HTMLEditorKit.ParserCallback ()
{
boolean inlink = false;
@Override
public void handleStartTag( HTML.Tag t, MutableAttributeSet a, int pos )
{
if ( t.equals( HTML.Tag.A ) )
{
inlink = true;
}
text.append( "<" );
text.append( t.toString() );
Enumeration attEnum = a.getAttributeNames();
while ( attEnum.hasMoreElements() )
{
Object att = attEnum.nextElement();
if ( !( att instanceof HTML.Attribute ) )
{
continue;
}
text.append( ' ' );
text.append( att.toString() );
text.append( "=\"" );
if ( a.getAttribute( att ) != null )
{
text.append( a.getAttribute( att ).toString() );
}
text.append( "\"" );
}
text.append( ">" );
}
@Override
public void handleEndTag( HTML.Tag t, int pos )
{
if ( t.equals( HTML.Tag.A ) )
{
inlink = false;
}
text.append( "</" );
text.append( t.toString() );
text.append( ">" );
}
@Override
public void handleSimpleTag( HTML.Tag t, MutableAttributeSet a, int pos )
{
text.append( "<" );
text.append( t.toString() );
Enumeration attEnum = a.getAttributeNames();
while ( attEnum.hasMoreElements() )
{
Object att = attEnum.nextElement();
if ( !( att instanceof HTML.Attribute ) )
{
continue;
}
text.append( ' ' );
text.append( att.toString() );
text.append( "=\"" );
if ( a.getAttribute( att ) != null )
{
text.append( a.getAttribute( att ).toString() );
}
text.append( "\"" );
}
text.append( " />" );
}
@Override
public void handleText( char[] data, int pos )
{
StringTokenizer tokens = new StringTokenizer( new String( data ), " ", true );
while ( tokens.hasMoreElements() )
{
String token = (String) tokens.nextElement();
/* weird that the parser should return these brackets... */
if ( token.startsWith( ">" ) )
{
if ( token.length() == 1 )
{
continue;
}
else
{
token = token.substring( 1 );
}
}
if ( token.indexOf( ':' ) > -1 )
{
if ( !inlink )
{
String link = MarkedUpTextModel.markUp( token, project );
if ( link == null )
{
text.write( escapeString( token ) );
}
else
{
text.write( link );
}
}
else
{
text.write( escapeString( token ) );
}
}
else
{
text.write( escapeString( token ) );
}
}
}
@Override
public void handleEndOfLineString( String eol )
{
text.append( eol );
}
};
new ParserDelegator().parse( new StringReader( in ), callback, false );
return text.toString();
}
catch ( IOException e )
{
return "(unable to parse document)";
}
}
| public static String markupLinks( String in, final Project project,
final Map<String,LinkProvider> linkProviders )
{
try
{
final StringWriter text = new StringWriter();
HTMLEditorKit.ParserCallback callback = new HTMLEditorKit.ParserCallback ()
{
boolean inlink = false;
@Override
public void handleStartTag( HTML.Tag t, MutableAttributeSet a, int pos )
{
if ( t.equals( HTML.Tag.A ) )
{
inlink = true;
}
text.append( "<" );
text.append( t.toString() );
Enumeration attEnum = a.getAttributeNames();
while ( attEnum.hasMoreElements() )
{
Object att = attEnum.nextElement();
if ( !( att instanceof HTML.Attribute ) )
{
continue;
}
text.append( ' ' );
text.append( att.toString() );
text.append( "=\"" );
if ( a.getAttribute( att ) != null )
{
text.append( a.getAttribute( att ).toString() );
}
text.append( "\"" );
}
text.append( ">" );
}
@Override
public void handleEndTag( HTML.Tag t, int pos )
{
if ( t.equals( HTML.Tag.A ) )
{
inlink = false;
}
text.append( "</" );
text.append( t.toString() );
text.append( ">" );
}
@Override
public void handleSimpleTag( HTML.Tag t, MutableAttributeSet a, int pos )
{
text.append( "<" );
text.append( t.toString() );
Enumeration attEnum = a.getAttributeNames();
while ( attEnum.hasMoreElements() )
{
Object att = attEnum.nextElement();
if ( !( att instanceof HTML.Attribute ) )
{
continue;
}
text.append( ' ' );
text.append( att.toString() );
text.append( "=\"" );
if ( a.getAttribute( att ) != null )
{
text.append( a.getAttribute( att ).toString() );
}
text.append( "\"" );
}
text.append( " />" );
}
@Override
public void handleText( char[] data, int pos )
{
StringTokenizer tokens = new StringTokenizer( new String( data ), " ", true );
while ( tokens.hasMoreElements() )
{
String token = (String) tokens.nextElement();
/* weird that the parser should return these brackets... */
if ( token.startsWith( ">" ) )
{
if ( token.length() == 1 )
{
text.write( ">" );
continue;
}
else
{
token = token.substring( 1 );
}
}
if ( token.indexOf( ':' ) > -1 )
{
if ( !inlink )
{
String link = MarkedUpTextModel.markUp( token, project );
if ( link == null )
{
text.write( escapeString( token ) );
}
else
{
text.write( link );
}
}
else
{
text.write( escapeString( token ) );
}
}
else
{
text.write( escapeString( token ) );
}
}
}
@Override
public void handleEndOfLineString( String eol )
{
text.append( eol );
}
};
new ParserDelegator().parse( new StringReader( in ), callback, false );
return text.toString();
}
catch ( IOException e )
{
return "(unable to parse document)";
}
}
|
diff --git a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/init/ResourceDatabasePopulator.java b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/init/ResourceDatabasePopulator.java
index 157794a02..2e8e90702 100644
--- a/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/init/ResourceDatabasePopulator.java
+++ b/org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/init/ResourceDatabasePopulator.java
@@ -1,249 +1,249 @@
/*
* Copyright 2002-2009 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.jdbc.datasource.init;
import java.io.IOException;
import java.io.LineNumberReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.util.StringUtils;
/**
* Populates a database from SQL scripts defined in external resources.
*
* <p>Call {@link #addScript(Resource)} to add a SQL script location.<br>
* Call {@link #setSqlScriptEncoding(String)} to set the encoding for all added scripts.<br>
*
* @author Keith Donald
* @author Dave Syer
* @since 3.0
*/
public class ResourceDatabasePopulator implements DatabasePopulator {
private static final Log logger = LogFactory.getLog(ResourceDatabasePopulator.class);
private List<Resource> scripts = new ArrayList<Resource>();
private String sqlScriptEncoding;
private boolean continueOnError = false;
private boolean ignoreFailedDrops = false;
private static String COMMENT_PREFIX = "--";
/**
* Add a script to execute to populate the database.
* @param script the path to a SQL script
*/
public void addScript(Resource script) {
scripts.add(script);
}
/**
* Set the scripts to execute to populate the database.
* @param scripts the scripts to execute
*/
public void setScripts(Resource[] scripts) {
this.scripts = Arrays.asList(scripts);
}
/**
* Specify the encoding for SQL scripts, if different from the platform encoding.
* Note setting this property has no effect on added scripts that are already
* {@link EncodedResource encoded resources}.
* @see #addScript(Resource)
*/
public void setSqlScriptEncoding(String sqlScriptEncoding) {
this.sqlScriptEncoding = sqlScriptEncoding;
}
/**
* Flag to indicate that all failures in SQL should be logged but not cause a failure.
* Defaults to false.
* @param continueOnError the flag value to set
*/
public void setContinueOnError(boolean continueOnError) {
this.continueOnError = continueOnError;
}
/**
* Flag to indicate that a failed SQL <code>DROP</code> statement can be ignored.
* This is useful for non-embedded databases whose SQL dialect does not support an <code>IF EXISTS</code> clause in a <code>DROP</code>.
* The default is false so that if it the populator runs accidentally, it will failfast when the script starts with a <code>DROP</code>.
* @param ignoreFailedDrops the flag value to set
*/
public void setIgnoreFailedDrops(boolean ignoreFailedDrops) {
this.ignoreFailedDrops = ignoreFailedDrops;
}
public void populate(Connection connection) throws SQLException {
for (Resource script : this.scripts) {
executeSqlScript(connection, applyEncodingIfNecessary(script), this.continueOnError, this.ignoreFailedDrops);
}
}
private EncodedResource applyEncodingIfNecessary(Resource script) {
if (script instanceof EncodedResource) {
return (EncodedResource) script;
} else {
return new EncodedResource(script, this.sqlScriptEncoding);
}
}
/**
* Execute the given SQL script. <p>The script will normally be loaded by classpath. There should be one statement
* per line. Any semicolons will be removed. <b>Do not use this method to execute DDL if you expect rollback.</b>
* @param template the SimpleJdbcTemplate with which to perform JDBC operations
* @param resource the resource (potentially associated with a specific encoding) to load the SQL script from.
* @param continueOnError whether or not to continue without throwing an exception in the event of an error.
* @param ignoreFailedDrops whether of not to continue in thw event of specifically an error on a <code>DROP</code>.
*/
private void executeSqlScript(Connection connection, EncodedResource resource, boolean continueOnError, boolean ignoreFailedDrops)
throws SQLException {
if (logger.isInfoEnabled()) {
logger.info("Executing SQL script from " + resource);
}
long startTime = System.currentTimeMillis();
List<String> statements = new LinkedList<String>();
String script;
try {
script = readScript(resource);
} catch (IOException e) {
throw new CannotReadScriptException(resource, e);
}
char delimiter = ';';
if (!containsSqlScriptDelimiters(script, delimiter)) {
delimiter = '\n';
}
splitSqlScript(script, delimiter, statements);
int lineNumber = 0;
Statement stmt = connection.createStatement();
try {
for (String statement : statements) {
lineNumber++;
try {
int rowsAffected = stmt.executeUpdate(statement);
if (logger.isDebugEnabled()) {
logger.debug(rowsAffected + " rows affected by SQL: " + statement);
}
} catch (SQLException ex) {
boolean dropStatement = statement.trim().toLowerCase().startsWith("drop");
if (continueOnError || (dropStatement && ignoreFailedDrops)) {
- if (logger.isWarnEnabled()) {
- logger.warn("Line " + lineNumber + " statement failed: " + statement, ex);
+ if (logger.isDebugEnabled()) {
+ logger.debug("Line " + lineNumber + " statement failed: " + statement, ex);
}
} else {
throw ex;
}
}
}
} finally {
try {
stmt.close();
} catch (Throwable ex) {
logger.debug("Could not close JDBC Statement", ex);
}
}
long elapsedTime = System.currentTimeMillis() - startTime;
if (logger.isInfoEnabled()) {
logger.info("Done executing SQL script from " + resource + " in " + elapsedTime + " ms.");
}
}
/**
* Read a script from the LineNumberReader and build a String containing the lines.
* @param lineNumberReader the <code>LineNumberReader</> containing the script to be processed
* @return <code>String</code> containing the script lines
* @throws IOException
*/
private static String readScript(EncodedResource resource) throws IOException {
LineNumberReader lnr = new LineNumberReader(resource.getReader());
String currentStatement = lnr.readLine();
StringBuilder scriptBuilder = new StringBuilder();
while (currentStatement != null) {
if (StringUtils.hasText(currentStatement) && !currentStatement.startsWith(COMMENT_PREFIX)) {
if (scriptBuilder.length() > 0) {
scriptBuilder.append('\n');
}
scriptBuilder.append(currentStatement);
}
currentStatement = lnr.readLine();
}
return scriptBuilder.toString();
}
/**
* Does the provided SQL script contain the specified delimiter?
* @param script the SQL script
* @param delim character delimiting each statement - typically a ';' character
*/
private static boolean containsSqlScriptDelimiters(String script, char delim) {
boolean inLiteral = false;
char[] content = script.toCharArray();
for (int i = 0; i < script.length(); i++) {
if (content[i] == '\'') {
inLiteral = !inLiteral;
}
if (content[i] == delim && !inLiteral) {
return true;
}
}
return false;
}
/**
* Split an SQL script into separate statements delimited with the provided delimiter character. Each individual
* statement will be added to the provided <code>List</code>.
* @param script the SQL script
* @param delim character delimiting each statement - typically a ';' character
* @param statements the List that will contain the individual statements
*/
private static void splitSqlScript(String script, char delim, List<String> statements) {
StringBuilder sb = new StringBuilder();
boolean inLiteral = false;
char[] content = script.toCharArray();
for (int i = 0; i < script.length(); i++) {
if (content[i] == '\'') {
inLiteral = !inLiteral;
}
if (content[i] == delim && !inLiteral) {
if (sb.length() > 0) {
statements.add(sb.toString());
sb = new StringBuilder();
}
} else {
sb.append(content[i]);
}
}
if (sb.length() > 0) {
statements.add(sb.toString());
}
}
}
| true | true | private void executeSqlScript(Connection connection, EncodedResource resource, boolean continueOnError, boolean ignoreFailedDrops)
throws SQLException {
if (logger.isInfoEnabled()) {
logger.info("Executing SQL script from " + resource);
}
long startTime = System.currentTimeMillis();
List<String> statements = new LinkedList<String>();
String script;
try {
script = readScript(resource);
} catch (IOException e) {
throw new CannotReadScriptException(resource, e);
}
char delimiter = ';';
if (!containsSqlScriptDelimiters(script, delimiter)) {
delimiter = '\n';
}
splitSqlScript(script, delimiter, statements);
int lineNumber = 0;
Statement stmt = connection.createStatement();
try {
for (String statement : statements) {
lineNumber++;
try {
int rowsAffected = stmt.executeUpdate(statement);
if (logger.isDebugEnabled()) {
logger.debug(rowsAffected + " rows affected by SQL: " + statement);
}
} catch (SQLException ex) {
boolean dropStatement = statement.trim().toLowerCase().startsWith("drop");
if (continueOnError || (dropStatement && ignoreFailedDrops)) {
if (logger.isWarnEnabled()) {
logger.warn("Line " + lineNumber + " statement failed: " + statement, ex);
}
} else {
throw ex;
}
}
}
} finally {
try {
stmt.close();
} catch (Throwable ex) {
logger.debug("Could not close JDBC Statement", ex);
}
}
long elapsedTime = System.currentTimeMillis() - startTime;
if (logger.isInfoEnabled()) {
logger.info("Done executing SQL script from " + resource + " in " + elapsedTime + " ms.");
}
}
| private void executeSqlScript(Connection connection, EncodedResource resource, boolean continueOnError, boolean ignoreFailedDrops)
throws SQLException {
if (logger.isInfoEnabled()) {
logger.info("Executing SQL script from " + resource);
}
long startTime = System.currentTimeMillis();
List<String> statements = new LinkedList<String>();
String script;
try {
script = readScript(resource);
} catch (IOException e) {
throw new CannotReadScriptException(resource, e);
}
char delimiter = ';';
if (!containsSqlScriptDelimiters(script, delimiter)) {
delimiter = '\n';
}
splitSqlScript(script, delimiter, statements);
int lineNumber = 0;
Statement stmt = connection.createStatement();
try {
for (String statement : statements) {
lineNumber++;
try {
int rowsAffected = stmt.executeUpdate(statement);
if (logger.isDebugEnabled()) {
logger.debug(rowsAffected + " rows affected by SQL: " + statement);
}
} catch (SQLException ex) {
boolean dropStatement = statement.trim().toLowerCase().startsWith("drop");
if (continueOnError || (dropStatement && ignoreFailedDrops)) {
if (logger.isDebugEnabled()) {
logger.debug("Line " + lineNumber + " statement failed: " + statement, ex);
}
} else {
throw ex;
}
}
}
} finally {
try {
stmt.close();
} catch (Throwable ex) {
logger.debug("Could not close JDBC Statement", ex);
}
}
long elapsedTime = System.currentTimeMillis() - startTime;
if (logger.isInfoEnabled()) {
logger.info("Done executing SQL script from " + resource + " in " + elapsedTime + " ms.");
}
}
|
diff --git a/src/java/org/lwjgl/test/opengl/Game.java b/src/java/org/lwjgl/test/opengl/Game.java
index 0f6c9658..3cdbdfa1 100644
--- a/src/java/org/lwjgl/test/opengl/Game.java
+++ b/src/java/org/lwjgl/test/opengl/Game.java
@@ -1,193 +1,193 @@
/*
* Copyright (c) 2002 Lightweight Java Game Library Project
* 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 'Light Weight Java Game Library' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* $Id$
*
* Simple java test program.
*
* @author elias_naur <[email protected]>
* @version $Revision$
*/
package org.lwjgl.test.opengl;
import org.lwjgl.*;
import org.lwjgl.opengl.*;
import org.lwjgl.input.*;
import java.nio.*;
public final class Game {
static {
try {
//find first display mode that allows us 640*480*16
int mode = -1;
DisplayMode[] modes = Display.getAvailableDisplayModes();
for (int i = 0; i < modes.length; i++) {
if (modes[i].width == 640
&& modes[i].height == 480
&& modes[i].bpp >= 16) {
mode = i;
break;
}
}
//select above found displaymode
Display.create(modes[mode], false, "LWJGL Game Example");
System.out.println("Created display.");
} catch (Exception e) {
System.err.println("Failed to create display due to " + e);
System.exit(1);
}
}
public static final GL gl = new GL();
public static final GLU glu = new GLU(gl);
static {
try {
gl.create();
System.out.println("Created OpenGL.");
} catch (Exception e) {
System.err.println("Failed to create OpenGL due to "+e);
System.exit(1);
}
}
/** Is the game finished? */
private static boolean finished;
/** A rotating square! */
private static float angle;
/**
* No construction allowed
*/
private Game() {
}
public static void main(String[] arguments) {
try {
init();
while (!finished) {
// Keyboard.poll();
mainLoop();
render();
gl.swapBuffers();
}
} catch (Throwable t) {
t.printStackTrace();
} finally {
cleanup();
}
}
/**
* All calculations are done in here
*/
private static void mainLoop() {
angle += 1f;
if (angle > 360.0f)
angle = 0.0f;
Mouse.poll();
- if (Mouse.dx != 0 || Mouse.dy != 0 || Mouse.dz != 0)
- System.out.println("Mouse moved " + Mouse.dx + " " + Mouse.dy + " " + Mouse.dz);
- for (int i = 0; i < 8; i++)
+ if (Mouse.dx != 0 || Mouse.dy != 0 || Mouse.dwheel != 0)
+ System.out.println("Mouse moved " + Mouse.dx + " " + Mouse.dy + " " + Mouse.dwheel);
+ for (int i = 0; i < Mouse.buttonCount; i++)
if (Mouse.isButtonDown(i))
System.out.println("Button " + i + " down");
/* Keyboard.poll();
if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE))
finished = true;*/
Keyboard.read();
for (int i = 0; i < Keyboard.getNumKeyboardEvents(); i++) {
Keyboard.next();
if (Keyboard.key == Keyboard.KEY_ESCAPE && Keyboard.state)
finished = true;
if (Keyboard.key == Keyboard.KEY_T && Keyboard.state)
System.out.println("Current time: " + Sys.getTime());
}
}
/**
* All rendering is done in here
*/
private static void render() {
gl.clear(GL.COLOR_BUFFER_BIT);
gl.pushMatrix();
gl.translatef(Display.getWidth() / 2, Display.getHeight() / 2, 0.0f);
gl.rotatef(angle, 0, 0, 1.0f);
gl.begin(GL.QUADS);
gl.vertex2i(-50, -50);
gl.vertex2i(50, -50);
gl.vertex2i(50, 50);
gl.vertex2i(-50, 50);
gl.end();
gl.popMatrix();
}
/**
* Initialize
*/
private static void init() throws Exception {
Keyboard.create();
Keyboard.enableBuffer();
Mouse.create();
Sys.setTime(0);
Sys.setProcessPriority(Sys.HIGH_PRIORITY);
System.out.println("Timer resolution: " + Sys.getTimerResolution());
// Go into orthographic projection mode.
gl.matrixMode(GL.PROJECTION);
gl.loadIdentity();
glu.ortho2D(0, Display.getWidth(), 0, Display.getHeight());
gl.matrixMode(GL.MODELVIEW);
gl.loadIdentity();
gl.viewport(0, 0, Display.getWidth(), Display.getHeight());
ByteBuffer num_tex_units_buf = ByteBuffer.allocateDirect(4);
num_tex_units_buf.order(ByteOrder.nativeOrder());
int buf_addr = Sys.getDirectBufferAddress(num_tex_units_buf);
gl.getIntegerv(GL.MAX_TEXTURE_UNITS_ARB, buf_addr);
System.out.println("Number of texture units: " + num_tex_units_buf.getInt());
// Fix the refresh rate to the display frequency.
// gl.wglSwapIntervalEXT(1);
}
/**
* Cleanup
*/
private static void cleanup() {
Keyboard.destroy();
Mouse.destroy();
gl.destroy();
Display.destroy();
}
}
| true | true | private static void mainLoop() {
angle += 1f;
if (angle > 360.0f)
angle = 0.0f;
Mouse.poll();
if (Mouse.dx != 0 || Mouse.dy != 0 || Mouse.dz != 0)
System.out.println("Mouse moved " + Mouse.dx + " " + Mouse.dy + " " + Mouse.dz);
for (int i = 0; i < 8; i++)
if (Mouse.isButtonDown(i))
System.out.println("Button " + i + " down");
/* Keyboard.poll();
if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE))
finished = true;*/
Keyboard.read();
for (int i = 0; i < Keyboard.getNumKeyboardEvents(); i++) {
Keyboard.next();
if (Keyboard.key == Keyboard.KEY_ESCAPE && Keyboard.state)
finished = true;
if (Keyboard.key == Keyboard.KEY_T && Keyboard.state)
System.out.println("Current time: " + Sys.getTime());
}
}
| private static void mainLoop() {
angle += 1f;
if (angle > 360.0f)
angle = 0.0f;
Mouse.poll();
if (Mouse.dx != 0 || Mouse.dy != 0 || Mouse.dwheel != 0)
System.out.println("Mouse moved " + Mouse.dx + " " + Mouse.dy + " " + Mouse.dwheel);
for (int i = 0; i < Mouse.buttonCount; i++)
if (Mouse.isButtonDown(i))
System.out.println("Button " + i + " down");
/* Keyboard.poll();
if (Keyboard.isKeyDown(Keyboard.KEY_ESCAPE))
finished = true;*/
Keyboard.read();
for (int i = 0; i < Keyboard.getNumKeyboardEvents(); i++) {
Keyboard.next();
if (Keyboard.key == Keyboard.KEY_ESCAPE && Keyboard.state)
finished = true;
if (Keyboard.key == Keyboard.KEY_T && Keyboard.state)
System.out.println("Current time: " + Sys.getTime());
}
}
|
diff --git a/client/Android/FreeRDPCore/src/com/freerdp/freerdpcore/services/BookmarkDB.java b/client/Android/FreeRDPCore/src/com/freerdp/freerdpcore/services/BookmarkDB.java
index 1ea56d1f9..5d10d7048 100644
--- a/client/Android/FreeRDPCore/src/com/freerdp/freerdpcore/services/BookmarkDB.java
+++ b/client/Android/FreeRDPCore/src/com/freerdp/freerdpcore/services/BookmarkDB.java
@@ -1,140 +1,142 @@
/*
Android Bookmark Database
Copyright 2013 Thinstuff Technologies GmbH, Author: Martin Fleisz
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.freerdp.freerdpcore.services;
import android.content.Context;
import android.provider.BaseColumns;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class BookmarkDB extends SQLiteOpenHelper
{
private static final int DB_VERSION = 1;
private static final String DB_NAME = "bookmarks.db";
public static final String ID = BaseColumns._ID;
public BookmarkDB(Context context)
{
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
String sqlScreenSettings =
"CREATE TABLE tbl_screen_settings ("
+ ID + " INTEGER PRIMARY KEY, "
+ "colors INTEGER DEFAULT 16, "
+ "resolution INTEGER DEFAULT 0, "
+ "width, "
+ "height);";
db.execSQL(sqlScreenSettings);
String sqlPerformanceFlags =
"CREATE TABLE tbl_performance_flags ("
+ ID + " INTEGER PRIMARY KEY, "
+ "perf_remotefx INTEGER, "
+ "perf_wallpaper INTEGER, "
+ "perf_theming INTEGER, "
+ "perf_full_window_drag INTEGER, "
+ "perf_menu_animations INTEGER, "
+ "perf_font_smoothing INTEGER, "
+ "perf_desktop_composition INTEGER);";
db.execSQL(sqlPerformanceFlags);
String sqlManualBookmarks =
"CREATE TABLE tbl_manual_bookmarks ("
+ ID + " INTEGER PRIMARY KEY, "
+ "label TEXT NOT NULL, "
+ "hostname TEXT NOT NULL, "
+ "username TEXT NOT NULL, "
+ "password TEXT, "
+ "domain TEXT, "
+ "port TEXT, "
+ "screen_settings INTEGER NOT NULL, "
+ "performance_flags INTEGER NOT NULL, "
+ "enable_3g_settings INTEGER DEFAULT 0, "
+ "screen_3g INTEGER NOT NULL, "
+ "performance_3g INTEGER NOT NULL, "
+ "security INTEGER, "
+ "remote_program TEXT, "
+ "work_dir TEXT, "
+ "console_mode INTEGER, "
+ "FOREIGN KEY(screen_settings) REFERENCES tbl_screen_settings(" + ID + "), "
+ "FOREIGN KEY(performance_flags) REFERENCES tbl_performance_flags(" + ID + "), "
+ "FOREIGN KEY(screen_3g) REFERENCES tbl_screen_settings(" + ID + "), "
+ "FOREIGN KEY(performance_3g) REFERENCES tbl_performance_flags(" + ID + ") "
+ ");";
db.execSQL(sqlManualBookmarks);
// Insert a test entry
String sqlInsertDefaultScreenEntry =
"INSERT INTO tbl_screen_settings ("
+ "colors, "
+ "resolution, "
+ "width, "
+ "height) "
+ "VALUES ( "
+ "32, 1, 1024, 768);";
db.execSQL(sqlInsertDefaultScreenEntry);
+ db.execSQL(sqlInsertDefaultScreenEntry);
String sqlInsertDefaultPerfFlags =
"INSERT INTO tbl_performance_flags ("
+ "perf_remotefx, "
+ "perf_wallpaper, "
+ "perf_theming, "
+ "perf_full_window_drag, "
+ "perf_menu_animations, "
+ "perf_font_smoothing, "
+ "perf_desktop_composition) "
+ "VALUES ( "
+ "1, 0, 0, 0, 0, 0, 0);";
db.execSQL(sqlInsertDefaultPerfFlags);
+ db.execSQL(sqlInsertDefaultPerfFlags);
String sqlInsertDefaultSessionEntry =
"INSERT INTO tbl_manual_bookmarks ("
+ "label, "
+ "hostname, "
+ "username, "
+ "password, "
+ "domain, "
+ "port, "
+ "screen_settings, "
+ "performance_flags, "
+ "screen_3g, "
+ "performance_3g, "
+ "security, "
+ "remote_program, "
+ "work_dir, "
+ "console_mode) "
+ "VALUES ( "
+ "'Test Server', "
+ "'testservice.afreerdp.com', "
+ "'', "
+ "'', "
+ "'', "
+ "3389, "
+ "1, 1, 2, 2, 0, '', '', 0);";
db.execSQL(sqlInsertDefaultSessionEntry);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
}
| false | true | public void onCreate(SQLiteDatabase db)
{
String sqlScreenSettings =
"CREATE TABLE tbl_screen_settings ("
+ ID + " INTEGER PRIMARY KEY, "
+ "colors INTEGER DEFAULT 16, "
+ "resolution INTEGER DEFAULT 0, "
+ "width, "
+ "height);";
db.execSQL(sqlScreenSettings);
String sqlPerformanceFlags =
"CREATE TABLE tbl_performance_flags ("
+ ID + " INTEGER PRIMARY KEY, "
+ "perf_remotefx INTEGER, "
+ "perf_wallpaper INTEGER, "
+ "perf_theming INTEGER, "
+ "perf_full_window_drag INTEGER, "
+ "perf_menu_animations INTEGER, "
+ "perf_font_smoothing INTEGER, "
+ "perf_desktop_composition INTEGER);";
db.execSQL(sqlPerformanceFlags);
String sqlManualBookmarks =
"CREATE TABLE tbl_manual_bookmarks ("
+ ID + " INTEGER PRIMARY KEY, "
+ "label TEXT NOT NULL, "
+ "hostname TEXT NOT NULL, "
+ "username TEXT NOT NULL, "
+ "password TEXT, "
+ "domain TEXT, "
+ "port TEXT, "
+ "screen_settings INTEGER NOT NULL, "
+ "performance_flags INTEGER NOT NULL, "
+ "enable_3g_settings INTEGER DEFAULT 0, "
+ "screen_3g INTEGER NOT NULL, "
+ "performance_3g INTEGER NOT NULL, "
+ "security INTEGER, "
+ "remote_program TEXT, "
+ "work_dir TEXT, "
+ "console_mode INTEGER, "
+ "FOREIGN KEY(screen_settings) REFERENCES tbl_screen_settings(" + ID + "), "
+ "FOREIGN KEY(performance_flags) REFERENCES tbl_performance_flags(" + ID + "), "
+ "FOREIGN KEY(screen_3g) REFERENCES tbl_screen_settings(" + ID + "), "
+ "FOREIGN KEY(performance_3g) REFERENCES tbl_performance_flags(" + ID + ") "
+ ");";
db.execSQL(sqlManualBookmarks);
// Insert a test entry
String sqlInsertDefaultScreenEntry =
"INSERT INTO tbl_screen_settings ("
+ "colors, "
+ "resolution, "
+ "width, "
+ "height) "
+ "VALUES ( "
+ "32, 1, 1024, 768);";
db.execSQL(sqlInsertDefaultScreenEntry);
String sqlInsertDefaultPerfFlags =
"INSERT INTO tbl_performance_flags ("
+ "perf_remotefx, "
+ "perf_wallpaper, "
+ "perf_theming, "
+ "perf_full_window_drag, "
+ "perf_menu_animations, "
+ "perf_font_smoothing, "
+ "perf_desktop_composition) "
+ "VALUES ( "
+ "1, 0, 0, 0, 0, 0, 0);";
db.execSQL(sqlInsertDefaultPerfFlags);
String sqlInsertDefaultSessionEntry =
"INSERT INTO tbl_manual_bookmarks ("
+ "label, "
+ "hostname, "
+ "username, "
+ "password, "
+ "domain, "
+ "port, "
+ "screen_settings, "
+ "performance_flags, "
+ "screen_3g, "
+ "performance_3g, "
+ "security, "
+ "remote_program, "
+ "work_dir, "
+ "console_mode) "
+ "VALUES ( "
+ "'Test Server', "
+ "'testservice.afreerdp.com', "
+ "'', "
+ "'', "
+ "'', "
+ "3389, "
+ "1, 1, 2, 2, 0, '', '', 0);";
db.execSQL(sqlInsertDefaultSessionEntry);
}
| public void onCreate(SQLiteDatabase db)
{
String sqlScreenSettings =
"CREATE TABLE tbl_screen_settings ("
+ ID + " INTEGER PRIMARY KEY, "
+ "colors INTEGER DEFAULT 16, "
+ "resolution INTEGER DEFAULT 0, "
+ "width, "
+ "height);";
db.execSQL(sqlScreenSettings);
String sqlPerformanceFlags =
"CREATE TABLE tbl_performance_flags ("
+ ID + " INTEGER PRIMARY KEY, "
+ "perf_remotefx INTEGER, "
+ "perf_wallpaper INTEGER, "
+ "perf_theming INTEGER, "
+ "perf_full_window_drag INTEGER, "
+ "perf_menu_animations INTEGER, "
+ "perf_font_smoothing INTEGER, "
+ "perf_desktop_composition INTEGER);";
db.execSQL(sqlPerformanceFlags);
String sqlManualBookmarks =
"CREATE TABLE tbl_manual_bookmarks ("
+ ID + " INTEGER PRIMARY KEY, "
+ "label TEXT NOT NULL, "
+ "hostname TEXT NOT NULL, "
+ "username TEXT NOT NULL, "
+ "password TEXT, "
+ "domain TEXT, "
+ "port TEXT, "
+ "screen_settings INTEGER NOT NULL, "
+ "performance_flags INTEGER NOT NULL, "
+ "enable_3g_settings INTEGER DEFAULT 0, "
+ "screen_3g INTEGER NOT NULL, "
+ "performance_3g INTEGER NOT NULL, "
+ "security INTEGER, "
+ "remote_program TEXT, "
+ "work_dir TEXT, "
+ "console_mode INTEGER, "
+ "FOREIGN KEY(screen_settings) REFERENCES tbl_screen_settings(" + ID + "), "
+ "FOREIGN KEY(performance_flags) REFERENCES tbl_performance_flags(" + ID + "), "
+ "FOREIGN KEY(screen_3g) REFERENCES tbl_screen_settings(" + ID + "), "
+ "FOREIGN KEY(performance_3g) REFERENCES tbl_performance_flags(" + ID + ") "
+ ");";
db.execSQL(sqlManualBookmarks);
// Insert a test entry
String sqlInsertDefaultScreenEntry =
"INSERT INTO tbl_screen_settings ("
+ "colors, "
+ "resolution, "
+ "width, "
+ "height) "
+ "VALUES ( "
+ "32, 1, 1024, 768);";
db.execSQL(sqlInsertDefaultScreenEntry);
db.execSQL(sqlInsertDefaultScreenEntry);
String sqlInsertDefaultPerfFlags =
"INSERT INTO tbl_performance_flags ("
+ "perf_remotefx, "
+ "perf_wallpaper, "
+ "perf_theming, "
+ "perf_full_window_drag, "
+ "perf_menu_animations, "
+ "perf_font_smoothing, "
+ "perf_desktop_composition) "
+ "VALUES ( "
+ "1, 0, 0, 0, 0, 0, 0);";
db.execSQL(sqlInsertDefaultPerfFlags);
db.execSQL(sqlInsertDefaultPerfFlags);
String sqlInsertDefaultSessionEntry =
"INSERT INTO tbl_manual_bookmarks ("
+ "label, "
+ "hostname, "
+ "username, "
+ "password, "
+ "domain, "
+ "port, "
+ "screen_settings, "
+ "performance_flags, "
+ "screen_3g, "
+ "performance_3g, "
+ "security, "
+ "remote_program, "
+ "work_dir, "
+ "console_mode) "
+ "VALUES ( "
+ "'Test Server', "
+ "'testservice.afreerdp.com', "
+ "'', "
+ "'', "
+ "'', "
+ "3389, "
+ "1, 1, 2, 2, 0, '', '', 0);";
db.execSQL(sqlInsertDefaultSessionEntry);
}
|
diff --git a/motech-mobile-omp/src/main/java/com/dreamoval/motech/omp/manager/orserve/ORServeGatewayMessageHandlerImpl.java b/motech-mobile-omp/src/main/java/com/dreamoval/motech/omp/manager/orserve/ORServeGatewayMessageHandlerImpl.java
index 225050d6..826fdc5b 100644
--- a/motech-mobile-omp/src/main/java/com/dreamoval/motech/omp/manager/orserve/ORServeGatewayMessageHandlerImpl.java
+++ b/motech-mobile-omp/src/main/java/com/dreamoval/motech/omp/manager/orserve/ORServeGatewayMessageHandlerImpl.java
@@ -1,179 +1,179 @@
package com.dreamoval.motech.omp.manager.orserve;
import com.dreamoval.motech.core.manager.CoreManager;
import com.dreamoval.motech.core.model.GatewayRequest;
import com.dreamoval.motech.core.model.GatewayResponse;
import com.dreamoval.motech.core.model.MStatus;
import com.dreamoval.motech.core.service.MotechContext;
import com.dreamoval.motech.omp.manager.GatewayMessageHandler;
import java.util.Date;
import java.util.Set;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
/**
* Handles preparation and parsing of messages and responses from the OutReach Server message gateway
*
* @author Kofi A. Asamoah ([email protected])
* @date Jul 15, 2009
*/
public class ORServeGatewayMessageHandlerImpl implements GatewayMessageHandler {
private CoreManager coreManager;
private static Logger logger = Logger.getLogger(ORServeGatewayMessageHandlerImpl.class);
private Map<MStatus, String> codeStatusMap;
private Map<MStatus, String> codeResponseMap;
/**
*
* @see GatewayMessageHandler.parseResponse
*/
public Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse, MotechContext context) {
logger.info("Parsing message gateway response");
logger.debug(gatewayResponse);
if(message == null)
return null;
if(gatewayResponse.isEmpty())
return null;
Set<GatewayResponse> responses = new HashSet<GatewayResponse>();
if(gatewayResponse.contains("error:") && gatewayResponse.contains("param:")){
- gatewayResponse = gatewayResponse.substring(0, 15).replace("\n", "");
+ gatewayResponse = gatewayResponse.trim().replace("\n", "");
}
String[] responseLines = gatewayResponse.split("\n");
for(String line : responseLines){
String[] responseParts = line.split(" ");
if(responseParts[0].equalsIgnoreCase("ID:")){
GatewayResponse response = getCoreManager().createGatewayResponse(context);
response.setGatewayMessageId(responseParts[1]);
response.setRequestId(message.getRequestId());
response.setMessageStatus(MStatus.PENDING);
response.setGatewayRequest(message);
response.setResponseText(gatewayResponse);
response.setDateCreated(new Date());
if(responseParts.length == 4)
response.setRecipientNumber(responseParts[3]);
else
response.setRecipientNumber(message.getRecipientsNumber());
responses.add(response);
}
else{
logger.error("Gateway returned error: " + gatewayResponse);
String errorCode = responseParts[1];
errorCode.replaceAll(",", "");
errorCode.trim();
MStatus status = lookupResponse(errorCode);
GatewayResponse response = getCoreManager().createGatewayResponse(context);
response.setRequestId(message.getRequestId());
response.setMessageStatus(status);
response.setGatewayRequest(message);
response.setResponseText(gatewayResponse);
response.setDateCreated(new Date());
responses.add(response);
}
}
logger.debug(responses);
return responses;
}
/**
*
* @see GatewayMessageHandler.parseMessageStatus
*/
public MStatus parseMessageStatus(String gatewayResponse) {
logger.info("Parsing message gateway status response");
String status;
String[] responseParts = gatewayResponse.split(" ");
if(responseParts.length == 4){
status = responseParts[3];
}
else{
status = "";
}
return lookupStatus(status);
}
/**
* @see GatewayMessageHandler.lookupStatus
*/
public MStatus lookupStatus(String code){
if(code.isEmpty()){
return MStatus.PENDING;
}
for(Entry<MStatus, String> entry: codeStatusMap.entrySet()){
if(entry.getValue().contains(code)){
return entry.getKey();
}
}
return MStatus.PENDING;
}
/**
* @see GatewayMessageHandler.lookupResponse
*/
public MStatus lookupResponse(String code){
if(code.isEmpty()){
return MStatus.SCHEDULED;
}
for(Entry<MStatus, String> entry: codeResponseMap.entrySet()){
if(entry.getValue().contains(code)){
return entry.getKey();
}
}
return MStatus.SCHEDULED;
}
/**
* @return the coreManager
*/
public CoreManager getCoreManager() {
return coreManager;
}
/**
* @param coreManager the coreManager to set
*/
public void setCoreManager(CoreManager coreManager) {
logger.debug("Setting ORServeGatewayMessageHandlerImpl.coreManager");
logger.debug(coreManager);
this.coreManager = coreManager;
}
public Map<MStatus, String> getCodeStatusMap() {
return codeStatusMap;
}
public void setCodeStatusMap(Map<MStatus, String> codeStatusMap) {
this.codeStatusMap = codeStatusMap;
}
public Map<MStatus, String> getCodeResponseMap() {
return codeResponseMap;
}
public void setCodeResponseMap(Map<MStatus, String> codeResponseMap) {
this.codeResponseMap = codeResponseMap;
}
}
| true | true | public Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse, MotechContext context) {
logger.info("Parsing message gateway response");
logger.debug(gatewayResponse);
if(message == null)
return null;
if(gatewayResponse.isEmpty())
return null;
Set<GatewayResponse> responses = new HashSet<GatewayResponse>();
if(gatewayResponse.contains("error:") && gatewayResponse.contains("param:")){
gatewayResponse = gatewayResponse.substring(0, 15).replace("\n", "");
}
String[] responseLines = gatewayResponse.split("\n");
for(String line : responseLines){
String[] responseParts = line.split(" ");
if(responseParts[0].equalsIgnoreCase("ID:")){
GatewayResponse response = getCoreManager().createGatewayResponse(context);
response.setGatewayMessageId(responseParts[1]);
response.setRequestId(message.getRequestId());
response.setMessageStatus(MStatus.PENDING);
response.setGatewayRequest(message);
response.setResponseText(gatewayResponse);
response.setDateCreated(new Date());
if(responseParts.length == 4)
response.setRecipientNumber(responseParts[3]);
else
response.setRecipientNumber(message.getRecipientsNumber());
responses.add(response);
}
else{
logger.error("Gateway returned error: " + gatewayResponse);
String errorCode = responseParts[1];
errorCode.replaceAll(",", "");
errorCode.trim();
MStatus status = lookupResponse(errorCode);
GatewayResponse response = getCoreManager().createGatewayResponse(context);
response.setRequestId(message.getRequestId());
response.setMessageStatus(status);
response.setGatewayRequest(message);
response.setResponseText(gatewayResponse);
response.setDateCreated(new Date());
responses.add(response);
}
}
logger.debug(responses);
return responses;
}
| public Set<GatewayResponse> parseMessageResponse(GatewayRequest message, String gatewayResponse, MotechContext context) {
logger.info("Parsing message gateway response");
logger.debug(gatewayResponse);
if(message == null)
return null;
if(gatewayResponse.isEmpty())
return null;
Set<GatewayResponse> responses = new HashSet<GatewayResponse>();
if(gatewayResponse.contains("error:") && gatewayResponse.contains("param:")){
gatewayResponse = gatewayResponse.trim().replace("\n", "");
}
String[] responseLines = gatewayResponse.split("\n");
for(String line : responseLines){
String[] responseParts = line.split(" ");
if(responseParts[0].equalsIgnoreCase("ID:")){
GatewayResponse response = getCoreManager().createGatewayResponse(context);
response.setGatewayMessageId(responseParts[1]);
response.setRequestId(message.getRequestId());
response.setMessageStatus(MStatus.PENDING);
response.setGatewayRequest(message);
response.setResponseText(gatewayResponse);
response.setDateCreated(new Date());
if(responseParts.length == 4)
response.setRecipientNumber(responseParts[3]);
else
response.setRecipientNumber(message.getRecipientsNumber());
responses.add(response);
}
else{
logger.error("Gateway returned error: " + gatewayResponse);
String errorCode = responseParts[1];
errorCode.replaceAll(",", "");
errorCode.trim();
MStatus status = lookupResponse(errorCode);
GatewayResponse response = getCoreManager().createGatewayResponse(context);
response.setRequestId(message.getRequestId());
response.setMessageStatus(status);
response.setGatewayRequest(message);
response.setResponseText(gatewayResponse);
response.setDateCreated(new Date());
responses.add(response);
}
}
logger.debug(responses);
return responses;
}
|
diff --git a/src/org/ohmage/dao/CampaignCreationDao.java b/src/org/ohmage/dao/CampaignCreationDao.java
index 0ce2d762..5f4bcfab 100644
--- a/src/org/ohmage/dao/CampaignCreationDao.java
+++ b/src/org/ohmage/dao/CampaignCreationDao.java
@@ -1,458 +1,458 @@
/*******************************************************************************
* Copyright 2011 The Regents of the University of California
*
* 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.ohmage.dao;
import java.io.IOException;
import java.io.StringReader;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.List;
import java.util.ListIterator;
import javax.sql.DataSource;
import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.ParsingException;
import nu.xom.ValidityException;
import org.apache.log4j.Logger;
import org.ohmage.cache.CacheMissException;
import org.ohmage.cache.CampaignPrivacyStateCache;
import org.ohmage.cache.CampaignRoleCache;
import org.ohmage.cache.CampaignRunningStateCache;
import org.ohmage.cache.ClassRoleCache;
import org.ohmage.request.AwRequest;
import org.ohmage.request.InputKeys;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.SingleColumnRowMapper;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
/**
* Adds the campaign to the database.
*
* @author John Jenkins
*/
public class CampaignCreationDao extends AbstractDao {
private static Logger _logger = Logger.getLogger(CampaignCreationDao.class);
private static final String SQL_GET_CAMPAIGN_ID = "SELECT id " +
"FROM campaign " +
"WHERE urn = ?";
private static final String SQL_GET_CLASS_ID = "SELECT id " +
"FROM class " +
"WHERE urn = ?";
private static final String SQL_GET_USER_ID = "SELECT id " +
"FROM user " +
"WHERE login_id = ?";
private static final String SQL_GET_CAMPAIGN_CLASS_ID = "SELECT id " +
"FROM campaign_class cc " +
"WHERE campaign_id = ? " +
"AND class_id = ?";
private static final String SQL_GET_USERS_FROM_CLASS = "SELECT user_id, user_class_role_id " +
"FROM user_class " +
"WHERE class_id = ?";
private static final String SQL_GET_CAMPAIGN_CLASS_DEFAULT_ROLES = "SELECT user_role_id " +
"FROM campaign_class_default_role " +
"WHERE campaign_class_id = ? " +
"AND user_class_role_id = ?";
private static final String SQL_INSERT_CAMPAIGN = "INSERT INTO campaign(description, xml, running_state_id, privacy_state_id, name, urn, creation_timestamp) " +
"VALUES (?,?,?,?,?,?,?)";
private static final String SQL_INSERT_CAMPAIGN_CLASS = "INSERT INTO campaign_class(campaign_id, class_id) " +
"VALUES (?,?)";
private static final String SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE = "INSERT INTO campaign_class_default_role(campaign_class_id, user_class_role_id, user_role_id) " +
"VALUES (?,?,?)";
private static final String SQL_INSERT_USER_ROLE_CAMPAIGN = "INSERT INTO user_role_campaign(user_id, campaign_id, user_role_id) " +
"VALUES (?,?,?)";
/**
* A private inner class for the purposes of retrieving the user id and
* IDs when querying the users in a class.
*
* @author John Jenkins
*/
private class UserAndRole {
public int _userId;
public int _roleId;
UserAndRole(int userId, int roleId) {
_userId = userId;
_roleId = roleId;
}
}
/**
* Creates a basic DAO.
*
* @param dataSource The DataSource that we will run our queries against.
*/
public CampaignCreationDao(DataSource dataSource) {
super(dataSource);
}
/**
* Adds the campaign to the database, connects the classes to the
* campaign, and sets the currently logged in user as the creator.
*/
@Override
public void execute(AwRequest awRequest) {
_logger.info("Inserting campaign into the database.");
// Note: This function is a bear, but I tried to document it well and
// give it a nice flow. May need refactoring if major changes are to
// be made.
String campaignXml;
try {
campaignXml = (String) awRequest.getToProcessValue(InputKeys.XML);
}
catch(IllegalArgumentException e) {
throw new DataAccessException(e);
}
// Now use XOM to retrieve a Document and a root node for further processing. XOM is used because it has a
// very simple XPath API
Builder builder = new Builder();
Document document;
try {
document = builder.build(new StringReader(campaignXml));
} catch (IOException e) {
// The XML should already have been validated, so this should
// never happen.
_logger.error("Unable to read XML.", e);
throw new DataAccessException("XML was unreadable.");
} catch (ValidityException e) {
// The XML should already have been validated, so this should
// never happen.
_logger.error("Invalid XML.", e);
throw new DataAccessException("XML was invalid.");
} catch (ParsingException e) {
// The XML should already have been validated, so this should
// never happen.
_logger.error("Unparcelable XML.", e);
throw new DataAccessException("XML was unparcelable.");
}
Element root = document.getRootElement();
- String campaignUrn = root.query("/campaign/campaignUrn").get(0).getValue();
- String campaignName = root.query("/campaign/campaignName").get(0).getValue();
+ String campaignUrn = root.query("/campaign/campaignUrn").get(0).getValue().trim();
+ String campaignName = root.query("/campaign/campaignName").get(0).getValue().trim();
Calendar now = Calendar.getInstance();
String nowFormatted = now.get(Calendar.YEAR) + "-" + now.get(Calendar.MONTH) + "-" + now.get(Calendar.DAY_OF_MONTH) + " " +
now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND);
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setName("Campaign creation and user/class hookups.");
try {
PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource());
TransactionStatus status = transactionManager.getTransaction(def);
try {
getJdbcTemplate().update(SQL_INSERT_CAMPAIGN,
new Object[] { ((awRequest.existsInToProcess(InputKeys.DESCRIPTION)) ? awRequest.getToProcessValue(InputKeys.DESCRIPTION) : "" ),
awRequest.getToProcessValue(InputKeys.XML),
CampaignRunningStateCache.instance().lookup((String) awRequest.getToProcessValue(InputKeys.RUNNING_STATE)),
CampaignPrivacyStateCache.instance().lookup((String) awRequest.getToProcessValue(InputKeys.PRIVACY_STATE)),
campaignName,
campaignUrn,
nowFormatted});
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_INSERT_CAMPAIGN + "' with parameters: " +
((awRequest.existsInToProcess(InputKeys.DESCRIPTION)) ? awRequest.getToProcessValue(InputKeys.DESCRIPTION) : "" ) + ", " +
awRequest.getToProcessValue(InputKeys.XML) + ", " +
awRequest.getToProcessValue(InputKeys.RUNNING_STATE) + ", " +
awRequest.getToProcessValue(InputKeys.PRIVACY_STATE) + ", " +
campaignName + ", " +
campaignUrn + ", " +
nowFormatted, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
catch(CacheMissException e) {
transactionManager.rollback(status);
throw new DataAccessException("Unknown running or privacy state in the cache.", e);
}
catch(IllegalArgumentException e) {
transactionManager.rollback(status);
throw new DataAccessException("Missing parameter in the toProcess map.", e);
}
// Get campaign ID.
int campaignId;
try {
campaignId = getJdbcTemplate().queryForInt(SQL_GET_CAMPAIGN_ID, new Object[] { campaignUrn });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_GET_CAMPAIGN_ID + "' with parameter: " + campaignUrn, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Get the campaign role supervisor's ID.
int supervisorId;
try {
supervisorId = CampaignRoleCache.instance().lookup(CampaignRoleCache.ROLE_SUPERVISOR);
}
catch(CacheMissException e) {
_logger.error("The cache doesn't know about known role " + CampaignRoleCache.ROLE_SUPERVISOR, e);
throw new DataAccessException(e);
}
// Get the campaign role analyst's ID.
int analystId;
try {
analystId = CampaignRoleCache.instance().lookup(CampaignRoleCache.ROLE_ANALYST);
}
catch(CacheMissException e) {
_logger.error("The cache doesn't know about known role " + CampaignRoleCache.ROLE_ANALYST, e);
throw new DataAccessException(e);
}
// Get the campaign role author's ID.
int authorId;
try {
authorId = CampaignRoleCache.instance().lookup(CampaignRoleCache.ROLE_AUTHOR);
}
catch(CacheMissException dae) {
_logger.error("The cache doesn't know about known role " + CampaignRoleCache.ROLE_AUTHOR, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Get the campaign role participant's ID.
int participantId;
try {
participantId = CampaignRoleCache.instance().lookup(CampaignRoleCache.ROLE_PARTICIPANT);
}
catch(CacheMissException e) {
_logger.error("The cache doesn't know about known role " + CampaignRoleCache.ROLE_PARTICIPANT, e);
throw new DataAccessException(e);
}
// Get the ID for privileged users.
int privilegedId;
try {
privilegedId = ClassRoleCache.instance().lookup(ClassRoleCache.ROLE_PRIVILEGED);
}
catch(CacheMissException e) {
_logger.error("The cache doesn't know about known role " + ClassRoleCache.ROLE_PRIVILEGED, e);
throw new DataAccessException(e);
}
// Get the ID for restricted users.
int restrictedId;
try {
restrictedId = ClassRoleCache.instance().lookup(ClassRoleCache.ROLE_RESTRICTED);
}
catch(CacheMissException e) {
_logger.error("The cache doesn't know about known role " + ClassRoleCache.ROLE_RESTRICTED, e);
throw new DataAccessException(e);
}
// Get the currently logged in user's ID.
int userId;
try {
userId = getJdbcTemplate().queryForInt(SQL_GET_USER_ID, new Object[] { awRequest.getUser().getUserName() });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_GET_USER_ID + "' with parameter: " + awRequest.getUser().getUserName(), dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Make the current user the creator.
try {
getJdbcTemplate().update(SQL_INSERT_USER_ROLE_CAMPAIGN, new Object[] { userId, campaignId, authorId });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_INSERT_USER_ROLE_CAMPAIGN + "' with parameters: " + userId + ", " + campaignId + ", " + authorId, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Hookup to classes and users.
String[] classes = ((String) awRequest.getToProcessValue(InputKeys.CLASS_URN_LIST)).split(InputKeys.LIST_ITEM_SEPARATOR);
for(int i = 0; i < classes.length; i++) {
// Get the current class' ID.
int classId;
try {
classId = getJdbcTemplate().queryForInt(SQL_GET_CLASS_ID, new Object[] { classes[i] });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_GET_CLASS_ID + "' with parameter: " + classes[i], dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Hookup the current class with the campaign.
try {
getJdbcTemplate().update(SQL_INSERT_CAMPAIGN_CLASS, new Object[] { campaignId, classId });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_INSERT_CAMPAIGN_CLASS + "' with parameters: " + campaignId + ", " + classId, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Get the ID of that newly inserted row.
int campaignClassId;
try {
campaignClassId = getJdbcTemplate().queryForInt(SQL_GET_CAMPAIGN_CLASS_ID, new Object[] { campaignId, classId });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_GET_CAMPAIGN_CLASS_ID + "' with parameters: " + campaignId + ", " + classId, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Insert the default campaign_class_default_role
// relationships for privileged users.
// TODO: This should be a parameter in the API.
try {
getJdbcTemplate().update(SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE, new Object[] { campaignClassId, privilegedId, supervisorId });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE + "' with parameters: " + campaignClassId + ", " + privilegedId + ", " + supervisorId, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
try {
getJdbcTemplate().update(SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE, new Object[] { campaignClassId, privilegedId, participantId });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE + "' with parameters: " + campaignClassId + ", " + privilegedId + ", " + participantId, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Insert the default campaign_class_default_role
// relationships for restricted users.
// TODO: This should be a parameter in the API.
try {
getJdbcTemplate().update(SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE, new Object[] { campaignClassId, restrictedId, analystId });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE + "' with parameters: " + campaignClassId + ", " + restrictedId + ", " + supervisorId, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
try {
getJdbcTemplate().update(SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE, new Object[] { campaignClassId, restrictedId, participantId });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE + "' with parameters: " + campaignClassId + ", " + restrictedId + ", " + participantId, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Get the list of students in this class.
List<?> users;
try {
users = getJdbcTemplate().query(SQL_GET_USERS_FROM_CLASS,
new Object[] { classId },
new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
return new UserAndRole(rs.getInt("user_id"), rs.getInt("user_class_role_id"));
}
});
}
catch(org.springframework.dao.DataAccessException e) {
_logger.error("Error executing SQL '" + SQL_GET_USERS_FROM_CLASS + "' with parameter: " + classId, e);
transactionManager.rollback(status);
throw new DataAccessException(e);
}
// Associate the students with the campaign based on their
// class role.
ListIterator<?> usersIter = users.listIterator();
while(usersIter.hasNext()) {
UserAndRole uar = (UserAndRole) usersIter.next();
// Get the list of default roles for a user in this class
// associated with this campaign.
List<?> defaultRoles;
try {
defaultRoles = getJdbcTemplate().query(SQL_GET_CAMPAIGN_CLASS_DEFAULT_ROLES, new Object[] { campaignClassId, uar._roleId }, new SingleColumnRowMapper());
}
catch(org.springframework.dao.DataAccessException e) {
_logger.error("Error executing SQL '" + SQL_GET_CAMPAIGN_CLASS_DEFAULT_ROLES + "' with parameters: " + campaignClassId + ", " + uar._roleId, e);
transactionManager.rollback(status);
throw new DataAccessException(e);
}
// For each of these default roles
ListIterator<?> defaultRolesIter = defaultRoles.listIterator();
while(defaultRolesIter.hasNext()) {
int defaultRole = (Integer) defaultRolesIter.next();
if((uar._userId == userId) && (defaultRole == authorId)) {
// This already happened above.
continue;
}
// Associate the user with the campaign and the
// default role.
try {
getJdbcTemplate().update(SQL_INSERT_USER_ROLE_CAMPAIGN, new Object[] { uar._userId, campaignId, defaultRole });
}
catch(org.springframework.dao.DataIntegrityViolationException e) {
_logger.info("Attempting to add a user with the ID '" + uar._userId + "' into the user_role_campaign table with a role ID of '" +
defaultRole + "'; however such an association already exists for campaign '" + campaignId + "'.");
}
catch(org.springframework.dao.DataAccessException e) {
_logger.error("Error executing SQL '" + SQL_INSERT_USER_ROLE_CAMPAIGN + "' with parameters: " +
uar._userId + ", " + campaignId + ", " + defaultRole, e);
throw new DataAccessException(e);
}
}
}
}
// Try to commit everything and finish.
try {
transactionManager.commit(status);
}
catch(TransactionException e) {
_logger.error("Error while attempting to commit the transaction. Attempting to rollback.");
transactionManager.rollback(status);
throw new DataAccessException(e);
}
}
catch(TransactionException e) {
_logger.error("Error while attempting to rollback transaction.", e);
throw new DataAccessException(e);
}
}
}
| true | true | public void execute(AwRequest awRequest) {
_logger.info("Inserting campaign into the database.");
// Note: This function is a bear, but I tried to document it well and
// give it a nice flow. May need refactoring if major changes are to
// be made.
String campaignXml;
try {
campaignXml = (String) awRequest.getToProcessValue(InputKeys.XML);
}
catch(IllegalArgumentException e) {
throw new DataAccessException(e);
}
// Now use XOM to retrieve a Document and a root node for further processing. XOM is used because it has a
// very simple XPath API
Builder builder = new Builder();
Document document;
try {
document = builder.build(new StringReader(campaignXml));
} catch (IOException e) {
// The XML should already have been validated, so this should
// never happen.
_logger.error("Unable to read XML.", e);
throw new DataAccessException("XML was unreadable.");
} catch (ValidityException e) {
// The XML should already have been validated, so this should
// never happen.
_logger.error("Invalid XML.", e);
throw new DataAccessException("XML was invalid.");
} catch (ParsingException e) {
// The XML should already have been validated, so this should
// never happen.
_logger.error("Unparcelable XML.", e);
throw new DataAccessException("XML was unparcelable.");
}
Element root = document.getRootElement();
String campaignUrn = root.query("/campaign/campaignUrn").get(0).getValue();
String campaignName = root.query("/campaign/campaignName").get(0).getValue();
Calendar now = Calendar.getInstance();
String nowFormatted = now.get(Calendar.YEAR) + "-" + now.get(Calendar.MONTH) + "-" + now.get(Calendar.DAY_OF_MONTH) + " " +
now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND);
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setName("Campaign creation and user/class hookups.");
try {
PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource());
TransactionStatus status = transactionManager.getTransaction(def);
try {
getJdbcTemplate().update(SQL_INSERT_CAMPAIGN,
new Object[] { ((awRequest.existsInToProcess(InputKeys.DESCRIPTION)) ? awRequest.getToProcessValue(InputKeys.DESCRIPTION) : "" ),
awRequest.getToProcessValue(InputKeys.XML),
CampaignRunningStateCache.instance().lookup((String) awRequest.getToProcessValue(InputKeys.RUNNING_STATE)),
CampaignPrivacyStateCache.instance().lookup((String) awRequest.getToProcessValue(InputKeys.PRIVACY_STATE)),
campaignName,
campaignUrn,
nowFormatted});
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_INSERT_CAMPAIGN + "' with parameters: " +
((awRequest.existsInToProcess(InputKeys.DESCRIPTION)) ? awRequest.getToProcessValue(InputKeys.DESCRIPTION) : "" ) + ", " +
awRequest.getToProcessValue(InputKeys.XML) + ", " +
awRequest.getToProcessValue(InputKeys.RUNNING_STATE) + ", " +
awRequest.getToProcessValue(InputKeys.PRIVACY_STATE) + ", " +
campaignName + ", " +
campaignUrn + ", " +
nowFormatted, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
catch(CacheMissException e) {
transactionManager.rollback(status);
throw new DataAccessException("Unknown running or privacy state in the cache.", e);
}
catch(IllegalArgumentException e) {
transactionManager.rollback(status);
throw new DataAccessException("Missing parameter in the toProcess map.", e);
}
// Get campaign ID.
int campaignId;
try {
campaignId = getJdbcTemplate().queryForInt(SQL_GET_CAMPAIGN_ID, new Object[] { campaignUrn });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_GET_CAMPAIGN_ID + "' with parameter: " + campaignUrn, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Get the campaign role supervisor's ID.
int supervisorId;
try {
supervisorId = CampaignRoleCache.instance().lookup(CampaignRoleCache.ROLE_SUPERVISOR);
}
catch(CacheMissException e) {
_logger.error("The cache doesn't know about known role " + CampaignRoleCache.ROLE_SUPERVISOR, e);
throw new DataAccessException(e);
}
// Get the campaign role analyst's ID.
int analystId;
try {
analystId = CampaignRoleCache.instance().lookup(CampaignRoleCache.ROLE_ANALYST);
}
catch(CacheMissException e) {
_logger.error("The cache doesn't know about known role " + CampaignRoleCache.ROLE_ANALYST, e);
throw new DataAccessException(e);
}
// Get the campaign role author's ID.
int authorId;
try {
authorId = CampaignRoleCache.instance().lookup(CampaignRoleCache.ROLE_AUTHOR);
}
catch(CacheMissException dae) {
_logger.error("The cache doesn't know about known role " + CampaignRoleCache.ROLE_AUTHOR, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Get the campaign role participant's ID.
int participantId;
try {
participantId = CampaignRoleCache.instance().lookup(CampaignRoleCache.ROLE_PARTICIPANT);
}
catch(CacheMissException e) {
_logger.error("The cache doesn't know about known role " + CampaignRoleCache.ROLE_PARTICIPANT, e);
throw new DataAccessException(e);
}
// Get the ID for privileged users.
int privilegedId;
try {
privilegedId = ClassRoleCache.instance().lookup(ClassRoleCache.ROLE_PRIVILEGED);
}
catch(CacheMissException e) {
_logger.error("The cache doesn't know about known role " + ClassRoleCache.ROLE_PRIVILEGED, e);
throw new DataAccessException(e);
}
// Get the ID for restricted users.
int restrictedId;
try {
restrictedId = ClassRoleCache.instance().lookup(ClassRoleCache.ROLE_RESTRICTED);
}
catch(CacheMissException e) {
_logger.error("The cache doesn't know about known role " + ClassRoleCache.ROLE_RESTRICTED, e);
throw new DataAccessException(e);
}
// Get the currently logged in user's ID.
int userId;
try {
userId = getJdbcTemplate().queryForInt(SQL_GET_USER_ID, new Object[] { awRequest.getUser().getUserName() });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_GET_USER_ID + "' with parameter: " + awRequest.getUser().getUserName(), dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Make the current user the creator.
try {
getJdbcTemplate().update(SQL_INSERT_USER_ROLE_CAMPAIGN, new Object[] { userId, campaignId, authorId });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_INSERT_USER_ROLE_CAMPAIGN + "' with parameters: " + userId + ", " + campaignId + ", " + authorId, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Hookup to classes and users.
String[] classes = ((String) awRequest.getToProcessValue(InputKeys.CLASS_URN_LIST)).split(InputKeys.LIST_ITEM_SEPARATOR);
for(int i = 0; i < classes.length; i++) {
// Get the current class' ID.
int classId;
try {
classId = getJdbcTemplate().queryForInt(SQL_GET_CLASS_ID, new Object[] { classes[i] });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_GET_CLASS_ID + "' with parameter: " + classes[i], dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Hookup the current class with the campaign.
try {
getJdbcTemplate().update(SQL_INSERT_CAMPAIGN_CLASS, new Object[] { campaignId, classId });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_INSERT_CAMPAIGN_CLASS + "' with parameters: " + campaignId + ", " + classId, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Get the ID of that newly inserted row.
int campaignClassId;
try {
campaignClassId = getJdbcTemplate().queryForInt(SQL_GET_CAMPAIGN_CLASS_ID, new Object[] { campaignId, classId });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_GET_CAMPAIGN_CLASS_ID + "' with parameters: " + campaignId + ", " + classId, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Insert the default campaign_class_default_role
// relationships for privileged users.
// TODO: This should be a parameter in the API.
try {
getJdbcTemplate().update(SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE, new Object[] { campaignClassId, privilegedId, supervisorId });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE + "' with parameters: " + campaignClassId + ", " + privilegedId + ", " + supervisorId, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
try {
getJdbcTemplate().update(SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE, new Object[] { campaignClassId, privilegedId, participantId });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE + "' with parameters: " + campaignClassId + ", " + privilegedId + ", " + participantId, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Insert the default campaign_class_default_role
// relationships for restricted users.
// TODO: This should be a parameter in the API.
try {
getJdbcTemplate().update(SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE, new Object[] { campaignClassId, restrictedId, analystId });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE + "' with parameters: " + campaignClassId + ", " + restrictedId + ", " + supervisorId, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
try {
getJdbcTemplate().update(SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE, new Object[] { campaignClassId, restrictedId, participantId });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE + "' with parameters: " + campaignClassId + ", " + restrictedId + ", " + participantId, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Get the list of students in this class.
List<?> users;
try {
users = getJdbcTemplate().query(SQL_GET_USERS_FROM_CLASS,
new Object[] { classId },
new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
return new UserAndRole(rs.getInt("user_id"), rs.getInt("user_class_role_id"));
}
});
}
catch(org.springframework.dao.DataAccessException e) {
_logger.error("Error executing SQL '" + SQL_GET_USERS_FROM_CLASS + "' with parameter: " + classId, e);
transactionManager.rollback(status);
throw new DataAccessException(e);
}
// Associate the students with the campaign based on their
// class role.
ListIterator<?> usersIter = users.listIterator();
while(usersIter.hasNext()) {
UserAndRole uar = (UserAndRole) usersIter.next();
// Get the list of default roles for a user in this class
// associated with this campaign.
List<?> defaultRoles;
try {
defaultRoles = getJdbcTemplate().query(SQL_GET_CAMPAIGN_CLASS_DEFAULT_ROLES, new Object[] { campaignClassId, uar._roleId }, new SingleColumnRowMapper());
}
catch(org.springframework.dao.DataAccessException e) {
_logger.error("Error executing SQL '" + SQL_GET_CAMPAIGN_CLASS_DEFAULT_ROLES + "' with parameters: " + campaignClassId + ", " + uar._roleId, e);
transactionManager.rollback(status);
throw new DataAccessException(e);
}
// For each of these default roles
ListIterator<?> defaultRolesIter = defaultRoles.listIterator();
while(defaultRolesIter.hasNext()) {
int defaultRole = (Integer) defaultRolesIter.next();
if((uar._userId == userId) && (defaultRole == authorId)) {
// This already happened above.
continue;
}
// Associate the user with the campaign and the
// default role.
try {
getJdbcTemplate().update(SQL_INSERT_USER_ROLE_CAMPAIGN, new Object[] { uar._userId, campaignId, defaultRole });
}
catch(org.springframework.dao.DataIntegrityViolationException e) {
_logger.info("Attempting to add a user with the ID '" + uar._userId + "' into the user_role_campaign table with a role ID of '" +
defaultRole + "'; however such an association already exists for campaign '" + campaignId + "'.");
}
catch(org.springframework.dao.DataAccessException e) {
_logger.error("Error executing SQL '" + SQL_INSERT_USER_ROLE_CAMPAIGN + "' with parameters: " +
uar._userId + ", " + campaignId + ", " + defaultRole, e);
throw new DataAccessException(e);
}
}
}
}
// Try to commit everything and finish.
try {
transactionManager.commit(status);
}
catch(TransactionException e) {
_logger.error("Error while attempting to commit the transaction. Attempting to rollback.");
transactionManager.rollback(status);
throw new DataAccessException(e);
}
}
catch(TransactionException e) {
_logger.error("Error while attempting to rollback transaction.", e);
throw new DataAccessException(e);
}
}
| public void execute(AwRequest awRequest) {
_logger.info("Inserting campaign into the database.");
// Note: This function is a bear, but I tried to document it well and
// give it a nice flow. May need refactoring if major changes are to
// be made.
String campaignXml;
try {
campaignXml = (String) awRequest.getToProcessValue(InputKeys.XML);
}
catch(IllegalArgumentException e) {
throw new DataAccessException(e);
}
// Now use XOM to retrieve a Document and a root node for further processing. XOM is used because it has a
// very simple XPath API
Builder builder = new Builder();
Document document;
try {
document = builder.build(new StringReader(campaignXml));
} catch (IOException e) {
// The XML should already have been validated, so this should
// never happen.
_logger.error("Unable to read XML.", e);
throw new DataAccessException("XML was unreadable.");
} catch (ValidityException e) {
// The XML should already have been validated, so this should
// never happen.
_logger.error("Invalid XML.", e);
throw new DataAccessException("XML was invalid.");
} catch (ParsingException e) {
// The XML should already have been validated, so this should
// never happen.
_logger.error("Unparcelable XML.", e);
throw new DataAccessException("XML was unparcelable.");
}
Element root = document.getRootElement();
String campaignUrn = root.query("/campaign/campaignUrn").get(0).getValue().trim();
String campaignName = root.query("/campaign/campaignName").get(0).getValue().trim();
Calendar now = Calendar.getInstance();
String nowFormatted = now.get(Calendar.YEAR) + "-" + now.get(Calendar.MONTH) + "-" + now.get(Calendar.DAY_OF_MONTH) + " " +
now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND);
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setName("Campaign creation and user/class hookups.");
try {
PlatformTransactionManager transactionManager = new DataSourceTransactionManager(getDataSource());
TransactionStatus status = transactionManager.getTransaction(def);
try {
getJdbcTemplate().update(SQL_INSERT_CAMPAIGN,
new Object[] { ((awRequest.existsInToProcess(InputKeys.DESCRIPTION)) ? awRequest.getToProcessValue(InputKeys.DESCRIPTION) : "" ),
awRequest.getToProcessValue(InputKeys.XML),
CampaignRunningStateCache.instance().lookup((String) awRequest.getToProcessValue(InputKeys.RUNNING_STATE)),
CampaignPrivacyStateCache.instance().lookup((String) awRequest.getToProcessValue(InputKeys.PRIVACY_STATE)),
campaignName,
campaignUrn,
nowFormatted});
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_INSERT_CAMPAIGN + "' with parameters: " +
((awRequest.existsInToProcess(InputKeys.DESCRIPTION)) ? awRequest.getToProcessValue(InputKeys.DESCRIPTION) : "" ) + ", " +
awRequest.getToProcessValue(InputKeys.XML) + ", " +
awRequest.getToProcessValue(InputKeys.RUNNING_STATE) + ", " +
awRequest.getToProcessValue(InputKeys.PRIVACY_STATE) + ", " +
campaignName + ", " +
campaignUrn + ", " +
nowFormatted, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
catch(CacheMissException e) {
transactionManager.rollback(status);
throw new DataAccessException("Unknown running or privacy state in the cache.", e);
}
catch(IllegalArgumentException e) {
transactionManager.rollback(status);
throw new DataAccessException("Missing parameter in the toProcess map.", e);
}
// Get campaign ID.
int campaignId;
try {
campaignId = getJdbcTemplate().queryForInt(SQL_GET_CAMPAIGN_ID, new Object[] { campaignUrn });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_GET_CAMPAIGN_ID + "' with parameter: " + campaignUrn, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Get the campaign role supervisor's ID.
int supervisorId;
try {
supervisorId = CampaignRoleCache.instance().lookup(CampaignRoleCache.ROLE_SUPERVISOR);
}
catch(CacheMissException e) {
_logger.error("The cache doesn't know about known role " + CampaignRoleCache.ROLE_SUPERVISOR, e);
throw new DataAccessException(e);
}
// Get the campaign role analyst's ID.
int analystId;
try {
analystId = CampaignRoleCache.instance().lookup(CampaignRoleCache.ROLE_ANALYST);
}
catch(CacheMissException e) {
_logger.error("The cache doesn't know about known role " + CampaignRoleCache.ROLE_ANALYST, e);
throw new DataAccessException(e);
}
// Get the campaign role author's ID.
int authorId;
try {
authorId = CampaignRoleCache.instance().lookup(CampaignRoleCache.ROLE_AUTHOR);
}
catch(CacheMissException dae) {
_logger.error("The cache doesn't know about known role " + CampaignRoleCache.ROLE_AUTHOR, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Get the campaign role participant's ID.
int participantId;
try {
participantId = CampaignRoleCache.instance().lookup(CampaignRoleCache.ROLE_PARTICIPANT);
}
catch(CacheMissException e) {
_logger.error("The cache doesn't know about known role " + CampaignRoleCache.ROLE_PARTICIPANT, e);
throw new DataAccessException(e);
}
// Get the ID for privileged users.
int privilegedId;
try {
privilegedId = ClassRoleCache.instance().lookup(ClassRoleCache.ROLE_PRIVILEGED);
}
catch(CacheMissException e) {
_logger.error("The cache doesn't know about known role " + ClassRoleCache.ROLE_PRIVILEGED, e);
throw new DataAccessException(e);
}
// Get the ID for restricted users.
int restrictedId;
try {
restrictedId = ClassRoleCache.instance().lookup(ClassRoleCache.ROLE_RESTRICTED);
}
catch(CacheMissException e) {
_logger.error("The cache doesn't know about known role " + ClassRoleCache.ROLE_RESTRICTED, e);
throw new DataAccessException(e);
}
// Get the currently logged in user's ID.
int userId;
try {
userId = getJdbcTemplate().queryForInt(SQL_GET_USER_ID, new Object[] { awRequest.getUser().getUserName() });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_GET_USER_ID + "' with parameter: " + awRequest.getUser().getUserName(), dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Make the current user the creator.
try {
getJdbcTemplate().update(SQL_INSERT_USER_ROLE_CAMPAIGN, new Object[] { userId, campaignId, authorId });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_INSERT_USER_ROLE_CAMPAIGN + "' with parameters: " + userId + ", " + campaignId + ", " + authorId, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Hookup to classes and users.
String[] classes = ((String) awRequest.getToProcessValue(InputKeys.CLASS_URN_LIST)).split(InputKeys.LIST_ITEM_SEPARATOR);
for(int i = 0; i < classes.length; i++) {
// Get the current class' ID.
int classId;
try {
classId = getJdbcTemplate().queryForInt(SQL_GET_CLASS_ID, new Object[] { classes[i] });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_GET_CLASS_ID + "' with parameter: " + classes[i], dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Hookup the current class with the campaign.
try {
getJdbcTemplate().update(SQL_INSERT_CAMPAIGN_CLASS, new Object[] { campaignId, classId });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_INSERT_CAMPAIGN_CLASS + "' with parameters: " + campaignId + ", " + classId, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Get the ID of that newly inserted row.
int campaignClassId;
try {
campaignClassId = getJdbcTemplate().queryForInt(SQL_GET_CAMPAIGN_CLASS_ID, new Object[] { campaignId, classId });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_GET_CAMPAIGN_CLASS_ID + "' with parameters: " + campaignId + ", " + classId, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Insert the default campaign_class_default_role
// relationships for privileged users.
// TODO: This should be a parameter in the API.
try {
getJdbcTemplate().update(SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE, new Object[] { campaignClassId, privilegedId, supervisorId });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE + "' with parameters: " + campaignClassId + ", " + privilegedId + ", " + supervisorId, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
try {
getJdbcTemplate().update(SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE, new Object[] { campaignClassId, privilegedId, participantId });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE + "' with parameters: " + campaignClassId + ", " + privilegedId + ", " + participantId, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Insert the default campaign_class_default_role
// relationships for restricted users.
// TODO: This should be a parameter in the API.
try {
getJdbcTemplate().update(SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE, new Object[] { campaignClassId, restrictedId, analystId });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE + "' with parameters: " + campaignClassId + ", " + restrictedId + ", " + supervisorId, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
try {
getJdbcTemplate().update(SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE, new Object[] { campaignClassId, restrictedId, participantId });
}
catch(org.springframework.dao.DataAccessException dae) {
_logger.error("Error executing SQL '" + SQL_INSERT_CAMPAIGN_CLASS_DEFAULT_ROLE + "' with parameters: " + campaignClassId + ", " + restrictedId + ", " + participantId, dae);
transactionManager.rollback(status);
throw new DataAccessException(dae);
}
// Get the list of students in this class.
List<?> users;
try {
users = getJdbcTemplate().query(SQL_GET_USERS_FROM_CLASS,
new Object[] { classId },
new RowMapper() {
@Override
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
return new UserAndRole(rs.getInt("user_id"), rs.getInt("user_class_role_id"));
}
});
}
catch(org.springframework.dao.DataAccessException e) {
_logger.error("Error executing SQL '" + SQL_GET_USERS_FROM_CLASS + "' with parameter: " + classId, e);
transactionManager.rollback(status);
throw new DataAccessException(e);
}
// Associate the students with the campaign based on their
// class role.
ListIterator<?> usersIter = users.listIterator();
while(usersIter.hasNext()) {
UserAndRole uar = (UserAndRole) usersIter.next();
// Get the list of default roles for a user in this class
// associated with this campaign.
List<?> defaultRoles;
try {
defaultRoles = getJdbcTemplate().query(SQL_GET_CAMPAIGN_CLASS_DEFAULT_ROLES, new Object[] { campaignClassId, uar._roleId }, new SingleColumnRowMapper());
}
catch(org.springframework.dao.DataAccessException e) {
_logger.error("Error executing SQL '" + SQL_GET_CAMPAIGN_CLASS_DEFAULT_ROLES + "' with parameters: " + campaignClassId + ", " + uar._roleId, e);
transactionManager.rollback(status);
throw new DataAccessException(e);
}
// For each of these default roles
ListIterator<?> defaultRolesIter = defaultRoles.listIterator();
while(defaultRolesIter.hasNext()) {
int defaultRole = (Integer) defaultRolesIter.next();
if((uar._userId == userId) && (defaultRole == authorId)) {
// This already happened above.
continue;
}
// Associate the user with the campaign and the
// default role.
try {
getJdbcTemplate().update(SQL_INSERT_USER_ROLE_CAMPAIGN, new Object[] { uar._userId, campaignId, defaultRole });
}
catch(org.springframework.dao.DataIntegrityViolationException e) {
_logger.info("Attempting to add a user with the ID '" + uar._userId + "' into the user_role_campaign table with a role ID of '" +
defaultRole + "'; however such an association already exists for campaign '" + campaignId + "'.");
}
catch(org.springframework.dao.DataAccessException e) {
_logger.error("Error executing SQL '" + SQL_INSERT_USER_ROLE_CAMPAIGN + "' with parameters: " +
uar._userId + ", " + campaignId + ", " + defaultRole, e);
throw new DataAccessException(e);
}
}
}
}
// Try to commit everything and finish.
try {
transactionManager.commit(status);
}
catch(TransactionException e) {
_logger.error("Error while attempting to commit the transaction. Attempting to rollback.");
transactionManager.rollback(status);
throw new DataAccessException(e);
}
}
catch(TransactionException e) {
_logger.error("Error while attempting to rollback transaction.", e);
throw new DataAccessException(e);
}
}
|
diff --git a/src/org/mozilla/javascript/regexp/RegExpImpl.java b/src/org/mozilla/javascript/regexp/RegExpImpl.java
index b1a5e4ff..cb9030f9 100644
--- a/src/org/mozilla/javascript/regexp/RegExpImpl.java
+++ b/src/org/mozilla/javascript/regexp/RegExpImpl.java
@@ -1,567 +1,569 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express oqr
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is Rhino code, released
* May 6, 1998.
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1997-1999 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU Public License (the "GPL"), in which case the
* provisions of the GPL are applicable instead of those above.
* If you wish to allow use of your version of this file only
* under the terms of the GPL and not to allow others to use your
* version of this file under the NPL, indicate your decision by
* deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete
* the provisions above, a recipient may use your version of this
* file under either the NPL or the GPL.
*/
package org.mozilla.javascript.regexp;
import org.mozilla.javascript.*;
import java.util.Vector;
/**
*
*/
public class RegExpImpl implements RegExpProxy {
public RegExpImpl() {
parens = new Vector(9);
}
public boolean isRegExp(Object obj) {
return obj instanceof NativeRegExp;
}
public Object newRegExp(Context cx, Scriptable scope, String source,
String global, boolean flat)
{
return new NativeRegExp(cx, scope, source, global, flat);
}
public Object match(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
throws JavaScriptException
{
MatchData mdata = new MatchData();
mdata.optarg = 1;
mdata.mode = GlobData.GLOB_MATCH;
mdata.parent = ScriptableObject.getTopLevelScope(scope);
Object rval = matchOrReplace(cx, scope, thisObj, args,
this, mdata, false);
return mdata.arrayobj == null ? rval : mdata.arrayobj;
}
public Object search(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
throws JavaScriptException
{
MatchData mdata = new MatchData();
mdata.optarg = 1;
mdata.mode = GlobData.GLOB_SEARCH;
mdata.parent = ScriptableObject.getTopLevelScope(scope);
return matchOrReplace(cx, scope, thisObj, args, this, mdata, false);
}
public Object replace(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
throws JavaScriptException
{
Object arg1 = args.length < 2 ? Undefined.instance : args[1];
String repstr = null;
Function lambda = null;
if (arg1 instanceof Function) {
lambda = (Function) arg1;
} else {
repstr = ScriptRuntime.toString(arg1);
}
ReplaceData rdata = new ReplaceData();
rdata.optarg = 2;
rdata.mode = GlobData.GLOB_REPLACE;
rdata.lambda = lambda;
rdata.repstr = repstr == null ? null : repstr.toCharArray();
rdata.dollar = repstr == null ? -1 : repstr.indexOf('$');
rdata.charArray = null;
rdata.length = 0;
rdata.index = 0;
rdata.leftIndex = 0;
Object val = matchOrReplace(cx, scope, thisObj, args,
this, rdata, true);
char[] charArray;
if (rdata.charArray == null) {
if (rdata.global || val == null || !val.equals(Boolean.TRUE)) {
/* Didn't match even once. */
return rdata.str;
}
int leftlen = this.leftContext.length;
int length = leftlen + rdata.findReplen(cx, this);
charArray = new char[length];
SubString leftContext = this.leftContext;
System.arraycopy(leftContext.charArray, leftContext.index,
charArray, 0, leftlen);
rdata.doReplace(cx, this, charArray, leftlen);
rdata.charArray = charArray;
rdata.length = length;
}
SubString rc = this.rightContext;
int rightlen = rc.length;
int length = rdata.length + rightlen;
charArray = new char[length];
System.arraycopy(rdata.charArray, 0,
charArray, 0, rdata.charArray.length);
System.arraycopy(rc.charArray, rc.index, charArray,
rdata.length, rightlen);
return new String(charArray, 0, length);
}
/**
* Analog of C match_or_replace.
*/
private static Object matchOrReplace(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args,
RegExpImpl reImpl,
GlobData data, boolean forceFlat)
throws JavaScriptException
{
NativeRegExp re;
String str = ScriptRuntime.toString(thisObj);
data.str = str;
Scriptable topScope = ScriptableObject.getTopLevelScope(scope);
if (args.length == 0)
re = new NativeRegExp(cx, topScope, "", "", false);
else
if (args[0] instanceof NativeRegExp) {
re = (NativeRegExp) args[0];
} else {
String src = ScriptRuntime.toString(args[0]);
String opt;
if (data.optarg < args.length) {
args[0] = src;
opt = ScriptRuntime.toString(args[data.optarg]);
} else {
opt = null;
}
re = new NativeRegExp(cx, topScope, src, opt, forceFlat);
}
data.regexp = re;
data.global = (re.getFlags() & NativeRegExp.GLOB) != 0;
int[] indexp = { 0 };
Object result = null;
if (data.mode == GlobData.GLOB_SEARCH) {
result = re.executeRegExp(cx, scope, reImpl,
str, indexp, NativeRegExp.TEST);
if (result != null && result.equals(Boolean.TRUE))
result = new Integer(reImpl.leftContext.length);
else
result = new Integer(-1);
} else if (data.global) {
re.setLastIndex(0);
for (int count = 0; indexp[0] <= str.length(); count++) {
result = re.executeRegExp(cx, scope, reImpl,
str, indexp, NativeRegExp.TEST);
if (result == null || !result.equals(Boolean.TRUE))
break;
data.doGlobal(cx, scope, count, reImpl);
if (reImpl.lastMatch.length == 0) {
if (indexp[0] == str.length())
break;
indexp[0]++;
}
}
} else {
result = re.executeRegExp(cx, scope, reImpl, str, indexp,
((data.mode == GlobData.GLOB_REPLACE)
? NativeRegExp.TEST
: NativeRegExp.MATCH));
}
return result;
}
public int find_split(Scriptable scope, String target, String separator,
Object reObj, int[] ip, int[] matchlen,
boolean[] matched, String[][] parensp)
{
int i = ip[0];
int length = target.length();
int result;
Context cx = Context.getCurrentContext();
int version = cx.getLanguageVersion();
NativeRegExp re = (NativeRegExp) reObj;
again:
while (true) { // imitating C label
/* JS1.2 deviated from Perl by never matching at end of string. */
int ipsave = ip[0]; // reuse ip to save object creation
ip[0] = i;
Object ret = re.executeRegExp(cx, scope, this, target, ip,
NativeRegExp.TEST);
if (ret != Boolean.TRUE) {
// Mismatch: ensure our caller advances i past end of string.
ip[0] = ipsave;
matchlen[0] = 1;
matched[0] = false;
return length;
}
i = ip[0];
ip[0] = ipsave;
matched[0] = true;
SubString sep = this.lastMatch;
matchlen[0] = sep.length;
if (matchlen[0] == 0) {
/*
* Empty string match: never split on an empty
* match at the start of a find_split cycle. Same
* rule as for an empty global match in
* match_or_replace.
*/
if (i == ip[0]) {
/*
* "Bump-along" to avoid sticking at an empty
* match, but don't bump past end of string --
* our caller must do that by adding
* sep->length to our return value.
*/
if (i == length) {
if (version == Context.VERSION_1_2) {
matchlen[0] = 1;
result = i;
}
else
result = -1;
break;
}
i++;
continue again; // imitating C goto
}
}
// PR_ASSERT((size_t)i >= sep->length);
result = i - matchlen[0];
break;
}
int size = parens.size();
parensp[0] = new String[size];
for (int num = 0; num < size; num++) {
SubString parsub = getParenSubString(num);
parensp[0][num] = parsub.toString();
}
return result;
}
/**
* Analog of REGEXP_PAREN_SUBSTRING in C jsregexp.h.
* Assumes zero-based; i.e., for $3, i==2
*/
SubString getParenSubString(int i) {
if (i >= parens.size())
return SubString.emptySubString;
return (SubString) parens.elementAt(i);
}
String input; /* input string to match (perl $_, GC root) */
boolean multiline; /* whether input contains newlines (perl $*) */
Vector parens; /* Vector of SubString; last set of parens
matched (perl $1, $2) */
SubString lastMatch; /* last string matched (perl $&) */
SubString lastParen; /* last paren matched (perl $+) */
SubString leftContext; /* input to left of last match (perl $`) */
SubString rightContext; /* input to right of last match (perl $') */
}
abstract class GlobData {
static final int GLOB_MATCH = 1;
static final int GLOB_REPLACE = 2;
static final int GLOB_SEARCH = 3;
abstract void doGlobal(Context cx, Scriptable scope, int count,
RegExpImpl reImpl)
throws JavaScriptException;
byte mode; /* input: return index, match object, or void */
int optarg; /* input: index of optional flags argument */
boolean global; /* output: whether regexp was global */
String str; /* output: 'this' parameter object as string */
NativeRegExp regexp;/* output: regexp parameter object private data */
Scriptable parent;
}
class MatchData extends GlobData {
/*
* Analog of match_glob() in jsstr.c
*/
void doGlobal(Context cx, Scriptable scope, int count, RegExpImpl reImpl)
throws JavaScriptException
{
MatchData mdata;
Object v;
mdata = this;
if (arrayobj == null) {
Scriptable s = ScriptableObject.getTopLevelScope(scope);
arrayobj = ScriptRuntime.newObject(cx, s, "Array", null);
}
SubString matchsub = reImpl.lastMatch;
String matchstr = matchsub.toString();
arrayobj.put(count, arrayobj, matchstr);
}
Scriptable arrayobj;
}
class ReplaceData extends GlobData {
ReplaceData() {
dollar = -1;
}
/*
* Analog of replace_glob() in jsstr.c
*/
void doGlobal(Context cx, Scriptable scope, int count, RegExpImpl reImpl)
throws JavaScriptException
{
ReplaceData rdata = this;
SubString lc = reImpl.leftContext;
char[] leftArray = lc.charArray;
int leftIndex = rdata.leftIndex;
int leftlen = reImpl.lastMatch.index - leftIndex;
rdata.leftIndex = reImpl.lastMatch.index + reImpl.lastMatch.length;
int replen = findReplen(cx, reImpl);
int growth = leftlen + replen;
char[] charArray;
if (rdata.charArray != null) {
charArray = new char[rdata.length + growth];
System.arraycopy(rdata.charArray, 0, charArray, 0, rdata.length);
} else {
charArray = new char[growth];
}
rdata.charArray = charArray;
rdata.length += growth;
int index = rdata.index;
rdata.index += growth;
System.arraycopy(leftArray, leftIndex, charArray, index, leftlen);
index += leftlen;
doReplace(cx, reImpl, charArray, index);
}
static SubString dollarStr = new SubString("$");
static SubString interpretDollar(Context cx, RegExpImpl res,
char[] da, int dp, int bp, int[] skip)
{
char[] ca;
int cp;
char dc;
int num, tmp;
/* Allow a real backslash (literal "\\") to escape "$1" etc. */
if (da[dp] != '$')
throw new RuntimeException();
if ((cx.getLanguageVersion() != Context.VERSION_DEFAULT)
&& (cx.getLanguageVersion() <= Context.VERSION_1_4))
if (dp > bp && da[dp-1] == '\\')
return null;
+ if (dp+1 >= da.length)
+ return null;
/* Interpret all Perl match-induced dollar variables. */
dc = da[dp+1];
- if (NativeRegExp.isDigit(dc)) {
+ if (NativeRegExp.isDigit(dc)) {
if ((cx.getLanguageVersion() != Context.VERSION_DEFAULT)
&& (cx.getLanguageVersion() <= Context.VERSION_1_4)) {
if (dc == '0')
return null;
/* Check for overflow to avoid gobbling arbitrary decimal digits. */
num = 0;
ca = da;
cp = dp;
while (++cp < ca.length && NativeRegExp.isDigit(dc = ca[cp])) {
tmp = 10 * num + NativeRegExp.unDigit(dc);
if (tmp < num)
break;
num = tmp;
}
}
else { /* ECMA 3, 1-9 or 01-99 */
num = NativeRegExp.unDigit(dc);
cp = dp + 2;
if ((dp + 2) < da.length) {
dc = da[dp + 2];
if (NativeRegExp.isDigit(dc)) {
num = 10 * num + NativeRegExp.unDigit(dc);
cp++;
}
}
if (num == 0) return null; /* $0 or $00 is not valid */
}
/* Adjust num from 1 $n-origin to 0 array-index-origin. */
num--;
skip[0] = cp - dp;
return res.getParenSubString(num);
}
skip[0] = 2;
switch (dc) {
case '$':
return dollarStr;
case '&':
return res.lastMatch;
case '+':
return res.lastParen;
case '`':
if (cx.getLanguageVersion() == Context.VERSION_1_2) {
/*
* JS1.2 imitated the Perl4 bug where left context at each step
* in an iterative use of a global regexp started from last match,
* not from the start of the target string. But Perl4 does start
* $` at the beginning of the target string when it is used in a
* substitution, so we emulate that special case here.
*/
res.leftContext.index = 0;
res.leftContext.length = res.lastMatch.index;
}
return res.leftContext;
case '\'':
return res.rightContext;
}
return null;
}
/**
* Corresponds to find_replen in jsstr.c. rdata is 'this', and
* the result parameter sizep is the return value (errors are
* propagated with exceptions).
*/
int findReplen(Context cx, RegExpImpl reImpl)
throws JavaScriptException
{
if (lambda != null) {
// invoke lambda function with args lastMatch, $1, $2, ... $n,
// leftContext.length, whole string.
Vector parens = reImpl.parens;
int parenCount = parens.size();
Object[] args = new Object[parenCount + 3];
args[0] = reImpl.lastMatch.toString();
for (int i=0; i < parenCount; i++) {
SubString sub = (SubString) parens.elementAt(i);
args[i+1] = sub.toString();
}
args[parenCount+1] = new Integer(reImpl.leftContext.length);
args[parenCount+2] = str;
Scriptable parent = lambda.getParentScope();
Object result = lambda.call(cx, parent, parent, args);
this.repstr = ScriptRuntime.toString(result).toCharArray();
return this.repstr.length;
}
int replen = this.repstr.length;
if (dollar == -1)
return replen;
int bp = 0;
for (int dp = dollar; dp < this.repstr.length ; ) {
char c = this.repstr[dp];
if (c != '$') {
dp++;
continue;
}
int[] skip = { 0 };
SubString sub = interpretDollar(cx, reImpl, this.repstr, dp,
bp, skip);
if (sub != null) {
replen += sub.length - skip[0];
dp += skip[0];
}
else
dp++;
}
return replen;
}
/**
* Analog of do_replace in jsstr.c
*/
void doReplace(Context cx, RegExpImpl regExpImpl, char[] charArray,
int arrayIndex)
{
int cp = 0;
char[] da = repstr;
int dp = this.dollar;
int bp = cp;
if (dp != -1) {
outer:
for (;;) {
int len = dp - cp;
System.arraycopy(repstr, cp, charArray, arrayIndex,
len);
arrayIndex += len;
cp = dp;
int[] skip = { 0 };
SubString sub = interpretDollar(cx, regExpImpl, da,
dp, bp, skip);
if (sub != null) {
len = sub.length;
if (len > 0) {
System.arraycopy(sub.charArray, sub.index, charArray,
arrayIndex, len);
}
arrayIndex += len;
cp += skip[0];
dp += skip[0];
}
else
dp++;
if (dp >= repstr.length) break;
while (repstr[dp] != '$') {
dp++;
if (dp >= repstr.length) break outer;
}
}
}
if (repstr.length > cp) {
System.arraycopy(repstr, cp, charArray, arrayIndex,
repstr.length - cp);
}
}
Function lambda; /* replacement function object or null */
char[] repstr; /* replacement string */
int dollar; /* -1 or index of first $ in repstr */
char[] charArray; /* result characters, null initially */
int length; /* result length, 0 initially */
int index; /* index in result of next replacement */
int leftIndex; /* leftContext index, always 0 for JS1.2 */
}
| false | true | static SubString interpretDollar(Context cx, RegExpImpl res,
char[] da, int dp, int bp, int[] skip)
{
char[] ca;
int cp;
char dc;
int num, tmp;
/* Allow a real backslash (literal "\\") to escape "$1" etc. */
if (da[dp] != '$')
throw new RuntimeException();
if ((cx.getLanguageVersion() != Context.VERSION_DEFAULT)
&& (cx.getLanguageVersion() <= Context.VERSION_1_4))
if (dp > bp && da[dp-1] == '\\')
return null;
/* Interpret all Perl match-induced dollar variables. */
dc = da[dp+1];
if (NativeRegExp.isDigit(dc)) {
if ((cx.getLanguageVersion() != Context.VERSION_DEFAULT)
&& (cx.getLanguageVersion() <= Context.VERSION_1_4)) {
if (dc == '0')
return null;
/* Check for overflow to avoid gobbling arbitrary decimal digits. */
num = 0;
ca = da;
cp = dp;
while (++cp < ca.length && NativeRegExp.isDigit(dc = ca[cp])) {
tmp = 10 * num + NativeRegExp.unDigit(dc);
if (tmp < num)
break;
num = tmp;
}
}
else { /* ECMA 3, 1-9 or 01-99 */
num = NativeRegExp.unDigit(dc);
cp = dp + 2;
if ((dp + 2) < da.length) {
dc = da[dp + 2];
if (NativeRegExp.isDigit(dc)) {
num = 10 * num + NativeRegExp.unDigit(dc);
cp++;
}
}
if (num == 0) return null; /* $0 or $00 is not valid */
}
/* Adjust num from 1 $n-origin to 0 array-index-origin. */
num--;
skip[0] = cp - dp;
return res.getParenSubString(num);
}
skip[0] = 2;
switch (dc) {
case '$':
return dollarStr;
case '&':
return res.lastMatch;
case '+':
return res.lastParen;
case '`':
if (cx.getLanguageVersion() == Context.VERSION_1_2) {
/*
* JS1.2 imitated the Perl4 bug where left context at each step
* in an iterative use of a global regexp started from last match,
* not from the start of the target string. But Perl4 does start
* $` at the beginning of the target string when it is used in a
* substitution, so we emulate that special case here.
*/
res.leftContext.index = 0;
res.leftContext.length = res.lastMatch.index;
}
return res.leftContext;
case '\'':
return res.rightContext;
}
return null;
}
| static SubString interpretDollar(Context cx, RegExpImpl res,
char[] da, int dp, int bp, int[] skip)
{
char[] ca;
int cp;
char dc;
int num, tmp;
/* Allow a real backslash (literal "\\") to escape "$1" etc. */
if (da[dp] != '$')
throw new RuntimeException();
if ((cx.getLanguageVersion() != Context.VERSION_DEFAULT)
&& (cx.getLanguageVersion() <= Context.VERSION_1_4))
if (dp > bp && da[dp-1] == '\\')
return null;
if (dp+1 >= da.length)
return null;
/* Interpret all Perl match-induced dollar variables. */
dc = da[dp+1];
if (NativeRegExp.isDigit(dc)) {
if ((cx.getLanguageVersion() != Context.VERSION_DEFAULT)
&& (cx.getLanguageVersion() <= Context.VERSION_1_4)) {
if (dc == '0')
return null;
/* Check for overflow to avoid gobbling arbitrary decimal digits. */
num = 0;
ca = da;
cp = dp;
while (++cp < ca.length && NativeRegExp.isDigit(dc = ca[cp])) {
tmp = 10 * num + NativeRegExp.unDigit(dc);
if (tmp < num)
break;
num = tmp;
}
}
else { /* ECMA 3, 1-9 or 01-99 */
num = NativeRegExp.unDigit(dc);
cp = dp + 2;
if ((dp + 2) < da.length) {
dc = da[dp + 2];
if (NativeRegExp.isDigit(dc)) {
num = 10 * num + NativeRegExp.unDigit(dc);
cp++;
}
}
if (num == 0) return null; /* $0 or $00 is not valid */
}
/* Adjust num from 1 $n-origin to 0 array-index-origin. */
num--;
skip[0] = cp - dp;
return res.getParenSubString(num);
}
skip[0] = 2;
switch (dc) {
case '$':
return dollarStr;
case '&':
return res.lastMatch;
case '+':
return res.lastParen;
case '`':
if (cx.getLanguageVersion() == Context.VERSION_1_2) {
/*
* JS1.2 imitated the Perl4 bug where left context at each step
* in an iterative use of a global regexp started from last match,
* not from the start of the target string. But Perl4 does start
* $` at the beginning of the target string when it is used in a
* substitution, so we emulate that special case here.
*/
res.leftContext.index = 0;
res.leftContext.length = res.lastMatch.index;
}
return res.leftContext;
case '\'':
return res.rightContext;
}
return null;
}
|
diff --git a/app/beans/ProcExecutorEventListener.java b/app/beans/ProcExecutorEventListener.java
index f7c5f7c..80716f9 100644
--- a/app/beans/ProcExecutorEventListener.java
+++ b/app/beans/ProcExecutorEventListener.java
@@ -1,61 +1,61 @@
/*******************************************************************************
* Copyright (c) 2011 GigaSpaces Technologies Ltd. All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package beans;
import play.cache.Cache;
import server.WriteEventListener;
/**
*
* A process executer output stream event listener.
* This event listener writes all output from the process into the Play Cash.
*
* @author adaml
*
*/
public class ProcExecutorEventListener implements WriteEventListener {
private String serverNodeId;
private StringBuilder sb = null;
private String keyFormat = "output-%s";
public ProcExecutorEventListener( String serverNodeId ) {
this.serverNodeId = serverNodeId;
}
public ProcExecutorEventListener( ) {
}
@Override
public void writeEvent(int b) {
if (this.sb == null) {
sb = ( (StringBuilder) Cache.get( String.format( keyFormat, serverNodeId) ) );
}
- sb.append(b);
+ sb.append((byte) b);
}
public void setKeyFormat( String keyFormat ){
this.keyFormat = keyFormat;
}
@Override
public void setKey(String serverNodeId) {
this.serverNodeId = serverNodeId;
}
}
| true | true | public void writeEvent(int b) {
if (this.sb == null) {
sb = ( (StringBuilder) Cache.get( String.format( keyFormat, serverNodeId) ) );
}
sb.append(b);
}
| public void writeEvent(int b) {
if (this.sb == null) {
sb = ( (StringBuilder) Cache.get( String.format( keyFormat, serverNodeId) ) );
}
sb.append((byte) b);
}
|
diff --git a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/MethodInfo.java b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/MethodInfo.java
index bf720fdb..95fc51c4 100644
--- a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/MethodInfo.java
+++ b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/MethodInfo.java
@@ -1,292 +1,294 @@
package jp.ac.osaka_u.ist.sel.metricstool.main.data.target;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import jp.ac.osaka_u.ist.sel.metricstool.main.Settings;
import jp.ac.osaka_u.ist.sel.metricstool.main.data.metric.MetricMeasurable;
import jp.ac.osaka_u.ist.sel.metricstool.main.security.MetricsToolSecurityManager;
/**
* ���\�b�h��\���N���X
*
* @author higo
*
*/
public abstract class MethodInfo extends CallableUnitInfo implements MetricMeasurable, Member {
/**
* ���\�b�h�I�u�W�F�N�g������������
*
* @param modifiers �C���q��Set
* @param methodName ���\�b�h��
* @param ownerClass ��`������N���X
* @param privateVisible private����
* @param namespaceVisible ���O��ԉ���
* @param inheritanceVisible �q�N���X�������
* @param publicVisible public����
* @param fromLine �J�n�s
* @param fromColumn �J�n��
* @param toLine �I���s
* @param toColumn �I����
*/
MethodInfo(final Set<ModifierInfo> modifiers, final String methodName,
final ClassInfo ownerClass, final boolean privateVisible,
final boolean namespaceVisible, final boolean inheritanceVisible,
final boolean publicVisible, final int fromLine, final int fromColumn,
final int toLine, final int toColumn) {
super(modifiers, ownerClass, privateVisible, namespaceVisible, inheritanceVisible,
publicVisible, fromLine, fromColumn, toLine, toColumn);
MetricsToolSecurityManager.getInstance().checkAccess();
if ((null == methodName) || (null == ownerClass)) {
throw new NullPointerException();
}
this.methodName = methodName;
this.returnType = null;
this.overridees = new TreeSet<MethodInfo>();
this.overriders = new TreeSet<MethodInfo>();
}
/**
* ���̃��\�b�h���C�����ŗ^����ꂽ�����g���ČĂяo�����Ƃ��ł��邩�ǂ����肷��D
*
* @param methodName ���\�b�h��
* @param actualParameters �������̃��X�g
* @return �Ăяo����ꍇ�� true�C�����łȂ��ꍇ�� false
*/
public final boolean canCalledWith(final String methodName,
final List<ExpressionInfo> actualParameters) {
if ((null == methodName) || (null == actualParameters)) {
throw new IllegalArgumentException();
}
// ���\�b�h�����������Ȃ��ꍇ�͊Y�����Ȃ�
if (!methodName.equals(this.getMethodName())) {
return false;
}
return super.canCalledWith(actualParameters);
}
/**
* ���̃��\�b�h�������ŗ^����ꂽ�I�u�W�F�N�g�i���\�b�h�j�Ɠ��������ǂ����肷��
*
* @param o ��r�ΏۃI�u�W�F�N�g�i���\�b�h�j
* @return �������ꍇ�� true, �������Ȃ��ꍇ�� false
*/
@Override
public final boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof MethodInfo)) {
return false;
}
return 0 == this.compareTo((MethodInfo) o);
}
/**
* ���g���N�X�v���ΏۂƂ��Ă̖��O��Ԃ�
*
* @return ���g���N�X�v���ΏۂƂ��Ă̖��O
*/
@Override
public final String getMeasuredUnitName() {
final StringBuilder sb = new StringBuilder();
final String fullQualifiedName = this.getOwnerClass().getFullQualifiedName(
Settings.getInstance().getLanguage().getNamespaceDelimiter());
sb.append(fullQualifiedName);
sb.append("#");
final String methodName = this.getMethodName();
sb.append(methodName);
sb.append("(");
- for (final ParameterInfo parameter : this.getParameters()) {
- final TypeInfo parameterType = parameter.getType();
- sb.append(parameterType.getTypeName());
- sb.append(" ");
+ if (this.getParameters().size() > 0){
+ for (final ParameterInfo parameter : this.getParameters()) {
+ final TypeInfo parameterType = parameter.getType();
+ sb.append(parameterType.getTypeName());
+ sb.append(" ");
+ }
+ sb.deleteCharAt(sb.length() - 1);
}
- sb.deleteCharAt(sb.length() - 1);
sb.append(")");
return sb.toString();
}
@Override
public final String getSignatureText(){
final StringBuilder text = new StringBuilder();
text.append(this.getReturnType().getTypeName());
text.append(" ");
text.append(this.getMethodName());
text.append("(");
for(final ParameterInfo parameter : this.getParameters()){
text.append(parameter.getType().getTypeName());
text.append(",");
}
if(0 < this.getParameterNumber()){
text.deleteCharAt(text.length() -1);
}
text.append(")");
return text.toString();
}
/**
* ���̃��\�b�h�̖��O��Ԃ�
*
* @return ���\�b�h��
*/
public final String getMethodName() {
return this.methodName;
}
/**
* ���̃��\�b�h�̕Ԃ�l�̌^��Ԃ�
*
* @return �Ԃ�l�̌^
*/
public final TypeInfo getReturnType() {
if (null == this.returnType) {
throw new NullPointerException();
}
return this.returnType;
}
/**
* ���̃��\�b�h�̈�����lj�����D public �錾���Ă��邪�C �v���O�C������̌Ăяo���͂͂����D
*
* @param parameter �lj��������
*/
public void addParameter(final ParameterInfo parameter) {
MetricsToolSecurityManager.getInstance().checkAccess();
if (null == parameter) {
throw new NullPointerException();
}
this.parameters.add(parameter);
}
/**
* ���̃��\�b�h�̈�����lj�����D public �錾���Ă��邪�C �v���O�C������̌Ăяo���͂͂����D
*
* @param parameters �lj���������Q
*/
public void addParameters(final List<ParameterInfo> parameters) {
MetricsToolSecurityManager.getInstance().checkAccess();
if (null == parameters) {
throw new NullPointerException();
}
this.parameters.addAll(parameters);
}
/**
* ���̃��\�b�h�̕Ԃ�l���Z�b�g����D
*
* @param returnType ���̃��\�b�h�̕Ԃ�l
*/
public void setReturnType(final TypeInfo returnType) {
MetricsToolSecurityManager.getInstance().checkAccess();
if (null == returnType) {
throw new NullPointerException();
}
this.returnType = returnType;
}
/**
* ���̃��\�b�h���I�[�o�[���C�h���Ă��郁�\�b�h��lj�����D�v���O�C������ĂԂƃ����^�C���G���[�D
*
* @param overridee �lj�����I�[�o�[���C�h����Ă��郁�\�b�h
*/
public void addOverridee(final MethodInfo overridee) {
MetricsToolSecurityManager.getInstance().checkAccess();
if (null == overridee) {
throw new NullPointerException();
}
this.overridees.add(overridee);
}
/**
* ���̃��\�b�h���I�[�o�[���C�h���Ă��郁�\�b�h��lj�����D�v���O�C������ĂԂƃ����^�C���G���[�D
*
* @param overrider �lj�����I�[�o�[���C�h���Ă��郁�\�b�h
*
*/
public void addOverrider(final MethodInfo overrider) {
MetricsToolSecurityManager.getInstance().checkAccess();
if (null == overrider) {
throw new NullPointerException();
}
this.overriders.add(overrider);
}
/**
* ���̃��\�b�h���I�[�o�[���C�h���Ă��郁�\�b�h�� SortedSet ��Ԃ��D
*
* @return ���̃��\�b�h���I�[�o�[���C�h���Ă��郁�\�b�h�� SortedSet
*/
public SortedSet<MethodInfo> getOverridees() {
return Collections.unmodifiableSortedSet(this.overridees);
}
/**
* ���̃��\�b�h���I�[�o�[���C�h���Ă��郁�\�b�h�� SortedSet ��Ԃ��D
*
* @return ���̃��\�b�h���I�[�o�[���C�h���Ă��郁�\�b�h�� SortedSet
*/
public SortedSet<MethodInfo> getOverriders() {
return Collections.unmodifiableSortedSet(this.overriders);
}
/**
* ���\�b�h����ۑ����邽�߂̕ϐ�
*/
private final String methodName;
/**
* �Ԃ�l�̌^��ۑ����邽�߂̕ϐ�
*/
private TypeInfo returnType;
/**
* ���̃��\�b�h���I�[�o�[���C�h���Ă��郁�\�b�h�ꗗ��ۑ����邽�߂̕ϐ�
*/
protected final SortedSet<MethodInfo> overridees;
/**
* �I�[�o�[���C�h����Ă��郁�\�b�h��ۑ����邽�߂̕ϐ�
*/
protected final SortedSet<MethodInfo> overriders;
}
| false | true | public final String getMeasuredUnitName() {
final StringBuilder sb = new StringBuilder();
final String fullQualifiedName = this.getOwnerClass().getFullQualifiedName(
Settings.getInstance().getLanguage().getNamespaceDelimiter());
sb.append(fullQualifiedName);
sb.append("#");
final String methodName = this.getMethodName();
sb.append(methodName);
sb.append("(");
for (final ParameterInfo parameter : this.getParameters()) {
final TypeInfo parameterType = parameter.getType();
sb.append(parameterType.getTypeName());
sb.append(" ");
}
sb.deleteCharAt(sb.length() - 1);
sb.append(")");
return sb.toString();
}
| public final String getMeasuredUnitName() {
final StringBuilder sb = new StringBuilder();
final String fullQualifiedName = this.getOwnerClass().getFullQualifiedName(
Settings.getInstance().getLanguage().getNamespaceDelimiter());
sb.append(fullQualifiedName);
sb.append("#");
final String methodName = this.getMethodName();
sb.append(methodName);
sb.append("(");
if (this.getParameters().size() > 0){
for (final ParameterInfo parameter : this.getParameters()) {
final TypeInfo parameterType = parameter.getType();
sb.append(parameterType.getTypeName());
sb.append(" ");
}
sb.deleteCharAt(sb.length() - 1);
}
sb.append(")");
return sb.toString();
}
|
diff --git a/JSTUN.java b/JSTUN.java
index 3ec613b..7e1a839 100644
--- a/JSTUN.java
+++ b/JSTUN.java
@@ -1,280 +1,281 @@
package plugins.JSTUN;
import java.lang.reflect.Method;
import java.net.BindException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Vector;
import java.util.Random;
import plugins.JSTUN.de.javawi.jstun.test.DiscoveryInfo;
import plugins.JSTUN.de.javawi.jstun.test.DiscoveryTest;
import freenet.pluginmanager.DetectedIP;
import freenet.pluginmanager.FredPlugin;
import freenet.pluginmanager.FredPluginHTTP;
import freenet.pluginmanager.FredPluginIPDetector;
import freenet.pluginmanager.FredPluginThreadless;
import freenet.pluginmanager.FredPluginVersioned;
import freenet.pluginmanager.PluginHTTPException;
import freenet.pluginmanager.PluginRespirator;
import freenet.support.HTMLNode;
import freenet.support.Logger;
import freenet.support.api.HTTPRequest;
// threadless in the sense that it doesn't need a thread running all the time.
// but getAddress() can and will block!
public class JSTUN implements FredPlugin, FredPluginIPDetector, FredPluginThreadless, FredPluginHTTP, FredPluginVersioned {
// From http://www.voip-info.org/wiki-STUN
String[] publicSTUNServers = new String[] {
"stun.ekiga.net",
"stun.fwdnet.net",
"stun.ideasip.com",
"stun01.sipphone.com",
"stun.softjoys.com",
"stun.voipbuster.org",
"stun.voxgratia.org",
"stun.xten.com"
};
private DiscoveryInfo reportedData;
private PluginRespirator pr;
private boolean hasRunTestBeenCalled = false;
DetectedIP[] runTest(InetAddress iaddress) {
this.hasRunTestBeenCalled = true;
Random r = new Random(); // FIXME use something safer?
Vector v = new Vector(publicSTUNServers.length);
Vector out = new Vector();
int countLikely = 0;
int countUnlikely = 0;
for(int i=0;i<publicSTUNServers.length;i++)
v.add(publicSTUNServers[i]);
while(!v.isEmpty()) {
+ if(WrapperManager.hasShutdownHookBeenTriggered()) return null;
String stunServer = (String) v.remove(r.nextInt(v.size()));
try {
DiscoveryTest test = new DiscoveryTest(iaddress, stunServer, 3478);
// iphone-stun.freenet.de:3478
// larry.gloo.net:3478
// stun.xten.net:3478
reportedData = test.test();
if(((reportedData.isBlockedUDP() || reportedData.isError()) && !v.isEmpty())) {
Logger.error(this, "Server unreachable?: "+stunServer);
continue;
}
Logger.normal(this, "Successful STUN discovery from "+stunServer+"!:" + reportedData+" likely detections: "+countLikely+" unlikely detections "+countUnlikely+" remaining "+v.size());
System.err.println("Successful STUN discovery from "+stunServer+"!:" + reportedData+" likely detections: "+countLikely+" unlikely detections "+countUnlikely+" remaining "+v.size());
DetectedIP ip = convert(reportedData);
if(ip == null) {
Logger.normal(this, "Failed to parse reported data, skipping server "+stunServer);
continue;
}
out.add(ip);
if(ip.natType == DetectedIP.NO_UDP || ip.natType == DetectedIP.NOT_SUPPORTED || ip.natType == DetectedIP.SYMMETRIC_NAT || ip.natType == DetectedIP.SYMMETRIC_UDP_FIREWALL)
countUnlikely++; // unlikely outcomes
else
countLikely++;
if(countUnlikely >= 3 || countLikely >= 2 || v.isEmpty()) return (DetectedIP[])out.toArray(new DetectedIP[out.size()]);
} catch (BindException be) {
System.err.println(iaddress.toString() + ": " + be.getMessage());
} catch (UnknownHostException e) {
System.err.println("Could not find the STUN server "+stunServer+" : "+e+" - DNS problems? Trying another...");
} catch (SocketException e) {
System.err.println("Could not connect to the STUN server: "+stunServer+" : "+e+" - trying another...");
} catch (Exception e) {
System.err.println("Failed to run STUN to server "+stunServer+": "+e+" - trying another, report if persistent");
e.printStackTrace();
}
}
System.err.println("STUN failed: likely detections="+countLikely+" unlikely detections="+countUnlikely);
return null;
}
private DetectedIP convert(DiscoveryInfo info) {
InetAddress addr = info.getPublicIP();
if(addr == null || addr.isLinkLocalAddress() || addr.isSiteLocalAddress())
return null;
if(info.isError())
return null;
if(info.isOpenAccess())
return new DetectedIP(addr, DetectedIP.FULL_INTERNET);
if(info.isBlockedUDP())
return new DetectedIP(addr, DetectedIP.NO_UDP);
if(info.isFullCone())
return new DetectedIP(addr, DetectedIP.FULL_CONE_NAT);
if(info.isRestrictedCone())
return new DetectedIP(addr, DetectedIP.RESTRICTED_CONE_NAT);
if(info.isPortRestrictedCone())
return new DetectedIP(addr, DetectedIP.PORT_RESTRICTED_NAT);
if(info.isSymmetricCone())
return new DetectedIP(addr, DetectedIP.SYMMETRIC_NAT);
if(info.isSymmetricUDPFirewall())
return new DetectedIP(addr, DetectedIP.SYMMETRIC_UDP_FIREWALL);
return new DetectedIP(addr, DetectedIP.NOT_SUPPORTED);
}
public DetectedIP[] getAddress() {
Enumeration<NetworkInterface> ifaces;
try {
ifaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e1) {
System.err.println("Caught "+e1);
e1.printStackTrace();
return null;
}
while (ifaces.hasMoreElements()) {
NetworkInterface iface = ifaces.nextElement();
Enumeration<InetAddress> iaddresses = iface.getInetAddresses();
while (iaddresses.hasMoreElements()) {
InetAddress iaddress = iaddresses.nextElement();
if (!iaddress.isLoopbackAddress() && !iaddress.isLinkLocalAddress()) {
Thread detector = new DetectorThread(iaddress);
synchronized(this) {
detectors.add(detector);
}
try {
detector.start();
} catch (Throwable t) {
synchronized(this) {
detectors.remove(detector);
}
}
}
}
}
synchronized(this) {
while(true) {
if(detectors.isEmpty()) {
if(detected.isEmpty()) {
System.err.println("STUN failed to detect IP addresses");
return null;
}
DetectedIP[] ips = (DetectedIP[]) detected.toArray(new DetectedIP[detected.size()]);
return ips;
}
try {
wait();
} catch (InterruptedException e) {
// Check whether finished
}
}
}
}
private final HashSet detected = new HashSet();
private final HashSet detectors = new HashSet();
class DetectorThread extends Thread {
DetectorThread(InetAddress addr) {
this.startAddress = addr;
this.setDaemon(true);
this.setName("STUN IP detector for "+addr);
}
final InetAddress startAddress;
public void run() {
DetectedIP[] ip;
try {
ip = runTest(startAddress);
NetworkInterface nif = NetworkInterface.getByInetAddress(startAddress);
int mtu = -1;
if(nif != null) {
try {
Class c = nif.getClass();
Method m = c.getDeclaredMethod("getMTU", new Class[0]);
if(m != null) {
Integer iMTU = (Integer) m.invoke(nif, new Object[0]);
if(iMTU != null) {
mtu = iMTU.intValue();
System.err.println("Found interface MTU: "+nif.getName()+" : "+mtu);
}
}
} catch (Throwable t) {
System.err.println("Trying to access 1.6 getMTU(), caught "+t);
}
}
if(ip != null) {
for(int i=0; i<ip.length; i++)
ip[i].mtu = mtu;
}
} catch (Throwable t) {
ip = null;
System.err.println("Caught "+t);
t.printStackTrace();
}
synchronized(JSTUN.this) {
detectors.remove(this);
if(ip != null) {
for(int i=0;i<ip.length;i++)
detected.add(ip[i]);
}
JSTUN.this.notifyAll();
}
}
}
public void terminate() {
return;
}
public void runPlugin(PluginRespirator pr) {
this.pr = pr;
}
public String handleHTTPGet(HTTPRequest request) throws PluginHTTPException {
HTMLNode pageNode = pr.getPageMaker().getPageNode("JSTUN plugin", false, null);
HTMLNode contentNode = pr.getPageMaker().getContentNode(pageNode);
if(reportedData == null) {
if(hasRunTestBeenCalled) {
HTMLNode jSTUNReportInfobox = contentNode.addChild("div", "class", "infobox infobox-warning");
HTMLNode jSTUNReportInfoboxHeader = jSTUNReportInfobox.addChild("div", "class", "infobox-header");
HTMLNode jSTUNReportInfoboxContent = jSTUNReportInfobox.addChild("div", "class", "infobox-content");
jSTUNReportInfoboxHeader.addChild("#", "JSTUN detection report");
jSTUNReportInfoboxContent.addChild("#", "The plugin hasn't managed to contact any server yet.");
} else {
HTMLNode jSTUNReportInfobox = contentNode.addChild("div", "class", "infobox infobox-normal");
HTMLNode jSTUNReportInfoboxHeader = jSTUNReportInfobox.addChild("div", "class", "infobox-header");
HTMLNode jSTUNReportInfoboxContent = jSTUNReportInfobox.addChild("div", "class", "infobox-content");
jSTUNReportInfoboxHeader.addChild("#", "JSTUN detection report");
jSTUNReportInfoboxContent.addChild("#", "There is no need for the plugin to determine your ip address: the node knows it.");
}
} else {
HTMLNode jSTUNReportErrorInfobox = contentNode.addChild("div", "class", "infobox infobox-normal");
HTMLNode jSTUNReportInfoboxHeader = jSTUNReportErrorInfobox.addChild("div", "class", "infobox-header");
HTMLNode jSTUNReportInfoboxContent = jSTUNReportErrorInfobox.addChild("div", "class", "infobox-content");
jSTUNReportInfoboxHeader.addChild("#", "JSTUN detection report");
jSTUNReportInfoboxContent.addChild("#", "The plugin has reported the following data to the node:");
HTMLNode data = jSTUNReportInfoboxContent.addChild("pre");
data.addChild("#", reportedData.toString());
}
return pageNode.generate();
}
public String handleHTTPPost(HTTPRequest request)
throws PluginHTTPException {
return null;
}
public String handleHTTPPut(HTTPRequest request) throws PluginHTTPException {
return null;
}
public String getVersion() {
return "1.0";
}
}
| true | true | DetectedIP[] runTest(InetAddress iaddress) {
this.hasRunTestBeenCalled = true;
Random r = new Random(); // FIXME use something safer?
Vector v = new Vector(publicSTUNServers.length);
Vector out = new Vector();
int countLikely = 0;
int countUnlikely = 0;
for(int i=0;i<publicSTUNServers.length;i++)
v.add(publicSTUNServers[i]);
while(!v.isEmpty()) {
String stunServer = (String) v.remove(r.nextInt(v.size()));
try {
DiscoveryTest test = new DiscoveryTest(iaddress, stunServer, 3478);
// iphone-stun.freenet.de:3478
// larry.gloo.net:3478
// stun.xten.net:3478
reportedData = test.test();
if(((reportedData.isBlockedUDP() || reportedData.isError()) && !v.isEmpty())) {
Logger.error(this, "Server unreachable?: "+stunServer);
continue;
}
Logger.normal(this, "Successful STUN discovery from "+stunServer+"!:" + reportedData+" likely detections: "+countLikely+" unlikely detections "+countUnlikely+" remaining "+v.size());
System.err.println("Successful STUN discovery from "+stunServer+"!:" + reportedData+" likely detections: "+countLikely+" unlikely detections "+countUnlikely+" remaining "+v.size());
DetectedIP ip = convert(reportedData);
if(ip == null) {
Logger.normal(this, "Failed to parse reported data, skipping server "+stunServer);
continue;
}
out.add(ip);
if(ip.natType == DetectedIP.NO_UDP || ip.natType == DetectedIP.NOT_SUPPORTED || ip.natType == DetectedIP.SYMMETRIC_NAT || ip.natType == DetectedIP.SYMMETRIC_UDP_FIREWALL)
countUnlikely++; // unlikely outcomes
else
countLikely++;
if(countUnlikely >= 3 || countLikely >= 2 || v.isEmpty()) return (DetectedIP[])out.toArray(new DetectedIP[out.size()]);
} catch (BindException be) {
System.err.println(iaddress.toString() + ": " + be.getMessage());
} catch (UnknownHostException e) {
System.err.println("Could not find the STUN server "+stunServer+" : "+e+" - DNS problems? Trying another...");
} catch (SocketException e) {
System.err.println("Could not connect to the STUN server: "+stunServer+" : "+e+" - trying another...");
} catch (Exception e) {
System.err.println("Failed to run STUN to server "+stunServer+": "+e+" - trying another, report if persistent");
e.printStackTrace();
}
}
System.err.println("STUN failed: likely detections="+countLikely+" unlikely detections="+countUnlikely);
return null;
}
| DetectedIP[] runTest(InetAddress iaddress) {
this.hasRunTestBeenCalled = true;
Random r = new Random(); // FIXME use something safer?
Vector v = new Vector(publicSTUNServers.length);
Vector out = new Vector();
int countLikely = 0;
int countUnlikely = 0;
for(int i=0;i<publicSTUNServers.length;i++)
v.add(publicSTUNServers[i]);
while(!v.isEmpty()) {
if(WrapperManager.hasShutdownHookBeenTriggered()) return null;
String stunServer = (String) v.remove(r.nextInt(v.size()));
try {
DiscoveryTest test = new DiscoveryTest(iaddress, stunServer, 3478);
// iphone-stun.freenet.de:3478
// larry.gloo.net:3478
// stun.xten.net:3478
reportedData = test.test();
if(((reportedData.isBlockedUDP() || reportedData.isError()) && !v.isEmpty())) {
Logger.error(this, "Server unreachable?: "+stunServer);
continue;
}
Logger.normal(this, "Successful STUN discovery from "+stunServer+"!:" + reportedData+" likely detections: "+countLikely+" unlikely detections "+countUnlikely+" remaining "+v.size());
System.err.println("Successful STUN discovery from "+stunServer+"!:" + reportedData+" likely detections: "+countLikely+" unlikely detections "+countUnlikely+" remaining "+v.size());
DetectedIP ip = convert(reportedData);
if(ip == null) {
Logger.normal(this, "Failed to parse reported data, skipping server "+stunServer);
continue;
}
out.add(ip);
if(ip.natType == DetectedIP.NO_UDP || ip.natType == DetectedIP.NOT_SUPPORTED || ip.natType == DetectedIP.SYMMETRIC_NAT || ip.natType == DetectedIP.SYMMETRIC_UDP_FIREWALL)
countUnlikely++; // unlikely outcomes
else
countLikely++;
if(countUnlikely >= 3 || countLikely >= 2 || v.isEmpty()) return (DetectedIP[])out.toArray(new DetectedIP[out.size()]);
} catch (BindException be) {
System.err.println(iaddress.toString() + ": " + be.getMessage());
} catch (UnknownHostException e) {
System.err.println("Could not find the STUN server "+stunServer+" : "+e+" - DNS problems? Trying another...");
} catch (SocketException e) {
System.err.println("Could not connect to the STUN server: "+stunServer+" : "+e+" - trying another...");
} catch (Exception e) {
System.err.println("Failed to run STUN to server "+stunServer+": "+e+" - trying another, report if persistent");
e.printStackTrace();
}
}
System.err.println("STUN failed: likely detections="+countLikely+" unlikely detections="+countUnlikely);
return null;
}
|
diff --git a/src/it/wolfed/operation/MergeGraphsOperation.java b/src/it/wolfed/operation/MergeGraphsOperation.java
index 4cc2508..b0853a5 100644
--- a/src/it/wolfed/operation/MergeGraphsOperation.java
+++ b/src/it/wolfed/operation/MergeGraphsOperation.java
@@ -1,77 +1,79 @@
package it.wolfed.operation;
import com.mxgraph.model.mxCell;
import it.wolfed.model.ArcEdge;
import it.wolfed.model.InterfaceVertex;
import it.wolfed.model.PetriNetGraph;
import it.wolfed.model.PlaceVertex;
import it.wolfed.model.TransitionVertex;
import it.wolfed.model.Vertex;
import java.util.Arrays;
import java.util.List;
/**
*
*/
public class MergeGraphsOperation extends Operation
{
protected List<PetriNetGraph> inputGraphs;
/**
* Clone all the cells from inputGraphs into operationGraph.
*
* @param operationGraph
* @param inputGraphs
* @throws Exception
*/
public MergeGraphsOperation(PetriNetGraph operationGraph, PetriNetGraph... inputGraphs) throws Exception
{
super(operationGraph);
this.inputGraphs = Arrays.asList(inputGraphs);
execute();
}
@Override
void process()
{
mxCell clone = null;
Object parent = operationGraph.getDefaultParent();
for (int i = 0; i < inputGraphs.size(); i++)
{
PetriNetGraph net = inputGraphs.get(i);
for (Object cellObj : net.getChildCells(net.getDefaultParent()))
{
mxCell cell = (mxCell) cellObj;
if(cell instanceof PlaceVertex)
{
+ PlaceVertex place = (PlaceVertex) cell;
clone = new PlaceVertex(parent, getPrefix(i + 1) + cell.getId(), cell.getValue(), 0, 0);
- }
+ ((PlaceVertex)clone).setTokens(place.getTokens());
+ }
else if(cell instanceof TransitionVertex)
{
clone = new TransitionVertex(parent, getPrefix(i + 1) + cell.getId(), cell.getValue(), 0, 0);
}
else if(cell instanceof InterfaceVertex)
{
clone = new InterfaceVertex(parent, getPrefix(i + 1) + cell.getId(), cell.getValue());
}
// @todo check instanceof Arc when the mouserelease creation of arcs will be type-zed
// ArcEdge e mxCell.isEdge()
else if(cell.isEdge())
{
// Get
Vertex source = operationGraph.getVertexById(getPrefix(i + 1) + cell.getSource().getId());
Vertex target = operationGraph.getVertexById(getPrefix(i + 1) + cell.getTarget().getId());
// Clone
clone = new ArcEdge(parent, getPrefix(i + 1) + cell.getId(), cell.getValue(), source, target);
}
operationGraph.addCell(clone);
}
}
}
}
| false | true | void process()
{
mxCell clone = null;
Object parent = operationGraph.getDefaultParent();
for (int i = 0; i < inputGraphs.size(); i++)
{
PetriNetGraph net = inputGraphs.get(i);
for (Object cellObj : net.getChildCells(net.getDefaultParent()))
{
mxCell cell = (mxCell) cellObj;
if(cell instanceof PlaceVertex)
{
clone = new PlaceVertex(parent, getPrefix(i + 1) + cell.getId(), cell.getValue(), 0, 0);
}
else if(cell instanceof TransitionVertex)
{
clone = new TransitionVertex(parent, getPrefix(i + 1) + cell.getId(), cell.getValue(), 0, 0);
}
else if(cell instanceof InterfaceVertex)
{
clone = new InterfaceVertex(parent, getPrefix(i + 1) + cell.getId(), cell.getValue());
}
// @todo check instanceof Arc when the mouserelease creation of arcs will be type-zed
// ArcEdge e mxCell.isEdge()
else if(cell.isEdge())
{
// Get
Vertex source = operationGraph.getVertexById(getPrefix(i + 1) + cell.getSource().getId());
Vertex target = operationGraph.getVertexById(getPrefix(i + 1) + cell.getTarget().getId());
// Clone
clone = new ArcEdge(parent, getPrefix(i + 1) + cell.getId(), cell.getValue(), source, target);
}
operationGraph.addCell(clone);
}
}
}
| void process()
{
mxCell clone = null;
Object parent = operationGraph.getDefaultParent();
for (int i = 0; i < inputGraphs.size(); i++)
{
PetriNetGraph net = inputGraphs.get(i);
for (Object cellObj : net.getChildCells(net.getDefaultParent()))
{
mxCell cell = (mxCell) cellObj;
if(cell instanceof PlaceVertex)
{
PlaceVertex place = (PlaceVertex) cell;
clone = new PlaceVertex(parent, getPrefix(i + 1) + cell.getId(), cell.getValue(), 0, 0);
((PlaceVertex)clone).setTokens(place.getTokens());
}
else if(cell instanceof TransitionVertex)
{
clone = new TransitionVertex(parent, getPrefix(i + 1) + cell.getId(), cell.getValue(), 0, 0);
}
else if(cell instanceof InterfaceVertex)
{
clone = new InterfaceVertex(parent, getPrefix(i + 1) + cell.getId(), cell.getValue());
}
// @todo check instanceof Arc when the mouserelease creation of arcs will be type-zed
// ArcEdge e mxCell.isEdge()
else if(cell.isEdge())
{
// Get
Vertex source = operationGraph.getVertexById(getPrefix(i + 1) + cell.getSource().getId());
Vertex target = operationGraph.getVertexById(getPrefix(i + 1) + cell.getTarget().getId());
// Clone
clone = new ArcEdge(parent, getPrefix(i + 1) + cell.getId(), cell.getValue(), source, target);
}
operationGraph.addCell(clone);
}
}
}
|
diff --git a/EAPLI/src/eapli/NewClass.java b/EAPLI/src/eapli/NewClass.java
index 6e73579..d20c215 100644
--- a/EAPLI/src/eapli/NewClass.java
+++ b/EAPLI/src/eapli/NewClass.java
@@ -1,31 +1,31 @@
/*
* NewClass
* 08-Mar-2013
*
* funcoes:
* main
*
*
* Comentários:
* Teste
*
* Créditos:
* Joás V. Pereira <[email protected]>
*/
package eapli;
/**
*
* @author Joás V. Pereira <[email protected]>
*/
public class NewClass {
public static void main(String[] args) {
for (int i = 0; i < 10; i++){
- System.out.println("--->"+i);
+ System.out.println("--->"+(1+i));
}
}
}
| true | true | public static void main(String[] args) {
for (int i = 0; i < 10; i++){
System.out.println("--->"+i);
}
}
| public static void main(String[] args) {
for (int i = 0; i < 10; i++){
System.out.println("--->"+(1+i));
}
}
|
diff --git a/src/com/mahn42/anhalter42/creator/CommandWorldEditFlood.java b/src/com/mahn42/anhalter42/creator/CommandWorldEditFlood.java
index 352d077..becfbde 100644
--- a/src/com/mahn42/anhalter42/creator/CommandWorldEditFlood.java
+++ b/src/com/mahn42/anhalter42/creator/CommandWorldEditFlood.java
@@ -1,78 +1,83 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.mahn42.anhalter42.creator;
import com.mahn42.framework.BlockPosition;
import com.mahn42.framework.BlockPositionDelta;
import com.mahn42.framework.BlockPositionWalkAround;
import com.mahn42.framework.Framework;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
*
* @author andre
*/
public class CommandWorldEditFlood implements CommandExecutor {
// c_we_flood <mat> <data> [<transmat1> [<transmat2>...]]
@Override
public boolean onCommand(CommandSender aCommandSender, Command aCommand, String aString, String[] aStrings) {
if (aCommandSender instanceof Player) {
if (aStrings.length > 1) {
ArrayList<Material> lTrans = new ArrayList<Material>();
if (aStrings.length > 2) {
int lIndex = 2;
while (lIndex < aStrings.length) {
lTrans.add(CreatorPlugin.plugin.getMaterialForPlayer(aCommandSender, aStrings[lIndex]));
lIndex++;
}
} else {
lTrans.add(Material.AIR);
}
World lWorld;
Player lPlayer = ((Player)aCommandSender);
lWorld = lPlayer.getWorld();
List<Block> lastTwoTargetBlocks = lPlayer.getLastTwoTargetBlocks(null, 20);
- BlockPosition lStart = new BlockPosition(lastTwoTargetBlocks.get(0).getLocation());
+ BlockPosition lStart;
+ if (lTrans.contains(lastTwoTargetBlocks.get(1).getType())) {
+ lStart = new BlockPosition(lastTwoTargetBlocks.get(1).getLocation());
+ } else {
+ lStart = new BlockPosition(lastTwoTargetBlocks.get(0).getLocation());
+ }
Material lMat = CreatorPlugin.plugin.getMaterialForPlayer(aCommandSender, aStrings[0]);
byte lData = Byte.parseByte(aStrings[1]);
int lMaxBlocks = 20000;
ArrayList<BlockPosition> lStack = new ArrayList<BlockPosition>();
ArrayList<BlockPosition> lAll = new ArrayList<BlockPosition>();
lStack.add(lStart);
while (!lStack.isEmpty() && lAll.size() < lMaxBlocks) {
ArrayList<BlockPosition> lNext = new ArrayList<BlockPosition>();
for(BlockPosition lpos : lStack) {
if (lTrans.contains(lpos.getBlockType(lWorld))) {
lAll.add(lpos);
for(BlockPosition lnp : new BlockPositionWalkAround(lpos, BlockPositionDelta.HorizontalAndDown)) {
if (!lNext.contains(lnp) && !lAll.contains(lnp)) {
Material lnpm = lnp.getBlockType(lWorld);
if (lTrans.contains(lnpm)) {
lNext.add(lnp);
}
}
}
}
}
lStack.clear();
lStack = lNext;
}
for(BlockPosition lPos : lAll) {
Framework.plugin.setTypeAndData(lPos.getLocation(lWorld), lMat, lData, true);
}
}
}
return true;
}
}
| true | true | public boolean onCommand(CommandSender aCommandSender, Command aCommand, String aString, String[] aStrings) {
if (aCommandSender instanceof Player) {
if (aStrings.length > 1) {
ArrayList<Material> lTrans = new ArrayList<Material>();
if (aStrings.length > 2) {
int lIndex = 2;
while (lIndex < aStrings.length) {
lTrans.add(CreatorPlugin.plugin.getMaterialForPlayer(aCommandSender, aStrings[lIndex]));
lIndex++;
}
} else {
lTrans.add(Material.AIR);
}
World lWorld;
Player lPlayer = ((Player)aCommandSender);
lWorld = lPlayer.getWorld();
List<Block> lastTwoTargetBlocks = lPlayer.getLastTwoTargetBlocks(null, 20);
BlockPosition lStart = new BlockPosition(lastTwoTargetBlocks.get(0).getLocation());
Material lMat = CreatorPlugin.plugin.getMaterialForPlayer(aCommandSender, aStrings[0]);
byte lData = Byte.parseByte(aStrings[1]);
int lMaxBlocks = 20000;
ArrayList<BlockPosition> lStack = new ArrayList<BlockPosition>();
ArrayList<BlockPosition> lAll = new ArrayList<BlockPosition>();
lStack.add(lStart);
while (!lStack.isEmpty() && lAll.size() < lMaxBlocks) {
ArrayList<BlockPosition> lNext = new ArrayList<BlockPosition>();
for(BlockPosition lpos : lStack) {
if (lTrans.contains(lpos.getBlockType(lWorld))) {
lAll.add(lpos);
for(BlockPosition lnp : new BlockPositionWalkAround(lpos, BlockPositionDelta.HorizontalAndDown)) {
if (!lNext.contains(lnp) && !lAll.contains(lnp)) {
Material lnpm = lnp.getBlockType(lWorld);
if (lTrans.contains(lnpm)) {
lNext.add(lnp);
}
}
}
}
}
lStack.clear();
lStack = lNext;
}
for(BlockPosition lPos : lAll) {
Framework.plugin.setTypeAndData(lPos.getLocation(lWorld), lMat, lData, true);
}
}
}
return true;
}
| public boolean onCommand(CommandSender aCommandSender, Command aCommand, String aString, String[] aStrings) {
if (aCommandSender instanceof Player) {
if (aStrings.length > 1) {
ArrayList<Material> lTrans = new ArrayList<Material>();
if (aStrings.length > 2) {
int lIndex = 2;
while (lIndex < aStrings.length) {
lTrans.add(CreatorPlugin.plugin.getMaterialForPlayer(aCommandSender, aStrings[lIndex]));
lIndex++;
}
} else {
lTrans.add(Material.AIR);
}
World lWorld;
Player lPlayer = ((Player)aCommandSender);
lWorld = lPlayer.getWorld();
List<Block> lastTwoTargetBlocks = lPlayer.getLastTwoTargetBlocks(null, 20);
BlockPosition lStart;
if (lTrans.contains(lastTwoTargetBlocks.get(1).getType())) {
lStart = new BlockPosition(lastTwoTargetBlocks.get(1).getLocation());
} else {
lStart = new BlockPosition(lastTwoTargetBlocks.get(0).getLocation());
}
Material lMat = CreatorPlugin.plugin.getMaterialForPlayer(aCommandSender, aStrings[0]);
byte lData = Byte.parseByte(aStrings[1]);
int lMaxBlocks = 20000;
ArrayList<BlockPosition> lStack = new ArrayList<BlockPosition>();
ArrayList<BlockPosition> lAll = new ArrayList<BlockPosition>();
lStack.add(lStart);
while (!lStack.isEmpty() && lAll.size() < lMaxBlocks) {
ArrayList<BlockPosition> lNext = new ArrayList<BlockPosition>();
for(BlockPosition lpos : lStack) {
if (lTrans.contains(lpos.getBlockType(lWorld))) {
lAll.add(lpos);
for(BlockPosition lnp : new BlockPositionWalkAround(lpos, BlockPositionDelta.HorizontalAndDown)) {
if (!lNext.contains(lnp) && !lAll.contains(lnp)) {
Material lnpm = lnp.getBlockType(lWorld);
if (lTrans.contains(lnpm)) {
lNext.add(lnp);
}
}
}
}
}
lStack.clear();
lStack = lNext;
}
for(BlockPosition lPos : lAll) {
Framework.plugin.setTypeAndData(lPos.getLocation(lWorld), lMat, lData, true);
}
}
}
return true;
}
|
diff --git a/src/org/geworkbench/engine/skin/Skin.java b/src/org/geworkbench/engine/skin/Skin.java
index d630b873..711786e3 100755
--- a/src/org/geworkbench/engine/skin/Skin.java
+++ b/src/org/geworkbench/engine/skin/Skin.java
@@ -1,830 +1,831 @@
package org.geworkbench.engine.skin;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import net.eleritec.docking.DockableAdapter;
import net.eleritec.docking.DockingManager;
import net.eleritec.docking.DockingPort;
import net.eleritec.docking.defaults.ComponentProviderAdapter;
import net.eleritec.docking.defaults.DefaultDockingPort;
import org.apache.commons.collections15.map.ReferenceMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geworkbench.bison.datastructure.biocollections.DSDataSet;
import org.geworkbench.bison.datastructure.bioobjects.DSBioObject;
import org.geworkbench.builtin.projects.Icons;
import org.geworkbench.engine.ccm.ComponentConfigurationManagerWindow2;
import org.geworkbench.engine.config.Closable;
import org.geworkbench.engine.config.GUIFramework;
import org.geworkbench.engine.config.PluginDescriptor;
import org.geworkbench.engine.config.VisualPlugin;
import org.geworkbench.engine.config.events.AppEventListenerException;
import org.geworkbench.engine.config.events.EventSource;
import org.geworkbench.engine.config.rules.GeawConfigObject;
import org.geworkbench.engine.management.ComponentRegistry;
import org.geworkbench.engine.properties.PropertiesManager;
import org.geworkbench.events.ComponentDockingEvent;
import org.geworkbench.events.listeners.ComponentDockingListener;
import org.geworkbench.util.FilePathnameUtils;
import org.geworkbench.util.JAutoList;
/**
* <p>Title: Bioworks</p>
* <p>Description: Modular Application Framework for Gene Expession, Sequence and Genotype Analysis</p>
* <p>Copyright: Copyright (c) 2003 -2004</p>
* <p>Company: Columbia University</p>
*
* @author manjunath at genomecenter dot columbia dot edu
* @version $Id$
*/
public class Skin extends GUIFramework {
private static final String YES = "yes";
private static final String NO = "no";
private static final long serialVersionUID = 3617137568252369693L;
static Log log = LogFactory.getLog(Skin.class);
private static Map<Component, String> visualRegistry = new HashMap<Component, String>();
private JPanel contentPane;
private JLabel statusBar = new JLabel();
private BorderLayout borderLayout1 = new BorderLayout();
private JSplitPane jSplitPane1 = new JSplitPane();
private DefaultDockingPort visualPanel = new DefaultDockingPort();
private DefaultDockingPort commandPanel = new DefaultDockingPort();
private JSplitPane jSplitPane2 = new JSplitPane();
private JSplitPane jSplitPane3 = new JSplitPane();
private DefaultDockingPort selectionPanel = new DefaultDockingPort();
private JToolBar jToolBar = new JToolBar();
private DefaultDockingPort projectPanel = new DefaultDockingPort();
private Map<String, DefaultDockingPort> areas = new Hashtable<String, DefaultDockingPort>();
DockingNotifier eventSink = new DockingNotifier();
@SuppressWarnings("unchecked")
private Set<Class> acceptors;
private HashMap<Component, Class<?>> mainComponentClass = new HashMap<Component, Class<?>>();
private ReferenceMap<DSDataSet<? extends DSBioObject>, String> visualLastSelected = new ReferenceMap<DSDataSet<? extends DSBioObject>, String>();
private ReferenceMap<DSDataSet<? extends DSBioObject>, String> commandLastSelected = new ReferenceMap<DSDataSet<? extends DSBioObject>, String>();
private ReferenceMap<DSDataSet<? extends DSBioObject>, String> selectionLastSelected = new ReferenceMap<DSDataSet<? extends DSBioObject>, String>();
private ArrayList<DockableImpl> visualDockables = new ArrayList<DockableImpl>();
private ArrayList<DockableImpl> commandDockables = new ArrayList<DockableImpl>();
private ArrayList<DockableImpl> selectorDockables = new ArrayList<DockableImpl>();
private DSDataSet<? extends DSBioObject> currentDataSet;
private boolean tabSwappingMode = false;
public static final String APP_SIZE_FILE = "appCoords.txt";
public String getVisualLastSelected(DSDataSet<? extends DSBioObject> dataSet) {
return visualLastSelected.get(dataSet);
}
public String getCommandLastSelected(DSDataSet<? extends DSBioObject> dataSet) {
return commandLastSelected.get(dataSet);
}
public String getSelectionLastSelected(DSDataSet<? extends DSBioObject> dataSet) {
return selectionLastSelected.get(dataSet);
}
public void setVisualLastSelected(DSDataSet<? extends DSBioObject> dataSet, String component) {
if (component != null) {
visualLastSelected.put(dataSet, component);
}
}
public void setCommandLastSelected(DSDataSet<? extends DSBioObject> dataSet, String component) {
if (component != null) {
commandLastSelected.put(dataSet, component);
}
}
public void setSelectionLastSelected(DSDataSet<? extends DSBioObject> dataSet, String component) {
if (component != null) {
selectionLastSelected.put(dataSet, component);
}
}
public Skin() {
registerAreas();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Dimension finalSize = getSize();
Point finalLocation = getLocation();
File f = new File(FilePathnameUtils.getTemporaryFilesDirectoryPath() + APP_SIZE_FILE);
try {
PrintWriter out = new PrintWriter(new FileWriter(f));
out.println("" + finalSize.width);
out.println("" + finalSize.height);
out.println("" + finalLocation.x);
out.println("" + finalLocation.y);
out.close();
List<Object> list = ComponentRegistry.getRegistry().getComponentsList();
for(Object obj: list)
{
if ( obj instanceof Closable)
((Closable)obj).closing();
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
private void setApplicationTitle() {
MessageFormat format = new MessageFormat(System.getProperty("application.title"));
Object[] version = { VERSION };
setTitle(format.format(version));
}
private void jbInit() throws Exception {
contentPane = (JPanel) this.getContentPane();
this.setIconImage(Icons.MICROARRAYS_ICON.getImage());
contentPane.setLayout(borderLayout1);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int guiHeight = 0;
int guiWidth = 0;
boolean foundSize = false;
File sizeFile = new File(FilePathnameUtils.getTemporaryFilesDirectoryPath() + APP_SIZE_FILE);
if (sizeFile.exists()) {
try {
BufferedReader in = new BufferedReader(new FileReader(sizeFile));
guiWidth = Integer.parseInt(in.readLine());
guiHeight = Integer.parseInt(in.readLine());
int guiX = Integer.parseInt(in.readLine());
int guiY = Integer.parseInt(in.readLine());
setLocation(guiX, guiY);
foundSize = true;
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (!foundSize) {
guiWidth = (int) (dim.getWidth() * 0.9);
guiHeight = (int) (dim.getHeight() * 0.9);
this.setLocation((dim.width - guiWidth) / 2, (dim.height - guiHeight) / 2);
}
setSize(new Dimension(guiWidth, guiHeight));
setApplicationTitle();
statusBar.setText(" ");
jSplitPane1.setBorder(BorderFactory.createLineBorder(Color.black));
jSplitPane1.setDoubleBuffered(true);
jSplitPane1.setContinuousLayout(true);
jSplitPane1.setBackground(Color.black);
jSplitPane1.setDividerSize(8);
jSplitPane1.setOneTouchExpandable(true);
jSplitPane1.setResizeWeight(0);
jSplitPane2.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane2.setDoubleBuffered(true);
jSplitPane2.setContinuousLayout(true);
jSplitPane2.setDividerSize(8);
jSplitPane2.setOneTouchExpandable(true);
jSplitPane2.setResizeWeight(0.9);
jSplitPane2.setMinimumSize(new Dimension(0, 0));
jSplitPane3.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane3.setBorder(BorderFactory.createLineBorder(Color.black));
jSplitPane3.setDoubleBuffered(true);
jSplitPane3.setContinuousLayout(true);
jSplitPane3.setDividerSize(8);
jSplitPane3.setOneTouchExpandable(true);
jSplitPane3.setResizeWeight(0.1);
jSplitPane3.setMinimumSize(new Dimension(0, 0));
contentPane.add(statusBar, BorderLayout.SOUTH);
contentPane.add(jSplitPane1, BorderLayout.CENTER);
jSplitPane1.add(jSplitPane2, JSplitPane.RIGHT);
jSplitPane2.add(commandPanel, JSplitPane.BOTTOM);
jSplitPane2.add(visualPanel, JSplitPane.TOP);
jSplitPane1.add(jSplitPane3, JSplitPane.LEFT);
jSplitPane3.add(selectionPanel, JSplitPane.BOTTOM);
jSplitPane3.add(projectPanel, JSplitPane.LEFT);
contentPane.add(jToolBar, BorderLayout.NORTH);
jSplitPane1.setDividerLocation(230);
jSplitPane2.setDividerLocation((int) (guiHeight * 0.60));
jSplitPane3.setDividerLocation((int) (guiHeight * 0.35));
visualPanel.setComponentProvider(new ComponentProvider(VISUAL_AREA));
commandPanel.setComponentProvider(new ComponentProvider(COMMAND_AREA));
selectionPanel.setComponentProvider(new ComponentProvider(SELECTION_AREA));
projectPanel.setComponentProvider(new ComponentProvider(PROJECT_AREA));
final String CANCEL_DIALOG = "cancel-dialog";
contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), CANCEL_DIALOG);
contentPane.getActionMap().put(CANCEL_DIALOG, new AbstractAction() {
private static final long serialVersionUID = 6732252343409902879L;
public void actionPerformed(ActionEvent event) {
chooseComponent();
}
});// contentPane.addKeyListener(new KeyAdapter() {
final String RCM_DIALOG = "rcm-dialog";
contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0), RCM_DIALOG);
contentPane.getActionMap().put(RCM_DIALOG, new AbstractAction() {
private static final long serialVersionUID = 3053589598512384113L;
public void actionPerformed(ActionEvent event) {
loadRCM();
}
});
}
private static class DialogResult {
public boolean cancelled = false;
}
void loadRCM(){
ComponentConfigurationManagerWindow2.load();
}
@SuppressWarnings("unchecked")
void chooseComponent() {
if (acceptors == null) {
// Get all appropriate acceptors
acceptors = new HashSet<Class>();
}
// 1) Get all visual components
ComponentRegistry registry = ComponentRegistry.getRegistry();
VisualPlugin[] plugins = registry.getModules(VisualPlugin.class);
ArrayList<String> availablePlugins = new ArrayList<String>();
for (int i = 0; i < plugins.length; i++) {
String name = registry.getDescriptorForPlugin(plugins[i]).getLabel();
for (Class type: acceptors) {
if (registry.getDescriptorForPluginClass(type).getLabel().equals(name)) {
availablePlugins.add(name);
break;
}
}
}
final String[] names = availablePlugins.toArray(new String[0]);
// 2) Sort alphabetically
Arrays.sort(names);
// 3) Create dialog with JAutoText (prefix mode)
DefaultListModel model = new DefaultListModel();
for (int i = 0; i < names.length; i++) {
model.addElement(names[i]);
}
final JDialog dialog = new JDialog();
final DialogResult dialogResult = new DialogResult();
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dialogResult.cancelled = true;
}
});
final JAutoList autoList = new JAutoList(model) {
private static final long serialVersionUID = -5117126504179347748L;
protected void keyPressed(KeyEvent event) {
if (event.getKeyChar() == '\n') {
if (getHighlightedIndex() == -1 ){
return;
}
dialogResult.cancelled = false;
dialog.dispose();
} else if (event.getKeyChar() == 0x1b) {
dialogResult.cancelled = true;
dialog.dispose();
} else {
super.keyPressed(event);
}
}
protected void elementDoubleClicked(int index, MouseEvent e) {
dialogResult.cancelled = false;
dialog.dispose();
}
};
autoList.setPrefixMode(true);
dialog.setTitle("Component");
dialog.getContentPane().add(autoList);
dialog.setModal(true);
dialog.pack();
dialog.setSize(200, 300);
Dimension size = dialog.getSize();
Dimension frameSize = getSize();
int x = getLocationOnScreen().x + (frameSize.width - size.width) / 2;
int y = getLocationOnScreen().y + (frameSize.height - size.height) / 2;
// 5) Display and get result
dialog.setBounds(x, y, size.width, size.height);
dialog.setVisible(true);
if (!dialogResult.cancelled) {
int index = autoList.getHighlightedIndex();
boolean found = false;
for (String key : areas.keySet()) {
if (areas.get(key) instanceof DefaultDockingPort) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(key);
if (port.getDockedComponent() instanceof JTabbedPane) {
JTabbedPane pane = (JTabbedPane) port.getDockedComponent();
int n = pane.getTabCount();
for (int i = 0; i < n; i++) {
String title = pane.getTitleAt(i);
if (title.equals(names[index])) {
pane.setSelectedIndex(i);
pane.getComponentAt(i).requestFocus();
found = true;
break;
}
}
if (found) {
break;
}
}
}
}
}
}
/**
* Associates Visual Areas with Component Holders
*/
protected void registerAreas() {
// areas.put(TOOL_AREA, jToolBar); // this is not used any more
areas.put(VISUAL_AREA, visualPanel);
areas.put(COMMAND_AREA, commandPanel);
areas.put(SELECTION_AREA, selectionPanel);
areas.put(PROJECT_AREA, projectPanel);
}
// Is this used?
public void addToContainer(String areaName, Component visualPlugin) {
DockableImpl wrapper = new DockableImpl(visualPlugin, visualPlugin.getName());
DockingManager.registerDockable(wrapper);
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
port.dock(wrapper, DockingPort.CENTER_REGION);
visualRegistry.put(visualPlugin, areaName);
}
/**
* Removes the designated <code>visualPlugin</code> from the GUI.
*
* @param visualPlugin component to be removed
*/
public void remove(Component visualPluginComponent) {
mainComponentClass.remove(visualPluginComponent);
visualRegistry.remove(visualPluginComponent);
}
public String getVisualArea(Component visualPlugin) {
return (String) visualRegistry.get(visualPlugin);
}
@SuppressWarnings("unchecked")
@Override
public void addToContainer(String areaName, Component visualPlugin, String pluginName, Class mainPluginClass) {
visualPlugin.setName(pluginName);
DockableImpl wrapper = new DockableImpl(visualPlugin, pluginName);
DockingManager.registerDockable(wrapper);
if (!areaName.equals(GUIFramework.VISUAL_AREA) && !areaName.equals(GUIFramework.COMMAND_AREA)) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
port.dock(wrapper, DockingPort.CENTER_REGION);
} else {
log.debug("Plugin wanting to go to visual or command area: " + pluginName);
}
visualRegistry.put(visualPlugin, areaName);
mainComponentClass.put(visualPlugin, mainPluginClass);
}
private void dockingFinished(DockableImpl comp) {
for (String area: areas.keySet()) {
Component port = (Component) areas.get(area);
Component container = comp.getDockable().getParent();
if (container instanceof JTabbedPane || container instanceof JSplitPane) {
if (container.getParent() == port) {
eventSink.throwEvent(comp.getPlugin(), area);
}
} else if (container instanceof DefaultDockingPort) {
if (container == port)
eventSink.throwEvent(comp.getPlugin(), area);
}
}
}
private class DockableImpl extends DockableAdapter {
private JPanel wrapper = null;
private JLabel initiator = null;
private String description = null;
private Component plugin = null;
private JPanel buttons = new JPanel();
private JPanel topBar = new JPanel();
private JButton docker = new JButton();
private boolean docked = true;
private ImageIcon dock_grey = new ImageIcon(Skin.class.getResource("dock_grey.gif"));
private ImageIcon dock = new ImageIcon(Skin.class.getResource("dock.gif"));
private ImageIcon dock_active = new ImageIcon(Skin.class.getResource("dock_active.gif"));
private ImageIcon undock_grey = new ImageIcon(Skin.class.getResource("undock_grey.gif"));
private ImageIcon undock = new ImageIcon(Skin.class.getResource("undock.gif"));
private ImageIcon undock_active = new ImageIcon(Skin.class.getResource("undock_active.gif"));
DockableImpl(Component plugin, String desc) {
this.plugin = plugin;
wrapper = new JPanel();
docker.setPreferredSize(new Dimension(16, 16));
docker.setBorderPainted(false);
docker.setIcon(undock_grey);
docker.setRolloverEnabled(true);
docker.setRolloverIcon(undock);
docker.setPressedIcon(undock_active);
docker.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
docker_actionPerformed(e);
}
});
buttons.setLayout(new GridLayout(1, 3));
buttons.add(docker);
initiator = new JLabel(" ");
initiator.setForeground(Color.darkGray);
initiator.setBackground(Color.getHSBColor(0.0f, 0.0f, 0.6f));
initiator.setOpaque(true);
initiator.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
setMoveCursor(me);
}
public void mouseExited(MouseEvent me) {
setDefaultCursor(me);
}
});
topBar.setLayout(new BorderLayout());
topBar.add(initiator, BorderLayout.CENTER);
topBar.add(buttons, BorderLayout.EAST);
wrapper.setLayout(new BorderLayout());
wrapper.add(topBar, BorderLayout.NORTH);
wrapper.add(plugin, BorderLayout.CENTER);
description = desc;
}
private JFrame frame = null;
private void docker_actionPerformed(ActionEvent e) {
log.debug("Action performed.");
String areaName = getVisualArea(this.getPlugin());
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
if (docked) {
undock(port);
return;
} else {
redock(port);
}
}
public void undock(final DefaultDockingPort port) {
log.debug("Undocking.");
port.undock(wrapper);
port.reevaluateContainerTree();
port.revalidate();
port.repaint();
docker.setIcon(dock_grey);
docker.setRolloverIcon(dock);
docker.setPressedIcon(dock_active);
docker.setSelected(false);
docker.repaint();
frame = new JFrame(description);
frame.setUndecorated(false);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
redock(port);
}
});
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(wrapper, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.repaint();
docked = false;
return;
}
public void redock(DefaultDockingPort port) {
if (frame != null) {
log.debug("Redocking " + plugin);
docker.setIcon(undock_grey);
docker.setRolloverIcon(undock);
docker.setPressedIcon(undock_active);
docker.setSelected(false);
port.dock(this, DockingPort.CENTER_REGION);
port.reevaluateContainerTree();
port.revalidate();
docked = true;
frame.getContentPane().remove(wrapper);
frame.dispose();
}
}
private void setMoveCursor(MouseEvent me) {
initiator.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
private void setDefaultCursor(MouseEvent me) {
initiator.setCursor(Cursor.getDefaultCursor());
}
public Component getDockable() {
return wrapper;
}
public String getDockableDesc() {
return description;
}
public Component getInitiator() {
return initiator;
}
public Component getPlugin() {
return plugin;
}
public void dockingCompleted() {
dockingFinished(this);
}
}
private class ComponentProvider extends ComponentProviderAdapter {
private String area;
public ComponentProvider(String area) {
this.area = area;
}
// Add change listeners to appropriate areas so
public JTabbedPane createTabbedPane() {
final JTabbedPane pane = new JTabbedPane();
if (area.equals(VISUAL_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, visualLastSelected));
} else if (area.equals(COMMAND_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, commandLastSelected));
} else if (area.equals(SELECTION_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, selectionLastSelected));
}
return pane;
}
}
private class TabChangeListener implements ChangeListener {
private final JTabbedPane pane;
private final ReferenceMap<DSDataSet<? extends DSBioObject>, String> lastSelected;
public TabChangeListener(JTabbedPane pane, ReferenceMap<DSDataSet<? extends DSBioObject>, String> lastSelected) {
this.pane = pane;
this.lastSelected = lastSelected;
}
public void stateChanged(ChangeEvent e) {
if ((currentDataSet != null) && !tabSwappingMode) {
int index = pane.getSelectedIndex();
if(index>=0) {
lastSelected.put(currentDataSet, pane.getTitleAt(index));
}
}
}
}
private class DockingNotifier extends EventSource {
public void throwEvent(Component source, String region) {
try {
throwEvent(ComponentDockingListener.class, "dockingAreaChanged", new ComponentDockingEvent(this, source, region));
} catch (AppEventListenerException aele) {
aele.printStackTrace();
}
}
}
@SuppressWarnings("unchecked")
public void setVisualizationType(DSDataSet type) {
currentDataSet = type;
// These are default acceptors
acceptors = ComponentRegistry.getRegistry().getAcceptors(null);
if (type != null) {
acceptors.addAll(ComponentRegistry.getRegistry().getAcceptors(type.getClass()));
}
if (type == null) {
log.trace("Default acceptors found:");
} else {
log.trace("Found the following acceptors for type " + type.getClass());
}
// Set up Visual Area
tabSwappingMode = true;
addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables);
selectLastComponent(GUIFramework.VISUAL_AREA, visualLastSelected.get(type));
addAppropriateComponents(acceptors, GUIFramework.COMMAND_AREA, commandDockables);
selectLastComponent(GUIFramework.COMMAND_AREA, commandLastSelected.get(type));
selectLastComponent(GUIFramework.SELECTION_AREA, selectionLastSelected.get(type));
addAppropriateComponents(acceptors, GUIFramework.SELECTION_AREA, selectorDockables);
tabSwappingMode = false;
contentPane.revalidate();
contentPane.repaint();
}
@SuppressWarnings("unchecked")
private void addAppropriateComponents(Set<Class> acceptors, String screenRegion, ArrayList<DockableImpl> dockables) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion);
for (DockableImpl dockable : dockables) {
dockable.redock(port);
}
dockables.clear();
port.removeAll();
SortedMap<Integer, Component> tabsToAdd = new TreeMap<Integer, Component>();
for (Component component : visualRegistry.keySet()) {
if (visualRegistry.get(component).equals(screenRegion)) {
Class<?> mainclass = mainComponentClass.get(component);
if (acceptors.contains(mainclass)) {
log.trace("Found component in "+screenRegion+" to show: " + mainclass.toString());
PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainclass);
tabsToAdd.put(desc.getPreferredOrder(), component);
}
}
}
for (Integer tabIndex : tabsToAdd.keySet()) {
PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainComponentClass.get(tabsToAdd.get(tabIndex)));
Component component = tabsToAdd.get(tabIndex);
DockableImpl dockable = new DockableImpl(component, desc.getLabel());
dockables.add(dockable);
port.dock(dockable, DockingPort.CENTER_REGION);
}
port.invalidate();
}
private void selectLastComponent(String screenRegion, String selected) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion);
if (selected != null) {
Component docked = port.getDockedComponent();
if (docked instanceof JTabbedPane) {
JTabbedPane pane = (JTabbedPane) docked;
int n = pane.getTabCount();
for (int i = 0; i < n; i++) {
if (selected.equals(pane.getTitleAt(i))) {
pane.setSelectedIndex(i);
break;
}
}
}
}
}
public void resetSelectorTabOrder() {
selectLastComponent(GUIFramework.SELECTION_AREA, "Markers");
}
public void initWelcomeScreen() {
PropertiesManager pm = PropertiesManager.getInstance();
try {
String showWelcomeScreen = pm.getProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION, YES);
if(showWelcomeScreen.equalsIgnoreCase(YES)) {
showWelcomeScreen();
} else {
hideWelcomeScreen();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public void showWelcomeScreen() {
// TODO Does register needs a public method for add a acceptor?
HashMap<Class, List<Class>> acceptorsNew = ComponentRegistry.getRegistry()
.getAcceptorsHashMap();
List<Class> list = acceptorsNew.get(null);
Class welcomeScreenClass;
try {
welcomeScreenClass = Class.forName("org.geworkbench.engine.WelcomeScreen");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
return;
}
list.add(welcomeScreenClass);
acceptorsNew.put(null, list);
ComponentRegistry.getRegistry().setAcceptorsHashMap(acceptorsNew);
if(acceptors==null)
acceptors = ComponentRegistry.getRegistry().getAcceptors(null);
acceptors.add(welcomeScreenClass);
addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables);
contentPane.revalidate();
PropertiesManager pm = PropertiesManager.getInstance();
try {
pm.setProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION,
YES);
} catch (IOException e) {
e.printStackTrace();
}
GeawConfigObject.enableWelcomeScreenMenu(false);
}
@SuppressWarnings("unchecked")
public void hideWelcomeScreen() {
if(acceptors==null)
acceptors = ComponentRegistry.getRegistry().getAcceptors(null);
// TODO register needs a public method for remove a acceptor
HashMap<Class, List<Class>> acceptorsNew = ComponentRegistry
.getRegistry().getAcceptorsHashMap();
List<Class> componentList = acceptorsNew.get(null);
+ List<Class> newComponentList = new ArrayList<Class>();
for (Class<?> componentClass : componentList) {
String componentClassName = componentClass.getName();
if ( componentClassName
.equals("org.geworkbench.engine.WelcomeScreen") ) {
- componentList.remove(componentClass);
acceptors.remove(componentClass);
break;
+ } else {
+ newComponentList.add(componentClass);
}
}
- acceptorsNew.put(null, componentList);
- ComponentRegistry.getRegistry().setAcceptorsHashMap(acceptorsNew);
+ acceptorsNew.put(null, newComponentList);
addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables);
contentPane.revalidate();
contentPane.repaint();
PropertiesManager pm = PropertiesManager.getInstance();
try {
pm.setProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION,
NO);
} catch (IOException e) {
e.printStackTrace();
}
GeawConfigObject.enableWelcomeScreenMenu(true);
}
private static final String WELCOME_SCREEN_KEY = "Welcome Screen ";
private static final String VERSION = System.getProperty("application.version");
}
| false | true | private void jbInit() throws Exception {
contentPane = (JPanel) this.getContentPane();
this.setIconImage(Icons.MICROARRAYS_ICON.getImage());
contentPane.setLayout(borderLayout1);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int guiHeight = 0;
int guiWidth = 0;
boolean foundSize = false;
File sizeFile = new File(FilePathnameUtils.getTemporaryFilesDirectoryPath() + APP_SIZE_FILE);
if (sizeFile.exists()) {
try {
BufferedReader in = new BufferedReader(new FileReader(sizeFile));
guiWidth = Integer.parseInt(in.readLine());
guiHeight = Integer.parseInt(in.readLine());
int guiX = Integer.parseInt(in.readLine());
int guiY = Integer.parseInt(in.readLine());
setLocation(guiX, guiY);
foundSize = true;
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (!foundSize) {
guiWidth = (int) (dim.getWidth() * 0.9);
guiHeight = (int) (dim.getHeight() * 0.9);
this.setLocation((dim.width - guiWidth) / 2, (dim.height - guiHeight) / 2);
}
setSize(new Dimension(guiWidth, guiHeight));
setApplicationTitle();
statusBar.setText(" ");
jSplitPane1.setBorder(BorderFactory.createLineBorder(Color.black));
jSplitPane1.setDoubleBuffered(true);
jSplitPane1.setContinuousLayout(true);
jSplitPane1.setBackground(Color.black);
jSplitPane1.setDividerSize(8);
jSplitPane1.setOneTouchExpandable(true);
jSplitPane1.setResizeWeight(0);
jSplitPane2.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane2.setDoubleBuffered(true);
jSplitPane2.setContinuousLayout(true);
jSplitPane2.setDividerSize(8);
jSplitPane2.setOneTouchExpandable(true);
jSplitPane2.setResizeWeight(0.9);
jSplitPane2.setMinimumSize(new Dimension(0, 0));
jSplitPane3.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane3.setBorder(BorderFactory.createLineBorder(Color.black));
jSplitPane3.setDoubleBuffered(true);
jSplitPane3.setContinuousLayout(true);
jSplitPane3.setDividerSize(8);
jSplitPane3.setOneTouchExpandable(true);
jSplitPane3.setResizeWeight(0.1);
jSplitPane3.setMinimumSize(new Dimension(0, 0));
contentPane.add(statusBar, BorderLayout.SOUTH);
contentPane.add(jSplitPane1, BorderLayout.CENTER);
jSplitPane1.add(jSplitPane2, JSplitPane.RIGHT);
jSplitPane2.add(commandPanel, JSplitPane.BOTTOM);
jSplitPane2.add(visualPanel, JSplitPane.TOP);
jSplitPane1.add(jSplitPane3, JSplitPane.LEFT);
jSplitPane3.add(selectionPanel, JSplitPane.BOTTOM);
jSplitPane3.add(projectPanel, JSplitPane.LEFT);
contentPane.add(jToolBar, BorderLayout.NORTH);
jSplitPane1.setDividerLocation(230);
jSplitPane2.setDividerLocation((int) (guiHeight * 0.60));
jSplitPane3.setDividerLocation((int) (guiHeight * 0.35));
visualPanel.setComponentProvider(new ComponentProvider(VISUAL_AREA));
commandPanel.setComponentProvider(new ComponentProvider(COMMAND_AREA));
selectionPanel.setComponentProvider(new ComponentProvider(SELECTION_AREA));
projectPanel.setComponentProvider(new ComponentProvider(PROJECT_AREA));
final String CANCEL_DIALOG = "cancel-dialog";
contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), CANCEL_DIALOG);
contentPane.getActionMap().put(CANCEL_DIALOG, new AbstractAction() {
private static final long serialVersionUID = 6732252343409902879L;
public void actionPerformed(ActionEvent event) {
chooseComponent();
}
});// contentPane.addKeyListener(new KeyAdapter() {
final String RCM_DIALOG = "rcm-dialog";
contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0), RCM_DIALOG);
contentPane.getActionMap().put(RCM_DIALOG, new AbstractAction() {
private static final long serialVersionUID = 3053589598512384113L;
public void actionPerformed(ActionEvent event) {
loadRCM();
}
});
}
private static class DialogResult {
public boolean cancelled = false;
}
void loadRCM(){
ComponentConfigurationManagerWindow2.load();
}
@SuppressWarnings("unchecked")
void chooseComponent() {
if (acceptors == null) {
// Get all appropriate acceptors
acceptors = new HashSet<Class>();
}
// 1) Get all visual components
ComponentRegistry registry = ComponentRegistry.getRegistry();
VisualPlugin[] plugins = registry.getModules(VisualPlugin.class);
ArrayList<String> availablePlugins = new ArrayList<String>();
for (int i = 0; i < plugins.length; i++) {
String name = registry.getDescriptorForPlugin(plugins[i]).getLabel();
for (Class type: acceptors) {
if (registry.getDescriptorForPluginClass(type).getLabel().equals(name)) {
availablePlugins.add(name);
break;
}
}
}
final String[] names = availablePlugins.toArray(new String[0]);
// 2) Sort alphabetically
Arrays.sort(names);
// 3) Create dialog with JAutoText (prefix mode)
DefaultListModel model = new DefaultListModel();
for (int i = 0; i < names.length; i++) {
model.addElement(names[i]);
}
final JDialog dialog = new JDialog();
final DialogResult dialogResult = new DialogResult();
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dialogResult.cancelled = true;
}
});
final JAutoList autoList = new JAutoList(model) {
private static final long serialVersionUID = -5117126504179347748L;
protected void keyPressed(KeyEvent event) {
if (event.getKeyChar() == '\n') {
if (getHighlightedIndex() == -1 ){
return;
}
dialogResult.cancelled = false;
dialog.dispose();
} else if (event.getKeyChar() == 0x1b) {
dialogResult.cancelled = true;
dialog.dispose();
} else {
super.keyPressed(event);
}
}
protected void elementDoubleClicked(int index, MouseEvent e) {
dialogResult.cancelled = false;
dialog.dispose();
}
};
autoList.setPrefixMode(true);
dialog.setTitle("Component");
dialog.getContentPane().add(autoList);
dialog.setModal(true);
dialog.pack();
dialog.setSize(200, 300);
Dimension size = dialog.getSize();
Dimension frameSize = getSize();
int x = getLocationOnScreen().x + (frameSize.width - size.width) / 2;
int y = getLocationOnScreen().y + (frameSize.height - size.height) / 2;
// 5) Display and get result
dialog.setBounds(x, y, size.width, size.height);
dialog.setVisible(true);
if (!dialogResult.cancelled) {
int index = autoList.getHighlightedIndex();
boolean found = false;
for (String key : areas.keySet()) {
if (areas.get(key) instanceof DefaultDockingPort) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(key);
if (port.getDockedComponent() instanceof JTabbedPane) {
JTabbedPane pane = (JTabbedPane) port.getDockedComponent();
int n = pane.getTabCount();
for (int i = 0; i < n; i++) {
String title = pane.getTitleAt(i);
if (title.equals(names[index])) {
pane.setSelectedIndex(i);
pane.getComponentAt(i).requestFocus();
found = true;
break;
}
}
if (found) {
break;
}
}
}
}
}
}
/**
* Associates Visual Areas with Component Holders
*/
protected void registerAreas() {
// areas.put(TOOL_AREA, jToolBar); // this is not used any more
areas.put(VISUAL_AREA, visualPanel);
areas.put(COMMAND_AREA, commandPanel);
areas.put(SELECTION_AREA, selectionPanel);
areas.put(PROJECT_AREA, projectPanel);
}
// Is this used?
public void addToContainer(String areaName, Component visualPlugin) {
DockableImpl wrapper = new DockableImpl(visualPlugin, visualPlugin.getName());
DockingManager.registerDockable(wrapper);
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
port.dock(wrapper, DockingPort.CENTER_REGION);
visualRegistry.put(visualPlugin, areaName);
}
/**
* Removes the designated <code>visualPlugin</code> from the GUI.
*
* @param visualPlugin component to be removed
*/
public void remove(Component visualPluginComponent) {
mainComponentClass.remove(visualPluginComponent);
visualRegistry.remove(visualPluginComponent);
}
public String getVisualArea(Component visualPlugin) {
return (String) visualRegistry.get(visualPlugin);
}
@SuppressWarnings("unchecked")
@Override
public void addToContainer(String areaName, Component visualPlugin, String pluginName, Class mainPluginClass) {
visualPlugin.setName(pluginName);
DockableImpl wrapper = new DockableImpl(visualPlugin, pluginName);
DockingManager.registerDockable(wrapper);
if (!areaName.equals(GUIFramework.VISUAL_AREA) && !areaName.equals(GUIFramework.COMMAND_AREA)) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
port.dock(wrapper, DockingPort.CENTER_REGION);
} else {
log.debug("Plugin wanting to go to visual or command area: " + pluginName);
}
visualRegistry.put(visualPlugin, areaName);
mainComponentClass.put(visualPlugin, mainPluginClass);
}
private void dockingFinished(DockableImpl comp) {
for (String area: areas.keySet()) {
Component port = (Component) areas.get(area);
Component container = comp.getDockable().getParent();
if (container instanceof JTabbedPane || container instanceof JSplitPane) {
if (container.getParent() == port) {
eventSink.throwEvent(comp.getPlugin(), area);
}
} else if (container instanceof DefaultDockingPort) {
if (container == port)
eventSink.throwEvent(comp.getPlugin(), area);
}
}
}
private class DockableImpl extends DockableAdapter {
private JPanel wrapper = null;
private JLabel initiator = null;
private String description = null;
private Component plugin = null;
private JPanel buttons = new JPanel();
private JPanel topBar = new JPanel();
private JButton docker = new JButton();
private boolean docked = true;
private ImageIcon dock_grey = new ImageIcon(Skin.class.getResource("dock_grey.gif"));
private ImageIcon dock = new ImageIcon(Skin.class.getResource("dock.gif"));
private ImageIcon dock_active = new ImageIcon(Skin.class.getResource("dock_active.gif"));
private ImageIcon undock_grey = new ImageIcon(Skin.class.getResource("undock_grey.gif"));
private ImageIcon undock = new ImageIcon(Skin.class.getResource("undock.gif"));
private ImageIcon undock_active = new ImageIcon(Skin.class.getResource("undock_active.gif"));
DockableImpl(Component plugin, String desc) {
this.plugin = plugin;
wrapper = new JPanel();
docker.setPreferredSize(new Dimension(16, 16));
docker.setBorderPainted(false);
docker.setIcon(undock_grey);
docker.setRolloverEnabled(true);
docker.setRolloverIcon(undock);
docker.setPressedIcon(undock_active);
docker.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
docker_actionPerformed(e);
}
});
buttons.setLayout(new GridLayout(1, 3));
buttons.add(docker);
initiator = new JLabel(" ");
initiator.setForeground(Color.darkGray);
initiator.setBackground(Color.getHSBColor(0.0f, 0.0f, 0.6f));
initiator.setOpaque(true);
initiator.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
setMoveCursor(me);
}
public void mouseExited(MouseEvent me) {
setDefaultCursor(me);
}
});
topBar.setLayout(new BorderLayout());
topBar.add(initiator, BorderLayout.CENTER);
topBar.add(buttons, BorderLayout.EAST);
wrapper.setLayout(new BorderLayout());
wrapper.add(topBar, BorderLayout.NORTH);
wrapper.add(plugin, BorderLayout.CENTER);
description = desc;
}
private JFrame frame = null;
private void docker_actionPerformed(ActionEvent e) {
log.debug("Action performed.");
String areaName = getVisualArea(this.getPlugin());
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
if (docked) {
undock(port);
return;
} else {
redock(port);
}
}
public void undock(final DefaultDockingPort port) {
log.debug("Undocking.");
port.undock(wrapper);
port.reevaluateContainerTree();
port.revalidate();
port.repaint();
docker.setIcon(dock_grey);
docker.setRolloverIcon(dock);
docker.setPressedIcon(dock_active);
docker.setSelected(false);
docker.repaint();
frame = new JFrame(description);
frame.setUndecorated(false);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
redock(port);
}
});
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(wrapper, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.repaint();
docked = false;
return;
}
public void redock(DefaultDockingPort port) {
if (frame != null) {
log.debug("Redocking " + plugin);
docker.setIcon(undock_grey);
docker.setRolloverIcon(undock);
docker.setPressedIcon(undock_active);
docker.setSelected(false);
port.dock(this, DockingPort.CENTER_REGION);
port.reevaluateContainerTree();
port.revalidate();
docked = true;
frame.getContentPane().remove(wrapper);
frame.dispose();
}
}
private void setMoveCursor(MouseEvent me) {
initiator.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
private void setDefaultCursor(MouseEvent me) {
initiator.setCursor(Cursor.getDefaultCursor());
}
public Component getDockable() {
return wrapper;
}
public String getDockableDesc() {
return description;
}
public Component getInitiator() {
return initiator;
}
public Component getPlugin() {
return plugin;
}
public void dockingCompleted() {
dockingFinished(this);
}
}
private class ComponentProvider extends ComponentProviderAdapter {
private String area;
public ComponentProvider(String area) {
this.area = area;
}
// Add change listeners to appropriate areas so
public JTabbedPane createTabbedPane() {
final JTabbedPane pane = new JTabbedPane();
if (area.equals(VISUAL_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, visualLastSelected));
} else if (area.equals(COMMAND_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, commandLastSelected));
} else if (area.equals(SELECTION_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, selectionLastSelected));
}
return pane;
}
}
private class TabChangeListener implements ChangeListener {
private final JTabbedPane pane;
private final ReferenceMap<DSDataSet<? extends DSBioObject>, String> lastSelected;
public TabChangeListener(JTabbedPane pane, ReferenceMap<DSDataSet<? extends DSBioObject>, String> lastSelected) {
this.pane = pane;
this.lastSelected = lastSelected;
}
public void stateChanged(ChangeEvent e) {
if ((currentDataSet != null) && !tabSwappingMode) {
int index = pane.getSelectedIndex();
if(index>=0) {
lastSelected.put(currentDataSet, pane.getTitleAt(index));
}
}
}
}
private class DockingNotifier extends EventSource {
public void throwEvent(Component source, String region) {
try {
throwEvent(ComponentDockingListener.class, "dockingAreaChanged", new ComponentDockingEvent(this, source, region));
} catch (AppEventListenerException aele) {
aele.printStackTrace();
}
}
}
@SuppressWarnings("unchecked")
public void setVisualizationType(DSDataSet type) {
currentDataSet = type;
// These are default acceptors
acceptors = ComponentRegistry.getRegistry().getAcceptors(null);
if (type != null) {
acceptors.addAll(ComponentRegistry.getRegistry().getAcceptors(type.getClass()));
}
if (type == null) {
log.trace("Default acceptors found:");
} else {
log.trace("Found the following acceptors for type " + type.getClass());
}
// Set up Visual Area
tabSwappingMode = true;
addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables);
selectLastComponent(GUIFramework.VISUAL_AREA, visualLastSelected.get(type));
addAppropriateComponents(acceptors, GUIFramework.COMMAND_AREA, commandDockables);
selectLastComponent(GUIFramework.COMMAND_AREA, commandLastSelected.get(type));
selectLastComponent(GUIFramework.SELECTION_AREA, selectionLastSelected.get(type));
addAppropriateComponents(acceptors, GUIFramework.SELECTION_AREA, selectorDockables);
tabSwappingMode = false;
contentPane.revalidate();
contentPane.repaint();
}
@SuppressWarnings("unchecked")
private void addAppropriateComponents(Set<Class> acceptors, String screenRegion, ArrayList<DockableImpl> dockables) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion);
for (DockableImpl dockable : dockables) {
dockable.redock(port);
}
dockables.clear();
port.removeAll();
SortedMap<Integer, Component> tabsToAdd = new TreeMap<Integer, Component>();
for (Component component : visualRegistry.keySet()) {
if (visualRegistry.get(component).equals(screenRegion)) {
Class<?> mainclass = mainComponentClass.get(component);
if (acceptors.contains(mainclass)) {
log.trace("Found component in "+screenRegion+" to show: " + mainclass.toString());
PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainclass);
tabsToAdd.put(desc.getPreferredOrder(), component);
}
}
}
for (Integer tabIndex : tabsToAdd.keySet()) {
PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainComponentClass.get(tabsToAdd.get(tabIndex)));
Component component = tabsToAdd.get(tabIndex);
DockableImpl dockable = new DockableImpl(component, desc.getLabel());
dockables.add(dockable);
port.dock(dockable, DockingPort.CENTER_REGION);
}
port.invalidate();
}
private void selectLastComponent(String screenRegion, String selected) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion);
if (selected != null) {
Component docked = port.getDockedComponent();
if (docked instanceof JTabbedPane) {
JTabbedPane pane = (JTabbedPane) docked;
int n = pane.getTabCount();
for (int i = 0; i < n; i++) {
if (selected.equals(pane.getTitleAt(i))) {
pane.setSelectedIndex(i);
break;
}
}
}
}
}
public void resetSelectorTabOrder() {
selectLastComponent(GUIFramework.SELECTION_AREA, "Markers");
}
public void initWelcomeScreen() {
PropertiesManager pm = PropertiesManager.getInstance();
try {
String showWelcomeScreen = pm.getProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION, YES);
if(showWelcomeScreen.equalsIgnoreCase(YES)) {
showWelcomeScreen();
} else {
hideWelcomeScreen();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public void showWelcomeScreen() {
// TODO Does register needs a public method for add a acceptor?
HashMap<Class, List<Class>> acceptorsNew = ComponentRegistry.getRegistry()
.getAcceptorsHashMap();
List<Class> list = acceptorsNew.get(null);
Class welcomeScreenClass;
try {
welcomeScreenClass = Class.forName("org.geworkbench.engine.WelcomeScreen");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
return;
}
list.add(welcomeScreenClass);
acceptorsNew.put(null, list);
ComponentRegistry.getRegistry().setAcceptorsHashMap(acceptorsNew);
if(acceptors==null)
acceptors = ComponentRegistry.getRegistry().getAcceptors(null);
acceptors.add(welcomeScreenClass);
addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables);
contentPane.revalidate();
PropertiesManager pm = PropertiesManager.getInstance();
try {
pm.setProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION,
YES);
} catch (IOException e) {
e.printStackTrace();
}
GeawConfigObject.enableWelcomeScreenMenu(false);
}
@SuppressWarnings("unchecked")
public void hideWelcomeScreen() {
if(acceptors==null)
acceptors = ComponentRegistry.getRegistry().getAcceptors(null);
// TODO register needs a public method for remove a acceptor
HashMap<Class, List<Class>> acceptorsNew = ComponentRegistry
.getRegistry().getAcceptorsHashMap();
List<Class> componentList = acceptorsNew.get(null);
for (Class<?> componentClass : componentList) {
String componentClassName = componentClass.getName();
if ( componentClassName
.equals("org.geworkbench.engine.WelcomeScreen") ) {
componentList.remove(componentClass);
acceptors.remove(componentClass);
break;
}
}
acceptorsNew.put(null, componentList);
ComponentRegistry.getRegistry().setAcceptorsHashMap(acceptorsNew);
addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables);
contentPane.revalidate();
contentPane.repaint();
PropertiesManager pm = PropertiesManager.getInstance();
try {
pm.setProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION,
NO);
} catch (IOException e) {
e.printStackTrace();
}
GeawConfigObject.enableWelcomeScreenMenu(true);
}
private static final String WELCOME_SCREEN_KEY = "Welcome Screen ";
private static final String VERSION = System.getProperty("application.version");
}
| private void jbInit() throws Exception {
contentPane = (JPanel) this.getContentPane();
this.setIconImage(Icons.MICROARRAYS_ICON.getImage());
contentPane.setLayout(borderLayout1);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int guiHeight = 0;
int guiWidth = 0;
boolean foundSize = false;
File sizeFile = new File(FilePathnameUtils.getTemporaryFilesDirectoryPath() + APP_SIZE_FILE);
if (sizeFile.exists()) {
try {
BufferedReader in = new BufferedReader(new FileReader(sizeFile));
guiWidth = Integer.parseInt(in.readLine());
guiHeight = Integer.parseInt(in.readLine());
int guiX = Integer.parseInt(in.readLine());
int guiY = Integer.parseInt(in.readLine());
setLocation(guiX, guiY);
foundSize = true;
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (!foundSize) {
guiWidth = (int) (dim.getWidth() * 0.9);
guiHeight = (int) (dim.getHeight() * 0.9);
this.setLocation((dim.width - guiWidth) / 2, (dim.height - guiHeight) / 2);
}
setSize(new Dimension(guiWidth, guiHeight));
setApplicationTitle();
statusBar.setText(" ");
jSplitPane1.setBorder(BorderFactory.createLineBorder(Color.black));
jSplitPane1.setDoubleBuffered(true);
jSplitPane1.setContinuousLayout(true);
jSplitPane1.setBackground(Color.black);
jSplitPane1.setDividerSize(8);
jSplitPane1.setOneTouchExpandable(true);
jSplitPane1.setResizeWeight(0);
jSplitPane2.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane2.setDoubleBuffered(true);
jSplitPane2.setContinuousLayout(true);
jSplitPane2.setDividerSize(8);
jSplitPane2.setOneTouchExpandable(true);
jSplitPane2.setResizeWeight(0.9);
jSplitPane2.setMinimumSize(new Dimension(0, 0));
jSplitPane3.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane3.setBorder(BorderFactory.createLineBorder(Color.black));
jSplitPane3.setDoubleBuffered(true);
jSplitPane3.setContinuousLayout(true);
jSplitPane3.setDividerSize(8);
jSplitPane3.setOneTouchExpandable(true);
jSplitPane3.setResizeWeight(0.1);
jSplitPane3.setMinimumSize(new Dimension(0, 0));
contentPane.add(statusBar, BorderLayout.SOUTH);
contentPane.add(jSplitPane1, BorderLayout.CENTER);
jSplitPane1.add(jSplitPane2, JSplitPane.RIGHT);
jSplitPane2.add(commandPanel, JSplitPane.BOTTOM);
jSplitPane2.add(visualPanel, JSplitPane.TOP);
jSplitPane1.add(jSplitPane3, JSplitPane.LEFT);
jSplitPane3.add(selectionPanel, JSplitPane.BOTTOM);
jSplitPane3.add(projectPanel, JSplitPane.LEFT);
contentPane.add(jToolBar, BorderLayout.NORTH);
jSplitPane1.setDividerLocation(230);
jSplitPane2.setDividerLocation((int) (guiHeight * 0.60));
jSplitPane3.setDividerLocation((int) (guiHeight * 0.35));
visualPanel.setComponentProvider(new ComponentProvider(VISUAL_AREA));
commandPanel.setComponentProvider(new ComponentProvider(COMMAND_AREA));
selectionPanel.setComponentProvider(new ComponentProvider(SELECTION_AREA));
projectPanel.setComponentProvider(new ComponentProvider(PROJECT_AREA));
final String CANCEL_DIALOG = "cancel-dialog";
contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), CANCEL_DIALOG);
contentPane.getActionMap().put(CANCEL_DIALOG, new AbstractAction() {
private static final long serialVersionUID = 6732252343409902879L;
public void actionPerformed(ActionEvent event) {
chooseComponent();
}
});// contentPane.addKeyListener(new KeyAdapter() {
final String RCM_DIALOG = "rcm-dialog";
contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0), RCM_DIALOG);
contentPane.getActionMap().put(RCM_DIALOG, new AbstractAction() {
private static final long serialVersionUID = 3053589598512384113L;
public void actionPerformed(ActionEvent event) {
loadRCM();
}
});
}
private static class DialogResult {
public boolean cancelled = false;
}
void loadRCM(){
ComponentConfigurationManagerWindow2.load();
}
@SuppressWarnings("unchecked")
void chooseComponent() {
if (acceptors == null) {
// Get all appropriate acceptors
acceptors = new HashSet<Class>();
}
// 1) Get all visual components
ComponentRegistry registry = ComponentRegistry.getRegistry();
VisualPlugin[] plugins = registry.getModules(VisualPlugin.class);
ArrayList<String> availablePlugins = new ArrayList<String>();
for (int i = 0; i < plugins.length; i++) {
String name = registry.getDescriptorForPlugin(plugins[i]).getLabel();
for (Class type: acceptors) {
if (registry.getDescriptorForPluginClass(type).getLabel().equals(name)) {
availablePlugins.add(name);
break;
}
}
}
final String[] names = availablePlugins.toArray(new String[0]);
// 2) Sort alphabetically
Arrays.sort(names);
// 3) Create dialog with JAutoText (prefix mode)
DefaultListModel model = new DefaultListModel();
for (int i = 0; i < names.length; i++) {
model.addElement(names[i]);
}
final JDialog dialog = new JDialog();
final DialogResult dialogResult = new DialogResult();
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dialogResult.cancelled = true;
}
});
final JAutoList autoList = new JAutoList(model) {
private static final long serialVersionUID = -5117126504179347748L;
protected void keyPressed(KeyEvent event) {
if (event.getKeyChar() == '\n') {
if (getHighlightedIndex() == -1 ){
return;
}
dialogResult.cancelled = false;
dialog.dispose();
} else if (event.getKeyChar() == 0x1b) {
dialogResult.cancelled = true;
dialog.dispose();
} else {
super.keyPressed(event);
}
}
protected void elementDoubleClicked(int index, MouseEvent e) {
dialogResult.cancelled = false;
dialog.dispose();
}
};
autoList.setPrefixMode(true);
dialog.setTitle("Component");
dialog.getContentPane().add(autoList);
dialog.setModal(true);
dialog.pack();
dialog.setSize(200, 300);
Dimension size = dialog.getSize();
Dimension frameSize = getSize();
int x = getLocationOnScreen().x + (frameSize.width - size.width) / 2;
int y = getLocationOnScreen().y + (frameSize.height - size.height) / 2;
// 5) Display and get result
dialog.setBounds(x, y, size.width, size.height);
dialog.setVisible(true);
if (!dialogResult.cancelled) {
int index = autoList.getHighlightedIndex();
boolean found = false;
for (String key : areas.keySet()) {
if (areas.get(key) instanceof DefaultDockingPort) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(key);
if (port.getDockedComponent() instanceof JTabbedPane) {
JTabbedPane pane = (JTabbedPane) port.getDockedComponent();
int n = pane.getTabCount();
for (int i = 0; i < n; i++) {
String title = pane.getTitleAt(i);
if (title.equals(names[index])) {
pane.setSelectedIndex(i);
pane.getComponentAt(i).requestFocus();
found = true;
break;
}
}
if (found) {
break;
}
}
}
}
}
}
/**
* Associates Visual Areas with Component Holders
*/
protected void registerAreas() {
// areas.put(TOOL_AREA, jToolBar); // this is not used any more
areas.put(VISUAL_AREA, visualPanel);
areas.put(COMMAND_AREA, commandPanel);
areas.put(SELECTION_AREA, selectionPanel);
areas.put(PROJECT_AREA, projectPanel);
}
// Is this used?
public void addToContainer(String areaName, Component visualPlugin) {
DockableImpl wrapper = new DockableImpl(visualPlugin, visualPlugin.getName());
DockingManager.registerDockable(wrapper);
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
port.dock(wrapper, DockingPort.CENTER_REGION);
visualRegistry.put(visualPlugin, areaName);
}
/**
* Removes the designated <code>visualPlugin</code> from the GUI.
*
* @param visualPlugin component to be removed
*/
public void remove(Component visualPluginComponent) {
mainComponentClass.remove(visualPluginComponent);
visualRegistry.remove(visualPluginComponent);
}
public String getVisualArea(Component visualPlugin) {
return (String) visualRegistry.get(visualPlugin);
}
@SuppressWarnings("unchecked")
@Override
public void addToContainer(String areaName, Component visualPlugin, String pluginName, Class mainPluginClass) {
visualPlugin.setName(pluginName);
DockableImpl wrapper = new DockableImpl(visualPlugin, pluginName);
DockingManager.registerDockable(wrapper);
if (!areaName.equals(GUIFramework.VISUAL_AREA) && !areaName.equals(GUIFramework.COMMAND_AREA)) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
port.dock(wrapper, DockingPort.CENTER_REGION);
} else {
log.debug("Plugin wanting to go to visual or command area: " + pluginName);
}
visualRegistry.put(visualPlugin, areaName);
mainComponentClass.put(visualPlugin, mainPluginClass);
}
private void dockingFinished(DockableImpl comp) {
for (String area: areas.keySet()) {
Component port = (Component) areas.get(area);
Component container = comp.getDockable().getParent();
if (container instanceof JTabbedPane || container instanceof JSplitPane) {
if (container.getParent() == port) {
eventSink.throwEvent(comp.getPlugin(), area);
}
} else if (container instanceof DefaultDockingPort) {
if (container == port)
eventSink.throwEvent(comp.getPlugin(), area);
}
}
}
private class DockableImpl extends DockableAdapter {
private JPanel wrapper = null;
private JLabel initiator = null;
private String description = null;
private Component plugin = null;
private JPanel buttons = new JPanel();
private JPanel topBar = new JPanel();
private JButton docker = new JButton();
private boolean docked = true;
private ImageIcon dock_grey = new ImageIcon(Skin.class.getResource("dock_grey.gif"));
private ImageIcon dock = new ImageIcon(Skin.class.getResource("dock.gif"));
private ImageIcon dock_active = new ImageIcon(Skin.class.getResource("dock_active.gif"));
private ImageIcon undock_grey = new ImageIcon(Skin.class.getResource("undock_grey.gif"));
private ImageIcon undock = new ImageIcon(Skin.class.getResource("undock.gif"));
private ImageIcon undock_active = new ImageIcon(Skin.class.getResource("undock_active.gif"));
DockableImpl(Component plugin, String desc) {
this.plugin = plugin;
wrapper = new JPanel();
docker.setPreferredSize(new Dimension(16, 16));
docker.setBorderPainted(false);
docker.setIcon(undock_grey);
docker.setRolloverEnabled(true);
docker.setRolloverIcon(undock);
docker.setPressedIcon(undock_active);
docker.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
docker_actionPerformed(e);
}
});
buttons.setLayout(new GridLayout(1, 3));
buttons.add(docker);
initiator = new JLabel(" ");
initiator.setForeground(Color.darkGray);
initiator.setBackground(Color.getHSBColor(0.0f, 0.0f, 0.6f));
initiator.setOpaque(true);
initiator.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
setMoveCursor(me);
}
public void mouseExited(MouseEvent me) {
setDefaultCursor(me);
}
});
topBar.setLayout(new BorderLayout());
topBar.add(initiator, BorderLayout.CENTER);
topBar.add(buttons, BorderLayout.EAST);
wrapper.setLayout(new BorderLayout());
wrapper.add(topBar, BorderLayout.NORTH);
wrapper.add(plugin, BorderLayout.CENTER);
description = desc;
}
private JFrame frame = null;
private void docker_actionPerformed(ActionEvent e) {
log.debug("Action performed.");
String areaName = getVisualArea(this.getPlugin());
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
if (docked) {
undock(port);
return;
} else {
redock(port);
}
}
public void undock(final DefaultDockingPort port) {
log.debug("Undocking.");
port.undock(wrapper);
port.reevaluateContainerTree();
port.revalidate();
port.repaint();
docker.setIcon(dock_grey);
docker.setRolloverIcon(dock);
docker.setPressedIcon(dock_active);
docker.setSelected(false);
docker.repaint();
frame = new JFrame(description);
frame.setUndecorated(false);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
redock(port);
}
});
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(wrapper, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.repaint();
docked = false;
return;
}
public void redock(DefaultDockingPort port) {
if (frame != null) {
log.debug("Redocking " + plugin);
docker.setIcon(undock_grey);
docker.setRolloverIcon(undock);
docker.setPressedIcon(undock_active);
docker.setSelected(false);
port.dock(this, DockingPort.CENTER_REGION);
port.reevaluateContainerTree();
port.revalidate();
docked = true;
frame.getContentPane().remove(wrapper);
frame.dispose();
}
}
private void setMoveCursor(MouseEvent me) {
initiator.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
private void setDefaultCursor(MouseEvent me) {
initiator.setCursor(Cursor.getDefaultCursor());
}
public Component getDockable() {
return wrapper;
}
public String getDockableDesc() {
return description;
}
public Component getInitiator() {
return initiator;
}
public Component getPlugin() {
return plugin;
}
public void dockingCompleted() {
dockingFinished(this);
}
}
private class ComponentProvider extends ComponentProviderAdapter {
private String area;
public ComponentProvider(String area) {
this.area = area;
}
// Add change listeners to appropriate areas so
public JTabbedPane createTabbedPane() {
final JTabbedPane pane = new JTabbedPane();
if (area.equals(VISUAL_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, visualLastSelected));
} else if (area.equals(COMMAND_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, commandLastSelected));
} else if (area.equals(SELECTION_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, selectionLastSelected));
}
return pane;
}
}
private class TabChangeListener implements ChangeListener {
private final JTabbedPane pane;
private final ReferenceMap<DSDataSet<? extends DSBioObject>, String> lastSelected;
public TabChangeListener(JTabbedPane pane, ReferenceMap<DSDataSet<? extends DSBioObject>, String> lastSelected) {
this.pane = pane;
this.lastSelected = lastSelected;
}
public void stateChanged(ChangeEvent e) {
if ((currentDataSet != null) && !tabSwappingMode) {
int index = pane.getSelectedIndex();
if(index>=0) {
lastSelected.put(currentDataSet, pane.getTitleAt(index));
}
}
}
}
private class DockingNotifier extends EventSource {
public void throwEvent(Component source, String region) {
try {
throwEvent(ComponentDockingListener.class, "dockingAreaChanged", new ComponentDockingEvent(this, source, region));
} catch (AppEventListenerException aele) {
aele.printStackTrace();
}
}
}
@SuppressWarnings("unchecked")
public void setVisualizationType(DSDataSet type) {
currentDataSet = type;
// These are default acceptors
acceptors = ComponentRegistry.getRegistry().getAcceptors(null);
if (type != null) {
acceptors.addAll(ComponentRegistry.getRegistry().getAcceptors(type.getClass()));
}
if (type == null) {
log.trace("Default acceptors found:");
} else {
log.trace("Found the following acceptors for type " + type.getClass());
}
// Set up Visual Area
tabSwappingMode = true;
addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables);
selectLastComponent(GUIFramework.VISUAL_AREA, visualLastSelected.get(type));
addAppropriateComponents(acceptors, GUIFramework.COMMAND_AREA, commandDockables);
selectLastComponent(GUIFramework.COMMAND_AREA, commandLastSelected.get(type));
selectLastComponent(GUIFramework.SELECTION_AREA, selectionLastSelected.get(type));
addAppropriateComponents(acceptors, GUIFramework.SELECTION_AREA, selectorDockables);
tabSwappingMode = false;
contentPane.revalidate();
contentPane.repaint();
}
@SuppressWarnings("unchecked")
private void addAppropriateComponents(Set<Class> acceptors, String screenRegion, ArrayList<DockableImpl> dockables) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion);
for (DockableImpl dockable : dockables) {
dockable.redock(port);
}
dockables.clear();
port.removeAll();
SortedMap<Integer, Component> tabsToAdd = new TreeMap<Integer, Component>();
for (Component component : visualRegistry.keySet()) {
if (visualRegistry.get(component).equals(screenRegion)) {
Class<?> mainclass = mainComponentClass.get(component);
if (acceptors.contains(mainclass)) {
log.trace("Found component in "+screenRegion+" to show: " + mainclass.toString());
PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainclass);
tabsToAdd.put(desc.getPreferredOrder(), component);
}
}
}
for (Integer tabIndex : tabsToAdd.keySet()) {
PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainComponentClass.get(tabsToAdd.get(tabIndex)));
Component component = tabsToAdd.get(tabIndex);
DockableImpl dockable = new DockableImpl(component, desc.getLabel());
dockables.add(dockable);
port.dock(dockable, DockingPort.CENTER_REGION);
}
port.invalidate();
}
private void selectLastComponent(String screenRegion, String selected) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion);
if (selected != null) {
Component docked = port.getDockedComponent();
if (docked instanceof JTabbedPane) {
JTabbedPane pane = (JTabbedPane) docked;
int n = pane.getTabCount();
for (int i = 0; i < n; i++) {
if (selected.equals(pane.getTitleAt(i))) {
pane.setSelectedIndex(i);
break;
}
}
}
}
}
public void resetSelectorTabOrder() {
selectLastComponent(GUIFramework.SELECTION_AREA, "Markers");
}
public void initWelcomeScreen() {
PropertiesManager pm = PropertiesManager.getInstance();
try {
String showWelcomeScreen = pm.getProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION, YES);
if(showWelcomeScreen.equalsIgnoreCase(YES)) {
showWelcomeScreen();
} else {
hideWelcomeScreen();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public void showWelcomeScreen() {
// TODO Does register needs a public method for add a acceptor?
HashMap<Class, List<Class>> acceptorsNew = ComponentRegistry.getRegistry()
.getAcceptorsHashMap();
List<Class> list = acceptorsNew.get(null);
Class welcomeScreenClass;
try {
welcomeScreenClass = Class.forName("org.geworkbench.engine.WelcomeScreen");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
return;
}
list.add(welcomeScreenClass);
acceptorsNew.put(null, list);
ComponentRegistry.getRegistry().setAcceptorsHashMap(acceptorsNew);
if(acceptors==null)
acceptors = ComponentRegistry.getRegistry().getAcceptors(null);
acceptors.add(welcomeScreenClass);
addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables);
contentPane.revalidate();
PropertiesManager pm = PropertiesManager.getInstance();
try {
pm.setProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION,
YES);
} catch (IOException e) {
e.printStackTrace();
}
GeawConfigObject.enableWelcomeScreenMenu(false);
}
@SuppressWarnings("unchecked")
public void hideWelcomeScreen() {
if(acceptors==null)
acceptors = ComponentRegistry.getRegistry().getAcceptors(null);
// TODO register needs a public method for remove a acceptor
HashMap<Class, List<Class>> acceptorsNew = ComponentRegistry
.getRegistry().getAcceptorsHashMap();
List<Class> componentList = acceptorsNew.get(null);
List<Class> newComponentList = new ArrayList<Class>();
for (Class<?> componentClass : componentList) {
String componentClassName = componentClass.getName();
if ( componentClassName
.equals("org.geworkbench.engine.WelcomeScreen") ) {
acceptors.remove(componentClass);
break;
} else {
newComponentList.add(componentClass);
}
}
acceptorsNew.put(null, newComponentList);
addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables);
contentPane.revalidate();
contentPane.repaint();
PropertiesManager pm = PropertiesManager.getInstance();
try {
pm.setProperty(this.getClass(), WELCOME_SCREEN_KEY+VERSION,
NO);
} catch (IOException e) {
e.printStackTrace();
}
GeawConfigObject.enableWelcomeScreenMenu(true);
}
private static final String WELCOME_SCREEN_KEY = "Welcome Screen ";
private static final String VERSION = System.getProperty("application.version");
}
|
diff --git a/Bending2/src/tools/ConfigManager.java b/Bending2/src/tools/ConfigManager.java
index db15f6f..8079cb2 100644
--- a/Bending2/src/tools/ConfigManager.java
+++ b/Bending2/src/tools/ConfigManager.java
@@ -1,567 +1,567 @@
package tools;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.MemoryConfiguration;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
public class ConfigManager {
public static boolean enabled = true;
public static boolean bendToItem = false;
public static boolean colors = true;
public static boolean compatibility = true;
public static int airdmg = 1;
public static int earthdmg = 7;
public static int waterdmg = 7;
public static Map<String, String> prefixes = new HashMap<String, String>();
public static Map<String, String> color = new HashMap<String, String>();
public static List<String> earthbendable = new ArrayList<String>();
public static Map<String, Boolean> useWeapon = new HashMap<String, Boolean>();
public static boolean useMySQL = false;
public static String dbHost = "localhost";
public static String dbUser = "root";
public static String dbPass = "";
public static String dbDB = "minecraft";
public static String dbPort = "3306";
public static double airBlastSpeed = 25;
public static double airBlastRange = 20;
public static double airBlastRadius = 2;
public static double airBlastPush = 1;
public static int airBubbleRadius = 7;
public static float airPassiveFactor = 0.3F;
public static double airShieldRadius = 7;
public static double airSuctionSpeed = 25;
public static double airSuctionRange = 20;
public static double airSuctionRadius = 2;
public static double airSuctionPush = 1;
public static double airSwipeRange = 16;
public static int airSwipeArc = 20;
public static double airSwipeSpeed = 25;
public static double airSwipeRadius = 2;
public static double airSwipePush = 1;
public static long airSwipeCooldown = 1000;
public static double airScooterSpeed = .675;
public static double tornadoRadius = 10;
public static double tornadoHeight = 25;
public static double tornadoRange = 25;
public static double tornadoMobPush = 1;
public static double tornadoPlayerPush = 1;
public static int catapultLength = 7;
public static double catapultSpeed = 12;
public static double catapultPush = 5;
public static double compactColumnRange = 20;
public static double compactColumnSpeed = 8;
public static double earthBlastRange = 20;
public static double earthBlastSpeed = 35;
public static int earthColumnHeight = 6;
public static double earthGrabRange = 15;
public static long earthPassive = 3000;
public static double earthTunnelMaxRadius = 1;
public static double earthTunnelRange = 10;
public static double earthTunnelRadius = 0.25;
public static long earthTunnelInterval = 30;
public static int earthWallRange = 15;
public static int earthWallHeight = 8;
public static int earthWallWidth = 6;
public static int collapseRange = 20;
public static double collapseRadius = 7;
public static long tremorsenseCooldown = 3000;
public static int tremorsenseMaxDepth;
public static int tremorsenseRadius;
public static byte tremorsenseLightThreshold;
public static int arcOfFireArc = 20;
public static int arcOfFireRange = 9;
public static int ringOfFireRange = 7;
public static double extinguishRange = 20;
public static double extinguishRadius = 20;
public static long fireballCooldown = 2000;
public static double fireballSpeed = 0.3;
public static double fireJetSpeed = 0.7;
public static long fireJetDuration = 1500;
public static long fireJetCooldown = 6000;
public static double fireStreamSpeed = 15;
public static double dayFactor = 1.3;
public static int illuminationRange = 5;
public static int heatMeltRange = 15;
public static int heatMeltRadius = 5;
public static int freezeMeltRange = 20;
public static int freezeMeltRadius = 5;
public static double healingWatersRadius = 5;
public static long healingWatersInterval = 750;
public static int plantbendingRange = 10;
public static double walkOnWaterRadius = 3.5;
public static double waterManipulationRange = 20;
public static double waterManipulationSpeed = 35;
public static int waterSpoutHeight = 15;
public static double waterWallRange = 5;
public static double waterWallRadius = 2;
public static double waveRadius = 3;
public static double waveHorizontalPush = 1;
public static double waveVerticalPush = 0.2;
public static long globalCooldown = 500;
public static double fastSwimmingFactor = 0.7;
public static double nightFactor = 1.5;
public static long chiblockduration = 2500;
public static double dodgechance = 25;
public static double punchmultiplier = 3;
public static double falldamagereduction = 50;
public static boolean reverseearthbending = true;
public static long revertchecktime = 300000;
private static List<String> defaultearthbendable = new ArrayList<String>();
public static long dissipateAfter = 400;
public void load(File file) {
FileConfiguration config = new YamlConfiguration();
try {
if (file.exists())
config.load(file);
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidConfigurationException e) {
e.printStackTrace();
}
config.setDefaults(getDefaults());
colors = config.getBoolean("Chat.Colors");
bendToItem = config.getBoolean("Bending.Option.Bend-To-Item");
airdmg = config.getInt("Bending.Damage.AirSwipe");
enabled = config.getBoolean("Chat.Enabled");
compatibility = config.getBoolean("Chat.Compatibility");
waterdmg = config.getInt("Bending.Damage.WaterManipulation");
earthdmg = config.getInt("Bending.Damage.EarthBlast");
prefixes.put("Air", config.getString("Chat.Prefix.Air"));
prefixes.put("Avatar", config.getString("Chat.Prefix.Avatar"));
prefixes.put("Fire", config.getString("Chat.Prefix.Fire"));
prefixes.put("Water", config.getString("Chat.Prefix.Water"));
prefixes.put("Earth", config.getString("Chat.Prefix.Earth"));
prefixes.put("ChiBlocker", config.getString("Chat.Prefix.ChiBlocker"));
color.put("Avatar", config.getString("Chat.Color.Avatar"));
color.put("Air", config.getString("Chat.Color.Air"));
color.put("Fire", config.getString("Chat.Color.Fire"));
color.put("Water", config.getString("Chat.Color.Water"));
color.put("Earth", config.getString("Chat.Color.Earth"));
color.put("ChiBlocker", config.getString("Chat.Color.ChiBlocker"));
earthbendable = config.getStringList("Bending.Option.EarthBendable");
useWeapon
.put("Air", config.getBoolean(
"Bending.Option.Bend-With-Weapon.Air", false));
useWeapon.put("Earth", config.getBoolean(
"Bending.Option.Bend-With-Weapon.Earth", false));
useWeapon.put("Fire", config.getBoolean(
"Bending.Option.Bend-With-Weapon.Fire", false));
useWeapon.put("Water", config.getBoolean(
"Bending.Option.Bend-With-Weapon.Water", false));
// MySQL
useMySQL = config.getBoolean("MySQL.Use-MySQL", false);
dbHost = config.getString("MySQL.MySQL-host",
"jdbc:mysql://localhost:3306");
dbUser = config.getString("MySQL.User", "root");
dbPass = config.getString("MySQL.Password", "");
dbDB = config.getString("MySQL.Database", "minecraft");
Integer dbPortint = (Integer) config.getInt("MySQL.MySQL-portnumber");
dbPort = dbPortint.toString();
useWeapon
.put("ChiBlocker",
config.getBoolean("Bending.Option.Bend-With-Weapon.ChiBlocker"));
// Earthbending revert
reverseearthbending = config
.getBoolean("Bending.Option.Reverse-Earthbending");
revertchecktime = config
.getLong("Bending.Option.Reverse-Earthbending-Check-Time");
chiblockduration = config
.getLong("Properties.ChiBlocker.ChiBlock-Duration");
dodgechance = config.getDouble("Properties.ChiBlocker.Dodge-Chance");
punchmultiplier = config
.getDouble("Properties.ChiBlocker.Punch-Multiplier");
falldamagereduction = config
.getDouble("Properties.ChiBlocker.Fall-Damage-Reduction");
dissipateAfter = config
- .getLong("Properties.Option.Firebending-Dissipate-Time");
+ .getLong("Bending.Option.Firebending-Dissipate-Time");
// PROPERTIES
globalCooldown = config.getLong("Properties.GlobalCooldown");
// AIR
// AirBlast
airBlastSpeed = config.getDouble("Properties.Air.AirBlast.Speed");
airBlastRange = config.getDouble("Properties.Air.AirBlast.Range");
airBlastRadius = config
.getDouble("Properties.Air.AirBlast.Affecting-Radius");
airBlastPush = config.getDouble("Properties.Air.AirBlast.Push-Factor");
// AirBubble
airBubbleRadius = config.getInt("Properties.Air.AirBubble.Radius");
// AirPassive
airPassiveFactor = (float) config
.getDouble("Properties.Air.Passive.Factor");
// AirShield
airShieldRadius = config.getDouble("Properties.Air.AirShield.Radius");
// AirSuction
airSuctionSpeed = config.getDouble("Properties.Air.AirSuction.Speed");
airSuctionRange = config.getDouble("Properties.Air.AirSuction.Range");
airSuctionRadius = config
.getDouble("Properties.Air.AirSuction.Affecting-Radius");
airSuctionPush = config
.getDouble("Properties.Air.AirSuction.Push-Factor");
// AirSwipe
airSwipeRange = config.getDouble("Properties.Air.AirSwipe.Range");
airSwipeArc = config.getInt("Properties.Air.AirSwipe.Arc");
airSwipeSpeed = config.getDouble("Properties.Air.AirSwipe.Speed");
airSwipeRadius = config
.getDouble("Properties.Air.AirSwipe.Affecting-Radius");
airSwipePush = config.getDouble("Properties.Air.AirSwipe.Push-Factor");
airSwipeCooldown = config.getLong("Properties.Air.AirSwipe.Cooldown");
// Tornado
tornadoRadius = config.getDouble("Properties.Air.Tornado.Radius");
tornadoHeight = config.getDouble("Properties.Air.Tornado.Height");
tornadoRange = config.getDouble("Properties.Air.Tornado.Range");
tornadoMobPush = config
.getDouble("Properties.Air.Tornado.Mob-Push-Factor");
tornadoPlayerPush = config
.getDouble("Properties.Air.Tornado.Player-Push-Factor");
// Air Scooter
airScooterSpeed = config.getDouble("Properties.Air.AirScooter.Speed");
// EARTH
// Catapult
catapultLength = config.getInt("Properties.Earth.Catapult.Length");
catapultSpeed = config.getDouble("Properties.Earth.Catapult.Speed");
catapultPush = config.getDouble("Properties.Earth.Catapult.Push");
// CompactColumn
compactColumnRange = config
.getDouble("Properties.Earth.CompactColumn.Range");
compactColumnSpeed = config
.getDouble("Properties.Earth.CompactColumn.Speed");
// EarthBlast
earthBlastRange = config.getDouble("Properties.Earth.EarthBlast.Range");
earthBlastSpeed = config.getDouble("Properties.Earth.EarthBlast.Speed");
// EarthColumn
earthColumnHeight = config
.getInt("Properties.Earth.EarthColumn.Height");
// EarthGrab
earthGrabRange = config.getDouble("Properties.Earth.EarthGrab.Range");
// EarthPassive
earthPassive = config
.getLong("Properties.Earth.EarthPassive.Wait-Before-Reverse-Changes");
// EarthTunnel
earthTunnelMaxRadius = config
.getDouble("Properties.Earth.EarthTunnel.Max-Radius");
earthTunnelRange = config
.getDouble("Properties.Earth.EarthTunnel.Range");
earthTunnelRadius = config
.getDouble("Properties.Earth.EarthTunnel.Radius");
earthTunnelInterval = config
.getLong("Properties.Earth.EarthTunnel.Interval");
// EarthWall
earthWallRange = config.getInt("Properties.Earth.EarthWall.Range");
earthWallHeight = config.getInt("Properties.Earth.EarthWall.Height");
earthWallWidth = config.getInt("Properties.Earth.EarthWall.Width");
// Collapse
collapseRange = config.getInt("Properties.Earth.Collapse.Range");
collapseRadius = config.getDouble("Properties.Earth.Collapse.Radius");
// Tremorsense
tremorsenseCooldown = config
.getLong("Properties.Earth.Tremorsense.Cooldown");
tremorsenseMaxDepth = config
.getInt("Properties.Earth.Tremorsense.Max-Depth");
tremorsenseRadius = config
.getInt("Properties.Earth.Tremorsense.Radius");
tremorsenseLightThreshold = (byte) config
.getInt("Properties.Earth.Tremorsense.Light-Threshold");
// FIRE
// ArcOfFire
arcOfFireArc = config.getInt("Properties.Fire.ArcOfFire.Arc");
arcOfFireRange = config.getInt("Properties.Fire.ArcOfFire.Range");
// RingOfFire
ringOfFireRange = config.getInt("Properties.Fire.RingOfFire.Range");
// Extinguish
extinguishRange = config.getDouble("Properties.Fire.Extinguish.Range");
extinguishRadius = config
.getDouble("Properties.Fire.Extinguish.Radius");
// Fireball
fireballCooldown = config.getLong("Properties.Fire.Fireball.Cooldown");
fireballSpeed = config.getDouble("Properties.Fire.Fireball.Speed");
// FireJet
fireJetSpeed = config.getDouble("Properties.Fire.FireJet.Speed");
fireJetDuration = config.getLong("Properties.Fire.FireJet.Duration");
fireJetCooldown = config.getLong("Properties.Fire.FireJet.CoolDown");
// FireStream
fireStreamSpeed = config.getDouble("Properties.Fire.FireStream.Speed");
// HeatMelt
heatMeltRange = config.getInt("Properties.Fire.HeatMelt.Range");
heatMeltRadius = config.getInt("Properties.Fire.HeatMelt.Radius");
// Illumination
illuminationRange = config.getInt("Properties.Fire.Illumination.Range");
// Day
dayFactor = config.getDouble("Properties.Fire.Day-Power-Factor");
// WATER
// FreezeMelt
freezeMeltRange = config.getInt("Properties.Water.FreezeMelt.Range");
freezeMeltRadius = config.getInt("Properties.Water.FreezeMelt.Radius");
// HealingWaters
healingWatersRadius = config
.getDouble("Properties.Water.HealingWaters.Radius");
healingWatersInterval = config
.getLong("Properties.Water.HealingWaters.Interval");
// Plantbending
plantbendingRange = config
.getInt("Properties.Water.Plantbending.Range");
// WalkOnWater
walkOnWaterRadius = config
.getDouble("Properties.Water.WalkOnWater.Radius");
// WaterManipulation
waterManipulationRange = config
.getDouble("Properties.Water.WaterManipulation.Range");
waterManipulationSpeed = config
.getDouble("Properties.Water.WaterManipulation.Speed");
// WaterSpout
waterSpoutHeight = config.getInt("Properties.Water.WaterSpout.Height");
// WaterWall
waterWallRange = config.getDouble("Properties.Water.WaterWall.Range");
waterWallRadius = config.getDouble("Properties.Water.WaterWall.Radius");
// Wave
waveRadius = config.getDouble("Properties.Water.Wave.Radius");
waveHorizontalPush = config
.getDouble("Properties.Water.Wave.Horizontal-Push-Force");
waveVerticalPush = config
.getDouble("Properties.Water.Wave.Vertical-Push-Force");
// Fast Swimming
fastSwimmingFactor = config
.getDouble("Properties.Water.FastSwimming.Factor");
// Night
nightFactor = config.getDouble("Properties.Water.Night-Power-Factor");
try {
config.options().copyDefaults(true);
config.save(file);
} catch (IOException e) {
e.printStackTrace();
}
}
private MemoryConfiguration getDefaults() {
MemoryConfiguration config = new MemoryConfiguration();
config.set("Chat.Enabled", Boolean.valueOf(true));
config.set("Chat.Colors", Boolean.valueOf(true));
config.set("Chat.Compatibility", Boolean.valueOf(false));
config.set("Chat.Prefix.Avatar", "[Avatar] ");
config.set("Chat.Prefix.Air", "[Airbender] ");
config.set("Chat.Prefix.Fire", "[Firebender] ");
config.set("Chat.Prefix.Water", "[Waterbender] ");
config.set("Chat.Prefix.Earth", "[Earthbender] ");
config.set("Chat.Prefix.ChiBlocker", "[ChiBlocker] ");
config.set("Bending.Damage.AirSwipe", Integer.valueOf(2));
config.set("Bending.Damage.EarthBlast", Integer.valueOf(7));
config.set("Bending.Damage.WaterManipulation", Integer.valueOf(5));
config.set("Chat.Color.Avatar", "DARK_PURPLE");
config.set("Chat.Color.Air", "GRAY");
config.set("Chat.Color.Fire", "RED");
config.set("Chat.Color.Water", "AQUA");
config.set("Chat.Color.Earth", "GREEN");
config.set("Chat.Color.ChiBlocker", "GOLD");
config.set("Bending.Option.EarthBendable", defaultearthbendable);
config.set("Bending.Option.Bend-With-Weapon.Air", false);
config.set("Bending.Option.Bend-With-Weapon.Fire", true);
config.set("Bending.Option.Bend-With-Weapon.Water", true);
config.set("Bending.Option.Bend-With-Weapon.Earth", true);
config.set("Bending.Option.Bend-With-Weapon.ChiBlocker", false);
config.set("Bending.Option.Bend-To-Item", false);
config.set("Bending.Option.Reverse-Earthbending", false);
config.set("Bending.Option.Reverse-Earthbending-Check-Time", 500000);
config.set("Bending.Option.Firebending-Dissipate-Time", 400);
config.set("Properties.ChiBlocker.ChiBlock-Duration", 2500);
config.set("Properties.ChiBlocker.Dodge-Chance", 25);
config.set("Properties.ChiBlocker.Punch-Multiplier", 3);
config.set("Properties.ChiBlocker.Fall-Damage-Reduction", 50);
config.set("Properties.GlobalCooldown", 500);
config.set("Properties.Air.AirBlast.Speed", 25);
config.set("Properties.Air.AirBlast.Range", 20);
config.set("Properties.Air.AirBlast.Affecting-Radius", 2);
config.set("Properties.Air.AirBlast.Push-Factor", 1);
config.set("Properties.Air.AirBubble.Radius", 5);
config.set("Properties.Air.Passive.Factor", 0.3F);
config.set("Properties.Air.AirShield.Radius", 7);
config.set("Properties.Air.AirSuction.Speed", 25);
config.set("Properties.Air.AirSuction.Range", 20);
config.set("Properties.Air.AirSuction.Affecting-Radius", 2);
config.set("Properties.Air.AirSuction.Push-Factor", 1);
config.set("Properties.Air.AirSwipe.Range", 16);
config.set("Properties.Air.AirSwipe.Arc", 20);
config.set("Properties.Air.AirSwipe.Speed", 25);
config.set("Properties.Air.AirSwipe.Affecting-Radius", 2);
config.set("Properties.Air.AirSwipe.Push-Factor", 1);
config.set("Properties.Air.AirSwipe.Cooldown", 1000);
config.set("Properties.Air.Tornado.Radius", 10);
config.set("Properties.Air.Tornado.Height", 25);
config.set("Properties.Air.Tornado.Range", 25);
config.set("Properties.Air.Tornado.Mob-Push-Factor", 1);
config.set("Properties.Air.Tornado.Player-Push-Factor", 1);
config.set("Properties.Air.AirScooter.Speed", .675);
config.set("Properties.Earth.Catapult.Length", 7);
config.set("Properties.Earth.Catapult.Speed", 12);
config.set("Properties.Earth.Catapult.Push", 5);
config.set("Properties.Earth.CompactColumn.Range", 20);
config.set("Properties.Earth.CompactColumn.Speed", 8);
config.set("Properties.Earth.EarthBlast.Range", 20);
config.set("Properties.Earth.EarthBlast.Speed", 35);
config.set("Properties.Earth.EarthColumn.Height", 6);
config.set("Properties.Earth.EarthGrab.Range", 15);
config.set("Properties.Earth.EarthPassive.Wait-Before-Reverse-Changes",
3000);
config.set("Properties.Earth.EarthTunnel.Max-Radius", 1);
config.set("Properties.Earth.EarthTunnel.Range", 10);
config.set("Properties.Earth.EarthTunnel.Radius", 0.25);
config.set("Properties.Earth.EarthTunnel.Interval", 30);
config.set("Properties.Earth.EarthWall.Range", 15);
config.set("Properties.Earth.EarthWall.Height", 8);
config.set("Properties.Earth.EarthWall.Width", 6);
config.set("Properties.Earth.Collapse.Range", 20);
config.set("Properties.Earth.Collapse.Radius", 7);
config.set("Properties.Earth.Tremorsense.Cooldown", 3000);
config.set("Properties.Earth.Tremorsense.Max-Depth", 10);
config.set("Properties.Earth.Tremorsense.Radius", 5);
config.set("Properties.Earth.Tremorsense.Light-Threshold", 7);
config.set("Properties.Fire.ArcOfFire.Arc", 20);
config.set("Properties.Fire.ArcOfFire.Range", 9);
config.set("Properties.Fire.RingOfFire.Range", 7);
config.set("Properties.Fire.Extinguish.Range", 20);
config.set("Properties.Fire.Extinguish.Radius", 20);
config.set("Properties.Fire.Fireball.Cooldown", 2000);
config.set("Properties.Fire.Fireball.Speed", 0.3);
config.set("Properties.Fire.FireJet.Speed", 0.7);
config.set("Properties.Fire.FireJet.Duration", 1500);
config.set("Properties.Fire.FireJet.CoolDown", 6000);
config.set("Properties.Fire.FireStream.Speed", 15);
config.set("Properties.Fire.HeatMelt.Range", 15);
config.set("Properties.Fire.HeatMelt.Radius", 5);
config.set("Properties.Fire.Illumination.Range", 5);
config.set("Properties.Fire.Day-Power-Factor", 1.3);
config.set("Properties.Water.FreezeMelt.Range", 20);
config.set("Properties.Water.FreezeMelt.Radius", 5);
config.set("Properties.Water.HealingWaters.Radius", 5);
config.set("Properties.Water.HealingWaters.Interval", 750);
config.set("Properties.Water.Plantbending.Range", 10);
config.set("Properties.Water.WalkOnWater.Radius", 3.5);
config.set("Properties.Water.WaterManipulation.Range", 20);
config.set("Properties.Water.WaterManipulation.Speed", 35);
config.set("Properties.Water.WaterSpout.Height", 15);
config.set("Properties.Water.WaterWall.Range", 5);
config.set("Properties.Water.WaterWall.Radius", 2);
config.set("Properties.Water.Wave.Radius", 3);
config.set("Properties.Water.Wave.Horizontal-Push-Force", 1);
config.set("Properties.Water.Wave.Vertical-Push-Force", 0.2);
config.set("Properties.Water.FastSwimming.Factor", 0.4);
config.set("Properties.Water.Night-Power-Factor", 1.5);
config.set("MySQL.Use-MySQL", false);
config.set("MySQL.MySQL-host", "localhost");
config.set("MySQL.MySQL-portnumber", 3306);
config.set("MySQL.User", "root");
config.set("MySQL.Password", "");
config.set("MySQL.Database", "minecraft");
return config;
}
public static String getColor(String element) {
return color.get(element);
}
public static String getPrefix(String element) {
return prefixes.get(element);
}
static {
defaultearthbendable.add("STONE");
defaultearthbendable.add("CLAY");
defaultearthbendable.add("COAL_ORE");
defaultearthbendable.add("DIAMOND_ORE");
defaultearthbendable.add("DIRT");
defaultearthbendable.add("GOLD_ORE");
defaultearthbendable.add("GRASS");
defaultearthbendable.add("GRAVEL");
defaultearthbendable.add("IRON_ORE");
defaultearthbendable.add("LAPIS_ORE");
defaultearthbendable.add("REDSTONE_ORE");
defaultearthbendable.add("SAND");
defaultearthbendable.add("SANDSTONE");
}
}
| true | true | public void load(File file) {
FileConfiguration config = new YamlConfiguration();
try {
if (file.exists())
config.load(file);
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidConfigurationException e) {
e.printStackTrace();
}
config.setDefaults(getDefaults());
colors = config.getBoolean("Chat.Colors");
bendToItem = config.getBoolean("Bending.Option.Bend-To-Item");
airdmg = config.getInt("Bending.Damage.AirSwipe");
enabled = config.getBoolean("Chat.Enabled");
compatibility = config.getBoolean("Chat.Compatibility");
waterdmg = config.getInt("Bending.Damage.WaterManipulation");
earthdmg = config.getInt("Bending.Damage.EarthBlast");
prefixes.put("Air", config.getString("Chat.Prefix.Air"));
prefixes.put("Avatar", config.getString("Chat.Prefix.Avatar"));
prefixes.put("Fire", config.getString("Chat.Prefix.Fire"));
prefixes.put("Water", config.getString("Chat.Prefix.Water"));
prefixes.put("Earth", config.getString("Chat.Prefix.Earth"));
prefixes.put("ChiBlocker", config.getString("Chat.Prefix.ChiBlocker"));
color.put("Avatar", config.getString("Chat.Color.Avatar"));
color.put("Air", config.getString("Chat.Color.Air"));
color.put("Fire", config.getString("Chat.Color.Fire"));
color.put("Water", config.getString("Chat.Color.Water"));
color.put("Earth", config.getString("Chat.Color.Earth"));
color.put("ChiBlocker", config.getString("Chat.Color.ChiBlocker"));
earthbendable = config.getStringList("Bending.Option.EarthBendable");
useWeapon
.put("Air", config.getBoolean(
"Bending.Option.Bend-With-Weapon.Air", false));
useWeapon.put("Earth", config.getBoolean(
"Bending.Option.Bend-With-Weapon.Earth", false));
useWeapon.put("Fire", config.getBoolean(
"Bending.Option.Bend-With-Weapon.Fire", false));
useWeapon.put("Water", config.getBoolean(
"Bending.Option.Bend-With-Weapon.Water", false));
// MySQL
useMySQL = config.getBoolean("MySQL.Use-MySQL", false);
dbHost = config.getString("MySQL.MySQL-host",
"jdbc:mysql://localhost:3306");
dbUser = config.getString("MySQL.User", "root");
dbPass = config.getString("MySQL.Password", "");
dbDB = config.getString("MySQL.Database", "minecraft");
Integer dbPortint = (Integer) config.getInt("MySQL.MySQL-portnumber");
dbPort = dbPortint.toString();
useWeapon
.put("ChiBlocker",
config.getBoolean("Bending.Option.Bend-With-Weapon.ChiBlocker"));
// Earthbending revert
reverseearthbending = config
.getBoolean("Bending.Option.Reverse-Earthbending");
revertchecktime = config
.getLong("Bending.Option.Reverse-Earthbending-Check-Time");
chiblockduration = config
.getLong("Properties.ChiBlocker.ChiBlock-Duration");
dodgechance = config.getDouble("Properties.ChiBlocker.Dodge-Chance");
punchmultiplier = config
.getDouble("Properties.ChiBlocker.Punch-Multiplier");
falldamagereduction = config
.getDouble("Properties.ChiBlocker.Fall-Damage-Reduction");
dissipateAfter = config
.getLong("Properties.Option.Firebending-Dissipate-Time");
// PROPERTIES
globalCooldown = config.getLong("Properties.GlobalCooldown");
// AIR
// AirBlast
airBlastSpeed = config.getDouble("Properties.Air.AirBlast.Speed");
airBlastRange = config.getDouble("Properties.Air.AirBlast.Range");
airBlastRadius = config
.getDouble("Properties.Air.AirBlast.Affecting-Radius");
airBlastPush = config.getDouble("Properties.Air.AirBlast.Push-Factor");
// AirBubble
airBubbleRadius = config.getInt("Properties.Air.AirBubble.Radius");
// AirPassive
airPassiveFactor = (float) config
.getDouble("Properties.Air.Passive.Factor");
// AirShield
airShieldRadius = config.getDouble("Properties.Air.AirShield.Radius");
// AirSuction
airSuctionSpeed = config.getDouble("Properties.Air.AirSuction.Speed");
airSuctionRange = config.getDouble("Properties.Air.AirSuction.Range");
airSuctionRadius = config
.getDouble("Properties.Air.AirSuction.Affecting-Radius");
airSuctionPush = config
.getDouble("Properties.Air.AirSuction.Push-Factor");
// AirSwipe
airSwipeRange = config.getDouble("Properties.Air.AirSwipe.Range");
airSwipeArc = config.getInt("Properties.Air.AirSwipe.Arc");
airSwipeSpeed = config.getDouble("Properties.Air.AirSwipe.Speed");
airSwipeRadius = config
.getDouble("Properties.Air.AirSwipe.Affecting-Radius");
airSwipePush = config.getDouble("Properties.Air.AirSwipe.Push-Factor");
airSwipeCooldown = config.getLong("Properties.Air.AirSwipe.Cooldown");
// Tornado
tornadoRadius = config.getDouble("Properties.Air.Tornado.Radius");
tornadoHeight = config.getDouble("Properties.Air.Tornado.Height");
tornadoRange = config.getDouble("Properties.Air.Tornado.Range");
tornadoMobPush = config
.getDouble("Properties.Air.Tornado.Mob-Push-Factor");
tornadoPlayerPush = config
.getDouble("Properties.Air.Tornado.Player-Push-Factor");
// Air Scooter
airScooterSpeed = config.getDouble("Properties.Air.AirScooter.Speed");
// EARTH
// Catapult
catapultLength = config.getInt("Properties.Earth.Catapult.Length");
catapultSpeed = config.getDouble("Properties.Earth.Catapult.Speed");
catapultPush = config.getDouble("Properties.Earth.Catapult.Push");
// CompactColumn
compactColumnRange = config
.getDouble("Properties.Earth.CompactColumn.Range");
compactColumnSpeed = config
.getDouble("Properties.Earth.CompactColumn.Speed");
// EarthBlast
earthBlastRange = config.getDouble("Properties.Earth.EarthBlast.Range");
earthBlastSpeed = config.getDouble("Properties.Earth.EarthBlast.Speed");
// EarthColumn
earthColumnHeight = config
.getInt("Properties.Earth.EarthColumn.Height");
// EarthGrab
earthGrabRange = config.getDouble("Properties.Earth.EarthGrab.Range");
// EarthPassive
earthPassive = config
.getLong("Properties.Earth.EarthPassive.Wait-Before-Reverse-Changes");
// EarthTunnel
earthTunnelMaxRadius = config
.getDouble("Properties.Earth.EarthTunnel.Max-Radius");
earthTunnelRange = config
.getDouble("Properties.Earth.EarthTunnel.Range");
earthTunnelRadius = config
.getDouble("Properties.Earth.EarthTunnel.Radius");
earthTunnelInterval = config
.getLong("Properties.Earth.EarthTunnel.Interval");
// EarthWall
earthWallRange = config.getInt("Properties.Earth.EarthWall.Range");
earthWallHeight = config.getInt("Properties.Earth.EarthWall.Height");
earthWallWidth = config.getInt("Properties.Earth.EarthWall.Width");
// Collapse
collapseRange = config.getInt("Properties.Earth.Collapse.Range");
collapseRadius = config.getDouble("Properties.Earth.Collapse.Radius");
// Tremorsense
tremorsenseCooldown = config
.getLong("Properties.Earth.Tremorsense.Cooldown");
tremorsenseMaxDepth = config
.getInt("Properties.Earth.Tremorsense.Max-Depth");
tremorsenseRadius = config
.getInt("Properties.Earth.Tremorsense.Radius");
tremorsenseLightThreshold = (byte) config
.getInt("Properties.Earth.Tremorsense.Light-Threshold");
// FIRE
// ArcOfFire
arcOfFireArc = config.getInt("Properties.Fire.ArcOfFire.Arc");
arcOfFireRange = config.getInt("Properties.Fire.ArcOfFire.Range");
// RingOfFire
ringOfFireRange = config.getInt("Properties.Fire.RingOfFire.Range");
// Extinguish
extinguishRange = config.getDouble("Properties.Fire.Extinguish.Range");
extinguishRadius = config
.getDouble("Properties.Fire.Extinguish.Radius");
// Fireball
fireballCooldown = config.getLong("Properties.Fire.Fireball.Cooldown");
fireballSpeed = config.getDouble("Properties.Fire.Fireball.Speed");
// FireJet
fireJetSpeed = config.getDouble("Properties.Fire.FireJet.Speed");
fireJetDuration = config.getLong("Properties.Fire.FireJet.Duration");
fireJetCooldown = config.getLong("Properties.Fire.FireJet.CoolDown");
// FireStream
fireStreamSpeed = config.getDouble("Properties.Fire.FireStream.Speed");
// HeatMelt
heatMeltRange = config.getInt("Properties.Fire.HeatMelt.Range");
heatMeltRadius = config.getInt("Properties.Fire.HeatMelt.Radius");
// Illumination
illuminationRange = config.getInt("Properties.Fire.Illumination.Range");
// Day
dayFactor = config.getDouble("Properties.Fire.Day-Power-Factor");
// WATER
// FreezeMelt
freezeMeltRange = config.getInt("Properties.Water.FreezeMelt.Range");
freezeMeltRadius = config.getInt("Properties.Water.FreezeMelt.Radius");
// HealingWaters
healingWatersRadius = config
.getDouble("Properties.Water.HealingWaters.Radius");
healingWatersInterval = config
.getLong("Properties.Water.HealingWaters.Interval");
// Plantbending
plantbendingRange = config
.getInt("Properties.Water.Plantbending.Range");
// WalkOnWater
walkOnWaterRadius = config
.getDouble("Properties.Water.WalkOnWater.Radius");
// WaterManipulation
waterManipulationRange = config
.getDouble("Properties.Water.WaterManipulation.Range");
waterManipulationSpeed = config
.getDouble("Properties.Water.WaterManipulation.Speed");
// WaterSpout
waterSpoutHeight = config.getInt("Properties.Water.WaterSpout.Height");
// WaterWall
waterWallRange = config.getDouble("Properties.Water.WaterWall.Range");
waterWallRadius = config.getDouble("Properties.Water.WaterWall.Radius");
// Wave
waveRadius = config.getDouble("Properties.Water.Wave.Radius");
waveHorizontalPush = config
.getDouble("Properties.Water.Wave.Horizontal-Push-Force");
waveVerticalPush = config
.getDouble("Properties.Water.Wave.Vertical-Push-Force");
// Fast Swimming
fastSwimmingFactor = config
.getDouble("Properties.Water.FastSwimming.Factor");
// Night
nightFactor = config.getDouble("Properties.Water.Night-Power-Factor");
try {
config.options().copyDefaults(true);
config.save(file);
} catch (IOException e) {
e.printStackTrace();
}
}
| public void load(File file) {
FileConfiguration config = new YamlConfiguration();
try {
if (file.exists())
config.load(file);
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidConfigurationException e) {
e.printStackTrace();
}
config.setDefaults(getDefaults());
colors = config.getBoolean("Chat.Colors");
bendToItem = config.getBoolean("Bending.Option.Bend-To-Item");
airdmg = config.getInt("Bending.Damage.AirSwipe");
enabled = config.getBoolean("Chat.Enabled");
compatibility = config.getBoolean("Chat.Compatibility");
waterdmg = config.getInt("Bending.Damage.WaterManipulation");
earthdmg = config.getInt("Bending.Damage.EarthBlast");
prefixes.put("Air", config.getString("Chat.Prefix.Air"));
prefixes.put("Avatar", config.getString("Chat.Prefix.Avatar"));
prefixes.put("Fire", config.getString("Chat.Prefix.Fire"));
prefixes.put("Water", config.getString("Chat.Prefix.Water"));
prefixes.put("Earth", config.getString("Chat.Prefix.Earth"));
prefixes.put("ChiBlocker", config.getString("Chat.Prefix.ChiBlocker"));
color.put("Avatar", config.getString("Chat.Color.Avatar"));
color.put("Air", config.getString("Chat.Color.Air"));
color.put("Fire", config.getString("Chat.Color.Fire"));
color.put("Water", config.getString("Chat.Color.Water"));
color.put("Earth", config.getString("Chat.Color.Earth"));
color.put("ChiBlocker", config.getString("Chat.Color.ChiBlocker"));
earthbendable = config.getStringList("Bending.Option.EarthBendable");
useWeapon
.put("Air", config.getBoolean(
"Bending.Option.Bend-With-Weapon.Air", false));
useWeapon.put("Earth", config.getBoolean(
"Bending.Option.Bend-With-Weapon.Earth", false));
useWeapon.put("Fire", config.getBoolean(
"Bending.Option.Bend-With-Weapon.Fire", false));
useWeapon.put("Water", config.getBoolean(
"Bending.Option.Bend-With-Weapon.Water", false));
// MySQL
useMySQL = config.getBoolean("MySQL.Use-MySQL", false);
dbHost = config.getString("MySQL.MySQL-host",
"jdbc:mysql://localhost:3306");
dbUser = config.getString("MySQL.User", "root");
dbPass = config.getString("MySQL.Password", "");
dbDB = config.getString("MySQL.Database", "minecraft");
Integer dbPortint = (Integer) config.getInt("MySQL.MySQL-portnumber");
dbPort = dbPortint.toString();
useWeapon
.put("ChiBlocker",
config.getBoolean("Bending.Option.Bend-With-Weapon.ChiBlocker"));
// Earthbending revert
reverseearthbending = config
.getBoolean("Bending.Option.Reverse-Earthbending");
revertchecktime = config
.getLong("Bending.Option.Reverse-Earthbending-Check-Time");
chiblockduration = config
.getLong("Properties.ChiBlocker.ChiBlock-Duration");
dodgechance = config.getDouble("Properties.ChiBlocker.Dodge-Chance");
punchmultiplier = config
.getDouble("Properties.ChiBlocker.Punch-Multiplier");
falldamagereduction = config
.getDouble("Properties.ChiBlocker.Fall-Damage-Reduction");
dissipateAfter = config
.getLong("Bending.Option.Firebending-Dissipate-Time");
// PROPERTIES
globalCooldown = config.getLong("Properties.GlobalCooldown");
// AIR
// AirBlast
airBlastSpeed = config.getDouble("Properties.Air.AirBlast.Speed");
airBlastRange = config.getDouble("Properties.Air.AirBlast.Range");
airBlastRadius = config
.getDouble("Properties.Air.AirBlast.Affecting-Radius");
airBlastPush = config.getDouble("Properties.Air.AirBlast.Push-Factor");
// AirBubble
airBubbleRadius = config.getInt("Properties.Air.AirBubble.Radius");
// AirPassive
airPassiveFactor = (float) config
.getDouble("Properties.Air.Passive.Factor");
// AirShield
airShieldRadius = config.getDouble("Properties.Air.AirShield.Radius");
// AirSuction
airSuctionSpeed = config.getDouble("Properties.Air.AirSuction.Speed");
airSuctionRange = config.getDouble("Properties.Air.AirSuction.Range");
airSuctionRadius = config
.getDouble("Properties.Air.AirSuction.Affecting-Radius");
airSuctionPush = config
.getDouble("Properties.Air.AirSuction.Push-Factor");
// AirSwipe
airSwipeRange = config.getDouble("Properties.Air.AirSwipe.Range");
airSwipeArc = config.getInt("Properties.Air.AirSwipe.Arc");
airSwipeSpeed = config.getDouble("Properties.Air.AirSwipe.Speed");
airSwipeRadius = config
.getDouble("Properties.Air.AirSwipe.Affecting-Radius");
airSwipePush = config.getDouble("Properties.Air.AirSwipe.Push-Factor");
airSwipeCooldown = config.getLong("Properties.Air.AirSwipe.Cooldown");
// Tornado
tornadoRadius = config.getDouble("Properties.Air.Tornado.Radius");
tornadoHeight = config.getDouble("Properties.Air.Tornado.Height");
tornadoRange = config.getDouble("Properties.Air.Tornado.Range");
tornadoMobPush = config
.getDouble("Properties.Air.Tornado.Mob-Push-Factor");
tornadoPlayerPush = config
.getDouble("Properties.Air.Tornado.Player-Push-Factor");
// Air Scooter
airScooterSpeed = config.getDouble("Properties.Air.AirScooter.Speed");
// EARTH
// Catapult
catapultLength = config.getInt("Properties.Earth.Catapult.Length");
catapultSpeed = config.getDouble("Properties.Earth.Catapult.Speed");
catapultPush = config.getDouble("Properties.Earth.Catapult.Push");
// CompactColumn
compactColumnRange = config
.getDouble("Properties.Earth.CompactColumn.Range");
compactColumnSpeed = config
.getDouble("Properties.Earth.CompactColumn.Speed");
// EarthBlast
earthBlastRange = config.getDouble("Properties.Earth.EarthBlast.Range");
earthBlastSpeed = config.getDouble("Properties.Earth.EarthBlast.Speed");
// EarthColumn
earthColumnHeight = config
.getInt("Properties.Earth.EarthColumn.Height");
// EarthGrab
earthGrabRange = config.getDouble("Properties.Earth.EarthGrab.Range");
// EarthPassive
earthPassive = config
.getLong("Properties.Earth.EarthPassive.Wait-Before-Reverse-Changes");
// EarthTunnel
earthTunnelMaxRadius = config
.getDouble("Properties.Earth.EarthTunnel.Max-Radius");
earthTunnelRange = config
.getDouble("Properties.Earth.EarthTunnel.Range");
earthTunnelRadius = config
.getDouble("Properties.Earth.EarthTunnel.Radius");
earthTunnelInterval = config
.getLong("Properties.Earth.EarthTunnel.Interval");
// EarthWall
earthWallRange = config.getInt("Properties.Earth.EarthWall.Range");
earthWallHeight = config.getInt("Properties.Earth.EarthWall.Height");
earthWallWidth = config.getInt("Properties.Earth.EarthWall.Width");
// Collapse
collapseRange = config.getInt("Properties.Earth.Collapse.Range");
collapseRadius = config.getDouble("Properties.Earth.Collapse.Radius");
// Tremorsense
tremorsenseCooldown = config
.getLong("Properties.Earth.Tremorsense.Cooldown");
tremorsenseMaxDepth = config
.getInt("Properties.Earth.Tremorsense.Max-Depth");
tremorsenseRadius = config
.getInt("Properties.Earth.Tremorsense.Radius");
tremorsenseLightThreshold = (byte) config
.getInt("Properties.Earth.Tremorsense.Light-Threshold");
// FIRE
// ArcOfFire
arcOfFireArc = config.getInt("Properties.Fire.ArcOfFire.Arc");
arcOfFireRange = config.getInt("Properties.Fire.ArcOfFire.Range");
// RingOfFire
ringOfFireRange = config.getInt("Properties.Fire.RingOfFire.Range");
// Extinguish
extinguishRange = config.getDouble("Properties.Fire.Extinguish.Range");
extinguishRadius = config
.getDouble("Properties.Fire.Extinguish.Radius");
// Fireball
fireballCooldown = config.getLong("Properties.Fire.Fireball.Cooldown");
fireballSpeed = config.getDouble("Properties.Fire.Fireball.Speed");
// FireJet
fireJetSpeed = config.getDouble("Properties.Fire.FireJet.Speed");
fireJetDuration = config.getLong("Properties.Fire.FireJet.Duration");
fireJetCooldown = config.getLong("Properties.Fire.FireJet.CoolDown");
// FireStream
fireStreamSpeed = config.getDouble("Properties.Fire.FireStream.Speed");
// HeatMelt
heatMeltRange = config.getInt("Properties.Fire.HeatMelt.Range");
heatMeltRadius = config.getInt("Properties.Fire.HeatMelt.Radius");
// Illumination
illuminationRange = config.getInt("Properties.Fire.Illumination.Range");
// Day
dayFactor = config.getDouble("Properties.Fire.Day-Power-Factor");
// WATER
// FreezeMelt
freezeMeltRange = config.getInt("Properties.Water.FreezeMelt.Range");
freezeMeltRadius = config.getInt("Properties.Water.FreezeMelt.Radius");
// HealingWaters
healingWatersRadius = config
.getDouble("Properties.Water.HealingWaters.Radius");
healingWatersInterval = config
.getLong("Properties.Water.HealingWaters.Interval");
// Plantbending
plantbendingRange = config
.getInt("Properties.Water.Plantbending.Range");
// WalkOnWater
walkOnWaterRadius = config
.getDouble("Properties.Water.WalkOnWater.Radius");
// WaterManipulation
waterManipulationRange = config
.getDouble("Properties.Water.WaterManipulation.Range");
waterManipulationSpeed = config
.getDouble("Properties.Water.WaterManipulation.Speed");
// WaterSpout
waterSpoutHeight = config.getInt("Properties.Water.WaterSpout.Height");
// WaterWall
waterWallRange = config.getDouble("Properties.Water.WaterWall.Range");
waterWallRadius = config.getDouble("Properties.Water.WaterWall.Radius");
// Wave
waveRadius = config.getDouble("Properties.Water.Wave.Radius");
waveHorizontalPush = config
.getDouble("Properties.Water.Wave.Horizontal-Push-Force");
waveVerticalPush = config
.getDouble("Properties.Water.Wave.Vertical-Push-Force");
// Fast Swimming
fastSwimmingFactor = config
.getDouble("Properties.Water.FastSwimming.Factor");
// Night
nightFactor = config.getDouble("Properties.Water.Night-Power-Factor");
try {
config.options().copyDefaults(true);
config.save(file);
} catch (IOException e) {
e.printStackTrace();
}
}
|
diff --git a/GAE/src/org/waterforpeople/mapping/app/web/TestHarnessServlet.java b/GAE/src/org/waterforpeople/mapping/app/web/TestHarnessServlet.java
index 4a27e5062..b3135512f 100644
--- a/GAE/src/org/waterforpeople/mapping/app/web/TestHarnessServlet.java
+++ b/GAE/src/org/waterforpeople/mapping/app/web/TestHarnessServlet.java
@@ -1,396 +1,396 @@
package org.waterforpeople.mapping.app.web;
import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.url;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.waterforpeople.mapping.analytics.dao.AccessPointStatusSummaryDao;
import org.waterforpeople.mapping.analytics.domain.AccessPointStatusSummary;
import org.waterforpeople.mapping.analytics.domain.SurveyQuestionSummary;
import org.waterforpeople.mapping.dao.CommunityDao;
import org.waterforpeople.mapping.dao.SurveyInstanceDAO;
import org.waterforpeople.mapping.domain.AccessPoint;
import org.waterforpeople.mapping.domain.Community;
import org.waterforpeople.mapping.domain.QuestionAnswerStore;
import org.waterforpeople.mapping.domain.SurveyInstance;
import org.waterforpeople.mapping.domain.SurveyQuestion;
import org.waterforpeople.mapping.domain.AccessPoint.AccessPointType;
import org.waterforpeople.mapping.domain.AccessPoint.Status;
import org.waterforpeople.mapping.domain.SurveyQuestion.QuestionAnswerType;
import org.waterforpeople.mapping.helper.AccessPointHelper;
import org.waterforpeople.mapping.helper.GeoRegionHelper;
import com.gallatinsystems.framework.dao.BaseDAO;
import com.gallatinsystems.gis.geography.domain.Country;
import com.gallatinsystems.survey.dao.SurveyDAO;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
public class TestHarnessServlet extends HttpServlet {
private static Logger log = Logger.getLogger(TestHarnessServlet.class
.getName());
private static final long serialVersionUID = -5673118002247715049L;
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
String action = req.getParameter("action");
if ("testBaseDomain".equals(action)) {
SurveyDAO surveyDAO = new SurveyDAO();
surveyDAO.test();
String outString = surveyDAO.getForTest();
BaseDAO<AccessPoint> pointDao = new BaseDAO<AccessPoint>(
AccessPoint.class);
AccessPoint point = new AccessPoint();
point.setLatitude(78d);
point.setLongitude(43d);
pointDao.save(point);
try {
resp.getWriter().print(outString);
} catch (IOException e) {
log.log(Level.SEVERE, "Could not execute test", e);
}
} else if ("testSaveRegion".equals(action)) {
GeoRegionHelper geoHelp = new GeoRegionHelper();
ArrayList<String> regionLines = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
StringBuilder builder = new StringBuilder();
builder.append("1,").append("" + i).append(",test,").append(
20 + i + ",").append(30 + i + "\n");
regionLines.add(builder.toString());
}
geoHelp.processRegionsSurvey(regionLines);
try {
resp.getWriter().print("Save complete");
} catch (IOException e) {
log.log(Level.SEVERE, "Could not save test region", e);
}
} else if ("testSurveyQuestion".equals(action)) {
SurveyDAO surveyDao = new SurveyDAO();
SurveyQuestion q = new SurveyQuestion();
q.setId("q6");
q.setText("Source");
q.setType(QuestionAnswerType.option);
surveyDao.save(q);
q = new SurveyQuestion();
q.setId("q7");
q.setText("Collection Point");
q.setType(QuestionAnswerType.option);
surveyDao.save(q);
SurveyQuestionSummary summ = new SurveyQuestionSummary();
summ.setQuestionId("q6");
summ.setCount(new Long(10));
summ.setResponse("Spring");
surveyDao.save(summ);
summ = new SurveyQuestionSummary();
summ.setQuestionId("q6");
summ.setCount(new Long(7));
summ.setResponse("Borehole");
surveyDao.save(summ);
summ = new SurveyQuestionSummary();
summ.setQuestionId("q6");
summ.setCount(new Long(22));
summ.setResponse("Surface Water");
surveyDao.save(summ);
summ = new SurveyQuestionSummary();
summ.setQuestionId("q7");
summ.setCount(new Long(19));
summ.setResponse("Public Handpump");
surveyDao.save(summ);
summ = new SurveyQuestionSummary();
summ.setQuestionId("q7");
summ.setCount(new Long(32));
summ.setResponse("Yard Connection");
surveyDao.save(summ);
summ = new SurveyQuestionSummary();
summ.setQuestionId("q7");
summ.setCount(new Long(3));
summ.setResponse("House Connection");
surveyDao.save(summ);
} else if ("createAP".equals(action)) {
AccessPoint ap = new AccessPoint();
ap.setCollectionDate(new Date());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setPointType(AccessPointType.WATER_POINT);
AccessPointHelper helper = new AccessPointHelper();
helper.saveAccessPoint(ap);
} else if ("createInstance".equals(action)) {
SurveyInstance si = new SurveyInstance();
si.setCollectionDate(new Date());
ArrayList<QuestionAnswerStore> store = new ArrayList<QuestionAnswerStore>();
QuestionAnswerStore ans = new QuestionAnswerStore();
ans.setQuestionID("q2");
ans.setValue("Geneva");
store.add(ans);
si.setQuestionAnswersStore(store);
SurveyInstanceDAO dao = new SurveyInstanceDAO();
si = dao.save(si);
Queue summQueue = QueueFactory.getQueue("dataSummarization");
summQueue.add(url("/app_worker/datasummarization").param(
"objectKey", si.getKey().getId() + "").param("type",
"SurveyInstance"));
} else if ("createCommunity".equals(action)) {
CommunityDao dao = new CommunityDao();
Country c = new Country();
c.setIsoAlpha2Code("CA");
c.setName("Canada");
c.setDisplayName("Canada");
Community comm = new Community();
comm.setCommunityCode("ON");
dao.save(c);
comm.setCountryCode("CA");
comm.setLat(54.99);
comm.setLon(-74.72);
dao.save(comm);
c = new Country();
c.setIsoAlpha2Code("US");
c.setName("United States");
c.setDisplayName("Unites States");
comm = new Community();
comm.setCommunityCode("Omaha");
comm.setCountryCode("US");
comm.setLat(34.99);
comm.setLon(-74.72);
dao.save(c);
dao.save(comm);
} else if ("createAPSummary".equals(action)) {
AccessPointStatusSummary sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2000");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
AccessPointStatusSummaryDao dao = new AccessPointStatusSummaryDao();
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2001");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2003");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2004");
sum.setStatus(AccessPoint.Status.FUNCTIONING_OK);
dao.save(sum);
- sum.setCommunity("US");
- sum.setCountry("NY");
+ sum.setCommunity("NY");
+ sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2000");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
- sum.setCommunity("US");
- sum.setCountry("NY");
+ sum.setCommunity("NY");
+ sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2001");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
- sum.setCommunity("US");
- sum.setCountry("NY");
+ sum.setCommunity("NY");
+ sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2003");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
- sum.setCommunity("US");
- sum.setCountry("NY");
+ sum.setCommunity("NY");
+ sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2004");
sum.setStatus(AccessPoint.Status.FUNCTIONING_OK);
dao.save(sum);
} else if ("createApHistory".equals(action)) {
GregorianCalendar cal = new GregorianCalendar();
AccessPointHelper apHelper = new AccessPointHelper();
AccessPoint ap = new AccessPoint();
cal.set(Calendar.YEAR, 2000);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(300l);
ap.setCostPer(43.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2001);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(317l);
ap.setCostPer(40.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2002);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(340l);
ap.setCostPer(37.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2003);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(340l);
ap.setCostPer(34.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2004);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(338l);
ap.setCostPer(38.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2000);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(170l);
ap.setCostPer(19.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2001);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(201l);
ap.setCostPer(19.00);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2002);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(211l);
ap.setCostPer(17.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2003);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(220l);
ap.setCostPer(25.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2004);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(175l);
ap.setCostPer(24.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
} else if ("createQuestionLookup".equals(action)) {
SurveyDAO surveyDao = new SurveyDAO();
SurveyQuestion q = new SurveyQuestion();
q.setId("qm5");
q.setText("Technology Type");
q.setType(QuestionAnswerType.option);
surveyDao.save(q);
q = new SurveyQuestion();
q.setId("qm8");
q.setText("Is farthest household within 500m");
q.setType(QuestionAnswerType.option);
surveyDao.save(q);
q = new SurveyQuestion();
q.setId("qm9");
q.setText("Management Structure");
q.setType(QuestionAnswerType.option);
surveyDao.save(q);
q = new SurveyQuestion();
q.setId("qm10");
q.setText("Status");
q.setType(QuestionAnswerType.option);
surveyDao.save(q);
}
}
}
| false | true | public void doGet(HttpServletRequest req, HttpServletResponse resp) {
String action = req.getParameter("action");
if ("testBaseDomain".equals(action)) {
SurveyDAO surveyDAO = new SurveyDAO();
surveyDAO.test();
String outString = surveyDAO.getForTest();
BaseDAO<AccessPoint> pointDao = new BaseDAO<AccessPoint>(
AccessPoint.class);
AccessPoint point = new AccessPoint();
point.setLatitude(78d);
point.setLongitude(43d);
pointDao.save(point);
try {
resp.getWriter().print(outString);
} catch (IOException e) {
log.log(Level.SEVERE, "Could not execute test", e);
}
} else if ("testSaveRegion".equals(action)) {
GeoRegionHelper geoHelp = new GeoRegionHelper();
ArrayList<String> regionLines = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
StringBuilder builder = new StringBuilder();
builder.append("1,").append("" + i).append(",test,").append(
20 + i + ",").append(30 + i + "\n");
regionLines.add(builder.toString());
}
geoHelp.processRegionsSurvey(regionLines);
try {
resp.getWriter().print("Save complete");
} catch (IOException e) {
log.log(Level.SEVERE, "Could not save test region", e);
}
} else if ("testSurveyQuestion".equals(action)) {
SurveyDAO surveyDao = new SurveyDAO();
SurveyQuestion q = new SurveyQuestion();
q.setId("q6");
q.setText("Source");
q.setType(QuestionAnswerType.option);
surveyDao.save(q);
q = new SurveyQuestion();
q.setId("q7");
q.setText("Collection Point");
q.setType(QuestionAnswerType.option);
surveyDao.save(q);
SurveyQuestionSummary summ = new SurveyQuestionSummary();
summ.setQuestionId("q6");
summ.setCount(new Long(10));
summ.setResponse("Spring");
surveyDao.save(summ);
summ = new SurveyQuestionSummary();
summ.setQuestionId("q6");
summ.setCount(new Long(7));
summ.setResponse("Borehole");
surveyDao.save(summ);
summ = new SurveyQuestionSummary();
summ.setQuestionId("q6");
summ.setCount(new Long(22));
summ.setResponse("Surface Water");
surveyDao.save(summ);
summ = new SurveyQuestionSummary();
summ.setQuestionId("q7");
summ.setCount(new Long(19));
summ.setResponse("Public Handpump");
surveyDao.save(summ);
summ = new SurveyQuestionSummary();
summ.setQuestionId("q7");
summ.setCount(new Long(32));
summ.setResponse("Yard Connection");
surveyDao.save(summ);
summ = new SurveyQuestionSummary();
summ.setQuestionId("q7");
summ.setCount(new Long(3));
summ.setResponse("House Connection");
surveyDao.save(summ);
} else if ("createAP".equals(action)) {
AccessPoint ap = new AccessPoint();
ap.setCollectionDate(new Date());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setPointType(AccessPointType.WATER_POINT);
AccessPointHelper helper = new AccessPointHelper();
helper.saveAccessPoint(ap);
} else if ("createInstance".equals(action)) {
SurveyInstance si = new SurveyInstance();
si.setCollectionDate(new Date());
ArrayList<QuestionAnswerStore> store = new ArrayList<QuestionAnswerStore>();
QuestionAnswerStore ans = new QuestionAnswerStore();
ans.setQuestionID("q2");
ans.setValue("Geneva");
store.add(ans);
si.setQuestionAnswersStore(store);
SurveyInstanceDAO dao = new SurveyInstanceDAO();
si = dao.save(si);
Queue summQueue = QueueFactory.getQueue("dataSummarization");
summQueue.add(url("/app_worker/datasummarization").param(
"objectKey", si.getKey().getId() + "").param("type",
"SurveyInstance"));
} else if ("createCommunity".equals(action)) {
CommunityDao dao = new CommunityDao();
Country c = new Country();
c.setIsoAlpha2Code("CA");
c.setName("Canada");
c.setDisplayName("Canada");
Community comm = new Community();
comm.setCommunityCode("ON");
dao.save(c);
comm.setCountryCode("CA");
comm.setLat(54.99);
comm.setLon(-74.72);
dao.save(comm);
c = new Country();
c.setIsoAlpha2Code("US");
c.setName("United States");
c.setDisplayName("Unites States");
comm = new Community();
comm.setCommunityCode("Omaha");
comm.setCountryCode("US");
comm.setLat(34.99);
comm.setLon(-74.72);
dao.save(c);
dao.save(comm);
} else if ("createAPSummary".equals(action)) {
AccessPointStatusSummary sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2000");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
AccessPointStatusSummaryDao dao = new AccessPointStatusSummaryDao();
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2001");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2003");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2004");
sum.setStatus(AccessPoint.Status.FUNCTIONING_OK);
dao.save(sum);
sum.setCommunity("US");
sum.setCountry("NY");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2000");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("US");
sum.setCountry("NY");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2001");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("US");
sum.setCountry("NY");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2003");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("US");
sum.setCountry("NY");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2004");
sum.setStatus(AccessPoint.Status.FUNCTIONING_OK);
dao.save(sum);
} else if ("createApHistory".equals(action)) {
GregorianCalendar cal = new GregorianCalendar();
AccessPointHelper apHelper = new AccessPointHelper();
AccessPoint ap = new AccessPoint();
cal.set(Calendar.YEAR, 2000);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(300l);
ap.setCostPer(43.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2001);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(317l);
ap.setCostPer(40.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2002);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(340l);
ap.setCostPer(37.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2003);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(340l);
ap.setCostPer(34.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2004);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(338l);
ap.setCostPer(38.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2000);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(170l);
ap.setCostPer(19.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2001);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(201l);
ap.setCostPer(19.00);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2002);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(211l);
ap.setCostPer(17.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2003);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(220l);
ap.setCostPer(25.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2004);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(175l);
ap.setCostPer(24.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
} else if ("createQuestionLookup".equals(action)) {
SurveyDAO surveyDao = new SurveyDAO();
SurveyQuestion q = new SurveyQuestion();
q.setId("qm5");
q.setText("Technology Type");
q.setType(QuestionAnswerType.option);
surveyDao.save(q);
q = new SurveyQuestion();
q.setId("qm8");
q.setText("Is farthest household within 500m");
q.setType(QuestionAnswerType.option);
surveyDao.save(q);
q = new SurveyQuestion();
q.setId("qm9");
q.setText("Management Structure");
q.setType(QuestionAnswerType.option);
surveyDao.save(q);
q = new SurveyQuestion();
q.setId("qm10");
q.setText("Status");
q.setType(QuestionAnswerType.option);
surveyDao.save(q);
}
}
| public void doGet(HttpServletRequest req, HttpServletResponse resp) {
String action = req.getParameter("action");
if ("testBaseDomain".equals(action)) {
SurveyDAO surveyDAO = new SurveyDAO();
surveyDAO.test();
String outString = surveyDAO.getForTest();
BaseDAO<AccessPoint> pointDao = new BaseDAO<AccessPoint>(
AccessPoint.class);
AccessPoint point = new AccessPoint();
point.setLatitude(78d);
point.setLongitude(43d);
pointDao.save(point);
try {
resp.getWriter().print(outString);
} catch (IOException e) {
log.log(Level.SEVERE, "Could not execute test", e);
}
} else if ("testSaveRegion".equals(action)) {
GeoRegionHelper geoHelp = new GeoRegionHelper();
ArrayList<String> regionLines = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
StringBuilder builder = new StringBuilder();
builder.append("1,").append("" + i).append(",test,").append(
20 + i + ",").append(30 + i + "\n");
regionLines.add(builder.toString());
}
geoHelp.processRegionsSurvey(regionLines);
try {
resp.getWriter().print("Save complete");
} catch (IOException e) {
log.log(Level.SEVERE, "Could not save test region", e);
}
} else if ("testSurveyQuestion".equals(action)) {
SurveyDAO surveyDao = new SurveyDAO();
SurveyQuestion q = new SurveyQuestion();
q.setId("q6");
q.setText("Source");
q.setType(QuestionAnswerType.option);
surveyDao.save(q);
q = new SurveyQuestion();
q.setId("q7");
q.setText("Collection Point");
q.setType(QuestionAnswerType.option);
surveyDao.save(q);
SurveyQuestionSummary summ = new SurveyQuestionSummary();
summ.setQuestionId("q6");
summ.setCount(new Long(10));
summ.setResponse("Spring");
surveyDao.save(summ);
summ = new SurveyQuestionSummary();
summ.setQuestionId("q6");
summ.setCount(new Long(7));
summ.setResponse("Borehole");
surveyDao.save(summ);
summ = new SurveyQuestionSummary();
summ.setQuestionId("q6");
summ.setCount(new Long(22));
summ.setResponse("Surface Water");
surveyDao.save(summ);
summ = new SurveyQuestionSummary();
summ.setQuestionId("q7");
summ.setCount(new Long(19));
summ.setResponse("Public Handpump");
surveyDao.save(summ);
summ = new SurveyQuestionSummary();
summ.setQuestionId("q7");
summ.setCount(new Long(32));
summ.setResponse("Yard Connection");
surveyDao.save(summ);
summ = new SurveyQuestionSummary();
summ.setQuestionId("q7");
summ.setCount(new Long(3));
summ.setResponse("House Connection");
surveyDao.save(summ);
} else if ("createAP".equals(action)) {
AccessPoint ap = new AccessPoint();
ap.setCollectionDate(new Date());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setPointType(AccessPointType.WATER_POINT);
AccessPointHelper helper = new AccessPointHelper();
helper.saveAccessPoint(ap);
} else if ("createInstance".equals(action)) {
SurveyInstance si = new SurveyInstance();
si.setCollectionDate(new Date());
ArrayList<QuestionAnswerStore> store = new ArrayList<QuestionAnswerStore>();
QuestionAnswerStore ans = new QuestionAnswerStore();
ans.setQuestionID("q2");
ans.setValue("Geneva");
store.add(ans);
si.setQuestionAnswersStore(store);
SurveyInstanceDAO dao = new SurveyInstanceDAO();
si = dao.save(si);
Queue summQueue = QueueFactory.getQueue("dataSummarization");
summQueue.add(url("/app_worker/datasummarization").param(
"objectKey", si.getKey().getId() + "").param("type",
"SurveyInstance"));
} else if ("createCommunity".equals(action)) {
CommunityDao dao = new CommunityDao();
Country c = new Country();
c.setIsoAlpha2Code("CA");
c.setName("Canada");
c.setDisplayName("Canada");
Community comm = new Community();
comm.setCommunityCode("ON");
dao.save(c);
comm.setCountryCode("CA");
comm.setLat(54.99);
comm.setLon(-74.72);
dao.save(comm);
c = new Country();
c.setIsoAlpha2Code("US");
c.setName("United States");
c.setDisplayName("Unites States");
comm = new Community();
comm.setCommunityCode("Omaha");
comm.setCountryCode("US");
comm.setLat(34.99);
comm.setLon(-74.72);
dao.save(c);
dao.save(comm);
} else if ("createAPSummary".equals(action)) {
AccessPointStatusSummary sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2000");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
AccessPointStatusSummaryDao dao = new AccessPointStatusSummaryDao();
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2001");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2003");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("ON");
sum.setCountry("CA");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2004");
sum.setStatus(AccessPoint.Status.FUNCTIONING_OK);
dao.save(sum);
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2000");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2001");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2003");
sum.setStatus(AccessPoint.Status.FUNCTIONING_HIGH);
dao.save(sum);
sum = new AccessPointStatusSummary();
sum.setCommunity("NY");
sum.setCountry("US");
sum.setType(AccessPointType.WATER_POINT.toString());
sum.setYear("2004");
sum.setStatus(AccessPoint.Status.FUNCTIONING_OK);
dao.save(sum);
} else if ("createApHistory".equals(action)) {
GregorianCalendar cal = new GregorianCalendar();
AccessPointHelper apHelper = new AccessPointHelper();
AccessPoint ap = new AccessPoint();
cal.set(Calendar.YEAR, 2000);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(300l);
ap.setCostPer(43.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2001);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(317l);
ap.setCostPer(40.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2002);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(340l);
ap.setCostPer(37.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2003);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(340l);
ap.setCostPer(34.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2004);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Geneva");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(47.3);
ap.setLongitude(9d);
ap.setNumberOfHouseholdsUsingPoint(338l);
ap.setCostPer(38.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2000);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(170l);
ap.setCostPer(19.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2001);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(201l);
ap.setCostPer(19.00);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2002);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_HIGH);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(211l);
ap.setCostPer(17.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2003);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_WITH_PROBLEMS);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(220l);
ap.setCostPer(25.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
ap = new AccessPoint();
cal.set(Calendar.YEAR, 2004);
ap.setCollectionDate(cal.getTime());
ap.setCommunityCode("Omaha");
ap.setPointStatus(Status.FUNCTIONING_OK);
ap.setLatitude(40.87d);
ap.setLongitude(-95.2d);
ap.setNumberOfHouseholdsUsingPoint(175l);
ap.setCostPer(24.20);
ap.setPointType(AccessPointType.WATER_POINT);
apHelper.saveAccessPoint(ap);
} else if ("createQuestionLookup".equals(action)) {
SurveyDAO surveyDao = new SurveyDAO();
SurveyQuestion q = new SurveyQuestion();
q.setId("qm5");
q.setText("Technology Type");
q.setType(QuestionAnswerType.option);
surveyDao.save(q);
q = new SurveyQuestion();
q.setId("qm8");
q.setText("Is farthest household within 500m");
q.setType(QuestionAnswerType.option);
surveyDao.save(q);
q = new SurveyQuestion();
q.setId("qm9");
q.setText("Management Structure");
q.setType(QuestionAnswerType.option);
surveyDao.save(q);
q = new SurveyQuestion();
q.setId("qm10");
q.setText("Status");
q.setType(QuestionAnswerType.option);
surveyDao.save(q);
}
}
|
diff --git a/src/main/java/org/spout/vanilla/command/AdministrationCommands.java b/src/main/java/org/spout/vanilla/command/AdministrationCommands.java
index 05b641ae..27445018 100644
--- a/src/main/java/org/spout/vanilla/command/AdministrationCommands.java
+++ b/src/main/java/org/spout/vanilla/command/AdministrationCommands.java
@@ -1,214 +1,214 @@
/*
* This file is part of Vanilla (http://www.spout.org/).
*
* Vanilla is licensed under the SpoutDev License Version 1.
*
* Vanilla 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.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the SpoutDev License Version 1.
*
* Vanilla 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,
* the MIT license and the SpoutDev license version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license,
* including the MIT license.
*/
package org.spout.vanilla.command;
import java.util.Set;
import org.spout.api.Spout;
import org.spout.api.command.CommandContext;
import org.spout.api.command.CommandSource;
import org.spout.api.command.annotated.Command;
import org.spout.api.command.annotated.CommandPermissions;
import org.spout.api.exception.CommandException;
import org.spout.api.geo.cuboid.Chunk;
import org.spout.api.player.Player;
import org.spout.api.protocol.NetworkSynchronizer;
import org.spout.vanilla.VanillaPlugin;
/**
* Commands to emulate core Minecraft admin functions.
*/
public class AdministrationCommands {
public AdministrationCommands(VanillaPlugin plugin) {
}
@Command(aliases = {"gamemode", "gm"}, usage = "[player] <1|2> (1 = SURVIVAL, 2 = CREATIVE)", desc = "Change a player's gamemode", max = 2)
@CommandPermissions("vanilla.command.gamemode")
public void gamemode(CommandContext args, CommandSource source) throws CommandException {
// If source is player
if (args.length() == 1) {
if (source instanceof Player) {
Player sender = (Player) source;
if (this.isInteger(args.getString(0))) {
int mode = args.getInteger(0);
switch (mode) {
case 1:
source.sendMessage("Your gamemode has been switched to SURVIVAL.");
break; // TODO: Switch sender to survival
case 2:
source.sendMessage("Your gamemode has been switched to CREATIVE.");
break; // TODO: Switch sender to creative
default:
throw new CommandException("You must be a player to toggle your gamemode.");
}
} else if (args.getString(0).equalsIgnoreCase("creative")) {
source.sendMessage("Your gamemode has been switched to CREATIVE.");
// TODO: Switch sender to creative
} else if (args.getString(0).equalsIgnoreCase("survival")) {
source.sendMessage("Your gamemode has been switched to SURVIVAL.");
// TODO: Switch sender to survival
} else {
throw new CommandException("A gamemode must be either a number between 1 and 2, 'CREATIVE' or 'SURVIVAL'");
}
} else {
throw new CommandException("You must be a player to toggle your gamemode.");
}
}
// If source is not player
if (args.length() == 2) {
Player player = Spout.getGame().getPlayer(args.getString(0), true);
if (player != null) {
if (this.isInteger(args.getString(1))) {
int mode = args.getInteger(1);
switch (mode) {
case 1:
source.sendMessage(player.getName() + "'s gamemode has been switched to SURVIVAL.");
player.sendMessage("Your gamemode has been switched to SURVIVAL.");
break; // TODO: Switch player to survival
case 2:
- source.sendMessage(player.getName() + "'s gamemode has been switched to SURVIVAL.");
+ source.sendMessage(player.getName() + "'s gamemode has been switched to CREATIVE.");
player.sendMessage("Your gamemode has been switched to CREATIVE.");
break; // TODO: Switch player to creative
default:
throw new CommandException("A gamemode must be between 1 and 2.");
}
} else if (args.getString(1).equalsIgnoreCase("creative")) {
source.sendMessage(player.getName() + "'s gamemode has been switched to CREATIVE.");
player.sendMessage("Your gamemode has been switched to CREATIVE.");
// TODO: Switch player to creative
} else if (args.getString(1).equalsIgnoreCase("survival")) {
source.sendMessage(player.getName() + "'s gamemode has been switched to SURVIVAL.");
player.sendMessage("Your gamemode has been switched to SURVIVAL.");
// TODO: Switch player to survival
} else {
throw new CommandException("A gamemode must be either a number between 1 and 2, 'CREATIVE' or 'SURVIVAL'");
}
} else {
throw new CommandException(args.getString(0) + " is not online.");
}
}
}
@Command(aliases = "xp", usage = "[player] <amount>", desc = "Give/take experience from a player", max = 2)
@CommandPermissions("vanilla.command.xp")
public void xp(CommandContext args, CommandSource source) throws CommandException {
// If source is player
if (args.length() == 1) {
if (source instanceof Player) {
Player sender = (Player) source;
int amount = args.getInteger(0);
source.sendMessage("You have been given " + amount + " xp.");
// TODO: Give player 'amount' of xp.
} else {
throw new CommandException("You must be a player to give yourself xp.");
}
}
// If source is not player
if (args.length() == 2) {
Player player = Spout.getGame().getPlayer(args.getString(0), true);
if (player != null) {
int amount = args.getInteger(1);
player.sendMessage("You have been given " + amount + " xp.");
// TODO: Give player 'amount' of xp.
} else {
throw new CommandException(args.getString(0) + " is not online.");
}
}
}
@Command(aliases = "weather", usage = "<1|2|3> (1 = RAIN, 2 = SNOW, 3 = LIGHTNING)", desc = "Toggles weather on/off", max = 1)
@CommandPermissions("vanilla.command.weather")
public void weather(CommandContext args, CommandSource source) throws CommandException {
if (args.length() == 1) {
if (this.isInteger(args.getString(0))) {
int mode = args.getInteger(0);
switch (mode) {
case 1:
source.sendMessage("Weather set to RAIN.");
break; // TODO: Switch weather to rain
case 2:
source.sendMessage("Weather set to SNOW.");
break; // TODO: Switch weather to snow
case 3:
source.sendMessage("Weather set to LIGHTNING.");
break; // TODO: Start a storm
default:
throw new CommandException("Weather must be between 1 and 3.");
}
} else if (args.getString(0).equalsIgnoreCase("rain")) {
source.sendMessage("Weather set to RAIN.");
// TODO: Switch weather to rain.
} else if (args.getString(0).equalsIgnoreCase("snow")) {
source.sendMessage("Weather set to SNOW.");
// TODO: Switch weather to snow.
} else if (args.getString(0).equalsIgnoreCase("lightning")) {
source.sendMessage("Weather set to LIGHTNING.");
// TODO: Switch weather to lightning.
} else {
throw new CommandException("Weather must be a mode between 1 and 3, 'RAIN', 'SNOW', or 'LIGHTNING'");
}
}
}
public boolean isInteger(String arg) {
try {
Integer.parseInt(arg);
} catch (NumberFormatException e) {
return false;
}
return true;
}
@Command(aliases = "debug", usage = "[type] (/resend /resendall)", desc = "Debug commands", max = 1)
//@CommandPermissions("vanilla.command.debug")
public void debug(CommandContext args, CommandSource source) throws CommandException {
Player player = null;
if (source instanceof Player) {
player = (Player)source;
}
else {
player = Spout.getGame().getPlayer(args.getString(1, ""), true);
if (player == null) {
source.sendMessage("Must be a player or send player name in arguments");
return;
}
}
if (args.getString(0, "").contains("resendall")) {
NetworkSynchronizer network = player.getNetworkSynchronizer();
Set<Chunk> chunks = network.getActiveChunks();
for (Chunk c : chunks) {
network.sendChunk(c);
}
source.sendMessage("All chunks resent");
}
else if (args.getString(0, "").contains("resend")) {
player.getNetworkSynchronizer().sendChunk(player.getEntity().getChunk());
source.sendMessage("Chunk resent");
}
}
}
| true | true | public void gamemode(CommandContext args, CommandSource source) throws CommandException {
// If source is player
if (args.length() == 1) {
if (source instanceof Player) {
Player sender = (Player) source;
if (this.isInteger(args.getString(0))) {
int mode = args.getInteger(0);
switch (mode) {
case 1:
source.sendMessage("Your gamemode has been switched to SURVIVAL.");
break; // TODO: Switch sender to survival
case 2:
source.sendMessage("Your gamemode has been switched to CREATIVE.");
break; // TODO: Switch sender to creative
default:
throw new CommandException("You must be a player to toggle your gamemode.");
}
} else if (args.getString(0).equalsIgnoreCase("creative")) {
source.sendMessage("Your gamemode has been switched to CREATIVE.");
// TODO: Switch sender to creative
} else if (args.getString(0).equalsIgnoreCase("survival")) {
source.sendMessage("Your gamemode has been switched to SURVIVAL.");
// TODO: Switch sender to survival
} else {
throw new CommandException("A gamemode must be either a number between 1 and 2, 'CREATIVE' or 'SURVIVAL'");
}
} else {
throw new CommandException("You must be a player to toggle your gamemode.");
}
}
// If source is not player
if (args.length() == 2) {
Player player = Spout.getGame().getPlayer(args.getString(0), true);
if (player != null) {
if (this.isInteger(args.getString(1))) {
int mode = args.getInteger(1);
switch (mode) {
case 1:
source.sendMessage(player.getName() + "'s gamemode has been switched to SURVIVAL.");
player.sendMessage("Your gamemode has been switched to SURVIVAL.");
break; // TODO: Switch player to survival
case 2:
source.sendMessage(player.getName() + "'s gamemode has been switched to SURVIVAL.");
player.sendMessage("Your gamemode has been switched to CREATIVE.");
break; // TODO: Switch player to creative
default:
throw new CommandException("A gamemode must be between 1 and 2.");
}
} else if (args.getString(1).equalsIgnoreCase("creative")) {
source.sendMessage(player.getName() + "'s gamemode has been switched to CREATIVE.");
player.sendMessage("Your gamemode has been switched to CREATIVE.");
// TODO: Switch player to creative
} else if (args.getString(1).equalsIgnoreCase("survival")) {
source.sendMessage(player.getName() + "'s gamemode has been switched to SURVIVAL.");
player.sendMessage("Your gamemode has been switched to SURVIVAL.");
// TODO: Switch player to survival
} else {
throw new CommandException("A gamemode must be either a number between 1 and 2, 'CREATIVE' or 'SURVIVAL'");
}
} else {
throw new CommandException(args.getString(0) + " is not online.");
}
}
}
| public void gamemode(CommandContext args, CommandSource source) throws CommandException {
// If source is player
if (args.length() == 1) {
if (source instanceof Player) {
Player sender = (Player) source;
if (this.isInteger(args.getString(0))) {
int mode = args.getInteger(0);
switch (mode) {
case 1:
source.sendMessage("Your gamemode has been switched to SURVIVAL.");
break; // TODO: Switch sender to survival
case 2:
source.sendMessage("Your gamemode has been switched to CREATIVE.");
break; // TODO: Switch sender to creative
default:
throw new CommandException("You must be a player to toggle your gamemode.");
}
} else if (args.getString(0).equalsIgnoreCase("creative")) {
source.sendMessage("Your gamemode has been switched to CREATIVE.");
// TODO: Switch sender to creative
} else if (args.getString(0).equalsIgnoreCase("survival")) {
source.sendMessage("Your gamemode has been switched to SURVIVAL.");
// TODO: Switch sender to survival
} else {
throw new CommandException("A gamemode must be either a number between 1 and 2, 'CREATIVE' or 'SURVIVAL'");
}
} else {
throw new CommandException("You must be a player to toggle your gamemode.");
}
}
// If source is not player
if (args.length() == 2) {
Player player = Spout.getGame().getPlayer(args.getString(0), true);
if (player != null) {
if (this.isInteger(args.getString(1))) {
int mode = args.getInteger(1);
switch (mode) {
case 1:
source.sendMessage(player.getName() + "'s gamemode has been switched to SURVIVAL.");
player.sendMessage("Your gamemode has been switched to SURVIVAL.");
break; // TODO: Switch player to survival
case 2:
source.sendMessage(player.getName() + "'s gamemode has been switched to CREATIVE.");
player.sendMessage("Your gamemode has been switched to CREATIVE.");
break; // TODO: Switch player to creative
default:
throw new CommandException("A gamemode must be between 1 and 2.");
}
} else if (args.getString(1).equalsIgnoreCase("creative")) {
source.sendMessage(player.getName() + "'s gamemode has been switched to CREATIVE.");
player.sendMessage("Your gamemode has been switched to CREATIVE.");
// TODO: Switch player to creative
} else if (args.getString(1).equalsIgnoreCase("survival")) {
source.sendMessage(player.getName() + "'s gamemode has been switched to SURVIVAL.");
player.sendMessage("Your gamemode has been switched to SURVIVAL.");
// TODO: Switch player to survival
} else {
throw new CommandException("A gamemode must be either a number between 1 and 2, 'CREATIVE' or 'SURVIVAL'");
}
} else {
throw new CommandException(args.getString(0) + " is not online.");
}
}
}
|
diff --git a/src/main/java/org/delegator/engine/LoggedUserBean.java b/src/main/java/org/delegator/engine/LoggedUserBean.java
index 7e41109..6ef338a 100644
--- a/src/main/java/org/delegator/engine/LoggedUserBean.java
+++ b/src/main/java/org/delegator/engine/LoggedUserBean.java
@@ -1,50 +1,51 @@
package org.delegator.engine;
import javax.persistence.NoResultException;
import org.delegator.engine.HibernateUtils;
import org.delegator.entities.Employee;
import org.hibernate.Session;
public class LoggedUserBean implements LoggedUser {
private int _userEid;
private Employee emp;
public LoggedUserBean() {
}
public Employee getEmp() {
return emp;
}
public void setEmp(Employee emp) {
this.emp = emp;
}
public int get_UserEid() {
return _userEid;
}
public void set_UserEid(int userEid) {
_userEid = userEid;
}
public int isRegistered(String username, String password) {
try {
Session session = HibernateUtils.getSessionFactory().getCurrentSession();
+ session.beginTransaction();
emp = (Employee)session
.createQuery(
- "from Employee where username = :username and password = :password")
- .setParameter("username", username)
- .setParameter("password", Integer.valueOf(password))
+ "from Employee where userName = :u and password = :p")
+ .setParameter("u", username)
+ .setParameter("p", Integer.valueOf(password))
.uniqueResult();
if (emp != null) {
_userEid = emp.getEid();
return _userEid;
}
} catch (NoResultException ex) {
return -1;
}
return -1;
}
}
| false | true | public int isRegistered(String username, String password) {
try {
Session session = HibernateUtils.getSessionFactory().getCurrentSession();
emp = (Employee)session
.createQuery(
"from Employee where username = :username and password = :password")
.setParameter("username", username)
.setParameter("password", Integer.valueOf(password))
.uniqueResult();
if (emp != null) {
_userEid = emp.getEid();
return _userEid;
}
} catch (NoResultException ex) {
return -1;
}
return -1;
}
| public int isRegistered(String username, String password) {
try {
Session session = HibernateUtils.getSessionFactory().getCurrentSession();
session.beginTransaction();
emp = (Employee)session
.createQuery(
"from Employee where userName = :u and password = :p")
.setParameter("u", username)
.setParameter("p", Integer.valueOf(password))
.uniqueResult();
if (emp != null) {
_userEid = emp.getEid();
return _userEid;
}
} catch (NoResultException ex) {
return -1;
}
return -1;
}
|
diff --git a/addon/src/test/java/com/vaadin/addon/charts/demoandtestapp/lineandscatter/SplineWithSymbols.java b/addon/src/test/java/com/vaadin/addon/charts/demoandtestapp/lineandscatter/SplineWithSymbols.java
index d400f412..03fdcb88 100644
--- a/addon/src/test/java/com/vaadin/addon/charts/demoandtestapp/lineandscatter/SplineWithSymbols.java
+++ b/addon/src/test/java/com/vaadin/addon/charts/demoandtestapp/lineandscatter/SplineWithSymbols.java
@@ -1,94 +1,94 @@
package com.vaadin.addon.charts.demoandtestapp.lineandscatter;
import com.vaadin.addon.charts.Chart;
import com.vaadin.addon.charts.demoandtestapp.AbstractVaadinChartExample;
import com.vaadin.addon.charts.model.Axis;
import com.vaadin.addon.charts.model.ChartType;
import com.vaadin.addon.charts.model.Configuration;
import com.vaadin.addon.charts.model.DataSeries;
import com.vaadin.addon.charts.model.Labels;
import com.vaadin.addon.charts.model.Marker;
import com.vaadin.addon.charts.model.MarkerSymbolEnum;
import com.vaadin.addon.charts.model.MarkerSymbolUrl;
import com.vaadin.addon.charts.model.PlotOptionsSpline;
import com.vaadin.addon.charts.model.Title;
import com.vaadin.addon.charts.model.style.SolidColor;
import com.vaadin.ui.Component;
public class SplineWithSymbols extends AbstractVaadinChartExample {
@Override
public String getDescription() {
return "Spline With Symbols";
}
@Override
protected Component getChart() {
Chart chart = new Chart();
chart.setHeight("450px");
chart.setWidth("100%");
Configuration configuration = new Configuration();
configuration.getChart().setType(ChartType.SPLINE);
configuration.getTitle().setText("Monthly Average Temperature");
configuration.getSubTitle().setText("Source: WorldClimate.com");
configuration.getxAxis().setCategories("Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
Axis yAxis = configuration.getyAxis();
yAxis.setTitle(new Title("Temperature"));
Labels labels = new Labels();
labels.setFormatter("this.value +'°'");
yAxis.setLabels(labels);
configuration.getTooltip().setShared(true);
configuration.getTooltip().setCrosshairs(true);
PlotOptionsSpline plotOptions = new PlotOptionsSpline();
configuration.setPlotOptions(plotOptions);
plotOptions.setMarker(new Marker(true));
plotOptions.getMarker().setRadius(4);
plotOptions.getMarker()
.setLineColor(new SolidColor("#666666"));
plotOptions.getMarker().setLineWidth(1);
DataSeries ls = new DataSeries();
plotOptions = new PlotOptionsSpline();
Marker marker = new Marker();
marker.setSymbol(MarkerSymbolEnum.SQUARE);
plotOptions.setMarker(marker);
ls.setPlotOptions(plotOptions);
ls.setName("Tokyo");
ls.setData(7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3,
13.9, 9.6);
ls.get("26.5")
.getMarker()
.setSymbol(
new MarkerSymbolUrl(
- "url(http://www.highcharts.com/demo/gfx/sun.png)"));
+ "http://www.highcharts.com/demo/gfx/sun.png"));
configuration.addSeries(ls);
ls = new DataSeries();
plotOptions = new PlotOptionsSpline();
marker = new Marker();
marker.setSymbol(MarkerSymbolEnum.DIAMOND);
plotOptions.setMarker(marker);
ls.setPlotOptions(plotOptions);
ls.setName("London");
ls.setData(3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6,
4.8);
ls.get("3.9")
.getMarker()
.setSymbol(
new MarkerSymbolUrl(
- "url(http://www.highcharts.com/demo/gfx/snow.png)"));
+ "http://www.highcharts.com/demo/gfx/snow.png"));
configuration.addSeries(ls);
chart.drawChart(configuration);
return chart;
}
}
| false | true | protected Component getChart() {
Chart chart = new Chart();
chart.setHeight("450px");
chart.setWidth("100%");
Configuration configuration = new Configuration();
configuration.getChart().setType(ChartType.SPLINE);
configuration.getTitle().setText("Monthly Average Temperature");
configuration.getSubTitle().setText("Source: WorldClimate.com");
configuration.getxAxis().setCategories("Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
Axis yAxis = configuration.getyAxis();
yAxis.setTitle(new Title("Temperature"));
Labels labels = new Labels();
labels.setFormatter("this.value +'°'");
yAxis.setLabels(labels);
configuration.getTooltip().setShared(true);
configuration.getTooltip().setCrosshairs(true);
PlotOptionsSpline plotOptions = new PlotOptionsSpline();
configuration.setPlotOptions(plotOptions);
plotOptions.setMarker(new Marker(true));
plotOptions.getMarker().setRadius(4);
plotOptions.getMarker()
.setLineColor(new SolidColor("#666666"));
plotOptions.getMarker().setLineWidth(1);
DataSeries ls = new DataSeries();
plotOptions = new PlotOptionsSpline();
Marker marker = new Marker();
marker.setSymbol(MarkerSymbolEnum.SQUARE);
plotOptions.setMarker(marker);
ls.setPlotOptions(plotOptions);
ls.setName("Tokyo");
ls.setData(7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3,
13.9, 9.6);
ls.get("26.5")
.getMarker()
.setSymbol(
new MarkerSymbolUrl(
"url(http://www.highcharts.com/demo/gfx/sun.png)"));
configuration.addSeries(ls);
ls = new DataSeries();
plotOptions = new PlotOptionsSpline();
marker = new Marker();
marker.setSymbol(MarkerSymbolEnum.DIAMOND);
plotOptions.setMarker(marker);
ls.setPlotOptions(plotOptions);
ls.setName("London");
ls.setData(3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6,
4.8);
ls.get("3.9")
.getMarker()
.setSymbol(
new MarkerSymbolUrl(
"url(http://www.highcharts.com/demo/gfx/snow.png)"));
configuration.addSeries(ls);
chart.drawChart(configuration);
return chart;
}
| protected Component getChart() {
Chart chart = new Chart();
chart.setHeight("450px");
chart.setWidth("100%");
Configuration configuration = new Configuration();
configuration.getChart().setType(ChartType.SPLINE);
configuration.getTitle().setText("Monthly Average Temperature");
configuration.getSubTitle().setText("Source: WorldClimate.com");
configuration.getxAxis().setCategories("Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
Axis yAxis = configuration.getyAxis();
yAxis.setTitle(new Title("Temperature"));
Labels labels = new Labels();
labels.setFormatter("this.value +'°'");
yAxis.setLabels(labels);
configuration.getTooltip().setShared(true);
configuration.getTooltip().setCrosshairs(true);
PlotOptionsSpline plotOptions = new PlotOptionsSpline();
configuration.setPlotOptions(plotOptions);
plotOptions.setMarker(new Marker(true));
plotOptions.getMarker().setRadius(4);
plotOptions.getMarker()
.setLineColor(new SolidColor("#666666"));
plotOptions.getMarker().setLineWidth(1);
DataSeries ls = new DataSeries();
plotOptions = new PlotOptionsSpline();
Marker marker = new Marker();
marker.setSymbol(MarkerSymbolEnum.SQUARE);
plotOptions.setMarker(marker);
ls.setPlotOptions(plotOptions);
ls.setName("Tokyo");
ls.setData(7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3,
13.9, 9.6);
ls.get("26.5")
.getMarker()
.setSymbol(
new MarkerSymbolUrl(
"http://www.highcharts.com/demo/gfx/sun.png"));
configuration.addSeries(ls);
ls = new DataSeries();
plotOptions = new PlotOptionsSpline();
marker = new Marker();
marker.setSymbol(MarkerSymbolEnum.DIAMOND);
plotOptions.setMarker(marker);
ls.setPlotOptions(plotOptions);
ls.setName("London");
ls.setData(3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6,
4.8);
ls.get("3.9")
.getMarker()
.setSymbol(
new MarkerSymbolUrl(
"http://www.highcharts.com/demo/gfx/snow.png"));
configuration.addSeries(ls);
chart.drawChart(configuration);
return chart;
}
|
diff --git a/src/core/schedule/DailySchedule.java b/src/core/schedule/DailySchedule.java
index 8201150..910ddc8 100644
--- a/src/core/schedule/DailySchedule.java
+++ b/src/core/schedule/DailySchedule.java
@@ -1,158 +1,159 @@
package core.schedule;
import core.schedule.task.Task;
import core.utils.Hour;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* La clase {@code DayliSchedule} es un schedule para un día completo.
* Se pueden schedulear multiples {@code Task}s durante el día, pero solo puede
* existir una(1) task por momento del día.
* @author kiira
* @version 1.0
*/
public class DailySchedule extends Schedule {
/** Estructura de datos que mantiene las {@code Task}s scheduleadas. */
private SortedSet<Task> tasks;
/**
* Inicializa el schedule.
*/
public DailySchedule() {
this.tasks = new TreeSet<Task>();
}
/**
* Permite crear un tarea básica y asignarla al {@code DailySchedule}.
* @param init horario de inicio de la tarea.
* @param end horario de fin de la tarea.
* @param desc descripcion de la tarea.
* @return {@code true} si la tarea se pudo crear y asignar correctamente
* (si el período indicado por la tarea no esta ocupado);
* {@code false} si la tarea no se pudo crear y asignar correctamente.
*/
public boolean createTask( Hour init, Hour end, String desc ) {
Task newTask = new Task( init, end, desc );
return this.addTask( newTask );
}
/**
* {@inheritDoc}
*/
@Override
public boolean addTask( Task task ) {
boolean res = this.isPeriodAvailable( task.getInitHour(),
task.getEndHour() );
if ( res )
this.tasks.add( task );
return res;
}
/**
* {@inheritDoc}
*/
@Override
public boolean removeTask( Task task ) {
boolean res = this.tasks.remove( task );
if ( res )
task.delete();
return res;
}
/**
* Indica si el período de tiempo establecido se encuentra libre en el
* schedule.
* @param init horario de inicio del período.
* @param end horario de fin del período.
* @return {@code true} si el período de tiempo esta disponible.;
* {@code false} si el periodo de tiempo no esta disponible.
*/
private boolean isPeriodAvailable( Hour init, Hour end ) {
boolean res = true;
//recorremos las tasks
for ( Task t : this.tasks ) {
//comprobamos si la task transcurre DURANTE el horario inicial
if ( t.isTranscurringAt( init ) )
res = false;
//sino, comprobamos si la task transcurre después del horario
//inicial
else if ( t.isAfter( init ) ) {
//y si es así, comprobamos si la tarea termina antes del horario
//final, o si incluye el horario final
if ( t.isTranscurringAt( end ) || t.isBefore( end ) )
res = false;
- } //si llegamos a esta instancia, la tarea transcurre ANTES del
- //horario inicial, por lo tanto no tiene sentido seguir analizando
- else
+ }
+ //si comprobamos que la tarea ocurre luego de terminar el periodo
+ //no es necesario segir analizando
+ else if ( t.isAfter( end ) )
break;
//finalmente, salimos del ciclo si ya comprobamos que el periodo
//no esta disponible
if ( !res )
break;
}
return res;
}
/**
* Devuelve la tarea específica que está scheduleada para el horario
* indicado, o {@code null} en caso de no existir.
* @param hour horario a comprobar.
* @return la {@code Task} correspondiente al horario o {@code null} en
* caso de no existir una asignada.
*/
public Task taskAtTime( Hour hour ) {
Task finded = null;
for ( Task t : this.tasks )
if ( t.isTranscurringAt( hour ) ) {
finded = t;
break;
} else if ( t.isBefore( hour ) )
break;
return finded;
}
/**
* {@inheritDoc}
*/
@Override
public Iterator<Task> iterator() {
return this.tasks.iterator();
}
/**
* {@inheritDoc}
*/
@Override
public int size() {
return this.tasks.size();
}
/**
* Representa este schedule en forma de una lista simple y ordenada de las
* tareas scheduleadas, en orden temporal.
* @return representación en forma de {@code String} de este schedule.
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder( "Schedule:\n" );
for ( Task t : this.tasks )
builder.append( '*' ).append( t.toString() ).append( "\n" );
return builder.toString();
}
}
| true | true | private boolean isPeriodAvailable( Hour init, Hour end ) {
boolean res = true;
//recorremos las tasks
for ( Task t : this.tasks ) {
//comprobamos si la task transcurre DURANTE el horario inicial
if ( t.isTranscurringAt( init ) )
res = false;
//sino, comprobamos si la task transcurre después del horario
//inicial
else if ( t.isAfter( init ) ) {
//y si es así, comprobamos si la tarea termina antes del horario
//final, o si incluye el horario final
if ( t.isTranscurringAt( end ) || t.isBefore( end ) )
res = false;
} //si llegamos a esta instancia, la tarea transcurre ANTES del
//horario inicial, por lo tanto no tiene sentido seguir analizando
else
break;
//finalmente, salimos del ciclo si ya comprobamos que el periodo
//no esta disponible
if ( !res )
break;
}
return res;
}
| private boolean isPeriodAvailable( Hour init, Hour end ) {
boolean res = true;
//recorremos las tasks
for ( Task t : this.tasks ) {
//comprobamos si la task transcurre DURANTE el horario inicial
if ( t.isTranscurringAt( init ) )
res = false;
//sino, comprobamos si la task transcurre después del horario
//inicial
else if ( t.isAfter( init ) ) {
//y si es así, comprobamos si la tarea termina antes del horario
//final, o si incluye el horario final
if ( t.isTranscurringAt( end ) || t.isBefore( end ) )
res = false;
}
//si comprobamos que la tarea ocurre luego de terminar el periodo
//no es necesario segir analizando
else if ( t.isAfter( end ) )
break;
//finalmente, salimos del ciclo si ya comprobamos que el periodo
//no esta disponible
if ( !res )
break;
}
return res;
}
|
diff --git a/src/main/java/org/osiam/resources/scim/User.java b/src/main/java/org/osiam/resources/scim/User.java
index fdcd34b..5fe296b 100644
--- a/src/main/java/org/osiam/resources/scim/User.java
+++ b/src/main/java/org/osiam/resources/scim/User.java
@@ -1,458 +1,458 @@
/*
* Copyright (C) 2013 tarent AG
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.osiam.resources.scim;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* <p>Java class for User complex type.
* <p/>
* <p>The following schema fragment specifies the expected content contained within this class.
*/
@JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY)
public class User extends CoreResource {
private String userName;
private Name name;
private String displayName;
private String nickName;
private String profileUrl;
private String title;
private String userType;
private String preferredLanguage;
private String locale;
private String timezone;
private Boolean active;
private String password;
private List<MultiValuedAttribute> emails;
private List<MultiValuedAttribute> phoneNumbers;
private List<MultiValuedAttribute> ims;
private List<MultiValuedAttribute> photos;
private List<Address> addresses;
private List<MultiValuedAttribute> groups;
private List<MultiValuedAttribute> entitlements;
private List<MultiValuedAttribute> roles;
private List<MultiValuedAttribute> x509Certificates;
private Set<Object> any;
public User() {
}
private User(Builder builder) {
super(builder);
this.userName = builder.userName;
this.name = builder.name;
this.displayName = builder.displayName;
this.nickName = builder.nickName;
this.profileUrl = builder.profileUrl;
this.title = builder.title;
this.userType = builder.userType;
this.preferredLanguage = builder.preferredLanguage;
this.locale = builder.locale;
this.timezone = builder.timezone;
this.active = builder.active;
this.password = builder.password;
this.emails = builder.emails;
this.phoneNumbers = builder.phoneNumbers;
this.ims = builder.ims;
this.photos = builder.photos;
this.addresses = builder.addresses;
this.groups = builder.groups;
this.entitlements = builder.entitlements;
this.roles = builder.roles;
this.x509Certificates = builder.x509Certificates;
this.any = builder.any;
}
/**
* Gets the value of the userName property.
*
* @return possible object is
* {@link String }
*/
public String getUserName() {
return userName;
}
/**
* Gets the value of the name property.
*
* @return possible object is
* {@link Name }
*/
public Name getName() {
return name;
}
/**
* Gets the value of the displayName property.
*
* @return possible object is
* {@link String }
*/
public String getDisplayName() {
return displayName;
}
/**
* Gets the value of the nickName property.
*
* @return possible object is
* {@link String }
*/
public String getNickName() {
return nickName;
}
/**
* Gets the value of the profileUrl property.
*
* @return possible object is
* {@link String }
*/
public String getProfileUrl() {
return profileUrl;
}
/**
* Gets the value of the title property.
*
* @return possible object is
* {@link String }
*/
public String getTitle() {
return title;
}
/**
* Gets the value of the userType property.
*
* @return possible object is
* {@link String }
*/
public String getUserType() {
return userType;
}
/**
* Gets the value of the preferredLanguage property.
*
* @return possible object is
* {@link String }
*/
public String getPreferredLanguage() {
return preferredLanguage;
}
/**
* Gets the value of the locale property.
*
* @return possible object is
* {@link String }
*/
public String getLocale() {
return locale;
}
/**
* Gets the value of the timezone property.
*
* @return possible object is
* {@link String }
*/
public String getTimezone() {
return timezone;
}
/**
* Gets the value of the active property.
*
* @return possible object is
* {@link Boolean }
*/
public Boolean isActive() {
return active;
}
/**
* Gets the value of the password property.
*
* @return possible object is
* {@link String }
*/
public String getPassword() {
return password;
}
public List<MultiValuedAttribute> getEmails() {
return emails;
}
public List<MultiValuedAttribute> getPhoneNumbers() {
return phoneNumbers;
}
public List<MultiValuedAttribute> getIms() {
return ims;
}
public List<MultiValuedAttribute> getPhotos() {
return photos;
}
public List<Address> getAddresses() {
return addresses;
}
public List<MultiValuedAttribute> getGroups() {
return groups;
}
public List<MultiValuedAttribute> getEntitlements() {
return entitlements;
}
public List<MultiValuedAttribute> getRoles() {
return roles;
}
public List<MultiValuedAttribute> getX509Certificates() {
return x509Certificates;
}
/**
* Gets the value of the any property.
* <p/>
* <p/>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the any property.
* <p/>
* <p/>
* For example, to add a new item, do as follows:
* <pre>
* getAny().add(newItem);
* </pre>
* <p/>
* <p/>
* <p/>
* Objects of the following type(s) are allowed in the list
* {@link Object }
*/
public Set<Object> getAny() {
return this.any;
}
public static class Builder extends CoreResource.Builder {
private final String userName;
private String password;
private Boolean active;
private String timezone;
private String locale;
private String preferredLanguage;
private String userType;
private String title;
private String profileUrl;
private String nickName;
private String displayName;
private Name name;
private List<MultiValuedAttribute> emails = new ArrayList<>();
private List<MultiValuedAttribute> phoneNumbers = new ArrayList<>();
private List<MultiValuedAttribute> ims = new ArrayList<>();
private List<MultiValuedAttribute> photos = new ArrayList<>();
private List<Address> addresses = new ArrayList<>();
private List<MultiValuedAttribute> groups = new ArrayList<>();
private List<MultiValuedAttribute> entitlements = new ArrayList<>();
private List<MultiValuedAttribute> roles = new ArrayList<>();
private List<MultiValuedAttribute> x509Certificates = new ArrayList<>();
private Set<Object> any;
public Builder(String userName) {
if (userName == null) { throw new IllegalArgumentException("userName must not be null."); }
this.userName = userName;
}
public Builder() {
this.userName = null;
}
/**
* This class is for generating the output of an User. It does not copy the password and it checks for empty
* lists; if a list is empty it will be nulled so that json-mapping will ignore it.
*
* @param user
* @return new (filtered) {@link User} object
*/
- public static User generateForOuput(User user) {
+ public static User generateForOutput(User user) {
if (user == null) {
return null;
}
Builder builder = new Builder(user.userName);
builder.id = user.getId();
builder.meta = user.getMeta();
builder.externalId = user.getExternalId();
builder.name = user.name;
builder.displayName = user.displayName;
builder.nickName = user.nickName;
builder.profileUrl = user.profileUrl;
builder.title = user.title;
builder.userType = user.userType;
builder.preferredLanguage = user.preferredLanguage;
builder.locale = user.locale;
builder.timezone = user.timezone;
builder.active = user.active;
// null lists when empty
builder.emails = user.emails;
builder.phoneNumbers = user.phoneNumbers;
builder.ims = user.ims;
builder.photos = user.photos;
builder.addresses =user.addresses;
builder.groups = user.groups;
builder.entitlements = user.entitlements ;
builder.roles = user.roles;
builder.x509Certificates = user.x509Certificates;
builder.any = user.any;
builder.schemas = user.getSchemas();
return builder.build();
}
public Builder setName(Name name) {
this.name = name;
return this;
}
public Builder setDisplayName(String displayName) {
this.displayName = displayName;
return this;
}
public Builder setNickName(String nickName) {
this.nickName = nickName;
return this;
}
public Builder setProfileUrl(String profileUrl) {
this.profileUrl = profileUrl;
return this;
}
public Builder setTitle(String title) {
this.title = title;
return this;
}
public Builder setUserType(String userType) {
this.userType = userType;
return this;
}
public Builder setPreferredLanguage(String preferredLanguage) {
this.preferredLanguage = preferredLanguage;
return this;
}
public Builder setLocale(String locale) {
this.locale = locale;
return this;
}
public Builder setTimezone(String timezone) {
this.timezone = timezone;
return this;
}
public Builder setActive(Boolean active) {
this.active = active;
return this;
}
public Builder setPassword(String password) {
this.password = password;
return this;
}
public Builder setEmails(List<MultiValuedAttribute> emails) {
this.emails = emails;
return this;
}
public Builder setPhoneNumbers(List<MultiValuedAttribute> phoneNumbers) {
this.phoneNumbers = phoneNumbers;
return this;
}
public Builder setIms(List<MultiValuedAttribute> ims) {
this.ims = ims;
return this;
}
public Builder setPhotos(List<MultiValuedAttribute> photos) {
this.photos = photos;
return this;
}
public Builder setAddresses(List<Address> addresses) {
this.addresses = addresses;
return this;
}
public Builder setGroups(List<MultiValuedAttribute> groups) {
this.groups = groups;
return this;
}
public Builder setEntitlements(List<MultiValuedAttribute> entitlements) {
this.entitlements = entitlements;
return this;
}
public Builder setRoles(List<MultiValuedAttribute> roles) {
this.roles = roles;
return this;
}
public Builder setX509Certificates(List<MultiValuedAttribute> x509Certificates) {
this.x509Certificates = x509Certificates;
return this;
}
public Builder setAny(Set<Object> any) {
this.any = any;
return this;
}
@Override
public User build() {
return new User(this);
}
}
}
| true | true | public static User generateForOuput(User user) {
if (user == null) {
return null;
}
Builder builder = new Builder(user.userName);
builder.id = user.getId();
builder.meta = user.getMeta();
builder.externalId = user.getExternalId();
builder.name = user.name;
builder.displayName = user.displayName;
builder.nickName = user.nickName;
builder.profileUrl = user.profileUrl;
builder.title = user.title;
builder.userType = user.userType;
builder.preferredLanguage = user.preferredLanguage;
builder.locale = user.locale;
builder.timezone = user.timezone;
builder.active = user.active;
// null lists when empty
builder.emails = user.emails;
builder.phoneNumbers = user.phoneNumbers;
builder.ims = user.ims;
builder.photos = user.photos;
builder.addresses =user.addresses;
builder.groups = user.groups;
builder.entitlements = user.entitlements ;
builder.roles = user.roles;
builder.x509Certificates = user.x509Certificates;
builder.any = user.any;
builder.schemas = user.getSchemas();
return builder.build();
}
| public static User generateForOutput(User user) {
if (user == null) {
return null;
}
Builder builder = new Builder(user.userName);
builder.id = user.getId();
builder.meta = user.getMeta();
builder.externalId = user.getExternalId();
builder.name = user.name;
builder.displayName = user.displayName;
builder.nickName = user.nickName;
builder.profileUrl = user.profileUrl;
builder.title = user.title;
builder.userType = user.userType;
builder.preferredLanguage = user.preferredLanguage;
builder.locale = user.locale;
builder.timezone = user.timezone;
builder.active = user.active;
// null lists when empty
builder.emails = user.emails;
builder.phoneNumbers = user.phoneNumbers;
builder.ims = user.ims;
builder.photos = user.photos;
builder.addresses =user.addresses;
builder.groups = user.groups;
builder.entitlements = user.entitlements ;
builder.roles = user.roles;
builder.x509Certificates = user.x509Certificates;
builder.any = user.any;
builder.schemas = user.getSchemas();
return builder.build();
}
|
diff --git a/modules/auth/org/molgenis/auth/ui/form/DatabaseAuthenticationForm.java b/modules/auth/org/molgenis/auth/ui/form/DatabaseAuthenticationForm.java
index 1368891dd..68bfda9ec 100644
--- a/modules/auth/org/molgenis/auth/ui/form/DatabaseAuthenticationForm.java
+++ b/modules/auth/org/molgenis/auth/ui/form/DatabaseAuthenticationForm.java
@@ -1,28 +1,30 @@
package org.molgenis.auth.ui.form;
import org.molgenis.framework.ui.html.ActionInput;
import org.molgenis.framework.ui.html.Container;
import org.molgenis.framework.ui.html.PasswordInput;
import org.molgenis.framework.ui.html.StringInput;
public class DatabaseAuthenticationForm extends Container
{
private static final long serialVersionUID = 798533925465868923L;
public DatabaseAuthenticationForm()
{
StringInput usernameInput = new StringInput("username");
usernameInput.setNillable(false);
+ usernameInput.setDescription("The name of a registered user.");
this.add(usernameInput);
PasswordInput passwordInput = new PasswordInput("password");
passwordInput.setNillable(false);
+ passwordInput.setDescription("The password of a registered user."); //FIXME: does not show
this.add(passwordInput);
ActionInput loginInput = new ActionInput("Login");
loginInput.setTooltip("Login");
this.add(loginInput);
ActionInput logoutInput = new ActionInput("Logout");
logoutInput.setTooltip("Logout");
this.add(logoutInput);
}
}
| false | true | public DatabaseAuthenticationForm()
{
StringInput usernameInput = new StringInput("username");
usernameInput.setNillable(false);
this.add(usernameInput);
PasswordInput passwordInput = new PasswordInput("password");
passwordInput.setNillable(false);
this.add(passwordInput);
ActionInput loginInput = new ActionInput("Login");
loginInput.setTooltip("Login");
this.add(loginInput);
ActionInput logoutInput = new ActionInput("Logout");
logoutInput.setTooltip("Logout");
this.add(logoutInput);
}
| public DatabaseAuthenticationForm()
{
StringInput usernameInput = new StringInput("username");
usernameInput.setNillable(false);
usernameInput.setDescription("The name of a registered user.");
this.add(usernameInput);
PasswordInput passwordInput = new PasswordInput("password");
passwordInput.setNillable(false);
passwordInput.setDescription("The password of a registered user."); //FIXME: does not show
this.add(passwordInput);
ActionInput loginInput = new ActionInput("Login");
loginInput.setTooltip("Login");
this.add(loginInput);
ActionInput logoutInput = new ActionInput("Logout");
logoutInput.setTooltip("Logout");
this.add(logoutInput);
}
|
diff --git a/h2/src/main/org/h2/server/web/DbContextRule.java b/h2/src/main/org/h2/server/web/DbContextRule.java
index 84675b910..71624689d 100644
--- a/h2/src/main/org/h2/server/web/DbContextRule.java
+++ b/h2/src/main/org/h2/server/web/DbContextRule.java
@@ -1,481 +1,480 @@
/*
* Copyright 2004-2010 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.server.web;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import org.h2.bnf.BnfVisitor;
import org.h2.bnf.Rule;
import org.h2.bnf.RuleHead;
import org.h2.bnf.Sentence;
import org.h2.command.Parser;
import org.h2.message.DbException;
import org.h2.util.New;
import org.h2.util.StringUtils;
/**
* A BNF terminal rule that is linked to the database context information.
* This class is used by the H2 Console, to support auto-complete.
*/
public class DbContextRule implements Rule {
static final int COLUMN = 0, TABLE = 1, TABLE_ALIAS = 2;
static final int NEW_TABLE_ALIAS = 3;
static final int COLUMN_ALIAS = 4, SCHEMA = 5;
private static final boolean SUGGEST_TABLE_ALIAS = false;
private DbContents contents;
private int type;
DbContextRule(DbContents contents, int type) {
this.contents = contents;
this.type = type;
}
public String toString() {
switch (type) {
case SCHEMA:
return "schema";
case TABLE:
return "table";
case NEW_TABLE_ALIAS:
return "nt";
case TABLE_ALIAS:
return "t";
case COLUMN_ALIAS:
return "c";
case COLUMN:
return "column";
default:
return "?";
}
}
public String name() {
return null;
}
public void setLinks(HashMap<String, RuleHead> ruleMap) {
// nothing to do
}
public void addNextTokenList(Sentence sentence) {
switch (type) {
case SCHEMA:
addSchema(sentence);
break;
case TABLE:
addTable(sentence);
break;
case NEW_TABLE_ALIAS:
addNewTableAlias(sentence);
break;
case TABLE_ALIAS:
addTableAlias(sentence);
break;
case COLUMN_ALIAS:
// addColumnAlias(query, sentence);
// break;
case COLUMN:
addColumn(sentence);
break;
default:
}
}
private void addTableAlias(Sentence sentence) {
String query = sentence.getQuery();
String q = StringUtils.toUpperEnglish(query.trim());
HashMap<String, DbTableOrView> map = sentence.getAliases();
HashSet<String> set = New.hashSet();
if (map != null) {
for (Map.Entry<String, DbTableOrView> entry : map.entrySet()) {
String alias = entry.getKey();
DbTableOrView table = entry.getValue();
set.add(StringUtils.toUpperEnglish(table.name));
if (q.length() == 0 || alias.startsWith(q)) {
if (q.length() < alias.length()) {
sentence.add(alias + ".", alias.substring(q.length()) + ".", Sentence.CONTEXT);
}
}
}
}
HashSet<DbTableOrView> tables = sentence.getTables();
if (tables != null) {
for (DbTableOrView table : tables) {
String tableName = StringUtils.toUpperEnglish(table.name);
//DbTableOrView[] tables = contents.defaultSchema.tables;
//for(int i=0; i<tables.length; i++) {
// DbTableOrView table = tables[i];
// String tableName = StringUtils.toUpperEnglish(table.name);
if (!set.contains(tableName)) {
if (q.length() == 0 || tableName.startsWith(q)) {
if (q.length() < tableName.length()) {
sentence.add(tableName + ".", tableName.substring(q.length()) + ".", Sentence.CONTEXT);
}
}
}
}
}
}
private void addNewTableAlias(Sentence sentence) {
if (SUGGEST_TABLE_ALIAS) {
// good for testing!
String query = sentence.getQuery();
if (query.length() > 3) {
return;
}
String lastTableName = StringUtils.toUpperEnglish(sentence.getLastTable().name);
if (lastTableName == null) {
return;
}
HashMap<String, DbTableOrView> map = sentence.getAliases();
String shortName = lastTableName.substring(0, 1);
if (map != null && map.containsKey(shortName)) {
int result = 0;
for (int i = 1;; i++) {
if (!map.containsKey(shortName + i)) {
result = i;
break;
}
}
shortName += result;
}
String q = StringUtils.toUpperEnglish(query.trim());
if (q.length() == 0 || StringUtils.toUpperEnglish(shortName).startsWith(q)) {
if (q.length() < shortName.length()) {
sentence.add(shortName, shortName.substring(q.length()), Sentence.CONTEXT);
}
}
}
}
// private boolean startWithIgnoreCase(String a, String b) {
// if(a.length() < b.length()) {
// return false;
// }
// for(int i=0; i<b.length(); i++) {
// if(Character.toUpperCase(a.charAt(i))
// != Character.toUpperCase(b.charAt(i))) {
// return false;
// }
// }
// return true;
// }
private void addSchema(Sentence sentence) {
String query = sentence.getQuery();
String q = StringUtils.toUpperEnglish(query);
if (q.trim().length() == 0) {
q = q.trim();
}
for (DbSchema schema : contents.schemas) {
if (schema == contents.defaultSchema) {
continue;
}
if (q.length() == 0 || StringUtils.toUpperEnglish(schema.name).startsWith(q)) {
if (q.length() < schema.quotedName.length()) {
sentence.add(schema.quotedName + ".", schema.quotedName.substring(q.length()) + ".", Sentence.CONTEXT);
}
}
}
}
private void addTable(Sentence sentence) {
String query = sentence.getQuery();
DbSchema schema = sentence.getLastMatchedSchema();
if (schema == null) {
schema = contents.defaultSchema;
}
String q = StringUtils.toUpperEnglish(query);
if (q.trim().length() == 0) {
q = q.trim();
}
for (DbTableOrView table : schema.tables) {
if (q.length() == 0 || StringUtils.toUpperEnglish(table.name).startsWith(q)) {
if (q.length() < table.quotedName.length()) {
sentence.add(table.quotedName, table.quotedName.substring(q.length()), Sentence.CONTEXT);
}
}
}
}
private void addColumn(Sentence sentence) {
String query = sentence.getQuery();
String tableName = query;
String columnPattern = "";
if (query.trim().length() == 0) {
tableName = null;
} else {
tableName = StringUtils.toUpperEnglish(query.trim());
if (tableName.endsWith(".")) {
tableName = tableName.substring(0, tableName.length() - 1);
} else {
columnPattern = StringUtils.toUpperEnglish(query.trim());
tableName = null;
}
}
HashSet<DbTableOrView> set = null;
HashMap<String, DbTableOrView> aliases = sentence.getAliases();
if (tableName == null && sentence.getTables() != null) {
set = sentence.getTables();
}
DbTableOrView table = null;
if (tableName != null && aliases != null && aliases.get(tableName) != null) {
table = aliases.get(tableName);
tableName = StringUtils.toUpperEnglish(table.name);
}
if (tableName == null) {
if (set == null && aliases == null) {
return;
}
if ((set != null && set.size() > 1) || (aliases != null && aliases.size() > 1)) {
return;
}
}
if (table == null) {
for (DbTableOrView tab : contents.defaultSchema.tables) {
String t = StringUtils.toUpperEnglish(tab.name);
if (tableName != null && !tableName.equals(t)) {
continue;
}
if (set != null && !set.contains(tab)) {
continue;
}
table = tab;
break;
}
}
if (table != null && table.columns != null) {
for (DbColumn column : table.columns) {
String columnName = column.name;
if (!StringUtils.toUpperEnglish(columnName).startsWith(columnPattern)) {
continue;
}
if (columnPattern.length() < columnName.length()) {
String sub = columnName.substring(columnPattern.length());
if (sub.equals(columnName) && contents.needsQuotes(columnName)) {
columnName = StringUtils.quoteIdentifier(columnName);
sub = columnName;
}
-System.out.println("add " + columnName + " " + columnName.substring(columnPattern.length()));
sentence.add(columnName, sub, Sentence.CONTEXT);
}
}
}
}
public boolean matchRemove(Sentence sentence) {
if (sentence.getQuery().length() == 0) {
return false;
}
String s;
switch (type) {
case SCHEMA:
s = matchSchema(sentence);
break;
case TABLE:
s = matchTable(sentence);
break;
case NEW_TABLE_ALIAS:
s = matchTableAlias(sentence, true);
break;
case TABLE_ALIAS:
s = matchTableAlias(sentence, false);
break;
case COLUMN_ALIAS:
s = matchColumnAlias(sentence);
break;
case COLUMN:
s = matchColumn(sentence);
break;
default:
throw DbException.throwInternalError("type=" + type);
}
if (s == null) {
return false;
}
sentence.setQuery(s);
return true;
}
private String matchSchema(Sentence sentence) {
String query = sentence.getQuery();
String up = sentence.getQueryUpper();
DbSchema[] schemas = contents.schemas;
String best = null;
DbSchema bestSchema = null;
for (DbSchema schema: schemas) {
String schemaName = StringUtils.toUpperEnglish(schema.name);
if (up.startsWith(schemaName)) {
if (best == null || schemaName.length() > best.length()) {
best = schemaName;
bestSchema = schema;
}
}
}
sentence.setLastMatchedSchema(bestSchema);
if (best == null) {
return null;
}
query = query.substring(best.length());
// while(query.length()>0 && Character.isWhitespace(query.charAt(0))) {
// query = query.substring(1);
// }
return query;
}
private String matchTable(Sentence sentence) {
String query = sentence.getQuery();
String up = sentence.getQueryUpper();
DbSchema schema = sentence.getLastMatchedSchema();
if (schema == null) {
schema = contents.defaultSchema;
}
DbTableOrView[] tables = schema.tables;
String best = null;
DbTableOrView bestTable = null;
for (DbTableOrView table : tables) {
String tableName = StringUtils.toUpperEnglish(table.name);
if (up.startsWith(tableName)) {
if (best == null || tableName.length() > best.length()) {
best = tableName;
bestTable = table;
}
}
}
if (best == null) {
return null;
}
sentence.addTable(bestTable);
query = query.substring(best.length());
// while(query.length()>0 && Character.isWhitespace(query.charAt(0))) {
// query = query.substring(1);
// }
return query;
}
private String matchColumnAlias(Sentence sentence) {
String query = sentence.getQuery();
String up = sentence.getQueryUpper();
int i = 0;
if (query.indexOf(' ') < 0) {
return null;
}
for (; i < up.length(); i++) {
char ch = up.charAt(i);
if (ch != '_' && !Character.isLetterOrDigit(ch)) {
break;
}
}
if (i == 0) {
return null;
}
String alias = up.substring(0, i);
if (Parser.isKeyword(alias, true)) {
return null;
}
return query.substring(alias.length());
}
private String matchTableAlias(Sentence sentence, boolean add) {
String query = sentence.getQuery();
String up = sentence.getQueryUpper();
int i = 0;
if (query.indexOf(' ') < 0) {
return null;
}
for (; i < up.length(); i++) {
char ch = up.charAt(i);
if (ch != '_' && !Character.isLetterOrDigit(ch)) {
break;
}
}
if (i == 0) {
return null;
}
String alias = up.substring(0, i);
if (Parser.isKeyword(alias, true)) {
return null;
}
if (add) {
sentence.addAlias(alias, sentence.getLastTable());
}
HashMap<String, DbTableOrView> map = sentence.getAliases();
if ((map != null && map.containsKey(alias)) || (sentence.getLastTable() == null)) {
if (add && query.length() == alias.length()) {
return query;
}
query = query.substring(alias.length());
return query;
}
HashSet<DbTableOrView> tables = sentence.getTables();
if (tables != null) {
String best = null;
for (DbTableOrView table : tables) {
String tableName = StringUtils.toUpperEnglish(table.name);
//DbTableOrView[] tables = contents.defaultSchema.tables;
//for(int i=0; i<tables.length; i++) {
// DbTableOrView table = tables[i];
// String tableName = StringUtils.toUpperEnglish(table.name);
if (alias.startsWith(tableName) && (best == null || tableName.length() > best.length())) {
sentence.setLastMatchedTable(table);
best = tableName;
}
}
if (best != null) {
query = query.substring(best.length());
return query;
}
}
return null;
}
private String matchColumn(Sentence sentence) {
String query = sentence.getQuery();
String up = sentence.getQueryUpper();
HashSet<DbTableOrView> set = sentence.getTables();
String best = null;
DbTableOrView last = sentence.getLastMatchedTable();
if (last != null && last.columns != null) {
for (DbColumn column : last.columns) {
String name = StringUtils.toUpperEnglish(column.name);
if (up.startsWith(name)) {
String b = query.substring(name.length());
if (best == null || b.length() < best.length()) {
best = b;
}
}
}
}
for (DbTableOrView table : contents.defaultSchema.tables) {
if (table != last && set != null && !set.contains(table)) {
continue;
}
if (table == null || table.columns == null) {
continue;
}
for (DbColumn column : table.columns) {
String name = StringUtils.toUpperEnglish(column.name);
if (up.startsWith(name)) {
String b = query.substring(name.length());
if (best == null || b.length() < best.length()) {
best = b;
}
}
}
}
return best;
}
public void accept(BnfVisitor visitor) {
// nothing to do
}
}
| true | true | private void addColumn(Sentence sentence) {
String query = sentence.getQuery();
String tableName = query;
String columnPattern = "";
if (query.trim().length() == 0) {
tableName = null;
} else {
tableName = StringUtils.toUpperEnglish(query.trim());
if (tableName.endsWith(".")) {
tableName = tableName.substring(0, tableName.length() - 1);
} else {
columnPattern = StringUtils.toUpperEnglish(query.trim());
tableName = null;
}
}
HashSet<DbTableOrView> set = null;
HashMap<String, DbTableOrView> aliases = sentence.getAliases();
if (tableName == null && sentence.getTables() != null) {
set = sentence.getTables();
}
DbTableOrView table = null;
if (tableName != null && aliases != null && aliases.get(tableName) != null) {
table = aliases.get(tableName);
tableName = StringUtils.toUpperEnglish(table.name);
}
if (tableName == null) {
if (set == null && aliases == null) {
return;
}
if ((set != null && set.size() > 1) || (aliases != null && aliases.size() > 1)) {
return;
}
}
if (table == null) {
for (DbTableOrView tab : contents.defaultSchema.tables) {
String t = StringUtils.toUpperEnglish(tab.name);
if (tableName != null && !tableName.equals(t)) {
continue;
}
if (set != null && !set.contains(tab)) {
continue;
}
table = tab;
break;
}
}
if (table != null && table.columns != null) {
for (DbColumn column : table.columns) {
String columnName = column.name;
if (!StringUtils.toUpperEnglish(columnName).startsWith(columnPattern)) {
continue;
}
if (columnPattern.length() < columnName.length()) {
String sub = columnName.substring(columnPattern.length());
if (sub.equals(columnName) && contents.needsQuotes(columnName)) {
columnName = StringUtils.quoteIdentifier(columnName);
sub = columnName;
}
System.out.println("add " + columnName + " " + columnName.substring(columnPattern.length()));
sentence.add(columnName, sub, Sentence.CONTEXT);
}
}
}
}
| private void addColumn(Sentence sentence) {
String query = sentence.getQuery();
String tableName = query;
String columnPattern = "";
if (query.trim().length() == 0) {
tableName = null;
} else {
tableName = StringUtils.toUpperEnglish(query.trim());
if (tableName.endsWith(".")) {
tableName = tableName.substring(0, tableName.length() - 1);
} else {
columnPattern = StringUtils.toUpperEnglish(query.trim());
tableName = null;
}
}
HashSet<DbTableOrView> set = null;
HashMap<String, DbTableOrView> aliases = sentence.getAliases();
if (tableName == null && sentence.getTables() != null) {
set = sentence.getTables();
}
DbTableOrView table = null;
if (tableName != null && aliases != null && aliases.get(tableName) != null) {
table = aliases.get(tableName);
tableName = StringUtils.toUpperEnglish(table.name);
}
if (tableName == null) {
if (set == null && aliases == null) {
return;
}
if ((set != null && set.size() > 1) || (aliases != null && aliases.size() > 1)) {
return;
}
}
if (table == null) {
for (DbTableOrView tab : contents.defaultSchema.tables) {
String t = StringUtils.toUpperEnglish(tab.name);
if (tableName != null && !tableName.equals(t)) {
continue;
}
if (set != null && !set.contains(tab)) {
continue;
}
table = tab;
break;
}
}
if (table != null && table.columns != null) {
for (DbColumn column : table.columns) {
String columnName = column.name;
if (!StringUtils.toUpperEnglish(columnName).startsWith(columnPattern)) {
continue;
}
if (columnPattern.length() < columnName.length()) {
String sub = columnName.substring(columnPattern.length());
if (sub.equals(columnName) && contents.needsQuotes(columnName)) {
columnName = StringUtils.quoteIdentifier(columnName);
sub = columnName;
}
sentence.add(columnName, sub, Sentence.CONTEXT);
}
}
}
}
|
diff --git a/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/internal/provisional/commons/ui/DatePicker.java b/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/internal/provisional/commons/ui/DatePicker.java
index 206bb9e7..b90748c3 100644
--- a/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/internal/provisional/commons/ui/DatePicker.java
+++ b/org.eclipse.mylyn.commons.ui/src/org/eclipse/mylyn/internal/provisional/commons/ui/DatePicker.java
@@ -1,335 +1,338 @@
/*******************************************************************************
* Copyright (c) 2004, 2009 Tasktop Technologies 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:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.provisional.commons.ui;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.jface.window.Window;
import org.eclipse.mylyn.internal.commons.ui.Messages;
import org.eclipse.mylyn.internal.provisional.commons.ui.dialogs.AbstractInPlaceDialog;
import org.eclipse.mylyn.internal.provisional.commons.ui.dialogs.IInPlaceDialogListener;
import org.eclipse.mylyn.internal.provisional.commons.ui.dialogs.InPlaceDateSelectionDialog;
import org.eclipse.mylyn.internal.provisional.commons.ui.dialogs.InPlaceDialogEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.widgets.ImageHyperlink;
/**
* Temporary date picker from patch posted to: https://bugs.eclipse.org/bugs/show_bug.cgi?taskId=19945 see bug# 19945
* TODO: remove this class when an SWT date picker is added
*
* @author Bahadir Yagan
* @author Mik Kersten
* @since 1.0
*/
public class DatePicker extends Composite {
public final static String TITLE_DIALOG = Messages.DatePicker_Choose_Date;
public static final String LABEL_CHOOSE = Messages.DatePicker_Choose_Date;
private Text dateText;
private Button pickButton;
private Calendar date;
private final List<SelectionListener> pickerListeners = new LinkedList<SelectionListener>();
private DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);
private String initialText = LABEL_CHOOSE;
private final boolean includeTimeOfday;
private final int hourOfDay = 0;
private int selectedHourOfDay = 0;
private ImageHyperlink clearControl;
public DatePicker(Composite parent, int style, String initialText, boolean includeHours, int selectedHourOfDay) {
super(parent, style);
this.initialText = initialText;
this.includeTimeOfday = includeHours;
this.selectedHourOfDay = selectedHourOfDay;
initialize((style & SWT.FLAT) != 0 ? SWT.FLAT : 0);
}
public DateFormat getDateFormat() {
return dateFormat;
}
public void setDatePattern(String pattern) {
this.dateFormat = new SimpleDateFormat(pattern);
}
public void setDateFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
}
private void initialize(int style) {
GridLayout gridLayout = new GridLayout(3, false);
- gridLayout.horizontalSpacing = 3;
+ gridLayout.horizontalSpacing = 0;
gridLayout.verticalSpacing = 0;
gridLayout.marginWidth = 0;
gridLayout.marginHeight = 0;
this.setLayout(gridLayout);
dateText = new Text(this, style);
GridData dateTextGridData = new GridData(SWT.FILL, SWT.FILL, false, false);
dateTextGridData.grabExcessHorizontalSpace = true;
dateTextGridData.verticalAlignment = SWT.FILL;
dateText.setLayoutData(dateTextGridData);
dateText.setText(initialText);
dateText.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
// key listener used because setting of date picker text causes
// modify listener to fire which results in perpetual dirty
// editor
notifyPickerListeners();
}
});
dateText.addFocusListener(new FocusAdapter() {
Calendar calendar = Calendar.getInstance();
@Override
public void focusLost(FocusEvent e) {
Date reminderDate;
try {
reminderDate = dateFormat.parse(dateText.getText());
calendar.setTime(reminderDate);
date = calendar;
updateDateText();
} catch (ParseException e1) {
updateDateText();
}
}
});
clearControl = new ImageHyperlink(this, SWT.NONE);
clearControl.setImage(CommonImages.getImage(CommonImages.FIND_CLEAR_DISABLED));
clearControl.setHoverImage(CommonImages.getImage(CommonImages.FIND_CLEAR));
clearControl.setToolTipText(Messages.DatePicker_Clear);
clearControl.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
dateSelected(false, null);
}
});
clearControl.setBackground(clearControl.getDisplay().getSystemColor(SWT.COLOR_WHITE));
- clearControl.setLayoutData(new GridData());
+ GridData clearButtonGridData = new GridData();
+ clearButtonGridData.horizontalIndent = 3;
+ clearControl.setLayoutData(clearButtonGridData);
pickButton = new Button(this, style | SWT.ARROW | SWT.DOWN);
GridData pickButtonGridData = new GridData(SWT.RIGHT, SWT.FILL, false, true);
pickButtonGridData.verticalIndent = 0;
+ pickButtonGridData.horizontalIndent = 3;
pickButton.setLayoutData(pickButtonGridData);
pickButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
final Calendar newCalendar = Calendar.getInstance();
newCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
newCalendar.set(Calendar.MINUTE, 0);
newCalendar.set(Calendar.SECOND, 0);
newCalendar.set(Calendar.MILLISECOND, 0);
if (date != null) {
newCalendar.setTime(date.getTime());
}
Shell shell = pickButton.getShell();
if (shell == null) {
//fall back
if (PlatformUI.getWorkbench().getActiveWorkbenchWindow() != null) {
shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
} else {
shell = new Shell(PlatformUI.getWorkbench().getDisplay());
}
}
final InPlaceDateSelectionDialog dialog = new InPlaceDateSelectionDialog(shell, pickButton,
newCalendar, DatePicker.TITLE_DIALOG, includeTimeOfday, selectedHourOfDay);
dialog.addEventListener(new IInPlaceDialogListener() {
public void buttonPressed(InPlaceDialogEvent event) {
Calendar selectedCalendar = newCalendar;
if (event.getReturnCode() == AbstractInPlaceDialog.ID_CLEAR) {
dateSelected(event.getReturnCode() == Window.CANCEL, null);
} else if (event.getReturnCode() == Window.OK) {
if (dialog.getDate() != null) {
if (selectedCalendar == null) {
selectedCalendar = Calendar.getInstance();
}
selectedCalendar.setTime(dialog.getDate());
} else {
selectedCalendar = null;
}
dateSelected(event.getReturnCode() == Window.CANCEL, selectedCalendar);
}
}
});
dialog.open();
}
});
updateClearControlVisibility();
pack();
}
public void addPickerSelectionListener(SelectionListener listener) {
pickerListeners.add(listener);
}
/**
* must check for null return value
*
* @return Calendar
*/
public Calendar getDate() {
return date;
}
@Override
public void setBackground(Color backgroundColor) {
dateText.setBackground(backgroundColor);
pickButton.setBackground(backgroundColor);
super.setBackground(backgroundColor);
}
public void setDate(Calendar date) {
this.date = date;
updateDateText();
}
// private void showDatePicker(int x, int y) {
// pickerShell = new Shell(SWT.APPLICATION_MODAL);//| SWT.ON_TOP
// pickerShell.setText("Shell");
// pickerShell.setLayout(new FillLayout());
// if (date == null) {
// date = new GregorianCalendar();
// }
// // datePickerPanel.setDate(date);
// datePickerPanel = new DatePickerPanel(pickerShell, SWT.NONE, date);
// datePickerPanel.addSelectionChangedListener(new
// ISelectionChangedListener() {
//
// public void selectionChanged(SelectionChangedEvent event) {
// if(!event.getSelection().isEmpty()) {
// dateSelected(event.getSelection().isEmpty(),
// ((DateSelection)event.getSelection()).getDate());
// } else {
// dateSelected(false, null);
// }
// }});
//
// pickerShell.setSize(new Point(240, 180));
// pickerShell.setLocation(new Point(x, y));
//
// datePickerPanel.addKeyListener(new KeyListener() {
// public void keyPressed(KeyEvent e) {
// if (e.keyCode == SWT.ESC) {
// dateSelected(true, null);
// }
// }
//
// public void keyReleased(KeyEvent e) {
// }
// });
//
// pickerShell.addFocusListener(new FocusListener() {
//
// public void focusGained(FocusEvent e) {
//
// }
//
// public void focusLost(FocusEvent e) {
//
// }});
//
// pickerShell.pack();
// pickerShell.open();
// }
/** Called when the user has selected a date */
protected void dateSelected(boolean canceled, Calendar selectedDate) {
if (!canceled) {
this.date = selectedDate != null ? selectedDate : null;
updateDateText();
notifyPickerListeners();
}
}
private void notifyPickerListeners() {
for (SelectionListener listener : pickerListeners) {
listener.widgetSelected(null);
}
}
private void updateDateText() {
if (date != null) {
Date currentDate = new Date(date.getTimeInMillis());
dateText.setText(dateFormat.format(currentDate));
} else {
dateText.setEnabled(false);
dateText.setText(LABEL_CHOOSE);
dateText.setEnabled(true);
}
updateClearControlVisibility();
}
private void updateClearControlVisibility() {
if (clearControl != null && clearControl.getLayoutData() instanceof GridData) {
GridData gd = (GridData) clearControl.getLayoutData();
gd.exclude = date == null;
clearControl.getParent().layout();
}
}
@Override
public void setEnabled(boolean enabled) {
dateText.setEnabled(enabled);
pickButton.setEnabled(enabled);
clearControl.setEnabled(enabled);
super.setEnabled(enabled);
}
}
| false | true | private void initialize(int style) {
GridLayout gridLayout = new GridLayout(3, false);
gridLayout.horizontalSpacing = 3;
gridLayout.verticalSpacing = 0;
gridLayout.marginWidth = 0;
gridLayout.marginHeight = 0;
this.setLayout(gridLayout);
dateText = new Text(this, style);
GridData dateTextGridData = new GridData(SWT.FILL, SWT.FILL, false, false);
dateTextGridData.grabExcessHorizontalSpace = true;
dateTextGridData.verticalAlignment = SWT.FILL;
dateText.setLayoutData(dateTextGridData);
dateText.setText(initialText);
dateText.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
// key listener used because setting of date picker text causes
// modify listener to fire which results in perpetual dirty
// editor
notifyPickerListeners();
}
});
dateText.addFocusListener(new FocusAdapter() {
Calendar calendar = Calendar.getInstance();
@Override
public void focusLost(FocusEvent e) {
Date reminderDate;
try {
reminderDate = dateFormat.parse(dateText.getText());
calendar.setTime(reminderDate);
date = calendar;
updateDateText();
} catch (ParseException e1) {
updateDateText();
}
}
});
clearControl = new ImageHyperlink(this, SWT.NONE);
clearControl.setImage(CommonImages.getImage(CommonImages.FIND_CLEAR_DISABLED));
clearControl.setHoverImage(CommonImages.getImage(CommonImages.FIND_CLEAR));
clearControl.setToolTipText(Messages.DatePicker_Clear);
clearControl.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
dateSelected(false, null);
}
});
clearControl.setBackground(clearControl.getDisplay().getSystemColor(SWT.COLOR_WHITE));
clearControl.setLayoutData(new GridData());
pickButton = new Button(this, style | SWT.ARROW | SWT.DOWN);
GridData pickButtonGridData = new GridData(SWT.RIGHT, SWT.FILL, false, true);
pickButtonGridData.verticalIndent = 0;
pickButton.setLayoutData(pickButtonGridData);
pickButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
final Calendar newCalendar = Calendar.getInstance();
newCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
newCalendar.set(Calendar.MINUTE, 0);
newCalendar.set(Calendar.SECOND, 0);
newCalendar.set(Calendar.MILLISECOND, 0);
if (date != null) {
newCalendar.setTime(date.getTime());
}
Shell shell = pickButton.getShell();
if (shell == null) {
//fall back
if (PlatformUI.getWorkbench().getActiveWorkbenchWindow() != null) {
shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
} else {
shell = new Shell(PlatformUI.getWorkbench().getDisplay());
}
}
final InPlaceDateSelectionDialog dialog = new InPlaceDateSelectionDialog(shell, pickButton,
newCalendar, DatePicker.TITLE_DIALOG, includeTimeOfday, selectedHourOfDay);
dialog.addEventListener(new IInPlaceDialogListener() {
public void buttonPressed(InPlaceDialogEvent event) {
Calendar selectedCalendar = newCalendar;
if (event.getReturnCode() == AbstractInPlaceDialog.ID_CLEAR) {
dateSelected(event.getReturnCode() == Window.CANCEL, null);
} else if (event.getReturnCode() == Window.OK) {
if (dialog.getDate() != null) {
if (selectedCalendar == null) {
selectedCalendar = Calendar.getInstance();
}
selectedCalendar.setTime(dialog.getDate());
} else {
selectedCalendar = null;
}
dateSelected(event.getReturnCode() == Window.CANCEL, selectedCalendar);
}
}
});
dialog.open();
}
});
updateClearControlVisibility();
pack();
}
| private void initialize(int style) {
GridLayout gridLayout = new GridLayout(3, false);
gridLayout.horizontalSpacing = 0;
gridLayout.verticalSpacing = 0;
gridLayout.marginWidth = 0;
gridLayout.marginHeight = 0;
this.setLayout(gridLayout);
dateText = new Text(this, style);
GridData dateTextGridData = new GridData(SWT.FILL, SWT.FILL, false, false);
dateTextGridData.grabExcessHorizontalSpace = true;
dateTextGridData.verticalAlignment = SWT.FILL;
dateText.setLayoutData(dateTextGridData);
dateText.setText(initialText);
dateText.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
// key listener used because setting of date picker text causes
// modify listener to fire which results in perpetual dirty
// editor
notifyPickerListeners();
}
});
dateText.addFocusListener(new FocusAdapter() {
Calendar calendar = Calendar.getInstance();
@Override
public void focusLost(FocusEvent e) {
Date reminderDate;
try {
reminderDate = dateFormat.parse(dateText.getText());
calendar.setTime(reminderDate);
date = calendar;
updateDateText();
} catch (ParseException e1) {
updateDateText();
}
}
});
clearControl = new ImageHyperlink(this, SWT.NONE);
clearControl.setImage(CommonImages.getImage(CommonImages.FIND_CLEAR_DISABLED));
clearControl.setHoverImage(CommonImages.getImage(CommonImages.FIND_CLEAR));
clearControl.setToolTipText(Messages.DatePicker_Clear);
clearControl.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
dateSelected(false, null);
}
});
clearControl.setBackground(clearControl.getDisplay().getSystemColor(SWT.COLOR_WHITE));
GridData clearButtonGridData = new GridData();
clearButtonGridData.horizontalIndent = 3;
clearControl.setLayoutData(clearButtonGridData);
pickButton = new Button(this, style | SWT.ARROW | SWT.DOWN);
GridData pickButtonGridData = new GridData(SWT.RIGHT, SWT.FILL, false, true);
pickButtonGridData.verticalIndent = 0;
pickButtonGridData.horizontalIndent = 3;
pickButton.setLayoutData(pickButtonGridData);
pickButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent arg0) {
final Calendar newCalendar = Calendar.getInstance();
newCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
newCalendar.set(Calendar.MINUTE, 0);
newCalendar.set(Calendar.SECOND, 0);
newCalendar.set(Calendar.MILLISECOND, 0);
if (date != null) {
newCalendar.setTime(date.getTime());
}
Shell shell = pickButton.getShell();
if (shell == null) {
//fall back
if (PlatformUI.getWorkbench().getActiveWorkbenchWindow() != null) {
shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
} else {
shell = new Shell(PlatformUI.getWorkbench().getDisplay());
}
}
final InPlaceDateSelectionDialog dialog = new InPlaceDateSelectionDialog(shell, pickButton,
newCalendar, DatePicker.TITLE_DIALOG, includeTimeOfday, selectedHourOfDay);
dialog.addEventListener(new IInPlaceDialogListener() {
public void buttonPressed(InPlaceDialogEvent event) {
Calendar selectedCalendar = newCalendar;
if (event.getReturnCode() == AbstractInPlaceDialog.ID_CLEAR) {
dateSelected(event.getReturnCode() == Window.CANCEL, null);
} else if (event.getReturnCode() == Window.OK) {
if (dialog.getDate() != null) {
if (selectedCalendar == null) {
selectedCalendar = Calendar.getInstance();
}
selectedCalendar.setTime(dialog.getDate());
} else {
selectedCalendar = null;
}
dateSelected(event.getReturnCode() == Window.CANCEL, selectedCalendar);
}
}
});
dialog.open();
}
});
updateClearControlVisibility();
pack();
}
|
diff --git a/mail/src/main/java/com/sun/mail/imap/protocol/BODYSTRUCTURE.java b/mail/src/main/java/com/sun/mail/imap/protocol/BODYSTRUCTURE.java
index 0b698d4..119149c 100644
--- a/mail/src/main/java/com/sun/mail/imap/protocol/BODYSTRUCTURE.java
+++ b/mail/src/main/java/com/sun/mail/imap/protocol/BODYSTRUCTURE.java
@@ -1,409 +1,415 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.mail.imap.protocol;
import java.util.Vector;
import javax.mail.internet.ParameterList;
import com.sun.mail.iap.*;
import com.sun.mail.util.PropUtil;
/**
* A BODYSTRUCTURE response.
*
* @author John Mani
* @author Bill Shannon
*/
public class BODYSTRUCTURE implements Item {
static final char[] name =
{'B','O','D','Y','S','T','R','U','C','T','U','R','E'};
public int msgno;
public String type; // Type
public String subtype; // Subtype
public String encoding; // Encoding
public int lines = -1; // Size in lines
public int size = -1; // Size in bytes
public String disposition; // Disposition
public String id; // Content-ID
public String description; // Content-Description
public String md5; // MD-5 checksum
public String attachment; // Attachment name
public ParameterList cParams; // Body parameters
public ParameterList dParams; // Disposition parameters
public String[] language; // Language
public BODYSTRUCTURE[] bodies; // array of BODYSTRUCTURE objects
// for multipart & message/rfc822
public ENVELOPE envelope; // for message/rfc822
private static int SINGLE = 1;
private static int MULTI = 2;
private static int NESTED = 3;
private int processedType; // MULTI | SINGLE | NESTED
// special debugging output to debug parsing errors
private static boolean parseDebug =
PropUtil.getBooleanSystemProperty("mail.imap.parse.debug", false);
public BODYSTRUCTURE(FetchResponse r) throws ParsingException {
if (parseDebug)
System.out.println("DEBUG IMAP: parsing BODYSTRUCTURE");
msgno = r.getNumber();
if (parseDebug)
System.out.println("DEBUG IMAP: msgno " + msgno);
r.skipSpaces();
if (r.readByte() != '(')
throw new ParsingException(
"BODYSTRUCTURE parse error: missing ``('' at start");
if (r.peekByte() == '(') { // multipart
if (parseDebug)
System.out.println("DEBUG IMAP: parsing multipart");
type = "multipart";
processedType = MULTI;
Vector v = new Vector(1);
int i = 1;
do {
v.addElement(new BODYSTRUCTURE(r));
/*
* Even though the IMAP spec says there can't be any spaces
* between parts, some servers erroneously put a space in
* here. In the spirit of "be liberal in what you accept",
* we skip it.
*/
r.skipSpaces();
} while (r.peekByte() == '(');
// setup bodies.
bodies = new BODYSTRUCTURE[v.size()];
v.copyInto(bodies);
subtype = r.readString(); // subtype
if (parseDebug)
System.out.println("DEBUG IMAP: subtype " + subtype);
if (r.readByte() == ')') { // done
if (parseDebug)
System.out.println("DEBUG IMAP: parse DONE");
return;
}
// Else, we have extension data
if (parseDebug)
System.out.println("DEBUG IMAP: parsing extension data");
// Body parameters
cParams = parseParameters(r);
if (r.readByte() == ')') { // done
if (parseDebug)
System.out.println("DEBUG IMAP: body parameters DONE");
return;
}
// Disposition
byte b = r.readByte();
if (b == '(') {
if (parseDebug)
System.out.println("DEBUG IMAP: parse disposition");
disposition = r.readString();
if (parseDebug)
System.out.println("DEBUG IMAP: disposition " +
disposition);
dParams = parseParameters(r);
if (r.readByte() != ')') // eat the end ')'
throw new ParsingException(
"BODYSTRUCTURE parse error: " +
"missing ``)'' at end of disposition in multipart");
if (parseDebug)
System.out.println("DEBUG IMAP: disposition DONE");
} else if (b == 'N' || b == 'n') {
if (parseDebug)
System.out.println("DEBUG IMAP: disposition NIL");
r.skip(2); // skip 'NIL'
} else {
throw new ParsingException(
"BODYSTRUCTURE parse error: " +
type + "/" + subtype + ": " +
"bad multipart disposition, b " + b);
}
// RFC3501 allows no body-fld-lang after body-fld-disp,
// even though RFC2060 required it
if ((b = r.readByte()) == ')') {
if (parseDebug)
System.out.println("DEBUG IMAP: no body-fld-lang");
return; // done
}
if (b != ' ')
throw new ParsingException(
"BODYSTRUCTURE parse error: " +
"missing space after disposition");
// Language
if (r.peekByte() == '(') { // a list follows
language = r.readStringList();
if (parseDebug)
System.out.println(
"DEBUG IMAP: language len " + language.length);
} else {
String l = r.readString();
if (l != null) {
String[] la = { l };
language = la;
if (parseDebug)
System.out.println("DEBUG IMAP: language " + l);
}
}
// RFC3501 defines an optional "body location" next,
// but for now we ignore it along with other extensions.
// Throw away any further extension data
while (r.readByte() == ' ')
parseBodyExtension(r);
}
else { // Single part
if (parseDebug)
System.out.println("DEBUG IMAP: single part");
type = r.readString();
if (parseDebug)
System.out.println("DEBUG IMAP: type " + type);
processedType = SINGLE;
subtype = r.readString();
if (parseDebug)
System.out.println("DEBUG IMAP: subtype " + subtype);
// SIMS 4.0 returns NIL for a Content-Type of "binary", fix it here
if (type == null) {
type = "application";
subtype = "octet-stream";
}
cParams = parseParameters(r);
if (parseDebug)
System.out.println("DEBUG IMAP: cParams " + cParams);
id = r.readString();
if (parseDebug)
System.out.println("DEBUG IMAP: id " + id);
description = r.readString();
if (parseDebug)
System.out.println("DEBUG IMAP: description " + description);
- encoding = r.readString();
+ /*
+ * XXX - Work around bug in Exchange 2010 that
+ * returns unquoted string.
+ */
+ encoding = r.readAtomString();
+ if (encoding != null && encoding.equalsIgnoreCase("NIL"))
+ encoding = null;
if (parseDebug)
System.out.println("DEBUG IMAP: encoding " + encoding);
size = r.readNumber();
if (parseDebug)
System.out.println("DEBUG IMAP: size " + size);
if (size < 0)
throw new ParsingException(
"BODYSTRUCTURE parse error: bad ``size'' element");
// "text/*" & "message/rfc822" types have additional data ..
if (type.equalsIgnoreCase("text")) {
lines = r.readNumber();
if (parseDebug)
System.out.println("DEBUG IMAP: lines " + lines);
if (lines < 0)
throw new ParsingException(
"BODYSTRUCTURE parse error: bad ``lines'' element");
} else if (type.equalsIgnoreCase("message") &&
subtype.equalsIgnoreCase("rfc822")) {
// Nested message
processedType = NESTED;
envelope = new ENVELOPE(r);
BODYSTRUCTURE[] bs = { new BODYSTRUCTURE(r) };
bodies = bs;
lines = r.readNumber();
if (parseDebug)
System.out.println("DEBUG IMAP: lines " + lines);
if (lines < 0)
throw new ParsingException(
"BODYSTRUCTURE parse error: bad ``lines'' element");
} else {
// Detect common error of including lines element on other types
r.skipSpaces();
byte bn = r.peekByte();
if (Character.isDigit((char)bn)) // number
throw new ParsingException(
"BODYSTRUCTURE parse error: server erroneously " +
"included ``lines'' element with type " +
type + "/" + subtype);
}
if (r.peekByte() == ')') {
r.readByte();
if (parseDebug)
System.out.println("DEBUG IMAP: parse DONE");
return; // done
}
// Optional extension data
// MD5
md5 = r.readString();
if (r.readByte() == ')') {
if (parseDebug)
System.out.println("DEBUG IMAP: no MD5 DONE");
return; // done
}
// Disposition
byte b = r.readByte();
if (b == '(') {
disposition = r.readString();
if (parseDebug)
System.out.println("DEBUG IMAP: disposition " +
disposition);
dParams = parseParameters(r);
if (parseDebug)
System.out.println("DEBUG IMAP: dParams " + dParams);
if (r.readByte() != ')') // eat the end ')'
throw new ParsingException(
"BODYSTRUCTURE parse error: " +
"missing ``)'' at end of disposition");
} else if (b == 'N' || b == 'n') {
if (parseDebug)
System.out.println("DEBUG IMAP: disposition NIL");
r.skip(2); // skip 'NIL'
} else {
throw new ParsingException(
"BODYSTRUCTURE parse error: " +
type + "/" + subtype + ": " +
"bad single part disposition, b " + b);
}
if (r.readByte() == ')') {
if (parseDebug)
System.out.println("DEBUG IMAP: disposition DONE");
return; // done
}
// Language
if (r.peekByte() == '(') { // a list follows
language = r.readStringList();
if (parseDebug)
System.out.println("DEBUG IMAP: language len " +
language.length);
} else { // protocol is unnessarily complex here
String l = r.readString();
if (l != null) {
String[] la = { l };
language = la;
if (parseDebug)
System.out.println("DEBUG IMAP: language " + l);
}
}
// RFC3501 defines an optional "body location" next,
// but for now we ignore it along with other extensions.
// Throw away any further extension data
while (r.readByte() == ' ')
parseBodyExtension(r);
if (parseDebug)
System.out.println("DEBUG IMAP: all DONE");
}
}
public boolean isMulti() {
return processedType == MULTI;
}
public boolean isSingle() {
return processedType == SINGLE;
}
public boolean isNested() {
return processedType == NESTED;
}
private ParameterList parseParameters(Response r)
throws ParsingException {
r.skipSpaces();
ParameterList list = null;
byte b = r.readByte();
if (b == '(') {
list = new ParameterList();
do {
String name = r.readString();
if (parseDebug)
System.out.println("DEBUG IMAP: parameter name " + name);
if (name == null)
throw new ParsingException(
"BODYSTRUCTURE parse error: " +
type + "/" + subtype + ": " +
"null name in parameter list");
String value = r.readString();
if (parseDebug)
System.out.println("DEBUG IMAP: parameter value " + value);
list.set(name, value);
} while (r.readByte() != ')');
list.set(null, "DONE"); // XXX - hack
} else if (b == 'N' || b == 'n') {
if (parseDebug)
System.out.println("DEBUG IMAP: parameter list NIL");
r.skip(2);
} else
throw new ParsingException("Parameter list parse error");
return list;
}
private void parseBodyExtension(Response r) throws ParsingException {
r.skipSpaces();
byte b = r.peekByte();
if (b == '(') {
r.skip(1); // skip '('
do {
parseBodyExtension(r);
} while (r.readByte() != ')');
} else if (Character.isDigit((char)b)) // number
r.readNumber();
else // nstring
r.readString();
}
}
| true | true | public BODYSTRUCTURE(FetchResponse r) throws ParsingException {
if (parseDebug)
System.out.println("DEBUG IMAP: parsing BODYSTRUCTURE");
msgno = r.getNumber();
if (parseDebug)
System.out.println("DEBUG IMAP: msgno " + msgno);
r.skipSpaces();
if (r.readByte() != '(')
throw new ParsingException(
"BODYSTRUCTURE parse error: missing ``('' at start");
if (r.peekByte() == '(') { // multipart
if (parseDebug)
System.out.println("DEBUG IMAP: parsing multipart");
type = "multipart";
processedType = MULTI;
Vector v = new Vector(1);
int i = 1;
do {
v.addElement(new BODYSTRUCTURE(r));
/*
* Even though the IMAP spec says there can't be any spaces
* between parts, some servers erroneously put a space in
* here. In the spirit of "be liberal in what you accept",
* we skip it.
*/
r.skipSpaces();
} while (r.peekByte() == '(');
// setup bodies.
bodies = new BODYSTRUCTURE[v.size()];
v.copyInto(bodies);
subtype = r.readString(); // subtype
if (parseDebug)
System.out.println("DEBUG IMAP: subtype " + subtype);
if (r.readByte() == ')') { // done
if (parseDebug)
System.out.println("DEBUG IMAP: parse DONE");
return;
}
// Else, we have extension data
if (parseDebug)
System.out.println("DEBUG IMAP: parsing extension data");
// Body parameters
cParams = parseParameters(r);
if (r.readByte() == ')') { // done
if (parseDebug)
System.out.println("DEBUG IMAP: body parameters DONE");
return;
}
// Disposition
byte b = r.readByte();
if (b == '(') {
if (parseDebug)
System.out.println("DEBUG IMAP: parse disposition");
disposition = r.readString();
if (parseDebug)
System.out.println("DEBUG IMAP: disposition " +
disposition);
dParams = parseParameters(r);
if (r.readByte() != ')') // eat the end ')'
throw new ParsingException(
"BODYSTRUCTURE parse error: " +
"missing ``)'' at end of disposition in multipart");
if (parseDebug)
System.out.println("DEBUG IMAP: disposition DONE");
} else if (b == 'N' || b == 'n') {
if (parseDebug)
System.out.println("DEBUG IMAP: disposition NIL");
r.skip(2); // skip 'NIL'
} else {
throw new ParsingException(
"BODYSTRUCTURE parse error: " +
type + "/" + subtype + ": " +
"bad multipart disposition, b " + b);
}
// RFC3501 allows no body-fld-lang after body-fld-disp,
// even though RFC2060 required it
if ((b = r.readByte()) == ')') {
if (parseDebug)
System.out.println("DEBUG IMAP: no body-fld-lang");
return; // done
}
if (b != ' ')
throw new ParsingException(
"BODYSTRUCTURE parse error: " +
"missing space after disposition");
// Language
if (r.peekByte() == '(') { // a list follows
language = r.readStringList();
if (parseDebug)
System.out.println(
"DEBUG IMAP: language len " + language.length);
} else {
String l = r.readString();
if (l != null) {
String[] la = { l };
language = la;
if (parseDebug)
System.out.println("DEBUG IMAP: language " + l);
}
}
// RFC3501 defines an optional "body location" next,
// but for now we ignore it along with other extensions.
// Throw away any further extension data
while (r.readByte() == ' ')
parseBodyExtension(r);
}
else { // Single part
if (parseDebug)
System.out.println("DEBUG IMAP: single part");
type = r.readString();
if (parseDebug)
System.out.println("DEBUG IMAP: type " + type);
processedType = SINGLE;
subtype = r.readString();
if (parseDebug)
System.out.println("DEBUG IMAP: subtype " + subtype);
// SIMS 4.0 returns NIL for a Content-Type of "binary", fix it here
if (type == null) {
type = "application";
subtype = "octet-stream";
}
cParams = parseParameters(r);
if (parseDebug)
System.out.println("DEBUG IMAP: cParams " + cParams);
id = r.readString();
if (parseDebug)
System.out.println("DEBUG IMAP: id " + id);
description = r.readString();
if (parseDebug)
System.out.println("DEBUG IMAP: description " + description);
encoding = r.readString();
if (parseDebug)
System.out.println("DEBUG IMAP: encoding " + encoding);
size = r.readNumber();
if (parseDebug)
System.out.println("DEBUG IMAP: size " + size);
if (size < 0)
throw new ParsingException(
"BODYSTRUCTURE parse error: bad ``size'' element");
// "text/*" & "message/rfc822" types have additional data ..
if (type.equalsIgnoreCase("text")) {
lines = r.readNumber();
if (parseDebug)
System.out.println("DEBUG IMAP: lines " + lines);
if (lines < 0)
throw new ParsingException(
"BODYSTRUCTURE parse error: bad ``lines'' element");
} else if (type.equalsIgnoreCase("message") &&
subtype.equalsIgnoreCase("rfc822")) {
// Nested message
processedType = NESTED;
envelope = new ENVELOPE(r);
BODYSTRUCTURE[] bs = { new BODYSTRUCTURE(r) };
bodies = bs;
lines = r.readNumber();
if (parseDebug)
System.out.println("DEBUG IMAP: lines " + lines);
if (lines < 0)
throw new ParsingException(
"BODYSTRUCTURE parse error: bad ``lines'' element");
} else {
// Detect common error of including lines element on other types
r.skipSpaces();
byte bn = r.peekByte();
if (Character.isDigit((char)bn)) // number
throw new ParsingException(
"BODYSTRUCTURE parse error: server erroneously " +
"included ``lines'' element with type " +
type + "/" + subtype);
}
if (r.peekByte() == ')') {
r.readByte();
if (parseDebug)
System.out.println("DEBUG IMAP: parse DONE");
return; // done
}
// Optional extension data
// MD5
md5 = r.readString();
if (r.readByte() == ')') {
if (parseDebug)
System.out.println("DEBUG IMAP: no MD5 DONE");
return; // done
}
// Disposition
byte b = r.readByte();
if (b == '(') {
disposition = r.readString();
if (parseDebug)
System.out.println("DEBUG IMAP: disposition " +
disposition);
dParams = parseParameters(r);
if (parseDebug)
System.out.println("DEBUG IMAP: dParams " + dParams);
if (r.readByte() != ')') // eat the end ')'
throw new ParsingException(
"BODYSTRUCTURE parse error: " +
"missing ``)'' at end of disposition");
} else if (b == 'N' || b == 'n') {
if (parseDebug)
System.out.println("DEBUG IMAP: disposition NIL");
r.skip(2); // skip 'NIL'
} else {
throw new ParsingException(
"BODYSTRUCTURE parse error: " +
type + "/" + subtype + ": " +
"bad single part disposition, b " + b);
}
if (r.readByte() == ')') {
if (parseDebug)
System.out.println("DEBUG IMAP: disposition DONE");
return; // done
}
// Language
if (r.peekByte() == '(') { // a list follows
language = r.readStringList();
if (parseDebug)
System.out.println("DEBUG IMAP: language len " +
language.length);
} else { // protocol is unnessarily complex here
String l = r.readString();
if (l != null) {
String[] la = { l };
language = la;
if (parseDebug)
System.out.println("DEBUG IMAP: language " + l);
}
}
// RFC3501 defines an optional "body location" next,
// but for now we ignore it along with other extensions.
// Throw away any further extension data
while (r.readByte() == ' ')
parseBodyExtension(r);
if (parseDebug)
System.out.println("DEBUG IMAP: all DONE");
}
}
| public BODYSTRUCTURE(FetchResponse r) throws ParsingException {
if (parseDebug)
System.out.println("DEBUG IMAP: parsing BODYSTRUCTURE");
msgno = r.getNumber();
if (parseDebug)
System.out.println("DEBUG IMAP: msgno " + msgno);
r.skipSpaces();
if (r.readByte() != '(')
throw new ParsingException(
"BODYSTRUCTURE parse error: missing ``('' at start");
if (r.peekByte() == '(') { // multipart
if (parseDebug)
System.out.println("DEBUG IMAP: parsing multipart");
type = "multipart";
processedType = MULTI;
Vector v = new Vector(1);
int i = 1;
do {
v.addElement(new BODYSTRUCTURE(r));
/*
* Even though the IMAP spec says there can't be any spaces
* between parts, some servers erroneously put a space in
* here. In the spirit of "be liberal in what you accept",
* we skip it.
*/
r.skipSpaces();
} while (r.peekByte() == '(');
// setup bodies.
bodies = new BODYSTRUCTURE[v.size()];
v.copyInto(bodies);
subtype = r.readString(); // subtype
if (parseDebug)
System.out.println("DEBUG IMAP: subtype " + subtype);
if (r.readByte() == ')') { // done
if (parseDebug)
System.out.println("DEBUG IMAP: parse DONE");
return;
}
// Else, we have extension data
if (parseDebug)
System.out.println("DEBUG IMAP: parsing extension data");
// Body parameters
cParams = parseParameters(r);
if (r.readByte() == ')') { // done
if (parseDebug)
System.out.println("DEBUG IMAP: body parameters DONE");
return;
}
// Disposition
byte b = r.readByte();
if (b == '(') {
if (parseDebug)
System.out.println("DEBUG IMAP: parse disposition");
disposition = r.readString();
if (parseDebug)
System.out.println("DEBUG IMAP: disposition " +
disposition);
dParams = parseParameters(r);
if (r.readByte() != ')') // eat the end ')'
throw new ParsingException(
"BODYSTRUCTURE parse error: " +
"missing ``)'' at end of disposition in multipart");
if (parseDebug)
System.out.println("DEBUG IMAP: disposition DONE");
} else if (b == 'N' || b == 'n') {
if (parseDebug)
System.out.println("DEBUG IMAP: disposition NIL");
r.skip(2); // skip 'NIL'
} else {
throw new ParsingException(
"BODYSTRUCTURE parse error: " +
type + "/" + subtype + ": " +
"bad multipart disposition, b " + b);
}
// RFC3501 allows no body-fld-lang after body-fld-disp,
// even though RFC2060 required it
if ((b = r.readByte()) == ')') {
if (parseDebug)
System.out.println("DEBUG IMAP: no body-fld-lang");
return; // done
}
if (b != ' ')
throw new ParsingException(
"BODYSTRUCTURE parse error: " +
"missing space after disposition");
// Language
if (r.peekByte() == '(') { // a list follows
language = r.readStringList();
if (parseDebug)
System.out.println(
"DEBUG IMAP: language len " + language.length);
} else {
String l = r.readString();
if (l != null) {
String[] la = { l };
language = la;
if (parseDebug)
System.out.println("DEBUG IMAP: language " + l);
}
}
// RFC3501 defines an optional "body location" next,
// but for now we ignore it along with other extensions.
// Throw away any further extension data
while (r.readByte() == ' ')
parseBodyExtension(r);
}
else { // Single part
if (parseDebug)
System.out.println("DEBUG IMAP: single part");
type = r.readString();
if (parseDebug)
System.out.println("DEBUG IMAP: type " + type);
processedType = SINGLE;
subtype = r.readString();
if (parseDebug)
System.out.println("DEBUG IMAP: subtype " + subtype);
// SIMS 4.0 returns NIL for a Content-Type of "binary", fix it here
if (type == null) {
type = "application";
subtype = "octet-stream";
}
cParams = parseParameters(r);
if (parseDebug)
System.out.println("DEBUG IMAP: cParams " + cParams);
id = r.readString();
if (parseDebug)
System.out.println("DEBUG IMAP: id " + id);
description = r.readString();
if (parseDebug)
System.out.println("DEBUG IMAP: description " + description);
/*
* XXX - Work around bug in Exchange 2010 that
* returns unquoted string.
*/
encoding = r.readAtomString();
if (encoding != null && encoding.equalsIgnoreCase("NIL"))
encoding = null;
if (parseDebug)
System.out.println("DEBUG IMAP: encoding " + encoding);
size = r.readNumber();
if (parseDebug)
System.out.println("DEBUG IMAP: size " + size);
if (size < 0)
throw new ParsingException(
"BODYSTRUCTURE parse error: bad ``size'' element");
// "text/*" & "message/rfc822" types have additional data ..
if (type.equalsIgnoreCase("text")) {
lines = r.readNumber();
if (parseDebug)
System.out.println("DEBUG IMAP: lines " + lines);
if (lines < 0)
throw new ParsingException(
"BODYSTRUCTURE parse error: bad ``lines'' element");
} else if (type.equalsIgnoreCase("message") &&
subtype.equalsIgnoreCase("rfc822")) {
// Nested message
processedType = NESTED;
envelope = new ENVELOPE(r);
BODYSTRUCTURE[] bs = { new BODYSTRUCTURE(r) };
bodies = bs;
lines = r.readNumber();
if (parseDebug)
System.out.println("DEBUG IMAP: lines " + lines);
if (lines < 0)
throw new ParsingException(
"BODYSTRUCTURE parse error: bad ``lines'' element");
} else {
// Detect common error of including lines element on other types
r.skipSpaces();
byte bn = r.peekByte();
if (Character.isDigit((char)bn)) // number
throw new ParsingException(
"BODYSTRUCTURE parse error: server erroneously " +
"included ``lines'' element with type " +
type + "/" + subtype);
}
if (r.peekByte() == ')') {
r.readByte();
if (parseDebug)
System.out.println("DEBUG IMAP: parse DONE");
return; // done
}
// Optional extension data
// MD5
md5 = r.readString();
if (r.readByte() == ')') {
if (parseDebug)
System.out.println("DEBUG IMAP: no MD5 DONE");
return; // done
}
// Disposition
byte b = r.readByte();
if (b == '(') {
disposition = r.readString();
if (parseDebug)
System.out.println("DEBUG IMAP: disposition " +
disposition);
dParams = parseParameters(r);
if (parseDebug)
System.out.println("DEBUG IMAP: dParams " + dParams);
if (r.readByte() != ')') // eat the end ')'
throw new ParsingException(
"BODYSTRUCTURE parse error: " +
"missing ``)'' at end of disposition");
} else if (b == 'N' || b == 'n') {
if (parseDebug)
System.out.println("DEBUG IMAP: disposition NIL");
r.skip(2); // skip 'NIL'
} else {
throw new ParsingException(
"BODYSTRUCTURE parse error: " +
type + "/" + subtype + ": " +
"bad single part disposition, b " + b);
}
if (r.readByte() == ')') {
if (parseDebug)
System.out.println("DEBUG IMAP: disposition DONE");
return; // done
}
// Language
if (r.peekByte() == '(') { // a list follows
language = r.readStringList();
if (parseDebug)
System.out.println("DEBUG IMAP: language len " +
language.length);
} else { // protocol is unnessarily complex here
String l = r.readString();
if (l != null) {
String[] la = { l };
language = la;
if (parseDebug)
System.out.println("DEBUG IMAP: language " + l);
}
}
// RFC3501 defines an optional "body location" next,
// but for now we ignore it along with other extensions.
// Throw away any further extension data
while (r.readByte() == ' ')
parseBodyExtension(r);
if (parseDebug)
System.out.println("DEBUG IMAP: all DONE");
}
}
|
diff --git a/beam-visat-rcp/src/main/java/org/esa/beam/visat/toolviews/spectrum/SpectrumToolView.java b/beam-visat-rcp/src/main/java/org/esa/beam/visat/toolviews/spectrum/SpectrumToolView.java
index 90cfb234e..e0c9acc78 100644
--- a/beam-visat-rcp/src/main/java/org/esa/beam/visat/toolviews/spectrum/SpectrumToolView.java
+++ b/beam-visat-rcp/src/main/java/org/esa/beam/visat/toolviews/spectrum/SpectrumToolView.java
@@ -1,638 +1,640 @@
/*
* $Id: SpectrumToolView.java,v 1.1 2007/04/19 10:41:38 norman Exp $
*
* Copyright (C) 2002 by Brockmann Consult ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation. This program is distributed in the hope 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 org.esa.beam.visat.toolviews.spectrum;
import org.esa.beam.framework.datamodel.Band;
import org.esa.beam.framework.datamodel.DataNode;
import org.esa.beam.framework.datamodel.Pin;
import org.esa.beam.framework.datamodel.Product;
import org.esa.beam.framework.datamodel.ProductManager;
import org.esa.beam.framework.datamodel.ProductNodeEvent;
import org.esa.beam.framework.datamodel.ProductNodeGroup;
import org.esa.beam.framework.datamodel.ProductNodeListenerAdapter;
import org.esa.beam.framework.help.HelpSys;
import org.esa.beam.framework.ui.GridBagUtils;
import org.esa.beam.framework.ui.ModalDialog;
import org.esa.beam.framework.ui.PixelPositionListener;
import org.esa.beam.framework.ui.UIUtils;
import org.esa.beam.framework.ui.application.support.AbstractToolView;
import org.esa.beam.framework.ui.diagram.DiagramCanvas;
import org.esa.beam.framework.ui.product.BandChooser;
import org.esa.beam.framework.ui.product.ProductSceneView;
import org.esa.beam.framework.ui.tool.ToolButtonFactory;
import org.esa.beam.util.Debug;
import org.esa.beam.visat.VisatApp;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.BevelBorder;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import com.bc.ceres.glayer.support.ImageLayer;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* A window which displays product spectra.
*/
public class SpectrumToolView extends AbstractToolView {
public static final String ID = SpectrumToolView.class.getName();
private static final String SUPPRESS_MESSAGE_KEY = "plugin.spectrum.tip";
private static final String MSG_NO_SPECTRAL_BANDS = "No spectral bands."; /*I18N*/
private ProductSceneView currentView;
private Product currentProduct;
private Map<Product, CursorSpectrumPPL> cursorSpectrumPPLMap;
private final HashMap<Product, SpectraDiagram> productToDiagramMap;
private final ProductNodeListenerAdapter productNodeHandler;
private DiagramCanvas diagramCanvas;
private AbstractButton filterButton;
private boolean tipShown;
private String originalDescriptorTitle;
private AbstractButton showSpectrumForCursorButton;
private AbstractButton showSpectraForSelectedPinsButton;
private AbstractButton showSpectraForAllPinsButton;
private AbstractButton showGridButton;
// todo - not yet implemented for 4.1 but planned for 4.2 (mp - 31.10.2007)
// private AbstractButton showAveragePinSpectrumButton;
// private AbstractButton showGraphPointsButton;
private int pixelX;
private int pixelY;
private int level;
public SpectrumToolView() {
productNodeHandler = new ProductNodeHandler();
productToDiagramMap = new HashMap<Product, SpectraDiagram>(4);
cursorSpectrumPPLMap = new HashMap<Product, CursorSpectrumPPL>(4);
}
public ProductSceneView getCurrentView() {
return currentView;
}
public void setCurrentView(ProductSceneView view) {
if (originalDescriptorTitle != null) {
originalDescriptorTitle = getDescriptor().getTitle();
}
ProductSceneView oldView = currentView;
currentView = view;
if (oldView != currentView) {
if (currentView != null) {
setCurrentProduct(currentView.getProduct());
}
updateUIState();
}
}
public Product getCurrentProduct() {
return currentProduct;
}
public void setCurrentProduct(Product product) {
Product oldProduct = currentProduct;
currentProduct = product;
if (currentProduct != oldProduct) {
if (oldProduct != null) {
oldProduct.removeProductNodeListener(productNodeHandler);
}
if (currentProduct != null) {
currentProduct.addProductNodeListener(productNodeHandler);
// reset stored pixel location, may be invalid for new product
pixelX = 0;
pixelY = 0;
SpectraDiagram spectraDiagram = getSpectraDiagram();
if (spectraDiagram != null) {
diagramCanvas.setDiagram(spectraDiagram);
} else {
recreateSpectraDiagram();
}
}
if (currentProduct == null) {
diagramCanvas.setDiagram(null);
diagramCanvas.setMessageText("No product selected."); /*I18N*/
} else {
diagramCanvas.setMessageText(null);
}
updateUIState();
updateTitle();
}
}
private void updateTitle() {
if (currentProduct != null) {
setTitle(getDescriptor().getTitle() + " - " + currentView.getProduct().getProductRefString());
} else {
setTitle(getDescriptor().getTitle());
}
}
private void updateUIState() {
boolean hasView = getCurrentView() != null;
boolean hasProduct = getCurrentProduct() != null;
boolean hasSelectedPins = hasProduct && getCurrentProduct().getPinGroup().getSelectedNode() != null;
boolean hasPins = hasProduct && getCurrentProduct().getPinGroup().getNodeCount() > 0;
boolean hasDiagram = diagramCanvas.getDiagram() != null;
filterButton.setEnabled(hasProduct);
showSpectrumForCursorButton.setEnabled(hasView);
showSpectraForSelectedPinsButton.setEnabled(hasSelectedPins);
showSpectraForAllPinsButton.setEnabled(hasPins);
showGridButton.setEnabled(hasDiagram);
// todo - not yet implemented for 4.1 but planned for 4.2 (mp - 31.10.2007)
// showAveragePinSpectrumButton.setEnabled(hasPins); // todo - hasSpectraGraphs
// showGraphPointsButton.setEnabled(hasDiagram);
diagramCanvas.setEnabled(hasProduct); // todo - hasSpectraGraphs
if (diagramCanvas.getDiagram() != null) {
showGridButton.setSelected(diagramCanvas.getDiagram().getDrawGrid());
}
}
public void updateSpectra(int pixelX, int pixelY, int level) {
maybeShowTip();
diagramCanvas.setMessageText(null);
this.pixelX = pixelX;
this.pixelY = pixelY;
this.level = level;
SpectraDiagram spectraDiagram = getSpectraDiagram();
if (spectraDiagram.getBands().length > 0) {
spectraDiagram.updateSpectra(pixelX, pixelY, level);
} else {
diagramCanvas.setMessageText(MSG_NO_SPECTRAL_BANDS);
}
}
private void maybeShowTip() {
if (!tipShown) {
final String message = "Tip: If you press the SHIFT key while moving the mouse cursor over \n" +
"an image, " + VisatApp.getApp().getAppName() + " adjusts the diagram axes " +
"to the local values at the\n" +
"current pixel position, if you release the SHIFT key again, then the\n" +
"min/max are accumulated again.";
VisatApp.getApp().showInfoDialog("Spectrum Tip", message, SUPPRESS_MESSAGE_KEY);
tipShown = true;
}
}
private Band[] getSelectedSpectralBands() {
return getSpectraDiagram().getBands();
}
private Band[] getAvailableSpectralBands() {
Debug.assertNotNull(getCurrentProduct());
Band[] bands = getCurrentProduct().getBands();
ArrayList<Band> spectralBands = new ArrayList<Band>(15);
for (Band band : bands) {
if (band.getSpectralWavelength() > 0.0) {
if (!band.isFlagBand()) {
spectralBands.add(band);
}
}
}
return spectralBands.toArray(new Band[spectralBands.size()]);
}
@Override
public JComponent createControl() {
filterButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Filter24.gif"), false);
filterButton.setName("filterButton");
filterButton.setEnabled(false);
filterButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectSpectralBands();
}
});
showSpectrumForCursorButton = ToolButtonFactory.createButton(
UIUtils.loadImageIcon("icons/CursorSpectrum24.gif"), true);
showSpectrumForCursorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
recreateSpectraDiagram();
}
});
showSpectrumForCursorButton.setName("showSpectrumForCursorButton");
showSpectrumForCursorButton.setSelected(true);
showSpectrumForCursorButton.setToolTipText("Show spectrum at cursor position.");
showSpectraForSelectedPinsButton = ToolButtonFactory.createButton(
UIUtils.loadImageIcon("icons/SelectedPinSpectra24.gif"), true);
showSpectraForSelectedPinsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (isShowingSpectraForAllPins()) {
showSpectraForAllPinsButton.setSelected(false);
}
recreateSpectraDiagram();
}
});
showSpectraForSelectedPinsButton.setName("showSpectraForSelectedPinsButton");
showSpectraForSelectedPinsButton.setToolTipText("Show spectra for selected pins.");
showSpectraForAllPinsButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/PinSpectra24.gif"),
true);
showSpectraForAllPinsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (isShowingSpectraForSelectedPins()) {
showSpectraForSelectedPinsButton.setSelected(false);
}
recreateSpectraDiagram();
}
});
showSpectraForAllPinsButton.setName("showSpectraForAllPinsButton");
showSpectraForAllPinsButton.setToolTipText("Show spectra for all pins.");
// todo - not yet implemented for 4.1 but planned for 4.2 (mp - 31.10.2007)
// showAveragePinSpectrumButton = ToolButtonFactory.createButton(
// UIUtils.loadImageIcon("icons/AverageSpectrum24.gif"), true);
// showAveragePinSpectrumButton.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// // todo - implement
// JOptionPane.showMessageDialog(null, "Not implemented");
// }
// });
// showAveragePinSpectrumButton.setName("showAveragePinSpectrumButton");
// showAveragePinSpectrumButton.setToolTipText("Show average spectrum of all pin spectra.");
showGridButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/SpectrumGrid24.gif"), true);
showGridButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
- diagramCanvas.getDiagram().setDrawGrid(showGridButton.isSelected());
+ if (diagramCanvas.getDiagram() != null) {
+ diagramCanvas.getDiagram().setDrawGrid(showGridButton.isSelected());
+ }
}
});
showGridButton.setName("showGridButton");
showGridButton.setToolTipText("Show diagram grid.");
// todo - not yet implemented for 4.1 but planned for 4.2 (mp - 31.10.2007)
// showGraphPointsButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/GraphPoints24.gif"), true);
// showGraphPointsButton.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// // todo - implement
// JOptionPane.showMessageDialog(null, "Not implemented");
// }
// });
// showGraphPointsButton.setName("showGraphPointsButton");
// showGraphPointsButton.setToolTipText("Show graph points grid.");
AbstractButton exportSpectraButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Export24.gif"),
false);
exportSpectraButton.addActionListener(new SpectraExportAction(this));
exportSpectraButton.setToolTipText("Export spectra to text file.");
exportSpectraButton.setName("exportSpectraButton");
AbstractButton helpButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Help24.gif"), false);
helpButton.setName("helpButton");
helpButton.setToolTipText("Help."); /*I18N*/
final JPanel buttonPane = GridBagUtils.createPanel();
final GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.NONE;
gbc.insets.top = 2;
gbc.gridy = 0;
buttonPane.add(filterButton, gbc);
gbc.gridy++;
buttonPane.add(showSpectrumForCursorButton, gbc);
gbc.gridy++;
buttonPane.add(showSpectraForSelectedPinsButton, gbc);
gbc.gridy++;
buttonPane.add(showSpectraForAllPinsButton, gbc);
gbc.gridy++;
// todo - not yet implemented for 4.1 but planned for 4.2 (mp - 31.10.2007)
// buttonPane.add(showAveragePinSpectrumButton, gbc);
// gbc.gridy++;
buttonPane.add(showGridButton, gbc);
gbc.gridy++;
// todo - not yet implemented for 4.1 but planned for 4.2 (mp - 31.10.2007)
// buttonPane.add(showGraphPointsButton, gbc);
// gbc.gridy++;
buttonPane.add(exportSpectraButton, gbc);
gbc.gridy++;
gbc.insets.bottom = 0;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.weighty = 1.0;
gbc.gridwidth = 2;
buttonPane.add(new JLabel(" "), gbc); // filler
gbc.fill = GridBagConstraints.NONE;
gbc.weighty = 0.0;
gbc.gridy = 10;
gbc.anchor = GridBagConstraints.EAST;
buttonPane.add(helpButton, gbc);
diagramCanvas = new DiagramCanvas();
diagramCanvas.setPreferredSize(new Dimension(300, 200));
diagramCanvas.setMessageText("No product selected."); /*I18N*/
diagramCanvas.setBackground(Color.white);
diagramCanvas.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createBevelBorder(BevelBorder.LOWERED),
BorderFactory.createEmptyBorder(2, 2, 2, 2)));
JPanel mainPane = new JPanel(new BorderLayout(4, 4));
mainPane.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
mainPane.add(BorderLayout.CENTER, diagramCanvas);
mainPane.add(BorderLayout.EAST, buttonPane);
mainPane.setPreferredSize(new Dimension(320, 200));
if (getDescriptor().getHelpId() != null) {
HelpSys.enableHelpOnButton(helpButton, getDescriptor().getHelpId());
HelpSys.enableHelpKey(mainPane, getDescriptor().getHelpId());
}
// Add an internal frame listener to VISAT so that we can update our
// spectrum dialog with the information of the currently activated
// product scene view.
//
VisatApp.getApp().addInternalFrameListener(new SpectrumIFL());
VisatApp.getApp().getProductManager().addListener(new ProductManager.Listener() {
public void productAdded(ProductManager.Event event) {
// ignored
}
public void productRemoved(ProductManager.Event event) {
final Product product = event.getProduct();
cursorSpectrumPPLMap.remove(product);
if (getCurrentProduct() == product) {
setSpectraDiagram(null);
setCurrentView(null);
setCurrentProduct(null);
}
}
});
final ProductSceneView view = VisatApp.getApp().getSelectedProductSceneView();
if (view != null) {
handleViewActivated(view);
} else {
setCurrentView(view);
}
return mainPane;
}
private void selectSpectralBands() {
Band[] allBandNames = getAvailableSpectralBands();
Band[] selectedBands = getSelectedSpectralBands();
if (selectedBands == null) {
selectedBands = allBandNames;
}
BandChooser bandChooser = new BandChooser(getWindowAncestor(), "Available Spectral Bands",
getDescriptor().getHelpId(),
allBandNames, selectedBands);
if (bandChooser.show() == ModalDialog.ID_OK) {
getSpectraDiagram().setBands(bandChooser.getSelectedBands());
}
}
public SpectraDiagram getSpectraDiagram() {
Debug.assertNotNull(currentProduct);
return productToDiagramMap.get(currentProduct);
}
private void setSpectraDiagram(final SpectraDiagram newDiagram) {
Debug.assertNotNull(currentProduct);
SpectraDiagram oldDiagram;
if (newDiagram != null) {
oldDiagram = productToDiagramMap.put(currentProduct, newDiagram);
} else {
oldDiagram = productToDiagramMap.remove(currentProduct);
}
diagramCanvas.setDiagram(newDiagram);
if (oldDiagram != null && oldDiagram != newDiagram) {
oldDiagram.dispose();
}
}
private CursorSpectrumPPL getOrCreateCursorSpectrumPPL(Product product) {
CursorSpectrumPPL ppl = getCursorSpectrumPPL(product);
if (ppl == null) {
ppl = new CursorSpectrumPPL(product);
cursorSpectrumPPLMap.put(product, ppl);
}
return ppl;
}
private CursorSpectrumPPL getCursorSpectrumPPL(Product product) {
return cursorSpectrumPPLMap.get(product);
}
private boolean isShowingCursorSpectrum() {
return showSpectrumForCursorButton.isSelected();
}
private boolean isShowingPinSpectra() {
return isShowingSpectraForSelectedPins() || isShowingSpectraForAllPins();
}
private boolean isShowingSpectraForAllPins() {
return showSpectraForAllPinsButton.isSelected();
}
private void recreateSpectraDiagram() {
SpectraDiagram spectraDiagram = new SpectraDiagram(getCurrentProduct());
if (isShowingSpectraForSelectedPins()) {
ProductNodeGroup<Pin> pinGroup = getCurrentProduct().getPinGroup();
Pin[] pins = pinGroup.toArray(new Pin[pinGroup.getNodeCount()]);
for (Pin pin : pins) {
if (pin.isSelected()) {
spectraDiagram.addSpectrumGraph(pin);
}
}
} else if (isShowingSpectraForAllPins()) {
ProductNodeGroup<Pin> pinGroup = getCurrentProduct().getPinGroup();
Pin[] pins = pinGroup.toArray(new Pin[pinGroup.getNodeCount()]);
for (Pin pin : pins) {
spectraDiagram.addSpectrumGraph(pin);
}
}
if (isShowingCursorSpectrum()) {
spectraDiagram.addCursorSpectrumGraph();
}
if (getSpectraDiagram() != null && getSelectedSpectralBands() != null) {
spectraDiagram.setBands(getSelectedSpectralBands());
} else {
spectraDiagram.setBands(getAvailableSpectralBands());
}
spectraDiagram.updateSpectra(pixelX, pixelY, level);
setSpectraDiagram(spectraDiagram);
}
private boolean isShowingSpectraForSelectedPins() {
return showSpectraForSelectedPinsButton.isSelected();
}
private void handleViewActivated(final ProductSceneView view) {
final Product product = view.getProduct();
view.addPixelPositionListener(getOrCreateCursorSpectrumPPL(product));
setCurrentView(view);
}
private void handleViewDeactivated(final ProductSceneView view) {
final Product product = view.getProduct();
view.removePixelPositionListener(getCursorSpectrumPPL(product));
setCurrentView(null);
}
/////////////////////////////////////////////////////////////////////////
// View change handling
private class SpectrumIFL extends InternalFrameAdapter {
@Override
public void internalFrameActivated(InternalFrameEvent e) {
final Container contentPane = e.getInternalFrame().getContentPane();
if (contentPane instanceof ProductSceneView) {
handleViewActivated((ProductSceneView) contentPane);
}
}
@Override
public void internalFrameDeactivated(InternalFrameEvent e) {
final Container contentPane = e.getInternalFrame().getContentPane();
if (contentPane instanceof ProductSceneView) {
handleViewDeactivated((ProductSceneView) contentPane);
}
}
}
/////////////////////////////////////////////////////////////////////////
// Pixel position change handling
private class CursorSpectrumPPL implements PixelPositionListener {
private final Product _product;
public CursorSpectrumPPL(Product product) {
_product = product;
}
public Product getProduct() {
return _product;
}
public void pixelPosChanged(ImageLayer imageLayer,
int pixelX,
int pixelY,
int currentLevel,
boolean pixelPosValid,
MouseEvent e) {
diagramCanvas.setMessageText(null);
if (isActive()) {
if (pixelPosValid) {
getSpectraDiagram().addCursorSpectrumGraph();
updateSpectra(pixelX, pixelY, currentLevel);
}
}
if (e.isShiftDown()) {
getSpectraDiagram().adjustAxes(true);
}
}
public void pixelPosNotAvailable() {
if (isActive()) {
getSpectraDiagram().removeCursorSpectrumGraph();
diagramCanvas.repaint();
}
}
private boolean isActive() {
return isVisible() && isShowingCursorSpectrum() && getSpectraDiagram() != null;
}
}
/////////////////////////////////////////////////////////////////////////
// Product change handling
private class ProductNodeHandler extends ProductNodeListenerAdapter {
@Override
public void nodeChanged(final ProductNodeEvent event) {
if (!isActive()) {
return;
}
if (event.getSourceNode() instanceof Band) {
final String propertyName = event.getPropertyName();
if (propertyName.equals(DataNode.PROPERTY_NAME_UNIT)
|| propertyName.equals(Band.PROPERTY_NAME_SPECTRAL_WAVELENGTH)) {
recreateSpectraDiagram();
}
} else if (event.getSourceNode() instanceof Pin) {
if (isShowingPinSpectra()) {
recreateSpectraDiagram();
}
}
updateUIState();
}
@Override
public void nodeAdded(final ProductNodeEvent event) {
if (!isActive()) {
return;
}
if (event.getSourceNode() instanceof Band) {
recreateSpectraDiagram();
} else if (event.getSourceNode() instanceof Pin) {
if (isShowingPinSpectra()) {
recreateSpectraDiagram();
}
}
updateUIState();
}
@Override
public void nodeRemoved(final ProductNodeEvent event) {
if (!isActive()) {
return;
}
if (event.getSourceNode() instanceof Band) {
recreateSpectraDiagram();
} else if (event.getSourceNode() instanceof Pin) {
if (isShowingPinSpectra()) {
recreateSpectraDiagram();
}
}
updateUIState();
}
private boolean isActive() {
return isVisible() && getCurrentProduct() != null;
}
}
}
| true | true | public JComponent createControl() {
filterButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Filter24.gif"), false);
filterButton.setName("filterButton");
filterButton.setEnabled(false);
filterButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectSpectralBands();
}
});
showSpectrumForCursorButton = ToolButtonFactory.createButton(
UIUtils.loadImageIcon("icons/CursorSpectrum24.gif"), true);
showSpectrumForCursorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
recreateSpectraDiagram();
}
});
showSpectrumForCursorButton.setName("showSpectrumForCursorButton");
showSpectrumForCursorButton.setSelected(true);
showSpectrumForCursorButton.setToolTipText("Show spectrum at cursor position.");
showSpectraForSelectedPinsButton = ToolButtonFactory.createButton(
UIUtils.loadImageIcon("icons/SelectedPinSpectra24.gif"), true);
showSpectraForSelectedPinsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (isShowingSpectraForAllPins()) {
showSpectraForAllPinsButton.setSelected(false);
}
recreateSpectraDiagram();
}
});
showSpectraForSelectedPinsButton.setName("showSpectraForSelectedPinsButton");
showSpectraForSelectedPinsButton.setToolTipText("Show spectra for selected pins.");
showSpectraForAllPinsButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/PinSpectra24.gif"),
true);
showSpectraForAllPinsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (isShowingSpectraForSelectedPins()) {
showSpectraForSelectedPinsButton.setSelected(false);
}
recreateSpectraDiagram();
}
});
showSpectraForAllPinsButton.setName("showSpectraForAllPinsButton");
showSpectraForAllPinsButton.setToolTipText("Show spectra for all pins.");
// todo - not yet implemented for 4.1 but planned for 4.2 (mp - 31.10.2007)
// showAveragePinSpectrumButton = ToolButtonFactory.createButton(
// UIUtils.loadImageIcon("icons/AverageSpectrum24.gif"), true);
// showAveragePinSpectrumButton.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// // todo - implement
// JOptionPane.showMessageDialog(null, "Not implemented");
// }
// });
// showAveragePinSpectrumButton.setName("showAveragePinSpectrumButton");
// showAveragePinSpectrumButton.setToolTipText("Show average spectrum of all pin spectra.");
showGridButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/SpectrumGrid24.gif"), true);
showGridButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
diagramCanvas.getDiagram().setDrawGrid(showGridButton.isSelected());
}
});
showGridButton.setName("showGridButton");
showGridButton.setToolTipText("Show diagram grid.");
// todo - not yet implemented for 4.1 but planned for 4.2 (mp - 31.10.2007)
// showGraphPointsButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/GraphPoints24.gif"), true);
// showGraphPointsButton.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// // todo - implement
// JOptionPane.showMessageDialog(null, "Not implemented");
// }
// });
// showGraphPointsButton.setName("showGraphPointsButton");
// showGraphPointsButton.setToolTipText("Show graph points grid.");
AbstractButton exportSpectraButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Export24.gif"),
false);
exportSpectraButton.addActionListener(new SpectraExportAction(this));
exportSpectraButton.setToolTipText("Export spectra to text file.");
exportSpectraButton.setName("exportSpectraButton");
AbstractButton helpButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Help24.gif"), false);
helpButton.setName("helpButton");
helpButton.setToolTipText("Help."); /*I18N*/
final JPanel buttonPane = GridBagUtils.createPanel();
final GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.NONE;
gbc.insets.top = 2;
gbc.gridy = 0;
buttonPane.add(filterButton, gbc);
gbc.gridy++;
buttonPane.add(showSpectrumForCursorButton, gbc);
gbc.gridy++;
buttonPane.add(showSpectraForSelectedPinsButton, gbc);
gbc.gridy++;
buttonPane.add(showSpectraForAllPinsButton, gbc);
gbc.gridy++;
// todo - not yet implemented for 4.1 but planned for 4.2 (mp - 31.10.2007)
// buttonPane.add(showAveragePinSpectrumButton, gbc);
// gbc.gridy++;
buttonPane.add(showGridButton, gbc);
gbc.gridy++;
// todo - not yet implemented for 4.1 but planned for 4.2 (mp - 31.10.2007)
// buttonPane.add(showGraphPointsButton, gbc);
// gbc.gridy++;
buttonPane.add(exportSpectraButton, gbc);
gbc.gridy++;
gbc.insets.bottom = 0;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.weighty = 1.0;
gbc.gridwidth = 2;
buttonPane.add(new JLabel(" "), gbc); // filler
gbc.fill = GridBagConstraints.NONE;
gbc.weighty = 0.0;
gbc.gridy = 10;
gbc.anchor = GridBagConstraints.EAST;
buttonPane.add(helpButton, gbc);
diagramCanvas = new DiagramCanvas();
diagramCanvas.setPreferredSize(new Dimension(300, 200));
diagramCanvas.setMessageText("No product selected."); /*I18N*/
diagramCanvas.setBackground(Color.white);
diagramCanvas.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createBevelBorder(BevelBorder.LOWERED),
BorderFactory.createEmptyBorder(2, 2, 2, 2)));
JPanel mainPane = new JPanel(new BorderLayout(4, 4));
mainPane.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
mainPane.add(BorderLayout.CENTER, diagramCanvas);
mainPane.add(BorderLayout.EAST, buttonPane);
mainPane.setPreferredSize(new Dimension(320, 200));
if (getDescriptor().getHelpId() != null) {
HelpSys.enableHelpOnButton(helpButton, getDescriptor().getHelpId());
HelpSys.enableHelpKey(mainPane, getDescriptor().getHelpId());
}
// Add an internal frame listener to VISAT so that we can update our
// spectrum dialog with the information of the currently activated
// product scene view.
//
VisatApp.getApp().addInternalFrameListener(new SpectrumIFL());
VisatApp.getApp().getProductManager().addListener(new ProductManager.Listener() {
public void productAdded(ProductManager.Event event) {
// ignored
}
public void productRemoved(ProductManager.Event event) {
final Product product = event.getProduct();
cursorSpectrumPPLMap.remove(product);
if (getCurrentProduct() == product) {
setSpectraDiagram(null);
setCurrentView(null);
setCurrentProduct(null);
}
}
});
final ProductSceneView view = VisatApp.getApp().getSelectedProductSceneView();
if (view != null) {
handleViewActivated(view);
} else {
setCurrentView(view);
}
return mainPane;
}
| public JComponent createControl() {
filterButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Filter24.gif"), false);
filterButton.setName("filterButton");
filterButton.setEnabled(false);
filterButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectSpectralBands();
}
});
showSpectrumForCursorButton = ToolButtonFactory.createButton(
UIUtils.loadImageIcon("icons/CursorSpectrum24.gif"), true);
showSpectrumForCursorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
recreateSpectraDiagram();
}
});
showSpectrumForCursorButton.setName("showSpectrumForCursorButton");
showSpectrumForCursorButton.setSelected(true);
showSpectrumForCursorButton.setToolTipText("Show spectrum at cursor position.");
showSpectraForSelectedPinsButton = ToolButtonFactory.createButton(
UIUtils.loadImageIcon("icons/SelectedPinSpectra24.gif"), true);
showSpectraForSelectedPinsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (isShowingSpectraForAllPins()) {
showSpectraForAllPinsButton.setSelected(false);
}
recreateSpectraDiagram();
}
});
showSpectraForSelectedPinsButton.setName("showSpectraForSelectedPinsButton");
showSpectraForSelectedPinsButton.setToolTipText("Show spectra for selected pins.");
showSpectraForAllPinsButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/PinSpectra24.gif"),
true);
showSpectraForAllPinsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (isShowingSpectraForSelectedPins()) {
showSpectraForSelectedPinsButton.setSelected(false);
}
recreateSpectraDiagram();
}
});
showSpectraForAllPinsButton.setName("showSpectraForAllPinsButton");
showSpectraForAllPinsButton.setToolTipText("Show spectra for all pins.");
// todo - not yet implemented for 4.1 but planned for 4.2 (mp - 31.10.2007)
// showAveragePinSpectrumButton = ToolButtonFactory.createButton(
// UIUtils.loadImageIcon("icons/AverageSpectrum24.gif"), true);
// showAveragePinSpectrumButton.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// // todo - implement
// JOptionPane.showMessageDialog(null, "Not implemented");
// }
// });
// showAveragePinSpectrumButton.setName("showAveragePinSpectrumButton");
// showAveragePinSpectrumButton.setToolTipText("Show average spectrum of all pin spectra.");
showGridButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/SpectrumGrid24.gif"), true);
showGridButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (diagramCanvas.getDiagram() != null) {
diagramCanvas.getDiagram().setDrawGrid(showGridButton.isSelected());
}
}
});
showGridButton.setName("showGridButton");
showGridButton.setToolTipText("Show diagram grid.");
// todo - not yet implemented for 4.1 but planned for 4.2 (mp - 31.10.2007)
// showGraphPointsButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/GraphPoints24.gif"), true);
// showGraphPointsButton.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// // todo - implement
// JOptionPane.showMessageDialog(null, "Not implemented");
// }
// });
// showGraphPointsButton.setName("showGraphPointsButton");
// showGraphPointsButton.setToolTipText("Show graph points grid.");
AbstractButton exportSpectraButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Export24.gif"),
false);
exportSpectraButton.addActionListener(new SpectraExportAction(this));
exportSpectraButton.setToolTipText("Export spectra to text file.");
exportSpectraButton.setName("exportSpectraButton");
AbstractButton helpButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Help24.gif"), false);
helpButton.setName("helpButton");
helpButton.setToolTipText("Help."); /*I18N*/
final JPanel buttonPane = GridBagUtils.createPanel();
final GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.NONE;
gbc.insets.top = 2;
gbc.gridy = 0;
buttonPane.add(filterButton, gbc);
gbc.gridy++;
buttonPane.add(showSpectrumForCursorButton, gbc);
gbc.gridy++;
buttonPane.add(showSpectraForSelectedPinsButton, gbc);
gbc.gridy++;
buttonPane.add(showSpectraForAllPinsButton, gbc);
gbc.gridy++;
// todo - not yet implemented for 4.1 but planned for 4.2 (mp - 31.10.2007)
// buttonPane.add(showAveragePinSpectrumButton, gbc);
// gbc.gridy++;
buttonPane.add(showGridButton, gbc);
gbc.gridy++;
// todo - not yet implemented for 4.1 but planned for 4.2 (mp - 31.10.2007)
// buttonPane.add(showGraphPointsButton, gbc);
// gbc.gridy++;
buttonPane.add(exportSpectraButton, gbc);
gbc.gridy++;
gbc.insets.bottom = 0;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.weighty = 1.0;
gbc.gridwidth = 2;
buttonPane.add(new JLabel(" "), gbc); // filler
gbc.fill = GridBagConstraints.NONE;
gbc.weighty = 0.0;
gbc.gridy = 10;
gbc.anchor = GridBagConstraints.EAST;
buttonPane.add(helpButton, gbc);
diagramCanvas = new DiagramCanvas();
diagramCanvas.setPreferredSize(new Dimension(300, 200));
diagramCanvas.setMessageText("No product selected."); /*I18N*/
diagramCanvas.setBackground(Color.white);
diagramCanvas.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createBevelBorder(BevelBorder.LOWERED),
BorderFactory.createEmptyBorder(2, 2, 2, 2)));
JPanel mainPane = new JPanel(new BorderLayout(4, 4));
mainPane.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
mainPane.add(BorderLayout.CENTER, diagramCanvas);
mainPane.add(BorderLayout.EAST, buttonPane);
mainPane.setPreferredSize(new Dimension(320, 200));
if (getDescriptor().getHelpId() != null) {
HelpSys.enableHelpOnButton(helpButton, getDescriptor().getHelpId());
HelpSys.enableHelpKey(mainPane, getDescriptor().getHelpId());
}
// Add an internal frame listener to VISAT so that we can update our
// spectrum dialog with the information of the currently activated
// product scene view.
//
VisatApp.getApp().addInternalFrameListener(new SpectrumIFL());
VisatApp.getApp().getProductManager().addListener(new ProductManager.Listener() {
public void productAdded(ProductManager.Event event) {
// ignored
}
public void productRemoved(ProductManager.Event event) {
final Product product = event.getProduct();
cursorSpectrumPPLMap.remove(product);
if (getCurrentProduct() == product) {
setSpectraDiagram(null);
setCurrentView(null);
setCurrentProduct(null);
}
}
});
final ProductSceneView view = VisatApp.getApp().getSelectedProductSceneView();
if (view != null) {
handleViewActivated(view);
} else {
setCurrentView(view);
}
return mainPane;
}
|
diff --git a/src/to/joe/util/Packeteer/Packeteer20NamedEntitySpawn.java b/src/to/joe/util/Packeteer/Packeteer20NamedEntitySpawn.java
index b8517bb..f30a5dc 100644
--- a/src/to/joe/util/Packeteer/Packeteer20NamedEntitySpawn.java
+++ b/src/to/joe/util/Packeteer/Packeteer20NamedEntitySpawn.java
@@ -1,33 +1,33 @@
package to.joe.util.Packeteer;
import net.minecraft.server.Packet20NamedEntitySpawn;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.getspout.spout.packet.standard.MCCraftPacket;
import org.getspout.spoutapi.packet.listener.PacketListener;
import org.getspout.spoutapi.packet.standard.MCPacket;
import to.joe.util.Vanish;
public class Packeteer20NamedEntitySpawn implements PacketListener {
private final Vanish vanish;
public Packeteer20NamedEntitySpawn(Vanish vanish) {
this.vanish = vanish;
}
@Override
public boolean checkPacket(Player player, MCPacket packet) {
final Packet20NamedEntitySpawn packet20 = (Packet20NamedEntitySpawn) ((MCCraftPacket) packet).getPacket();
if (this.vanish.isEIDVanished(packet20.a)) {
packet20.b = ChatColor.DARK_AQUA + packet20.b;
- if(packet20.b.length()==16){
+ if(packet20.b.length()>15){
packet20.b=packet20.b.substring(0, 15);
}
}
return !this.vanish.shouldHide(player, packet20.a);
}
}
| true | true | public boolean checkPacket(Player player, MCPacket packet) {
final Packet20NamedEntitySpawn packet20 = (Packet20NamedEntitySpawn) ((MCCraftPacket) packet).getPacket();
if (this.vanish.isEIDVanished(packet20.a)) {
packet20.b = ChatColor.DARK_AQUA + packet20.b;
if(packet20.b.length()==16){
packet20.b=packet20.b.substring(0, 15);
}
}
return !this.vanish.shouldHide(player, packet20.a);
}
| public boolean checkPacket(Player player, MCPacket packet) {
final Packet20NamedEntitySpawn packet20 = (Packet20NamedEntitySpawn) ((MCCraftPacket) packet).getPacket();
if (this.vanish.isEIDVanished(packet20.a)) {
packet20.b = ChatColor.DARK_AQUA + packet20.b;
if(packet20.b.length()>15){
packet20.b=packet20.b.substring(0, 15);
}
}
return !this.vanish.shouldHide(player, packet20.a);
}
|
diff --git a/src/com/android/shakemusic/Instrument.java b/src/com/android/shakemusic/Instrument.java
index 2b4c957..5a2ccb6 100644
--- a/src/com/android/shakemusic/Instrument.java
+++ b/src/com/android/shakemusic/Instrument.java
@@ -1,16 +1,16 @@
package com.android.shakemusic;
public interface Instrument {
final int fs = 44100;
final double inharmonity = 0.01;
final double gam = 1.7;
final double pi = Math.PI;
final double pisqr = pi * pi;
final int NORM_BPM = 80;
final int HIGH_BPM = 120;
final int LOW_BPM = 60;
- public short[] Note(int freq);
+ public byte[] Note(int freq);
}
| true | true | public short[] Note(int freq);
| public byte[] Note(int freq);
|
diff --git a/src_new/org/argouml/ui/ProjectBrowser.java b/src_new/org/argouml/ui/ProjectBrowser.java
index ad2c97e..8b7e23c 100644
--- a/src_new/org/argouml/ui/ProjectBrowser.java
+++ b/src_new/org/argouml/ui/ProjectBrowser.java
@@ -1,823 +1,824 @@
// Copyright (c) 1996-2001 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.ui;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import ru.novosoft.uml.foundation.core.*;
import ru.novosoft.uml.model_management.*;
import org.tigris.gef.base.*;
import org.tigris.gef.ui.*;
import org.tigris.gef.util.*;
import org.argouml.application.api.*;
import org.argouml.application.events.*;
import org.argouml.kernel.*;
import org.argouml.ui.*;
import org.argouml.cognitive.*;
import org.argouml.cognitive.ui.*;
import org.argouml.uml.diagram.ui.UMLDiagram;
import org.argouml.uml.ui.*;
/** The main window of the Argo/UML application. */
public class ProjectBrowser extends JFrame
implements IStatusBar, NavigationListener, ArgoModuleEventListener {
////////////////////////////////////////////////////////////////
// constants
// public static int WIDTH = 800;
// public static int HEIGHT = 600;
// public static int INITIAL_WIDTH = 400; // for showing progress bar
// public static int INITIAL_HEIGHT = 200;
public static int DEFAULT_VSPLIT = 270;
public static int DEFAULT_HSPLIT = 512;
////////////////////////////////////////////////////////////////
// class variables
public static ProjectBrowser TheInstance;
protected static Action _actionCreateMultiple = Actions.CreateMultiple;
// ----- diagrams
protected static Action _actionClassDiagram = ActionClassDiagram.SINGLETON;
protected static Action _actionUseCaseDiagram = ActionUseCaseDiagram.SINGLETON;
protected static Action _actionStateDiagram = ActionStateDiagram.SINGLETON;
protected static Action _actionActivityDiagram = ActionActivityDiagram.SINGLETON;
protected static Action _actionCollaborationDiagram = ActionCollaborationDiagram.SINGLETON;
protected static Action _actionDeploymentDiagram = ActionDeploymentDiagram.SINGLETON;
protected static Action _actionSequenceDiagram = ActionSequenceDiagram.SINGLETON;
// ----- model elements
//protected static Action _actionModel = Actions.MModel;
protected static Action _actionAddTopLevelPackage = ActionAddTopLevelPackage.SINGLETON;
////////////////////////////////////////////////////////////////
// instance variables
protected String _appName = "ProjectBrowser";
protected Project _project = null;
protected NavigatorPane _navPane;
public ToDoPane _toDoPane;
protected MultiEditorPane _multiPane;
protected DetailsPane _detailsPane;
protected JMenuBar _menuBar = new JMenuBar();
protected JMenu _tools = null;
protected StatusBar _statusBar = new StatusBar();
//protected JToolBar _toolBar = new JToolBar();
protected ComponentResizer _componentResizer = null;
public Font defaultFont = new Font("Dialog", Font.PLAIN, 10);
// public static JFrame _Frame;
protected JSplitPane _mainSplit, _topSplit, _botSplit;
private NavigationHistory _history = new NavigationHistory();
////////////////////////////////////////////////////////////////
// constructors
public ProjectBrowser() {new ProjectBrowser("Test",null);}
public ProjectBrowser(String appName, StatusBar sb) {
super(appName);
sb.showStatus("Making Project Browser: Navigator Pane");
sb.incProgress(5);
_navPane = new NavigatorPane();
sb.showStatus("Making Project Browser: To Do Pane");
sb.incProgress(5);
_toDoPane = new ToDoPane();
_multiPane = new MultiEditorPane(sb);
_multiPane.addNavigationListener(this);
_detailsPane = new DetailsPane(sb);
_detailsPane.addNavigationListener(this);
setAppName(appName);
if (TheInstance == null) TheInstance = this;
//setName(title);
//loadImages();
getContentPane().setFont(defaultFont);
getContentPane().setLayout(new BorderLayout());
initMenus();
//initToolBar();
getContentPane().add(_menuBar, BorderLayout.NORTH);
//JPanel p = new JPanel();
//p.setLayout(new BorderLayout());
//getContentPane().add(p, BorderLayout.CENTER);
//p.add(_toolBar, BorderLayout.NORTH);
getContentPane().add(createPanels(), BorderLayout.CENTER);
getContentPane().add(_statusBar, BorderLayout.SOUTH);
_toDoPane.setRoot(Designer.TheDesigner.getToDoList());
// allows me to ask "Do you want to save first?"
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowCloser());
if (_componentResizer == null) _componentResizer = new ComponentResizer();
addComponentListener(_componentResizer);
}
// void loadImages() {
// String s = "A blue bullet icon - to draw attention to a menu item";
// blueDot = loadImageIcon("images/dot.gif", s);
// s = "A red bullet icon - to draw attention to a menu item";
// redDot = loadImageIcon("images/redDot.gif", s);
// }
public Locale getLocale() {
return Locale.getDefault();
}
static final protected KeyStroke getShortcut(String key) {
return Localizer.getShortcut("CoreMenu",key);
}
static final protected void setMnemonic(JMenuItem item,String key,char defMnemonic) {
String localMnemonic = Localizer.localize("CoreMenu","Mnemonic_" + key);
char mnemonic = defMnemonic;
if(localMnemonic != null && localMnemonic.length() == 1) {
mnemonic = localMnemonic.charAt(0);
}
item.setMnemonic(mnemonic);
}
static final protected String menuLocalize(String key) {
return Localizer.localize("CoreMenu",key);
}
static final protected void setAccelerator(JMenuItem item,KeyStroke keystroke) {
if(keystroke != null) {
item.setAccelerator(keystroke);
}
}
protected void initMenus() {
KeyStroke ctrlN = Localizer.getShortcut("CoreMenu","Shortcut_New");
KeyStroke ctrlO = Localizer.getShortcut("CoreMenu","Shortcut_Open");
KeyStroke ctrlS = Localizer.getShortcut("CoreMenu","Shortcut_Save");
KeyStroke ctrlP = Localizer.getShortcut("CoreMenu","Shortcut_Print");
KeyStroke ctrlA = Localizer.getShortcut("CoreMenu","Shortcut_Select_All");
KeyStroke ctrlC = Localizer.getShortcut("CoreMenu","Shortcut_Copy");
KeyStroke ctrlV = Localizer.getShortcut("CoreMenu","Shortcut_Paste");
KeyStroke ctrlX = Localizer.getShortcut("CoreMenu","Shortcut_Cut");
KeyStroke ctrlR = Localizer.getShortcut("CoreMenu","Shortcut_Remove_From_Diagram");
KeyStroke F3 = Localizer.getShortcut("CoreMenu","Shortcut_Find");
KeyStroke F7 = Localizer.getShortcut("CoreMenu","Shortcut_Generate_All");
KeyStroke altF4 = Localizer.getShortcut("CoreMenu","Shortcut_Exit");
KeyStroke delKey = Localizer.getShortcut("CoreMenu","Shortcut_Delete");
JMenuItem mi;
// File Menu
JMenu file = new JMenu(menuLocalize("File"));
_menuBar.add(file);
setMnemonic(file,"File",'F');
JMenuItem newItem = file.add(ActionNew.SINGLETON);
setMnemonic(newItem,"New",'N');
setAccelerator(newItem,ctrlN);
JMenuItem openProjectItem = file.add(ActionOpenProject.SINGLETON);
setMnemonic(openProjectItem,"Open",'O');
setAccelerator(openProjectItem,ctrlO);
//JMenuItem saveItem = file.add(_actionSave);
//file.add(_actionSaveAs);
//file.add(_actionSaveAsXMI);
JMenuItem saveProjectItem = file.add(ActionSaveProject.SINGLETON);
setMnemonic(saveProjectItem,"Save",'S');
setAccelerator(saveProjectItem,ctrlS);
JMenuItem saveProjectAsItem = file.add(ActionSaveProjectAs.SINGLETON);
setMnemonic(saveProjectAsItem,"SaveAs",'A');
file.addSeparator();
JMenuItem importProjectAsItem = file.add(ActionImportFromSources.SINGLETON);
file.addSeparator();
JMenuItem loadModelFromDBItem = file.add(ActionLoadModelFromDB.SINGLETON);
JMenuItem storeModelToDBItem = file.add(ActionStoreModelToDB.SINGLETON);
file.addSeparator();
JMenuItem printItem = file.add(Actions.Print);
setMnemonic(printItem,"Print",'P');
setAccelerator(printItem,ctrlP);
JMenuItem saveGraphicsItem = file.add(ActionSaveGraphics.SINGLETON);
setMnemonic(saveGraphicsItem,"SaveGraphics",'G');
// JMenuItem savePSItem = file.add(Actions.SavePS);
file.addSeparator();
file.add(ActionSaveConfiguration.SINGLETON);
file.addSeparator();
JMenuItem exitItem = file.add(ActionExit.SINGLETON);
setMnemonic(exitItem,"Exit",'x');
setAccelerator(exitItem,altF4);
JMenu edit = (JMenu) _menuBar.add(new JMenu(menuLocalize("Edit")));
setMnemonic(edit,"Edit",'E');
JMenu select = new JMenu(menuLocalize("Select"));
edit.add(select);
JMenuItem selectAllItem = select.add(new CmdSelectAll());
setAccelerator(selectAllItem,ctrlA);
JMenuItem selectNextItem = select.add(new CmdSelectNext(false));
//tab
JMenuItem selectPrevItem = select.add(new CmdSelectNext(true));
// shift tab
select.add(new CmdSelectInvert());
edit.add(Actions.Undo);
edit.add(Actions.Redo);
edit.addSeparator();
JMenuItem cutItem = edit.add(ActionCut.SINGLETON);
setMnemonic(cutItem,"Cut",'X');
setAccelerator(cutItem,ctrlX);
JMenuItem copyItem = edit.add(ActionCopy.SINGLETON);
setMnemonic(copyItem,"Copy",'C');
setAccelerator(copyItem,ctrlC);
JMenuItem pasteItem = edit.add(ActionPaste.SINGLETON);
setMnemonic(pasteItem,"Paste",'V');
setAccelerator(pasteItem,ctrlV);
edit.addSeparator();
// needs-more-work: confusing name change
JMenuItem deleteItem = edit.add(ActionDeleteFromDiagram.SINGLETON);
setMnemonic(deleteItem,"RemoveFromDiagram",'R');
setAccelerator(deleteItem,ctrlR);
JMenuItem removeItem = edit.add(ActionRemoveFromModel.SINGLETON);
setMnemonic(removeItem,"DeleteFromModel",'D');
setAccelerator(removeItem,delKey);
JMenuItem emptyItem = edit.add(ActionEmptyTrash.SINGLETON);
edit.addSeparator();
edit.add(ActionSettings.getInstance());
Menu view = (Menu) _menuBar.add(new Menu(menuLocalize("View")));
// maybe should be Navigate instead of view
setMnemonic(view,"View",'V');
// JMenu nav = (JMenu) view.add(new JMenu("Navigate"));
// JMenuItem downItem = nav.add(_actionNavDown);
// downItem.setAccelerator(ctrldown);
// JMenuItem upItem = nav.add(_actionNavUp);
// upItem.setAccelerator(ctrlup);
// JMenuItem backItem = nav.add(_actionNavBack);
// backItem.setAccelerator(ctrlleft);
// JMenuItem forwItem = nav.add(_actionNavForw);
// forwItem.setAccelerator(ctrlright);
view.add(Actions.GotoDiagram);
JMenuItem findItem = view.add(Actions.Find);
setAccelerator(findItem,F3);
view.addSeparator();
JMenu zoom = (JMenu) view.add(new JMenu(menuLocalize("Zoom")));
zoom.add(new ActionZoom(25));
zoom.add(new ActionZoom(50));
zoom.add(new ActionZoom(75));
zoom.add(new ActionZoom(100));
zoom.add(new ActionZoom(125));
zoom.add(new ActionZoom(150));
view.addSeparator();
JMenu editTabs = (JMenu) view.add(new JMenu(menuLocalize("Editor Tabs")));
//view.addSeparator();
//view.add(_actionAddToFavorites);
JMenu detailsTabs = (JMenu) view.add(new JMenu(menuLocalize("Details Tabs")));
view.addSeparator();
view.add(new CmdAdjustGrid());
view.add(new CmdAdjustGuide());
view.add(new CmdAdjustPageBreaks());
view.addCheckItem(Actions.ShowRapidButtons);
//JMenu create = (JMenu) _menuBar.add(new JMenu(menuLocalize("Create")));
//setMnemonic(create,"Create",'C');
//create.add(Actions.CreateMultiple);
//create.addSeparator();
JMenu createDiagrams = (JMenu) _menuBar.add(new JMenu(menuLocalize("Create Diagram")));
+ setMnemonic(createDiagrams, "Create Diagram",'C');
createDiagrams.add(ActionClassDiagram.SINGLETON);
createDiagrams.add(ActionUseCaseDiagram.SINGLETON);
createDiagrams.add(ActionStateDiagram.SINGLETON);
createDiagrams.add(ActionActivityDiagram.SINGLETON);
createDiagrams.add(ActionCollaborationDiagram.SINGLETON);
createDiagrams.add(ActionDeploymentDiagram.SINGLETON);
createDiagrams.add(ActionSequenceDiagram.SINGLETON);
//JMenu createModelElements = (JMenu) create.add(new JMenu("Model Elements"));
//createModelElements.add(Actions.AddTopLevelPackage);
//createModelElements.add(_actionClass);
//createModelElements.add(_actionInterface);
//createModelElements.add(_actionActor);
//createModelElements.add(_actionUseCase);
//createModelElements.add(_actionState);
//createModelElements.add(_actionPseudostate);
//createModelElements.add(_actionAttr);
//createModelElements.add(_actionOper);
//JMenu createFig = (JMenu) create.add(new JMenu("Shapes"));
//createFig.add(_actionRectangle);
//createFig.add(_actionRRectangle);
//createFig.add(_actionCircle);
//createFig.add(_actionLine);
//createFig.add(_actionText);
//createFig.add(_actionPoly);
//createFig.add(_actionInk);
JMenu arrange = (JMenu) _menuBar.add(new JMenu(menuLocalize("Arrange")));
setMnemonic(arrange,"Arrange",'A');
JMenu align = (JMenu) arrange.add(new JMenu(menuLocalize("Align")));
JMenu distribute = (JMenu) arrange.add(new JMenu(menuLocalize("Distribute")));
JMenu reorder = (JMenu) arrange.add(new JMenu(menuLocalize("Reorder")));
JMenu nudge = (JMenu) arrange.add(new JMenu(menuLocalize("Nudge")));
JMenu layout = (JMenu) arrange.add(new JMenu(menuLocalize("Layout")));
Runnable initLater = new
InitMenusLater(align, distribute, reorder, nudge, layout, editTabs, detailsTabs);
org.argouml.application.Main.addPostLoadAction(initLater);
JMenu generate = (JMenu) _menuBar.add(new JMenu(menuLocalize("Generation")));
setMnemonic(generate,"Generate",'G');
generate.add(ActionGenerateOne.SINGLETON);
JMenuItem genAllItem = generate.add(ActionGenerateAll.SINGLETON);
setAccelerator(genAllItem,F7);
//generate.add(Actions.GenerateWeb);
Menu critique = (Menu) _menuBar.add(new Menu(menuLocalize("Critique")));
setMnemonic(critique,"Critique",'R');
critique.addCheckItem(Actions.AutoCritique);
critique.addSeparator();
critique.add(Actions.OpenDecisions);
critique.add(Actions.OpenGoals);
critique.add(Actions.OpenCritics);
// Tools Menu
_tools = new JMenu(menuLocalize("Tools"));
_tools.setEnabled(false);
Object[] context = { _tools, "Tools" };
ArrayList list = Argo.getPlugins(PluggableMenu.class, context);
ListIterator iterator = list.listIterator();
while (iterator.hasNext()) {
PluggableMenu module = (PluggableMenu)iterator.next();
_tools.setEnabled(true);
_tools.add(module.getMenuItem(_tools, "Tools"));
}
_menuBar.add(_tools);
// tools.add(ActionTest.getInstance());
// Help Menu
JMenu help = new JMenu(menuLocalize("Help"));
setMnemonic(help,"Help",'H');
help.add(Actions.AboutArgoUML);
//_menuBar.setHelpMenu(help);
_menuBar.add(help);
ArgoEventPump.addListener(ArgoEventTypes.ANY_MODULE_EVENT, this);
}
protected Component createPanels() {
_topSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, _navPane, _multiPane);
_botSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
_toDoPane, _detailsPane);
_mainSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, _topSplit, _botSplit);
_topSplit.setDividerSize(2);
_topSplit.setDividerLocation(Configuration.getInteger(Argo.KEY_SCREEN_VSPLITTOP, DEFAULT_VSPLIT));
_botSplit.setDividerSize(2);
_botSplit.setDividerLocation(Configuration.getInteger(Argo.KEY_SCREEN_VSPLITBOTTOM, DEFAULT_VSPLIT));
_mainSplit.setDividerSize(2);
_mainSplit.setDividerLocation(Configuration.getInteger(Argo.KEY_SCREEN_HSPLIT, DEFAULT_HSPLIT));
//_botSplit.setOneTouchExpandable(true);
// Enable the property listeners after all changes are done
// (includes component listeners)
if (_componentResizer == null) _componentResizer = new ComponentResizer();
_navPane.addComponentListener(_componentResizer);
_toDoPane.addComponentListener(_componentResizer);
// needs-more-work: Listen for a specific property. JDK1.3 has
// JSplitPane.DIVIDER_LOCATION_PROPERTY.
// _topSplit.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, this);
// _botSplit.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, this);
// _mainSplit.addPropertyChangeListener(JSplitPane.DIVIDER_LOCATION_PROPERTY, this);
return _mainSplit;
}
////////////////////////////////////////////////////////////////
// accessors
public void setProject(Project p) {
_project = p;
_navPane.setRoot(_project);
updateTitle();
Actions.updateAllEnabled();
//Designer.TheDesigner.getToDoList().removeAllElements();
Designer.TheDesigner.setCritiquingRoot(_project);
// update all panes
setTarget(_project.getInitialTarget());
_navPane.forceUpdate();
}
public Project getProject() {
// only for testing...
if (_project == null) _project = Project.makeEmptyProject();
return _project;
}
public void updateTitle() {
if (_project == null) setTitle(null);
else setTitle(_project.getName());
}
public void setTitle(String title) {
if (title == null || "".equals(title)) setTitle(getAppName());
else super.setTitle(getAppName() + " - " + title);
}
public String getAppName() { return _appName; }
public void setAppName(String n) { _appName = n; }
public void setPerspectives(Vector v) {
_navPane.setPerspectives(v);
}
public Vector getPerspectives() {
return _navPane.getPerspectives();
}
public void setCurPerspective(NavPerspective tm) {
_navPane.setCurPerspective(tm);
}
public NavPerspective getCurPerspective() {
return _navPane.getCurPerspective();
}
public void setToDoPerspectives(Vector v) {
_toDoPane.setPerspectives(v);
}
public Vector getToDoPerspectives() {
return _toDoPane.getPerspectives();
}
public void setToDoCurPerspective(TreeModel tm) {
_toDoPane.setCurPerspective(tm);
}
public void select(Object o) {
_multiPane.select(o);
_detailsPane.setTarget(o);
Actions.updateAllEnabled();
}
public void setTarget(Object o) {
_multiPane.setTarget(o);
_detailsPane.setTarget(o);
if (o instanceof MNamespace) _project.setCurrentNamespace((MNamespace)o);
if (o instanceof UMLDiagram) {
MNamespace m = ((UMLDiagram)o).getNamespace();
if (m != null) _project.setCurrentNamespace(m);
}
if (o instanceof MModelElement) {
MModelElement eo = (MModelElement)o;
if (eo == null) { System.out.println("no path to model"); return; }
_project.setCurrentNamespace(eo.getNamespace());
}
Actions.updateAllEnabled();
}
public Object getTarget() {
if (_multiPane == null) return null;
return _multiPane.getTarget();
}
public void setToDoItem(Object o) {
_detailsPane.setToDoItem(o);
}
public void setDetailsTarget(Object o) {
_detailsPane.setTarget(o);
Actions.updateAllEnabled();
}
public Object getDetailsTarget() {
return _detailsPane.getTarget();
}
public StatusBar getStatusBar() { return _statusBar; }
public ToDoPane getToDoPane() { return _toDoPane; }
public NavigatorPane getNavPane() { return _navPane; }
public MultiEditorPane getEditorPane() { return _multiPane; }
public DetailsPane getDetailsPane() { return _detailsPane; }
public void jumpToDiagramShowing(VectorSet dms) {
if (dms.size() == 0) return;
Object first = dms.elementAt(0);
if (first instanceof Diagram && dms.size() > 1) {
setTarget(first);
select(dms.elementAt(1));
return;
}
if (first instanceof Diagram && dms.size() == 1) {
setTarget(first);
select(null);
return;
}
Vector diagrams = getProject().getDiagrams();
Object target = _multiPane.getTarget();
if ((target instanceof Diagram) &&
((Diagram)target).countContained(dms) == dms.size()) {
select(first);
return;
}
Diagram bestDiagram = null;
int bestNumContained = 0;
for (int i = 0; i < diagrams.size(); i++) {
Diagram d = (Diagram) diagrams.elementAt(i);
int nc = d.countContained(dms);
if (nc > bestNumContained) {
bestNumContained = nc;
bestDiagram = d;
}
if (nc == dms.size()) break;
}
if (bestDiagram != null) {
setTarget(bestDiagram);
select(first);
}
}
////////////////////////////////////////////////////////////////
// window operations
public void setVisible(boolean b) {
super.setVisible(b);
if (b) org.tigris.gef.base.Globals.setStatusBar(this);
}
////////////////////////////////////////////////////////////////
// IStatusBar
public void showStatus(String s) { _statusBar.showStatus(s); }
/** Called by a user interface element when a request to
* navigate to a model element has been received.
*/
public void navigateTo(Object element) {
_history.navigateTo(element);
setTarget(element);
}
/** Called by a user interface element when a request to
* open a model element in a new window has been recieved.
*/
public void open(Object element) {
}
public boolean navigateBack(boolean attempt) {
boolean navigated = false;
if(attempt) {
Object target = _history.navigateBack(attempt);
if(target != null) {
navigated = true;
setTarget(target);
}
}
return navigated;
}
public boolean navigateForward(boolean attempt) {
boolean navigated = false;
if(attempt) {
Object target = _history.navigateForward(attempt);
if(target != null) {
navigated = true;
setTarget(target);
}
}
return navigated;
}
public boolean isNavigateBackEnabled() {
return _history.isNavigateBackEnabled();
}
public boolean isNavigateForwardEnabled() {
return _history.isNavigateForwardEnabled();
}
public void moduleLoaded(ArgoModuleEvent event) {
if (event.getSource() instanceof PluggableMenu) {
PluggableMenu module = (PluggableMenu)event.getSource();
if (module.inContext(module.buildContext(_tools, "Tools"))) {
_tools.add(module.getMenuItem(_tools, "Tools"));
_tools.setEnabled(true);
}
}
}
public void moduleUnloaded(ArgoModuleEvent event) {
// needs-more-work: Disable menu
}
public void moduleEnabled(ArgoModuleEvent event) {
// needs-more-work: Enable menu
}
public void moduleDisabled(ArgoModuleEvent event) {
// needs-more-work: Disable menu
}
} /* end class ProjectBrowser */
class WindowCloser extends WindowAdapter {
public WindowCloser() { }
public void windowClosing(WindowEvent e) {
ActionExit.SINGLETON.actionPerformed(null);
}
} /* end class WindowCloser */
class ComponentResizer extends ComponentAdapter {
public ComponentResizer() { }
public void componentResized(ComponentEvent ce) {
Component c = ce.getComponent();
if (c instanceof NavigatorPane) {
// Got the 2 and the 4 by experimentation. This is equivalent
// to jdk 1.3 property JSplitPane.DIVIDER_LOCATION_PROPERTY.
// If the width and height are not adjusted by this amount,
// the divider will slowly creep after close and open.
Configuration.setInteger(Argo.KEY_SCREEN_VSPLITTOP, c.getWidth() + 2);
Configuration.setInteger(Argo.KEY_SCREEN_HSPLIT, c.getHeight() + 4);
}
else if (c instanceof ToDoPane) {
// Got the 2 by experimentation. This is equivalent to jdk 1.3
// property JSplitPane.DIVIDER_LOCATION_PROPERTY. If the width
// is not adjusted by this amount, the divider will slowly creep
// after close and open.
Configuration.setInteger(Argo.KEY_SCREEN_VSPLITBOTTOM, c.getWidth() + 2);
}
else if (c instanceof ProjectBrowser) {
Configuration.setInteger(Argo.KEY_SCREEN_WIDTH, c.getWidth());
Configuration.setInteger(Argo.KEY_SCREEN_HEIGHT, c.getHeight());
}
}
public void componentMoved(ComponentEvent ce) {
Component c = ce.getComponent();
if (c instanceof ProjectBrowser) {
Configuration.setInteger(Argo.KEY_SCREEN_LEFT_X, c.getX());
Configuration.setInteger(Argo.KEY_SCREEN_TOP_Y, c.getY());
}
}
} /* end class ComponentResizer */
class InitMenusLater implements Runnable {
JMenu align, distribute, reorder, nudge, layout;
JMenu editTabs, detailsTabs;
public InitMenusLater(JMenu a, JMenu d, JMenu r, JMenu n, JMenu l,
JMenu et, JMenu dt) {
align = a;
distribute = d;
reorder = r;
nudge = n;
layout = l;
editTabs = et;
detailsTabs = dt;
}
public void run() {
KeyStroke F1 = KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0);
KeyStroke F2 = KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0);
KeyStroke F3 = KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0);
KeyStroke F4 = KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0);
KeyStroke F5 = KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0);
KeyStroke F6 = KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0);
KeyStroke F7 = KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0);
KeyStroke F8 = KeyStroke.getKeyStroke(KeyEvent.VK_F8, 0);
KeyStroke F9 = KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0);
KeyStroke F10 = KeyStroke.getKeyStroke(KeyEvent.VK_F10, 0);
KeyStroke alt1 = KeyStroke.getKeyStroke(KeyEvent.VK_1, KeyEvent.ALT_MASK);
KeyStroke alt2 = KeyStroke.getKeyStroke(KeyEvent.VK_2, KeyEvent.ALT_MASK);
KeyStroke alt3 = KeyStroke.getKeyStroke(KeyEvent.VK_3, KeyEvent.ALT_MASK);
KeyStroke alt4 = KeyStroke.getKeyStroke(KeyEvent.VK_4, KeyEvent.ALT_MASK);
KeyStroke alt5 = KeyStroke.getKeyStroke(KeyEvent.VK_5, KeyEvent.ALT_MASK);
KeyStroke alt6 = KeyStroke.getKeyStroke(KeyEvent.VK_6, KeyEvent.ALT_MASK);
KeyStroke alt7 = KeyStroke.getKeyStroke(KeyEvent.VK_7, KeyEvent.ALT_MASK);
KeyStroke alt8 = KeyStroke.getKeyStroke(KeyEvent.VK_8, KeyEvent.ALT_MASK);
KeyStroke alt9 = KeyStroke.getKeyStroke(KeyEvent.VK_9, KeyEvent.ALT_MASK);
KeyStroke alt0 = KeyStroke.getKeyStroke(KeyEvent.VK_0, KeyEvent.ALT_MASK);
KeyStroke altshift1 =
KeyStroke.getKeyStroke(KeyEvent.VK_1,
KeyEvent.ALT_MASK | KeyEvent.SHIFT_MASK);
KeyStroke altshift2 =
KeyStroke.getKeyStroke(KeyEvent.VK_2,
KeyEvent.ALT_MASK | KeyEvent.SHIFT_MASK);
KeyStroke altshift3 =
KeyStroke.getKeyStroke(KeyEvent.VK_3,
KeyEvent.ALT_MASK | KeyEvent.SHIFT_MASK);
align.add(new CmdAlign(CmdAlign.ALIGN_TOPS));
align.add(new CmdAlign(CmdAlign.ALIGN_BOTTOMS));
align.add(new CmdAlign(CmdAlign.ALIGN_LEFTS));
align.add(new CmdAlign(CmdAlign.ALIGN_RIGHTS));
align.add(new CmdAlign(CmdAlign.ALIGN_H_CENTERS));
align.add(new CmdAlign(CmdAlign.ALIGN_V_CENTERS));
align.add(new CmdAlign(CmdAlign.ALIGN_TO_GRID));
distribute.add(new CmdDistribute(CmdDistribute.H_SPACING));
distribute.add(new CmdDistribute(CmdDistribute.H_CENTERS));
distribute.add(new CmdDistribute(CmdDistribute.V_SPACING));
distribute.add(new CmdDistribute(CmdDistribute.V_CENTERS));
reorder.add(new CmdReorder(CmdReorder.SEND_TO_BACK));
reorder.add(new CmdReorder(CmdReorder.BRING_TO_FRONT));
reorder.add(new CmdReorder(CmdReorder.SEND_BACKWARD));
reorder.add(new CmdReorder(CmdReorder.BRING_FORWARD));
nudge.add(new CmdNudge(CmdNudge.LEFT));
nudge.add(new CmdNudge(CmdNudge.RIGHT));
nudge.add(new CmdNudge(CmdNudge.UP));
nudge.add(new CmdNudge(CmdNudge.DOWN));
JMenuItem autoLayout = layout.add(new ActionLayout("Automatic"));
JMenuItem incrLayout = layout.add(new ActionLayout("Incremental"));
JMenuItem nextEditItem = editTabs.add(Actions.NextEditTab);
nextEditItem.setAccelerator(F6);
editTabs.addSeparator();
JMenuItem tabe1Item = editTabs.add(new ActionGoToEdit("As Diagram"));
tabe1Item.setAccelerator(altshift1);
JMenuItem tabe2Item = editTabs.add(new ActionGoToEdit("As Table"));
tabe2Item.setAccelerator(altshift2);
JMenuItem tabe3Item = editTabs.add(new ActionGoToEdit("As Metrics"));
tabe3Item.setAccelerator(altshift3);
JMenuItem nextDetailsItem = detailsTabs.add(Actions.NextDetailsTab);
nextDetailsItem.setAccelerator(F5);
detailsTabs.addSeparator();
JMenuItem tab1Item = detailsTabs.add(new ActionGoToDetails("ToDoItem"));
tab1Item.setAccelerator(alt1);
JMenuItem tab2Item = detailsTabs.add(new ActionGoToDetails("Properties"));
tab2Item.setAccelerator(alt2);
JMenuItem tab3Item = detailsTabs.add(new ActionGoToDetails("Javadocs"));
tab3Item.setAccelerator(alt3);
JMenuItem tab4Item = detailsTabs.add(new ActionGoToDetails("Source"));
tab4Item.setAccelerator(alt4);
JMenuItem tab5Item = detailsTabs.add(new ActionGoToDetails("Constraints"));
tab5Item.setAccelerator(alt5);
JMenuItem tab6Item = detailsTabs.add(new ActionGoToDetails("TaggedValues"));
tab6Item.setAccelerator(alt6);
JMenuItem tab7Item = detailsTabs.add(new ActionGoToDetails("Checklist"));
tab7Item.setAccelerator(alt7);
JMenuItem tab8Item = detailsTabs.add(new ActionGoToDetails("History"));
tab8Item.setAccelerator(alt8);
//JMenuItem tab9Item = detailsTabs.add(new ActionGoToDetails(""));
//tab9Item.setAccelerator(alt9);
//JMenuItem tab0Item = detailsTabs.add(new ActionGoToDetails(""));
//tab0Item.setAccelerator(alt0);
}
} /* end class InitMenusLater */
| true | true | protected void initMenus() {
KeyStroke ctrlN = Localizer.getShortcut("CoreMenu","Shortcut_New");
KeyStroke ctrlO = Localizer.getShortcut("CoreMenu","Shortcut_Open");
KeyStroke ctrlS = Localizer.getShortcut("CoreMenu","Shortcut_Save");
KeyStroke ctrlP = Localizer.getShortcut("CoreMenu","Shortcut_Print");
KeyStroke ctrlA = Localizer.getShortcut("CoreMenu","Shortcut_Select_All");
KeyStroke ctrlC = Localizer.getShortcut("CoreMenu","Shortcut_Copy");
KeyStroke ctrlV = Localizer.getShortcut("CoreMenu","Shortcut_Paste");
KeyStroke ctrlX = Localizer.getShortcut("CoreMenu","Shortcut_Cut");
KeyStroke ctrlR = Localizer.getShortcut("CoreMenu","Shortcut_Remove_From_Diagram");
KeyStroke F3 = Localizer.getShortcut("CoreMenu","Shortcut_Find");
KeyStroke F7 = Localizer.getShortcut("CoreMenu","Shortcut_Generate_All");
KeyStroke altF4 = Localizer.getShortcut("CoreMenu","Shortcut_Exit");
KeyStroke delKey = Localizer.getShortcut("CoreMenu","Shortcut_Delete");
JMenuItem mi;
// File Menu
JMenu file = new JMenu(menuLocalize("File"));
_menuBar.add(file);
setMnemonic(file,"File",'F');
JMenuItem newItem = file.add(ActionNew.SINGLETON);
setMnemonic(newItem,"New",'N');
setAccelerator(newItem,ctrlN);
JMenuItem openProjectItem = file.add(ActionOpenProject.SINGLETON);
setMnemonic(openProjectItem,"Open",'O');
setAccelerator(openProjectItem,ctrlO);
//JMenuItem saveItem = file.add(_actionSave);
//file.add(_actionSaveAs);
//file.add(_actionSaveAsXMI);
JMenuItem saveProjectItem = file.add(ActionSaveProject.SINGLETON);
setMnemonic(saveProjectItem,"Save",'S');
setAccelerator(saveProjectItem,ctrlS);
JMenuItem saveProjectAsItem = file.add(ActionSaveProjectAs.SINGLETON);
setMnemonic(saveProjectAsItem,"SaveAs",'A');
file.addSeparator();
JMenuItem importProjectAsItem = file.add(ActionImportFromSources.SINGLETON);
file.addSeparator();
JMenuItem loadModelFromDBItem = file.add(ActionLoadModelFromDB.SINGLETON);
JMenuItem storeModelToDBItem = file.add(ActionStoreModelToDB.SINGLETON);
file.addSeparator();
JMenuItem printItem = file.add(Actions.Print);
setMnemonic(printItem,"Print",'P');
setAccelerator(printItem,ctrlP);
JMenuItem saveGraphicsItem = file.add(ActionSaveGraphics.SINGLETON);
setMnemonic(saveGraphicsItem,"SaveGraphics",'G');
// JMenuItem savePSItem = file.add(Actions.SavePS);
file.addSeparator();
file.add(ActionSaveConfiguration.SINGLETON);
file.addSeparator();
JMenuItem exitItem = file.add(ActionExit.SINGLETON);
setMnemonic(exitItem,"Exit",'x');
setAccelerator(exitItem,altF4);
JMenu edit = (JMenu) _menuBar.add(new JMenu(menuLocalize("Edit")));
setMnemonic(edit,"Edit",'E');
JMenu select = new JMenu(menuLocalize("Select"));
edit.add(select);
JMenuItem selectAllItem = select.add(new CmdSelectAll());
setAccelerator(selectAllItem,ctrlA);
JMenuItem selectNextItem = select.add(new CmdSelectNext(false));
//tab
JMenuItem selectPrevItem = select.add(new CmdSelectNext(true));
// shift tab
select.add(new CmdSelectInvert());
edit.add(Actions.Undo);
edit.add(Actions.Redo);
edit.addSeparator();
JMenuItem cutItem = edit.add(ActionCut.SINGLETON);
setMnemonic(cutItem,"Cut",'X');
setAccelerator(cutItem,ctrlX);
JMenuItem copyItem = edit.add(ActionCopy.SINGLETON);
setMnemonic(copyItem,"Copy",'C');
setAccelerator(copyItem,ctrlC);
JMenuItem pasteItem = edit.add(ActionPaste.SINGLETON);
setMnemonic(pasteItem,"Paste",'V');
setAccelerator(pasteItem,ctrlV);
edit.addSeparator();
// needs-more-work: confusing name change
JMenuItem deleteItem = edit.add(ActionDeleteFromDiagram.SINGLETON);
setMnemonic(deleteItem,"RemoveFromDiagram",'R');
setAccelerator(deleteItem,ctrlR);
JMenuItem removeItem = edit.add(ActionRemoveFromModel.SINGLETON);
setMnemonic(removeItem,"DeleteFromModel",'D');
setAccelerator(removeItem,delKey);
JMenuItem emptyItem = edit.add(ActionEmptyTrash.SINGLETON);
edit.addSeparator();
edit.add(ActionSettings.getInstance());
Menu view = (Menu) _menuBar.add(new Menu(menuLocalize("View")));
// maybe should be Navigate instead of view
setMnemonic(view,"View",'V');
// JMenu nav = (JMenu) view.add(new JMenu("Navigate"));
// JMenuItem downItem = nav.add(_actionNavDown);
// downItem.setAccelerator(ctrldown);
// JMenuItem upItem = nav.add(_actionNavUp);
// upItem.setAccelerator(ctrlup);
// JMenuItem backItem = nav.add(_actionNavBack);
// backItem.setAccelerator(ctrlleft);
// JMenuItem forwItem = nav.add(_actionNavForw);
// forwItem.setAccelerator(ctrlright);
view.add(Actions.GotoDiagram);
JMenuItem findItem = view.add(Actions.Find);
setAccelerator(findItem,F3);
view.addSeparator();
JMenu zoom = (JMenu) view.add(new JMenu(menuLocalize("Zoom")));
zoom.add(new ActionZoom(25));
zoom.add(new ActionZoom(50));
zoom.add(new ActionZoom(75));
zoom.add(new ActionZoom(100));
zoom.add(new ActionZoom(125));
zoom.add(new ActionZoom(150));
view.addSeparator();
JMenu editTabs = (JMenu) view.add(new JMenu(menuLocalize("Editor Tabs")));
//view.addSeparator();
//view.add(_actionAddToFavorites);
JMenu detailsTabs = (JMenu) view.add(new JMenu(menuLocalize("Details Tabs")));
view.addSeparator();
view.add(new CmdAdjustGrid());
view.add(new CmdAdjustGuide());
view.add(new CmdAdjustPageBreaks());
view.addCheckItem(Actions.ShowRapidButtons);
//JMenu create = (JMenu) _menuBar.add(new JMenu(menuLocalize("Create")));
//setMnemonic(create,"Create",'C');
//create.add(Actions.CreateMultiple);
//create.addSeparator();
JMenu createDiagrams = (JMenu) _menuBar.add(new JMenu(menuLocalize("Create Diagram")));
createDiagrams.add(ActionClassDiagram.SINGLETON);
createDiagrams.add(ActionUseCaseDiagram.SINGLETON);
createDiagrams.add(ActionStateDiagram.SINGLETON);
createDiagrams.add(ActionActivityDiagram.SINGLETON);
createDiagrams.add(ActionCollaborationDiagram.SINGLETON);
createDiagrams.add(ActionDeploymentDiagram.SINGLETON);
createDiagrams.add(ActionSequenceDiagram.SINGLETON);
//JMenu createModelElements = (JMenu) create.add(new JMenu("Model Elements"));
//createModelElements.add(Actions.AddTopLevelPackage);
//createModelElements.add(_actionClass);
//createModelElements.add(_actionInterface);
//createModelElements.add(_actionActor);
//createModelElements.add(_actionUseCase);
//createModelElements.add(_actionState);
//createModelElements.add(_actionPseudostate);
//createModelElements.add(_actionAttr);
//createModelElements.add(_actionOper);
//JMenu createFig = (JMenu) create.add(new JMenu("Shapes"));
//createFig.add(_actionRectangle);
//createFig.add(_actionRRectangle);
//createFig.add(_actionCircle);
//createFig.add(_actionLine);
//createFig.add(_actionText);
//createFig.add(_actionPoly);
//createFig.add(_actionInk);
JMenu arrange = (JMenu) _menuBar.add(new JMenu(menuLocalize("Arrange")));
setMnemonic(arrange,"Arrange",'A');
JMenu align = (JMenu) arrange.add(new JMenu(menuLocalize("Align")));
JMenu distribute = (JMenu) arrange.add(new JMenu(menuLocalize("Distribute")));
JMenu reorder = (JMenu) arrange.add(new JMenu(menuLocalize("Reorder")));
JMenu nudge = (JMenu) arrange.add(new JMenu(menuLocalize("Nudge")));
JMenu layout = (JMenu) arrange.add(new JMenu(menuLocalize("Layout")));
Runnable initLater = new
InitMenusLater(align, distribute, reorder, nudge, layout, editTabs, detailsTabs);
org.argouml.application.Main.addPostLoadAction(initLater);
JMenu generate = (JMenu) _menuBar.add(new JMenu(menuLocalize("Generation")));
setMnemonic(generate,"Generate",'G');
generate.add(ActionGenerateOne.SINGLETON);
JMenuItem genAllItem = generate.add(ActionGenerateAll.SINGLETON);
setAccelerator(genAllItem,F7);
//generate.add(Actions.GenerateWeb);
Menu critique = (Menu) _menuBar.add(new Menu(menuLocalize("Critique")));
setMnemonic(critique,"Critique",'R');
critique.addCheckItem(Actions.AutoCritique);
critique.addSeparator();
critique.add(Actions.OpenDecisions);
critique.add(Actions.OpenGoals);
critique.add(Actions.OpenCritics);
// Tools Menu
_tools = new JMenu(menuLocalize("Tools"));
_tools.setEnabled(false);
Object[] context = { _tools, "Tools" };
ArrayList list = Argo.getPlugins(PluggableMenu.class, context);
ListIterator iterator = list.listIterator();
while (iterator.hasNext()) {
PluggableMenu module = (PluggableMenu)iterator.next();
_tools.setEnabled(true);
_tools.add(module.getMenuItem(_tools, "Tools"));
}
_menuBar.add(_tools);
// tools.add(ActionTest.getInstance());
// Help Menu
JMenu help = new JMenu(menuLocalize("Help"));
setMnemonic(help,"Help",'H');
help.add(Actions.AboutArgoUML);
//_menuBar.setHelpMenu(help);
_menuBar.add(help);
ArgoEventPump.addListener(ArgoEventTypes.ANY_MODULE_EVENT, this);
}
| protected void initMenus() {
KeyStroke ctrlN = Localizer.getShortcut("CoreMenu","Shortcut_New");
KeyStroke ctrlO = Localizer.getShortcut("CoreMenu","Shortcut_Open");
KeyStroke ctrlS = Localizer.getShortcut("CoreMenu","Shortcut_Save");
KeyStroke ctrlP = Localizer.getShortcut("CoreMenu","Shortcut_Print");
KeyStroke ctrlA = Localizer.getShortcut("CoreMenu","Shortcut_Select_All");
KeyStroke ctrlC = Localizer.getShortcut("CoreMenu","Shortcut_Copy");
KeyStroke ctrlV = Localizer.getShortcut("CoreMenu","Shortcut_Paste");
KeyStroke ctrlX = Localizer.getShortcut("CoreMenu","Shortcut_Cut");
KeyStroke ctrlR = Localizer.getShortcut("CoreMenu","Shortcut_Remove_From_Diagram");
KeyStroke F3 = Localizer.getShortcut("CoreMenu","Shortcut_Find");
KeyStroke F7 = Localizer.getShortcut("CoreMenu","Shortcut_Generate_All");
KeyStroke altF4 = Localizer.getShortcut("CoreMenu","Shortcut_Exit");
KeyStroke delKey = Localizer.getShortcut("CoreMenu","Shortcut_Delete");
JMenuItem mi;
// File Menu
JMenu file = new JMenu(menuLocalize("File"));
_menuBar.add(file);
setMnemonic(file,"File",'F');
JMenuItem newItem = file.add(ActionNew.SINGLETON);
setMnemonic(newItem,"New",'N');
setAccelerator(newItem,ctrlN);
JMenuItem openProjectItem = file.add(ActionOpenProject.SINGLETON);
setMnemonic(openProjectItem,"Open",'O');
setAccelerator(openProjectItem,ctrlO);
//JMenuItem saveItem = file.add(_actionSave);
//file.add(_actionSaveAs);
//file.add(_actionSaveAsXMI);
JMenuItem saveProjectItem = file.add(ActionSaveProject.SINGLETON);
setMnemonic(saveProjectItem,"Save",'S');
setAccelerator(saveProjectItem,ctrlS);
JMenuItem saveProjectAsItem = file.add(ActionSaveProjectAs.SINGLETON);
setMnemonic(saveProjectAsItem,"SaveAs",'A');
file.addSeparator();
JMenuItem importProjectAsItem = file.add(ActionImportFromSources.SINGLETON);
file.addSeparator();
JMenuItem loadModelFromDBItem = file.add(ActionLoadModelFromDB.SINGLETON);
JMenuItem storeModelToDBItem = file.add(ActionStoreModelToDB.SINGLETON);
file.addSeparator();
JMenuItem printItem = file.add(Actions.Print);
setMnemonic(printItem,"Print",'P');
setAccelerator(printItem,ctrlP);
JMenuItem saveGraphicsItem = file.add(ActionSaveGraphics.SINGLETON);
setMnemonic(saveGraphicsItem,"SaveGraphics",'G');
// JMenuItem savePSItem = file.add(Actions.SavePS);
file.addSeparator();
file.add(ActionSaveConfiguration.SINGLETON);
file.addSeparator();
JMenuItem exitItem = file.add(ActionExit.SINGLETON);
setMnemonic(exitItem,"Exit",'x');
setAccelerator(exitItem,altF4);
JMenu edit = (JMenu) _menuBar.add(new JMenu(menuLocalize("Edit")));
setMnemonic(edit,"Edit",'E');
JMenu select = new JMenu(menuLocalize("Select"));
edit.add(select);
JMenuItem selectAllItem = select.add(new CmdSelectAll());
setAccelerator(selectAllItem,ctrlA);
JMenuItem selectNextItem = select.add(new CmdSelectNext(false));
//tab
JMenuItem selectPrevItem = select.add(new CmdSelectNext(true));
// shift tab
select.add(new CmdSelectInvert());
edit.add(Actions.Undo);
edit.add(Actions.Redo);
edit.addSeparator();
JMenuItem cutItem = edit.add(ActionCut.SINGLETON);
setMnemonic(cutItem,"Cut",'X');
setAccelerator(cutItem,ctrlX);
JMenuItem copyItem = edit.add(ActionCopy.SINGLETON);
setMnemonic(copyItem,"Copy",'C');
setAccelerator(copyItem,ctrlC);
JMenuItem pasteItem = edit.add(ActionPaste.SINGLETON);
setMnemonic(pasteItem,"Paste",'V');
setAccelerator(pasteItem,ctrlV);
edit.addSeparator();
// needs-more-work: confusing name change
JMenuItem deleteItem = edit.add(ActionDeleteFromDiagram.SINGLETON);
setMnemonic(deleteItem,"RemoveFromDiagram",'R');
setAccelerator(deleteItem,ctrlR);
JMenuItem removeItem = edit.add(ActionRemoveFromModel.SINGLETON);
setMnemonic(removeItem,"DeleteFromModel",'D');
setAccelerator(removeItem,delKey);
JMenuItem emptyItem = edit.add(ActionEmptyTrash.SINGLETON);
edit.addSeparator();
edit.add(ActionSettings.getInstance());
Menu view = (Menu) _menuBar.add(new Menu(menuLocalize("View")));
// maybe should be Navigate instead of view
setMnemonic(view,"View",'V');
// JMenu nav = (JMenu) view.add(new JMenu("Navigate"));
// JMenuItem downItem = nav.add(_actionNavDown);
// downItem.setAccelerator(ctrldown);
// JMenuItem upItem = nav.add(_actionNavUp);
// upItem.setAccelerator(ctrlup);
// JMenuItem backItem = nav.add(_actionNavBack);
// backItem.setAccelerator(ctrlleft);
// JMenuItem forwItem = nav.add(_actionNavForw);
// forwItem.setAccelerator(ctrlright);
view.add(Actions.GotoDiagram);
JMenuItem findItem = view.add(Actions.Find);
setAccelerator(findItem,F3);
view.addSeparator();
JMenu zoom = (JMenu) view.add(new JMenu(menuLocalize("Zoom")));
zoom.add(new ActionZoom(25));
zoom.add(new ActionZoom(50));
zoom.add(new ActionZoom(75));
zoom.add(new ActionZoom(100));
zoom.add(new ActionZoom(125));
zoom.add(new ActionZoom(150));
view.addSeparator();
JMenu editTabs = (JMenu) view.add(new JMenu(menuLocalize("Editor Tabs")));
//view.addSeparator();
//view.add(_actionAddToFavorites);
JMenu detailsTabs = (JMenu) view.add(new JMenu(menuLocalize("Details Tabs")));
view.addSeparator();
view.add(new CmdAdjustGrid());
view.add(new CmdAdjustGuide());
view.add(new CmdAdjustPageBreaks());
view.addCheckItem(Actions.ShowRapidButtons);
//JMenu create = (JMenu) _menuBar.add(new JMenu(menuLocalize("Create")));
//setMnemonic(create,"Create",'C');
//create.add(Actions.CreateMultiple);
//create.addSeparator();
JMenu createDiagrams = (JMenu) _menuBar.add(new JMenu(menuLocalize("Create Diagram")));
setMnemonic(createDiagrams, "Create Diagram",'C');
createDiagrams.add(ActionClassDiagram.SINGLETON);
createDiagrams.add(ActionUseCaseDiagram.SINGLETON);
createDiagrams.add(ActionStateDiagram.SINGLETON);
createDiagrams.add(ActionActivityDiagram.SINGLETON);
createDiagrams.add(ActionCollaborationDiagram.SINGLETON);
createDiagrams.add(ActionDeploymentDiagram.SINGLETON);
createDiagrams.add(ActionSequenceDiagram.SINGLETON);
//JMenu createModelElements = (JMenu) create.add(new JMenu("Model Elements"));
//createModelElements.add(Actions.AddTopLevelPackage);
//createModelElements.add(_actionClass);
//createModelElements.add(_actionInterface);
//createModelElements.add(_actionActor);
//createModelElements.add(_actionUseCase);
//createModelElements.add(_actionState);
//createModelElements.add(_actionPseudostate);
//createModelElements.add(_actionAttr);
//createModelElements.add(_actionOper);
//JMenu createFig = (JMenu) create.add(new JMenu("Shapes"));
//createFig.add(_actionRectangle);
//createFig.add(_actionRRectangle);
//createFig.add(_actionCircle);
//createFig.add(_actionLine);
//createFig.add(_actionText);
//createFig.add(_actionPoly);
//createFig.add(_actionInk);
JMenu arrange = (JMenu) _menuBar.add(new JMenu(menuLocalize("Arrange")));
setMnemonic(arrange,"Arrange",'A');
JMenu align = (JMenu) arrange.add(new JMenu(menuLocalize("Align")));
JMenu distribute = (JMenu) arrange.add(new JMenu(menuLocalize("Distribute")));
JMenu reorder = (JMenu) arrange.add(new JMenu(menuLocalize("Reorder")));
JMenu nudge = (JMenu) arrange.add(new JMenu(menuLocalize("Nudge")));
JMenu layout = (JMenu) arrange.add(new JMenu(menuLocalize("Layout")));
Runnable initLater = new
InitMenusLater(align, distribute, reorder, nudge, layout, editTabs, detailsTabs);
org.argouml.application.Main.addPostLoadAction(initLater);
JMenu generate = (JMenu) _menuBar.add(new JMenu(menuLocalize("Generation")));
setMnemonic(generate,"Generate",'G');
generate.add(ActionGenerateOne.SINGLETON);
JMenuItem genAllItem = generate.add(ActionGenerateAll.SINGLETON);
setAccelerator(genAllItem,F7);
//generate.add(Actions.GenerateWeb);
Menu critique = (Menu) _menuBar.add(new Menu(menuLocalize("Critique")));
setMnemonic(critique,"Critique",'R');
critique.addCheckItem(Actions.AutoCritique);
critique.addSeparator();
critique.add(Actions.OpenDecisions);
critique.add(Actions.OpenGoals);
critique.add(Actions.OpenCritics);
// Tools Menu
_tools = new JMenu(menuLocalize("Tools"));
_tools.setEnabled(false);
Object[] context = { _tools, "Tools" };
ArrayList list = Argo.getPlugins(PluggableMenu.class, context);
ListIterator iterator = list.listIterator();
while (iterator.hasNext()) {
PluggableMenu module = (PluggableMenu)iterator.next();
_tools.setEnabled(true);
_tools.add(module.getMenuItem(_tools, "Tools"));
}
_menuBar.add(_tools);
// tools.add(ActionTest.getInstance());
// Help Menu
JMenu help = new JMenu(menuLocalize("Help"));
setMnemonic(help,"Help",'H');
help.add(Actions.AboutArgoUML);
//_menuBar.setHelpMenu(help);
_menuBar.add(help);
ArgoEventPump.addListener(ArgoEventTypes.ANY_MODULE_EVENT, this);
}
|
diff --git a/tests/frontend/org/voltdb/planner/plannerTester.java b/tests/frontend/org/voltdb/planner/plannerTester.java
index 9edd47c4e..b7479c3e6 100644
--- a/tests/frontend/org/voltdb/planner/plannerTester.java
+++ b/tests/frontend/org/voltdb/planner/plannerTester.java
@@ -1,837 +1,841 @@
/* This file is part of VoltDB.
* Copyright (C) 2008-2012 VoltDB Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.voltdb.planner;
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.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.json_voltpatches.JSONArray;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONObject;
import org.voltdb.catalog.CatalogMap;
import org.voltdb.catalog.Cluster;
import org.voltdb.catalog.Column;
import org.voltdb.catalog.Database;
import org.voltdb.catalog.Table;
import org.voltdb.plannodes.AbstractPlanNode;
import org.voltdb.plannodes.AbstractScanPlanNode;
import org.voltdb.plannodes.IndexScanPlanNode;
import org.voltdb.plannodes.PlanNodeTree;
import org.voltdb.plannodes.SendPlanNode;
import org.voltdb.types.PlanNodeType;
public class plannerTester {
private static PlannerTestAideDeCamp aide;
private static String m_currentConfig;
private static String m_testName;
private static String m_pathRefPlan;
private static String m_baseName;
private static String m_pathDDL;
private static ArrayList<String> m_savePlanPaths = new ArrayList<String>();
private static String m_savePlanPath;
private static boolean m_isSavePathFromCML = false;
private static Map<String,String> m_partitionColumns = new HashMap<String, String>();
private static ArrayList<String> m_stmts = new ArrayList<String>();
private static int m_treeSizeDiff;
private static boolean m_changedSQL;
private static boolean m_isCompileSave = false;
private static boolean m_isDiff = false;
private static boolean m_showExpainedPlan = false;
private static boolean m_showSQLStatement = false;
private static ArrayList<String> m_config = new ArrayList<String>();
private static int m_numPass;
private static int m_numFail;
public static ArrayList<String> m_diffMessages = new ArrayList<String>();
private static String m_reportDir = "/tmp/";
private static BufferedWriter m_reportWriter;
private static ArrayList<String> m_filters = new ArrayList<String> ();
public static class diffPair {
private Object m_first;
private Object m_second;
public diffPair( Object first, Object second ) {
m_first = first;
m_second = second;
}
@Override
public String toString() {
String first = ( ( m_first == null ) || ( m_first == "" ) ) ?
"[]" : m_first.toString();
String second = ( m_second == null || ( m_second == "" )) ?
"[]" : m_second.toString();
return "("+first+" => "+second+")";
}
public boolean equals() {
return m_first.equals(m_second);
}
public void setFirst( Object first ) {
m_first = first;
}
public void setSecond( Object second ) {
m_second = second;
}
public void set( Object first, Object second ) {
m_first = first;
m_second = second;
}
}
//TODO maybe a more robust parser? Need to figure out how to handle config file array if using the CLIConfig below
// private static class PlannerTesterConfig extends CLIConfig {
// @Option(shortOpt = "d", desc = "Do the diff")
// boolean isDiff = false;
// @Option(shortOpt = "cs", desc = "Compile queris and save according to the config file")
// boolean isCompileSave = false;
// @Option(shortOpt = "C", desc = "Specify the path to the config file")
// ArrayList<String> configFiles = new ArrayList<String> ();
//
// @Override
// public void validate() {
// if (maxerrors < 0)
// exitWithMessageAndUsage("abortfailurecount must be >=0");
// }
//
// @Override
// public void printUsage() {
// System.out
// .println("Usage: csvloader [args] tablename");
// System.out
// .println(" csvloader [args] -p procedurename");
// super.printUsage();
// }
// }
public static void main( String[] args ) {
int size = args.length;
for( int i=0; i<size; i++ ) {
String str = args[i];
if( str.startsWith("-C=")) {
String subStr = str.split("=")[1];
String [] configs = subStr.split(",");
for( String config : configs ) {
m_config.add( config.trim() );
}
}
if( str.startsWith("-sp=")) {
m_isSavePathFromCML = true;
String subStr = str.split("=")[1];
String [] savePaths = subStr.split(",");
for( String savePath : savePaths ) {
savePath = savePath.trim();
if( !savePath.endsWith("/") ){
savePath += "/";
}
m_savePlanPaths.add( savePath );
}
}
else if( str.startsWith("-cd") ) {
m_isCompileSave = true;
m_isDiff = true;
m_showExpainedPlan = true;
m_showSQLStatement = true;
}
else if( str.startsWith("-cs") ) {
m_isCompileSave = true;
}
else if( str.startsWith("-d") ) {
m_isDiff = true;
}
else if( str.startsWith("-r") ){
m_reportDir = str.split("=")[1];
m_reportDir = m_reportDir.trim();
if( !m_reportDir.endsWith("/") ) {
m_reportDir += "/";
}
}
else if( str.startsWith("-e") ){
m_showExpainedPlan = true;
}
else if( str.startsWith("-s") ){
m_showSQLStatement = true;
}
else if( str.startsWith("-i=") ) {
m_filters.add(str.split("=")[1] );
}
else if( str.startsWith("-help") || str.startsWith("-h") ){
printUsage();
System.exit(0);
}
}
size = m_config.size();
if( m_isCompileSave ) {
Iterator<String> it = m_savePlanPaths.iterator();
for( String config : m_config ) {
try {
setUp( config );
if( m_isSavePathFromCML && it.hasNext() ) {
m_savePlanPath = it.next();
}
batchCompileSave();
} catch (Exception e) {
e.printStackTrace();
}
}
}
if( m_isDiff ) {
if( !new File(m_reportDir).exists() ) {
new File(m_reportDir).mkdirs();
}
try {
m_reportWriter = new BufferedWriter(new FileWriter( m_reportDir+"plannerTester.report" ));
} catch (IOException e1) {
System.out.println(e1.getMessage());
System.exit(-1);
}
+ Iterator<String> it = m_savePlanPaths.iterator();
for( String config : m_config ) {
try {
setUp( config );
+ if( m_isSavePathFromCML && it.hasNext() ) {
+ m_savePlanPath = it.next();
+ }
startDiff();
} catch (Exception e) {
e.printStackTrace();
}
}
int numTest = m_numPass + m_numFail;
System.out.println("Test: "+numTest);
System.out.println("Pass: "+m_numPass);
System.out.println("Fail: "+m_numFail);
try {
m_reportWriter.write( "\nTest: "+numTest+"\n"
+"Pass: "+m_numPass+"\n"
+"Fail: "+m_numFail+"\n");
m_reportWriter.flush();
m_reportWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Report file created at "+m_reportDir+"plannerTester.report");
}
if( m_numFail == 0 ) {
System.exit(0);
} else {
System.exit(1);
}
}
public static void printUsage() {
System.out.println("-C='configFile1, configFile2, ...'" +
"\nSpecify the path to a config file.\n");
System.out.println("-sp='savePath1, savePath2, ...'" +
"\nspecify save paths for newly generated plan files, should be in the same order of the config files.\n");
System.out.println("-r=reportFileDir " +
"\nSpecify report file path, default will be tmp/, report file name is plannerTester.report.\n");
System.out.println("-i=ignorePattern" +
"\nSpecify a pattern to ignore, the pattern will not be recorded in the report file.\n");
System.out.println("-cd" +
"\nSame as putting -cs -d -e -s.\n");
System.out.println("-cs" +
"\nCompile queries and save the plans according to the config files.\n");
System.out.println("-d" +
"\nDo the diff between plan files in baseline and the current ones.\n");
System.out.println("-e" +
"\nOutput explained plan along with diff.\n");
System.out.println("-s" +
"\nOutput sql statement along with diff.\n");
}
public static void setUp( String pathConfigFile ) throws IOException {
m_currentConfig = pathConfigFile;
m_partitionColumns.clear();
BufferedReader reader = new BufferedReader( new FileReader( pathConfigFile ) );
String line = null;
while( ( line = reader.readLine() ) != null ) {
if( line.startsWith("#") ) {
continue;
}
else if( line.equalsIgnoreCase("Name:") ) {
line = reader.readLine();
m_testName = line;
}
else if ( line.equalsIgnoreCase("Ref:") ) {
line = reader.readLine();
m_pathRefPlan = new File( line ).getCanonicalPath();
m_pathRefPlan += "/";
}
else if( line.equalsIgnoreCase("DDL:")) {
line = reader.readLine();
m_pathDDL = new File( line ).getCanonicalPath();
}
else if( line.equalsIgnoreCase("Base Name:") ) {
line = reader.readLine();
m_baseName = line;
}
else if( line.equalsIgnoreCase("SQL:")) {
m_stmts.clear();
while( (line = reader.readLine()).length() > 6 ) {
if( line.startsWith("#") ) {
continue;
}
m_stmts.add( line );
}
}
else if( line.equalsIgnoreCase("Save Path:") ) {
line = reader.readLine();
m_savePlanPath = ( new File( line ).getCanonicalPath() ) + "/";
}
else if( line.equalsIgnoreCase("Partition Columns:") ) {
line = reader.readLine();
int index = line.indexOf(".");
if( index == -1 ) {
System.err.println("Config file syntax error : Partition Columns should be table.column");
}
m_partitionColumns.put( line.substring(0, index).toLowerCase(), line.substring(index+1).toLowerCase());
}
}
try {
setUpSchema();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void setUpForTest( String pathDDL, String baseName, String table, String column ) {
m_partitionColumns.clear();
m_partitionColumns.put( table.toLowerCase(), column.toLowerCase());
m_pathDDL = pathDDL;
m_baseName = baseName;
try {
setUpSchema();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void setUpSchema() throws Exception {
File ddlFile = new File(m_pathDDL);
aide = new PlannerTestAideDeCamp(ddlFile.toURI().toURL(),
m_baseName);
// Set all tables to non-replicated.
Cluster cluster = aide.getCatalog().getClusters().get("cluster");
CatalogMap<Table> tmap = cluster.getDatabases().get("database").getTables();
for( String tableName : m_partitionColumns.keySet() ) {
Table t = tmap.getIgnoreCase( tableName );
t.setIsreplicated(false);
Column column = t.getColumns().getIgnoreCase( m_partitionColumns.get(tableName) );
t.setPartitioncolumn(column);
}
}
public static void setTestName ( String name ) {
m_testName = name;
}
protected void tearDown() throws Exception {
aide.tearDown();
}
public static List<AbstractPlanNode> compile( String sql, int paramCount,
boolean singlePartition ) throws Exception {
List<AbstractPlanNode> pnList = null;
pnList = aide.compile(sql, paramCount, singlePartition);
return pnList;
}
public static void writePlanToFile( AbstractPlanNode pn, String pathToDir, String fileName, String sql) {
if( pn == null ) {
System.err.println("the plan node is null, nothing to write");
return;
}
PlanNodeTree pnt = new PlanNodeTree( pn );
String prettyJson = pnt.toJSONString();
if( !new File(pathToDir).exists() ) {
new File(pathToDir).mkdirs();
}
try {
BufferedWriter writer = new BufferedWriter( new FileWriter( pathToDir+fileName ) );
writer.write( sql );
writer.write( "\n" );
writer.write( prettyJson );
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static PlanNodeTree loadPlanFromFile( String path, ArrayList<String> getsql ) throws FileNotFoundException {
PlanNodeTree pnt = new PlanNodeTree();
String prettyJson = "";
String line = null;
BufferedReader reader = new BufferedReader( new FileReader( path ));
try {
getsql.add( reader.readLine() );
while( (line = reader.readLine() ) != null ){
line = line.trim();
prettyJson += line;
}
} catch (IOException e1) {
e1.printStackTrace();
}
JSONObject jobj;
try {
jobj = new JSONObject( prettyJson );
JSONArray jarray = jobj.getJSONArray("PLAN_NODES");
Database db = aide.getDatabase();
pnt.loadFromJSONArray(jarray, db);
} catch (JSONException e) {
e.printStackTrace();
}
return pnt;
}
public static ArrayList< AbstractPlanNode > getJoinNodes( ArrayList<AbstractPlanNode> pnlist ) {
ArrayList< AbstractPlanNode > joinNodeList = new ArrayList<AbstractPlanNode>();
for( AbstractPlanNode pn : pnlist ) {
if( pn.getPlanNodeType().equals(PlanNodeType.NESTLOOP) ||
pn.getPlanNodeType().equals(PlanNodeType.NESTLOOPINDEX) ) {
joinNodeList.add(pn);
}
}
return joinNodeList;
}
public static void batchCompileSave( ) throws Exception {
int size = m_stmts.size();
for( int i = 0; i < size; i++ ) {
List<AbstractPlanNode> pnList = compile( m_stmts.get(i), 0, false);
AbstractPlanNode pn = pnList.get(0);
if( pnList.size() == 2 ){//multi partition query plan
assert( pnList.get(1) instanceof SendPlanNode );
if( ! pn.reattachFragment( ( SendPlanNode) pnList.get(1) ) ) {
System.err.println( "Receive plan node not found while reattachFragment." );
}
}
writePlanToFile(pn, m_savePlanPath, m_testName+".plan"+i, m_stmts.get(i) );
}
System.out.println("Plan files generated at: "+m_savePlanPath);
}
//parameters : path to baseline and the new plans
//size : number of total files in the baseline directory
public static void batchDiff( ) throws IOException {
PlanNodeTree pnt1 = null;
PlanNodeTree pnt2 = null;
int size = m_stmts.size();
String baseStmt = null;
for( int i = 0; i < size; i++ ){
ArrayList<String> getsql = new ArrayList<String>();
try {
pnt1 = loadPlanFromFile( m_pathRefPlan+m_testName+".plan"+i, getsql );
baseStmt = getsql.get(0);
} catch (FileNotFoundException e) {
System.err.println("Plan file "+m_pathRefPlan+m_testName+".plan"+i+" don't exist. Use -cs(batchCompileSave) to generate plans and copy base plans to baseline directory.");
System.exit(1);
}
//if sql stmts not consistent
if( !baseStmt.equalsIgnoreCase( m_stmts.get(i)) ) {
diffPair strPair = new diffPair( baseStmt, m_stmts.get(i) );
m_reportWriter.write("Statement "+i+" of "+m_testName+":\n SQL statement is not consistent with the one in baseline :"+"\n"+
strPair.toString()+"\n");
m_numFail++;
continue;
}
try{
pnt2 = loadPlanFromFile( m_savePlanPath+m_testName+".plan"+i, getsql );
} catch (FileNotFoundException e) {
System.err.println("Plan file "+m_savePlanPath+m_testName+".plan"+i+" don't exist. Use -cs(batchCompileSave) to generate and save plans.");
System.exit(1);
}
AbstractPlanNode pn1 = pnt1.getRootPlanNode();
AbstractPlanNode pn2 = pnt2.getRootPlanNode();
if( diff( pn1, pn2, false ) ) {
m_numPass++;
} else {
m_numFail++;
m_reportWriter.write( "Statement "+i+" of "+m_testName+": \n" );
//TODO add more logic to determine which plan is better
if( !m_changedSQL ){
if( m_treeSizeDiff < 0 ){
m_reportWriter.write( "Old plan might be better\n" );
}
else if( m_treeSizeDiff > 0 ) {
m_reportWriter.write( "New plan might be better\n" );
}
}
for( String msg : m_diffMessages ) {
boolean isIgnore = false;
for( String filter : m_filters ) {
if( msg.contains( filter ) ) {
isIgnore = true;
break;
}
}
if( !isIgnore )
m_reportWriter.write( msg+"\n\n" );
}
if( m_showSQLStatement ) {
m_reportWriter.write( "SQL statement:\n"+baseStmt+"\n==>\n"+m_stmts.get(i)+"\n");
}
if( m_showExpainedPlan ) {
m_reportWriter.write("\nExplained plan:\n"+pn1.toExplainPlanString()+"\n==>\n"+pn2.toExplainPlanString()+"\n");
}
m_reportWriter.write("Path to the config file :"+m_currentConfig+"\n"
+"Path to the baseline file :"+m_pathRefPlan+m_testName+".plan"+i+"\n"
+"Path to the current plan file :"+m_savePlanPath+m_testName+".plan"+i+
"\n\n----------------------------------------------------------------------\n");
}
}
m_reportWriter.flush();
}
public static void startDiff( ) throws IOException {
m_reportWriter.write( "===================================================================Begin test "+m_testName+"\n" );
batchDiff( );
m_reportWriter.write( "==================================================================="+
"End of "+m_testName+"\n");
m_reportWriter.flush();
}
public static boolean diffInlineAndJoin( AbstractPlanNode oldpn1, AbstractPlanNode newpn2 ) {
m_treeSizeDiff = 0;
boolean noDiff = true;
ArrayList<String> messages = new ArrayList<String>();
ArrayList<AbstractPlanNode> list1 = oldpn1.getPlanNodeList();
ArrayList<AbstractPlanNode> list2 = newpn2.getPlanNodeList();
int size1 = list1.size();
int size2 = list2.size();
m_treeSizeDiff = size1 - size2;
diffPair intdiffPair = new diffPair(0,0);
diffPair stringdiffPair = new diffPair(null,null);
if( size1 != size2 ) {
intdiffPair.set(size1, size2);
messages.add( "Plan tree size diff: "+intdiffPair.toString() );
}
Map<String,ArrayList<Integer>> planNodesPosMap1 = new LinkedHashMap<String,ArrayList<Integer>> ();
Map<String,ArrayList<AbstractPlanNode>> inlineNodesPosMap1 = new LinkedHashMap<String,ArrayList<AbstractPlanNode>> ();
Map<String,ArrayList<Integer>> planNodesPosMap2 = new LinkedHashMap<String,ArrayList<Integer>> ();
Map<String,ArrayList<AbstractPlanNode>> inlineNodesPosMap2 = new LinkedHashMap<String,ArrayList<AbstractPlanNode>> ();
fetchPositionInfoFromList(list1, planNodesPosMap1, inlineNodesPosMap1);
fetchPositionInfoFromList(list2, planNodesPosMap2, inlineNodesPosMap2);
planNodePositionDiff( planNodesPosMap1, planNodesPosMap2, messages );
inlineNodePositionDiff( inlineNodesPosMap1, inlineNodesPosMap2, messages );
//join nodes diff
ArrayList<AbstractPlanNode> joinNodes1 = getJoinNodes( list1 );
ArrayList<AbstractPlanNode> joinNodes2 = getJoinNodes( list2 );
size1 = joinNodes1.size();
size2 = joinNodes2.size();
if( size1 != size2 ) {
intdiffPair.set( size1 , size2);
messages.add( "Join Nodes Number diff:\n"+intdiffPair.toString()+"\nSQL statement might be changed.");
m_changedSQL = true;
String str1 = "";
String str2 = "";
for( AbstractPlanNode pn : joinNodes1 ) {
str1 = str1 + pn.toString() + ", ";
}
for( AbstractPlanNode pn : joinNodes2 ) {
str2 = str2 + pn.toString() + ", ";
}
if( str1.length() > 1 ){
str1 = ( str1.subSequence(0, str1.length()-2) ).toString();
}
if( str2.length() > 1 ){
str2 = ( str2.subSequence(0, str2.length()-2) ).toString();
}
stringdiffPair.set( str1, str2 );
messages.add( "Join Node List diff: "+"\n"+stringdiffPair.toString()+"\n");
}
else {
for( int i = 0 ; i < size1 ; i++ ) {
AbstractPlanNode pn1 = joinNodes1.get(i);
AbstractPlanNode pn2 = joinNodes2.get(i);
PlanNodeType pnt1 = pn1.getPlanNodeType();
PlanNodeType pnt2 = pn2.getPlanNodeType();
if( !pnt1.equals(pnt2) ) {
stringdiffPair.set( pn1.toString(), pn2.toString() );
messages.add( "Join Node Type diff:\n"+stringdiffPair.toString());
}
}
}
for( String msg : messages ) {
if( msg.contains("diff") || msg.contains("Diff") ) {
noDiff = false;
break;
}
}
m_diffMessages.addAll(messages);
return noDiff;
}
private static void fetchPositionInfoFromList( Collection<AbstractPlanNode> list,
Map<String,ArrayList<Integer>> planNodesPosMap,
Map<String,ArrayList<AbstractPlanNode>> inlineNodesPosMap ) {
for( AbstractPlanNode pn : list ) {
String nodeTypeStr = pn.getPlanNodeType().name();
if( !planNodesPosMap.containsKey(nodeTypeStr) ) {
ArrayList<Integer> intList = new ArrayList<Integer>( );
intList.add( pn.getPlanNodeId() );
planNodesPosMap.put(nodeTypeStr, intList );
}
else{
planNodesPosMap.get( nodeTypeStr ).add( pn.getPlanNodeId() );
}
//walk inline nodes
for( AbstractPlanNode inlinepn : pn.getInlinePlanNodes().values() ) {
String inlineNodeTypeStr = inlinepn.getPlanNodeType().name();
if( !inlineNodesPosMap.containsKey( inlineNodeTypeStr ) ) {
ArrayList<AbstractPlanNode> nodeList = new ArrayList<AbstractPlanNode>( );
nodeList.add(pn);
inlineNodesPosMap.put( inlineNodeTypeStr, nodeList );
}
else{
inlineNodesPosMap.get( inlineNodeTypeStr ).add( pn );
}
}
}
}
private static void planNodePositionDiff( Map<String,ArrayList<Integer>> planNodesPosMap1, Map<String,ArrayList<Integer>> planNodesPosMap2, ArrayList<String> messages ) {
Set<String> typeWholeSet = new HashSet<String>();
typeWholeSet.addAll( planNodesPosMap1.keySet() );
typeWholeSet.addAll( planNodesPosMap2.keySet() );
for( String planNodeTypeStr : typeWholeSet ) {
if( ! planNodesPosMap1.containsKey( planNodeTypeStr ) && planNodesPosMap2.containsKey( planNodeTypeStr ) ){
diffPair strPair = new diffPair( null, planNodesPosMap2.get(planNodeTypeStr).toString() );
messages.add( planNodeTypeStr+" diff: \n"+strPair.toString() );
}
else if( planNodesPosMap1.containsKey( planNodeTypeStr ) && !planNodesPosMap2.containsKey( planNodeTypeStr ) ) {
diffPair strPair = new diffPair( planNodesPosMap1.get(planNodeTypeStr).toString(), null );
messages.add( planNodeTypeStr+" diff: \n"+strPair.toString() );
}
else{
diffPair strPair = new diffPair( planNodesPosMap1.get(planNodeTypeStr).toString(), planNodesPosMap2.get(planNodeTypeStr).toString() );
if( !strPair.equals() ) {
messages.add( planNodeTypeStr+" diff: \n"+strPair.toString() );
}
}
}
}
private static void inlineNodePositionDiff( Map<String,ArrayList<AbstractPlanNode>> inlineNodesPosMap1, Map<String,ArrayList<AbstractPlanNode>> inlineNodesPosMap2, ArrayList<String> messages ) {
Set<String> typeWholeSet = new HashSet<String>();
typeWholeSet.addAll( inlineNodesPosMap1.keySet() );
typeWholeSet.addAll( inlineNodesPosMap2.keySet() );
for( String planNodeTypeStr : typeWholeSet ) {
if( ! inlineNodesPosMap1.containsKey( planNodeTypeStr ) && inlineNodesPosMap2.containsKey( planNodeTypeStr ) ){
diffPair strPair = new diffPair( null, inlineNodesPosMap2.get(planNodeTypeStr).toString() );
messages.add( "Inline "+planNodeTypeStr+" diff: \n"+strPair.toString() );
}
else if( inlineNodesPosMap1.containsKey( planNodeTypeStr ) && !inlineNodesPosMap2.containsKey( planNodeTypeStr ) ) {
diffPair strPair = new diffPair( inlineNodesPosMap1.get(planNodeTypeStr).toString(), null );
messages.add( "Inline "+planNodeTypeStr+" diff: \n"+strPair.toString() );
}
else{
diffPair strPair = new diffPair( inlineNodesPosMap1.get(planNodeTypeStr).toString(), inlineNodesPosMap2.get(planNodeTypeStr).toString() );
if( !strPair.equals() ) {
messages.add( "Inline "+planNodeTypeStr+" diff: \n"+strPair.toString() );
}
}
}
}
private static void scanNodeDiffModule( int leafID, AbstractScanPlanNode spn1, AbstractScanPlanNode spn2, ArrayList<String> messages ) {
diffPair stringdiffPair = new diffPair("", "");
String table1 = "";
String table2 = "";
String nodeType1 = "";
String nodeType2 = "";
String index1 = "";
String index2 = "";
if( spn1 == null && spn2 != null ) {
table2 = spn2.getTargetTableName();
nodeType2 = spn2.getPlanNodeType().toString();
if( nodeType2.equalsIgnoreCase(PlanNodeType.INDEXSCAN.name() ) ) {
index2 = ((IndexScanPlanNode)spn2).getTargetIndexName();
}
}
else if( spn2 == null && spn1 != null ) {
table1 = spn1.getTargetTableName();
nodeType1 = spn1.getPlanNodeType().toString();
if( nodeType1.equalsIgnoreCase(PlanNodeType.INDEXSCAN.name() ) ) {
index1 = ((IndexScanPlanNode)spn1).getTargetIndexName();
}
}
//both null is not possible
else{
table1 = spn1.getTargetTableName();
table2 = spn2.getTargetTableName();
nodeType1 = spn1.getPlanNodeType().toString();
nodeType2 = spn2.getPlanNodeType().toString();
if( nodeType1.equalsIgnoreCase(PlanNodeType.INDEXSCAN.name() ) ) {
index1 = ((IndexScanPlanNode)spn1).getTargetIndexName();
}
if( nodeType2.equalsIgnoreCase(PlanNodeType.INDEXSCAN.name() ) ) {
index2 = ((IndexScanPlanNode)spn2).getTargetIndexName();
}
}
if( !table1.equals(table2) ) {
stringdiffPair.set( table1.equals("") ? null : nodeType1+" on "+table1,
table2.equals("") ? null : nodeType2+" on "+table2 );
messages.add( "Table diff at leaf "+leafID+":"+"\n"+stringdiffPair.toString());
}
else if( !nodeType1.equals(nodeType2) ) {
stringdiffPair.set(nodeType1+" on "+table1, nodeType2+" on "+table2);
messages.add("Scan diff at leaf "+leafID+" :"+"\n"+stringdiffPair.toString());
}
else if ( nodeType1.equalsIgnoreCase(PlanNodeType.INDEXSCAN.name()) ) {
if( !index1.equals(index2) ) {
stringdiffPair.set( index1, index2);
messages.add("Index diff at leaf "+leafID+" :"+"\n"+stringdiffPair.toString());
} else {
messages.add("Same at leaf "+leafID);
}
}
//either index scan using same index or seqscan on same table
else{
messages.add("Same at leaf "+leafID);
}
}
public static boolean diffScans( AbstractPlanNode oldpn, AbstractPlanNode newpn ){
m_changedSQL = false;
boolean noDiff = true;
ArrayList<AbstractScanPlanNode> list1 = oldpn.getScanNodeList();
ArrayList<AbstractScanPlanNode> list2 = newpn.getScanNodeList();
int size1 = list1.size();
int size2 = list2.size();
int max = Math.max(size1, size2);
int min = Math.min(size1, size2);
diffPair intdiffPair = new diffPair(0,0);
ArrayList<String> messages = new ArrayList<String>();
AbstractScanPlanNode spn1 = null;
AbstractScanPlanNode spn2 = null;
if( max == 0 ) {
messages.add("0 scan statement");
}
else {
if( size1 != size2 ){
intdiffPair.set(size1, size2);
messages.add("Scan time diff : "+"\n"+intdiffPair.toString()+"\n"+"SQL statement might be changed");
m_changedSQL = true;
for( int i = 0; i < min; i++ ) {
spn1 = list1.get(i);
spn2 = list2.get(i);
scanNodeDiffModule(i, spn1, spn2, messages);
}
//lists size are different
if( size2 < max ) {
for( int i = min; i < max; i++ ) {
spn1 = list1.get(i);
spn2 = null;
scanNodeDiffModule(i, spn1, spn2, messages);
}
}
else if( size1 < max ) {
for( int i = min; i < max; i++ ) {
spn1 = null;
spn2 = list2.get(i);
scanNodeDiffModule(i, spn1, spn2, messages);
}
}
}
else {
messages.add( "same leaf size" );
if( max == 1 ) {
messages.add("Single scan plan");
spn1 = list1.get(0);
spn2 = list2.get(0);
scanNodeDiffModule(0, spn1, spn2, messages);
}
else {
messages.add("Join query");
for( int i = 0; i < max; i++ ) {
spn1 = list1.get(i);
spn2 = list2.get(i);
scanNodeDiffModule(i, spn1, spn2, messages);
}
}
}
}
for( String msg : messages ) {
if( msg.contains("diff") || msg.contains("Diff") ) {
noDiff = false;
break;
}
}
m_diffMessages.addAll(messages);
return noDiff;
}
//return true is there are no diff
//false if there's any diff
public static boolean diff( AbstractPlanNode oldpn, AbstractPlanNode newpn, boolean print ) {
m_diffMessages.clear();
boolean noDiff1 = diffScans(oldpn, newpn);
boolean noDiff2 = diffInlineAndJoin(oldpn, newpn);
noDiff1 = noDiff1 && noDiff2;
if( noDiff1 ) {
return true;
}
else {
if( print ) {
for( String msg : m_diffMessages ) {
System.out.println(msg);
}
}
return false;
}
}
}
| false | true | public static void main( String[] args ) {
int size = args.length;
for( int i=0; i<size; i++ ) {
String str = args[i];
if( str.startsWith("-C=")) {
String subStr = str.split("=")[1];
String [] configs = subStr.split(",");
for( String config : configs ) {
m_config.add( config.trim() );
}
}
if( str.startsWith("-sp=")) {
m_isSavePathFromCML = true;
String subStr = str.split("=")[1];
String [] savePaths = subStr.split(",");
for( String savePath : savePaths ) {
savePath = savePath.trim();
if( !savePath.endsWith("/") ){
savePath += "/";
}
m_savePlanPaths.add( savePath );
}
}
else if( str.startsWith("-cd") ) {
m_isCompileSave = true;
m_isDiff = true;
m_showExpainedPlan = true;
m_showSQLStatement = true;
}
else if( str.startsWith("-cs") ) {
m_isCompileSave = true;
}
else if( str.startsWith("-d") ) {
m_isDiff = true;
}
else if( str.startsWith("-r") ){
m_reportDir = str.split("=")[1];
m_reportDir = m_reportDir.trim();
if( !m_reportDir.endsWith("/") ) {
m_reportDir += "/";
}
}
else if( str.startsWith("-e") ){
m_showExpainedPlan = true;
}
else if( str.startsWith("-s") ){
m_showSQLStatement = true;
}
else if( str.startsWith("-i=") ) {
m_filters.add(str.split("=")[1] );
}
else if( str.startsWith("-help") || str.startsWith("-h") ){
printUsage();
System.exit(0);
}
}
size = m_config.size();
if( m_isCompileSave ) {
Iterator<String> it = m_savePlanPaths.iterator();
for( String config : m_config ) {
try {
setUp( config );
if( m_isSavePathFromCML && it.hasNext() ) {
m_savePlanPath = it.next();
}
batchCompileSave();
} catch (Exception e) {
e.printStackTrace();
}
}
}
if( m_isDiff ) {
if( !new File(m_reportDir).exists() ) {
new File(m_reportDir).mkdirs();
}
try {
m_reportWriter = new BufferedWriter(new FileWriter( m_reportDir+"plannerTester.report" ));
} catch (IOException e1) {
System.out.println(e1.getMessage());
System.exit(-1);
}
for( String config : m_config ) {
try {
setUp( config );
startDiff();
} catch (Exception e) {
e.printStackTrace();
}
}
int numTest = m_numPass + m_numFail;
System.out.println("Test: "+numTest);
System.out.println("Pass: "+m_numPass);
System.out.println("Fail: "+m_numFail);
try {
m_reportWriter.write( "\nTest: "+numTest+"\n"
+"Pass: "+m_numPass+"\n"
+"Fail: "+m_numFail+"\n");
m_reportWriter.flush();
m_reportWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Report file created at "+m_reportDir+"plannerTester.report");
}
if( m_numFail == 0 ) {
System.exit(0);
} else {
System.exit(1);
}
}
| public static void main( String[] args ) {
int size = args.length;
for( int i=0; i<size; i++ ) {
String str = args[i];
if( str.startsWith("-C=")) {
String subStr = str.split("=")[1];
String [] configs = subStr.split(",");
for( String config : configs ) {
m_config.add( config.trim() );
}
}
if( str.startsWith("-sp=")) {
m_isSavePathFromCML = true;
String subStr = str.split("=")[1];
String [] savePaths = subStr.split(",");
for( String savePath : savePaths ) {
savePath = savePath.trim();
if( !savePath.endsWith("/") ){
savePath += "/";
}
m_savePlanPaths.add( savePath );
}
}
else if( str.startsWith("-cd") ) {
m_isCompileSave = true;
m_isDiff = true;
m_showExpainedPlan = true;
m_showSQLStatement = true;
}
else if( str.startsWith("-cs") ) {
m_isCompileSave = true;
}
else if( str.startsWith("-d") ) {
m_isDiff = true;
}
else if( str.startsWith("-r") ){
m_reportDir = str.split("=")[1];
m_reportDir = m_reportDir.trim();
if( !m_reportDir.endsWith("/") ) {
m_reportDir += "/";
}
}
else if( str.startsWith("-e") ){
m_showExpainedPlan = true;
}
else if( str.startsWith("-s") ){
m_showSQLStatement = true;
}
else if( str.startsWith("-i=") ) {
m_filters.add(str.split("=")[1] );
}
else if( str.startsWith("-help") || str.startsWith("-h") ){
printUsage();
System.exit(0);
}
}
size = m_config.size();
if( m_isCompileSave ) {
Iterator<String> it = m_savePlanPaths.iterator();
for( String config : m_config ) {
try {
setUp( config );
if( m_isSavePathFromCML && it.hasNext() ) {
m_savePlanPath = it.next();
}
batchCompileSave();
} catch (Exception e) {
e.printStackTrace();
}
}
}
if( m_isDiff ) {
if( !new File(m_reportDir).exists() ) {
new File(m_reportDir).mkdirs();
}
try {
m_reportWriter = new BufferedWriter(new FileWriter( m_reportDir+"plannerTester.report" ));
} catch (IOException e1) {
System.out.println(e1.getMessage());
System.exit(-1);
}
Iterator<String> it = m_savePlanPaths.iterator();
for( String config : m_config ) {
try {
setUp( config );
if( m_isSavePathFromCML && it.hasNext() ) {
m_savePlanPath = it.next();
}
startDiff();
} catch (Exception e) {
e.printStackTrace();
}
}
int numTest = m_numPass + m_numFail;
System.out.println("Test: "+numTest);
System.out.println("Pass: "+m_numPass);
System.out.println("Fail: "+m_numFail);
try {
m_reportWriter.write( "\nTest: "+numTest+"\n"
+"Pass: "+m_numPass+"\n"
+"Fail: "+m_numFail+"\n");
m_reportWriter.flush();
m_reportWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Report file created at "+m_reportDir+"plannerTester.report");
}
if( m_numFail == 0 ) {
System.exit(0);
} else {
System.exit(1);
}
}
|
diff --git a/project-set/external/service-clients/rackspace-auth-v1.1/src/main/java/com/rackspace/auth/v1_1/AuthenticationServiceClient.java b/project-set/external/service-clients/rackspace-auth-v1.1/src/main/java/com/rackspace/auth/v1_1/AuthenticationServiceClient.java
index a5c8fb92dc..07cfa31085 100644
--- a/project-set/external/service-clients/rackspace-auth-v1.1/src/main/java/com/rackspace/auth/v1_1/AuthenticationServiceClient.java
+++ b/project-set/external/service-clients/rackspace-auth-v1.1/src/main/java/com/rackspace/auth/v1_1/AuthenticationServiceClient.java
@@ -1,152 +1,152 @@
package com.rackspace.auth.v1_1;
import com.rackspace.papi.commons.util.regex.ExtractorResult;
import com.rackspacecloud.docs.auth.api.v1.FullToken;
import com.rackspacecloud.docs.auth.api.v1.GroupsList;
import com.sun.jersey.api.client.ClientResponse;
import net.sf.ehcache.CacheManager;
import java.util.Calendar;
import java.util.GregorianCalendar;
/**
*
* @author jhopper
*/
public class AuthenticationServiceClient {
private final String targetHostUri;
private final ServiceClient serviceClient;
private final ResponseUnmarshaller responseUnmarshaller;
private final CacheManager cacheManager;
private final AuthenticationCache authenticationCache;
private static enum AccountTypes {
MOSSO("MOSSO", "mosso"),
CLOUD("CLOUD", "users");
private final String prefix;
private final String type;
AccountTypes(String type, String prefix) {
this.prefix = prefix;
this.type = type;
}
public String getPrefix() {
return prefix;
}
public String getType() {
return type;
}
public static AccountTypes getAccountType(String type) {
for (AccountTypes t: AccountTypes.values()) {
if (t.type.equalsIgnoreCase(type)) {
return t;
}
}
return null;
}
}
public AuthenticationServiceClient(String targetHostUri, ResponseUnmarshaller responseUnmarshaller, ServiceClient serviceClient,
CacheManager cacheManager, AuthenticationCache authenticationCache) {
this.targetHostUri = targetHostUri;
this.responseUnmarshaller = responseUnmarshaller;
this.serviceClient = serviceClient;
this.cacheManager = cacheManager;
this.authenticationCache = authenticationCache;
}
public CachableTokenInfo validateToken(ExtractorResult<String> account, String token) {
CachableTokenInfo tokenInfo = authenticationCache.tokenIsCached(account.getResult(), token);
- if (token == null) {
+ if (tokenInfo == null) {
final ServiceClientResponse<FullToken> validateTokenMethod = serviceClient.get(targetHostUri + "/token/" + token,
"belongsTo", account.getResult(),
"type", account.getKey());
final int response = validateTokenMethod.getStatusCode();
switch (response) {
case 200:
final FullToken tokenResponse = responseUnmarshaller.unmarshall(validateTokenMethod.getData(), FullToken.class);
final int expireTtl = getTtl(tokenResponse.getExpires().toGregorianCalendar(), Calendar.getInstance());
final String userName = getUserNameForUserId(account.getResult(), account.getKey());
tokenInfo = authenticationCache.cacheUserAuthToken(account.getResult(), expireTtl, userName, tokenResponse.getId());
}
}
return tokenInfo;
}
public static int getTtl(GregorianCalendar expirationDate, Calendar currentTime) {
int ttl = Integer.MAX_VALUE;
final Long expireTtl = convertFromMillisecondsToSeconds(expirationDate.getTimeInMillis() - currentTime.getTimeInMillis());
if (expireTtl <= Integer.MAX_VALUE && expireTtl > 0) {
ttl = expireTtl.intValue();
}
return ttl;
}
// ehcache expects ttl in seconds
private static Long convertFromMillisecondsToSeconds(long milliseconds) {
final long numberOfMillisecondsInASecond = 1000;
return milliseconds / numberOfMillisecondsInASecond;
}
private String getLastPart(String value, String sep) {
if (value == null) {
return "";
}
String[] parts = value.split(sep);
return parts[parts.length - 1];
}
public String getUserNameForUserId(String userId, String type) {
final AccountTypes accountType = AccountTypes.getAccountType(type);
if (accountType == null) {
throw new IllegalArgumentException("Invalid account type");
}
final String prefix = accountType.getPrefix();
final String url = "/" + prefix + "/" + userId;
final ClientResponse response = serviceClient.getClientResponse(targetHostUri + url);
return getLastPart(response.getHeaders().getFirst("Location"), "/");
}
public GroupsList getGroups(String userName) {
final ServiceClientResponse<GroupsList> serviceResponse = serviceClient.get(targetHostUri + "/users/" + userName + "/groups");
final int response = serviceResponse.getStatusCode();
GroupsList groups = null;
switch (response) {
case 200:
groups = responseUnmarshaller.unmarshall(serviceResponse.getData(), GroupsList.class);
}
return groups;
}
@Override
protected void finalize() throws Throwable {
try {
if (cacheManager != null) {
cacheManager.shutdown();
}
} finally {
super.finalize();
}
}
}
| true | true | public CachableTokenInfo validateToken(ExtractorResult<String> account, String token) {
CachableTokenInfo tokenInfo = authenticationCache.tokenIsCached(account.getResult(), token);
if (token == null) {
final ServiceClientResponse<FullToken> validateTokenMethod = serviceClient.get(targetHostUri + "/token/" + token,
"belongsTo", account.getResult(),
"type", account.getKey());
final int response = validateTokenMethod.getStatusCode();
switch (response) {
case 200:
final FullToken tokenResponse = responseUnmarshaller.unmarshall(validateTokenMethod.getData(), FullToken.class);
final int expireTtl = getTtl(tokenResponse.getExpires().toGregorianCalendar(), Calendar.getInstance());
final String userName = getUserNameForUserId(account.getResult(), account.getKey());
tokenInfo = authenticationCache.cacheUserAuthToken(account.getResult(), expireTtl, userName, tokenResponse.getId());
}
}
return tokenInfo;
}
| public CachableTokenInfo validateToken(ExtractorResult<String> account, String token) {
CachableTokenInfo tokenInfo = authenticationCache.tokenIsCached(account.getResult(), token);
if (tokenInfo == null) {
final ServiceClientResponse<FullToken> validateTokenMethod = serviceClient.get(targetHostUri + "/token/" + token,
"belongsTo", account.getResult(),
"type", account.getKey());
final int response = validateTokenMethod.getStatusCode();
switch (response) {
case 200:
final FullToken tokenResponse = responseUnmarshaller.unmarshall(validateTokenMethod.getData(), FullToken.class);
final int expireTtl = getTtl(tokenResponse.getExpires().toGregorianCalendar(), Calendar.getInstance());
final String userName = getUserNameForUserId(account.getResult(), account.getKey());
tokenInfo = authenticationCache.cacheUserAuthToken(account.getResult(), expireTtl, userName, tokenResponse.getId());
}
}
return tokenInfo;
}
|
diff --git a/org.envirocar.app/src/org/envirocar/app/protocol/drivedeck/DriveDeckSportConnector.java b/org.envirocar.app/src/org/envirocar/app/protocol/drivedeck/DriveDeckSportConnector.java
index b917bfe7..0edfa1d8 100644
--- a/org.envirocar.app/src/org/envirocar/app/protocol/drivedeck/DriveDeckSportConnector.java
+++ b/org.envirocar.app/src/org/envirocar/app/protocol/drivedeck/DriveDeckSportConnector.java
@@ -1,345 +1,348 @@
/*
* enviroCar 2013
* Copyright (C) 2013
* Martin Dueren, Jakob Moellers, Gerald Pape, Christopher Stephan
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
package org.envirocar.app.protocol.drivedeck;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import org.envirocar.app.commands.CommonCommand;
import org.envirocar.app.commands.IntakePressure;
import org.envirocar.app.commands.IntakeTemperature;
import org.envirocar.app.commands.MAF;
import org.envirocar.app.commands.PIDSupported;
import org.envirocar.app.commands.RPM;
import org.envirocar.app.commands.CommonCommand.CommonCommandState;
import org.envirocar.app.commands.Speed;
import org.envirocar.app.logging.Logger;
import org.envirocar.app.protocol.AbstractAsynchronousConnector;
import org.envirocar.app.protocol.ResponseParser;
import org.envirocar.app.protocol.drivedeck.CycleCommand.PID;
public class DriveDeckSportConnector extends AbstractAsynchronousConnector {
private static final Logger logger = Logger.getLogger(DriveDeckSportConnector.class);
private static final char CARRIAGE_RETURN = '\r';
static final char END_OF_LINE_RESPONSE = '>';
private Protocol protocol;
private String vin;
private long firstConnectionResponse;
private CycleCommand cycleCommand;
private ResponseParser responseParser = new LocalResponseParser();
private ConnectionState state = ConnectionState.DISCONNECTED;
private boolean send;
private static enum Protocol {
CAN11500, CAN11250, CAN29500, CAN29250, KWP_SLOW, KWP_FAST, ISO9141
}
public DriveDeckSportConnector() {
createCycleCommand();
logger.info("Static CycleCommand: "+new String(cycleCommand.getOutgoingBytes()));
}
private void createCycleCommand() {
List<PID> pidList = new ArrayList<PID>();
pidList.add(PID.SPEED);
pidList.add(PID.MAF);
pidList.add(PID.RPM);
pidList.add(PID.IAP);
pidList.add(PID.IAT);
this.cycleCommand = new CycleCommand(pidList);
}
@Override
public ConnectionState connectionState() {
return this.state;
}
private void processDiscoveredControlUnits(String substring) {
logger.info("Discovered CUs... ");
}
private void processSupportedPID(byte[] bytes, int start, int count) {
String group = new String(bytes, start+6, 2);
if (group.equals("00")) {
/*
* this is the first group containing the PIDs of major interest
*/
PIDSupported pidCmd = new PIDSupported();
byte[] rawBytes = new byte[12];
rawBytes[0] = '4';
rawBytes[1] = '1';
rawBytes[2] = (byte) pidCmd.getResponseTypeID().charAt(0);
rawBytes[3] = (byte) pidCmd.getResponseTypeID().charAt(1);
int target = 4;
String hexTmp;
for (int i = 9; i < 14; i++) {
if (i == 11) continue;
hexTmp = oneByteToHex(bytes[i+start]);
rawBytes[target++] = (byte) hexTmp.charAt(0);
rawBytes[target++] = (byte) hexTmp.charAt(1);
}
pidCmd.setRawData(rawBytes);
pidCmd.parseRawData();
logger.info(pidCmd.getSupportedPIDs().toArray().toString());
}
}
private String oneByteToHex(byte b) {
String result = Integer.toString(b, 16).toUpperCase(Locale.US);
if (result.length() == 1) result = "0".concat(result);
return result;
}
private void processVIN(String vinInt) {
this.vin = vinInt;
logger.info("VIN is: "+this.vin);
updateConnectionState();
}
private void updateConnectionState() {
if (state == ConnectionState.VERIFIED) {
return;
}
if (protocol != null && vin != null) {
state = ConnectionState.CONNECTED;
}
}
private void determineProtocol(String protocolInt) {
int prot = Integer.parseInt(protocolInt);
switch (prot) {
case 1:
protocol = Protocol.CAN11500;
break;
case 2:
protocol = Protocol.CAN11250;
break;
case 3:
protocol = Protocol.CAN29500;
break;
case 4:
protocol = Protocol.CAN29250;
break;
case 5:
protocol = Protocol.KWP_SLOW;
break;
case 6:
protocol = Protocol.KWP_FAST;
break;
case 7:
protocol = Protocol.ISO9141;
break;
default:
return;
}
logger.info("Protocol is: "+ protocol.toString());
logger.info("Connected in "+ (System.currentTimeMillis() - firstConnectionResponse) +" ms.");
updateConnectionState();
}
@Override
public boolean supportsDevice(String deviceName) {
return deviceName.contains("DRIVEDECK") && deviceName.contains("W4");
}
private CommonCommand parsePIDResponse(String pid,
byte[] rawBytes, long now) {
CommonCommand result = null;
if (pid.equals("41")) {
//Speed
result = new Speed();
}
else if (pid.equals("42")) {
//MAF
result = new MAF();
}
else if (pid.equals("52")) {
//IAP
result = new IntakeTemperature();
}
else if (pid.equals("49")) {
//IAT
result = new IntakePressure();
}
else if (pid.equals("40") || pid.equals("51")) {
//RPM
result = new RPM();
}
if (result != null) {
byte[] rawData = createRawData(rawBytes, result.getResponseTypeID());
result.setRawData(rawData);
result.parseRawData();
result.setCommandState(CommonCommandState.FINISHED);
result.setResultTime(now);
this.state = ConnectionState.VERIFIED;
}
return result;
}
private byte[] createRawData(byte[] rawBytes, String type) {
byte[] result = new byte[4 + rawBytes.length*2];
byte[] typeBytes = type.getBytes();
result[0] = (byte) '4';
result[1] = (byte) '1';
result[2] = typeBytes[0];
result[3] = typeBytes[1];
for (int i = 0; i < rawBytes.length; i++) {
String hex = byteToHex(rawBytes[i]);
result[(i*2)+4] = (byte) hex.charAt(0);
result[(i*2)+1+4] = (byte) hex.charAt(1);
}
return result;
}
private String byteToHex(byte b) {
String result = Integer.toString((int) b, 16);
if (result.length() == 1) {
result = "0".concat(result);
}
return result;
}
@Override
protected List<CommonCommand> getRequestCommands() {
if (!send) {
send = true;
return Collections.singletonList((CommonCommand) cycleCommand);
}
else {
return Collections.emptyList();
}
}
@Override
protected char getRequestEndOfLine() {
return CARRIAGE_RETURN;
}
@Override
protected ResponseParser getResponseParser() {
return responseParser;
}
@Override
protected List<CommonCommand> getInitializationCommands() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
logger.warn(e.getMessage(), e);
}
return Collections.singletonList((CommonCommand) new CarriageReturnCommand());
}
@Override
public int getMaximumTriesForInitialization() {
return 15;
}
private class LocalResponseParser implements ResponseParser {
@Override
public CommonCommand processResponse(byte[] bytes, int start, int count) {
if (count <= 0) return null;
char type = (char) bytes[start+0];
if (type == CycleCommand.RESPONSE_PREFIX_CHAR) {
if ((char) bytes[start+4] == CycleCommand.TOKEN_SEPARATOR_CHAR) return null;
String pid = new String(bytes, start+1, 2);
/*
* METADATA Stuff
*/
if (pid.equals("14")) {
logger.debug("Status: CONNECTING");
}
else if (pid.equals("15")) {
processVIN(new String(bytes, start+3, count-3));
}
else if (pid.equals("70")) {
- processSupportedPID(bytes, start, count);
+ /*
+ * short term fix for #192: disable
+ */
+// processSupportedPID(bytes, start, count);
}
else if (pid.equals("71")) {
processDiscoveredControlUnits(new String(bytes, start+3, count-3));
}
else {
/*
* A PID response
*/
long now = System.currentTimeMillis();
logger.info("Processing PID Response:" +pid);
byte[] pidResponseValue = new byte[2];
int target;
for (int i = start+4; i <= count+start; i++) {
if ((char) bytes[i] == CycleCommand.TOKEN_SEPARATOR_CHAR)
break;
target = i-(start+4);
if (target >= pidResponseValue.length) break;
pidResponseValue[target] = bytes[i];
}
return parsePIDResponse(pid, pidResponseValue, now);
}
}
else if (type == 'C') {
determineProtocol(new String(bytes, start+1, count-1));
}
return null;
}
@Override
public char getEndOfLine() {
return END_OF_LINE_RESPONSE;
}
}
@Override
protected long getSleepTimeBetweenCommands() {
return 0;
}
}
| true | true | public CommonCommand processResponse(byte[] bytes, int start, int count) {
if (count <= 0) return null;
char type = (char) bytes[start+0];
if (type == CycleCommand.RESPONSE_PREFIX_CHAR) {
if ((char) bytes[start+4] == CycleCommand.TOKEN_SEPARATOR_CHAR) return null;
String pid = new String(bytes, start+1, 2);
/*
* METADATA Stuff
*/
if (pid.equals("14")) {
logger.debug("Status: CONNECTING");
}
else if (pid.equals("15")) {
processVIN(new String(bytes, start+3, count-3));
}
else if (pid.equals("70")) {
processSupportedPID(bytes, start, count);
}
else if (pid.equals("71")) {
processDiscoveredControlUnits(new String(bytes, start+3, count-3));
}
else {
/*
* A PID response
*/
long now = System.currentTimeMillis();
logger.info("Processing PID Response:" +pid);
byte[] pidResponseValue = new byte[2];
int target;
for (int i = start+4; i <= count+start; i++) {
if ((char) bytes[i] == CycleCommand.TOKEN_SEPARATOR_CHAR)
break;
target = i-(start+4);
if (target >= pidResponseValue.length) break;
pidResponseValue[target] = bytes[i];
}
return parsePIDResponse(pid, pidResponseValue, now);
}
}
else if (type == 'C') {
determineProtocol(new String(bytes, start+1, count-1));
}
return null;
}
| public CommonCommand processResponse(byte[] bytes, int start, int count) {
if (count <= 0) return null;
char type = (char) bytes[start+0];
if (type == CycleCommand.RESPONSE_PREFIX_CHAR) {
if ((char) bytes[start+4] == CycleCommand.TOKEN_SEPARATOR_CHAR) return null;
String pid = new String(bytes, start+1, 2);
/*
* METADATA Stuff
*/
if (pid.equals("14")) {
logger.debug("Status: CONNECTING");
}
else if (pid.equals("15")) {
processVIN(new String(bytes, start+3, count-3));
}
else if (pid.equals("70")) {
/*
* short term fix for #192: disable
*/
// processSupportedPID(bytes, start, count);
}
else if (pid.equals("71")) {
processDiscoveredControlUnits(new String(bytes, start+3, count-3));
}
else {
/*
* A PID response
*/
long now = System.currentTimeMillis();
logger.info("Processing PID Response:" +pid);
byte[] pidResponseValue = new byte[2];
int target;
for (int i = start+4; i <= count+start; i++) {
if ((char) bytes[i] == CycleCommand.TOKEN_SEPARATOR_CHAR)
break;
target = i-(start+4);
if (target >= pidResponseValue.length) break;
pidResponseValue[target] = bytes[i];
}
return parsePIDResponse(pid, pidResponseValue, now);
}
}
else if (type == 'C') {
determineProtocol(new String(bytes, start+1, count-1));
}
return null;
}
|
diff --git a/src/BoardFiller.java b/src/BoardFiller.java
index 66ce177..6530523 100644
--- a/src/BoardFiller.java
+++ b/src/BoardFiller.java
@@ -1,166 +1,166 @@
import java.util.LinkedList;
import java.util.Random;
/**
* Generates a board
* Randomly assigns values, checks they work, reassigns if required
* @author laura
*
*/
public class BoardFiller {
public BoardFiller(Board b)
{
this.b = b;
}
/*
public boolean fillBoardOld(){
int i, j, k;
int x = 0;
Random r = new Random();
LinkedList<Integer> l = new LinkedList<Integer>();
int resetPoint;
int counter = 0;
for(i = 0; i < 9; i++){
counter = 0;
j = 0;
while(j < 9){
k = squareNo(i, j);
// TODO THIS IS A NICE PLACE TO WATCH FROM IF YOU WANT TO =)
//System.out.printf("\n\n\n\n");
//printBoard();
//System.out.printf("\n\n\n");
//remove to here
for(int m = 1; m < 10; m++){
l.add(m);
}
do{
x = l.remove(r.nextInt(l.size()));
} while(!l.isEmpty() && (b.rowHas(i+1, x) || b.columnHas(j+1, x) || b.squareHas(k+1, x)));
if(l.isEmpty()){
if(i%3 == 2){
resetPoint = ((int)Math.floor(j/3)*3);
} else {
resetPoint = 0;
}
for(int p = resetPoint; p < 9; p++){
b.removeCellValue(i+1, p+1);
}
j = resetPoint;
counter++;
if (counter > 50){
b.clear();
return false;
}
continue;
}
b.setCellValue(i+1, j+1, x);
j++;
}
}
printBoard();
return true;
}*/
public boolean fillBoard(){
int row, col, square;
int x = 0;
Random r = new Random();
LinkedList<Integer> l = new LinkedList<Integer>();
int counter = 0;
row = 0;
while(row < 9){
counter = 0;
col = 0;
while(col < 9){
square = squareNo(row, col);
// TODO THIS IS A NICE PLACE TO WATCH FROM IF YOU WANT TO =)
//System.out.printf("\n\n\n\n");
//printBoard();
//System.out.printf("\n\n\n");
//remove to here
for(int m = 1; m < 10; m++){
l.add(m);
}
do{
x = l.remove(r.nextInt(l.size()));
} while(!l.isEmpty() && (b.rowHas(row+1, x) || b.columnHas(col+1, x) || b.squareHas(square+1, x)));
if(l.isEmpty()){
col = reset(row, col);
counter++;
if (counter > ATTEMPT_LIMIT){
//TODO test to make sure this still works
b.clear();
- row = 0;
+ row = -1;
break;
}
} else {
b.setCellValue(row+1, col+1, x);
col++;
}
}
row++;
}
return true;
}
/**
* Unsets the values in the cells up to a reset point based on current progress at board filling
* @param row row the filler got stuck on
* @param col column the filler got stuck on
* @return column the filler has reset to
*/
private int reset(int row, int col){
int resetPoint;
if(row%3 == 2){
resetPoint = ((int)Math.floor(col/3)*3);
} else {
resetPoint = 0;
}
for(int p = resetPoint; p < 9; p++){
b.removeCellValue(row+1, p+1);
}
return resetPoint;
}
/**
* The number of the square the given cell is in
* @param row row of cell
* @param column column of cell
* @return square number
*/
private int squareNo(int row, int column){
return ((int)Math.floor(column/3) + (int)Math.floor(row/3)*3);
}
//FOR DEBUGGING PURPOSES ONLY DO NOT USE
//TODO remove after debugging is finished
public void printBoard(){
int i,j;
for(i = 0; i < 9; i++){
for(j = 0; j < 9; j++){
//System.out.println("checking if " + i + " " + j + " is initially visible");
if(b.hasInput(i+1, j+1)){
System.out.printf("%d" , b.getCellValue(i+1, j+1));
} else {
System.out.printf("%d", 0);
}
}
System.out.printf("\n");
}
}
private Board b;
private static final int ATTEMPT_LIMIT = 20;
}
| true | true | public boolean fillBoard(){
int row, col, square;
int x = 0;
Random r = new Random();
LinkedList<Integer> l = new LinkedList<Integer>();
int counter = 0;
row = 0;
while(row < 9){
counter = 0;
col = 0;
while(col < 9){
square = squareNo(row, col);
// TODO THIS IS A NICE PLACE TO WATCH FROM IF YOU WANT TO =)
//System.out.printf("\n\n\n\n");
//printBoard();
//System.out.printf("\n\n\n");
//remove to here
for(int m = 1; m < 10; m++){
l.add(m);
}
do{
x = l.remove(r.nextInt(l.size()));
} while(!l.isEmpty() && (b.rowHas(row+1, x) || b.columnHas(col+1, x) || b.squareHas(square+1, x)));
if(l.isEmpty()){
col = reset(row, col);
counter++;
if (counter > ATTEMPT_LIMIT){
//TODO test to make sure this still works
b.clear();
row = 0;
break;
}
} else {
b.setCellValue(row+1, col+1, x);
col++;
}
}
row++;
}
return true;
}
| public boolean fillBoard(){
int row, col, square;
int x = 0;
Random r = new Random();
LinkedList<Integer> l = new LinkedList<Integer>();
int counter = 0;
row = 0;
while(row < 9){
counter = 0;
col = 0;
while(col < 9){
square = squareNo(row, col);
// TODO THIS IS A NICE PLACE TO WATCH FROM IF YOU WANT TO =)
//System.out.printf("\n\n\n\n");
//printBoard();
//System.out.printf("\n\n\n");
//remove to here
for(int m = 1; m < 10; m++){
l.add(m);
}
do{
x = l.remove(r.nextInt(l.size()));
} while(!l.isEmpty() && (b.rowHas(row+1, x) || b.columnHas(col+1, x) || b.squareHas(square+1, x)));
if(l.isEmpty()){
col = reset(row, col);
counter++;
if (counter > ATTEMPT_LIMIT){
//TODO test to make sure this still works
b.clear();
row = -1;
break;
}
} else {
b.setCellValue(row+1, col+1, x);
col++;
}
}
row++;
}
return true;
}
|
diff --git a/src/java/main/org/strasa/web/uploadstudy/view/model/UploadData.java b/src/java/main/org/strasa/web/uploadstudy/view/model/UploadData.java
index 8bac36e3..88f7cd47 100644
--- a/src/java/main/org/strasa/web/uploadstudy/view/model/UploadData.java
+++ b/src/java/main/org/strasa/web/uploadstudy/view/model/UploadData.java
@@ -1,722 +1,721 @@
package org.strasa.web.uploadstudy.view.model;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.security.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.input.ReaderInputStream;
import org.strasa.middleware.filesystem.manager.UserFileManager;
import org.strasa.middleware.manager.GermplasmManagerImpl;
import org.strasa.middleware.manager.ProgramManagerImpl;
import org.strasa.middleware.manager.ProjectManagerImpl;
import org.strasa.middleware.manager.StudyDerivedDataManagerImpl;
import org.strasa.middleware.manager.StudyGermplasmManagerImpl;
import org.strasa.middleware.manager.StudyRawDataManagerImpl;
import org.strasa.middleware.manager.StudyTypeManagerImpl;
import org.strasa.middleware.manager.StudyVariableManagerImpl;
import org.strasa.middleware.model.Program;
import org.strasa.middleware.model.Project;
import org.strasa.middleware.model.Study;
import org.strasa.middleware.model.StudyGermplasm;
import org.strasa.middleware.model.StudyRawDataByDataColumn;
import org.strasa.middleware.model.StudyType;
import org.strasa.web.common.api.Encryptions;
import org.strasa.web.common.api.ProcessTabViewModel;
import org.strasa.web.uploadstudy.view.pojos.UploadCSVDataVariableModel;
import org.strasa.web.utilities.FileUtilities;
import org.zkoss.bind.BindContext;
import org.zkoss.bind.BindUtils;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.ContextParam;
import org.zkoss.bind.annotation.ContextType;
import org.zkoss.bind.annotation.GlobalCommand;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.UploadEvent;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;
import au.com.bytecode.opencsv.CSVReader;
public class UploadData extends ProcessTabViewModel {
private List<String> columnList = new ArrayList<String>();
public String dataFileName;
private List<String[]> dataList = new ArrayList<String[]>();
private ArrayList<String> programList = new ArrayList<String>();
private ArrayList<String> projectList = new ArrayList<String>();
private ArrayList<String> studyTypeList = new ArrayList<String>();
private ArrayList<String> dataTypeList = new ArrayList<String>();
private ArrayList<GenotypeFileModel> genotypeFileList = new ArrayList<UploadData.GenotypeFileModel>();
private String txtProgram = new String();
private String txtProject = new String();
private String txtStudyName = new String();
private String txtStudyType = new String();
private int startYear = Calendar.getInstance().get(Calendar.YEAR);
private int endYear = Calendar.getInstance().get(Calendar.YEAR);
private int pageSize = 10;
private int activePage = 0;
private File tempFile;
private String uploadTo = "database";
private String studyType = "rawdata";
public ArrayList<GenotypeFileModel> getGenotypeFileList() {
return genotypeFileList;
}
public void setGenotypeFileList(
ArrayList<GenotypeFileModel> genotypeFileList) {
this.genotypeFileList = genotypeFileList;
}
public int getTotalSize() {
return dataList.size();
}
public Study getStudy() {
return study;
}
public int getStartYear() {
return startYear;
}
public void setStartYear(int startYear) {
this.startYear = startYear;
}
public int getEndYear() {
return endYear;
}
public void setEndYear(int endYear) {
this.endYear = endYear;
}
public void setStudy(Study study) {
this.study = study;
}
private String txtYear = "";
public int getPageSize() {
return pageSize;
}
@NotifyChange("*")
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
@NotifyChange("*")
public int getActivePage() {
return activePage;
}
@NotifyChange("*")
public void setActivePage(int activePage) {
System.out.println("pageSize");
this.activePage = activePage;
}
public boolean isVariableDataVisible = false;
private Study study;
public List<UploadCSVDataVariableModel> varData = new ArrayList<UploadCSVDataVariableModel>();
private int userId = 1;
public ArrayList<String> getProgramList() {
return programList;
}
public void setProgramList(ArrayList<String> programList) {
this.programList = programList;
}
public String getUploadTo() {
return uploadTo;
}
public void setUploadTo(String uploadTo) {
this.uploadTo = uploadTo;
}
public String getStudyType() {
return studyType;
}
public void setStudyType(String studyType) {
this.studyType = studyType;
}
public ArrayList<String> getProjectList() {
return projectList;
}
public void setProjectList(ArrayList<String> projectList) {
this.projectList = projectList;
}
public ArrayList<String> getDataTypeList() {
return dataTypeList;
}
public void setDataTypeList(ArrayList<String> dataTypeList) {
this.dataTypeList = dataTypeList;
}
public ArrayList<String> getStudyTypeList() {
studyTypeList.clear();
for (StudyType studyType : new StudyTypeManagerImpl().getAllStudyType()) {
studyTypeList.add(studyType.getStudytype());
}
;
return studyTypeList;
}
public void setStudyTypeList(ArrayList<String> studyTypeList) {
this.studyTypeList = studyTypeList;
}
public String getTxtProgram() {
return txtProgram;
}
public void setTxtProgram(String txtProgram) {
this.txtProgram = txtProgram;
}
public String getTxtProject() {
return txtProject;
}
public void setTxtProject(String txtProject) {
this.txtProject = txtProject;
}
public String getTxtStudyName() {
return txtStudyName;
}
public void setTxtStudyName(String txtStudyName) {
this.txtStudyName = txtStudyName;
}
public String getTxtStudyType() {
return txtStudyType;
}
public void setTxtStudyType(String txtStudyType) {
this.txtStudyType = txtStudyType;
}
public String getTxtYear() {
return txtYear;
}
public void setTxtYear(String txtYear) {
this.txtYear = txtYear;
}
public List<String> getColumnList() {
return columnList;
}
public void setColumnList(List<String> columnList) {
this.columnList = columnList;
}
public List<String[]> getDataList() {
if (true)
return dataList;
ArrayList<String[]> pageData = new ArrayList<String[]>();
for (int i = activePage * pageSize; i < activePage * pageSize
+ pageSize; i++) {
pageData.add(dataList.get(i));
System.out.println(Arrays.toString(dataList.get(i)));
}
return pageData;
}
public ArrayList<ArrayList<String>> getCsvData() {
ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
if (dataList.isEmpty())
return result;
for (int i = activePage * pageSize; i < activePage * pageSize
+ pageSize
&& i < dataList.size(); i++) {
ArrayList<String> row = new ArrayList<String>();
row.addAll(Arrays.asList(dataList.get(i)));
result.add(row);
row.add(0, " ");
System.out.println(Arrays.toString(dataList.get(i)) + "ROW: "
+ row.get(0));
}
return result;
}
public void setDataList(List<String[]> dataList) {
this.dataList = dataList;
}
public String getDataFileName() {
return dataFileName;
}
public boolean isVariableDataVisible() {
return isVariableDataVisible;
}
public void setVariableDataVisible(boolean isVariableDataVisible) {
this.isVariableDataVisible = isVariableDataVisible;
}
public List<UploadCSVDataVariableModel> getVarData() {
return varData;
}
@Command
@NotifyChange("variableData")
public void changeVar(
@ContextParam(ContextType.BIND_CONTEXT) BindContext ctx,
@ContextParam(ContextType.VIEW) Component view,
@BindingParam("oldVar") String oldVar) {
Map<String, Object> params = new HashMap<String, Object>();
System.out.println(oldVar);
params.put("oldVar", oldVar);
params.put("parent", view);
Window popup = (Window) Executions.createComponents(
DataColumnChanged.ZUL_PATH, view, params);
popup.doModal();
}
@NotifyChange("*")
@Command("uploadCSV")
public void uploadCSV(
@ContextParam(ContextType.BIND_CONTEXT) BindContext ctx,
@ContextParam(ContextType.VIEW) Component view) {
UploadEvent event = (UploadEvent) ctx.getTriggerEvent();
// System.out.println(event.getMedia().getStringData());
String name = event.getMedia().getName();
if (tempFile == null)
try {
tempFile = File.createTempFile(name, ".tmp");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (!name.endsWith(".csv")) {
Messagebox.show("Error: File must be a text-based csv format",
"Upload Error", Messagebox.OK, Messagebox.ERROR);
return;
}
InputStream in = event.getMedia().isBinary() ? event.getMedia()
.getStreamData() : new ReaderInputStream(event.getMedia()
.getReaderData());
FileUtilities.uploadFile(tempFile.getAbsolutePath(), in);
BindUtils.postNotifyChange(null, null, this, "*");
ArrayList<String> invalidHeader = new ArrayList<String>();
boolean isHeaderValid = true;
try {
StudyVariableManagerImpl studyVarMan = new StudyVariableManagerImpl();
CSVReader reader = new CSVReader(new FileReader(
tempFile.getAbsolutePath()));
String[] header = reader.readNext();
for (String column : header) {
if (!studyVarMan.hasVariable(column)) {
invalidHeader.add(column);
isHeaderValid = false;
}
}
System.out.println(invalidHeader.size());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
isVariableDataVisible = true;
dataFileName = name;
if (!isHeaderValid)
openCSVHeaderValidator(tempFile.getAbsolutePath(), false);
else
refreshCsv();
}
public void uploadFile(String path, String name, String data) {
String filePath = path + name;
try {
PrintWriter out = new PrintWriter(filePath);
out.println(data);
out.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Command("addProgram")
public void addProgram() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("oldVar", null);
params.put("parent", getMainView());
Window popup = (Window) Executions.createComponents(
AddProgram.ZUL_PATH, getMainView(), params);
popup.doModal();
}
@Command("addProject")
public void addProject() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("oldVar", null);
params.put("parent", getMainView());
Window popup = (Window) Executions.createComponents(
AddProject.ZUL_PATH, getMainView(), params);
popup.doModal();
}
@GlobalCommand
public void testGlobalCom(@BindingParam("newVal") double newVal) {
System.out.println("globalCom: " + newVal);
}
@Init
public void init(@ContextParam(ContextType.VIEW) Component view) {
setMainView(view);
refreshProgramList(null);
refreshProjectList(null);
System.out.println("LOADED");
}
public void openCSVHeaderValidator(String CSVPath, boolean showAll) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("CSVPath", CSVPath);
params.put("parent", getMainView());
params.put("showAll", showAll);
Window popup = (Window) Executions.createComponents(
DataColumnValidation.ZUL_PATH, getMainView(), params);
popup.doModal();
}
@NotifyChange("*")
@Command("refreshVarList")
public void refreshList(@BindingParam("newValue") String newValue,
@BindingParam("oldVar") String oldVar) {
for (int i = 0; i < varData.size(); i++) {
if (varData.get(i).getCurrentVariable().equals(oldVar)) {
System.out.println(" ss");
varData.get(i).setNewVariable(newValue);
}
}
}
@NotifyChange("*")
@Command("removeUpload")
public void removeUpload() {
isVariableDataVisible = false;
dataFileName = "";
varData.clear();
}
@NotifyChange("*")
@Command("refreshCsv")
public void refreshCsv() {
activePage = 0;
CSVReader reader;
try {
reader = new CSVReader(new FileReader(tempFile.getAbsolutePath()));
List<String[]> rawData = reader.readAll();
columnList.clear();
dataList.clear();
columnList = new ArrayList<String>(Arrays.asList(rawData.get(0)));
rawData.remove(0);
dataList = new ArrayList<String[]>(rawData);
System.out.println(Arrays.toString(dataList.get(0)));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@NotifyChange("*")
@Command("refreshProgramList")
public void refreshProgramList(@BindingParam("selected") String selected) {
ProgramManagerImpl programMan = new ProgramManagerImpl();
programList.clear();
for (Program data : programMan.getProgramByUserId(1)) {
programList.add(data.getName());
}
System.out.print(selected);
txtProgram = selected;
}
@NotifyChange("*")
@Command("refreshProjectList")
public void refreshProjectList(@BindingParam("selected") String selected) {
ProjectManagerImpl programMan = new ProjectManagerImpl();
projectList.clear();
for (Project data : programMan.getProjectByUserId(1)) {
projectList.add(data.getName());
}
System.out.print(selected);
txtProject = selected;
}
@Override
public boolean validateTab() {
Runtimer timer = new Runtimer();
timer.start();
boolean isRawData = studyType.equalsIgnoreCase("rawdata");
System.out.println("StudyType: " + studyType + " + " + isRawData);
if (txtProgram == null || txtProject == null || txtStudyName == null
|| txtStudyType == null) {
Messagebox.show("Error: All fields are required", "Upload Error",
Messagebox.OK, Messagebox.ERROR);
// TODO: must have message DIalog
return false;
}
if (txtProgram.isEmpty() || txtProject.isEmpty()
|| txtStudyName.isEmpty() || txtStudyType.isEmpty()
) {
Messagebox.show("Error: All fields are required", "Upload Error",
Messagebox.OK, Messagebox.ERROR);
// TODO: must have message DIalog
return false;
}
if (tempFile == null || !isVariableDataVisible) {
Messagebox.show("Error: You must upload a data first",
"Upload Error", Messagebox.OK, Messagebox.ERROR);
return false;
}
if(startYear < Calendar.getInstance().get(Calendar.YEAR)){
Messagebox.show("Error: Invalid start year. Year must be greater or equal than the present year(" + Calendar.getInstance().get(Calendar.YEAR) + " )",
"Upload Error", Messagebox.OK, Messagebox.ERROR);
return false;
}
if(endYear < Calendar.getInstance().get(Calendar.YEAR)){
Messagebox.show("Error: Invalid end year. Year must be greater or equal than the present year(" + Calendar.getInstance().get(Calendar.YEAR) + " )",
"Upload Error", Messagebox.OK, Messagebox.ERROR);
return false;
}
UserFileManager fileMan = new UserFileManager();
StudyRawDataManagerImpl studyRawData = new StudyRawDataManagerImpl(isRawData);
- StudyDerivedDataManagerImpl studyDerivedDataMan = new StudyDerivedDataManagerImpl();
if (study == null) {
study = new Study();
}
study.setName(txtStudyName);
study.setStudytypeid(new StudyTypeManagerImpl().getStudyTypeByName(
txtStudyType).getId());
study.setProgramid(new ProgramManagerImpl().getProgramByName(
txtProgram, userId).getId());
study.setProjectid(new ProjectManagerImpl().getProjectByName(
txtProject, userId).getId());
study.setStartyear(String.valueOf(startYear));
study.setEndyear(String.valueOf(String.valueOf(endYear)));
if (uploadTo.equals("database")) {
studyRawData.addStudyRawData(study,columnList.toArray(new String[columnList.size()]),dataList);
// studyRawData.addStudyRawDataByRawCsvList(study,
// new CSVReader(new FileReader(tempFile)).readAll());
// GermplasmManagerImpl germplasmManager = new GermplasmManagerImpl();
// StudyGermplasmManagerImpl studyGermplasmManager = new StudyGermplasmManagerImpl();
//
// StudyRawDataManagerImpl studyRawDataManagerImpl = new StudyRawDataManagerImpl(isRawData);
// ArrayList<StudyRawDataByDataColumn> list = (ArrayList<StudyRawDataByDataColumn>) studyRawDataManagerImpl
// .getStudyRawDataColumn(study.getId(), "GName");
// for (StudyRawDataByDataColumn s : list) {
// // System.out.println(s.getStudyid()+
// // " "+s.getDatacolumn()+
// // " "+ s.getDatavalue());
//
// if (!germplasmManager.isGermplasmExisting(s
// .getDatavalue())) {
// StudyGermplasm studyGermplasmData = new StudyGermplasm();
// studyGermplasmData.setGermplasmname(s
// .getDatavalue());
// studyGermplasmData.setStudyid(study.getId());
// studyGermplasmManager
// .addStudyGermplasm(studyGermplasmData);
// }
}
else{
fileMan.createNewFileFromUpload(1, study.getId(), dataFileName, tempFile, (isRaw) ? "rd":"dd");
}
for(GenotypeFileModel genoFile : genotypeFileList){
fileMan.createNewFileFromUpload(1, study.getId(), genoFile.name, genoFile.tempFile,"gd");
}
this.setStudyID(study.getId());
this.isRaw = isRawData;
System.out.println("Timer ends in: " + timer.end());
return true;
}
@NotifyChange("genotypeFileList")
@Command("uploadGenotypeData")
public void uploadGenotypeData(
@ContextParam(ContextType.BIND_CONTEXT) BindContext ctx,
@ContextParam(ContextType.VIEW) Component view) {
UploadEvent event = (UploadEvent) ctx.getTriggerEvent();
// System.out.println(event.getMedia().getStringData());
String name = event.getMedia().getName();
if (!name.endsWith(".txt")) {
Messagebox.show("Error: File must be a text-based format",
"Upload Error", Messagebox.OK, Messagebox.ERROR);
return;
}
try {
String filename = name
+ Encryptions.encryptStringToNumber(name,
new Date().getTime());
File tempGenoFile = File.createTempFile(filename, ".tmp");
InputStream in = event.getMedia().isBinary() ? event.getMedia()
.getStreamData() : new ReaderInputStream(event.getMedia()
.getReaderData());
FileUtilities.uploadFile(tempGenoFile.getAbsolutePath(), in);
GenotypeFileModel newGenotypeFile = new GenotypeFileModel(name,
tempGenoFile);
genotypeFileList.add(newGenotypeFile);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
@Command
public void modifyDataHeader() {
openCSVHeaderValidator(tempFile.getAbsolutePath(), true);
}
@NotifyChange("genotypeFileList")
@Command("removeGenotypeFile")
public void removeGenotypeFile(@BindingParam("index") int index) {
System.out.println("Deleted file index: " + index);
genotypeFileList.get(index).tempFile.delete();
genotypeFileList.remove(index);
}
public class Runtimer {
long startTime = System.nanoTime();
public long start(){
startTime = System.nanoTime();
return startTime;
}
public double end() {
long endTime = System.nanoTime();
return (endTime - startTime) / 1000000000.0;
}
}
public class GenotypeFileModel {
private String name;
private File tempFile;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public File getFilepath() {
return tempFile;
}
public void setFilepath(File filepath) {
this.tempFile = filepath;
}
public GenotypeFileModel(String name, File path) {
this.name = name;
this.tempFile = path;
}
}
}
| true | true | public boolean validateTab() {
Runtimer timer = new Runtimer();
timer.start();
boolean isRawData = studyType.equalsIgnoreCase("rawdata");
System.out.println("StudyType: " + studyType + " + " + isRawData);
if (txtProgram == null || txtProject == null || txtStudyName == null
|| txtStudyType == null) {
Messagebox.show("Error: All fields are required", "Upload Error",
Messagebox.OK, Messagebox.ERROR);
// TODO: must have message DIalog
return false;
}
if (txtProgram.isEmpty() || txtProject.isEmpty()
|| txtStudyName.isEmpty() || txtStudyType.isEmpty()
) {
Messagebox.show("Error: All fields are required", "Upload Error",
Messagebox.OK, Messagebox.ERROR);
// TODO: must have message DIalog
return false;
}
if (tempFile == null || !isVariableDataVisible) {
Messagebox.show("Error: You must upload a data first",
"Upload Error", Messagebox.OK, Messagebox.ERROR);
return false;
}
if(startYear < Calendar.getInstance().get(Calendar.YEAR)){
Messagebox.show("Error: Invalid start year. Year must be greater or equal than the present year(" + Calendar.getInstance().get(Calendar.YEAR) + " )",
"Upload Error", Messagebox.OK, Messagebox.ERROR);
return false;
}
if(endYear < Calendar.getInstance().get(Calendar.YEAR)){
Messagebox.show("Error: Invalid end year. Year must be greater or equal than the present year(" + Calendar.getInstance().get(Calendar.YEAR) + " )",
"Upload Error", Messagebox.OK, Messagebox.ERROR);
return false;
}
UserFileManager fileMan = new UserFileManager();
StudyRawDataManagerImpl studyRawData = new StudyRawDataManagerImpl(isRawData);
StudyDerivedDataManagerImpl studyDerivedDataMan = new StudyDerivedDataManagerImpl();
if (study == null) {
study = new Study();
}
study.setName(txtStudyName);
study.setStudytypeid(new StudyTypeManagerImpl().getStudyTypeByName(
txtStudyType).getId());
study.setProgramid(new ProgramManagerImpl().getProgramByName(
txtProgram, userId).getId());
study.setProjectid(new ProjectManagerImpl().getProjectByName(
txtProject, userId).getId());
study.setStartyear(String.valueOf(startYear));
study.setEndyear(String.valueOf(String.valueOf(endYear)));
if (uploadTo.equals("database")) {
studyRawData.addStudyRawData(study,columnList.toArray(new String[columnList.size()]),dataList);
// studyRawData.addStudyRawDataByRawCsvList(study,
// new CSVReader(new FileReader(tempFile)).readAll());
// GermplasmManagerImpl germplasmManager = new GermplasmManagerImpl();
// StudyGermplasmManagerImpl studyGermplasmManager = new StudyGermplasmManagerImpl();
//
// StudyRawDataManagerImpl studyRawDataManagerImpl = new StudyRawDataManagerImpl(isRawData);
// ArrayList<StudyRawDataByDataColumn> list = (ArrayList<StudyRawDataByDataColumn>) studyRawDataManagerImpl
// .getStudyRawDataColumn(study.getId(), "GName");
// for (StudyRawDataByDataColumn s : list) {
// // System.out.println(s.getStudyid()+
// // " "+s.getDatacolumn()+
// // " "+ s.getDatavalue());
//
// if (!germplasmManager.isGermplasmExisting(s
// .getDatavalue())) {
// StudyGermplasm studyGermplasmData = new StudyGermplasm();
// studyGermplasmData.setGermplasmname(s
// .getDatavalue());
// studyGermplasmData.setStudyid(study.getId());
// studyGermplasmManager
// .addStudyGermplasm(studyGermplasmData);
// }
}
else{
fileMan.createNewFileFromUpload(1, study.getId(), dataFileName, tempFile, (isRaw) ? "rd":"dd");
}
for(GenotypeFileModel genoFile : genotypeFileList){
fileMan.createNewFileFromUpload(1, study.getId(), genoFile.name, genoFile.tempFile,"gd");
}
this.setStudyID(study.getId());
this.isRaw = isRawData;
System.out.println("Timer ends in: " + timer.end());
return true;
}
| public boolean validateTab() {
Runtimer timer = new Runtimer();
timer.start();
boolean isRawData = studyType.equalsIgnoreCase("rawdata");
System.out.println("StudyType: " + studyType + " + " + isRawData);
if (txtProgram == null || txtProject == null || txtStudyName == null
|| txtStudyType == null) {
Messagebox.show("Error: All fields are required", "Upload Error",
Messagebox.OK, Messagebox.ERROR);
// TODO: must have message DIalog
return false;
}
if (txtProgram.isEmpty() || txtProject.isEmpty()
|| txtStudyName.isEmpty() || txtStudyType.isEmpty()
) {
Messagebox.show("Error: All fields are required", "Upload Error",
Messagebox.OK, Messagebox.ERROR);
// TODO: must have message DIalog
return false;
}
if (tempFile == null || !isVariableDataVisible) {
Messagebox.show("Error: You must upload a data first",
"Upload Error", Messagebox.OK, Messagebox.ERROR);
return false;
}
if(startYear < Calendar.getInstance().get(Calendar.YEAR)){
Messagebox.show("Error: Invalid start year. Year must be greater or equal than the present year(" + Calendar.getInstance().get(Calendar.YEAR) + " )",
"Upload Error", Messagebox.OK, Messagebox.ERROR);
return false;
}
if(endYear < Calendar.getInstance().get(Calendar.YEAR)){
Messagebox.show("Error: Invalid end year. Year must be greater or equal than the present year(" + Calendar.getInstance().get(Calendar.YEAR) + " )",
"Upload Error", Messagebox.OK, Messagebox.ERROR);
return false;
}
UserFileManager fileMan = new UserFileManager();
StudyRawDataManagerImpl studyRawData = new StudyRawDataManagerImpl(isRawData);
if (study == null) {
study = new Study();
}
study.setName(txtStudyName);
study.setStudytypeid(new StudyTypeManagerImpl().getStudyTypeByName(
txtStudyType).getId());
study.setProgramid(new ProgramManagerImpl().getProgramByName(
txtProgram, userId).getId());
study.setProjectid(new ProjectManagerImpl().getProjectByName(
txtProject, userId).getId());
study.setStartyear(String.valueOf(startYear));
study.setEndyear(String.valueOf(String.valueOf(endYear)));
if (uploadTo.equals("database")) {
studyRawData.addStudyRawData(study,columnList.toArray(new String[columnList.size()]),dataList);
// studyRawData.addStudyRawDataByRawCsvList(study,
// new CSVReader(new FileReader(tempFile)).readAll());
// GermplasmManagerImpl germplasmManager = new GermplasmManagerImpl();
// StudyGermplasmManagerImpl studyGermplasmManager = new StudyGermplasmManagerImpl();
//
// StudyRawDataManagerImpl studyRawDataManagerImpl = new StudyRawDataManagerImpl(isRawData);
// ArrayList<StudyRawDataByDataColumn> list = (ArrayList<StudyRawDataByDataColumn>) studyRawDataManagerImpl
// .getStudyRawDataColumn(study.getId(), "GName");
// for (StudyRawDataByDataColumn s : list) {
// // System.out.println(s.getStudyid()+
// // " "+s.getDatacolumn()+
// // " "+ s.getDatavalue());
//
// if (!germplasmManager.isGermplasmExisting(s
// .getDatavalue())) {
// StudyGermplasm studyGermplasmData = new StudyGermplasm();
// studyGermplasmData.setGermplasmname(s
// .getDatavalue());
// studyGermplasmData.setStudyid(study.getId());
// studyGermplasmManager
// .addStudyGermplasm(studyGermplasmData);
// }
}
else{
fileMan.createNewFileFromUpload(1, study.getId(), dataFileName, tempFile, (isRaw) ? "rd":"dd");
}
for(GenotypeFileModel genoFile : genotypeFileList){
fileMan.createNewFileFromUpload(1, study.getId(), genoFile.name, genoFile.tempFile,"gd");
}
this.setStudyID(study.getId());
this.isRaw = isRawData;
System.out.println("Timer ends in: " + timer.end());
return true;
}
|
diff --git a/src/main/java/com/gitblit/wicket/pages/DashboardPage.java b/src/main/java/com/gitblit/wicket/pages/DashboardPage.java
index 66bbf734..5d838391 100644
--- a/src/main/java/com/gitblit/wicket/pages/DashboardPage.java
+++ b/src/main/java/com/gitblit/wicket/pages/DashboardPage.java
@@ -1,441 +1,441 @@
/*
* Copyright 2013 gitblit.com.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gitblit.wicket.pages;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.TreeSet;
import org.apache.wicket.Component;
import org.apache.wicket.PageParameters;
import org.apache.wicket.behavior.HeaderContributor;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Fragment;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Repository;
import com.gitblit.GitBlit;
import com.gitblit.Keys;
import com.gitblit.models.DailyLogEntry;
import com.gitblit.models.Metric;
import com.gitblit.models.PushLogEntry;
import com.gitblit.models.RepositoryCommit;
import com.gitblit.models.RepositoryModel;
import com.gitblit.models.UserModel;
import com.gitblit.utils.ArrayUtils;
import com.gitblit.utils.MarkdownUtils;
import com.gitblit.utils.PushLogUtils;
import com.gitblit.utils.StringUtils;
import com.gitblit.wicket.GitBlitWebApp;
import com.gitblit.wicket.GitBlitWebSession;
import com.gitblit.wicket.PageRegistration;
import com.gitblit.wicket.PageRegistration.DropDownMenuItem;
import com.gitblit.wicket.PageRegistration.DropDownMenuRegistration;
import com.gitblit.wicket.WicketUtils;
import com.gitblit.wicket.charting.GoogleChart;
import com.gitblit.wicket.charting.GoogleCharts;
import com.gitblit.wicket.charting.GooglePieChart;
import com.gitblit.wicket.ng.NgController;
import com.gitblit.wicket.panels.LinkPanel;
import com.gitblit.wicket.panels.PushesPanel;
public class DashboardPage extends RootPage {
public DashboardPage() {
super();
setup(null);
}
public DashboardPage(PageParameters params) {
super(params);
setup(params);
}
@Override
protected boolean reusePageParameters() {
return true;
}
private void setup(PageParameters params) {
setupPage("", "");
// check to see if we should display a login message
boolean authenticateView = GitBlit.getBoolean(Keys.web.authenticateViewPages, true);
if (authenticateView && !GitBlitWebSession.get().isLoggedIn()) {
String messageSource = GitBlit.getString(Keys.web.loginMessage, "gitblit");
String message = readMarkdown(messageSource, "login.mkd");
Component repositoriesMessage = new Label("repositoriesMessage", message);
add(repositoriesMessage.setEscapeModelStrings(false));
add(new Label("digests"));
add(new Label("active").setVisible(false));
add(new Label("starred").setVisible(false));
add(new Label("owned").setVisible(false));
return;
}
// Load the markdown welcome message
String messageSource = GitBlit.getString(Keys.web.repositoriesMessage, "gitblit");
String message = readMarkdown(messageSource, "welcome.mkd");
Component repositoriesMessage = new Label("repositoriesMessage", message)
.setEscapeModelStrings(false).setVisible(message.length() > 0);
add(repositoriesMessage);
UserModel user = GitBlitWebSession.get().getUser();
if (user == null) {
user = UserModel.ANONYMOUS;
}
Comparator<RepositoryModel> lastUpdateSort = new Comparator<RepositoryModel>() {
@Override
public int compare(RepositoryModel o1, RepositoryModel o2) {
return o2.lastChange.compareTo(o1.lastChange);
}
};
// parameters
int daysBack = params == null ? 0 : WicketUtils.getDaysBack(params);
if (daysBack < 1) {
- daysBack = 14;
+ daysBack = 7;
}
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, -1*daysBack);
Date minimumDate = c.getTime();
TimeZone timezone = getTimeZone();
// build repo lists
List<RepositoryModel> starred = new ArrayList<RepositoryModel>();
List<RepositoryModel> owned = new ArrayList<RepositoryModel>();
List<RepositoryModel> active = new ArrayList<RepositoryModel>();
- for (RepositoryModel model : GitBlit.self().getRepositoryModels(user)) {
+ for (RepositoryModel model : getRepositoryModels()) {
if (model.isUsersPersonalRepository(user.username) || model.isOwner(user.username)) {
owned.add(model);
}
if (user.getPreferences().isStarredRepository(model.name)) {
starred.add(model);
}
if (model.isShowActivity() && model.lastChange.after(minimumDate)) {
active.add(model);
}
}
Collections.sort(owned, lastUpdateSort);
Collections.sort(starred, lastUpdateSort);
Collections.sort(active, lastUpdateSort);
Set<RepositoryModel> feedSources = new HashSet<RepositoryModel>();
feedSources.addAll(starred);
if (feedSources.isEmpty()) {
feedSources.addAll(active);
}
// create daily commit digest feed
List<PushLogEntry> pushes = new ArrayList<PushLogEntry>();
for (RepositoryModel model : feedSources) {
Repository repository = GitBlit.self().getRepository(model.name);
List<DailyLogEntry> entries = PushLogUtils.getDailyLogByRef(model.name, repository, minimumDate, timezone);
pushes.addAll(entries);
repository.close();
}
if (pushes.size() == 0) {
// quiet or no starred repositories
if (feedSources.size() == 0) {
if (UserModel.ANONYMOUS.equals(user)) {
add(new Label("digests", getString("gb.noActivity")));
} else {
add(new LinkPanel("digests", null, getString("gb.findSomeRepositories"), RepositoriesPage.class));
}
} else {
add(new Label("digests", getString("gb.noActivity")));
}
} else {
// show daily commit digest feed
Collections.sort(pushes);
add(new PushesPanel("digests", pushes));
}
// add the nifty charts
if (!ArrayUtils.isEmpty(pushes)) {
// aggregate author exclusions
Set<String> authorExclusions = new TreeSet<String>();
for (String author : GitBlit.getStrings(Keys.web.metricAuthorExclusions)) {
authorExclusions.add(author.toLowerCase());
}
for (RepositoryModel model : feedSources) {
if (!ArrayUtils.isEmpty(model.metricAuthorExclusions)) {
for (String author : model.metricAuthorExclusions) {
authorExclusions.add(author.toLowerCase());
}
}
}
GoogleCharts charts = createCharts(pushes, authorExclusions);
add(new HeaderContributor(charts));
}
// active repository list
if (starred.isEmpty()) {
Fragment activeView = createNgList("active", "activeListFragment", "activeCtrl", active);
add(activeView);
} else {
add(new Label("active").setVisible(false));
}
// starred repository list
if (ArrayUtils.isEmpty(starred)) {
add(new Label("starred").setVisible(false));
} else {
Fragment starredView = createNgList("starred", "starredListFragment", "starredCtrl", starred);
add(starredView);
}
// owned repository list
if (ArrayUtils.isEmpty(owned)) {
add(new Label("owned").setVisible(false));
} else {
Fragment ownedView = createNgList("owned", "ownedListFragment", "ownedCtrl", owned);
if (user.canCreate) {
// create button
ownedView.add(new LinkPanel("create", "btn btn-mini", getString("gb.newRepository"), EditRepositoryPage.class));
} else {
// no button
ownedView.add(new Label("create").setVisible(false));
}
add(ownedView);
}
}
protected Fragment createNgList(String wicketId, String fragmentId, String ngController, List<RepositoryModel> repositories) {
String format = GitBlit.getString(Keys.web.datestampShortFormat, "MM/dd/yy");
final DateFormat df = new SimpleDateFormat(format);
df.setTimeZone(getTimeZone());
Fragment fragment = new Fragment(wicketId, fragmentId, this);
List<RepoListItem> list = new ArrayList<RepoListItem>();
for (RepositoryModel repo : repositories) {
String name = StringUtils.stripDotGit(repo.name);
String path = "";
if (name.indexOf('/') > -1) {
path = name.substring(0, name.lastIndexOf('/') + 1);
name = name.substring(name.lastIndexOf('/') + 1);
}
RepoListItem item = new RepoListItem();
item.n = name;
item.p = path;
item.r = repo.name;
item.s = GitBlit.self().getStarCount(repo);
item.t = getTimeUtils().timeAgo(repo.lastChange);
item.d = df.format(repo.lastChange);
item.c = StringUtils.getColor(StringUtils.stripDotGit(repo.name));
item.wc = repo.isBare ? 0 : 1;
list.add(item);
}
// inject an AngularJS controller with static data
NgController ctrl = new NgController(ngController);
ctrl.addVariable(wicketId, list);
add(new HeaderContributor(ctrl));
return fragment;
}
@Override
protected void addDropDownMenus(List<PageRegistration> pages) {
PageParameters params = getPageParameters();
DropDownMenuRegistration menu = new DropDownMenuRegistration("gb.filters",
GitBlitWebApp.HOME_PAGE_CLASS);
// preserve time filter option on repository choices
menu.menuItems.addAll(getRepositoryFilterItems(params));
// preserve repository filter option on time choices
menu.menuItems.addAll(getTimeFilterItems(params));
if (menu.menuItems.size() > 0) {
// Reset Filter
menu.menuItems.add(new DropDownMenuItem(getString("gb.reset"), null, null));
}
pages.add(menu);
}
private String readMarkdown(String messageSource, String resource) {
String message = "";
if (messageSource.equalsIgnoreCase("gitblit")) {
// Read default message
message = readDefaultMarkdown(resource);
} else {
// Read user-supplied message
if (!StringUtils.isEmpty(messageSource)) {
File file = GitBlit.getFileOrFolder(messageSource);
if (file.exists()) {
try {
FileInputStream fis = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(fis,
Constants.CHARACTER_ENCODING);
message = MarkdownUtils.transformMarkdown(reader);
reader.close();
} catch (Throwable t) {
message = getString("gb.failedToRead") + " " + file;
warn(message, t);
}
} else {
message = messageSource + " " + getString("gb.isNotValidFile");
}
}
}
return message;
}
private String readDefaultMarkdown(String file) {
String base = file.substring(0, file.lastIndexOf('.'));
String ext = file.substring(file.lastIndexOf('.'));
String lc = getLanguageCode();
String cc = getCountryCode();
// try to read file_en-us.ext, file_en.ext, file.ext
List<String> files = new ArrayList<String>();
if (!StringUtils.isEmpty(lc)) {
if (!StringUtils.isEmpty(cc)) {
files.add(base + "_" + lc + "-" + cc + ext);
files.add(base + "_" + lc + "_" + cc + ext);
}
files.add(base + "_" + lc + ext);
}
files.add(file);
for (String name : files) {
String message;
InputStreamReader reader = null;
try {
InputStream is = getClass().getResourceAsStream("/" + name);
if (is == null) {
continue;
}
reader = new InputStreamReader(is, Constants.CHARACTER_ENCODING);
message = MarkdownUtils.transformMarkdown(reader);
reader.close();
return message;
} catch (Throwable t) {
message = MessageFormat.format(getString("gb.failedToReadMessage"), file);
error(message, t, false);
return message;
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
}
}
}
}
return MessageFormat.format(getString("gb.failedToReadMessage"), file);
}
/**
* Creates the daily activity line chart, the active repositories pie chart,
* and the active authors pie chart
*
* @param recentPushes
* @return
*/
private GoogleCharts createCharts(List<PushLogEntry> recentPushes, Set<String> authorExclusions) {
// activity metrics
Map<String, Metric> repositoryMetrics = new HashMap<String, Metric>();
Map<String, Metric> authorMetrics = new HashMap<String, Metric>();
// aggregate repository and author metrics
for (PushLogEntry push : recentPushes) {
// aggregate repository metrics
String repository = StringUtils.stripDotGit(push.repository);
if (!repositoryMetrics.containsKey(repository)) {
repositoryMetrics.put(repository, new Metric(repository));
}
repositoryMetrics.get(repository).count += 1;
for (RepositoryCommit commit : push.getCommits()) {
String author = StringUtils.removeNewlines(commit.getAuthorIdent().getName());
String authorName = author.toLowerCase();
String authorEmail = StringUtils.removeNewlines(commit.getAuthorIdent().getEmailAddress()).toLowerCase();
if (!authorExclusions.contains(authorName) && !authorExclusions.contains(authorEmail)) {
if (!authorMetrics.containsKey(author)) {
authorMetrics.put(author, new Metric(author));
}
authorMetrics.get(author).count += 1;
}
}
}
// build google charts
GoogleCharts charts = new GoogleCharts();
// active repositories pie chart
GoogleChart chart = new GooglePieChart("chartRepositories", getString("gb.activeRepositories"),
getString("gb.repository"), getString("gb.commits"));
for (Metric metric : repositoryMetrics.values()) {
chart.addValue(metric.name, metric.count);
}
chart.setShowLegend(false);
charts.addChart(chart);
// active authors pie chart
chart = new GooglePieChart("chartAuthors", getString("gb.activeAuthors"),
getString("gb.author"), getString("gb.commits"));
for (Metric metric : authorMetrics.values()) {
chart.addValue(metric.name, metric.count);
}
chart.setShowLegend(false);
charts.addChart(chart);
return charts;
}
class RepoListItem implements Serializable {
private static final long serialVersionUID = 1L;
String r; // repository
String n; // name
String p; // project/path
String t; // time ago
String d; // last updated
long s; // stars
String c; // html color
int wc; // working copy, 1 = true
}
}
| false | true | private void setup(PageParameters params) {
setupPage("", "");
// check to see if we should display a login message
boolean authenticateView = GitBlit.getBoolean(Keys.web.authenticateViewPages, true);
if (authenticateView && !GitBlitWebSession.get().isLoggedIn()) {
String messageSource = GitBlit.getString(Keys.web.loginMessage, "gitblit");
String message = readMarkdown(messageSource, "login.mkd");
Component repositoriesMessage = new Label("repositoriesMessage", message);
add(repositoriesMessage.setEscapeModelStrings(false));
add(new Label("digests"));
add(new Label("active").setVisible(false));
add(new Label("starred").setVisible(false));
add(new Label("owned").setVisible(false));
return;
}
// Load the markdown welcome message
String messageSource = GitBlit.getString(Keys.web.repositoriesMessage, "gitblit");
String message = readMarkdown(messageSource, "welcome.mkd");
Component repositoriesMessage = new Label("repositoriesMessage", message)
.setEscapeModelStrings(false).setVisible(message.length() > 0);
add(repositoriesMessage);
UserModel user = GitBlitWebSession.get().getUser();
if (user == null) {
user = UserModel.ANONYMOUS;
}
Comparator<RepositoryModel> lastUpdateSort = new Comparator<RepositoryModel>() {
@Override
public int compare(RepositoryModel o1, RepositoryModel o2) {
return o2.lastChange.compareTo(o1.lastChange);
}
};
// parameters
int daysBack = params == null ? 0 : WicketUtils.getDaysBack(params);
if (daysBack < 1) {
daysBack = 14;
}
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, -1*daysBack);
Date minimumDate = c.getTime();
TimeZone timezone = getTimeZone();
// build repo lists
List<RepositoryModel> starred = new ArrayList<RepositoryModel>();
List<RepositoryModel> owned = new ArrayList<RepositoryModel>();
List<RepositoryModel> active = new ArrayList<RepositoryModel>();
for (RepositoryModel model : GitBlit.self().getRepositoryModels(user)) {
if (model.isUsersPersonalRepository(user.username) || model.isOwner(user.username)) {
owned.add(model);
}
if (user.getPreferences().isStarredRepository(model.name)) {
starred.add(model);
}
if (model.isShowActivity() && model.lastChange.after(minimumDate)) {
active.add(model);
}
}
Collections.sort(owned, lastUpdateSort);
Collections.sort(starred, lastUpdateSort);
Collections.sort(active, lastUpdateSort);
Set<RepositoryModel> feedSources = new HashSet<RepositoryModel>();
feedSources.addAll(starred);
if (feedSources.isEmpty()) {
feedSources.addAll(active);
}
// create daily commit digest feed
List<PushLogEntry> pushes = new ArrayList<PushLogEntry>();
for (RepositoryModel model : feedSources) {
Repository repository = GitBlit.self().getRepository(model.name);
List<DailyLogEntry> entries = PushLogUtils.getDailyLogByRef(model.name, repository, minimumDate, timezone);
pushes.addAll(entries);
repository.close();
}
if (pushes.size() == 0) {
// quiet or no starred repositories
if (feedSources.size() == 0) {
if (UserModel.ANONYMOUS.equals(user)) {
add(new Label("digests", getString("gb.noActivity")));
} else {
add(new LinkPanel("digests", null, getString("gb.findSomeRepositories"), RepositoriesPage.class));
}
} else {
add(new Label("digests", getString("gb.noActivity")));
}
} else {
// show daily commit digest feed
Collections.sort(pushes);
add(new PushesPanel("digests", pushes));
}
// add the nifty charts
if (!ArrayUtils.isEmpty(pushes)) {
// aggregate author exclusions
Set<String> authorExclusions = new TreeSet<String>();
for (String author : GitBlit.getStrings(Keys.web.metricAuthorExclusions)) {
authorExclusions.add(author.toLowerCase());
}
for (RepositoryModel model : feedSources) {
if (!ArrayUtils.isEmpty(model.metricAuthorExclusions)) {
for (String author : model.metricAuthorExclusions) {
authorExclusions.add(author.toLowerCase());
}
}
}
GoogleCharts charts = createCharts(pushes, authorExclusions);
add(new HeaderContributor(charts));
}
// active repository list
if (starred.isEmpty()) {
Fragment activeView = createNgList("active", "activeListFragment", "activeCtrl", active);
add(activeView);
} else {
add(new Label("active").setVisible(false));
}
// starred repository list
if (ArrayUtils.isEmpty(starred)) {
add(new Label("starred").setVisible(false));
} else {
Fragment starredView = createNgList("starred", "starredListFragment", "starredCtrl", starred);
add(starredView);
}
// owned repository list
if (ArrayUtils.isEmpty(owned)) {
add(new Label("owned").setVisible(false));
} else {
Fragment ownedView = createNgList("owned", "ownedListFragment", "ownedCtrl", owned);
if (user.canCreate) {
// create button
ownedView.add(new LinkPanel("create", "btn btn-mini", getString("gb.newRepository"), EditRepositoryPage.class));
} else {
// no button
ownedView.add(new Label("create").setVisible(false));
}
add(ownedView);
}
}
| private void setup(PageParameters params) {
setupPage("", "");
// check to see if we should display a login message
boolean authenticateView = GitBlit.getBoolean(Keys.web.authenticateViewPages, true);
if (authenticateView && !GitBlitWebSession.get().isLoggedIn()) {
String messageSource = GitBlit.getString(Keys.web.loginMessage, "gitblit");
String message = readMarkdown(messageSource, "login.mkd");
Component repositoriesMessage = new Label("repositoriesMessage", message);
add(repositoriesMessage.setEscapeModelStrings(false));
add(new Label("digests"));
add(new Label("active").setVisible(false));
add(new Label("starred").setVisible(false));
add(new Label("owned").setVisible(false));
return;
}
// Load the markdown welcome message
String messageSource = GitBlit.getString(Keys.web.repositoriesMessage, "gitblit");
String message = readMarkdown(messageSource, "welcome.mkd");
Component repositoriesMessage = new Label("repositoriesMessage", message)
.setEscapeModelStrings(false).setVisible(message.length() > 0);
add(repositoriesMessage);
UserModel user = GitBlitWebSession.get().getUser();
if (user == null) {
user = UserModel.ANONYMOUS;
}
Comparator<RepositoryModel> lastUpdateSort = new Comparator<RepositoryModel>() {
@Override
public int compare(RepositoryModel o1, RepositoryModel o2) {
return o2.lastChange.compareTo(o1.lastChange);
}
};
// parameters
int daysBack = params == null ? 0 : WicketUtils.getDaysBack(params);
if (daysBack < 1) {
daysBack = 7;
}
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, -1*daysBack);
Date minimumDate = c.getTime();
TimeZone timezone = getTimeZone();
// build repo lists
List<RepositoryModel> starred = new ArrayList<RepositoryModel>();
List<RepositoryModel> owned = new ArrayList<RepositoryModel>();
List<RepositoryModel> active = new ArrayList<RepositoryModel>();
for (RepositoryModel model : getRepositoryModels()) {
if (model.isUsersPersonalRepository(user.username) || model.isOwner(user.username)) {
owned.add(model);
}
if (user.getPreferences().isStarredRepository(model.name)) {
starred.add(model);
}
if (model.isShowActivity() && model.lastChange.after(minimumDate)) {
active.add(model);
}
}
Collections.sort(owned, lastUpdateSort);
Collections.sort(starred, lastUpdateSort);
Collections.sort(active, lastUpdateSort);
Set<RepositoryModel> feedSources = new HashSet<RepositoryModel>();
feedSources.addAll(starred);
if (feedSources.isEmpty()) {
feedSources.addAll(active);
}
// create daily commit digest feed
List<PushLogEntry> pushes = new ArrayList<PushLogEntry>();
for (RepositoryModel model : feedSources) {
Repository repository = GitBlit.self().getRepository(model.name);
List<DailyLogEntry> entries = PushLogUtils.getDailyLogByRef(model.name, repository, minimumDate, timezone);
pushes.addAll(entries);
repository.close();
}
if (pushes.size() == 0) {
// quiet or no starred repositories
if (feedSources.size() == 0) {
if (UserModel.ANONYMOUS.equals(user)) {
add(new Label("digests", getString("gb.noActivity")));
} else {
add(new LinkPanel("digests", null, getString("gb.findSomeRepositories"), RepositoriesPage.class));
}
} else {
add(new Label("digests", getString("gb.noActivity")));
}
} else {
// show daily commit digest feed
Collections.sort(pushes);
add(new PushesPanel("digests", pushes));
}
// add the nifty charts
if (!ArrayUtils.isEmpty(pushes)) {
// aggregate author exclusions
Set<String> authorExclusions = new TreeSet<String>();
for (String author : GitBlit.getStrings(Keys.web.metricAuthorExclusions)) {
authorExclusions.add(author.toLowerCase());
}
for (RepositoryModel model : feedSources) {
if (!ArrayUtils.isEmpty(model.metricAuthorExclusions)) {
for (String author : model.metricAuthorExclusions) {
authorExclusions.add(author.toLowerCase());
}
}
}
GoogleCharts charts = createCharts(pushes, authorExclusions);
add(new HeaderContributor(charts));
}
// active repository list
if (starred.isEmpty()) {
Fragment activeView = createNgList("active", "activeListFragment", "activeCtrl", active);
add(activeView);
} else {
add(new Label("active").setVisible(false));
}
// starred repository list
if (ArrayUtils.isEmpty(starred)) {
add(new Label("starred").setVisible(false));
} else {
Fragment starredView = createNgList("starred", "starredListFragment", "starredCtrl", starred);
add(starredView);
}
// owned repository list
if (ArrayUtils.isEmpty(owned)) {
add(new Label("owned").setVisible(false));
} else {
Fragment ownedView = createNgList("owned", "ownedListFragment", "ownedCtrl", owned);
if (user.canCreate) {
// create button
ownedView.add(new LinkPanel("create", "btn btn-mini", getString("gb.newRepository"), EditRepositoryPage.class));
} else {
// no button
ownedView.add(new Label("create").setVisible(false));
}
add(ownedView);
}
}
|
diff --git a/CheMet/CheMet-Visualisation/src/main/java/uk/ac/ebi/chemet/render/components/MetaboliteMatchIndication.java b/CheMet/CheMet-Visualisation/src/main/java/uk/ac/ebi/chemet/render/components/MetaboliteMatchIndication.java
index 7abeeb05..66e06cf5 100644
--- a/CheMet/CheMet-Visualisation/src/main/java/uk/ac/ebi/chemet/render/components/MetaboliteMatchIndication.java
+++ b/CheMet/CheMet-Visualisation/src/main/java/uk/ac/ebi/chemet/render/components/MetaboliteMatchIndication.java
@@ -1,169 +1,169 @@
/**
* MetaboliteMatchIndication.java
*
* 2012.02.02
*
* This file is part of the CheMet library
*
* The CheMet library is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CheMet 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 Lesser General Public License
* along with CheMet. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.ac.ebi.chemet.render.components;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Box;
import javax.swing.JComponent;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.openscience.cdk.Element;
import org.openscience.cdk.Isotope;
import org.openscience.cdk.interfaces.IMolecularFormula;
import org.openscience.cdk.tools.manipulator.MolecularFormulaManipulator;
import uk.ac.ebi.annotation.chemical.MolecularFormula;
import uk.ac.ebi.caf.utility.TextUtility;
import uk.ac.ebi.interfaces.entities.Metabolite;
/**
*
* MetaboliteMatchIndication 2012.02.02
* @version $Rev$ : Last Changed $Date$
* @author johnmay
* @author $Author$ (this version)
*
* Class description
*
*/
public class MetaboliteMatchIndication {
private static final Logger LOGGER = Logger.getLogger(MetaboliteMatchIndication.class);
private JComponent component;
private Metabolite query;
private Metabolite subject;
private MatchIndication name = new MatchIndication(300, 300);
private MatchIndication formula = new MatchIndication(300, 300);
private MatchIndication charge = new MatchIndication(300, 300);
public MetaboliteMatchIndication() {
component = Box.createVerticalBox();
component.add(name.getComponent());
component.add(formula.getComponent());
component.add(charge.getComponent());
}
public JComponent getComponent() {
return component;
}
public void setQueryName(String string) {
name.setLeft(string);
}
public void setQuery(Metabolite query) {
this.query = query;
name.setLeft(query.getName());
charge.setLeft(query.getCharge() == null ? "N/A" : query.getCharge().toString());
}
public void setSubject(Metabolite subject) {
this.subject = subject;
name.setRight(subject.getName());
Integer nameDiff = StringUtils.getLevenshteinDistance(query.getName().toLowerCase(), subject.getName().toLowerCase());
name.setDifference(nameDiff.toString());
name.setQuality(nameDiff <= 2 ? MatchIndication.Quality.Good
: nameDiff <= 5 ? MatchIndication.Quality.Okay
: MatchIndication.Quality.Bad);
double queryCharge = query.getCharge() == null ? 0 : query.getCharge();
double subjectCharge = subject.getCharge() == null ? 0 : subject.getCharge();
charge.setRight(Double.toString(subjectCharge));
double chargeDiff = Math.abs(queryCharge - subjectCharge);
charge.setQuality(chargeDiff < 1 ? MatchIndication.Quality.Good
: chargeDiff < 2 ? MatchIndication.Quality.Okay
: MatchIndication.Quality.Bad);
setFormulaQuality();
}
public void setFormulaQuality() {
formula.setQuality(MatchIndication.Quality.Bad);
List<MolecularFormula> queryMfs = new ArrayList(query.getAnnotationsExtending(MolecularFormula.class));
- List<MolecularFormula> subjectMfs = new ArrayList(query.getAnnotationsExtending(MolecularFormula.class));
+ List<MolecularFormula> subjectMfs = new ArrayList(subject.getAnnotationsExtending(MolecularFormula.class));
formula.setLeft("N/A");
formula.setRight("N/A");
if (!queryMfs.isEmpty()) {
formula.setLeft(TextUtility.html(queryMfs.get(0).toHTML()));
}
if (!subjectMfs.isEmpty()) {
formula.setRight(TextUtility.html(subjectMfs.get(0).toHTML()));
}
Isotope hydrogen = new Isotope(new Element("H"));
for (MolecularFormula queryMf : queryMfs) {
for (MolecularFormula subjectMf : subjectMfs) {
if (MolecularFormulaManipulator.compare(queryMf.getFormula(), subjectMf.getFormula())) {
formula.setQuality(MatchIndication.Quality.Good);
formula.setLeft(TextUtility.html(queryMf.toHTML()));
formula.setRight(TextUtility.html(subjectMf.toHTML()));
return;
} else {
IMolecularFormula mf1 = queryMf.getFormula();
IMolecularFormula mf2 = subjectMf.getFormula();
int mf1hc = MolecularFormulaManipulator.getElementCount(mf1, hydrogen);
int mf2hc = MolecularFormulaManipulator.getElementCount(mf2, hydrogen);
mf1 = MolecularFormulaManipulator.removeElement(mf1, hydrogen);
mf2 = MolecularFormulaManipulator.removeElement(mf2, hydrogen);
if (MolecularFormulaManipulator.compare(mf1, mf2)) {
formula.setQuality(MatchIndication.Quality.Okay);
formula.setLeft(TextUtility.html(queryMf.toHTML()));
formula.setRight(TextUtility.html(subjectMf.toHTML()));
}
mf1.addIsotope(hydrogen, mf1hc);
mf2.addIsotope(hydrogen, mf2hc);
}
}
}
}
}
| true | true | public void setFormulaQuality() {
formula.setQuality(MatchIndication.Quality.Bad);
List<MolecularFormula> queryMfs = new ArrayList(query.getAnnotationsExtending(MolecularFormula.class));
List<MolecularFormula> subjectMfs = new ArrayList(query.getAnnotationsExtending(MolecularFormula.class));
formula.setLeft("N/A");
formula.setRight("N/A");
if (!queryMfs.isEmpty()) {
formula.setLeft(TextUtility.html(queryMfs.get(0).toHTML()));
}
if (!subjectMfs.isEmpty()) {
formula.setRight(TextUtility.html(subjectMfs.get(0).toHTML()));
}
Isotope hydrogen = new Isotope(new Element("H"));
for (MolecularFormula queryMf : queryMfs) {
for (MolecularFormula subjectMf : subjectMfs) {
if (MolecularFormulaManipulator.compare(queryMf.getFormula(), subjectMf.getFormula())) {
formula.setQuality(MatchIndication.Quality.Good);
formula.setLeft(TextUtility.html(queryMf.toHTML()));
formula.setRight(TextUtility.html(subjectMf.toHTML()));
return;
} else {
IMolecularFormula mf1 = queryMf.getFormula();
IMolecularFormula mf2 = subjectMf.getFormula();
int mf1hc = MolecularFormulaManipulator.getElementCount(mf1, hydrogen);
int mf2hc = MolecularFormulaManipulator.getElementCount(mf2, hydrogen);
mf1 = MolecularFormulaManipulator.removeElement(mf1, hydrogen);
mf2 = MolecularFormulaManipulator.removeElement(mf2, hydrogen);
if (MolecularFormulaManipulator.compare(mf1, mf2)) {
formula.setQuality(MatchIndication.Quality.Okay);
formula.setLeft(TextUtility.html(queryMf.toHTML()));
formula.setRight(TextUtility.html(subjectMf.toHTML()));
}
mf1.addIsotope(hydrogen, mf1hc);
mf2.addIsotope(hydrogen, mf2hc);
}
}
}
}
| public void setFormulaQuality() {
formula.setQuality(MatchIndication.Quality.Bad);
List<MolecularFormula> queryMfs = new ArrayList(query.getAnnotationsExtending(MolecularFormula.class));
List<MolecularFormula> subjectMfs = new ArrayList(subject.getAnnotationsExtending(MolecularFormula.class));
formula.setLeft("N/A");
formula.setRight("N/A");
if (!queryMfs.isEmpty()) {
formula.setLeft(TextUtility.html(queryMfs.get(0).toHTML()));
}
if (!subjectMfs.isEmpty()) {
formula.setRight(TextUtility.html(subjectMfs.get(0).toHTML()));
}
Isotope hydrogen = new Isotope(new Element("H"));
for (MolecularFormula queryMf : queryMfs) {
for (MolecularFormula subjectMf : subjectMfs) {
if (MolecularFormulaManipulator.compare(queryMf.getFormula(), subjectMf.getFormula())) {
formula.setQuality(MatchIndication.Quality.Good);
formula.setLeft(TextUtility.html(queryMf.toHTML()));
formula.setRight(TextUtility.html(subjectMf.toHTML()));
return;
} else {
IMolecularFormula mf1 = queryMf.getFormula();
IMolecularFormula mf2 = subjectMf.getFormula();
int mf1hc = MolecularFormulaManipulator.getElementCount(mf1, hydrogen);
int mf2hc = MolecularFormulaManipulator.getElementCount(mf2, hydrogen);
mf1 = MolecularFormulaManipulator.removeElement(mf1, hydrogen);
mf2 = MolecularFormulaManipulator.removeElement(mf2, hydrogen);
if (MolecularFormulaManipulator.compare(mf1, mf2)) {
formula.setQuality(MatchIndication.Quality.Okay);
formula.setLeft(TextUtility.html(queryMf.toHTML()));
formula.setRight(TextUtility.html(subjectMf.toHTML()));
}
mf1.addIsotope(hydrogen, mf1hc);
mf2.addIsotope(hydrogen, mf2hc);
}
}
}
}
|
diff --git a/src/gnu/io/RXTXCommDriver.java b/src/gnu/io/RXTXCommDriver.java
index 3615719..fa39cdc 100644
--- a/src/gnu/io/RXTXCommDriver.java
+++ b/src/gnu/io/RXTXCommDriver.java
@@ -1,743 +1,755 @@
/*-------------------------------------------------------------------------
| A wrapper to convert RXTX into Linux Java Comm
| Copyright 1998 Kevin Hester, [email protected]
| Copyright 2000-2002 Trent Jarvi, [email protected]
|
| This library is free software; you can redistribute it and/or
| modify it under the terms of the GNU Library General Public
| License as published by the Free Software Foundation; either
| version 2 of the License, or (at your option) any later version.
|
| This library is distributed in the hope that it will be useful,
| but WITHOUT ANY WARRANTY; without even the implied warranty of
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
| Library General Public License for more details.
|
| You should have received a copy of the GNU Library General Public
| License along with this library; if not, write to the Free
| Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--------------------------------------------------------------------------*/
/* Martin Pool <[email protected]> added support for explicitly-specified
* lists of ports, October 2000. */
/* Joseph Goldstone <[email protected]> reorganized to support registered ports,
* known ports, and scanned ports, July 2001 */
package gnu.io;
import java.util.*;
import java.io.*;
import java.util.StringTokenizer;
/**
This is the JavaComm for Linux driver.
*/
public class RXTXCommDriver implements CommDriver
{
private final static boolean debug = false;
static
{
if(debug ) System.out.println("RXTXCommDriver {}");
System.loadLibrary( "rxtxSerial" );
/*
Perform a crude check to make sure people don't mix
versions of the Jar and native lib
Mixing the libs can create a nightmare.
It could be possible to move this over to RXTXVersion
but All we want to do is warn people when first loading
the Library.
*/
String JarVersion = RXTXVersion.getVersion();
String LibVersion = nativeGetVersion();
if ( ! JarVersion.equals( LibVersion ) )
{
System.out.println( "WARNING: RXTX Version mismatch\n\tJar version = " + JarVersion + "\n\tnative lib Version = " + LibVersion );
}
else if ( debug )
{
System.out.println( "RXTXCommDriver:\n\tJar version = " + JarVersion + "\n\tnative lib Version = " + LibVersion );
}
}
/** Get the Serial port prefixes for the running OS */
private String deviceDirectory;
private String osName;
private static native String nativeGetVersion();
private native boolean registerKnownPorts(int PortType);
private native boolean isPortPrefixValid(String dev);
private native boolean testRead(String dev, int type);
private native String getDeviceDirectory();
private final String[] getValidPortPrefixes(String CandidatePortPrefixes[])
{
/*
256 is the number of prefixes ( COM, cua, ttyS, ...) not
the number of devices (ttyS0, ttyS1, ttyS2, ...)
On a Linux system there are about 400 prefixes in
deviceDirectory.
registerScannedPorts() assigns CandidatePortPrefixes to
something less than 50 prefixes.
Trent
*/
String ValidPortPrefixes[]=new String [256];
if (debug)
System.out.println("\nRXTXCommDriver:getValidPortPrefixes()");
if(CandidatePortPrefixes==null)
{
if (debug)
System.out.println("\nRXTXCommDriver:getValidPortPrefixes() No ports prefixes known for this System.\nPlease check the port prefixes listed for " + osName + " in RXTXCommDriver:registerScannedPorts()\n");
}
int i=0;
for(int j=0;j<CandidatePortPrefixes.length;j++){
if(isPortPrefixValid(CandidatePortPrefixes[j])) {
ValidPortPrefixes[i++]=
new String(CandidatePortPrefixes[j]);
}
}
String[] returnArray=new String[i];
System.arraycopy(ValidPortPrefixes, 0, returnArray, 0, i);
if(ValidPortPrefixes[0]==null)
{
if (debug)
{
System.out.println("\nRXTXCommDriver:getValidPortPrefixes() No ports matched the list assumed for this\nSystem in the directory " + deviceDirectory + ". Please check the ports listed for \"" + osName + "\" in\nRXTXCommDriver:registerScannedPorts()\nTried:");
for(int j=0;j<CandidatePortPrefixes.length;j++){
System.out.println("\t" +
CandidatePortPrefixes[i]);
}
}
}
else
{
if (debug)
System.out.println("\nRXTXCommDriver:getValidPortPrefixes()\nThe following port prefixes have been identified as valid on " + osName + ":\n");
/*
for(int j=0;j<returnArray.length;j++)
{
if (debug)
System.out.println("\t" + j + " " +
returnArray[j]);
}
*/
}
return returnArray;
}
/** handle solaris/sunos /dev/cua/a convention */
private void checkSolaris(String PortName, int PortType)
{
char p[] = { 91 };
for( p[0] =97 ;p[0] < 123; p[0]++ )
{
if (testRead(PortName.concat(new String(p)),PortType))
{
CommPortIdentifier.addPortName(
PortName.concat(new String(p)),
PortType,
this
);
}
}
}
private void registerValidPorts(
String CandidateDeviceNames[],
String ValidPortPrefixes[],
int PortType
) {
int i =0;
int p =0 ;
/* FIXME quick fix to get COM1-8 on windows working. The
Read test is not working properly and its crunch time...
if(osName.toLowerCase().indexOf("windows") != -1 )
{
for( i=0;i < CandidateDeviceNames.length;i++ )
{
CommPortIdentifier.addPortName( CandidateDeviceNames[i],
PortType, this );
}
return;
}
*/
if (debug)
{
System.out.println("Entering registerValidPorts()");
/* */
System.out.println(" Candidate devices:");
for (int dn=0;dn<CandidateDeviceNames.length;dn++)
System.out.println(" " +
CandidateDeviceNames[dn]);
System.out.println(" valid port prefixes:");
for (int pp=0;pp<ValidPortPrefixes.length;pp++)
System.out.println(" "+ValidPortPrefixes[pp]);
/* */
}
if ( CandidateDeviceNames!=null && ValidPortPrefixes!=null)
{
for( i = 0;i<CandidateDeviceNames.length; i++ ) {
for( p = 0;p<ValidPortPrefixes.length; p++ ) {
/* this determines:
* device file Valid ports
* /dev/ttyR[0-9]* != /dev/ttyS[0-9]*
* /dev/ttySI[0-9]* != /dev/ttyS[0-9]*
* /dev/ttyS[0-9]* == /dev/ttyS[0-9]*
* Otherwise we check some ports
* multiple times. Perl would rock
* here.
*
* If the above passes, we try to read
* from the port. If there is no err
* the port is added.
* Trent
*/
String V = ValidPortPrefixes[ p ];
int VL = V.length();
String C = CandidateDeviceNames[ i ];
if( C.length() < VL ) continue;
String CU =
C.substring(VL).toUpperCase();
String Cl =
C.substring(VL).toLowerCase();
if( !( C.regionMatches(0, V, 0, VL ) &&
CU.equals( Cl ) ) )
{
continue;
}
String PortName =
new String(deviceDirectory +
C );
if (debug)
{
System.out.println( C +
" " + V );
System.out.println( CU +
" " + Cl );
}
if( osName.equals("Solaris") ||
osName.equals("SunOS"))
checkSolaris(PortName,PortType);
else if (testRead(PortName, PortType))
{
CommPortIdentifier.addPortName(
PortName,
PortType,
this
);
}
}
}
}
if (debug)
System.out.println("Leaving registerValidPorts()");
}
/*
* initialize() will be called by the CommPortIdentifier's static
* initializer. The responsibility of this method is:
* 1) Ensure that that the hardware is present.
* 2) Load any required native libraries.
* 3) Register the port names with the CommPortIdentifier.
*
* <p>From the NullDriver.java CommAPI sample.
*
* added printerport stuff
* Holger Lehmann
* July 12, 1999
* IBM
* Added ttyM for Moxa boards
* Removed obsolete device cuaa
* Peter Bennett
* January 02, 2000
* Bencom
*/
/**
* Determine the OS and where the OS has the devices located
*/
public void initialize()
{
if (debug) System.out.println("RXTXCommDriver:initialize()");
osName=System.getProperty("os.name");
deviceDirectory=getDeviceDirectory();
/*
First try to register ports specified in the properties
file. If that doesn't exist, then scan for ports.
*/
for (int PortType=CommPortIdentifier.PORT_SERIAL;PortType<=CommPortIdentifier.PORT_PARALLEL;PortType++) {
if (!registerSpecifiedPorts(PortType)) {
if (!registerKnownPorts(PortType)) {
registerScannedPorts(PortType);
}
}
}
}
private void addSpecifiedPorts(String names, int PortType)
{
final String pathSep = System.getProperty("path.separator", ":");
final StringTokenizer tok = new StringTokenizer(names, pathSep);
if (debug)
System.out.println("\nRXTXCommDriver:addSpecifiedPorts()");
while (tok.hasMoreElements())
{
String PortName = tok.nextToken();
if (testRead(PortName, PortType))
CommPortIdentifier.addPortName(PortName,
PortType, this);
}
}
/*
* Register ports specified in the file "gnu.io.rxtx.properties"
* Key system properties:
* gnu.io.rxtx.SerialPorts
* gnu.io.rxtx.ParallelPorts
*
* Tested only with sun jdk1.3
* The file gnu.io.rxtx.properties must reside in the java extension dir
*
* Example: /usr/local/java/jre/lib/ext/gnu.io.rxtx.properties
*
* The file contains the following key properties:
*
* gnu.io.rxtx.SerialPorts=/dev/ttyS0:/dev/ttyS1:
* gnu.io.rxtx.ParallelPorts=/dev/lp0:
*
*/
private boolean registerSpecifiedPorts(int PortType)
{
String val = null;
try
{
String ext_dir=System.getProperty("java.ext.dirs")+System.getProperty("file.separator");
FileInputStream rxtx_prop=new FileInputStream(ext_dir+"gnu.io.rxtx.properties");
Properties p=new Properties(System.getProperties());
p.load(rxtx_prop);
System.setProperties(p);
}catch(Exception e){
if (debug){
System.out.println("The file: gnu.io.rxtx.properties doesn't exists.");
System.out.println(e.toString());
}//end if
}//end catch
if (debug)
System.out.println("checking for system-known ports of type "+PortType);
if (debug)
System.out.println("checking registry for ports of type "+PortType);
switch (PortType) {
case CommPortIdentifier.PORT_SERIAL:
if ((val = System.getProperty("gnu.io.rxtx.SerialPorts")) == null)
val = System.getProperty("gnu.io.SerialPorts");
break;
case CommPortIdentifier.PORT_PARALLEL:
if ((val = System.getProperty("gnu.io.rxtx.ParallelPorts")) == null)
val = System.getProperty("gnu.io.ParallelPorts");
break;
default:
if (debug)
System.out.println("unknown port type "+PortType+" passed to RXTXCommDriver.registerSpecifiedPorts()");
}
if (val != null) {
addSpecifiedPorts(val, PortType);
return true;
} else return false;
}
/*
* Look for all entries in deviceDirectory, and if they look like they should
* be serial ports on this OS and they can be opened then register
* them.
*
*/
private void registerScannedPorts(int PortType)
{
String[] CandidateDeviceNames;
if (debug)
System.out.println("scanning device directory "+deviceDirectory+" for ports of type "+PortType);
if(osName.equals("Windows CE"))
{
String[] temp =
{ "COM1:", "COM2:","COM3:","COM4:",
"COM5:", "COM6:", "COM7:", "COM8:" };
CandidateDeviceNames=temp;
}
else if(osName.toLowerCase().indexOf("windows") != -1 )
{
/* //./name is supposed to work for port numbers > 8 */
/*
{ "//./COM1", "//./COM2", "//./COM3",
"//./COM4", "//./COM5", "//./COM6",
"//./COM7", "//./COM8" };
*/
String[] temp =
{ "COM1", "COM2","COM3","COM4",
"COM5", "COM6", "COM7", "COM8" };
CandidateDeviceNames=temp;
}
else if ( osName.equals("Solaris") || osName.equals("SunOS"))
{
/* Solaris uses a few different ways to identify ports.
They could be /dev/term/a /dev/term0 /dev/cua/a /dev/cuaa
the /dev/???/a appears to be on more systems.
The uucp lock files should not cause problems.
*/
/*
File dev = new File( "/dev/term" );
String deva[] = dev.list();
dev = new File( "/dev/cua" );
String devb[] = dev.list();
String[] temp = new String[ deva.length + devb.length ];
for(int j =0;j<deva.length;j++)
deva[j] = "term/" + deva[j];
for(int j =0;j<devb.length;j++)
devb[j] = "cua/" + devb[j];
System.arraycopy( deva, 0, temp, 0, deva.length );
System.arraycopy( devb, 0, temp,
deva.length, devb.length );
if( debug ) {
for( int j = 0; j< temp.length;j++)
System.out.println( temp[j] );
}
CandidateDeviceNames=temp;
*/
/*
ok.. Look the the dirctories representing the port
kernel driver interface.
If there are entries there are possibly ports we can
use and need to enumerate.
*/
String term[] = new String[2];
int l = 0;
File dev = null;
dev = new File( "/dev/term" );
if( dev.list().length > 0 );
term[l++] = new String( "term/" );
/*
dev = new File( "/dev/cua0" );
if( dev.list().length > 0 );
term[l++] = new String( "cua/" );
*/
String[] temp = new String[l];
for(l--;l >= 0;l--)
temp[l] = term[l];
CandidateDeviceNames=temp;
}
else
{
File dev = new File( deviceDirectory );
String[] temp = dev.list();
CandidateDeviceNames=temp;
}
if (CandidateDeviceNames==null)
{
if (debug)
System.out.println("RXTXCommDriver:registerScannedPorts() no Device files to check ");
return;
}
String CandidatePortPrefixes[] = {};
switch (PortType) {
case CommPortIdentifier.PORT_SERIAL:
if (debug)
System.out.println("scanning for serial ports for os "+osName);
if(osName.equals("Linux"))
{
String[] Temp = {
"ttyS" // linux Serial Ports
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("Linux-all-ports"))
{
/* if you want to enumerate all ports ~5000
possible, then replace the above with this
*/
String[] Temp = {
"comx", // linux COMMX synchronous serial card
"holter", // custom card for heart monitoring
"modem", // linux symbolic link to modem.
"ttyircomm", // linux IrCommdevices (IrDA serial emu)
"ttycosa0c", // linux COSA/SRP synchronous serial card
"ttycosa1c", // linux COSA/SRP synchronous serial card
"ttyC", // linux cyclades cards
"ttyCH",// linux Chase Research AT/PCI-Fast serial card
"ttyD", // linux Digiboard serial card
"ttyE", // linux Stallion serial card
"ttyF", // linux Computone IntelliPort serial card
"ttyH", // linux Chase serial card
"ttyI", // linux virtual modems
"ttyL", // linux SDL RISCom serial card
"ttyM", // linux PAM Software's multimodem boards
// linux ISI serial card
"ttyMX",// linux Moxa Smart IO cards
"ttyP", // linux Hayes ESP serial card
"ttyR", // linux comtrol cards
// linux Specialix RIO serial card
"ttyS", // linux Serial Ports
"ttySI",// linux SmartIO serial card
"ttySR",// linux Specialix RIO serial card 257+
"ttyT", // linux Technology Concepts serial card
"ttyUSB",//linux USB serial converters
"ttyV", // linux Comtrol VS-1000 serial controller
"ttyW", // linux specialix cards
"ttyX" // linux SpecialX serial card
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("Irix"))
{
String[] Temp = {
"ttyc", // irix raw character devices
"ttyd", // irix basic serial ports
"ttyf", // irix serial ports with hardware flow
"ttym", // irix modems
"ttyq", // irix pseudo ttys
"tty4d",// irix RS422
"tty4f",// irix RS422 with HSKo/HSki
"midi", // irix serial midi
"us" // irix mapped interface
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("FreeBSD")) //FIXME this is probably wrong
{
String[] Temp = {
- "cuaa" // FreeBSD Serial Ports
+ "ttyd", //general purpose serial ports
+ "cuaa", //dialout serial ports
+ "ttyA", //Specialix SI/XIO dialin ports
+ "cuaA", //Specialix SI/XIO dialout ports
+ "ttyD", //Digiboard - 16 dialin ports
+ "cuaD", //Digiboard - 16 dialout ports
+ "ttyE", //Stallion EasyIO (stl) dialin ports
+ "cuaE", //Stallion EasyIO (stl) dialout ports
+ "ttyF", //Stallion Brumby (stli) dialin ports
+ "cuaF", //Stallion Brumby (stli) dialout ports
+ "ttyR", //Rocketport dialin ports
+ "cuaR", //Rocketport dialout ports
+ "stl" //Stallion EasyIO board or Brumby N
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("NetBSD")) // FIXME this is probably wrong
{
String[] Temp = {
"tty0" // netbsd serial ports
};
CandidatePortPrefixes=Temp;
}
else if ( osName.equals("Solaris")
|| osName.equals("SunOS"))
{
String[] Temp = {
"term/",
"cua/"
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("HP-UX"))
{
String[] Temp = {
"tty0p",// HP-UX serial ports
"tty1p" // HP-UX serial ports
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("UnixWare") ||
osName.equals("OpenUNIX"))
{
String[] Temp = {
"tty00s", // UW7/OU8 serial ports
"tty01s",
"tty02s",
"tty03s"
};
CandidatePortPrefixes=Temp;
}
else if (osName.equals("OpenServer"))
{
String[] Temp = {
"tty1A", // OSR5 serial ports
"tty2A",
"tty3A",
"tty4A",
"tty5A",
"tty6A",
"tty7A",
"tty8A",
"tty9A",
"tty10A",
"tty11A",
"tty12A",
"tty13A",
"tty14A",
"tty15A",
"tty16A",
"ttyu1A", // OSR5 USB-serial ports
"ttyu2A",
"ttyu3A",
"ttyu4A",
"ttyu5A",
"ttyu6A",
"ttyu7A",
"ttyu8A",
"ttyu9A",
"ttyu10A",
"ttyu11A",
"ttyu12A",
"ttyu13A",
"ttyu14A",
"ttyu15A",
"ttyu16A"
};
CandidatePortPrefixes=Temp;
}
else if (osName.equals("Compaq's Digital UNIX") || osName.equals("OSF1"))
{
String[] Temp = {
"tty0" // Digital Unix serial ports
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("BeOS"))
{
String[] Temp = {
"serial" // BeOS serial ports
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("Mac OS X"))
{
String[] Temp = {
// Keyspan USA-28X adapter, USB port 1
"cu.KeyUSA28X191.",
// Keyspan USA-28X adapter, USB port 1
"tty.KeyUSA28X191.",
// Keyspan USA-28X adapter, USB port 2
"cu.KeyUSA28X181.",
// Keyspan USA-28X adapter, USB port 2
"tty.KeyUSA28X181.",
// Keyspan USA-19 adapter
"cu.KeyUSA19181.",
// Keyspan USA-19 adapter
"tty.KeyUSA19181."
};
CandidatePortPrefixes=Temp;
}
else if(osName.toLowerCase().indexOf("windows") != -1 )
{
String[] Temp = {
"COM" // win32 serial ports
};
CandidatePortPrefixes=Temp;
}
else
{
if (debug)
System.out.println("No valid prefixes for serial ports have been entered for "+osName + " in RXTXCommDriver.java. This may just be a typo in the method registerScanPorts().");
}
break;
case CommPortIdentifier.PORT_PARALLEL:
if (debug)
System.out.println("scanning for parallel ports for os "+osName);
/** Get the Parallel port prefixes for the running os
* Holger Lehmann
* July 12, 1999
* IBM
*/
if(osName.equals("Linux")
/*
|| osName.equals("NetBSD") FIXME
|| osName.equals("HP-UX") FIXME
|| osName.equals("Irix") FIXME
|| osName.equals("BeOS") FIXME
|| osName.equals("Compaq's Digital UNIX") FIXME
*/
)
{
String[] temp={
"lp" // linux printer port
};
CandidatePortPrefixes=temp;
}
else if(osName.equals("FreeBSD"))
{
String[] temp={
"lpt"
};
CandidatePortPrefixes=temp;
}
else /* printer support is green */
{
String [] temp={};
CandidatePortPrefixes=temp;
}
break;
default:
if (debug)
System.out.println("Unknown PortType "+PortType+" passed to RXTXCommDriver.registerScannedPorts()");
}
registerValidPorts(CandidateDeviceNames, CandidatePortPrefixes, PortType);
}
/*
* <p>From the NullDriver.java CommAPI sample.
*/
/**
* @param PortName The name of the port the OS recognizes
* @param PortType CommPortIdentifier.PORT_SERIAL or PORT_PARALLEL
* @returns CommPort
* getCommPort() will be called by CommPortIdentifier from its
* openPort() method. PortName is a string that was registered earlier
* using the CommPortIdentifier.addPortName() method. getCommPort()
* returns an object that extends either SerialPort or ParallelPort.
*/
public CommPort getCommPort( String PortName, int PortType )
{
if (debug) System.out.println("RXTXCommDriver:getCommPort("
+PortName+","+PortType+")");
try {
switch (PortType) {
case CommPortIdentifier.PORT_SERIAL:
return new RXTXPort( PortName );
case CommPortIdentifier.PORT_PARALLEL:
return new LPRPort( PortName );
default:
if (debug)
System.out.println("unknown PortType "+PortType+" passed to RXTXCommDriver.getCommPort()");
}
} catch( PortInUseException e ) {
if (debug)
System.out.println(
"Port "+PortName+" in use by another application");
}
return null;
}
/* Yikes. Trying to call println from C for odd reasons */
public void Report( String arg )
{
System.out.println(arg);
}
}
| true | true | private void registerScannedPorts(int PortType)
{
String[] CandidateDeviceNames;
if (debug)
System.out.println("scanning device directory "+deviceDirectory+" for ports of type "+PortType);
if(osName.equals("Windows CE"))
{
String[] temp =
{ "COM1:", "COM2:","COM3:","COM4:",
"COM5:", "COM6:", "COM7:", "COM8:" };
CandidateDeviceNames=temp;
}
else if(osName.toLowerCase().indexOf("windows") != -1 )
{
/* //./name is supposed to work for port numbers > 8 */
/*
{ "//./COM1", "//./COM2", "//./COM3",
"//./COM4", "//./COM5", "//./COM6",
"//./COM7", "//./COM8" };
*/
String[] temp =
{ "COM1", "COM2","COM3","COM4",
"COM5", "COM6", "COM7", "COM8" };
CandidateDeviceNames=temp;
}
else if ( osName.equals("Solaris") || osName.equals("SunOS"))
{
/* Solaris uses a few different ways to identify ports.
They could be /dev/term/a /dev/term0 /dev/cua/a /dev/cuaa
the /dev/???/a appears to be on more systems.
The uucp lock files should not cause problems.
*/
/*
File dev = new File( "/dev/term" );
String deva[] = dev.list();
dev = new File( "/dev/cua" );
String devb[] = dev.list();
String[] temp = new String[ deva.length + devb.length ];
for(int j =0;j<deva.length;j++)
deva[j] = "term/" + deva[j];
for(int j =0;j<devb.length;j++)
devb[j] = "cua/" + devb[j];
System.arraycopy( deva, 0, temp, 0, deva.length );
System.arraycopy( devb, 0, temp,
deva.length, devb.length );
if( debug ) {
for( int j = 0; j< temp.length;j++)
System.out.println( temp[j] );
}
CandidateDeviceNames=temp;
*/
/*
ok.. Look the the dirctories representing the port
kernel driver interface.
If there are entries there are possibly ports we can
use and need to enumerate.
*/
String term[] = new String[2];
int l = 0;
File dev = null;
dev = new File( "/dev/term" );
if( dev.list().length > 0 );
term[l++] = new String( "term/" );
/*
dev = new File( "/dev/cua0" );
if( dev.list().length > 0 );
term[l++] = new String( "cua/" );
*/
String[] temp = new String[l];
for(l--;l >= 0;l--)
temp[l] = term[l];
CandidateDeviceNames=temp;
}
else
{
File dev = new File( deviceDirectory );
String[] temp = dev.list();
CandidateDeviceNames=temp;
}
if (CandidateDeviceNames==null)
{
if (debug)
System.out.println("RXTXCommDriver:registerScannedPorts() no Device files to check ");
return;
}
String CandidatePortPrefixes[] = {};
switch (PortType) {
case CommPortIdentifier.PORT_SERIAL:
if (debug)
System.out.println("scanning for serial ports for os "+osName);
if(osName.equals("Linux"))
{
String[] Temp = {
"ttyS" // linux Serial Ports
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("Linux-all-ports"))
{
/* if you want to enumerate all ports ~5000
possible, then replace the above with this
*/
String[] Temp = {
"comx", // linux COMMX synchronous serial card
"holter", // custom card for heart monitoring
"modem", // linux symbolic link to modem.
"ttyircomm", // linux IrCommdevices (IrDA serial emu)
"ttycosa0c", // linux COSA/SRP synchronous serial card
"ttycosa1c", // linux COSA/SRP synchronous serial card
"ttyC", // linux cyclades cards
"ttyCH",// linux Chase Research AT/PCI-Fast serial card
"ttyD", // linux Digiboard serial card
"ttyE", // linux Stallion serial card
"ttyF", // linux Computone IntelliPort serial card
"ttyH", // linux Chase serial card
"ttyI", // linux virtual modems
"ttyL", // linux SDL RISCom serial card
"ttyM", // linux PAM Software's multimodem boards
// linux ISI serial card
"ttyMX",// linux Moxa Smart IO cards
"ttyP", // linux Hayes ESP serial card
"ttyR", // linux comtrol cards
// linux Specialix RIO serial card
"ttyS", // linux Serial Ports
"ttySI",// linux SmartIO serial card
"ttySR",// linux Specialix RIO serial card 257+
"ttyT", // linux Technology Concepts serial card
"ttyUSB",//linux USB serial converters
"ttyV", // linux Comtrol VS-1000 serial controller
"ttyW", // linux specialix cards
"ttyX" // linux SpecialX serial card
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("Irix"))
{
String[] Temp = {
"ttyc", // irix raw character devices
"ttyd", // irix basic serial ports
"ttyf", // irix serial ports with hardware flow
"ttym", // irix modems
"ttyq", // irix pseudo ttys
"tty4d",// irix RS422
"tty4f",// irix RS422 with HSKo/HSki
"midi", // irix serial midi
"us" // irix mapped interface
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("FreeBSD")) //FIXME this is probably wrong
{
String[] Temp = {
"cuaa" // FreeBSD Serial Ports
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("NetBSD")) // FIXME this is probably wrong
{
String[] Temp = {
"tty0" // netbsd serial ports
};
CandidatePortPrefixes=Temp;
}
else if ( osName.equals("Solaris")
|| osName.equals("SunOS"))
{
String[] Temp = {
"term/",
"cua/"
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("HP-UX"))
{
String[] Temp = {
"tty0p",// HP-UX serial ports
"tty1p" // HP-UX serial ports
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("UnixWare") ||
osName.equals("OpenUNIX"))
{
String[] Temp = {
"tty00s", // UW7/OU8 serial ports
"tty01s",
"tty02s",
"tty03s"
};
CandidatePortPrefixes=Temp;
}
else if (osName.equals("OpenServer"))
{
String[] Temp = {
"tty1A", // OSR5 serial ports
"tty2A",
"tty3A",
"tty4A",
"tty5A",
"tty6A",
"tty7A",
"tty8A",
"tty9A",
"tty10A",
"tty11A",
"tty12A",
"tty13A",
"tty14A",
"tty15A",
"tty16A",
"ttyu1A", // OSR5 USB-serial ports
"ttyu2A",
"ttyu3A",
"ttyu4A",
"ttyu5A",
"ttyu6A",
"ttyu7A",
"ttyu8A",
"ttyu9A",
"ttyu10A",
"ttyu11A",
"ttyu12A",
"ttyu13A",
"ttyu14A",
"ttyu15A",
"ttyu16A"
};
CandidatePortPrefixes=Temp;
}
else if (osName.equals("Compaq's Digital UNIX") || osName.equals("OSF1"))
{
String[] Temp = {
"tty0" // Digital Unix serial ports
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("BeOS"))
{
String[] Temp = {
"serial" // BeOS serial ports
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("Mac OS X"))
{
String[] Temp = {
// Keyspan USA-28X adapter, USB port 1
"cu.KeyUSA28X191.",
// Keyspan USA-28X adapter, USB port 1
"tty.KeyUSA28X191.",
// Keyspan USA-28X adapter, USB port 2
"cu.KeyUSA28X181.",
// Keyspan USA-28X adapter, USB port 2
"tty.KeyUSA28X181.",
// Keyspan USA-19 adapter
"cu.KeyUSA19181.",
// Keyspan USA-19 adapter
"tty.KeyUSA19181."
};
CandidatePortPrefixes=Temp;
}
else if(osName.toLowerCase().indexOf("windows") != -1 )
{
String[] Temp = {
"COM" // win32 serial ports
};
CandidatePortPrefixes=Temp;
}
else
{
if (debug)
System.out.println("No valid prefixes for serial ports have been entered for "+osName + " in RXTXCommDriver.java. This may just be a typo in the method registerScanPorts().");
}
break;
case CommPortIdentifier.PORT_PARALLEL:
if (debug)
System.out.println("scanning for parallel ports for os "+osName);
/** Get the Parallel port prefixes for the running os
* Holger Lehmann
* July 12, 1999
* IBM
*/
if(osName.equals("Linux")
/*
|| osName.equals("NetBSD") FIXME
|| osName.equals("HP-UX") FIXME
|| osName.equals("Irix") FIXME
|| osName.equals("BeOS") FIXME
|| osName.equals("Compaq's Digital UNIX") FIXME
*/
)
{
String[] temp={
"lp" // linux printer port
};
CandidatePortPrefixes=temp;
}
else if(osName.equals("FreeBSD"))
{
String[] temp={
"lpt"
};
CandidatePortPrefixes=temp;
}
else /* printer support is green */
{
String [] temp={};
CandidatePortPrefixes=temp;
}
break;
default:
if (debug)
System.out.println("Unknown PortType "+PortType+" passed to RXTXCommDriver.registerScannedPorts()");
}
registerValidPorts(CandidateDeviceNames, CandidatePortPrefixes, PortType);
}
| private void registerScannedPorts(int PortType)
{
String[] CandidateDeviceNames;
if (debug)
System.out.println("scanning device directory "+deviceDirectory+" for ports of type "+PortType);
if(osName.equals("Windows CE"))
{
String[] temp =
{ "COM1:", "COM2:","COM3:","COM4:",
"COM5:", "COM6:", "COM7:", "COM8:" };
CandidateDeviceNames=temp;
}
else if(osName.toLowerCase().indexOf("windows") != -1 )
{
/* //./name is supposed to work for port numbers > 8 */
/*
{ "//./COM1", "//./COM2", "//./COM3",
"//./COM4", "//./COM5", "//./COM6",
"//./COM7", "//./COM8" };
*/
String[] temp =
{ "COM1", "COM2","COM3","COM4",
"COM5", "COM6", "COM7", "COM8" };
CandidateDeviceNames=temp;
}
else if ( osName.equals("Solaris") || osName.equals("SunOS"))
{
/* Solaris uses a few different ways to identify ports.
They could be /dev/term/a /dev/term0 /dev/cua/a /dev/cuaa
the /dev/???/a appears to be on more systems.
The uucp lock files should not cause problems.
*/
/*
File dev = new File( "/dev/term" );
String deva[] = dev.list();
dev = new File( "/dev/cua" );
String devb[] = dev.list();
String[] temp = new String[ deva.length + devb.length ];
for(int j =0;j<deva.length;j++)
deva[j] = "term/" + deva[j];
for(int j =0;j<devb.length;j++)
devb[j] = "cua/" + devb[j];
System.arraycopy( deva, 0, temp, 0, deva.length );
System.arraycopy( devb, 0, temp,
deva.length, devb.length );
if( debug ) {
for( int j = 0; j< temp.length;j++)
System.out.println( temp[j] );
}
CandidateDeviceNames=temp;
*/
/*
ok.. Look the the dirctories representing the port
kernel driver interface.
If there are entries there are possibly ports we can
use and need to enumerate.
*/
String term[] = new String[2];
int l = 0;
File dev = null;
dev = new File( "/dev/term" );
if( dev.list().length > 0 );
term[l++] = new String( "term/" );
/*
dev = new File( "/dev/cua0" );
if( dev.list().length > 0 );
term[l++] = new String( "cua/" );
*/
String[] temp = new String[l];
for(l--;l >= 0;l--)
temp[l] = term[l];
CandidateDeviceNames=temp;
}
else
{
File dev = new File( deviceDirectory );
String[] temp = dev.list();
CandidateDeviceNames=temp;
}
if (CandidateDeviceNames==null)
{
if (debug)
System.out.println("RXTXCommDriver:registerScannedPorts() no Device files to check ");
return;
}
String CandidatePortPrefixes[] = {};
switch (PortType) {
case CommPortIdentifier.PORT_SERIAL:
if (debug)
System.out.println("scanning for serial ports for os "+osName);
if(osName.equals("Linux"))
{
String[] Temp = {
"ttyS" // linux Serial Ports
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("Linux-all-ports"))
{
/* if you want to enumerate all ports ~5000
possible, then replace the above with this
*/
String[] Temp = {
"comx", // linux COMMX synchronous serial card
"holter", // custom card for heart monitoring
"modem", // linux symbolic link to modem.
"ttyircomm", // linux IrCommdevices (IrDA serial emu)
"ttycosa0c", // linux COSA/SRP synchronous serial card
"ttycosa1c", // linux COSA/SRP synchronous serial card
"ttyC", // linux cyclades cards
"ttyCH",// linux Chase Research AT/PCI-Fast serial card
"ttyD", // linux Digiboard serial card
"ttyE", // linux Stallion serial card
"ttyF", // linux Computone IntelliPort serial card
"ttyH", // linux Chase serial card
"ttyI", // linux virtual modems
"ttyL", // linux SDL RISCom serial card
"ttyM", // linux PAM Software's multimodem boards
// linux ISI serial card
"ttyMX",// linux Moxa Smart IO cards
"ttyP", // linux Hayes ESP serial card
"ttyR", // linux comtrol cards
// linux Specialix RIO serial card
"ttyS", // linux Serial Ports
"ttySI",// linux SmartIO serial card
"ttySR",// linux Specialix RIO serial card 257+
"ttyT", // linux Technology Concepts serial card
"ttyUSB",//linux USB serial converters
"ttyV", // linux Comtrol VS-1000 serial controller
"ttyW", // linux specialix cards
"ttyX" // linux SpecialX serial card
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("Irix"))
{
String[] Temp = {
"ttyc", // irix raw character devices
"ttyd", // irix basic serial ports
"ttyf", // irix serial ports with hardware flow
"ttym", // irix modems
"ttyq", // irix pseudo ttys
"tty4d",// irix RS422
"tty4f",// irix RS422 with HSKo/HSki
"midi", // irix serial midi
"us" // irix mapped interface
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("FreeBSD")) //FIXME this is probably wrong
{
String[] Temp = {
"ttyd", //general purpose serial ports
"cuaa", //dialout serial ports
"ttyA", //Specialix SI/XIO dialin ports
"cuaA", //Specialix SI/XIO dialout ports
"ttyD", //Digiboard - 16 dialin ports
"cuaD", //Digiboard - 16 dialout ports
"ttyE", //Stallion EasyIO (stl) dialin ports
"cuaE", //Stallion EasyIO (stl) dialout ports
"ttyF", //Stallion Brumby (stli) dialin ports
"cuaF", //Stallion Brumby (stli) dialout ports
"ttyR", //Rocketport dialin ports
"cuaR", //Rocketport dialout ports
"stl" //Stallion EasyIO board or Brumby N
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("NetBSD")) // FIXME this is probably wrong
{
String[] Temp = {
"tty0" // netbsd serial ports
};
CandidatePortPrefixes=Temp;
}
else if ( osName.equals("Solaris")
|| osName.equals("SunOS"))
{
String[] Temp = {
"term/",
"cua/"
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("HP-UX"))
{
String[] Temp = {
"tty0p",// HP-UX serial ports
"tty1p" // HP-UX serial ports
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("UnixWare") ||
osName.equals("OpenUNIX"))
{
String[] Temp = {
"tty00s", // UW7/OU8 serial ports
"tty01s",
"tty02s",
"tty03s"
};
CandidatePortPrefixes=Temp;
}
else if (osName.equals("OpenServer"))
{
String[] Temp = {
"tty1A", // OSR5 serial ports
"tty2A",
"tty3A",
"tty4A",
"tty5A",
"tty6A",
"tty7A",
"tty8A",
"tty9A",
"tty10A",
"tty11A",
"tty12A",
"tty13A",
"tty14A",
"tty15A",
"tty16A",
"ttyu1A", // OSR5 USB-serial ports
"ttyu2A",
"ttyu3A",
"ttyu4A",
"ttyu5A",
"ttyu6A",
"ttyu7A",
"ttyu8A",
"ttyu9A",
"ttyu10A",
"ttyu11A",
"ttyu12A",
"ttyu13A",
"ttyu14A",
"ttyu15A",
"ttyu16A"
};
CandidatePortPrefixes=Temp;
}
else if (osName.equals("Compaq's Digital UNIX") || osName.equals("OSF1"))
{
String[] Temp = {
"tty0" // Digital Unix serial ports
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("BeOS"))
{
String[] Temp = {
"serial" // BeOS serial ports
};
CandidatePortPrefixes=Temp;
}
else if(osName.equals("Mac OS X"))
{
String[] Temp = {
// Keyspan USA-28X adapter, USB port 1
"cu.KeyUSA28X191.",
// Keyspan USA-28X adapter, USB port 1
"tty.KeyUSA28X191.",
// Keyspan USA-28X adapter, USB port 2
"cu.KeyUSA28X181.",
// Keyspan USA-28X adapter, USB port 2
"tty.KeyUSA28X181.",
// Keyspan USA-19 adapter
"cu.KeyUSA19181.",
// Keyspan USA-19 adapter
"tty.KeyUSA19181."
};
CandidatePortPrefixes=Temp;
}
else if(osName.toLowerCase().indexOf("windows") != -1 )
{
String[] Temp = {
"COM" // win32 serial ports
};
CandidatePortPrefixes=Temp;
}
else
{
if (debug)
System.out.println("No valid prefixes for serial ports have been entered for "+osName + " in RXTXCommDriver.java. This may just be a typo in the method registerScanPorts().");
}
break;
case CommPortIdentifier.PORT_PARALLEL:
if (debug)
System.out.println("scanning for parallel ports for os "+osName);
/** Get the Parallel port prefixes for the running os
* Holger Lehmann
* July 12, 1999
* IBM
*/
if(osName.equals("Linux")
/*
|| osName.equals("NetBSD") FIXME
|| osName.equals("HP-UX") FIXME
|| osName.equals("Irix") FIXME
|| osName.equals("BeOS") FIXME
|| osName.equals("Compaq's Digital UNIX") FIXME
*/
)
{
String[] temp={
"lp" // linux printer port
};
CandidatePortPrefixes=temp;
}
else if(osName.equals("FreeBSD"))
{
String[] temp={
"lpt"
};
CandidatePortPrefixes=temp;
}
else /* printer support is green */
{
String [] temp={};
CandidatePortPrefixes=temp;
}
break;
default:
if (debug)
System.out.println("Unknown PortType "+PortType+" passed to RXTXCommDriver.registerScannedPorts()");
}
registerValidPorts(CandidateDeviceNames, CandidatePortPrefixes, PortType);
}
|
diff --git a/pn-dispatcher/src/main/java/info/papyri/dispatch/Reader.java b/pn-dispatcher/src/main/java/info/papyri/dispatch/Reader.java
index 6d6fd924..7bf128f2 100644
--- a/pn-dispatcher/src/main/java/info/papyri/dispatch/Reader.java
+++ b/pn-dispatcher/src/main/java/info/papyri/dispatch/Reader.java
@@ -1,242 +1,239 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package info.papyri.dispatch;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.net.SocketTimeoutException;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.JsonNode;
/**
*
* @author hcayless
*/
@WebServlet(name = "Reader", urlPatterns = {"/reader"})
public class Reader extends HttpServlet {
private static String graph = "rmi://localhost/papyri.info#pi";
private static String path = "/sparql/";
private String mulgara;
private String xmlPath = "";
private String htmlPath = "";
private FileUtils util;
private SolrUtils solrutil;
private byte[] buffer = new byte[8192];
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
xmlPath = config.getInitParameter("xmlPath");
htmlPath = config.getInitParameter("htmlPath");
util = new FileUtils(xmlPath, htmlPath);
solrutil = new SolrUtils(config);
mulgara = config.getInitParameter("mulgaraUrl");
}
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String page = request.getParameter("p");
if (page != null) {
// Redirection for old static URLs
if (page.contains("current") && (page.contains("-citations-") || page.contains("index.html"))) {
response.sendError(HttpServletResponse.SC_GONE);
} else if (page.endsWith(".html")) {
if (page.contains("ddb/html") || page.contains("aggregated/html")) {
response.setHeader("Location", FileUtils.rewriteOldUrl(page));
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
} else if (page.contains("hgvmeta")) {
response.setHeader("Location", page.replaceAll("^[/a-z]+/HGV\\d+/([0-9]+[a-z]*).html$", "http://papyri.info/hgv/$1"));
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
}
} else if (page.contains("/")) {
String collection = FileUtils.substringBefore(page, "/");
String item = FileUtils.substringAfter(page, "/").replaceAll("/$", "");
File file = null;
if (item.endsWith("/source")) {
response.setContentType("application/xml;charset=UTF-8");
file = util.getXmlFile(collection, item.replace("/source", ""));
- if (file == null) response.sendError(response.SC_NOT_FOUND);
- if (!file.exists()) { //use triple store to resolve to source file
+ if (file != null && !file.exists()) { //use triple store to resolve to source file
file = resolveFile("http://papyri.info/" + collection + "/" + item + "/source", "Xml");
}
} else if (page.endsWith("text")) {
response.setContentType("text/plain;charset=UTF-8");
file = util.getTextFile(collection, item.replace("/text", ""));
- if (file == null) response.sendError(response.SC_NOT_FOUND);
- if (!file.exists()) { //use triple store to resolve to source file
+ if (file != null && !file.exists()) { //use triple store to resolve to source file
file = resolveFile("http://papyri.info/" + collection + "/" + item + "/source", "Text");
}
} else {
response.setContentType("text/html;charset=UTF-8");
file = util.getHtmlFile(collection, item);
- if (file == null) response.sendError(response.SC_NOT_FOUND);
- if (!file.exists()) { //use triple store to resolve to source file
+ if (file != null && !file.exists()) { //use triple store to resolve to source file
file = resolveFile("http://papyri.info/" + collection + "/" + item + "/source", "Html");
}
}
if (file == null) {
response.sendError(response.SC_NOT_FOUND);
} else {
if (request.getParameter("q") != null) {
sendWithHighlight(response, file, request.getParameter("q"));
} else {
send(response, file);
}
}
}
} else {
response.sendError(response.SC_NOT_FOUND);
}
}
private void send(HttpServletResponse response, File f)
throws ServletException, IOException {
FileInputStream reader = null;
OutputStream out = response.getOutputStream();
if (f != null && f.exists()) {
try {
reader = new FileInputStream(f);
int size = reader.read(buffer);
while (size > 0) {
out.write(buffer, 0, size);
size = reader.read(buffer);
}
} catch (IOException e) {
response.sendError(response.SC_NOT_FOUND);
System.out.println("Failed to send " + f);
} finally {
reader.close();
out.close();
}
} else {
response.sendError(response.SC_NOT_FOUND);
}
}
private void sendWithHighlight(HttpServletResponse response, File f, String q)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
if (q.contains("transcription_l")) {
try {
StringBuilder query = new StringBuilder();
query.append(FileUtils.substringBefore(q, "transcription_l", false));
query.append("transcription_ia:(");
query.append(solrutil.expandLemmas(FileUtils.substringBefore(FileUtils.substringAfter(q, "transcription_l:(", false), ")", false)));
query.append(")");
query.append(FileUtils.substringAfter(FileUtils.substringAfter(q, "transcription_l:(", false), ")", false));
q = query.toString();
System.out.println(q);
} catch (Exception e) {
e.printStackTrace();
}
}
if (f != null && f.exists()) {
try {
out.write(util.highlight(q, util.loadFile(f)));
} catch (Exception e) {
e.printStackTrace(System.out);
} finally {
out.close();
}
} else {
response.sendError(response.SC_NOT_FOUND);
}
}
private File resolveFile(String page, String type) {
File result = null;
String sparql = "prefix dc: <http://purl.org/dc/terms/> "
+ "select ?related "
+ "from <rmi://localhost/papyri.info#pi> "
+ "where { <" + page +"> dc:relation ?related . "
+ "optional { ?related dc:isReplacedBy ?orig } . "
+ "filter (!bound(?orig)) . "
+ "filter regex(str(?related), \"^http://papyri.info/(ddbdp|hgv)\") }";
try {
URL m = new URL(mulgara + path + "?query=" + URLEncoder.encode(sparql, "UTF-8") + "&format=json");
HttpURLConnection http = (HttpURLConnection)m.openConnection();
http.setConnectTimeout(2000);
ObjectMapper o = new ObjectMapper();
JsonNode root = o.readValue(http.getInputStream(), JsonNode.class);
Iterator<JsonNode> i = root.path("results").path("bindings").iterator();
String uri = "";
while (i.hasNext()) {
uri = FileUtils.substringBefore(i.next().path("related").path("value").getValueAsText(), "/source");
if (uri.contains("ddbdp/")) {
result = (File)util.getClass().getMethod("get"+type+"FileFromId", String.class).invoke(util, uri);
}
if (uri.contains("hgv/")) {
result = (File)util.getClass().getMethod("get"+type+"FileFromId", String.class).invoke(util, uri);
}
if (result.exists()) break;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(sparql);
return null;
}
return result;
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| false | true | protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String page = request.getParameter("p");
if (page != null) {
// Redirection for old static URLs
if (page.contains("current") && (page.contains("-citations-") || page.contains("index.html"))) {
response.sendError(HttpServletResponse.SC_GONE);
} else if (page.endsWith(".html")) {
if (page.contains("ddb/html") || page.contains("aggregated/html")) {
response.setHeader("Location", FileUtils.rewriteOldUrl(page));
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
} else if (page.contains("hgvmeta")) {
response.setHeader("Location", page.replaceAll("^[/a-z]+/HGV\\d+/([0-9]+[a-z]*).html$", "http://papyri.info/hgv/$1"));
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
}
} else if (page.contains("/")) {
String collection = FileUtils.substringBefore(page, "/");
String item = FileUtils.substringAfter(page, "/").replaceAll("/$", "");
File file = null;
if (item.endsWith("/source")) {
response.setContentType("application/xml;charset=UTF-8");
file = util.getXmlFile(collection, item.replace("/source", ""));
if (file == null) response.sendError(response.SC_NOT_FOUND);
if (!file.exists()) { //use triple store to resolve to source file
file = resolveFile("http://papyri.info/" + collection + "/" + item + "/source", "Xml");
}
} else if (page.endsWith("text")) {
response.setContentType("text/plain;charset=UTF-8");
file = util.getTextFile(collection, item.replace("/text", ""));
if (file == null) response.sendError(response.SC_NOT_FOUND);
if (!file.exists()) { //use triple store to resolve to source file
file = resolveFile("http://papyri.info/" + collection + "/" + item + "/source", "Text");
}
} else {
response.setContentType("text/html;charset=UTF-8");
file = util.getHtmlFile(collection, item);
if (file == null) response.sendError(response.SC_NOT_FOUND);
if (!file.exists()) { //use triple store to resolve to source file
file = resolveFile("http://papyri.info/" + collection + "/" + item + "/source", "Html");
}
}
if (file == null) {
response.sendError(response.SC_NOT_FOUND);
} else {
if (request.getParameter("q") != null) {
sendWithHighlight(response, file, request.getParameter("q"));
} else {
send(response, file);
}
}
}
} else {
response.sendError(response.SC_NOT_FOUND);
}
}
| protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String page = request.getParameter("p");
if (page != null) {
// Redirection for old static URLs
if (page.contains("current") && (page.contains("-citations-") || page.contains("index.html"))) {
response.sendError(HttpServletResponse.SC_GONE);
} else if (page.endsWith(".html")) {
if (page.contains("ddb/html") || page.contains("aggregated/html")) {
response.setHeader("Location", FileUtils.rewriteOldUrl(page));
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
} else if (page.contains("hgvmeta")) {
response.setHeader("Location", page.replaceAll("^[/a-z]+/HGV\\d+/([0-9]+[a-z]*).html$", "http://papyri.info/hgv/$1"));
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
}
} else if (page.contains("/")) {
String collection = FileUtils.substringBefore(page, "/");
String item = FileUtils.substringAfter(page, "/").replaceAll("/$", "");
File file = null;
if (item.endsWith("/source")) {
response.setContentType("application/xml;charset=UTF-8");
file = util.getXmlFile(collection, item.replace("/source", ""));
if (file != null && !file.exists()) { //use triple store to resolve to source file
file = resolveFile("http://papyri.info/" + collection + "/" + item + "/source", "Xml");
}
} else if (page.endsWith("text")) {
response.setContentType("text/plain;charset=UTF-8");
file = util.getTextFile(collection, item.replace("/text", ""));
if (file != null && !file.exists()) { //use triple store to resolve to source file
file = resolveFile("http://papyri.info/" + collection + "/" + item + "/source", "Text");
}
} else {
response.setContentType("text/html;charset=UTF-8");
file = util.getHtmlFile(collection, item);
if (file != null && !file.exists()) { //use triple store to resolve to source file
file = resolveFile("http://papyri.info/" + collection + "/" + item + "/source", "Html");
}
}
if (file == null) {
response.sendError(response.SC_NOT_FOUND);
} else {
if (request.getParameter("q") != null) {
sendWithHighlight(response, file, request.getParameter("q"));
} else {
send(response, file);
}
}
}
} else {
response.sendError(response.SC_NOT_FOUND);
}
}
|
diff --git a/railo-java/railo-core/src/railo/runtime/listener/ModernAppListener.java b/railo-java/railo-core/src/railo/runtime/listener/ModernAppListener.java
index 15754e741..1a8c151d1 100755
--- a/railo-java/railo-core/src/railo/runtime/listener/ModernAppListener.java
+++ b/railo-java/railo-core/src/railo/runtime/listener/ModernAppListener.java
@@ -1,424 +1,424 @@
package railo.runtime.listener;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.Cookie;
import railo.commons.io.DevNullOutputStream;
import railo.commons.io.res.Resource;
import railo.commons.io.res.util.ResourceUtil;
import railo.commons.lang.StringUtil;
import railo.commons.lang.types.RefBoolean;
import railo.commons.lang.types.RefBooleanImpl;
import railo.runtime.CFMLFactory;
import railo.runtime.Component;
import railo.runtime.ComponentPage;
import railo.runtime.ComponentPro;
import railo.runtime.PageContext;
import railo.runtime.PageContextImpl;
import railo.runtime.PageSource;
import railo.runtime.component.ComponentLoader;
import railo.runtime.component.Member;
import railo.runtime.exp.Abort;
import railo.runtime.exp.MissingIncludeException;
import railo.runtime.exp.PageException;
import railo.runtime.interpreter.JSONExpressionInterpreter;
import railo.runtime.net.http.HttpServletRequestDummy;
import railo.runtime.net.http.HttpServletResponseDummy;
import railo.runtime.op.Caster;
import railo.runtime.op.Decision;
import railo.runtime.orm.ORMUtil;
import railo.runtime.type.Array;
import railo.runtime.type.ArrayImpl;
import railo.runtime.type.Collection;
import railo.runtime.type.Collection.Key;
import railo.runtime.type.KeyImpl;
import railo.runtime.type.Struct;
import railo.runtime.type.cfc.ComponentAccess;
import railo.runtime.type.util.ArrayUtil;
import railo.runtime.type.util.StructUtil;
public class ModernAppListener extends AppListenerSupport {
private static final Collection.Key ON_REQUEST_START = KeyImpl.intern("onRequestStart");
private static final Collection.Key ON_CFCREQUEST = KeyImpl.intern("onCFCRequest");
private static final Collection.Key ON_REQUEST = KeyImpl.intern("onRequest");
private static final Collection.Key ON_REQUEST_END = KeyImpl.intern("onRequestEnd");
private static final Collection.Key ON_APPLICATION_START = KeyImpl.intern("onApplicationStart");
private static final Collection.Key ON_APPLICATION_END = KeyImpl.intern("onApplicationEnd");
private static final Collection.Key ON_SESSION_START = KeyImpl.intern("onSessionStart");
private static final Collection.Key ON_SESSION_END = KeyImpl.intern("onSessionEnd");
private static final Collection.Key ON_DEBUG = KeyImpl.intern("onDebug");
private static final Collection.Key ON_ERROR = KeyImpl.intern("onError");
private static final Collection.Key ON_MISSING_TEMPLATE = KeyImpl.intern("onMissingTemplate");
//private ComponentImpl app;
private Map apps=new HashMap();
protected int mode=MODE_CURRENT2ROOT;
private String type;
private Boolean hasOnSessionStart;
//private ApplicationContextImpl appContext;
//private long cfcCompileTime;
/**
*
* @throws PageException
* @see railo.runtime.listener.ApplicationListener#onRequest(railo.runtime.PageContext, railo.runtime.PageSource)
*/
public void onRequest(PageContext pc, PageSource requestedPage) throws PageException {
// on requestStart
PageSource appPS=//pc.isCFCRequest()?null:
AppListenerUtil.getApplicationPageSource(pc,requestedPage,"Application.cfc",mode);
_onRequest(pc, requestedPage, appPS);
}
protected void _onRequest(PageContext pc, PageSource requestedPage,PageSource appPS) throws PageException {
PageContextImpl pci = (PageContextImpl)pc;
if(appPS!=null) {
String callPath=appPS.getComponentName();
- ComponentAccess app = ComponentLoader.loadComponent(pci,null,appPS, callPath, false,true);
+ ComponentAccess app = ComponentLoader.loadComponent(pci,null,appPS, callPath, false,false);
String targetPage=requestedPage.getFullRealpath();
// init
initApplicationContext(pci,app);
apps.put(pc.getApplicationContext().getName(), app);
if(!pci.initApplicationContext()) return;
// onRequestStart
if(app.contains(pc,ON_REQUEST_START)) {
Object rtn=call(app,pci, ON_REQUEST_START, new Object[]{targetPage});
if(!Caster.toBooleanValue(rtn,true))
return;
}
// onRequest
boolean isCFC=ResourceUtil.getExtension(targetPage,"").equalsIgnoreCase(pc.getConfig().getCFCExtension());
Object method;
if(isCFC && app.contains(pc,ON_CFCREQUEST) && (method=pc.urlFormScope().get(ComponentPage.METHOD,null))!=null) {
Struct url = StructUtil.duplicate(pc.urlFormScope(),true);
url.removeEL(KeyImpl.FIELD_NAMES);
url.removeEL(ComponentPage.METHOD);
Object args=url.get(KeyImpl.ARGUMENT_COLLECTION,null);
Object returnFormat=url.removeEL(KeyImpl.RETURN_FORMAT);
Object queryFormat=url.removeEL(ComponentPage.QUERY_FORMAT);
if(args==null){
args=pc.getHttpServletRequest().getAttribute("argumentCollection");
}
if(args instanceof String){
args=new JSONExpressionInterpreter().interpret(pc, (String)args);
}
if(args!=null) {
if(Decision.isCastableToStruct(args)){
Struct sct = Caster.toStruct(args,false);
Key[] keys = url.keys();
for(int i=0;i<keys.length;i++){
sct.setEL(keys[i],url.get(keys[i]));
}
args=sct;
}
else if(Decision.isCastableToArray(args)){
args = Caster.toArray(args);
}
else {
Array arr = new ArrayImpl();
arr.appendEL(args);
args=arr;
}
}
else
args=url;
//print.out("c:"+requestedPage.getComponentName());
//print.out("c:"+requestedPage.getComponentName());
Object rtn = call(app,pci, ON_CFCREQUEST, new Object[]{requestedPage.getComponentName(),method,args});
if(rtn!=null){
if(pc.getHttpServletRequest().getHeader("AMF-Forward")!=null) {
pc.variablesScope().setEL("AMF-Forward", rtn);
//ThreadLocalWDDXResult.set(rtn);
}
else {
try {
pc.forceWrite(ComponentPage.convertResult(pc,app,method.toString(),returnFormat,queryFormat,rtn));
} catch (Exception e) {
throw Caster.toPageException(e);
}
}
}
}
else if(!isCFC && app.contains(pc,ON_REQUEST)) {
call(app,pci, ON_REQUEST, new Object[]{targetPage});
}
else {
// TODO impl die nicht so generisch ist
try{
pci.doInclude(requestedPage);
}
catch(PageException pe){
if(!Abort.isSilentAbort(pe)) {
if(pe instanceof MissingIncludeException){
if(((MissingIncludeException) pe).getPageSource().equals(requestedPage)){
if(app.contains(pc,ON_MISSING_TEMPLATE)) {
if(!Caster.toBooleanValue(call(app,pci, ON_MISSING_TEMPLATE, new Object[]{targetPage}),true))
throw pe;
}
else throw pe;
}
else throw pe;
}
else throw pe;
}
}
}
// onRequestEnd
if(app.contains(pc,ON_REQUEST_END)) {
call(app,pci, ON_REQUEST_END, new Object[]{targetPage});
}
}
else {
apps.put(pc.getApplicationContext().getName(), null);
pc.doInclude(requestedPage);
}
}
/**
*
* @see railo.runtime.listener.ApplicationListener#onApplicationStart(railo.runtime.PageContext)
*/
public boolean onApplicationStart(PageContext pc) throws PageException {
ComponentAccess app = (ComponentAccess) apps.get(pc.getApplicationContext().getName());
if(app!=null && app.contains(pc,ON_APPLICATION_START)) {
Object rtn = call(app,pc, ON_APPLICATION_START, ArrayUtil.OBJECT_EMPTY);
return Caster.toBooleanValue(rtn,true);
}
return true;
}
public void onApplicationEnd(CFMLFactory factory, String applicationName) throws PageException {
ComponentAccess app = (ComponentAccess) apps.get(applicationName);
if(app==null || !app.containsKey(ON_APPLICATION_END)) return;
PageContextImpl pc=null;
try {
pc = (PageContextImpl) createPageContext(factory,app,applicationName,null,ON_APPLICATION_END);
call(app,pc, ON_APPLICATION_END, new Object[]{pc.applicationScope()});
}
finally {
if(pc!=null){
factory.releasePageContext(pc);
}
}
}
/**
*
* @see railo.runtime.listener.ApplicationListener#onSessionStart(railo.runtime.PageContext)
*/
public void onSessionStart(PageContext pc) throws PageException {
ComponentAccess app = (ComponentAccess) apps.get(pc.getApplicationContext().getName());
if(hasOnSessionStart(pc,app)) {
call(app,pc, ON_SESSION_START, ArrayUtil.OBJECT_EMPTY);
}
}
/**
*
* @see railo.runtime.listener.ApplicationListener#onSessionEnd(railo.runtime.CFMLFactory, java.lang.String, java.lang.String)
*/
public void onSessionEnd(CFMLFactory factory, String applicationName, String cfid) throws PageException {
ComponentAccess app = (ComponentAccess) apps.get(applicationName);
if(app==null || !app.containsKey(ON_SESSION_END)) return;
PageContextImpl pc=null;
try {
pc = createPageContext(factory,app,applicationName,cfid,ON_SESSION_END);
call(app,pc, ON_SESSION_END, new Object[]{pc.sessionScope(false),pc.applicationScope()});
}
finally {
if(pc!=null){
factory.releasePageContext(pc);
}
}
}
private PageContextImpl createPageContext(CFMLFactory factory, ComponentAccess app, String applicationName, String cfid,Collection.Key methodName) throws PageException {
Resource root = factory.getConfig().getRootDirectory();
String path = app.getPageSource().getFullRealpath();
// Request
HttpServletRequestDummy req = new HttpServletRequestDummy(root,"localhost",path,"",null,null,null,null,null);
if(!StringUtil.isEmpty(cfid))req.setCookies(new Cookie[]{new Cookie("cfid",cfid),new Cookie("cftoken","0")});
// Response
OutputStream os=DevNullOutputStream.DEV_NULL_OUTPUT_STREAM;
try {
Resource out = factory.getConfig().getConfigDir().getRealResource("output/"+methodName.getString()+".out");
out.getParentResource().mkdirs();
os = out.getOutputStream(false);
}
catch (IOException e) {
e.printStackTrace();
// TODO was passiert hier
}
HttpServletResponseDummy rsp = new HttpServletResponseDummy(os);
// PageContext
PageContextImpl pc = (PageContextImpl) factory.getRailoPageContext(factory.getServlet(), req, rsp, null, false, -1, false);
// ApplicationContext
ClassicApplicationContext ap = new ClassicApplicationContext(factory.getConfig(),applicationName,false,app==null?null:ResourceUtil.getResource(pc,app.getPageSource(),null));
initApplicationContext(pc, app);
ap.setName(applicationName);
ap.setSetSessionManagement(true);
//if(!ap.hasName())ap.setName("Controler")
// Base
pc.setBase(app.getPageSource());
return pc;
}
/**
*
* @see railo.runtime.listener.ApplicationListener#onDebug(railo.runtime.PageContext)
*/
public void onDebug(PageContext pc) throws PageException {
if(((PageContextImpl)pc).isGatewayContext()) return;
ComponentAccess app = (ComponentAccess) apps.get(pc.getApplicationContext().getName());
if(app!=null && app.contains(pc,ON_DEBUG)) {
call(app,pc, ON_DEBUG, new Object[]{pc.getDebugger().getDebuggingData()});
return;
}
try {
pc.getDebugger().writeOut(pc);
}
catch (IOException e) {
throw Caster.toPageException(e);
}
}
/**
*
* @see railo.runtime.listener.ApplicationListener#onError(railo.runtime.PageContext, railo.runtime.exp.PageException)
*/
public void onError(PageContext pc, PageException pe) {
ComponentAccess app = (ComponentAccess) apps.get(pc.getApplicationContext().getName());
if(app!=null && app.containsKey(ON_ERROR) && !Abort.isSilentAbort(pe)) {
try {
String eventName="";
if(pe instanceof ModernAppListenerException) eventName= ((ModernAppListenerException)pe).getEventName();
if(eventName==null)eventName="";
call(app,pc, ON_ERROR, new Object[]{pe.getCatchBlock(pc),eventName});
return;
}
catch(PageException _pe) {
pe=_pe;
}
}
pc.handlePageException(pe);
}
private Object call(ComponentPro app, PageContext pc, Collection.Key eventName, Object[] args) throws ModernAppListenerException {
try {
return app.call(pc, eventName, args);
}
catch (PageException pe) {
if(Abort.isSilentAbort(pe)) return Boolean.FALSE;
throw new ModernAppListenerException(pe,eventName.getString());
}
}
private void initApplicationContext(PageContextImpl pc, ComponentAccess app) throws PageException {
// use existing app context
RefBoolean throwsErrorWhileInit=new RefBooleanImpl(false);
ModernApplicationContext appContext = new ModernApplicationContext(pc,app,throwsErrorWhileInit);
pc.setApplicationContext(appContext);
if(appContext.isORMEnabled()) {
boolean hasError=throwsErrorWhileInit.toBooleanValue();
if(hasError)pc.addPageSource(app.getPageSource(), true);
try{
ORMUtil.resetEngine(pc,false);
}
finally {
if(hasError)pc.removeLastPageSource(true);
}
}
}
private static Object get(ComponentAccess app, Key name,String defaultValue) {
Member mem = app.getMember(Component.ACCESS_PRIVATE, name, true, false);
if(mem==null) return defaultValue;
return mem.getValue();
}
/**
*
* @see railo.runtime.listener.ApplicationListener#setMode(int)
*/
public void setMode(int mode) {
this.mode=mode;
}
/**
*
* @see railo.runtime.listener.ApplicationListener#getMode()
*/
public int getMode() {
return mode;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(String type) {
this.type = type;
}
/**
* @see railo.runtime.listener.AppListenerSupport#hasOnSessionStart(railo.runtime.PageContext)
*/
public boolean hasOnSessionStart(PageContext pc) {
return hasOnSessionStart(pc,(ComponentAccess) apps.get(pc.getApplicationContext().getName()));
}
private boolean hasOnSessionStart(PageContext pc,ComponentAccess app) {
return app!=null && app.contains(pc,ON_SESSION_START);
}
}
| true | true | protected void _onRequest(PageContext pc, PageSource requestedPage,PageSource appPS) throws PageException {
PageContextImpl pci = (PageContextImpl)pc;
if(appPS!=null) {
String callPath=appPS.getComponentName();
ComponentAccess app = ComponentLoader.loadComponent(pci,null,appPS, callPath, false,true);
String targetPage=requestedPage.getFullRealpath();
// init
initApplicationContext(pci,app);
apps.put(pc.getApplicationContext().getName(), app);
if(!pci.initApplicationContext()) return;
// onRequestStart
if(app.contains(pc,ON_REQUEST_START)) {
Object rtn=call(app,pci, ON_REQUEST_START, new Object[]{targetPage});
if(!Caster.toBooleanValue(rtn,true))
return;
}
// onRequest
boolean isCFC=ResourceUtil.getExtension(targetPage,"").equalsIgnoreCase(pc.getConfig().getCFCExtension());
Object method;
if(isCFC && app.contains(pc,ON_CFCREQUEST) && (method=pc.urlFormScope().get(ComponentPage.METHOD,null))!=null) {
Struct url = StructUtil.duplicate(pc.urlFormScope(),true);
url.removeEL(KeyImpl.FIELD_NAMES);
url.removeEL(ComponentPage.METHOD);
Object args=url.get(KeyImpl.ARGUMENT_COLLECTION,null);
Object returnFormat=url.removeEL(KeyImpl.RETURN_FORMAT);
Object queryFormat=url.removeEL(ComponentPage.QUERY_FORMAT);
if(args==null){
args=pc.getHttpServletRequest().getAttribute("argumentCollection");
}
if(args instanceof String){
args=new JSONExpressionInterpreter().interpret(pc, (String)args);
}
if(args!=null) {
if(Decision.isCastableToStruct(args)){
Struct sct = Caster.toStruct(args,false);
Key[] keys = url.keys();
for(int i=0;i<keys.length;i++){
sct.setEL(keys[i],url.get(keys[i]));
}
args=sct;
}
else if(Decision.isCastableToArray(args)){
args = Caster.toArray(args);
}
else {
Array arr = new ArrayImpl();
arr.appendEL(args);
args=arr;
}
}
else
args=url;
//print.out("c:"+requestedPage.getComponentName());
//print.out("c:"+requestedPage.getComponentName());
Object rtn = call(app,pci, ON_CFCREQUEST, new Object[]{requestedPage.getComponentName(),method,args});
if(rtn!=null){
if(pc.getHttpServletRequest().getHeader("AMF-Forward")!=null) {
pc.variablesScope().setEL("AMF-Forward", rtn);
//ThreadLocalWDDXResult.set(rtn);
}
else {
try {
pc.forceWrite(ComponentPage.convertResult(pc,app,method.toString(),returnFormat,queryFormat,rtn));
} catch (Exception e) {
throw Caster.toPageException(e);
}
}
}
}
else if(!isCFC && app.contains(pc,ON_REQUEST)) {
call(app,pci, ON_REQUEST, new Object[]{targetPage});
}
else {
// TODO impl die nicht so generisch ist
try{
pci.doInclude(requestedPage);
}
catch(PageException pe){
if(!Abort.isSilentAbort(pe)) {
if(pe instanceof MissingIncludeException){
if(((MissingIncludeException) pe).getPageSource().equals(requestedPage)){
if(app.contains(pc,ON_MISSING_TEMPLATE)) {
if(!Caster.toBooleanValue(call(app,pci, ON_MISSING_TEMPLATE, new Object[]{targetPage}),true))
throw pe;
}
else throw pe;
}
else throw pe;
}
else throw pe;
}
}
}
// onRequestEnd
if(app.contains(pc,ON_REQUEST_END)) {
call(app,pci, ON_REQUEST_END, new Object[]{targetPage});
}
}
else {
apps.put(pc.getApplicationContext().getName(), null);
pc.doInclude(requestedPage);
}
}
| protected void _onRequest(PageContext pc, PageSource requestedPage,PageSource appPS) throws PageException {
PageContextImpl pci = (PageContextImpl)pc;
if(appPS!=null) {
String callPath=appPS.getComponentName();
ComponentAccess app = ComponentLoader.loadComponent(pci,null,appPS, callPath, false,false);
String targetPage=requestedPage.getFullRealpath();
// init
initApplicationContext(pci,app);
apps.put(pc.getApplicationContext().getName(), app);
if(!pci.initApplicationContext()) return;
// onRequestStart
if(app.contains(pc,ON_REQUEST_START)) {
Object rtn=call(app,pci, ON_REQUEST_START, new Object[]{targetPage});
if(!Caster.toBooleanValue(rtn,true))
return;
}
// onRequest
boolean isCFC=ResourceUtil.getExtension(targetPage,"").equalsIgnoreCase(pc.getConfig().getCFCExtension());
Object method;
if(isCFC && app.contains(pc,ON_CFCREQUEST) && (method=pc.urlFormScope().get(ComponentPage.METHOD,null))!=null) {
Struct url = StructUtil.duplicate(pc.urlFormScope(),true);
url.removeEL(KeyImpl.FIELD_NAMES);
url.removeEL(ComponentPage.METHOD);
Object args=url.get(KeyImpl.ARGUMENT_COLLECTION,null);
Object returnFormat=url.removeEL(KeyImpl.RETURN_FORMAT);
Object queryFormat=url.removeEL(ComponentPage.QUERY_FORMAT);
if(args==null){
args=pc.getHttpServletRequest().getAttribute("argumentCollection");
}
if(args instanceof String){
args=new JSONExpressionInterpreter().interpret(pc, (String)args);
}
if(args!=null) {
if(Decision.isCastableToStruct(args)){
Struct sct = Caster.toStruct(args,false);
Key[] keys = url.keys();
for(int i=0;i<keys.length;i++){
sct.setEL(keys[i],url.get(keys[i]));
}
args=sct;
}
else if(Decision.isCastableToArray(args)){
args = Caster.toArray(args);
}
else {
Array arr = new ArrayImpl();
arr.appendEL(args);
args=arr;
}
}
else
args=url;
//print.out("c:"+requestedPage.getComponentName());
//print.out("c:"+requestedPage.getComponentName());
Object rtn = call(app,pci, ON_CFCREQUEST, new Object[]{requestedPage.getComponentName(),method,args});
if(rtn!=null){
if(pc.getHttpServletRequest().getHeader("AMF-Forward")!=null) {
pc.variablesScope().setEL("AMF-Forward", rtn);
//ThreadLocalWDDXResult.set(rtn);
}
else {
try {
pc.forceWrite(ComponentPage.convertResult(pc,app,method.toString(),returnFormat,queryFormat,rtn));
} catch (Exception e) {
throw Caster.toPageException(e);
}
}
}
}
else if(!isCFC && app.contains(pc,ON_REQUEST)) {
call(app,pci, ON_REQUEST, new Object[]{targetPage});
}
else {
// TODO impl die nicht so generisch ist
try{
pci.doInclude(requestedPage);
}
catch(PageException pe){
if(!Abort.isSilentAbort(pe)) {
if(pe instanceof MissingIncludeException){
if(((MissingIncludeException) pe).getPageSource().equals(requestedPage)){
if(app.contains(pc,ON_MISSING_TEMPLATE)) {
if(!Caster.toBooleanValue(call(app,pci, ON_MISSING_TEMPLATE, new Object[]{targetPage}),true))
throw pe;
}
else throw pe;
}
else throw pe;
}
else throw pe;
}
}
}
// onRequestEnd
if(app.contains(pc,ON_REQUEST_END)) {
call(app,pci, ON_REQUEST_END, new Object[]{targetPage});
}
}
else {
apps.put(pc.getApplicationContext().getName(), null);
pc.doInclude(requestedPage);
}
}
|
diff --git a/src/main/java/org/esa/beam/dataViewer3D/data/color/HSVColorProvider.java b/src/main/java/org/esa/beam/dataViewer3D/data/color/HSVColorProvider.java
index 0815074..c11ffad 100644
--- a/src/main/java/org/esa/beam/dataViewer3D/data/color/HSVColorProvider.java
+++ b/src/main/java/org/esa/beam/dataViewer3D/data/color/HSVColorProvider.java
@@ -1,23 +1,25 @@
/**
*
*/
package org.esa.beam.dataViewer3D.data.color;
import java.awt.Color;
/**
* A color provider returning colors based on HSV spectrum.
*
* @author Martin Pecka
*/
public class HSVColorProvider extends AbstractColorProvider
{
@Override
public Color getColor(double sample, double weight)
{
final double val = (sample < min ? min : (sample > max ? max : sample));
- return Color.getHSBColor((float) ((val - min) / difference), 1f, (float) weight);
+ // we scale the hue to interval [0, 0.8], because if it would go up to 1.0, the color for min and max would be
+ // the same
+ return Color.getHSBColor((float) ((val - min) / difference) * 0.8f, 1f, (float) weight);
}
}
| true | true | public Color getColor(double sample, double weight)
{
final double val = (sample < min ? min : (sample > max ? max : sample));
return Color.getHSBColor((float) ((val - min) / difference), 1f, (float) weight);
}
| public Color getColor(double sample, double weight)
{
final double val = (sample < min ? min : (sample > max ? max : sample));
// we scale the hue to interval [0, 0.8], because if it would go up to 1.0, the color for min and max would be
// the same
return Color.getHSBColor((float) ((val - min) / difference) * 0.8f, 1f, (float) weight);
}
|
diff --git a/update/org.eclipse.update.configurator/src/org/eclipse/update/internal/configurator/branding/AboutInfo.java b/update/org.eclipse.update.configurator/src/org/eclipse/update/internal/configurator/branding/AboutInfo.java
index a3a7a31bc..dd2b59fc1 100644
--- a/update/org.eclipse.update.configurator/src/org/eclipse/update/internal/configurator/branding/AboutInfo.java
+++ b/update/org.eclipse.update.configurator/src/org/eclipse/update/internal/configurator/branding/AboutInfo.java
@@ -1,253 +1,254 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.update.internal.configurator.branding;
import java.net.*;
import java.util.*;
import org.eclipse.core.runtime.*;
/**
* The information within this object is obtained from the about INI file.
* This file resides within an install configurations directory and must be a
* standard java property file.
* <p>
* This class is not intended to be instantiated or subclassed by clients.
* </p>
*/
public final class AboutInfo {
private final static String INI_FILENAME = "about.ini"; //$NON-NLS-1$
private final static String PROPERTIES_FILENAME = "about.properties"; //$NON-NLS-1$
private final static String MAPPINGS_FILENAME = "about.mappings"; //$NON-NLS-1$
private String featureId;
private String versionId = ""; //$NON-NLS-1$
private String featurePluginLabel;
private String providerName;
private String appName;
private URL windowImageURL;
private URL[] windowImagesURLs;
private URL aboutImageURL;
private URL featureImageURL;
private URL welcomePageURL;
private String aboutText;
private String welcomePerspective;
private String tipsAndTricksHref;
/*
* Create a new about info for a feature with the given id.
*/
/* package */ AboutInfo(String featureId) {
super();
this.featureId = featureId;
}
/**
* Returns the configuration information for the feature with the
* given id.
*
* @param featureId the feature id
* @param versionId the version id (of the feature)
* @param pluginId the plug-in id
* @return the configuration information for the feature
*/
public static AboutInfo readFeatureInfo(String featureId, String versionId, String pluginId) {
// Assert.isNotNull(featureId);
// Assert.isNotNull(versionId);
// Assert.isNotNull(pluginId);
IniFileReader reader = new IniFileReader(featureId, pluginId, INI_FILENAME, PROPERTIES_FILENAME, MAPPINGS_FILENAME);
IStatus status = reader.load();
- if (!status.isOK()) {
- //return null;
- return new AboutInfo(featureId); // dummy about info
- }
+// bug 78031
+// if (!status.isOK()) {
+// //return null;
+// return new AboutInfo(featureId); // dummy about info
+// }
AboutInfo info = new AboutInfo(featureId);
Hashtable runtimeMappings = new Hashtable();
runtimeMappings.put("{featureVersion}", versionId); //$NON-NLS-1$
info.versionId = versionId;
info.featurePluginLabel = reader.getFeaturePluginLabel();
info.providerName = reader.getProviderName();
info.appName = reader.getString("appName", true, runtimeMappings); //$NON-NLS-1$
info.aboutText = reader.getString("aboutText", true, runtimeMappings); //$NON-NLS-1$
info.windowImageURL = reader.getURL("windowImage"); //$NON-NLS-1$
// look for the newer array, but if its not there then use the older,
// single image definition
info.windowImagesURLs = reader.getURLs("windowImages"); //$NON-NLS-1$
info.aboutImageURL = reader.getURL("aboutImage"); //$NON-NLS-1$
info.featureImageURL = reader.getURL("featureImage"); //$NON-NLS-1$
info.welcomePageURL = reader.getURL("welcomePage"); //$NON-NLS-1$
info.welcomePerspective = reader.getString("welcomePerspective", false, runtimeMappings); //$NON-NLS-1$
info.tipsAndTricksHref = reader.getString("tipsAndTricksHref", false, runtimeMappings); //$NON-NLS-1$
return info;
}
/**
* Returns the URL for an image which can be shown in an "about" dialog
* for this product. Products designed to run "headless" typically would not
* have such an image.
*
* @return the URL for an about image, or <code>null</code> if none
*/
public URL getAboutImageURL() {
return aboutImageURL;
}
/**
* Returns the URL for an image which can be shown in an "about features"
* dialog. Products designed to run "headless" typically would not have such an image.
*
* @return the URL for a feature image, or <code>null</code> if none
*/
public URL getFeatureImageURL() {
return featureImageURL;
}
/**
* Returns the simple name of the feature image file.
*
* @return the simple name of the feature image file,
* or <code>null</code> if none
*/
public String getFeatureImageName() {
if (featureImageURL != null) {
IPath path = new Path(featureImageURL.getPath());
return path.lastSegment();
} else {
return null;
}
}
/**
* Returns a label for the feature plugn, or <code>null</code>.
*/
public String getFeatureLabel() {
return featurePluginLabel;
}
/**
* Returns the id for this feature.
*
* @return the feature id
*/
public String getFeatureId() {
return featureId;
}
/**
* Returns the text to show in an "about" dialog for this product.
* Products designed to run "headless" typically would not have such text.
*
* @return the about text, or <code>null</code> if none
*/
public String getAboutText() {
return aboutText;
}
/**
* Returns the application name or <code>null</code>.
* Note this is never shown to the user.
* It is used to initialize the SWT Display.
* <p>
* On Motif, for example, this can be used
* to set the name used for resource lookup.
* </p>
*
* @return the application name, or <code>null</code>
*/
public String getAppName() {
return appName;
}
/**
* Returns the product name or <code>null</code>.
* This is shown in the window title and the About action.
*
* @return the product name, or <code>null</code>
*/
public String getProductName() {
return featurePluginLabel;
}
/**
* Returns the provider name or <code>null</code>.
*
* @return the provider name, or <code>null</code>
*/
public String getProviderName() {
return providerName;
}
/**
* Returns the feature version id.
*
* @return the version id of the feature
*/
public String getVersionId() {
return versionId;
}
/**
* Returns a <code>URL</code> for the welcome page.
* Products designed to run "headless" typically would not have such an page.
*
* @return the welcome page, or <code>null</code> if none
*/
public URL getWelcomePageURL() {
return welcomePageURL;
}
/**
* Returns the ID of a perspective in which to show the welcome page.
* May be <code>null</code>.
*
* @return the welcome page perspective id, or <code>null</code> if none
*/
public String getWelcomePerspectiveId() {
return welcomePerspective;
}
/**
* Returns a <code>String</code> for the tips and trick href.
*
* @return the tips and tricks href, or <code>null</code> if none
*/
public String getTipsAndTricksHref() {
return tipsAndTricksHref;
}
/**
* Returns the image url for the window image to use for this product.
* Products designed to run "headless" typically would not have such an image.
*
* @return the image url for the window image, or <code>null</code> if none
*/
public URL getWindowImageURL() {
return windowImageURL;
}
/**
* Return an array of image URLs for the window images to use for
* this product. The expectations is that the elements will be the same
* image rendered at different sizes. Products designed to run "headless"
* typically would not have such images.
*
* @return an array of the image descriptors for the window images, or
* <code>null</code> if none
* @since 3.0
*/
public URL[] getWindowImagesURLs() {
return windowImagesURLs;
}
}
| true | true | public static AboutInfo readFeatureInfo(String featureId, String versionId, String pluginId) {
// Assert.isNotNull(featureId);
// Assert.isNotNull(versionId);
// Assert.isNotNull(pluginId);
IniFileReader reader = new IniFileReader(featureId, pluginId, INI_FILENAME, PROPERTIES_FILENAME, MAPPINGS_FILENAME);
IStatus status = reader.load();
if (!status.isOK()) {
//return null;
return new AboutInfo(featureId); // dummy about info
}
AboutInfo info = new AboutInfo(featureId);
Hashtable runtimeMappings = new Hashtable();
runtimeMappings.put("{featureVersion}", versionId); //$NON-NLS-1$
info.versionId = versionId;
info.featurePluginLabel = reader.getFeaturePluginLabel();
info.providerName = reader.getProviderName();
info.appName = reader.getString("appName", true, runtimeMappings); //$NON-NLS-1$
info.aboutText = reader.getString("aboutText", true, runtimeMappings); //$NON-NLS-1$
info.windowImageURL = reader.getURL("windowImage"); //$NON-NLS-1$
// look for the newer array, but if its not there then use the older,
// single image definition
info.windowImagesURLs = reader.getURLs("windowImages"); //$NON-NLS-1$
info.aboutImageURL = reader.getURL("aboutImage"); //$NON-NLS-1$
info.featureImageURL = reader.getURL("featureImage"); //$NON-NLS-1$
info.welcomePageURL = reader.getURL("welcomePage"); //$NON-NLS-1$
info.welcomePerspective = reader.getString("welcomePerspective", false, runtimeMappings); //$NON-NLS-1$
info.tipsAndTricksHref = reader.getString("tipsAndTricksHref", false, runtimeMappings); //$NON-NLS-1$
return info;
}
| public static AboutInfo readFeatureInfo(String featureId, String versionId, String pluginId) {
// Assert.isNotNull(featureId);
// Assert.isNotNull(versionId);
// Assert.isNotNull(pluginId);
IniFileReader reader = new IniFileReader(featureId, pluginId, INI_FILENAME, PROPERTIES_FILENAME, MAPPINGS_FILENAME);
IStatus status = reader.load();
// bug 78031
// if (!status.isOK()) {
// //return null;
// return new AboutInfo(featureId); // dummy about info
// }
AboutInfo info = new AboutInfo(featureId);
Hashtable runtimeMappings = new Hashtable();
runtimeMappings.put("{featureVersion}", versionId); //$NON-NLS-1$
info.versionId = versionId;
info.featurePluginLabel = reader.getFeaturePluginLabel();
info.providerName = reader.getProviderName();
info.appName = reader.getString("appName", true, runtimeMappings); //$NON-NLS-1$
info.aboutText = reader.getString("aboutText", true, runtimeMappings); //$NON-NLS-1$
info.windowImageURL = reader.getURL("windowImage"); //$NON-NLS-1$
// look for the newer array, but if its not there then use the older,
// single image definition
info.windowImagesURLs = reader.getURLs("windowImages"); //$NON-NLS-1$
info.aboutImageURL = reader.getURL("aboutImage"); //$NON-NLS-1$
info.featureImageURL = reader.getURL("featureImage"); //$NON-NLS-1$
info.welcomePageURL = reader.getURL("welcomePage"); //$NON-NLS-1$
info.welcomePerspective = reader.getString("welcomePerspective", false, runtimeMappings); //$NON-NLS-1$
info.tipsAndTricksHref = reader.getString("tipsAndTricksHref", false, runtimeMappings); //$NON-NLS-1$
return info;
}
|
diff --git a/src/com/dmdirc/addons/ui_swing/dialogs/aliases/AliasManagerLinker.java b/src/com/dmdirc/addons/ui_swing/dialogs/aliases/AliasManagerLinker.java
index 524db08c..5c2c3bd3 100644
--- a/src/com/dmdirc/addons/ui_swing/dialogs/aliases/AliasManagerLinker.java
+++ b/src/com/dmdirc/addons/ui_swing/dialogs/aliases/AliasManagerLinker.java
@@ -1,326 +1,338 @@
/*
* Copyright (c) 2006-2014 DMDirc Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.dmdirc.addons.ui_swing.dialogs.aliases;
import com.dmdirc.addons.ui_swing.components.GenericTableModel;
import com.dmdirc.addons.ui_swing.components.vetoable.VetoableListSelectionModel;
import com.dmdirc.addons.ui_swing.dialogs.StandardInputDialog;
import com.dmdirc.commandparser.aliases.Alias;
import com.dmdirc.ui.IconManager;
import com.google.common.base.Optional;
import java.awt.Dialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import javax.swing.JButton;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
/**
* Links the Alias Manager Dialog with its controller and model.
*/
public class AliasManagerLinker {
private final AliasManagerController controller;
private final AliasManagerModel model;
private final AliasManagerDialog dialog;
private final IconManager iconManager;
public AliasManagerLinker(final AliasManagerController controller,
final AliasManagerModel model,
final AliasManagerDialog dialog,
final IconManager iconManager) {
this.controller = controller;
this.model = model;
this.dialog = dialog;
this.iconManager = iconManager;
}
public void bindCommandList(final JTable commandList) {
final GenericTableModel<Alias> commandModel = new GenericTableModel<>(
Alias.class, "getName", "getMinArguments", "getSubstitution");
commandModel.setHeaderNames("Name", "Minimum Arguments", "Substitution");
commandList.setModel(commandModel);
commandList.setSelectionModel(new VetoableListSelectionModel());
((VetoableListSelectionModel) commandList.getSelectionModel()).addVetoableSelectionListener(
new VetoableChangeListener() {
@Override
public void vetoableChange(final PropertyChangeEvent evt) throws
PropertyVetoException {
if ((Integer) evt.getNewValue() == -1) {
throw new PropertyVetoException("Blank selection not allowed", evt);
}
}
});
commandList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(final ListSelectionEvent e) {
final int index = commandList.getSelectedRow();
if (index == -1) {
model.setSelectedAlias(Optional.<Alias>absent());
+ } else if (index >= commandModel.getRowCount()) {
+ model.setSelectedAlias(Optional.fromNullable(commandModel.getValue(index - 1)));
} else {
model.setSelectedAlias(Optional.fromNullable(commandModel.getValue(index)));
}
}
});
model.addPropertyChangeListener("aliases", new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
for (Alias alias : model.getAliases()) {
commandModel.addValue(alias);
}
if (commandModel.getRowCount() > 0) {
commandList.getSelectionModel().setLeadSelectionIndex(0);
}
}
});
model.addPropertyChangeListener("editAlias", new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
if (evt.getNewValue() != null) {
final Alias oldAlias = (Alias) evt.getOldValue();
final Alias newAlias = (Alias) evt.getNewValue();
final int oldIndex = commandModel.getIndex(oldAlias);
commandModel.replaceValueAt(newAlias, oldIndex);
}
}
});
model.addPropertyChangeListener("renameAlias", new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
if (evt.getNewValue() != null) {
final Alias oldAlias = (Alias) evt.getOldValue();
final Alias newAlias = (Alias) evt.getNewValue();
final int oldIndex = commandModel.getIndex(oldAlias);
commandModel.replaceValueAt(newAlias, oldIndex);
}
}
});
model.addPropertyChangeListener("deleteAlias", new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
if (evt.getOldValue() != null) {
commandModel.removeValue((Alias) evt.getOldValue());
+ final int index = commandList.getSelectedRow();
+ if (index == -1) {
+ model.setSelectedAlias(Optional.<Alias>absent());
+ } else if (index >= commandModel.getRowCount()) {
+ model.setSelectedAlias(Optional.fromNullable(commandModel.
+ getValue(index - 1)));
+ commandList.getSelectionModel().setLeadSelectionIndex(index - 1);
+ } else {
+ model.setSelectedAlias(Optional.fromNullable(commandModel.getValue(index)));
+ }
}
}
});
model.addPropertyChangeListener("addAlias", new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
if (evt.getNewValue() != null) {
final Alias alias = (Alias) evt.getNewValue();
commandModel.addValue(alias);
commandList.getSelectionModel().setSelectionInterval(
commandModel.getIndex(alias), commandModel.getIndex(alias));
}
}
});
}
public void bindCommand(final JTextField command) {
command.setEnabled(false);
model.addPropertyChangeListener("selectedAlias", new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
final Optional<Alias> selectedAlias = model.getSelectedAlias();
command.setEnabled(selectedAlias.isPresent());
command.setText(model.getName());
}
});
command.getDocument().addDocumentListener(new DocumentListener() {
private void update() {
model.setName(command.getText());
}
@Override
public void insertUpdate(final DocumentEvent e) {
update();
}
@Override
public void removeUpdate(final DocumentEvent e) {
update();
}
@Override
public void changedUpdate(final DocumentEvent e) {
update();
}
});
}
public void bindArgumentsNumber(final JSpinner argumentsNumber) {
argumentsNumber.setEnabled(false);
argumentsNumber.setModel(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 1));
model.addPropertyChangeListener("selectedAlias", new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
final Optional<Alias> selectedAlias = model.getSelectedAlias();
argumentsNumber.setEnabled(selectedAlias.isPresent());
if (selectedAlias.isPresent()) {
argumentsNumber.setValue(model.getSelectedAlias().get().getMinArguments());
} else {
argumentsNumber.setValue(0);
}
}
});
argumentsNumber.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(final ChangeEvent e) {
model.setMinimumArguments((Integer) argumentsNumber.getValue());
}
});
}
public void bindResponse(final JTextArea response) {
response.setEnabled(false);
model.addPropertyChangeListener("selectedAlias", new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
final Optional<Alias> selectedAlias = model.getSelectedAlias();
response.setEnabled(selectedAlias.isPresent());
if (selectedAlias.isPresent()) {
response.setText(model.getSelectedAlias().get().getSubstitution());
} else {
response.setText("");
}
}
});
response.getDocument().addDocumentListener(new DocumentListener() {
private void update() {
model.setSubstitution(response.getText());
}
@Override
public void insertUpdate(final DocumentEvent e) {
update();
}
@Override
public void removeUpdate(final DocumentEvent e) {
update();
}
@Override
public void changedUpdate(final DocumentEvent e) {
update();
}
});
}
public void bindAddAlias(final JButton addAlias) {
addAlias.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
new StandardInputDialog(dialog, Dialog.ModalityType.DOCUMENT_MODAL, iconManager,
"Add Alias", "Enter the alias name", model.getNewCommandValidator()) {
private static final long serialVersionUID = 3;
@Override
public boolean save() {
model.addAlias(getText(), 0, "");
return true;
}
@Override
public void cancelled() {
}
}.display();
}
});
}
public void bindDeleteAlias(final JButton deleteAlias) {
deleteAlias.setEnabled(false);
model.addPropertyChangeListener("selectedAlias", new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
final Optional<Alias> alias = model.getSelectedAlias();
deleteAlias.setEnabled(alias.isPresent());
}
});
deleteAlias.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final Optional<Alias> alias = model.getSelectedAlias();
if (alias.isPresent()) {
model.removeAlias(alias.get().getName());
}
}
});
}
public void bindOKButton(final JButton okButton) {
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
controller.saveAndCloseDialog();
}
});
}
public void bindCancelButton(final JButton cancelButton) {
cancelButton.setEnabled(true);
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
controller.discardAndCloseDialog();
}
});
}
}
| false | true | public void bindCommandList(final JTable commandList) {
final GenericTableModel<Alias> commandModel = new GenericTableModel<>(
Alias.class, "getName", "getMinArguments", "getSubstitution");
commandModel.setHeaderNames("Name", "Minimum Arguments", "Substitution");
commandList.setModel(commandModel);
commandList.setSelectionModel(new VetoableListSelectionModel());
((VetoableListSelectionModel) commandList.getSelectionModel()).addVetoableSelectionListener(
new VetoableChangeListener() {
@Override
public void vetoableChange(final PropertyChangeEvent evt) throws
PropertyVetoException {
if ((Integer) evt.getNewValue() == -1) {
throw new PropertyVetoException("Blank selection not allowed", evt);
}
}
});
commandList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(final ListSelectionEvent e) {
final int index = commandList.getSelectedRow();
if (index == -1) {
model.setSelectedAlias(Optional.<Alias>absent());
} else {
model.setSelectedAlias(Optional.fromNullable(commandModel.getValue(index)));
}
}
});
model.addPropertyChangeListener("aliases", new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
for (Alias alias : model.getAliases()) {
commandModel.addValue(alias);
}
if (commandModel.getRowCount() > 0) {
commandList.getSelectionModel().setLeadSelectionIndex(0);
}
}
});
model.addPropertyChangeListener("editAlias", new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
if (evt.getNewValue() != null) {
final Alias oldAlias = (Alias) evt.getOldValue();
final Alias newAlias = (Alias) evt.getNewValue();
final int oldIndex = commandModel.getIndex(oldAlias);
commandModel.replaceValueAt(newAlias, oldIndex);
}
}
});
model.addPropertyChangeListener("renameAlias", new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
if (evt.getNewValue() != null) {
final Alias oldAlias = (Alias) evt.getOldValue();
final Alias newAlias = (Alias) evt.getNewValue();
final int oldIndex = commandModel.getIndex(oldAlias);
commandModel.replaceValueAt(newAlias, oldIndex);
}
}
});
model.addPropertyChangeListener("deleteAlias", new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
if (evt.getOldValue() != null) {
commandModel.removeValue((Alias) evt.getOldValue());
}
}
});
model.addPropertyChangeListener("addAlias", new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
if (evt.getNewValue() != null) {
final Alias alias = (Alias) evt.getNewValue();
commandModel.addValue(alias);
commandList.getSelectionModel().setSelectionInterval(
commandModel.getIndex(alias), commandModel.getIndex(alias));
}
}
});
}
| public void bindCommandList(final JTable commandList) {
final GenericTableModel<Alias> commandModel = new GenericTableModel<>(
Alias.class, "getName", "getMinArguments", "getSubstitution");
commandModel.setHeaderNames("Name", "Minimum Arguments", "Substitution");
commandList.setModel(commandModel);
commandList.setSelectionModel(new VetoableListSelectionModel());
((VetoableListSelectionModel) commandList.getSelectionModel()).addVetoableSelectionListener(
new VetoableChangeListener() {
@Override
public void vetoableChange(final PropertyChangeEvent evt) throws
PropertyVetoException {
if ((Integer) evt.getNewValue() == -1) {
throw new PropertyVetoException("Blank selection not allowed", evt);
}
}
});
commandList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(final ListSelectionEvent e) {
final int index = commandList.getSelectedRow();
if (index == -1) {
model.setSelectedAlias(Optional.<Alias>absent());
} else if (index >= commandModel.getRowCount()) {
model.setSelectedAlias(Optional.fromNullable(commandModel.getValue(index - 1)));
} else {
model.setSelectedAlias(Optional.fromNullable(commandModel.getValue(index)));
}
}
});
model.addPropertyChangeListener("aliases", new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
for (Alias alias : model.getAliases()) {
commandModel.addValue(alias);
}
if (commandModel.getRowCount() > 0) {
commandList.getSelectionModel().setLeadSelectionIndex(0);
}
}
});
model.addPropertyChangeListener("editAlias", new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
if (evt.getNewValue() != null) {
final Alias oldAlias = (Alias) evt.getOldValue();
final Alias newAlias = (Alias) evt.getNewValue();
final int oldIndex = commandModel.getIndex(oldAlias);
commandModel.replaceValueAt(newAlias, oldIndex);
}
}
});
model.addPropertyChangeListener("renameAlias", new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
if (evt.getNewValue() != null) {
final Alias oldAlias = (Alias) evt.getOldValue();
final Alias newAlias = (Alias) evt.getNewValue();
final int oldIndex = commandModel.getIndex(oldAlias);
commandModel.replaceValueAt(newAlias, oldIndex);
}
}
});
model.addPropertyChangeListener("deleteAlias", new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
if (evt.getOldValue() != null) {
commandModel.removeValue((Alias) evt.getOldValue());
final int index = commandList.getSelectedRow();
if (index == -1) {
model.setSelectedAlias(Optional.<Alias>absent());
} else if (index >= commandModel.getRowCount()) {
model.setSelectedAlias(Optional.fromNullable(commandModel.
getValue(index - 1)));
commandList.getSelectionModel().setLeadSelectionIndex(index - 1);
} else {
model.setSelectedAlias(Optional.fromNullable(commandModel.getValue(index)));
}
}
}
});
model.addPropertyChangeListener("addAlias", new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
if (evt.getNewValue() != null) {
final Alias alias = (Alias) evt.getNewValue();
commandModel.addValue(alias);
commandList.getSelectionModel().setSelectionInterval(
commandModel.getIndex(alias), commandModel.getIndex(alias));
}
}
});
}
|
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/dispatchers/SubsequentRequestDispatcher.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/dispatchers/SubsequentRequestDispatcher.java
index 354c9e8cf..ce9adf616 100644
--- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/dispatchers/SubsequentRequestDispatcher.java
+++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/dispatchers/SubsequentRequestDispatcher.java
@@ -1,285 +1,285 @@
/*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.mobicents.servlet.sip.core.dispatchers;
import gov.nist.javax.sip.header.CSeq;
import gov.nist.javax.sip.header.extensions.JoinHeader;
import gov.nist.javax.sip.header.extensions.ReplacesHeader;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.sip.ProxyBranch;
import javax.servlet.sip.SipServletResponse;
import javax.sip.Dialog;
import javax.sip.SipException;
import javax.sip.SipProvider;
import javax.sip.header.CSeqHeader;
import javax.sip.header.Parameters;
import javax.sip.header.RouteHeader;
import javax.sip.header.SubscriptionStateHeader;
import javax.sip.header.ToHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;
import org.apache.log4j.Logger;
import org.mobicents.servlet.sip.core.ApplicationRoutingHeaderComposer;
import org.mobicents.servlet.sip.core.SipApplicationDispatcher;
import org.mobicents.servlet.sip.core.session.MobicentsSipApplicationSession;
import org.mobicents.servlet.sip.core.session.MobicentsSipSession;
import org.mobicents.servlet.sip.core.session.SessionManagerUtil;
import org.mobicents.servlet.sip.core.session.SipApplicationSessionKey;
import org.mobicents.servlet.sip.core.session.SipManager;
import org.mobicents.servlet.sip.core.session.SipSessionKey;
import org.mobicents.servlet.sip.message.SipFactoryImpl;
import org.mobicents.servlet.sip.message.SipServletMessageImpl;
import org.mobicents.servlet.sip.message.SipServletRequestImpl;
import org.mobicents.servlet.sip.proxy.ProxyBranchImpl;
import org.mobicents.servlet.sip.proxy.ProxyImpl;
import org.mobicents.servlet.sip.startup.SipContext;
/**
* This class is responsible for routing and dispatching subsequent request to applications according to JSR 289 Section
* 15.6 Responses, Subsequent Requests and Application Path
*
* It uses route header parameters for proxy apps or to tag parameter for UAS/B2BUA apps
* that were previously set by the container on
* record route headers or to tag to know which app has to be called
*
* @author <A HREF="mailto:[email protected]">Jean Deruelle</A>
*
*/
public class SubsequentRequestDispatcher extends RequestDispatcher {
private static transient Logger logger = Logger.getLogger(SubsequentRequestDispatcher.class);
public SubsequentRequestDispatcher(
SipApplicationDispatcher sipApplicationDispatcher) {
super(sipApplicationDispatcher);
}
/**
* {@inheritDoc}
*/
public void dispatchMessage(final SipProvider sipProvider, SipServletMessageImpl sipServletMessage) throws DispatcherException {
final SipFactoryImpl sipFactoryImpl = sipApplicationDispatcher.getSipFactory();
final SipServletRequestImpl sipServletRequest = (SipServletRequestImpl) sipServletMessage;
if(logger.isDebugEnabled()) {
logger.debug("Routing of Subsequent Request " + sipServletRequest);
}
final Request request = (Request) sipServletRequest.getMessage();
final Dialog dialog = sipServletRequest.getDialog();
final RouteHeader poppedRouteHeader = sipServletRequest.getPoppedRouteHeader();
String applicationName = null;
String applicationId = null;
if(poppedRouteHeader != null){
final Parameters poppedAddress = (Parameters)poppedRouteHeader.getAddress().getURI();
//Extract information from the Route Header
final String applicationNameHashed = poppedAddress.getParameter(RR_PARAM_APPLICATION_NAME);
if(applicationNameHashed != null && applicationNameHashed.length() > 0) {
applicationName = sipApplicationDispatcher.getApplicationNameFromHash(applicationNameHashed);
applicationId = poppedAddress.getParameter(APP_ID);
}
}
if(applicationId == null) {
final ToHeader toHeader = (ToHeader) request.getHeader(ToHeader.NAME);
final String arText = toHeader.getTag();
final String[] tuple = ApplicationRoutingHeaderComposer.getAppNameAndSessionId(sipApplicationDispatcher, arText);
applicationName = tuple[0];
applicationId = tuple[1];
if(Request.ACK.equals(request.getMethod()) && applicationId == null && applicationName == null) {
//Means that this is an ACK to a container generated error response, so we can drop it
if(logger.isDebugEnabled()) {
logger.debug("The popped Route, application Id and name are null for an ACK, so this is an ACK to a container generated error response, so it is dropped");
}
return ;
}
}
boolean inverted = false;
if(dialog != null && !dialog.isServer()) {
inverted = true;
}
final SipContext sipContext = sipApplicationDispatcher.findSipApplication(applicationName);
if(sipContext == null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request +
"in this popped routed header " + poppedRouteHeader);
}
final SipManager sipManager = (SipManager)sipContext.getManager();
SipApplicationSessionKey sipApplicationSessionKey = SessionManagerUtil.getSipApplicationSessionKey(
applicationName,
applicationId);
MobicentsSipSession tmpSipSession = null;
MobicentsSipApplicationSession sipApplicationSession = sipManager.getSipApplicationSession(sipApplicationSessionKey, false);
if(sipApplicationSession == null) {
if(logger.isDebugEnabled()) {
sipManager.dumpSipApplicationSessions();
}
//trying the join or replaces matching sip app sessions
final SipApplicationSessionKey joinSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, JoinHeader.NAME);
final SipApplicationSessionKey replacesSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, ReplacesHeader.NAME);
if(joinSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(joinSipApplicationSessionKey, false);
sipApplicationSessionKey = joinSipApplicationSessionKey;
} else if(replacesSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(replacesSipApplicationSessionKey, false);
sipApplicationSessionKey = replacesSipApplicationSessionKey;
}
if(sipApplicationSession == null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip application session to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
}
}
SipSessionKey key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, inverted);
if(logger.isDebugEnabled()) {
logger.debug("Trying to find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
}
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
// Added by Vladimir because the inversion detection on proxied requests doesn't work
if(tmpSipSession == null) {
if(logger.isDebugEnabled()) {
logger.debug("Cannot find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute() + ". Trying inverted.");
}
key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, !inverted);
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
}
if(tmpSipSession == null) {
sipManager.dumpSipSessions();
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
} else {
if(logger.isDebugEnabled()) {
logger.debug("Inverted try worked. sip session found : " + tmpSipSession.getId());
}
}
final MobicentsSipSession sipSession = tmpSipSession;
sipServletRequest.setSipSession(sipSession);
// BEGIN validation delegated to the applicationas per JSIP patch for http://code.google.com/p/mobicents/issues/detail?id=766
if(request.getMethod().equalsIgnoreCase("ACK")) {
if(sipSession.isAckReceived()) {
- // Filter out ACK retransmissions as per changes in
+ // Filter out ACK retransmissions for JSIP patch for http://code.google.com/p/mobicents/issues/detail?id=766
logger.debug("ACK filtered out as a retransmission. This Sip Session already has been ACKed.");
return;
}
sipSession.setAckReceived(true);
}
CSeqHeader cseq = (CSeqHeader) request.getHeader(CSeqHeader.NAME);
long localCseq = sipSession.getCseq();
long remoteCseq = cseq.getSeqNumber();
if(localCseq>remoteCseq) {
logger.error("CSeq out of order for the following request");
SipServletResponse response = sipServletRequest.createResponse(500, "CSeq out of order");
try {
response.send();
} catch (IOException e) {
logger.error("Can not send error response", e);
}
}
sipSession.setCseq(remoteCseq);
// END of validation for http://code.google.com/p/mobicents/issues/detail?id=766
DispatchTask dispatchTask = new DispatchTask(sipServletRequest, sipProvider) {
public void dispatch() throws DispatcherException {
sipContext.enterSipApp(sipServletRequest, null, sipManager, true, true);
final String requestMethod = sipServletRequest.getMethod();
final SubscriptionStateHeader subscriptionStateHeader = (SubscriptionStateHeader)
sipServletRequest.getMessage().getHeader(SubscriptionStateHeader.NAME);
try {
sipSession.setSessionCreatingTransaction(sipServletRequest.getTransaction());
// JSR 289 Section 6.2.1 :
// any state transition caused by the reception of a SIP message,
// the state change must be accomplished by the container before calling
// the service() method of any SipServlet to handle the incoming message.
sipSession.updateStateOnSubsequentRequest(sipServletRequest, true);
try {
// RFC 3265 : If a matching NOTIFY request contains a "Subscription-State" of "active" or "pending", it creates
// a new subscription and a new dialog (unless they have already been
// created by a matching response, as described above).
if(Request.NOTIFY.equals(requestMethod) &&
(subscriptionStateHeader != null &&
SubscriptionStateHeader.ACTIVE.equalsIgnoreCase(subscriptionStateHeader.getState()) ||
SubscriptionStateHeader.PENDING.equalsIgnoreCase(subscriptionStateHeader.getState()))) {
sipSession.addSubscription(sipServletRequest);
}
// See if the subsequent request should go directly to the proxy
final ProxyImpl proxy = sipSession.getProxy();
if(proxy != null) {
final ProxyBranchImpl finalBranch = proxy.getFinalBranchForSubsequentRequests();
if(finalBranch != null) {
proxy.setAckReceived(requestMethod.equalsIgnoreCase(Request.ACK));
proxy.setOriginalRequest(sipServletRequest);
callServlet(sipServletRequest);
finalBranch.proxySubsequentRequest(sipServletRequest);
} else if(requestMethod.equals(Request.PRACK)) {
callServlet(sipServletRequest);
List<ProxyBranch> branches = proxy.getProxyBranches();
for(ProxyBranch pb : branches) {
ProxyBranchImpl proxyBranch = (ProxyBranchImpl) pb;
if(proxyBranch.isWaitingForPrack()) {
proxyBranch.proxyDialogStateless(sipServletRequest);
proxyBranch.setWaitingForPrack(false);
}
}
}
}
// If it's not for a proxy then it's just an AR, so go to the next application
else {
callServlet(sipServletRequest);
}
} catch (ServletException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
} catch (SipException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
} catch (IOException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
}
} finally {
// A subscription is destroyed when a notifier sends a NOTIFY request
// with a "Subscription-State" of "terminated".
if(Request.NOTIFY.equals(requestMethod) &&
(subscriptionStateHeader != null &&
SubscriptionStateHeader.TERMINATED.equalsIgnoreCase(subscriptionStateHeader.getState()))) {
sipSession.removeSubscription(sipServletRequest);
}
sipContext.exitSipApp(sipServletRequest, null);
}
//nothing more needs to be done, either the app acted as UA, PROXY or B2BUA. in any case we stop routing
}
};
getConcurrencyModelExecutorService(sipContext, sipServletMessage).execute(dispatchTask);
}
}
| true | true | public void dispatchMessage(final SipProvider sipProvider, SipServletMessageImpl sipServletMessage) throws DispatcherException {
final SipFactoryImpl sipFactoryImpl = sipApplicationDispatcher.getSipFactory();
final SipServletRequestImpl sipServletRequest = (SipServletRequestImpl) sipServletMessage;
if(logger.isDebugEnabled()) {
logger.debug("Routing of Subsequent Request " + sipServletRequest);
}
final Request request = (Request) sipServletRequest.getMessage();
final Dialog dialog = sipServletRequest.getDialog();
final RouteHeader poppedRouteHeader = sipServletRequest.getPoppedRouteHeader();
String applicationName = null;
String applicationId = null;
if(poppedRouteHeader != null){
final Parameters poppedAddress = (Parameters)poppedRouteHeader.getAddress().getURI();
//Extract information from the Route Header
final String applicationNameHashed = poppedAddress.getParameter(RR_PARAM_APPLICATION_NAME);
if(applicationNameHashed != null && applicationNameHashed.length() > 0) {
applicationName = sipApplicationDispatcher.getApplicationNameFromHash(applicationNameHashed);
applicationId = poppedAddress.getParameter(APP_ID);
}
}
if(applicationId == null) {
final ToHeader toHeader = (ToHeader) request.getHeader(ToHeader.NAME);
final String arText = toHeader.getTag();
final String[] tuple = ApplicationRoutingHeaderComposer.getAppNameAndSessionId(sipApplicationDispatcher, arText);
applicationName = tuple[0];
applicationId = tuple[1];
if(Request.ACK.equals(request.getMethod()) && applicationId == null && applicationName == null) {
//Means that this is an ACK to a container generated error response, so we can drop it
if(logger.isDebugEnabled()) {
logger.debug("The popped Route, application Id and name are null for an ACK, so this is an ACK to a container generated error response, so it is dropped");
}
return ;
}
}
boolean inverted = false;
if(dialog != null && !dialog.isServer()) {
inverted = true;
}
final SipContext sipContext = sipApplicationDispatcher.findSipApplication(applicationName);
if(sipContext == null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request +
"in this popped routed header " + poppedRouteHeader);
}
final SipManager sipManager = (SipManager)sipContext.getManager();
SipApplicationSessionKey sipApplicationSessionKey = SessionManagerUtil.getSipApplicationSessionKey(
applicationName,
applicationId);
MobicentsSipSession tmpSipSession = null;
MobicentsSipApplicationSession sipApplicationSession = sipManager.getSipApplicationSession(sipApplicationSessionKey, false);
if(sipApplicationSession == null) {
if(logger.isDebugEnabled()) {
sipManager.dumpSipApplicationSessions();
}
//trying the join or replaces matching sip app sessions
final SipApplicationSessionKey joinSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, JoinHeader.NAME);
final SipApplicationSessionKey replacesSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, ReplacesHeader.NAME);
if(joinSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(joinSipApplicationSessionKey, false);
sipApplicationSessionKey = joinSipApplicationSessionKey;
} else if(replacesSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(replacesSipApplicationSessionKey, false);
sipApplicationSessionKey = replacesSipApplicationSessionKey;
}
if(sipApplicationSession == null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip application session to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
}
}
SipSessionKey key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, inverted);
if(logger.isDebugEnabled()) {
logger.debug("Trying to find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
}
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
// Added by Vladimir because the inversion detection on proxied requests doesn't work
if(tmpSipSession == null) {
if(logger.isDebugEnabled()) {
logger.debug("Cannot find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute() + ". Trying inverted.");
}
key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, !inverted);
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
}
if(tmpSipSession == null) {
sipManager.dumpSipSessions();
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
} else {
if(logger.isDebugEnabled()) {
logger.debug("Inverted try worked. sip session found : " + tmpSipSession.getId());
}
}
final MobicentsSipSession sipSession = tmpSipSession;
sipServletRequest.setSipSession(sipSession);
// BEGIN validation delegated to the applicationas per JSIP patch for http://code.google.com/p/mobicents/issues/detail?id=766
if(request.getMethod().equalsIgnoreCase("ACK")) {
if(sipSession.isAckReceived()) {
// Filter out ACK retransmissions as per changes in
logger.debug("ACK filtered out as a retransmission. This Sip Session already has been ACKed.");
return;
}
sipSession.setAckReceived(true);
}
CSeqHeader cseq = (CSeqHeader) request.getHeader(CSeqHeader.NAME);
long localCseq = sipSession.getCseq();
long remoteCseq = cseq.getSeqNumber();
if(localCseq>remoteCseq) {
logger.error("CSeq out of order for the following request");
SipServletResponse response = sipServletRequest.createResponse(500, "CSeq out of order");
try {
response.send();
} catch (IOException e) {
logger.error("Can not send error response", e);
}
}
sipSession.setCseq(remoteCseq);
// END of validation for http://code.google.com/p/mobicents/issues/detail?id=766
DispatchTask dispatchTask = new DispatchTask(sipServletRequest, sipProvider) {
public void dispatch() throws DispatcherException {
sipContext.enterSipApp(sipServletRequest, null, sipManager, true, true);
final String requestMethod = sipServletRequest.getMethod();
final SubscriptionStateHeader subscriptionStateHeader = (SubscriptionStateHeader)
sipServletRequest.getMessage().getHeader(SubscriptionStateHeader.NAME);
try {
sipSession.setSessionCreatingTransaction(sipServletRequest.getTransaction());
// JSR 289 Section 6.2.1 :
// any state transition caused by the reception of a SIP message,
// the state change must be accomplished by the container before calling
// the service() method of any SipServlet to handle the incoming message.
sipSession.updateStateOnSubsequentRequest(sipServletRequest, true);
try {
// RFC 3265 : If a matching NOTIFY request contains a "Subscription-State" of "active" or "pending", it creates
// a new subscription and a new dialog (unless they have already been
// created by a matching response, as described above).
if(Request.NOTIFY.equals(requestMethod) &&
(subscriptionStateHeader != null &&
SubscriptionStateHeader.ACTIVE.equalsIgnoreCase(subscriptionStateHeader.getState()) ||
SubscriptionStateHeader.PENDING.equalsIgnoreCase(subscriptionStateHeader.getState()))) {
sipSession.addSubscription(sipServletRequest);
}
// See if the subsequent request should go directly to the proxy
final ProxyImpl proxy = sipSession.getProxy();
if(proxy != null) {
final ProxyBranchImpl finalBranch = proxy.getFinalBranchForSubsequentRequests();
if(finalBranch != null) {
proxy.setAckReceived(requestMethod.equalsIgnoreCase(Request.ACK));
proxy.setOriginalRequest(sipServletRequest);
callServlet(sipServletRequest);
finalBranch.proxySubsequentRequest(sipServletRequest);
} else if(requestMethod.equals(Request.PRACK)) {
callServlet(sipServletRequest);
List<ProxyBranch> branches = proxy.getProxyBranches();
for(ProxyBranch pb : branches) {
ProxyBranchImpl proxyBranch = (ProxyBranchImpl) pb;
if(proxyBranch.isWaitingForPrack()) {
proxyBranch.proxyDialogStateless(sipServletRequest);
proxyBranch.setWaitingForPrack(false);
}
}
}
}
// If it's not for a proxy then it's just an AR, so go to the next application
else {
callServlet(sipServletRequest);
}
} catch (ServletException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
} catch (SipException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
} catch (IOException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
}
} finally {
// A subscription is destroyed when a notifier sends a NOTIFY request
// with a "Subscription-State" of "terminated".
if(Request.NOTIFY.equals(requestMethod) &&
(subscriptionStateHeader != null &&
SubscriptionStateHeader.TERMINATED.equalsIgnoreCase(subscriptionStateHeader.getState()))) {
sipSession.removeSubscription(sipServletRequest);
}
sipContext.exitSipApp(sipServletRequest, null);
}
//nothing more needs to be done, either the app acted as UA, PROXY or B2BUA. in any case we stop routing
}
};
getConcurrencyModelExecutorService(sipContext, sipServletMessage).execute(dispatchTask);
}
| public void dispatchMessage(final SipProvider sipProvider, SipServletMessageImpl sipServletMessage) throws DispatcherException {
final SipFactoryImpl sipFactoryImpl = sipApplicationDispatcher.getSipFactory();
final SipServletRequestImpl sipServletRequest = (SipServletRequestImpl) sipServletMessage;
if(logger.isDebugEnabled()) {
logger.debug("Routing of Subsequent Request " + sipServletRequest);
}
final Request request = (Request) sipServletRequest.getMessage();
final Dialog dialog = sipServletRequest.getDialog();
final RouteHeader poppedRouteHeader = sipServletRequest.getPoppedRouteHeader();
String applicationName = null;
String applicationId = null;
if(poppedRouteHeader != null){
final Parameters poppedAddress = (Parameters)poppedRouteHeader.getAddress().getURI();
//Extract information from the Route Header
final String applicationNameHashed = poppedAddress.getParameter(RR_PARAM_APPLICATION_NAME);
if(applicationNameHashed != null && applicationNameHashed.length() > 0) {
applicationName = sipApplicationDispatcher.getApplicationNameFromHash(applicationNameHashed);
applicationId = poppedAddress.getParameter(APP_ID);
}
}
if(applicationId == null) {
final ToHeader toHeader = (ToHeader) request.getHeader(ToHeader.NAME);
final String arText = toHeader.getTag();
final String[] tuple = ApplicationRoutingHeaderComposer.getAppNameAndSessionId(sipApplicationDispatcher, arText);
applicationName = tuple[0];
applicationId = tuple[1];
if(Request.ACK.equals(request.getMethod()) && applicationId == null && applicationName == null) {
//Means that this is an ACK to a container generated error response, so we can drop it
if(logger.isDebugEnabled()) {
logger.debug("The popped Route, application Id and name are null for an ACK, so this is an ACK to a container generated error response, so it is dropped");
}
return ;
}
}
boolean inverted = false;
if(dialog != null && !dialog.isServer()) {
inverted = true;
}
final SipContext sipContext = sipApplicationDispatcher.findSipApplication(applicationName);
if(sipContext == null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "cannot find the application to handle this subsequent request " + request +
"in this popped routed header " + poppedRouteHeader);
}
final SipManager sipManager = (SipManager)sipContext.getManager();
SipApplicationSessionKey sipApplicationSessionKey = SessionManagerUtil.getSipApplicationSessionKey(
applicationName,
applicationId);
MobicentsSipSession tmpSipSession = null;
MobicentsSipApplicationSession sipApplicationSession = sipManager.getSipApplicationSession(sipApplicationSessionKey, false);
if(sipApplicationSession == null) {
if(logger.isDebugEnabled()) {
sipManager.dumpSipApplicationSessions();
}
//trying the join or replaces matching sip app sessions
final SipApplicationSessionKey joinSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, JoinHeader.NAME);
final SipApplicationSessionKey replacesSipApplicationSessionKey = sipContext.getSipSessionsUtil().getCorrespondingSipApplicationSession(sipApplicationSessionKey, ReplacesHeader.NAME);
if(joinSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(joinSipApplicationSessionKey, false);
sipApplicationSessionKey = joinSipApplicationSessionKey;
} else if(replacesSipApplicationSessionKey != null) {
sipApplicationSession = sipManager.getSipApplicationSession(replacesSipApplicationSessionKey, false);
sipApplicationSessionKey = replacesSipApplicationSessionKey;
}
if(sipApplicationSession == null) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip application session to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
}
}
SipSessionKey key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, inverted);
if(logger.isDebugEnabled()) {
logger.debug("Trying to find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
}
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
// Added by Vladimir because the inversion detection on proxied requests doesn't work
if(tmpSipSession == null) {
if(logger.isDebugEnabled()) {
logger.debug("Cannot find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute() + ". Trying inverted.");
}
key = SessionManagerUtil.getSipSessionKey(sipApplicationSession.getKey().getId(), applicationName, request, !inverted);
tmpSipSession = sipManager.getSipSession(key, false, sipFactoryImpl, sipApplicationSession);
}
if(tmpSipSession == null) {
sipManager.dumpSipSessions();
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "Cannot find the corresponding sip session with key " + key + " to this subsequent request " + request +
" with the following popped route header " + sipServletRequest.getPoppedRoute());
} else {
if(logger.isDebugEnabled()) {
logger.debug("Inverted try worked. sip session found : " + tmpSipSession.getId());
}
}
final MobicentsSipSession sipSession = tmpSipSession;
sipServletRequest.setSipSession(sipSession);
// BEGIN validation delegated to the applicationas per JSIP patch for http://code.google.com/p/mobicents/issues/detail?id=766
if(request.getMethod().equalsIgnoreCase("ACK")) {
if(sipSession.isAckReceived()) {
// Filter out ACK retransmissions for JSIP patch for http://code.google.com/p/mobicents/issues/detail?id=766
logger.debug("ACK filtered out as a retransmission. This Sip Session already has been ACKed.");
return;
}
sipSession.setAckReceived(true);
}
CSeqHeader cseq = (CSeqHeader) request.getHeader(CSeqHeader.NAME);
long localCseq = sipSession.getCseq();
long remoteCseq = cseq.getSeqNumber();
if(localCseq>remoteCseq) {
logger.error("CSeq out of order for the following request");
SipServletResponse response = sipServletRequest.createResponse(500, "CSeq out of order");
try {
response.send();
} catch (IOException e) {
logger.error("Can not send error response", e);
}
}
sipSession.setCseq(remoteCseq);
// END of validation for http://code.google.com/p/mobicents/issues/detail?id=766
DispatchTask dispatchTask = new DispatchTask(sipServletRequest, sipProvider) {
public void dispatch() throws DispatcherException {
sipContext.enterSipApp(sipServletRequest, null, sipManager, true, true);
final String requestMethod = sipServletRequest.getMethod();
final SubscriptionStateHeader subscriptionStateHeader = (SubscriptionStateHeader)
sipServletRequest.getMessage().getHeader(SubscriptionStateHeader.NAME);
try {
sipSession.setSessionCreatingTransaction(sipServletRequest.getTransaction());
// JSR 289 Section 6.2.1 :
// any state transition caused by the reception of a SIP message,
// the state change must be accomplished by the container before calling
// the service() method of any SipServlet to handle the incoming message.
sipSession.updateStateOnSubsequentRequest(sipServletRequest, true);
try {
// RFC 3265 : If a matching NOTIFY request contains a "Subscription-State" of "active" or "pending", it creates
// a new subscription and a new dialog (unless they have already been
// created by a matching response, as described above).
if(Request.NOTIFY.equals(requestMethod) &&
(subscriptionStateHeader != null &&
SubscriptionStateHeader.ACTIVE.equalsIgnoreCase(subscriptionStateHeader.getState()) ||
SubscriptionStateHeader.PENDING.equalsIgnoreCase(subscriptionStateHeader.getState()))) {
sipSession.addSubscription(sipServletRequest);
}
// See if the subsequent request should go directly to the proxy
final ProxyImpl proxy = sipSession.getProxy();
if(proxy != null) {
final ProxyBranchImpl finalBranch = proxy.getFinalBranchForSubsequentRequests();
if(finalBranch != null) {
proxy.setAckReceived(requestMethod.equalsIgnoreCase(Request.ACK));
proxy.setOriginalRequest(sipServletRequest);
callServlet(sipServletRequest);
finalBranch.proxySubsequentRequest(sipServletRequest);
} else if(requestMethod.equals(Request.PRACK)) {
callServlet(sipServletRequest);
List<ProxyBranch> branches = proxy.getProxyBranches();
for(ProxyBranch pb : branches) {
ProxyBranchImpl proxyBranch = (ProxyBranchImpl) pb;
if(proxyBranch.isWaitingForPrack()) {
proxyBranch.proxyDialogStateless(sipServletRequest);
proxyBranch.setWaitingForPrack(false);
}
}
}
}
// If it's not for a proxy then it's just an AR, so go to the next application
else {
callServlet(sipServletRequest);
}
} catch (ServletException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
} catch (SipException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
} catch (IOException e) {
throw new DispatcherException(Response.SERVER_INTERNAL_ERROR, "An unexpected servlet exception occured while processing the following subsequent request " + request, e);
}
} finally {
// A subscription is destroyed when a notifier sends a NOTIFY request
// with a "Subscription-State" of "terminated".
if(Request.NOTIFY.equals(requestMethod) &&
(subscriptionStateHeader != null &&
SubscriptionStateHeader.TERMINATED.equalsIgnoreCase(subscriptionStateHeader.getState()))) {
sipSession.removeSubscription(sipServletRequest);
}
sipContext.exitSipApp(sipServletRequest, null);
}
//nothing more needs to be done, either the app acted as UA, PROXY or B2BUA. in any case we stop routing
}
};
getConcurrencyModelExecutorService(sipContext, sipServletMessage).execute(dispatchTask);
}
|
diff --git a/src/logreporter/SuiteReporter.java b/src/logreporter/SuiteReporter.java
index fa19c90..f9c7cc5 100644
--- a/src/logreporter/SuiteReporter.java
+++ b/src/logreporter/SuiteReporter.java
@@ -1,285 +1,285 @@
/*
Copyright 2011 SugarCRM 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 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.
Please see the License for the specific language governing permissions and
limitations under the License.
*/
package logreporter;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Takes in a File type input (should be the directory of .log files), reads all the log files and
* generate a nice html summary table of the tests. The generated html will be in the same directory
*
* @param folder - path of the folder containing SODA report logs
*
*/
public class SuiteReporter {
private String HTML_HEADER_RESOURCE = "suitereporter-header.txt";
private File folder = null;
private File[] filesList = null;
private int count = 0;
private String suiteName = null;
private FileReader input = null;
private BufferedReader br = null;
private String strLine, tmp = null;
private FileOutputStream output = null;
private PrintStream repFile = null;
/**
* default constructor
*/
public SuiteReporter(){
folder = new File("");
filesList = new File[0];
count = 0;
}
/**
* Constructor for class SuiteReporter
* @param folder - the File folder in which the suite log files reside.
*/
public SuiteReporter(File folder){
folder = folder;
filesList = folder.listFiles();
count = 0;
suiteName = folder.getName();
/**
* set up file output
*/
try {
output = new FileOutputStream(folder.getAbsolutePath()+"/"+suiteName+".html");
repFile = new PrintStream(output);
} catch(Exception e) {
System.err.println("Error writing to file "+suiteName+".html");
e.printStackTrace();
}
}
/**
* generates a html report file
*/
public void generateReport() {
generateHTMLHeader();
/**
* find files in folder that ends with .log, and process them
*/
for (int i = 0; i < filesList.length; i++) {
//ignores nonfiles and hidden files
if (filesList[i].isFile() && !filesList[i].isHidden()) {
//read if is .log file
if (filesList[i].getName().endsWith("log")) {
readNextLog(filesList[i]);
//remove the .log extention
String temp = filesList[i].getName().substring(0, filesList[i].getName().indexOf("."));
//get last line
try {
while ((tmp = br.readLine()) != null) {
strLine = tmp;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//find log status, generate table row
if (strLine.contains("blocked:1")) {
generateTableRow(temp, 2, null);
} else if (strLine.contains("result:-1")) {
generateTableRow(temp, 0, strLine);
} else {
generateTableRow(temp, 1, null);
}
}
}
}
repFile.print("\n</table>\n</body>\n</html>\n");
repFile.close();
}
private String GenMiniErrorTable(String line) {
String result = "";
Pattern p = null;
Matcher m = null;
String exceptions = "";
String watchdog = "";
String fasserts = "";
String errors = "";
String color = "";
try {
p = Pattern.compile("failedasserts:(\\d+).*exceptions:(\\d+).*errors:(\\d+).*watchdog:(\\d+)",
Pattern.CASE_INSENSITIVE);
m = p.matcher(line);
if (!m.find()) {
System.out.printf("(!)Error: Failed to find needed matches when parsing a failed tests results line!\n");
System.out.printf("--)Line: '%s'\n\n", line);
return "";
}
fasserts = m.group(1);
exceptions = m.group(2);
watchdog = m.group(3);
errors = m.group(4);
result = "\t<td class=\"td_issues_data\">\n\t<table class=\"table_sub\">\n"+
"\t<tr>\n";
if (Integer.valueOf(watchdog) > 0) {
color = "#FF0000";
} else {
color = "#000000";
}
result += "\t\t<td class=\"td_sub\">"+
"WD: <font color=\"" + color + "\">" + watchdog + "</font></td>\n";
- if (Integer.valueOf(exceptions) > 0) {
+ if (Integer.valueOf(exceptions) > 0) {
color = "#FF0000";
} else {
color = "#000000";
}
result += "\t\t<td class=\"td_sub\">Exp: <font color=\"" +
color + "\">" + exceptions + "</font></td>\n";
- if (Integer.valueOf(fasserts) > 0) {
+ if (Integer.valueOf(fasserts) > 0) {
color = "#FF0000";
} else {
color = "#000000";
}
result += "\t\t<td class=\"td_sub\">"+
"FA: <font color=\"" + color + "\">" + fasserts + "</font></td>\n";
if (Integer.valueOf(errors) > 0) {
color = "#FF0000";
} else {
color = "#000000";
}
result += "\t\t<td class=\"td_sub\">"+
"E: <font color=\"" + color + "\">" + errors + "</font></td>\n"+
"\t</tr>\n\t</table>\n\t</td>\n";
} catch (Exception exp) {
exp.printStackTrace();
}
return result;
}
/**
* generates a html table row based on data from .log report file
*
* @param fileName - name of the .log report file this table row is representing
* @param failed - status of the test. 0 = failed, 1 = passed, 2 = blocked
*
* Note:
* I find it odd that the intern needed to change failed = 0, when -1 was already
* 0 and 0 always means success in C programming...
*
*/
public void generateTableRow(String fileName, int status, String line){
String html = "\t<td class=\"td_issues_data\"></td>\n";
count ++;
repFile.println("<tr id=\""+count+"\" onMouseOver=\"this.className='highlight'\" "+
"onMouseOut=\"this.className='tr_normal'\" class=\"tr_normal\" >");
repFile.println("\t<td class=\"td_file_data\">"+count+"</td>");
repFile.println("\t<td class=\"td_file_data\">"+fileName+".xml</td>");
switch (status) {
case 0:
html = GenMiniErrorTable(line);
html += "\t<td class=\"td_failed_data\">Failed</td>";
repFile.println(html);
break;
case 1:
html += "\t<td class=\"td_passed_data\">Passed</td>";
repFile.println(html);
break;
default:
html += "\t<td class=\"_data\">Blocked</td>";
repFile.println(html);
}
repFile.println("\t<td class=\"td_report_data\"><a href='Report-"+fileName+".html'>Report Log</a></td>");
repFile.println("</tr>");
}
/**
* generates the html header for the report file
*/
private void generateHTMLHeader() {
String title = "suite "+suiteName+".xml test results";
String header = "";
InputStream stream = null;
String line = null;
boolean found_title = false;
boolean found_suitename = false;
try {
stream = getClass().getResourceAsStream(this.HTML_HEADER_RESOURCE);
InputStreamReader in = new InputStreamReader(stream);
BufferedReader br = new BufferedReader(in);
while ((line = br.readLine()) != null) {
if ( (found_title != true) && (line.contains("__TITLE__"))) {
line = line.replace("__TITLE__", title);
found_title = true;
}
if ((found_suitename != true) && (line.contains("__SUITENAME__")) ) {
line = line.replace("__SUITENAME__", suiteName);
found_suitename = true;
}
header += line;
header += "\n";
}
} catch (Exception exp) {
exp.printStackTrace();
}
repFile.print(header);
}
/**
* sets up FileReader and BufferedReader for the next report file
* @param inputFile - a properly formatted .log SODA report file
*/
private void readNextLog(File inputFile) {
try{
/*sets up file reader to read input one character at a time*/
input = new FileReader(inputFile);
/*sets up buffered reader to read input one line at a time*/
br = new BufferedReader(input);
} catch (FileNotFoundException e) {
System.err.println("file not found: "+inputFile);
} catch (Exception e) {
System.err.println("error reading file" + inputFile);
}
}
}
| false | true | private String GenMiniErrorTable(String line) {
String result = "";
Pattern p = null;
Matcher m = null;
String exceptions = "";
String watchdog = "";
String fasserts = "";
String errors = "";
String color = "";
try {
p = Pattern.compile("failedasserts:(\\d+).*exceptions:(\\d+).*errors:(\\d+).*watchdog:(\\d+)",
Pattern.CASE_INSENSITIVE);
m = p.matcher(line);
if (!m.find()) {
System.out.printf("(!)Error: Failed to find needed matches when parsing a failed tests results line!\n");
System.out.printf("--)Line: '%s'\n\n", line);
return "";
}
fasserts = m.group(1);
exceptions = m.group(2);
watchdog = m.group(3);
errors = m.group(4);
result = "\t<td class=\"td_issues_data\">\n\t<table class=\"table_sub\">\n"+
"\t<tr>\n";
if (Integer.valueOf(watchdog) > 0) {
color = "#FF0000";
} else {
color = "#000000";
}
result += "\t\t<td class=\"td_sub\">"+
"WD: <font color=\"" + color + "\">" + watchdog + "</font></td>\n";
if (Integer.valueOf(exceptions) > 0) {
color = "#FF0000";
} else {
color = "#000000";
}
result += "\t\t<td class=\"td_sub\">Exp: <font color=\"" +
color + "\">" + exceptions + "</font></td>\n";
if (Integer.valueOf(fasserts) > 0) {
color = "#FF0000";
} else {
color = "#000000";
}
result += "\t\t<td class=\"td_sub\">"+
"FA: <font color=\"" + color + "\">" + fasserts + "</font></td>\n";
if (Integer.valueOf(errors) > 0) {
color = "#FF0000";
} else {
color = "#000000";
}
result += "\t\t<td class=\"td_sub\">"+
"E: <font color=\"" + color + "\">" + errors + "</font></td>\n"+
"\t</tr>\n\t</table>\n\t</td>\n";
} catch (Exception exp) {
exp.printStackTrace();
}
return result;
}
| private String GenMiniErrorTable(String line) {
String result = "";
Pattern p = null;
Matcher m = null;
String exceptions = "";
String watchdog = "";
String fasserts = "";
String errors = "";
String color = "";
try {
p = Pattern.compile("failedasserts:(\\d+).*exceptions:(\\d+).*errors:(\\d+).*watchdog:(\\d+)",
Pattern.CASE_INSENSITIVE);
m = p.matcher(line);
if (!m.find()) {
System.out.printf("(!)Error: Failed to find needed matches when parsing a failed tests results line!\n");
System.out.printf("--)Line: '%s'\n\n", line);
return "";
}
fasserts = m.group(1);
exceptions = m.group(2);
watchdog = m.group(3);
errors = m.group(4);
result = "\t<td class=\"td_issues_data\">\n\t<table class=\"table_sub\">\n"+
"\t<tr>\n";
if (Integer.valueOf(watchdog) > 0) {
color = "#FF0000";
} else {
color = "#000000";
}
result += "\t\t<td class=\"td_sub\">"+
"WD: <font color=\"" + color + "\">" + watchdog + "</font></td>\n";
if (Integer.valueOf(exceptions) > 0) {
color = "#FF0000";
} else {
color = "#000000";
}
result += "\t\t<td class=\"td_sub\">Exp: <font color=\"" +
color + "\">" + exceptions + "</font></td>\n";
if (Integer.valueOf(fasserts) > 0) {
color = "#FF0000";
} else {
color = "#000000";
}
result += "\t\t<td class=\"td_sub\">"+
"FA: <font color=\"" + color + "\">" + fasserts + "</font></td>\n";
if (Integer.valueOf(errors) > 0) {
color = "#FF0000";
} else {
color = "#000000";
}
result += "\t\t<td class=\"td_sub\">"+
"E: <font color=\"" + color + "\">" + errors + "</font></td>\n"+
"\t</tr>\n\t</table>\n\t</td>\n";
} catch (Exception exp) {
exp.printStackTrace();
}
return result;
}
|
diff --git a/proxytoys-website/src/java/minimesh/Page.java b/proxytoys-website/src/java/minimesh/Page.java
index 1a0003a..84cc930 100644
--- a/proxytoys-website/src/java/minimesh/Page.java
+++ b/proxytoys-website/src/java/minimesh/Page.java
@@ -1,160 +1,160 @@
package minimesh;
import com.opensymphony.module.sitemesh.html.BasicRule;
import com.opensymphony.module.sitemesh.html.CustomTag;
import com.opensymphony.module.sitemesh.html.HTMLProcessor;
import com.opensymphony.module.sitemesh.html.Tag;
import com.opensymphony.module.sitemesh.html.rules.BodyTagRule;
import com.opensymphony.module.sitemesh.html.rules.HeadExtractingRule;
import com.opensymphony.module.sitemesh.html.rules.MetaTagRule;
import com.opensymphony.module.sitemesh.html.rules.PageBuilder;
import com.opensymphony.module.sitemesh.html.rules.RegexReplacementTextFilter;
import com.opensymphony.module.sitemesh.html.rules.TitleExtractingRule;
import com.opensymphony.module.sitemesh.html.util.CharArray;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Properties;
/**
* A single page in a website, including title, filename and content.
*
* All this information is loaded from an HTML file (using the SiteMesh library).
*
* @author Joe Walnes
*/
public class Page {
private Properties properties;
private String filename;
private String head;
private String body;
private Collection links = new HashSet();
public Page(File htmlFile) {
try {
filename = htmlFile.getName();
FileSystem fileSystem = new FileSystem();
char[] rawHTML = fileSystem.readFile(htmlFile);
extractContentFromHTML(rawHTML);
} catch (IOException e) {
throw new CannotParsePageException(e);
}
}
public Page(String filename, String htmlContent) {
try {
this.filename = filename;
extractContentFromHTML(htmlContent.toCharArray());
} catch (IOException e) {
throw new CannotParsePageException(e);
}
}
private void extractContentFromHTML(char[] rawHTML) throws IOException {
// where to dump properties extracted from the page
properties = new Properties();
PageBuilder pageBuilder = new PageBuilder() {
public void addProperty(String key, String value) {
properties.setProperty(key, value);
}
};
// buffers to hold head and body content
CharArray headBuffer = new CharArray(64);
CharArray bodyBuffer = new CharArray(4096);
// setup rules for html processor
HTMLProcessor htmlProcessor = new HTMLProcessor(rawHTML, bodyBuffer);
htmlProcessor.addRule(new BodyTagRule(pageBuilder, bodyBuffer));
htmlProcessor.addRule(new HeadExtractingRule(headBuffer));
htmlProcessor.addRule(new TitleExtractingRule(pageBuilder));
htmlProcessor.addRule(new MetaTagRule(pageBuilder));
htmlProcessor.addRule(new LinkExtractingRule());
htmlProcessor.addRule(new AddFirstChildClassToHeader());
// turn JIRA:XSTR-123 snippets into links
- htmlProcessor.addTextFilter(new RegexReplacementTextFilter("JIRA:(XSTR\\-[0-9]+)", "<a href=\"http://jira.codehaus.org/browse/$1\">$1</a>"));
+ htmlProcessor.addTextFilter(new RegexReplacementTextFilter("JIRA:(PTOYS\\-[0-9]+)", "<a href=\"http://jira.codehaus.org/browse/$1\">$1</a>"));
// go!
htmlProcessor.process();
this.head = headBuffer.toString();
this.body = bodyBuffer.toString();
}
public String getTitle() {
if (properties.containsKey("meta.short")) {
return properties.getProperty("meta.short");
} else {
return properties.getProperty("title");
}
}
public String getHead() {
return head.toString();
}
public String getBody() {
return body.toString();
}
public String getFilename() {
return filename;
}
public String getHref() {
return getFilename();
}
public Collection getLinks() {
return Collections.unmodifiableCollection(links);
}
public static class CannotParsePageException extends RuntimeException {
public CannotParsePageException(Throwable cause) {
super(cause);
}
}
/**
* Rule for HTMLProcessor that records all <a href=""> links.
*/
private class LinkExtractingRule extends BasicRule {
public boolean shouldProcess(String tag) {
return tag.equalsIgnoreCase("a");
}
public void process(Tag tag) {
if (tag.hasAttribute("href", false)) {
links.add(tag.getAttributeValue("href", false));
}
tag.writeTo(currentBuffer());
}
}
/**
* Rule for HTMLProcessor that adds class=""FirstChild" to the first header of the body
* if it is the first element.
*/
private class AddFirstChildClassToHeader extends BasicRule {
private boolean firstChildIsHeader = true;
public boolean shouldProcess(String tag) {
return tag.equalsIgnoreCase("p") || tag.matches("^[hH][1-9]$");
}
public void process(Tag tag) {
if (firstChildIsHeader) {
if (!tag.getName().equalsIgnoreCase("p")) {
CustomTag customTag = new CustomTag(tag);
customTag.addAttribute("class", "FirstChild");
tag = customTag;
}
firstChildIsHeader = false;
}
tag.writeTo(currentBuffer());
}
}
}
| true | true | private void extractContentFromHTML(char[] rawHTML) throws IOException {
// where to dump properties extracted from the page
properties = new Properties();
PageBuilder pageBuilder = new PageBuilder() {
public void addProperty(String key, String value) {
properties.setProperty(key, value);
}
};
// buffers to hold head and body content
CharArray headBuffer = new CharArray(64);
CharArray bodyBuffer = new CharArray(4096);
// setup rules for html processor
HTMLProcessor htmlProcessor = new HTMLProcessor(rawHTML, bodyBuffer);
htmlProcessor.addRule(new BodyTagRule(pageBuilder, bodyBuffer));
htmlProcessor.addRule(new HeadExtractingRule(headBuffer));
htmlProcessor.addRule(new TitleExtractingRule(pageBuilder));
htmlProcessor.addRule(new MetaTagRule(pageBuilder));
htmlProcessor.addRule(new LinkExtractingRule());
htmlProcessor.addRule(new AddFirstChildClassToHeader());
// turn JIRA:XSTR-123 snippets into links
htmlProcessor.addTextFilter(new RegexReplacementTextFilter("JIRA:(XSTR\\-[0-9]+)", "<a href=\"http://jira.codehaus.org/browse/$1\">$1</a>"));
// go!
htmlProcessor.process();
this.head = headBuffer.toString();
this.body = bodyBuffer.toString();
}
| private void extractContentFromHTML(char[] rawHTML) throws IOException {
// where to dump properties extracted from the page
properties = new Properties();
PageBuilder pageBuilder = new PageBuilder() {
public void addProperty(String key, String value) {
properties.setProperty(key, value);
}
};
// buffers to hold head and body content
CharArray headBuffer = new CharArray(64);
CharArray bodyBuffer = new CharArray(4096);
// setup rules for html processor
HTMLProcessor htmlProcessor = new HTMLProcessor(rawHTML, bodyBuffer);
htmlProcessor.addRule(new BodyTagRule(pageBuilder, bodyBuffer));
htmlProcessor.addRule(new HeadExtractingRule(headBuffer));
htmlProcessor.addRule(new TitleExtractingRule(pageBuilder));
htmlProcessor.addRule(new MetaTagRule(pageBuilder));
htmlProcessor.addRule(new LinkExtractingRule());
htmlProcessor.addRule(new AddFirstChildClassToHeader());
// turn JIRA:XSTR-123 snippets into links
htmlProcessor.addTextFilter(new RegexReplacementTextFilter("JIRA:(PTOYS\\-[0-9]+)", "<a href=\"http://jira.codehaus.org/browse/$1\">$1</a>"));
// go!
htmlProcessor.process();
this.head = headBuffer.toString();
this.body = bodyBuffer.toString();
}
|
diff --git a/src/com/github/pageallocation/gui/table/PageFaultRenderer.java b/src/com/github/pageallocation/gui/table/PageFaultRenderer.java
index 3f94cb8..ac1924b 100644
--- a/src/com/github/pageallocation/gui/table/PageFaultRenderer.java
+++ b/src/com/github/pageallocation/gui/table/PageFaultRenderer.java
@@ -1,92 +1,92 @@
package com.github.pageallocation.gui.table;
import java.awt.Color;
import java.awt.Component;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableModel;
import com.github.pageallocation.util.Util;
/**
* Renderer used to depict a Page Fault. If the current reference was not in the
* previous column then a Page Fault occurred.
*
* @author Victor J.
*
*/
public class PageFaultRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Component renderer = super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, column);
boolean pageFault = pageFaultOccurred(table.getModel(), column);
if (pageFault) {
renderer.setBackground(Color.CYAN);
} else {
renderer.setBackground(Color.WHITE);
}
return renderer;
}
private boolean pageFaultOccurred(final TableModel model, final int column) {
String columnName = model.getColumnName(column);
if (column == 0) {// Frames column
return false;
}
if (column == 1) {// First reference and its not in the initial state
- return !Util.isInteger(columnName);
+ return Util.isInteger(columnName);
} else if (column > 1) {
if (!Util.isInteger(columnName)) {
return false;
}
int rows = model.getRowCount();
if (isColumnEmpty(model, column, rows)) {
return false;
}
int searchColumn = column - 1;
for (int i = 0; i < rows; i++) {// Search the value
Object value = model.getValueAt(i, searchColumn);
if (value == null) {
continue;
} else {
String v = (String) value;
if (columnName.equals(v)) {// found it, no page fault
return false;
}
}
}
}
return true;
}
/**
* Verifies if a column is empty. Either all columns are "" or null.
* @param model
* @param column
* @param rows
* @return
*/
private boolean isColumnEmpty(TableModel model, int column, int rows) {
for (int i = 0; i < rows; i++) {
Object val = model.getValueAt(i, column);
if (val != null) {
if (!((String) val).isEmpty()) {
return false;
}
}
}
return true;
}
}
| true | true | private boolean pageFaultOccurred(final TableModel model, final int column) {
String columnName = model.getColumnName(column);
if (column == 0) {// Frames column
return false;
}
if (column == 1) {// First reference and its not in the initial state
return !Util.isInteger(columnName);
} else if (column > 1) {
if (!Util.isInteger(columnName)) {
return false;
}
int rows = model.getRowCount();
if (isColumnEmpty(model, column, rows)) {
return false;
}
int searchColumn = column - 1;
for (int i = 0; i < rows; i++) {// Search the value
Object value = model.getValueAt(i, searchColumn);
if (value == null) {
continue;
} else {
String v = (String) value;
if (columnName.equals(v)) {// found it, no page fault
return false;
}
}
}
}
return true;
}
| private boolean pageFaultOccurred(final TableModel model, final int column) {
String columnName = model.getColumnName(column);
if (column == 0) {// Frames column
return false;
}
if (column == 1) {// First reference and its not in the initial state
return Util.isInteger(columnName);
} else if (column > 1) {
if (!Util.isInteger(columnName)) {
return false;
}
int rows = model.getRowCount();
if (isColumnEmpty(model, column, rows)) {
return false;
}
int searchColumn = column - 1;
for (int i = 0; i < rows; i++) {// Search the value
Object value = model.getValueAt(i, searchColumn);
if (value == null) {
continue;
} else {
String v = (String) value;
if (columnName.equals(v)) {// found it, no page fault
return false;
}
}
}
}
return true;
}
|
diff --git a/src/main/java/com/soulgalore/crawler/core/HTMLPageResponse.java b/src/main/java/com/soulgalore/crawler/core/HTMLPageResponse.java
index b3ea830..b2b6104 100644
--- a/src/main/java/com/soulgalore/crawler/core/HTMLPageResponse.java
+++ b/src/main/java/com/soulgalore/crawler/core/HTMLPageResponse.java
@@ -1,163 +1,168 @@
/******************************************************
* Web crawler
*
*
* Copyright (C) 2012 by Peter Hedenskog (http://peterhedenskog.com)
*
******************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*
*******************************************************
*/
package com.soulgalore.crawler.core;
import java.util.Map;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
/**
* The response for a html page.
*
*/
public class HTMLPageResponse {
private static final int NO_HTTP_PORT = -1;
private final Document doc;
private final String encoding;
private final PageURL url;
private final int responseCode;
private final String responseType;
private final Map<String, String> headers;
private final long fetchTime;
/**
* Create a response.
* @param pageUrl the url
* @param theResponseCode the response code
* @param theHeaders the headers
* @param theBody the body
* @param theEncoding the encoding
* @param theSize the size
* @param fetchTime the time it took to fetch the response
*/
public HTMLPageResponse(PageURL pageUrl, int theResponseCode,
Map<String, String> theHeaders, String theBody, String theEncoding,
long theSize, String theResponseType, long theFetchTime) {
encoding = theEncoding;
url = pageUrl;
responseCode = theResponseCode;
responseType = theResponseType;
headers = theHeaders;
fetchTime = theFetchTime;
// special hack:
// if the path contains a . (.html etc) then use the full path,
//
// relative links using ../ get's confused if the path don't
// ends with an /
+ if (!pageUrl.isWrongSyntax()) {
final String baseUri = pageUrl.getUri().getScheme()
+ "://"
+ pageUrl.getUri().getHost()
+ ((pageUrl.getUri().getPort() != NO_HTTP_PORT) ? ":" + pageUrl
.getUri().getPort() : "")
+ ((pageUrl.getUri().getPath().contains(".")) ? pageUrl
.getUri().getPath() : pageUrl.getUri().getPath()
+ (pageUrl.getUri().getPath().endsWith("/") ? "" : "/"));
doc = Jsoup.parse(theBody, baseUri);
+ }
+ else {
+ doc = null;
+ }
}
public String getEncoding() {
return encoding;
}
public Document getBody() {
return doc;
}
public String getUrl() {
return url.getUrl();
}
public String getResponseType() {
return responseType;
}
public PageURL getPageUrl() {
return url;
}
public int getResponseCode() {
return responseCode;
}
public Map<String, String> getResponseHeaders() {
return headers;
}
public String getHeaderValue(String key) {
return headers.get(key);
}
public long getFetchTime() {
return fetchTime;
}
@Override
public String toString() {
// left out the body & headers for now
return this.getClass().getSimpleName() + "url:" + getUrl() + "responseCode:" + getResponseCode()+ "encoding:"+ encoding + " type:" + responseType;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + responseCode;
result = prime * result
+ ((responseType == null) ? 0 : responseType.hashCode());
result = prime * result + ((url == null) ? 0 : url.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
HTMLPageResponse other = (HTMLPageResponse) obj;
if (responseCode != other.responseCode)
return false;
if (responseType == null) {
if (other.responseType != null)
return false;
} else if (!responseType.equals(other.responseType))
return false;
if (url == null) {
if (other.url != null)
return false;
} else if (!url.equals(other.url))
return false;
return true;
}
}
| false | true | public HTMLPageResponse(PageURL pageUrl, int theResponseCode,
Map<String, String> theHeaders, String theBody, String theEncoding,
long theSize, String theResponseType, long theFetchTime) {
encoding = theEncoding;
url = pageUrl;
responseCode = theResponseCode;
responseType = theResponseType;
headers = theHeaders;
fetchTime = theFetchTime;
// special hack:
// if the path contains a . (.html etc) then use the full path,
//
// relative links using ../ get's confused if the path don't
// ends with an /
final String baseUri = pageUrl.getUri().getScheme()
+ "://"
+ pageUrl.getUri().getHost()
+ ((pageUrl.getUri().getPort() != NO_HTTP_PORT) ? ":" + pageUrl
.getUri().getPort() : "")
+ ((pageUrl.getUri().getPath().contains(".")) ? pageUrl
.getUri().getPath() : pageUrl.getUri().getPath()
+ (pageUrl.getUri().getPath().endsWith("/") ? "" : "/"));
doc = Jsoup.parse(theBody, baseUri);
}
| public HTMLPageResponse(PageURL pageUrl, int theResponseCode,
Map<String, String> theHeaders, String theBody, String theEncoding,
long theSize, String theResponseType, long theFetchTime) {
encoding = theEncoding;
url = pageUrl;
responseCode = theResponseCode;
responseType = theResponseType;
headers = theHeaders;
fetchTime = theFetchTime;
// special hack:
// if the path contains a . (.html etc) then use the full path,
//
// relative links using ../ get's confused if the path don't
// ends with an /
if (!pageUrl.isWrongSyntax()) {
final String baseUri = pageUrl.getUri().getScheme()
+ "://"
+ pageUrl.getUri().getHost()
+ ((pageUrl.getUri().getPort() != NO_HTTP_PORT) ? ":" + pageUrl
.getUri().getPort() : "")
+ ((pageUrl.getUri().getPath().contains(".")) ? pageUrl
.getUri().getPath() : pageUrl.getUri().getPath()
+ (pageUrl.getUri().getPath().endsWith("/") ? "" : "/"));
doc = Jsoup.parse(theBody, baseUri);
}
else {
doc = null;
}
}
|
diff --git a/Configuration.java b/Configuration.java
index 9a19224..9940ad1 100644
--- a/Configuration.java
+++ b/Configuration.java
@@ -1,232 +1,232 @@
import java.io.*;
import java.util.*;
public class Configuration extends Module {
private HashMap<String, Configuration.PeerInfo> peerList;
private Configuration.CommonInfo commonInfo;
/**
* @return the peerList
*/
public HashMap<String, Configuration.PeerInfo> getPeerList() {
return peerList;
}
/**
* @return the commonInfo
*/
public Configuration.CommonInfo getCommonInfo() {
return commonInfo;
}
public class CommonInfo
{
private int numberOfPreferredNeighbors;
private float unchokingInterval;
private float optimisticUnchokingInterval;
private String fileName;
private int fileSize;
private int pieceSize;
/**
* @return the numberOfPreferredNeighbors
*/
public int getNumberOfPreferredNeighbors() {
return numberOfPreferredNeighbors;
}
/**
* @param numberOfPreferredNeighbors the numberOfPreferredNeighbors to set
*/
public void setNumberOfPreferredNeighbors(int numberOfPreferredNeighbors) {
this.numberOfPreferredNeighbors = numberOfPreferredNeighbors;
}
/**
* @return the unchokingInterval
*/
public float getUnchokingInterval() {
return unchokingInterval;
}
/**
* @param unchokingInterval the unchokingInterval to set
*/
public void setUnchokingInterval(float unchokingInterval) {
this.unchokingInterval = unchokingInterval;
}
/**
* @return the optimisticUnchokingInterval
*/
public float getOptimisticUnchokingInterval() {
return optimisticUnchokingInterval;
}
/**
* @param optimisticUnchokingInterval the optimisticUnchokingInterval to set
*/
public void setOptimisticUnchokingInterval(float optimisticUnchokingInterval) {
this.optimisticUnchokingInterval = optimisticUnchokingInterval;
}
/**
* @return the fileName
*/
public String getFileName() {
return fileName;
}
/**
* @param fileName the fileName to set
*/
public void setFileName(String fileName) {
this.fileName = fileName;
}
/**
* @return the fileSize
*/
public int getFileSize() {
return fileSize;
}
/**
* @param fileSize the fileSize to set
*/
public void setFileSize(int fileSize) {
this.fileSize = fileSize;
}
/**
* @return the pieceSize
*/
public int getPieceSize() {
return pieceSize;
}
/**
* @param pieceSize the pieceSize to set
*/
public void setPieceSize(int pieceSize) {
this.pieceSize = pieceSize;
}
}
public class PeerInfo
{
private int peerID;
private String hostName;
private int portNumber;
private boolean hasFile;
protected void setPeerID(int peerID)
{
this.peerID = peerID;
}
public int getPeerID()
{
return peerID;
}
protected void setHostName(String hostName)
{
this.hostName = hostName;
}
public String getHostName()
{
return hostName;
}
protected void setPortNumber(int portNumber)
{
this.portNumber = portNumber;
}
public int getPortNumber()
{
return portNumber;
}
protected void setHasFile(boolean hasFile)
{
this.hasFile = hasFile;
}
public boolean getHasFile()
{
return hasFile;
}
}
public void initialConfiguration() {
String st;
boolean hasFile;
peerList = new HashMap<String, Configuration.PeerInfo>();
Configuration.PeerInfo node = new Configuration.PeerInfo();
try {
BufferedReader in = new BufferedReader(new FileReader(Constants.PEER_CFG_FILE));
while((st = in.readLine()) != null)
{
String tokens[] = st.split(" ");
node.setPeerID(Integer.parseInt(tokens[0]));
node.setHostName(tokens[1]);
node.setPortNumber(Integer.parseInt(tokens[2]));
hasFile = (tokens[3] == "1") ? true : false;
node.setHasFile(hasFile);
getPeerList().put(tokens[0], node);
}
in.close();
} catch(IOException e)
{
System.out.println("There was a problem opening the peer configuration file. Make sure the file exists");
}
//read in config info
peerList = new HashMap<String, Configuration.PeerInfo>();
Configuration.CommonInfo commonInfo = new Configuration.CommonInfo();
try {
BufferedReader in = new BufferedReader(new FileReader(Constants.COMMON_CFG_FILE));
while((st = in.readLine()) != null)
{
String tokens[] = st.split(" ");
/*private int numberOfPreferredNeighbors;
private float unchokingInterval;
private float optimisticUnchokingInterval;
private String fileName;
private int fileSize;
private int pieceSize;*/
- commonInfo.setNumberOfPreferredNeighbors(Integer.parseInt(tokens[0]));
- commonInfo.setUnchokingInterval(Float.parseFloat(tokens[1]));
- commonInfo.setOptimisticUnchokingInterval(Float.parseFloat(tokens[2]));
- commonInfo.setFileName(tokens[3]);
- commonInfo.setFileSize(Integer.parseInt(tokens[4]));
- commonInfo.setPieceSize(Integer.parseInt(tokens[5]));
+ commonInfo.setNumberOfPreferredNeighbors(Integer.parseInt(tokens[1]));
+ commonInfo.setUnchokingInterval(Integer.parseInt(tokens[1]));
+ commonInfo.setOptimisticUnchokingInterval(Float.parseFloat(tokens[1]));
+ commonInfo.setFileName(tokens[1]);
+ commonInfo.setFileSize(Integer.parseInt(tokens[1]));
+ commonInfo.setPieceSize(Integer.parseInt(tokens[1]));
}
in.close();
} catch(IOException e)
{
System.out.println("There was a problem opening the common configuration file. Make sure the file exists");
}
}
}
| true | true | public void initialConfiguration() {
String st;
boolean hasFile;
peerList = new HashMap<String, Configuration.PeerInfo>();
Configuration.PeerInfo node = new Configuration.PeerInfo();
try {
BufferedReader in = new BufferedReader(new FileReader(Constants.PEER_CFG_FILE));
while((st = in.readLine()) != null)
{
String tokens[] = st.split(" ");
node.setPeerID(Integer.parseInt(tokens[0]));
node.setHostName(tokens[1]);
node.setPortNumber(Integer.parseInt(tokens[2]));
hasFile = (tokens[3] == "1") ? true : false;
node.setHasFile(hasFile);
getPeerList().put(tokens[0], node);
}
in.close();
} catch(IOException e)
{
System.out.println("There was a problem opening the peer configuration file. Make sure the file exists");
}
//read in config info
peerList = new HashMap<String, Configuration.PeerInfo>();
Configuration.CommonInfo commonInfo = new Configuration.CommonInfo();
try {
BufferedReader in = new BufferedReader(new FileReader(Constants.COMMON_CFG_FILE));
while((st = in.readLine()) != null)
{
String tokens[] = st.split(" ");
/*private int numberOfPreferredNeighbors;
private float unchokingInterval;
private float optimisticUnchokingInterval;
private String fileName;
private int fileSize;
private int pieceSize;*/
commonInfo.setNumberOfPreferredNeighbors(Integer.parseInt(tokens[0]));
commonInfo.setUnchokingInterval(Float.parseFloat(tokens[1]));
commonInfo.setOptimisticUnchokingInterval(Float.parseFloat(tokens[2]));
commonInfo.setFileName(tokens[3]);
commonInfo.setFileSize(Integer.parseInt(tokens[4]));
commonInfo.setPieceSize(Integer.parseInt(tokens[5]));
}
in.close();
} catch(IOException e)
{
System.out.println("There was a problem opening the common configuration file. Make sure the file exists");
}
}
| public void initialConfiguration() {
String st;
boolean hasFile;
peerList = new HashMap<String, Configuration.PeerInfo>();
Configuration.PeerInfo node = new Configuration.PeerInfo();
try {
BufferedReader in = new BufferedReader(new FileReader(Constants.PEER_CFG_FILE));
while((st = in.readLine()) != null)
{
String tokens[] = st.split(" ");
node.setPeerID(Integer.parseInt(tokens[0]));
node.setHostName(tokens[1]);
node.setPortNumber(Integer.parseInt(tokens[2]));
hasFile = (tokens[3] == "1") ? true : false;
node.setHasFile(hasFile);
getPeerList().put(tokens[0], node);
}
in.close();
} catch(IOException e)
{
System.out.println("There was a problem opening the peer configuration file. Make sure the file exists");
}
//read in config info
peerList = new HashMap<String, Configuration.PeerInfo>();
Configuration.CommonInfo commonInfo = new Configuration.CommonInfo();
try {
BufferedReader in = new BufferedReader(new FileReader(Constants.COMMON_CFG_FILE));
while((st = in.readLine()) != null)
{
String tokens[] = st.split(" ");
/*private int numberOfPreferredNeighbors;
private float unchokingInterval;
private float optimisticUnchokingInterval;
private String fileName;
private int fileSize;
private int pieceSize;*/
commonInfo.setNumberOfPreferredNeighbors(Integer.parseInt(tokens[1]));
commonInfo.setUnchokingInterval(Integer.parseInt(tokens[1]));
commonInfo.setOptimisticUnchokingInterval(Float.parseFloat(tokens[1]));
commonInfo.setFileName(tokens[1]);
commonInfo.setFileSize(Integer.parseInt(tokens[1]));
commonInfo.setPieceSize(Integer.parseInt(tokens[1]));
}
in.close();
} catch(IOException e)
{
System.out.println("There was a problem opening the common configuration file. Make sure the file exists");
}
}
|
diff --git a/src/jpcsp/graphics/RE/software/RendererTemplate.java b/src/jpcsp/graphics/RE/software/RendererTemplate.java
index 7ad8530f..c3c34f32 100644
--- a/src/jpcsp/graphics/RE/software/RendererTemplate.java
+++ b/src/jpcsp/graphics/RE/software/RendererTemplate.java
@@ -1,1776 +1,1780 @@
/*
This file is part of jpcsp.
Jpcsp is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Jpcsp is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Jpcsp. If not, see <http://www.gnu.org/licenses/>.
*/
package jpcsp.graphics.RE.software;
import static jpcsp.graphics.GeCommands.LMODE_SEPARATE_SPECULAR_COLOR;
import static jpcsp.graphics.GeCommands.SOP_REPLACE_STENCIL_VALUE;
import static jpcsp.graphics.GeCommands.TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888;
import static jpcsp.graphics.RE.software.PixelColor.addComponent;
import static jpcsp.graphics.RE.software.PixelColor.doubleColor;
import static jpcsp.graphics.RE.software.PixelColor.ONE;
import static jpcsp.graphics.RE.software.PixelColor.ZERO;
import static jpcsp.graphics.RE.software.PixelColor.absBGR;
import static jpcsp.graphics.RE.software.PixelColor.add;
import static jpcsp.graphics.RE.software.PixelColor.addBGR;
import static jpcsp.graphics.RE.software.PixelColor.combineComponent;
import static jpcsp.graphics.RE.software.PixelColor.doubleComponent;
import static jpcsp.graphics.RE.software.PixelColor.getAlpha;
import static jpcsp.graphics.RE.software.PixelColor.getBlue;
import static jpcsp.graphics.RE.software.PixelColor.getColor;
import static jpcsp.graphics.RE.software.PixelColor.getColorBGR;
import static jpcsp.graphics.RE.software.PixelColor.getGreen;
import static jpcsp.graphics.RE.software.PixelColor.getRed;
import static jpcsp.graphics.RE.software.PixelColor.maxBGR;
import static jpcsp.graphics.RE.software.PixelColor.minBGR;
import static jpcsp.graphics.RE.software.PixelColor.multiply;
import static jpcsp.graphics.RE.software.PixelColor.multiplyBGR;
import static jpcsp.graphics.RE.software.PixelColor.multiplyComponent;
import static jpcsp.graphics.RE.software.PixelColor.setAlpha;
import static jpcsp.graphics.RE.software.PixelColor.setBGR;
import static jpcsp.graphics.RE.software.PixelColor.substractBGR;
import static jpcsp.graphics.RE.software.PixelColor.substractComponent;
import static jpcsp.util.Utilities.pixelToTexel;
import static jpcsp.util.Utilities.wrap;
import static jpcsp.util.Utilities.clamp;
import static jpcsp.util.Utilities.dot3;
import static jpcsp.util.Utilities.max;
import static jpcsp.util.Utilities.min;
import static jpcsp.util.Utilities.normalize3;
import static jpcsp.util.Utilities.round;
import jpcsp.graphics.GeCommands;
import jpcsp.graphics.VideoEngine;
import jpcsp.graphics.RE.software.Rasterizer.Range;
import jpcsp.util.DurationStatistics;
/**
* @author gid15
*
*/
public class RendererTemplate {
public static boolean hasMemInt;
public static boolean needSourceDepthRead;
public static boolean needDestinationDepthRead;
public static boolean needDepthWrite;
public static boolean needTextureUV;
public static boolean simpleTextureUV;
public static boolean swapTextureUV;
public static boolean needScissoringX;
public static boolean needScissoringY;
public static boolean transform2D;
public static boolean clearMode;
public static boolean clearModeColor;
public static boolean clearModeStencil;
public static boolean clearModeDepth;
public static int nearZ;
public static int farZ;
public static boolean colorTestFlagEnabled;
public static int colorTestFunc;
public static boolean alphaTestFlagEnabled;
public static int alphaFunc;
public static int alphaRef;
public static boolean stencilTestFlagEnabled;
public static int stencilFunc;
public static int stencilRef;
public static int stencilOpFail;
public static int stencilOpZFail;
public static int stencilOpZPass;
public static boolean depthTestFlagEnabled;
public static int depthFunc;
public static boolean blendFlagEnabled;
public static int blendEquation;
public static int blendSrc;
public static int blendDst;
public static int sfix;
public static int dfix;
public static boolean colorLogicOpFlagEnabled;
public static int logicOp;
public static int colorMask;
public static boolean depthMask;
public static boolean textureFlagEnabled;
public static boolean useVertexTexture;
public static boolean lightingFlagEnabled;
public static boolean sameVertexColor;
public static boolean setVertexPrimaryColor;
public static boolean primaryColorSetGlobally;
public static boolean isTriangle;
public static boolean matFlagAmbient;
public static boolean matFlagDiffuse;
public static boolean matFlagSpecular;
public static boolean useVertexColor;
public static boolean textureColorDoubled;
public static int lightMode;
public static int texMapMode;
public static int texProjMapMode;
public static float texTranslateX;
public static float texTranslateY;
public static float texScaleX;
public static float texScaleY;
public static int texWrapS;
public static int texWrapT;
public static int textureFunc;
public static boolean textureAlphaUsed;
public static int psm;
public static int texMagFilter;
public static boolean needTextureWrapU;
public static boolean needTextureWrapV;
public static boolean needSourceDepthClamp;
public static boolean isLogTraceEnabled;
public static boolean collectStatistics;
public static boolean ditherFlagEnabled;
private static final boolean resampleTextureForMag = true;
private static DurationStatistics statistics;
public RendererTemplate() {
if (collectStatistics) {
if (statistics == null) {
statistics = new DurationStatistics(String.format("Duration %s", getClass().getName()));
}
}
}
public static boolean isRendererWriterNative(int[] memInt, int psm) {
return memInt != null && psm == GeCommands.TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888;
}
public DurationStatistics getStatistics() {
return statistics;
}
public void render(final BasePrimitiveRenderer renderer) {
doRender(renderer);
}
private static void doRenderStart(final BasePrimitiveRenderer renderer) {
if (isLogTraceEnabled) {
final PrimitiveState prim = renderer.prim;
String comment;
if (isTriangle) {
if (transform2D) {
comment = "Triangle doRender 2D";
} else {
comment = "Triangle doRender 3D";
}
} else {
if (transform2D) {
comment = "Sprite doRender 2D";
} else {
comment = "Sprite doRender 3D";
}
}
VideoEngine.log.trace(String.format("%s (%d,%d)-(%d,%d) skip=%d", comment, prim.pxMin, prim.pyMin, prim.pxMax, prim.pyMax, renderer.imageWriterSkipEOL));
}
renderer.preRender();
if (collectStatistics) {
if (isTriangle) {
if (transform2D) {
RESoftware.triangleRender2DStatistics.start();
} else {
RESoftware.triangleRender3DStatistics.start();
}
} else {
RESoftware.spriteRenderStatistics.start();
}
statistics.start();
}
}
private static void doRenderEnd(final BasePrimitiveRenderer renderer) {
if (collectStatistics) {
statistics.end();
if (isTriangle) {
if (transform2D) {
RESoftware.triangleRender2DStatistics.end();
} else {
RESoftware.triangleRender3DStatistics.end();
}
} else {
RESoftware.spriteRenderStatistics.end();
}
}
renderer.postRender();
}
private static IRandomTextureAccess resampleTexture(final BasePrimitiveRenderer renderer) {
IRandomTextureAccess textureAccess = renderer.textureAccess;
renderer.prim.needResample = false;
if (textureFlagEnabled && (!transform2D || useVertexTexture) && !clearMode) {
if (texMagFilter == GeCommands.TFLT_LINEAR) {
final PrimitiveState prim = renderer.prim;
if (needTextureUV && simpleTextureUV && transform2D) {
if (renderer.cachedTexture != null) {
if (Math.abs(prim.uStep) != 1f || Math.abs(prim.vStep) != 1f) {
prim.resampleFactorWidth = 1f / Math.abs(prim.uStep);
prim.resampleFactorHeight = 1f / Math.abs(prim.vStep);
if (renderer.cachedTexture.canResample(prim.resampleFactorWidth, prim.resampleFactorHeight)) {
prim.needResample = true;
prim.uStart *= prim.resampleFactorWidth;
prim.vStart *= prim.resampleFactorHeight;
prim.uStep = prim.uStep < 0f ? -1f : 1f;
prim.vStep = prim.vStep < 0f ? -1f : 1f;
} else if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Cannot resample with factors %f, %f", prim.resampleFactorWidth, prim.resampleFactorHeight));
}
}
}
} else {
if (resampleTextureForMag && !transform2D && renderer.cachedTexture != null) {
prim.resampleFactorWidth = 2f;
prim.resampleFactorHeight = 2f;
prim.needResample = renderer.cachedTexture.canResample(prim.resampleFactorWidth, prim.resampleFactorHeight);
}
}
}
}
return textureAccess;
}
private static void doRender(final BasePrimitiveRenderer renderer) {
final PixelState pixel = renderer.pixel;
final PrimitiveState prim = renderer.prim;
final IRendererWriter rendererWriter = renderer.rendererWriter;
final Lighting lighting = renderer.lighting;
IRandomTextureAccess textureAccess = resampleTexture(renderer);
doRenderStart(renderer);
int stencilRefAlpha = 0;
if (stencilTestFlagEnabled && !clearMode && stencilRef != 0) {
if (stencilOpFail == SOP_REPLACE_STENCIL_VALUE || stencilOpZFail == SOP_REPLACE_STENCIL_VALUE || stencilOpZPass == SOP_REPLACE_STENCIL_VALUE) {
// Prepare stencilRef as a ready-to-use alpha value
stencilRefAlpha = renderer.stencilRef << 24;
}
}
int stencilRefMasked = renderer.stencilRef & renderer.stencilMask;
int notColorMask = 0xFFFFFFFF;
if (!clearMode && colorMask != 0x00000000) {
notColorMask = ~renderer.colorMask;
}
int alpha, a, b, g, r;
int textureWidthMask = renderer.textureWidth - 1;
int textureHeightMask = renderer.textureHeight - 1;
float textureWidthFloat = renderer.textureWidth;
float textureHeightFloat = renderer.textureHeight;
final int alphaRef = renderer.alphaRef;
final int primSourceDepth = (int) prim.p2z;
float u = prim.uStart;
float v = prim.vStart;
ColorDepth colorDepth = new ColorDepth();
PrimarySecondaryColors colors = new PrimarySecondaryColors();
Range range = null;
Rasterizer rasterizer = null;
float t1uw = 0f;
float t1vw = 0f;
float t2uw = 0f;
float t2vw = 0f;
float t3uw = 0f;
float t3vw = 0f;
if (isTriangle) {
if (transform2D) {
t1uw = prim.t1u;
t1vw = prim.t1v;
t2uw = prim.t2u;
t2vw = prim.t2v;
t3uw = prim.t3u;
t3vw = prim.t3v;
} else {
t1uw = prim.t1u * prim.p1wInverted;
t1vw = prim.t1v * prim.p1wInverted;
t2uw = prim.t2u * prim.p2wInverted;
t2vw = prim.t2v * prim.p2wInverted;
t3uw = prim.t3u * prim.p3wInverted;
t3vw = prim.t3v * prim.p3wInverted;
}
range = new Range();
// No need to use a Rasterizer when rendering very small area.
// The overhead of the Rasterizer would lead to slower rendering.
if (prim.destinationWidth >= Rasterizer.MINIMUM_WIDTH && prim.destinationHeight >= Rasterizer.MINIMUM_HEIGHT) {
rasterizer = new Rasterizer(prim.p1x, prim.p1y, prim.p2x, prim.p2y, prim.p3x, prim.p3y, prim.pyMin, prim.pyMax);
rasterizer.setY(prim.pyMin);
}
}
int fbIndex = 0;
int depthIndex = 0;
int depthOffset = 0;
final int[] memInt = renderer.memInt;
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex = renderer.fbAddress >> 2;
depthIndex = renderer.depthAddress >> 2;
depthOffset = (renderer.depthAddress >> 1) & 1;
}
// Use local variables instead of "pixel" members.
// The Java JIT is then producing a slightly faster code.
int sourceColor = 0;
int sourceDepth = 0;
int destinationColor = 0;
int destinationDepth = 0;
int primaryColor = renderer.primaryColor;
int secondaryColor = 0;
float pixelU = 0f;
float pixelV = 0f;
boolean needResample = prim.needResample;
for (int y = prim.pyMin; y <= prim.pyMax; y++) {
int startX = prim.pxMin;
int endX = prim.pxMax;
if (isTriangle && rasterizer != null) {
rasterizer.getNextRange(range);
startX = max(range.xMin, startX);
endX = min(range.xMax, endX);
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Rasterizer line (%d-%d,%d)", startX, endX, y));
}
}
if (isTriangle && startX > endX) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex += prim.destinationWidth + renderer.imageWriterSkipEOL;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset += prim.destinationWidth + renderer.depthWriterSkipEOL;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(prim.destinationWidth + renderer.imageWriterSkipEOL, prim.destinationWidth + renderer.depthWriterSkipEOL);
}
} else {
if (needTextureUV && simpleTextureUV) {
if (swapTextureUV) {
v = prim.vStart;
} else {
u = prim.uStart;
}
}
if (isTriangle) {
int startSkip = startX - prim.pxMin;
if (startSkip > 0) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex += startSkip;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset += startSkip;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(startSkip, startSkip);
}
if (simpleTextureUV) {
if (swapTextureUV) {
v += startSkip * prim.vStep;
} else {
u += startSkip * prim.uStep;
}
}
}
prim.computeTriangleWeights(pixel, startX, y);
}
for (int x = startX; x <= endX; x++) {
// Use a dummy "do { } while (false);" loop to allow to exit
// quickly from the pixel rendering when a filter does not pass.
// When a filter does not pass, the following is executed:
// rendererWriter.skip(1, 1); // Skip the pixel
// continue;
do {
//
// Test if the pixel is inside the triangle
//
if (isTriangle && !pixel.isInsideTriangle()) {
// Pixel not inside triangle, skip the pixel
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d) outside triangle (%f, %f, %f)", x, y, pixel.triangleWeight1, pixel.triangleWeight2, pixel.triangleWeight3));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
//
// Start rendering the pixel
//
if (transform2D) {
pixel.newPixel2D();
} else {
pixel.newPixel3D();
}
//
// ScissorTest (performed as soon as the pixel screen coordinates are available)
//
if (transform2D) {
if (needScissoringX && needScissoringY) {
if (!(x >= renderer.scissorX1 && x <= renderer.scissorX2 && y >= renderer.scissorY1 && y <= renderer.scissorY2)) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
} else if (needScissoringX) {
if (!(x >= renderer.scissorX1 && x <= renderer.scissorX2)) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
} else if (needScissoringY) {
if (!(y >= renderer.scissorY1 && y <= renderer.scissorY2)) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
}
//
// Pixel source depth
//
if (needSourceDepthRead) {
if (isTriangle) {
sourceDepth = round(pixel.getTriangleWeightedValue(prim.p1z, prim.p2z, prim.p3z));
} else {
sourceDepth = primSourceDepth;
}
}
//
// ScissorDepthTest (performed as soon as the pixel source depth is available)
//
if (!transform2D && !clearMode && needSourceDepthRead) {
if (nearZ != 0x0000 || farZ != 0xFFFF) {
if (sourceDepth < renderer.nearZ || sourceDepth > renderer.farZ) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
}
//
// Pixel destination color and depth
//
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
destinationColor = memInt[fbIndex];
if (needDestinationDepthRead) {
if (depthOffset == 0) {
destinationDepth = memInt[depthIndex] & 0x0000FFFF;
} else {
destinationDepth = memInt[depthIndex] >>> 16;
}
}
} else {
rendererWriter.readCurrent(colorDepth);
destinationColor = colorDepth.color;
if (needDestinationDepthRead) {
destinationDepth = colorDepth.depth;
}
}
//
// StencilTest (performed as soon as destination color is known)
//
if (stencilTestFlagEnabled && !clearMode) {
switch (stencilFunc) {
case GeCommands.STST_FUNCTION_NEVER_PASS_STENCIL_TEST:
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.STST_FUNCTION_ALWAYS_PASS_STENCIL_TEST:
// Nothing to do
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_MATCHES:
- if ((getAlpha(destinationColor) & renderer.stencilMask) != stencilRefMasked) {
+ if (stencilRefMasked != (getAlpha(destinationColor) & renderer.stencilMask)) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_DIFFERS:
- if ((getAlpha(destinationColor) & renderer.stencilMask) == stencilRefMasked) {
+ if (stencilRefMasked == (getAlpha(destinationColor) & renderer.stencilMask)) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_LESS:
- if ((getAlpha(destinationColor) & renderer.stencilMask) >= stencilRefMasked) {
+ // Pass if the reference value is less than the destination value
+ if (stencilRefMasked >= (getAlpha(destinationColor) & renderer.stencilMask)) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_LESS_OR_EQUAL:
- if ((getAlpha(destinationColor) & renderer.stencilMask) > stencilRefMasked) {
+ // Pass if the reference value is less or equal to the destination value
+ if (stencilRefMasked > (getAlpha(destinationColor) & renderer.stencilMask)) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_GREATER:
- if ((getAlpha(destinationColor) & renderer.stencilMask) <= stencilRefMasked) {
+ // Pass if the reference value is greater than the destination value
+ if (stencilRefMasked <= (getAlpha(destinationColor) & renderer.stencilMask)) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_GREATER_OR_EQUAL:
- if ((getAlpha(destinationColor) & renderer.stencilMask) < stencilRefMasked) {
+ // Pass if the reference value is greater or equal to the destination value
+ if (stencilRefMasked < (getAlpha(destinationColor) & renderer.stencilMask)) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
}
}
//
// DepthTest (performed as soon as depths are known, but after the stencil test)
//
if (depthTestFlagEnabled && !clearMode) {
switch (depthFunc) {
case GeCommands.ZTST_FUNCTION_NEVER_PASS_PIXEL:
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.ZTST_FUNCTION_ALWAYS_PASS_PIXEL:
// No filter required
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_EQUAL:
if (sourceDepth != destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_ISNOT_EQUAL:
if (sourceDepth == destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_LESS:
if (sourceDepth >= destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_LESS_OR_EQUAL:
if (sourceDepth > destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_GREATER:
if (sourceDepth <= destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_GREATER_OR_EQUAL:
if (sourceDepth < destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
}
}
//
// Primary color
//
if (setVertexPrimaryColor) {
if (isTriangle) {
if (sameVertexColor) {
primaryColor = pixel.c3;
} else {
primaryColor = pixel.getTriangleColorWeightedValue();
}
}
}
//
// Material Flags
//
if (lightingFlagEnabled && !transform2D && useVertexColor && isTriangle) {
if (matFlagAmbient) {
pixel.materialAmbient = primaryColor;
}
if (matFlagDiffuse) {
pixel.materialDiffuse = primaryColor;
}
if (matFlagSpecular) {
pixel.materialSpecular = primaryColor;
}
}
//
// Lighting
//
if (lightingFlagEnabled && !transform2D) {
lighting.applyLighting(colors, pixel);
primaryColor = colors.primaryColor;
secondaryColor = colors.secondaryColor;
}
//
// Pixel texture U,V
//
if (needTextureUV) {
if (simpleTextureUV) {
pixelU = u;
pixelV = v;
} else {
// Compute the mapped texture u,v coordinates
// based on the Barycentric coordinates.
pixelU = pixel.getTriangleWeightedValue(t1uw, t2uw, t3uw);
pixelV = pixel.getTriangleWeightedValue(t1vw, t2vw, t3vw);
if (!transform2D) {
// In 3D, apply a perspective correction by weighting
// the coordinates by their "w" value. See
// http://en.wikipedia.org/wiki/Texture_mapping#Perspective_correctness
float weightInverted = 1.f / pixel.getTriangleWeightedValue(prim.p1wInverted, prim.p2wInverted, prim.p3wInverted);
pixelU *= weightInverted;
pixelV *= weightInverted;
}
}
}
//
// Texture
//
if (textureFlagEnabled && (!transform2D || useVertexTexture) && !clearMode) {
//
// TextureMapping
//
if (!transform2D) {
switch (texMapMode) {
case GeCommands.TMAP_TEXTURE_MAP_MODE_TEXTURE_COORDIATES_UV:
if (texScaleX != 1f) {
pixelU *= renderer.texScaleX;
}
if (texTranslateX != 0f) {
pixelU += renderer.texTranslateX;
}
if (texScaleY != 1f) {
pixelV *= renderer.texScaleY;
}
if (texTranslateY != 0f) {
pixelV += renderer.texTranslateY;
}
break;
case GeCommands.TMAP_TEXTURE_MAP_MODE_TEXTURE_MATRIX:
switch (texProjMapMode) {
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_POSITION:
final float[] V = pixel.getV();
pixelU = V[0] * pixel.textureMatrix[0] + V[1] * pixel.textureMatrix[4] + V[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12];
pixelV = V[0] * pixel.textureMatrix[1] + V[1] * pixel.textureMatrix[5] + V[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13];
//pixelQ = V[0] * pixel.textureMatrix[2] + V[1] * pixel.textureMatrix[6] + V[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14];
break;
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_TEXTURE_COORDINATES:
float tu = pixelU;
float tv = pixelV;
pixelU = tu * pixel.textureMatrix[0] + tv * pixel.textureMatrix[4] + pixel.textureMatrix[12];
pixelV = tu * pixel.textureMatrix[1] + tv * pixel.textureMatrix[5] + pixel.textureMatrix[13];
//pixelQ = tu * pixel.textureMatrix[2] + tv * pixel.textureMatrix[6] + pixel.textureMatrix[14];
break;
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_NORMALIZED_NORMAL:
final float[] normalizedN = pixel.getNormalizedN();
pixelU = normalizedN[0] * pixel.textureMatrix[0] + normalizedN[1] * pixel.textureMatrix[4] + normalizedN[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12];
pixelV = normalizedN[0] * pixel.textureMatrix[1] + normalizedN[1] * pixel.textureMatrix[5] + normalizedN[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13];
//pixelQ = normalizedN[0] * pixel.textureMatrix[2] + normalizedN[1] * pixel.textureMatrix[6] + normalizedN[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14];
break;
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_NORMAL:
final float[] N = pixel.getN();
pixelU = N[0] * pixel.textureMatrix[0] + N[1] * pixel.textureMatrix[4] + N[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12];
pixelV = N[0] * pixel.textureMatrix[1] + N[1] * pixel.textureMatrix[5] + N[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13];
//pixelQ = N[0] * pixel.textureMatrix[2] + N[1] * pixel.textureMatrix[6] + N[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14];
break;
}
break;
case GeCommands.TMAP_TEXTURE_MAP_MODE_ENVIRONMENT_MAP:
// Implementation based on shader.vert/ApplyTexture:
//
// vec3 Nn = normalize(N);
// vec3 Ve = vec3(gl_ModelViewMatrix * V);
// float k = gl_FrontMaterial.shininess;
// vec3 Lu = gl_LightSource[texShade.x].position.xyz - Ve.xyz * gl_LightSource[texShade.x].position.w;
// vec3 Lv = gl_LightSource[texShade.y].position.xyz - Ve.xyz * gl_LightSource[texShade.y].position.w;
// float Pu = psp_lightKind[texShade.x] == 0 ? dot(Nn, normalize(Lu)) : pow(dot(Nn, normalize(Lu + vec3(0.0, 0.0, 1.0))), k);
// float Pv = psp_lightKind[texShade.y] == 0 ? dot(Nn, normalize(Lv)) : pow(dot(Nn, normalize(Lv + vec3(0.0, 0.0, 1.0))), k);
// T.xyz = vec3(0.5*vec2(1.0 + Pu, 1.0 + Pv), 1.0);
//
final float[] Ve = new float[3];
final float[] Ne = new float[3];
final float[] Lu = new float[3];
final float[] Lv = new float[3];
pixel.getVe(Ve);
pixel.getNormalizedNe(Ne);
for (int i = 0; i < 3; i++) {
Lu[i] = renderer.envMapLightPosU[i] - Ve[i] * renderer.envMapLightPosU[3];
Lv[i] = renderer.envMapLightPosV[i] - Ve[i] * renderer.envMapLightPosV[3];
}
float Pu;
if (renderer.envMapDiffuseLightU) {
normalize3(Lu, Lu);
Pu = dot3(Ne, Lu);
} else {
Lu[2] += 1f;
normalize3(Lu, Lu);
Pu = (float) Math.pow(dot3(Ne, Lu), renderer.envMapShininess);
}
float Pv;
if (renderer.envMapDiffuseLightV) {
normalize3(Lv, Lv);
Pv = dot3(Ne, Lv);
} else {
Lv[2] += 1f;
normalize3(Lv, Lv);
Pv = (float) Math.pow(dot3(Ne, Lv), renderer.envMapShininess);
}
pixelU = (Pu + 1f) * 0.5f;
pixelV = (Pv + 1f) * 0.5f;
//pixelQ = 1f;
break;
}
}
//
// Texture resampling (as late as possible)
//
if (texMagFilter == GeCommands.TFLT_LINEAR) {
if (needResample) {
// Perform the resampling as late as possible.
// We might be lucky that all the pixel are eliminated
// by the depth or stencil tests. In which case,
// we don't need to resample.
textureAccess = renderer.cachedTexture.resample(prim.resampleFactorWidth, prim.resampleFactorHeight);
textureWidthMask = textureAccess.getWidth() - 1;
textureHeightMask = textureAccess.getHeight() - 1;
textureWidthFloat = textureAccess.getWidth();
textureHeightFloat = textureAccess.getHeight();
needResample = false;
}
}
//
// TextureWrap
//
if (needTextureWrapU) {
switch (texWrapS) {
case GeCommands.TWRAP_WRAP_MODE_REPEAT:
if (transform2D) {
pixelU = wrap(pixelU, textureWidthMask);
} else {
pixelU = wrap(pixelU);
}
break;
case GeCommands.TWRAP_WRAP_MODE_CLAMP:
if (transform2D) {
pixelU = clamp(pixelU, 0f, textureWidthMask);
} else {
// Clamp to [0..1[ (1 is excluded)
pixelU = clamp(pixelU, 0f, 0.99999f);
}
break;
}
}
if (needTextureWrapV) {
switch (texWrapT) {
case GeCommands.TWRAP_WRAP_MODE_REPEAT:
if (transform2D) {
pixelV = wrap(pixelV, textureHeightMask);
} else {
pixelV = wrap(pixelV);
}
break;
case GeCommands.TWRAP_WRAP_MODE_CLAMP:
if (transform2D) {
pixelV = clamp(pixelV, 0f, textureHeightMask);
} else {
// Clamp to [0..1[ (1 is excluded)
pixelV = clamp(pixelV, 0f, 0.99999f);
}
break;
}
}
//
// TextureReader
//
if (transform2D) {
sourceColor = textureAccess.readPixel(pixelToTexel(pixelU), pixelToTexel(pixelV));
} else {
sourceColor = textureAccess.readPixel(pixelToTexel(pixelU * textureWidthFloat), pixelToTexel(pixelV * textureHeightFloat));
}
//
// TextureFunction
//
switch (textureFunc) {
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_MODULATE:
if (textureAlphaUsed) {
sourceColor = multiply(sourceColor, primaryColor);
} else {
sourceColor = multiply(sourceColor | 0xFF000000, primaryColor);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_DECAL:
if (textureAlphaUsed) {
alpha = getAlpha(sourceColor);
a = getAlpha(primaryColor);
b = combineComponent(getBlue(primaryColor), getBlue(sourceColor), alpha);
g = combineComponent(getGreen(primaryColor), getGreen(sourceColor), alpha);
r = combineComponent(getRed(primaryColor), getRed(sourceColor), alpha);
sourceColor = getColor(a, b, g, r);
} else {
sourceColor = (sourceColor & 0x00FFFFFF) | (primaryColor & 0xFF000000);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_BLEND:
if (textureAlphaUsed) {
a = multiplyComponent(getAlpha(sourceColor), getAlpha(primaryColor));
b = combineComponent(getBlue(primaryColor), renderer.texEnvColorB, getBlue(sourceColor));
g = combineComponent(getGreen(primaryColor), renderer.texEnvColorG, getGreen(sourceColor));
r = combineComponent(getRed(primaryColor), renderer.texEnvColorR, getRed(sourceColor));
sourceColor = getColor(a, b, g, r);
} else {
a = getAlpha(primaryColor);
b = combineComponent(getBlue(primaryColor), renderer.texEnvColorB, getBlue(sourceColor));
g = combineComponent(getGreen(primaryColor), renderer.texEnvColorG, getGreen(sourceColor));
r = combineComponent(getRed(primaryColor), renderer.texEnvColorR, getRed(sourceColor));
sourceColor = getColor(a, b, g, r);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_REPLACE:
if (!textureAlphaUsed) {
sourceColor = (sourceColor & 0x00FFFFFF) | (primaryColor & 0xFF000000);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_ADD:
if (textureAlphaUsed) {
a = multiplyComponent(getAlpha(sourceColor), getAlpha(primaryColor));
sourceColor = setAlpha(addBGR(sourceColor, primaryColor), a);
} else {
sourceColor = add(sourceColor & 0x00FFFFFF, primaryColor);
}
break;
}
//
// ColorDoubling
//
if (textureColorDoubled) {
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
sourceColor = doubleColor(sourceColor);
secondaryColor = doubleColor(secondaryColor);
} else {
sourceColor = doubleColor(sourceColor);
}
}
//
// SourceColor
//
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
sourceColor = add(sourceColor, secondaryColor);
}
} else {
//
// ColorDoubling
//
if (textureColorDoubled) {
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
primaryColor = doubleColor(primaryColor);
secondaryColor = doubleColor(secondaryColor);
} else if (!primaryColorSetGlobally) {
primaryColor = doubleColor(primaryColor);
}
}
//
// SourceColor
//
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
sourceColor = add(primaryColor, secondaryColor);
} else {
sourceColor = primaryColor;
}
}
//
// ColorTest
//
if (colorTestFlagEnabled && !clearMode) {
switch (colorTestFunc) {
case GeCommands.CTST_COLOR_FUNCTION_ALWAYS_PASS_PIXEL:
// Nothing to do
break;
case GeCommands.CTST_COLOR_FUNCTION_NEVER_PASS_PIXEL:
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.CTST_COLOR_FUNCTION_PASS_PIXEL_IF_COLOR_MATCHES:
if ((sourceColor & renderer.colorTestMsk) != renderer.colorTestRef) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.CTST_COLOR_FUNCTION_PASS_PIXEL_IF_COLOR_DIFFERS:
if ((sourceColor & renderer.colorTestMsk) == renderer.colorTestRef) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
}
}
//
// AlphaTest
//
if (alphaTestFlagEnabled && !clearMode) {
switch (alphaFunc) {
case GeCommands.ATST_ALWAYS_PASS_PIXEL:
// Nothing to do
break;
case GeCommands.ATST_NEVER_PASS_PIXEL:
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.ATST_PASS_PIXEL_IF_MATCHES:
if (getAlpha(sourceColor) != alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_DIFFERS:
if (getAlpha(sourceColor) == alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_LESS:
if (getAlpha(sourceColor) >= alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_LESS_OR_EQUAL:
// No test if alphaRef==0xFF
if (RendererTemplate.alphaRef < 0xFF) {
if (getAlpha(sourceColor) > alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_GREATER:
if (getAlpha(sourceColor) <= alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_GREATER_OR_EQUAL:
// No test if alphaRef==0x00
if (RendererTemplate.alphaRef > 0x00) {
if (getAlpha(sourceColor) < alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
break;
}
}
//
// AlphaBlend
//
if (blendFlagEnabled && !clearMode) {
int filteredSrc;
int filteredDst;
switch (blendEquation) {
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_ADD:
if (blendSrc == GeCommands.ALPHA_FIX && sfix == 0xFFFFFF &&
blendDst == GeCommands.ALPHA_FIX && dfix == 0x000000) {
// Nothing to do, this is a NOP
} else if (blendSrc == GeCommands.ALPHA_FIX && sfix == 0xFFFFFF &&
blendDst == GeCommands.ALPHA_FIX && dfix == 0xFFFFFF) {
sourceColor = PixelColor.add(sourceColor, destinationColor & 0x00FFFFFF);
} else if (blendSrc == GeCommands.ALPHA_SOURCE_ALPHA && blendDst == GeCommands.ALPHA_ONE_MINUS_SOURCE_ALPHA) {
// This is the most common case and can be optimized
int srcAlpha = sourceColor >>> 24;
if (srcAlpha == ZERO) {
// Set color of destination
sourceColor = (sourceColor & 0xFF000000) | (destinationColor & 0x00FFFFFF);
} else if (srcAlpha == ONE) {
// Nothing to change
} else {
int oneMinusSrcAlpha = ONE - srcAlpha;
filteredSrc = multiplyBGR(sourceColor, srcAlpha, srcAlpha, srcAlpha);
filteredDst = multiplyBGR(destinationColor, oneMinusSrcAlpha, oneMinusSrcAlpha, oneMinusSrcAlpha);
sourceColor = setBGR(sourceColor, addBGR(filteredSrc, filteredDst));
}
} else {
filteredSrc = multiplyBGR(sourceColor, blendSrc(sourceColor, destinationColor, renderer.sfix));
filteredDst = multiplyBGR(destinationColor, blendDst(sourceColor, destinationColor, renderer.dfix));
sourceColor = setBGR(sourceColor, addBGR(filteredSrc, filteredDst));
}
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_SUBTRACT:
filteredSrc = multiplyBGR(sourceColor, blendSrc(sourceColor, destinationColor, renderer.sfix));
filteredDst = multiplyBGR(destinationColor, blendDst(sourceColor, destinationColor, renderer.dfix));
sourceColor = setBGR(sourceColor, substractBGR(filteredSrc, filteredDst));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_REVERSE_SUBTRACT:
filteredSrc = multiplyBGR(sourceColor, blendSrc(sourceColor, destinationColor, renderer.sfix));
filteredDst = multiplyBGR(destinationColor, blendDst(sourceColor, destinationColor, renderer.dfix));
sourceColor = setBGR(sourceColor, substractBGR(filteredDst, filteredSrc));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_MINIMUM_VALUE:
// Source and destination factors are not applied
sourceColor = setBGR(sourceColor, minBGR(sourceColor, destinationColor));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_MAXIMUM_VALUE:
// Source and destination factors are not applied
sourceColor = setBGR(sourceColor, maxBGR(sourceColor, destinationColor));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_ABSOLUTE_VALUE:
// Source and destination factors are not applied
sourceColor = setBGR(sourceColor, absBGR(sourceColor, destinationColor));
break;
}
}
if (ditherFlagEnabled) {
int ditherValue = renderer.ditherMatrix[((y & 0x3) << 2) + (x & 0x3)];
if (ditherValue > 0) {
b = addComponent(getBlue(sourceColor), ditherValue);
g = addComponent(getGreen(sourceColor), ditherValue);
r = addComponent(getRed(sourceColor), ditherValue);
sourceColor = setBGR(sourceColor, getColorBGR(b, g, r));
} else if (ditherValue < 0) {
ditherValue = -ditherValue;
b = substractComponent(getBlue(sourceColor), ditherValue);
g = substractComponent(getGreen(sourceColor), ditherValue);
r = substractComponent(getRed(sourceColor), ditherValue);
sourceColor = setBGR(sourceColor, getColorBGR(b, g, r));
}
}
//
// StencilOpZPass
//
if (stencilTestFlagEnabled && !clearMode) {
switch (stencilOpZPass) {
case GeCommands.SOP_KEEP_STENCIL_VALUE:
sourceColor = (sourceColor & 0x00FFFFFF) | (destinationColor & 0xFF000000);
break;
case GeCommands.SOP_ZERO_STENCIL_VALUE:
sourceColor &= 0x00FFFFFF;
break;
case GeCommands.SOP_REPLACE_STENCIL_VALUE:
if (stencilRef == 0) {
// SOP_REPLACE_STENCIL_VALUE with a 0 value is equivalent
// to SOP_ZERO_STENCIL_VALUE
sourceColor &= 0x00FFFFFF;
} else {
sourceColor = (sourceColor & 0x00FFFFFF) | stencilRefAlpha;
}
break;
case GeCommands.SOP_INVERT_STENCIL_VALUE:
sourceColor = (sourceColor & 0x00FFFFFF) | ((~destinationColor) & 0xFF000000);
break;
case GeCommands.SOP_INCREMENT_STENCIL_VALUE:
alpha = destinationColor & 0xFF000000;
if (alpha != 0xFF000000) {
alpha += 0x01000000;
}
sourceColor = (sourceColor & 0x00FFFFFF) | alpha;
break;
case GeCommands.SOP_DECREMENT_STENCIL_VALUE:
alpha = destinationColor & 0xFF000000;
if (alpha != 0x00000000) {
alpha -= 0x01000000;
}
sourceColor = (sourceColor & 0x00FFFFFF) | alpha;
break;
}
} else if (!clearMode) {
// Write the alpha/stencil value to the frame buffer
// only when the stencil test is enabled
sourceColor = (sourceColor & 0x00FFFFFF) | (destinationColor & 0xFF000000);
}
//
// ColorLogicalOperation
//
if (colorLogicOpFlagEnabled && !clearMode) {
switch (logicOp) {
case GeCommands.LOP_CLEAR:
sourceColor = ZERO;
break;
case GeCommands.LOP_AND:
sourceColor &= destinationColor;
break;
case GeCommands.LOP_REVERSE_AND:
sourceColor &= (~destinationColor);
break;
case GeCommands.LOP_COPY:
// This is a NOP
break;
case GeCommands.LOP_INVERTED_AND:
sourceColor = (~sourceColor) & destinationColor;
break;
case GeCommands.LOP_NO_OPERATION:
sourceColor = destinationColor;
break;
case GeCommands.LOP_EXLUSIVE_OR:
sourceColor ^= destinationColor;
break;
case GeCommands.LOP_OR:
sourceColor |= destinationColor;
break;
case GeCommands.LOP_NEGATED_OR:
sourceColor = ~(sourceColor | destinationColor);
break;
case GeCommands.LOP_EQUIVALENCE:
sourceColor = ~(sourceColor ^ destinationColor);
break;
case GeCommands.LOP_INVERTED:
sourceColor = ~destinationColor;
break;
case GeCommands.LOP_REVERSE_OR:
sourceColor |= (~destinationColor);
break;
case GeCommands.LOP_INVERTED_COPY:
sourceColor = ~sourceColor;
break;
case GeCommands.LOP_INVERTED_OR:
sourceColor = (~sourceColor) | destinationColor;
break;
case GeCommands.LOP_NEGATED_AND:
sourceColor = ~(sourceColor & destinationColor);
break;
case GeCommands.LOP_SET:
sourceColor = 0xFFFFFFFF;
break;
}
}
//
// ColorMask
//
if (clearMode) {
if (clearModeColor) {
if (!clearModeStencil) {
sourceColor = (sourceColor & 0x00FFFFFF) | (destinationColor & 0xFF000000);
}
} else {
if (clearModeStencil) {
sourceColor = (sourceColor & 0xFF000000) | (destinationColor & 0x00FFFFFF);
} else {
sourceColor = destinationColor;
}
}
} else {
if (colorMask != 0x00000000) {
sourceColor = (sourceColor & notColorMask) | (destinationColor & renderer.colorMask);
}
}
//
// DepthMask
//
if (needDepthWrite) {
if (clearMode) {
if (!clearModeDepth) {
sourceDepth = destinationDepth;
}
} else if (!depthTestFlagEnabled) {
// Depth writes are disabled when the depth test is not enabled.
sourceDepth = destinationDepth;
} else if (!depthMask) {
sourceDepth = destinationDepth;
}
}
//
// Filter passed
//
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), passed=true, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (needDepthWrite && needSourceDepthClamp) {
// Clamp between 0 and 65535
sourceDepth = Math.max(0, Math.min(sourceDepth, 65535));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
memInt[fbIndex] = sourceColor;
fbIndex++;
if (needDepthWrite) {
if (depthOffset == 0) {
memInt[depthIndex] = (memInt[depthIndex] & 0xFFFF0000) | (sourceDepth & 0x0000FFFF);
depthOffset = 1;
} else {
memInt[depthIndex] = (memInt[depthIndex] & 0x0000FFFF) | (sourceDepth << 16);
depthIndex++;
depthOffset = 0;
}
} else if (needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
if (needDepthWrite) {
colorDepth.color = sourceColor;
colorDepth.depth = sourceDepth;
rendererWriter.writeNext(colorDepth);
} else {
rendererWriter.writeNextColor(sourceColor);
}
}
} while (false);
if (needTextureUV && simpleTextureUV) {
if (swapTextureUV) {
v += prim.vStep;
} else {
u += prim.uStep;
}
}
if (isTriangle) {
prim.deltaXTriangleWeigths(pixel);
}
}
int skip = prim.pxMax - endX;
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex += skip + renderer.imageWriterSkipEOL;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset += skip + renderer.depthWriterSkipEOL;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(skip + renderer.imageWriterSkipEOL, skip + renderer.depthWriterSkipEOL);
}
}
if (needTextureUV && simpleTextureUV) {
if (swapTextureUV) {
u += prim.uStep;
} else {
v += prim.vStep;
}
}
}
doRenderEnd(renderer);
}
protected static int stencilOpFail(int destination, int stencilRefAlpha) {
int alpha;
switch (stencilOpFail) {
case GeCommands.SOP_KEEP_STENCIL_VALUE:
return destination;
case GeCommands.SOP_ZERO_STENCIL_VALUE:
return destination & 0x00FFFFFF;
case GeCommands.SOP_REPLACE_STENCIL_VALUE:
if (stencilRef == 0) {
// SOP_REPLACE_STENCIL_VALUE with a 0 value is equivalent
// to SOP_ZERO_STENCIL_VALUE
return destination & 0x00FFFFFF;
}
return (destination & 0x00FFFFFF) | stencilRefAlpha;
case GeCommands.SOP_INVERT_STENCIL_VALUE:
return destination ^ 0xFF000000;
case GeCommands.SOP_INCREMENT_STENCIL_VALUE:
alpha = destination & 0xFF000000;
if (alpha != 0xFF000000) {
alpha += 0x01000000;
}
return (destination & 0x00FFFFFF) | alpha;
case GeCommands.SOP_DECREMENT_STENCIL_VALUE:
alpha = destination & 0xFF000000;
if (alpha != 0x00000000) {
alpha -= 0x01000000;
}
return (destination & 0x00FFFFFF) | alpha;
}
return destination;
}
protected static int stencilOpZFail(int destination, int stencilRefAlpha) {
int alpha;
switch (stencilOpZFail) {
case GeCommands.SOP_KEEP_STENCIL_VALUE:
return destination;
case GeCommands.SOP_ZERO_STENCIL_VALUE:
return destination & 0x00FFFFFF;
case GeCommands.SOP_REPLACE_STENCIL_VALUE:
if (stencilRef == 0) {
// SOP_REPLACE_STENCIL_VALUE with a 0 value is equivalent
// to SOP_ZERO_STENCIL_VALUE
return destination & 0x00FFFFFF;
}
return (destination & 0x00FFFFFF) | stencilRefAlpha;
case GeCommands.SOP_INVERT_STENCIL_VALUE:
return destination ^ 0xFF000000;
case GeCommands.SOP_INCREMENT_STENCIL_VALUE:
alpha = destination & 0xFF000000;
if (alpha != 0xFF000000) {
alpha += 0x01000000;
}
return (destination & 0x00FFFFFF) | alpha;
case GeCommands.SOP_DECREMENT_STENCIL_VALUE:
alpha = destination & 0xFF000000;
if (alpha != 0x00000000) {
alpha -= 0x01000000;
}
return (destination & 0x00FFFFFF) | alpha;
}
return destination;
}
protected static int blendSrc(int source, int destination, int fix) {
int alpha;
switch (blendSrc) {
case GeCommands.ALPHA_SOURCE_COLOR:
return source;
case GeCommands.ALPHA_ONE_MINUS_SOURCE_COLOR:
return 0xFFFFFFFF - source;
case GeCommands.ALPHA_SOURCE_ALPHA:
alpha = getAlpha(source);
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_ONE_MINUS_SOURCE_ALPHA:
alpha = ONE - getAlpha(source);
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_DESTINATION_ALPHA:
alpha = getAlpha(destination);
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_ONE_MINUS_DESTINATION_ALPHA:
alpha = ONE - getAlpha(destination);
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_DOUBLE_SOURCE_ALPHA:
alpha = doubleComponent(getAlpha(source));
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_ONE_MINUS_DOUBLE_SOURCE_ALPHA:
alpha = ONE - doubleComponent(getAlpha(source));
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_DOUBLE_DESTINATION_ALPHA:
alpha = doubleComponent(getAlpha(destination));
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_ONE_MINUS_DOUBLE_DESTINATION_ALPHA:
alpha = ONE - doubleComponent(getAlpha(destination));
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_FIX:
return fix;
}
return source;
}
protected static int blendDst(int source, int destination, int fix) {
int alpha;
switch (blendDst) {
case GeCommands.ALPHA_DESTINATION_COLOR:
return destination;
case GeCommands.ALPHA_ONE_MINUS_DESTINATION_COLOR:
return 0xFFFFFFFF - destination;
case GeCommands.ALPHA_SOURCE_ALPHA:
alpha = getAlpha(source);
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_ONE_MINUS_SOURCE_ALPHA:
alpha = ONE - getAlpha(source);
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_DESTINATION_ALPHA:
alpha = getAlpha(destination);
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_ONE_MINUS_DESTINATION_ALPHA:
alpha = ONE - getAlpha(destination);
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_DOUBLE_SOURCE_ALPHA:
alpha = doubleComponent(getAlpha(source));
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_ONE_MINUS_DOUBLE_SOURCE_ALPHA:
alpha = ONE - doubleComponent(getAlpha(source));
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_DOUBLE_DESTINATION_ALPHA:
alpha = doubleComponent(getAlpha(destination));
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_ONE_MINUS_DOUBLE_DESTINATION_ALPHA:
alpha = ONE - doubleComponent(getAlpha(destination));
return getColorBGR(alpha, alpha, alpha);
case GeCommands.ALPHA_FIX:
return fix;
}
return destination;
}
}
| false | true | private static void doRender(final BasePrimitiveRenderer renderer) {
final PixelState pixel = renderer.pixel;
final PrimitiveState prim = renderer.prim;
final IRendererWriter rendererWriter = renderer.rendererWriter;
final Lighting lighting = renderer.lighting;
IRandomTextureAccess textureAccess = resampleTexture(renderer);
doRenderStart(renderer);
int stencilRefAlpha = 0;
if (stencilTestFlagEnabled && !clearMode && stencilRef != 0) {
if (stencilOpFail == SOP_REPLACE_STENCIL_VALUE || stencilOpZFail == SOP_REPLACE_STENCIL_VALUE || stencilOpZPass == SOP_REPLACE_STENCIL_VALUE) {
// Prepare stencilRef as a ready-to-use alpha value
stencilRefAlpha = renderer.stencilRef << 24;
}
}
int stencilRefMasked = renderer.stencilRef & renderer.stencilMask;
int notColorMask = 0xFFFFFFFF;
if (!clearMode && colorMask != 0x00000000) {
notColorMask = ~renderer.colorMask;
}
int alpha, a, b, g, r;
int textureWidthMask = renderer.textureWidth - 1;
int textureHeightMask = renderer.textureHeight - 1;
float textureWidthFloat = renderer.textureWidth;
float textureHeightFloat = renderer.textureHeight;
final int alphaRef = renderer.alphaRef;
final int primSourceDepth = (int) prim.p2z;
float u = prim.uStart;
float v = prim.vStart;
ColorDepth colorDepth = new ColorDepth();
PrimarySecondaryColors colors = new PrimarySecondaryColors();
Range range = null;
Rasterizer rasterizer = null;
float t1uw = 0f;
float t1vw = 0f;
float t2uw = 0f;
float t2vw = 0f;
float t3uw = 0f;
float t3vw = 0f;
if (isTriangle) {
if (transform2D) {
t1uw = prim.t1u;
t1vw = prim.t1v;
t2uw = prim.t2u;
t2vw = prim.t2v;
t3uw = prim.t3u;
t3vw = prim.t3v;
} else {
t1uw = prim.t1u * prim.p1wInverted;
t1vw = prim.t1v * prim.p1wInverted;
t2uw = prim.t2u * prim.p2wInverted;
t2vw = prim.t2v * prim.p2wInverted;
t3uw = prim.t3u * prim.p3wInverted;
t3vw = prim.t3v * prim.p3wInverted;
}
range = new Range();
// No need to use a Rasterizer when rendering very small area.
// The overhead of the Rasterizer would lead to slower rendering.
if (prim.destinationWidth >= Rasterizer.MINIMUM_WIDTH && prim.destinationHeight >= Rasterizer.MINIMUM_HEIGHT) {
rasterizer = new Rasterizer(prim.p1x, prim.p1y, prim.p2x, prim.p2y, prim.p3x, prim.p3y, prim.pyMin, prim.pyMax);
rasterizer.setY(prim.pyMin);
}
}
int fbIndex = 0;
int depthIndex = 0;
int depthOffset = 0;
final int[] memInt = renderer.memInt;
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex = renderer.fbAddress >> 2;
depthIndex = renderer.depthAddress >> 2;
depthOffset = (renderer.depthAddress >> 1) & 1;
}
// Use local variables instead of "pixel" members.
// The Java JIT is then producing a slightly faster code.
int sourceColor = 0;
int sourceDepth = 0;
int destinationColor = 0;
int destinationDepth = 0;
int primaryColor = renderer.primaryColor;
int secondaryColor = 0;
float pixelU = 0f;
float pixelV = 0f;
boolean needResample = prim.needResample;
for (int y = prim.pyMin; y <= prim.pyMax; y++) {
int startX = prim.pxMin;
int endX = prim.pxMax;
if (isTriangle && rasterizer != null) {
rasterizer.getNextRange(range);
startX = max(range.xMin, startX);
endX = min(range.xMax, endX);
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Rasterizer line (%d-%d,%d)", startX, endX, y));
}
}
if (isTriangle && startX > endX) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex += prim.destinationWidth + renderer.imageWriterSkipEOL;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset += prim.destinationWidth + renderer.depthWriterSkipEOL;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(prim.destinationWidth + renderer.imageWriterSkipEOL, prim.destinationWidth + renderer.depthWriterSkipEOL);
}
} else {
if (needTextureUV && simpleTextureUV) {
if (swapTextureUV) {
v = prim.vStart;
} else {
u = prim.uStart;
}
}
if (isTriangle) {
int startSkip = startX - prim.pxMin;
if (startSkip > 0) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex += startSkip;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset += startSkip;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(startSkip, startSkip);
}
if (simpleTextureUV) {
if (swapTextureUV) {
v += startSkip * prim.vStep;
} else {
u += startSkip * prim.uStep;
}
}
}
prim.computeTriangleWeights(pixel, startX, y);
}
for (int x = startX; x <= endX; x++) {
// Use a dummy "do { } while (false);" loop to allow to exit
// quickly from the pixel rendering when a filter does not pass.
// When a filter does not pass, the following is executed:
// rendererWriter.skip(1, 1); // Skip the pixel
// continue;
do {
//
// Test if the pixel is inside the triangle
//
if (isTriangle && !pixel.isInsideTriangle()) {
// Pixel not inside triangle, skip the pixel
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d) outside triangle (%f, %f, %f)", x, y, pixel.triangleWeight1, pixel.triangleWeight2, pixel.triangleWeight3));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
//
// Start rendering the pixel
//
if (transform2D) {
pixel.newPixel2D();
} else {
pixel.newPixel3D();
}
//
// ScissorTest (performed as soon as the pixel screen coordinates are available)
//
if (transform2D) {
if (needScissoringX && needScissoringY) {
if (!(x >= renderer.scissorX1 && x <= renderer.scissorX2 && y >= renderer.scissorY1 && y <= renderer.scissorY2)) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
} else if (needScissoringX) {
if (!(x >= renderer.scissorX1 && x <= renderer.scissorX2)) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
} else if (needScissoringY) {
if (!(y >= renderer.scissorY1 && y <= renderer.scissorY2)) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
}
//
// Pixel source depth
//
if (needSourceDepthRead) {
if (isTriangle) {
sourceDepth = round(pixel.getTriangleWeightedValue(prim.p1z, prim.p2z, prim.p3z));
} else {
sourceDepth = primSourceDepth;
}
}
//
// ScissorDepthTest (performed as soon as the pixel source depth is available)
//
if (!transform2D && !clearMode && needSourceDepthRead) {
if (nearZ != 0x0000 || farZ != 0xFFFF) {
if (sourceDepth < renderer.nearZ || sourceDepth > renderer.farZ) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
}
//
// Pixel destination color and depth
//
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
destinationColor = memInt[fbIndex];
if (needDestinationDepthRead) {
if (depthOffset == 0) {
destinationDepth = memInt[depthIndex] & 0x0000FFFF;
} else {
destinationDepth = memInt[depthIndex] >>> 16;
}
}
} else {
rendererWriter.readCurrent(colorDepth);
destinationColor = colorDepth.color;
if (needDestinationDepthRead) {
destinationDepth = colorDepth.depth;
}
}
//
// StencilTest (performed as soon as destination color is known)
//
if (stencilTestFlagEnabled && !clearMode) {
switch (stencilFunc) {
case GeCommands.STST_FUNCTION_NEVER_PASS_STENCIL_TEST:
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.STST_FUNCTION_ALWAYS_PASS_STENCIL_TEST:
// Nothing to do
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_MATCHES:
if ((getAlpha(destinationColor) & renderer.stencilMask) != stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_DIFFERS:
if ((getAlpha(destinationColor) & renderer.stencilMask) == stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_LESS:
if ((getAlpha(destinationColor) & renderer.stencilMask) >= stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_LESS_OR_EQUAL:
if ((getAlpha(destinationColor) & renderer.stencilMask) > stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_GREATER:
if ((getAlpha(destinationColor) & renderer.stencilMask) <= stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_GREATER_OR_EQUAL:
if ((getAlpha(destinationColor) & renderer.stencilMask) < stencilRefMasked) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
}
}
//
// DepthTest (performed as soon as depths are known, but after the stencil test)
//
if (depthTestFlagEnabled && !clearMode) {
switch (depthFunc) {
case GeCommands.ZTST_FUNCTION_NEVER_PASS_PIXEL:
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.ZTST_FUNCTION_ALWAYS_PASS_PIXEL:
// No filter required
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_EQUAL:
if (sourceDepth != destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_ISNOT_EQUAL:
if (sourceDepth == destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_LESS:
if (sourceDepth >= destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_LESS_OR_EQUAL:
if (sourceDepth > destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_GREATER:
if (sourceDepth <= destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_GREATER_OR_EQUAL:
if (sourceDepth < destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
}
}
//
// Primary color
//
if (setVertexPrimaryColor) {
if (isTriangle) {
if (sameVertexColor) {
primaryColor = pixel.c3;
} else {
primaryColor = pixel.getTriangleColorWeightedValue();
}
}
}
//
// Material Flags
//
if (lightingFlagEnabled && !transform2D && useVertexColor && isTriangle) {
if (matFlagAmbient) {
pixel.materialAmbient = primaryColor;
}
if (matFlagDiffuse) {
pixel.materialDiffuse = primaryColor;
}
if (matFlagSpecular) {
pixel.materialSpecular = primaryColor;
}
}
//
// Lighting
//
if (lightingFlagEnabled && !transform2D) {
lighting.applyLighting(colors, pixel);
primaryColor = colors.primaryColor;
secondaryColor = colors.secondaryColor;
}
//
// Pixel texture U,V
//
if (needTextureUV) {
if (simpleTextureUV) {
pixelU = u;
pixelV = v;
} else {
// Compute the mapped texture u,v coordinates
// based on the Barycentric coordinates.
pixelU = pixel.getTriangleWeightedValue(t1uw, t2uw, t3uw);
pixelV = pixel.getTriangleWeightedValue(t1vw, t2vw, t3vw);
if (!transform2D) {
// In 3D, apply a perspective correction by weighting
// the coordinates by their "w" value. See
// http://en.wikipedia.org/wiki/Texture_mapping#Perspective_correctness
float weightInverted = 1.f / pixel.getTriangleWeightedValue(prim.p1wInverted, prim.p2wInverted, prim.p3wInverted);
pixelU *= weightInverted;
pixelV *= weightInverted;
}
}
}
//
// Texture
//
if (textureFlagEnabled && (!transform2D || useVertexTexture) && !clearMode) {
//
// TextureMapping
//
if (!transform2D) {
switch (texMapMode) {
case GeCommands.TMAP_TEXTURE_MAP_MODE_TEXTURE_COORDIATES_UV:
if (texScaleX != 1f) {
pixelU *= renderer.texScaleX;
}
if (texTranslateX != 0f) {
pixelU += renderer.texTranslateX;
}
if (texScaleY != 1f) {
pixelV *= renderer.texScaleY;
}
if (texTranslateY != 0f) {
pixelV += renderer.texTranslateY;
}
break;
case GeCommands.TMAP_TEXTURE_MAP_MODE_TEXTURE_MATRIX:
switch (texProjMapMode) {
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_POSITION:
final float[] V = pixel.getV();
pixelU = V[0] * pixel.textureMatrix[0] + V[1] * pixel.textureMatrix[4] + V[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12];
pixelV = V[0] * pixel.textureMatrix[1] + V[1] * pixel.textureMatrix[5] + V[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13];
//pixelQ = V[0] * pixel.textureMatrix[2] + V[1] * pixel.textureMatrix[6] + V[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14];
break;
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_TEXTURE_COORDINATES:
float tu = pixelU;
float tv = pixelV;
pixelU = tu * pixel.textureMatrix[0] + tv * pixel.textureMatrix[4] + pixel.textureMatrix[12];
pixelV = tu * pixel.textureMatrix[1] + tv * pixel.textureMatrix[5] + pixel.textureMatrix[13];
//pixelQ = tu * pixel.textureMatrix[2] + tv * pixel.textureMatrix[6] + pixel.textureMatrix[14];
break;
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_NORMALIZED_NORMAL:
final float[] normalizedN = pixel.getNormalizedN();
pixelU = normalizedN[0] * pixel.textureMatrix[0] + normalizedN[1] * pixel.textureMatrix[4] + normalizedN[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12];
pixelV = normalizedN[0] * pixel.textureMatrix[1] + normalizedN[1] * pixel.textureMatrix[5] + normalizedN[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13];
//pixelQ = normalizedN[0] * pixel.textureMatrix[2] + normalizedN[1] * pixel.textureMatrix[6] + normalizedN[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14];
break;
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_NORMAL:
final float[] N = pixel.getN();
pixelU = N[0] * pixel.textureMatrix[0] + N[1] * pixel.textureMatrix[4] + N[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12];
pixelV = N[0] * pixel.textureMatrix[1] + N[1] * pixel.textureMatrix[5] + N[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13];
//pixelQ = N[0] * pixel.textureMatrix[2] + N[1] * pixel.textureMatrix[6] + N[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14];
break;
}
break;
case GeCommands.TMAP_TEXTURE_MAP_MODE_ENVIRONMENT_MAP:
// Implementation based on shader.vert/ApplyTexture:
//
// vec3 Nn = normalize(N);
// vec3 Ve = vec3(gl_ModelViewMatrix * V);
// float k = gl_FrontMaterial.shininess;
// vec3 Lu = gl_LightSource[texShade.x].position.xyz - Ve.xyz * gl_LightSource[texShade.x].position.w;
// vec3 Lv = gl_LightSource[texShade.y].position.xyz - Ve.xyz * gl_LightSource[texShade.y].position.w;
// float Pu = psp_lightKind[texShade.x] == 0 ? dot(Nn, normalize(Lu)) : pow(dot(Nn, normalize(Lu + vec3(0.0, 0.0, 1.0))), k);
// float Pv = psp_lightKind[texShade.y] == 0 ? dot(Nn, normalize(Lv)) : pow(dot(Nn, normalize(Lv + vec3(0.0, 0.0, 1.0))), k);
// T.xyz = vec3(0.5*vec2(1.0 + Pu, 1.0 + Pv), 1.0);
//
final float[] Ve = new float[3];
final float[] Ne = new float[3];
final float[] Lu = new float[3];
final float[] Lv = new float[3];
pixel.getVe(Ve);
pixel.getNormalizedNe(Ne);
for (int i = 0; i < 3; i++) {
Lu[i] = renderer.envMapLightPosU[i] - Ve[i] * renderer.envMapLightPosU[3];
Lv[i] = renderer.envMapLightPosV[i] - Ve[i] * renderer.envMapLightPosV[3];
}
float Pu;
if (renderer.envMapDiffuseLightU) {
normalize3(Lu, Lu);
Pu = dot3(Ne, Lu);
} else {
Lu[2] += 1f;
normalize3(Lu, Lu);
Pu = (float) Math.pow(dot3(Ne, Lu), renderer.envMapShininess);
}
float Pv;
if (renderer.envMapDiffuseLightV) {
normalize3(Lv, Lv);
Pv = dot3(Ne, Lv);
} else {
Lv[2] += 1f;
normalize3(Lv, Lv);
Pv = (float) Math.pow(dot3(Ne, Lv), renderer.envMapShininess);
}
pixelU = (Pu + 1f) * 0.5f;
pixelV = (Pv + 1f) * 0.5f;
//pixelQ = 1f;
break;
}
}
//
// Texture resampling (as late as possible)
//
if (texMagFilter == GeCommands.TFLT_LINEAR) {
if (needResample) {
// Perform the resampling as late as possible.
// We might be lucky that all the pixel are eliminated
// by the depth or stencil tests. In which case,
// we don't need to resample.
textureAccess = renderer.cachedTexture.resample(prim.resampleFactorWidth, prim.resampleFactorHeight);
textureWidthMask = textureAccess.getWidth() - 1;
textureHeightMask = textureAccess.getHeight() - 1;
textureWidthFloat = textureAccess.getWidth();
textureHeightFloat = textureAccess.getHeight();
needResample = false;
}
}
//
// TextureWrap
//
if (needTextureWrapU) {
switch (texWrapS) {
case GeCommands.TWRAP_WRAP_MODE_REPEAT:
if (transform2D) {
pixelU = wrap(pixelU, textureWidthMask);
} else {
pixelU = wrap(pixelU);
}
break;
case GeCommands.TWRAP_WRAP_MODE_CLAMP:
if (transform2D) {
pixelU = clamp(pixelU, 0f, textureWidthMask);
} else {
// Clamp to [0..1[ (1 is excluded)
pixelU = clamp(pixelU, 0f, 0.99999f);
}
break;
}
}
if (needTextureWrapV) {
switch (texWrapT) {
case GeCommands.TWRAP_WRAP_MODE_REPEAT:
if (transform2D) {
pixelV = wrap(pixelV, textureHeightMask);
} else {
pixelV = wrap(pixelV);
}
break;
case GeCommands.TWRAP_WRAP_MODE_CLAMP:
if (transform2D) {
pixelV = clamp(pixelV, 0f, textureHeightMask);
} else {
// Clamp to [0..1[ (1 is excluded)
pixelV = clamp(pixelV, 0f, 0.99999f);
}
break;
}
}
//
// TextureReader
//
if (transform2D) {
sourceColor = textureAccess.readPixel(pixelToTexel(pixelU), pixelToTexel(pixelV));
} else {
sourceColor = textureAccess.readPixel(pixelToTexel(pixelU * textureWidthFloat), pixelToTexel(pixelV * textureHeightFloat));
}
//
// TextureFunction
//
switch (textureFunc) {
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_MODULATE:
if (textureAlphaUsed) {
sourceColor = multiply(sourceColor, primaryColor);
} else {
sourceColor = multiply(sourceColor | 0xFF000000, primaryColor);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_DECAL:
if (textureAlphaUsed) {
alpha = getAlpha(sourceColor);
a = getAlpha(primaryColor);
b = combineComponent(getBlue(primaryColor), getBlue(sourceColor), alpha);
g = combineComponent(getGreen(primaryColor), getGreen(sourceColor), alpha);
r = combineComponent(getRed(primaryColor), getRed(sourceColor), alpha);
sourceColor = getColor(a, b, g, r);
} else {
sourceColor = (sourceColor & 0x00FFFFFF) | (primaryColor & 0xFF000000);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_BLEND:
if (textureAlphaUsed) {
a = multiplyComponent(getAlpha(sourceColor), getAlpha(primaryColor));
b = combineComponent(getBlue(primaryColor), renderer.texEnvColorB, getBlue(sourceColor));
g = combineComponent(getGreen(primaryColor), renderer.texEnvColorG, getGreen(sourceColor));
r = combineComponent(getRed(primaryColor), renderer.texEnvColorR, getRed(sourceColor));
sourceColor = getColor(a, b, g, r);
} else {
a = getAlpha(primaryColor);
b = combineComponent(getBlue(primaryColor), renderer.texEnvColorB, getBlue(sourceColor));
g = combineComponent(getGreen(primaryColor), renderer.texEnvColorG, getGreen(sourceColor));
r = combineComponent(getRed(primaryColor), renderer.texEnvColorR, getRed(sourceColor));
sourceColor = getColor(a, b, g, r);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_REPLACE:
if (!textureAlphaUsed) {
sourceColor = (sourceColor & 0x00FFFFFF) | (primaryColor & 0xFF000000);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_ADD:
if (textureAlphaUsed) {
a = multiplyComponent(getAlpha(sourceColor), getAlpha(primaryColor));
sourceColor = setAlpha(addBGR(sourceColor, primaryColor), a);
} else {
sourceColor = add(sourceColor & 0x00FFFFFF, primaryColor);
}
break;
}
//
// ColorDoubling
//
if (textureColorDoubled) {
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
sourceColor = doubleColor(sourceColor);
secondaryColor = doubleColor(secondaryColor);
} else {
sourceColor = doubleColor(sourceColor);
}
}
//
// SourceColor
//
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
sourceColor = add(sourceColor, secondaryColor);
}
} else {
//
// ColorDoubling
//
if (textureColorDoubled) {
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
primaryColor = doubleColor(primaryColor);
secondaryColor = doubleColor(secondaryColor);
} else if (!primaryColorSetGlobally) {
primaryColor = doubleColor(primaryColor);
}
}
//
// SourceColor
//
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
sourceColor = add(primaryColor, secondaryColor);
} else {
sourceColor = primaryColor;
}
}
//
// ColorTest
//
if (colorTestFlagEnabled && !clearMode) {
switch (colorTestFunc) {
case GeCommands.CTST_COLOR_FUNCTION_ALWAYS_PASS_PIXEL:
// Nothing to do
break;
case GeCommands.CTST_COLOR_FUNCTION_NEVER_PASS_PIXEL:
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.CTST_COLOR_FUNCTION_PASS_PIXEL_IF_COLOR_MATCHES:
if ((sourceColor & renderer.colorTestMsk) != renderer.colorTestRef) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.CTST_COLOR_FUNCTION_PASS_PIXEL_IF_COLOR_DIFFERS:
if ((sourceColor & renderer.colorTestMsk) == renderer.colorTestRef) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
}
}
//
// AlphaTest
//
if (alphaTestFlagEnabled && !clearMode) {
switch (alphaFunc) {
case GeCommands.ATST_ALWAYS_PASS_PIXEL:
// Nothing to do
break;
case GeCommands.ATST_NEVER_PASS_PIXEL:
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.ATST_PASS_PIXEL_IF_MATCHES:
if (getAlpha(sourceColor) != alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_DIFFERS:
if (getAlpha(sourceColor) == alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_LESS:
if (getAlpha(sourceColor) >= alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_LESS_OR_EQUAL:
// No test if alphaRef==0xFF
if (RendererTemplate.alphaRef < 0xFF) {
if (getAlpha(sourceColor) > alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_GREATER:
if (getAlpha(sourceColor) <= alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_GREATER_OR_EQUAL:
// No test if alphaRef==0x00
if (RendererTemplate.alphaRef > 0x00) {
if (getAlpha(sourceColor) < alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
break;
}
}
//
// AlphaBlend
//
if (blendFlagEnabled && !clearMode) {
int filteredSrc;
int filteredDst;
switch (blendEquation) {
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_ADD:
if (blendSrc == GeCommands.ALPHA_FIX && sfix == 0xFFFFFF &&
blendDst == GeCommands.ALPHA_FIX && dfix == 0x000000) {
// Nothing to do, this is a NOP
} else if (blendSrc == GeCommands.ALPHA_FIX && sfix == 0xFFFFFF &&
blendDst == GeCommands.ALPHA_FIX && dfix == 0xFFFFFF) {
sourceColor = PixelColor.add(sourceColor, destinationColor & 0x00FFFFFF);
} else if (blendSrc == GeCommands.ALPHA_SOURCE_ALPHA && blendDst == GeCommands.ALPHA_ONE_MINUS_SOURCE_ALPHA) {
// This is the most common case and can be optimized
int srcAlpha = sourceColor >>> 24;
if (srcAlpha == ZERO) {
// Set color of destination
sourceColor = (sourceColor & 0xFF000000) | (destinationColor & 0x00FFFFFF);
} else if (srcAlpha == ONE) {
// Nothing to change
} else {
int oneMinusSrcAlpha = ONE - srcAlpha;
filteredSrc = multiplyBGR(sourceColor, srcAlpha, srcAlpha, srcAlpha);
filteredDst = multiplyBGR(destinationColor, oneMinusSrcAlpha, oneMinusSrcAlpha, oneMinusSrcAlpha);
sourceColor = setBGR(sourceColor, addBGR(filteredSrc, filteredDst));
}
} else {
filteredSrc = multiplyBGR(sourceColor, blendSrc(sourceColor, destinationColor, renderer.sfix));
filteredDst = multiplyBGR(destinationColor, blendDst(sourceColor, destinationColor, renderer.dfix));
sourceColor = setBGR(sourceColor, addBGR(filteredSrc, filteredDst));
}
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_SUBTRACT:
filteredSrc = multiplyBGR(sourceColor, blendSrc(sourceColor, destinationColor, renderer.sfix));
filteredDst = multiplyBGR(destinationColor, blendDst(sourceColor, destinationColor, renderer.dfix));
sourceColor = setBGR(sourceColor, substractBGR(filteredSrc, filteredDst));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_REVERSE_SUBTRACT:
filteredSrc = multiplyBGR(sourceColor, blendSrc(sourceColor, destinationColor, renderer.sfix));
filteredDst = multiplyBGR(destinationColor, blendDst(sourceColor, destinationColor, renderer.dfix));
sourceColor = setBGR(sourceColor, substractBGR(filteredDst, filteredSrc));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_MINIMUM_VALUE:
// Source and destination factors are not applied
sourceColor = setBGR(sourceColor, minBGR(sourceColor, destinationColor));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_MAXIMUM_VALUE:
// Source and destination factors are not applied
sourceColor = setBGR(sourceColor, maxBGR(sourceColor, destinationColor));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_ABSOLUTE_VALUE:
// Source and destination factors are not applied
sourceColor = setBGR(sourceColor, absBGR(sourceColor, destinationColor));
break;
}
}
if (ditherFlagEnabled) {
int ditherValue = renderer.ditherMatrix[((y & 0x3) << 2) + (x & 0x3)];
if (ditherValue > 0) {
b = addComponent(getBlue(sourceColor), ditherValue);
g = addComponent(getGreen(sourceColor), ditherValue);
r = addComponent(getRed(sourceColor), ditherValue);
sourceColor = setBGR(sourceColor, getColorBGR(b, g, r));
} else if (ditherValue < 0) {
ditherValue = -ditherValue;
b = substractComponent(getBlue(sourceColor), ditherValue);
g = substractComponent(getGreen(sourceColor), ditherValue);
r = substractComponent(getRed(sourceColor), ditherValue);
sourceColor = setBGR(sourceColor, getColorBGR(b, g, r));
}
}
//
// StencilOpZPass
//
if (stencilTestFlagEnabled && !clearMode) {
switch (stencilOpZPass) {
case GeCommands.SOP_KEEP_STENCIL_VALUE:
sourceColor = (sourceColor & 0x00FFFFFF) | (destinationColor & 0xFF000000);
break;
case GeCommands.SOP_ZERO_STENCIL_VALUE:
sourceColor &= 0x00FFFFFF;
break;
case GeCommands.SOP_REPLACE_STENCIL_VALUE:
if (stencilRef == 0) {
// SOP_REPLACE_STENCIL_VALUE with a 0 value is equivalent
// to SOP_ZERO_STENCIL_VALUE
sourceColor &= 0x00FFFFFF;
} else {
sourceColor = (sourceColor & 0x00FFFFFF) | stencilRefAlpha;
}
break;
case GeCommands.SOP_INVERT_STENCIL_VALUE:
sourceColor = (sourceColor & 0x00FFFFFF) | ((~destinationColor) & 0xFF000000);
break;
case GeCommands.SOP_INCREMENT_STENCIL_VALUE:
alpha = destinationColor & 0xFF000000;
if (alpha != 0xFF000000) {
alpha += 0x01000000;
}
sourceColor = (sourceColor & 0x00FFFFFF) | alpha;
break;
case GeCommands.SOP_DECREMENT_STENCIL_VALUE:
alpha = destinationColor & 0xFF000000;
if (alpha != 0x00000000) {
alpha -= 0x01000000;
}
sourceColor = (sourceColor & 0x00FFFFFF) | alpha;
break;
}
} else if (!clearMode) {
// Write the alpha/stencil value to the frame buffer
// only when the stencil test is enabled
sourceColor = (sourceColor & 0x00FFFFFF) | (destinationColor & 0xFF000000);
}
//
// ColorLogicalOperation
//
if (colorLogicOpFlagEnabled && !clearMode) {
switch (logicOp) {
case GeCommands.LOP_CLEAR:
sourceColor = ZERO;
break;
case GeCommands.LOP_AND:
sourceColor &= destinationColor;
break;
case GeCommands.LOP_REVERSE_AND:
sourceColor &= (~destinationColor);
break;
case GeCommands.LOP_COPY:
// This is a NOP
break;
case GeCommands.LOP_INVERTED_AND:
sourceColor = (~sourceColor) & destinationColor;
break;
case GeCommands.LOP_NO_OPERATION:
sourceColor = destinationColor;
break;
case GeCommands.LOP_EXLUSIVE_OR:
sourceColor ^= destinationColor;
break;
case GeCommands.LOP_OR:
sourceColor |= destinationColor;
break;
case GeCommands.LOP_NEGATED_OR:
sourceColor = ~(sourceColor | destinationColor);
break;
case GeCommands.LOP_EQUIVALENCE:
sourceColor = ~(sourceColor ^ destinationColor);
break;
case GeCommands.LOP_INVERTED:
sourceColor = ~destinationColor;
break;
case GeCommands.LOP_REVERSE_OR:
sourceColor |= (~destinationColor);
break;
case GeCommands.LOP_INVERTED_COPY:
sourceColor = ~sourceColor;
break;
case GeCommands.LOP_INVERTED_OR:
sourceColor = (~sourceColor) | destinationColor;
break;
case GeCommands.LOP_NEGATED_AND:
sourceColor = ~(sourceColor & destinationColor);
break;
case GeCommands.LOP_SET:
sourceColor = 0xFFFFFFFF;
break;
}
}
//
// ColorMask
//
if (clearMode) {
if (clearModeColor) {
if (!clearModeStencil) {
sourceColor = (sourceColor & 0x00FFFFFF) | (destinationColor & 0xFF000000);
}
} else {
if (clearModeStencil) {
sourceColor = (sourceColor & 0xFF000000) | (destinationColor & 0x00FFFFFF);
} else {
sourceColor = destinationColor;
}
}
} else {
if (colorMask != 0x00000000) {
sourceColor = (sourceColor & notColorMask) | (destinationColor & renderer.colorMask);
}
}
//
// DepthMask
//
if (needDepthWrite) {
if (clearMode) {
if (!clearModeDepth) {
sourceDepth = destinationDepth;
}
} else if (!depthTestFlagEnabled) {
// Depth writes are disabled when the depth test is not enabled.
sourceDepth = destinationDepth;
} else if (!depthMask) {
sourceDepth = destinationDepth;
}
}
//
// Filter passed
//
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), passed=true, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (needDepthWrite && needSourceDepthClamp) {
// Clamp between 0 and 65535
sourceDepth = Math.max(0, Math.min(sourceDepth, 65535));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
memInt[fbIndex] = sourceColor;
fbIndex++;
if (needDepthWrite) {
if (depthOffset == 0) {
memInt[depthIndex] = (memInt[depthIndex] & 0xFFFF0000) | (sourceDepth & 0x0000FFFF);
depthOffset = 1;
} else {
memInt[depthIndex] = (memInt[depthIndex] & 0x0000FFFF) | (sourceDepth << 16);
depthIndex++;
depthOffset = 0;
}
} else if (needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
if (needDepthWrite) {
colorDepth.color = sourceColor;
colorDepth.depth = sourceDepth;
rendererWriter.writeNext(colorDepth);
} else {
rendererWriter.writeNextColor(sourceColor);
}
}
} while (false);
if (needTextureUV && simpleTextureUV) {
if (swapTextureUV) {
v += prim.vStep;
} else {
u += prim.uStep;
}
}
if (isTriangle) {
prim.deltaXTriangleWeigths(pixel);
}
}
int skip = prim.pxMax - endX;
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex += skip + renderer.imageWriterSkipEOL;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset += skip + renderer.depthWriterSkipEOL;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(skip + renderer.imageWriterSkipEOL, skip + renderer.depthWriterSkipEOL);
}
}
if (needTextureUV && simpleTextureUV) {
if (swapTextureUV) {
u += prim.uStep;
} else {
v += prim.vStep;
}
}
}
doRenderEnd(renderer);
}
| private static void doRender(final BasePrimitiveRenderer renderer) {
final PixelState pixel = renderer.pixel;
final PrimitiveState prim = renderer.prim;
final IRendererWriter rendererWriter = renderer.rendererWriter;
final Lighting lighting = renderer.lighting;
IRandomTextureAccess textureAccess = resampleTexture(renderer);
doRenderStart(renderer);
int stencilRefAlpha = 0;
if (stencilTestFlagEnabled && !clearMode && stencilRef != 0) {
if (stencilOpFail == SOP_REPLACE_STENCIL_VALUE || stencilOpZFail == SOP_REPLACE_STENCIL_VALUE || stencilOpZPass == SOP_REPLACE_STENCIL_VALUE) {
// Prepare stencilRef as a ready-to-use alpha value
stencilRefAlpha = renderer.stencilRef << 24;
}
}
int stencilRefMasked = renderer.stencilRef & renderer.stencilMask;
int notColorMask = 0xFFFFFFFF;
if (!clearMode && colorMask != 0x00000000) {
notColorMask = ~renderer.colorMask;
}
int alpha, a, b, g, r;
int textureWidthMask = renderer.textureWidth - 1;
int textureHeightMask = renderer.textureHeight - 1;
float textureWidthFloat = renderer.textureWidth;
float textureHeightFloat = renderer.textureHeight;
final int alphaRef = renderer.alphaRef;
final int primSourceDepth = (int) prim.p2z;
float u = prim.uStart;
float v = prim.vStart;
ColorDepth colorDepth = new ColorDepth();
PrimarySecondaryColors colors = new PrimarySecondaryColors();
Range range = null;
Rasterizer rasterizer = null;
float t1uw = 0f;
float t1vw = 0f;
float t2uw = 0f;
float t2vw = 0f;
float t3uw = 0f;
float t3vw = 0f;
if (isTriangle) {
if (transform2D) {
t1uw = prim.t1u;
t1vw = prim.t1v;
t2uw = prim.t2u;
t2vw = prim.t2v;
t3uw = prim.t3u;
t3vw = prim.t3v;
} else {
t1uw = prim.t1u * prim.p1wInverted;
t1vw = prim.t1v * prim.p1wInverted;
t2uw = prim.t2u * prim.p2wInverted;
t2vw = prim.t2v * prim.p2wInverted;
t3uw = prim.t3u * prim.p3wInverted;
t3vw = prim.t3v * prim.p3wInverted;
}
range = new Range();
// No need to use a Rasterizer when rendering very small area.
// The overhead of the Rasterizer would lead to slower rendering.
if (prim.destinationWidth >= Rasterizer.MINIMUM_WIDTH && prim.destinationHeight >= Rasterizer.MINIMUM_HEIGHT) {
rasterizer = new Rasterizer(prim.p1x, prim.p1y, prim.p2x, prim.p2y, prim.p3x, prim.p3y, prim.pyMin, prim.pyMax);
rasterizer.setY(prim.pyMin);
}
}
int fbIndex = 0;
int depthIndex = 0;
int depthOffset = 0;
final int[] memInt = renderer.memInt;
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex = renderer.fbAddress >> 2;
depthIndex = renderer.depthAddress >> 2;
depthOffset = (renderer.depthAddress >> 1) & 1;
}
// Use local variables instead of "pixel" members.
// The Java JIT is then producing a slightly faster code.
int sourceColor = 0;
int sourceDepth = 0;
int destinationColor = 0;
int destinationDepth = 0;
int primaryColor = renderer.primaryColor;
int secondaryColor = 0;
float pixelU = 0f;
float pixelV = 0f;
boolean needResample = prim.needResample;
for (int y = prim.pyMin; y <= prim.pyMax; y++) {
int startX = prim.pxMin;
int endX = prim.pxMax;
if (isTriangle && rasterizer != null) {
rasterizer.getNextRange(range);
startX = max(range.xMin, startX);
endX = min(range.xMax, endX);
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Rasterizer line (%d-%d,%d)", startX, endX, y));
}
}
if (isTriangle && startX > endX) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex += prim.destinationWidth + renderer.imageWriterSkipEOL;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset += prim.destinationWidth + renderer.depthWriterSkipEOL;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(prim.destinationWidth + renderer.imageWriterSkipEOL, prim.destinationWidth + renderer.depthWriterSkipEOL);
}
} else {
if (needTextureUV && simpleTextureUV) {
if (swapTextureUV) {
v = prim.vStart;
} else {
u = prim.uStart;
}
}
if (isTriangle) {
int startSkip = startX - prim.pxMin;
if (startSkip > 0) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex += startSkip;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset += startSkip;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(startSkip, startSkip);
}
if (simpleTextureUV) {
if (swapTextureUV) {
v += startSkip * prim.vStep;
} else {
u += startSkip * prim.uStep;
}
}
}
prim.computeTriangleWeights(pixel, startX, y);
}
for (int x = startX; x <= endX; x++) {
// Use a dummy "do { } while (false);" loop to allow to exit
// quickly from the pixel rendering when a filter does not pass.
// When a filter does not pass, the following is executed:
// rendererWriter.skip(1, 1); // Skip the pixel
// continue;
do {
//
// Test if the pixel is inside the triangle
//
if (isTriangle && !pixel.isInsideTriangle()) {
// Pixel not inside triangle, skip the pixel
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d) outside triangle (%f, %f, %f)", x, y, pixel.triangleWeight1, pixel.triangleWeight2, pixel.triangleWeight3));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
//
// Start rendering the pixel
//
if (transform2D) {
pixel.newPixel2D();
} else {
pixel.newPixel3D();
}
//
// ScissorTest (performed as soon as the pixel screen coordinates are available)
//
if (transform2D) {
if (needScissoringX && needScissoringY) {
if (!(x >= renderer.scissorX1 && x <= renderer.scissorX2 && y >= renderer.scissorY1 && y <= renderer.scissorY2)) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
} else if (needScissoringX) {
if (!(x >= renderer.scissorX1 && x <= renderer.scissorX2)) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
} else if (needScissoringY) {
if (!(y >= renderer.scissorY1 && y <= renderer.scissorY2)) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
}
//
// Pixel source depth
//
if (needSourceDepthRead) {
if (isTriangle) {
sourceDepth = round(pixel.getTriangleWeightedValue(prim.p1z, prim.p2z, prim.p3z));
} else {
sourceDepth = primSourceDepth;
}
}
//
// ScissorDepthTest (performed as soon as the pixel source depth is available)
//
if (!transform2D && !clearMode && needSourceDepthRead) {
if (nearZ != 0x0000 || farZ != 0xFFFF) {
if (sourceDepth < renderer.nearZ || sourceDepth > renderer.farZ) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
}
//
// Pixel destination color and depth
//
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
destinationColor = memInt[fbIndex];
if (needDestinationDepthRead) {
if (depthOffset == 0) {
destinationDepth = memInt[depthIndex] & 0x0000FFFF;
} else {
destinationDepth = memInt[depthIndex] >>> 16;
}
}
} else {
rendererWriter.readCurrent(colorDepth);
destinationColor = colorDepth.color;
if (needDestinationDepthRead) {
destinationDepth = colorDepth.depth;
}
}
//
// StencilTest (performed as soon as destination color is known)
//
if (stencilTestFlagEnabled && !clearMode) {
switch (stencilFunc) {
case GeCommands.STST_FUNCTION_NEVER_PASS_STENCIL_TEST:
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.STST_FUNCTION_ALWAYS_PASS_STENCIL_TEST:
// Nothing to do
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_MATCHES:
if (stencilRefMasked != (getAlpha(destinationColor) & renderer.stencilMask)) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_DIFFERS:
if (stencilRefMasked == (getAlpha(destinationColor) & renderer.stencilMask)) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_LESS:
// Pass if the reference value is less than the destination value
if (stencilRefMasked >= (getAlpha(destinationColor) & renderer.stencilMask)) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_LESS_OR_EQUAL:
// Pass if the reference value is less or equal to the destination value
if (stencilRefMasked > (getAlpha(destinationColor) & renderer.stencilMask)) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_GREATER:
// Pass if the reference value is greater than the destination value
if (stencilRefMasked <= (getAlpha(destinationColor) & renderer.stencilMask)) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.STST_FUNCTION_PASS_TEST_IF_GREATER_OR_EQUAL:
// Pass if the reference value is greater or equal to the destination value
if (stencilRefMasked < (getAlpha(destinationColor) & renderer.stencilMask)) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), stencil test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (stencilOpFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
}
}
//
// DepthTest (performed as soon as depths are known, but after the stencil test)
//
if (depthTestFlagEnabled && !clearMode) {
switch (depthFunc) {
case GeCommands.ZTST_FUNCTION_NEVER_PASS_PIXEL:
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.ZTST_FUNCTION_ALWAYS_PASS_PIXEL:
// No filter required
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_EQUAL:
if (sourceDepth != destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_ISNOT_EQUAL:
if (sourceDepth == destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_LESS:
if (sourceDepth >= destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_LESS_OR_EQUAL:
if (sourceDepth > destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_GREATER:
if (sourceDepth <= destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ZTST_FUNCTION_PASS_PX_WHEN_DEPTH_IS_GREATER_OR_EQUAL:
if (sourceDepth < destinationDepth) {
if (stencilTestFlagEnabled && stencilOpZFail != GeCommands.SOP_KEEP_STENCIL_VALUE) {
destinationColor = stencilOpZFail(destinationColor, stencilRefAlpha);
}
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), depth test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
}
}
//
// Primary color
//
if (setVertexPrimaryColor) {
if (isTriangle) {
if (sameVertexColor) {
primaryColor = pixel.c3;
} else {
primaryColor = pixel.getTriangleColorWeightedValue();
}
}
}
//
// Material Flags
//
if (lightingFlagEnabled && !transform2D && useVertexColor && isTriangle) {
if (matFlagAmbient) {
pixel.materialAmbient = primaryColor;
}
if (matFlagDiffuse) {
pixel.materialDiffuse = primaryColor;
}
if (matFlagSpecular) {
pixel.materialSpecular = primaryColor;
}
}
//
// Lighting
//
if (lightingFlagEnabled && !transform2D) {
lighting.applyLighting(colors, pixel);
primaryColor = colors.primaryColor;
secondaryColor = colors.secondaryColor;
}
//
// Pixel texture U,V
//
if (needTextureUV) {
if (simpleTextureUV) {
pixelU = u;
pixelV = v;
} else {
// Compute the mapped texture u,v coordinates
// based on the Barycentric coordinates.
pixelU = pixel.getTriangleWeightedValue(t1uw, t2uw, t3uw);
pixelV = pixel.getTriangleWeightedValue(t1vw, t2vw, t3vw);
if (!transform2D) {
// In 3D, apply a perspective correction by weighting
// the coordinates by their "w" value. See
// http://en.wikipedia.org/wiki/Texture_mapping#Perspective_correctness
float weightInverted = 1.f / pixel.getTriangleWeightedValue(prim.p1wInverted, prim.p2wInverted, prim.p3wInverted);
pixelU *= weightInverted;
pixelV *= weightInverted;
}
}
}
//
// Texture
//
if (textureFlagEnabled && (!transform2D || useVertexTexture) && !clearMode) {
//
// TextureMapping
//
if (!transform2D) {
switch (texMapMode) {
case GeCommands.TMAP_TEXTURE_MAP_MODE_TEXTURE_COORDIATES_UV:
if (texScaleX != 1f) {
pixelU *= renderer.texScaleX;
}
if (texTranslateX != 0f) {
pixelU += renderer.texTranslateX;
}
if (texScaleY != 1f) {
pixelV *= renderer.texScaleY;
}
if (texTranslateY != 0f) {
pixelV += renderer.texTranslateY;
}
break;
case GeCommands.TMAP_TEXTURE_MAP_MODE_TEXTURE_MATRIX:
switch (texProjMapMode) {
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_POSITION:
final float[] V = pixel.getV();
pixelU = V[0] * pixel.textureMatrix[0] + V[1] * pixel.textureMatrix[4] + V[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12];
pixelV = V[0] * pixel.textureMatrix[1] + V[1] * pixel.textureMatrix[5] + V[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13];
//pixelQ = V[0] * pixel.textureMatrix[2] + V[1] * pixel.textureMatrix[6] + V[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14];
break;
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_TEXTURE_COORDINATES:
float tu = pixelU;
float tv = pixelV;
pixelU = tu * pixel.textureMatrix[0] + tv * pixel.textureMatrix[4] + pixel.textureMatrix[12];
pixelV = tu * pixel.textureMatrix[1] + tv * pixel.textureMatrix[5] + pixel.textureMatrix[13];
//pixelQ = tu * pixel.textureMatrix[2] + tv * pixel.textureMatrix[6] + pixel.textureMatrix[14];
break;
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_NORMALIZED_NORMAL:
final float[] normalizedN = pixel.getNormalizedN();
pixelU = normalizedN[0] * pixel.textureMatrix[0] + normalizedN[1] * pixel.textureMatrix[4] + normalizedN[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12];
pixelV = normalizedN[0] * pixel.textureMatrix[1] + normalizedN[1] * pixel.textureMatrix[5] + normalizedN[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13];
//pixelQ = normalizedN[0] * pixel.textureMatrix[2] + normalizedN[1] * pixel.textureMatrix[6] + normalizedN[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14];
break;
case GeCommands.TMAP_TEXTURE_PROJECTION_MODE_NORMAL:
final float[] N = pixel.getN();
pixelU = N[0] * pixel.textureMatrix[0] + N[1] * pixel.textureMatrix[4] + N[2] * pixel.textureMatrix[8] + pixel.textureMatrix[12];
pixelV = N[0] * pixel.textureMatrix[1] + N[1] * pixel.textureMatrix[5] + N[2] * pixel.textureMatrix[9] + pixel.textureMatrix[13];
//pixelQ = N[0] * pixel.textureMatrix[2] + N[1] * pixel.textureMatrix[6] + N[2] * pixel.textureMatrix[10] + pixel.textureMatrix[14];
break;
}
break;
case GeCommands.TMAP_TEXTURE_MAP_MODE_ENVIRONMENT_MAP:
// Implementation based on shader.vert/ApplyTexture:
//
// vec3 Nn = normalize(N);
// vec3 Ve = vec3(gl_ModelViewMatrix * V);
// float k = gl_FrontMaterial.shininess;
// vec3 Lu = gl_LightSource[texShade.x].position.xyz - Ve.xyz * gl_LightSource[texShade.x].position.w;
// vec3 Lv = gl_LightSource[texShade.y].position.xyz - Ve.xyz * gl_LightSource[texShade.y].position.w;
// float Pu = psp_lightKind[texShade.x] == 0 ? dot(Nn, normalize(Lu)) : pow(dot(Nn, normalize(Lu + vec3(0.0, 0.0, 1.0))), k);
// float Pv = psp_lightKind[texShade.y] == 0 ? dot(Nn, normalize(Lv)) : pow(dot(Nn, normalize(Lv + vec3(0.0, 0.0, 1.0))), k);
// T.xyz = vec3(0.5*vec2(1.0 + Pu, 1.0 + Pv), 1.0);
//
final float[] Ve = new float[3];
final float[] Ne = new float[3];
final float[] Lu = new float[3];
final float[] Lv = new float[3];
pixel.getVe(Ve);
pixel.getNormalizedNe(Ne);
for (int i = 0; i < 3; i++) {
Lu[i] = renderer.envMapLightPosU[i] - Ve[i] * renderer.envMapLightPosU[3];
Lv[i] = renderer.envMapLightPosV[i] - Ve[i] * renderer.envMapLightPosV[3];
}
float Pu;
if (renderer.envMapDiffuseLightU) {
normalize3(Lu, Lu);
Pu = dot3(Ne, Lu);
} else {
Lu[2] += 1f;
normalize3(Lu, Lu);
Pu = (float) Math.pow(dot3(Ne, Lu), renderer.envMapShininess);
}
float Pv;
if (renderer.envMapDiffuseLightV) {
normalize3(Lv, Lv);
Pv = dot3(Ne, Lv);
} else {
Lv[2] += 1f;
normalize3(Lv, Lv);
Pv = (float) Math.pow(dot3(Ne, Lv), renderer.envMapShininess);
}
pixelU = (Pu + 1f) * 0.5f;
pixelV = (Pv + 1f) * 0.5f;
//pixelQ = 1f;
break;
}
}
//
// Texture resampling (as late as possible)
//
if (texMagFilter == GeCommands.TFLT_LINEAR) {
if (needResample) {
// Perform the resampling as late as possible.
// We might be lucky that all the pixel are eliminated
// by the depth or stencil tests. In which case,
// we don't need to resample.
textureAccess = renderer.cachedTexture.resample(prim.resampleFactorWidth, prim.resampleFactorHeight);
textureWidthMask = textureAccess.getWidth() - 1;
textureHeightMask = textureAccess.getHeight() - 1;
textureWidthFloat = textureAccess.getWidth();
textureHeightFloat = textureAccess.getHeight();
needResample = false;
}
}
//
// TextureWrap
//
if (needTextureWrapU) {
switch (texWrapS) {
case GeCommands.TWRAP_WRAP_MODE_REPEAT:
if (transform2D) {
pixelU = wrap(pixelU, textureWidthMask);
} else {
pixelU = wrap(pixelU);
}
break;
case GeCommands.TWRAP_WRAP_MODE_CLAMP:
if (transform2D) {
pixelU = clamp(pixelU, 0f, textureWidthMask);
} else {
// Clamp to [0..1[ (1 is excluded)
pixelU = clamp(pixelU, 0f, 0.99999f);
}
break;
}
}
if (needTextureWrapV) {
switch (texWrapT) {
case GeCommands.TWRAP_WRAP_MODE_REPEAT:
if (transform2D) {
pixelV = wrap(pixelV, textureHeightMask);
} else {
pixelV = wrap(pixelV);
}
break;
case GeCommands.TWRAP_WRAP_MODE_CLAMP:
if (transform2D) {
pixelV = clamp(pixelV, 0f, textureHeightMask);
} else {
// Clamp to [0..1[ (1 is excluded)
pixelV = clamp(pixelV, 0f, 0.99999f);
}
break;
}
}
//
// TextureReader
//
if (transform2D) {
sourceColor = textureAccess.readPixel(pixelToTexel(pixelU), pixelToTexel(pixelV));
} else {
sourceColor = textureAccess.readPixel(pixelToTexel(pixelU * textureWidthFloat), pixelToTexel(pixelV * textureHeightFloat));
}
//
// TextureFunction
//
switch (textureFunc) {
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_MODULATE:
if (textureAlphaUsed) {
sourceColor = multiply(sourceColor, primaryColor);
} else {
sourceColor = multiply(sourceColor | 0xFF000000, primaryColor);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_DECAL:
if (textureAlphaUsed) {
alpha = getAlpha(sourceColor);
a = getAlpha(primaryColor);
b = combineComponent(getBlue(primaryColor), getBlue(sourceColor), alpha);
g = combineComponent(getGreen(primaryColor), getGreen(sourceColor), alpha);
r = combineComponent(getRed(primaryColor), getRed(sourceColor), alpha);
sourceColor = getColor(a, b, g, r);
} else {
sourceColor = (sourceColor & 0x00FFFFFF) | (primaryColor & 0xFF000000);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_BLEND:
if (textureAlphaUsed) {
a = multiplyComponent(getAlpha(sourceColor), getAlpha(primaryColor));
b = combineComponent(getBlue(primaryColor), renderer.texEnvColorB, getBlue(sourceColor));
g = combineComponent(getGreen(primaryColor), renderer.texEnvColorG, getGreen(sourceColor));
r = combineComponent(getRed(primaryColor), renderer.texEnvColorR, getRed(sourceColor));
sourceColor = getColor(a, b, g, r);
} else {
a = getAlpha(primaryColor);
b = combineComponent(getBlue(primaryColor), renderer.texEnvColorB, getBlue(sourceColor));
g = combineComponent(getGreen(primaryColor), renderer.texEnvColorG, getGreen(sourceColor));
r = combineComponent(getRed(primaryColor), renderer.texEnvColorR, getRed(sourceColor));
sourceColor = getColor(a, b, g, r);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_REPLACE:
if (!textureAlphaUsed) {
sourceColor = (sourceColor & 0x00FFFFFF) | (primaryColor & 0xFF000000);
}
break;
case GeCommands.TFUNC_FRAGMENT_DOUBLE_TEXTURE_EFECT_ADD:
if (textureAlphaUsed) {
a = multiplyComponent(getAlpha(sourceColor), getAlpha(primaryColor));
sourceColor = setAlpha(addBGR(sourceColor, primaryColor), a);
} else {
sourceColor = add(sourceColor & 0x00FFFFFF, primaryColor);
}
break;
}
//
// ColorDoubling
//
if (textureColorDoubled) {
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
sourceColor = doubleColor(sourceColor);
secondaryColor = doubleColor(secondaryColor);
} else {
sourceColor = doubleColor(sourceColor);
}
}
//
// SourceColor
//
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
sourceColor = add(sourceColor, secondaryColor);
}
} else {
//
// ColorDoubling
//
if (textureColorDoubled) {
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
primaryColor = doubleColor(primaryColor);
secondaryColor = doubleColor(secondaryColor);
} else if (!primaryColorSetGlobally) {
primaryColor = doubleColor(primaryColor);
}
}
//
// SourceColor
//
if (!transform2D && lightingFlagEnabled && lightMode == LMODE_SEPARATE_SPECULAR_COLOR) {
sourceColor = add(primaryColor, secondaryColor);
} else {
sourceColor = primaryColor;
}
}
//
// ColorTest
//
if (colorTestFlagEnabled && !clearMode) {
switch (colorTestFunc) {
case GeCommands.CTST_COLOR_FUNCTION_ALWAYS_PASS_PIXEL:
// Nothing to do
break;
case GeCommands.CTST_COLOR_FUNCTION_NEVER_PASS_PIXEL:
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.CTST_COLOR_FUNCTION_PASS_PIXEL_IF_COLOR_MATCHES:
if ((sourceColor & renderer.colorTestMsk) != renderer.colorTestRef) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.CTST_COLOR_FUNCTION_PASS_PIXEL_IF_COLOR_DIFFERS:
if ((sourceColor & renderer.colorTestMsk) == renderer.colorTestRef) {
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
}
}
//
// AlphaTest
//
if (alphaTestFlagEnabled && !clearMode) {
switch (alphaFunc) {
case GeCommands.ATST_ALWAYS_PASS_PIXEL:
// Nothing to do
break;
case GeCommands.ATST_NEVER_PASS_PIXEL:
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
case GeCommands.ATST_PASS_PIXEL_IF_MATCHES:
if (getAlpha(sourceColor) != alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_DIFFERS:
if (getAlpha(sourceColor) == alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_LESS:
if (getAlpha(sourceColor) >= alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_LESS_OR_EQUAL:
// No test if alphaRef==0xFF
if (RendererTemplate.alphaRef < 0xFF) {
if (getAlpha(sourceColor) > alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_GREATER:
if (getAlpha(sourceColor) <= alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
break;
case GeCommands.ATST_PASS_PIXEL_IF_GREATER_OR_EQUAL:
// No test if alphaRef==0x00
if (RendererTemplate.alphaRef > 0x00) {
if (getAlpha(sourceColor) < alphaRef) {
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), alpha test failed, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex++;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(1, 1);
}
continue;
}
}
break;
}
}
//
// AlphaBlend
//
if (blendFlagEnabled && !clearMode) {
int filteredSrc;
int filteredDst;
switch (blendEquation) {
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_ADD:
if (blendSrc == GeCommands.ALPHA_FIX && sfix == 0xFFFFFF &&
blendDst == GeCommands.ALPHA_FIX && dfix == 0x000000) {
// Nothing to do, this is a NOP
} else if (blendSrc == GeCommands.ALPHA_FIX && sfix == 0xFFFFFF &&
blendDst == GeCommands.ALPHA_FIX && dfix == 0xFFFFFF) {
sourceColor = PixelColor.add(sourceColor, destinationColor & 0x00FFFFFF);
} else if (blendSrc == GeCommands.ALPHA_SOURCE_ALPHA && blendDst == GeCommands.ALPHA_ONE_MINUS_SOURCE_ALPHA) {
// This is the most common case and can be optimized
int srcAlpha = sourceColor >>> 24;
if (srcAlpha == ZERO) {
// Set color of destination
sourceColor = (sourceColor & 0xFF000000) | (destinationColor & 0x00FFFFFF);
} else if (srcAlpha == ONE) {
// Nothing to change
} else {
int oneMinusSrcAlpha = ONE - srcAlpha;
filteredSrc = multiplyBGR(sourceColor, srcAlpha, srcAlpha, srcAlpha);
filteredDst = multiplyBGR(destinationColor, oneMinusSrcAlpha, oneMinusSrcAlpha, oneMinusSrcAlpha);
sourceColor = setBGR(sourceColor, addBGR(filteredSrc, filteredDst));
}
} else {
filteredSrc = multiplyBGR(sourceColor, blendSrc(sourceColor, destinationColor, renderer.sfix));
filteredDst = multiplyBGR(destinationColor, blendDst(sourceColor, destinationColor, renderer.dfix));
sourceColor = setBGR(sourceColor, addBGR(filteredSrc, filteredDst));
}
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_SUBTRACT:
filteredSrc = multiplyBGR(sourceColor, blendSrc(sourceColor, destinationColor, renderer.sfix));
filteredDst = multiplyBGR(destinationColor, blendDst(sourceColor, destinationColor, renderer.dfix));
sourceColor = setBGR(sourceColor, substractBGR(filteredSrc, filteredDst));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_REVERSE_SUBTRACT:
filteredSrc = multiplyBGR(sourceColor, blendSrc(sourceColor, destinationColor, renderer.sfix));
filteredDst = multiplyBGR(destinationColor, blendDst(sourceColor, destinationColor, renderer.dfix));
sourceColor = setBGR(sourceColor, substractBGR(filteredDst, filteredSrc));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_MINIMUM_VALUE:
// Source and destination factors are not applied
sourceColor = setBGR(sourceColor, minBGR(sourceColor, destinationColor));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_MAXIMUM_VALUE:
// Source and destination factors are not applied
sourceColor = setBGR(sourceColor, maxBGR(sourceColor, destinationColor));
break;
case GeCommands.ALPHA_SOURCE_BLEND_OPERATION_ABSOLUTE_VALUE:
// Source and destination factors are not applied
sourceColor = setBGR(sourceColor, absBGR(sourceColor, destinationColor));
break;
}
}
if (ditherFlagEnabled) {
int ditherValue = renderer.ditherMatrix[((y & 0x3) << 2) + (x & 0x3)];
if (ditherValue > 0) {
b = addComponent(getBlue(sourceColor), ditherValue);
g = addComponent(getGreen(sourceColor), ditherValue);
r = addComponent(getRed(sourceColor), ditherValue);
sourceColor = setBGR(sourceColor, getColorBGR(b, g, r));
} else if (ditherValue < 0) {
ditherValue = -ditherValue;
b = substractComponent(getBlue(sourceColor), ditherValue);
g = substractComponent(getGreen(sourceColor), ditherValue);
r = substractComponent(getRed(sourceColor), ditherValue);
sourceColor = setBGR(sourceColor, getColorBGR(b, g, r));
}
}
//
// StencilOpZPass
//
if (stencilTestFlagEnabled && !clearMode) {
switch (stencilOpZPass) {
case GeCommands.SOP_KEEP_STENCIL_VALUE:
sourceColor = (sourceColor & 0x00FFFFFF) | (destinationColor & 0xFF000000);
break;
case GeCommands.SOP_ZERO_STENCIL_VALUE:
sourceColor &= 0x00FFFFFF;
break;
case GeCommands.SOP_REPLACE_STENCIL_VALUE:
if (stencilRef == 0) {
// SOP_REPLACE_STENCIL_VALUE with a 0 value is equivalent
// to SOP_ZERO_STENCIL_VALUE
sourceColor &= 0x00FFFFFF;
} else {
sourceColor = (sourceColor & 0x00FFFFFF) | stencilRefAlpha;
}
break;
case GeCommands.SOP_INVERT_STENCIL_VALUE:
sourceColor = (sourceColor & 0x00FFFFFF) | ((~destinationColor) & 0xFF000000);
break;
case GeCommands.SOP_INCREMENT_STENCIL_VALUE:
alpha = destinationColor & 0xFF000000;
if (alpha != 0xFF000000) {
alpha += 0x01000000;
}
sourceColor = (sourceColor & 0x00FFFFFF) | alpha;
break;
case GeCommands.SOP_DECREMENT_STENCIL_VALUE:
alpha = destinationColor & 0xFF000000;
if (alpha != 0x00000000) {
alpha -= 0x01000000;
}
sourceColor = (sourceColor & 0x00FFFFFF) | alpha;
break;
}
} else if (!clearMode) {
// Write the alpha/stencil value to the frame buffer
// only when the stencil test is enabled
sourceColor = (sourceColor & 0x00FFFFFF) | (destinationColor & 0xFF000000);
}
//
// ColorLogicalOperation
//
if (colorLogicOpFlagEnabled && !clearMode) {
switch (logicOp) {
case GeCommands.LOP_CLEAR:
sourceColor = ZERO;
break;
case GeCommands.LOP_AND:
sourceColor &= destinationColor;
break;
case GeCommands.LOP_REVERSE_AND:
sourceColor &= (~destinationColor);
break;
case GeCommands.LOP_COPY:
// This is a NOP
break;
case GeCommands.LOP_INVERTED_AND:
sourceColor = (~sourceColor) & destinationColor;
break;
case GeCommands.LOP_NO_OPERATION:
sourceColor = destinationColor;
break;
case GeCommands.LOP_EXLUSIVE_OR:
sourceColor ^= destinationColor;
break;
case GeCommands.LOP_OR:
sourceColor |= destinationColor;
break;
case GeCommands.LOP_NEGATED_OR:
sourceColor = ~(sourceColor | destinationColor);
break;
case GeCommands.LOP_EQUIVALENCE:
sourceColor = ~(sourceColor ^ destinationColor);
break;
case GeCommands.LOP_INVERTED:
sourceColor = ~destinationColor;
break;
case GeCommands.LOP_REVERSE_OR:
sourceColor |= (~destinationColor);
break;
case GeCommands.LOP_INVERTED_COPY:
sourceColor = ~sourceColor;
break;
case GeCommands.LOP_INVERTED_OR:
sourceColor = (~sourceColor) | destinationColor;
break;
case GeCommands.LOP_NEGATED_AND:
sourceColor = ~(sourceColor & destinationColor);
break;
case GeCommands.LOP_SET:
sourceColor = 0xFFFFFFFF;
break;
}
}
//
// ColorMask
//
if (clearMode) {
if (clearModeColor) {
if (!clearModeStencil) {
sourceColor = (sourceColor & 0x00FFFFFF) | (destinationColor & 0xFF000000);
}
} else {
if (clearModeStencil) {
sourceColor = (sourceColor & 0xFF000000) | (destinationColor & 0x00FFFFFF);
} else {
sourceColor = destinationColor;
}
}
} else {
if (colorMask != 0x00000000) {
sourceColor = (sourceColor & notColorMask) | (destinationColor & renderer.colorMask);
}
}
//
// DepthMask
//
if (needDepthWrite) {
if (clearMode) {
if (!clearModeDepth) {
sourceDepth = destinationDepth;
}
} else if (!depthTestFlagEnabled) {
// Depth writes are disabled when the depth test is not enabled.
sourceDepth = destinationDepth;
} else if (!depthMask) {
sourceDepth = destinationDepth;
}
}
//
// Filter passed
//
if (isLogTraceEnabled) {
VideoEngine.log.trace(String.format("Pixel (%d,%d), passed=true, tex (%f, %f), source=0x%08X, dest=0x%08X, prim=0x%08X, sec=0x%08X, sourceDepth=%d, destDepth=%d", x, y, pixelU, pixelV, sourceColor, destinationColor, primaryColor, secondaryColor, sourceDepth, destinationDepth));
}
if (needDepthWrite && needSourceDepthClamp) {
// Clamp between 0 and 65535
sourceDepth = Math.max(0, Math.min(sourceDepth, 65535));
}
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
memInt[fbIndex] = sourceColor;
fbIndex++;
if (needDepthWrite) {
if (depthOffset == 0) {
memInt[depthIndex] = (memInt[depthIndex] & 0xFFFF0000) | (sourceDepth & 0x0000FFFF);
depthOffset = 1;
} else {
memInt[depthIndex] = (memInt[depthIndex] & 0x0000FFFF) | (sourceDepth << 16);
depthIndex++;
depthOffset = 0;
}
} else if (needDestinationDepthRead) {
depthOffset++;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
if (needDepthWrite) {
colorDepth.color = sourceColor;
colorDepth.depth = sourceDepth;
rendererWriter.writeNext(colorDepth);
} else {
rendererWriter.writeNextColor(sourceColor);
}
}
} while (false);
if (needTextureUV && simpleTextureUV) {
if (swapTextureUV) {
v += prim.vStep;
} else {
u += prim.uStep;
}
}
if (isTriangle) {
prim.deltaXTriangleWeigths(pixel);
}
}
int skip = prim.pxMax - endX;
if (hasMemInt && psm == TPSM_PIXEL_STORAGE_MODE_32BIT_ABGR8888) {
fbIndex += skip + renderer.imageWriterSkipEOL;
if (needDepthWrite || needDestinationDepthRead) {
depthOffset += skip + renderer.depthWriterSkipEOL;
depthIndex += depthOffset >> 1;
depthOffset &= 1;
}
} else {
rendererWriter.skip(skip + renderer.imageWriterSkipEOL, skip + renderer.depthWriterSkipEOL);
}
}
if (needTextureUV && simpleTextureUV) {
if (swapTextureUV) {
u += prim.uStep;
} else {
v += prim.vStep;
}
}
}
doRenderEnd(renderer);
}
|
diff --git a/e/hu.e.compiler/src/hu/e/compiler/tasks/internal/AbstractConverter.java b/e/hu.e.compiler/src/hu/e/compiler/tasks/internal/AbstractConverter.java
index c3c3218a..e48a2017 100644
--- a/e/hu.e.compiler/src/hu/e/compiler/tasks/internal/AbstractConverter.java
+++ b/e/hu.e.compiler/src/hu/e/compiler/tasks/internal/AbstractConverter.java
@@ -1,123 +1,123 @@
/**
*
*/
package hu.e.compiler.tasks.internal;
import hu.e.compiler.TaskUtils;
import hu.modembed.model.core.CorePackage;
import hu.modembed.model.core.MODembedElement;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EStructuralFeature;
/**
* @author balazs.grill
*
*/
public abstract class AbstractConverter {
private class Reference{
public final EObject source;
public final EReference reference;
public final EObject originalTarget;
private Reference(EObject source, EReference reference,
EObject originalTarget) {
this.source = source;
this.reference = reference;
this.originalTarget = originalTarget;
}
@SuppressWarnings("unchecked")
private void resolve(AbstractConverter converter){
EObject target = converter.getConverted(originalTarget);
if (reference.isMany()){
((List<EObject>)source.eGet(reference)).add(target);
}else{
source.eSet(reference, target);
}
}
}
private final Map<EObject, EObject> converted = new HashMap<EObject, EObject>();
private final List<Reference> references = new LinkedList<Reference>();
public EObject getConverted(EObject original) {
EObject target = converted.get(original);
if (target == null) target = original;
return target;
}
public void addReference(EObject source, EReference reference, EObject originalTarget){
references.add(new Reference(source, reference, originalTarget));
}
public void resolveCrossReferences(){
for(Reference ref : references){
ref.resolve(this);
}
}
protected EObject internalCopy(EObject element){
EClass eclass = element.eClass();
EObject result = eclass.getEPackage().getEFactoryInstance().create(eclass);
converted.put(element, result);
if (element instanceof MODembedElement){
- TaskUtils.addOrigin((MODembedElement) element, (MODembedElement)result);
+ TaskUtils.addOrigin((MODembedElement) result, (MODembedElement)element);
}
for(EStructuralFeature feature: eclass.getEAllStructuralFeatures()){
if (!CorePackage.eINSTANCE.getMODembedElement_Origins().equals(feature)){
if (feature instanceof EAttribute){
result.eSet(feature, element.eGet(feature));
}
if (feature instanceof EReference){
if (((EReference) feature).isContainment()){
if (feature.isMany()){
@SuppressWarnings("unchecked")
List<EObject> resultList = (List<EObject>) result.eGet(feature);
for(Object o : (List<?>)element.eGet(feature)){
EObject copied = copy((EObject)o);
if (copied != null)
resultList.add(copied);
}
}else{
Object o = element.eGet(feature);
if (o instanceof EObject){
result.eSet(feature, copy((EObject)o));
}
}
}else{
if (feature.isMany()){
for(Object o : (List<?>)element.eGet(feature)){
addReference(result, (EReference)feature, (EObject)o);
}
}else{
Object o = element.eGet(feature);
if (o instanceof EObject){
addReference(result, (EReference)feature, (EObject)o);
}
}
}
}
}
}
return result;
}
@SuppressWarnings("unchecked")
public <T extends EObject> T copy(T element){
return (T)internalCopy(element);
}
}
| true | true | protected EObject internalCopy(EObject element){
EClass eclass = element.eClass();
EObject result = eclass.getEPackage().getEFactoryInstance().create(eclass);
converted.put(element, result);
if (element instanceof MODembedElement){
TaskUtils.addOrigin((MODembedElement) element, (MODembedElement)result);
}
for(EStructuralFeature feature: eclass.getEAllStructuralFeatures()){
if (!CorePackage.eINSTANCE.getMODembedElement_Origins().equals(feature)){
if (feature instanceof EAttribute){
result.eSet(feature, element.eGet(feature));
}
if (feature instanceof EReference){
if (((EReference) feature).isContainment()){
if (feature.isMany()){
@SuppressWarnings("unchecked")
List<EObject> resultList = (List<EObject>) result.eGet(feature);
for(Object o : (List<?>)element.eGet(feature)){
EObject copied = copy((EObject)o);
if (copied != null)
resultList.add(copied);
}
}else{
Object o = element.eGet(feature);
if (o instanceof EObject){
result.eSet(feature, copy((EObject)o));
}
}
}else{
if (feature.isMany()){
for(Object o : (List<?>)element.eGet(feature)){
addReference(result, (EReference)feature, (EObject)o);
}
}else{
Object o = element.eGet(feature);
if (o instanceof EObject){
addReference(result, (EReference)feature, (EObject)o);
}
}
}
}
}
}
return result;
}
| protected EObject internalCopy(EObject element){
EClass eclass = element.eClass();
EObject result = eclass.getEPackage().getEFactoryInstance().create(eclass);
converted.put(element, result);
if (element instanceof MODembedElement){
TaskUtils.addOrigin((MODembedElement) result, (MODembedElement)element);
}
for(EStructuralFeature feature: eclass.getEAllStructuralFeatures()){
if (!CorePackage.eINSTANCE.getMODembedElement_Origins().equals(feature)){
if (feature instanceof EAttribute){
result.eSet(feature, element.eGet(feature));
}
if (feature instanceof EReference){
if (((EReference) feature).isContainment()){
if (feature.isMany()){
@SuppressWarnings("unchecked")
List<EObject> resultList = (List<EObject>) result.eGet(feature);
for(Object o : (List<?>)element.eGet(feature)){
EObject copied = copy((EObject)o);
if (copied != null)
resultList.add(copied);
}
}else{
Object o = element.eGet(feature);
if (o instanceof EObject){
result.eSet(feature, copy((EObject)o));
}
}
}else{
if (feature.isMany()){
for(Object o : (List<?>)element.eGet(feature)){
addReference(result, (EReference)feature, (EObject)o);
}
}else{
Object o = element.eGet(feature);
if (o instanceof EObject){
addReference(result, (EReference)feature, (EObject)o);
}
}
}
}
}
}
return result;
}
|
diff --git a/support/org/intellij/grammar/generator/RuleGraphHelper.java b/support/org/intellij/grammar/generator/RuleGraphHelper.java
index 0ccccc6..5139f78 100755
--- a/support/org/intellij/grammar/generator/RuleGraphHelper.java
+++ b/support/org/intellij/grammar/generator/RuleGraphHelper.java
@@ -1,697 +1,697 @@
/*
* Copyright 2011-2011 Gregory Shrago
*
* 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.intellij.grammar.generator;
import com.intellij.lang.Language;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.PsiElement;
import com.intellij.psi.impl.source.tree.LeafPsiElement;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.CachedValue;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.containers.MultiMapBasedOnSet;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.intellij.grammar.KnownAttribute;
import org.intellij.grammar.analysis.BnfFirstNextAnalyzer;
import org.intellij.grammar.psi.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import static org.intellij.grammar.generator.ParserGeneratorUtil.*;
import static org.intellij.grammar.generator.RuleGraphHelper.Cardinality.*;
import static org.intellij.grammar.psi.BnfTypes.BNF_SEQUENCE;
import static org.intellij.grammar.psi.impl.GrammarUtil.collectExtraArguments;
import static org.intellij.grammar.psi.impl.GrammarUtil.nextOrParent;
/**
* @author gregory
* Date: 16.07.11 10:41
*/
public class RuleGraphHelper {
private final BnfFile myFile;
private final MultiMap<BnfRule, BnfRule> myRuleExtendsMap;
private final Map<BnfRule, Map<PsiElement, Cardinality>> myRuleContentsMap;
private final MultiMap<BnfRule,BnfRule> myRulesGraph;
private final Set<BnfRule> myRulesWithTokens = new THashSet<BnfRule>();
private static final LeafPsiElement LEFT_MARKER = new LeafPsiElement(new IElementType("LEFT_MARKER", Language.ANY, false) {}, "LEFT_MARKER");
private static final IElementType EXTERNAL_TYPE = new IElementType("EXTERNAL_TYPE", Language.ANY, false) {};
public static String getCardinalityText(Cardinality cardinality) {
if (cardinality == AT_LEAST_ONE) {
return "+";
}
else if (cardinality == ANY_NUMBER) {
return "*";
}
else if (cardinality == OPTIONAL) {
return "?";
}
return "";
}
public enum Cardinality {
NONE, OPTIONAL, REQUIRED, AT_LEAST_ONE, ANY_NUMBER;
boolean optional() {
return this == OPTIONAL || this == ANY_NUMBER || this == NONE;
}
boolean many() {
return this == AT_LEAST_ONE || this == ANY_NUMBER;
}
Cardinality single() {
return this == AT_LEAST_ONE? REQUIRED : this == ANY_NUMBER? OPTIONAL : this;
}
public static Cardinality fromNodeType(IElementType type) {
if (type == BnfTypes.BNF_OP_OPT) {
return OPTIONAL;
}
else if (type == BnfTypes.BNF_SEQUENCE || type == BnfTypes.BNF_REFERENCE_OR_TOKEN) {
return REQUIRED;
}
else if (type == BnfTypes.BNF_CHOICE) {
return OPTIONAL;
}
else if (type == BnfTypes.BNF_OP_ONEMORE) {
return AT_LEAST_ONE;
}
else if (type == BnfTypes.BNF_OP_ZEROMORE) {
return ANY_NUMBER;
}
else {
throw new AssertionError("unexpected: " + type);
}
}
public Cardinality and(Cardinality c) {
if (c == null) return this;
if (this == NONE || c == NONE) return NONE;
if (optional() || c.optional()) {
return many() || c.many() ? ANY_NUMBER : OPTIONAL;
}
else {
return many() || c.many() ? AT_LEAST_ONE : REQUIRED;
}
}
public Cardinality or(Cardinality c) {
if (c == null) c = NONE;
if (this == NONE && c == NONE) return NONE;
if (this == NONE) return c;
if (c == NONE) return this;
return optional() && c.optional() ? ANY_NUMBER : AT_LEAST_ONE;
}
}
public static MultiMap<BnfRule, BnfRule> computeInheritance(BnfFile file) {
final MultiMap<BnfRule, BnfRule> ruleExtendsMap = new MultiMapBasedOnSet<BnfRule, BnfRule>();
for (BnfRule rule : file.getRules()) {
if (Rule.isPrivate(rule) || Rule.isExternal(rule)) continue;
BnfRule superRule = file.getRule(getAttribute(rule, KnownAttribute.EXTENDS));
if (superRule == null) continue;
ruleExtendsMap.putValue(superRule, rule);
ruleExtendsMap.putValue(superRule, getSynonymTargetOrSelf(rule));
}
for (int i = 0, len = ruleExtendsMap.size(); i < len; i++) {
boolean changed = false;
for (BnfRule superRule : ruleExtendsMap.keySet()) {
final Collection<BnfRule> rules = ruleExtendsMap.get(superRule);
for (BnfRule rule : new ArrayList<BnfRule>(rules)) {
changed |= rules.addAll(ruleExtendsMap.get(rule));
}
}
if (!changed) break;
}
for (BnfRule rule : ruleExtendsMap.keySet()) {
ruleExtendsMap.putValue(rule, rule); // add super to itself
}
return ruleExtendsMap;
}
private static final Key<CachedValue<Map<String, String>>> TOKEN_MAP_KEY = Key.create("TOKEN_MAP_KEY");
public static Map<String, String> getTokenMap(final BnfFile file) {
CachedValue<Map<String, String>> value = file.getUserData(TOKEN_MAP_KEY);
if (value == null) {
file.putUserData(TOKEN_MAP_KEY, value =
CachedValuesManager.getManager(file.getProject()).createCachedValue(new CachedValueProvider<Map<String, String>>() {
@Nullable
@Override
public Result<Map<String, String>> compute() {
return new Result<Map<String, String>>(computeTokens(file), file);
}
}, false));
}
return value.getValue();
}
public static Map<String, String> computeTokens(BnfFile file) {
Map<String, String> result = new LinkedHashMap<String, String>();
for (Pair<String, String> pair : getRootAttribute(file, KnownAttribute.TOKENS)) {
result.put(pair.second, pair.first); // string value to constant name
}
return result;
}
private static final Key<CachedValue<RuleGraphHelper>> RULE_GRAPH_HELPER_KEY = Key.create("RULE_GRAPH_HELPER_KEY");
public static RuleGraphHelper getCached(final BnfFile file) {
CachedValue<RuleGraphHelper> value = file.getUserData(RULE_GRAPH_HELPER_KEY);
if (value == null) {
file.putUserData(RULE_GRAPH_HELPER_KEY, value = CachedValuesManager.getManager(file.getProject()).createCachedValue(new CachedValueProvider<RuleGraphHelper>() {
@Nullable
@Override
public Result<RuleGraphHelper> compute() {
return new Result<RuleGraphHelper>(new RuleGraphHelper(file), file);
}
}, false));
}
return value.getValue();
}
public RuleGraphHelper(BnfFile file) {
this(file, computeInheritance(file));
}
public RuleGraphHelper(BnfFile file, MultiMap<BnfRule, BnfRule> ruleExtendsMap) {
myFile = file;
myRuleExtendsMap = ruleExtendsMap;
myRuleContentsMap = new THashMap<BnfRule, Map<PsiElement, Cardinality>>();
// ordered!
myRulesGraph = new MultiMapBasedOnSet<BnfRule, BnfRule>() {
@Override
protected Collection<BnfRule> createCollection() {
return new LinkedHashSet<BnfRule>();
}
};
buildRulesGraph();
buildContentsMap();
}
private void buildContentsMap() {
final Collection<? extends BnfRule> inheritors = new THashSet<BnfRule>(myRuleExtendsMap.values());
List<BnfRule> rules = topoSort(myFile.getRules(), new Topology<BnfRule>() {
@Override
public boolean contains(BnfRule t1, BnfRule t2) {
return myRulesGraph.get(t1).contains(t2);
}
@Override
public BnfRule forceChoose(Collection<BnfRule> col) {
return super.forceChooseInner(
col, new Condition<BnfRule>() {
@Override
public boolean value(BnfRule bnfRule) {
if (myRulesWithTokens.contains(bnfRule)) return false;
for (BnfRule r : myRulesGraph.get(bnfRule)) {
if (!inheritors.contains(r)) return false;
}
return true;
}
}, new Condition<BnfRule>() {
@Override
public boolean value(BnfRule bnfRule) {
return !myRulesWithTokens.contains(bnfRule);
}
}, Condition.TRUE
);
}
});
THashSet<PsiElement> visited = new THashSet<PsiElement>();
for (BnfRule rule : rules) {
if (myRuleContentsMap.containsKey(rule)) continue;
Map<PsiElement, Cardinality> map = collectMembers(rule, rule.getExpression(), rule.getName(), visited);
if (map.size() == 1 && ContainerUtil.getFirstItem(map.values()) == REQUIRED && !Rule.isPrivate(rule)) {
PsiElement r = ContainerUtil.getFirstItem(map.keySet());
if (r == rule || r instanceof BnfRule && collapseEachOther((BnfRule)r, rule)) {
myRuleContentsMap.put(rule, Collections.<PsiElement, Cardinality>emptyMap());
}
else {
myRuleContentsMap.put(rule, map);
}
}
else {
myRuleContentsMap.put(rule, map);
}
ParserGenerator.LOG.assertTrue(visited.isEmpty());
}
}
public boolean collapseEachOther(BnfRule r1, BnfRule r2) {
for (BnfRule superRule : myRuleExtendsMap.keySet()) {
Collection<BnfRule> set = myRuleExtendsMap.get(superRule);
if (set.contains(r1) && set.contains(r2)) return true;
}
return false;
}
private void buildRulesGraph() {
for (BnfRule rule : myFile.getRules()) {
BnfExpression expression = rule.getExpression();
for (PsiElement cur = nextOrParent(expression.getPrevSibling(), expression);
cur != null;
cur = nextOrParent(cur, expression) ) {
boolean checkPredicate = cur instanceof BnfReferenceOrToken || cur instanceof BnfStringLiteralExpression;
if (!checkPredicate || PsiTreeUtil.getParentOfType(cur, BnfPredicate.class) != null) continue;
BnfRule r = cur instanceof BnfReferenceOrToken? myFile.getRule(cur.getText()) : null;
if (r != null) {
myRulesGraph.putValue(rule, r);
}
else {
myRulesWithTokens.add(rule);
}
}
}
for (BnfRule rule : myFile.getRules()) {
if (Rule.isLeft(rule) && !Rule.isPrivate(rule) && !Rule.isInner(rule)) {
for (BnfRule r : getRulesToTheLeft(rule).keySet()) {
myRulesGraph.putValue(rule, r);
}
}
}
}
public Collection<BnfRule> getExtendsRules(BnfRule rule) {
return myRuleExtendsMap.get(rule);
}
public Collection<BnfRule> getSubRules(BnfRule rule) {
return myRulesGraph.get(rule);
}
@NotNull
public Map<PsiElement, Cardinality> getFor(BnfRule rule) {
return myRuleContentsMap.get(rule);
}
private Map<PsiElement, Cardinality> collectMembers(BnfRule rule, BnfExpression tree, String funcName, Set<PsiElement> visited) {
if (tree instanceof BnfPredicate) return Collections.emptyMap();
if (tree instanceof BnfLiteralExpression) return psiMap(tree, REQUIRED);
if (!visited.add(tree)) return psiMap(tree, REQUIRED);
Map<PsiElement, Cardinality> result;
if (tree instanceof BnfReferenceOrToken) {
BnfRule targetRule = myFile.getRule(tree.getText());
if (targetRule != null) {
if (Rule.isExternal(targetRule)) {
result = psiMap(new LeafPsiElement(EXTERNAL_TYPE, targetRule.getName()), REQUIRED);
}
else if (Rule.isLeft(targetRule)) {
if (!Rule.isInner(targetRule) && !Rule.isPrivate(targetRule)) {
result = new HashMap<PsiElement, Cardinality>();
result.put(getSynonymTargetOrSelf(targetRule), REQUIRED);
result.put(LEFT_MARKER, REQUIRED);
}
else {
result = Collections.emptyMap();
}
}
else if (Rule.isPrivate(targetRule)) {
result = myRuleContentsMap.get(targetRule); // optimize performance
if (result == null) {
BnfExpression body = targetRule.getExpression();
Map<PsiElement, Cardinality> map = collectMembers(targetRule, body, targetRule.getName(), visited);
result = map.containsKey(body) ? joinMaps(null, BnfTypes.BNF_CHOICE, Arrays.asList(map, map)) : map;
myRuleContentsMap.put(targetRule, result);
}
}
else {
result = psiMap(getSynonymTargetOrSelf(targetRule), REQUIRED);
}
}
else {
result = psiMap(tree, REQUIRED);
}
}
else if (tree instanceof BnfExternalExpression) {
List<BnfExpression> expressionList = ((BnfExternalExpression)tree).getExpressionList();
if (expressionList.size() == 1 && Rule.isMeta(rule)) {
result = psiMap(tree, REQUIRED);
}
else {
BnfExpression ruleRef = expressionList.get(0);
BnfRule metaRule = myFile.getRule(ruleRef.getText());
if (metaRule == null) {
- result = psiMap(new LeafPsiElement(EXTERNAL_TYPE, "<<"+ruleRef.getText()+">>"), REQUIRED);
+ result = psiMap(new LeafPsiElement(EXTERNAL_TYPE, "#"+ruleRef.getText()), REQUIRED);
}
else if (Rule.isPrivate(metaRule)) {
result = new HashMap<PsiElement, Cardinality>();
Map<PsiElement, Cardinality> metaResults = collectMembers(rule, ruleRef, funcName, new HashSet<PsiElement>());
List<String> params = null;
for (PsiElement member : metaResults.keySet()) {
Cardinality cardinality = metaResults.get(member);
if (!(member instanceof BnfExternalExpression)) {
result.put(member, cardinality);
}
else {
if (params == null) {
params = collectExtraArguments(metaRule, metaRule.getExpression());
}
int idx = params.indexOf(member.getText());
if (idx > -1 && idx + 1 < expressionList.size()) {
Map<PsiElement, Cardinality> argMap = collectMembers(rule, expressionList.get(idx + 1), getNextName(funcName, idx), visited);
for (PsiElement element : argMap.keySet()) {
result.put(element, cardinality.and(argMap.get(element)));
}
}
}
}
}
else {
result = psiMap(metaRule, REQUIRED);
}
}
}
else {
IElementType type = getEffectiveType(tree);
boolean firstNonTrivial = tree == Rule.firstNotTrivial(rule);
PinMatcher pinMatcher = new PinMatcher(rule, type, firstNonTrivial ? rule.getName() : funcName);
boolean pinApplied = false;
List<Map<PsiElement, Cardinality>> list = new ArrayList<Map<PsiElement, Cardinality>>();
List<BnfExpression> childExpressions = getChildExpressions(tree);
for (int i = 0, childExpressionsSize = childExpressions.size(); i < childExpressionsSize; i++) {
BnfExpression child = childExpressions.get(i);
Map<PsiElement, Cardinality> nextMap = collectMembers(rule, child, getNextName(funcName, i), visited);
if (pinApplied) {
nextMap = joinMaps(null, BnfTypes.BNF_OP_OPT, Collections.singletonList(nextMap));
}
list.add(nextMap);
if (type == BNF_SEQUENCE && !pinApplied && pinMatcher.matches(i, child)) {
pinApplied = true;
}
}
result = joinMaps(firstNonTrivial ? rule : null, type, list);
}
if (rule.getExpression() == tree && Rule.isLeft(rule) && !Rule.isPrivate(rule) && !Rule.isInner(rule)) {
List<Map<PsiElement, Cardinality>> list = new ArrayList<Map<PsiElement, Cardinality>>();
Map<BnfRule, Cardinality> rulesToTheLeft = getRulesToTheLeft(rule);
for (BnfRule r : rulesToTheLeft.keySet()) {
Cardinality cardinality = rulesToTheLeft.get(r);
Map<PsiElement, Cardinality> leftMap = psiMap(getSynonymTargetOrSelf(r), REQUIRED);
if (cardinality.many()) {
list.add(joinMaps(null, BnfTypes.BNF_CHOICE, Arrays.asList(leftMap, psiMap(getSynonymTargetOrSelf(rule), REQUIRED))));
}
else {
list.add(leftMap);
}
}
Map<PsiElement, Cardinality> combinedLeftMap = joinMaps(null, BnfTypes.BNF_CHOICE, list);
result = joinMaps(null, BnfTypes.BNF_SEQUENCE, Arrays.asList(result, combinedLeftMap));
}
visited.remove(tree);
return result;
}
private static Map<BnfRule, Cardinality> getRulesToTheLeft(BnfRule rule) {
Map<BnfRule, Cardinality> result = new HashMap<BnfRule, Cardinality>();
Map<BnfExpression, BnfExpression> nextMap = new BnfFirstNextAnalyzer().setBackward(true).setPublicRuleOpaque(true).calcNext(rule);
BnfFile containingFile = (BnfFile)rule.getContainingFile();
for (BnfExpression e : nextMap.keySet()) {
if (!(e instanceof BnfReferenceOrToken)) continue;
BnfRule r = containingFile.getRule(e.getText());
if (r == null || ParserGeneratorUtil.Rule.isPrivate(r)) continue;
BnfExpression context = nextMap.get(e);
Cardinality cardinality = REQUIRED;
for (PsiElement cur = context; !(cur instanceof BnfRule); cur = cur.getParent()) {
if (PsiTreeUtil.isAncestor(cur, e, true)) break;
IElementType curType = getEffectiveType(cur);
if (curType == BnfTypes.BNF_OP_OPT || curType == BnfTypes.BNF_OP_ONEMORE || curType == BnfTypes.BNF_OP_ZEROMORE) {
cardinality = cardinality.and(Cardinality.fromNodeType(curType));
}
}
Cardinality prev = result.get(r);
result.put(r, prev == null? cardinality : cardinality.or(prev));
}
return result;
}
private Map<PsiElement, Cardinality> joinMaps(@Nullable BnfRule rule, IElementType type, List<Map<PsiElement, Cardinality>> list) {
if (list.isEmpty()) return Collections.emptyMap();
boolean checkInheritance = rule != null && myRuleExtendsMap.containsScalarValue(rule);
if (type == BnfTypes.BNF_OP_OPT || type == BnfTypes.BNF_OP_ZEROMORE || type == BnfTypes.BNF_OP_ONEMORE) {
assert list.size() == 1;
list = compactInheritors(list);
Map<PsiElement, Cardinality> m = list.get(0);
if (type == BnfTypes.BNF_OP_OPT && checkInheritance && m.size() == 1 && collapseNode(rule, m.keySet().iterator().next())) {
return Collections.emptyMap();
}
Map<PsiElement, Cardinality> map = new HashMap<PsiElement, Cardinality>();
boolean leftMarker = m.containsKey(LEFT_MARKER);
for (PsiElement t : m.keySet()) {
Cardinality joinedCard = fromNodeType(type).and(m.get(t));
if (leftMarker) {
joinedCard = joinedCard.single();
}
map.put(t, joinedCard);
}
return map;
}
else if (type == BnfTypes.BNF_SEQUENCE || type == BnfTypes.BNF_EXPRESSION || type == BnfTypes.BNF_REFERENCE_OR_TOKEN) {
list = new ArrayList<Map<PsiElement, Cardinality>>(compactInheritors(list));
for (Iterator<Map<PsiElement, Cardinality>> it = list.iterator(); it.hasNext(); ) {
if (it.next().isEmpty()) it.remove();
}
Map<PsiElement, Cardinality> map = new HashMap<PsiElement, Cardinality>();
for (Map<PsiElement, Cardinality> m : list) {
Cardinality leftMarker = m.get(LEFT_MARKER);
if (leftMarker == REQUIRED) {
map.clear();
leftMarker = null;
}
else if (leftMarker == OPTIONAL) {
for (PsiElement t : map.keySet()) {
if (!m.containsKey(t)) {
map.put(t, map.get(t).and(Cardinality.OPTIONAL));
}
}
}
for (PsiElement t : m.keySet()) {
if (t == LEFT_MARKER && m != list.get(0)) continue;
Cardinality c1 = map.get(t);
Cardinality c2 = m.get(t);
Cardinality joinedCard;
if (leftMarker == null) {
joinedCard = c2.or(c1);
}
// handle left semantic in a choice-like way
else if (c1 == null) {
joinedCard = c2;
}
else {
if (c1 == REQUIRED) joinedCard = c2.many()? AT_LEAST_ONE : REQUIRED;
else if (c1 == AT_LEAST_ONE) joinedCard = ANY_NUMBER;
else joinedCard = c1;
}
map.put(t, joinedCard);
}
}
if (checkInheritance && map.size() == 1 && collapseNode(rule, map.keySet().iterator().next())) {
return Collections.emptyMap();
}
return map;
}
else if (type == BnfTypes.BNF_CHOICE) {
Map<PsiElement, Cardinality> map = new HashMap<PsiElement, Cardinality>();
list = compactInheritors(list);
for (int i = 0, newListSize = list.size(); i < newListSize; i++) {
Map<PsiElement, Cardinality> m = list.get(i);
if (checkInheritance && m.size() == 1 && collapseNode(rule, m.keySet().iterator().next())) {
list.set(i, Collections.<PsiElement, Cardinality>emptyMap());
}
}
Map<PsiElement, Cardinality> m0 = list.get(0);
map.putAll(m0);
for (Map<PsiElement, Cardinality> m : list) {
map.keySet().retainAll(m.keySet());
}
for (PsiElement t : new ArrayList<PsiElement>(map.keySet())) {
map.put(t, REQUIRED.and(m0.get(t)));
for (Map<PsiElement, Cardinality> m : list) {
if (m == list.get(0)) continue;
map.put(t, map.get(t).and(m.get(t)));
}
}
for (Map<PsiElement, Cardinality> m : list) {
for (PsiElement t : m.keySet()) {
if (map.containsKey(t)) continue;
if (checkInheritance && collapseNode(rule, t)) continue;
map.put(t, OPTIONAL.and(m.get(t)));
}
}
return map;
}
else {
throw new AssertionError("unexpected: " + type);
}
}
private boolean collapseNode(BnfRule rule, PsiElement t) {
if (!(t instanceof BnfRule)) return false;
for (BnfRule superRule : myRuleExtendsMap.keySet()) {
Collection<BnfRule> set = myRuleExtendsMap.get(superRule);
if (set.contains(t) && set.contains(rule)) {
return true;
}
}
return false;
}
// damn java generics
public static <V> java.util.Map<PsiElement, V> psiMap(PsiElement k, V v) {
return Collections.singletonMap(k, v);
}
private List<Map<PsiElement, Cardinality>> compactInheritors(List<Map<PsiElement, Cardinality>> mapList) {
Set<BnfRule> rulesToTry = new LinkedHashSet<BnfRule>();
// collect all rules
for (Map<PsiElement, Cardinality> map : mapList) {
for (PsiElement psiElement : map.keySet()) {
if (!(psiElement instanceof BnfRule)) continue;
rulesToTry.add((BnfRule)psiElement);
}
}
// add their supers & collapse-caused rules
BnfRule[] origRulesCopy = rulesToTry.toArray(new BnfRule[rulesToTry.size()]);
Set<BnfRule> origRules = new LinkedHashSet<BnfRule>(rulesToTry);
for (BnfRule realRule : origRulesCopy) {
Map<PsiElement, Cardinality> availableResult = myRuleContentsMap.get(realRule);
Set<PsiElement> content = availableResult == null? null : availableResult.keySet();
for (BnfRule superRule : myRuleExtendsMap.keySet()) {
if (superRule == realRule) continue;
Collection<BnfRule> inheritors = myRuleExtendsMap.get(superRule);
if (inheritors.contains(realRule)) {
rulesToTry.add(superRule);
if (content != null) {
if (content.isEmpty()) { // will be definitely collapsed, replace with super
origRules.remove(realRule);
origRules.add(superRule);
}
else {
for (PsiElement element : content) {
if (!(element instanceof BnfRule)) continue;
BnfRule r = (BnfRule)element;
if (inheritors.contains(r)) {
origRules.add(r);
}
}
}
}
}
}
}
if (rulesToTry.size() < 2) return mapList;
// sort rules along with their supers
List<BnfRule> sorted = topoSort(rulesToTry, new Topology<BnfRule>() {
@Override
public boolean contains(BnfRule t1, BnfRule t2) {
return myRuleExtendsMap.get(t1).contains(t2);
}
});
// drop unnecessary super rules: doesn't combine much, not present due collapse
origRulesCopy = origRules.toArray(new BnfRule[origRules.size()]);
int max = 0;
BitSet bitSet = new BitSet(origRulesCopy.length);
for (Iterator<BnfRule> it = sorted.iterator(); it.hasNext(); ) {
BnfRule superRule = it.next();
Collection<BnfRule> inheritors = myRuleExtendsMap.get(superRule);
int count = 0;
boolean changed = false;
for (int i = 0; i < origRulesCopy.length; i++) {
BnfRule r = origRulesCopy[i];
if (r == superRule || inheritors.contains(r)) {
count ++;
if (!bitSet.get(i)) {
bitSet.set(i);
changed = true;
}
}
}
if (changed) {
max = 0;
}
else if (count > 1 && max < count) {
max = count;
}
else if (!changed) {
it.remove();
}
}
// apply changes and merge cards
Collections.reverse(sorted);
List<Map<PsiElement, Cardinality>> result = new ArrayList<Map<PsiElement, Cardinality>>(mapList.size());
for (Map<PsiElement, Cardinality> map : mapList) {
result.add(new HashMap<PsiElement, Cardinality>(map));
}
for (BnfRule superRule : sorted) {
for (Map<PsiElement, Cardinality> newMap : result) {
Cardinality cardinality = null;
for (Iterator<PsiElement> iterator = newMap.keySet().iterator(); iterator.hasNext(); ) {
PsiElement cur = iterator.next();
if (cur == superRule || !(cur instanceof BnfRule)) continue;
if (!myRuleExtendsMap.get(superRule).contains(cur)) {
continue;
}
cardinality = cardinality == null ? newMap.get(cur) : cardinality.or(newMap.get(cur));
iterator.remove();
}
if (cardinality != null) {
newMap.put(superRule, cardinality);
}
}
}
return result;
}
public static BnfRule getSynonymTargetOrSelf(BnfRule rule) {
String attr = getAttribute(rule, KnownAttribute.ELEMENT_TYPE);
if (attr != null) {
BnfRule realRule = ((BnfFile)rule.getContainingFile()).getRule(attr);
if (realRule != null && shouldGeneratePsi(realRule, false)) return realRule;
}
return rule;
}
public static boolean shouldGeneratePsi(BnfRule rule, boolean psiClasses) {
BnfFile containingFile = (BnfFile)rule.getContainingFile();
BnfRule grammarRoot = containingFile.getRules().get(0);
if (grammarRoot == rule) return false;
if (Rule.isPrivate(rule) || Rule.isExternal(rule)) return false;
String elementType = getAttribute(rule, KnownAttribute.ELEMENT_TYPE);
if (!psiClasses) return elementType == null;
BnfRule thatRule = containingFile.getRule(elementType);
return thatRule == null || thatRule == grammarRoot || Rule.isPrivate(thatRule) || Rule.isExternal(thatRule);
}
}
| true | true | private Map<PsiElement, Cardinality> collectMembers(BnfRule rule, BnfExpression tree, String funcName, Set<PsiElement> visited) {
if (tree instanceof BnfPredicate) return Collections.emptyMap();
if (tree instanceof BnfLiteralExpression) return psiMap(tree, REQUIRED);
if (!visited.add(tree)) return psiMap(tree, REQUIRED);
Map<PsiElement, Cardinality> result;
if (tree instanceof BnfReferenceOrToken) {
BnfRule targetRule = myFile.getRule(tree.getText());
if (targetRule != null) {
if (Rule.isExternal(targetRule)) {
result = psiMap(new LeafPsiElement(EXTERNAL_TYPE, targetRule.getName()), REQUIRED);
}
else if (Rule.isLeft(targetRule)) {
if (!Rule.isInner(targetRule) && !Rule.isPrivate(targetRule)) {
result = new HashMap<PsiElement, Cardinality>();
result.put(getSynonymTargetOrSelf(targetRule), REQUIRED);
result.put(LEFT_MARKER, REQUIRED);
}
else {
result = Collections.emptyMap();
}
}
else if (Rule.isPrivate(targetRule)) {
result = myRuleContentsMap.get(targetRule); // optimize performance
if (result == null) {
BnfExpression body = targetRule.getExpression();
Map<PsiElement, Cardinality> map = collectMembers(targetRule, body, targetRule.getName(), visited);
result = map.containsKey(body) ? joinMaps(null, BnfTypes.BNF_CHOICE, Arrays.asList(map, map)) : map;
myRuleContentsMap.put(targetRule, result);
}
}
else {
result = psiMap(getSynonymTargetOrSelf(targetRule), REQUIRED);
}
}
else {
result = psiMap(tree, REQUIRED);
}
}
else if (tree instanceof BnfExternalExpression) {
List<BnfExpression> expressionList = ((BnfExternalExpression)tree).getExpressionList();
if (expressionList.size() == 1 && Rule.isMeta(rule)) {
result = psiMap(tree, REQUIRED);
}
else {
BnfExpression ruleRef = expressionList.get(0);
BnfRule metaRule = myFile.getRule(ruleRef.getText());
if (metaRule == null) {
result = psiMap(new LeafPsiElement(EXTERNAL_TYPE, "<<"+ruleRef.getText()+">>"), REQUIRED);
}
else if (Rule.isPrivate(metaRule)) {
result = new HashMap<PsiElement, Cardinality>();
Map<PsiElement, Cardinality> metaResults = collectMembers(rule, ruleRef, funcName, new HashSet<PsiElement>());
List<String> params = null;
for (PsiElement member : metaResults.keySet()) {
Cardinality cardinality = metaResults.get(member);
if (!(member instanceof BnfExternalExpression)) {
result.put(member, cardinality);
}
else {
if (params == null) {
params = collectExtraArguments(metaRule, metaRule.getExpression());
}
int idx = params.indexOf(member.getText());
if (idx > -1 && idx + 1 < expressionList.size()) {
Map<PsiElement, Cardinality> argMap = collectMembers(rule, expressionList.get(idx + 1), getNextName(funcName, idx), visited);
for (PsiElement element : argMap.keySet()) {
result.put(element, cardinality.and(argMap.get(element)));
}
}
}
}
}
else {
result = psiMap(metaRule, REQUIRED);
}
}
}
else {
IElementType type = getEffectiveType(tree);
boolean firstNonTrivial = tree == Rule.firstNotTrivial(rule);
PinMatcher pinMatcher = new PinMatcher(rule, type, firstNonTrivial ? rule.getName() : funcName);
boolean pinApplied = false;
List<Map<PsiElement, Cardinality>> list = new ArrayList<Map<PsiElement, Cardinality>>();
List<BnfExpression> childExpressions = getChildExpressions(tree);
for (int i = 0, childExpressionsSize = childExpressions.size(); i < childExpressionsSize; i++) {
BnfExpression child = childExpressions.get(i);
Map<PsiElement, Cardinality> nextMap = collectMembers(rule, child, getNextName(funcName, i), visited);
if (pinApplied) {
nextMap = joinMaps(null, BnfTypes.BNF_OP_OPT, Collections.singletonList(nextMap));
}
list.add(nextMap);
if (type == BNF_SEQUENCE && !pinApplied && pinMatcher.matches(i, child)) {
pinApplied = true;
}
}
result = joinMaps(firstNonTrivial ? rule : null, type, list);
}
if (rule.getExpression() == tree && Rule.isLeft(rule) && !Rule.isPrivate(rule) && !Rule.isInner(rule)) {
List<Map<PsiElement, Cardinality>> list = new ArrayList<Map<PsiElement, Cardinality>>();
Map<BnfRule, Cardinality> rulesToTheLeft = getRulesToTheLeft(rule);
for (BnfRule r : rulesToTheLeft.keySet()) {
Cardinality cardinality = rulesToTheLeft.get(r);
Map<PsiElement, Cardinality> leftMap = psiMap(getSynonymTargetOrSelf(r), REQUIRED);
if (cardinality.many()) {
list.add(joinMaps(null, BnfTypes.BNF_CHOICE, Arrays.asList(leftMap, psiMap(getSynonymTargetOrSelf(rule), REQUIRED))));
}
else {
list.add(leftMap);
}
}
Map<PsiElement, Cardinality> combinedLeftMap = joinMaps(null, BnfTypes.BNF_CHOICE, list);
result = joinMaps(null, BnfTypes.BNF_SEQUENCE, Arrays.asList(result, combinedLeftMap));
}
visited.remove(tree);
return result;
}
| private Map<PsiElement, Cardinality> collectMembers(BnfRule rule, BnfExpression tree, String funcName, Set<PsiElement> visited) {
if (tree instanceof BnfPredicate) return Collections.emptyMap();
if (tree instanceof BnfLiteralExpression) return psiMap(tree, REQUIRED);
if (!visited.add(tree)) return psiMap(tree, REQUIRED);
Map<PsiElement, Cardinality> result;
if (tree instanceof BnfReferenceOrToken) {
BnfRule targetRule = myFile.getRule(tree.getText());
if (targetRule != null) {
if (Rule.isExternal(targetRule)) {
result = psiMap(new LeafPsiElement(EXTERNAL_TYPE, targetRule.getName()), REQUIRED);
}
else if (Rule.isLeft(targetRule)) {
if (!Rule.isInner(targetRule) && !Rule.isPrivate(targetRule)) {
result = new HashMap<PsiElement, Cardinality>();
result.put(getSynonymTargetOrSelf(targetRule), REQUIRED);
result.put(LEFT_MARKER, REQUIRED);
}
else {
result = Collections.emptyMap();
}
}
else if (Rule.isPrivate(targetRule)) {
result = myRuleContentsMap.get(targetRule); // optimize performance
if (result == null) {
BnfExpression body = targetRule.getExpression();
Map<PsiElement, Cardinality> map = collectMembers(targetRule, body, targetRule.getName(), visited);
result = map.containsKey(body) ? joinMaps(null, BnfTypes.BNF_CHOICE, Arrays.asList(map, map)) : map;
myRuleContentsMap.put(targetRule, result);
}
}
else {
result = psiMap(getSynonymTargetOrSelf(targetRule), REQUIRED);
}
}
else {
result = psiMap(tree, REQUIRED);
}
}
else if (tree instanceof BnfExternalExpression) {
List<BnfExpression> expressionList = ((BnfExternalExpression)tree).getExpressionList();
if (expressionList.size() == 1 && Rule.isMeta(rule)) {
result = psiMap(tree, REQUIRED);
}
else {
BnfExpression ruleRef = expressionList.get(0);
BnfRule metaRule = myFile.getRule(ruleRef.getText());
if (metaRule == null) {
result = psiMap(new LeafPsiElement(EXTERNAL_TYPE, "#"+ruleRef.getText()), REQUIRED);
}
else if (Rule.isPrivate(metaRule)) {
result = new HashMap<PsiElement, Cardinality>();
Map<PsiElement, Cardinality> metaResults = collectMembers(rule, ruleRef, funcName, new HashSet<PsiElement>());
List<String> params = null;
for (PsiElement member : metaResults.keySet()) {
Cardinality cardinality = metaResults.get(member);
if (!(member instanceof BnfExternalExpression)) {
result.put(member, cardinality);
}
else {
if (params == null) {
params = collectExtraArguments(metaRule, metaRule.getExpression());
}
int idx = params.indexOf(member.getText());
if (idx > -1 && idx + 1 < expressionList.size()) {
Map<PsiElement, Cardinality> argMap = collectMembers(rule, expressionList.get(idx + 1), getNextName(funcName, idx), visited);
for (PsiElement element : argMap.keySet()) {
result.put(element, cardinality.and(argMap.get(element)));
}
}
}
}
}
else {
result = psiMap(metaRule, REQUIRED);
}
}
}
else {
IElementType type = getEffectiveType(tree);
boolean firstNonTrivial = tree == Rule.firstNotTrivial(rule);
PinMatcher pinMatcher = new PinMatcher(rule, type, firstNonTrivial ? rule.getName() : funcName);
boolean pinApplied = false;
List<Map<PsiElement, Cardinality>> list = new ArrayList<Map<PsiElement, Cardinality>>();
List<BnfExpression> childExpressions = getChildExpressions(tree);
for (int i = 0, childExpressionsSize = childExpressions.size(); i < childExpressionsSize; i++) {
BnfExpression child = childExpressions.get(i);
Map<PsiElement, Cardinality> nextMap = collectMembers(rule, child, getNextName(funcName, i), visited);
if (pinApplied) {
nextMap = joinMaps(null, BnfTypes.BNF_OP_OPT, Collections.singletonList(nextMap));
}
list.add(nextMap);
if (type == BNF_SEQUENCE && !pinApplied && pinMatcher.matches(i, child)) {
pinApplied = true;
}
}
result = joinMaps(firstNonTrivial ? rule : null, type, list);
}
if (rule.getExpression() == tree && Rule.isLeft(rule) && !Rule.isPrivate(rule) && !Rule.isInner(rule)) {
List<Map<PsiElement, Cardinality>> list = new ArrayList<Map<PsiElement, Cardinality>>();
Map<BnfRule, Cardinality> rulesToTheLeft = getRulesToTheLeft(rule);
for (BnfRule r : rulesToTheLeft.keySet()) {
Cardinality cardinality = rulesToTheLeft.get(r);
Map<PsiElement, Cardinality> leftMap = psiMap(getSynonymTargetOrSelf(r), REQUIRED);
if (cardinality.many()) {
list.add(joinMaps(null, BnfTypes.BNF_CHOICE, Arrays.asList(leftMap, psiMap(getSynonymTargetOrSelf(rule), REQUIRED))));
}
else {
list.add(leftMap);
}
}
Map<PsiElement, Cardinality> combinedLeftMap = joinMaps(null, BnfTypes.BNF_CHOICE, list);
result = joinMaps(null, BnfTypes.BNF_SEQUENCE, Arrays.asList(result, combinedLeftMap));
}
visited.remove(tree);
return result;
}
|
diff --git a/deegree-core/deegree-core-commons/src/main/java/org/deegree/commons/xml/XMLAdapter.java b/deegree-core/deegree-core-commons/src/main/java/org/deegree/commons/xml/XMLAdapter.java
index b4830f2f90..9639bc47b5 100644
--- a/deegree-core/deegree-core-commons/src/main/java/org/deegree/commons/xml/XMLAdapter.java
+++ b/deegree-core/deegree-core-commons/src/main/java/org/deegree/commons/xml/XMLAdapter.java
@@ -1,1514 +1,1516 @@
// $HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
Department of Geography, University of Bonn
and
lat/lon GmbH
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.commons.xml;
import static javax.xml.XMLConstants.DEFAULT_NS_PREFIX;
import static javax.xml.XMLConstants.NULL_NS_URI;
import static javax.xml.stream.XMLStreamConstants.CDATA;
import static javax.xml.stream.XMLStreamConstants.CHARACTERS;
import static javax.xml.stream.XMLStreamConstants.END_ELEMENT;
import static javax.xml.stream.XMLStreamConstants.START_ELEMENT;
import static org.deegree.commons.utils.net.HttpUtils.STREAM;
import static org.deegree.commons.utils.net.HttpUtils.get;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMContainer;
import org.apache.axiom.om.OMDocument;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMException;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMText;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axiom.om.xpath.AXIOMXPath;
import org.deegree.commons.i18n.Messages;
import org.deegree.commons.tom.ows.Version;
import org.deegree.commons.xml.stax.XMLStreamReaderDoc;
import org.jaxen.JaxenException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <code>XMLAdapter</code> is the common base class of all hand-written (i.e. not automatically generated) XML parsers
* and exporters in deegree. Classes that extend <code>XMLAdapter</code> provide the binding between a certain type of
* XML documents and their corresponding Java bean representation.
* <p>
* <code>XMLAdapter</code> tries to make the process of writing custom XML parsers as painless as possible. It provides
* the following functionality:
* <ul>
* <li>Lookup of nodes using XPath expressions.</li>
* <li>Lookup of <i>required</i> nodes. These methods throw an {@link XMLParsingException} if the expression does not
* have a result.</li>
* <li>Convenient retrieving of node values as Java primitives (<code>int</code>, <code>boolean</code>, ...) or common
* Objects (<code>QName</code>, <code>SimpleLink</code>, ...). If the value can not be converted to the expected type,
* an {@link XMLParsingException} is thrown.
* <li>Loading the XML content from different sources (<code>URL</code>, <code>Reader</code>, <code>InputStream</code>).
* </li>
* <li>Resolving of relative URLs that occur in the document content, i.e. that refer to resources that are located
* relative to the document.</li>
* </ul>
* </p>
* <p>
* Technically, the XML handling is based on <a href="http://ws.apache.org/commons/axiom/">AXIOM (AXis Object
* Model)</a>.
* </p>
*
* @author <a href="mailto:[email protected]">Markus Schneider </a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public class XMLAdapter {
private static final Logger LOG = LoggerFactory.getLogger( XMLAdapter.class );
/**
* The context
*/
protected static final NamespaceBindings nsContext = CommonNamespaces.getNamespaceContext();
/**
* the xlink namespace
*/
protected static final String XLN_NS = CommonNamespaces.XLNNS;
private QName SCHEMA_ATTRIBUTE_NAME = new QName( CommonNamespaces.XSINS, "schemaLocation" );
/**
* Use this URL as SystemID only if the document content cannot be pinpointed to a URL - in this case it may not use
* any relative references!
*/
public static final String DEFAULT_URL = "http://www.deegree.org/unknownLocation";
/** Root element of the XML contents. */
protected OMElement rootElement;
// physical source of the element (used for resolving relative URLs in the document)
private String systemId;
/**
* Creates a new <code>XMLAdapter</code> which is not bound to an XML element.
*/
public XMLAdapter() {
// nothing to do
}
/**
* Creates a new <code>XMLAdapter</code> with the given OMElement as root element;
*
* @param rootElement
* the root element of the xml adapter
*/
public XMLAdapter( OMElement rootElement ) {
this.rootElement = rootElement;
}
/**
* Creates a new instance that loads its content from the given <code>URL</code>.
*
* @param url
* source of the xml content
* @throws XMLProcessingException
*/
public XMLAdapter( URL url ) throws XMLProcessingException {
load( url );
}
/**
* Creates a new instance that loads its content from the given <code>File</code>.
*
* @param file
* source of the xml content
* @throws XMLProcessingException
*/
public XMLAdapter( File file ) throws XMLProcessingException {
if ( file != null ) {
try {
load( file.toURI().toURL() );
} catch ( MalformedURLException e ) {
throw new XMLProcessingException( e );
}
}
}
/**
* Creates a new instance that loads its content from the given <code>StringReader</code> using the default url.
*
* @param reader
* source of the xml content
*
* @throws XMLProcessingException
*/
public XMLAdapter( StringReader reader ) throws XMLProcessingException {
load( reader, DEFAULT_URL );
}
/**
* Creates a new instance that loads its content from the given <code>StringReader</code>.
*
* @param reader
* source of the xml content
* @param systemId
* this string should represent a URL that is related to the passed reader. If this URL is not available
* or unknown, the string should contain the value of XMLAdapter.DEFAULT_URL
*
* @throws XMLProcessingException
*/
public XMLAdapter( StringReader reader, String systemId ) throws XMLProcessingException {
load( reader, systemId );
}
/**
* Creates a new instance that loads its content from the given <code>InputStream</code> using the default url.
*
* @param in
* source of the xml content
*
* @throws XMLProcessingException
*/
public XMLAdapter( InputStream in ) throws XMLProcessingException {
load( in, DEFAULT_URL );
}
/**
* Creates a new instance that loads its content from the given <code>InputStream</code>.
*
* @param in
* source of the xml content
* @param systemId
* this string should represent a URL that is related to the passed reader. If this URL is not available
* or unknown, the string should contain the value of XMLAdapter.DEFAULT_URL
*
* @throws XMLProcessingException
*/
public XMLAdapter( InputStream in, String systemId ) throws XMLProcessingException {
load( in, systemId );
}
/**
* Creates a new instance that wraps the submitted XML document.
*
* @param doc
* xml content
* @param systemId
* the URL that is the source of the passed doc. If this URL is not available or unknown, the string
* should contain the value of XMLFragment.DEFAULT_URL
*/
public XMLAdapter( OMDocument doc, String systemId ) {
this( doc.getOMDocumentElement(), systemId );
}
/**
* Creates a new instance that wraps the given XML element.
*
* @param rootElement
* xml content
* @param systemId
* the URL that is the source of the passed doc. If this URL is not available or unknown, the string
* should contain the value of XMLFragment.DEFAULT_URL
*/
public XMLAdapter( OMElement rootElement, String systemId ) {
setRootElement( rootElement );
setSystemId( systemId );
}
public XMLAdapter( XMLStreamReader xmlStream ) {
load( xmlStream );
}
/**
* Returns the systemId (the physical location of the wrapped XML content).
*
* @return the systemId
*/
public String getSystemId() {
return systemId;
}
/**
* Sets the systemId (the physical location of the wrapped XML content).
*
* @param systemId
* systemId (physical location) to set
*/
public void setSystemId( String systemId ) {
this.systemId = systemId;
}
/**
* Returns whether the wrapped XML element contains schema references.
*
* @return true, if the element contains schema references, false otherwise
*/
public boolean hasSchemas() {
return rootElement.getAttribute( SCHEMA_ATTRIBUTE_NAME ) != null;
}
/**
* Determines the namespace <code>URI</code>s and the bound schema <code>URL</code>s from the 'xsi:schemaLocation'
* attribute of the wrapped XML element.
*
* @return keys are URIs (namespaces), values are URLs (schema locations)
* @throws XMLProcessingException
*/
public Map<String, URL> getSchemas()
throws XMLProcessingException {
Map<String, URL> schemaMap = new HashMap<String, URL>();
OMAttribute schemaLocationAttr = rootElement.getAttribute( SCHEMA_ATTRIBUTE_NAME );
if ( schemaLocationAttr == null ) {
return schemaMap;
}
String target = schemaLocationAttr.getAttributeValue();
StringTokenizer tokenizer = new StringTokenizer( target );
while ( tokenizer.hasMoreTokens() ) {
URI nsURI = null;
String token = tokenizer.nextToken();
try {
nsURI = new URI( token );
} catch ( URISyntaxException e ) {
String msg = "Invalid 'xsi:schemaLocation' attribute: namespace " + token + "' is not a valid URI.";
LOG.error( msg );
throw new XMLProcessingException( msg );
}
URL schemaURL = null;
try {
token = tokenizer.nextToken();
schemaURL = resolve( token );
} catch ( NoSuchElementException e ) {
String msg = "Invalid 'xsi:schemaLocation' attribute: namespace '" + nsURI
+ "' is missing a schema URL.";
LOG.error( msg );
throw new XMLProcessingException( msg );
} catch ( MalformedURLException ex ) {
String msg = "Invalid 'xsi:schemaLocation' attribute: '" + token + "' for namespace '" + nsURI
+ "' could not be parsed as URL.";
throw new XMLProcessingException( msg );
}
schemaMap.put( token, schemaURL );
}
return schemaMap;
}
/**
* Initializes this <code>XMLAdapter</code> with the content from the given <code>URL</code>. Sets the SystemId,
* too.
*
* @param url
* source of the xml content
* @throws XMLProcessingException
*/
public void load( URL url )
throws XMLProcessingException {
if ( url == null ) {
throw new IllegalArgumentException( "The given url may not be null" );
}
try {
load( get( STREAM, url.toExternalForm(), null ), url.toExternalForm() );
} catch ( IOException e ) {
throw new XMLProcessingException( e.getMessage(), e );
}
}
/**
* Same as #load(URL), but with http basic authentication
*
* @param url
* @param httpBasicUser
* @param httpBasicPass
* @throws XMLProcessingException
*/
public void load( URL url, String httpBasicUser, String httpBasicPass )
throws XMLProcessingException {
if ( url == null ) {
throw new IllegalArgumentException( "The given url may not be null" );
}
try {
load( get( STREAM, url.toExternalForm(), null, httpBasicUser, httpBasicPass ), url.toExternalForm() );
} catch ( IOException e ) {
throw new XMLProcessingException( e.getMessage(), e );
}
}
/**
* Initializes this <code>XMLAdapter</code> with the content from the given <code>InputStream</code>. Sets the
* SystemId, too.
*
* @param istream
* source of the xml content
* @param systemId
* cannot be null. This string should represent a URL that is related to the passed istream. If this URL
* is not available or unknown, the string should contain the value of XMLFragment.DEFAULT_URL
*
* @throws XMLProcessingException
*/
public void load( InputStream istream, String systemId )
throws XMLProcessingException {
if ( istream != null ) {
// TODO evaluate correct encoding handling
// PushbackInputStream pbis = new PushbackInputStream( istream, 1024 );
// String encoding = determineEncoding( pbis );
//
// InputStreamReader isr;
// try {
// isr = new InputStreamReader( pbis, encoding );
// } catch ( UnsupportedEncodingException e ) {
// throw new XMLProcessingException( e.getMessage(), e );
// }
//
setSystemId( systemId );
// TODO the code below is used, because constructing from Reader causes an error if the
// document contains a DOCTYPE definition
try {
StAXOMBuilder builder = new StAXOMBuilder( istream );
rootElement = builder.getDocumentElement();
} catch ( XMLStreamException e ) {
throw new XMLProcessingException( e.getMessage(), e );
}
// load( isr, systemId );
} else {
throw new NullPointerException( "The stream may not be null." );
}
}
/**
* Initializes this <code>XMLAdapter</code> with the content from the given <code>InputStream</code> and sets the
* system id to the {@link #DEFAULT_URL}
*
* @param xmlStream
* to load the xml from.
* @throws XMLProcessingException
*/
public void load( XMLStreamReader xmlStream )
throws XMLProcessingException {
if ( xmlStream.getEventType() != XMLStreamConstants.START_DOCUMENT ) {
setRootElement( new StAXOMBuilder( new XMLStreamReaderDoc( xmlStream ) ).getDocumentElement() );
} else {
setRootElement( new StAXOMBuilder( xmlStream ).getDocumentElement() );
}
if ( xmlStream.getLocation() != null && xmlStream.getLocation().getSystemId() != null ) {
setSystemId( xmlStream.getLocation().getSystemId() );
}
}
/**
* Initializes this <code>XMLAdapter</code> with the content from the given <code>InputStream</code> and sets the
* system id to the {@link #DEFAULT_URL}
*
* @param resourceStream
* to load the xml from.
* @throws XMLProcessingException
*/
public void load( InputStream resourceStream )
throws XMLProcessingException {
load( resourceStream, DEFAULT_URL );
}
/**
* Determines the encoding of an XML document from its header. If no header available
* <code>CharsetUtils.getSystemCharset()</code> will be returned
*
* @param pbis
* @return encoding of a XML document
* @throws XMLProcessingException
*/
// private String determineEncoding( PushbackInputStream pbis )
// throws XMLProcessingException {
// try {
// byte[] b = new byte[80];
// int rd = pbis.read( b );
//
// // TODO think about this
// String encoding = "UTF-8";
// if ( rd > 0 ) {
// String s = new String( b ).toLowerCase();
//
// if ( s.indexOf( "?>" ) > -1 ) {
// int p = s.indexOf( "encoding=" );
// if ( p > -1 ) {
// StringBuffer sb = new StringBuffer();
// int k = p + 1 + "encoding=".length();
// while ( s.charAt( k ) != '"' && s.charAt( k ) != '\'' ) {
// sb.append( s.charAt( k++ ) );
// }
// encoding = sb.toString();
// }
// }
// pbis.unread( b, 0, rd );
// }
// return encoding;
// } catch ( IOException e ) {
// throw new XMLProcessingException( e.getMessage(), e );
// }
// }
/**
* Initializes this <code>XMLAdapter</code> with the content from the given <code>StringReader</code>. Sets the
* SystemId, too.
*
* @param reader
* source of the XML content
* @param systemId
* can not be null. This string should represent a URL that is related to the passed reader. If this URL
* is not available or unknown, the string should contain the value of XMLFragment.DEFAULT_URL
*
* @throws XMLProcessingException
*/
public void load( StringReader reader, String systemId )
throws XMLProcessingException {
try {
if ( systemId == null ) {
throw new NullPointerException( "'systemId' must not be null!" );
}
setSystemId( systemId );
XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader( reader );
StAXOMBuilder builder = new StAXOMBuilder( parser );
rootElement = builder.getDocumentElement();
} catch ( XMLStreamException e ) {
throw new XMLProcessingException( e.getMessage(), e );
} catch ( OMException e ) {
throw new XMLProcessingException( e.getMessage(), e );
} catch ( FactoryConfigurationError e ) {
throw new XMLProcessingException( e.getMessage(), e );
}
}
/**
* Initializes this <code>XMLAdapter</code> with the content from the given <code>StringReader</code> and sets the
* system id to the {@link #DEFAULT_URL}
*
* @param reader
* to load the xml from.
* @throws XMLProcessingException
*/
public void load( StringReader reader )
throws XMLProcessingException {
load( reader, DEFAULT_URL );
}
/**
* Sets the root element, i.e. the XML element encapsulated by this <code>XMLAdapter</code>.
*
* @param rootElement
* the root element
*/
public void setRootElement( OMElement rootElement ) {
this.rootElement = rootElement;
}
/**
* Returns the root element, i.e. the XML element encapsulated by this <code>XMLAdapter</code>.
*
* @return the root element
*/
public OMElement getRootElement() {
return rootElement;
}
/**
* Resolves the given URL (which may be relative) against the SystemID of this <code>XMLAdapter</code> into an
* absolute <code>URL</code>.
*
* @param url
* <code>URL</code> to be resolved (may be relative or absolute)
* @return the resolved URL
* @throws MalformedURLException
*/
public URL resolve( String url )
throws MalformedURLException {
LOG.debug( "Resolving URL '" + url + "' against SystemID '" + systemId + "'." );
// check if url is an absolute path
File file = new File( url );
if ( file.isAbsolute() ) {
return file.toURI().toURL();
}
// TODO this is not really nice, also think about handling url specs here
URL resolvedURL = new URL( new URL( systemId ), url.replace( " ", "%20" ) );
LOG.debug( "-> resolvedURL: '" + resolvedURL + "'" );
return resolvedURL;
}
public Object evaluateXPath( XPath xpath, Object context )
throws XMLProcessingException {
Object result;
try {
result = getAXIOMXPath( xpath ).evaluate( context );
} catch ( JaxenException e ) {
throw new XMLProcessingException( e.getMessage() );
}
return result;
}
/**
* Parses the submitted XML element as a {@link SimpleLink}.
* <p>
* Possible escaping of the attributes "xlink:href", "xlink:role" and "xlink:arcrole" is performed automatically.
* </p>
*
* @param element
* @return the object representation of the element
* @throws XMLParsingException
*/
public SimpleLink parseSimpleLink( OMElement element )
throws XMLParsingException {
URI href = null;
URI role = null;
URI arcrole = null;
String title = null;
String show = null;
String actuate = null;
String uriString = null;
try {
uriString = element.getAttributeValue( new QName( CommonNamespaces.XLNNS, "href" ) );
if ( uriString != null ) {
href = new URI( null, uriString, null );
}
uriString = element.getAttributeValue( new QName( CommonNamespaces.XLNNS, "role" ) );
if ( uriString != null ) {
role = new URI( null, uriString, null );
}
uriString = element.getAttributeValue( new QName( CommonNamespaces.XLNNS, "arcrole" ) );
if ( uriString != null ) {
arcrole = new URI( null, uriString, null );
}
} catch ( URISyntaxException e ) {
throw new XMLParsingException( this, element, "'" + uriString + "' is not a valid URI." );
}
return new SimpleLink( href, role, arcrole, title, show, actuate );
}
/**
* Parses the given <code>String</code> as an <code>xsd:boolean</code> value.
*
* @param s
* the <code>String</code> to be parsed
* @return corresponding boolean value
* @throws XMLParsingException
* if the given <code>String</code> is not a valid instance of <code>xsd:boolean</code>
*/
public boolean parseBoolean( String s )
throws XMLParsingException {
boolean value = false;
if ( "true".equals( s ) || "1".equals( s ) ) {
value = true;
} else if ( "false".equals( s ) || "0".equals( s ) ) {
value = false;
} else {
String msg = Messages.getMessage( "XML_SYNTAX_ERROR_BOOLEAN", s );
throw new XMLParsingException( this, (OMElement) null, msg );
}
return value;
}
/**
* Parses the given <code>String</code> as an <code>xsd:double</code> value.
*
* @param s
* the <code>String</code> to be parsed
* @return corresponding double value
* @throws XMLParsingException
* if the given <code>String</code> is not a valid instance of <code>xsd:double</code>
*/
public double parseDouble( String s )
throws XMLParsingException {
double value = 0.0;
try {
value = Double.parseDouble( s );
} catch ( NumberFormatException e ) {
String msg = Messages.getMessage( "XML_SYNTAX_ERROR_DOUBLE", s );
throw new XMLParsingException( this, (OMElement) null, msg );
}
return value;
}
/**
* Parses the given <code>String</code> as an <code>xsd:float</code> value.
*
* @param s
* the <code>String</code> to be parsed
* @return corresponding float value
* @throws XMLParsingException
* if the given <code>String</code> is not a valid instance of <code>xsd:float</code>
*/
public float parseFloat( String s )
throws XMLParsingException {
float value = 0.0f;
try {
value = Float.parseFloat( s );
} catch ( NumberFormatException e ) {
String msg = Messages.getMessage( "XML_SYNTAX_ERROR_FLOAT", s );
throw new XMLParsingException( this, (OMElement) null, msg );
}
return value;
}
/**
* Parses the given <code>String</code> as an <code>xsd:integer</code> value.
*
* @param s
* the <code>String</code> to be parsed
* @return corresponding integer value
* @throws XMLParsingException
* if the given <code>String</code> is not a valid instance of <code>xsd:integer</code>
*/
public int parseInt( String s )
throws XMLParsingException {
int value = 0;
try {
value = Integer.parseInt( s );
} catch ( NumberFormatException e ) {
String msg = Messages.getMessage( "XML_SYNTAX_ERROR_INT", s );
throw new XMLParsingException( this, (OMElement) null, msg );
}
return value;
}
/**
* Parses the given <code>String</code> as an {@link URL}.
*
* @param s
* the <code>String</code> to be parsed
* @return corresponding URL value
* @throws XMLParsingException
* if the given <code>String</code> is not a valid {@link URL}
*/
public URL parseURL( String s )
throws XMLParsingException {
URL value = null;
try {
value = new URL( s );
} catch ( MalformedURLException e ) {
String msg = Messages.getMessage( "XML_SYNTAX_ERROR_URL", s );
throw new XMLParsingException( this, (OMElement) null, msg );
}
return value;
}
/**
* Parses the given <code>String</code> as an <code>xsd:QName</code> value.
*
* @param s
* the <code>String</code> to be parsed
* @param element
* element that provides the namespace context (used to resolve the namespace prefix)
* @return corresponding QName value
* @throws XMLParsingException
* if the given <code>String</code> is not a valid instance of <code>xsd:QName</code>
*/
public QName parseQName( String s, OMElement element )
throws XMLParsingException {
QName value = element.resolveQName( s );
if ( value == null ) {
// unbound prefix
int colonIdx = s.indexOf( ':' );
if ( colonIdx != -1 ) {
String prefix = s.substring( 0, colonIdx );
String localPart = s.substring( colonIdx + 1 );
value = new QName( null, localPart, prefix );
} else {
value = new QName( s );
}
}
return value;
}
public OMElement getElement( OMElement context, XPath xpath )
throws XMLParsingException {
Object result = getNode( context, xpath );
if ( result == null ) {
return null;
}
if ( !( result instanceof OMElement ) ) {
String msg = Messages.getMessage( "XML_PARSING_ERROR_NOT_ELEMENT", xpath, context, result.getClass() );
throw new XMLParsingException( this, context, msg );
}
return (OMElement) result;
}
@SuppressWarnings("unchecked")
public List<OMElement> getElements( OMElement context, XPath xpath )
throws XMLParsingException {
return getNodes( context, xpath );
}
// TODO Should we consider changing OMElement in OMNode for getNode* methods?
public synchronized Object getNode( OMElement context, XPath xpath )
throws XMLParsingException {
Object node;
try {
node = getAXIOMXPath( xpath ).selectSingleNode( context );
} catch ( JaxenException e ) {
throw new XMLParsingException( this, context, e.getMessage() );
}
return node;
}
public boolean getNodeAsBoolean( OMElement context, XPath xpath, boolean defaultValue )
throws XMLParsingException {
boolean value = defaultValue;
String s = getNodeAsString( context, xpath, null );
if ( s != null ) {
value = parseBoolean( s );
}
return value;
}
public double getNodeAsDouble( OMElement context, XPath xpath, double defaultValue )
throws XMLParsingException {
double value = defaultValue;
String s = getNodeAsString( context, xpath, null );
if ( s != null ) {
value = parseDouble( s );
}
return value;
}
public float getNodeAsFloat( OMElement context, XPath xpath, float defaultValue )
throws XMLParsingException {
float value = defaultValue;
String s = getNodeAsString( context, xpath, null );
if ( s != null ) {
value = parseFloat( s );
}
return value;
}
public BigInteger getNodeAsBigInt( OMElement context, XPath xpath, BigInteger defaultValue )
throws XMLParsingException {
String s = getNodeAsString( context, xpath, null );
if ( s != null ) {
try {
return new BigInteger( s );
} catch ( NumberFormatException e ) {
throw new XMLParsingException( this, context, e.getMessage() );
}
}
return defaultValue;
}
public int getNodeAsInt( OMElement context, XPath xpath, int defaultValue )
throws XMLParsingException {
int value = defaultValue;
String s = getNodeAsString( context, xpath, null );
if ( s != null ) {
value = parseInt( s );
}
return value;
}
public URL getNodeAsURL( OMElement context, XPath xpath, URL defaultValue )
throws XMLParsingException {
URL value = defaultValue;
String s = getNodeAsString( context, xpath, null );
if ( s != null ) {
value = parseURL( s );
}
return value;
}
public QName getNodeAsQName( OMElement context, XPath xpath, QName defaultValue )
throws XMLParsingException {
QName value = defaultValue;
Object node = getNode( context, xpath );
if ( node != null ) {
if ( node instanceof OMText ) {
value = ( (OMText) node ).getTextAsQName();
} else if ( node instanceof OMElement ) {
OMElement element = (OMElement) node;
value = element.resolveQName( element.getText() );
} else if ( node instanceof OMAttribute ) {
OMAttribute attribute = (OMAttribute) node;
value = attribute.getOwner().resolveQName( attribute.getAttributeValue() );
} else {
String msg = "Unexpected node type '" + node.getClass() + "'.";
throw new XMLParsingException( this, context, msg );
}
}
return value;
}
public String getNodeAsString( OMElement context, XPath xpath, String defaultValue )
throws XMLParsingException {
String value = defaultValue;
Object node = getNode( context, xpath );
if ( node != null ) {
try {
if ( node instanceof OMText ) {
value = ( (OMText) node ).getText();
} else if ( node instanceof OMElement ) {
value = ( (OMElement) node ).getText();
} else if ( node instanceof OMAttribute ) {
value = ( (OMAttribute) node ).getAttributeValue();
} else {
String msg = "Unexpected node type '" + node.getClass() + "'.";
throw new XMLParsingException( this, context, msg );
}
} catch ( OMException ex ) {
String msg = "Internal error while accessing node '" + ex.getMessage() + "'.";
throw new XMLParsingException( this, context, msg );
}
}
return value;
}
public Version getNodeAsVersion( OMElement context, XPath xpath, Version defaultValue )
throws XMLParsingException {
Version value = defaultValue;
String s = getNodeAsString( context, xpath, null );
if ( s != null ) {
value = Version.parseVersion( s );
}
return value;
}
public synchronized List getNodes( OMElement context, XPath xpath )
throws XMLParsingException {
List<?> nodes;
try {
nodes = getAXIOMXPath( xpath ).selectNodes( context );
} catch ( JaxenException e ) {
throw new XMLParsingException( this, context, e.getMessage() );
}
return nodes;
}
public String[] getNodesAsStrings( OMElement contextNode, XPath xpath ) {
String[] values = null;
List<?> nl = getNodes( contextNode, xpath );
if ( nl != null ) {
values = new String[nl.size()];
for ( int i = 0; i < nl.size(); i++ ) {
Object node = nl.get( i );
String value = null;
if ( node != null ) {
try {
if ( node instanceof OMText ) {
value = ( (OMText) node ).getText();
} else if ( node instanceof OMElement ) {
value = ( (OMElement) node ).getText();
} else if ( node instanceof OMAttribute ) {
value = ( (OMAttribute) node ).getAttributeValue();
} else {
String msg = "Unexpected node type '" + node.getClass() + "'.";
throw new XMLParsingException( this, contextNode, msg );
}
} catch ( OMException ex ) {
String msg = "Internal error while accessing node '" + ex.getMessage() + "'.";
throw new XMLParsingException( this, contextNode, msg );
}
}
values[i] = value;
}
} else {
values = new String[0];
}
return values;
}
public QName[] getNodesAsQNames( OMElement contextNode, XPath xpath ) {
QName[] values = null;
List<?> nl = getNodes( contextNode, xpath );
if ( nl != null ) {
values = new QName[nl.size()];
for ( int i = 0; i < nl.size(); i++ ) {
Object node = nl.get( i );
QName value = null;
if ( node instanceof OMText ) {
value = ( (OMText) node ).getTextAsQName();
} else if ( node instanceof OMElement ) {
OMElement element = (OMElement) node;
value = element.resolveQName( element.getText() );
} else if ( node instanceof OMAttribute ) {
OMAttribute attribute = (OMAttribute) node;
value = attribute.getOwner().resolveQName( attribute.getAttributeValue() );
} else {
String msg = "Unexpected node type '" + node.getClass() + "'.";
throw new XMLParsingException( this, contextNode, msg );
}
values[i] = value;
}
} else {
values = new QName[0];
}
return values;
}
public OMElement getRequiredElement( OMElement context, XPath xpath )
throws XMLParsingException {
OMElement element = getElement( context, xpath );
if ( element == null ) {
String msg = Messages.getMessage( "XML_REQUIRED_ELEMENT_MISSING", xpath, context.getQName() );
throw new XMLParsingException( this, context, msg );
}
return element;
}
public List<OMElement> getRequiredElements( OMElement context, XPath xpath )
throws XMLParsingException {
List<OMElement> elements = getElements( context, xpath );
if ( elements.size() == 0 ) {
String msg = Messages.getMessage( "XML_REQUIRED_ELEMENT_MISSING", xpath, context.getQName() );
throw new XMLParsingException( this, context, msg );
}
return elements;
}
public Object getRequiredNode( OMElement context, XPath xpath )
throws XMLParsingException {
Object node = getNode( context, xpath );
if ( node == null ) {
String msg = Messages.getMessage( "XML_REQUIRED_NODE_MISSING", xpath, context.getQName() );
throw new XMLParsingException( this, context, msg );
}
return node;
}
public boolean getRequiredNodeAsBoolean( OMElement context, XPath xpath )
throws XMLParsingException {
String s = getRequiredNodeAsString( context, xpath );
boolean value = parseBoolean( s );
return value;
}
public double getRequiredNodeAsDouble( OMElement context, XPath xpath )
throws XMLParsingException {
String s = getRequiredNodeAsString( context, xpath );
double value = parseDouble( s );
return value;
}
public float getRequiredNodeAsFloat( OMElement context, XPath xpath )
throws XMLParsingException {
String s = getRequiredNodeAsString( context, xpath );
float value = parseFloat( s );
return value;
}
public int getRequiredNodeAsInteger( OMElement context, XPath xpath )
throws XMLParsingException {
String s = getRequiredNodeAsString( context, xpath );
int value = parseInt( s );
return value;
}
public URL getRequiredNodeAsURL( OMElement context, XPath xpath )
throws XMLParsingException {
String s = getRequiredNodeAsString( context, xpath );
URL value = parseURL( s );
return value;
}
public String getRequiredNodeAsString( OMElement context, XPath xpath )
throws XMLParsingException {
String value = getNodeAsString( context, xpath, null );
if ( value == null ) {
String msg = Messages.getMessage( "XML_REQUIRED_NODE_MISSING", xpath, context.getQName() );
throw new XMLParsingException( this, context, msg );
}
return value;
}
public QName getRequiredNodeAsQName( OMElement context, XPath xpath )
throws XMLParsingException {
QName value = getNodeAsQName( context, xpath, null );
if ( value == null ) {
String msg = Messages.getMessage( "XML_REQUIRED_NODE_MISSING", xpath, context.getQName() );
throw new XMLParsingException( this, context, msg );
}
return value;
}
public Version getRequiredNodeAsVersion( OMElement context, XPath xpath )
throws XMLParsingException {
Version value = getNodeAsVersion( context, xpath, null );
if ( value == null ) {
String msg = Messages.getMessage( "XML_REQUIRED_NODE_MISSING", xpath, context.getQName() );
throw new XMLParsingException( this, context, msg );
}
return value;
}
@SuppressWarnings("unchecked")
public List getRequiredNodes( OMElement context, XPath xpath )
throws XMLParsingException {
List nodes = getNodes( context, xpath );
if ( nodes.size() == 0 ) {
String msg = Messages.getMessage( "XML_REQUIRED_NODE_MISSING", xpath, context.getQName() );
throw new XMLParsingException( this, context, msg );
}
return nodes;
}
private AXIOMXPath getAXIOMXPath( XPath xpath )
throws JaxenException {
AXIOMXPath compiledXPath = new AXIOMXPath( xpath.getXPath() );
compiledXPath.setNamespaceContext( xpath.getNamespaceContext() );
return compiledXPath;
}
/**
* Constructs a {@link NamespaceContext} from all active namespace bindings available in the scope of the given
* {@link OMElement}.
*
* @param element
* the given element
* @return the constructed namespace context
*/
public NamespaceBindings getNamespaceContext( OMElement element ) {
NamespaceBindings nsContext = new NamespaceBindings();
augmentNamespaceContext( element, nsContext );
return nsContext;
}
@SuppressWarnings("unchecked")
private void augmentNamespaceContext( OMElement element, NamespaceBindings nsContext ) {
Iterator<OMNamespace> iterator = element.getAllDeclaredNamespaces();
while ( iterator.hasNext() ) {
OMNamespace namespace = iterator.next();
if ( nsContext.translateNamespacePrefixToUri( namespace.getPrefix() ) == null ) {
nsContext.addNamespace( namespace.getPrefix(), namespace.getNamespaceURI() );
}
}
OMContainer parent = element.getParent();
if ( parent != null && parent instanceof OMElement ) {
augmentNamespaceContext( (OMElement) parent, nsContext );
}
}
/**
* Write an element with simple text content into the XMLStream.
* <p>
* Convenience method to write simple elements like:
*
* <pre>
* <ogc:GeometryOperand>gml:Envelope</ogc:GeometryOperand>
* <gml:upperCorner>90 180</gml:upperCorner>
* </pre>
*
* @param writer
* @param namespace
* the namespace of the element
* @param elemName
* the element name
* @param value
* the text value of the element
* @throws XMLStreamException
*/
public static void writeElement( XMLStreamWriter writer, String namespace, String elemName, String value )
throws XMLStreamException {
writer.writeStartElement( namespace, elemName );
if ( value != null ) {
writer.writeCharacters( value );
}
writer.writeEndElement();
}
/**
* Write an element with simple text content and an attribute into the XMLStream.
* <p>
* Convenience method to write simple elements like:
*
* <pre>
* <ogc:GeometryOperand name="env">gml:Envelope</ogc:GeometryOperand>
* <gml:upperCorner>90 180</gml:upperCorner>
* </pre>
*
* @param writer
* @param namespace
* the namespace of the element
* @param elemName
* the element name
* @param value
* the text value of the element
* @param attrNS
* the namespace of the attribute, <code>null</null> if the local namespace of the element should be used
* @param attribPRE
* to use for the namespace binding
* @param attrName
* the attribute name
* @param attrValue
* the attribute value, if <code>null</code> the attribute will not be written.
* @throws XMLStreamException
*/
public static void writeElement( XMLStreamWriter writer, String namespace, String elemName, String value,
String attrNS, String attribPRE, String attrName, String attrValue )
throws XMLStreamException {
writeElement( writer, namespace, elemName, value, attrNS, attribPRE, attrName, attrValue, false );
}
public static void writeElement( XMLStreamWriter writer, String namespace, String elemName, String value,
String attrNS, String attribPRE, String attrName, String attrValue,
boolean writeNamespace )
throws XMLStreamException {
writer.writeStartElement( namespace, elemName );
if ( writeNamespace && attrNS != null && attribPRE != null ) {
writer.writeNamespace( attribPRE, attrNS );
}
if ( attrValue != null ) {
if ( attrNS == null ) {
writer.writeAttribute( attrName, attrValue );
} else {
if ( attribPRE == null ) {
writer.writeAttribute( attrNS, attrName, attrValue );
} else {
writer.writeAttribute( attribPRE, attrNS, attrName, attrValue );
}
}
}
if ( value != null ) {
writer.writeCharacters( value );
}
writer.writeEndElement();
}
/**
* Write an optional attribute at the current position of the writer. If the value is empty or <code>null</code> no
* attribute will be written.
*
* @param writer
* @param name
* @param value
* @throws XMLStreamException
*/
public static void writeOptionalAttribute( XMLStreamWriter writer, String name, String value )
throws XMLStreamException {
if ( value != null && !"".equals( value ) ) {
writer.writeAttribute( name, value );
}
}
/**
* Write an optional attribute at the current position of the writer. If the value is empty or <code>null</code> no
* attribute will be written.
*
* @param writer
* @param namespace
* of the attribute
* @param name
* of the attribute
* @param value
* of the attribute might be <code>null</code>
* @throws XMLStreamException
*/
public static void writeOptionalNSAttribute( XMLStreamWriter writer, String namespace, String name, String value )
throws XMLStreamException {
if ( value != null && !"".equals( value ) ) {
writer.writeAttribute( namespace, name, value );
}
}
/**
* Write an element with a single attribute into the XMLStream.
*
* <p>
* Convenience method to write simple elements like:
*
* <pre>
* <ows:Post xlink:href="http://localhost/" />
* <ogc:TemporalOperator name="TM_Begins" />
* </pre>
*
* @param writer
* @param namespace
* the namespace of the element
* @param elemName
* the element name
* @param attrNS
* the namespace of the attribute, <code>null</null> if the local namespace of the element should be used
* @param attrName
* the attribute name
* @param attrValue
* the attribute value
* @throws XMLStreamException
*/
public static void writeElement( XMLStreamWriter writer, String namespace, String elemName, String attrNS,
String attrName, String attrValue )
throws XMLStreamException {
writer.writeStartElement( namespace, elemName );
if ( attrNS == null ) {
writer.writeAttribute( attrName, attrValue );
} else {
writer.writeAttribute( attrNS, attrName, attrValue );
}
writer.writeEndElement();
}
/**
* Write an optional element with simple text content into the XMLStream. If the value is <code>null</code>, than
* the element is omitted.
*
* <p>
* Convenience method to write simple elements like:
*
* <pre>
* <ogc:GeometryOperand>gml:Envelope</ogc:GeometryOperand>
* <gml:upperCorner>10 -42</gml:upperCorner>
* </pre>
*
* @param writer
* @param namespace
* the namespace of the element
* @param elemName
* the element name
* @param value
* the text value of the element
* @throws XMLStreamException
*/
public static void writeOptionalElement( XMLStreamWriter writer, String namespace, String elemName, String value )
throws XMLStreamException {
if ( value != null ) {
writer.writeStartElement( namespace, elemName );
writer.writeCharacters( value );
writer.writeEndElement();
}
}
/**
* Copies an XML element (including all attributes and subnodes) from an {@link XMLStreamReader} into the given
* {@link XMLStreamWriter}.
*
* @param writer
* {@link XMLStreamWriter} that the xml is appended to
* @param inStream
* cursor must point at a <code>START_ELEMENT</code> event and points at the corresponding
* <code>END_ELEMENT</code> event afterwards
* @throws XMLStreamException
*/
public static void writeElement( XMLStreamWriter writer, XMLStreamReader inStream )
throws XMLStreamException {
if ( inStream.getEventType() != XMLStreamConstants.START_ELEMENT ) {
throw new XMLStreamException( "Input stream does not point to a START_ELEMENT event." );
}
int openElements = 0;
boolean firstRun = true;
while ( firstRun || openElements > 0 ) {
firstRun = false;
int eventType = inStream.getEventType();
switch ( eventType ) {
case CDATA: {
writer.writeCData( inStream.getText() );
break;
}
case CHARACTERS: {
writer.writeCharacters( inStream.getTextCharacters(), inStream.getTextStart(), inStream.getTextLength() );
break;
}
case END_ELEMENT: {
writer.writeEndElement();
openElements--;
break;
}
case START_ELEMENT: {
String prefix = inStream.getPrefix();
String namespaceURI = inStream.getNamespaceURI();
if ( NULL_NS_URI.equals( namespaceURI ) && ( prefix == null || DEFAULT_NS_PREFIX.equals( prefix ) ) ) {
writer.writeStartElement( inStream.getLocalName() );
} else {
if ( prefix == null || DEFAULT_NS_PREFIX.equals( prefix ) ) {
writer.writeStartElement( DEFAULT_NS_PREFIX, inStream.getLocalName(), namespaceURI );
} else {
writer.writeStartElement( prefix, inStream.getLocalName(), namespaceURI );
}
}
// copy all namespace bindings
for ( int i = 0; i < inStream.getNamespaceCount(); i++ ) {
String nsPrefix = inStream.getNamespacePrefix( i );
String nsURI = inStream.getNamespaceURI( i );
if ( nsPrefix != null && nsURI != null ) {
writer.writeNamespace( nsPrefix, nsURI );
} else if ( nsPrefix == null ) {
writer.writeDefaultNamespace( nsURI );
}
}
- ensureBinding( writer, prefix, namespaceURI );
+ if ( namespaceURI != null ) {
+ ensureBinding( writer, prefix, namespaceURI );
+ }
// copy all attributes
for ( int i = 0; i < inStream.getAttributeCount(); i++ ) {
String localName = inStream.getAttributeLocalName( i );
String nsPrefix = inStream.getAttributePrefix( i );
String value = inStream.getAttributeValue( i );
String nsURI = inStream.getAttributeNamespace( i );
- if ( nsURI == null || "".equals( nsURI )) {
+ if ( nsURI == null || "".equals( nsURI ) ) {
writer.writeAttribute( localName, value );
} else {
ensureBinding( writer, nsPrefix, nsURI );
writer.writeAttribute( nsPrefix, nsURI, localName, value );
}
}
openElements++;
break;
}
default: {
break;
}
}
if ( openElements > 0 ) {
inStream.next();
}
}
}
private static void ensureBinding( XMLStreamWriter writer, String prefix, String namespaceURI )
throws XMLStreamException {
String boundPrefix = writer.getPrefix( namespaceURI );
if ( prefix == null && !NULL_NS_URI.equals( boundPrefix ) ) {
writer.writeDefaultNamespace( namespaceURI );
} else if ( prefix != null && !prefix.equals( writer.getPrefix( namespaceURI ) ) ) {
writer.writeNamespace( prefix, namespaceURI );
}
}
/**
* Writes an element without namespace, and with an (optional) text
*
* @param writer
* @param name
* @param text
* @throws XMLStreamException
*/
public static void writeElement( XMLStreamWriter writer, String name, String text )
throws XMLStreamException {
writer.writeStartElement( name );
if ( text != null ) {
writer.writeCharacters( text );
}
writer.writeEndElement();
}
/**
* Writes an element without namespace, only if text not null
*
* @param writer
* @param name
* @param text
* @throws XMLStreamException
*/
public static void maybeWriteElement( XMLStreamWriter writer, String name, String text )
throws XMLStreamException {
if ( text != null ) {
writer.writeStartElement( name );
writer.writeCharacters( text );
writer.writeEndElement();
}
}
/**
* Writes an element with namespace, only if text not null
*
* @param writer
* @param ns
* @param name
* @param text
* @throws XMLStreamException
*/
public static void maybeWriteElementNS( XMLStreamWriter writer, String ns, String name, String text )
throws XMLStreamException {
if ( text != null ) {
writer.writeStartElement( ns, name );
writer.writeCharacters( text );
writer.writeEndElement();
}
}
@Override
public String toString() {
return rootElement == null ? "(no document)" : rootElement.toString();
}
}
| false | true | public static void writeElement( XMLStreamWriter writer, XMLStreamReader inStream )
throws XMLStreamException {
if ( inStream.getEventType() != XMLStreamConstants.START_ELEMENT ) {
throw new XMLStreamException( "Input stream does not point to a START_ELEMENT event." );
}
int openElements = 0;
boolean firstRun = true;
while ( firstRun || openElements > 0 ) {
firstRun = false;
int eventType = inStream.getEventType();
switch ( eventType ) {
case CDATA: {
writer.writeCData( inStream.getText() );
break;
}
case CHARACTERS: {
writer.writeCharacters( inStream.getTextCharacters(), inStream.getTextStart(), inStream.getTextLength() );
break;
}
case END_ELEMENT: {
writer.writeEndElement();
openElements--;
break;
}
case START_ELEMENT: {
String prefix = inStream.getPrefix();
String namespaceURI = inStream.getNamespaceURI();
if ( NULL_NS_URI.equals( namespaceURI ) && ( prefix == null || DEFAULT_NS_PREFIX.equals( prefix ) ) ) {
writer.writeStartElement( inStream.getLocalName() );
} else {
if ( prefix == null || DEFAULT_NS_PREFIX.equals( prefix ) ) {
writer.writeStartElement( DEFAULT_NS_PREFIX, inStream.getLocalName(), namespaceURI );
} else {
writer.writeStartElement( prefix, inStream.getLocalName(), namespaceURI );
}
}
// copy all namespace bindings
for ( int i = 0; i < inStream.getNamespaceCount(); i++ ) {
String nsPrefix = inStream.getNamespacePrefix( i );
String nsURI = inStream.getNamespaceURI( i );
if ( nsPrefix != null && nsURI != null ) {
writer.writeNamespace( nsPrefix, nsURI );
} else if ( nsPrefix == null ) {
writer.writeDefaultNamespace( nsURI );
}
}
ensureBinding( writer, prefix, namespaceURI );
// copy all attributes
for ( int i = 0; i < inStream.getAttributeCount(); i++ ) {
String localName = inStream.getAttributeLocalName( i );
String nsPrefix = inStream.getAttributePrefix( i );
String value = inStream.getAttributeValue( i );
String nsURI = inStream.getAttributeNamespace( i );
if ( nsURI == null || "".equals( nsURI )) {
writer.writeAttribute( localName, value );
} else {
ensureBinding( writer, nsPrefix, nsURI );
writer.writeAttribute( nsPrefix, nsURI, localName, value );
}
}
openElements++;
break;
}
default: {
break;
}
}
if ( openElements > 0 ) {
inStream.next();
}
}
}
| public static void writeElement( XMLStreamWriter writer, XMLStreamReader inStream )
throws XMLStreamException {
if ( inStream.getEventType() != XMLStreamConstants.START_ELEMENT ) {
throw new XMLStreamException( "Input stream does not point to a START_ELEMENT event." );
}
int openElements = 0;
boolean firstRun = true;
while ( firstRun || openElements > 0 ) {
firstRun = false;
int eventType = inStream.getEventType();
switch ( eventType ) {
case CDATA: {
writer.writeCData( inStream.getText() );
break;
}
case CHARACTERS: {
writer.writeCharacters( inStream.getTextCharacters(), inStream.getTextStart(), inStream.getTextLength() );
break;
}
case END_ELEMENT: {
writer.writeEndElement();
openElements--;
break;
}
case START_ELEMENT: {
String prefix = inStream.getPrefix();
String namespaceURI = inStream.getNamespaceURI();
if ( NULL_NS_URI.equals( namespaceURI ) && ( prefix == null || DEFAULT_NS_PREFIX.equals( prefix ) ) ) {
writer.writeStartElement( inStream.getLocalName() );
} else {
if ( prefix == null || DEFAULT_NS_PREFIX.equals( prefix ) ) {
writer.writeStartElement( DEFAULT_NS_PREFIX, inStream.getLocalName(), namespaceURI );
} else {
writer.writeStartElement( prefix, inStream.getLocalName(), namespaceURI );
}
}
// copy all namespace bindings
for ( int i = 0; i < inStream.getNamespaceCount(); i++ ) {
String nsPrefix = inStream.getNamespacePrefix( i );
String nsURI = inStream.getNamespaceURI( i );
if ( nsPrefix != null && nsURI != null ) {
writer.writeNamespace( nsPrefix, nsURI );
} else if ( nsPrefix == null ) {
writer.writeDefaultNamespace( nsURI );
}
}
if ( namespaceURI != null ) {
ensureBinding( writer, prefix, namespaceURI );
}
// copy all attributes
for ( int i = 0; i < inStream.getAttributeCount(); i++ ) {
String localName = inStream.getAttributeLocalName( i );
String nsPrefix = inStream.getAttributePrefix( i );
String value = inStream.getAttributeValue( i );
String nsURI = inStream.getAttributeNamespace( i );
if ( nsURI == null || "".equals( nsURI ) ) {
writer.writeAttribute( localName, value );
} else {
ensureBinding( writer, nsPrefix, nsURI );
writer.writeAttribute( nsPrefix, nsURI, localName, value );
}
}
openElements++;
break;
}
default: {
break;
}
}
if ( openElements > 0 ) {
inStream.next();
}
}
}
|
diff --git a/src/java/org/codehaus/groovy/grails/support/MockFileResource.java b/src/java/org/codehaus/groovy/grails/support/MockFileResource.java
index 8da64151f..ad4ea8408 100644
--- a/src/java/org/codehaus/groovy/grails/support/MockFileResource.java
+++ b/src/java/org/codehaus/groovy/grails/support/MockFileResource.java
@@ -1,46 +1,46 @@
/* Copyright 2004-2005 Graeme Rocher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.support;
import org.springframework.core.io.ByteArrayResource;
import java.io.UnsupportedEncodingException;
/**
* A resource that mocks the behavior of a FileResource
*
* @author Graeme Rocher
* @since 1.1
* <p/>
* Created: Feb 6, 2009
*/
public class MockFileResource extends ByteArrayResource{
private String fileName;
- public MockFileResource(String fileName, String contents) {
+ public MockFileResource(String fileName, String contents) throws UnsupportedEncodingException {
super(contents.getBytes("UTF-8"));
this.fileName = fileName;
}
public MockFileResource(String fileName, String contents, String encoding) throws UnsupportedEncodingException {
super(contents.getBytes(encoding));
this.fileName = fileName;
}
@Override
public String getFilename() throws IllegalStateException {
return this.fileName;
}
}
| true | true | public MockFileResource(String fileName, String contents) {
super(contents.getBytes("UTF-8"));
this.fileName = fileName;
}
| public MockFileResource(String fileName, String contents) throws UnsupportedEncodingException {
super(contents.getBytes("UTF-8"));
this.fileName = fileName;
}
|
diff --git a/src/main/java/org/iplantc/de/server/FileDownloadServlet.java b/src/main/java/org/iplantc/de/server/FileDownloadServlet.java
index 2fd0183a..f1b2b4bd 100644
--- a/src/main/java/org/iplantc/de/server/FileDownloadServlet.java
+++ b/src/main/java/org/iplantc/de/server/FileDownloadServlet.java
@@ -1,138 +1,137 @@
package org.iplantc.de.server;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.iplantc.de.shared.services.ServiceCallWrapper;
import org.iplantc.irodsfile.util.LargeIOUtils;
/**
* A servlet for downloading a file.
*/
@SuppressWarnings("serial")
public class FileDownloadServlet extends HttpServlet {
private static final String[] HEADER_FIELDS_TO_COPY = {"Content-Disposition"}; //$NON-NLS-1$
// private static final Logger logger = Logger.getLogger(FileDownloadServlet.class);
/**
* {@inheritDoc}
*/
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
DEServiceInputStream fileContents = null;
try {
String address = buildRequestAddress(request);
ServiceCallWrapper wrapper = new ServiceCallWrapper(address);
DEServiceDispatcher dispatcher = createServiceDispatcher(request);
fileContents = dispatcher.getServiceStream(wrapper);
copyHeaderFields(response, fileContents);
copyFileContents(response, fileContents);
} catch (Exception e) {
throw new ServletException(e.getMessage(), e);
} finally {
if (fileContents != null) {
try {
fileContents.close();
} catch (IOException ignore) {
}
}
}
}
/**
* Copies the file contents from the given input stream to the output stream controlled by the given
* response object.
*
* @param response the HTTP servlet response object.
* @param fileContents the input stream used to retrieve the file contents.
* @throws IOException if an I/O error occurs.
*/
private void copyFileContents(HttpServletResponse response, InputStream fileContents)
throws IOException {
OutputStream out = null;
try {
out = response.getOutputStream();
LargeIOUtils.copy(fileContents, out);
} finally {
fileContents.close();
if (out != null) {
out.close();
}
}
}
/**
* Copies the content type along with any other HTTP header fields that are supposed to be copied
* from the original HTTP response to our HTTP servlet response.
*
* @param response our HTTP servlet response.
* @param fileContents the file contents along with the HTTP headers and content type.
*/
private void copyHeaderFields(HttpServletResponse response, DEServiceInputStream fileContents) {
String contentType = fileContents.getContentType();
response.setContentType(contentType == null ? "" : contentType); //$NON-NLS-1$
for (String fieldName : HEADER_FIELDS_TO_COPY) {
response.setHeader(fieldName, fileContents.getHeaderField(fieldName));
}
}
/**
* Creates the service dispatcher that will be used to fetch the file contents.
*
* @param request our HTTP servlet request.
* @return the service dispatcher.
*/
private DEServiceDispatcher createServiceDispatcher(HttpServletRequest request) {
DEServiceDispatcher dispatcher = new DEServiceDispatcher();
try {
dispatcher.init(getServletConfig());
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dispatcher.setContext(getServletContext());
dispatcher.setRequest(request);
return dispatcher;
}
/**
* Builds the URL used to fetch the file contents.
*
* @param request out HTTP servlet request.
* @return the URL.
* @throws UnsupportedEncodingException
*/
private String buildRequestAddress(HttpServletRequest request) throws UnsupportedEncodingException {
String user = URLEncoder.encode(request.getParameter("user"), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$
String path = URLEncoder.encode(request.getParameter("path"), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$
String attachment = request.getParameter("attachment"); //$NON-NLS-1$
if (attachment == null) {
attachment = "1"; //$NON-NLS-1$
}
attachment = URLEncoder.encode(attachment, "UTF-8"); //$NON-NLS-1$
String downloadUrl = request.getParameter("url"); //$NON-NLS-1$
if (downloadUrl == null) {
downloadUrl = DiscoveryEnvironmentProperties.getDownloadFileServiceBaseUrl();
} else {
- downloadUrl = DiscoveryEnvironmentProperties.getDataMgmtServiceBaseUrl() + "/" //$NON-NLS-1$
- + downloadUrl;
+ downloadUrl = DiscoveryEnvironmentProperties.getDataMgmtServiceBaseUrl() + downloadUrl;
}
String address = String.format("%s?user=%s&path=%s&attachment=%s", downloadUrl, user, path, //$NON-NLS-1$
attachment);
return address;
}
}
| true | true | private String buildRequestAddress(HttpServletRequest request) throws UnsupportedEncodingException {
String user = URLEncoder.encode(request.getParameter("user"), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$
String path = URLEncoder.encode(request.getParameter("path"), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$
String attachment = request.getParameter("attachment"); //$NON-NLS-1$
if (attachment == null) {
attachment = "1"; //$NON-NLS-1$
}
attachment = URLEncoder.encode(attachment, "UTF-8"); //$NON-NLS-1$
String downloadUrl = request.getParameter("url"); //$NON-NLS-1$
if (downloadUrl == null) {
downloadUrl = DiscoveryEnvironmentProperties.getDownloadFileServiceBaseUrl();
} else {
downloadUrl = DiscoveryEnvironmentProperties.getDataMgmtServiceBaseUrl() + "/" //$NON-NLS-1$
+ downloadUrl;
}
String address = String.format("%s?user=%s&path=%s&attachment=%s", downloadUrl, user, path, //$NON-NLS-1$
attachment);
return address;
}
| private String buildRequestAddress(HttpServletRequest request) throws UnsupportedEncodingException {
String user = URLEncoder.encode(request.getParameter("user"), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$
String path = URLEncoder.encode(request.getParameter("path"), "UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$
String attachment = request.getParameter("attachment"); //$NON-NLS-1$
if (attachment == null) {
attachment = "1"; //$NON-NLS-1$
}
attachment = URLEncoder.encode(attachment, "UTF-8"); //$NON-NLS-1$
String downloadUrl = request.getParameter("url"); //$NON-NLS-1$
if (downloadUrl == null) {
downloadUrl = DiscoveryEnvironmentProperties.getDownloadFileServiceBaseUrl();
} else {
downloadUrl = DiscoveryEnvironmentProperties.getDataMgmtServiceBaseUrl() + downloadUrl;
}
String address = String.format("%s?user=%s&path=%s&attachment=%s", downloadUrl, user, path, //$NON-NLS-1$
attachment);
return address;
}
|
diff --git a/src/main/java/org/primefaces/extensions/behavior/javascript/JavascriptBehaviorRenderer.java b/src/main/java/org/primefaces/extensions/behavior/javascript/JavascriptBehaviorRenderer.java
index a1de2dbe..9616f66a 100644
--- a/src/main/java/org/primefaces/extensions/behavior/javascript/JavascriptBehaviorRenderer.java
+++ b/src/main/java/org/primefaces/extensions/behavior/javascript/JavascriptBehaviorRenderer.java
@@ -1,88 +1,88 @@
/*
* Copyright 2011 PrimeFaces Extensions.
*
* 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.
*
* $Id$
*/
package org.primefaces.extensions.behavior.javascript;
import javax.faces.component.UIComponent;
import javax.faces.component.UIParameter;
import javax.faces.component.behavior.ClientBehavior;
import javax.faces.component.behavior.ClientBehaviorContext;
import javax.faces.context.FacesContext;
import javax.faces.render.ClientBehaviorRenderer;
import org.primefaces.extensions.util.ComponentUtils;
/**
* {@link ClientBehaviorRenderer} implementation for the {@link JavascriptBehavior}.
*
* @author Thomas Andraschko / last modified by $Author$
* @version $Revision$
* @since 0.2
*/
public class JavascriptBehaviorRenderer extends ClientBehaviorRenderer {
@Override
public String getScript(final ClientBehaviorContext behaviorContext, final ClientBehavior behavior) {
final JavascriptBehavior javascriptBehavior = (JavascriptBehavior) behavior;
if (javascriptBehavior.isDisabled()) {
return null;
}
final FacesContext context = behaviorContext.getFacesContext();
final UIComponent component = behaviorContext.getComponent();
String source = behaviorContext.getSourceId();
if (source == null) {
source = component.getClientId(context);
}
final StringBuilder script = new StringBuilder();
- script.append("return PrimeFacesExt.behavior.Javascript({");
+ script.append("PrimeFacesExt.behavior.Javascript({");
script.append("source:'").append(ComponentUtils.escapeComponentId(source)).append("'");
script.append(",event:'").append(behaviorContext.getEventName()).append("'");
script.append(",execute:function(source, event, params, ext){");
script.append(javascriptBehavior.getExecute()).append(";}");
// params
boolean paramWritten = false;
for (final UIComponent child : component.getChildren()) {
if (child instanceof UIParameter) {
final UIParameter parameter = (UIParameter) child;
if (paramWritten) {
script.append(",");
} else {
paramWritten = true;
script.append(",params:{");
}
script.append("'");
script.append(parameter.getName()).append("':'").append(parameter.getValue());
script.append("'");
}
}
if (paramWritten) {
script.append("}");
}
script.append("}, arguments[1]);");
return script.toString();
}
}
| true | true | public String getScript(final ClientBehaviorContext behaviorContext, final ClientBehavior behavior) {
final JavascriptBehavior javascriptBehavior = (JavascriptBehavior) behavior;
if (javascriptBehavior.isDisabled()) {
return null;
}
final FacesContext context = behaviorContext.getFacesContext();
final UIComponent component = behaviorContext.getComponent();
String source = behaviorContext.getSourceId();
if (source == null) {
source = component.getClientId(context);
}
final StringBuilder script = new StringBuilder();
script.append("return PrimeFacesExt.behavior.Javascript({");
script.append("source:'").append(ComponentUtils.escapeComponentId(source)).append("'");
script.append(",event:'").append(behaviorContext.getEventName()).append("'");
script.append(",execute:function(source, event, params, ext){");
script.append(javascriptBehavior.getExecute()).append(";}");
// params
boolean paramWritten = false;
for (final UIComponent child : component.getChildren()) {
if (child instanceof UIParameter) {
final UIParameter parameter = (UIParameter) child;
if (paramWritten) {
script.append(",");
} else {
paramWritten = true;
script.append(",params:{");
}
script.append("'");
script.append(parameter.getName()).append("':'").append(parameter.getValue());
script.append("'");
}
}
if (paramWritten) {
script.append("}");
}
script.append("}, arguments[1]);");
return script.toString();
}
| public String getScript(final ClientBehaviorContext behaviorContext, final ClientBehavior behavior) {
final JavascriptBehavior javascriptBehavior = (JavascriptBehavior) behavior;
if (javascriptBehavior.isDisabled()) {
return null;
}
final FacesContext context = behaviorContext.getFacesContext();
final UIComponent component = behaviorContext.getComponent();
String source = behaviorContext.getSourceId();
if (source == null) {
source = component.getClientId(context);
}
final StringBuilder script = new StringBuilder();
script.append("PrimeFacesExt.behavior.Javascript({");
script.append("source:'").append(ComponentUtils.escapeComponentId(source)).append("'");
script.append(",event:'").append(behaviorContext.getEventName()).append("'");
script.append(",execute:function(source, event, params, ext){");
script.append(javascriptBehavior.getExecute()).append(";}");
// params
boolean paramWritten = false;
for (final UIComponent child : component.getChildren()) {
if (child instanceof UIParameter) {
final UIParameter parameter = (UIParameter) child;
if (paramWritten) {
script.append(",");
} else {
paramWritten = true;
script.append(",params:{");
}
script.append("'");
script.append(parameter.getName()).append("':'").append(parameter.getValue());
script.append("'");
}
}
if (paramWritten) {
script.append("}");
}
script.append("}, arguments[1]);");
return script.toString();
}
|
diff --git a/src/com/librelio/activity/SlideShowActivity.java b/src/com/librelio/activity/SlideShowActivity.java
index 82241ca..0ee8458 100644
--- a/src/com/librelio/activity/SlideShowActivity.java
+++ b/src/com/librelio/activity/SlideShowActivity.java
@@ -1,81 +1,81 @@
/**
*
*/
package com.librelio.activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.LinearLayout;
import com.artifex.mupdf.MediaHolder;
import com.librelio.base.BaseActivity;
import com.librelio.view.ImagePager;
import com.niveales.wind.R;
/**
* @author Mike Osipov
*/
public class SlideShowActivity extends BaseActivity {
private static final String TAG = "SlideShowActivity";
private ImagePager imagePager;
private Handler autoPlayHandler;
private String fullPath;
private int autoPlayDelay;
private int bgColor;
private int initialSlidePosition;
private boolean transition = true;
private boolean autoPlay;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sideshow_activity_layout);
LinearLayout frame = (LinearLayout)findViewById(R.id.slide_show_full);
autoPlayDelay = getIntent().getExtras().getInt(MediaHolder.PLAY_DELAY_KEY);
transition = getIntent().getExtras().getBoolean(MediaHolder.TRANSITION_KEY);
autoPlay = getIntent().getExtras().getBoolean(MediaHolder.AUTO_PLAY_KEY);
bgColor = getIntent().getExtras().getInt(MediaHolder.BG_COLOR_KEY);
fullPath = getIntent().getExtras().getString(MediaHolder.FULL_PATH_KEY);
initialSlidePosition = getIntent().getExtras().getInt(MediaHolder.INITIAL_SLIDE_POSITION);
- imagePager = new ImagePager(this, fullPath, transition, 100, 100);
- imagePager.post(new Runnable() {
+ imagePager = new ImagePager(this, fullPath, transition, 0, 0);
+ imagePager.postDelayed(new Runnable() {
@Override
public void run() {
imagePager.setViewWidth(imagePager.getWidth());
imagePager.setViewHeight(imagePager.getHeight());
}
- });
+ }, 250);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
lp.gravity = Gravity.CENTER;
imagePager.setLayoutParams(lp);
if(autoPlay) {
autoPlayHandler = new Handler();
autoPlayHandler.postDelayed(new Runnable() {
@Override
public void run() {
Log.d(TAG, "autoPlayHandler start");
imagePager.setCurrentPosition(imagePager.getCurrentPosition() + 1, transition);
autoPlayHandler.postDelayed(this, autoPlayDelay);
}}, autoPlayDelay);
}
if (initialSlidePosition > 0){
imagePager.setCurrentPosition(initialSlidePosition, false);
}
imagePager.setBackgroundColor(bgColor);
frame.addView(imagePager);
}
}
| false | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sideshow_activity_layout);
LinearLayout frame = (LinearLayout)findViewById(R.id.slide_show_full);
autoPlayDelay = getIntent().getExtras().getInt(MediaHolder.PLAY_DELAY_KEY);
transition = getIntent().getExtras().getBoolean(MediaHolder.TRANSITION_KEY);
autoPlay = getIntent().getExtras().getBoolean(MediaHolder.AUTO_PLAY_KEY);
bgColor = getIntent().getExtras().getInt(MediaHolder.BG_COLOR_KEY);
fullPath = getIntent().getExtras().getString(MediaHolder.FULL_PATH_KEY);
initialSlidePosition = getIntent().getExtras().getInt(MediaHolder.INITIAL_SLIDE_POSITION);
imagePager = new ImagePager(this, fullPath, transition, 100, 100);
imagePager.post(new Runnable() {
@Override
public void run() {
imagePager.setViewWidth(imagePager.getWidth());
imagePager.setViewHeight(imagePager.getHeight());
}
});
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
lp.gravity = Gravity.CENTER;
imagePager.setLayoutParams(lp);
if(autoPlay) {
autoPlayHandler = new Handler();
autoPlayHandler.postDelayed(new Runnable() {
@Override
public void run() {
Log.d(TAG, "autoPlayHandler start");
imagePager.setCurrentPosition(imagePager.getCurrentPosition() + 1, transition);
autoPlayHandler.postDelayed(this, autoPlayDelay);
}}, autoPlayDelay);
}
if (initialSlidePosition > 0){
imagePager.setCurrentPosition(initialSlidePosition, false);
}
imagePager.setBackgroundColor(bgColor);
frame.addView(imagePager);
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sideshow_activity_layout);
LinearLayout frame = (LinearLayout)findViewById(R.id.slide_show_full);
autoPlayDelay = getIntent().getExtras().getInt(MediaHolder.PLAY_DELAY_KEY);
transition = getIntent().getExtras().getBoolean(MediaHolder.TRANSITION_KEY);
autoPlay = getIntent().getExtras().getBoolean(MediaHolder.AUTO_PLAY_KEY);
bgColor = getIntent().getExtras().getInt(MediaHolder.BG_COLOR_KEY);
fullPath = getIntent().getExtras().getString(MediaHolder.FULL_PATH_KEY);
initialSlidePosition = getIntent().getExtras().getInt(MediaHolder.INITIAL_SLIDE_POSITION);
imagePager = new ImagePager(this, fullPath, transition, 0, 0);
imagePager.postDelayed(new Runnable() {
@Override
public void run() {
imagePager.setViewWidth(imagePager.getWidth());
imagePager.setViewHeight(imagePager.getHeight());
}
}, 250);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
lp.gravity = Gravity.CENTER;
imagePager.setLayoutParams(lp);
if(autoPlay) {
autoPlayHandler = new Handler();
autoPlayHandler.postDelayed(new Runnable() {
@Override
public void run() {
Log.d(TAG, "autoPlayHandler start");
imagePager.setCurrentPosition(imagePager.getCurrentPosition() + 1, transition);
autoPlayHandler.postDelayed(this, autoPlayDelay);
}}, autoPlayDelay);
}
if (initialSlidePosition > 0){
imagePager.setCurrentPosition(initialSlidePosition, false);
}
imagePager.setBackgroundColor(bgColor);
frame.addView(imagePager);
}
|
diff --git a/org.eclipse.mylyn.resources.ui/src/org/eclipse/mylyn/internal/resources/ui/ContextEditorManager.java b/org.eclipse.mylyn.resources.ui/src/org/eclipse/mylyn/internal/resources/ui/ContextEditorManager.java
index 1aa52d0d1..eec2af147 100644
--- a/org.eclipse.mylyn.resources.ui/src/org/eclipse/mylyn/internal/resources/ui/ContextEditorManager.java
+++ b/org.eclipse.mylyn.resources.ui/src/org/eclipse/mylyn/internal/resources/ui/ContextEditorManager.java
@@ -1,289 +1,290 @@
/*******************************************************************************
* Copyright (c) 2004 - 2006 University Of British Columbia 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:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.internal.resources.ui;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.mylar.context.core.AbstractContextStructureBridge;
import org.eclipse.mylar.context.core.ContextCorePlugin;
import org.eclipse.mylar.context.core.IMylarContext;
import org.eclipse.mylar.context.core.IMylarContextListener;
import org.eclipse.mylar.context.core.IMylarElement;
import org.eclipse.mylar.context.ui.AbstractContextUiBridge;
import org.eclipse.mylar.context.ui.ContextUiPlugin;
import org.eclipse.mylar.core.MylarStatusHandler;
import org.eclipse.mylar.internal.context.ui.ContextUiPrefContstants;
import org.eclipse.mylar.resources.MylarResourcesPlugin;
import org.eclipse.mylar.tasks.core.DateRangeContainer;
import org.eclipse.mylar.tasks.core.ITask;
import org.eclipse.mylar.tasks.core.ITaskActivityListener;
import org.eclipse.mylar.tasks.ui.TasksUiPlugin;
import org.eclipse.mylar.tasks.ui.editors.NewTaskEditorInput;
import org.eclipse.mylar.tasks.ui.editors.TaskEditor;
import org.eclipse.mylar.tasks.ui.editors.TaskEditorInput;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.XMLMemento;
import org.eclipse.ui.internal.EditorManager;
import org.eclipse.ui.internal.IPreferenceConstants;
import org.eclipse.ui.internal.IWorkbenchConstants;
import org.eclipse.ui.internal.Workbench;
import org.eclipse.ui.internal.WorkbenchMessages;
import org.eclipse.ui.internal.WorkbenchPage;
/**
* @author Mik Kersten
*/
public class ContextEditorManager implements IMylarContextListener, ITaskActivityListener {
private static final String PREFS_PREFIX = "editors.task.";
private static final String KEY_CONTEXT_EDITORS = "ContextOpenEditors";
private boolean previousCloseEditorsSetting = Workbench.getInstance().getPreferenceStore().getBoolean(
IPreferenceConstants.REUSE_EDITORS_BOOLEAN);
public void taskActivated(ITask task) {
if (!Workbench.getInstance().isStarting()
&& ContextUiPlugin.getDefault().getPreferenceStore().getBoolean(
ContextUiPrefContstants.AUTO_MANAGE_EDITORS)) {
Workbench workbench = (Workbench) PlatformUI.getWorkbench();
previousCloseEditorsSetting = workbench.getPreferenceStore().getBoolean(
IPreferenceConstants.REUSE_EDITORS_BOOLEAN);
workbench.getPreferenceStore().setValue(IPreferenceConstants.REUSE_EDITORS_BOOLEAN, false);
boolean wasPaused = ContextCorePlugin.getContextManager().isContextCapturePaused();
try {
if (!wasPaused) {
ContextCorePlugin.getContextManager().setContextCapturePaused(true);
}
WorkbenchPage page = (WorkbenchPage) workbench.getActiveWorkbenchWindow().getActivePage();
+ String mementoString = null;
try {
- String mementoString = MylarResourcesPlugin.getDefault().getPreferenceStore().getString(
+ mementoString = MylarResourcesPlugin.getDefault().getPreferenceStore().getString(
PREFS_PREFIX + task.getHandleIdentifier());
if (mementoString != null) {
IMemento memento = XMLMemento.createReadRoot(new StringReader(mementoString));
if (memento != null) {
restoreEditors(page, memento);
}
}
} catch (Exception e) {
- MylarStatusHandler.log(e, "Could not restore all editors");
+ MylarStatusHandler.log(e, "Could not restore all editors, memento: " + mementoString);
}
IMylarElement activeNode = ContextCorePlugin.getContextManager().getActiveContext().getActiveNode();
if (activeNode != null) {
ContextUiPlugin.getDefault().getUiBridge(activeNode.getContentType()).open(activeNode);
}
} catch (Exception e) {
MylarStatusHandler.fail(e, "failed to open editors on activation", false);
} finally {
ContextCorePlugin.getContextManager().setContextCapturePaused(false);
}
}
}
public void taskDeactivated(ITask task) {
if (!PlatformUI.getWorkbench().isClosing()
&& ContextUiPlugin.getDefault().getPreferenceStore().getBoolean(
ContextUiPrefContstants.AUTO_MANAGE_EDITORS)) {
XMLMemento memento = XMLMemento.createWriteRoot(KEY_CONTEXT_EDITORS);
((WorkbenchPage) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()).getEditorManager()
.saveState(memento);
// TODO: avoid storing with preferneces due to bloat?
StringWriter writer = new StringWriter();
try {
memento.save(writer);
MylarResourcesPlugin.getDefault().getPreferenceStore().setValue(
PREFS_PREFIX + task.getHandleIdentifier(), writer.getBuffer().toString());
} catch (IOException e) {
MylarStatusHandler.fail(e, "Could not store editor state", false);
}
Workbench.getInstance().getPreferenceStore().setValue(IPreferenceConstants.REUSE_EDITORS_BOOLEAN,
previousCloseEditorsSetting);
closeAllEditors();
}
}
public void contextActivated(IMylarContext context) {
// ignore, using task activation
}
@SuppressWarnings("unchecked")
private void restoreEditors(WorkbenchPage page, IMemento memento) {
EditorManager editorManager = page.getEditorManager();
final ArrayList visibleEditors = new ArrayList(5);
final IEditorReference activeEditor[] = new IEditorReference[1];
final MultiStatus result = new MultiStatus(PlatformUI.PLUGIN_ID, IStatus.OK,
WorkbenchMessages.EditorManager_problemsRestoringEditors, null);
// HACK: using reflection to gain accessibility
Class<?> clazz = editorManager.getClass();
try {
Method method = clazz.getDeclaredMethod("restoreEditorState", IMemento.class, ArrayList.class,
IEditorReference[].class, MultiStatus.class);
method.setAccessible(true);
IMemento[] editorMementos = memento.getChildren(IWorkbenchConstants.TAG_EDITOR);
for (int x = 0; x < editorMementos.length; x++) {
// editorManager.restoreEditorState(editorMementos[x], visibleEditors, activeEditor, result);
method.invoke(editorManager, new Object[] { editorMementos[x], visibleEditors, activeEditor, result });
}
for (int i = 0; i < visibleEditors.size(); i++) {
editorManager.setVisibleEditor((IEditorReference) visibleEditors.get(i), false);
}
if (activeEditor[0] != null) {
IWorkbenchPart editor = activeEditor[0].getPart(true);
if (editor != null) {
page.activate(editor);
}
}
} catch (Exception e) {
MylarStatusHandler.fail(e, "Could not restore editors", false);
}
}
public void contextDeactivated(IMylarContext context) {
// ignore, using task activation
}
public void closeAllEditors() {
try {
if (PlatformUI.getWorkbench().isClosing()) {
return;
}
for (IWorkbenchWindow window : PlatformUI.getWorkbench().getWorkbenchWindows()) {
IWorkbenchPage page = window.getActivePage();
if (page != null) {
IEditorReference[] references = page.getEditorReferences();
List<IEditorReference> toClose = new ArrayList<IEditorReference>();
for (int i = 0; i < references.length; i++) {
if (!isActiveTaskEditor(references[i]) && !isUnsubmittedTaskEditor(references[i])) {
toClose.add(references[i]);
}
}
page.closeEditors(toClose.toArray(new IEditorReference[toClose.size()]), true);
}
}
} catch (Throwable t) {
MylarStatusHandler.fail(t, "Could not auto close editor.", false);
}
}
private boolean isUnsubmittedTaskEditor(IEditorReference editorReference) {
IEditorPart part = editorReference.getEditor(false);
if (part instanceof TaskEditor) {
try {
IEditorInput input = editorReference.getEditorInput();
if (input instanceof NewTaskEditorInput) {
return true;
}
} catch (PartInitException e) {
// ignore
}
}
return false;
}
private boolean isActiveTaskEditor(IEditorReference editorReference) {
ITask activeTask = TasksUiPlugin.getTaskListManager().getTaskList().getActiveTask();
try {
IEditorInput input = editorReference.getEditorInput();
if (input instanceof TaskEditorInput) {
TaskEditorInput taskEditorInput = (TaskEditorInput) input;
if (activeTask != null && taskEditorInput.getTask() != null
&& taskEditorInput.getTask().getHandleIdentifier().equals(activeTask.getHandleIdentifier())) {
return true;
}
}
} catch (PartInitException e) {
// ignore
}
return false;
}
public void presentationSettingsChanging(UpdateKind kind) {
// ignore
}
public void presentationSettingsChanged(UpdateKind kind) {
// ignore
}
public void interestChanged(List<IMylarElement> elements) {
for (IMylarElement element : elements) {
if (ContextUiPlugin.getDefault().getPreferenceStore().getBoolean(
ContextUiPrefContstants.AUTO_MANAGE_EDITORS)) {
if (!element.getInterest().isInteresting()) {
AbstractContextStructureBridge bridge = ContextCorePlugin.getDefault().getStructureBridge(
element.getContentType());
if (bridge.isDocument(element.getHandleIdentifier())) {
AbstractContextUiBridge uiBridge = ContextUiPlugin.getDefault().getUiBridge(
element.getContentType());
uiBridge.close(element);
}
}
}
}
}
public void elementDeleted(IMylarElement node) {
// ignore
}
public void landmarkAdded(IMylarElement node) {
// ignore
}
public void landmarkRemoved(IMylarElement node) {
// ignore
}
public void relationsChanged(IMylarElement node) {
// ignore
}
public void activityChanged(DateRangeContainer week) {
// ignore
}
public void calendarChanged() {
// ignore
}
public void taskListRead() {
// ignore
}
public void tasksActivated(List<ITask> tasks) {
// ignore
}
}
| false | true | public void taskActivated(ITask task) {
if (!Workbench.getInstance().isStarting()
&& ContextUiPlugin.getDefault().getPreferenceStore().getBoolean(
ContextUiPrefContstants.AUTO_MANAGE_EDITORS)) {
Workbench workbench = (Workbench) PlatformUI.getWorkbench();
previousCloseEditorsSetting = workbench.getPreferenceStore().getBoolean(
IPreferenceConstants.REUSE_EDITORS_BOOLEAN);
workbench.getPreferenceStore().setValue(IPreferenceConstants.REUSE_EDITORS_BOOLEAN, false);
boolean wasPaused = ContextCorePlugin.getContextManager().isContextCapturePaused();
try {
if (!wasPaused) {
ContextCorePlugin.getContextManager().setContextCapturePaused(true);
}
WorkbenchPage page = (WorkbenchPage) workbench.getActiveWorkbenchWindow().getActivePage();
try {
String mementoString = MylarResourcesPlugin.getDefault().getPreferenceStore().getString(
PREFS_PREFIX + task.getHandleIdentifier());
if (mementoString != null) {
IMemento memento = XMLMemento.createReadRoot(new StringReader(mementoString));
if (memento != null) {
restoreEditors(page, memento);
}
}
} catch (Exception e) {
MylarStatusHandler.log(e, "Could not restore all editors");
}
IMylarElement activeNode = ContextCorePlugin.getContextManager().getActiveContext().getActiveNode();
if (activeNode != null) {
ContextUiPlugin.getDefault().getUiBridge(activeNode.getContentType()).open(activeNode);
}
} catch (Exception e) {
MylarStatusHandler.fail(e, "failed to open editors on activation", false);
} finally {
ContextCorePlugin.getContextManager().setContextCapturePaused(false);
}
}
}
| public void taskActivated(ITask task) {
if (!Workbench.getInstance().isStarting()
&& ContextUiPlugin.getDefault().getPreferenceStore().getBoolean(
ContextUiPrefContstants.AUTO_MANAGE_EDITORS)) {
Workbench workbench = (Workbench) PlatformUI.getWorkbench();
previousCloseEditorsSetting = workbench.getPreferenceStore().getBoolean(
IPreferenceConstants.REUSE_EDITORS_BOOLEAN);
workbench.getPreferenceStore().setValue(IPreferenceConstants.REUSE_EDITORS_BOOLEAN, false);
boolean wasPaused = ContextCorePlugin.getContextManager().isContextCapturePaused();
try {
if (!wasPaused) {
ContextCorePlugin.getContextManager().setContextCapturePaused(true);
}
WorkbenchPage page = (WorkbenchPage) workbench.getActiveWorkbenchWindow().getActivePage();
String mementoString = null;
try {
mementoString = MylarResourcesPlugin.getDefault().getPreferenceStore().getString(
PREFS_PREFIX + task.getHandleIdentifier());
if (mementoString != null) {
IMemento memento = XMLMemento.createReadRoot(new StringReader(mementoString));
if (memento != null) {
restoreEditors(page, memento);
}
}
} catch (Exception e) {
MylarStatusHandler.log(e, "Could not restore all editors, memento: " + mementoString);
}
IMylarElement activeNode = ContextCorePlugin.getContextManager().getActiveContext().getActiveNode();
if (activeNode != null) {
ContextUiPlugin.getDefault().getUiBridge(activeNode.getContentType()).open(activeNode);
}
} catch (Exception e) {
MylarStatusHandler.fail(e, "failed to open editors on activation", false);
} finally {
ContextCorePlugin.getContextManager().setContextCapturePaused(false);
}
}
}
|
diff --git a/src/ca/mcgill/hs/serv/HSServAutoStart.java b/src/ca/mcgill/hs/serv/HSServAutoStart.java
index 43e9130..2bc6431 100644
--- a/src/ca/mcgill/hs/serv/HSServAutoStart.java
+++ b/src/ca/mcgill/hs/serv/HSServAutoStart.java
@@ -1,40 +1,40 @@
package ca.mcgill.hs.serv;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
public class HSServAutoStart extends BroadcastReceiver{
public static final String HSANDROID_PREFS_NAME = "HSAndroidPrefs";
private SharedPreferences settings;
private ComponentName comp;
private ComponentName svc;
@Override
public void onReceive(Context context, Intent intent){
//check if the received intent is BOOT_COMPLETED
if( "android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
//get the saved settings
settings = context.getSharedPreferences(HSANDROID_PREFS_NAME, Activity.MODE_WORLD_READABLE);
//read the setting for StartAtPhoneBoot if it exists, and only load service if it's set to true
if (settings.contains("StartAtPhoneBoot")){
- if (settings.getBoolean("StartAtPhoneBoot", true)){
+ if (settings.getBoolean("StartAtPhoneBoot", false)){
comp = new ComponentName(context.getPackageName(), HSService.class.getName());
svc = context.startService(new Intent().setComponent(comp));
}
}
if (svc == null){
Log.e("HSServAutoStart", "Could not start HSService " + comp.toString());
}
}
}
}
| true | true | public void onReceive(Context context, Intent intent){
//check if the received intent is BOOT_COMPLETED
if( "android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
//get the saved settings
settings = context.getSharedPreferences(HSANDROID_PREFS_NAME, Activity.MODE_WORLD_READABLE);
//read the setting for StartAtPhoneBoot if it exists, and only load service if it's set to true
if (settings.contains("StartAtPhoneBoot")){
if (settings.getBoolean("StartAtPhoneBoot", true)){
comp = new ComponentName(context.getPackageName(), HSService.class.getName());
svc = context.startService(new Intent().setComponent(comp));
}
}
if (svc == null){
Log.e("HSServAutoStart", "Could not start HSService " + comp.toString());
}
}
}
| public void onReceive(Context context, Intent intent){
//check if the received intent is BOOT_COMPLETED
if( "android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
//get the saved settings
settings = context.getSharedPreferences(HSANDROID_PREFS_NAME, Activity.MODE_WORLD_READABLE);
//read the setting for StartAtPhoneBoot if it exists, and only load service if it's set to true
if (settings.contains("StartAtPhoneBoot")){
if (settings.getBoolean("StartAtPhoneBoot", false)){
comp = new ComponentName(context.getPackageName(), HSService.class.getName());
svc = context.startService(new Intent().setComponent(comp));
}
}
if (svc == null){
Log.e("HSServAutoStart", "Could not start HSService " + comp.toString());
}
}
}
|
diff --git a/src/main/java/com/salesforce/phoenix/pig/TypeUtil.java b/src/main/java/com/salesforce/phoenix/pig/TypeUtil.java
index 97f9e5a4..d8c42657 100644
--- a/src/main/java/com/salesforce/phoenix/pig/TypeUtil.java
+++ b/src/main/java/com/salesforce/phoenix/pig/TypeUtil.java
@@ -1,183 +1,183 @@
/*******************************************************************************
* Copyright (c) 2013, Salesforce.com, 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 Salesforce.com nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package com.salesforce.phoenix.pig;
import java.io.IOException;
import java.sql.*;
import org.apache.pig.builtin.Utf8StorageConverter;
import org.apache.pig.data.DataByteArray;
import org.apache.pig.data.DataType;
import org.joda.time.DateTime;
import com.salesforce.phoenix.schema.PDataType;
public class TypeUtil {
private static final Utf8StorageConverter utf8Converter = new Utf8StorageConverter();
/**
* This method returns the most appropriate PDataType associated with
* the incoming Pig type. Note for Pig DataType DATETIME, returns DATE as
* inferredSqlType.
*
* This is later used to make a cast to targetPhoenixType accordingly. See
* {@link #castPigTypeToPhoenix(Object, byte, PDataType)}
*
* @param obj
* @return PDataType
*/
public static PDataType getType(Object obj, byte type) {
if (obj == null) {
return null;
}
PDataType sqlType;
switch (type) {
case DataType.BYTEARRAY:
sqlType = PDataType.VARBINARY;
break;
case DataType.CHARARRAY:
sqlType = PDataType.VARCHAR;
break;
case DataType.DOUBLE:
+ sqlType = PDataType.DOUBLE;
+ break;
case DataType.FLOAT:
- //case DataType.BIGDECIMAL: not in Pig v 0.11.0
- sqlType = PDataType.DECIMAL;
+ sqlType = PDataType.FLOAT;
break;
case DataType.INTEGER:
sqlType = PDataType.INTEGER;
break;
case DataType.LONG:
- // case DataType.BIGINTEGER: not in Pig v 0.11.0
sqlType = PDataType.LONG;
break;
case DataType.BOOLEAN:
sqlType = PDataType.BOOLEAN;
break;
case DataType.DATETIME:
sqlType = PDataType.DATE;
break;
default:
throw new RuntimeException("Unknown type " + obj.getClass().getName()
+ " passed to PhoenixHBaseStorage");
}
return sqlType;
}
/**
* This method encodes a value with Phoenix data type. It begins
* with checking whether an object is BINARY and makes a call to
* {@link #castBytes(Object, PDataType)} to convery bytes to
* targetPhoenixType
*
* @param o
* @param targetPhoenixType
* @return Object
*/
public static Object castPigTypeToPhoenix(Object o, byte objectType, PDataType targetPhoenixType) {
PDataType inferredPType = getType(o, objectType);
if(inferredPType == null) {
return null;
}
if(inferredPType == PDataType.VARBINARY && targetPhoenixType != PDataType.VARBINARY) {
try {
o = castBytes(o, targetPhoenixType);
inferredPType = getType(o, DataType.findType(o));
} catch (IOException e) {
throw new RuntimeException("Error while casting bytes for object " +o);
}
}
if(inferredPType == PDataType.DATE) {
int inferredSqlType = targetPhoenixType.getSqlType();
if(inferredSqlType == Types.DATE) {
return new Date(((DateTime)o).getMillis());
}
if(inferredSqlType == Types.TIME) {
return new Time(((DateTime)o).getMillis());
}
if(inferredSqlType == Types.TIMESTAMP) {
return new Timestamp(((DateTime)o).getMillis());
}
}
if (targetPhoenixType == inferredPType || inferredPType.isCoercibleTo(targetPhoenixType)) {
return inferredPType.toObject(o, targetPhoenixType);
}
throw new RuntimeException(o.getClass().getName()
+ " cannot be coerced to "+targetPhoenixType.toString());
}
/**
* This method converts bytes to the target type required
* for Phoenix. It uses {@link Utf8StorageConverter} for
* the conversion.
*
* @param o
* @param targetPhoenixType
* @return Object
* @throws IOException
*/
public static Object castBytes(Object o, PDataType targetPhoenixType) throws IOException {
byte[] bytes = ((DataByteArray)o).get();
switch(targetPhoenixType) {
case CHAR:
case VARCHAR:
return utf8Converter.bytesToCharArray(bytes);
case UNSIGNED_INT:
case INTEGER:
return utf8Converter.bytesToInteger(bytes);
case BOOLEAN:
return utf8Converter.bytesToBoolean(bytes);
// case DECIMAL: not in Pig v 0.11.0, so using double for now
// return utf8Converter.bytesToBigDecimal(bytes);
case DECIMAL:
return utf8Converter.bytesToDouble(bytes);
case UNSIGNED_LONG:
case LONG:
return utf8Converter.bytesToLong(bytes);
case TIME:
case TIMESTAMP:
case DATE:
return utf8Converter.bytesToDateTime(bytes);
default:
return o;
}
}
}
| false | true | public static PDataType getType(Object obj, byte type) {
if (obj == null) {
return null;
}
PDataType sqlType;
switch (type) {
case DataType.BYTEARRAY:
sqlType = PDataType.VARBINARY;
break;
case DataType.CHARARRAY:
sqlType = PDataType.VARCHAR;
break;
case DataType.DOUBLE:
case DataType.FLOAT:
//case DataType.BIGDECIMAL: not in Pig v 0.11.0
sqlType = PDataType.DECIMAL;
break;
case DataType.INTEGER:
sqlType = PDataType.INTEGER;
break;
case DataType.LONG:
// case DataType.BIGINTEGER: not in Pig v 0.11.0
sqlType = PDataType.LONG;
break;
case DataType.BOOLEAN:
sqlType = PDataType.BOOLEAN;
break;
case DataType.DATETIME:
sqlType = PDataType.DATE;
break;
default:
throw new RuntimeException("Unknown type " + obj.getClass().getName()
+ " passed to PhoenixHBaseStorage");
}
return sqlType;
}
| public static PDataType getType(Object obj, byte type) {
if (obj == null) {
return null;
}
PDataType sqlType;
switch (type) {
case DataType.BYTEARRAY:
sqlType = PDataType.VARBINARY;
break;
case DataType.CHARARRAY:
sqlType = PDataType.VARCHAR;
break;
case DataType.DOUBLE:
sqlType = PDataType.DOUBLE;
break;
case DataType.FLOAT:
sqlType = PDataType.FLOAT;
break;
case DataType.INTEGER:
sqlType = PDataType.INTEGER;
break;
case DataType.LONG:
sqlType = PDataType.LONG;
break;
case DataType.BOOLEAN:
sqlType = PDataType.BOOLEAN;
break;
case DataType.DATETIME:
sqlType = PDataType.DATE;
break;
default:
throw new RuntimeException("Unknown type " + obj.getClass().getName()
+ " passed to PhoenixHBaseStorage");
}
return sqlType;
}
|
diff --git a/webapp/src/main/java/uk/ac/ebi/arrayexpress/servlets/LookupServlet.java b/webapp/src/main/java/uk/ac/ebi/arrayexpress/servlets/LookupServlet.java
index 5630ee97..8f1bf239 100644
--- a/webapp/src/main/java/uk/ac/ebi/arrayexpress/servlets/LookupServlet.java
+++ b/webapp/src/main/java/uk/ac/ebi/arrayexpress/servlets/LookupServlet.java
@@ -1,105 +1,105 @@
package uk.ac.ebi.arrayexpress.servlets;
/*
* Copyright 2009-2011 European Molecular Biology Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.ebi.arrayexpress.app.ApplicationServlet;
import uk.ac.ebi.arrayexpress.components.Autocompletion;
import uk.ac.ebi.arrayexpress.components.Experiments;
import uk.ac.ebi.arrayexpress.components.Ontologies;
import uk.ac.ebi.arrayexpress.utils.RegexHelper;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class LookupServlet extends ApplicationServlet
{
private static final long serialVersionUID = -5043275356216186598L;
private final Logger logger = LoggerFactory.getLogger(getClass());
protected boolean canAcceptRequest( HttpServletRequest request, RequestType requestType )
{
return (requestType == RequestType.GET || requestType == RequestType.POST);
}
// Respond to HTTP requests from browsers.
protected void doRequest( HttpServletRequest request, HttpServletResponse response, RequestType requestType )
throws ServletException, IOException
{
logRequest(logger, request, requestType);
- String[] requestArgs = new RegexHelper("/([^/]+)", "i")
+ String[] requestArgs = new RegexHelper("/([^/]+)$", "i")
.match(request.getRequestURL().toString());
String type = "";
String query = null != request.getParameter("q") ? request.getParameter("q") : "";
Integer limit = null != request.getParameter("limit") ? Integer.parseInt(request.getParameter("limit")) : null;
String efoId = null != request.getParameter("efoid") ? request.getParameter("efoid") : "";
// todo: remove this hack at all
efoId = efoId.replaceFirst("^http\\://wwwdev\\.ebi\\.ac\\.uk/", "http://www.ebi.ac.uk/");
if (null != requestArgs) {
if (!requestArgs[0].equals("")) {
type = requestArgs[0];
}
}
if (type.contains("json")) {
response.setContentType("application/json; charset=UTF-8");
} else {
response.setContentType("text/plain; charset=ISO-8859-1");
}
// Disable cache no matter what (or we're fucked on IE side)
response.addHeader("Pragma", "no-cache");
response.addHeader("Cache-Control", "no-cache");
response.addHeader("Cache-Control", "must-revalidate");
response.addHeader("Expires", "Fri, 16 May 2008 10:00:00 GMT"); // some date in the past
// Output goes to the response PrintWriter.
PrintWriter out = response.getWriter();
try {
Experiments experiments = (Experiments)getComponent("Experiments");
Ontologies ontologies = (Ontologies)getComponent("Ontologies");
Autocompletion autocompletion = (Autocompletion)getComponent("Autocompletion");
if (type.equals("arrays")) {
out.print(experiments.getArrays());
} else if (type.equals("species")) {
out.print(experiments.getSpecies());
} else if (type.equals("expdesign")) {
out.print(experiments.getAssaysByMolecule(query));
} else if (type.equals("exptech")) {
out.print(experiments.getAssaysByInstrument(query));
} else if (type.equals("keywords")) {
String field = (null != request.getParameter("field") ? request.getParameter("field") : "");
out.print(autocompletion.getKeywords(query, field, limit));
} else if (type.equals("efotree")) {
out.print(ontologies.getEfoChildren(efoId));
}
} catch (Exception x) {
throw new RuntimeException(x);
}
out.close();
}
}
| true | true | protected void doRequest( HttpServletRequest request, HttpServletResponse response, RequestType requestType )
throws ServletException, IOException
{
logRequest(logger, request, requestType);
String[] requestArgs = new RegexHelper("/([^/]+)", "i")
.match(request.getRequestURL().toString());
String type = "";
String query = null != request.getParameter("q") ? request.getParameter("q") : "";
Integer limit = null != request.getParameter("limit") ? Integer.parseInt(request.getParameter("limit")) : null;
String efoId = null != request.getParameter("efoid") ? request.getParameter("efoid") : "";
// todo: remove this hack at all
efoId = efoId.replaceFirst("^http\\://wwwdev\\.ebi\\.ac\\.uk/", "http://www.ebi.ac.uk/");
if (null != requestArgs) {
if (!requestArgs[0].equals("")) {
type = requestArgs[0];
}
}
if (type.contains("json")) {
response.setContentType("application/json; charset=UTF-8");
} else {
response.setContentType("text/plain; charset=ISO-8859-1");
}
// Disable cache no matter what (or we're fucked on IE side)
response.addHeader("Pragma", "no-cache");
response.addHeader("Cache-Control", "no-cache");
response.addHeader("Cache-Control", "must-revalidate");
response.addHeader("Expires", "Fri, 16 May 2008 10:00:00 GMT"); // some date in the past
// Output goes to the response PrintWriter.
PrintWriter out = response.getWriter();
try {
Experiments experiments = (Experiments)getComponent("Experiments");
Ontologies ontologies = (Ontologies)getComponent("Ontologies");
Autocompletion autocompletion = (Autocompletion)getComponent("Autocompletion");
if (type.equals("arrays")) {
out.print(experiments.getArrays());
} else if (type.equals("species")) {
out.print(experiments.getSpecies());
} else if (type.equals("expdesign")) {
out.print(experiments.getAssaysByMolecule(query));
} else if (type.equals("exptech")) {
out.print(experiments.getAssaysByInstrument(query));
} else if (type.equals("keywords")) {
String field = (null != request.getParameter("field") ? request.getParameter("field") : "");
out.print(autocompletion.getKeywords(query, field, limit));
} else if (type.equals("efotree")) {
out.print(ontologies.getEfoChildren(efoId));
}
} catch (Exception x) {
throw new RuntimeException(x);
}
out.close();
}
| protected void doRequest( HttpServletRequest request, HttpServletResponse response, RequestType requestType )
throws ServletException, IOException
{
logRequest(logger, request, requestType);
String[] requestArgs = new RegexHelper("/([^/]+)$", "i")
.match(request.getRequestURL().toString());
String type = "";
String query = null != request.getParameter("q") ? request.getParameter("q") : "";
Integer limit = null != request.getParameter("limit") ? Integer.parseInt(request.getParameter("limit")) : null;
String efoId = null != request.getParameter("efoid") ? request.getParameter("efoid") : "";
// todo: remove this hack at all
efoId = efoId.replaceFirst("^http\\://wwwdev\\.ebi\\.ac\\.uk/", "http://www.ebi.ac.uk/");
if (null != requestArgs) {
if (!requestArgs[0].equals("")) {
type = requestArgs[0];
}
}
if (type.contains("json")) {
response.setContentType("application/json; charset=UTF-8");
} else {
response.setContentType("text/plain; charset=ISO-8859-1");
}
// Disable cache no matter what (or we're fucked on IE side)
response.addHeader("Pragma", "no-cache");
response.addHeader("Cache-Control", "no-cache");
response.addHeader("Cache-Control", "must-revalidate");
response.addHeader("Expires", "Fri, 16 May 2008 10:00:00 GMT"); // some date in the past
// Output goes to the response PrintWriter.
PrintWriter out = response.getWriter();
try {
Experiments experiments = (Experiments)getComponent("Experiments");
Ontologies ontologies = (Ontologies)getComponent("Ontologies");
Autocompletion autocompletion = (Autocompletion)getComponent("Autocompletion");
if (type.equals("arrays")) {
out.print(experiments.getArrays());
} else if (type.equals("species")) {
out.print(experiments.getSpecies());
} else if (type.equals("expdesign")) {
out.print(experiments.getAssaysByMolecule(query));
} else if (type.equals("exptech")) {
out.print(experiments.getAssaysByInstrument(query));
} else if (type.equals("keywords")) {
String field = (null != request.getParameter("field") ? request.getParameter("field") : "");
out.print(autocompletion.getKeywords(query, field, limit));
} else if (type.equals("efotree")) {
out.print(ontologies.getEfoChildren(efoId));
}
} catch (Exception x) {
throw new RuntimeException(x);
}
out.close();
}
|
diff --git a/citations-tool/tool/src/java/org/sakaiproject/citation/tool/CitationHelperAction.java b/citations-tool/tool/src/java/org/sakaiproject/citation/tool/CitationHelperAction.java
index d8ad183..2c4114c 100644
--- a/citations-tool/tool/src/java/org/sakaiproject/citation/tool/CitationHelperAction.java
+++ b/citations-tool/tool/src/java/org/sakaiproject/citation/tool/CitationHelperAction.java
@@ -1,5317 +1,5319 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2006, 2007, 2008, 2009 The Sakai Foundation
*
* 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.citation.tool;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.io.input.BOMInputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.antivirus.api.VirusFoundException;
import org.sakaiproject.authz.api.SecurityAdvisor;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.cheftool.VelocityPortletPaneledAction;
import org.sakaiproject.citation.api.ActiveSearch;
import org.sakaiproject.citation.api.Citation;
import org.sakaiproject.citation.api.CitationCollection;
import org.sakaiproject.citation.api.CitationHelper;
import org.sakaiproject.citation.api.CitationIterator;
import org.sakaiproject.citation.api.CitationService;
import org.sakaiproject.citation.api.ConfigurationService;
import org.sakaiproject.citation.api.Schema;
import org.sakaiproject.citation.api.Schema.Field;
import org.sakaiproject.citation.api.SearchCategory;
import org.sakaiproject.citation.api.SearchDatabaseHierarchy;
import org.sakaiproject.citation.api.SearchManager;
import org.sakaiproject.citation.util.api.SearchCancelException;
import org.sakaiproject.citation.util.api.SearchException;
import org.sakaiproject.citation.util.api.SearchQuery;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.content.api.ContentCollection;
import org.sakaiproject.content.api.ContentEntity;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.api.ContentResourceEdit;
import org.sakaiproject.content.api.GroupAwareEntity.AccessMode;
import org.sakaiproject.content.api.ResourceToolAction;
import org.sakaiproject.content.api.ResourceToolActionPipe;
import org.sakaiproject.content.api.ResourceType;
import org.sakaiproject.entity.api.EntityManager;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.event.api.NotificationService;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdLengthException;
import org.sakaiproject.exception.IdUniquenessException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.InUseException;
import org.sakaiproject.exception.InconsistentException;
import org.sakaiproject.exception.OverQuotaException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.exception.ServerOverloadException;
import org.sakaiproject.exception.TypeException;
import org.sakaiproject.site.api.Group;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.tool.api.ToolException;
import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.tool.api.ToolSession;
import org.sakaiproject.util.FileItem;
import org.sakaiproject.util.ParameterParser;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.Validator;
import org.sakaiproject.util.api.FormattedText;
/**
*
*/
public class CitationHelperAction extends VelocityPortletPaneledAction
{
/**
* This class contains constants and utility methods to maintain state of
* the advanced search form UI and process submitted data
*
* @author gbhatnag
*/
protected static class AdvancedSearchHelper
{
/* ids for fields */
public static final String KEYWORD_ID = "keyword";
public static final String AUTHOR_ID = "author";
public static final String TITLE_ID = "title";
public static final String SUBJECT_ID = "subject";
public static final String YEAR_ID = "year";
/* keys to hold state information */
public static final String STATE_FIELD1 = CitationHelper.CITATION_PREFIX + "advField1";
public static final String STATE_FIELD2 = CitationHelper.CITATION_PREFIX + "advField2";
public static final String STATE_FIELD3 = CitationHelper.CITATION_PREFIX + "advField3";
public static final String STATE_FIELD4 = CitationHelper.CITATION_PREFIX + "advField4";
public static final String STATE_FIELD5 = CitationHelper.CITATION_PREFIX + "advField5";
public static final String STATE_CRITERIA1 = CitationHelper.CITATION_PREFIX + "advCriteria1";
public static final String STATE_CRITERIA2 = CitationHelper.CITATION_PREFIX + "advCriteria2";
public static final String STATE_CRITERIA3 = CitationHelper.CITATION_PREFIX + "advCriteria3";
public static final String STATE_CRITERIA4 = CitationHelper.CITATION_PREFIX + "advCriteria4";
public static final String STATE_CRITERIA5 = CitationHelper.CITATION_PREFIX + "advCriteria5";
/**
* Puts field selections stored in session state (using setFieldSelections())
* into the given context
*
* @param context context to put field selections into
* @param state SessionState to pull field selections from
*/
public static void putFieldSelections( Context context, SessionState state )
{
/*
context.put( "advField1", ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD1 ) );
context.put( "advField2", ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD2 ) );
context.put( "advField3", ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD3 ) );
context.put( "advField4", ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD4 ) );
context.put( "advField5", ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD5 ) );
*/
String advField1 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD1 );
String advField2 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD2 );
String advField3 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD3 );
String advField4 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD4 );
String advField5 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD5 );
if( advField1 != null && !advField1.trim().equals("") )
{
context.put( "advField1", advField1 );
}
else
{
context.put( "advField1", KEYWORD_ID );
}
if( advField2 != null && !advField2.trim().equals("") )
{
context.put( "advField2", advField2 );
}
else
{
context.put( "advField2", AUTHOR_ID );
}
if( advField3 != null && !advField3.trim().equals("") )
{
context.put( "advField3", advField3 );
}
else
{
context.put( "advField3", TITLE_ID );
}
if( advField4 != null && !advField4.trim().equals("") )
{
context.put( "advField4", advField4 );
}
else
{
context.put( "advField4", SUBJECT_ID );
}
if( advField5 != null && !advField5.trim().equals("") )
{
context.put( "advField5", advField5 );
}
else
{
context.put( "advField5", YEAR_ID );
}
}
/**
* Puts field criteria stored in session state (using setFieldCriteria())
* into the given context
*
* @param context context to put field criteria into
* @param state SessionState to pull field criteria from
*/
public static void putFieldCriteria( Context context, SessionState state )
{
context.put( "advCriteria1", ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA1 ) );
context.put( "advCriteria2", ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA2 ) );
context.put( "advCriteria3", ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA3 ) );
context.put( "advCriteria4", ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA4 ) );
context.put( "advCriteria5", ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA5 ) );
}
/**
* Sets user-selected fields in session state from request parameters
*
* @param params request parameters from doBeginSearch
* @param state SessionState to store field selections
*/
public static void setFieldSelections( ParameterParser params, SessionState state )
{
String advField1 = params.getString( "advField1" );
if( advField1 != null && !advField1.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_FIELD1, advField1 );
}
String advField2 = params.getString( "advField2" );
if( advField2 != null && !advField2.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_FIELD2, advField2 );
}
String advField3 = params.getString( "advField3" );
if( advField3 != null && !advField3.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_FIELD3, advField3 );
}
String advField4 = params.getString( "advField4" );
if( advField4 != null && !advField4.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_FIELD4, advField4 );
}
String advField5 = params.getString( "advField5" );
if( advField5 != null && !advField5.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_FIELD5, advField5 );
}
}
/**
* Sets user-entered search field criteria in session state
* from request parameters
*
* @param params request parameters from doBeginSearch
* @param state SessionState to store field criteria
*/
public static void setFieldCriteria( ParameterParser params, SessionState state )
{
String advCriteria1 = params.getString( "advCriteria1" );
if( advCriteria1 != null && !advCriteria1.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_CRITERIA1, advCriteria1 );
}
String advCriteria2 = params.getString( "advCriteria2" );
if( advCriteria2 != null && !advCriteria2.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_CRITERIA2, advCriteria2 );
}
String advCriteria3 = params.getString( "advCriteria3" );
if( advCriteria3 != null && !advCriteria3.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_CRITERIA3, advCriteria3 );
}
String advCriteria4 = params.getString( "advCriteria4" );
if( advCriteria4 != null && !advCriteria4.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_CRITERIA4, advCriteria4 );
}
String advCriteria5 = params.getString( "advCriteria5" );
if( advCriteria5 != null && !advCriteria5.trim().equals("") )
{
state.setAttribute( AdvancedSearchHelper.STATE_CRITERIA5, advCriteria5 );
}
}
public static SearchQuery getAdvancedCriteria( SessionState state )
{
String advField1 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD1 );
String advField2 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD2 );
String advField3 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD3 );
String advField4 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD4 );
String advField5 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_FIELD5 );
String advCriteria1 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA1 );
String advCriteria2 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA2 );
String advCriteria3 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA3 );
String advCriteria4 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA4 );
String advCriteria5 = ( String )state.getAttribute( AdvancedSearchHelper.STATE_CRITERIA5 );
SearchQuery searchQuery = new org.sakaiproject.citation.util.impl.SearchQuery();
/*
* put fielded, non-null criteria into the searchQuery
*/
if( advField1 != null && advCriteria1 != null )
{
if( advField1.equalsIgnoreCase( KEYWORD_ID ) )
{
searchQuery.addKeywords( advCriteria1 );
}
else if( advField1.equalsIgnoreCase( AUTHOR_ID ) )
{
searchQuery.addAuthor( advCriteria1 );
}
else if( advField1.equalsIgnoreCase( TITLE_ID ) )
{
searchQuery.addTitle( advCriteria1 );
}
else if( advField1.equalsIgnoreCase( SUBJECT_ID ) )
{
searchQuery.addSubject( advCriteria1 );
}
else if( advField1.equalsIgnoreCase( YEAR_ID ) )
{
searchQuery.addYear( advCriteria1 );
}
}
if( advField2 != null && advCriteria2 != null )
{
if( advField2.equalsIgnoreCase( KEYWORD_ID ) )
{
searchQuery.addKeywords( advCriteria2 );
}
else if( advField2.equalsIgnoreCase( AUTHOR_ID ) )
{
searchQuery.addAuthor( advCriteria2 );
}
else if( advField2.equalsIgnoreCase( TITLE_ID ) )
{
searchQuery.addTitle( advCriteria2 );
}
else if( advField2.equalsIgnoreCase( SUBJECT_ID ) )
{
searchQuery.addSubject( advCriteria2 );
}
else if( advField2.equalsIgnoreCase( YEAR_ID ) )
{
searchQuery.addYear( advCriteria2 );
}
}
if( advField3 != null && advCriteria3 != null )
{
if( advField3.equalsIgnoreCase( KEYWORD_ID ) )
{
searchQuery.addKeywords( advCriteria3 );
}
else if( advField3.equalsIgnoreCase( AUTHOR_ID ) )
{
searchQuery.addAuthor( advCriteria3 );
}
else if( advField3.equalsIgnoreCase( TITLE_ID ) )
{
searchQuery.addTitle( advCriteria3 );
}
else if( advField3.equalsIgnoreCase( SUBJECT_ID ) )
{
searchQuery.addSubject( advCriteria3 );
}
else if( advField3.equalsIgnoreCase( YEAR_ID ) )
{
searchQuery.addYear( advCriteria3 );
}
}
if( advField4 != null && advCriteria4 != null )
{
if( advField4.equalsIgnoreCase( KEYWORD_ID ) )
{
searchQuery.addKeywords( advCriteria4 );
}
else if( advField4.equalsIgnoreCase( AUTHOR_ID ) )
{
searchQuery.addAuthor( advCriteria4 );
}
else if( advField4.equalsIgnoreCase( TITLE_ID ) )
{
searchQuery.addTitle( advCriteria4 );
}
else if( advField4.equalsIgnoreCase( SUBJECT_ID ) )
{
searchQuery.addSubject( advCriteria4 );
}
else if( advField4.equalsIgnoreCase( YEAR_ID ) )
{
searchQuery.addYear( advCriteria4 );
}
}
if( advField5 != null && advCriteria5 != null )
{
if( advField5.equalsIgnoreCase( KEYWORD_ID ) )
{
searchQuery.addKeywords( advCriteria5 );
}
else if( advField5.equalsIgnoreCase( AUTHOR_ID ) )
{
searchQuery.addAuthor( advCriteria5 );
}
else if( advField5.equalsIgnoreCase( TITLE_ID ) )
{
searchQuery.addTitle( advCriteria5 );
}
else if( advField5.equalsIgnoreCase( SUBJECT_ID ) )
{
searchQuery.addSubject( advCriteria5 );
}
else if( advField5.equalsIgnoreCase( YEAR_ID ) )
{
searchQuery.addYear( advCriteria5 );
}
}
return searchQuery;
}
public static void clearAdvancedFormState( SessionState state )
{
state.removeAttribute( AdvancedSearchHelper.STATE_FIELD1 );
state.removeAttribute( AdvancedSearchHelper.STATE_FIELD2 );
state.removeAttribute( AdvancedSearchHelper.STATE_FIELD3 );
state.removeAttribute( AdvancedSearchHelper.STATE_FIELD4 );
state.removeAttribute( AdvancedSearchHelper.STATE_FIELD5 );
state.removeAttribute( AdvancedSearchHelper.STATE_CRITERIA1 );
state.removeAttribute( AdvancedSearchHelper.STATE_CRITERIA2 );
state.removeAttribute( AdvancedSearchHelper.STATE_CRITERIA3 );
state.removeAttribute( AdvancedSearchHelper.STATE_CRITERIA4 );
state.removeAttribute( AdvancedSearchHelper.STATE_CRITERIA5 );
}
}
protected final static Log logger = LogFactory.getLog(CitationHelperAction.class);
public static ResourceLoader rb = new ResourceLoader("citations");
protected CitationService citationService;
protected ConfigurationService configurationService;
protected SearchManager searchManager;
protected ContentHostingService contentService;
protected EntityManager entityManager;
protected SessionManager sessionManager;
protected static FormattedText formattedText;
protected static ToolManager toolManager;
public static final Integer DEFAULT_RESULTS_PAGE_SIZE = new Integer(10);
public static final Integer DEFAULT_LIST_PAGE_SIZE = new Integer(50);
public static Integer defaultListPageSize = DEFAULT_LIST_PAGE_SIZE;
protected static final String ELEMENT_ID_CREATE_FORM = "createForm";
protected static final String ELEMENT_ID_EDIT_FORM = "editForm";
protected static final String ELEMENT_ID_LIST_FORM = "listForm";
protected static final String ELEMENT_ID_SEARCH_FORM = "searchForm";
protected static final String ELEMENT_ID_RESULTS_FORM = "resultsForm";
protected static final String ELEMENT_ID_VIEW_FORM = "viewForm";
/**
* The calling application reflects the nature of our caller
*/
public final static String CITATIONS_HELPER_CALLER = "citations_helper_caller";
public enum Caller
{
RESOURCE_TOOL,
EDITOR_INTEGRATION;
}
/**
* Mode defines a complete set of values describing the user's navigation intentions
*/
public enum Mode
{
NEW_RESOURCE,
DATABASE,
CREATE,
EDIT,
ERROR,
ERROR_FATAL,
LIST,
REORDER,
ADD_CITATIONS,
IMPORT_CITATIONS,
MESSAGE,
SEARCH,
RESULTS,
VIEW;
}
/*
* define a set of "fake" Modes (asynchronous calls) to maintain proper
* back-button stack state
*/
protected static Set<Mode> ignoreModes = new java.util.HashSet<Mode>();
static {
ignoreModes.add( Mode.DATABASE );
ignoreModes.add( Mode.MESSAGE );
}
protected static final String PARAM_FORM_NAME = "FORM_NAME";
protected static final String STATE_RESOURCES_ADD = CitationHelper.CITATION_PREFIX + "resources_add";
protected static final String STATE_CURRENT_DATABASES = CitationHelper.CITATION_PREFIX + "current_databases";
protected static final String STATE_CANCEL_PAGE = CitationHelper.CITATION_PREFIX + "cancel_page";
protected static final String STATE_CITATION_COLLECTION_ID = CitationHelper.CITATION_PREFIX + "citation_collection_id";
protected static final String STATE_CITATION_COLLECTION = CitationHelper.CITATION_PREFIX + "citation_collection";
protected static final String STATE_CITATION_ID = CitationHelper.CITATION_PREFIX + "citation_id";
protected static final String STATE_COLLECTION_TITLE = CitationHelper.CITATION_PREFIX + "collection_name";
protected static final String STATE_CURRENT_REPOSITORY = CitationHelper.CITATION_PREFIX + "current_repository";
protected static final String STATE_CURRENT_RESULTS = CitationHelper.CITATION_PREFIX + "current_results";
protected static final String STATE_LIST_ITERATOR = CitationHelper.CITATION_PREFIX + "list_iterator";
protected static final String STATE_LIST_PAGE = CitationHelper.CITATION_PREFIX + "list_page";
protected static final String STATE_LIST_PAGE_SIZE = CitationHelper.CITATION_PREFIX + "list_page_size";
protected static final String STATE_LIST_NO_SCROLL = CitationHelper.CITATION_PREFIX + "list_no_scroll";
protected static final String STATE_NO_KEYWORDS = CitationHelper.CITATION_PREFIX + "no_search_criteria";
protected static final String STATE_NO_DATABASES = CitationHelper.CITATION_PREFIX + "no_databases";
protected static final String STATE_NO_RESULTS = CitationHelper.CITATION_PREFIX + "no_results";
protected static final String STATE_SEARCH_HIERARCHY = CitationHelper.CITATION_PREFIX + "search_hierarchy";
protected static final String STATE_SELECTED_CATEGORY = CitationHelper.CITATION_PREFIX + "selected_category";
protected static final String STATE_DEFAULT_CATEGORY = CitationHelper.CITATION_PREFIX + "default_category";
protected static final String STATE_UNAUTHORIZED_DB = CitationHelper.CITATION_PREFIX + "unauthorized_database";
protected static final String STATE_REPOSITORY_MAP = CitationHelper.CITATION_PREFIX + "repository_map";
protected static final String STATE_RESULTS_PAGE_SIZE = CitationHelper.CITATION_PREFIX + "results_page_size";
protected static final String STATE_KEYWORDS = CitationHelper.CITATION_PREFIX + "search_criteria";
protected static final String STATE_SEARCH_INFO = CitationHelper.CITATION_PREFIX + "search_info";
protected static final String STATE_BASIC_SEARCH = CitationHelper.CITATION_PREFIX + "basic_search";
protected static final String STATE_SEARCH_RESULTS = CitationHelper.CITATION_PREFIX + "search_results";
protected static final String STATE_RESOURCE_ENTITY_PROPERTIES = CitationHelper.CITATION_PREFIX + "citationList_properties";
protected static final String STATE_SORT = CitationHelper.CITATION_PREFIX + "sort";
protected static final String TEMPLATE_NEW_RESOURCE = "citation/new_resource";
protected static final String TEMPLATE_CREATE = "citation/create";
protected static final String TEMPLATE_EDIT = "citation/edit";
protected static final String TEMPLATE_ERROR = "citation/error";
protected static final String TEMPLATE_ERROR_FATAL = "citation/error_fatal";
protected static final String TEMPLATE_LIST = "citation/list";
protected static final String TEMPLATE_REORDER = "citation/reorder";
protected static final String TEMPLATE_ADD_CITATIONS = "citation/add_citations";
protected static final String TEMPLATE_IMPORT_CITATIONS = "citation/import_citations";
protected static final String TEMPLATE_MESSAGE = "citation/_message";
protected static final String TEMPLATE_SEARCH = "citation/search";
protected static final String TEMPLATE_RESULTS = "citation/results";
protected static final String TEMPLATE_VIEW = "citation/view";
protected static final String TEMPLATE_DATABASE = "citation/_databases";
protected static final String PROP_ACCESS_MODE = "accessMode";
protected static final String PROP_IS_COLLECTION = "isCollection";
protected static final String PROP_IS_DROPBOX = "isDropbox";
protected static final String PROP_IS_GROUP_INHERITED = "isGroupInherited";
protected static final String PROP_IS_GROUP_POSSIBLE = "isGroupPossible";
protected static final String PROP_IS_HIDDEN = "isHidden";
protected static final String PROP_IS_PUBVIEW = "isPubview";
protected static final String PROP_IS_PUBVIEW_INHERITED = "isPubviewInherited";
protected static final String PROP_IS_PUBVIEW_POSSIBLE = "isPubviewPossible";
protected static final String PROP_IS_SINGLE_GROUP_INHERITED = "isSingleGroupInherited";
protected static final String PROP_IS_SITE_COLLECTION = "isSiteCollection";
protected static final String PROP_IS_SITE_ONLY = "isSiteOnly";
protected static final String PROP_IS_USER_SITE = "isUserSite";
protected static final String PROP_POSSIBLE_GROUPS = "possibleGroups";
protected static final String PROP_RELEASE_DATE = "releaseDate";
protected static final String PROP_RELEASE_DATE_STR = "releaseDateStr";
protected static final String PROP_RETRACT_DATE = "retractDate";
protected static final String PROP_RETRACT_DATE_STR = "retractDateStr";
protected static final String PROP_USE_RELEASE_DATE = "useReleaseDate";
protected static final String PROP_USE_RETRACT_DATE = "useRetractDate";
public static final String CITATION_ACTION = "citation_action";
public static final String UPDATE_RESOURCE = "update_resource";
public static final String CREATE_RESOURCE = "create_resource";
public static final String IMPORT_CITATIONS = "import_citations";
public static final String UPDATE_SAVED_SORT = "update_saved_sort";
public static final String CHECK_FOR_UPDATES = "check_for_updates";
public static final String MIMETYPE_JSON = "application/json";
public static final String MIMETYPE_HTML = "text/html";
public static final String REQUESTED_MIMETYPE = "requested_mimetype";
public static final String CHARSET_UTF8 = "UTF-8";
/** A long representing the number of milliseconds in one week. Used for date calculations */
public static final long ONE_DAY = 24L * 60L * 60L * 1000L;
/** A long representing the number of milliseconds in one week. Used for date calculations */
public static final long ONE_WEEK = 7L * ONE_DAY;
public void init() throws ServletException {
ServerConfigurationService scs
= (ServerConfigurationService) ComponentManager.get(ServerConfigurationService.class);
if(scs != null) {
defaultListPageSize = scs.getInt("citations.default.list.page.size", DEFAULT_LIST_PAGE_SIZE);
} else {
logger.warn("Failed to get default list page size as ServerConfigurationService is null. Defaulting to " + DEFAULT_LIST_PAGE_SIZE);
defaultListPageSize = DEFAULT_LIST_PAGE_SIZE;
}
}
/**
* Check for the helper-done case locally and handle it before letting the VPPA.toolModeDispatch() handle the actual dispatch.
* @see org.sakaiproject.cheftool.VelocityPortletPaneledAction#toolModeDispatch(java.lang.String, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
protected void toolModeDispatch(String methodBase, String methodExt, HttpServletRequest req, HttpServletResponse res)
throws ToolException
{
logger.debug("toolModeDispatch()");
//SessionState sstate = getState(req);
ToolSession toolSession = getSessionManager().getCurrentToolSession();
//String mode = (String) sstate.getAttribute(ResourceToolAction.STATE_MODE);
//Object started = toolSession.getAttribute(ResourceToolAction.STARTED);
Object done = toolSession.getAttribute(ResourceToolAction.DONE);
// if we're done or not properly initialized, redirect to Resources
if ( done != null || !initHelper( getState(req) ) )
{
toolSession.removeAttribute(ResourceToolAction.STARTED);
Tool tool = getToolManager().getCurrentTool();
String url = (String) toolSession.getAttribute(tool.getId() + Tool.HELPER_DONE_URL);
toolSession.removeAttribute(tool.getId() + Tool.HELPER_DONE_URL);
try
{
res.sendRedirect(url); // TODO
}
catch (IOException e)
{
logger.warn("IOException", e);
// Log.warn("chef", this + " : ", e);
}
return;
}
super.toolModeDispatch(methodBase, methodExt, req, res);
}
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException {
logger.info("doGet()");
String isAjaxRequest = req.getParameter("ajaxRequest");
if(isAjaxRequest != null && isAjaxRequest.trim().equalsIgnoreCase(Boolean.toString(true))) {
ParameterParser params = (ParameterParser) req.getAttribute(ATTR_PARAMS);
if(params == null) {
params = new ParameterParser(req);
}
SessionState state = getState(req);
// Check whether this is an AJAX request expecting a JSON response and if it is
// dispatch the request to the buildJsonResponse() method, avoiding VPPA's
// html rendering. Other options might be HTML-fragment, XML, etc.
//String requestedMimetype = (String) toolSession.getAttribute(REQUESTED_MIMETYPE);
String requestedMimetype = params.getString(REQUESTED_MIMETYPE);
logger.info("doGet() requestedMimetype == " + requestedMimetype);
if(requestedMimetype != null && requestedMimetype.equals(MIMETYPE_JSON)) {
doGetJsonResponse(params, state, req, res);
} else if(requestedMimetype != null && requestedMimetype.equals(MIMETYPE_HTML)) {
doGetHtmlFragmentResponse(params, state, req, res);
} else {
// throw something
}
return;
}
super.doGet(req, res);
}
protected void doGetHtmlFragmentResponse(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
}
protected void doGetJsonResponse(ParameterParser params, SessionState state,
HttpServletRequest req, HttpServletResponse res) {
res.setCharacterEncoding(CHARSET_UTF8);
res.setContentType(MIMETYPE_JSON);
Map<String,Object> jsonMap = new HashMap<String,Object>();
String sakai_csrf_token = params.getString("sakai_csrf_token");
if(sakai_csrf_token != null && ! sakai_csrf_token.trim().equals("")) {
jsonMap.put("sakai_csrf_token", sakai_csrf_token);
}
jsonMap.put("timestamp", Long.toString(System.currentTimeMillis()));
String citation_action = params.getString("citation_action");
if(citation_action != null && citation_action.trim().equals(CHECK_FOR_UPDATES)) {
Map<String,Object> result = this.checkForUpdates(params, state, req, res);
jsonMap.putAll(result);
}
// convert to json string
String jsonString = JSONObject.fromObject(jsonMap).toString();
try {
PrintWriter writer = res.getWriter();
writer.print(jsonString);
writer.flush();
} catch (IOException e) {
logger.warn("IOException in doGetJsonResponse() " + e);
}
}
protected Map<String, Object> checkForUpdates(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
Map<String, Object> result = new HashMap<String, Object>();
boolean changed = false;
long lastcheckLong = 0L;
String lastcheck = params.getString("lastcheck");
if(lastcheck == null || lastcheck.trim().equals("")) {
// do nothing
} else {
try {
lastcheckLong = Long.parseLong(lastcheck);
} catch(Exception e) {
logger.warn("Error parsing long from string: " + lastcheck, e);
}
}
if(lastcheckLong > 0L) {
String citationCollectionId = params.getString("citationCollectionId");
if(citationCollectionId != null && !citationCollectionId.trim().equals("")) {
try {
CitationCollection citationCollection = this.citationService.getCollection(citationCollectionId);
if(citationCollection.getLastModifiedDate().getTime() > lastcheckLong) {
changed = true;
result.put("html", "<div>something goes here</div>");
}
} catch (IdUnusedException e) {
logger.warn("IdUnusedException in checkForUpdates() " + e);
}
}
}
result.put("changed", Boolean.toString(changed));
return result;
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException {
logger.info("doPost()");
// Enumeration<String> names = req.getHeaderNames();
// while(names.hasMoreElements()) {
// String name = names.nextElement();
// String value = req.getHeader(name);
// logger.info("doPost() header " + name + " == " + value);
// }
//
// Cookie[] cookies = req.getCookies();
// for(Cookie cookie : cookies) {
// logger.info("doPost() ==cookie== " + cookie.getName() + " == " + cookie.getValue());
// }
// handle AJAX requests here and send other requests on to the VPPA dispatcher
String isAjaxRequest = req.getParameter("ajaxRequest");
if(isAjaxRequest != null && isAjaxRequest.trim().equalsIgnoreCase(Boolean.toString(true))) {
ParameterParser params = (ParameterParser) req.getAttribute(ATTR_PARAMS);
if(params == null) {
params = new ParameterParser(req);
}
SessionState state = getState(req);
// Check whether this is an AJAX request expecting a JSON response and if it is
// dispatch the request to the buildJsonResponse() method, avoiding VPPA's
// html rendering. Other options might be HTML-fragment, XML, etc.
//String requestedMimetype = (String) toolSession.getAttribute(REQUESTED_MIMETYPE);
String requestedMimetype = params.getString(REQUESTED_MIMETYPE);
logger.info("doPost() requestedMimetype == " + requestedMimetype);
if(requestedMimetype != null && requestedMimetype.equals(MIMETYPE_JSON)) {
doPostJsonResponse(params, state, req, res);
} else if(requestedMimetype != null && requestedMimetype.equals(MIMETYPE_HTML)) {
doPostHtmlFragmentResponse(params, state, req, res);
}
return;
}
super.doPost(req, res);
}
protected void doPostHtmlFragmentResponse(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
Map<String, Object> result = this.ensureCitationListExists(params, state, req, res);
res.setCharacterEncoding(CHARSET_UTF8);
res.setContentType(MIMETYPE_HTML);
String sakai_csrf_token = params.getString("sakai_csrf_token");
if(sakai_csrf_token != null && ! sakai_csrf_token.trim().equals("")) {
setVmReference("sakai_csrf_token", sakai_csrf_token, req);
}
for(Map.Entry<String,Object> entry : result.entrySet()) {
setVmReference(entry.getKey(), entry.getValue(), req);
}
}
protected void doPostJsonResponse(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
res.setCharacterEncoding(CHARSET_UTF8);
res.setContentType(MIMETYPE_JSON);
Map<String,Object> jsonMap = new HashMap<String,Object>();
String sakai_csrf_token = params.getString("sakai_csrf_token");
if(sakai_csrf_token != null && ! sakai_csrf_token.trim().equals("")) {
jsonMap.put("sakai_csrf_token", sakai_csrf_token);
}
jsonMap.put("timestamp", Long.toString(System.currentTimeMillis()));
String citation_action = params.getString("citation_action");
if(citation_action != null && citation_action.trim().equals(UPDATE_RESOURCE)) {
Map<String,Object> result = this.updateCitationList(params, state, req, res);
jsonMap.putAll(result);
} else if(citation_action != null && citation_action.trim().equals(UPDATE_SAVED_SORT)) {
Map<String,Object> result = this.updateSavedSort(params, state, req, res);
jsonMap.putAll(result);
} else {
Map<String,Object> result = this.createCitationList(params, state, req, res);
jsonMap.putAll(result);
}
// convert to json string
String jsonString = JSONObject.fromObject(jsonMap).toString();
try {
PrintWriter writer = res.getWriter();
writer.print(jsonString);
writer.flush();
} catch (IOException e) {
logger.warn("IOException in doPostJsonResponse() ", e);
// what goes back?
}
}
protected Map<String, Object> updateSavedSort(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
Map<String, Object> results = new HashMap<String, Object>();
String message = null;
String citationCollectionId = params.getString("citationCollectionId");
String new_sort = params.getString("new_sort");
if(citationCollectionId == null || citationCollectionId.trim().equals("")) {
// need to report error
results.put("message", rb.getString("sort.save.error"));
} else {
if(new_sort == null || new_sort.trim().equals("")) {
new_sort = "default";
}
try {
CitationCollection citationCollection = this.citationService.getCollection(citationCollectionId);
citationCollection.setSort(new_sort, true);
this.citationService.save(citationCollection);
results.put("message", rb.getString("sort.save.success"));
} catch (IdUnusedException e) {
// need to report error
results.put("message", rb.getString("sort.save.error"));
}
}
return results;
}
protected Map<String, Object> createCitationList(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
Map<String, Object> results = new HashMap<String, Object>();
results.putAll(this.ensureCitationListExists(params, state, req, res));
return results;
}
protected Map<String, Object> updateCitationList(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
Map<String, Object> results = new HashMap<String, Object>();
String resourceUuid = params.getString("resourceUuid");
String message = null;
if(resourceUuid == null) {
results.putAll(this.ensureCitationListExists(params, state, req, res));
} else {
try {
String resourceId = this.getContentService().resolveUuid(resourceUuid);
ContentResourceEdit edit = getContentService().editResource(resourceId);
this.captureDisplayName(params, state, edit, results);
this.captureDescription(params, state, edit, results);
this.captureAccess(params, state, edit, results);
this.captureAvailability(params, edit, results);
getContentService().commitResource(edit);
message = "Resource updated";
} catch (IdUnusedException e) {
message = e.getMessage();
logger.warn("IdUnusedException in updateCitationList() " + e);
} catch (TypeException e) {
message = e.getMessage();
logger.warn("TypeException in updateCitationList() " + e);
} catch (InUseException e) {
message = e.getMessage();
logger.warn("InUseException in updateCitationList() " + e);
} catch (PermissionException e) {
message = e.getMessage();
logger.warn("PermissionException in updateCitationList() " + e);
} catch (OverQuotaException e) {
message = e.getMessage();
logger.warn("OverQuotaException in updateCitationList() " + e);
} catch (ServerOverloadException e) {
message = e.getMessage();
logger.warn("ServerOverloadException in updateCitationList() " + e);
} catch (VirusFoundException e) {
message = e.getMessage();
logger.warn("VirusFoundException in updateCitationList() " + e);
}
if(message != null && ! message.trim().equals("")) {
results.put("message", message);
}
}
return results;
}
/**
* Check whether we are editing an existing resource or working on a new citation list.
* If it exists, we'll update any attributes that have changed. If it's new, we will
* create it and return the resourceUuid, along with other attributes, in a map.
* @param params
* @param state
* @param req
* @param res
* @return
*/
protected Map<String,Object> ensureCitationListExists(ParameterParser params,
SessionState state, HttpServletRequest req, HttpServletResponse res) {
Map<String, Object> results = new HashMap<String,Object>();
String message = null;
String displayName = params.getString("displayName");
if(displayName == null) {
// error ??
}
CitationCollection cCollection = this.getCitationCollection(state, true);
if(cCollection == null) {
// error
} else {
String citationCollectionId = cCollection.getId();
String collectionId = params.getString("collectionId");
if(collectionId == null || collectionId.trim().equals("")) {
ToolSession toolSession = getSessionManager().getCurrentToolSession();
ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE);
collectionId = pipe.getContentEntity().getId();
}
ContentResource resource = null;
String resourceUuid = params.getString("resourceUuid");
String resourceId = null;
if(resourceUuid == null || resourceUuid.trim().equals("")) {
// create resource
if(collectionId == null) {
// error?
message = rb.getString("resource.null_collectionId.error");
} else {
int priority = 0;
// create resource
try {
ContentResourceEdit edit = getContentService().addResource(collectionId, displayName, null, ContentHostingService.MAXIMUM_ATTEMPTS_FOR_UNIQUENESS);
edit.setResourceType(CitationService.CITATION_LIST_ID);
byte[] bytes = citationCollectionId.getBytes();
edit.setContent(bytes );
captureDescription(params, state, edit, results);
captureAccess(params, state, edit, results);
captureAvailability(params, edit, results);
ResourceProperties properties = edit.getPropertiesEdit();
properties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, displayName);
properties.addProperty(ContentHostingService.PROP_ALTERNATE_REFERENCE, CitationService.REFERENCE_ROOT);
properties.addProperty(ResourceProperties.PROP_CONTENT_TYPE, ResourceType.MIME_TYPE_HTML);
getContentService().commitResource(edit, priority);
resourceId = edit.getId();
message = rb.getFormattedMessage("resource.new.success", new String[]{ displayName });
} catch (IdUniquenessException e) {
message = e.getMessage();
logger.warn("IdUniquenessException in ensureCitationListExists() " + e);
} catch (IdLengthException e) {
message = e.getMessage();
logger.warn("IdLengthException in ensureCitationListExists() " + e);
} catch (IdInvalidException e) {
message = e.getMessage();
logger.warn("IdInvalidException in ensureCitationListExists() " + e);
} catch (OverQuotaException e) {
message = e.getMessage();
logger.warn("OverQuotaException in ensureCitationListExists() " + e);
} catch (ServerOverloadException e) {
message = e.getMessage();
logger.warn("ServerOverloadException in ensureCitationListExists() " + e);
} catch (PermissionException e) {
message = e.getMessage();
logger.warn("PermissionException in ensureCitationListExists() " + e);
} catch (IdUnusedException e) {
message = e.getMessage();
logger.warn("IdUnusedException in ensureCitationListExists() " + e);
}
}
} else {
// get resource
resourceId = this.getContentService().resolveUuid(resourceUuid);
if(citationCollectionId == null) {
try {
resource = this.contentService.getResource(resourceId);
citationCollectionId = new String(resource.getContent());
} catch (IdUnusedException e) {
message = e.getMessage();
logger.warn("IdUnusedException in getting resource in ensureCitationListExists() " + e);
} catch (TypeException e) {
message = e.getMessage();
logger.warn("TypeException in getting resource in ensureCitationListExists() " + e);
} catch (PermissionException e) {
message = e.getMessage();
logger.warn("PermissionException in getting resource in ensureCitationListExists() " + e);
} catch (ServerOverloadException e) {
message = e.getMessage();
logger.warn("ServerOverloadException in getting citationCollectionId in ensureCitationListExists() " + e);
}
}
// possibly revise displayName, other properties
// commit changes
// report success/failure
}
results.put("citationCollectionId", citationCollectionId);
//results.put("resourceId", resourceId);
resourceUuid = this.getContentService().getUuid(resourceId);
logger.info("ensureCitationListExists() created new resource with resourceUuid == " + resourceUuid + " and resourceId == " + resourceId);
results.put("resourceUuid", resourceUuid );
String clientId = params.getString("saveciteClientId");
if(clientId != null && ! clientId.trim().equals("")) {
Locale locale = rb.getLocale();
List<Map<String,String>> saveciteClients = getConfigurationService().getSaveciteClientsForLocale(locale);
if(saveciteClients != null) {
for(Map<String,String> client : saveciteClients) {
if(client != null && client.get("id") != null && client.get("id").equalsIgnoreCase(clientId)) {
String saveciteUrl = getSearchManager().getSaveciteUrl(resourceUuid,clientId);
try {
saveciteUrl = java.net.URLEncoder.encode(saveciteUrl,"UTF-8");
} catch (UnsupportedEncodingException e) {
logger.warn("Error encoding savecite URL",e);
}
// ${client.searchurl_base}?linkurl_base=${client.saveciteUrl}#if(${client.linkurl_id})&linkurl_id=${client.linkurl_id}
StringBuilder buf = new StringBuilder();
buf.append(client.get("searchurl_base"));
buf.append("?linkurl_base=");
buf.append(saveciteUrl);
if(client.get("linkurl_id") != null && ! client.get("linkurl_id").trim().equals("")) {
buf.append("&linkurl_id=");
buf.append(client.get("linkurl_id"));
}
buf.append('&');
results.put("saveciteUrl", buf.toString());
break;
}
}
}
}
results.put("collectionId", collectionId);
}
results.put("message", message);
return results;
}
private void captureDescription(ParameterParser params, SessionState state,
ContentResourceEdit edit, Map<String, Object> results) {
String description = params.get("description");
String oldDescription = edit.getProperties().getProperty(ResourceProperties.PROP_DESCRIPTION);
if(description == null || description.trim().equals("")) {
if(oldDescription != null) {
edit.getPropertiesEdit().removeProperty(ResourceProperties.PROP_DESCRIPTION);
results.put("description", "");
}
} else {
if(oldDescription == null || ! oldDescription.equals(description)) {
edit.getPropertiesEdit().removeProperty(ResourceProperties.PROP_DESCRIPTION);
edit.getPropertiesEdit().addProperty(ResourceProperties.PROP_DESCRIPTION, description);
results.put("description", description);
}
}
}
protected void captureDisplayName(ParameterParser params, SessionState state,
ContentResourceEdit edit, Map<String, Object> results) {
String displayName = params.getString("displayName");
if(displayName == null || displayName.trim().equals("")) {
throw new RuntimeException("invalid name for resource: " + displayName);
}
String oldDisplayName = edit.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
if(oldDisplayName == null || ! oldDisplayName.equals(displayName)) {
ResourcePropertiesEdit props = edit.getPropertiesEdit();
props.removeProperty(ResourceProperties.PROP_DISPLAY_NAME);
props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, displayName);
results.put("displayName", displayName);
}
}
/**
* @param params
* @param edit
* @param results TODO
*/
protected void captureAvailability(ParameterParser params,
ContentResourceEdit edit, Map<String, Object> results) {
boolean hidden = params.getBoolean("hidden");
boolean useReleaseDate = params.getBoolean("use_start_date");
DateFormat df = DateFormat.getDateTimeInstance();
Time releaseDate = null;
if(useReleaseDate) {
String releaseDateStr = params.getString(PROP_RELEASE_DATE);
if(releaseDateStr != null) {
try {
releaseDate = TimeService.newTime(df.parse(releaseDateStr).getTime());
} catch (ParseException e) {
logger.warn("ParseException in captureAvailability() " + e);
}
}
}
Time retractDate = null;
boolean useRetractDate = params.getBoolean("use_end_date");
if(useRetractDate) {
String retractDateStr = params.getString(PROP_RETRACT_DATE);
if(retractDateStr != null) {
try {
retractDate = TimeService.newTime(df.parse(retractDateStr).getTime());
} catch (ParseException e) {
logger.warn("ParseException in captureAvailability() " + e);
}
}
}
boolean oldHidden = edit.isHidden();
Time oldReleaseDate = edit.getReleaseDate();
Time oldRetractDate = edit.getRetractDate();
boolean changesFound = false;
if(oldHidden != hidden) {
results.put(PROP_IS_HIDDEN, Boolean.toString(hidden));
changesFound = true;
}
if(oldReleaseDate == null && releaseDate == null) {
// no change here
} else if((oldReleaseDate == null) || ! oldReleaseDate.equals(releaseDate)) {
if(releaseDate == null) {
results.put(PROP_RELEASE_DATE_STR, df.format(new Date()));
} else {
results.put(PROP_RELEASE_DATE_STR, df.format(new Date(releaseDate.getTime())));
}
results.put(PROP_RELEASE_DATE, releaseDate);
results.put(PROP_USE_RELEASE_DATE, useReleaseDate);
changesFound = true;
}
if(oldRetractDate == null && retractDate == null) {
// no change here
} else if (oldRetractDate == null || ! oldRetractDate.equals(retractDate)) {
if(retractDate == null) {
results.put(PROP_RETRACT_DATE_STR, df.format(new Date(System.currentTimeMillis() + ONE_WEEK)));
} else {
results.put(PROP_RETRACT_DATE_STR, df.format(new Date(retractDate.getTime() )));
}
results.put(PROP_RETRACT_DATE, retractDate);
changesFound = true;
}
if(changesFound) {
edit.setAvailability(hidden, releaseDate, retractDate);
}
}
protected void captureAccess(ParameterParser params, SessionState state,
ContentResourceEdit edit, Map<String, Object> results) {
Map<String,Object> entityProperties = (Map<String, Object>) state.getAttribute(STATE_RESOURCE_ENTITY_PROPERTIES);
boolean changesFound = false;
String access_mode = params.getString("access_mode");
if(access_mode == null) {
access_mode = AccessMode.INHERITED.toString();
}
String oldAccessMode = entityProperties.get(PROP_ACCESS_MODE).toString();
if(oldAccessMode == null) {
oldAccessMode = AccessMode.INHERITED.toString();
}
if(! access_mode.equals(oldAccessMode)) {
results.put(PROP_ACCESS_MODE, AccessMode.fromString(access_mode));
changesFound = true;
}
if(AccessMode.GROUPED.toString().equals(access_mode)) {
// we inherit more than one group and must check whether group access changes at this item
String[] access_groups = params.getStrings("access_groups");
SortedSet<String> new_groups = new TreeSet<String>();
if(access_groups != null) {
new_groups.addAll(Arrays.asList(access_groups));
}
List<Map<String,String>> possibleGroups = (List<Map<String, String>>) entityProperties.get(PROP_POSSIBLE_GROUPS);
if(possibleGroups == null) {
possibleGroups = new ArrayList<Map<String,String>>();
}
Map<String, String> possibleGroupMap = mapGroupRefs(possibleGroups);
SortedSet<String> new_group_refs = convertToRefs(new_groups, possibleGroupMap );
boolean groups_are_inherited = (new_groups.size() == possibleGroupMap.size()) && possibleGroupMap.keySet().containsAll(new_groups);
try {
if(groups_are_inherited) {
edit.clearGroupAccess();
edit.setGroupAccess(new_group_refs);
} else {
edit.setGroupAccess(new_group_refs);
}
edit.clearPublicAccess();
} catch (InconsistentException e) {
logger.warn("InconsistentException in captureAccess() " + e);
} catch (PermissionException e) {
logger.warn("PermissionException in captureAccess() " + e);
}
} else if("public".equals(access_mode)) {
Boolean isPubviewInherited = (Boolean) entityProperties.get(PROP_IS_PUBVIEW_INHERITED);
if(isPubviewInherited == null || ! isPubviewInherited) {
try {
edit.setPublicAccess();
} catch (InconsistentException e) {
logger.warn("InconsistentException in captureAccess() " + e);
} catch (PermissionException e) {
logger.warn("PermissionException in captureAccess() " + e);
}
}
} else if(AccessMode.INHERITED.toString().equals(access_mode)) {
try {
if(edit.getAccess() == AccessMode.GROUPED) {
edit.clearGroupAccess();
}
edit.clearPublicAccess();
} catch (InconsistentException e) {
logger.warn("InconsistentException in captureAccess() " + e);
} catch (PermissionException e) {
logger.warn("PermissionException in captureAccess() " + e);
}
}
// isPubview
results.put(PROP_IS_PUBVIEW, getContentService().isPubView(edit.getId()));
// isPubviewInherited
results.put(PROP_IS_PUBVIEW_INHERITED, new Boolean(getContentService().isInheritingPubView(edit.getId())));
// isPubviewPossible
Boolean preventPublicDisplay = (Boolean) state.getAttribute("resources.request.prevent_public_display");
if(preventPublicDisplay == null) {
preventPublicDisplay = Boolean.FALSE;
}
results.put(PROP_IS_PUBVIEW_POSSIBLE, new Boolean(! preventPublicDisplay.booleanValue()));
// accessMode
results.put(PROP_ACCESS_MODE, edit.getAccess());
// isGroupInherited
results.put(PROP_IS_GROUP_INHERITED, AccessMode.GROUPED == edit.getInheritedAccess());
// possibleGroups
Collection<Group> inheritedGroupObjs = edit.getInheritedGroupObjects();
Map<String,Map<String,String>> groups = new HashMap<String,Map<String,String>>();
if(inheritedGroupObjs != null) {
for(Group group : inheritedGroupObjs) {
Map<String, String> grp = new HashMap<String, String>();
grp.put("groupId", group.getId());
grp.put("title", group.getTitle());
grp.put("description", group.getDescription());
grp.put("entityRef", group.getReference());
groups.put(grp.get("groupId"), grp);
}
}
results.put(PROP_POSSIBLE_GROUPS, groups);
// isGroupPossible
results.put(PROP_IS_GROUP_POSSIBLE, new Boolean(groups != null && groups.size() > 0));
// isSingleGroupInherited
results.put(PROP_IS_SINGLE_GROUP_INHERITED, new Boolean(groups != null && groups.size() == 1));
// isSiteOnly = ! isPubviewPossible && ! isGroupPossible
results.put(PROP_IS_SITE_ONLY, new Boolean(preventPublicDisplay.booleanValue() && (groups == null || groups.size() < 1)));
// isUserSite
SiteService siteService = (SiteService) ComponentManager.get(SiteService.class);
Reference ref = getEntityManager().newReference(edit.getReference());
results.put(PROP_IS_USER_SITE, siteService.isUserSite(ref.getContext()));
}
private Map<String, String> mapGroupRefs(
List<Map<String, String>> possibleGroups) {
Map<String, String> groupRefMap = new HashMap<String, String>();
for(Map<String, String> groupInfo : possibleGroups) {
if(groupInfo.get("groupId") != null && groupInfo.get("entityRef") != null) {
groupRefMap.put(groupInfo.get("groupId"), groupInfo.get("entityRef"));
}
}
return groupRefMap ;
}
public SortedSet<String> convertToRefs(Collection<String> groupIds, Map<String, String> possibleGroupMap)
{
SortedSet<String> groupRefs = new TreeSet<String>();
for(String groupId : groupIds)
{
String groupRef = possibleGroupMap.get(groupId);
if(groupRef != null)
{
groupRefs.add(groupRef);
}
}
return groupRefs;
}
protected void preserveEntityIds(ParameterParser params, SessionState state) {
String resourceId = params.getString("resourceId");
String resourceUuid = params.getString("resourceUuid");
String citationCollectionId = params.getString("citationCollectionId");
if(resourceId == null || resourceId.trim().equals("")) {
// do nothing
} else {
state.setAttribute(CitationHelper.RESOURCE_ID, resourceId);
}
if(resourceUuid == null || resourceUuid.trim().equals("")) {
// do nothing
} else {
state.setAttribute(CitationHelper.RESOURCE_UUID, resourceUuid);
}
if(citationCollectionId == null || citationCollectionId.trim().equals("")) {
// do nothing
} else {
state.setAttribute(CitationHelper.CITATION_COLLECTION_ID, citationCollectionId);
}
}
protected void putCitationCollectionDetails( Context context, SessionState state )
{
// get the citation list title
String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
String refStr = getContentService().getReference(resourceId);
Reference ref = getEntityManager().newReference(refStr);
String collectionTitle = null;
if( ref != null )
{
collectionTitle = ref.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
if(collectionTitle == null) {
collectionTitle = (String)state.getAttribute( STATE_COLLECTION_TITLE );
}
if( collectionTitle != null && !collectionTitle.trim().equals("") )
{
context.put( "collectionTitle", getFormattedText().escapeHtml(collectionTitle));
}
// get the collection we're now working on
String collectionId = (String)state.getAttribute(STATE_CITATION_COLLECTION_ID);
context.put( "collectionId", collectionId );
CitationCollection collection = getCitationCollection(state, false);
int collectionSize = 0;
if (collection == null)
{
logger.warn( "buildAddCitationsPanelContext unable to access citationCollection " + collectionId );
return;
}
else
{
// get the size of the list
collectionSize = collection.size();
}
context.put( "collectionSize", new Integer( collectionSize ) );
}
public String buildImportCitationsPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
context.put("state", state);
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validator
context.put("xilator", new Validator());
context.put("FORM_NAME", "importForm");
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_IMPORT_CITATIONS;
} // buildImportPanelContext
/**
*
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
public String buildAddCitationsPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
context.put("state", state);
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// body onload handler
context.put("sakai_onload", "setMainFrameHeight( window.name )");
// get the citation list title
String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
String refStr = getContentService().getReference(resourceId);
Reference ref = getEntityManager().newReference(refStr);
String collectionTitle = null;
if( ref != null )
{
collectionTitle = ref.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
if(collectionTitle == null) {
collectionTitle = (String)state.getAttribute( STATE_COLLECTION_TITLE );
}
if( collectionTitle != null && !collectionTitle.trim().equals("") )
{
context.put( "collectionTitle", getFormattedText().escapeHtml(collectionTitle));
}
// get the collection we're now working on
String collectionId = (String)state.getAttribute(STATE_CITATION_COLLECTION_ID);
context.put( "collectionId", collectionId );
CitationCollection citationCollection = getCitationCollection(state, false);
int collectionSize = 0;
if(citationCollection == null)
{
logger.warn( "buildAddCitationsPanelContext unable to access citationCollection " + collectionId );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_ERROR;
}
else
{
// get the size of the list
collectionSize = citationCollection.size();
}
context.put( "collectionSize", new Integer( collectionSize ) );
Locale locale = rb.getLocale();
List<Map<String,String>> saveciteClients = getConfigurationService().getSaveciteClientsForLocale(locale);
if(saveciteClients != null) {
for(Map<String,String> client : saveciteClients) {
String saveciteUrl = getSearchManager().getSaveciteUrl(getContentService().getUuid(resourceId),client.get("id"));
try {
client.put("saveciteUrl", java.net.URLEncoder.encode(saveciteUrl,"UTF-8"));
} catch (UnsupportedEncodingException e) {
logger.warn("Error encoding savecite URL",e);
}
}
context.put("saveciteClients",saveciteClients);
}
// determine which features to display
if( getConfigurationService().isGoogleScholarEnabled() )
{
String googleUrl = getSearchManager().getGoogleScholarUrl(getContentService().getUuid(resourceId));
context.put( "googleUrl", googleUrl );
// object array for formatted messages
Object[] googleArgs = { rb.getString( "linkLabel.google" ) };
context.put( "googleArgs", googleArgs );
}
if( getConfigurationService().librarySearchEnabled() )
{
context.put( "searchLibrary", Boolean.TRUE );
}
// form name
context.put(PARAM_FORM_NAME, ELEMENT_ID_CREATE_FORM);
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_ADD_CITATIONS;
} // buildAddCitationsPanelContext
/**
* build the context.
*
* @return The name of the template to use.
*/
public String buildCreatePanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
context.put("state", state);
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validator
context.put("xilator", new Validator());
//context.put("sakai_onload", "setPopupHeight('create');checkinWithOpener('create');");
//context.put("sakai_onunload", "window.opener.parent.popups['create']=null;");
//context.put("mainFrameId", CitationHelper.CITATION_FRAME_ID);
//context.put("citationToolId", CitationHelper.CITATION_ID);
//context.put("specialHelperFlag", CitationHelper.SPECIAL_HELPER_ID);
context.put(PARAM_FORM_NAME, ELEMENT_ID_CREATE_FORM);
List schemas = getCitationService().getSchemas();
context.put("TEMPLATES", schemas);
Schema defaultSchema = getCitationService().getDefaultSchema();
context.put("DEFAULT_TEMPLATE", defaultSchema);
// Object array for instruction message
Object[] instrArgs = { rb.getString( "submit.create" ) };
context.put( "instrArgs", instrArgs );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_CREATE;
} // buildCreatePanelContext
/**
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
public String buildDatabasePanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// get hierarchy
SearchDatabaseHierarchy hierarchy = ( SearchDatabaseHierarchy )
state.getAttribute(STATE_SEARCH_HIERARCHY);
// get selected category
SearchCategory category = ( SearchCategory ) state.getAttribute(
STATE_SELECTED_CATEGORY );
if( category == null )
{
// bad...
logger.warn( "buildDatabasePanelContext getting null selected " +
"category from state." );
}
// put selected category into context
context.put( "category", category );
// maxDbNum
Integer maxDbNum = new Integer(hierarchy.getNumMaxSearchableDb());
context.put( "maxDbNum", maxDbNum );
// object array for formatted messages
Object[] maxDbArgs = { maxDbNum };
context.put( "maxDbArgs", maxDbArgs );
// validator
context.put("xilator", new Validator());
// change mode back to SEARCH (DATABASE not needed anymore)
setMode( state, Mode.SEARCH );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_DATABASE;
} // buildDatabasePanelContext
/**
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
public String buildEditPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validator
context.put("xilator", new Validator());
context.put("sakai_onload", "setMainFrameHeight( window.name ); heavyResize();");
//context.put("sakai_onunload", "window.opener.parent.popups['edit']=null;");
//context.put("mainFrameId", CitationHelper.CITATION_FRAME_ID);
//context.put("citationToolId", CitationHelper.CITATION_ID);
//context.put("specialHelperFlag", CitationHelper.SPECIAL_HELPER_ID);
context.put(PARAM_FORM_NAME, ELEMENT_ID_CREATE_FORM);
Citation citation = (Citation) state.getAttribute(CitationHelper.CITATION_EDIT_ITEM);
if(citation == null)
{
doEdit(rundata);
citation = (Citation) state.getAttribute(CitationHelper.CITATION_EDIT_ITEM);
}
context.put("citation", citation);
String citationId = (String) state.getAttribute(CitationHelper.CITATION_EDIT_ID);
String collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
context.put("citationId", citationId);
context.put("collectionId", collectionId);
List schemas = getCitationService().getSchemas();
context.put("TEMPLATES", schemas);
context.put("DEFAULT_TEMPLATE", citation.getSchema());
// Object array for formatted instruction
Object[] instrArgs = { rb.getString( "submit.edit" ) };
context.put( "instrArgs", instrArgs );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_EDIT;
}
/**
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
private String buildErrorPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
//context.put("sakai_onload", "setPopupHeight('error');");
//context.put("sakai_onunload", "window.opener.parent.popups['error']=null;");
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_ERROR;
}
private String buildErrorFatalPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
//context.put("sakai_onload", "setPopupHeight('error');");
//context.put("sakai_onunload", "window.opener.parent.popups['error']=null;");
return TEMPLATE_ERROR_FATAL;
}
/**
* build the context.
*
* @return The name of the template to use.
*/
public String buildListPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
// state.setAttribute("fromListPage", true);
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validator
context.put("xilator", new Validator());
if( state.removeAttribute( STATE_LIST_NO_SCROLL ) == null )
{
context.put("sakai_onload", "setMainFrameHeight( window.name )");
}
else
{
context.put("sakai_onload", "resizeFrame()");
}
//context.put("mainFrameId", CitationHelper.CITATION_FRAME_ID);
//context.put("citationToolId", CitationHelper.CITATION_ID);
//context.put("specialHelperFlag", CitationHelper.SPECIAL_HELPER_ID);
// get the citation list title
String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
try {
ContentResource resource = this.getContentService().getResource(resourceId);
String description = resource.getProperties().getProperty(ResourceProperties.PROP_DESCRIPTION);
context.put("description", description);
} catch (Exception e) {
// TODO: Fix this. What exception is this dealing with?
logger.warn(e.getMessage(), e);
}
String refStr = getContentService().getReference(resourceId);
Reference ref = getEntityManager().newReference(refStr);
String collectionTitle = null;
if( ref != null )
{
collectionTitle = ref.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
if(collectionTitle == null) {
collectionTitle = (String)state.getAttribute( STATE_COLLECTION_TITLE );
}
if( collectionTitle != null && !collectionTitle.trim().equals("") )
{
context.put( "collectionTitle", getFormattedText().escapeHtml(collectionTitle));
}
context.put("openUrlLabel", getConfigurationService().getSiteConfigOpenUrlLabel());
context.put(PARAM_FORM_NAME, ELEMENT_ID_LIST_FORM);
CitationCollection collection = getCitationCollection(state, true);
// collection size
context.put( "collectionSize", new Integer( collection.size() ) );
// export URLs
String exportUrlSel = collection.getUrl(CitationService.REF_TYPE_EXPORT_RIS_SEL);
String exportUrlAll = collection.getUrl(CitationService.REF_TYPE_EXPORT_RIS_ALL);
context.put("exportUrlSel", exportUrlSel);
context.put("exportUrlAll", exportUrlAll);
Integer listPageSize = (Integer) state.getAttribute(STATE_LIST_PAGE_SIZE);
if(listPageSize == null)
{
listPageSize = defaultListPageSize;
state.setAttribute(STATE_LIST_PAGE_SIZE, listPageSize);
}
context.put("listPageSize", listPageSize);
CitationIterator newIterator = collection.iterator();
CitationIterator oldIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(oldIterator != null)
{
newIterator.setPageSize(listPageSize.intValue());
newIterator.setStart(oldIterator.getStart());
// newIterator.setPage(oldIterator.getPage());
}
context.put("citations", newIterator);
context.put("collectionId", collection.getId());
if(! collection.isEmpty())
{
context.put("show_citations", Boolean.TRUE);
// int page = newIterator.getPage();
// int pageSize = newIterator.getPageSize();
int totalSize = collection.size();
int start = newIterator.getStart();
int end = newIterator.getEnd();
// int start = page * pageSize + 1;
// int end = Math.min((page + 1) * pageSize, totalSize);
Integer[] position = { new Integer(start+1) , new Integer(end), new Integer(totalSize)};
String showing = (String) rb.getFormattedMessage("showing.results", position);
context.put("showing", showing);
}
state.setAttribute(STATE_LIST_ITERATOR, newIterator);
// back to search results button control
context.put("searchResults", state.getAttribute(STATE_SEARCH_RESULTS) );
// constant schema identifier
context.put( "titleProperty", Schema.TITLE );
/*
* Object arrays for formatted messages
*/
Object[] instrMainArgs = { getConfigurationService().getSiteConfigOpenUrlLabel() };
context.put( "instrMainArgs", instrMainArgs );
Object[] instrSubArgs = { rb.getString( "label.finish" ) };
context.put( "instrSubArgs", instrSubArgs );
Object[] emptyListArgs = { rb.getString( "label.menu" ) };
context.put( "emptyListArgs", emptyListArgs );
String sort = (String) state.getAttribute(STATE_SORT);
if (sort == null || sort.trim().length() == 0)
sort = collection.getSort();
context.put("sort", sort);
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_LIST;
} // buildListPanelContext
public String buildReorderPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state) {
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validator
context.put("xilator", new Validator());
if( state.removeAttribute( STATE_LIST_NO_SCROLL ) == null ) {
context.put("sakai_onload", "setMainFrameHeight( window.name )");
}
else {
context.put("sakai_onload", "resizeFrame()");
}
// get the citation list title
String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
String refStr = getContentService().getReference(resourceId);
Reference ref = getEntityManager().newReference(refStr);
String collectionTitle = null;
if( ref != null ) {
collectionTitle = ref.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
}
if(collectionTitle == null) {
collectionTitle = (String)state.getAttribute( STATE_COLLECTION_TITLE );
}
else if( !collectionTitle.trim().equals("") ) {
context.put( "collectionTitle", Validator.escapeHtml(collectionTitle));
}
CitationCollection collection = getCitationCollection(state, true);
collection.setSort(CitationCollection.SORT_BY_POSITION,true);
CitationIterator newIterator = collection.iterator();
context.put("citations", newIterator);
context.put("collectionId", collection.getId());
state.setAttribute(STATE_LIST_ITERATOR, newIterator);
return TEMPLATE_REORDER;
}
/**
* This method retrieves the CitationCollection for the current session.
* If the CitationCollection is already in session-state and has not been
* updated in the persistent storage since it was last accessed, the copy
* in session-state will be returned. If it has been updated in storage,
* the copy in session-state will be updated and returned. If the
* CitationCollection has not yet been created in storage and the second
* parameter is true, this method will create the collection and return it.
* In that case, values will be added to session-state for attributes named
* STATE_COLLECTION_ID and STATE_COLLECTION. If the CitationCollection has
* not yet been created in storage and the second parameter is false, the
* method will return null.
* @param state The SessionState object for the current session.
* @param create A flag indicating whether the collection should be created
* if it does not already exist.
* @return The CitationCollection for the current session, or null.
*/
protected CitationCollection getCitationCollection(SessionState state, boolean create)
{
CitationCollection citationCollection = (CitationCollection) state.getAttribute(STATE_CITATION_COLLECTION);
if(citationCollection == null)
{
String citationCollectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
if(citationCollectionId == null && create)
{
citationCollection = getCitationService().addCollection();
getCitationService().save(citationCollection);
}
else
{
try
{
citationCollection = getCitationService().getCollection(citationCollectionId);
}
catch (IdUnusedException e)
{
logger.warn("IdUnusedException: CitationHelperAction.getCitationCollection() unable to access citationCollection " + citationCollectionId);
}
if(citationCollection == null && create)
{
citationCollection = getCitationService().addCollection();
getCitationService().save(citationCollection);
}
}
if(citationCollection != null) {
state.setAttribute(STATE_CITATION_COLLECTION, citationCollection);
state.setAttribute(STATE_CITATION_COLLECTION_ID, citationCollection.getId());
}
}
return citationCollection;
}
/**
* build the context.
*
* @return The name of the template to use.
*/
public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
logger.debug("buildMainPanelContext()");
// always put appropriate bundle in velocity context
context.put("tlang", rb);
//context.put("mainFrameId", CitationHelper.CITATION_FRAME_ID);
//context.put("citationToolId", CitationHelper.CITATION_ID);
//context.put("specialHelperFlag", CitationHelper.SPECIAL_HELPER_ID);
// always put whether this is a Resources Add or Revise operation
if( state.getAttribute( STATE_RESOURCES_ADD ) != null )
{
context.put( "resourcesAddAction", Boolean.TRUE );
}
// make sure observers are disabled
VelocityPortletPaneledAction.disableObservers(state);
String template = "";
Mode mode = (Mode) state.getAttribute(CitationHelper.STATE_HELPER_MODE);
if(mode == null)
{
// mode really shouldn't be null here
logger.warn( "buildMainPanelContext() getting null Mode from state" );
mode = Mode.NEW_RESOURCE;
//mode = Mode.ADD_CITATIONS;
setMode(state, mode);
}
// add mode to the template
context.put( "citationsHelperMode", mode );
switch(mode)
{
case NEW_RESOURCE:
template = buildNewResourcePanelContext(portlet, context, rundata, state);
break;
case IMPORT_CITATIONS:
template = buildImportCitationsPanelContext(portlet, context, rundata, state);
break;
case ADD_CITATIONS:
template = buildAddCitationsPanelContext(portlet, context, rundata, state);
break;
case CREATE:
template = buildCreatePanelContext(portlet, context, rundata, state);
break;
case DATABASE:
template = buildDatabasePanelContext(portlet, context, rundata, state);
break;
case EDIT:
template = buildEditPanelContext(portlet, context, rundata, state);
break;
case ERROR:
template = buildErrorPanelContext(portlet, context, rundata, state);
break;
case ERROR_FATAL:
template = buildErrorFatalPanelContext(portlet, context, rundata, state);
break;
case LIST:
template = buildListPanelContext(portlet, context, rundata, state);
break;
case REORDER:
template = buildReorderPanelContext(portlet, context, rundata, state);
break;
case MESSAGE:
template = buildMessagePanelContext(portlet, context, rundata, state);
break;
case SEARCH:
template = buildSearchPanelContext(portlet, context, rundata, state);
break;
case RESULTS:
template = buildResultsPanelContext(portlet, context, rundata, state);
break;
case VIEW:
template = buildViewPanelContext(portlet, context, rundata, state);
break;
}
return template;
} // buildMainPanelContext
public String buildNewResourcePanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state) {
logger.debug("buildNewResourcePanelContext()");
context.put("MIMETYPE_JSON", MIMETYPE_JSON);
context.put("REQUESTED_MIMETYPE", REQUESTED_MIMETYPE);
context.put("xilator", new Validator());
context.put("availability_is_enabled", Boolean.TRUE);
context.put("GROUP_ACCESS", AccessMode.GROUPED);
context.put("INHERITED_ACCESS", AccessMode.INHERITED);
Boolean resourceAdd = (Boolean) state.getAttribute(STATE_RESOURCES_ADD);
if(resourceAdd != null && resourceAdd.equals(true)) {
context.put("resourceAdd", Boolean.TRUE);
context.put(CITATION_ACTION, CREATE_RESOURCE);
} else {
context.put(CITATION_ACTION, UPDATE_RESOURCE);
}
// resource-related
String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
String resourceUuid = (String) state.getAttribute(CitationHelper.RESOURCE_UUID);
if(resourceId == null || resourceId.trim().equals("")) {
if(resourceUuid == null || resourceUuid.trim().equals("")) {
// Will be dealt with later by creating new resource when needed
} else if(resourceUuid.startsWith("/")) {
// UUID and ID may be switched
resourceId = resourceUuid;
resourceUuid = this.getContentService().getUuid(resourceId);
if(resourceUuid != null) {
state.setAttribute(CitationHelper.RESOURCE_ID, resourceId);
state.setAttribute(CitationHelper.RESOURCE_UUID, resourceUuid);
}
} else {
// see if we can get the resourceId from the UUID
resourceId = this.getContentService().resolveUuid(resourceUuid);
if(resourceId != null) {
state.setAttribute(CitationHelper.RESOURCE_ID, resourceId);
}
}
} else if(resourceUuid == null || resourceUuid.trim().equals("")) {
resourceUuid = this.getContentService().getUuid(resourceId);
if(resourceUuid != null) {
state.setAttribute(CitationHelper.RESOURCE_UUID, resourceUuid);
}
}
if(logger.isInfoEnabled()) {
logger.info("buildNewResourcePanelContext() resourceUuid == " + resourceUuid + " resourceId == " + resourceId);
}
String citationCollectionId = null;
ContentResource resource = null;
Map<String,Object> contentProperties = null;
if(resourceId == null) {
} else {
try {
resource = getContentService().getResource(resourceId);
} catch (IdUnusedException e) {
logger.warn("IdUnusedException geting resource in buildNewResourcePanelContext() " + e);
} catch (TypeException e) {
logger.warn("TypeException geting resource in buildNewResourcePanelContext() " + e);
} catch (PermissionException e) {
logger.warn("PermissionException geting resource in buildNewResourcePanelContext() " + e);
}
// String guid = getContentService().getUuid(resourceId);
// context.put("RESOURCE_ID", guid);
}
if(resource == null) {
context.put(CITATION_ACTION, CREATE_RESOURCE);
ToolSession toolSession = getSessionManager().getCurrentToolSession();
ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE);
String collectionId = pipe.getContentEntity().getId();
context.put("collectionId", collectionId);
ContentCollection collection;
try {
collection = getContentService().getCollection(collectionId);
contentProperties = this.getProperties(collection, state);
} catch (IdUnusedException e) {
logger.warn("IdUnusedException geting collection in buildNewResourcePanelContext() " + e);
} catch (TypeException e) {
logger.warn("TypeException geting collection in buildNewResourcePanelContext() " + e);
} catch (PermissionException e) {
logger.warn("PermissionException geting collection in buildNewResourcePanelContext() " + e);
}
} else {
ResourceProperties props = resource.getProperties();
contentProperties = this.getProperties(resource, state);
context.put("resourceTitle", props.getProperty(ResourceProperties.PROP_DISPLAY_NAME));
context.put("resourceDescription", props.getProperty(ResourceProperties.PROP_DESCRIPTION));
//resourceUuid = this.getContentService().getUuid(resourceId);
context.put("resourceUuid", resourceUuid );
context.put("collectionId", resource.getContainingCollection().getId());
try {
citationCollectionId = new String(resource.getContent());
} catch (ServerOverloadException e) {
logger.warn("ServerOverloadException geting props in buildNewResourcePanelContext() " + e);
}
context.put(CITATION_ACTION, UPDATE_RESOURCE);
}
if(contentProperties == null) {
contentProperties = new HashMap<String,Object>();
}
context.put("contentProperties", contentProperties);
int collectionSize = 0;
CitationCollection citationCollection = null;
if(citationCollectionId == null) {
citationCollectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
//String citationCollectionId = (String) state.getAttribute(CitationHelper.CITATION_COLLECTION_ID);
}
if(citationCollectionId == null) {
} else {
citationCollection = getCitationCollection(state, true);
if(citationCollection == null) {
logger.warn( "buildAddCitationsPanelContext unable to access citationCollection " + citationCollectionId );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_ERROR;
} else {
// get the size of the list
collectionSize = citationCollection.size();
}
context.put("collectionId", citationCollectionId);
}
context.put( "collectionSize", new Integer( collectionSize ) );
Locale locale = rb.getLocale();
List<Map<String,String>> saveciteClients = getConfigurationService().getSaveciteClientsForLocale(locale);
if(saveciteClients != null) {
if(resource != null && resourceId != null) {
for(Map<String,String> client : saveciteClients) {
String saveciteUrl = getSearchManager().getSaveciteUrl(resourceUuid,client.get("id"));
try {
client.put("saveciteUrl", java.net.URLEncoder.encode(saveciteUrl,"UTF-8"));
} catch (UnsupportedEncodingException e) {
logger.warn("Error encoding savecite URL",e);
}
}
}
context.put("saveciteClients",saveciteClients);
}
// determine which features to display
if( getConfigurationService().isGoogleScholarEnabled() ) {
String googleUrl = getSearchManager().getGoogleScholarUrl(getContentService().getUuid(resourceId));
context.put( "googleUrl", googleUrl );
// object array for formatted messages
Object[] googleArgs = { rb.getString( "linkLabel.google" ) };
context.put( "googleArgs", googleArgs );
}
if( getConfigurationService().librarySearchEnabled() ) {
context.put( "searchLibrary", Boolean.TRUE );
}
if(citationCollection == null || citationCollection.size() <= 0) {
} else {
context.put("openUrlLabel", getConfigurationService().getSiteConfigOpenUrlLabel());
String currentSort = (String) state.getAttribute(STATE_SORT);
if (currentSort == null || currentSort.trim().length() == 0)
currentSort = citationCollection.getSort();
if(currentSort == null || currentSort.trim().length() == 0) {
currentSort = CitationCollection.SORT_BY_TITLE;
}
context.put("currentSort", currentSort);
String savedSort = citationCollection.getSort();
if(savedSort == null || savedSort.trim().equals("")) {
savedSort = CitationCollection.SORT_BY_TITLE;
}
if(savedSort != currentSort) {
citationCollection.setSort(currentSort, true);
}
//context.put(PARAM_FORM_NAME, ELEMENT_ID_LIST_FORM);
// collection size
context.put( "collectionSize", new Integer( citationCollection.size() ) );
// export URLs
String exportUrlSel = citationCollection.getUrl(CitationService.REF_TYPE_EXPORT_RIS_SEL);
String exportUrlAll = citationCollection.getUrl(CitationService.REF_TYPE_EXPORT_RIS_ALL);
context.put("exportUrlSel", exportUrlSel);
context.put("exportUrlAll", exportUrlAll);
Integer listPageSize = (Integer) state.getAttribute(STATE_LIST_PAGE_SIZE);
if(listPageSize == null)
{
listPageSize = defaultListPageSize;
state.setAttribute(STATE_LIST_PAGE_SIZE, listPageSize);
}
context.put("listPageSize", listPageSize);
CitationIterator newIterator = citationCollection.iterator();
CitationIterator oldIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
- if(oldIterator != null)
- {
+ if(oldIterator == null) {
+ newIterator.setPageSize(listPageSize.intValue());
+ newIterator.setStart(0);
+ } else {
newIterator.setPageSize(listPageSize.intValue());
newIterator.setStart(oldIterator.getStart());
// newIterator.setPage(oldIterator.getPage());
}
context.put("citations", newIterator);
context.put("citationCollectionId", citationCollection.getId());
if(! citationCollection.isEmpty())
{
context.put("show_citations", Boolean.TRUE);
// int page = newIterator.getPage();
// int pageSize = newIterator.getPageSize();
int totalSize = citationCollection.size();
int start = newIterator.getStart();
int end = newIterator.getEnd();
// int start = page * pageSize + 1;
// int end = Math.min((page + 1) * pageSize, totalSize);
Integer[] position = { new Integer(start+1) , new Integer(end), new Integer(totalSize)};
String showing = (String) rb.getFormattedMessage("showing.results", position);
context.put("showing", showing);
}
state.setAttribute(STATE_LIST_ITERATOR, newIterator);
// constant schema identifier
context.put( "titleProperty", Schema.TITLE );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
}
return TEMPLATE_NEW_RESOURCE;
}
/**
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
public String buildMessagePanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
context.put("sakai_onload", "");
//context.put("FORM_NAME", "messageForm");
context.put( "citationId", state.getAttribute( STATE_CITATION_ID ) );
// get the collection we're now working on
String collectionId = (String)state.getAttribute(STATE_CITATION_COLLECTION_ID);
context.put( "collectionId", collectionId );
int size = 0;
CitationCollection collection = getCitationCollection(state, false);
if(collection == null)
{
logger.warn( "buildMessagePanelContext unable to access citationCollection " + collectionId );
}
else
{
size = collection.size();
}
// get the size of the list
context.put( "citationCount", new Integer( size ) );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_MESSAGE;
}
/**
*
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
public String buildResultsPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
Caller caller = getCaller(state);
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validators
context.put("TextValidator", new QuotedTextValidator());
context.put("xilator", new Validator());
// Set:
// * the javascript to run on page load
// * the page execution context (resources tool or editor integration)
switch (caller)
{
case EDITOR_INTEGRATION:
context.put("sakai_onload", "SRC_initializePageInfo('"
+ ELEMENT_ID_RESULTS_FORM
+ "','"
+ rb.getString("add.results")
+ "'); SRC_verifyWindowOpener();");
context.put("editorIntegration", Boolean.TRUE);
context.put("resourcesTool", Boolean.FALSE);
break;
case RESOURCE_TOOL:
default:
context.put("sakai_onload", "setMainFrameHeight( window.name ); highlightButtonSelections( '" + rb.getString("remove.results") + "' )");
context.put("editorIntegration", Boolean.FALSE);
context.put("resourcesTool", Boolean.TRUE);
// put the citation list title and size
putCitationCollectionDetails(context, state);
break;
}
// signal basic/advanced search
Object basicSearch = state.getAttribute( STATE_BASIC_SEARCH );
context.put( "basicSearch", basicSearch );
if( basicSearch != null )
{
context.put( "searchType", ActiveSearch.BASIC_SEARCH_TYPE );
}
else
{
context.put( "searchType", ActiveSearch.ADVANCED_SEARCH_TYPE );
}
/*
* SEARCH RESULTS
*/
ActiveSearch searchResults = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS);
if(searchResults != null)
{
context.put("searchResults", searchResults);
List currentResults = (List) state.getAttribute(STATE_CURRENT_RESULTS);
context.put("currentResults", currentResults);
Integer[] position = { new Integer(searchResults.getFirstRecordIndex() + 1) , new Integer(searchResults.getLastRecordIndex()), searchResults.getNumRecordsFound()};
String showing = (String) rb.getFormattedMessage("showing.results", position);
context.put("showing", showing);
}
// selected databases
String[] databaseIds = (String[])state.getAttribute( STATE_CURRENT_DATABASES );
context.put( "selectedDatabases", databaseIds );
// load basic/advanced search form state
loadSearchFormState( context, state );
/*
* OTHER CONTEXT PARAMS
*/
// searchInfo
ActiveSearch searchInfo = (ActiveSearch) state.getAttribute(STATE_SEARCH_INFO);
context.put("searchInfo", searchInfo);
// form name
context.put(PARAM_FORM_NAME, ELEMENT_ID_RESULTS_FORM);
// OpenURL Label
context.put( "openUrlLabel", getConfigurationService().getSiteConfigOpenUrlLabel() );
// object arrays for formatted messages
Object[] instrMainArgs = { rb.getString( "add.results" ) };
context.put( "instrMainArgs", instrMainArgs );
Object[] instrSubArgs = { rb.getString( "label.new.search" ) };
context.put( "instrSubArgs", instrSubArgs );
/*
* ERROR CHECKING
*/
String alertMessages = (String) state.removeAttribute(STATE_MESSAGE);
if(alertMessages != null)
{
context.put("alertMessages", alertMessages);
}
Object noResults = state.removeAttribute( STATE_NO_RESULTS );
if( noResults != null )
{
context.put( "noResults", noResults );
}
Object noSearch = state.removeAttribute(STATE_NO_KEYWORDS);
if(noSearch != null)
{
context.put("noSearch", noSearch);
}
Object noDatabases = state.removeAttribute( STATE_NO_DATABASES );
if( noDatabases != null )
{
context.put( "noDatabases", noDatabases );
}
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_RESULTS;
} // buildResultsPanelContext
/**
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
public String buildSearchPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
Caller caller = getCaller(state);
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validators
context.put("TextValidator", new QuotedTextValidator());
context.put("xilator", new Validator());
// Set:
// * the javascript to run on page load
// * the page execution context (resources tool or editor integration)
switch (caller)
{
case EDITOR_INTEGRATION:
context.put("sakai_onload", "SRC_verifyWindowOpener(); showTopCategory();");
context.put("editorIntegration", Boolean.TRUE);
context.put("resourcesTool", Boolean.FALSE);
break;
case RESOURCE_TOOL:
default:
context.put("sakai_onload", "setMainFrameHeight( window.name ); showTopCategory();");
context.put("editorIntegration", Boolean.FALSE);
context.put("resourcesTool", Boolean.TRUE);
// put citation list title/size
putCitationCollectionDetails(context, state);
break;
}
// resource-related
String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
String guid = getContentService().getUuid(resourceId);
context.put("RESOURCE_ID", guid);
// category information from hierarchy
SearchDatabaseHierarchy hierarchy = (SearchDatabaseHierarchy) state.getAttribute(STATE_SEARCH_HIERARCHY);
context.put( "defaultCategory", hierarchy.getDefaultCategory() );
context.put( "categoryListing", hierarchy.getCategoryListing() );
// load basic/advanced search form state
loadSearchFormState( context, state );
/*
* MISCELLANEOUS CONTEXT PARAMS
*/
// default to basicSearch
context.put( "basicSearch", state.getAttribute( STATE_BASIC_SEARCH ) );
// searchInfo
ActiveSearch searchInfo = (ActiveSearch) state.getAttribute(STATE_SEARCH_INFO);
context.put("searchInfo", searchInfo);
// max number of searchable databases
Integer maxDbNum = new Integer(hierarchy.getNumMaxSearchableDb());
context.put( "maxDbNum", maxDbNum );
// form name
context.put(PARAM_FORM_NAME, ELEMENT_ID_SEARCH_FORM);
// OpenURL Label
context.put( "openUrlLabel", getConfigurationService().getSiteConfigOpenUrlLabel() );
// object arrays for formatted messages
Object[] instrArgs = { rb.getString( "submit.search" ) };
context.put( "instrArgs", instrArgs );
String searchType = null;
if (searchInfo != null)
{
searchType = searchInfo.getSearchType();
}
if (searchType == null)
searchType = ActiveSearch.BASIC_SEARCH_TYPE;
context.put("searchType", searchType);
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_SEARCH;
} // buildSearchPanelContext
/**
* @param portlet
* @param context
* @param rundata
* @param state
* @return
*/
public String buildViewPanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state)
{
// always put appropriate bundle in velocity context
context.put("tlang", rb);
// validator
context.put("xilator", new Validator());
//context.put("sakai_onload", "setMainFrameHeight('" + CitationHelper.CITATION_FRAME_ID + "');");
//context.put("mainFrameId", CitationHelper.CITATION_FRAME_ID);
//context.put("citationToolId", CitationHelper.CITATION_ID);
//context.put("specialHelperFlag", CitationHelper.SPECIAL_HELPER_ID);
context.put(PARAM_FORM_NAME, ELEMENT_ID_VIEW_FORM);
Citation citation = (Citation) state.getAttribute(CitationHelper.CITATION_VIEW_ITEM);
if(citation == null)
{
doEdit(rundata);
citation = (Citation) state.getAttribute(CitationHelper.CITATION_VIEW_ITEM);
}
context.put("citation", citation);
String citationId = (String) state.getAttribute(CitationHelper.CITATION_VIEW_ID);
String collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
context.put("citationId", citationId);
context.put("collectionId", collectionId);
List schemas = getCitationService().getSchemas();
context.put("TEMPLATES", schemas);
context.put("DEFAULT_TEMPLATE", citation.getSchema());
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_VIEW;
} // buildViewPanelContext
/**
*
* @param context
* @param state
*/
protected void loadSearchFormState( Context context, SessionState state )
{
// remember data previously entered
if( state.getAttribute( STATE_BASIC_SEARCH ) != null )
{
/* basic search */
context.put( "keywords", ( String )state.getAttribute( STATE_KEYWORDS ) );
// default advanced search selections
context.put( "advField1", AdvancedSearchHelper.KEYWORD_ID );
context.put( "advField2", AdvancedSearchHelper.AUTHOR_ID );
context.put( "advField3", AdvancedSearchHelper.TITLE_ID );
context.put( "advField4", AdvancedSearchHelper.SUBJECT_ID );
context.put( "advField5", AdvancedSearchHelper.YEAR_ID );
}
else
{
/* advanced search */
// field selections
AdvancedSearchHelper.putFieldSelections( context, state );
// field criteria
AdvancedSearchHelper.putFieldCriteria( context, state );
}
// basic/advanced search types
context.put( "basicSearchType", ActiveSearch.BASIC_SEARCH_TYPE );
context.put( "advancedSearchType", ActiveSearch.ADVANCED_SEARCH_TYPE );
}
/**
*
*/
public void doFinish ( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ToolSession toolSession = getSessionManager().getCurrentToolSession();
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE);
if (pipe == null)
{
logger.warn( "doFinish() pipe = null");
setMode(state, Mode.ERROR_FATAL);
return;
}
int citationCount = 0;
// if(pipe.getAction().getActionType() == ResourceToolAction.ActionType.CREATE_BY_HELPER)
// {
// /* PIPE remove */
//// SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//
// SecurityService securityService = (SecurityService) ComponentManager.get(SecurityService.class);
// // delete the temporary resource
// String temporaryResourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
// ContentResource tempResource = null;
// try
// {
// // get the temp resource
// tempResource = getContentService().getResource(temporaryResourceId);
//
// // use the temp resource to 'create' the real resource
// pipe.setRevisedContent(tempResource.getContent());
//
// // remove the temp resource
// if( getCitationService().allowRemoveCitationList( temporaryResourceId ) )
// {
// // setup a SecurityAdvisor
// CitationListSecurityAdviser advisor = new CitationListSecurityAdviser(
// getSessionManager().getCurrentSessionUserId(),
// ContentHostingService.AUTH_RESOURCE_REMOVE_ANY,
// tempResource.getReference() );
//
// try {
// securityService.pushAdvisor(advisor);
//
// // remove temp resource
// getContentService().removeResource(temporaryResourceId);
// } catch(Exception e) {
// logger.warn("Exception removing temporary resource for a citation list: " + temporaryResourceId + " --> " + e);
// } finally {
// // pop advisor
// securityService.popAdvisor(advisor);
// }
//
// tempResource = null;
// }
// }
// catch (PermissionException e)
// {
//
// logger.warn("PermissionException ", e);
// }
// catch (IdUnusedException e)
// {
//
// logger.warn("IdUnusedException ", e);
// }
// catch (TypeException e)
// {
//
// logger.warn("TypeException ", e);
// }
//// catch (InUseException e)
//// {
////
//// logger.warn("InUseException ", e);
//// }
// catch (ServerOverloadException e)
// {
//
// logger.warn("ServerOverloadException ", e);
// }
// catch (Exception e)
// {
//
// logger.warn("Exception ", e);
// }
// }
// // set content (mime) type
// pipe.setRevisedMimeType(ResourceType.MIME_TYPE_HTML);
// pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_TYPE, ResourceType.MIME_TYPE_HTML);
//
// // set the alternative_reference to point to reference_root for CitationService
// pipe.setRevisedResourceProperty(ContentHostingService.PROP_ALTERNATE_REFERENCE, CitationService.REFERENCE_ROOT);
/* PIPE remove */
// SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// get the collection we're now working on
CitationCollection collection = getCitationCollection(state, true);
if(collection == null) {
// error
} else {
String collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
String[] args = new String[]{ Integer.toString(collection.size()) };
String size_str = rb.getFormattedMessage("citation.count", args);
pipe.setRevisedResourceProperty(ResourceProperties.PROP_CONTENT_LENGTH, size_str);
// leave helper mode
pipe.setActionCanceled(false);
pipe.setErrorEncountered(false);
pipe.setActionCompleted(true);
toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE);
toolSession.removeAttribute(CitationHelper.CITATION_HELPER_INITIALIZED);
cleanup(toolSession, CitationHelper.CITATION_PREFIX, state);
// Remove session sort
state.removeAttribute(STATE_SORT);
// Remove session collection
state.removeAttribute(STATE_CITATION_COLLECTION_ID);
state.removeAttribute(STATE_CITATION_COLLECTION);
state.removeAttribute("fromListPage");
}
} // doFinish
/**
* Cancel the action for which the helper was launched.
*/
public void doCancel(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ToolSession toolSession = getSessionManager().getCurrentToolSession();
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE);
if (pipe == null)
{
logger.warn( "doCancel() pipe = null");
setMode(state, Mode.ERROR_FATAL);
return;
}
if(pipe.getAction().getActionType() == ResourceToolAction.ActionType.CREATE_BY_HELPER)
{
// TODO: delete the citation collection and all citations
// TODO: delete the temporary resource
// String temporaryResourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
// ContentResourceEdit edit = null;
// try
// {
// edit = getContentService().editResource(temporaryResourceId);
// getContentService().removeResource(edit);
// edit = null;
// }
// catch (PermissionException e)
// {
//
// logger.warn("PermissionException ", e);
// }
// catch (IdUnusedException e)
// {
//
// logger.warn("IdUnusedException ", e);
// }
// catch (TypeException e)
// {
//
// logger.warn("TypeException ", e);
// }
// catch (InUseException e)
// {
//
// logger.warn("InUseException ", e);
// }
//
// if(edit != null)
// {
// getContentService().cancelResource(edit);
// }
}
// leave helper mode
pipe.setActionCanceled(true);
pipe.setErrorEncountered(false);
pipe.setActionCompleted(true);
toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE);
toolSession.removeAttribute(CitationHelper.CITATION_HELPER_INITIALIZED);
state.removeAttribute("fromListPage");
cleanup(toolSession, CitationHelper.CITATION_PREFIX, state);
}
/**
* Adds a citation to the current citation collection. Called from the search-results popup.
*/
public void doAddCitation ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
// get the citation from search results, add it to the citation collection, and rebuild the context
String[] citationIds = params.getStrings("citationId");
String collectionId = params.getString("collectionId");
Integer page = (Integer) state.getAttribute(STATE_LIST_PAGE);
ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS);
CitationCollection tempCollection = search.getSearchResults();
Map index = search.getIndex();
if(index == null)
{
index = new Hashtable();
search.setIndex(index);
}
CitationCollection permCollection = getCitationCollection(state, true);
if(permCollection == null) {
// error
} else {
for(int i = 0; i < citationIds.length; i++)
{
try
{
Citation citation = tempCollection.getCitation(citationIds[i]);
citation.setAdded(true);
permCollection.add(citation);
}
catch(IdUnusedException ex)
{
logger.info("doAdd: unable to add citation " + citationIds[i] + " to collection " + collectionId);
}
}
getCitationService().save(permCollection);
}
// setMode(state, Mode.LIST);
}
/**
* Removes a citation from the current citation collection. Called from the search-results popup.
*/
public void doRemove ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
// get the citation number from search results, remove it from the citation collection, and rebuild the context
// get the citation from search results, add it to the citation collection, and rebuild the context
String[] citationIds = params.getStrings("citationId");
String collectionId = params.getString("collectionId");
ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS);
CitationCollection tempCollection = search.getSearchResults();
Map index = search.getIndex();
if(index == null)
{
index = new Hashtable();
search.setIndex(index);
}
CitationCollection permCollection = getCitationCollection(state, true);
if(permCollection == null) {
// error
} else {
for(int i = 0; i < citationIds.length; i++)
{
try
{
Citation citation = tempCollection.getCitation(citationIds[i]);
citation.setAdded(false);
permCollection.remove(citation);
}
catch(IdUnusedException ex)
{
logger.info("doAdd: unable to add citation " + citationIds[i] + " to collection " + collectionId);
}
}
getCitationService().save(permCollection);
}
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
}
public void doDatabasePopulate( RunData data )
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
// get category id
String categoryId = params.get( "categoryId" );
logger.debug( "doDatabasePopulate() categoryId from URL: " + categoryId );
if( categoryId == null )
{
// should not be null
setMode( state, Mode.ERROR );
return;
}
else
{
/* TODO can probably do this in build-method (don't need category in state)*/
// get selected category, put it in state
SearchDatabaseHierarchy hierarchy = ( SearchDatabaseHierarchy )
state.getAttribute( STATE_SEARCH_HIERARCHY );
SearchCategory category = hierarchy.getCategory( categoryId );
state.setAttribute( STATE_SELECTED_CATEGORY, category );
setMode(state, Mode.DATABASE);
}
}
/**
*
* @param data
*/
public void doImportPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
this.preserveEntityIds(params, state);
setMode(state, Mode.IMPORT_CITATIONS);
} // doImportPage
/**
*
* @param data
*/
public void doImport ( RunData data)
{
logger.debug( "doImport called.");
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
Iterator iter = params.getNames();
String param = null;
while (iter.hasNext())
{
param = (String) iter.next();
logger.debug( "param = " + param);
logger.debug( param + " value = " + params.get(param));
}
String collectionId = params.getString("collectionId");
if(collectionId == null)
{
collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
}
CitationCollection collection = null;
collection = getCitationCollection(state, false);
String ristext = params.get("ristext");
// We're going to read the RIS file from the submitted form's textarea first. If that's
// empty we'll read it from the uploaded file. We'll crate a BufferedReader in either
// circumstance so that the parsing code need not know where the ris text came from.
java.io.BufferedReader bread = null;
if (ristext.trim().length() > 0) // form has text in the risimport textarea
{
java.io.StringReader risStringReader = new java.io.StringReader(ristext);
bread = new java.io.BufferedReader(risStringReader);
logger.debug( "String buffered reader ready");
} // end RIS text is in the textarea
else // textarea empty, set the read of the import from the file
{
String upload = params.get("risupload");
logger.debug( "Upload String = " + upload);
FileItem risImport = params.getFileItem("risupload");
if (risImport == null)
{
logger.debug( "risImport is null.");
return;
}
logger.debug("Filename = " + risImport.getFileName());
InputStream risImportStream = risImport.getInputStream();
// Attempt to detect the encoding of the file.
BOMInputStream irs = new BOMInputStream(risImportStream);
// below is needed if UTF-8 above is commented out
Reader isr = null;
String bomCharsetName = null;
try
{
bomCharsetName = irs.getBOMCharsetName();
if (bomCharsetName != null)
{
isr = new InputStreamReader(risImportStream, bomCharsetName);
}
} catch (UnsupportedEncodingException uee)
{
// Something strange as the JRE should support all the formats.
logger.info("Problem using character set when importing RIS: "+ bomCharsetName);
}
catch (IOException ioe)
{
// Probably won't get any further, but may as well try.
logger.debug("Problem reading the character set from RIS import: "+ ioe.getMessage());
}
// Fallback to platform default
if (isr == null) {
isr = new InputStreamReader(irs);
}
bread = new java.io.BufferedReader(isr);
} // end set the read of the import from the uploaded file.
// The below code is a major work in progress.
// This code is for demonstration purposes only. No gambling or production use!
StringBuilder fileString = new StringBuilder();
String importLine = null;
java.util.List importList = new java.util.ArrayList();
// Read the BufferedReader and populate the importList. Each entry in the list
// is a line in the RIS import "file".
try
{
while ((importLine = bread.readLine()) != null)
{
importLine = importLine.trim();
if (importLine != null && importLine.length() > 2)
{
importList.add(importLine);
if(logger.isDebugEnabled()) {
fileString.append("\n");
fileString.append(importLine);
}
}
} // end while
} // end try
catch(Exception e)
{
logger.debug("ISR error = " + e);
} // end catch
finally {
if (bread != null) {
try {
bread.close();
} catch (IOException e) {
// tried
}
}
}
if(logger.isDebugEnabled()) {
logger.debug("fileString = \n" + fileString.toString());
}
// tempList holds the entries read in to make a citation up to and
// including the ER entry from importList
List tempList = new java.util.ArrayList();
Citation importCitation = getCitationService().getTemporaryCitation();
CitationCollection importCollection = getCitationService().getTemporaryCollection();
int sucessfullyReadCitations = 0;
int totalNumberCitations = 0;
// Read each entry in the RIS List and build a citation
for(int i=0; i< importList.size(); i++)
{
String importEntryString = (String) importList.get(i);
// logger.debug("Import line (#1) = " + importEntryString);
// logger.debug("Substring is = " + importEntryString.substring(0, 2));
tempList.add(importEntryString);
// make sure importEntryString can be tested for "ER" existence. It could
// be a dinky invalid line less than 2 characters.
if (importEntryString != null && importEntryString.length() > 1 &&
importEntryString.substring(0, 2).equalsIgnoreCase("ER"))
{
// end of citation (signaled by ER).
totalNumberCitations++;
logger.debug("------> Trying to add citation " + totalNumberCitations);
if (importCitation.importFromRisList(tempList)) // import went well
{
importCollection.add(importCitation);
sucessfullyReadCitations++;
}
tempList.clear();
importCitation = getCitationService().getTemporaryCitation();
}
} // end for
logger.debug("Done reading in " + sucessfullyReadCitations + " / " + totalNumberCitations + " citations.");
collection.addAll(importCollection);
getCitationService().save(collection);
// remove collection from state
state.removeAttribute(STATE_CITATION_COLLECTION);
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
} // end doImport()
public void doCreateResource(RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
setMode(state, Mode.NEW_RESOURCE);
//state.setAttribute(CitationHelper.SPECIAL_HELPER_ID, CitationHelper.CITATION_ID);
}
/**
*
*/
public void doCreate ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
setMode(state, Mode.CREATE);
//state.setAttribute(CitationHelper.SPECIAL_HELPER_ID, CitationHelper.CITATION_ID);
} // doCreate
/**
* Fetch the calling application
* @param state The session state
* @return The calling application (default to Resources if nothing is set)
*/
protected Caller getCaller(SessionState state)
{
Caller caller = (Caller) state.getAttribute(CITATIONS_HELPER_CALLER);
return (caller == null) ? Caller.RESOURCE_TOOL : Caller.EDITOR_INTEGRATION;
}
/**
* Set the calling applcation
* @param state The session state
* @param caller The calling application
*/
protected void setCaller(SessionState state, Caller caller)
{
state.setAttribute(CITATIONS_HELPER_CALLER, caller);
}
/**
* @param state
* @param new_mode
*/
protected void setMode(SessionState state, Mode new_mode)
{
// set state attributes
state.setAttribute( CitationHelper.STATE_HELPER_MODE, new_mode );
}
/**
*
*/
public void doCreateCitation ( RunData data)
{
// get the state object and the parameter parser
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
Set validPropertyNames = getCitationService().getValidPropertyNames();
String mediatype = params.getString("type");
CitationCollection collection = getCitationCollection(state, true);
if(collection == null) {
// error
} else {
// create a citation
Citation citation = getCitationService().addCitation(mediatype);
updateCitationFromParams(citation, params);
// add citation to current collection
collection.add(citation);
getCitationService().save(collection);
}
// call buildListPanelContext to show updated list
//state.setAttribute(CitationHelper.SPECIAL_HELPER_ID, CitationHelper.CITATION_ID);
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
} // doCreateCitation
/**
* @param citation
* @param params
*/
protected void updateCitationFromParams(Citation citation, ParameterParser params)
{
Schema schema = citation.getSchema();
List fields = schema.getFields();
Iterator fieldIt = fields.iterator();
while(fieldIt.hasNext())
{
Field field = (Field) fieldIt.next();
String name = field.getIdentifier();
if(field.isMultivalued())
{
List values = new Vector();
String count = params.getString(name + "_count");
int num = 10;
try
{
num = Integer.parseInt(count);
for(int i = 0; i < num; i++)
{
String value = params.getString(name + i);
if(value != null && !values.contains(value))
{
values.add(value);
}
}
citation.updateCitationProperty(name, values);
}
catch(NumberFormatException e)
{
}
}
else
{
String value = params.getString(name);
citation.setCitationProperty(name, value);
if(name.equals(Schema.TITLE))
{
citation.setDisplayName(value);
}
}
}
int urlCount = 0;
try
{
urlCount = params.getInt("url_count");
}
catch(Exception e)
{
logger.debug("doCreateCitation: unable to parse int for urlCount");
}
// clear preferredUrl - if there is one, we will find it after looping
// through all customUrls below
citation.setPreferredUrl( null );
String id = null;
for(int i = 0; i < urlCount; i++)
{
String label = params.getString("label_" + i);
String url = params.getString("url_" + i);
String urlid = params.getString("urlid_" + i);
String preferred = params.getString( "pref_" + i );
String addPrefix = params.getString( "addprefix_" + i );
if(url == null)
{
logger.debug("doCreateCitation: url null? " + url);
}
else
{
try
{
url = validateURL(url);
}
catch (MalformedURLException e)
{
logger.debug("doCreateCitation: unable to validate URL: " + url);
continue;
}
}
if(label == null || url == null)
{
logger.debug("doCreateCitation: label null? " + label + " url null? " + url);
continue;
}
else if(urlid == null || urlid.trim().equals(""))
{
id = citation.addCustomUrl(label, url, addPrefix);
if( preferred != null && !preferred.trim().equals( "" ) )
{
// this customUrl is the new preferredUrl
citation.setPreferredUrl( id );
}
}
else
{
// update an existing customUrl
citation.updateCustomUrl(urlid, label, url, addPrefix);
if( preferred != null && !preferred.trim().equals( "" ) )
{
// this customUrl is the new preferredUrl
citation.setPreferredUrl( urlid );
}
}
}
}
/**
*
*/
public void doEdit ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
String citationId = params.getString("citationId");
String collectionId = params.getString("collectionId");
CitationCollection collection = getCitationCollection(state, true);
if(collection == null) {
// error
} else {
Citation citation = null;
try
{
citation = collection.getCitation(citationId);
}
catch (IdUnusedException e)
{
// add an alert (below)
}
if(citation == null)
{
addAlert(state, rb.getString("alert.access"));
}
else
{
state.setAttribute(CitationHelper.CITATION_EDIT_ID, citationId);
state.setAttribute(CitationHelper.CITATION_EDIT_ITEM, citation);
setMode(state, Mode.EDIT);
}
}
} // doEdit
/**
*
*/
public void doList ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
} // doList
public void doResults( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
setMode(state, Mode.RESULTS);
}
/**
*
*/
public void doAddCitations ( RunData data)
{
logger.debug("doAddCitations()");
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
preserveEntityIds(params, state);
//setMode(state, Mode.ADD_CITATIONS);
setMode(state, Mode.NEW_RESOURCE);
logger.debug("doAddCitations()");
} // doAddCitations
public void doMessageFrame(RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
// get params
String citationId = params.getString("citationId");
String collectionId = params.getString("collectionId");
String operation = params.getString("operation");
// check params
if( operation == null )
{
logger.warn( "doMessageFrame() 'operation' null argument" );
setMode(state, Mode.ERROR);
return;
}
if( operation.trim().equalsIgnoreCase( "refreshCount" ) )
{
// do not need to do anything, let buildMessagePanelContext update
// count for citations
setMode( state, Mode.MESSAGE );
return;
}
if( operation == null || citationId == null || collectionId == null )
{
logger.warn( "doMessageFrame() null argument - operation: " +
operation + ", citationId: " + citationId + ", " +
"collectionId: " + collectionId );
setMode(state, Mode.ERROR);
return;
}
// get Citation using citationId
List<Citation> currentResults = (List<Citation>) state.getAttribute(STATE_CURRENT_RESULTS);
Citation citation = null;
for( Citation c : currentResults )
{
if( c.getId().equals( citationId ) )
{
citation = c;
break;
}
}
if( citation == null ) {
logger.warn( "doMessageFrame() bad citationId: " + citationId );
setMode(state, Mode.ERROR);
return;
}
// get CitationCollection using collectionId
CitationCollection collection = getCitationCollection(state, false);
if(collection == null) {
logger.warn( "doMessageFrame() unable to access citationCollection " + collectionId );
} else {
// do operation
if(operation.equalsIgnoreCase("add"))
{
logger.debug("adding citation " + citationId + " to " + collectionId);
citation.setAdded( true );
collection.add( citation );
getCitationService().save(collection);
}
else if(operation.equalsIgnoreCase("remove"))
{
logger.debug("removing citation " + citationId + " from " + collectionId);
collection.remove( citation );
citation.setAdded( false );
getCitationService().save(collection);
}
else
{
// do nothing
logger.debug("null operation: " + operation);
}
// store the citation's new id to send back to UI
state.setAttribute( STATE_CITATION_ID, citation.getId() );
}
setMode(state, Mode.MESSAGE);
}
public void doRemoveAllCitations( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
String collectionId = params.getString("collectionId");
CitationCollection collection = getCitationCollection(state, false);
if(collection == null)
{
// TODO add alert and log error
logger.warn("CitationHelperAction.doRemoveCitation collection null: " + collectionId);
}
else
{
// remove all citations
List<Citation> citations = collection.getCitations();
if( citations != null && citations.size() > 0 )
{
for( Citation citation : citations )
{
collection.remove( citation );
}
getCitationService().save(collection);
}
}
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
} // doRemoveAllCitations
public void doShowReorderCitations( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
setMode(state, Mode.REORDER);
} // doShowReorderCitations
public void doReorderCitations( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
String orderedCitationIds = params.getString("orderedCitationIds");
CitationCollection collection = getCitationCollection(state, false);
String[] splitIds = orderedCitationIds.split(",");
try
{
for(int i = 1;i <= splitIds.length;i++)
{
collection.getCitation(splitIds[i - 1]).setPosition(i);
}
getCitationService().save(collection);
}
catch(IdUnusedException iue)
{
logger.error("One of the supplied citation ids was invalid. The new order was not saved.");
}
// Had to do this to force a reload from storage in buildListPanelContext
state.removeAttribute(STATE_CITATION_COLLECTION);
state.setAttribute(STATE_SORT, CitationCollection.SORT_BY_POSITION);
setMode(state, Mode.NEW_RESOURCE);
} // doReorderCitations
public void doRemoveSelectedCitations( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
String collectionId = params.getString("collectionId");
CitationCollection collection = getCitationCollection(state, false);
if(collection == null)
{
// TODO add alert and log error
logger.warn("doRemoveSelectedCitation() collection null: " + collectionId);
}
else
{
// remove selected citations
String[] paramCitationIds = params.getStrings("citationId");
if( paramCitationIds != null && paramCitationIds.length > 0 )
{
List<String> citationIds = new java.util.ArrayList<String>();
citationIds.addAll(Arrays.asList(paramCitationIds));
try
{
for( String citationId : citationIds )
{
Citation citation = collection.getCitation(citationId);
collection.remove(citation);
}
getCitationService().save(collection);
}
catch( IdUnusedException e )
{
logger.warn("doRemoveSelectedCitation() unable to get and remove citation", e );
}
}
}
state.setAttribute( STATE_LIST_NO_SCROLL, Boolean.TRUE );
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
} // doRemoveSelectedCitations
/**
*
*/
public void doReviseCitation (RunData data)
{
// get the state object and the parameter parser
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
// Set validPropertyNames = getCitationService().getValidPropertyNames();
// String mediatype = params.getString("type");
CitationCollection collection = getCitationCollection(state, false);
if(collection == null)
{
// TODO add alert and log error
}
else
{
String citationId = (String) state.getAttribute(CitationHelper.CITATION_EDIT_ID);
if(citationId != null)
{
try
{
Citation citation = collection.getCitation(citationId);
String schemaId = params.getString("type");
Schema schema = getCitationService().getSchema(schemaId);
citation.setSchema(schema);
updateCitationFromParams(citation, params);
// add citation to current collection
collection.saveCitation(citation);
}
catch (IdUnusedException e)
{
// TODO add alert and log error
}
getCitationService().save(collection);
}
}
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
} // doReviseCitation
/**
*
* @param data
*/
public void doCancelSearch( RunData data )
{
// get state and params
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
// cancel the running search
ActiveSearch search = ( ActiveSearch )state.getAttribute( STATE_SEARCH_INFO );
if( search != null )
{
Thread searchThread = search.getSearchThread();
if( searchThread != null )
{
try
{
searchThread.interrupt();
}
catch( SecurityException se )
{
// not able to interrupt search
logger.warn( "doSearch() [in ThreadGroup "
+ Thread.currentThread().getThreadGroup().getName()
+ "] unable to interrupt search Thread [name="
+ searchThread.getName()
+ ", id=" + searchThread.getId()
+ ", group=" + searchThread.getThreadGroup().getName()
+ "]");
}
}
}
} // doCancelSearch
/**
* Resources Tool/Citation Helper search
* @param data Runtime data
*/
public void doSearch ( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
logger.debug("doSearch()");
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
//doSearchCommon(state, Mode.ADD_CITATIONS);
doSearchCommon(state, Mode.NEW_RESOURCE);
}
/**
* Common "doSearch()" support
* @param state Session state
* @param errorMode Next mode to set if we have database hierarchy problems
*/
protected void doSearchCommon(SessionState state, Mode errorMode)
{
// remove attributes from an old search session, if any
state.removeAttribute( STATE_SEARCH_RESULTS );
state.removeAttribute( STATE_CURRENT_RESULTS );
state.removeAttribute( STATE_KEYWORDS );
// indicate a basic search
state.setAttribute( STATE_BASIC_SEARCH, new Object() );
try
{
SearchDatabaseHierarchy hierarchy = getSearchManager().getSearchHierarchy();
if (hierarchy == null)
{
addAlert(state, rb.getString("search.problem"));
setMode(state, errorMode);
return;
}
state.setAttribute(STATE_SEARCH_HIERARCHY, hierarchy);
setMode(state, Mode.SEARCH);
}
catch (SearchException exception)
{
String error = exception.getMessage();
if ((error == null) || (error.length() == 0))
{
error = rb.getString("search.problem");
}
addAlert(state, error);
setMode(state, Mode.ERROR);
}
}
/**
*
*/
public void doBeginSearch ( RunData data)
{
// get state and params
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
// get search object from state
ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_INFO);
if(search == null)
{
logger.debug( "doBeginSearch() got null ActiveSearch from state." );
search = getSearchManager().newSearch();
}
// get databases selected
String[] databaseIds = params.getStrings( "databasesSelected" );
// check the databases to make sure they are indeed searchable by this user
if( databaseIds != null )
{
if(logger.isDebugEnabled())
{
logger.debug( "Databases selected:" );
for( String databaseId : databaseIds )
{
logger.debug( " " + databaseId );
}
}
SearchDatabaseHierarchy hierarchy =
(SearchDatabaseHierarchy)state.getAttribute(STATE_SEARCH_HIERARCHY);
for( int i = 0; i < databaseIds.length; i++ )
{
if( !hierarchy.isSearchableDatabase( databaseIds[ i ] ) )
{
// TODO collect a list of the databases which are
// not searchable and pass them to the UI
// do not search if databases selected
// are not searchable by this user
state.setAttribute( STATE_UNAUTHORIZED_DB, Boolean.TRUE );
logger.warn( "doBeginSearch() unauthorized database: " + databaseIds[i] );
setMode(state, Mode.RESULTS);
return;
}
}
/*
* Specify which databases should be searched
*/
search.setDatabaseIds(databaseIds);
state.setAttribute( STATE_CURRENT_DATABASES, databaseIds );
}
else
{
// no databases selected, cannot continue
state.setAttribute( STATE_NO_DATABASES, Boolean.TRUE );
setMode(state, Mode.RESULTS);
return;
}
/*
* do basic/advanced search-specific processing
*/
// determine which type of search has been issued
String searchType = params.getString( "searchType" );
if( searchType != null && searchType.equalsIgnoreCase( ActiveSearch.ADVANCED_SEARCH_TYPE ) )
{
doAdvancedSearch( params, state, search );
}
else
{
doBasicSearch( params, state, search );
}
// check for a cancel
String cancel = params.getString( "cancelOp" );
if( cancel != null && !cancel.trim().equals("") )
{
if( cancel.equalsIgnoreCase( ELEMENT_ID_RESULTS_FORM ) )
{
state.setAttribute( STATE_CANCEL_PAGE, Mode.RESULTS );
}
else
{
state.setAttribute( STATE_CANCEL_PAGE, Mode.SEARCH );
}
}
/*
* BEGIN SEARCH
*/
try
{
// set search thread to the current thread
search.setSearchThread( Thread.currentThread() );
state.setAttribute( STATE_SEARCH_INFO, search );
// initiate the search
List latestResults = search.viewPage();
String msg = search.getStatusMessage();
if(msg != null)
{
addAlert(state, msg);
search.setStatusMessage();
}
if( latestResults != null )
{
state.setAttribute(STATE_SEARCH_RESULTS, search);
state.setAttribute(STATE_CURRENT_RESULTS, latestResults);
setMode(state, Mode.RESULTS);
}
}
catch(SearchException se)
{
// either page indices are off or there has been a metasearch error
// do some logging & find the proper alert message
StringBuilder alertMsg = new StringBuilder( se.getMessage() );
logger.warn("doBeginSearch() SearchException: " + alertMsg );
if( search.getStatusMessage() != null && !search.getStatusMessage().trim().equals("") )
{
logger.warn( " |-- nested metasearch error: " + search.getStatusMessage() );
alertMsg.append( " (" + search.getStatusMessage() + ")" );
}
// add an alert and set the next mode
addAlert( state, alertMsg.toString() );
state.setAttribute( STATE_NO_RESULTS, Boolean.TRUE );
setMode(state, Mode.RESULTS);
return;
}
catch( SearchCancelException sce )
{
logger.debug( "doBeginSearch() SearchCancelException: user cancelled search" );
setMode( state, (Mode)state.getAttribute(STATE_CANCEL_PAGE) );
}
ActiveSearch newSearch = getSearchManager().newSearch();
state.setAttribute( STATE_SEARCH_INFO, newSearch );
} // doBeginSearch
/**
* Sets up a basic search.
*
* @param params request parameters from doBeginSearch
* @param state session state
* @param search current search
*/
protected void doBasicSearch( ParameterParser params, SessionState state, ActiveSearch search )
{
// signal a basic search
state.setAttribute( STATE_BASIC_SEARCH, new Object() );
search.setSearchType( ActiveSearch.BASIC_SEARCH_TYPE );
// get keywords
String keywords = params.getString("keywords");
if(keywords == null || keywords.trim().equals(""))
{
logger.warn( "doBasicSearch() getting null/empty keywords" );
}
// set up search query
SearchQuery basicQuery = new org.sakaiproject.citation.util.impl.SearchQuery();
basicQuery.addKeywords( keywords );
// set query for this search
search.setBasicQuery( basicQuery );
// save state
state.setAttribute( STATE_KEYWORDS, keywords );
} // doBasicSearch
/**
* Sets up an advanced search.
*
* @param params request parameters from doBeginSearch
* @param state session state
* @param search current search
*/
protected void doAdvancedSearch( ParameterParser params, SessionState state, ActiveSearch search )
{
// signal an advanced search
state.removeAttribute( STATE_BASIC_SEARCH );
search.setSearchType( ActiveSearch.ADVANCED_SEARCH_TYPE );
// clear old state
AdvancedSearchHelper.clearAdvancedFormState( state );
// set selected fields
AdvancedSearchHelper.setFieldSelections( params, state );
// set entered criteria
AdvancedSearchHelper.setFieldCriteria( params, state );
// get a Map of advancedCritera for the search
search.setAdvancedQuery( AdvancedSearchHelper.getAdvancedCriteria( state ) );
}
/**
*
*/
public void doNextListPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
CitationIterator listIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(listIterator == null)
{
CitationCollection collection = getCitationCollection(state, true);
if(collection == null) {
// error
} else {
listIterator = collection.iterator();
state.setAttribute(STATE_LIST_ITERATOR, listIterator);
}
}
if(listIterator != null && listIterator.hasNextPage())
{
listIterator.nextPage();
}
} // doNextListPage
/**
*
*/
public void doPrevListPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
CitationIterator listIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(listIterator == null)
{
CitationCollection collection = getCitationCollection(state, true);
if(collection == null) {
// error
} else {
listIterator = collection.iterator();
state.setAttribute(STATE_LIST_ITERATOR, listIterator);
}
}
if(listIterator != null && listIterator.hasPreviousPage())
{
listIterator.previousPage();
}
} // doSearch
/**
*
*/
public void doLastListPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
CitationCollection collection = getCitationCollection(state, true);
if(collection == null) {
// error
} else {
CitationIterator listIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(listIterator == null)
{
listIterator = collection.iterator();
state.setAttribute(STATE_LIST_ITERATOR, listIterator);
} else {
int pageSize = listIterator.getPageSize();
int totalSize = collection.size();
int lastPage = 0;
listIterator.setStart(totalSize - pageSize);
}
}
} // doSearch
/**
*
*/
public void doFirstListPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
if(state.getAttribute(CitationHelper.RESOURCE_ID) == null) {
String resourceId = params.get("resourceId");
if(resourceId == null || resourceId.trim().equals("")) {
String resourceUuid = (String) state.getAttribute(CitationHelper.RESOURCE_UUID);
if(resourceUuid == null || resourceUuid.trim().equals("")) {
resourceUuid = params.get("resourceUuid");
}
if(resourceUuid == null || resourceUuid.trim().equals("")) {
// Error? We can't identify resource
} else {
resourceId = this.getContentService().resolveUuid(resourceUuid);
state.setAttribute(CitationHelper.RESOURCE_ID, resourceId);
state.setAttribute(CitationHelper.RESOURCE_UUID, resourceUuid);
}
} else {
state.setAttribute(CitationHelper.RESOURCE_ID, resourceId);
}
}
CitationIterator listIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(listIterator == null)
{
CitationCollection collection = getCitationCollection(state, true);
if(collection == null) {
// error
} else {
listIterator = collection.iterator();
state.setAttribute(STATE_LIST_ITERATOR, listIterator);
}
}
if(listIterator != null) {
listIterator.setStart(0);
}
} // doSearch
/**
*
*/
public void doNextSearchPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS);
if(search == null)
{
search = getSearchManager().newSearch();
}
// search.prepareForNextPage();
try
{
List latestResults = search.viewPage(search.getViewPageNumber() + 1);
String msg = search.getStatusMessage();
if(msg != null)
{
addAlert(state, msg);
search.setStatusMessage();
}
state.setAttribute(STATE_CURRENT_RESULTS, latestResults);
setMode(state, Mode.RESULTS);
}
catch (SearchException e)
{
logger.warn("doNextSearchPage: " + e.getMessage());
addAlert(state, rb.getString( "error.search" ) );
setMode(state, Mode.RESULTS);
}
catch(Exception e)
{
logger.warn("doNextSearchPage: " + e.getMessage());
}
} // doSearch
/**
*
*/
public void doPrevSearchPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS);
if(search == null)
{
search = getSearchManager().newSearch();
}
// search.prepareForNextPage();
try
{
List latestResults = search.viewPage(search.getViewPageNumber() - 1);
String msg = search.getStatusMessage();
if(msg != null)
{
addAlert(state, msg);
search.setStatusMessage();
}
state.setAttribute(STATE_CURRENT_RESULTS, latestResults);
setMode(state, Mode.RESULTS);
}
catch (SearchException e)
{
logger.warn("doPrevSearchPage: " + e.getMessage());
addAlert(state, rb.getString( "error.search" ) );
setMode(state, Mode.RESULTS);
}
catch(Exception e)
{
logger.warn("doPrevSearchPage: " + e.getMessage());
}
} // doSearch
/**
*
*/
public void doFirstSearchPage ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS);
if(search == null)
{
search = getSearchManager().newSearch();
}
// search.prepareForNextPage();
try
{
List latestResults = search.viewPage(0);
String msg = search.getStatusMessage();
if(msg != null)
{
addAlert(state, msg);
search.setStatusMessage();
}
state.setAttribute(STATE_CURRENT_RESULTS, latestResults);
setMode(state, Mode.RESULTS);
}
catch (SearchException e)
{
logger.warn("doFirstSearchPage: " + e.getMessage());
addAlert(state, rb.getString( "error.search" ) );
setMode(state, Mode.RESULTS);
}
catch(Exception e)
{
logger.warn("doFirstSearchPage: " + e.getMessage());
}
} // doSearch
/**
*
*/
public void doChangeSearchPageSize ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
ActiveSearch search = (ActiveSearch) state.getAttribute(STATE_SEARCH_RESULTS);
if(search == null)
{
search = getSearchManager().newSearch();
state.setAttribute(STATE_SEARCH_RESULTS, search);
}
// search.prepareForNextPage();
// check for top or bottom page selector
String pageSelector = params.get( "pageSelector" );
int pageSize;
if( pageSelector.equals( "top" ) )
{
pageSize = params.getInt( "pageSizeTop" );
}
else
{
pageSize = params.getInt("pageSizeBottom");
}
if(pageSize > 0)
{
// use the new value
}
else
{
// use the old value
pageSize = search.getViewPageSize();
}
state.setAttribute(STATE_RESULTS_PAGE_SIZE, new Integer(pageSize));
try
{
int last = search.getLastRecordIndex();
int page = (last - 1)/pageSize;
search.setViewPageSize(pageSize);
List latestResults = search.viewPage(page);
String msg = search.getStatusMessage();
if(msg != null)
{
addAlert(state, msg);
search.setStatusMessage();
}
state.setAttribute(STATE_CURRENT_RESULTS, latestResults);
setMode(state, Mode.RESULTS);
}
catch (SearchException e)
{
logger.warn("doChangeSearchPageSize: " + e.getMessage());
addAlert(state, rb.getString( "error.search" ) );
setMode(state, Mode.RESULTS);
}
catch(Exception e)
{
logger.warn("doChangeSearchPageSize: " + e.getMessage());
}
} // doChangeSearchPageSize
/**
*
*/
public void doChangeListPageSize ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
int pageSize = params.getInt( "newPageSize" );
if(pageSize < 1) {
// check for top or bottom page selector
String pageSelector = params.get( "pageSelector" );
if( pageSelector.equals( "top" ) )
{
pageSize = params.getInt( "pageSizeTop" );
}
else
{
pageSize = params.getInt("pageSizeBottom");
}
}
if(pageSize > 0)
{
state.setAttribute(STATE_LIST_PAGE_SIZE, new Integer(pageSize));
CitationIterator tempIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
tempIterator.setPageSize(pageSize);
state.removeAttribute(STATE_LIST_ITERATOR);
state.setAttribute(STATE_LIST_ITERATOR, tempIterator);
}
} // doSearch
/**
*
*/
public void doView ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
String citationId = params.getString("citationId");
String collectionId = params.getString("collectionId");
CitationCollection collection = getCitationCollection(state, false);
if(collection == null)
{
addAlert(state, rb.getString("alert.access"));
}
else
{
Citation citation = null;
try
{
citation = collection.getCitation(citationId);
}
catch (IdUnusedException e)
{
// add an alert (below)
}
if(citation == null)
{
addAlert(state, rb.getString("alert.access"));
}
else
{
state.setAttribute(CitationHelper.CITATION_VIEW_ID, citationId);
state.setAttribute(CitationHelper.CITATION_VIEW_ITEM, citation);
setMode(state, Mode.VIEW);
}
}
} // doView
/**
* This method is used to ensure the Citations Helper is not invoked by
* the Resources tool in a state other than ADD_CITATIONS or LIST. It uses
* a simple state machine to accomplish this
*
* @return the Mode that the Citations Helper should be in
*/
protected Mode validateState()
{
return null;
}
/**
* This method is called upon each Citations Helper request to properly
* initialize the Citations Helper in case of a null Mode. Returns true if
* succeeded, false otherwise
*
* @param state
*/
protected boolean initHelper(SessionState state)
{
logger.info("initHelper()");
Mode mode;
/*
* Editor Integration support
*/
if (getCaller(state) == Caller.EDITOR_INTEGRATION)
{
mode = (Mode) state.getAttribute(CitationHelper.STATE_HELPER_MODE);
if (mode == null)
{
logger.debug("initHelper(): mode is undefined, using " + Mode.NEW_RESOURCE);
setMode(state, Mode.NEW_RESOURCE);
}
if (state.getAttribute(STATE_RESULTS_PAGE_SIZE) == null)
{
logger.debug("initHelper(): result page size is undefined, using "
+ DEFAULT_RESULTS_PAGE_SIZE);
state.setAttribute(STATE_RESULTS_PAGE_SIZE, DEFAULT_RESULTS_PAGE_SIZE);
}
return true;
}
/*
* Resources Tool support
*/
ToolSession toolSession = getSessionManager().getCurrentToolSession();
ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE);
// TODO: if not entering as a helper, will we need to create pipe???
if (pipe == null)
{
logger.warn( "initHelper() pipe = null");
setMode(state, Mode.ERROR_FATAL);
return true;
}
if(pipe.isActionCompleted())
{
return true;
}
/*
* Resources Tool/Citation Helper support
*/
if( toolSession.getAttribute(CitationHelper.CITATION_HELPER_INITIALIZED) == null )
{
// we're starting afresh: an action has been clicked in Resources
// set the Mode according to our action
switch(pipe.getAction().getActionType())
{
//case CREATE:
case CREATE_BY_HELPER:
// ContentResource tempResource = createTemporaryResource(pipe);
//
// // tempResource could be null if exception encountered
// if( tempResource == null )
// {
// // leave helper
// pipe.setActionCompleted( true );
// toolSession.setAttribute(ResourceToolAction.DONE, Boolean.TRUE);
// toolSession.removeAttribute(CitationHelper.CITATION_HELPER_INITIALIZED);
// cleanup( toolSession, CitationHelper.CITATION_PREFIX, state);
//
// return false;
// }
// state.setAttribute(CitationHelper.RESOURCE_ID, tempResource.getId());
//
// String displayName = tempResource.getProperties().getProperty( org.sakaiproject.entity.api.ResourceProperties.PROP_DISPLAY_NAME );
// state.setAttribute( STATE_COLLECTION_TITLE , displayName );
//
// try
// {
// state.setAttribute(STATE_COLLECTION_ID, new String(tempResource.getContent()));
// }
// catch (ServerOverloadException e)
// {
// logger.warn("ServerOverloadException ", e);
// }
state.setAttribute( STATE_RESOURCES_ADD, Boolean.TRUE );
//setMode(state, Mode.ADD_CITATIONS);
setMode(state, Mode.NEW_RESOURCE);
break;
case REVISE_CONTENT:
state.setAttribute(CitationHelper.RESOURCE_ID, pipe.getContentEntity().getId());
try
{
state.setAttribute(STATE_CITATION_COLLECTION_ID, new String(((ContentResource) pipe.getContentEntity()).getContent()));
}
catch (ServerOverloadException e)
{
logger.warn("ServerOverloadException ", e);
}
state.removeAttribute( STATE_RESOURCES_ADD );
setMode(state, Mode.NEW_RESOURCE);
break;
default:
break;
}
// set Citations Helper to "initialized"
//pipe.setInitializationId( "initialized" );
toolSession.setAttribute(CitationHelper.CITATION_HELPER_INITIALIZED, Boolean.toString(true));
}
else
{
// we're in the middle of a Citations Helper workflow:
// Citations Helper has been "initialized"
// (pipe.initializationId != null)
// make sure we have a Mode to display
mode = (Mode) state.getAttribute(CitationHelper.STATE_HELPER_MODE);
if( mode == null )
{
// default to ADD_CITATIONS
//setMode( state, Mode.ADD_CITATIONS );
setMode( state, Mode.NEW_RESOURCE );
}
}
if(state.getAttribute(STATE_RESULTS_PAGE_SIZE) == null)
{
state.setAttribute(STATE_RESULTS_PAGE_SIZE, DEFAULT_RESULTS_PAGE_SIZE);
}
if(state.getAttribute(STATE_LIST_PAGE_SIZE) == null)
{
state.setAttribute(STATE_LIST_PAGE_SIZE, defaultListPageSize);
}
return true;
} // initHelper
/**
*
* @param pipe
* @return
*/
protected ContentResource createTemporaryResource(ResourceToolActionPipe pipe)
{
try
{
ContentResourceEdit newItem = getContentService().addResource(pipe.getContentEntity().getId(), rb.getString("new.citations.list"), null, ContentHostingService.MAXIMUM_ATTEMPTS_FOR_UNIQUENESS);
newItem.setResourceType(getCitationService().CITATION_LIST_ID);
newItem.setContentType( ResourceType.MIME_TYPE_HTML );
//newItem.setHidden();
ResourcePropertiesEdit props = newItem.getPropertiesEdit();
// set the alternative_reference to point to reference_root for CitationService
props.addProperty(getContentService().PROP_ALTERNATE_REFERENCE, CitationService.REFERENCE_ROOT);
props.addProperty(ResourceProperties.PROP_CONTENT_TYPE, ResourceType.MIME_TYPE_HTML);
props.addProperty(getCitationService().PROP_TEMPORARY_CITATION_LIST, Boolean.TRUE.toString());
CitationCollection collection = getCitationService().addCollection();
newItem.setContent(collection.getId().getBytes());
newItem.setContentType(ResourceType.MIME_TYPE_HTML);
getContentService().commitResource(newItem, NotificationService.NOTI_NONE);
return newItem;
}
catch (PermissionException e)
{
logger.warn("PermissionException ", e);
}
catch (IdUniquenessException e)
{
logger.warn("IdUniquenessException ", e);
}
catch (IdLengthException e)
{
logger.warn("IdLengthException ", e);
}
catch (IdInvalidException e)
{
logger.warn("IdInvalidException ", e);
}
catch (IdUnusedException e)
{
logger.warn("IdUnusedException ", e);
}
catch (OverQuotaException e)
{
logger.warn( e.getMessage() );
// send an error back to Resources
pipe.setErrorEncountered( true );
pipe.setErrorMessage( rb.getString( "action.create.quota" ) );
}
catch (ServerOverloadException e)
{
logger.warn("ServerOverloadException ", e);
}
return null;
}
protected String validateURL(String url) throws MalformedURLException
{
if (url == null || url.trim().equals (""))
{
throw new MalformedURLException();
}
url = url.trim();
// does this URL start with a transport?
if (url.indexOf ("://") == -1)
{
// if it's missing the transport, add http://
url = "http://" + url;
}
// valid protocol?
try
{
// test to see if the input validates as a URL.
// Checks string for format only.
URL u = new URL(url);
}
catch (MalformedURLException e1)
{
try
{
Pattern pattern = Pattern.compile("\\s*([a-zA-Z0-9]+)://([^\\n]+)");
Matcher matcher = pattern.matcher(url);
if(matcher.matches())
{
// if URL has "unknown" protocol, check remaider with
// "http" protocol and accept input it that validates.
URL test = new URL("http://" + matcher.group(2));
}
else
{
throw e1;
}
}
catch (MalformedURLException e2)
{
throw e1;
}
}
return url;
}
public static class QuotedTextValidator
{
/**
* Return a string for insertion in a quote in an HTML tag (as the value of an element's attribute.
*
* @param string
* The string to escape.
* @return the escaped string.
*/
public static String escapeQuotedString(String string)
{
if (string == null) return "";
string = string.trim();
try
{
// convert the string to bytes in UTF-8
byte[] bytes = string.getBytes("UTF-8");
StringBuilder buf = new StringBuilder();
for (int i = 0; i < bytes.length; i++)
{
byte b = bytes[i];
if (b == '"')
{
buf.append("\\\"");
}
else if(b == '\\')
{
buf.append("\\\\");
}
else
{
buf.append((char) b);
}
}
String rv = buf.toString();
return rv;
}
catch (Exception e)
{
return string;
}
} // escapeQuotedString
/**
* Return a string that is safe to place into a JavaScript value wrapped
* in single quotes. In addition, all double quotes (") are replaced by
* the entity <i>"</i>.
*
* @param string The original string
* @return The [possibly] escaped string
*/
public static String escapeHtmlAndJsQuoted(String string)
{
String escapedText = getFormattedText().escapeJsQuoted(string);
return escapedText.replaceAll("\"", """);
}
}
/**
* Cleans up tool state used internally. Useful before leaving helper mode.
*
* @param toolSession
* @param prefix
*/
protected void cleanup(ToolSession toolSession, String prefix,
SessionState sessionState )
{
// cleanup everything dealing with citations
Enumeration attributeNames = toolSession.getAttributeNames();
while(attributeNames.hasMoreElements())
{
String aName = (String) attributeNames.nextElement();
if(aName.startsWith(prefix))
{
toolSession.removeAttribute(aName);
}
}
// re-enable observers
VelocityPortletPaneledAction.enableObservers(sessionState);
}
public void doSortCollection( RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
String collectionId = params.getString("collectionId");
String sort = params.getString("currentSort");
if(sort == null || sort.trim().equals("")) {
sort = CitationCollection.SORT_BY_TITLE;
}
CitationCollection collection = null;
if(collectionId == null)
{
collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
}
logger.debug("doSortCollection sort type = " + sort);
collection = getCitationCollection(state, false);
if(collection == null)
{
// TODO add alert and log error
logger.warn("doSortCollection() collection null: " + collectionId);
}
else
{
// sort the citation list
logger.debug("doSortCollection() ready to sort");
if (sort.equalsIgnoreCase(CitationCollection.SORT_BY_TITLE))
collection.setSort(CitationCollection.SORT_BY_TITLE, true);
else if (sort.equalsIgnoreCase(CitationCollection.SORT_BY_AUTHOR))
collection.setSort(CitationCollection.SORT_BY_AUTHOR, true);
else if (sort.equalsIgnoreCase(CitationCollection.SORT_BY_YEAR))
collection.setSort(CitationCollection.SORT_BY_YEAR , true);
else if (sort.equalsIgnoreCase(CitationCollection.SORT_BY_POSITION))
collection.setSort(CitationCollection.SORT_BY_POSITION , true);
state.setAttribute(STATE_SORT, sort);
Iterator iter = collection.iterator();
while (iter.hasNext())
{
Citation tempCit = (Citation) iter.next();
logger.debug("doSortCollection() tempcit 1 -------------");
logger.debug("doSortCollection() tempcit 1 (author) = " + tempCit.getFirstAuthor());
logger.debug("doSortCollection() tempcit 1 (year) = " + tempCit.getYear());
logger.debug("doSortCollection() tempcit 1 = " + tempCit.getDisplayName());
} // end while
// set the list iterator to the start of the list after a change in sort
CitationIterator listIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(listIterator != null)
{
listIterator.setStart(0);
}
} // end else
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
} // doSortCollection
public void doSaveCollection(RunData data )
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters();
int requestStateId = params.getInt("requestStateId", 0);
restoreRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX}, requestStateId);
String collectionId = params.getString("collectionId");
CitationCollection collection = null;
if(collectionId == null)
{
collectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
}
collection = getCitationCollection(state, false);
if(collection == null)
{
// TODO add alert and log error
logger.warn("doSaveCollection() collection null: " + collectionId);
return;
}
else
{
// save the collection (this will persist the sort order to the db)
getCitationService().save(collection);
String sort = collection.getSort();
if (sort != null)
state.setAttribute(STATE_SORT, sort);
//setMode(state, Mode.LIST);
setMode(state, Mode.NEW_RESOURCE);
}
} // end doSaveCollection
public class CitationListSecurityAdviser implements SecurityAdvisor
{
String userId;
String function;
String reference;
public CitationListSecurityAdviser(String userId, String function, String reference)
{
super();
this.userId = userId;
this.function = function;
this.reference = reference;
}
public SecurityAdvice isAllowed(String userId, String function, String reference)
{
SecurityAdvice advice = SecurityAdvice.PASS;
if((this.userId == null || this.userId.equals(userId)) && (this.function == null || this.function.equals(function)) || (this.reference == null || this.reference.equals(reference)))
{
advice = SecurityAdvice.ALLOWED;
}
return advice;
}
}
// temporary -- replace with a method in content-util
public static int preserveRequestState(SessionState state, String[] prefixes)
{
Map requestState = new HashMap();
int requestStateId = 0;
while(requestStateId == 0)
{
requestStateId = (int) (Math.random() * Integer.MAX_VALUE);
}
List<String> attrNames = state.getAttributeNames();
for(String attrName : attrNames)
{
for(String prefix : prefixes)
{
if(attrName.startsWith(prefix))
{
requestState.put(attrName,state.getAttribute(attrName));
break;
}
}
}
Object pipe = state.getAttribute(ResourceToolAction.ACTION_PIPE);
if(pipe != null)
{
requestState.put(ResourceToolAction.ACTION_PIPE, pipe);
}
Tool tool = getToolManager().getCurrentTool();
Object url = state.getAttribute(tool.getId() + Tool.HELPER_DONE_URL);
if( url != null)
{
requestState.put(tool.getId() + Tool.HELPER_DONE_URL, url);
}
state.setAttribute(CitationHelper.RESOURCES_SYS_PREFIX + requestStateId, requestState);
logger.debug("preserveRequestState() requestStateId == " + requestStateId + "\n" + requestState);
return requestStateId;
}
// temporary -- replace with a value in content-util or content-api
public static void restoreRequestState(SessionState state, String[] prefixes, int requestStateId)
{
Map<String, String> requestState = (Map<String, String>) state.removeAttribute(CitationHelper.RESOURCES_SYS_PREFIX + requestStateId);
logger.debug("restoreRequestState() requestStateId == " + requestStateId + "\n" + requestState);
if(requestState != null)
{
List<String> attrNames = state.getAttributeNames();
for(String attrName : attrNames)
{
for(String prefix : prefixes)
{
if(attrName.startsWith(prefix))
{
state.removeAttribute(attrName);
break;
}
}
}
for(Map.Entry<String, String> entry : requestState.entrySet())
{
state.setAttribute(entry.getKey(), entry.getValue());
}
}
}
protected Map<String,Object> getProperties(ContentEntity entity, SessionState state) {
Map<String,Object> props = new HashMap<String,Object>();
ResourceProperties properties = entity.getProperties();
Reference ref = getEntityManager().newReference(entity.getReference());
DateFormat df = DateFormat.getDateTimeInstance();
// isHidden
props.put(PROP_IS_HIDDEN, new Boolean(entity.isHidden()));
// releaseDate, useReleaseDate
Date releaseDate = null;
if(entity.getReleaseDate() == null) {
releaseDate = new Date(System.currentTimeMillis());
props.put(PROP_USE_RELEASE_DATE, Boolean.FALSE);
} else {
releaseDate = new Date(entity.getReleaseDate().getTime());
props.put(PROP_USE_RELEASE_DATE, Boolean.TRUE);
}
props.put(PROP_RELEASE_DATE_STR, df.format(releaseDate));
props.put(PROP_RELEASE_DATE, releaseDate);
// retractDate, useRetractDate
Date retractDate = null;
if(entity.getRetractDate() == null) {
retractDate = new Date(System.currentTimeMillis() + ONE_WEEK);
props.put(PROP_USE_RETRACT_DATE, Boolean.FALSE);
} else {
retractDate = new Date(entity.getRetractDate().getTime());
props.put(PROP_USE_RETRACT_DATE, Boolean.TRUE);
}
props.put(PROP_RETRACT_DATE_STR, df.format(retractDate));
props.put(PROP_RETRACT_DATE, retractDate);
// isCollection
props.put(PROP_IS_COLLECTION, entity.isCollection());
// isDropbox
props.put(PROP_IS_DROPBOX, new Boolean(getContentService().isInDropbox(entity.getId())));
// isSiteCollection
props.put(PROP_IS_SITE_COLLECTION, new Boolean(ref.getContext() != null && ref.getContext().equals(entity.getId())));
// isPubview
props.put(PROP_IS_PUBVIEW, getContentService().isPubView(entity.getId()));
// isPubviewInherited
props.put(PROP_IS_PUBVIEW_INHERITED, new Boolean(getContentService().isInheritingPubView(entity.getId())));
// isPubviewPossible
Boolean preventPublicDisplay = (Boolean) state.getAttribute("resources.request.prevent_public_display");
if(preventPublicDisplay == null) {
preventPublicDisplay = Boolean.FALSE;
}
props.put(PROP_IS_PUBVIEW_POSSIBLE, new Boolean(! preventPublicDisplay.booleanValue()));
// accessMode
AccessMode accessMode = entity.getAccess();
props.put(PROP_ACCESS_MODE, accessMode);
// isGroupInherited
props.put(PROP_IS_GROUP_INHERITED, AccessMode.GROUPED == entity.getInheritedAccess());
SiteService siteService = (SiteService) ComponentManager.get(SiteService.class);
Set<String> currentGroups = new TreeSet<String>();
if(AccessMode.GROUPED == accessMode) {
for(Group gr : (Collection<Group>) entity.getGroupObjects()) {
currentGroups.add(gr.getId());
}
}
// possibleGroups
Collection<Group> inheritedGroupObjs = null;
if(entity.getInheritedAccess() == AccessMode.GROUPED) {
inheritedGroupObjs = entity.getInheritedGroupObjects();
} else {
try {
Site site = siteService.getSite(ref.getContext());
inheritedGroupObjs = site.getGroups();
} catch (IdUnusedException e) {
logger.warn("IdUnusedException in getProperties() " + e);
}
}
List<Map<String,String>> groups = new ArrayList<Map<String,String>>();
if(inheritedGroupObjs != null) {
Collection<Group> groupsWithRemovePermission = null;
if(AccessMode.GROUPED == accessMode)
{
groupsWithRemovePermission = contentService.getGroupsWithRemovePermission(entity.getId());
String container = ref.getContainer();
if(container != null)
{
Collection<Group> more = contentService.getGroupsWithRemovePermission(container);
if(more != null && ! more.isEmpty())
{
groupsWithRemovePermission.addAll(more);
}
}
} else if(AccessMode.GROUPED == entity.getInheritedAccess()) {
groupsWithRemovePermission = contentService.getGroupsWithRemovePermission(ref.getContainer());
}
else if(ref.getContext() != null && contentService.getSiteCollection(ref.getContext()) != null)
{
groupsWithRemovePermission = contentService.getGroupsWithRemovePermission(contentService.getSiteCollection(ref.getContext()));
}
Set<String> idsOfGroupsWithRemovePermission = new TreeSet<String>();
if(groupsWithRemovePermission != null) {
for(Group gr : groupsWithRemovePermission) {
idsOfGroupsWithRemovePermission.add(gr.getId());
}
}
for(Group group : inheritedGroupObjs) {
Map<String, String> grp = new HashMap<String, String>();
grp.put("groupId", group.getId());
grp.put("title", group.getTitle());
grp.put("description", group.getDescription());
grp.put("entityRef", group.getReference());
if(currentGroups.contains(group.getId())) {
grp.put("isLocal", Boolean.toString(true));
}
if(idsOfGroupsWithRemovePermission.contains(group.getId())) {
grp.put("allowedRemove", Boolean.toString(true));
}
groups.add(grp);
}
}
props.put(PROP_POSSIBLE_GROUPS, groups);
// isGroupPossible
props.put(PROP_IS_GROUP_POSSIBLE, new Boolean(groups != null && groups.size() > 0));
// isSingleGroupInherited
props.put(PROP_IS_SINGLE_GROUP_INHERITED, new Boolean(groups != null && groups.size() == 1));
// isSiteOnly = ! isPubviewPossible && ! isGroupPossible
props.put(PROP_IS_SITE_ONLY, new Boolean(preventPublicDisplay.booleanValue() && (groups == null || groups.size() < 1)));
// isUserSite
props.put(PROP_IS_USER_SITE, siteService.isUserSite(ref.getContext()));
// getSelectedConditionKey
// getSubmittedResourceFilter
// isUseConditionalRelease
state.setAttribute(STATE_RESOURCE_ENTITY_PROPERTIES, props);
return props;
}
protected CitationService getCitationService() {
if(this.citationService == null) {
this.citationService = (CitationService) ComponentManager.get(CitationService.class);
}
return this.citationService;
}
protected ConfigurationService getConfigurationService() {
if(this.configurationService == null) {
this.configurationService = (ConfigurationService) ComponentManager.get(ConfigurationService.class);
}
return this.configurationService;
}
protected SearchManager getSearchManager() {
if(this.searchManager == null) {
this.searchManager = (SearchManager) ComponentManager.get(SearchManager.class);
}
return this.searchManager;
}
protected ContentHostingService getContentService() {
if(this.contentService == null) {
this.contentService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService");
}
return this.contentService;
}
protected EntityManager getEntityManager() {
if(this.entityManager == null) {
this.entityManager = (EntityManager) ComponentManager.get(EntityManager.class);
}
return this.entityManager;
}
protected SessionManager getSessionManager() {
if(this.sessionManager == null) {
this.sessionManager = (SessionManager) ComponentManager.get(SessionManager.class);
}
return this.sessionManager;
}
protected static ToolManager getToolManager() {
if(toolManager == null) {
toolManager = (ToolManager) ComponentManager.get(ToolManager.class);
}
return toolManager;
}
protected static FormattedText getFormattedText() {
if(formattedText == null) {
formattedText = (FormattedText) ComponentManager.get(FormattedText.class);
}
return formattedText;
}
} // class CitationHelperAction
| true | true | public String buildNewResourcePanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state) {
logger.debug("buildNewResourcePanelContext()");
context.put("MIMETYPE_JSON", MIMETYPE_JSON);
context.put("REQUESTED_MIMETYPE", REQUESTED_MIMETYPE);
context.put("xilator", new Validator());
context.put("availability_is_enabled", Boolean.TRUE);
context.put("GROUP_ACCESS", AccessMode.GROUPED);
context.put("INHERITED_ACCESS", AccessMode.INHERITED);
Boolean resourceAdd = (Boolean) state.getAttribute(STATE_RESOURCES_ADD);
if(resourceAdd != null && resourceAdd.equals(true)) {
context.put("resourceAdd", Boolean.TRUE);
context.put(CITATION_ACTION, CREATE_RESOURCE);
} else {
context.put(CITATION_ACTION, UPDATE_RESOURCE);
}
// resource-related
String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
String resourceUuid = (String) state.getAttribute(CitationHelper.RESOURCE_UUID);
if(resourceId == null || resourceId.trim().equals("")) {
if(resourceUuid == null || resourceUuid.trim().equals("")) {
// Will be dealt with later by creating new resource when needed
} else if(resourceUuid.startsWith("/")) {
// UUID and ID may be switched
resourceId = resourceUuid;
resourceUuid = this.getContentService().getUuid(resourceId);
if(resourceUuid != null) {
state.setAttribute(CitationHelper.RESOURCE_ID, resourceId);
state.setAttribute(CitationHelper.RESOURCE_UUID, resourceUuid);
}
} else {
// see if we can get the resourceId from the UUID
resourceId = this.getContentService().resolveUuid(resourceUuid);
if(resourceId != null) {
state.setAttribute(CitationHelper.RESOURCE_ID, resourceId);
}
}
} else if(resourceUuid == null || resourceUuid.trim().equals("")) {
resourceUuid = this.getContentService().getUuid(resourceId);
if(resourceUuid != null) {
state.setAttribute(CitationHelper.RESOURCE_UUID, resourceUuid);
}
}
if(logger.isInfoEnabled()) {
logger.info("buildNewResourcePanelContext() resourceUuid == " + resourceUuid + " resourceId == " + resourceId);
}
String citationCollectionId = null;
ContentResource resource = null;
Map<String,Object> contentProperties = null;
if(resourceId == null) {
} else {
try {
resource = getContentService().getResource(resourceId);
} catch (IdUnusedException e) {
logger.warn("IdUnusedException geting resource in buildNewResourcePanelContext() " + e);
} catch (TypeException e) {
logger.warn("TypeException geting resource in buildNewResourcePanelContext() " + e);
} catch (PermissionException e) {
logger.warn("PermissionException geting resource in buildNewResourcePanelContext() " + e);
}
// String guid = getContentService().getUuid(resourceId);
// context.put("RESOURCE_ID", guid);
}
if(resource == null) {
context.put(CITATION_ACTION, CREATE_RESOURCE);
ToolSession toolSession = getSessionManager().getCurrentToolSession();
ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE);
String collectionId = pipe.getContentEntity().getId();
context.put("collectionId", collectionId);
ContentCollection collection;
try {
collection = getContentService().getCollection(collectionId);
contentProperties = this.getProperties(collection, state);
} catch (IdUnusedException e) {
logger.warn("IdUnusedException geting collection in buildNewResourcePanelContext() " + e);
} catch (TypeException e) {
logger.warn("TypeException geting collection in buildNewResourcePanelContext() " + e);
} catch (PermissionException e) {
logger.warn("PermissionException geting collection in buildNewResourcePanelContext() " + e);
}
} else {
ResourceProperties props = resource.getProperties();
contentProperties = this.getProperties(resource, state);
context.put("resourceTitle", props.getProperty(ResourceProperties.PROP_DISPLAY_NAME));
context.put("resourceDescription", props.getProperty(ResourceProperties.PROP_DESCRIPTION));
//resourceUuid = this.getContentService().getUuid(resourceId);
context.put("resourceUuid", resourceUuid );
context.put("collectionId", resource.getContainingCollection().getId());
try {
citationCollectionId = new String(resource.getContent());
} catch (ServerOverloadException e) {
logger.warn("ServerOverloadException geting props in buildNewResourcePanelContext() " + e);
}
context.put(CITATION_ACTION, UPDATE_RESOURCE);
}
if(contentProperties == null) {
contentProperties = new HashMap<String,Object>();
}
context.put("contentProperties", contentProperties);
int collectionSize = 0;
CitationCollection citationCollection = null;
if(citationCollectionId == null) {
citationCollectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
//String citationCollectionId = (String) state.getAttribute(CitationHelper.CITATION_COLLECTION_ID);
}
if(citationCollectionId == null) {
} else {
citationCollection = getCitationCollection(state, true);
if(citationCollection == null) {
logger.warn( "buildAddCitationsPanelContext unable to access citationCollection " + citationCollectionId );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_ERROR;
} else {
// get the size of the list
collectionSize = citationCollection.size();
}
context.put("collectionId", citationCollectionId);
}
context.put( "collectionSize", new Integer( collectionSize ) );
Locale locale = rb.getLocale();
List<Map<String,String>> saveciteClients = getConfigurationService().getSaveciteClientsForLocale(locale);
if(saveciteClients != null) {
if(resource != null && resourceId != null) {
for(Map<String,String> client : saveciteClients) {
String saveciteUrl = getSearchManager().getSaveciteUrl(resourceUuid,client.get("id"));
try {
client.put("saveciteUrl", java.net.URLEncoder.encode(saveciteUrl,"UTF-8"));
} catch (UnsupportedEncodingException e) {
logger.warn("Error encoding savecite URL",e);
}
}
}
context.put("saveciteClients",saveciteClients);
}
// determine which features to display
if( getConfigurationService().isGoogleScholarEnabled() ) {
String googleUrl = getSearchManager().getGoogleScholarUrl(getContentService().getUuid(resourceId));
context.put( "googleUrl", googleUrl );
// object array for formatted messages
Object[] googleArgs = { rb.getString( "linkLabel.google" ) };
context.put( "googleArgs", googleArgs );
}
if( getConfigurationService().librarySearchEnabled() ) {
context.put( "searchLibrary", Boolean.TRUE );
}
if(citationCollection == null || citationCollection.size() <= 0) {
} else {
context.put("openUrlLabel", getConfigurationService().getSiteConfigOpenUrlLabel());
String currentSort = (String) state.getAttribute(STATE_SORT);
if (currentSort == null || currentSort.trim().length() == 0)
currentSort = citationCollection.getSort();
if(currentSort == null || currentSort.trim().length() == 0) {
currentSort = CitationCollection.SORT_BY_TITLE;
}
context.put("currentSort", currentSort);
String savedSort = citationCollection.getSort();
if(savedSort == null || savedSort.trim().equals("")) {
savedSort = CitationCollection.SORT_BY_TITLE;
}
if(savedSort != currentSort) {
citationCollection.setSort(currentSort, true);
}
//context.put(PARAM_FORM_NAME, ELEMENT_ID_LIST_FORM);
// collection size
context.put( "collectionSize", new Integer( citationCollection.size() ) );
// export URLs
String exportUrlSel = citationCollection.getUrl(CitationService.REF_TYPE_EXPORT_RIS_SEL);
String exportUrlAll = citationCollection.getUrl(CitationService.REF_TYPE_EXPORT_RIS_ALL);
context.put("exportUrlSel", exportUrlSel);
context.put("exportUrlAll", exportUrlAll);
Integer listPageSize = (Integer) state.getAttribute(STATE_LIST_PAGE_SIZE);
if(listPageSize == null)
{
listPageSize = defaultListPageSize;
state.setAttribute(STATE_LIST_PAGE_SIZE, listPageSize);
}
context.put("listPageSize", listPageSize);
CitationIterator newIterator = citationCollection.iterator();
CitationIterator oldIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(oldIterator != null)
{
newIterator.setPageSize(listPageSize.intValue());
newIterator.setStart(oldIterator.getStart());
// newIterator.setPage(oldIterator.getPage());
}
context.put("citations", newIterator);
context.put("citationCollectionId", citationCollection.getId());
if(! citationCollection.isEmpty())
{
context.put("show_citations", Boolean.TRUE);
// int page = newIterator.getPage();
// int pageSize = newIterator.getPageSize();
int totalSize = citationCollection.size();
int start = newIterator.getStart();
int end = newIterator.getEnd();
// int start = page * pageSize + 1;
// int end = Math.min((page + 1) * pageSize, totalSize);
Integer[] position = { new Integer(start+1) , new Integer(end), new Integer(totalSize)};
String showing = (String) rb.getFormattedMessage("showing.results", position);
context.put("showing", showing);
}
state.setAttribute(STATE_LIST_ITERATOR, newIterator);
// constant schema identifier
context.put( "titleProperty", Schema.TITLE );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
}
return TEMPLATE_NEW_RESOURCE;
}
| public String buildNewResourcePanelContext(VelocityPortlet portlet, Context context, RunData rundata, SessionState state) {
logger.debug("buildNewResourcePanelContext()");
context.put("MIMETYPE_JSON", MIMETYPE_JSON);
context.put("REQUESTED_MIMETYPE", REQUESTED_MIMETYPE);
context.put("xilator", new Validator());
context.put("availability_is_enabled", Boolean.TRUE);
context.put("GROUP_ACCESS", AccessMode.GROUPED);
context.put("INHERITED_ACCESS", AccessMode.INHERITED);
Boolean resourceAdd = (Boolean) state.getAttribute(STATE_RESOURCES_ADD);
if(resourceAdd != null && resourceAdd.equals(true)) {
context.put("resourceAdd", Boolean.TRUE);
context.put(CITATION_ACTION, CREATE_RESOURCE);
} else {
context.put(CITATION_ACTION, UPDATE_RESOURCE);
}
// resource-related
String resourceId = (String) state.getAttribute(CitationHelper.RESOURCE_ID);
String resourceUuid = (String) state.getAttribute(CitationHelper.RESOURCE_UUID);
if(resourceId == null || resourceId.trim().equals("")) {
if(resourceUuid == null || resourceUuid.trim().equals("")) {
// Will be dealt with later by creating new resource when needed
} else if(resourceUuid.startsWith("/")) {
// UUID and ID may be switched
resourceId = resourceUuid;
resourceUuid = this.getContentService().getUuid(resourceId);
if(resourceUuid != null) {
state.setAttribute(CitationHelper.RESOURCE_ID, resourceId);
state.setAttribute(CitationHelper.RESOURCE_UUID, resourceUuid);
}
} else {
// see if we can get the resourceId from the UUID
resourceId = this.getContentService().resolveUuid(resourceUuid);
if(resourceId != null) {
state.setAttribute(CitationHelper.RESOURCE_ID, resourceId);
}
}
} else if(resourceUuid == null || resourceUuid.trim().equals("")) {
resourceUuid = this.getContentService().getUuid(resourceId);
if(resourceUuid != null) {
state.setAttribute(CitationHelper.RESOURCE_UUID, resourceUuid);
}
}
if(logger.isInfoEnabled()) {
logger.info("buildNewResourcePanelContext() resourceUuid == " + resourceUuid + " resourceId == " + resourceId);
}
String citationCollectionId = null;
ContentResource resource = null;
Map<String,Object> contentProperties = null;
if(resourceId == null) {
} else {
try {
resource = getContentService().getResource(resourceId);
} catch (IdUnusedException e) {
logger.warn("IdUnusedException geting resource in buildNewResourcePanelContext() " + e);
} catch (TypeException e) {
logger.warn("TypeException geting resource in buildNewResourcePanelContext() " + e);
} catch (PermissionException e) {
logger.warn("PermissionException geting resource in buildNewResourcePanelContext() " + e);
}
// String guid = getContentService().getUuid(resourceId);
// context.put("RESOURCE_ID", guid);
}
if(resource == null) {
context.put(CITATION_ACTION, CREATE_RESOURCE);
ToolSession toolSession = getSessionManager().getCurrentToolSession();
ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE);
String collectionId = pipe.getContentEntity().getId();
context.put("collectionId", collectionId);
ContentCollection collection;
try {
collection = getContentService().getCollection(collectionId);
contentProperties = this.getProperties(collection, state);
} catch (IdUnusedException e) {
logger.warn("IdUnusedException geting collection in buildNewResourcePanelContext() " + e);
} catch (TypeException e) {
logger.warn("TypeException geting collection in buildNewResourcePanelContext() " + e);
} catch (PermissionException e) {
logger.warn("PermissionException geting collection in buildNewResourcePanelContext() " + e);
}
} else {
ResourceProperties props = resource.getProperties();
contentProperties = this.getProperties(resource, state);
context.put("resourceTitle", props.getProperty(ResourceProperties.PROP_DISPLAY_NAME));
context.put("resourceDescription", props.getProperty(ResourceProperties.PROP_DESCRIPTION));
//resourceUuid = this.getContentService().getUuid(resourceId);
context.put("resourceUuid", resourceUuid );
context.put("collectionId", resource.getContainingCollection().getId());
try {
citationCollectionId = new String(resource.getContent());
} catch (ServerOverloadException e) {
logger.warn("ServerOverloadException geting props in buildNewResourcePanelContext() " + e);
}
context.put(CITATION_ACTION, UPDATE_RESOURCE);
}
if(contentProperties == null) {
contentProperties = new HashMap<String,Object>();
}
context.put("contentProperties", contentProperties);
int collectionSize = 0;
CitationCollection citationCollection = null;
if(citationCollectionId == null) {
citationCollectionId = (String) state.getAttribute(STATE_CITATION_COLLECTION_ID);
//String citationCollectionId = (String) state.getAttribute(CitationHelper.CITATION_COLLECTION_ID);
}
if(citationCollectionId == null) {
} else {
citationCollection = getCitationCollection(state, true);
if(citationCollection == null) {
logger.warn( "buildAddCitationsPanelContext unable to access citationCollection " + citationCollectionId );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
return TEMPLATE_ERROR;
} else {
// get the size of the list
collectionSize = citationCollection.size();
}
context.put("collectionId", citationCollectionId);
}
context.put( "collectionSize", new Integer( collectionSize ) );
Locale locale = rb.getLocale();
List<Map<String,String>> saveciteClients = getConfigurationService().getSaveciteClientsForLocale(locale);
if(saveciteClients != null) {
if(resource != null && resourceId != null) {
for(Map<String,String> client : saveciteClients) {
String saveciteUrl = getSearchManager().getSaveciteUrl(resourceUuid,client.get("id"));
try {
client.put("saveciteUrl", java.net.URLEncoder.encode(saveciteUrl,"UTF-8"));
} catch (UnsupportedEncodingException e) {
logger.warn("Error encoding savecite URL",e);
}
}
}
context.put("saveciteClients",saveciteClients);
}
// determine which features to display
if( getConfigurationService().isGoogleScholarEnabled() ) {
String googleUrl = getSearchManager().getGoogleScholarUrl(getContentService().getUuid(resourceId));
context.put( "googleUrl", googleUrl );
// object array for formatted messages
Object[] googleArgs = { rb.getString( "linkLabel.google" ) };
context.put( "googleArgs", googleArgs );
}
if( getConfigurationService().librarySearchEnabled() ) {
context.put( "searchLibrary", Boolean.TRUE );
}
if(citationCollection == null || citationCollection.size() <= 0) {
} else {
context.put("openUrlLabel", getConfigurationService().getSiteConfigOpenUrlLabel());
String currentSort = (String) state.getAttribute(STATE_SORT);
if (currentSort == null || currentSort.trim().length() == 0)
currentSort = citationCollection.getSort();
if(currentSort == null || currentSort.trim().length() == 0) {
currentSort = CitationCollection.SORT_BY_TITLE;
}
context.put("currentSort", currentSort);
String savedSort = citationCollection.getSort();
if(savedSort == null || savedSort.trim().equals("")) {
savedSort = CitationCollection.SORT_BY_TITLE;
}
if(savedSort != currentSort) {
citationCollection.setSort(currentSort, true);
}
//context.put(PARAM_FORM_NAME, ELEMENT_ID_LIST_FORM);
// collection size
context.put( "collectionSize", new Integer( citationCollection.size() ) );
// export URLs
String exportUrlSel = citationCollection.getUrl(CitationService.REF_TYPE_EXPORT_RIS_SEL);
String exportUrlAll = citationCollection.getUrl(CitationService.REF_TYPE_EXPORT_RIS_ALL);
context.put("exportUrlSel", exportUrlSel);
context.put("exportUrlAll", exportUrlAll);
Integer listPageSize = (Integer) state.getAttribute(STATE_LIST_PAGE_SIZE);
if(listPageSize == null)
{
listPageSize = defaultListPageSize;
state.setAttribute(STATE_LIST_PAGE_SIZE, listPageSize);
}
context.put("listPageSize", listPageSize);
CitationIterator newIterator = citationCollection.iterator();
CitationIterator oldIterator = (CitationIterator) state.getAttribute(STATE_LIST_ITERATOR);
if(oldIterator == null) {
newIterator.setPageSize(listPageSize.intValue());
newIterator.setStart(0);
} else {
newIterator.setPageSize(listPageSize.intValue());
newIterator.setStart(oldIterator.getStart());
// newIterator.setPage(oldIterator.getPage());
}
context.put("citations", newIterator);
context.put("citationCollectionId", citationCollection.getId());
if(! citationCollection.isEmpty())
{
context.put("show_citations", Boolean.TRUE);
// int page = newIterator.getPage();
// int pageSize = newIterator.getPageSize();
int totalSize = citationCollection.size();
int start = newIterator.getStart();
int end = newIterator.getEnd();
// int start = page * pageSize + 1;
// int end = Math.min((page + 1) * pageSize, totalSize);
Integer[] position = { new Integer(start+1) , new Integer(end), new Integer(totalSize)};
String showing = (String) rb.getFormattedMessage("showing.results", position);
context.put("showing", showing);
}
state.setAttribute(STATE_LIST_ITERATOR, newIterator);
// constant schema identifier
context.put( "titleProperty", Schema.TITLE );
int requestStateId = preserveRequestState(state, new String[]{CitationHelper.RESOURCES_REQUEST_PREFIX, CitationHelper.CITATION_PREFIX});
context.put("requestStateId", requestStateId);
}
return TEMPLATE_NEW_RESOURCE;
}
|
diff --git a/ingest/src/main/java/org/apache/accumulo/examples/wikisearch/ingest/WikipediaInputFormat.java b/ingest/src/main/java/org/apache/accumulo/examples/wikisearch/ingest/WikipediaInputFormat.java
index 4c6a3b8..e8b8b52 100644
--- a/ingest/src/main/java/org/apache/accumulo/examples/wikisearch/ingest/WikipediaInputFormat.java
+++ b/ingest/src/main/java/org/apache/accumulo/examples/wikisearch/ingest/WikipediaInputFormat.java
@@ -1,129 +1,129 @@
/*
* 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.accumulo.examples.wikisearch.ingest;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.accumulo.examples.wikisearch.reader.AggregatingRecordReader;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
public class WikipediaInputFormat extends TextInputFormat {
public static class WikipediaInputSplit extends InputSplit implements Writable {
public WikipediaInputSplit(){}
public WikipediaInputSplit(FileSplit fileSplit, int partition)
{
this.fileSplit = fileSplit;
this.partition = partition;
}
private FileSplit fileSplit = null;
private int partition = -1;
public int getPartition()
{
return partition;
}
public FileSplit getFileSplit()
{
return fileSplit;
}
@Override
public long getLength() throws IOException, InterruptedException {
return fileSplit.getLength();
}
@Override
public String[] getLocations() throws IOException, InterruptedException {
return fileSplit.getLocations();
}
@Override
public void readFields(DataInput in) throws IOException {
Path file = new Path(in.readUTF());
long start = in.readLong();
long length = in.readLong();
int numHosts = in.readInt();
String[] hosts = new String[numHosts];
for(int i = 0; i < numHosts; i++)
hosts[i] = in.readUTF();
fileSplit = new FileSplit(file, start, length, hosts);
partition = in.readInt();
}
@Override
public void write(DataOutput out) throws IOException {
out.writeUTF(fileSplit.getPath().toString());
out.writeLong(fileSplit.getStart());
out.writeLong(fileSplit.getLength());
String [] hosts = fileSplit.getLocations();
out.writeInt(hosts.length);
for(String host:hosts)
out.writeUTF(host);
fileSplit.write(out);
out.writeInt(partition);
}
}
@Override
public List<InputSplit> getSplits(JobContext job) throws IOException {
List<InputSplit> superSplits = super.getSplits(job);
- List<WikipediaInputSplit> splits = new ArrayList<WikipediaInputSplit>();
+ List<InputSplit> splits = new ArrayList<InputSplit>();
int numGroups = WikipediaConfiguration.getNumGroups(job.getConfiguration());
for(InputSplit split:superSplits)
{
FileSplit fileSplit = (FileSplit)split;
for(int group = 0; group < numGroups; group++)
{
splits.add(new WikipediaInputSplit(fileSplit,group));
}
}
- return super.getSplits(job);
+ return splits;
}
@Override
public RecordReader<LongWritable,Text> createRecordReader(InputSplit split, TaskAttemptContext context) {
return new AggregatingRecordReader();
}
@Override
protected boolean isSplitable(JobContext context, Path file) {
return false;
}
}
| false | true | public List<InputSplit> getSplits(JobContext job) throws IOException {
List<InputSplit> superSplits = super.getSplits(job);
List<WikipediaInputSplit> splits = new ArrayList<WikipediaInputSplit>();
int numGroups = WikipediaConfiguration.getNumGroups(job.getConfiguration());
for(InputSplit split:superSplits)
{
FileSplit fileSplit = (FileSplit)split;
for(int group = 0; group < numGroups; group++)
{
splits.add(new WikipediaInputSplit(fileSplit,group));
}
}
return super.getSplits(job);
}
| public List<InputSplit> getSplits(JobContext job) throws IOException {
List<InputSplit> superSplits = super.getSplits(job);
List<InputSplit> splits = new ArrayList<InputSplit>();
int numGroups = WikipediaConfiguration.getNumGroups(job.getConfiguration());
for(InputSplit split:superSplits)
{
FileSplit fileSplit = (FileSplit)split;
for(int group = 0; group < numGroups; group++)
{
splits.add(new WikipediaInputSplit(fileSplit,group));
}
}
return splits;
}
|
diff --git a/sub/source/net/sourceforge/texlipse/editor/TexSourceViewerConfiguration.java b/sub/source/net/sourceforge/texlipse/editor/TexSourceViewerConfiguration.java
index cf5d209..24bcd7a 100644
--- a/sub/source/net/sourceforge/texlipse/editor/TexSourceViewerConfiguration.java
+++ b/sub/source/net/sourceforge/texlipse/editor/TexSourceViewerConfiguration.java
@@ -1,347 +1,347 @@
/*
* $Id$
*
* Copyright (c) 2004-2005 by the TeXlapse Team.
* 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
*/
package net.sourceforge.texlipse.editor;
import net.sourceforge.texlipse.TexlipsePlugin;
import net.sourceforge.texlipse.editor.hover.TexHover;
import net.sourceforge.texlipse.editor.scanner.TexCommentScanner;
import net.sourceforge.texlipse.editor.scanner.TexMathScanner;
import net.sourceforge.texlipse.editor.scanner.TexScanner;
import net.sourceforge.texlipse.properties.TexlipseProperties;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.IAutoIndentStrategy;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.TextAttribute;
import org.eclipse.jface.text.TextPresentation;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.presentation.IPresentationReconciler;
import org.eclipse.jface.text.presentation.PresentationReconciler;
import org.eclipse.jface.text.rules.DefaultDamagerRepairer;
import org.eclipse.jface.text.rules.Token;
import org.eclipse.jface.text.source.IAnnotationHover;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
* Configuration for the source viewer of the LaTeX
* editor.
*
* @author Oskar Ojala
* @author Antti Pirinen
*/
public class TexSourceViewerConfiguration extends SourceViewerConfiguration {
private TexEditor editor;
private TexMathScanner mathScanner;
private TexScanner scanner;
private TexCommentScanner commentScanner;
private ColorManager colorManager;
private TexAnnotationHover annotationHover;
private ContentAssistant assistant;
private TexHover textHover;
/**
* Creates a new source viewer configuration.
*
* @param te The editor that this configuration is associated to
*/
public TexSourceViewerConfiguration(TexEditor te) {
super();
this.editor = te;
this.colorManager = new ColorManager();
this.annotationHover = new TexAnnotationHover(editor);
// Adds a listener for changing content assistan properties if
// these are changed in the preferences
TexlipsePlugin.getDefault().getPreferenceStore().addPropertyChangeListener(new
IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (assistant == null)
return;
String property = event.getProperty();
if (TexlipseProperties.TEX_COMPLETION.equals(property)) {
assistant.enableAutoActivation(
TexlipsePlugin.getDefault().getPreferenceStore().getBoolean(
TexlipseProperties.TEX_COMPLETION));
} else if (TexlipseProperties.TEX_COMPLETION_DELAY.equals(property)) {
assistant.setAutoActivationDelay(
TexlipsePlugin.getDefault().getPreferenceStore().getInt(
TexlipseProperties.TEX_COMPLETION_DELAY));
}
};
});
}
/**
* @return the annotation hover text provider for this editor
*/
public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) {
return annotationHover;
}
// the deprecated interface must be used as a return value, since the extended class hasn't been
// updated to reflect the change
public IAutoIndentStrategy getAutoIndentStrategy(ISourceViewer sourceViewer, String contentType) {
return new TexAutoIndentStrategy(editor.getPreferences());
}
/**
* Returns the configured partitioning for the given source viewer.
* The partitioning is used when the querying content types from the
* source viewer's input document.
* @param sourceViewer the source viewer to be configured by this
* configuration
* @return the configured partitioning
* @see org.eclipse.jface.text.source.SourceViewerConfiguration#getConfiguredContentTypes(ISourceViewer)
*/
public String getConfiguredDocumentPartitioning(ISourceViewer sourceViewer) {
return TexEditor.TEX_PARTITIONING;
}
/**
* A method to get allowed content types.
* @param sourceViewer the source viewer to be configured by this
* configuration
* @return a new String[] array of content types.
*/
public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
return new String[] {
IDocument.DEFAULT_CONTENT_TYPE,
TexPartitionScanner.TEX_MATH,
TexPartitionScanner.TEX_CURLY_BRACKETS,
TexPartitionScanner.TEX_SQUARE_BRACKETS,
TexPartitionScanner.TEX_COMMENT
};
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.source.SourceViewerConfiguration#getContentAssistant(org.eclipse.jface.text.source.ISourceViewer)
*/
public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
// ContentAssistant assistant = new ContentAssistant();
assistant = new ContentAssistant();
assistant.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
// note that partitioning affects completions
//TexCompletionProcessor tcp = new TexCompletionProcessor(this.editor.getDocumentModel());
TexCompletionProcessor tcp = new TexCompletionProcessor(this.editor.getDocumentModel(), sourceViewer);
TexMathCompletionProcessor tmcp = new TexMathCompletionProcessor(this.editor.getDocumentModel(), sourceViewer);
// assistant.setContentAssistProcessor(new TexCompletionProcessor(this.editor.getDocumentModel()),
// IDocument.DEFAULT_CONTENT_TYPE);
assistant.setContentAssistProcessor(tcp, IDocument.DEFAULT_CONTENT_TYPE);
//assistant.setContentAssistProcessor(tcp, TexPartitionScanner.TEX_MATH);
assistant.setContentAssistProcessor(tmcp, TexPartitionScanner.TEX_MATH);
assistant.setContentAssistProcessor(tcp, TexPartitionScanner.TEX_CURLY_BRACKETS);
assistant.setContentAssistProcessor(tcp, TexPartitionScanner.TEX_SQUARE_BRACKETS);
assistant.enableAutoActivation(TexlipsePlugin.getDefault().getPreferenceStore().getBoolean(TexlipseProperties.TEX_COMPLETION));
assistant.enableAutoInsert(true);
assistant.setAutoActivationDelay(TexlipsePlugin.getDefault().getPreferenceStore().getInt(TexlipseProperties.TEX_COMPLETION_DELAY));
assistant.setProposalPopupOrientation(IContentAssistant.PROPOSAL_OVERLAY);
assistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE);
assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer));
return assistant;
}
public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) {
PresentationReconciler reconciler = new PresentationReconciler();
reconciler.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
DefaultDamagerRepairer dr = null;
dr = new DefaultDamagerRepairer(getTeXMathScanner());
reconciler.setDamager(dr, TexPartitionScanner.TEX_MATH);
reconciler.setRepairer(dr, TexPartitionScanner.TEX_MATH);
dr = new DefaultDamagerRepairer(getTexCommentScanner());
reconciler.setDamager(dr, TexPartitionScanner.TEX_COMMENT);
reconciler.setRepairer(dr, TexPartitionScanner.TEX_COMMENT);
dr = new DefaultDamagerRepairer(getTexScanner());
reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
return reconciler;
}
/**
* Defines a default partition skanner and sets the default
* color for it
* @return a scanner to find default partitions.
*/
protected TexScanner getTexScanner() {
if (scanner == null) {
scanner = new TexScanner(colorManager, editor);
scanner.setDefaultReturnToken(
new Token(
new TextAttribute(
colorManager.getColor(ColorManager.DEFAULT),
null,
colorManager.getStyle(ColorManager.DEFAULT_STYLE))));
}
return scanner;
}
/**
* Defines a math partition skanner and sets the default
* color for it.
* @return a scanner to detect math partitions
*/
protected TexMathScanner getTeXMathScanner() {
if (mathScanner == null) {
mathScanner = new TexMathScanner(colorManager, editor);
mathScanner.setDefaultReturnToken(
new Token(
new TextAttribute(
colorManager.getColor(ColorManager.EQUATION),
null,
colorManager.getStyle(ColorManager.EQUATION_STYLE))));
}
return mathScanner;
}
/**
* Defines a comment skanner and sets the default color for it
* @return a scanner to detect comment partitions
*/
protected TexCommentScanner getTexCommentScanner() {
if (commentScanner == null) {
commentScanner = new TexCommentScanner(colorManager,editor);
commentScanner.setDefaultReturnToken(
new Token(
new TextAttribute(
colorManager.getColor(ColorManager.COMMENT),
null,
colorManager.getStyle(ColorManager.COMMENT_STYLE))));
}
return commentScanner;
}
public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {
if (textHover == null) {
textHover = new TexHover(editor);
}
return textHover;
}
/**
* Displays all commands in bold and all groups in italic
*/
private static final DefaultInformationControl.IInformationPresenter
presenter = new DefaultInformationControl.IInformationPresenter() {
public String updatePresentation(Display display, String infoText,
TextPresentation presentation, int maxWidth, int maxHeight) {
int cstart = -1;
int gstart = -1;
// Loop over all characters of information text
for (int i = 0; i < infoText.length(); i++) {
switch (infoText.charAt(i)) {
case '{':
// if we get \foo\{ or \{, then a group doesn't start
if (cstart >= 0 && infoText.charAt(i-1) != '\\') {
boldRange(cstart, i - cstart + 1, presentation, false);
cstart = -1;
gstart = i;
} else if (cstart < 0) {
gstart = i;
}
break;
case '}':
// if we get \} then it doesn't mean that a group ends
if (cstart >= 0 && infoText.charAt(i-1) != '\\') {
boldRange(cstart, i - cstart + 1, presentation, true);
cstart = -1;
if (gstart >= 0) {
italicizeRange(gstart, cstart - gstart, presentation);
gstart = -1;
}
} else if (gstart >= 0) {
italicizeRange(gstart, i - gstart + 1, presentation);
gstart = -1;
}
break;
case '\\':
- if (cstart < 0) {
+ if (cstart < 0 && gstart < 0) {
cstart = i;
}
break;
case '\n':
case '\r':
case '\t':
case ' ':
if (cstart >= 0) {
if (gstart >= 0) {
italicizeRange(gstart, cstart - gstart, presentation);
boldRange(cstart, i - cstart + 1, presentation, true);
gstart = i;
} else {
boldRange(cstart, i - cstart + 1, presentation, false);
}
cstart = -1;
}
break;
}
}
// check if we want to bold to the end of string
if (gstart >= 0) {
italicizeRange(gstart, infoText.length() - gstart, presentation);
}
if (cstart >= 0) {
boldRange(cstart, infoText.length() - cstart, presentation, false);
}
// Return the information text
return infoText;
}
private void boldRange(int start, int end, TextPresentation presentation, boolean doItalic) {
// We have found a tag and create a new style range
int fontStyle = doItalic ? (SWT.BOLD | SWT.ITALIC) : SWT.BOLD;
StyleRange range = new StyleRange(start, end, null, null, fontStyle);
// Add this style range to the presentation
presentation.addStyleRange(range);
}
private void italicizeRange(int start, int end, TextPresentation presentation) {
StyleRange range = new StyleRange(start, end, null, null, SWT.ITALIC);
presentation.addStyleRange(range);
}
};
public IInformationControlCreator getInformationControlCreator
(ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
return new DefaultInformationControl(parent, presenter);
}
};
}
}
| true | true | public String updatePresentation(Display display, String infoText,
TextPresentation presentation, int maxWidth, int maxHeight) {
int cstart = -1;
int gstart = -1;
// Loop over all characters of information text
for (int i = 0; i < infoText.length(); i++) {
switch (infoText.charAt(i)) {
case '{':
// if we get \foo\{ or \{, then a group doesn't start
if (cstart >= 0 && infoText.charAt(i-1) != '\\') {
boldRange(cstart, i - cstart + 1, presentation, false);
cstart = -1;
gstart = i;
} else if (cstart < 0) {
gstart = i;
}
break;
case '}':
// if we get \} then it doesn't mean that a group ends
if (cstart >= 0 && infoText.charAt(i-1) != '\\') {
boldRange(cstart, i - cstart + 1, presentation, true);
cstart = -1;
if (gstart >= 0) {
italicizeRange(gstart, cstart - gstart, presentation);
gstart = -1;
}
} else if (gstart >= 0) {
italicizeRange(gstart, i - gstart + 1, presentation);
gstart = -1;
}
break;
case '\\':
if (cstart < 0) {
cstart = i;
}
break;
case '\n':
case '\r':
case '\t':
case ' ':
if (cstart >= 0) {
if (gstart >= 0) {
italicizeRange(gstart, cstart - gstart, presentation);
boldRange(cstart, i - cstart + 1, presentation, true);
gstart = i;
} else {
boldRange(cstart, i - cstart + 1, presentation, false);
}
cstart = -1;
}
break;
}
}
// check if we want to bold to the end of string
if (gstart >= 0) {
italicizeRange(gstart, infoText.length() - gstart, presentation);
}
if (cstart >= 0) {
boldRange(cstart, infoText.length() - cstart, presentation, false);
}
// Return the information text
return infoText;
}
| public String updatePresentation(Display display, String infoText,
TextPresentation presentation, int maxWidth, int maxHeight) {
int cstart = -1;
int gstart = -1;
// Loop over all characters of information text
for (int i = 0; i < infoText.length(); i++) {
switch (infoText.charAt(i)) {
case '{':
// if we get \foo\{ or \{, then a group doesn't start
if (cstart >= 0 && infoText.charAt(i-1) != '\\') {
boldRange(cstart, i - cstart + 1, presentation, false);
cstart = -1;
gstart = i;
} else if (cstart < 0) {
gstart = i;
}
break;
case '}':
// if we get \} then it doesn't mean that a group ends
if (cstart >= 0 && infoText.charAt(i-1) != '\\') {
boldRange(cstart, i - cstart + 1, presentation, true);
cstart = -1;
if (gstart >= 0) {
italicizeRange(gstart, cstart - gstart, presentation);
gstart = -1;
}
} else if (gstart >= 0) {
italicizeRange(gstart, i - gstart + 1, presentation);
gstart = -1;
}
break;
case '\\':
if (cstart < 0 && gstart < 0) {
cstart = i;
}
break;
case '\n':
case '\r':
case '\t':
case ' ':
if (cstart >= 0) {
if (gstart >= 0) {
italicizeRange(gstart, cstart - gstart, presentation);
boldRange(cstart, i - cstart + 1, presentation, true);
gstart = i;
} else {
boldRange(cstart, i - cstart + 1, presentation, false);
}
cstart = -1;
}
break;
}
}
// check if we want to bold to the end of string
if (gstart >= 0) {
italicizeRange(gstart, infoText.length() - gstart, presentation);
}
if (cstart >= 0) {
boldRange(cstart, infoText.length() - cstart, presentation, false);
}
// Return the information text
return infoText;
}
|
diff --git a/src/com/kkbox/toolkit/api/KKAPIJsonRequest.java b/src/com/kkbox/toolkit/api/KKAPIJsonRequest.java
index 540ea6f..a65865b 100644
--- a/src/com/kkbox/toolkit/api/KKAPIJsonRequest.java
+++ b/src/com/kkbox/toolkit/api/KKAPIJsonRequest.java
@@ -1,74 +1,78 @@
/* Copyright (C) 2014 KKBOX 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.kkbox.toolkit.api;
import android.content.Context;
import com.kkbox.toolkit.internal.api.APIRequest;
import com.kkbox.toolkit.internal.api.KKAPIJsonRequestListener;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
public class KKAPIJsonRequest extends APIRequest {
private KKAPIJsonRequestListener jsonRequestListener;
public KKAPIJsonRequest(String url, Cipher cipher, long reloadPeriod, Context context) {
super(url, cipher, reloadPeriod, context);
}
public KKAPIJsonRequest(String url, Cipher cipher) {
super(url, cipher);
}
public KKAPIJsonRequest(String url, Cipher cipher, int socketTimeout) {
super(url, cipher, socketTimeout);
}
@Override
public Void doInBackground(Object... params) {
jsonRequestListener = (KKAPIJsonRequestListener) params[0];
return super.doInBackground(params);
}
@Override
protected void readDataFromInputStream(ByteArrayOutputStream data) throws IOException {}
@Override
protected void preCompleteAndCachedAPI(ByteArrayOutputStream data, File cacheFile) throws BadPaddingException, IllegalBlockSizeException, IOException {
- if (is != null) {
- int readLength;
- byte[] buffer = new byte[128];
- FileOutputStream fileOutputStream = new FileOutputStream(cacheFile);
- while ((readLength = is.read(buffer, 0, buffer.length)) != -1) {
- fileOutputStream.write(buffer, 0, readLength);
+ InputStream inputStream;
+ if (cacheTimeOut > 0) {
+ if (is != null) {
+ int readLength;
+ byte[] buffer = new byte[128];
+ FileOutputStream fileOutputStream = new FileOutputStream(cacheFile);
+ while ((readLength = is.read(buffer, 0, buffer.length)) != -1) {
+ fileOutputStream.write(buffer, 0, readLength);
+ }
+ fileOutputStream.close();
}
- fileOutputStream.close();
+ inputStream = new FileInputStream(cacheFile);
+ } else {
+ inputStream = is;
}
- InputStream inputStream = new FileInputStream(cacheFile);
jsonRequestListener.onStreamPreComplete(inputStream);
- inputStream.close();
}
}
| false | true | protected void preCompleteAndCachedAPI(ByteArrayOutputStream data, File cacheFile) throws BadPaddingException, IllegalBlockSizeException, IOException {
if (is != null) {
int readLength;
byte[] buffer = new byte[128];
FileOutputStream fileOutputStream = new FileOutputStream(cacheFile);
while ((readLength = is.read(buffer, 0, buffer.length)) != -1) {
fileOutputStream.write(buffer, 0, readLength);
}
fileOutputStream.close();
}
InputStream inputStream = new FileInputStream(cacheFile);
jsonRequestListener.onStreamPreComplete(inputStream);
inputStream.close();
}
| protected void preCompleteAndCachedAPI(ByteArrayOutputStream data, File cacheFile) throws BadPaddingException, IllegalBlockSizeException, IOException {
InputStream inputStream;
if (cacheTimeOut > 0) {
if (is != null) {
int readLength;
byte[] buffer = new byte[128];
FileOutputStream fileOutputStream = new FileOutputStream(cacheFile);
while ((readLength = is.read(buffer, 0, buffer.length)) != -1) {
fileOutputStream.write(buffer, 0, readLength);
}
fileOutputStream.close();
}
inputStream = new FileInputStream(cacheFile);
} else {
inputStream = is;
}
jsonRequestListener.onStreamPreComplete(inputStream);
}
|
diff --git a/src/test/java/swing/revival/ActivePanelTest.java b/src/test/java/swing/revival/ActivePanelTest.java
index 947e8aa..6ba04c7 100644
--- a/src/test/java/swing/revival/ActivePanelTest.java
+++ b/src/test/java/swing/revival/ActivePanelTest.java
@@ -1,67 +1,67 @@
/**
* swing-revival:
* Swing Revival Toolkit
*
* Copyright (c) 2009 by Alistair A. Israel.
*
* This software is made available under the terms of the MIT License.
* See LICENSE.txt.
*
* Created Sep 30, 2009
*/
package swing.revival;
import javax.swing.JLabel;
import javax.swing.JTextField;
import junit.extensions.abbot.ComponentTestFixture;
import org.junit.Test;
import swing.revival.annotations.Component;
import swing.revival.annotations.Font;
/**
*
* @author Alistair A. Israel
*/
public final class ActivePanelTest extends ComponentTestFixture {
/**
*
* @author Alistair A. Israel
*/
@SuppressWarnings("serial")
@Font(name = "Tahoma")
public static final class MyPanel extends ActivePanel {
private JLabel field1Label;
@Component
private JTextField field1TextField;
}
/**
* @throws Exception
* on exception
*/
@Test
public void testMyPanel() throws Exception {
final MyPanel myPanel = new MyPanel();
final JLabel field1Label = myPanel.field1Label;
assertNotNull("field1Label is null!", field1Label);
assertEquals("field1Label", field1Label.getName());
assertEquals("Tahoma", field1Label.getFont().getName());
final JTextField field1TextField = myPanel.field1TextField;
assertNotNull("field1TextField is null!", field1TextField);
assertEquals("field1TextField", field1TextField.getName());
- assertEquals("field1TextField tooltip text", field1TextField.getToolTipText());
+ assertEquals("First field tool-tip text", field1TextField.getToolTipText());
assertEquals("Tahoma", field1TextField.getFont().getName());
assertSame("field1Label is not label for field1TextField!", field1TextField,
field1Label.getLabelFor());
showFrame(myPanel);
}
}
| true | true | public void testMyPanel() throws Exception {
final MyPanel myPanel = new MyPanel();
final JLabel field1Label = myPanel.field1Label;
assertNotNull("field1Label is null!", field1Label);
assertEquals("field1Label", field1Label.getName());
assertEquals("Tahoma", field1Label.getFont().getName());
final JTextField field1TextField = myPanel.field1TextField;
assertNotNull("field1TextField is null!", field1TextField);
assertEquals("field1TextField", field1TextField.getName());
assertEquals("field1TextField tooltip text", field1TextField.getToolTipText());
assertEquals("Tahoma", field1TextField.getFont().getName());
assertSame("field1Label is not label for field1TextField!", field1TextField,
field1Label.getLabelFor());
showFrame(myPanel);
}
| public void testMyPanel() throws Exception {
final MyPanel myPanel = new MyPanel();
final JLabel field1Label = myPanel.field1Label;
assertNotNull("field1Label is null!", field1Label);
assertEquals("field1Label", field1Label.getName());
assertEquals("Tahoma", field1Label.getFont().getName());
final JTextField field1TextField = myPanel.field1TextField;
assertNotNull("field1TextField is null!", field1TextField);
assertEquals("field1TextField", field1TextField.getName());
assertEquals("First field tool-tip text", field1TextField.getToolTipText());
assertEquals("Tahoma", field1TextField.getFont().getName());
assertSame("field1Label is not label for field1TextField!", field1TextField,
field1Label.getLabelFor());
showFrame(myPanel);
}
|
diff --git a/oeclib/src/ke/go/moh/oec/lib/HttpService.java b/oeclib/src/ke/go/moh/oec/lib/HttpService.java
index d90ad58..87fed53 100644
--- a/oeclib/src/ke/go/moh/oec/lib/HttpService.java
+++ b/oeclib/src/ke/go/moh/oec/lib/HttpService.java
@@ -1,454 +1,467 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is OpenEMRConnect.
*
* The Initial Developer of the Original Code is International Training &
* Education Center for Health (I-TECH) <http://www.go2itech.org/>
*
* Portions created by the Initial Developer are Copyright (C) 2011
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
package ke.go.moh.oec.lib;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.OutputStream;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
/**
* Handles HTTP requests and responses between OpenEMRConnect nodes.
*
* @author John Gitau
* @author Jim Grace
*/
class HttpService {
/**
* {@link Mediator} class instance to which we pass any received HTTP
* requests.
*/
private Mediator mediator = null;
private int id = 0;
private int port = 0;
HttpServer server;
MessageDigest messageDigest;
Map<String, Date> unreachableIpPorts = new HashMap<String, Date>();
private static final SimpleDateFormat SIMPLE_DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
private static final int HTTP_RESPONSE_OK = 200;
private static final int HTTP_RESPONSE_MD5_MISMATCH = 449; // No obvious choice here, this code is Microsoft "Retry With"
private class PartialMessage {
private int id;
private int segment = 0;
private int length = 0;
private List<byte[]> messageSegments = new ArrayList<byte[]>();
}
private Map<String, PartialMessage> partialMessages = new HashMap<String, PartialMessage>();
/**
* Constructor to set {@link Mediator} callback object
*
* @param mediator {@link Mediator} callback object for listener
*/
HttpService(Mediator mediator) {
this.mediator = mediator;
try {
messageDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(HttpService.class.getName()).log(Level.SEVERE, "Can't get an instance of the MD5 algorithm", ex);
}
}
/**
* Sends a HTTP message.
*
* @param m Message to send
* @return true if message was sent and HTTP response received, otherwise false
*/
boolean send(Message m) throws MalformedURLException, IOException {
if (port == 0) {
port = Integer.parseInt(Mediator.getProperty("HTTPHandler.ListenPort"));
}
boolean returnStatus = false;
String destinationAddress = m.getDestinationAddress();
NextHop nextHop = m.getNextHop();
if (nextHop == null) {
// If we are called from the QueueManager, we may not have the next hop information because they are not stored in the queue database.
// If this is the case, then get the IP address and port now, from the destination address.
nextHop = NextHop.getNextHop(destinationAddress);
m.setNextHop(nextHop);
}
String ipAddressPort = nextHop.getIpAddressPort();
int maxSize = nextHop.getMaxSize();
String url = "http://" + ipAddressPort + "/oecmessage?destination="
+ destinationAddress + "&tobequeued=" + m.isToBeQueued() + "&hopcount=" + m.getHopCount();
try {
/*Code thats performing a task should be placed in the try catch statement especially in the try part*/
byte[] compressedXml = m.getCompressedXml();
int compressedXmlLength = m.getCompressedXmlLength();
int sent = 0;
int toSend = compressedXmlLength;
if (compressedXmlLength > maxSize) { // If we're going to split this message:
// Append the next message ID onto the URL.
url += "&port=" + port + "&id=" + ++id + "&segment=";
}
int segment = 0;
while (sent < compressedXmlLength) {
String thisUrl = url;
if (compressedXmlLength > maxSize) {
thisUrl = url + Integer.toString(++segment);
if (compressedXmlLength - sent > maxSize) {
toSend = maxSize;
} else {
toSend = compressedXmlLength - sent;
thisUrl = thisUrl + "&end";
}
}
HttpURLConnection connection = (HttpURLConnection) new URL(thisUrl).openConnection();
String md5 = computeMd5(compressedXml, sent, toSend);
connection.setRequestProperty("Content-MD5", md5);
connection.setDoOutput(true);
OutputStream output = connection.getOutputStream();
output.write(compressedXml, sent, toSend);
output.close();
int responseCode = connection.getResponseCode();
//
// If we get a HTTP_RESPONSE_MD5_MISMATCH from the other side,
// then just keep retrying to send the same message over and over.
// As long as something is getting through, then the whole message should go through.
//
// If we get any other kind of response, account for the number of bytes
// sent, and continue sending (or finish if everything was sent.)
//
if (responseCode != HTTP_RESPONSE_MD5_MISMATCH) {
sent = sent + toSend;
InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream());
BufferedReader br = new BufferedReader(inputStreamReader);
while (br.readLine() != null) {
//content not required, just acknowlegment that message was received.
}
br.close();
inputStreamReader.close();
} else {
Logger.getLogger(HttpService.class.getName()).log(Level.FINE,
"MD5 mismatch reported. Retrying sending message to {0} at {1}",
new Object[]{m.getDestinationAddress(), url});
}
}
returnStatus = true;
canReach(ipAddressPort);
} catch (ConnectException ex) {
cannotReach(ipAddressPort, "Can't connect to " + ipAddressPort + " for message to " + destinationAddress);
} catch (UnknownHostException ex) {
cannotReach(ipAddressPort, "Unknown Host " + ipAddressPort + " for message to " + destinationAddress);
} catch (MalformedURLException ex) {
Logger.getLogger(HttpService.class.getName()).log(Level.SEVERE,
"While sending to " + m.getDestinationAddress() + " at " + url, ex);
} catch (IOException ex) {
String message = ex.getMessage();
if (message.equals("Premature EOF")
|| message.equals("Unexpected end of file from server")) {
returnStatus = true; // We expect End of File at some point
} else {
Logger.getLogger(HttpService.class.getName()).log(Level.SEVERE,
"While sending to " + m.getDestinationAddress() + " at " + url, ex);
// There was some transmission error we return false.
}
}
return returnStatus;
}
/**
* Handles the case where we can't reach a given IP address / port.
* <p>
* If this is the first time we have this problem: (a) log an error message,
* and (b) add this IP address / port to a list of IP addresses / ports with
* whom we are having trouble communicating.
* <p>
* If this IP address / port is already on the list of destinations we cannot
* reach, do nothing. This prevents trying to send a message to the
* logging server every time we retry sending to this IP address / port.
* If we did so, this could result in a lot of traffic to the logging server.
* Worse yet, the message to the logging server might itself not be able to
* be sent. Instead, we will send a single message to the logging server
* at a later time when we can send to this IP address / port again.
*
* @param ipAddressPort IP Address and Port we cannot reach
* @param errorMessage Error why we cannot reach this IP address / port.
*/
private synchronized void cannotReach(String ipAddressPort, String errorMessage) {
if (!unreachableIpPorts.containsKey(ipAddressPort)) {
Logger.getLogger(HttpService.class.getName()).log(Level.SEVERE, errorMessage);
unreachableIpPorts.put(ipAddressPort, new Date());
}
}
/**
* Handles the case where we can reach a given IP address / port.
* <p>
* If we were previously having trouble reaching the given IP address / port,
* it will be on a list of destinations with which we were having trouble.
* In this case, log an informational message that the trouble is now over.
* Include in this message the time when the trouble started. And remove
* this IP address / port combination from our trouble list.
*
* @param ipAddressPort IP Address and port we can reach
*/
private void canReach(String ipAddressPort) {
if (unreachableIpPorts.containsKey(ipAddressPort)) {
Date sinceDate = unreachableIpPorts.get(ipAddressPort);
Logger.getLogger(HttpService.class.getName()).log(Level.INFO,
"Can reach {0} for the first time since {1}",
new Object[]{ipAddressPort, SIMPLE_DATE_TIME_FORMAT.format(sinceDate)});
unreachableIpPorts.remove(ipAddressPort);
}
}
/**
* Starts listening for HTTP messages.
* <p>
* For each message received, call mediator.processReceivedMessage()
* @throws IOException
*/
void start() throws IOException {
//throw new UnsupportedOperationException("Not supported yet.");
if (port == 0) {
port = Integer.parseInt(Mediator.getProperty("HTTPHandler.ListenPort"));
}
InetSocketAddress addr = new InetSocketAddress(port);
server = HttpServer.create(addr, 0);
server.createContext("/oecmessage", (HttpHandler) new Handler(mediator));
server.setExecutor(Executors.newCachedThreadPool());
server.start();
Mediator.getLogger(HttpService.class.getName()).log(Level.INFO,
Mediator.getProperty("Instance.Name") + " "
+ Mediator.getProperty("Instance.Address") + " listening on port {0}",
Integer.toString(port)); // (Explicitly convert to string to avoid "," thousands seperator formatting.)
}
/**
* Stops listening for HTTP messages.
*/
void stop() {
final int delaySeconds = 0;
server.stop(delaySeconds);
}
/**
* The handler class below implements the HttpHandler interface properties and is called up to process
* HTTP exchanges.
*/
private class Handler implements HttpHandler {
private Mediator mediator = null;
private Handler(Mediator mediator) {
this.mediator = mediator;
}
/**
*
* @param exchange
* @throws IOException
*/
public void handle(HttpExchange exchange) throws IOException {
Message m = new Message();
/*
* Unpack the URL.
*/
String requestMethod = exchange.getRequestMethod();
URI uri = exchange.getRequestURI();
String query = uri.getQuery();
int port = 0;
int id = 0;
int segment = 0;
boolean end = false;
//
// Parse the URL arguments
//
for (String param : query.split("&")) {
String[] pair = param.split("=");
if (pair[0].equals("destination")) {
m.setDestinationAddress(pair[1]);
} else if (pair[0].equals("hopcount")) {
m.setHopCount(Integer.parseInt(pair[1]));
} else if (pair[0].equals("tobequeued")) {
m.setToBeQueued(Boolean.parseBoolean(pair[1]));
} else if (pair[0].equals("port")) {
port = Integer.parseInt(pair[1]);
} else if (pair[0].equals("id")) {
id = Integer.parseInt(pair[1]);
} else if (pair[0].equals("segment")) {
segment = Integer.parseInt(pair[1]);
} else if (pair[0].equals("end")) {
end = true;
}
}
if (requestMethod.equals("POST")) {
/*
* Read the posted content
*/
Headers headers = exchange.getRequestHeaders();
int responseCode = HTTP_RESPONSE_OK;
boolean outOfSequence = false;
int bufferSize = 50000; // Default buffer size if no Content-Length header is present.
String contentLength = headers.getFirst("Content-Length");
if (contentLength != null) {
bufferSize = Integer.parseInt(contentLength);
}
InputStream input = exchange.getRequestBody();
byte[] compressedXml = new byte[bufferSize];
int compressedXmlLength = input.read(compressedXml);
input.close();
String md5Reported = headers.getFirst("Content-MD5");
if (md5Reported != null) {
String md5Computed = computeMd5(compressedXml, 0, compressedXmlLength);
if (md5Reported.compareTo(md5Computed) != 0) {
responseCode = HTTP_RESPONSE_MD5_MISMATCH;
Logger.getLogger(HttpService.class.getName()).log(Level.FINE,
"MD5 reported as {0}, computed as {1}, length expected {2}, found {3}",
new Object[]{md5Reported, md5Computed, bufferSize, compressedXmlLength});
}
} else {
Logger.getLogger(HttpService.class.getName()).log(Level.FINE,
"MD5 not reported. length expected {0}, found {1}",
new Object[]{bufferSize, compressedXmlLength});
}
if (responseCode == HTTP_RESPONSE_OK) {
InetSocketAddress remoteAddress = exchange.getRemoteAddress();
String sendingIpAddress = remoteAddress.getAddress().getHostAddress();
boolean completeMessage = true;
m.setSendingIpAddress(sendingIpAddress);
m.setSegmentCount(1);
m.setLongestSegmentLength(compressedXmlLength);
if (id > 0) {
completeMessage = false;
String sendingIpAddressAndPort = sendingIpAddress + ":" + port;
PartialMessage pm = null;
if (segment == 1) {
pm = new PartialMessage();
pm.id = id;
pm.segment = segment;
byte[] a = Arrays.copyOf(compressedXml, compressedXmlLength);
pm.messageSegments.add(a);
pm.length += compressedXmlLength;
partialMessages.put(sendingIpAddressAndPort, pm);
} else {
pm = partialMessages.get(sendingIpAddressAndPort);
if (pm != null) {
if (pm.id == id && ++pm.segment == segment) {
byte[] a = Arrays.copyOf(compressedXml, compressedXmlLength);
pm.messageSegments.add(a);
pm.length += compressedXmlLength;
if (end) {
compressedXmlLength = pm.length;
compressedXml = new byte[compressedXmlLength];
int offset = 0;
int longest = 0;
for (byte[] seg : pm.messageSegments) {
System.arraycopy(seg, 0, compressedXml, offset, seg.length);
offset += seg.length;
if (seg.length > longest) {
longest = seg.length;
}
}
m.setSegmentCount(pm.messageSegments.size());
m.setLongestSegmentLength(longest);
completeMessage = true;
partialMessages.remove(sendingIpAddressAndPort);
}
} else {
+ if (pm.id != id) {
+ Logger.getLogger(HttpService.class.getName()).log(Level.FINE,
+ "Message id mismatch from {0}. Expected id {1}, found {2}, expected sequence {3}, found {4}",
+ new Object[]{sendingIpAddressAndPort, pm.id, id, pm.segment, segment});
+ } else {
+ Logger.getLogger(HttpService.class.getName()).log(Level.FINE,
+ "Message segment out of sequence from {0}, message id {1}, expected sequence {2}, found {3}",
+ new Object[]{sendingIpAddressAndPort, id, pm.segment, segment});
+ }
outOfSequence = true;
partialMessages.remove(sendingIpAddressAndPort);
}
+ } else {
+ Logger.getLogger(HttpService.class.getName()).log(Level.FINE,
+ "Received segment from {0}, id {1}, segment {2} but no partial message previously stored.",
+ new Object[]{sendingIpAddressAndPort, id, segment});
}
}
}
if (completeMessage) {
m.setSendingIpAddress(sendingIpAddress);
m.setCompressedXml(compressedXml);
m.setCompressedXmlLength(compressedXmlLength);
/*
* Process the message.
*/
mediator.processReceivedMessage(m);
}
}
if (!outOfSequence) {
/*
* Acknoweldge to the sender that we received the message.
* (Don't acknowledge an out-of-sequence message).
*/
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/plain");
- exchange.sendResponseHeaders(200, 0);
+ exchange.sendResponseHeaders(responseCode, 0);
OutputStream responseBody = exchange.getResponseBody();
responseBody.close();
}
exchange.close();
}
}
}
/**
* Computes the MD5 hash for an array of bytes.
*
* @param bytes array of bytes for which the MD5 hash will be computed
* @param offset starting offset for computing the MD5 hasn
* @param length length for computing the MD5 hash
* @return the MD5 hash in 32 characters hexadecimal.
*/
String computeMd5(byte[] bytes, int offset, int length) {
messageDigest.reset();
messageDigest.update(bytes, offset, length);
byte[] digest = messageDigest.digest();
BigInteger bigInt = new BigInteger(1, digest);
String hashtext = bigInt.toString(16);
// Now we need to zero pad it to get the full 32 chars.
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
}
}
| false | true | public void handle(HttpExchange exchange) throws IOException {
Message m = new Message();
/*
* Unpack the URL.
*/
String requestMethod = exchange.getRequestMethod();
URI uri = exchange.getRequestURI();
String query = uri.getQuery();
int port = 0;
int id = 0;
int segment = 0;
boolean end = false;
//
// Parse the URL arguments
//
for (String param : query.split("&")) {
String[] pair = param.split("=");
if (pair[0].equals("destination")) {
m.setDestinationAddress(pair[1]);
} else if (pair[0].equals("hopcount")) {
m.setHopCount(Integer.parseInt(pair[1]));
} else if (pair[0].equals("tobequeued")) {
m.setToBeQueued(Boolean.parseBoolean(pair[1]));
} else if (pair[0].equals("port")) {
port = Integer.parseInt(pair[1]);
} else if (pair[0].equals("id")) {
id = Integer.parseInt(pair[1]);
} else if (pair[0].equals("segment")) {
segment = Integer.parseInt(pair[1]);
} else if (pair[0].equals("end")) {
end = true;
}
}
if (requestMethod.equals("POST")) {
/*
* Read the posted content
*/
Headers headers = exchange.getRequestHeaders();
int responseCode = HTTP_RESPONSE_OK;
boolean outOfSequence = false;
int bufferSize = 50000; // Default buffer size if no Content-Length header is present.
String contentLength = headers.getFirst("Content-Length");
if (contentLength != null) {
bufferSize = Integer.parseInt(contentLength);
}
InputStream input = exchange.getRequestBody();
byte[] compressedXml = new byte[bufferSize];
int compressedXmlLength = input.read(compressedXml);
input.close();
String md5Reported = headers.getFirst("Content-MD5");
if (md5Reported != null) {
String md5Computed = computeMd5(compressedXml, 0, compressedXmlLength);
if (md5Reported.compareTo(md5Computed) != 0) {
responseCode = HTTP_RESPONSE_MD5_MISMATCH;
Logger.getLogger(HttpService.class.getName()).log(Level.FINE,
"MD5 reported as {0}, computed as {1}, length expected {2}, found {3}",
new Object[]{md5Reported, md5Computed, bufferSize, compressedXmlLength});
}
} else {
Logger.getLogger(HttpService.class.getName()).log(Level.FINE,
"MD5 not reported. length expected {0}, found {1}",
new Object[]{bufferSize, compressedXmlLength});
}
if (responseCode == HTTP_RESPONSE_OK) {
InetSocketAddress remoteAddress = exchange.getRemoteAddress();
String sendingIpAddress = remoteAddress.getAddress().getHostAddress();
boolean completeMessage = true;
m.setSendingIpAddress(sendingIpAddress);
m.setSegmentCount(1);
m.setLongestSegmentLength(compressedXmlLength);
if (id > 0) {
completeMessage = false;
String sendingIpAddressAndPort = sendingIpAddress + ":" + port;
PartialMessage pm = null;
if (segment == 1) {
pm = new PartialMessage();
pm.id = id;
pm.segment = segment;
byte[] a = Arrays.copyOf(compressedXml, compressedXmlLength);
pm.messageSegments.add(a);
pm.length += compressedXmlLength;
partialMessages.put(sendingIpAddressAndPort, pm);
} else {
pm = partialMessages.get(sendingIpAddressAndPort);
if (pm != null) {
if (pm.id == id && ++pm.segment == segment) {
byte[] a = Arrays.copyOf(compressedXml, compressedXmlLength);
pm.messageSegments.add(a);
pm.length += compressedXmlLength;
if (end) {
compressedXmlLength = pm.length;
compressedXml = new byte[compressedXmlLength];
int offset = 0;
int longest = 0;
for (byte[] seg : pm.messageSegments) {
System.arraycopy(seg, 0, compressedXml, offset, seg.length);
offset += seg.length;
if (seg.length > longest) {
longest = seg.length;
}
}
m.setSegmentCount(pm.messageSegments.size());
m.setLongestSegmentLength(longest);
completeMessage = true;
partialMessages.remove(sendingIpAddressAndPort);
}
} else {
outOfSequence = true;
partialMessages.remove(sendingIpAddressAndPort);
}
}
}
}
if (completeMessage) {
m.setSendingIpAddress(sendingIpAddress);
m.setCompressedXml(compressedXml);
m.setCompressedXmlLength(compressedXmlLength);
/*
* Process the message.
*/
mediator.processReceivedMessage(m);
}
}
if (!outOfSequence) {
/*
* Acknoweldge to the sender that we received the message.
* (Don't acknowledge an out-of-sequence message).
*/
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/plain");
exchange.sendResponseHeaders(200, 0);
OutputStream responseBody = exchange.getResponseBody();
responseBody.close();
}
exchange.close();
}
}
| public void handle(HttpExchange exchange) throws IOException {
Message m = new Message();
/*
* Unpack the URL.
*/
String requestMethod = exchange.getRequestMethod();
URI uri = exchange.getRequestURI();
String query = uri.getQuery();
int port = 0;
int id = 0;
int segment = 0;
boolean end = false;
//
// Parse the URL arguments
//
for (String param : query.split("&")) {
String[] pair = param.split("=");
if (pair[0].equals("destination")) {
m.setDestinationAddress(pair[1]);
} else if (pair[0].equals("hopcount")) {
m.setHopCount(Integer.parseInt(pair[1]));
} else if (pair[0].equals("tobequeued")) {
m.setToBeQueued(Boolean.parseBoolean(pair[1]));
} else if (pair[0].equals("port")) {
port = Integer.parseInt(pair[1]);
} else if (pair[0].equals("id")) {
id = Integer.parseInt(pair[1]);
} else if (pair[0].equals("segment")) {
segment = Integer.parseInt(pair[1]);
} else if (pair[0].equals("end")) {
end = true;
}
}
if (requestMethod.equals("POST")) {
/*
* Read the posted content
*/
Headers headers = exchange.getRequestHeaders();
int responseCode = HTTP_RESPONSE_OK;
boolean outOfSequence = false;
int bufferSize = 50000; // Default buffer size if no Content-Length header is present.
String contentLength = headers.getFirst("Content-Length");
if (contentLength != null) {
bufferSize = Integer.parseInt(contentLength);
}
InputStream input = exchange.getRequestBody();
byte[] compressedXml = new byte[bufferSize];
int compressedXmlLength = input.read(compressedXml);
input.close();
String md5Reported = headers.getFirst("Content-MD5");
if (md5Reported != null) {
String md5Computed = computeMd5(compressedXml, 0, compressedXmlLength);
if (md5Reported.compareTo(md5Computed) != 0) {
responseCode = HTTP_RESPONSE_MD5_MISMATCH;
Logger.getLogger(HttpService.class.getName()).log(Level.FINE,
"MD5 reported as {0}, computed as {1}, length expected {2}, found {3}",
new Object[]{md5Reported, md5Computed, bufferSize, compressedXmlLength});
}
} else {
Logger.getLogger(HttpService.class.getName()).log(Level.FINE,
"MD5 not reported. length expected {0}, found {1}",
new Object[]{bufferSize, compressedXmlLength});
}
if (responseCode == HTTP_RESPONSE_OK) {
InetSocketAddress remoteAddress = exchange.getRemoteAddress();
String sendingIpAddress = remoteAddress.getAddress().getHostAddress();
boolean completeMessage = true;
m.setSendingIpAddress(sendingIpAddress);
m.setSegmentCount(1);
m.setLongestSegmentLength(compressedXmlLength);
if (id > 0) {
completeMessage = false;
String sendingIpAddressAndPort = sendingIpAddress + ":" + port;
PartialMessage pm = null;
if (segment == 1) {
pm = new PartialMessage();
pm.id = id;
pm.segment = segment;
byte[] a = Arrays.copyOf(compressedXml, compressedXmlLength);
pm.messageSegments.add(a);
pm.length += compressedXmlLength;
partialMessages.put(sendingIpAddressAndPort, pm);
} else {
pm = partialMessages.get(sendingIpAddressAndPort);
if (pm != null) {
if (pm.id == id && ++pm.segment == segment) {
byte[] a = Arrays.copyOf(compressedXml, compressedXmlLength);
pm.messageSegments.add(a);
pm.length += compressedXmlLength;
if (end) {
compressedXmlLength = pm.length;
compressedXml = new byte[compressedXmlLength];
int offset = 0;
int longest = 0;
for (byte[] seg : pm.messageSegments) {
System.arraycopy(seg, 0, compressedXml, offset, seg.length);
offset += seg.length;
if (seg.length > longest) {
longest = seg.length;
}
}
m.setSegmentCount(pm.messageSegments.size());
m.setLongestSegmentLength(longest);
completeMessage = true;
partialMessages.remove(sendingIpAddressAndPort);
}
} else {
if (pm.id != id) {
Logger.getLogger(HttpService.class.getName()).log(Level.FINE,
"Message id mismatch from {0}. Expected id {1}, found {2}, expected sequence {3}, found {4}",
new Object[]{sendingIpAddressAndPort, pm.id, id, pm.segment, segment});
} else {
Logger.getLogger(HttpService.class.getName()).log(Level.FINE,
"Message segment out of sequence from {0}, message id {1}, expected sequence {2}, found {3}",
new Object[]{sendingIpAddressAndPort, id, pm.segment, segment});
}
outOfSequence = true;
partialMessages.remove(sendingIpAddressAndPort);
}
} else {
Logger.getLogger(HttpService.class.getName()).log(Level.FINE,
"Received segment from {0}, id {1}, segment {2} but no partial message previously stored.",
new Object[]{sendingIpAddressAndPort, id, segment});
}
}
}
if (completeMessage) {
m.setSendingIpAddress(sendingIpAddress);
m.setCompressedXml(compressedXml);
m.setCompressedXmlLength(compressedXmlLength);
/*
* Process the message.
*/
mediator.processReceivedMessage(m);
}
}
if (!outOfSequence) {
/*
* Acknoweldge to the sender that we received the message.
* (Don't acknowledge an out-of-sequence message).
*/
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/plain");
exchange.sendResponseHeaders(responseCode, 0);
OutputStream responseBody = exchange.getResponseBody();
responseBody.close();
}
exchange.close();
}
}
|
diff --git a/src/net/volus/ronwalf/phs2010/games/core/impl/BestNextMove.java b/src/net/volus/ronwalf/phs2010/games/core/impl/BestNextMove.java
index 4c6b867..4a627da 100644
--- a/src/net/volus/ronwalf/phs2010/games/core/impl/BestNextMove.java
+++ b/src/net/volus/ronwalf/phs2010/games/core/impl/BestNextMove.java
@@ -1,48 +1,50 @@
package net.volus.ronwalf.phs2010.games.core.impl;
import net.volus.ronwalf.phs2010.games.core.GamePlayer;
import net.volus.ronwalf.phs2010.games.core.GameTransition;
import net.volus.ronwalf.phs2010.games.core.HeuristicFunction;
import net.volus.ronwalf.phs2010.games.core.PlayerState;
import net.volus.ronwalf.phs2010.games.core.SearchController;
public class BestNextMove<State extends PlayerState, Action> implements GamePlayer<State, Action> {
private GameTransition<State, Action> transition;
private HeuristicFunction<State> heuristic;
private SearchController controller;
public BestNextMove(GameTransition<State, Action> transition,
HeuristicFunction<State> heuristic,
SearchController controller) {
this.transition = transition;
this.heuristic = heuristic;
this.controller = controller;
}
public Action move(State s) {
controller.start();
double best = Double.NEGATIVE_INFINITY;
Action bestAction = null;
for (Action a : transition.enumerate( s )) {
State sa = transition.apply(s, a);
double[] score = evaluate(sa);
if (score == null)
score = heuristic.score(sa);
- if (score[s.playerTurn()] > best)
+ if (score[s.playerTurn()] > best) {
+ best = score[s.playerTurn()];
bestAction = a;
+ }
}
controller.stop();
return bestAction;
}
public double[] evaluate(State s) {
return transition.score(s);
}
}
| false | true | public Action move(State s) {
controller.start();
double best = Double.NEGATIVE_INFINITY;
Action bestAction = null;
for (Action a : transition.enumerate( s )) {
State sa = transition.apply(s, a);
double[] score = evaluate(sa);
if (score == null)
score = heuristic.score(sa);
if (score[s.playerTurn()] > best)
bestAction = a;
}
controller.stop();
return bestAction;
}
| public Action move(State s) {
controller.start();
double best = Double.NEGATIVE_INFINITY;
Action bestAction = null;
for (Action a : transition.enumerate( s )) {
State sa = transition.apply(s, a);
double[] score = evaluate(sa);
if (score == null)
score = heuristic.score(sa);
if (score[s.playerTurn()] > best) {
best = score[s.playerTurn()];
bestAction = a;
}
}
controller.stop();
return bestAction;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.