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/smtp/src/org/subethamail/smtp/command/DataCommand.java b/smtp/src/org/subethamail/smtp/command/DataCommand.java
index 8308700..2289e50 100644
--- a/smtp/src/org/subethamail/smtp/command/DataCommand.java
+++ b/smtp/src/org/subethamail/smtp/command/DataCommand.java
@@ -1,40 +1,40 @@
package org.subethamail.smtp.command;
import java.io.IOException;
import org.subethamail.smtp.server.BaseCommand;
import org.subethamail.smtp.server.ConnectionContext;
import org.subethamail.smtp.server.Session;
/**
* @author Ian McFarland <[email protected]>
* @author Jon Stevens
* @author Jeff Schnitzer
*/
public class DataCommand extends BaseCommand
{
public DataCommand()
{
super("DATA", "Following text is collected as the message.\n" + "End data with <CR><LF>.<CR><LF>");
}
@Override
public void execute(String commandString, ConnectionContext context) throws IOException
{
Session session = context.getSession();
if (!session.getHasSender())
{
context.sendResponse("503 Error: need MAIL command");
return;
}
else if (session.getRecipientCount() == 0)
{
context.sendResponse("503 Error: need RCPT command");
return;
}
- context.sendResponse("354 End data with <CR><LF>.<CR><LF>");
session.setDataMode(true);
+ context.sendResponse("354 End data with <CR><LF>.<CR><LF>");
}
}
| false | true | public void execute(String commandString, ConnectionContext context) throws IOException
{
Session session = context.getSession();
if (!session.getHasSender())
{
context.sendResponse("503 Error: need MAIL command");
return;
}
else if (session.getRecipientCount() == 0)
{
context.sendResponse("503 Error: need RCPT command");
return;
}
context.sendResponse("354 End data with <CR><LF>.<CR><LF>");
session.setDataMode(true);
}
| public void execute(String commandString, ConnectionContext context) throws IOException
{
Session session = context.getSession();
if (!session.getHasSender())
{
context.sendResponse("503 Error: need MAIL command");
return;
}
else if (session.getRecipientCount() == 0)
{
context.sendResponse("503 Error: need RCPT command");
return;
}
session.setDataMode(true);
context.sendResponse("354 End data with <CR><LF>.<CR><LF>");
}
|
diff --git a/src/org/ohmage/domain/campaign/prompt/BoundedPrompt.java b/src/org/ohmage/domain/campaign/prompt/BoundedPrompt.java
index e9395ceb..e3f0091f 100644
--- a/src/org/ohmage/domain/campaign/prompt/BoundedPrompt.java
+++ b/src/org/ohmage/domain/campaign/prompt/BoundedPrompt.java
@@ -1,366 +1,376 @@
/*******************************************************************************
* Copyright 2012 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.domain.campaign.prompt;
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.json.JSONException;
import org.json.JSONObject;
import org.ohmage.config.grammar.custom.ConditionValuePair;
import org.ohmage.domain.campaign.Prompt;
import org.ohmage.domain.campaign.Response.NoResponse;
import org.ohmage.exception.DomainException;
/**
* This class represents prompts with numeric bounds. This includes but is not
* limited to numeric prompts where the numeric response must be between two
* numbers as well as text prompts where the number of characters that make up
* the result must be between two numbers.
*
* @author John Jenkins
*/
public abstract class BoundedPrompt extends Prompt {
private static final String JSON_KEY_LOWER_BOUND = "min";
private static final String JSON_KEY_UPPER_BOUND = "max";
private static final String JSON_KEY_DEFAULT = "default";
/**
* The campaign configuration property key for the lower bound.
*/
public static final String XML_KEY_MIN = "min";
/**
* The campaign configuration property key for the upper bound.
*/
public static final String XML_KEY_MAX = "max";
private final long min;
private final long max;
private final Long defaultValue;
/**
* Creates a new bounded prompt.
*
* @param condition The condition determining if this prompt should be
* displayed.
*
* @param id The unique identifier for the prompt within its survey item
* group.
*
* @param unit The unit value for this prompt.
*
* @param text The text to be displayed to the user for this prompt.
*
* @param abbreviatedText An abbreviated version of the text to be
* displayed to the user for this prompt.
*
* @param explanationText A more-verbose version of the text to be
* displayed to the user for this prompt.
*
* @param skippable Whether or not this prompt may be skipped.
*
* @param skipLabel The text to show to the user indicating that the prompt
* may be skipped.
*
* @param displayType This prompt's
* {@link org.ohmage.domain.campaign.Prompt.DisplayType}.
*
* @param displayLabel The display label for this prompt.
*
* @param min The lower bound for a response to this prompt.
*
* @param max The upper bound for a response to this prompt.
*
* @param defaultValue The default value for this prompt. This is optional
* and may be null if one doesn't exist.
*
* @param type This prompt's
* {@link org.ohmage.domain.campaign.Prompt.Type}.
*
* @param index This prompt's index in its container's list of survey
* items.
*
* @throws DomainException Thrown if any of the required parameters are
* missing or invalid.
*/
public BoundedPrompt(
final String id,
final String condition,
final String unit,
final String text,
final String abbreviatedText,
final String explanationText,
final boolean skippable,
final String skipLabel,
final DisplayType displayType,
final String displayLabel,
final long min,
final long max,
final Long defaultValue,
final Type type,
final int index)
throws DomainException {
super(id, condition, unit, text, abbreviatedText, explanationText,
skippable, skipLabel, displayType, displayLabel,
type, index);
this.min = min;
this.max = max;
if(defaultValue != null) {
if(defaultValue < min) {
throw new DomainException(
"The default value is less than the minimum value.");
}
else if(defaultValue > max) {
throw new DomainException(
"The default value is greater than hte maximum value.");
}
}
this.defaultValue = defaultValue;
}
/**
* Returns the lower bound for a response to this prompt.
*
* @return The lower bound for a response to this prompt.
*/
public long getMin() {
return min;
}
/**
* Returns the upper bound for a response to this prompt.
*
* @return The upper bound for a response to this prompt.
*/
public long getMax() {
return max;
}
/**
* Returns the default value.
*
* @return The default value. This may be null if none was given.
*/
public Long getDefault() {
return defaultValue;
}
/**
* Verifies that the value of the condition is not outside the bounds of
* the prompt.
*
* @param pair The condition-value pair to validate.
*
* @throws DomainException The value was not a number or was outside the
* predefined bounds.
*/
@Override
public void validateConditionValuePair(
final ConditionValuePair pair)
throws DomainException {
try {
long value = Long.decode(pair.getValue());
if(value < min) {
throw new DomainException(
"The value of the condition is less than the minimum allowed value (" +
min +
"): " +
pair.getValue());
}
else if(value > max) {
throw new DomainException(
"The value of the condition is greater than the maximum allowed value (" +
max +
"): " +
pair.getValue());
}
}
catch(NumberFormatException e) {
if(! checkNoResponseConditionValuePair(pair)) {
throw new DomainException(
"The value of the condition is not a number: " +
pair.getValue(),
e);
}
}
}
/**
* Validates that a given value is valid and, if so, converts it into an
* appropriate object.
*
* @param value The value to be validated. This must be one of the
* following:<br />
* <ul>
* <li>{@link NoResponse}</li>
* <li>{@link AtomicInteger}</li>
* <li>{@link AtomicLong}</li>
* <li>{@link BigInteger}</li>
* <li>{@link Integer}</li>
* <li>{@link Long}</li>
* <li>{@link Short}</li>
* <li>{@link String} that represents:</li>
* <ul>
* <li>{@link NoResponse}</li>
* <li>A whole number.</li>
* <ul>
* </ul>
*
* @return A {@link Long} object or a {@link NoResponse} object.
*
* @throws DomainException The value is invalid.
*/
@Override
public Object validateValue(final Object value) throws DomainException {
long longValue;
// If it's already a NoResponse value, then return make sure that if it
// was skipped that it as skippable.
if(value instanceof NoResponse) {
if(NoResponse.SKIPPED.equals(value) && (! skippable())) {
throw new DomainException(
"The prompt was skipped, but it is not skippable.");
}
return value;
}
// If it's already a number, first ensure that it is an integer and not
// a floating point number.
else if(value instanceof Number) {
if((value instanceof AtomicInteger) ||
(value instanceof AtomicLong) ||
(value instanceof BigInteger) ||
(value instanceof Integer) ||
(value instanceof Long) ||
(value instanceof Short)) {
longValue = ((Number) value).longValue();
}
else {
throw new DomainException("Only whole numbers are allowed.");
}
}
// If it is a string, parse it to check if it's a NoResponse value and,
// if not, parse it as a long. If that does not work either, throw an
// exception.
else if(value instanceof String) {
String stringValue = (String) value;
try {
//throw new NoResponseException(NoResponse.valueOf(stringValue));
return NoResponse.valueOf(stringValue);
}
catch(IllegalArgumentException iae) {
try {
longValue = Long.decode(stringValue);
}
catch(NumberFormatException nfe) {
throw new DomainException(
"The value is not a valid number.",
nfe);
}
}
}
// Finally, if its type is unknown, throw an exception.
else {
throw new DomainException(
"The value is not decodable as a response value.");
}
// Now that we have a Long value, verify that it is within bounds.
if(longValue < min) {
throw new DomainException(
- "The value is less than the lower bound.");
+ "The value is less than the lower bound (" +
+ min +
+ ") for the prompt, '" +
+ getId() +
+ "': " +
+ longValue);
}
else if(longValue > max) {
throw new DomainException(
- "The value is greater than the lower bound.");
+ "The value is greater than the upper bound (" +
+ max +
+ ") for the prompt, '" +
+ getId() +
+ "': " +
+ longValue);
}
return longValue;
}
/**
* Creates a JSONObject that represents this bounded prompt.
*
* @return A JSONObject that represents this bounded prompt.
*
* @throws JSONException There was a problem creating the JSONObject.
*/
@Override
public JSONObject toJson() throws JSONException {
JSONObject result = super.toJson();
result.put(JSON_KEY_LOWER_BOUND, min);
result.put(JSON_KEY_UPPER_BOUND, max);
result.put(JSON_KEY_DEFAULT, defaultValue);
return result;
}
/**
* Returns a hash code representing this prompt.
*
* @return A hash code representing this prompt.
*/
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result
+ ((defaultValue == null) ? 0 : defaultValue.hashCode());
result = prime * result + (int) (max ^ (max >>> 32));
result = prime * result + (int) (min ^ (min >>> 32));
return result;
}
/**
* Determines if this bounded prompt and another object are logically
* equal.
*
* @param obj The other object.
*
* @return True if the object is logically equivalent to this bounded
* prompt; false, otherwise.
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
BoundedPrompt other = (BoundedPrompt) obj;
if (defaultValue == null) {
if (other.defaultValue != null)
return false;
} else if (!defaultValue.equals(other.defaultValue))
return false;
if (max != other.max)
return false;
if (min != other.min)
return false;
return true;
}
}
| false | true | public Object validateValue(final Object value) throws DomainException {
long longValue;
// If it's already a NoResponse value, then return make sure that if it
// was skipped that it as skippable.
if(value instanceof NoResponse) {
if(NoResponse.SKIPPED.equals(value) && (! skippable())) {
throw new DomainException(
"The prompt was skipped, but it is not skippable.");
}
return value;
}
// If it's already a number, first ensure that it is an integer and not
// a floating point number.
else if(value instanceof Number) {
if((value instanceof AtomicInteger) ||
(value instanceof AtomicLong) ||
(value instanceof BigInteger) ||
(value instanceof Integer) ||
(value instanceof Long) ||
(value instanceof Short)) {
longValue = ((Number) value).longValue();
}
else {
throw new DomainException("Only whole numbers are allowed.");
}
}
// If it is a string, parse it to check if it's a NoResponse value and,
// if not, parse it as a long. If that does not work either, throw an
// exception.
else if(value instanceof String) {
String stringValue = (String) value;
try {
//throw new NoResponseException(NoResponse.valueOf(stringValue));
return NoResponse.valueOf(stringValue);
}
catch(IllegalArgumentException iae) {
try {
longValue = Long.decode(stringValue);
}
catch(NumberFormatException nfe) {
throw new DomainException(
"The value is not a valid number.",
nfe);
}
}
}
// Finally, if its type is unknown, throw an exception.
else {
throw new DomainException(
"The value is not decodable as a response value.");
}
// Now that we have a Long value, verify that it is within bounds.
if(longValue < min) {
throw new DomainException(
"The value is less than the lower bound.");
}
else if(longValue > max) {
throw new DomainException(
"The value is greater than the lower bound.");
}
return longValue;
}
| public Object validateValue(final Object value) throws DomainException {
long longValue;
// If it's already a NoResponse value, then return make sure that if it
// was skipped that it as skippable.
if(value instanceof NoResponse) {
if(NoResponse.SKIPPED.equals(value) && (! skippable())) {
throw new DomainException(
"The prompt was skipped, but it is not skippable.");
}
return value;
}
// If it's already a number, first ensure that it is an integer and not
// a floating point number.
else if(value instanceof Number) {
if((value instanceof AtomicInteger) ||
(value instanceof AtomicLong) ||
(value instanceof BigInteger) ||
(value instanceof Integer) ||
(value instanceof Long) ||
(value instanceof Short)) {
longValue = ((Number) value).longValue();
}
else {
throw new DomainException("Only whole numbers are allowed.");
}
}
// If it is a string, parse it to check if it's a NoResponse value and,
// if not, parse it as a long. If that does not work either, throw an
// exception.
else if(value instanceof String) {
String stringValue = (String) value;
try {
//throw new NoResponseException(NoResponse.valueOf(stringValue));
return NoResponse.valueOf(stringValue);
}
catch(IllegalArgumentException iae) {
try {
longValue = Long.decode(stringValue);
}
catch(NumberFormatException nfe) {
throw new DomainException(
"The value is not a valid number.",
nfe);
}
}
}
// Finally, if its type is unknown, throw an exception.
else {
throw new DomainException(
"The value is not decodable as a response value.");
}
// Now that we have a Long value, verify that it is within bounds.
if(longValue < min) {
throw new DomainException(
"The value is less than the lower bound (" +
min +
") for the prompt, '" +
getId() +
"': " +
longValue);
}
else if(longValue > max) {
throw new DomainException(
"The value is greater than the upper bound (" +
max +
") for the prompt, '" +
getId() +
"': " +
longValue);
}
return longValue;
}
|
diff --git a/src/frontend/EditingWindow.java b/src/frontend/EditingWindow.java
index 0e55de3..1fed27e 100644
--- a/src/frontend/EditingWindow.java
+++ b/src/frontend/EditingWindow.java
@@ -1,190 +1,192 @@
package frontend;
import java.awt.Toolkit;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Scanner;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.KeyStroke;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
import org.fife.ui.rtextarea.RTextScrollPane;
import edithistory.UndoController;
/**
* An editing view controller. Accepts a document and manages its editing and
* undo views as well as saving and loading.
*
* @author samuelainsworth
*
*/
public class EditingWindow {
private final Bruno parentApp;
private final DocumentModel doc;
private RSyntaxTextArea textArea;
private RTextScrollPane scrollPane;
private UndoController undoController;
public EditingWindow(final Bruno parentApp, final DocumentModel doc)
throws IOException, ClassNotFoundException {
this.parentApp = parentApp;
this.doc = doc;
// Read contents of file
StringBuilder contents = new StringBuilder();
if (doc.getFile() != null) {
Scanner scanner = null;
try {
scanner = new Scanner(doc.getFile());
while (scanner.hasNextLine()) {
contents.append(scanner.nextLine()
+ System.getProperty("line.separator"));
}
} finally {
scanner.close();
}
}
textArea = new RSyntaxTextArea();
textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
textArea.setCodeFoldingEnabled(true);
textArea.setAntiAliasingEnabled(true);
scrollPane = new RTextScrollPane(textArea);
scrollPane.setFoldIndicatorEnabled(true);
scrollPane.setLineNumbersEnabled(true);
// Set text in text area
textArea.setText(contents.toString());
// Stay at the top of the document
textArea.setCaretPosition(0);
// Setup undo tree
if (doc.getMetadataFile() != null && doc.getMetadataFile().exists()) {
// Read from metadata file if it exists
ObjectInputStream metadataStream = new ObjectInputStream(
new FileInputStream(doc.getMetadataFile()));
undoController = (UndoController) metadataStream.readObject();
metadataStream.close();
undoController.setTextArea(textArea);
} else {
// Otherwise, start with a blank slate
undoController = new UndoController(textArea);
}
textArea.getDocument().addUndoableEditListener(undoController);
textArea.getInputMap().put(
KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit
.getDefaultToolkit().getMenuShortcutKeyMask()),
undoController.getUndoAction());
/*
* textArea.getInputMap().put( KeyStroke.getKeyStroke(KeyEvent.VK_Z,
* Toolkit .getDefaultToolkit().getMenuShortcutKeyMask() +
* Event.SHIFT_MASK), undoController.getRedoAction());
*/
textArea.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
try {
- save();
+ if (doc != null && doc.getFile() != null) {
+ save();
+ }
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
@Override
public void focusGained(FocusEvent e) {
// Update the title bar
String filename = "Untitled";
if (doc.getFile() != null) {
filename = doc.getFile().getName();
}
parentApp.setTitle(filename + " - Bruno");
}
});
}
/**
* Save the document.
*
* @throws IOException
*/
public void save(boolean showEvenIfNewAndEmpty) throws IOException {
if (doc.getFile() == null) {
// If the file is unsaved and empty, ignore
if (textArea.getText().isEmpty() && !showEvenIfNewAndEmpty) {
return;
}
final JFileChooser fc = new JFileChooser();
fc.setFileFilter(new BrunoFileFilter());
if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
doc.setFile(file);
} else {
// They chose cancel, don't do anything else
return;
}
}
Writer writer = new OutputStreamWriter(new FileOutputStream(
doc.getFile()));
writer.write(textArea.getText());
writer.close();
// File where will we store edit history, etc.
ObjectOutputStream metadataWriter = new ObjectOutputStream(
new FileOutputStream(doc.getMetadataFile()));
// Save metadata
metadataWriter.writeObject(undoController);
metadataWriter.close();
}
public void save() throws IOException {
save(false);
}
public boolean requestFocusInWindow() {
return textArea.requestFocusInWindow();
}
public DocumentModel getDoc() {
return doc;
}
public RSyntaxTextArea getTextArea() {
return textArea;
}
public JComponent getView() {
return scrollPane;
}
public UndoController getUndoController() {
return undoController;
}
public void setSyntaxStyle(String syntaxStyle) {
getTextArea().setSyntaxEditingStyle(syntaxStyle);
getUndoController().setSyntaxStyle(syntaxStyle);
}
}
| true | true | public EditingWindow(final Bruno parentApp, final DocumentModel doc)
throws IOException, ClassNotFoundException {
this.parentApp = parentApp;
this.doc = doc;
// Read contents of file
StringBuilder contents = new StringBuilder();
if (doc.getFile() != null) {
Scanner scanner = null;
try {
scanner = new Scanner(doc.getFile());
while (scanner.hasNextLine()) {
contents.append(scanner.nextLine()
+ System.getProperty("line.separator"));
}
} finally {
scanner.close();
}
}
textArea = new RSyntaxTextArea();
textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
textArea.setCodeFoldingEnabled(true);
textArea.setAntiAliasingEnabled(true);
scrollPane = new RTextScrollPane(textArea);
scrollPane.setFoldIndicatorEnabled(true);
scrollPane.setLineNumbersEnabled(true);
// Set text in text area
textArea.setText(contents.toString());
// Stay at the top of the document
textArea.setCaretPosition(0);
// Setup undo tree
if (doc.getMetadataFile() != null && doc.getMetadataFile().exists()) {
// Read from metadata file if it exists
ObjectInputStream metadataStream = new ObjectInputStream(
new FileInputStream(doc.getMetadataFile()));
undoController = (UndoController) metadataStream.readObject();
metadataStream.close();
undoController.setTextArea(textArea);
} else {
// Otherwise, start with a blank slate
undoController = new UndoController(textArea);
}
textArea.getDocument().addUndoableEditListener(undoController);
textArea.getInputMap().put(
KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit
.getDefaultToolkit().getMenuShortcutKeyMask()),
undoController.getUndoAction());
/*
* textArea.getInputMap().put( KeyStroke.getKeyStroke(KeyEvent.VK_Z,
* Toolkit .getDefaultToolkit().getMenuShortcutKeyMask() +
* Event.SHIFT_MASK), undoController.getRedoAction());
*/
textArea.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
try {
save();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
@Override
public void focusGained(FocusEvent e) {
// Update the title bar
String filename = "Untitled";
if (doc.getFile() != null) {
filename = doc.getFile().getName();
}
parentApp.setTitle(filename + " - Bruno");
}
});
}
| public EditingWindow(final Bruno parentApp, final DocumentModel doc)
throws IOException, ClassNotFoundException {
this.parentApp = parentApp;
this.doc = doc;
// Read contents of file
StringBuilder contents = new StringBuilder();
if (doc.getFile() != null) {
Scanner scanner = null;
try {
scanner = new Scanner(doc.getFile());
while (scanner.hasNextLine()) {
contents.append(scanner.nextLine()
+ System.getProperty("line.separator"));
}
} finally {
scanner.close();
}
}
textArea = new RSyntaxTextArea();
textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
textArea.setCodeFoldingEnabled(true);
textArea.setAntiAliasingEnabled(true);
scrollPane = new RTextScrollPane(textArea);
scrollPane.setFoldIndicatorEnabled(true);
scrollPane.setLineNumbersEnabled(true);
// Set text in text area
textArea.setText(contents.toString());
// Stay at the top of the document
textArea.setCaretPosition(0);
// Setup undo tree
if (doc.getMetadataFile() != null && doc.getMetadataFile().exists()) {
// Read from metadata file if it exists
ObjectInputStream metadataStream = new ObjectInputStream(
new FileInputStream(doc.getMetadataFile()));
undoController = (UndoController) metadataStream.readObject();
metadataStream.close();
undoController.setTextArea(textArea);
} else {
// Otherwise, start with a blank slate
undoController = new UndoController(textArea);
}
textArea.getDocument().addUndoableEditListener(undoController);
textArea.getInputMap().put(
KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit
.getDefaultToolkit().getMenuShortcutKeyMask()),
undoController.getUndoAction());
/*
* textArea.getInputMap().put( KeyStroke.getKeyStroke(KeyEvent.VK_Z,
* Toolkit .getDefaultToolkit().getMenuShortcutKeyMask() +
* Event.SHIFT_MASK), undoController.getRedoAction());
*/
textArea.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
try {
if (doc != null && doc.getFile() != null) {
save();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
@Override
public void focusGained(FocusEvent e) {
// Update the title bar
String filename = "Untitled";
if (doc.getFile() != null) {
filename = doc.getFile().getName();
}
parentApp.setTitle(filename + " - Bruno");
}
});
}
|
diff --git a/src/org/freshwaterlife/fishlink/xlwrap/SheetWrite.java b/src/org/freshwaterlife/fishlink/xlwrap/SheetWrite.java
index 6393eae..a5c8c2d 100644
--- a/src/org/freshwaterlife/fishlink/xlwrap/SheetWrite.java
+++ b/src/org/freshwaterlife/fishlink/xlwrap/SheetWrite.java
@@ -1,493 +1,494 @@
package org.freshwaterlife.fishlink.xlwrap;
import org.freshwaterlife.fishlink.FishLinkException;
import at.jku.xlwrap.spreadsheet.Sheet;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import org.freshwaterlife.fishlink.FishLinkConstants;
import org.freshwaterlife.fishlink.FishLinkUtils;
import org.freshwaterlife.fishlink.ZeroNullType;
/**
*
* @author Christian
*/
public class SheetWrite extends AbstractSheet{
private int sheetNumber;
private String dataPath;
private String pid;
private NameChecker masterNameChecker;
private HashMap<String,String> idColumns;
private HashMap<String,String> categoryUris;
private ArrayList<String> allColumns;
SheetWrite (NameChecker nameChecker, Sheet annotatedSheet, int sheetNumber, String url, String pid)
throws FishLinkException{
super(annotatedSheet);
this.pid = pid;
this.sheetNumber = sheetNumber;
this.dataPath = url;
this.masterNameChecker = nameChecker;
idColumns = new HashMap<String,String>();
categoryUris = new HashMap<String,String>();
allColumns = new ArrayList<String>();
}
String getSheetInfo(){
return sheet.getSheetInfo();
}
private String template(){
return sheet.getName() + "template";
}
void writeMapping(BufferedWriter writer) throws FishLinkException{
try {
writer.write(" xl:offline \"false\"^^xsd:boolean ;");
writer.newLine();
writer.write(" xl:template [");
writer.newLine();
writer.write(" xl:fileName \"" + dataPath + "\" ;");
writer.newLine();
writer.write(" xl:sheetNumber \""+ sheetNumber +"\" ;");
writer.newLine();
writer.write(" xl:templateGraph :");
writer.write(template());
writer.write(" ;");
writer.newLine();
writer.write(" xl:transform [");
writer.newLine();
writer.write(" a rdf:Seq ;");
writer.newLine();
writer.write(" rdf:_1 [");
writer.newLine();
writer.write(" a xl:RowShift ;");
writer.newLine();
writer.write(" xl:restriction \"B" + firstData + ":" + lastDataColumn + firstData + "\" ;");
writer.newLine();
writer.write(" xl:steps \"1\" ;");
writer.newLine();
writer.write(" ] ;");
writer.newLine();
writer.write(" ]");
writer.newLine();
writer.write(" ] ;");
writer.newLine();
} catch (IOException ex) {
throw new FishLinkException("Unable to write mapping", ex);
}
}
private void writeUri(BufferedWriter writer, String category, String field, String idType,
String dataColumn, ZeroNullType zeroVsNulls) throws FishLinkException {
if(category.equalsIgnoreCase(FishLinkConstants.OBSERVATION_LABEL)) {
writeObservationUril(writer, field, idType, dataColumn, zeroVsNulls);
} else if (idType == null || idType.isEmpty() || idType.equalsIgnoreCase("n/a") ||
idType.equalsIgnoreCase(FishLinkConstants.AUTOMATIC_LABEL)){
writeUri(writer, category, field, dataColumn, zeroVsNulls);
} else {
//There is an Id reference to another dataColumn.
if (idType.equalsIgnoreCase("row")){
throw new FishLinkException("IDType row not longer supported. Found in sheet " + sheet.getSheetInfo());
} else if (idType.equalsIgnoreCase(FishLinkConstants.ALL_LABEL)){
throw new FishLinkException("Unexpected IDType " + FishLinkConstants.ALL_LABEL);
} else {
String idCategory = this.getCellValue(idType, categoryRow);
String idColumn = idColumns.get(idCategory);
writeUri(writer, idCategory, field, idColumn, zeroVsNulls);
}
}
}
private void writeUri(BufferedWriter writer, String category, String field, String dataColumn,
ZeroNullType dataZeroVsNulls) throws FishLinkException {
String uri = categoryUris.get(category);
if (field.toLowerCase().equals(FishLinkConstants.ID_LABEL)){
try {
writer.write("[ xl:uri \"ID_URI('" + uri + "', " + dataColumn + firstData + ",'"
+ dataZeroVsNulls + "')\"^^xl:Expr ] ");
} catch (IOException ex) {
throw new FishLinkException("Unable to write uri", ex);
}
return;
}
writeUriOther(writer, uri, category, dataColumn, dataZeroVsNulls);
}
private void writeObservationUril(BufferedWriter writer, String field, String idColumn,
String dataColumn, ZeroNullType dataZeroNull) throws FishLinkException {
String uri = categoryUris.get(FishLinkConstants.OBSERVATION_LABEL);
if(field.equalsIgnoreCase(FishLinkConstants.VALUE_LABEL)) {
try {
writer.write("[ xl:uri \"CELL_URI('" + uri + "', " + dataColumn + firstData + ",'"
+ dataZeroNull + "')\"^^xl:Expr ] ");
} catch (IOException ex) {
throw new FishLinkException("Unable to write uri", ex);
}
return;
}
if (idColumn == null || idColumn.isEmpty()){
throw new FishLinkException(sheet.getSheetInfo() + " Data Column " + dataColumn + " with category " +
FishLinkConstants.OBSERVATION_LABEL + " and field " + field + " needs an id Type");
}
String idNullZeroString = getCellValue (idColumn, idTypeRow);
ZeroNullType idZeroNull = ZeroNullType.parse(idNullZeroString);
try {
writer.write("[ xl:uri \"CELL_URI('" + uri + "', " + idColumn + firstData + ", '" + idZeroNull + "' ,"
+ dataColumn + firstData + ",'" + dataZeroNull + "')\"^^xl:Expr ] ");
} catch (IOException ex) {
throw new FishLinkException("Unable to write uri", ex);
}
}
private void writeUriOther(BufferedWriter writer, String uri, String category,
String dataColumn, ZeroNullType dataZeroVsNulls) throws FishLinkException {
//"row" is added for automatic ones where no id column found.
String idColumn = idColumns.get(category);
try {
if (idColumn.equalsIgnoreCase("row")){
writer.write("[ xl:uri \"ROW_URI('" + uri + "', " + dataColumn + firstData + ",'" +
dataZeroVsNulls + "')\"^^xl:Expr ] ");
} else {
String zeroNullString = getCellValue (idColumn, ZeroNullRow);
ZeroNullType idZeroNull = ZeroNullType.parse(zeroNullString);
writer.write("[ xl:uri \"ID_URI('" + uri + "', " + idColumn + firstData + ",'" + idZeroNull + "'," +
dataColumn + firstData + ",'" + dataZeroVsNulls + "')\"^^xl:Expr ] ");
}
} catch (IOException ex) {
throw new FishLinkException("Unable to write uri", ex);
}
}
private void writeVocab (BufferedWriter writer, String vocab) throws FishLinkException {
try {
if (vocab.startsWith("is") || vocab.startsWith("has")){
writer.write(" vocab:" + vocab + "\t");
} else {
writer.write(" vocab:has" + vocab + "\t");
}
} catch (IOException ex) {
throw new FishLinkException("Unable to write vocab", ex);
}
}
private void writeRdfType (BufferedWriter writer, String type) throws FishLinkException {
try {
writer.write (" rdf:type");
writeType(writer, type);
} catch (IOException ex) {
throw new FishLinkException("Unable to write vocab", ex);
}
}
private void writeType (BufferedWriter writer, String type) throws FishLinkException {
try {
writer.write (" type:" + type);
writer.write (" ;");
writer.newLine();
} catch (IOException ex) {
throw new FishLinkException("Unable to write vocab", ex);
}
}
private void writeConstant (BufferedWriter writer, String category, String column, int row)
throws FishLinkException{
String field = getCellValue ("A", row);
if (field == null){
return;
}
String value = getCellValue (column, row);
if (value == null){
return;
}
if (value.equalsIgnoreCase("n/a")){
return;
}
if (FishLinkConstants.isRdfTypeField(field)){
masterNameChecker.checkSubType(sheet.getSheetInfo(), category, value);
writeRdfType(writer, value);
} else {
masterNameChecker.checkConstant(sheet.getSheetInfo(), field, value);
writeVocab (writer, field);
if (!value.startsWith("'")){
value = "'" + value ;
}
if (!value.endsWith("'")){
value = value + "'";
}
try {
writer.write("[ xl:uri \"'" + FishLinkConstants.RDF_BASE_URL + "constant/' & URLENCODE(" + value + ")\"^^xl:Expr ] ;");
writer.newLine();
} catch (IOException ex) {
throw new FishLinkException("Unable to write constant", ex);
}
}
}
private ZeroNullType getZeroVsNull (String column) throws FishLinkException {
if (ZeroNullRow >= 0){
String ignoreZeroString = getCellValue (column, ZeroNullRow);
if (ignoreZeroString == null){
return ZeroNullType.KEEP;
} else if (ignoreZeroString.isEmpty()){
return ZeroNullType.KEEP;
} return ZeroNullType.parse(ignoreZeroString);
} else{
return ZeroNullType.KEEP;
}
}
private String refersToCategory(String subjectCategory, String field) throws FishLinkException{
if ( masterNameChecker.isCategory(field)) {
System.out.println("£££");
return field;
}
if (FishLinkConstants.refersToSameCategery(field)){
return subjectCategory;
}
return FishLinkConstants.refersToCategory(field);
}
private void writeData(BufferedWriter writer, String subjectCategory, String column, ZeroNullType zeroNull)
throws FishLinkException {
String field = getCellValue (column, fieldRow);
writeVocab(writer, field);
String category = refersToCategory(subjectCategory, field);
System.out.println(field + " = " + category);
try {
if (category == null) {
switch (zeroNull){
case KEEP:
writer.write("\"" + column + firstData + "\"^^xl:Expr ;");
break;
case ZEROS_AS_NULLS:
writer.write("\"ZERO_AS_NULL(" + column + firstData + ")\"^^xl:Expr ;");
break;
case NULLS_AS_ZERO:
writer.write("\"NULL_AS_ZERO(" + column + firstData + ")\"^^xl:Expr ;");
break;
default:
throw new FishLinkException("Unexpected ZeroNullType " + zeroNull);
}
} else {
String uri = getUri(column, category);
writer.write("[ xl:uri \"ID_URI('" + uri + "'," + column + firstData + ", '" + zeroNull +
"')\"^^xl:Expr ];");
}
writer.newLine();
} catch (IOException ex) {
throw new FishLinkException("Unable to write data", ex);
}
}
private void writeAutoRelated(BufferedWriter writer, String category, String column, ZeroNullType dataZeroVsNulls)
throws FishLinkException {
String related = FishLinkConstants.autoRelatedCategory(category);
if (related == null){
return;
}
String uri = categoryUris.get(related);
if (uri == null){
return;
}
writeVocab(writer, related);
writeUriOther(writer, uri, category, column, dataZeroVsNulls);
try {
writer.write(";");
writer.newLine();
} catch (IOException ex) {
throw new FishLinkException("Unable to write ", ex);
}
}
private void writeAllRelated(BufferedWriter writer, String category, ZeroNullType zeroVsNulls)
throws FishLinkException {
if (!category.equalsIgnoreCase(FishLinkConstants.OBSERVATION_LABEL)){
return;
}
String uri = categoryUris.get(category);
for (String column : allColumns){
String idNullZeroString = getCellValue (column, ZeroNullRow);
ZeroNullType idZeroNull = ZeroNullType.parse(idNullZeroString);
writeData(writer, category, column, idZeroNull);
}
}
private boolean writeTemplateColumn(BufferedWriter writer, String column)
throws FishLinkException{
String category = getCellValue (column, categoryRow);
//ystem.out.println(category + " " + metaColumn + " " + categoryRow);
String field = getCellValue (column, fieldRow);
String idType = getCellValue (column, idTypeRow);
String external = getExternal(column);
if (category == null || category.toLowerCase().equals("undefined")) {
FishLinkUtils.report("Skippig column " + column + " as no Category provided");
+ return false;
}
if (field == null){
FishLinkUtils.report("Skippig column " + column + " as no Feild provided");
return false;
}
masterNameChecker.checkName(sheet.getSheetInfo(), category, field);
if (field.equalsIgnoreCase("id") && !external.isEmpty()){
FishLinkUtils.report("Skipping column " + column + " as it is an external id");
return false;
}
if (idType != null && idType.equals(FishLinkConstants.ALL_LABEL)){
FishLinkUtils.report("Skipping column " + column + " as it is an all column.");
return false;
}
ZeroNullType zeroNull =getZeroVsNull(column);
writeUri(writer, category, field, idType, column, zeroNull);
try {
writer.write (" a ");
writeType (writer, category);
} catch (IOException ex) {
throw new FishLinkException("Unable to write a type", ex);
}
writeData(writer, category, column, zeroNull);
writeAutoRelated(writer, category, column, zeroNull);
writeAllRelated(writer, category, zeroNull);
for (int row = firstConstant; row <= lastConstant; row++){
writeConstant(writer, category, column, row);
}
try {
if (external.isEmpty()){
writeRdfType (writer, pid + "_" + sheet.getName() + "_" + category);
}
writer.write(".");
writer.newLine();
writer.newLine();
} catch (IOException ex) {
throw new FishLinkException("Unable to other type ", ex);
}
return true;
}
private String getExternal(String metaColumn) throws FishLinkException {
if (externalSheetRow < 1){
return "";
}
String externalFeild = getCellValue (metaColumn, externalSheetRow);
if (externalFeild == null){
return "";
}
return externalFeild;
}
private String getCatgerogyUri(String category){
return FishLinkConstants.RDF_BASE_URL + "resource/" + category + "_" + pid + "_" + sheet.getName() + "/";
}
private String getUri(String metaColumn , String category) throws FishLinkException {
String externalField = getExternal(metaColumn);
if (externalField.isEmpty()){
return getCatgerogyUri(category);
}
String externalPid;
String externalSheet;
if (externalField.startsWith("[")){
externalPid = externalField.substring(1, externalField.indexOf(']'));
externalSheet = externalField.substring( externalField.indexOf(']')+1);
} else {
externalPid = pid;
externalSheet = externalField;
}
return FishLinkConstants.RDF_BASE_URL + "resource/" + category + "_" + pid + "_" + externalSheet + "/";
}
private void findId(String category, String column) throws FishLinkException{
String field = getCellValue (column, fieldRow);
String id = idColumns.get(category);
if (field.equalsIgnoreCase("id")){
if (id == null || id.equalsIgnoreCase("row")){
System.out.println (column + " " +category + " " + column);
idColumns.put(category, column);
categoryUris.put(category, getUri(column, category));
} else {
throw new FishLinkException("Found two different id columns of type " + category);
}
} else {
if (id == null){
System.out.println (column + " " + category + " row");
idColumns.put(category, "row");
}//else leave the column or "row" already there.
if (categoryUris.get(category) == null){
categoryUris.put(category, getCatgerogyUri(category));
}
}
}
private void findAll(String category, String metaColumn) throws FishLinkException{
String idColumn = getCellValue (metaColumn, idTypeRow);
if (idColumn == null || !idColumn.equalsIgnoreCase("all")){
return;
}
if (category.equalsIgnoreCase(FishLinkConstants.OBSERVATION_LABEL)){
String field = getCellValue (metaColumn, fieldRow);
if (field == null || field.isEmpty()){
throw new FishLinkException ("All id.Value Column " + metaColumn + " missing a field value");
}
allColumns.add(metaColumn);
} else {
throw new FishLinkException ("All id.Value Column only supported for Categeroy " +
FishLinkConstants.OBSERVATION_LABEL);
}
}
private void findIds() throws FishLinkException{
int maxColumn = FishLinkUtils.alphaToIndex(lastDataColumn);
for (int i = 1; i < maxColumn; i++){
String metaColumn = FishLinkUtils.indexToAlpha(i);
String category = getCellValue (metaColumn, categoryRow);
if (category == null || category.isEmpty()){
//do nothing
} else {
findId(category, metaColumn);
findAll(category, metaColumn);
}
}
}
void writeTemplate(BufferedWriter writer) throws FishLinkException{
FishLinkUtils.report("Writing template for "+sheet.getSheetInfo());
findIds();
try {
writer.write(":");
writer.write(template());
writer.write(" {");
writer.newLine();
} catch (IOException ex) {
throw new FishLinkException("Unable to write template ", ex);
}
int maxColumn = FishLinkUtils.alphaToIndex(lastDataColumn);
boolean foundColumn = false;
//Start at 1 to ignore label column;
for (int i = 1; i < maxColumn; i++){
String column = FishLinkUtils.indexToAlpha(i);
if (writeTemplateColumn(writer, column)){
foundColumn = true;
}
}
if (!foundColumn){
throw new FishLinkException("No mappable columns found in sheet " + sheet.getSheetInfo());
}
try {
writer.write("}");
writer.newLine();
} catch (IOException ex) {
throw new FishLinkException("Unable to write template end ", ex);
}
}
}
| true | true | private boolean writeTemplateColumn(BufferedWriter writer, String column)
throws FishLinkException{
String category = getCellValue (column, categoryRow);
//ystem.out.println(category + " " + metaColumn + " " + categoryRow);
String field = getCellValue (column, fieldRow);
String idType = getCellValue (column, idTypeRow);
String external = getExternal(column);
if (category == null || category.toLowerCase().equals("undefined")) {
FishLinkUtils.report("Skippig column " + column + " as no Category provided");
}
if (field == null){
FishLinkUtils.report("Skippig column " + column + " as no Feild provided");
return false;
}
masterNameChecker.checkName(sheet.getSheetInfo(), category, field);
if (field.equalsIgnoreCase("id") && !external.isEmpty()){
FishLinkUtils.report("Skipping column " + column + " as it is an external id");
return false;
}
if (idType != null && idType.equals(FishLinkConstants.ALL_LABEL)){
FishLinkUtils.report("Skipping column " + column + " as it is an all column.");
return false;
}
ZeroNullType zeroNull =getZeroVsNull(column);
writeUri(writer, category, field, idType, column, zeroNull);
try {
writer.write (" a ");
writeType (writer, category);
} catch (IOException ex) {
throw new FishLinkException("Unable to write a type", ex);
}
writeData(writer, category, column, zeroNull);
writeAutoRelated(writer, category, column, zeroNull);
writeAllRelated(writer, category, zeroNull);
for (int row = firstConstant; row <= lastConstant; row++){
writeConstant(writer, category, column, row);
}
try {
if (external.isEmpty()){
writeRdfType (writer, pid + "_" + sheet.getName() + "_" + category);
}
writer.write(".");
writer.newLine();
writer.newLine();
} catch (IOException ex) {
throw new FishLinkException("Unable to other type ", ex);
}
return true;
}
| private boolean writeTemplateColumn(BufferedWriter writer, String column)
throws FishLinkException{
String category = getCellValue (column, categoryRow);
//ystem.out.println(category + " " + metaColumn + " " + categoryRow);
String field = getCellValue (column, fieldRow);
String idType = getCellValue (column, idTypeRow);
String external = getExternal(column);
if (category == null || category.toLowerCase().equals("undefined")) {
FishLinkUtils.report("Skippig column " + column + " as no Category provided");
return false;
}
if (field == null){
FishLinkUtils.report("Skippig column " + column + " as no Feild provided");
return false;
}
masterNameChecker.checkName(sheet.getSheetInfo(), category, field);
if (field.equalsIgnoreCase("id") && !external.isEmpty()){
FishLinkUtils.report("Skipping column " + column + " as it is an external id");
return false;
}
if (idType != null && idType.equals(FishLinkConstants.ALL_LABEL)){
FishLinkUtils.report("Skipping column " + column + " as it is an all column.");
return false;
}
ZeroNullType zeroNull =getZeroVsNull(column);
writeUri(writer, category, field, idType, column, zeroNull);
try {
writer.write (" a ");
writeType (writer, category);
} catch (IOException ex) {
throw new FishLinkException("Unable to write a type", ex);
}
writeData(writer, category, column, zeroNull);
writeAutoRelated(writer, category, column, zeroNull);
writeAllRelated(writer, category, zeroNull);
for (int row = firstConstant; row <= lastConstant; row++){
writeConstant(writer, category, column, row);
}
try {
if (external.isEmpty()){
writeRdfType (writer, pid + "_" + sheet.getName() + "_" + category);
}
writer.write(".");
writer.newLine();
writer.newLine();
} catch (IOException ex) {
throw new FishLinkException("Unable to other type ", ex);
}
return true;
}
|
diff --git a/src/main/java/org/lcf/android/data/DataManager.java b/src/main/java/org/lcf/android/data/DataManager.java
index 5eb638c..2422f5f 100644
--- a/src/main/java/org/lcf/android/data/DataManager.java
+++ b/src/main/java/org/lcf/android/data/DataManager.java
@@ -1,99 +1,100 @@
package org.lcf.android.data;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import android.util.Log;
import org.lcf.android.event.EventManager;
import org.lcf.android.event.EventThread;
import org.lcf.android.event.Observes;
import org.lcf.android.util.EncryptUtil;
import static org.lcf.android.data.Constants.DATA_REQ_EVENT;
@Singleton
public class DataManager{
public static final int DEFAULT_POOL_SIZE = 5;
protected Executor defaultExecutor = Executors.newFixedThreadPool(DEFAULT_POOL_SIZE);
@Inject EventManager eventManager;
@Observes(name="DATA_REQ_EVENT", threadType=EventThread.CURRENT)
public void onEvent(DataReqEvent event) {
defaultExecutor.execute(new DataTask(event,this.eventManager));
}
private static class DataTask implements java.lang.Runnable{
private DataReqEvent event;
private EventManager eventManager;
public DataTask(DataReqEvent event, EventManager eventManager){
this.event = event;
this.eventManager = eventManager;
}
public void run(){
if(event == null){
return;
}
HttpClient client=new DefaultHttpClient();
+ client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
//建立Http请求
HttpPost post = new HttpPost(Constants.getServerAddr() + event.getAddr());
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
TreeMap<String,Object> tm = new TreeMap<String,Object>();
if(event.getArgs() != null)
tm.putAll(event.getArgs());
if(event.getArgs() != null){
for(Map.Entry<String, Object> entry : tm.entrySet())
qparams.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
}
String queryString = URLEncodedUtils.format(qparams, "UTF-8");
//增加校验码
String signature = EncryptUtil.genSign(queryString + Constants.getSignature());
qparams.add(new BasicNameValuePair(Constants.SIGNATUE_NAME,signature ));
try {
post.setEntity(new UrlEncodedFormEntity(qparams, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//发送请求
String responseBody = null;
try {
BasicResponseHandler responseHandler = new BasicResponseHandler();
responseBody = client.execute(post, responseHandler);
//用json处理返回结果,发送结果事件
// try {
this.eventManager.fire(new DataRespEvent(this.event,responseBody));//new JSONObject(
// } catch (JSONException e) {
// Log.e(getClass().getName(), "Exception in Processing Json in DataManager::" + responseBody, e);
// }
}
catch (Exception e) {
Log.e(getClass().getName(), "Exception in DataManager", e);
this.eventManager.fire(new DataErrorEvent(this.event,e));
}
}
}
}
| true | true | public void run(){
if(event == null){
return;
}
HttpClient client=new DefaultHttpClient();
//建立Http请求
HttpPost post = new HttpPost(Constants.getServerAddr() + event.getAddr());
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
TreeMap<String,Object> tm = new TreeMap<String,Object>();
if(event.getArgs() != null)
tm.putAll(event.getArgs());
if(event.getArgs() != null){
for(Map.Entry<String, Object> entry : tm.entrySet())
qparams.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
}
String queryString = URLEncodedUtils.format(qparams, "UTF-8");
//增加校验码
String signature = EncryptUtil.genSign(queryString + Constants.getSignature());
qparams.add(new BasicNameValuePair(Constants.SIGNATUE_NAME,signature ));
try {
post.setEntity(new UrlEncodedFormEntity(qparams, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//发送请求
String responseBody = null;
try {
BasicResponseHandler responseHandler = new BasicResponseHandler();
responseBody = client.execute(post, responseHandler);
//用json处理返回结果,发送结果事件
// try {
this.eventManager.fire(new DataRespEvent(this.event,responseBody));//new JSONObject(
// } catch (JSONException e) {
// Log.e(getClass().getName(), "Exception in Processing Json in DataManager::" + responseBody, e);
// }
}
catch (Exception e) {
Log.e(getClass().getName(), "Exception in DataManager", e);
this.eventManager.fire(new DataErrorEvent(this.event,e));
}
}
| public void run(){
if(event == null){
return;
}
HttpClient client=new DefaultHttpClient();
client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
//建立Http请求
HttpPost post = new HttpPost(Constants.getServerAddr() + event.getAddr());
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
TreeMap<String,Object> tm = new TreeMap<String,Object>();
if(event.getArgs() != null)
tm.putAll(event.getArgs());
if(event.getArgs() != null){
for(Map.Entry<String, Object> entry : tm.entrySet())
qparams.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
}
String queryString = URLEncodedUtils.format(qparams, "UTF-8");
//增加校验码
String signature = EncryptUtil.genSign(queryString + Constants.getSignature());
qparams.add(new BasicNameValuePair(Constants.SIGNATUE_NAME,signature ));
try {
post.setEntity(new UrlEncodedFormEntity(qparams, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//发送请求
String responseBody = null;
try {
BasicResponseHandler responseHandler = new BasicResponseHandler();
responseBody = client.execute(post, responseHandler);
//用json处理返回结果,发送结果事件
// try {
this.eventManager.fire(new DataRespEvent(this.event,responseBody));//new JSONObject(
// } catch (JSONException e) {
// Log.e(getClass().getName(), "Exception in Processing Json in DataManager::" + responseBody, e);
// }
}
catch (Exception e) {
Log.e(getClass().getName(), "Exception in DataManager", e);
this.eventManager.fire(new DataErrorEvent(this.event,e));
}
}
|
diff --git a/src/org/yaxim/androidclient/service/XMPPService.java b/src/org/yaxim/androidclient/service/XMPPService.java
index 5b29615..104597d 100644
--- a/src/org/yaxim/androidclient/service/XMPPService.java
+++ b/src/org/yaxim/androidclient/service/XMPPService.java
@@ -1,466 +1,468 @@
package org.yaxim.androidclient.service;
import java.util.HashSet;
import java.util.concurrent.atomic.AtomicBoolean;
import org.yaxim.androidclient.IXMPPRosterCallback;
import org.yaxim.androidclient.MainWindow;
import org.yaxim.androidclient.R;
import org.yaxim.androidclient.exceptions.YaximXMPPException;
import org.yaxim.androidclient.util.ConnectionState;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
public class XMPPService extends GenericService {
private AtomicBoolean mConnectionDemanded = new AtomicBoolean(false); // should we try to reconnect?
private static final int RECONNECT_AFTER = 5;
private static final int RECONNECT_MAXIMUM = 10*60;
private static final String RECONNECT_ALARM = "org.yaxim.androidclient.RECONNECT_ALARM";
private int mReconnectTimeout = RECONNECT_AFTER;
private String mReconnectInfo = "";
private Intent mAlarmIntent = new Intent(RECONNECT_ALARM);
private PendingIntent mPAlarmIntent;
private BroadcastReceiver mAlarmReceiver = new ReconnectAlarmReceiver();
private ServiceNotification mServiceNotification = null;
private Smackable mSmackable;
private boolean create_account = false;
private IXMPPRosterService.Stub mService2RosterConnection;
private IXMPPChatService.Stub mServiceChatConnection;
private RemoteCallbackList<IXMPPRosterCallback> mRosterCallbacks = new RemoteCallbackList<IXMPPRosterCallback>();
private HashSet<String> mIsBoundTo = new HashSet<String>();
private Handler mMainHandler = new Handler();
@Override
public IBinder onBind(Intent intent) {
super.onBind(intent);
String chatPartner = intent.getDataString();
if ((chatPartner != null)) {
resetNotificationCounter(chatPartner);
mIsBoundTo.add(chatPartner);
return mServiceChatConnection;
}
return mService2RosterConnection;
}
@Override
public void onRebind(Intent intent) {
super.onRebind(intent);
String chatPartner = intent.getDataString();
if ((chatPartner != null)) {
mIsBoundTo.add(chatPartner);
resetNotificationCounter(chatPartner);
}
}
@Override
public boolean onUnbind(Intent intent) {
String chatPartner = intent.getDataString();
if ((chatPartner != null)) {
mIsBoundTo.remove(chatPartner);
}
return true;
}
@Override
public void onCreate() {
super.onCreate();
createServiceRosterStub();
createServiceChatStub();
mPAlarmIntent = PendingIntent.getBroadcast(this, 0, mAlarmIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
registerReceiver(mAlarmReceiver, new IntentFilter(RECONNECT_ALARM));
// for the initial connection, check if autoConnect is set
mConnectionDemanded.set(mConfig.autoConnect);
YaximBroadcastReceiver.initNetworkStatus(getApplicationContext());
if (mConfig.autoConnect) {
/*
* start our own service so it remains in background even when
* unbound
*/
Intent xmppServiceIntent = new Intent(this, XMPPService.class);
startService(xmppServiceIntent);
}
mServiceNotification = ServiceNotification.getInstance();
}
@Override
public void onDestroy() {
super.onDestroy();
((AlarmManager)getSystemService(Context.ALARM_SERVICE)).cancel(mPAlarmIntent);
mRosterCallbacks.kill();
if (mSmackable != null) {
manualDisconnect();
mSmackable.unRegisterCallback();
}
unregisterReceiver(mAlarmReceiver);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
logInfo("onStartCommand(), mConnectionDemanded=" + mConnectionDemanded.get());
if (intent != null) {
create_account = intent.getBooleanExtra("create_account", false);
if ("disconnect".equals(intent.getAction())) {
failConnection(getString(R.string.conn_networkchg));
return START_STICKY;
} else
if ("reconnect".equals(intent.getAction())) {
// reset reconnection timeout
mReconnectTimeout = RECONNECT_AFTER;
doConnect();
return START_STICKY;
} else
if ("ping".equals(intent.getAction())) {
if (mSmackable != null) {
mSmackable.sendServerPing();
return START_STICKY;
}
// if not yet connected, fall through to doConnect()
}
}
mConnectionDemanded.set(mConfig.autoConnect);
doConnect();
return START_STICKY;
}
private void createServiceChatStub() {
mServiceChatConnection = new IXMPPChatService.Stub() {
public void sendMessage(String user, String message)
throws RemoteException {
if (mSmackable != null)
mSmackable.sendMessage(user, message);
else
SmackableImp.sendOfflineMessage(getContentResolver(),
user, message);
}
public boolean isAuthenticated() throws RemoteException {
if (mSmackable != null) {
return mSmackable.isAuthenticated();
}
return false;
}
public void clearNotifications(String Jid) throws RemoteException {
clearNotification(Jid);
}
};
}
private void createServiceRosterStub() {
mService2RosterConnection = new IXMPPRosterService.Stub() {
public void registerRosterCallback(IXMPPRosterCallback callback)
throws RemoteException {
if (callback != null)
mRosterCallbacks.register(callback);
}
public void unregisterRosterCallback(IXMPPRosterCallback callback)
throws RemoteException {
if (callback != null)
mRosterCallbacks.unregister(callback);
}
public int getConnectionState() throws RemoteException {
if (mSmackable != null) {
return mSmackable.getConnectionState().ordinal();
} else {
return ConnectionState.OFFLINE.ordinal();
}
}
public String getConnectionStateString() throws RemoteException {
return XMPPService.this.getConnectionStateString();
}
public void setStatusFromConfig()
throws RemoteException {
- mSmackable.setStatusFromConfig();
- updateServiceNotification();
+ if (mSmackable != null) { // this should always be true, but stil...
+ mSmackable.setStatusFromConfig();
+ updateServiceNotification();
+ }
}
public void addRosterItem(String user, String alias, String group)
throws RemoteException {
try {
mSmackable.addRosterItem(user, alias, group);
} catch (YaximXMPPException e) {
shortToastNotify(e.getMessage());
logError("exception in addRosterItem(): " + e.getMessage());
}
}
public void addRosterGroup(String group) throws RemoteException {
mSmackable.addRosterGroup(group);
}
public void removeRosterItem(String user) throws RemoteException {
try {
mSmackable.removeRosterItem(user);
} catch (YaximXMPPException e) {
shortToastNotify(e.getMessage());
logError("exception in removeRosterItem(): "
+ e.getMessage());
}
}
public void moveRosterItemToGroup(String user, String group)
throws RemoteException {
try {
mSmackable.moveRosterItemToGroup(user, group);
} catch (YaximXMPPException e) {
shortToastNotify(e.getMessage());
logError("exception in moveRosterItemToGroup(): "
+ e.getMessage());
}
}
public void renameRosterItem(String user, String newName)
throws RemoteException {
try {
mSmackable.renameRosterItem(user, newName);
} catch (YaximXMPPException e) {
shortToastNotify(e.getMessage());
logError("exception in renameRosterItem(): "
+ e.getMessage());
}
}
public void renameRosterGroup(String group, String newGroup)
throws RemoteException {
mSmackable.renameRosterGroup(group, newGroup);
}
public void disconnect() throws RemoteException {
manualDisconnect();
}
public void connect() throws RemoteException {
mConnectionDemanded.set(true);
mReconnectTimeout = RECONNECT_AFTER;
doConnect();
}
public void sendPresenceRequest(String jid, String type)
throws RemoteException {
mSmackable.sendPresenceRequest(jid, type);
}
};
}
private String getConnectionStateString() {
StringBuilder sb = new StringBuilder();
sb.append(mReconnectInfo);
if (mSmackable != null && mSmackable.getLastError() != null) {
sb.append("\n");
sb.append(mSmackable.getLastError());
}
return sb.toString();
}
private void updateServiceNotification() {
ConnectionState cs = ConnectionState.OFFLINE;
if (mSmackable != null) {
cs = mSmackable.getConnectionState();
}
broadcastConnectionState(cs);
// do not show notification if not a foreground service
if (!mConfig.foregroundService)
return;
if (cs == ConnectionState.OFFLINE) {
mServiceNotification.hideNotification(this, SERVICE_NOTIFICATION);
return;
}
String title = getString(R.string.conn_title, mConfig.jabberID);
Notification n = new Notification(R.drawable.ic_offline, title,
System.currentTimeMillis());
n.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
Intent notificationIntent = new Intent(this, MainWindow.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
n.contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
String message;
if (cs == ConnectionState.ONLINE) {
message = MainWindow.getStatusTitle(this, mConfig.statusMode, mConfig.statusMessage);
n.icon = R.drawable.ic_online;
} else
message = getConnectionStateString();
n.setLatestEventInfo(this, title, message, n.contentIntent);
mServiceNotification.showNotification(this, SERVICE_NOTIFICATION,
n);
}
private void doConnect() {
mReconnectInfo = getString(R.string.conn_connecting);
updateServiceNotification();
if (mSmackable == null) {
createAdapter();
}
mSmackable.requestConnectionState(ConnectionState.ONLINE, create_account);
}
private void broadcastConnectionState(ConnectionState cs) {
final int broadCastItems = mRosterCallbacks.beginBroadcast();
for (int i = 0; i < broadCastItems; i++) {
try {
mRosterCallbacks.getBroadcastItem(i).connectionStateChanged(cs.ordinal());
} catch (RemoteException e) {
logError("caught RemoteException: " + e.getMessage());
}
}
mRosterCallbacks.finishBroadcast();
}
private NetworkInfo getNetworkInfo() {
Context ctx = getApplicationContext();
ConnectivityManager connMgr =
(ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
return connMgr.getActiveNetworkInfo();
}
private boolean networkConnected() {
NetworkInfo info = getNetworkInfo();
return info != null && info.isConnected();
}
private boolean networkConnectedOrConnecting() {
NetworkInfo info = getNetworkInfo();
return info != null && info.isConnectedOrConnecting();
}
// call this when Android tells us to shut down
private void failConnection(String reason) {
logInfo("failConnection: " + reason);
mReconnectInfo = reason;
updateServiceNotification();
if (mSmackable != null)
mSmackable.requestConnectionState(ConnectionState.DISCONNECTED);
}
// called from Smackable when connection broke down
private void connectionFailed(String reason) {
logInfo("connectionFailed: " + reason);
//TODO: error message from downstream?
//mLastConnectionError = reason;
if (!networkConnected()) {
mReconnectInfo = getString(R.string.conn_no_network);
mSmackable.requestConnectionState(ConnectionState.RECONNECT_NETWORK);
} else if (mConnectionDemanded.get()) {
mSmackable.requestConnectionState(ConnectionState.RECONNECT_DELAYED);
mReconnectInfo = getString(R.string.conn_reconnect, mReconnectTimeout);
logInfo("connectionFailed(): registering reconnect in " + mReconnectTimeout + "s");
((AlarmManager)getSystemService(Context.ALARM_SERVICE)).set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + mReconnectTimeout * 1000, mPAlarmIntent);
mReconnectTimeout = mReconnectTimeout * 2;
if (mReconnectTimeout > RECONNECT_MAXIMUM)
mReconnectTimeout = RECONNECT_MAXIMUM;
} else {
connectionClosed();
}
}
private void connectionClosed() {
logInfo("connectionClosed.");
mReconnectInfo = "";
mServiceNotification.hideNotification(this, SERVICE_NOTIFICATION);
}
public void manualDisconnect() {
mConnectionDemanded.set(false);
performDisconnect();
}
public void performDisconnect() {
if (mSmackable != null) {
// this is non-blocking
mSmackable.requestConnectionState(ConnectionState.OFFLINE);
}
}
private void createAdapter() {
System.setProperty("smack.debugEnabled", "" + mConfig.smackdebug);
try {
mSmackable = new SmackableImp(mConfig, getContentResolver(), this);
} catch (NullPointerException e) {
e.printStackTrace();
}
mSmackable.registerCallback(new XMPPServiceCallback() {
public void newMessage(String from, String message, boolean silent_notification) {
logInfo("notification: " + from);
notifyClient(from, mSmackable.getNameForJID(from), message, !mIsBoundTo.contains(from), silent_notification);
}
public void rosterChanged() {
}
public void connectionStateChanged() {
// TODO: OFFLINE is sometimes caused by XMPPConnection calling
// connectionClosed() callback on an error, need to catch that?
switch (mSmackable.getConnectionState()) {
//case OFFLINE:
case DISCONNECTED:
connectionFailed(getString(R.string.conn_disconnected));
break;
case ONLINE:
mReconnectTimeout = RECONNECT_AFTER;
default:
updateServiceNotification();
}
}
});
}
private class ReconnectAlarmReceiver extends BroadcastReceiver {
public void onReceive(Context ctx, Intent i) {
logInfo("Alarm received.");
if (!mConnectionDemanded.get()) {
return;
}
if (mSmackable != null && mSmackable.getConnectionState() == ConnectionState.ONLINE) {
logError("Reconnect attempt aborted: we are connected again!");
return;
}
doConnect();
}
}
}
| true | true | private void createServiceRosterStub() {
mService2RosterConnection = new IXMPPRosterService.Stub() {
public void registerRosterCallback(IXMPPRosterCallback callback)
throws RemoteException {
if (callback != null)
mRosterCallbacks.register(callback);
}
public void unregisterRosterCallback(IXMPPRosterCallback callback)
throws RemoteException {
if (callback != null)
mRosterCallbacks.unregister(callback);
}
public int getConnectionState() throws RemoteException {
if (mSmackable != null) {
return mSmackable.getConnectionState().ordinal();
} else {
return ConnectionState.OFFLINE.ordinal();
}
}
public String getConnectionStateString() throws RemoteException {
return XMPPService.this.getConnectionStateString();
}
public void setStatusFromConfig()
throws RemoteException {
mSmackable.setStatusFromConfig();
updateServiceNotification();
}
public void addRosterItem(String user, String alias, String group)
throws RemoteException {
try {
mSmackable.addRosterItem(user, alias, group);
} catch (YaximXMPPException e) {
shortToastNotify(e.getMessage());
logError("exception in addRosterItem(): " + e.getMessage());
}
}
public void addRosterGroup(String group) throws RemoteException {
mSmackable.addRosterGroup(group);
}
public void removeRosterItem(String user) throws RemoteException {
try {
mSmackable.removeRosterItem(user);
} catch (YaximXMPPException e) {
shortToastNotify(e.getMessage());
logError("exception in removeRosterItem(): "
+ e.getMessage());
}
}
public void moveRosterItemToGroup(String user, String group)
throws RemoteException {
try {
mSmackable.moveRosterItemToGroup(user, group);
} catch (YaximXMPPException e) {
shortToastNotify(e.getMessage());
logError("exception in moveRosterItemToGroup(): "
+ e.getMessage());
}
}
public void renameRosterItem(String user, String newName)
throws RemoteException {
try {
mSmackable.renameRosterItem(user, newName);
} catch (YaximXMPPException e) {
shortToastNotify(e.getMessage());
logError("exception in renameRosterItem(): "
+ e.getMessage());
}
}
public void renameRosterGroup(String group, String newGroup)
throws RemoteException {
mSmackable.renameRosterGroup(group, newGroup);
}
public void disconnect() throws RemoteException {
manualDisconnect();
}
public void connect() throws RemoteException {
mConnectionDemanded.set(true);
mReconnectTimeout = RECONNECT_AFTER;
doConnect();
}
public void sendPresenceRequest(String jid, String type)
throws RemoteException {
mSmackable.sendPresenceRequest(jid, type);
}
};
}
| private void createServiceRosterStub() {
mService2RosterConnection = new IXMPPRosterService.Stub() {
public void registerRosterCallback(IXMPPRosterCallback callback)
throws RemoteException {
if (callback != null)
mRosterCallbacks.register(callback);
}
public void unregisterRosterCallback(IXMPPRosterCallback callback)
throws RemoteException {
if (callback != null)
mRosterCallbacks.unregister(callback);
}
public int getConnectionState() throws RemoteException {
if (mSmackable != null) {
return mSmackable.getConnectionState().ordinal();
} else {
return ConnectionState.OFFLINE.ordinal();
}
}
public String getConnectionStateString() throws RemoteException {
return XMPPService.this.getConnectionStateString();
}
public void setStatusFromConfig()
throws RemoteException {
if (mSmackable != null) { // this should always be true, but stil...
mSmackable.setStatusFromConfig();
updateServiceNotification();
}
}
public void addRosterItem(String user, String alias, String group)
throws RemoteException {
try {
mSmackable.addRosterItem(user, alias, group);
} catch (YaximXMPPException e) {
shortToastNotify(e.getMessage());
logError("exception in addRosterItem(): " + e.getMessage());
}
}
public void addRosterGroup(String group) throws RemoteException {
mSmackable.addRosterGroup(group);
}
public void removeRosterItem(String user) throws RemoteException {
try {
mSmackable.removeRosterItem(user);
} catch (YaximXMPPException e) {
shortToastNotify(e.getMessage());
logError("exception in removeRosterItem(): "
+ e.getMessage());
}
}
public void moveRosterItemToGroup(String user, String group)
throws RemoteException {
try {
mSmackable.moveRosterItemToGroup(user, group);
} catch (YaximXMPPException e) {
shortToastNotify(e.getMessage());
logError("exception in moveRosterItemToGroup(): "
+ e.getMessage());
}
}
public void renameRosterItem(String user, String newName)
throws RemoteException {
try {
mSmackable.renameRosterItem(user, newName);
} catch (YaximXMPPException e) {
shortToastNotify(e.getMessage());
logError("exception in renameRosterItem(): "
+ e.getMessage());
}
}
public void renameRosterGroup(String group, String newGroup)
throws RemoteException {
mSmackable.renameRosterGroup(group, newGroup);
}
public void disconnect() throws RemoteException {
manualDisconnect();
}
public void connect() throws RemoteException {
mConnectionDemanded.set(true);
mReconnectTimeout = RECONNECT_AFTER;
doConnect();
}
public void sendPresenceRequest(String jid, String type)
throws RemoteException {
mSmackable.sendPresenceRequest(jid, type);
}
};
}
|
diff --git a/drools-analytics/src/test/java/org/drools/analytics/ConsequenceTest.java b/drools-analytics/src/test/java/org/drools/analytics/ConsequenceTest.java
index 1588dc2a80..29c4756380 100644
--- a/drools-analytics/src/test/java/org/drools/analytics/ConsequenceTest.java
+++ b/drools-analytics/src/test/java/org/drools/analytics/ConsequenceTest.java
@@ -1,61 +1,63 @@
package org.drools.analytics;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.drools.StatelessSession;
import org.drools.analytics.components.AnalyticsRule;
import org.drools.analytics.dao.AnalyticsDataFactory;
import org.drools.analytics.dao.AnalyticsResult;
import org.drools.analytics.report.components.AnalyticsMessage;
import org.drools.analytics.report.components.AnalyticsMessageBase;
import org.drools.base.RuleNameMatchesAgendaFilter;
/**
*
* @author Toni Rikkola
*
*/
public class ConsequenceTest extends TestBase {
- public void testMissingConsiquence() throws Exception {
+ public void testMissingConsequence() throws Exception {
StatelessSession session = getStatelessSession(this.getClass()
.getResourceAsStream("Consequence.drl"));
session.setAgendaFilter(new RuleNameMatchesAgendaFilter(
"No action - possibly commented out"));
+ AnalyticsDataFactory.getAnalyticsData();
Collection<? extends Object> testData = getTestData(this.getClass()
.getResourceAsStream("ConsequenceTest.drl"));
+ AnalyticsDataFactory.clearAnalyticsResult();
AnalyticsResult result = AnalyticsDataFactory.getAnalyticsResult();
session.setGlobal("result", result);
session.executeWithResults(testData);
Iterator<AnalyticsMessageBase> iter = result.getBySeverity(
AnalyticsMessageBase.Severity.WARNING).iterator();
Set<String> rulesThatHadErrors = new HashSet<String>();
while (iter.hasNext()) {
Object o = (Object) iter.next();
if (o instanceof AnalyticsMessage) {
AnalyticsRule rule = (AnalyticsRule) ((AnalyticsMessage) o)
.getFaulty();
rulesThatHadErrors.add(rule.getRuleName());
}
}
assertFalse(rulesThatHadErrors.contains("Has a consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 2"));
if (!rulesThatHadErrors.isEmpty()) {
for (String string : rulesThatHadErrors) {
fail("Rule " + string + " caused an error.");
}
}
}
}
| false | true | public void testMissingConsiquence() throws Exception {
StatelessSession session = getStatelessSession(this.getClass()
.getResourceAsStream("Consequence.drl"));
session.setAgendaFilter(new RuleNameMatchesAgendaFilter(
"No action - possibly commented out"));
Collection<? extends Object> testData = getTestData(this.getClass()
.getResourceAsStream("ConsequenceTest.drl"));
AnalyticsResult result = AnalyticsDataFactory.getAnalyticsResult();
session.setGlobal("result", result);
session.executeWithResults(testData);
Iterator<AnalyticsMessageBase> iter = result.getBySeverity(
AnalyticsMessageBase.Severity.WARNING).iterator();
Set<String> rulesThatHadErrors = new HashSet<String>();
while (iter.hasNext()) {
Object o = (Object) iter.next();
if (o instanceof AnalyticsMessage) {
AnalyticsRule rule = (AnalyticsRule) ((AnalyticsMessage) o)
.getFaulty();
rulesThatHadErrors.add(rule.getRuleName());
}
}
assertFalse(rulesThatHadErrors.contains("Has a consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 2"));
if (!rulesThatHadErrors.isEmpty()) {
for (String string : rulesThatHadErrors) {
fail("Rule " + string + " caused an error.");
}
}
}
| public void testMissingConsequence() throws Exception {
StatelessSession session = getStatelessSession(this.getClass()
.getResourceAsStream("Consequence.drl"));
session.setAgendaFilter(new RuleNameMatchesAgendaFilter(
"No action - possibly commented out"));
AnalyticsDataFactory.getAnalyticsData();
Collection<? extends Object> testData = getTestData(this.getClass()
.getResourceAsStream("ConsequenceTest.drl"));
AnalyticsDataFactory.clearAnalyticsResult();
AnalyticsResult result = AnalyticsDataFactory.getAnalyticsResult();
session.setGlobal("result", result);
session.executeWithResults(testData);
Iterator<AnalyticsMessageBase> iter = result.getBySeverity(
AnalyticsMessageBase.Severity.WARNING).iterator();
Set<String> rulesThatHadErrors = new HashSet<String>();
while (iter.hasNext()) {
Object o = (Object) iter.next();
if (o instanceof AnalyticsMessage) {
AnalyticsRule rule = (AnalyticsRule) ((AnalyticsMessage) o)
.getFaulty();
rulesThatHadErrors.add(rule.getRuleName());
}
}
assertFalse(rulesThatHadErrors.contains("Has a consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 2"));
if (!rulesThatHadErrors.isEmpty()) {
for (String string : rulesThatHadErrors) {
fail("Rule " + string + " caused an error.");
}
}
}
|
diff --git a/app/utils/DataUtil.java b/app/utils/DataUtil.java
index 2dd46ca..b066470 100644
--- a/app/utils/DataUtil.java
+++ b/app/utils/DataUtil.java
@@ -1,84 +1,84 @@
package utils;
import com.mongodb.DB;
import com.mongodb.MongoException;
import com.mongodb.ReadPreference;
import com.mongodb.MongoClient;
import models.User;
import net.vz.mongodb.jackson.DBCursor;
import net.vz.mongodb.jackson.DBQuery;
import net.vz.mongodb.jackson.JacksonDBCollection;
import java.net.UnknownHostException;
/**
* User: Charles
* Date: 4/28/13
*/
public class DataUtil {
private static MongoClient mongoClient;
public static DB getDB() {
try {
mongoClient = new MongoClient("ds061787.mongolab.com", 61787);
// mongoClient = new MongoClient( );
- mongoClient.setReadPreference(ReadPreference.primary());
+// mongoClient.setReadPreference(ReadPreference.primary());
DB dataBase = mongoClient.getDB("heroku_app15452455");
// DB dataBase = mongoClient.getDB("icm");
dataBase.authenticate("heroku_app15452455", "73mi73eoolvr4s7v47ugutfru9".toCharArray());
return dataBase;
} catch (UnknownHostException e) {
return null;
}
}
public static JacksonDBCollection getCollection(String collection, Class clazz) {
try {
return JacksonDBCollection.wrap(getDB().getCollection(collection), clazz, String.class);
} catch (Exception e) {
return null;
}
}
public static Object getEntityById(String collection, Class clazz, String id) {
try {
JacksonDBCollection jacksonDBCollection = JacksonDBCollection.wrap(getDB().getCollection(collection), clazz, String.class);
return jacksonDBCollection.findOneById(id);
} catch (Exception e) {
return null;
}
}
public static Boolean isDatabase() {
try {
JacksonDBCollection<User, String> collection = DataUtil.getCollection("users", User.class);
DBCursor cursorDoc = collection.find(DBQuery.is("username", "test"));
if (cursorDoc.hasNext())
return true;
else
return true;
} catch (MongoException e) {
e.printStackTrace();
return false;
}
}
}
| true | true | public static DB getDB() {
try {
mongoClient = new MongoClient("ds061787.mongolab.com", 61787);
// mongoClient = new MongoClient( );
mongoClient.setReadPreference(ReadPreference.primary());
DB dataBase = mongoClient.getDB("heroku_app15452455");
// DB dataBase = mongoClient.getDB("icm");
dataBase.authenticate("heroku_app15452455", "73mi73eoolvr4s7v47ugutfru9".toCharArray());
return dataBase;
} catch (UnknownHostException e) {
return null;
}
}
| public static DB getDB() {
try {
mongoClient = new MongoClient("ds061787.mongolab.com", 61787);
// mongoClient = new MongoClient( );
// mongoClient.setReadPreference(ReadPreference.primary());
DB dataBase = mongoClient.getDB("heroku_app15452455");
// DB dataBase = mongoClient.getDB("icm");
dataBase.authenticate("heroku_app15452455", "73mi73eoolvr4s7v47ugutfru9".toCharArray());
return dataBase;
} catch (UnknownHostException e) {
return null;
}
}
|
diff --git a/src/dev/mCraft/Coinz/GUI/TellerMenu/TellerPopup.java b/src/dev/mCraft/Coinz/GUI/TellerMenu/TellerPopup.java
index 5882262..12c205f 100644
--- a/src/dev/mCraft/Coinz/GUI/TellerMenu/TellerPopup.java
+++ b/src/dev/mCraft/Coinz/GUI/TellerMenu/TellerPopup.java
@@ -1,170 +1,170 @@
package dev.mCraft.Coinz.GUI.TellerMenu;
import org.getspout.spoutapi.gui.Color;
import org.getspout.spoutapi.gui.GenericButton;
import org.getspout.spoutapi.gui.GenericLabel;
import org.getspout.spoutapi.gui.GenericPopup;
import org.getspout.spoutapi.gui.GenericTextField;
import org.getspout.spoutapi.gui.GenericTexture;
import org.getspout.spoutapi.gui.RenderPriority;
import org.getspout.spoutapi.gui.WidgetAnchor;
import org.getspout.spoutapi.player.SpoutPlayer;
import dev.mCraft.Coinz.Coinz;
import dev.mCraft.Coinz.Lang.CLang;
public class TellerPopup extends GenericPopup {
public Coinz plugin = Coinz.instance;
public static TellerPopup hook;
//private GenericTexture backGround;
public GenericButton escape;
private GenericLabel title;
public GenericTextField enter;
public GenericButton deposit;
public GenericButton withdraw;
public GenericLabel amount;
public GenericLabel notEnoughA;
public GenericLabel notEnoughC;
public GenericLabel wrongChange;
public GenericLabel invalidChar;
public GenericLabel invalidAmount;
private GenericTexture copper;
private GenericTexture bronze;
private GenericTexture silver;
private GenericTexture gold;
private GenericTexture platinum;
private double balance = 0;
public TellerPopup(SpoutPlayer player) {
hook = this;
copper = new GenericTexture();
bronze = new GenericTexture();
silver = new GenericTexture();
gold = new GenericTexture();
platinum = new GenericTexture();
//backGround = new GenericTexture();
escape = new GenericButton();
title = new GenericLabel();
enter = new GenericTextField();
deposit = new GenericButton();
withdraw = new GenericButton();
amount = new GenericLabel();
notEnoughA = new GenericLabel();
notEnoughC = new GenericLabel();
wrongChange = new GenericLabel();
invalidChar = new GenericLabel();
invalidAmount = new GenericLabel();
Integer coinsize = 25;
Integer coindist = 30;
copper.setUrl("spoutcraft/cache/Coinz/CopperCoin.png");
copper.setTooltip(CLang.lookup("tooltip_copper"));
copper.setX(150).setY(100);
copper.setHeight(coinsize).setWidth(coinsize);
copper.setPriority(RenderPriority.High);
bronze.setUrl("spoutcraft/cache/Coinz/BronzeCoin.png");
bronze.setTooltip(CLang.lookup("tooltip_bronze"));
bronze.setX(copper.getX() + coindist).setY(100);
bronze.setHeight(coinsize).setWidth(coinsize);
bronze.setPriority(RenderPriority.High);
silver.setUrl("spoutcraft/cache/Coinz/SilverCoin.png");
silver.setTooltip(CLang.lookup("tooltip_silver"));
silver.setX(bronze.getX() + coindist).setY(100);
silver.setHeight(coinsize).setWidth(coinsize);
silver.setPriority(RenderPriority.High);
gold.setUrl("spoutcraft/cache/Coinz/GoldCoin.png");
gold.setTooltip(CLang.lookup("tooltip_gold"));
gold.setX(silver.getX() + coindist).setY(100);
gold.setHeight(coinsize).setWidth(coinsize);
gold.setPriority(RenderPriority.High);
platinum.setUrl("spoutcraft/cache/Coinz/PlatinumCoin.png");
platinum.setTooltip(CLang.lookup("tooltip_platinum"));
platinum.setX(gold.getX() + coindist).setY(100);
platinum.setHeight(coinsize).setWidth(coinsize);
platinum.setPriority(RenderPriority.High);
//backGround.setUrl("spoutcraft/cache/Coinz/GuiScreen.png");
//backGround.setX(141).setY(38);
//backGround.setHeight(150).setWidth(160);
//backGround.setPriority(RenderPriority.Highest);
escape.setText("X").setColor(new Color(1.0F, 0, 0, 1.0F));
- escape.setTooltip(CLang.lookup("tooltips_escape"));
+ escape.setTooltip(CLang.lookup("tooltip_escape"));
escape.setX(287).setY(84);
escape.setHeight(10).setWidth(10);
escape.setPriority(RenderPriority.Normal);
String locale = CLang.lookup("label_title");
String name = player.getName();
title.setTextColor(new Color(205F, 127F, 50F, 1.0F));
title.setText(CLang.replace(locale, "player", name));
title.setX(186).setY(69);
title.setHeight(20).setWidth(30);
title.setPriority(RenderPriority.Normal);
String message = CLang.lookup("label_balance");
balance = plugin.econ.getBalance(player.getName());
amount.setTextColor(new Color(0, 1.0F, 0, 1.0F));
amount.setText(CLang.replace(message, "holdings", plugin.econ.format(balance)));
amount.setX(159).setY(87);
amount.setHeight(20).setWidth(30);
amount.setPriority(RenderPriority.Normal);
enter.setHeight(9).setWidth(45);
enter.setX(200).setY(131);
enter.setPlaceholder(CLang.lookup("placeholder_teller"));
enter.setPriority(RenderPriority.Normal);
deposit.setX(enter.getX() - 33).setY(enter.getY()-4);
deposit.setHeight(14).setWidth(30);
deposit.setText(CLang.lookup("button_deposit")).setTooltip(CLang.lookup("tooltip_deposit"));
deposit.setPriority(RenderPriority.Normal);
withdraw.setX(enter.getX() + 47).setY(enter.getY()-4);
withdraw.setHeight(14).setWidth(33);
withdraw.setText(CLang.lookup("button_withdraw")).setTooltip(CLang.lookup("tooltip_withdraw"));
withdraw.setPriority(RenderPriority.Normal);
this.attachWidgets(plugin, copper, bronze, silver, gold, platinum, /*backGround,*/ escape, title, amount, enter, deposit, withdraw);
this.setAnchor(WidgetAnchor.CENTER_CENTER);
notEnoughA.setX(110).setY(150);
notEnoughA.setHeight(5).setWidth(30);
notEnoughA.setText(CLang.lookup("error_NEM")).setTextColor(new Color(1.0F, 0, 0, 1.0F));
notEnoughA.setPriority(RenderPriority.Normal);
notEnoughC.setX(110).setY(150);
notEnoughC.setHeight(5).setWidth(30);
notEnoughC.setText(CLang.lookup("error_NEC")).setTextColor(new Color(1.0F, 0, 0, 1.0F));
notEnoughC.setPriority(RenderPriority.Normal);
wrongChange.setX(110).setY(150);
wrongChange.setHeight(5).setWidth(20);
wrongChange.setText(CLang.lookup("error_WC")).setTextColor(new Color(1.0F, 0, 0, 1.0F));
wrongChange.setPriority(RenderPriority.Normal);
invalidChar.setX(110).setY(150);
invalidChar.setHeight(5).setWidth(20);
invalidChar.setText(CLang.lookup("error_IC")).setTextColor(new Color(1.0F, 0, 0, 1.0F));
invalidChar.setPriority(RenderPriority.Normal);
invalidAmount.setX(110).setY(150);
invalidAmount.setHeight(5).setWidth(20);
invalidAmount.setText(CLang.lookup("error_IA")).setTextColor(new Color(1.0F, 0, 0, 1.0F));
invalidAmount.setPriority(RenderPriority.Normal);
}
}
| true | true | public TellerPopup(SpoutPlayer player) {
hook = this;
copper = new GenericTexture();
bronze = new GenericTexture();
silver = new GenericTexture();
gold = new GenericTexture();
platinum = new GenericTexture();
//backGround = new GenericTexture();
escape = new GenericButton();
title = new GenericLabel();
enter = new GenericTextField();
deposit = new GenericButton();
withdraw = new GenericButton();
amount = new GenericLabel();
notEnoughA = new GenericLabel();
notEnoughC = new GenericLabel();
wrongChange = new GenericLabel();
invalidChar = new GenericLabel();
invalidAmount = new GenericLabel();
Integer coinsize = 25;
Integer coindist = 30;
copper.setUrl("spoutcraft/cache/Coinz/CopperCoin.png");
copper.setTooltip(CLang.lookup("tooltip_copper"));
copper.setX(150).setY(100);
copper.setHeight(coinsize).setWidth(coinsize);
copper.setPriority(RenderPriority.High);
bronze.setUrl("spoutcraft/cache/Coinz/BronzeCoin.png");
bronze.setTooltip(CLang.lookup("tooltip_bronze"));
bronze.setX(copper.getX() + coindist).setY(100);
bronze.setHeight(coinsize).setWidth(coinsize);
bronze.setPriority(RenderPriority.High);
silver.setUrl("spoutcraft/cache/Coinz/SilverCoin.png");
silver.setTooltip(CLang.lookup("tooltip_silver"));
silver.setX(bronze.getX() + coindist).setY(100);
silver.setHeight(coinsize).setWidth(coinsize);
silver.setPriority(RenderPriority.High);
gold.setUrl("spoutcraft/cache/Coinz/GoldCoin.png");
gold.setTooltip(CLang.lookup("tooltip_gold"));
gold.setX(silver.getX() + coindist).setY(100);
gold.setHeight(coinsize).setWidth(coinsize);
gold.setPriority(RenderPriority.High);
platinum.setUrl("spoutcraft/cache/Coinz/PlatinumCoin.png");
platinum.setTooltip(CLang.lookup("tooltip_platinum"));
platinum.setX(gold.getX() + coindist).setY(100);
platinum.setHeight(coinsize).setWidth(coinsize);
platinum.setPriority(RenderPriority.High);
//backGround.setUrl("spoutcraft/cache/Coinz/GuiScreen.png");
//backGround.setX(141).setY(38);
//backGround.setHeight(150).setWidth(160);
//backGround.setPriority(RenderPriority.Highest);
escape.setText("X").setColor(new Color(1.0F, 0, 0, 1.0F));
escape.setTooltip(CLang.lookup("tooltips_escape"));
escape.setX(287).setY(84);
escape.setHeight(10).setWidth(10);
escape.setPriority(RenderPriority.Normal);
String locale = CLang.lookup("label_title");
String name = player.getName();
title.setTextColor(new Color(205F, 127F, 50F, 1.0F));
title.setText(CLang.replace(locale, "player", name));
title.setX(186).setY(69);
title.setHeight(20).setWidth(30);
title.setPriority(RenderPriority.Normal);
String message = CLang.lookup("label_balance");
balance = plugin.econ.getBalance(player.getName());
amount.setTextColor(new Color(0, 1.0F, 0, 1.0F));
amount.setText(CLang.replace(message, "holdings", plugin.econ.format(balance)));
amount.setX(159).setY(87);
amount.setHeight(20).setWidth(30);
amount.setPriority(RenderPriority.Normal);
enter.setHeight(9).setWidth(45);
enter.setX(200).setY(131);
enter.setPlaceholder(CLang.lookup("placeholder_teller"));
enter.setPriority(RenderPriority.Normal);
deposit.setX(enter.getX() - 33).setY(enter.getY()-4);
deposit.setHeight(14).setWidth(30);
deposit.setText(CLang.lookup("button_deposit")).setTooltip(CLang.lookup("tooltip_deposit"));
deposit.setPriority(RenderPriority.Normal);
withdraw.setX(enter.getX() + 47).setY(enter.getY()-4);
withdraw.setHeight(14).setWidth(33);
withdraw.setText(CLang.lookup("button_withdraw")).setTooltip(CLang.lookup("tooltip_withdraw"));
withdraw.setPriority(RenderPriority.Normal);
this.attachWidgets(plugin, copper, bronze, silver, gold, platinum, /*backGround,*/ escape, title, amount, enter, deposit, withdraw);
this.setAnchor(WidgetAnchor.CENTER_CENTER);
notEnoughA.setX(110).setY(150);
notEnoughA.setHeight(5).setWidth(30);
notEnoughA.setText(CLang.lookup("error_NEM")).setTextColor(new Color(1.0F, 0, 0, 1.0F));
notEnoughA.setPriority(RenderPriority.Normal);
notEnoughC.setX(110).setY(150);
notEnoughC.setHeight(5).setWidth(30);
notEnoughC.setText(CLang.lookup("error_NEC")).setTextColor(new Color(1.0F, 0, 0, 1.0F));
notEnoughC.setPriority(RenderPriority.Normal);
wrongChange.setX(110).setY(150);
wrongChange.setHeight(5).setWidth(20);
wrongChange.setText(CLang.lookup("error_WC")).setTextColor(new Color(1.0F, 0, 0, 1.0F));
wrongChange.setPriority(RenderPriority.Normal);
invalidChar.setX(110).setY(150);
invalidChar.setHeight(5).setWidth(20);
invalidChar.setText(CLang.lookup("error_IC")).setTextColor(new Color(1.0F, 0, 0, 1.0F));
invalidChar.setPriority(RenderPriority.Normal);
invalidAmount.setX(110).setY(150);
invalidAmount.setHeight(5).setWidth(20);
invalidAmount.setText(CLang.lookup("error_IA")).setTextColor(new Color(1.0F, 0, 0, 1.0F));
invalidAmount.setPriority(RenderPriority.Normal);
}
| public TellerPopup(SpoutPlayer player) {
hook = this;
copper = new GenericTexture();
bronze = new GenericTexture();
silver = new GenericTexture();
gold = new GenericTexture();
platinum = new GenericTexture();
//backGround = new GenericTexture();
escape = new GenericButton();
title = new GenericLabel();
enter = new GenericTextField();
deposit = new GenericButton();
withdraw = new GenericButton();
amount = new GenericLabel();
notEnoughA = new GenericLabel();
notEnoughC = new GenericLabel();
wrongChange = new GenericLabel();
invalidChar = new GenericLabel();
invalidAmount = new GenericLabel();
Integer coinsize = 25;
Integer coindist = 30;
copper.setUrl("spoutcraft/cache/Coinz/CopperCoin.png");
copper.setTooltip(CLang.lookup("tooltip_copper"));
copper.setX(150).setY(100);
copper.setHeight(coinsize).setWidth(coinsize);
copper.setPriority(RenderPriority.High);
bronze.setUrl("spoutcraft/cache/Coinz/BronzeCoin.png");
bronze.setTooltip(CLang.lookup("tooltip_bronze"));
bronze.setX(copper.getX() + coindist).setY(100);
bronze.setHeight(coinsize).setWidth(coinsize);
bronze.setPriority(RenderPriority.High);
silver.setUrl("spoutcraft/cache/Coinz/SilverCoin.png");
silver.setTooltip(CLang.lookup("tooltip_silver"));
silver.setX(bronze.getX() + coindist).setY(100);
silver.setHeight(coinsize).setWidth(coinsize);
silver.setPriority(RenderPriority.High);
gold.setUrl("spoutcraft/cache/Coinz/GoldCoin.png");
gold.setTooltip(CLang.lookup("tooltip_gold"));
gold.setX(silver.getX() + coindist).setY(100);
gold.setHeight(coinsize).setWidth(coinsize);
gold.setPriority(RenderPriority.High);
platinum.setUrl("spoutcraft/cache/Coinz/PlatinumCoin.png");
platinum.setTooltip(CLang.lookup("tooltip_platinum"));
platinum.setX(gold.getX() + coindist).setY(100);
platinum.setHeight(coinsize).setWidth(coinsize);
platinum.setPriority(RenderPriority.High);
//backGround.setUrl("spoutcraft/cache/Coinz/GuiScreen.png");
//backGround.setX(141).setY(38);
//backGround.setHeight(150).setWidth(160);
//backGround.setPriority(RenderPriority.Highest);
escape.setText("X").setColor(new Color(1.0F, 0, 0, 1.0F));
escape.setTooltip(CLang.lookup("tooltip_escape"));
escape.setX(287).setY(84);
escape.setHeight(10).setWidth(10);
escape.setPriority(RenderPriority.Normal);
String locale = CLang.lookup("label_title");
String name = player.getName();
title.setTextColor(new Color(205F, 127F, 50F, 1.0F));
title.setText(CLang.replace(locale, "player", name));
title.setX(186).setY(69);
title.setHeight(20).setWidth(30);
title.setPriority(RenderPriority.Normal);
String message = CLang.lookup("label_balance");
balance = plugin.econ.getBalance(player.getName());
amount.setTextColor(new Color(0, 1.0F, 0, 1.0F));
amount.setText(CLang.replace(message, "holdings", plugin.econ.format(balance)));
amount.setX(159).setY(87);
amount.setHeight(20).setWidth(30);
amount.setPriority(RenderPriority.Normal);
enter.setHeight(9).setWidth(45);
enter.setX(200).setY(131);
enter.setPlaceholder(CLang.lookup("placeholder_teller"));
enter.setPriority(RenderPriority.Normal);
deposit.setX(enter.getX() - 33).setY(enter.getY()-4);
deposit.setHeight(14).setWidth(30);
deposit.setText(CLang.lookup("button_deposit")).setTooltip(CLang.lookup("tooltip_deposit"));
deposit.setPriority(RenderPriority.Normal);
withdraw.setX(enter.getX() + 47).setY(enter.getY()-4);
withdraw.setHeight(14).setWidth(33);
withdraw.setText(CLang.lookup("button_withdraw")).setTooltip(CLang.lookup("tooltip_withdraw"));
withdraw.setPriority(RenderPriority.Normal);
this.attachWidgets(plugin, copper, bronze, silver, gold, platinum, /*backGround,*/ escape, title, amount, enter, deposit, withdraw);
this.setAnchor(WidgetAnchor.CENTER_CENTER);
notEnoughA.setX(110).setY(150);
notEnoughA.setHeight(5).setWidth(30);
notEnoughA.setText(CLang.lookup("error_NEM")).setTextColor(new Color(1.0F, 0, 0, 1.0F));
notEnoughA.setPriority(RenderPriority.Normal);
notEnoughC.setX(110).setY(150);
notEnoughC.setHeight(5).setWidth(30);
notEnoughC.setText(CLang.lookup("error_NEC")).setTextColor(new Color(1.0F, 0, 0, 1.0F));
notEnoughC.setPriority(RenderPriority.Normal);
wrongChange.setX(110).setY(150);
wrongChange.setHeight(5).setWidth(20);
wrongChange.setText(CLang.lookup("error_WC")).setTextColor(new Color(1.0F, 0, 0, 1.0F));
wrongChange.setPriority(RenderPriority.Normal);
invalidChar.setX(110).setY(150);
invalidChar.setHeight(5).setWidth(20);
invalidChar.setText(CLang.lookup("error_IC")).setTextColor(new Color(1.0F, 0, 0, 1.0F));
invalidChar.setPriority(RenderPriority.Normal);
invalidAmount.setX(110).setY(150);
invalidAmount.setHeight(5).setWidth(20);
invalidAmount.setText(CLang.lookup("error_IA")).setTextColor(new Color(1.0F, 0, 0, 1.0F));
invalidAmount.setPriority(RenderPriority.Normal);
}
|
diff --git a/src/com/example/android/lasergame/LaserCalculator.java b/src/com/example/android/lasergame/LaserCalculator.java
index 0e3d114..b0004d7 100644
--- a/src/com/example/android/lasergame/LaserCalculator.java
+++ b/src/com/example/android/lasergame/LaserCalculator.java
@@ -1,167 +1,173 @@
package com.example.android.lasergame;
import com.example.android.lasergame.Intersection.Intersects;
public class LaserCalculator {
private int mCanvasWidth;
private int mCanvasHeight;
private double mDesiredDegrees;
private double mMaxLeftSideDegrees;
private Triangle[] mTriangles;
private Beam mBeam;
private double mMinimumFiringAngle;
private double mMaximumFiringAngle;
public LaserCalculator(int canvasWidth, int canvasHeight, double minimumFiringAngle, double maximumFiringAngle) {
mCanvasWidth = canvasWidth;
mCanvasHeight = canvasHeight;
mMinimumFiringAngle = minimumFiringAngle;
mMaximumFiringAngle = maximumFiringAngle;
mTriangles = new Triangle[] {};
}
public LaserCalculator(int canvasWidth, int canvasHeight, double minimumFiringAngle, double maximumFiringAngle,
Triangle[] triangles) {
mTriangles = triangles;
mCanvasWidth = canvasWidth;
mCanvasHeight = canvasHeight;
mMinimumFiringAngle = minimumFiringAngle;
mMaximumFiringAngle = maximumFiringAngle;
}
public Beam fireLaser(double desiredDegrees) {
setDesiredDegrees(desiredDegrees);
mBeam = new Beam();
Line firstLine = new Line(new Point(mCanvasWidth / 2, mCanvasHeight), new Point(0, 0));
mMaxLeftSideDegrees = getMaxLeftSideDegrees(firstLine.p1);
if (hittingLeftWall()) {
firstLine.p2.y = (int) (mCanvasHeight - Math.tan(Math.toRadians(mDesiredDegrees)) * firstLine.p1.x);
startReflecting(firstLine);
} else if (hittingBackWall()) {
if (firingStraightUp()) {
firstLine.p2.y = 0;
firstLine.p2.x = firstLine.p1.x;
mBeam.addLine(firstLine);
return mBeam;
} else if (hittingLeftSideOfBackWall()) {
firstLine.p2.x = (int) (firstLine.p1.x - Math.tan(Math.toRadians(180 - 90 - mDesiredDegrees))
* mCanvasHeight);
startReflecting(firstLine);
} else { // hitting right side...
firstLine.p2.x = (int) (firstLine.p1.x + Math.tan(Math.toRadians(mDesiredDegrees - 90)) * mCanvasHeight);
startReflecting(firstLine);
}
} else { // hitting right wall
firstLine.p2.x = mCanvasWidth;
mDesiredDegrees = 180 - mDesiredDegrees;
firstLine.p2.y = (int) (mCanvasHeight - Math.tan(Math.toRadians(mDesiredDegrees)) * firstLine.p1.x);
startReflecting(firstLine);
}
return mBeam;
}
private void setDesiredDegrees(double desiredDegrees) {
mDesiredDegrees = Math.max(desiredDegrees, mMinimumFiringAngle);
mDesiredDegrees = Math.min(mDesiredDegrees, mMaximumFiringAngle);
}
private void startReflecting(Line incomingLine) {
Line[] walls = { new Line(0, 0, 0, mCanvasHeight), new Line(0, 0, mCanvasWidth, 0),
new Line(mCanvasWidth, 0, mCanvasWidth, mCanvasHeight),
new Line(0, mCanvasHeight, mCanvasWidth, mCanvasHeight) };
Intersects intersects = Intersection.whichEdgeDoesTheLinePassThroughFirst(mTriangles, walls, incomingLine);
if (intersects != null) { // it has to intersect with SOMETHING
Line intersectsWithLine = intersects.edge;
Point intersectionPoint = intersects.intersectionP;
incomingLine.p2.x = intersectionPoint.x;
incomingLine.p2.y = intersectionPoint.y;
+ if (mBeam.lines.size() > 0
+ && incomingLine.p1.equals(mBeam.lines.get(mBeam.lines.size()-1).p2)
+ && incomingLine.p2.equals(mBeam.lines.get(mBeam.lines.size()-1).p1)) {
+ // return if "backtracking" here
+ return;
+ }
mBeam.addLine(incomingLine);
// start bouncing!!!!
Vector2 n1 = new Vector2(intersectsWithLine.p1.x, intersectsWithLine.p1.y);
Vector2 n2 = new Vector2(intersectsWithLine.p2.x, intersectsWithLine.p2.y);
Vector2 nN = n1.add(n2).nor();
Vector2 lineNorm = n1.sub(n2).nor();
Vector2 nNPerp = new Vector2(-lineNorm.y, lineNorm.x);
nN = nNPerp;
Vector2 v1 = new Vector2(incomingLine.p1.x, incomingLine.p1.y);
Vector2 v2 = new Vector2(incomingLine.p2.x, incomingLine.p2.y);
Vector2 vN = v2.sub(v1).nor();
Vector2 u = nN.mul(vN.dot(nN));
Vector2 w = vN.sub(u);
Vector2 vPrime = w.sub(u);
Line next = new Line(new Point(incomingLine.p2.x, incomingLine.p2.y), new Point(mCanvasWidth, 0));
next.p2.y = (int) (((vPrime.y / vPrime.x) * (mCanvasWidth - incomingLine.p2.x)) + incomingLine.p2.y);
Intersects nextIntersects = Intersection.whichEdgeDoesTheLinePassThroughFirst(mTriangles, walls, next);
if (hittingAWall(nextIntersects)) {
if (intersects.intersectionP.x == mCanvasWidth) {
next = new Line(new Point(incomingLine.p2.x, incomingLine.p2.y), new Point(0, 0));
// y = m(x-x1)+y1
next.p2.y = (int) (((vPrime.y / vPrime.x) * (0 - incomingLine.p2.x)) + incomingLine.p2.y);
}
if (next.p2.y < 0) {
next.p2.y = 0;
// x = ((y - y1)/m) + x1
next.p2.x = (int) ((0 - incomingLine.p2.y)/ (vPrime.y / vPrime.x) + incomingLine.p2.x);
}
} else {
// hitting a triangle
if (intersects.triangle != null) {
for (Line tLine : intersects.triangle.edges()) {
if (tLine != intersects.edge && Intersection.detect(tLine, next) != null) {
next = new Line(new Point(incomingLine.p2.x, incomingLine.p2.y), new Point(0, 0));
next.p2.y = (int) (((vPrime.y / vPrime.x) * (0 - incomingLine.p2.x)) + incomingLine.p2.y);
}
}
}
}
if (next.p2.y <= 0 || next.p2.y > mCanvasHeight) {
mBeam.addLine(next);
return;
} else {
startReflecting(next);
}
}
return;
}
private boolean hittingAWall(Intersects nextIntersects) {
return nextIntersects == null || (nextIntersects != null && nextIntersects.triangle == null);
}
private boolean hittingLeftSideOfBackWall() {
return mDesiredDegrees < 90;
}
private boolean firingStraightUp() {
return mDesiredDegrees == 90;
}
/**
* x ------------>x ****************** y *T* * | * * * | * * * | * * * | * *
* * y * M* * ****************** Returns the maximum number of degrees this
* map supports while still hitting the left wall
*/
private double getMaxLeftSideDegrees(Point startPoint) {
double T = Math.atan2(startPoint.x, startPoint.y) * 180.0F / Math.PI;
double M = 180 - (T + 90);
return M;
}
private boolean hittingBackWall() {
return mDesiredDegrees < mMaxLeftSideDegrees + (180 - mMaxLeftSideDegrees * 2);
}
private boolean hittingLeftWall() {
return mDesiredDegrees < mMaxLeftSideDegrees;
}
}
| true | true | private void startReflecting(Line incomingLine) {
Line[] walls = { new Line(0, 0, 0, mCanvasHeight), new Line(0, 0, mCanvasWidth, 0),
new Line(mCanvasWidth, 0, mCanvasWidth, mCanvasHeight),
new Line(0, mCanvasHeight, mCanvasWidth, mCanvasHeight) };
Intersects intersects = Intersection.whichEdgeDoesTheLinePassThroughFirst(mTriangles, walls, incomingLine);
if (intersects != null) { // it has to intersect with SOMETHING
Line intersectsWithLine = intersects.edge;
Point intersectionPoint = intersects.intersectionP;
incomingLine.p2.x = intersectionPoint.x;
incomingLine.p2.y = intersectionPoint.y;
mBeam.addLine(incomingLine);
// start bouncing!!!!
Vector2 n1 = new Vector2(intersectsWithLine.p1.x, intersectsWithLine.p1.y);
Vector2 n2 = new Vector2(intersectsWithLine.p2.x, intersectsWithLine.p2.y);
Vector2 nN = n1.add(n2).nor();
Vector2 lineNorm = n1.sub(n2).nor();
Vector2 nNPerp = new Vector2(-lineNorm.y, lineNorm.x);
nN = nNPerp;
Vector2 v1 = new Vector2(incomingLine.p1.x, incomingLine.p1.y);
Vector2 v2 = new Vector2(incomingLine.p2.x, incomingLine.p2.y);
Vector2 vN = v2.sub(v1).nor();
Vector2 u = nN.mul(vN.dot(nN));
Vector2 w = vN.sub(u);
Vector2 vPrime = w.sub(u);
Line next = new Line(new Point(incomingLine.p2.x, incomingLine.p2.y), new Point(mCanvasWidth, 0));
next.p2.y = (int) (((vPrime.y / vPrime.x) * (mCanvasWidth - incomingLine.p2.x)) + incomingLine.p2.y);
Intersects nextIntersects = Intersection.whichEdgeDoesTheLinePassThroughFirst(mTriangles, walls, next);
if (hittingAWall(nextIntersects)) {
if (intersects.intersectionP.x == mCanvasWidth) {
next = new Line(new Point(incomingLine.p2.x, incomingLine.p2.y), new Point(0, 0));
// y = m(x-x1)+y1
next.p2.y = (int) (((vPrime.y / vPrime.x) * (0 - incomingLine.p2.x)) + incomingLine.p2.y);
}
if (next.p2.y < 0) {
next.p2.y = 0;
// x = ((y - y1)/m) + x1
next.p2.x = (int) ((0 - incomingLine.p2.y)/ (vPrime.y / vPrime.x) + incomingLine.p2.x);
}
} else {
// hitting a triangle
if (intersects.triangle != null) {
for (Line tLine : intersects.triangle.edges()) {
if (tLine != intersects.edge && Intersection.detect(tLine, next) != null) {
next = new Line(new Point(incomingLine.p2.x, incomingLine.p2.y), new Point(0, 0));
next.p2.y = (int) (((vPrime.y / vPrime.x) * (0 - incomingLine.p2.x)) + incomingLine.p2.y);
}
}
}
}
if (next.p2.y <= 0 || next.p2.y > mCanvasHeight) {
mBeam.addLine(next);
return;
} else {
startReflecting(next);
}
}
return;
}
| private void startReflecting(Line incomingLine) {
Line[] walls = { new Line(0, 0, 0, mCanvasHeight), new Line(0, 0, mCanvasWidth, 0),
new Line(mCanvasWidth, 0, mCanvasWidth, mCanvasHeight),
new Line(0, mCanvasHeight, mCanvasWidth, mCanvasHeight) };
Intersects intersects = Intersection.whichEdgeDoesTheLinePassThroughFirst(mTriangles, walls, incomingLine);
if (intersects != null) { // it has to intersect with SOMETHING
Line intersectsWithLine = intersects.edge;
Point intersectionPoint = intersects.intersectionP;
incomingLine.p2.x = intersectionPoint.x;
incomingLine.p2.y = intersectionPoint.y;
if (mBeam.lines.size() > 0
&& incomingLine.p1.equals(mBeam.lines.get(mBeam.lines.size()-1).p2)
&& incomingLine.p2.equals(mBeam.lines.get(mBeam.lines.size()-1).p1)) {
// return if "backtracking" here
return;
}
mBeam.addLine(incomingLine);
// start bouncing!!!!
Vector2 n1 = new Vector2(intersectsWithLine.p1.x, intersectsWithLine.p1.y);
Vector2 n2 = new Vector2(intersectsWithLine.p2.x, intersectsWithLine.p2.y);
Vector2 nN = n1.add(n2).nor();
Vector2 lineNorm = n1.sub(n2).nor();
Vector2 nNPerp = new Vector2(-lineNorm.y, lineNorm.x);
nN = nNPerp;
Vector2 v1 = new Vector2(incomingLine.p1.x, incomingLine.p1.y);
Vector2 v2 = new Vector2(incomingLine.p2.x, incomingLine.p2.y);
Vector2 vN = v2.sub(v1).nor();
Vector2 u = nN.mul(vN.dot(nN));
Vector2 w = vN.sub(u);
Vector2 vPrime = w.sub(u);
Line next = new Line(new Point(incomingLine.p2.x, incomingLine.p2.y), new Point(mCanvasWidth, 0));
next.p2.y = (int) (((vPrime.y / vPrime.x) * (mCanvasWidth - incomingLine.p2.x)) + incomingLine.p2.y);
Intersects nextIntersects = Intersection.whichEdgeDoesTheLinePassThroughFirst(mTriangles, walls, next);
if (hittingAWall(nextIntersects)) {
if (intersects.intersectionP.x == mCanvasWidth) {
next = new Line(new Point(incomingLine.p2.x, incomingLine.p2.y), new Point(0, 0));
// y = m(x-x1)+y1
next.p2.y = (int) (((vPrime.y / vPrime.x) * (0 - incomingLine.p2.x)) + incomingLine.p2.y);
}
if (next.p2.y < 0) {
next.p2.y = 0;
// x = ((y - y1)/m) + x1
next.p2.x = (int) ((0 - incomingLine.p2.y)/ (vPrime.y / vPrime.x) + incomingLine.p2.x);
}
} else {
// hitting a triangle
if (intersects.triangle != null) {
for (Line tLine : intersects.triangle.edges()) {
if (tLine != intersects.edge && Intersection.detect(tLine, next) != null) {
next = new Line(new Point(incomingLine.p2.x, incomingLine.p2.y), new Point(0, 0));
next.p2.y = (int) (((vPrime.y / vPrime.x) * (0 - incomingLine.p2.x)) + incomingLine.p2.y);
}
}
}
}
if (next.p2.y <= 0 || next.p2.y > mCanvasHeight) {
mBeam.addLine(next);
return;
} else {
startReflecting(next);
}
}
return;
}
|
diff --git a/src/com/axelby/podax/ActiveDownloadListActivity.java b/src/com/axelby/podax/ActiveDownloadListActivity.java
index 0789bea..1a4f2f7 100644
--- a/src/com/axelby/podax/ActiveDownloadListActivity.java
+++ b/src/com/axelby/podax/ActiveDownloadListActivity.java
@@ -1,135 +1,135 @@
package com.axelby.podax;
import java.io.File;
import java.util.Vector;
import android.app.ListActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ActiveDownloadListActivity extends ListActivity {
Runnable refresher;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Runnable refresher = new Runnable() {
public void run() {
setListAdapter(new ActiveDownloadAdapter());
new Handler().postDelayed(this, 1000);
}
};
setContentView(R.layout.downloads_list);
refresher.run();
PlayerActivity.injectPlayerFooter(this);
}
public class ActiveDownloadAdapter extends BaseAdapter {
Podcast _active = null;
Vector<Podcast> _waiting = new Vector<Podcast>();
LayoutInflater _layoutInflater;
public ActiveDownloadAdapter() {
super();
_layoutInflater = LayoutInflater.from(ActiveDownloadListActivity.this);
DBAdapter dbAdapter = DBAdapter.getInstance(ActiveDownloadListActivity.this);
Integer activeId = dbAdapter.getActiveDownloadId();
Vector<Podcast> toProcess = dbAdapter.getQueue();
for (Podcast podcast : toProcess) {
if (!podcast.needsDownload())
continue;
if (activeId != null && podcast.getId() == activeId) {
_active = podcast;
}
_waiting.add(podcast);
}
}
public int getCount() {
return _waiting.size();
}
public Object getItem(int position) {
return _waiting.get(position);
}
public long getItemId(int position) {
return ((Podcast)getItem(position)).getId();
}
public View getView(int position, View convertView, ViewGroup parent) {
Podcast podcast = (Podcast)getItem(position);
LinearLayout view;
if (convertView == null) {
view = (LinearLayout)_layoutInflater.inflate(R.layout.downloads_list_item, null);
}
else {
view = (LinearLayout)convertView;
}
TextView title = (TextView)view.findViewById(R.id.title);
title.setText(podcast.getTitle());
TextView subscription = (TextView)view.findViewById(R.id.subscription);
subscription.setText(podcast.getSubscription().getDisplayTitle());
// TODO: figure out when this is null
- if (podcast != null && podcast == _active)
+ if (podcast != null && podcast == _active && podcast.getFileSize() != null)
{
int max = podcast.getFileSize();
int downloaded = (int) new File(podcast.getFilename()).length();
View extras = _layoutInflater.inflate(R.layout.downloads_list_active_item, null);
view.addView(extras);
ProgressBar progressBar = (ProgressBar)extras.findViewById(R.id.progressBar);
progressBar.setMax(max);
progressBar.setProgress(downloaded);
TextView progressText = (TextView)extras.findViewById(R.id.progressText);
progressText.setText(Math.round(100.0f * downloaded / max) + "% done");
}
else
{
View extras = view.findViewById(R.id.active);
if (extras != null)
view.removeView(extras);
}
return view;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "Restart Downloader");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
UpdateService.downloadPodcasts(this);
break;
default:
return super.onContextItemSelected(item);
}
return true;
}
}
| true | true | public View getView(int position, View convertView, ViewGroup parent) {
Podcast podcast = (Podcast)getItem(position);
LinearLayout view;
if (convertView == null) {
view = (LinearLayout)_layoutInflater.inflate(R.layout.downloads_list_item, null);
}
else {
view = (LinearLayout)convertView;
}
TextView title = (TextView)view.findViewById(R.id.title);
title.setText(podcast.getTitle());
TextView subscription = (TextView)view.findViewById(R.id.subscription);
subscription.setText(podcast.getSubscription().getDisplayTitle());
// TODO: figure out when this is null
if (podcast != null && podcast == _active)
{
int max = podcast.getFileSize();
int downloaded = (int) new File(podcast.getFilename()).length();
View extras = _layoutInflater.inflate(R.layout.downloads_list_active_item, null);
view.addView(extras);
ProgressBar progressBar = (ProgressBar)extras.findViewById(R.id.progressBar);
progressBar.setMax(max);
progressBar.setProgress(downloaded);
TextView progressText = (TextView)extras.findViewById(R.id.progressText);
progressText.setText(Math.round(100.0f * downloaded / max) + "% done");
}
else
{
View extras = view.findViewById(R.id.active);
if (extras != null)
view.removeView(extras);
}
return view;
}
| public View getView(int position, View convertView, ViewGroup parent) {
Podcast podcast = (Podcast)getItem(position);
LinearLayout view;
if (convertView == null) {
view = (LinearLayout)_layoutInflater.inflate(R.layout.downloads_list_item, null);
}
else {
view = (LinearLayout)convertView;
}
TextView title = (TextView)view.findViewById(R.id.title);
title.setText(podcast.getTitle());
TextView subscription = (TextView)view.findViewById(R.id.subscription);
subscription.setText(podcast.getSubscription().getDisplayTitle());
// TODO: figure out when this is null
if (podcast != null && podcast == _active && podcast.getFileSize() != null)
{
int max = podcast.getFileSize();
int downloaded = (int) new File(podcast.getFilename()).length();
View extras = _layoutInflater.inflate(R.layout.downloads_list_active_item, null);
view.addView(extras);
ProgressBar progressBar = (ProgressBar)extras.findViewById(R.id.progressBar);
progressBar.setMax(max);
progressBar.setProgress(downloaded);
TextView progressText = (TextView)extras.findViewById(R.id.progressText);
progressText.setText(Math.round(100.0f * downloaded / max) + "% done");
}
else
{
View extras = view.findViewById(R.id.active);
if (extras != null)
view.removeView(extras);
}
return view;
}
|
diff --git a/src/org/openmrs/module/reporting/dataset/definition/evaluator/SimplePatientDataSetEvaluator.java b/src/org/openmrs/module/reporting/dataset/definition/evaluator/SimplePatientDataSetEvaluator.java
index 0a0e495f..2debe133 100644
--- a/src/org/openmrs/module/reporting/dataset/definition/evaluator/SimplePatientDataSetEvaluator.java
+++ b/src/org/openmrs/module/reporting/dataset/definition/evaluator/SimplePatientDataSetEvaluator.java
@@ -1,123 +1,123 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.module.reporting.dataset.definition.evaluator;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Cohort;
import org.openmrs.Patient;
import org.openmrs.PatientIdentifier;
import org.openmrs.PatientIdentifierType;
import org.openmrs.PatientState;
import org.openmrs.PersonAttribute;
import org.openmrs.PersonAttributeType;
import org.openmrs.ProgramWorkflow;
import org.openmrs.annotation.Handler;
import org.openmrs.api.context.Context;
import org.openmrs.module.reporting.cohort.CohortUtil;
import org.openmrs.module.reporting.common.ObjectUtil;
import org.openmrs.module.reporting.dataset.DataSet;
import org.openmrs.module.reporting.dataset.DataSetColumn;
import org.openmrs.module.reporting.dataset.DataSetRow;
import org.openmrs.module.reporting.dataset.SimpleDataSet;
import org.openmrs.module.reporting.dataset.definition.SimplePatientDataSetDefinition;
import org.openmrs.module.reporting.dataset.definition.DataSetDefinition;
import org.openmrs.module.reporting.evaluation.EvaluationContext;
/**
* The logic that evaluates a {@link SimplePatientDataSetDefinition} and produces an {@link DataSet}
* @see SimplePatientDataSetDefinition
*/
@Handler(supports={SimplePatientDataSetDefinition.class})
public class SimplePatientDataSetEvaluator implements DataSetEvaluator {
protected Log log = LogFactory.getLog(this.getClass());
/**
* Public constructor
*/
public SimplePatientDataSetEvaluator() { }
/**
* @see DataSetEvaluator#evaluate(DataSetDefinition, EvaluationContext)
* @should evaluate a SimplePatientDataSetDefinition
*/
public DataSet evaluate(DataSetDefinition dataSetDefinition, EvaluationContext context) {
SimpleDataSet dataSet = new SimpleDataSet(dataSetDefinition, context);
SimplePatientDataSetDefinition definition = (SimplePatientDataSetDefinition) dataSetDefinition;
context = ObjectUtil.nvl(context, new EvaluationContext());
Cohort cohort = context.getBaseCohort();
// By default, get all patients
if (cohort == null) {
cohort = Context.getPatientSetService().getAllPatients();
}
if (context.getLimit() != null) {
CohortUtil.limitCohort(cohort, context.getLimit());
}
// Get a list of patients based on the cohort members
List<Patient> patients = Context.getPatientSetService().getPatients(cohort.getMemberIds());
// Pre-calculate the program states
Map<ProgramWorkflow, Map<Integer, PatientState>> states = new HashMap<ProgramWorkflow, Map<Integer, PatientState>>();
for (ProgramWorkflow wf : definition.getProgramWorkflows()) {
states.put(wf, Context.getPatientSetService().getCurrentStates(cohort, wf));
}
for (Patient p : patients) {
DataSetRow row = new DataSetRow();
for (PatientIdentifierType t : definition.getIdentifierTypes()) {
DataSetColumn c = new DataSetColumn(t.getName(), t.getName(), String.class);
PatientIdentifier id = p.getPatientIdentifier(t);
row.addColumnValue(c, id == null ? null : id.getIdentifier());
}
for (String s : definition.getPatientProperties()) {
try {
Method m = Patient.class.getMethod("get" + StringUtils.capitalize(s), new Class[] {});
DataSetColumn c = new DataSetColumn(s, s, m.getReturnType());
Object o = m.invoke(p, new Object[] {});
row.addColumnValue(c, o);
}
catch (Exception e) {
log.error("Unable to get property " + s + " on patient for dataset", e);
}
}
for (PersonAttributeType t : definition.getPersonAttributeTypes()) {
DataSetColumn c = new DataSetColumn(t.getName(), t.getName(), String.class);
PersonAttribute att = p.getAttribute(t);
row.addColumnValue(c, att == null ? null : att.getHydratedObject());
}
for (ProgramWorkflow t : definition.getProgramWorkflows()) {
String name = (t.getName() == null ? t.getConcept().getDisplayString() : t.getName());
DataSetColumn c = new DataSetColumn(name, name, String.class);
PatientState ps = states.get(t).get(p.getPatientId());
- row.addColumnValue(c, (ps == null || !ps.getActive() || ps.getState().getConcept() == null) ? null : ps.getState().getConcept().getDisplayString() == null ? ps.getState().getConcept().getName() : ps.getState().getConcept().getDisplayString());
+ row.addColumnValue(c, (ps == null || !ps.getActive()) ? null : ps.getState().getConcept() == null ? ps.getState().toString() : ps.getState().getConcept().getDisplayString());
}
dataSet.addRow(row);
}
return dataSet;
}
}
| true | true | public DataSet evaluate(DataSetDefinition dataSetDefinition, EvaluationContext context) {
SimpleDataSet dataSet = new SimpleDataSet(dataSetDefinition, context);
SimplePatientDataSetDefinition definition = (SimplePatientDataSetDefinition) dataSetDefinition;
context = ObjectUtil.nvl(context, new EvaluationContext());
Cohort cohort = context.getBaseCohort();
// By default, get all patients
if (cohort == null) {
cohort = Context.getPatientSetService().getAllPatients();
}
if (context.getLimit() != null) {
CohortUtil.limitCohort(cohort, context.getLimit());
}
// Get a list of patients based on the cohort members
List<Patient> patients = Context.getPatientSetService().getPatients(cohort.getMemberIds());
// Pre-calculate the program states
Map<ProgramWorkflow, Map<Integer, PatientState>> states = new HashMap<ProgramWorkflow, Map<Integer, PatientState>>();
for (ProgramWorkflow wf : definition.getProgramWorkflows()) {
states.put(wf, Context.getPatientSetService().getCurrentStates(cohort, wf));
}
for (Patient p : patients) {
DataSetRow row = new DataSetRow();
for (PatientIdentifierType t : definition.getIdentifierTypes()) {
DataSetColumn c = new DataSetColumn(t.getName(), t.getName(), String.class);
PatientIdentifier id = p.getPatientIdentifier(t);
row.addColumnValue(c, id == null ? null : id.getIdentifier());
}
for (String s : definition.getPatientProperties()) {
try {
Method m = Patient.class.getMethod("get" + StringUtils.capitalize(s), new Class[] {});
DataSetColumn c = new DataSetColumn(s, s, m.getReturnType());
Object o = m.invoke(p, new Object[] {});
row.addColumnValue(c, o);
}
catch (Exception e) {
log.error("Unable to get property " + s + " on patient for dataset", e);
}
}
for (PersonAttributeType t : definition.getPersonAttributeTypes()) {
DataSetColumn c = new DataSetColumn(t.getName(), t.getName(), String.class);
PersonAttribute att = p.getAttribute(t);
row.addColumnValue(c, att == null ? null : att.getHydratedObject());
}
for (ProgramWorkflow t : definition.getProgramWorkflows()) {
String name = (t.getName() == null ? t.getConcept().getDisplayString() : t.getName());
DataSetColumn c = new DataSetColumn(name, name, String.class);
PatientState ps = states.get(t).get(p.getPatientId());
row.addColumnValue(c, (ps == null || !ps.getActive() || ps.getState().getConcept() == null) ? null : ps.getState().getConcept().getDisplayString() == null ? ps.getState().getConcept().getName() : ps.getState().getConcept().getDisplayString());
}
dataSet.addRow(row);
}
return dataSet;
}
| public DataSet evaluate(DataSetDefinition dataSetDefinition, EvaluationContext context) {
SimpleDataSet dataSet = new SimpleDataSet(dataSetDefinition, context);
SimplePatientDataSetDefinition definition = (SimplePatientDataSetDefinition) dataSetDefinition;
context = ObjectUtil.nvl(context, new EvaluationContext());
Cohort cohort = context.getBaseCohort();
// By default, get all patients
if (cohort == null) {
cohort = Context.getPatientSetService().getAllPatients();
}
if (context.getLimit() != null) {
CohortUtil.limitCohort(cohort, context.getLimit());
}
// Get a list of patients based on the cohort members
List<Patient> patients = Context.getPatientSetService().getPatients(cohort.getMemberIds());
// Pre-calculate the program states
Map<ProgramWorkflow, Map<Integer, PatientState>> states = new HashMap<ProgramWorkflow, Map<Integer, PatientState>>();
for (ProgramWorkflow wf : definition.getProgramWorkflows()) {
states.put(wf, Context.getPatientSetService().getCurrentStates(cohort, wf));
}
for (Patient p : patients) {
DataSetRow row = new DataSetRow();
for (PatientIdentifierType t : definition.getIdentifierTypes()) {
DataSetColumn c = new DataSetColumn(t.getName(), t.getName(), String.class);
PatientIdentifier id = p.getPatientIdentifier(t);
row.addColumnValue(c, id == null ? null : id.getIdentifier());
}
for (String s : definition.getPatientProperties()) {
try {
Method m = Patient.class.getMethod("get" + StringUtils.capitalize(s), new Class[] {});
DataSetColumn c = new DataSetColumn(s, s, m.getReturnType());
Object o = m.invoke(p, new Object[] {});
row.addColumnValue(c, o);
}
catch (Exception e) {
log.error("Unable to get property " + s + " on patient for dataset", e);
}
}
for (PersonAttributeType t : definition.getPersonAttributeTypes()) {
DataSetColumn c = new DataSetColumn(t.getName(), t.getName(), String.class);
PersonAttribute att = p.getAttribute(t);
row.addColumnValue(c, att == null ? null : att.getHydratedObject());
}
for (ProgramWorkflow t : definition.getProgramWorkflows()) {
String name = (t.getName() == null ? t.getConcept().getDisplayString() : t.getName());
DataSetColumn c = new DataSetColumn(name, name, String.class);
PatientState ps = states.get(t).get(p.getPatientId());
row.addColumnValue(c, (ps == null || !ps.getActive()) ? null : ps.getState().getConcept() == null ? ps.getState().toString() : ps.getState().getConcept().getDisplayString());
}
dataSet.addRow(row);
}
return dataSet;
}
|
diff --git a/src/main/java/com/alexrnl/commons/arguments/Arguments.java b/src/main/java/com/alexrnl/commons/arguments/Arguments.java
index a5a507b..a6afa31 100644
--- a/src/main/java/com/alexrnl/commons/arguments/Arguments.java
+++ b/src/main/java/com/alexrnl/commons/arguments/Arguments.java
@@ -1,103 +1,103 @@
package com.alexrnl.commons.arguments;
import java.lang.reflect.Field;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Logger;
import com.alexrnl.commons.utils.StringUtils;
import com.alexrnl.commons.utils.object.ReflectUtils;
/**
* Class which allow to parse string arguments and store them in a target object.
* @author Alex
*/
public class Arguments {
/** Logger */
private static Logger lg = Logger.getLogger(Arguments.class.getName());
/** The tab character */
private static final Character TAB = '\t';
/** The name of the program. */
private final String programName;
/** The object which holds the target */
private final Object target;
/** The list of parameters in the target */
private final SortedSet<Parameter> parameters;
/**
* Constructor #1.<br />
* @param programName
* the name of the program.
* @param target
* the object which holds the target.
*/
public Arguments (final String programName, final Object target) {
super();
this.programName = programName;
this.target = target;
this.parameters = retrieveParameters(target);
}
/**
* Parse and build a list with the parameters field marked with the {@link Param} annotation in
* the object specified.
* @param obj
* the object to parse for parameters.
* @return the list of parameters associated to this object.
*/
private static SortedSet<Parameter> retrieveParameters (final Object obj) {
final SortedSet<Parameter> params = new TreeSet<>();
for (final Field field : ReflectUtils.retrieveFields(obj.getClass(), Param.class)) {
field.setAccessible(true);
params.add(new Parameter(field, field.getAnnotation(Param.class)));
}
return params;
}
/**
* Parse the arguments and set the target in the target object.
* @param arguments
* the arguments to parse.
*/
public void parse (final String... arguments) {
parse(arguments);
}
/**
* Parse the arguments and set the target in the target object.
* @param arguments
* the arguments to parse.
*/
public void parse (final Iterable<String> arguments) {
// TODO
}
/**
* Display the parameter's usage on the standard output.
*/
public void usage () {
System.out.println(this);
}
@Override
public String toString () {
- final StringBuilder usage = new StringBuilder(programName + " usage as follow:");
+ final StringBuilder usage = new StringBuilder(programName).append(" usage as follow:");
for (final Parameter param : parameters) {
usage.append(TAB);
if (!param.isRequired()) {
usage.append('[');
} else {
usage.append(' ');
}
usage.append(" ").append(StringUtils.separateWith(", ", param.getNames()));
int nbTabs = 4;
while (nbTabs-- > 0) {
usage.append(TAB);
}
usage.append(param.getDescription());
}
return usage.toString();
}
}
| true | true | public String toString () {
final StringBuilder usage = new StringBuilder(programName + " usage as follow:");
for (final Parameter param : parameters) {
usage.append(TAB);
if (!param.isRequired()) {
usage.append('[');
} else {
usage.append(' ');
}
usage.append(" ").append(StringUtils.separateWith(", ", param.getNames()));
int nbTabs = 4;
while (nbTabs-- > 0) {
usage.append(TAB);
}
usage.append(param.getDescription());
}
return usage.toString();
}
| public String toString () {
final StringBuilder usage = new StringBuilder(programName).append(" usage as follow:");
for (final Parameter param : parameters) {
usage.append(TAB);
if (!param.isRequired()) {
usage.append('[');
} else {
usage.append(' ');
}
usage.append(" ").append(StringUtils.separateWith(", ", param.getNames()));
int nbTabs = 4;
while (nbTabs-- > 0) {
usage.append(TAB);
}
usage.append(param.getDescription());
}
return usage.toString();
}
|
diff --git a/src/antgame/core/World.java b/src/antgame/core/World.java
index 9b2063a..4aef89f 100644
--- a/src/antgame/core/World.java
+++ b/src/antgame/core/World.java
@@ -1,261 +1,261 @@
package antgame.core;
import java.util.ArrayList;
import antgame.AntGame;
import antgame.services.RandomNumber;
public class World {
private Ant[] ants;
private Map map;
private AntBrain redAntBrain;
private AntBrain blackAntBrain;
private ArrayList<Cell> bAHLoc = new ArrayList<Cell>();
private ArrayList<Cell> rAHLoc = new ArrayList<Cell>();
private int foodInRAH;
private int foodInBAH;
public World(String mapLocation, String antR, String antB, int numOfAnts){//, String antR, String antB){
this.map = new Map(mapLocation);
ants = new Ant[numOfAnts];
this.redAntBrain = new AntBrain(antR);
this.blackAntBrain = new AntBrain(antB);
// antPointer is the pointer in the array of ants to point to the next free positon also used as the uID
int antPointer = 0;
/* the following goes trough all of the cells looking for cells that contain an anthill
* once it finds an anthill it creates an ant sets its antid to the ant pointer, its direction to zero, its color dependant on the color
* ant hill, its state which is 0 and its intial location.
* it then adds the ant to the map !!!!!! should this be the constructor or call the method ant.
* it then increases the pointer
*
*/
for (int y = 0; y < (map.getYSize()); y++) {
for (int x = 0; x < (map.getXSize()); x++) {
if(map.getCell(x, y).containsRedAntHill()){
ants[antPointer] = new Ant(antPointer, 0, AntColour.RED, 0,map.getCell(x, y),redAntBrain);
rAHLoc.add(map.getCell(x, y));
map.getCell(x, y).antMoveIn(ants[antPointer]);
antPointer ++;
}
if(map.getCell(x, y).containsBlackAntHill()){
ants[antPointer] = new Ant(antPointer, 0, AntColour.BLACK, 0,map.getCell(x, y),blackAntBrain);
bAHLoc.add(map.getCell(x, y));
map.getCell(x, y).antMoveIn(ants[antPointer]);
antPointer ++;
}
}
}
}
public void step(){
for(int i=0; i < Integer.parseInt(AntGame.CONFIG.getProperty("numRound")); i++){
for(int j = 0; j<ants.length;i++){
foodInEachAntHill();
Ant curAnt = ants[j];
if(isAntSurronded(curAnt)){
curAnt.killAnt();
}
if(curAnt.isAlive()){
BrainState antsState = curAnt.getBrainState();
switch (antsState) {
case SENSE:
Cell cellTS = sensedCell(curAnt.getCurrentPos(),curAnt.getDir(),antsState.getSenseDirection());
SenseCondition sCon = antsState.getSenseCondition();
if(sCon == SenseCondition.MARKER){
if(cellTS.senseCheck(curAnt, sCon, sCon.getMarker())){
curAnt.setBrainState(antsState.getNextState());
}
else{
curAnt.setBrainState(antsState.getAltNextState());
}
}
else{
if(cellTS.senseCheck(curAnt, sCon, null)){
curAnt.setBrainState(antsState.getNextState());
}
else{
curAnt.setBrainState(antsState.getAltNextState());
}
}
break;
case MARK:
- curAnt.getCurrentPos().setMarker(curAnt.getColour(), antsState.getMarker());
+ curAnt.getCurrentPos().setMarker(antsState.getMarker());
curAnt.setBrainState(antsState.getNextState());
break;
case UNMARK:
- curAnt.getCurrentPos().clearMarker(curAnt.getColour(), antsState.getMarker());
+ curAnt.getCurrentPos().clearMarker(antsState.getMarker());
curAnt.setBrainState(antsState.getNextState());
break;
case PICKUP:
if(curAnt.getCurrentPos().isContainsFood()){
curAnt.getCurrentPos().removeFood();
curAnt.pickupFood();
curAnt.setBrainState(antsState.getNextState());
}
else{
curAnt.setBrainState(antsState.getAltNextState());
}
break;
case DROP:
if(curAnt.isHasFood()){
curAnt.dropFood();
curAnt.getCurrentPos().addFood();
}
curAnt.setBrainState(antsState.getNextState());
break;
case TURN:
curAnt.turn(antsState.getLeftRight());
break;
case MOVE:
Cell cellGoingTo = map.adjacentCell(curAnt.getCurrentPos(), curAnt.getDir());
if(cellGoingTo.isClear()){
curAnt.getCurrentPos().antMoveOut();
cellGoingTo.antMoveIn(curAnt);
curAnt.setCurrentPos(cellGoingTo);
curAnt.setBrainState(antsState.getNextState());
}
else{
curAnt.setBrainState(antsState.getAltNextState());
}
break;
case FLIP:
RandomNumber rN = new RandomNumber();
if(rN.nextInt(antsState.getRandomInt()) ==0){
curAnt.setBrainState(antsState.getNextState());
}
else{
curAnt.setBrainState(antsState.getAltNextState());
}
break;
}
}
}
}
}
public Cell sensedCell(Cell cell, int dir, SenseDirection senseDir){
switch (senseDir){
case HERE:
return cell;
case AHEAD:
return map.adjacentCell(cell,dir);
case LEFTAHEAD:
return map.adjacentCell(cell,((dir+5)%6));
case RIGHTAHEAD:
return map.adjacentCell(cell,(dir+1));
default:
return null;
}
}
public void foodInEachAntHill(){
int redFood = 0;
for(int i = 0; i<=rAHLoc.size();i++){
redFood = redFood + rAHLoc.get(i).getNumberOfFoodParticles();
}
foodInRAH = redFood;
int blackFood = 0;
for(int i = 0; i<=bAHLoc.size();i++){
blackFood = blackFood + bAHLoc.get(i).getNumberOfFoodParticles();
}
foodInBAH = blackFood;
}
public Ant getAnt(Cell cell){
if(cell.isContainsAnt()){
return cell.getAnt();
}
else{
return null;
}
}
public Ant getAnt(int[] pos){
Cell cell = map.getCell(pos);
if(cell.isContainsAnt()){
return cell.getAnt();
}
else{
return null;
}
}
public boolean isAntAt(Cell cell){
return cell.isContainsAnt();
}
public boolean isAntAt(int[] pos){
Cell cell = map.getCell(pos);
return cell.isContainsAnt();
}
public void killAntAt(Cell cell){
if(cell.isContainsAnt()){
//cell.getAnt().die();
cell.addNumFood(3);
ants[cell.getAnt().getuID()] = null;
cell.antMoveOut();
}
else{
System.err.print("No ant in Cell");
}
}
public void setAntAt(Ant ant, Cell cell){
if(cell.isClear()){
ant.setCurrentPos(cell);
cell.antMoveIn(ant);
}
}
public boolean nieveIsAntSurronded(Ant ant){
ArrayList<Cell> adjCells = map.adjacentCells(ant.getCurrentPos());
boolean surrounded = true;
for(Cell c:adjCells){
if(c.isClear()){
//
surrounded = false;
}
}
return surrounded;
}
public boolean isAntSurronded(Ant ant){
ArrayList<Cell> adjCells = map.adjacentCells(ant.getCurrentPos());
boolean surrounded = true;
for(Cell c:adjCells){
if(c.isClear()){
surrounded = false;
}
else if(ant.getColour() == AntColour.RED && c.containsRedAnt()){
//if red ant
surrounded = false;
}
else if(ant.getColour() == AntColour.BLACK && c.containsBlackAnt()){
//if red ant
surrounded = false;
}
}
return surrounded;
}
public static void main (String[] args){
}
}
| false | true | public World(String mapLocation, String antR, String antB, int numOfAnts){//, String antR, String antB){
this.map = new Map(mapLocation);
ants = new Ant[numOfAnts];
this.redAntBrain = new AntBrain(antR);
this.blackAntBrain = new AntBrain(antB);
// antPointer is the pointer in the array of ants to point to the next free positon also used as the uID
int antPointer = 0;
/* the following goes trough all of the cells looking for cells that contain an anthill
* once it finds an anthill it creates an ant sets its antid to the ant pointer, its direction to zero, its color dependant on the color
* ant hill, its state which is 0 and its intial location.
* it then adds the ant to the map !!!!!! should this be the constructor or call the method ant.
* it then increases the pointer
*
*/
for (int y = 0; y < (map.getYSize()); y++) {
for (int x = 0; x < (map.getXSize()); x++) {
if(map.getCell(x, y).containsRedAntHill()){
ants[antPointer] = new Ant(antPointer, 0, AntColour.RED, 0,map.getCell(x, y),redAntBrain);
rAHLoc.add(map.getCell(x, y));
map.getCell(x, y).antMoveIn(ants[antPointer]);
antPointer ++;
}
if(map.getCell(x, y).containsBlackAntHill()){
ants[antPointer] = new Ant(antPointer, 0, AntColour.BLACK, 0,map.getCell(x, y),blackAntBrain);
bAHLoc.add(map.getCell(x, y));
map.getCell(x, y).antMoveIn(ants[antPointer]);
antPointer ++;
}
}
}
}
public void step(){
for(int i=0; i < Integer.parseInt(AntGame.CONFIG.getProperty("numRound")); i++){
for(int j = 0; j<ants.length;i++){
foodInEachAntHill();
Ant curAnt = ants[j];
if(isAntSurronded(curAnt)){
curAnt.killAnt();
}
if(curAnt.isAlive()){
BrainState antsState = curAnt.getBrainState();
switch (antsState) {
case SENSE:
Cell cellTS = sensedCell(curAnt.getCurrentPos(),curAnt.getDir(),antsState.getSenseDirection());
SenseCondition sCon = antsState.getSenseCondition();
if(sCon == SenseCondition.MARKER){
if(cellTS.senseCheck(curAnt, sCon, sCon.getMarker())){
curAnt.setBrainState(antsState.getNextState());
}
else{
curAnt.setBrainState(antsState.getAltNextState());
}
}
else{
if(cellTS.senseCheck(curAnt, sCon, null)){
curAnt.setBrainState(antsState.getNextState());
}
else{
curAnt.setBrainState(antsState.getAltNextState());
}
}
break;
case MARK:
curAnt.getCurrentPos().setMarker(curAnt.getColour(), antsState.getMarker());
curAnt.setBrainState(antsState.getNextState());
break;
case UNMARK:
curAnt.getCurrentPos().clearMarker(curAnt.getColour(), antsState.getMarker());
curAnt.setBrainState(antsState.getNextState());
break;
case PICKUP:
if(curAnt.getCurrentPos().isContainsFood()){
curAnt.getCurrentPos().removeFood();
curAnt.pickupFood();
curAnt.setBrainState(antsState.getNextState());
}
else{
curAnt.setBrainState(antsState.getAltNextState());
}
break;
case DROP:
if(curAnt.isHasFood()){
curAnt.dropFood();
curAnt.getCurrentPos().addFood();
}
curAnt.setBrainState(antsState.getNextState());
break;
case TURN:
curAnt.turn(antsState.getLeftRight());
break;
case MOVE:
Cell cellGoingTo = map.adjacentCell(curAnt.getCurrentPos(), curAnt.getDir());
if(cellGoingTo.isClear()){
curAnt.getCurrentPos().antMoveOut();
cellGoingTo.antMoveIn(curAnt);
curAnt.setCurrentPos(cellGoingTo);
curAnt.setBrainState(antsState.getNextState());
}
else{
curAnt.setBrainState(antsState.getAltNextState());
}
break;
case FLIP:
RandomNumber rN = new RandomNumber();
if(rN.nextInt(antsState.getRandomInt()) ==0){
curAnt.setBrainState(antsState.getNextState());
}
else{
curAnt.setBrainState(antsState.getAltNextState());
}
break;
}
}
}
}
}
public Cell sensedCell(Cell cell, int dir, SenseDirection senseDir){
switch (senseDir){
case HERE:
return cell;
case AHEAD:
return map.adjacentCell(cell,dir);
case LEFTAHEAD:
return map.adjacentCell(cell,((dir+5)%6));
case RIGHTAHEAD:
return map.adjacentCell(cell,(dir+1));
default:
return null;
}
}
public void foodInEachAntHill(){
int redFood = 0;
for(int i = 0; i<=rAHLoc.size();i++){
redFood = redFood + rAHLoc.get(i).getNumberOfFoodParticles();
}
foodInRAH = redFood;
int blackFood = 0;
for(int i = 0; i<=bAHLoc.size();i++){
blackFood = blackFood + bAHLoc.get(i).getNumberOfFoodParticles();
}
foodInBAH = blackFood;
}
public Ant getAnt(Cell cell){
if(cell.isContainsAnt()){
return cell.getAnt();
}
else{
return null;
}
}
public Ant getAnt(int[] pos){
Cell cell = map.getCell(pos);
if(cell.isContainsAnt()){
return cell.getAnt();
}
else{
return null;
}
}
public boolean isAntAt(Cell cell){
return cell.isContainsAnt();
}
public boolean isAntAt(int[] pos){
Cell cell = map.getCell(pos);
return cell.isContainsAnt();
}
public void killAntAt(Cell cell){
if(cell.isContainsAnt()){
//cell.getAnt().die();
cell.addNumFood(3);
ants[cell.getAnt().getuID()] = null;
cell.antMoveOut();
}
else{
System.err.print("No ant in Cell");
}
}
public void setAntAt(Ant ant, Cell cell){
if(cell.isClear()){
ant.setCurrentPos(cell);
cell.antMoveIn(ant);
}
}
public boolean nieveIsAntSurronded(Ant ant){
ArrayList<Cell> adjCells = map.adjacentCells(ant.getCurrentPos());
boolean surrounded = true;
for(Cell c:adjCells){
if(c.isClear()){
//
surrounded = false;
}
}
return surrounded;
}
public boolean isAntSurronded(Ant ant){
ArrayList<Cell> adjCells = map.adjacentCells(ant.getCurrentPos());
boolean surrounded = true;
for(Cell c:adjCells){
if(c.isClear()){
surrounded = false;
}
else if(ant.getColour() == AntColour.RED && c.containsRedAnt()){
//if red ant
surrounded = false;
}
else if(ant.getColour() == AntColour.BLACK && c.containsBlackAnt()){
//if red ant
surrounded = false;
}
}
return surrounded;
}
public static void main (String[] args){
}
}
| public World(String mapLocation, String antR, String antB, int numOfAnts){//, String antR, String antB){
this.map = new Map(mapLocation);
ants = new Ant[numOfAnts];
this.redAntBrain = new AntBrain(antR);
this.blackAntBrain = new AntBrain(antB);
// antPointer is the pointer in the array of ants to point to the next free positon also used as the uID
int antPointer = 0;
/* the following goes trough all of the cells looking for cells that contain an anthill
* once it finds an anthill it creates an ant sets its antid to the ant pointer, its direction to zero, its color dependant on the color
* ant hill, its state which is 0 and its intial location.
* it then adds the ant to the map !!!!!! should this be the constructor or call the method ant.
* it then increases the pointer
*
*/
for (int y = 0; y < (map.getYSize()); y++) {
for (int x = 0; x < (map.getXSize()); x++) {
if(map.getCell(x, y).containsRedAntHill()){
ants[antPointer] = new Ant(antPointer, 0, AntColour.RED, 0,map.getCell(x, y),redAntBrain);
rAHLoc.add(map.getCell(x, y));
map.getCell(x, y).antMoveIn(ants[antPointer]);
antPointer ++;
}
if(map.getCell(x, y).containsBlackAntHill()){
ants[antPointer] = new Ant(antPointer, 0, AntColour.BLACK, 0,map.getCell(x, y),blackAntBrain);
bAHLoc.add(map.getCell(x, y));
map.getCell(x, y).antMoveIn(ants[antPointer]);
antPointer ++;
}
}
}
}
public void step(){
for(int i=0; i < Integer.parseInt(AntGame.CONFIG.getProperty("numRound")); i++){
for(int j = 0; j<ants.length;i++){
foodInEachAntHill();
Ant curAnt = ants[j];
if(isAntSurronded(curAnt)){
curAnt.killAnt();
}
if(curAnt.isAlive()){
BrainState antsState = curAnt.getBrainState();
switch (antsState) {
case SENSE:
Cell cellTS = sensedCell(curAnt.getCurrentPos(),curAnt.getDir(),antsState.getSenseDirection());
SenseCondition sCon = antsState.getSenseCondition();
if(sCon == SenseCondition.MARKER){
if(cellTS.senseCheck(curAnt, sCon, sCon.getMarker())){
curAnt.setBrainState(antsState.getNextState());
}
else{
curAnt.setBrainState(antsState.getAltNextState());
}
}
else{
if(cellTS.senseCheck(curAnt, sCon, null)){
curAnt.setBrainState(antsState.getNextState());
}
else{
curAnt.setBrainState(antsState.getAltNextState());
}
}
break;
case MARK:
curAnt.getCurrentPos().setMarker(antsState.getMarker());
curAnt.setBrainState(antsState.getNextState());
break;
case UNMARK:
curAnt.getCurrentPos().clearMarker(antsState.getMarker());
curAnt.setBrainState(antsState.getNextState());
break;
case PICKUP:
if(curAnt.getCurrentPos().isContainsFood()){
curAnt.getCurrentPos().removeFood();
curAnt.pickupFood();
curAnt.setBrainState(antsState.getNextState());
}
else{
curAnt.setBrainState(antsState.getAltNextState());
}
break;
case DROP:
if(curAnt.isHasFood()){
curAnt.dropFood();
curAnt.getCurrentPos().addFood();
}
curAnt.setBrainState(antsState.getNextState());
break;
case TURN:
curAnt.turn(antsState.getLeftRight());
break;
case MOVE:
Cell cellGoingTo = map.adjacentCell(curAnt.getCurrentPos(), curAnt.getDir());
if(cellGoingTo.isClear()){
curAnt.getCurrentPos().antMoveOut();
cellGoingTo.antMoveIn(curAnt);
curAnt.setCurrentPos(cellGoingTo);
curAnt.setBrainState(antsState.getNextState());
}
else{
curAnt.setBrainState(antsState.getAltNextState());
}
break;
case FLIP:
RandomNumber rN = new RandomNumber();
if(rN.nextInt(antsState.getRandomInt()) ==0){
curAnt.setBrainState(antsState.getNextState());
}
else{
curAnt.setBrainState(antsState.getAltNextState());
}
break;
}
}
}
}
}
public Cell sensedCell(Cell cell, int dir, SenseDirection senseDir){
switch (senseDir){
case HERE:
return cell;
case AHEAD:
return map.adjacentCell(cell,dir);
case LEFTAHEAD:
return map.adjacentCell(cell,((dir+5)%6));
case RIGHTAHEAD:
return map.adjacentCell(cell,(dir+1));
default:
return null;
}
}
public void foodInEachAntHill(){
int redFood = 0;
for(int i = 0; i<=rAHLoc.size();i++){
redFood = redFood + rAHLoc.get(i).getNumberOfFoodParticles();
}
foodInRAH = redFood;
int blackFood = 0;
for(int i = 0; i<=bAHLoc.size();i++){
blackFood = blackFood + bAHLoc.get(i).getNumberOfFoodParticles();
}
foodInBAH = blackFood;
}
public Ant getAnt(Cell cell){
if(cell.isContainsAnt()){
return cell.getAnt();
}
else{
return null;
}
}
public Ant getAnt(int[] pos){
Cell cell = map.getCell(pos);
if(cell.isContainsAnt()){
return cell.getAnt();
}
else{
return null;
}
}
public boolean isAntAt(Cell cell){
return cell.isContainsAnt();
}
public boolean isAntAt(int[] pos){
Cell cell = map.getCell(pos);
return cell.isContainsAnt();
}
public void killAntAt(Cell cell){
if(cell.isContainsAnt()){
//cell.getAnt().die();
cell.addNumFood(3);
ants[cell.getAnt().getuID()] = null;
cell.antMoveOut();
}
else{
System.err.print("No ant in Cell");
}
}
public void setAntAt(Ant ant, Cell cell){
if(cell.isClear()){
ant.setCurrentPos(cell);
cell.antMoveIn(ant);
}
}
public boolean nieveIsAntSurronded(Ant ant){
ArrayList<Cell> adjCells = map.adjacentCells(ant.getCurrentPos());
boolean surrounded = true;
for(Cell c:adjCells){
if(c.isClear()){
//
surrounded = false;
}
}
return surrounded;
}
public boolean isAntSurronded(Ant ant){
ArrayList<Cell> adjCells = map.adjacentCells(ant.getCurrentPos());
boolean surrounded = true;
for(Cell c:adjCells){
if(c.isClear()){
surrounded = false;
}
else if(ant.getColour() == AntColour.RED && c.containsRedAnt()){
//if red ant
surrounded = false;
}
else if(ant.getColour() == AntColour.BLACK && c.containsBlackAnt()){
//if red ant
surrounded = false;
}
}
return surrounded;
}
public static void main (String[] args){
}
}
|
diff --git a/source/RMG/jing/rxnSys/ReactionModelGenerator.java b/source/RMG/jing/rxnSys/ReactionModelGenerator.java
index 4448286d..61b63956 100644
--- a/source/RMG/jing/rxnSys/ReactionModelGenerator.java
+++ b/source/RMG/jing/rxnSys/ReactionModelGenerator.java
@@ -1,4183 +1,4189 @@
////////////////////////////////////////////////////////////////////////////////
//
// RMG - Reaction Mechanism Generator
//
// Copyright (c) 2002-2009 Prof. William H. Green ([email protected]) and the
// RMG Team ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////
package jing.rxnSys;
import java.io.*;
import jing.rxnSys.ReactionSystem;
import jing.rxn.*;
import jing.chem.*;
import java.util.*;
import jing.mathTool.UncertainDouble;
import jing.param.*;
import jing.chemUtil.*;
import jing.chemParser.*;
//## package jing::rxnSys
//----------------------------------------------------------------------------
// jing\rxnSys\ReactionModelGenerator.java
//----------------------------------------------------------------------------
//## class ReactionModelGenerator
public class ReactionModelGenerator {
protected LinkedList timeStep; //## attribute timeStep
protected ReactionModel reactionModel; //gmagoon 9/24/07
protected String workingDirectory; //## attribute workingDirectory
// protected ReactionSystem reactionSystem;
protected LinkedList reactionSystemList; //10/24/07 gmagoon: changed from reactionSystem to reactionSystemList
protected int paraInfor;//svp
protected boolean error;//svp
protected boolean sensitivity;//svp
protected LinkedList species;//svp
// protected InitialStatus initialStatus;//svp
protected LinkedList initialStatusList; //10/23/07 gmagoon: changed from initialStatus to initialStatusList
protected double rtol;//svp
protected static double atol;
protected PrimaryReactionLibrary primaryReactionLibrary;//9/24/07 gmagoon
protected ReactionModelEnlarger reactionModelEnlarger;//9/24/07 gmagoon
protected LinkedHashSet speciesSeed;//9/24/07 gmagoon;
protected ReactionGenerator reactionGenerator;//9/24/07 gmagoon
protected LibraryReactionGenerator lrg;// = new LibraryReactionGenerator();//9/24/07 gmagoon: moved from ReactionSystem.java;10/4/07 gmagoon: postponed initialization of lrg til later
//10/23/07 gmagoon: added additional variables
protected LinkedList tempList;
protected LinkedList presList;
protected LinkedList validList;//10/24/07 gmagoon: added
//10/25/07 gmagoon: moved variables from modelGeneration()
protected LinkedList initList = new LinkedList();
protected LinkedList beginList = new LinkedList();
protected LinkedList endList = new LinkedList();
protected LinkedList lastTList = new LinkedList();
protected LinkedList currentTList = new LinkedList();
protected LinkedList lastPList = new LinkedList();
protected LinkedList currentPList = new LinkedList();
protected LinkedList conditionChangedList = new LinkedList();
protected LinkedList reactionChangedList = new LinkedList();
protected int numConversions;//5/6/08 gmagoon: moved from initializeReactionSystem() to be an attribute so it can be accessed by modelGenerator()
protected String equationOfState;
// 24Jun2009 MRH: variable stores the first temperature encountered in the condition.txt file
// This temperature is used to select the "best" kinetics from the rxn library
protected static Temperature temp4BestKinetics;
// This is the new "PrimaryReactionLibrary"
protected SeedMechanism seedMechanism;
protected PrimaryThermoLibrary primaryThermoLibrary;
protected boolean restart = false;
protected boolean readrestart = false;
protected boolean writerestart = false;
protected LinkedHashSet restartCoreSpcs = new LinkedHashSet();
protected LinkedHashSet restartEdgeSpcs = new LinkedHashSet();
protected LinkedHashSet restartCoreRxns = new LinkedHashSet();
protected LinkedHashSet restartEdgeRxns = new LinkedHashSet();
// Constructors
private HashSet specs = new HashSet();
//public static native long getCpuTime();
//static {System.loadLibrary("cpuTime");}
//## operation ReactionModelGenerator()
public ReactionModelGenerator() {
//#[ operation ReactionModelGenerator()
workingDirectory = System.getProperty("RMG.workingDirectory");
//#]
}
//## operation initializeReactionSystem()
//10/24/07 gmagoon: changed name to initializeReactionSystems
public void initializeReactionSystems() throws InvalidSymbolException, IOException {
//#[ operation initializeReactionSystem()
try {
String initialConditionFile = System.getProperty("jing.rxnSys.ReactionModelGenerator.conditionFile");
if (initialConditionFile == null) {
System.out.println("undefined system property: jing.rxnSys.ReactionModelGenerator.conditionFile");
System.exit(0);
}
//double sandeep = getCpuTime();
//System.out.println(getCpuTime()/1e9/60);
FileReader in = new FileReader(initialConditionFile);
BufferedReader reader = new BufferedReader(in);
//TemperatureModel temperatureModel = null;//10/27/07 gmagoon: commented out
//PressureModel pressureModel = null;//10/27/07 gmagoon: commented out
// ReactionModelEnlarger reactionModelEnlarger = null;//10/9/07 gmagoon: commented out: unneeded now and causes scope problems
FinishController finishController = null;
//DynamicSimulator dynamicSimulator = null;//10/27/07 gmagoon: commented out and replaced with following line
LinkedList dynamicSimulatorList = new LinkedList();
//PrimaryReactionLibrary primaryReactionLibrary = null;//10/14/07 gmagoon: see below
setPrimaryReactionLibrary(null);//10/14/07 gmagoon: changed to use setPrimaryReactionLibrary
double [] conversionSet = new double[50];
String line = ChemParser.readMeaningfulLine(reader);
/*if (line.startsWith("Restart")){
StringTokenizer st = new StringTokenizer(line);
String token = st.nextToken();
token = st.nextToken();
if (token.equalsIgnoreCase("true")) {
//Runtime.getRuntime().exec("cp Restart/allSpecies.txt Restart/allSpecies1.txt");
//Runtime.getRuntime().exec("echo >> allSpecies.txt");
restart = true;
}
else if (token.equalsIgnoreCase("false")) {
Runtime.getRuntime().exec("rm Restart/allSpecies.txt");
restart = false;
}
else throw new InvalidSymbolException("UnIdentified Symbol "+token+" after Restart:");
}
else throw new InvalidSymbolException("Can't find Restart!");*/
//line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Database")){//svp
line = ChemParser.readMeaningfulLine(reader);
}
else throw new InvalidSymbolException("Can't find database!");
// if (line.startsWith("PrimaryThermoLibrary")){//svp
// line = ChemParser.readMeaningfulLine(reader);
// }
// else throw new InvalidSymbolException("Can't find primary thermo library!");
/*
* Added by MRH on 15-Jun-2009
* Give user the option to change the maximum carbon, oxygen,
* and/or radical number for all species. These lines will be
* optional in the condition.txt file. Values are hard-
* coded into RMG (in ChemGraph.java), but any user-
* defined input will override these values.
*/
/*
* Moved from before InitialStatus to before PrimaryThermoLibary
* by MRH on 27-Oct-2009
* Overriding default values of maximum number of "X" per
* chemgraph should come before RMG attempts to make any
* chemgraph. The first instance RMG will attempt to make a
* chemgraph is in reading the primary thermo library.
*/
if (line.startsWith("MaxCarbonNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxCarbonNumberPerSpecies:"
int maxCNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxCarbonNumber(maxCNum);
System.out.println("Note: Overriding RMG-defined MAX_CARBON_NUM with user-defined value: " + maxCNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxOxygenNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxOxygenNumberPerSpecies:"
int maxONum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxOxygenNumber(maxONum);
System.out.println("Note: Overriding RMG-defined MAX_OXYGEN_NUM with user-defined value: " + maxONum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxRadicalNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxRadicalNumberPerSpecies:"
int maxRadNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxRadicalNumber(maxRadNum);
System.out.println("Note: Overriding RMG-defined MAX_RADICAL_NUM with user-defined value: " + maxRadNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxSulfurNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxSulfurNumberPerSpecies:"
int maxSNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxSulfurNumber(maxSNum);
System.out.println("Note: Overriding RMG-defined MAX_SULFUR_NUM with user-defined value: " + maxSNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxSiliconNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxSiliconNumberPerSpecies:"
int maxSiNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxSiliconNumber(maxSiNum);
System.out.println("Note: Overriding RMG-defined MAX_SILICON_NUM with user-defined value: " + maxSiNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxHeavyAtom")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxHeavyAtomPerSpecies:"
int maxHANum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxHeavyAtomNumber(maxHANum);
System.out.println("Note: Overriding RMG-defined MAX_HEAVYATOM_NUM with user-defined value: " + maxHANum);
line = ChemParser.readMeaningfulLine(reader);
}
/*
* Read in the Primary Thermo Library
* MRH 7-Jul-2009
*/
if (line.startsWith("PrimaryThermoLibrary:")) {
/*
* MRH 27Feb2010:
* Changing the "read in Primary Thermo Library information" code
* into it's own method.
*
* Other modules (e.g. PopulateReactions) will be utilizing the exact code.
* Rather than copying and pasting code into other modules, just have
* everything call this new method: readAndMakePTL
*/
readAndMakePTL(reader);
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate PrimaryThermoLibrary field");
line = ChemParser.readMeaningfulLine(reader);
// Extra forbidden structures may be specified after the Primary Thermo Library
if (line.startsWith("ForbiddenStructures:")) {
readExtraForbiddenStructures(reader);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.toLowerCase().startsWith("readrestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "ReadRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes")) {
readrestart = true;
readRestartSpecies();
} else readrestart = false;
line = ChemParser.readMeaningfulLine(reader);
} else throw new InvalidSymbolException("Cannot locate ReadRestart field");
if (line.toLowerCase().startsWith("writerestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "WriteRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes"))
writerestart = true;
else writerestart = false;
line = ChemParser.readMeaningfulLine(reader);
} else throw new InvalidSymbolException("Cannot locate WriteRestart field");
// read temperature model
//gmagoon 10/23/07: modified to handle multiple temperatures; note that this requires different formatting of units in condition.txt
if (line.startsWith("TemperatureModel:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String modelType = st.nextToken();
//String t = st.nextToken();
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (modelType.equals("Constant")) {
tempList = new LinkedList();
//read first temperature
double t = Double.parseDouble(st.nextToken());
tempList.add(new ConstantTM(t, unit));
Temperature temp = new Temperature(t, unit);//10/29/07 gmagoon: added this line and next two lines to set Global.lowTemperature and Global.highTemperature
Global.lowTemperature = (Temperature)temp.clone();
Global.highTemperature = (Temperature)temp.clone();
//read remaining temperatures
while (st.hasMoreTokens()) {
t = Double.parseDouble(st.nextToken());
tempList.add(new ConstantTM(t, unit));
temp = new Temperature(t,unit);//10/29/07 gmagoon: added this line and next two "if" statements to set Global.lowTemperature and Global.highTemperature
if(temp.getK() < Global.lowTemperature.getK())
Global.lowTemperature = (Temperature)temp.clone();
if(temp.getK() > Global.highTemperature.getK())
Global.highTemperature = (Temperature)temp.clone();
}
// Global.temperature = new Temperature(t,unit);
}
//10/23/07 gmagoon: commenting out; further updates needed to get this to work
//else if (modelType.equals("Curved")) {
// String t = st.nextToken();
// // add reading curved temperature function here
// temperatureModel = new CurvedTM(new LinkedList());
//}
else {
throw new InvalidSymbolException("condition.txt: Unknown TemperatureModel = " + modelType);
}
}
else throw new InvalidSymbolException("condition.txt: can't find TemperatureModel!");
// read in pressure model
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("PressureModel:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String modelType = st.nextToken();
//String p = st.nextToken();
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (modelType.equals("Constant")) {
presList = new LinkedList();
//read first pressure
double p = Double.parseDouble(st.nextToken());
Pressure pres = new Pressure(p, unit);
Global.lowPressure = (Pressure)pres.clone();
Global.highPressure = (Pressure)pres.clone();
presList.add(new ConstantPM(p, unit));
//read remaining temperatures
while (st.hasMoreTokens()) {
p = Double.parseDouble(st.nextToken());
presList.add(new ConstantPM(p, unit));
pres = new Pressure(p, unit);
if(pres.getBar() < Global.lowPressure.getBar())
Global.lowPressure = (Pressure)pres.clone();
if(pres.getBar() > Global.lowPressure.getBar())
Global.highPressure = (Pressure)pres.clone();
}
//Global.pressure = new Pressure(p, unit);
}
//10/23/07 gmagoon: commenting out; further updates needed to get this to work
//else if (modelType.equals("Curved")) {
// // add reading curved pressure function here
// pressureModel = new CurvedPM(new LinkedList());
//}
else {
throw new InvalidSymbolException("condition.txt: Unknown PressureModel = " + modelType);
}
}
else throw new InvalidSymbolException("condition.txt: can't find PressureModel!");
// after PressureModel comes an optional line EquationOfState
// if "EquationOfState: Liquid" is found then initial concentrations are assumed to be correct
// if it is ommited, then initial concentrations are normalised to ensure PV=NRT (ideal gas law)
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("EquationOfState")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String eosType = st.nextToken();
if (eosType.equals("Liquid")) {
equationOfState="Liquid";
System.out.println("Equation of state: Liquid. Relying on concentrations in input file to get density correct; not checking PV=NRT");
}
line = ChemParser.readMeaningfulLine(reader);
}
// Read in InChI generation
if (line.startsWith("InChIGeneration:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String inchiOnOff = st.nextToken().toLowerCase();
if (inchiOnOff.equals("on")) {
Species.useInChI = true;
} else if (inchiOnOff.equals("off")) {
Species.useInChI = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown InChIGeneration flag: " + inchiOnOff);
line = ChemParser.readMeaningfulLine(reader);
}
// Read in Solvation effects
if (line.startsWith("Solvation:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String solvationOnOff = st.nextToken().toLowerCase();
if (solvationOnOff.equals("on")) {
Species.useSolvation = true;
} else if (solvationOnOff.equals("off")) {
Species.useSolvation = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
line = ChemParser.readMeaningfulLine(reader);
}
//line = ChemParser.readMeaningfulLine(reader);//read in reactants or thermo line
// Read in optional QM thermo generation
if (line.startsWith("ThermoMethod:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String thermoMethod = st.nextToken().toLowerCase();
if (thermoMethod.equals("qm")) {
ChemGraph.useQM = true;
line=ChemParser.readMeaningfulLine(reader);
if(line.startsWith("QMForCyclicsOnly:")){
StringTokenizer st2 = new StringTokenizer(line);
String nameCyc = st2.nextToken();
String option = st2.nextToken().toLowerCase();
if (option.equals("on")) {
ChemGraph.useQMonCyclicsOnly = true;
}
}
else{
System.out.println("condition.txt: Can't find 'QMForCyclicsOnly:' field");
System.exit(0);
}
line=ChemParser.readMeaningfulLine(reader);
if(line.startsWith("MaxRadNumForQM:")){
StringTokenizer st3 = new StringTokenizer(line);
String nameRadNum = st3.nextToken();
Global.maxRadNumForQM = Integer.parseInt(st3.nextToken());
}
else{
System.out.println("condition.txt: Can't find 'MaxRadNumForQM:' field");
System.exit(0);
}
}//otherwise, the flag useQM will remain false by default and the traditional group additivity approach will be used
line = ChemParser.readMeaningfulLine(reader);//read in reactants
}
// // Read in Solvation effects
// if (line.startsWith("Solvation:")) {
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String solvationOnOff = st.nextToken().toLowerCase();
// if (solvationOnOff.equals("on")) {
// Species.useSolvation = true;
// } else if (solvationOnOff.equals("off")) {
// Species.useSolvation = false;
// }
// else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
// }
// else throw new InvalidSymbolException("condition.txt: Cannot find solvation flag.");
// read in reactants
//
//10/4/07 gmagoon: moved to initializeCoreEdgeReactionModel
//LinkedHashSet p_speciesSeed = new LinkedHashSet();//gmagoon 10/4/07: changed to p_speciesSeed
//setSpeciesSeed(p_speciesSeed);//gmagoon 10/4/07: added
LinkedHashMap speciesSet = new LinkedHashMap();
LinkedHashMap speciesStatus = new LinkedHashMap();
int speciesnum = 1;
//System.out.println(line);
if (line.startsWith("InitialStatus")) {
line = ChemParser.readMeaningfulLine(reader);
while (!line.equals("END")) {
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String name = null;
if (!index.startsWith("(")) name = index;
else name = st.nextToken();
//if (restart) name += "("+speciesnum+")";
// 24Jun2009: MRH
// Check if the species name begins with a number.
// If so, terminate the program and inform the user to choose
// a different name. This is implemented so that the chem.inp
// file generated will be valid when run in Chemkin
try {
int doesNameBeginWithNumber = Integer.parseInt(name.substring(0,1));
System.out.println("\nA species name should not begin with a number." +
" Please rename species: " + name + "\n");
System.exit(0);
} catch (NumberFormatException e) {
// We're good
}
speciesnum ++;
if (!(st.hasMoreTokens())) throw new InvalidSymbolException("Couldn't find concentration of species: "+name);
String conc = st.nextToken();
double concentration = Double.parseDouble(conc);
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
concentration /= 1000;
unit = "mol/cm3";
}
else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
concentration /= 1000000;
unit = "mol/cm3";
}
else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
concentration /= 6.022e23;
}
else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
throw new InvalidUnitException("Species Concentration in condition.txt!");
}
//GJB to allow "unreactive" species that only follow user-defined library reactions.
// They will not react according to RMG reaction families
boolean IsReactive = true;
boolean IsConstantConcentration = false;
while (st.hasMoreTokens()) {
String reactive = st.nextToken().trim();
if (reactive.equalsIgnoreCase("unreactive"))
IsReactive = false;
if (reactive.equalsIgnoreCase("constantconcentration"))
IsConstantConcentration=true;
}
Graph g = ChemParser.readChemGraph(reader);
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
}
catch (ForbiddenStructureException e) {
System.out.println("Forbidden Structure:\n" + e.getMessage());
throw new InvalidSymbolException("A species in the input file has a forbidden structure.");
}
//System.out.println(name);
Species species = Species.make(name,cg);
species.setReactivity(IsReactive); // GJB
species.setConstantConcentration(IsConstantConcentration);
speciesSet.put(name, species);
getSpeciesSeed().add(species);
double flux = 0;
int species_type = 1; // reacted species
SpeciesStatus ss = new SpeciesStatus(species,species_type,concentration,flux);
speciesStatus.put(species, ss);
line = ChemParser.readMeaningfulLine(reader);
}
ReactionTime initial = new ReactionTime(0,"S");
//10/23/07 gmagoon: modified for handling multiple temperature, pressure conditions; note: concentration within speciesStatus (and list of conversion values) should not need to be modified for each T,P since this is done within isTPCconsistent in ReactionSystem
initialStatusList = new LinkedList();
for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
TemperatureModel tm = (TemperatureModel)iter.next();
for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
PressureModel pm = (PressureModel)iter2.next();
// LinkedHashMap speStat = (LinkedHashMap)speciesStatus.clone();//10/31/07 gmagoon: trying creating multiple instances of speciesStatus to address issues with concentration normalization (last normalization seems to apply to all)
Set ks = speciesStatus.keySet();
LinkedHashMap speStat = new LinkedHashMap();
for (Iterator iter3 = ks.iterator(); iter3.hasNext();){//11/1/07 gmagoon: perform deep copy; (is there an easier or more elegant way to do this?)
SpeciesStatus ssCopy = (SpeciesStatus)speciesStatus.get(iter3.next());
speStat.put(ssCopy.getSpecies(),new SpeciesStatus(ssCopy.getSpecies(),ssCopy.getSpeciesType(),ssCopy.getConcentration(),ssCopy.getFlux()));
}
initialStatusList.add(new InitialStatus(speStat,tm.getTemperature(initial),pm.getPressure(initial)));
}
}
}
else throw new InvalidSymbolException("condition.txt: can't find InitialStatus!");
// read in inert gas concentration
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("InertGas:")) {
line = ChemParser.readMeaningfulLine(reader);
while (!line.equals("END")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken().trim();
String conc = st.nextToken();
double inertConc = Double.parseDouble(conc);
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
inertConc /= 1000;
unit = "mol/cm3";
}
else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
inertConc /= 1000000;
unit = "mol/cm3";
}
else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
inertConc /= 6.022e23;
unit = "mol/cm3";
}
else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
throw new InvalidUnitException("Inert Gas Concentration not recognized: " + unit);
}
//SystemSnapshot.putInertGas(name,inertConc);
for(Iterator iter=initialStatusList.iterator();iter.hasNext(); ){//6/23/09 gmagoon: needed to change this to accommodate non-static inertConc
((InitialStatus)iter.next()).putInertGas(name,inertConc);
}
line = ChemParser.readMeaningfulLine(reader);
}
}
else throw new InvalidSymbolException("condition.txt: can't find Inert gas concentration!");
// read in spectroscopic data estimator
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("SpectroscopicDataEstimator:")) {
setSpectroscopicDataMode(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String sdeType = st.nextToken().toLowerCase();
// if (sdeType.equals("frequencygroups") || sdeType.equals("default")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
// }
// else if (sdeType.equals("therfit") || sdeType.equals("threefrequencymodel")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
// }
// else if (sdeType.equals("off") || sdeType.equals("none")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.OFF;
// }
// else throw new InvalidSymbolException("condition.txt: Unknown SpectroscopicDataEstimator = " + sdeType);
}
else throw new InvalidSymbolException("condition.txt: can't find SpectroscopicDataEstimator!");
// pressure dependence and related flags
line = ChemParser.readMeaningfulLine(reader);
if (line.toLowerCase().startsWith("pressuredependence:"))
line = setPressureDependenceOptions(line,reader);
else
throw new InvalidSymbolException("condition.txt: can't find PressureDependence flag!");
// include species (optional)
- if (!PDepRateConstant.getMode().name().equals("CHEBYSHEV") &&
- !PDepRateConstant.getMode().name().equals("PDEPARRHENIUS"))
- line = ChemParser.readMeaningfulLine(reader);
+ /*
+ *
+ * MRH 3-APR-2010:
+ * This if statement is no longer necessary and was causing an error
+ * when the PressureDependence field was set to "off"
+ */
+// if (!PDepRateConstant.getMode().name().equals("CHEBYSHEV") &&
+// !PDepRateConstant.getMode().name().equals("PDEPARRHENIUS"))
+// line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("IncludeSpecies")) {
StringTokenizer st = new StringTokenizer(line);
String iS = st.nextToken();
String fileName = st.nextToken();
HashSet includeSpecies = readIncludeSpecies(fileName);
((RateBasedRME)reactionModelEnlarger).addIncludeSpecies(includeSpecies);
line = ChemParser.readMeaningfulLine(reader);
}
// read in finish controller
if (line.startsWith("FinishController")) {
line = ChemParser.readMeaningfulLine(reader);
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String goal = st.nextToken();
String type = st.nextToken();
TerminationTester tt;
if (type.startsWith("Conversion")) {
LinkedList spc = new LinkedList();
while (st.hasMoreTokens()) {
String name = st.nextToken();
Species spe = (Species)speciesSet.get(name);
if (spe == null) throw new InvalidConversionException("Unknown reactant: " + name);
String conv = st.nextToken();
double conversion;
try {
if (conv.endsWith("%")) {
conversion = Double.parseDouble(conv.substring(0,conv.length()-1))/100;
}
else {
conversion = Double.parseDouble(conv);
}
conversionSet[49] = conversion;
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
SpeciesConversion sc = new SpeciesConversion(spe, conversion);
spc.add(sc);
}
tt = new ConversionTT(spc);
}
else if (type.startsWith("ReactionTime")) {
double time = Double.parseDouble(st.nextToken());
String unit = ChemParser.removeBrace(st.nextToken());
ReactionTime rt = new ReactionTime(time, unit);
tt = new ReactionTimeTT(rt);
}
else {
throw new InvalidSymbolException("condition.txt: Unknown FinishController = " + type);
}
line = ChemParser.readMeaningfulLine(reader);
st = new StringTokenizer(line, ":");
String temp = st.nextToken();
String tol = st.nextToken();
double tolerance;
try {
if (tol.endsWith("%")) {
tolerance = Double.parseDouble(tol.substring(0,tol.length()-1))/100;
}
else {
tolerance = Double.parseDouble(tol);
}
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
ValidityTester vt = null;
if (reactionModelEnlarger instanceof RateBasedRME) vt = new RateBasedVT(tolerance);
else if (reactionModelEnlarger instanceof RateBasedPDepRME) vt = new RateBasedPDepVT(tolerance);
else throw new InvalidReactionModelEnlargerException();
finishController = new FinishController(tt, vt);
}
else throw new InvalidSymbolException("condition.txt: can't find FinishController!");
// read in dynamic simulator
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("DynamicSimulator")) {
StringTokenizer st = new StringTokenizer(line,":");
String temp = st.nextToken();
String simulator = st.nextToken().trim();
//read in non-negative option if it exists: syntax would be something like this: "DynamicSimulator: DASSL: non-negative"
if (st.hasMoreTokens()){
if (st.nextToken().trim().toLowerCase().equals("non-negative")){
if(simulator.toLowerCase().equals("dassl")) JDAS.nonnegative = true;
else{
System.err.println("Non-negative option is currently only supported for DASSL. Switch to DASSL solver or remove non-negative option.");
System.exit(0);
}
}
}
numConversions = 0;//5/6/08 gmagoon: moved declaration from initializeReactionSystem() to be an attribute so it can be accessed by modelGenerator()
//int numConversions = 0;
boolean autoflag = false;//5/2/08 gmagoon: updating the following if/else-if block to consider input where we want to check model validity within the ODE solver at each time step; this will be indicated by the use of a string beginning with "AUTO" after the "TimeStep" or "Conversions" line
// read in time step
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("TimeStep:") && finishController.terminationTester instanceof ReactionTimeTT) {
st = new StringTokenizer(line);
temp = st.nextToken();
while (st.hasMoreTokens()) {
temp = st.nextToken();
if (temp.startsWith("AUTO")){//note potential opportunity for making case insensitive by using: temp.toUpperCase().startsWith("AUTO")
autoflag=true;
}
else if (!autoflag){//use "else if" to make sure additional numbers are not read in case numbers are erroneously used following AUTO; note that there could still be a problem if numbers come before "AUTO"
double tStep = Double.parseDouble(temp);
String unit = "sec";
setTimeStep(new ReactionTime(tStep, unit));
}
}
((ReactionTimeTT)finishController.terminationTester).setTimeSteps(timeStep);
}
else if (line.startsWith("Conversions:") && finishController.terminationTester instanceof ConversionTT){
st = new StringTokenizer(line);
temp = st.nextToken();
int i=0;
SpeciesConversion sc = (SpeciesConversion)((ConversionTT)finishController.terminationTester).speciesGoalConversionSet.get(0);
Species convSpecies = sc.species;
Iterator iter = ((InitialStatus)(initialStatusList.get(0))).getSpeciesStatus();//10/23/07 gmagoon: changed to use first element of initialStatusList, as subsequent operations should not be affected by which one is chosen
double initialConc = 0;
while (iter.hasNext()){
SpeciesStatus sps = (SpeciesStatus)iter.next();
if (sps.species.equals(convSpecies)) initialConc = sps.concentration;
}
while (st.hasMoreTokens()){
temp=st.nextToken();
if (temp.startsWith("AUTO")){
autoflag=true;
}
else if (!autoflag){
double conv = Double.parseDouble(temp);
conversionSet[i] = (1-conv) * initialConc;
i++;
}
}
conversionSet[i] = (1 - conversionSet[49])* initialConc;
numConversions = i+1;
}
else throw new InvalidSymbolException("condition.txt: can't find time step for dynamic simulator!");
// read in atol
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Atol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
atol = Double.parseDouble(st.nextToken());
}
else throw new InvalidSymbolException("condition.txt: can't find Atol for dynamic simulator!");
// read in rtol
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Rtol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
String rel_tol = st.nextToken();
if (rel_tol.endsWith("%"))
rtol = Double.parseDouble(rel_tol.substring(0,rel_tol.length()-1));
else
rtol = Double.parseDouble(rel_tol);
}
else throw new InvalidSymbolException("condition.txt: can't find Rtol for dynamic simulator!");
if (simulator.equals("DASPK")) {
paraInfor = 0;//svp
// read in SA
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Error bars")) {//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0) {
paraInfor = 1;
error = true;
}
else if (sa.compareToIgnoreCase("off")==0) {
paraInfor = 0;
error = false;
}
else throw new InvalidSymbolException("condition.txt: can't find error on/off information!");
}
else throw new InvalidSymbolException("condition.txt: can't find SA information!");
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Display sensitivity coefficients")){//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0){
paraInfor = 1;
sensitivity = true;
}
else if (sa.compareToIgnoreCase("off")==0){
if (paraInfor != 1){
paraInfor = 0;
}
sensitivity = false;
}
else throw new InvalidSymbolException("condition.txt: can't find SA on/off information!");
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
//6/25/08 gmagoon: changed loop to use i index, and updated DASPK constructor to pass i (mirroring changes to DASSL
//6/25/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i,finishController.getValidityTester(), autoflag));
}
}
species = new LinkedList();
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Display sensitivity information") ){
line = ChemParser.readMeaningfulLine(reader);
System.out.println(line);
while (!line.equals("END")){
st = new StringTokenizer(line);
String name = st.nextToken();
if (name.toUpperCase().equals("ALL")) ReactionSystem.printAllSens = true; //gmagoon 12/22/09: if the line contains the word "all", turn on the flag to print out sensitivity information for everything
species.add(name);
line = ChemParser.readMeaningfulLine(reader);
}
}
}
else if (simulator.equals("DASSL")) {
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
// for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
// dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)iter.next()));
// }
//11/1/07 gmagoon: changed loop to use i index, and updated DASSL constructor to pass i
//5/5/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i, finishController.getValidityTester(), autoflag));
}
}
else if (simulator.equals("Chemkin")) {
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("ReactorType")) {
st = new StringTokenizer(line, ":");
temp = st.nextToken();
String reactorType = st.nextToken().trim();
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
//dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)iter.next()));
dynamicSimulatorList.add(new Chemkin(rtol, atol, reactorType));//11/4/07 gmagoon: fixing apparent cut/paste error
}
}
}
else throw new InvalidSymbolException("condition.txt: Unknown DynamicSimulator = " + simulator);
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList; note: although conversionSet should actually be different for each T,P condition, it will be modified in isTPCconsistent within ReactionSystem
for (Iterator iter = dynamicSimulatorList.iterator(); iter.hasNext(); ) {
double [] cs = conversionSet.clone();//11/1/07 gmagoon: trying to make sure multiple instances of conversionSet are used
((DynamicSimulator)(iter.next())).addConversion(cs, numConversions);
}
}
else throw new InvalidSymbolException("condition.txt: can't find DynamicSimulator!");
// read in reaction model enlarger
/* Read in the Primary Reaction Library
* The user can specify as many PRLs,
* including none, as they like.
*/
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("PrimaryReactionLibrary:")) {
readAndMakePRL(reader);
} else throw new InvalidSymbolException("condition.txt: can't find PrimaryReactionLibrary");
/*
* Added by MRH 12-Jun-2009
*
* The SeedMechanism acts almost exactly as the old
* PrimaryReactionLibrary did. Whatever is in the SeedMechanism
* will be placed in the core at the beginning of the simulation.
* The user can specify as many seed mechanisms as they like, with
* the priority (in the case of duplicates) given to the first
* instance. There is no on/off flag.
*/
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("SeedMechanism:")) {
int numMechs = 0;
line = ChemParser.readMeaningfulLine(reader);
while (!line.equals("END")) {
String[] tempString = line.split("Name: ");
String name = tempString[tempString.length-1].trim();
line = ChemParser.readMeaningfulLine(reader);
tempString = line.split("Location: ");
String location = tempString[tempString.length-1].trim();
line = ChemParser.readMeaningfulLine(reader);
tempString = line.split("GenerateReactions: ");
String generateStr = tempString[tempString.length-1].trim();
boolean generate = true;
if (generateStr.equalsIgnoreCase("yes") ||
generateStr.equalsIgnoreCase("on") ||
generateStr.equalsIgnoreCase("true")){
generate = true;
System.out.println("Will generate cross-reactions between species in seed mechanism " + name);
} else if(generateStr.equalsIgnoreCase("no") ||
generateStr.equalsIgnoreCase("off") ||
generateStr.equalsIgnoreCase("false")) {
generate = false;
System.out.println("Will NOT initially generate cross-reactions between species in seed mechanism "+ name);
System.out.println("This may have unintended consequences");
}
else {
System.err.println("Input file invalid");
System.err.println("Please include a 'GenerateReactions: yes/no' line for seed mechanism "+name);
System.exit(0);
}
String path = System.getProperty("jing.rxn.ReactionLibrary.pathName");
path += "/" + location;
if (numMechs==0) {
setSeedMechanism(new SeedMechanism(name, path, generate));
++numMechs;
}
else {
getSeedMechanism().appendSeedMechanism(name, path, generate);
++numMechs;
}
line = ChemParser.readMeaningfulLine(reader);
}
if (numMechs != 0) System.out.println("Seed Mechanisms in use: " + getSeedMechanism().getName());
else setSeedMechanism(null);
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate SeedMechanism field");
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("ChemkinUnits")) {
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Verbose:")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken();
String OnOff = st.nextToken().toLowerCase();
if (OnOff.equals("off")) {
ArrheniusKinetics.setVerbose(false);
} else if (OnOff.equals("on")) {
ArrheniusKinetics.setVerbose(true);
}
line = ChemParser.readMeaningfulLine(reader);
}
/*
* MRH 3MAR2010:
* Adding user option regarding chemkin file
*
* New field: If user would like the empty SMILES string
* printed with each species in the thermochemistry portion
* of the generated chem.inp file
*/
if (line.toUpperCase().startsWith("SMILES")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // Should be "SMILES:"
String OnOff = st.nextToken().toLowerCase();
if (OnOff.equals("off")) {
Chemkin.setSMILES(false);
} else if (OnOff.equals("on")) {
Chemkin.setSMILES(true);
/*
* MRH 9MAR2010:
* MRH decided not to generate an InChI for every new species
* during an RMG simulation (especially since it is not used
* for anything). Instead, they will only be generated in the
* post-processing, if the user asked for InChIs.
*/
//Species.useInChI = true;
}
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("A")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // Should be "A:"
String units = st.nextToken();
if (units.equals("moles") || units.equals("molecules"))
ArrheniusKinetics.setAUnits(units);
else {
System.err.println("Units for A were not recognized: " + units);
System.exit(0);
}
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate Chemkin units A field.");
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Ea")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // Should be "Ea:"
String units = st.nextToken();
if (units.equals("kcal/mol") || units.equals("cal/mol") ||
units.equals("kJ/mol") || units.equals("J/mol") || units.equals("Kelvins"))
ArrheniusKinetics.setEaUnits(units);
else {
System.err.println("Units for Ea were not recognized: " + units);
System.exit(0);
}
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate Chemkin units Ea field.");
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate ChemkinUnits field.");
in.close();
//11/6/07 gmagoon: initializing temperatureArray and pressureArray before libraryReactionGenerator is initialized (initialization calls PDepNetwork and performs initializekLeak); UPDATE: moved after initialStatusList initialization (in case primaryReactionLibrary calls the similar pdep functions
// LinkedList temperatureArray = new LinkedList();
// LinkedList pressureArray = new LinkedList();
// Iterator iterIS = initialStatusList.iterator();
// for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
// TemperatureModel tm = (TemperatureModel)iter.next();
// for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
// PressureModel pm = (PressureModel)iter2.next();
// InitialStatus is = (InitialStatus)iterIS.next();
// temperatureArray.add(tm.getTemperature(is.getTime()));
// pressureArray.add(pm.getPressure(is.getTime()));
// }
// }
// PDepNetwork.setTemperatureArray(temperatureArray);
// PDepNetwork.setPressureArray(pressureArray);
//10/4/07 gmagoon: moved to modelGeneration()
//ReactionGenerator p_reactionGenerator = new TemplateReactionGenerator();//10/4/07 gmagoon: changed to p_reactionGenerator from reactionGenerator
// setReactionGenerator(p_reactionGenerator);//10/4/07 gmagoon: added
/*
* MRH 12-Jun-2009
* A TemplateReactionGenerator now requires a Temperature be passed to it.
* This allows RMG to determine the "best" kinetic parameters to use
* in the mechanism generation. For now, I choose to pass the first
* temperature in the list of temperatures. RMG only outputs one mechanism,
* even for multiple temperature/pressure systems, so we can only have one
* set of kinetics.
*/
Temperature t = new Temperature(300,"K");
for (Iterator iter = tempList.iterator(); iter.hasNext();) {
TemperatureModel tm = (TemperatureModel)iter.next();
t = tm.getTemperature(new ReactionTime(0,"sec"));
setTemp4BestKinetics(t);
break;
}
setReactionGenerator(new TemplateReactionGenerator()); //11/4/07 gmagoon: moved from modelGeneration; mysteriously, moving this later moves "Father" lines up in output at runtime, immediately after condition file (as in original code); previously, these Father lines were just before "Can't read primary reaction library files!"
lrg = new LibraryReactionGenerator();//10/10/07 gmagoon: moved from modelGeneration (sequence lrg increases species id, and the different sequence was causing problems as main species id was 6 instead of 1); //10/31/07 gmagoon: restored this line from 10/10/07 backup: somehow it got lost along the way; 11/5/07 gmagoon: changed to use "lrg =" instead of setLibraryReactionGenerator
//10/24/07 gmagoon: updated to use multiple reactionSystem variables
reactionSystemList = new LinkedList();
// LinkedList temperatureArray = new LinkedList();//10/30/07 gmagoon: added temperatureArray variable for passing to PDepNetwork; 11/6/07 gmagoon: moved before initialization of lrg;
// LinkedList pressureArray = new LinkedList();//10/30/07 gmagoon: same for pressure;//UPDATE: commenting out: not needed if updateKLeak is done for one temperature/pressure at a time; 11/1-2/07 restored;11/6/07 gmagoon: moved before initialization of lrg;
Iterator iter3 = initialStatusList.iterator();
Iterator iter4 = dynamicSimulatorList.iterator();
int i = 0;//10/30/07 gmagoon: added
for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
TemperatureModel tm = (TemperatureModel)iter.next();
//InitialStatus is = (InitialStatus)iter3.next();//10/31/07 gmagoon: fixing apparent bug by moving these inside inner "for loop"
//DynamicSimulator ds = (DynamicSimulator)iter4.next();
for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
PressureModel pm = (PressureModel)iter2.next();
InitialStatus is = (InitialStatus)iter3.next();//10/31/07 gmagoon: moved from outer "for loop""
DynamicSimulator ds = (DynamicSimulator)iter4.next();
// temperatureArray.add(tm.getTemperature(is.getTime()));//10/30/07 gmagoon: added; //10/31/07 added .getTemperature(is.getTime()); 11/6/07 gmagoon: moved before initialization of lrg;
// pressureArray.add(pm.getPressure(is.getTime()));//10/30/07 gmagoon: added//UPDATE: commenting out: not needed if updateKLeak is done for one temperature/pressure at a time;11/1-2/07 restored with .getTemperature(is.getTime()) added;11/6/07 gmagoon: moved before initialization of lrg;
//11/1/07 gmagoon: trying to make a deep copy of terminationTester when it is instance of ConversionTT
//UPDATE: actually, I don't think this deep copy was necessary; original case with FinishController fc = new FinishController(finishController.getTerminationTester(), finishController.getValidityTester()) is probably OK; (in any case, this didn't do completetly deep copy (references to speciesConversion element in LinkedList were the same);
// TerminationTester termTestCopy;
// if (finishController.getTerminationTester() instanceof ConversionTT){
// ConversionTT termTest = (ConversionTT)finishController.getTerminationTester();
// LinkedList spcCopy = (LinkedList)(termTest.getSpeciesGoalConversionSetList().clone());
// termTestCopy = new ConversionTT(spcCopy);
// }
// else{
// termTestCopy = finishController.getTerminationTester();
// }
FinishController fc = new FinishController(finishController.getTerminationTester(), finishController.getValidityTester());//10/31/07 gmagoon: changed to create new finishController instance in each case (apparently, the finish controller becomes associated with reactionSystem in setFinishController within ReactionSystem); alteratively, could use clone, but might need to change FinishController to be "cloneable"
// FinishController fc = new FinishController(termTestCopy, finishController.getValidityTester());
reactionSystemList.add(new ReactionSystem(tm, pm, reactionModelEnlarger, fc, ds, getPrimaryReactionLibrary(), getReactionGenerator(), getSpeciesSeed(), is, getReactionModel(),lrg, i, equationOfState));
i++;//10/30/07 gmagoon: added
System.out.println("Created reaction system "+i+"\n");
}
}
// PDepNetwork.setTemperatureArray(temperatureArray);//10/30/07 gmagoon: passing temperatureArray to PDepNetwork; 11/6/07 gmagoon: moved before initialization of lrg;
// PDepNetwork.setPressureArray(pressureArray);//10/30/07 gmagoon: same for pressure;//UPDATE: commenting out: not needed if updateKLeak is done for one temperature/pressure at a time; 11/1-2/07 restored; 11/6/07 gmagoon: moved before initialization of lrg;
}
catch (IOException e) {
System.err.println("Error reading reaction system initialization file.");
throw new IOException("Input file error: " + e.getMessage());
}
}
public void setReactionModel(ReactionModel p_ReactionModel) {
reactionModel = p_ReactionModel;
}
public void modelGeneration() {
//long begin_t = System.currentTimeMillis();
try{
ChemGraph.readForbiddenStructure();
setSpeciesSeed(new LinkedHashSet());//10/4/07 gmagoon moved from initializeCoreEdgeReactionModel
// setReactionGenerator(new TemplateReactionGenerator());//10/4/07 gmagoon: moved inside initializeReactionSystem; 11/3-4/07 gmagoon: probably reverted on or before 10/10/07 (although I have not investigated this change in detail); //11/4/07 gmagoon: moved inside initializeReactionSystems
// setLibraryReactionGenerator(new LibraryReactionGenerator());//10/10/07 gmagoon: moved after initializeReactionSystem
// initializeCoreEdgeReactionModel();//10/4/07 gmagoon moved from below to run initializeCoreEdgeReactionModel before initializeReactionSystem; 11/3-4/07 gmagoon: probably reverted on or before 10/10/07
initializeReactionSystems();
}
catch (IOException e) {
System.err.println(e.getMessage());
System.exit(0);
}
catch (InvalidSymbolException e) {
System.err.println(e.getMessage());
System.exit(0);
}
//10/31/07 gmagoon: initialize validList (to false) before initializeCoreEdgeReactionModel is called
validList = new LinkedList();
for (Integer i = 0; i<reactionSystemList.size();i++) {
validList.add(false);
}
initializeCoreEdgeReactionModel();//10/4/07 gmagoon: moved before initializeReactionSystem; 11/3-4/07 gmagoon: probably reverted on or before 10/10/07
//10/24/07 gmagoon: changed to use reactionSystemList
// LinkedList initList = new LinkedList();//10/25/07 gmagoon: moved these variables to apply to entire class
// LinkedList beginList = new LinkedList();
// LinkedList endList = new LinkedList();
// LinkedList lastTList = new LinkedList();
// LinkedList currentTList = new LinkedList();
// LinkedList lastPList = new LinkedList();
// LinkedList currentPList = new LinkedList();
// LinkedList conditionChangedList = new LinkedList();
// LinkedList reactionChangedList = new LinkedList();
//5/6/08 gmagoon: determine whether there are intermediate time/conversion steps, type of termination tester is based on characteristics of 1st reaction system (it is assumed that they are all identical in terms of type of termination tester)
boolean intermediateSteps = true;
ReactionSystem rs0 = (ReactionSystem)reactionSystemList.get(0);
if (rs0.finishController.terminationTester instanceof ReactionTimeTT){
if (timeStep == null){
intermediateSteps = false;
}
}
else if (numConversions==1){ //if we get to this block, we presumably have a conversion terminationTester; this required moving numConversions to be attribute...alternative to using numConversions is to access one of the DynamicSimulators and determine conversion length
intermediateSteps=false;
}
//10/24/07 gmagoon: note: each element of for loop could be done in parallel if desired; some modifications would be needed
for (Iterator iter = reactionSystemList.iterator(); iter.hasNext(); ) {
ReactionSystem rs = (ReactionSystem)iter.next();
if ((reactionModelEnlarger instanceof RateBasedPDepRME)) {//1/2/09 gmagoon and rwest: only call initializePDepNetwork for P-dep cases
rs.initializePDepNetwork();
}
ReactionTime init = rs.getInitialReactionTime();
initList.add(init);
ReactionTime begin = init;
beginList.add(begin);
ReactionTime end;
if (rs.finishController.terminationTester instanceof ReactionTimeTT){
//5/5/08 gmagoon: added below if statement to avoid null pointer exception in cases where there are no intermediate time steps specified
if (!(timeStep==null)){
end = (ReactionTime)timeStep.get(0);
}
else{
end= ((ReactionTimeTT)rs.finishController.terminationTester).finalTime;
}
//end = (ReactionTime)timeStep.get(0);
endList.add(end);
}
else{
end = new ReactionTime(1e6,"sec");
endList.add(end);
}
// int iterationNumber = 1;
lastTList.add(rs.getTemperature(init));
currentTList.add(rs.getTemperature(init));
lastPList.add(rs.getPressure(init));
currentPList.add(rs.getPressure(init));
conditionChangedList.add(false);
reactionChangedList.add(false);//10/31/07 gmagoon: added
//Chemkin.writeChemkinInputFile(reactionSystem.getReactionModel(),reactionSystem.getPresentStatus());
}
int iterationNumber = 1;
LinkedList terminatedList = new LinkedList();//10/24/07 gmagoon: this may not be necessary, as if one reactionSystem is terminated, I think all should be terminated
//validList = new LinkedList();//10/31/07 gmagoon: moved before initializeCoreEdgeReactionModel
//10/24/07 gmagoon: initialize allTerminated and allValid to true; these variables keep track of whether all the reactionSystem variables satisfy termination and validity, respectively
boolean allTerminated = true;
boolean allValid = true;
// IF RESTART IS TURNED ON
// Update the systemSnapshot for each ReactionSystem in the reactionSystemList
if (readrestart) {
for (Integer i=0; i<reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
InitialStatus is = rs.getInitialStatus();
putRestartSpeciesInInitialStatus(is,i);
rs.appendUnreactedSpeciesStatus((InitialStatus)initialStatusList.get(i), rs.getPresentTemperature());
}
}
//10/24/07 gmagoon: note: each element of for loop could be done in parallel if desired; some modifications would be needed
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
ReactionTime begin = (ReactionTime)beginList.get(i);
ReactionTime end = (ReactionTime)endList.get(i);
endList.set(i,rs.solveReactionSystem(begin, end, true, true, true, iterationNumber-1));
Chemkin.writeChemkinInputFile(rs);//11/9/07 gmagoon:****temporarily commenting out: there is a NullPointerException in Reaction.toChemkinString when called from writeChemkinPdepReactions; occurs with pre-modified version of RMG as well; //11/12/07 gmagoon: restored; ****this appears to be source of non-Pdep bug
boolean terminated = rs.isReactionTerminated();
terminatedList.add(terminated);
if(!terminated)
allTerminated = false;
boolean valid = rs.isModelValid();
//validList.add(valid);
validList.set(i, valid);//10/31/07 gmagoon: validList initialization moved before initializeCoreEdgeReactionModel
if(!valid)
allValid = false;
reactionChangedList.set(i,false);
}
//9/1/09 gmagoon: if we are using QM, output a file with the CHEMKIN name, the RMG name, the (modified) InChI, and the (modified) InChIKey
if (ChemGraph.useQM){
writeInChIs(getReactionModel());
}
writeDictionary(getReactionModel());
//System.exit(0);
System.out.println("The model core has " + ((CoreEdgeReactionModel)getReactionModel()).getReactedReactionSet().size() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species.");
System.out.println("The model edge has " + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().size() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().size() + " species.");
StringBuilder print_info = Global.diagnosticInfo;
print_info.append("\nMolecule \t Flux\t\tTime\t \t\t \t Core \t \t Edge \t \t memory\n");
print_info.append(" \t moleular \t characteristic \t findspecies \t moveUnreactedToReacted \t enlarger \t restart1 \t totalEnlarger \t resetSystem \t readSolverFile\t writeSolverFile \t justSolver \t SolverIterations \t solverSpeciesStatus \t Totalsolver \t gc \t restart+diagnosis \t chemkin thermo \t chemkin reactions \t validitytester \t Species \t Reactions\t Species\t Reactions \t memory used \t allSpecies \t TotalTime \t findRateConstant\t identifyReactedSites \t reactChemGraph \t makespecies\t CheckReverseReaction \t makeTemplateReaction \t getReactionfromStruc \t genReverseFromReac");
print_info.append("\t\t\t\t\t\t\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size()+ "\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedReactionSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSetIncludingReverseSize() + "\t"+Global.makeSpecies+"\n");
double solverMin = 0;
double vTester = 0;
/*if (!restart){
writeRestartFile();
writeCoreReactions();
writeAllReactions();
}*/
//System.exit(0);
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
System.out.println("Species dictionary size: "+dictionary.size());
//boolean reactionChanged = false;//10/24/07 gmagoon: I don't know if this is even required, but I will change to use reactionChangedList (I put analogous line of code for list in above for loop); update: yes, it is required; I had been thinking of conditionChangedList
double tAtInitialization = Global.tAtInitialization;
//10/24/07: changed to use allTerminated and allValid
// step 2: iteratively grow reaction system
while (!allTerminated || !allValid) {
while (!allValid) {
//writeCoreSpecies();
double pt = System.currentTimeMillis();
// ENLARGE THE MODEL!!! (this is where the good stuff happens)
enlargeReactionModel();//10/24/07 gmagoon: need to adjust this function
double totalEnlarger = (System.currentTimeMillis() - pt)/1000/60;
//PDepNetwork.completeNetwork(reactionSystem.reactionModel.getSpeciesSet());
//10/24/07 gmagoon: changed to use reactionSystemList
if ((reactionModelEnlarger instanceof RateBasedPDepRME)) {//1/2/09 gmagoon and rwest: only call initializePDepNetwork for P-dep cases
for (Iterator iter = reactionSystemList.iterator(); iter.hasNext(); ) {
ReactionSystem rs = (ReactionSystem)iter.next();
rs.initializePDepNetwork();
}
//reactionSystem.initializePDepNetwork();
}
pt = System.currentTimeMillis();
//10/24/07 gmagoon: changed to use reactionSystemList
for (Iterator iter = reactionSystemList.iterator(); iter.hasNext(); ) {
ReactionSystem rs = (ReactionSystem)iter.next();
rs.resetSystemSnapshot();
}
//reactionSystem.resetSystemSnapshot();
double resetSystem = (System.currentTimeMillis() - pt)/1000/60;
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
//reactionChanged = true;
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
reactionChangedList.set(i,true);
// begin = init;
beginList.set(i, (ReactionTime)initList.get(i));
if (rs.finishController.terminationTester instanceof ReactionTimeTT){
//5/5/08 gmagoon: added below if statement to avoid null pointer exception in cases where there are no intermediate time steps specified
if (!(timeStep==null)){
endList.set(i,(ReactionTime)timeStep.get(0));
}
else{
endList.set(i, ((ReactionTimeTT)rs.finishController.terminationTester).finalTime);
}
// endList.set(i, (ReactionTime)timeStep.get(0));
//end = (ReactionTime)timeStep.get(0);
}
else
endList.set(i, new ReactionTime(1e6,"sec"));
//end = new ReactionTime(1e6,"sec");
// iterationNumber = 1;//10/24/07 gmagoon: moved outside of loop
currentTList.set(i,rs.getTemperature((ReactionTime)beginList.get(i)));
currentPList.set(i,rs.getPressure((ReactionTime)beginList.get(i)));
conditionChangedList.set(i,!(((Temperature)currentTList.get(i)).equals((Temperature)lastTList.get(i))) || !(((Pressure)currentPList.get(i)).equals((Pressure)lastPList.get(i))));
//currentT = reactionSystem.getTemperature(begin);
//currentP = reactionSystem.getPressure(begin);
//conditionChanged = (!currentT.equals(lastT) || !currentP.equals(lastP));
}
iterationNumber = 1;
double startTime = System.currentTimeMillis();
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean reactionChanged = (Boolean)reactionChangedList.get(i);
boolean conditionChanged = (Boolean)conditionChangedList.get(i);
ReactionTime begin = (ReactionTime)beginList.get(i);
ReactionTime end = (ReactionTime)endList.get(i);
endList.set(i,rs.solveReactionSystem(begin, end, false, reactionChanged, conditionChanged, iterationNumber-1));
//end = reactionSystem.solveReactionSystem(begin, end, false, reactionChanged, conditionChanged, iterationNumber-1);
}
solverMin = solverMin + (System.currentTimeMillis()-startTime)/1000/60;
startTime = System.currentTimeMillis();
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
Chemkin.writeChemkinInputFile(rs);//10/25/07 gmagoon: ***I don't know if this will still work with multiple reaction systems: may want to modify to only write one chemkin input file for all reaction systems //11/9/07 gmagoon:****temporarily commenting out; cf. previous comment; //11/12/07 gmagoon: restored; ****this appears to be source of non-Pdep bug
//Chemkin.writeChemkinInputFile(reactionSystem);
}
//9/1/09 gmagoon: if we are using QM, output a file with the CHEMKIN name, the RMG name, the (modified) InChI, and the (modified) InChIKey
if (ChemGraph.useQM){
writeInChIs(getReactionModel());
}
writeDictionary(getReactionModel());
double chemkint = (System.currentTimeMillis()-startTime)/1000/60;
if (writerestart) {
writeCoreSpecies();
writeCoreReactions();
writeEdgeSpecies();
writeEdgeReactions();
if (PDepNetwork.generateNetworks == true) writePDepNetworks();
}
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
System.out.println("For reaction system: "+(i+1)+" out of "+reactionSystemList.size());
System.out.println("At this time: " + ((ReactionTime)endList.get(i)).toString());
Species spe = SpeciesDictionary.getSpeciesFromID(1);
double conv = rs.getPresentConversion(spe);
System.out.print("Conversion of " + spe.getName() + " is:");
System.out.println(conv);
}
System.out.println("Running Time is: " + String.valueOf((System.currentTimeMillis()-tAtInitialization)/1000/60) + " minutes.");
System.out.println("The model edge has " + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().size() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().size() + " species.");
//10/24/07 gmagoon: note: all reaction systems should use the same core, but I will display for each reactionSystem for testing purposes:
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
System.out.println("For reaction system: "+(i+1)+" out of "+reactionSystemList.size());
if (rs.getDynamicSimulator() instanceof JDASPK){
JDASPK solver = (JDASPK)rs.getDynamicSimulator();
System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species.");
}
else{
JDASSL solver = (JDASSL)rs.getDynamicSimulator();
System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species.");
}
}
// if (reactionSystem.getDynamicSimulator() instanceof JDASPK){
// JDASPK solver = (JDASPK)reactionSystem.getDynamicSimulator();
// System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species.");
//}
//else{
// JDASSL solver = (JDASSL)reactionSystem.getDynamicSimulator();
// System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species.");
//}
startTime = System.currentTimeMillis();
double mU = memoryUsed();
double gc = (System.currentTimeMillis()-startTime)/1000/60;
startTime = System.currentTimeMillis();
//10/24/07 gmagoon: updating to use reactionSystemList
allValid = true;
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean valid = rs.isModelValid();
if(!valid)
allValid = false;
validList.set(i,valid);
//valid = reactionSystem.isModelValid();
}
vTester = vTester + (System.currentTimeMillis()-startTime)/1000/60;
startTime = System.currentTimeMillis();
writeDiagnosticInfo();
writeEnlargerInfo();
double restart2 = (System.currentTimeMillis()-startTime)/1000/60;
int allSpecies, allReactions;
allSpecies = SpeciesDictionary.getInstance().size();
print_info.append(totalEnlarger + "\t" + resetSystem + "\t" + Global.readSolverFile + "\t" + Global.writeSolverFile + "\t" + Global.solvertime + "\t" + Global.solverIterations + "\t" + Global.speciesStatusGenerator + "\t" + solverMin + "\t" + gc + "\t" + restart2 + "\t" + Global.chemkinThermo + '\t' + Global.chemkinReaction + "\t" + vTester + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size()+ "\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedReactionSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSetIncludingReverseSize() + "\t" + mU + "\t" + allSpecies + "\t" + (System.currentTimeMillis()-Global.tAtInitialization)/1000/60 + "\t"+ String.valueOf(Global.RT_findRateConstant)+"\t"+Global.RT_identifyReactedSites+"\t"+Global.RT_reactChemGraph+"\t"+Global.makeSpecies+"\t"+Global.checkReactionReverse+"\t"+Global.makeTR+ "\t" + Global.getReacFromStruc + "\t" + Global.generateReverse+"\n");
}
//5/6/08 gmagoon: in order to handle cases where no intermediate time/conversion steps are used, only evaluate the next block of code when there are intermediate time/conversion steps
double startTime = System.currentTimeMillis();
if(intermediateSteps){
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
reactionChangedList.set(i, false);
//reactionChanged = false;
Temperature currentT = (Temperature)currentTList.get(i);
Pressure currentP = (Pressure)currentPList.get(i);
lastTList.set(i,(Temperature)currentT.clone()) ;
lastPList.set(i,(Pressure)currentP.clone());
//lastT = (Temperature)currentT.clone();
//lastP = (Pressure)currentP.clone();
currentTList.set(i,rs.getTemperature((ReactionTime)beginList.get(i)));//10/24/07 gmagoon: ****I think this should actually be at end? (it shouldn't matter for isothermal/isobaric case)
currentPList.set(i,rs.getPressure((ReactionTime)beginList.get(i)));
conditionChangedList.set(i,!(((Temperature)currentTList.get(i)).equals((Temperature)lastTList.get(i))) || !(((Pressure)currentPList.get(i)).equals((Pressure)lastPList.get(i))));
//currentT = reactionSystem.getTemperature(begin);//10/24/07 gmagoon: ****I think this should actually be at end? (it shouldn't matter for isothermal/isobaric case)
//currentP = reactionSystem.getPressure(begin);
//conditionChanged = (!currentT.equals(lastT) || !currentP.equals(lastP));
beginList.set(i,((SystemSnapshot)(rs.getSystemSnapshotEnd().next())).time);
// begin=((SystemSnapshot)(reactionSystem.getSystemSnapshotEnd().next())).time;
if (rs.finishController.terminationTester instanceof ReactionTimeTT){
if (iterationNumber < timeStep.size()){
endList.set(i,(ReactionTime)timeStep.get(iterationNumber));
//end = (ReactionTime)timeStep.get(iterationNumber);
}
else
endList.set(i, ((ReactionTimeTT)rs.finishController.terminationTester).finalTime);
//end = ((ReactionTimeTT)reactionSystem.finishController.terminationTester).finalTime;
}
else
endList.set(i,new ReactionTime(1e6,"sec"));
//end = new ReactionTime(1e6,"sec");
}
iterationNumber++;
startTime = System.currentTimeMillis();//5/6/08 gmagoon: moved declaration outside of if statement so it can be accessed in subsequent vTester line; previous steps are probably so fast that I could eliminate this line without much effect on normal operation with intermediate steps
//double startTime = System.currentTimeMillis();
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean reactionChanged = (Boolean)reactionChangedList.get(i);
boolean conditionChanged = (Boolean)conditionChangedList.get(i);
ReactionTime begin = (ReactionTime)beginList.get(i);
ReactionTime end = (ReactionTime)endList.get(i);
endList.set(i,rs.solveReactionSystem(begin, end, false, reactionChanged, false, iterationNumber-1));
// end = reactionSystem.solveReactionSystem(begin, end, false, reactionChanged, false, iterationNumber-1);
}
solverMin = solverMin + (System.currentTimeMillis()-startTime)/1000/60;
startTime = System.currentTimeMillis();
//5/6/08 gmagoon: changed to separate validity and termination testing, and termination testing is done last...termination testing should be done even if there are no intermediate conversions; however, validity is guaranteed if there are no intermediate conversions based on previous conditional if statement
allValid = true;
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean valid = rs.isModelValid();
validList.set(i,valid);
if(!valid)
allValid = false;
}
}//5/6/08 gmagoon: end of block for intermediateSteps
allTerminated = true;
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean terminated = rs.isReactionTerminated();
terminatedList.set(i,terminated);
if(!terminated){
allTerminated = false;
System.out.println("Reaction System "+(i+1)+" has not reached its termination criterion");
if (rs.isModelValid()&& runKillableToPreventInfiniteLoop(intermediateSteps, iterationNumber)) {
System.out.println("although it seems to be valid (complete), so it was not interrupted for being invalid.");
System.out.println("This probably means there was an error with the ODE solver, and we risk entering an endless loop.");
System.out.println("Stopping.");
throw new Error();
}
}
}
// //10/24/07 gmagoon: changed to use reactionSystemList
// allTerminated = true;
// allValid = true;
// for (Integer i = 0; i<reactionSystemList.size();i++) {
// ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
// boolean terminated = rs.isReactionTerminated();
// terminatedList.set(i,terminated);
// if(!terminated)
// allTerminated = false;
// boolean valid = rs.isModelValid();
// validList.set(i,valid);
// if(!valid)
// allValid = false;
// }
// //terminated = reactionSystem.isReactionTerminated();
// //valid = reactionSystem.isModelValid();
//10/24/07 gmagoon: changed to use reactionSystemList, allValid
if (allValid) {
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
System.out.println("For reaction system: "+(i+1)+" out of "+reactionSystemList.size());
System.out.println("At this reaction time: " + ((ReactionTime)endList.get(i)).toString());
Species spe = SpeciesDictionary.getSpeciesFromID(1);
double conv = rs.getPresentConversion(spe);
System.out.print("Conversion of " + spe.getName() + " is:");
System.out.println(conv);
}
//System.out.println("At this time: " + end.toString());
//Species spe = SpeciesDictionary.getSpeciesFromID(1);
//double conv = reactionSystem.getPresentConversion(spe);
//System.out.print("current conversion = ");
//System.out.println(conv);
Runtime runTime = Runtime.getRuntime();
System.out.print("Memory used: ");
System.out.println(runTime.totalMemory());
System.out.print("Free memory: ");
System.out.println(runTime.freeMemory());
//runTime.gc();
/* if we're not calling runTime.gc() then don't bother printing this:
System.out.println("After garbage collection:");
System.out.print("Memory used: ");
System.out.println(runTime.totalMemory());
System.out.print("Free memory: ");
System.out.println(runTime.freeMemory());
*/
//10/24/07 gmagoon: note: all reaction systems should use the same core, but I will display for each reactionSystem for testing purposes:
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
System.out.println("For reaction system: "+(i+1)+" out of "+reactionSystemList.size());
if (rs.getDynamicSimulator() instanceof JDASPK){
JDASPK solver = (JDASPK)rs.getDynamicSimulator();
System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species.");
}
else{
JDASSL solver = (JDASSL)rs.getDynamicSimulator();
System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species.");
System.out.println("(although rs.getReactionModel().getReactionNumber() returns "+rs.getReactionModel().getReactionNumber()+")");
}
}
// if (reactionSystem.getDynamicSimulator() instanceof JDASPK){
// JDASPK solver = (JDASPK)reactionSystem.getDynamicSimulator();
// System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species.");
// }
// else{
// JDASSL solver = (JDASSL)reactionSystem.getDynamicSimulator();
// System.out.println("The model core has " + solver.getReactionSize() + " reactions and "+ ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size() + " species.");
// }
}
vTester = vTester + (System.currentTimeMillis()-startTime)/1000/60;//5/6/08 gmagoon: for case where intermediateSteps = false, this will use startTime declared just before intermediateSteps loop, and will only include termination testing, but no validity testing
}
//System.out.println("Performing model reduction");
if (paraInfor != 0){
System.out.println("Model Generation performed. Now generating sensitivity data.");
//10/24/07 gmagoon: updated to use reactionSystemList
LinkedList dynamicSimulator2List = new LinkedList();
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
//6/25/08 gmagoon: updated to pass index i
//6/25/08 gmagoon: updated to pass (dummy) finishController and autoflag (set to false here);
dynamicSimulator2List.add(new JDASPK(rtol, atol, paraInfor, (InitialStatus)initialStatusList.get(i),i));
//DynamicSimulator dynamicSimulator2 = new JDASPK(rtol, atol, paraInfor, initialStatus);
((DynamicSimulator)dynamicSimulator2List.get(i)).addConversion(((JDASPK)rs.dynamicSimulator).conversionSet, ((JDASPK)rs.dynamicSimulator).conversionSet.length);
//dynamicSimulator2.addConversion(((JDASPK)reactionSystem.dynamicSimulator).conversionSet, ((JDASPK)reactionSystem.dynamicSimulator).conversionSet.length);
rs.setDynamicSimulator((DynamicSimulator)dynamicSimulator2List.get(i));
//reactionSystem.setDynamicSimulator(dynamicSimulator2);
int numSteps = rs.systemSnapshot.size() -1;
rs.resetSystemSnapshot();
beginList.set(i, (ReactionTime)initList.get(i));
//begin = init;
if (rs.finishController.terminationTester instanceof ReactionTimeTT){
endList.set(i,((ReactionTimeTT)rs.finishController.terminationTester).finalTime);
//end = ((ReactionTimeTT)reactionSystem.finishController.terminationTester).finalTime;
}
else{
ReactionTime end = (ReactionTime)endList.get(i);
endList.set(i, end.add(end));
//end = end.add(end);
}
terminatedList.set(i, false);
//terminated = false;
ReactionTime begin = (ReactionTime)beginList.get(i);
ReactionTime end = (ReactionTime)endList.get(i);
rs.solveReactionSystemwithSEN(begin, end, true, false, false);
//reactionSystem.solveReactionSystemwithSEN(begin, end, true, false, false);
}
}
//10/24/07 gmagoon: updated to use reactionSystemList (***see previous comment regarding having one Chemkin input file)
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
Chemkin.writeChemkinInputFile(getReactionModel(),rs.getPresentStatus());//11/9/07 gmagoon: temporarily commenting out; see previous comment; this line may not cause a problem because it is different instance of writeChemkinInputFile, but I am commenting out just in case//11/12/07 gmagoon: restored; ****this appears to be source of non-Pdep bug
}
//9/1/09 gmagoon: if we are using QM, output a file with the CHEMKIN name, the RMG name, the (modified) InChI, and the (modified) InChIKey
if (ChemGraph.useQM){
writeInChIs(getReactionModel());
}
writeDictionary(getReactionModel());
System.out.println("Model Generation Completed");
return;
}
//9/1/09 gmagoon: this function writes a "dictionary" with Chemkin name, RMG name, (modified) InChI, and InChIKey
//this is based off of writeChemkinFile in ChemkinInputFile.java
private void writeInChIs(ReactionModel p_reactionModel) {
StringBuilder result=new StringBuilder();
for (Iterator iter = ((CoreEdgeReactionModel)p_reactionModel).core.getSpecies(); iter.hasNext(); ) {
Species species = (Species) iter.next();
result.append(species.getChemkinName() + "\t"+species.getName() + "\t" + species.getChemGraph().getModifiedInChIAnew() + "\t" + species.getChemGraph().getModifiedInChIKeyAnew()+ "\n");
}
String file = "inchiDictionary.txt";
try {
FileWriter fw = new FileWriter(file);
fw.write(result.toString());
fw.close();
}
catch (Exception e) {
System.out.println("Error in writing InChI file inchiDictionary.txt!");
System.out.println(e.getMessage());
System.exit(0);
}
}
//9/14/09 gmagoon: function to write dictionary, based on code copied from RMG.java
private void writeDictionary(ReactionModel rm){
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)rm;
//Write core species to RMG_Dictionary.txt
String coreSpecies ="";
Iterator iter = cerm.getSpecies();
if (Species.useInChI) {
while (iter.hasNext()){
int i=1;
Species spe = (Species) iter.next();
coreSpecies = coreSpecies + spe.getChemkinName() + " " + spe.getInChI() + "\n"+spe.getChemGraph().toString(i)+"\n\n";
}
} else {
while (iter.hasNext()){
int i=1;
Species spe = (Species) iter.next();
coreSpecies = coreSpecies + spe.getChemkinName() + "\n"+spe.getChemGraph().toString(i)+"\n\n";
}
}
try{
File rmgDictionary = new File("RMG_Dictionary.txt");
FileWriter fw = new FileWriter(rmgDictionary);
fw.write(coreSpecies);
fw.close();
}
catch (IOException e) {
System.out.println("Could not write RMG_Dictionary.txt");
System.exit(0);
}
// If we have solvation on, then every time we write the dictionary, also write the solvation properties
if (Species.useSolvation) {
writeSolvationProperties(rm);
}
}
private void writeSolvationProperties(ReactionModel rm){
//Write core species to RMG_Solvation_Properties.txt
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)rm;
StringBuilder result = new StringBuilder();
result.append("ChemkinName\tChemicalFormula\tMolecularWeight\tRadius\tDiffusivity\tAbrahamS\tAbrahamB\tAbrahamE\tAbrahamL\tAbrahamA\tChemkinName\n\n");
Iterator iter = cerm.getSpecies();
while (iter.hasNext()){
Species spe = (Species)iter.next();
result.append(spe.getChemkinName() + "\t");
result.append(spe.getChemGraph().getChemicalFormula()+ "\t");
result.append(spe.getMolecularWeight() + "\t");
result.append(spe.getChemGraph().getRadius()+ "\t");
result.append(spe.getChemGraph().getDiffusivity()+ "\t");
result.append(spe.getChemGraph().getAbramData().toString()+ "\t");
result.append(spe.getChemkinName() + "\n");
}
try{
File rmgSolvationProperties = new File("RMG_Solvation_Properties.txt");
FileWriter fw = new FileWriter(rmgSolvationProperties);
fw.write(result.toString() );
fw.close();
}
catch (IOException e) {
System.out.println("Could not write RMG_Solvation_Properties.txt");
System.exit(0);
}
}
private void parseRestartFiles() {
parseAllSpecies();
parseCoreSpecies();
parseEdgeSpecies();
parseAllReactions();
parseCoreReactions();
}
private void parseEdgeReactions() {
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
//HasMap speciesMap = dictionary.dictionary;
try{
File coreReactions = new File("Restart/edgeReactions.txt");
FileReader fr = new FileReader(coreReactions);
BufferedReader reader = new BufferedReader(fr);
String line = ChemParser.readMeaningfulLine(reader);
boolean found = false;
LinkedHashSet reactionSet = new LinkedHashSet();
while (line != null){
Reaction reaction = ChemParser.parseEdgeArrheniusReaction(dictionary,line,1,1);
boolean added = reactionSet.add(reaction);
if (!added){
if (reaction.hasResonanceIsomerAsReactant()){
//Structure reactionStructure = reaction.getStructure();
found = getResonanceStructure(reaction,"reactants", reactionSet);
}
if (reaction.hasResonanceIsomerAsProduct() && !found){
//Structure reactionStructure = reaction.getStructure();
found = getResonanceStructure(reaction,"products", reactionSet);
}
if (!found){
System.out.println("Cannot add reaction "+line+" to the Reaction Edge. All resonance isomers have already been added");
System.exit(0);
}
else found = false;
}
//Reaction reverse = reaction.getReverseReaction();
//if (reverse != null) reactionSet.add(reverse);
line = ChemParser.readMeaningfulLine(reader);
}
((CoreEdgeReactionModel)getReactionModel()).addReactionSet(reactionSet);
}
catch (IOException e){
System.out.println("Could not read the corespecies restart file");
System.exit(0);
}
}
public void parseCoreReactions() {
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
int i=1;
//HasMap speciesMap = dictionary.dictionary;
try{
File coreReactions = new File("Restart/coreReactions.txt");
FileReader fr = new FileReader(coreReactions);
BufferedReader reader = new BufferedReader(fr);
String line = ChemParser.readMeaningfulLine(reader);
boolean found = false;
LinkedHashSet reactionSet = new LinkedHashSet();
while (line != null){
Reaction reaction = ChemParser.parseCoreArrheniusReaction(dictionary,line,1,1);//,((CoreEdgeReactionModel)reactionSystem.reactionModel));
boolean added = reactionSet.add(reaction);
if (!added){
if (reaction.hasResonanceIsomerAsReactant()){
//Structure reactionStructure = reaction.getStructure();
found = getResonanceStructure(reaction,"reactants", reactionSet);
}
if (reaction.hasResonanceIsomerAsProduct() && !found){
//Structure reactionStructure = reaction.getStructure();
found = getResonanceStructure(reaction,"products", reactionSet);
}
if (!found){
System.out.println("Cannot add reaction "+line+" to the Reaction Core. All resonance isomers have already been added");
//System.exit(0);
}
else found = false;
}
Reaction reverse = reaction.getReverseReaction();
if (reverse != null) {
reactionSet.add(reverse);
//System.out.println(2 + "\t " + line);
}
//else System.out.println(1 + "\t" + line);
line = ChemParser.readMeaningfulLine(reader);
i=i+1;
}
((CoreEdgeReactionModel)getReactionModel()).addReactedReactionSet(reactionSet);
}
catch (IOException e){
System.out.println("Could not read the coreReactions restart file");
System.exit(0);
}
}
private void parseAllReactions() {
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
int i=1;
//HasMap speciesMap = dictionary.dictionary;
try{
File allReactions = new File("Restart/allReactions.txt");
FileReader fr = new FileReader(allReactions);
BufferedReader reader = new BufferedReader(fr);
String line = ChemParser.readMeaningfulLine(reader);
boolean found = false;
LinkedHashSet reactionSet = new LinkedHashSet();
OuterLoop:
while (line != null){
Reaction reaction = ChemParser.parseArrheniusReaction(dictionary,line,1,1,((CoreEdgeReactionModel)getReactionModel()));
if (((CoreEdgeReactionModel)getReactionModel()).categorizeReaction(reaction)==-1){
boolean added = reactionSet.add(reaction);
if (!added){
found = false;
if (reaction.hasResonanceIsomerAsReactant()){
//Structure reactionStructure = reaction.getStructure();
found = getResonanceStructure(reaction,"reactants", reactionSet);
}
if (reaction.hasResonanceIsomerAsProduct() && !found){
//Structure reactionStructure = reaction.getStructure();
found = getResonanceStructure(reaction,"products", reactionSet);
}
if (!found){
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction reacTemp = (Reaction)iter.next();
if (reacTemp.equals(reaction)){
reactionSet.remove(reacTemp);
reactionSet.add(reaction);
break;
}
}
//System.out.println("Cannot add reaction "+line+" to the Reaction Core. All resonance isomers have already been added");
//System.exit(0);
}
//else found = false;
}
}
/*Reaction reverse = reaction.getReverseReaction();
if (reverse != null && ((CoreEdgeReactionModel)reactionSystem.reactionModel).isReactedReaction(reaction)) {
reactionSet.add(reverse);
//System.out.println(2 + "\t " + line);
}*/
//else System.out.println(1 + "\t" + line);
i=i+1;
line = ChemParser.readMeaningfulLine(reader);
}
((CoreEdgeReactionModel)getReactionModel()).addReactionSet(reactionSet);
}
catch (IOException e){
System.out.println("Could not read the corespecies restart file");
System.exit(0);
}
}
private boolean getResonanceStructure(Reaction p_Reaction, String rOrP, LinkedHashSet reactionSet) {
Structure reactionStructure = p_Reaction.getStructure();
//Structure tempreactionStructure = new Structure(reactionStructure.getReactantList(),reactionStructure.getProductList());
boolean found = false;
if (rOrP.equals("reactants")){
Iterator originalreactants = reactionStructure.getReactants();
HashSet tempHashSet = new HashSet();
while(originalreactants.hasNext()){
tempHashSet.add(originalreactants.next());
}
Iterator reactants = tempHashSet.iterator();
while(reactants.hasNext() && !found){
ChemGraph reactant = (ChemGraph)reactants.next();
if (reactant.getSpecies().hasResonanceIsomers()){
Iterator chemGraphIterator = reactant.getSpecies().getResonanceIsomers();
ChemGraph newChemGraph ;//= (ChemGraph)chemGraphIterator.next();
while(chemGraphIterator.hasNext() && !found){
newChemGraph = (ChemGraph)chemGraphIterator.next();
reactionStructure.removeReactants(reactant);
reactionStructure.addReactants(newChemGraph);
reactant = newChemGraph;
if (reactionSet.add(p_Reaction)){
found = true;
}
}
}
}
}
else{
Iterator originalproducts = reactionStructure.getProducts();
HashSet tempHashSet = new HashSet();
while(originalproducts.hasNext()){
tempHashSet.add(originalproducts.next());
}
Iterator products = tempHashSet.iterator();
while(products.hasNext() && !found){
ChemGraph product = (ChemGraph)products.next();
if (product.getSpecies().hasResonanceIsomers()){
Iterator chemGraphIterator = product.getSpecies().getResonanceIsomers();
ChemGraph newChemGraph ;//= (ChemGraph)chemGraphIterator.next();
while(chemGraphIterator.hasNext() && !found){
newChemGraph = (ChemGraph)chemGraphIterator.next();
reactionStructure.removeProducts(product);
reactionStructure.addProducts(newChemGraph);
product = newChemGraph;
if (reactionSet.add(p_Reaction)){
found = true;
}
}
}
}
}
return found;
}
public void parseCoreSpecies() {
// String restartFileContent ="";
//int speciesCount = 0;
//boolean added;
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
try{
File coreSpecies = new File ("Restart/coreSpecies.txt");
FileReader fr = new FileReader(coreSpecies);
BufferedReader reader = new BufferedReader(fr);
String line = ChemParser.readMeaningfulLine(reader);
//HashSet speciesSet = new HashSet();
// if (reactionSystem == null){//10/24/07 gmagoon: commenting out since contents of if was already commented out anyway
// //ReactionSystem reactionSystem = new ReactionSystem();
// }
setReactionModel(new CoreEdgeReactionModel());//10/4/07 gmagoon:changed to setReactionModel
while (line!=null) {
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
int ID = Integer.parseInt(index);
Species spe = dictionary.getSpeciesFromID(ID);
if (spe == null)
System.out.println("There was no species with ID "+ID +" in the species dictionary");
((CoreEdgeReactionModel)getReactionModel()).addReactedSpecies(spe);
line = ChemParser.readMeaningfulLine(reader);
}
}
catch (IOException e){
System.out.println("Could not read the corespecies restart file");
System.exit(0);
}
}
public static void garbageCollect(){
System.gc();
}
public static long memoryUsed(){
garbageCollect();
Runtime rT = Runtime.getRuntime();
long uM, tM, fM;
tM = rT.totalMemory();
fM = rT.freeMemory();
uM = tM - fM;
System.out.println("After garbage collection:");
System.out.print("Memory used: ");
System.out.println(tM);
System.out.print("Free memory: ");
System.out.println(fM);
return uM;
}
private HashSet readIncludeSpecies(String fileName) {
HashSet speciesSet = new HashSet();
try {
File includeSpecies = new File (fileName);
FileReader fr = new FileReader(includeSpecies);
BufferedReader reader = new BufferedReader(fr);
String line = ChemParser.readMeaningfulLine(reader);
while (line!=null) {
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String name = null;
if (!index.startsWith("(")) name = index;
else name = st.nextToken().trim();
Graph g = ChemParser.readChemGraph(reader);
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
}
catch (ForbiddenStructureException e) {
System.out.println("Forbidden Structure:\n" + e.getMessage());
System.out.println("Included species file "+fileName+" contains a forbidden structure.");
System.exit(0);
}
Species species = Species.make(name,cg);
//speciesSet.put(name, species);
speciesSet.add(species);
line = ChemParser.readMeaningfulLine(reader);
System.out.println(line);
}
}
catch (IOException e){
System.out.println("Could not read the included species file" + fileName);
System.exit(0);
}
return speciesSet;
}
public LinkedHashSet parseAllSpecies() {
// String restartFileContent ="";
int speciesCount = 0;
LinkedHashSet speciesSet = new LinkedHashSet();
boolean added;
try{
long initialTime = System.currentTimeMillis();
File allSpecies = new File ("allSpecies.txt");
BufferedReader reader = new BufferedReader(new FileReader(allSpecies));
String line = ChemParser.readMeaningfulLine(reader);
int i=0;
while (line!=null) {
i++;
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String name = null;
if (!index.startsWith("(")) name = index;
else name = st.nextToken().trim();
int ID = getID(name);
name = getName(name);
Graph g = ChemParser.readChemGraph(reader);
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
}
catch (ForbiddenStructureException e) {
System.out.println("Forbidden Structure:\n" + e.getMessage());
System.out.println("The allSpecies.txt restart file contains a forbidden structure.");
System.exit(0);
}
Species species;
if (ID == 0)
species = Species.make(name,cg);
else
species = Species.make(name,cg,ID);
speciesSet.add(species);
double flux = 0;
int species_type = 1;
line = ChemParser.readMeaningfulLine(reader);
System.out.println(line);
}
}
catch (IOException e){
System.out.println("Could not read the allSpecies restart file.");
System.exit(0);
}
return speciesSet;
}
private String getName(String name) {
//int id;
String number = "";
int index=0;
if (!name.endsWith(")")) return name;
else {
char [] nameChars = name.toCharArray();
String temp = String.copyValueOf(nameChars);
int i=name.length()-2;
//char test = "(";
while (i>0){
if (name.charAt(i)== '(') {
index=i;
i=0;
}
else i = i-1;
}
}
number = name.substring(0,index);
return number;
}
private int getID(String name) {
int id;
String number = "";
if (!name.endsWith(")")) return 0;
else {
char [] nameChars = name.toCharArray();
int i=name.length()-2;
//char test = "(";
while (i>0){
if (name.charAt(i)== '(') i=0;
else{
number = name.charAt(i)+number;
i = i-1;
}
}
}
id = Integer.parseInt(number);
return id;
}
private void parseEdgeSpecies() {
// String restartFileContent ="";
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
try{
File edgeSpecies = new File ("Restart/edgeSpecies.txt");
FileReader fr = new FileReader(edgeSpecies);
BufferedReader reader = new BufferedReader(fr);
String line = ChemParser.readMeaningfulLine(reader);
//HashSet speciesSet = new HashSet();
while (line!=null) {
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
int ID = Integer.parseInt(index);
Species spe = dictionary.getSpeciesFromID(ID);
if (spe == null)
System.out.println("There was no species with ID "+ID +" in the species dictionary");
//reactionSystem.reactionModel = new CoreEdgeReactionModel();
((CoreEdgeReactionModel)getReactionModel()).addUnreactedSpecies(spe);
line = ChemParser.readMeaningfulLine(reader);
}
}
catch (IOException e){
System.out.println("Could not read the edgepecies restart file");
System.exit(0);
}
}
/*private int calculateAllReactionsinReactionTemplate() {
int totalnum = 0;
TemplateReactionGenerator trg = (TemplateReactionGenerator)reactionSystem.reactionGenerator;
Iterator iter = trg.getReactionTemplateLibrary().getReactionTemplate();
while (iter.hasNext()){
ReactionTemplate rt = (ReactionTemplate)iter.next();
totalnum += rt.getNumberOfReactions();
}
return totalnum;
}*/
private void writeEnlargerInfo() {
try {
File diagnosis = new File("enlarger.xls");
FileWriter fw = new FileWriter(diagnosis);
fw.write(Global.enlargerInfo.toString());
fw.close();
}
catch (IOException e) {
System.out.println("Cannot write enlarger file");
System.exit(0);
}
}
private void writeDiagnosticInfo() {
try {
File diagnosis = new File("diagnosis.xls");
FileWriter fw = new FileWriter(diagnosis);
fw.write(Global.diagnosticInfo.toString());
fw.close();
}
catch (IOException e) {
System.out.println("Cannot write diagnosis file");
System.exit(0);
}
}
//10/25/07 gmagoon: I don't think this is used, but I will update to use reactionSystem and reactionTime as parameter to access temperature; commented-out usage of writeRestartFile will need to be modified
//Is still incomplete.
public void writeRestartFile(ReactionSystem p_rs, ReactionTime p_time ) {
//writeCoreSpecies(p_rs);
//writeCoreReactions(p_rs, p_time);
//writeEdgeSpecies();
//writeAllReactions(p_rs, p_time);
//writeEdgeReactions(p_rs, p_time);
//String restartFileName;
//String restartFileContent="";
/*File restartFile;
try {
restartFileName="Restart.txt";
restartFile = new File(restartFileName);
FileWriter fw = new FileWriter(restartFile);
restartFileContent = restartFileContent+ "TemperatureModel: Constant " + reactionSystem.temperatureModel.getTemperature(reactionSystem.getInitialReactionTime()).getStandard()+ " (K)\n";
restartFileContent = restartFileContent+ "PressureModel: Constant " + reactionSystem.pressureModel.getPressure(reactionSystem.getInitialReactionTime()).getAtm() + " (atm)\n\n";
restartFileContent = restartFileContent+ "InitialStatus: \n";
int speciesCount = 1;
for(Iterator iter=reactionSystem.reactionModel.getSpecies();iter.hasNext();){
Species species = (Species) iter.next();
restartFileContent = restartFileContent + "("+ speciesCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
restartFileContent = restartFileContent + species.toStringWithoutH(1) + "\n";
speciesCount = speciesCount + 1;
}
restartFileContent = restartFileContent + "\n\n END \n\nInertGas:\n";
for (Iterator iter=reactionSystem.getPresentStatus().getInertGas(); iter.hasNext();){
String inertName= (String) iter.next();
restartFileContent = restartFileContent + inertName + " " + reactionSystem.getPresentStatus().getInertGas(inertName) + " mol/cm3 \n";
}
restartFileContent = restartFileContent + "END\n";
double tolerance;
if (reactionSystem.reactionModelEnlarger instanceof RateBasedPDepRME){
restartFileContent = restartFileContent + "ReactionModelEnlarger: RateBasedPDepModelEnlarger\n";
restartFileContent = restartFileContent + "FinishController: RateBasedPDepFinishController\n";
}
else {
restartFileContent = restartFileContent + "ReactionModelEnlarger: RateBasedModelEnlarger\n";
restartFileContent = restartFileContent + "FinishController: RateBasedFinishController\n";
}
if (reactionSystem.finishController.terminationTester instanceof ConversionTT){
restartFileContent = restartFileContent + "(1) Goal Conversion: ";
for (Iterator iter = ((ConversionTT)reactionSystem.finishController.terminationTester).getSpeciesGoalConversionSet();iter.hasNext();){
SpeciesConversion sc = (SpeciesConversion) iter.next();
restartFileContent = restartFileContent + sc.getSpecies().getName()+" "+sc.conversion + "\n";
}
}
else {
restartFileContent = restartFileContent + "(1) Goal ReactionTime: "+((ReactionTimeTT)reactionSystem.finishController.terminationTester).finalTime.toString();
}
restartFileContent = restartFileContent + "Error Tolerance: " +((RateBasedVT) reactionSystem.finishController.validityTester).tolerance + "\n";
fw.write(restartFileContent);
fw.close();
}
catch (IOException e) {
System.out.println("Could not write the restart file");
System.exit(0);
}*/
}
/*Only write the forward reactions in the model core.
The reverse reactions are generated from the forward reactions.*/
//10/25/07 gmagoon: added reaction system and reaction time as parameters and eliminated use of Global.temperature
private void writeEdgeReactions(ReactionSystem p_rs, ReactionTime p_time) {
StringBuilder restartFileContent =new StringBuilder();
int reactionCount = 1;
try{
File coreSpecies = new File ("Restart/edgeReactions.txt");
FileWriter fw = new FileWriter(coreSpecies);
for(Iterator iter=((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().iterator();iter.hasNext();){
Reaction reaction = (Reaction) iter.next();
//if (reaction.getDirection()==1){
//restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n");
reactionCount = reactionCount + 1;
//}
}
//restartFileContent += "\nEND";
fw.write(restartFileContent.toString());
fw.close();
}
catch (IOException e){
System.out.println("Could not write the restart edgereactions file");
System.exit(0);
}
}
//10/25/07 gmagoon: added reaction system and reaction time as parameters and eliminated use of Global.temperature
private void writeAllReactions(ReactionSystem p_rs, ReactionTime p_time) {
StringBuilder restartFileContent = new StringBuilder();
int reactionCount = 1;
try{
File allReactions = new File ("Restart/allReactions.txt");
FileWriter fw = new FileWriter(allReactions);
for(Iterator iter=getReactionModel().getReaction();iter.hasNext();){
Reaction reaction = (Reaction) iter.next();
//restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n");
}
for(Iterator iter=((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().iterator();iter.hasNext();){
Reaction reaction = (Reaction) iter.next();
//if (reaction.getDirection()==1){
//restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n");
}
//restartFileContent += "\nEND";
fw.write(restartFileContent.toString());
fw.close();
}
catch (IOException e){
System.out.println("Could not write the restart edgereactions file");
System.exit(0);
}
}
private void writeEdgeSpecies() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Restart/edgeSpecies.txt"));
for(Iterator iter=((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().iterator();iter.hasNext();){
Species species = (Species) iter.next();
bw.write(species.getChemkinName());
bw.newLine();
int dummyInt = 0;
bw.write(species.getChemGraph().toString(dummyInt));
bw.newLine();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
//10/25/07 gmagoon: added reaction system and reaction time as parameters and eliminated use of Global.temperature
private void writeCoreReactions(ReactionSystem p_rs, ReactionTime p_time) {
StringBuilder restartFileContent = new StringBuilder();
int reactionCount = 0;
try{
File coreSpecies = new File ("Restart/coreReactions.txt");
FileWriter fw = new FileWriter(coreSpecies);
for(Iterator iter=getReactionModel().getReaction();iter.hasNext();){
Reaction reaction = (Reaction) iter.next();
if (reaction.getDirection()==1){
//restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n");
reactionCount = reactionCount + 1;
}
}
//restartFileContent += "\nEND";
fw.write(restartFileContent.toString());
fw.close();
}
catch (IOException e){
System.out.println("Could not write the restart corereactions file");
System.exit(0);
}
}
private void writeCoreSpecies() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Restart/coreSpecies.txt"));
for(Iterator iter=getReactionModel().getSpecies();iter.hasNext();){
Species species = (Species) iter.next();
bw.write(species.getChemkinName());
bw.newLine();
int dummyInt = 0;
bw.write(species.getChemGraph().toString(dummyInt));
bw.newLine();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private void writeCoreReactions() {
BufferedWriter bw_rxns = null;
BufferedWriter bw_troe = null;
BufferedWriter bw_lindemann = null;
BufferedWriter bw_thirdbody = null;
try {
bw_rxns = new BufferedWriter(new FileWriter("Restart/coreReactions.txt"));
bw_troe = new BufferedWriter(new FileWriter("Restart/troeReactions.txt"));
bw_lindemann = new BufferedWriter(new FileWriter("Restart/lindemannReactions.txt"));
bw_thirdbody = new BufferedWriter(new FileWriter("Restart/thirdBodyReactions.txt"));
String EaUnits = ArrheniusKinetics.getEaUnits();
String AUnits = ArrheniusKinetics.getAUnits();
bw_rxns.write("UnitsOfEa: " + EaUnits);
bw_rxns.newLine();
bw_troe.write("Unit:\nA: mol/cm3/s\nE: " + EaUnits + "\n\nReactions:");
bw_troe.newLine();
bw_lindemann.write("Unit:\nA: mol/cm3/s\nE: " + EaUnits + "\n\nReactions:");
bw_lindemann.newLine();
bw_thirdbody.write("Unit:\nA: mol/cm3/s\nE: " + EaUnits + "\n\nReactions :");
bw_thirdbody.newLine();
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)getReactionModel();
LinkedHashSet allcoreRxns = cerm.core.reaction;
for(Iterator iter=allcoreRxns.iterator(); iter.hasNext();){
Reaction reaction = (Reaction) iter.next();
if (reaction.isForward()) {
if (reaction instanceof TROEReaction) {
TROEReaction troeRxn = (TROEReaction) reaction;
bw_troe.write(troeRxn.toRestartString(new Temperature(298,"K")));
bw_troe.newLine();
}
else if (reaction instanceof LindemannReaction) {
LindemannReaction lindeRxn = (LindemannReaction) reaction;
bw_lindemann.write(lindeRxn.toRestartString(new Temperature(298,"K")));
bw_lindemann.newLine();
}
else if (reaction instanceof ThirdBodyReaction) {
ThirdBodyReaction tbRxn = (ThirdBodyReaction) reaction;
bw_thirdbody.write(tbRxn.toRestartString(new Temperature(298,"K")));
bw_thirdbody.newLine();
}
else {
//bw.write(reaction.toChemkinString(new Temperature(298,"K")));
bw_rxns.write(reaction.toRestartString(new Temperature(298,"K")));
bw_rxns.newLine();
}
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw_rxns != null) {
bw_rxns.flush();
bw_rxns.close();
}
if (bw_troe != null) {
bw_troe.flush();
bw_troe.close();
}
if (bw_lindemann != null) {
bw_lindemann.flush();
bw_lindemann.close();
}
if (bw_thirdbody != null) {
bw_thirdbody.flush();
bw_thirdbody.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private void writeEdgeReactions() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Restart/edgeReactions.txt"));
String EaUnits = ArrheniusKinetics.getEaUnits();
bw.write("UnitsOfEa: " + EaUnits);
bw.newLine();
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)getReactionModel();
LinkedHashSet alledgeRxns = cerm.edge.reaction;
for(Iterator iter=alledgeRxns.iterator(); iter.hasNext();){
Reaction reaction = (Reaction) iter.next();
if (reaction.isForward()) {
//bw.write(reaction.toChemkinString(new Temperature(298,"K")));
bw.write(reaction.toRestartString(new Temperature(298,"K")));
bw.newLine();
} else if (reaction.getReverseReaction().isForward()) {
//bw.write(reaction.getReverseReaction().toChemkinString(new Temperature(298,"K")));
bw.write(reaction.getReverseReaction().toRestartString(new Temperature(298,"K")));
bw.newLine();
} else
System.out.println("Could not determine forward direction for following rxn: " + reaction.toString());
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private void writePDepNetworks() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Restart/pdepnetworks.txt"));
int numFameTemps = PDepRateConstant.getTemperatures().length;
int numFamePress = PDepRateConstant.getPressures().length;
int numChebyTemps = ChebyshevPolynomials.getNT();
int numChebyPress = ChebyshevPolynomials.getNP();
int numPlog = PDepArrheniusKinetics.getNumPressures();
String EaUnits = ArrheniusKinetics.getEaUnits();
bw.write("UnitsOfEa: " + EaUnits);
bw.newLine();
bw.write("NumberOfFameTemps: " + numFameTemps);
bw.newLine();
bw.write("NumberOfFamePress: " + numFamePress);
bw.newLine();
bw.write("NumberOfChebyTemps: " + numChebyTemps);
bw.newLine();
bw.write("NumberOfChebyPress: " + numChebyPress);
bw.newLine();
bw.write("NumberOfPLogs: " + numPlog);
bw.newLine();
bw.newLine();
LinkedList allNets = PDepNetwork.getNetworks();
int netCounter = 0;
for(Iterator iter=allNets.iterator(); iter.hasNext();){
PDepNetwork pdepnet = (PDepNetwork) iter.next();
++netCounter;
bw.write("PDepNetwork #" + netCounter);
bw.newLine();
// Write netReactionList
LinkedList netRxns = pdepnet.getNetReactions();
bw.write("netReactionList:");
bw.newLine();
for (Iterator iter2=netRxns.iterator(); iter2.hasNext();) {
PDepReaction currentPDepRxn = (PDepReaction)iter2.next();
bw.write(currentPDepRxn.toString());
bw.newLine();
bw.write(writeRatesAndParameters(currentPDepRxn,numFameTemps,
numFamePress,numChebyTemps,numChebyPress,numPlog));
PDepReaction currentPDepReverseRxn = currentPDepRxn.getReverseReaction();
bw.write(currentPDepReverseRxn.toString());
bw.newLine();
bw.write(writeRatesAndParameters(currentPDepReverseRxn,numFameTemps,
numFamePress,numChebyTemps,numChebyPress,numPlog));
}
// Write nonincludedReactionList
LinkedList nonIncludeRxns = pdepnet.getNonincludedReactions();
bw.write("nonIncludedReactionList:");
bw.newLine();
for (Iterator iter2=nonIncludeRxns.iterator(); iter2.hasNext();) {
PDepReaction currentPDepRxn = (PDepReaction)iter2.next();
bw.write(currentPDepRxn.toString());
bw.newLine();
bw.write(writeRatesAndParameters(currentPDepRxn,numFameTemps,
numFamePress,numChebyTemps,numChebyPress,numPlog));
PDepReaction currentPDepReverseRxn = currentPDepRxn.getReverseReaction();
bw.write(currentPDepReverseRxn.toString());
bw.newLine();
bw.write(writeRatesAndParameters(currentPDepReverseRxn,numFameTemps,
numFamePress,numChebyTemps,numChebyPress,numPlog));
}
// Write pathReactionList
LinkedList pathRxns = pdepnet.getPathReactions();
bw.write("pathReactionList:");
bw.newLine();
for (Iterator iter2=pathRxns.iterator(); iter2.hasNext();) {
PDepReaction currentPDepRxn = (PDepReaction)iter2.next();
bw.write(currentPDepRxn.getDirection() + "\t" + currentPDepRxn.toChemkinString(new Temperature(298,"K")));
bw.newLine();
}
bw.newLine();
bw.newLine();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public String writeRatesAndParameters(PDepReaction pdeprxn, int numFameTemps,
int numFamePress, int numChebyTemps, int numChebyPress, int numPlog) {
StringBuilder sb = new StringBuilder();
// Write the rate coefficients
double[][] rateConstants = pdeprxn.getPDepRate().getRateConstants();
for (int i=0; i<numFameTemps; i++) {
for (int j=0; j<numFamePress; j++) {
sb.append(rateConstants[i][j] + "\t");
}
sb.append("\n");
}
sb.append("\n");
// If chebyshev polynomials are present, write them
if (numChebyTemps != 0) {
ChebyshevPolynomials chebyPolys = pdeprxn.getPDepRate().getChebyshev();
for (int i=0; i<numChebyTemps; i++) {
for (int j=0; j<numChebyPress; j++) {
sb.append(chebyPolys.getAlpha(i,j) + "\t");
}
sb.append("\n");
}
sb.append("\n");
}
// If plog parameters are present, write them
else if (numPlog != 0) {
PDepArrheniusKinetics kinetics = pdeprxn.getPDepRate().getPDepArrheniusKinetics();
for (int i=0; i<numPlog; i++) {
double Hrxn = pdeprxn.calculateHrxn(new Temperature(298,"K"));
sb.append(kinetics.pressures[i].getPa() + "\t" + kinetics.getKinetics(i).toChemkinString(Hrxn,new Temperature(298,"K"),false) + "\n");
}
sb.append("\n");
}
return sb.toString();
}
public LinkedList getTimeStep() {
return timeStep;
}
public void setTimeStep(ReactionTime p_timeStep) {
if (timeStep == null)
timeStep = new LinkedList();
timeStep.add(p_timeStep);
}
public String getWorkingDirectory() {
return workingDirectory;
}
public void setWorkingDirectory(String p_workingDirectory) {
workingDirectory = p_workingDirectory;
}
//svp
public boolean getError(){
return error;
}
//svp
public boolean getSensitivity(){
return sensitivity;
}
public LinkedList getSpeciesList() {
return species;
}
//gmagoon 10/24/07: commented out getReactionSystem and setReactionSystem
// public ReactionSystem getReactionSystem() {
// return reactionSystem;
// }
//11/2/07 gmagoon: adding accessor method for reactionSystemList
public LinkedList getReactionSystemList(){
return reactionSystemList;
}
//added by gmagoon 9/24/07
// public void setReactionSystem(ReactionSystem p_ReactionSystem) {
// reactionSystem = p_ReactionSystem;
// }
//copied from ReactionSystem.java by gmagoon 9/24/07
public ReactionModel getReactionModel() {
return reactionModel;
}
public void readRestartSpecies() {
System.out.println("Reading in species from Restart folder");
// Read in core species -- NOTE code is almost duplicated in Read in edge species (second part of procedure)
try {
FileReader in = new FileReader("Restart/coreSpecies.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader);
while (line != null) {
// The first line of a new species is the user-defined name
String totalSpeciesName = line;
String[] splitString1 = totalSpeciesName.split("[(]");
String[] splitString2 = splitString1[splitString1.length-1].split("[)]");
// The remaining lines are the graph
Graph g = ChemParser.readChemGraph(reader);
// Make the ChemGraph, assuming it does not contain a forbidden structure
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
} catch (ForbiddenStructureException e) {
System.out.println("Error reading graph: Graph contains a forbidden structure.\n" + g.toString());
System.exit(0);
}
// Make the species
int intLocation = totalSpeciesName.indexOf("(" + splitString2[0] + ")");
Species species = Species.make(totalSpeciesName.substring(0,intLocation),cg,Integer.parseInt(splitString2[0]));
// Add the new species to the set of species
restartCoreSpcs.add(species);
/*int species_type = 1; // reacted species
for (int i=0; i<numRxnSystems; i++) {
SpeciesStatus ss = new SpeciesStatus(species,species_type,y[i],yprime[i]);
speciesStatus[i].put(species, ss);
}*/
line = ChemParser.readMeaningfulLine(reader);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Read in edge species
try {
FileReader in = new FileReader("Restart/edgeSpecies.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader);
while (line != null) {
// The first line of a new species is the user-defined name
String totalSpeciesName = line;
String[] splitString1 = totalSpeciesName.split("[(]");
String[] splitString2 = splitString1[splitString1.length-1].split("[)]"); // Change JDM to reflect MRH 2-11-2010
// The remaining lines are the graph
Graph g = ChemParser.readChemGraph(reader);
// Make the ChemGraph, assuming it does not contain a forbidden structure
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
} catch (ForbiddenStructureException e) {
System.out.println("Error reading graph: Graph contains a forbidden structure.\n" + g.toString());
System.exit(0);
}
// Make the species
Species species = Species.make(splitString1[0],cg,Integer.parseInt(splitString2[0]));
// Add the new species to the set of species
restartEdgeSpcs.add(species);
line = ChemParser.readMeaningfulLine(reader);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void readRestartReactions() {
// Grab the IDs from the core species
int[] coreSpcsIds = new int[restartCoreSpcs.size()];
int i = 0;
for (Iterator iter = restartCoreSpcs.iterator(); iter.hasNext();) {
Species spcs = (Species)iter.next();
coreSpcsIds[i] = spcs.getID();
++i;
}
// Read in core reactions
try {
FileReader in = new FileReader("Restart/coreReactions.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader);
// Determine units of Ea
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken();
String EaUnits = st.nextToken();
line = ChemParser.readMeaningfulLine(reader);
while (line != null) {
if (!line.trim().equals("DUP")) {
Reaction r = ChemParser.parseRestartReaction(line,coreSpcsIds,"core",EaUnits);
Iterator rxnIter = restartCoreRxns.iterator();
boolean foundRxn = false;
while (rxnIter.hasNext()) {
Reaction old = (Reaction)rxnIter.next();
if (old.equals(r)) {
old.addAdditionalKinetics(r.getKinetics(),1);
foundRxn = true;
break;
}
}
if (!foundRxn) {
if (r.hasReverseReaction()) r.generateReverseReaction();
restartCoreRxns.add(r);
}
}
line = ChemParser.readMeaningfulLine(reader);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
SeedMechanism.readThirdBodyReactions("Restart/thirdBodyReactions.txt");
} catch (IOException e1) {
e1.printStackTrace();
}
try {
SeedMechanism.readLindemannReactions("Restart/lindemannReactions.txt");
} catch (IOException e1) {
e1.printStackTrace();
}
try {
SeedMechanism.readTroeReactions("Restart/troeReactions.txt");
} catch (IOException e1) {
e1.printStackTrace();
}
restartCoreRxns.addAll(SeedMechanism.reactionSet);
// Read in edge reactions
try {
FileReader in = new FileReader("Restart/edgeReactions.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader);
// Determine units of Ea
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken();
String EaUnits = st.nextToken();
line = ChemParser.readMeaningfulLine(reader);
while (line != null) {
if (!line.trim().equals("DUP")) {
Reaction r = ChemParser.parseRestartReaction(line,coreSpcsIds,"edge",EaUnits);
Iterator rxnIter = restartEdgeRxns.iterator();
boolean foundRxn = false;
while (rxnIter.hasNext()) {
Reaction old = (Reaction)rxnIter.next();
if (old.equals(r)) {
old.addAdditionalKinetics(r.getKinetics(),1);
foundRxn = true;
break;
}
}
if (!foundRxn) {
r.generateReverseReaction();
restartEdgeRxns.add(r);
}
}
line = ChemParser.readMeaningfulLine(reader);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public LinkedHashMap getRestartSpeciesStatus(int i) {
LinkedHashMap speciesStatus = new LinkedHashMap();
try {
FileReader in = new FileReader("Restart/coreSpecies.txt");
BufferedReader reader = new BufferedReader(in);
Integer numRxnSystems = Integer.parseInt(ChemParser.readMeaningfulLine(reader));
String line = ChemParser.readMeaningfulLine(reader);
while (line != null) {
// The first line of a new species is the user-defined name
String totalSpeciesName = line;
String[] splitString1 = totalSpeciesName.split("[(]");
String[] splitString2 = splitString1[1].split("[)]");
double y = 0.0;
double yprime = 0.0;
for (int j=0; j<numRxnSystems; j++) {
StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
if (j == i) {
y = Double.parseDouble(st.nextToken());
yprime = Double.parseDouble(st.nextToken());
}
}
// The remaining lines are the graph
Graph g = ChemParser.readChemGraph(reader);
// Make the ChemGraph, assuming it does not contain a forbidden structure
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
} catch (ForbiddenStructureException e) {
System.out.println("Error reading graph: Graph contains a forbidden structure.\n" + g.toString());
System.exit(0);
}
// Make the species
Species species = Species.make(splitString1[0],cg);
// Add the new species to the set of species
//restartCoreSpcs.add(species);
int species_type = 1; // reacted species
SpeciesStatus ss = new SpeciesStatus(species,species_type,y,yprime);
speciesStatus.put(species, ss);
line = ChemParser.readMeaningfulLine(reader);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return speciesStatus;
}
public void putRestartSpeciesInInitialStatus(InitialStatus is, int i) {
try {
FileReader in = new FileReader("Restart/coreSpecies.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader);
while (line != null) {
// The first line of a new species is the user-defined name
String totalSpeciesName = line;
String[] splitString1 = totalSpeciesName.split("[(]");
String[] splitString2 = splitString1[1].split("[)]");
// The remaining lines are the graph
Graph g = ChemParser.readChemGraph(reader);
// Make the ChemGraph, assuming it does not contain a forbidden structure
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
} catch (ForbiddenStructureException e) {
System.out.println("Error reading graph: Graph contains a forbidden structure.\n" + g.toString());
System.exit(0);
}
// Make the species
Species species = Species.make(splitString1[0],cg);
// Add the new species to the set of species
//restartCoreSpcs.add(species);
if (is.getSpeciesStatus(species) == null) {
SpeciesStatus ss = new SpeciesStatus(species,1,0.0,0.0);
is.putSpeciesStatus(ss);
}
line = ChemParser.readMeaningfulLine(reader);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void readPDepNetworks() {
SpeciesDictionary sd = SpeciesDictionary.getInstance();
LinkedList allNetworks = PDepNetwork.getNetworks();
try {
FileReader in = new FileReader("Restart/pdepnetworks.txt");
BufferedReader reader = new BufferedReader(in);
StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
String tempString = st.nextToken();
String EaUnits = st.nextToken();
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
tempString = st.nextToken();
int numFameTs = Integer.parseInt(st.nextToken());
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
tempString = st.nextToken();
int numFamePs = Integer.parseInt(st.nextToken());
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
tempString = st.nextToken();
int numChebyTs = Integer.parseInt(st.nextToken());
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
tempString = st.nextToken();
int numChebyPs = Integer.parseInt(st.nextToken());
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
tempString = st.nextToken();
int numPlogs = Integer.parseInt(st.nextToken());
double[][] rateCoefficients = new double[numFameTs][numFamePs];
double[][] chebyPolys = new double[numChebyTs][numChebyPs];
Kinetics[] plogKinetics = new Kinetics[numPlogs];
String line = ChemParser.readMeaningfulLine(reader); // line should be "PDepNetwork #"
while (line != null) {
line = ChemParser.readMeaningfulLine(reader); // line should now be "netReactionList:"
PDepNetwork newNetwork = new PDepNetwork();
LinkedList netRxns = newNetwork.getNetReactions();
LinkedList nonincludeRxns = newNetwork.getNonincludedReactions();
line = ChemParser.readMeaningfulLine(reader); // line is either data or "nonIncludedReactionList"
// If line is "nonincludedreactionlist", we need to skip over this while loop
if (!line.toLowerCase().startsWith("nonincludedreactionlist")) {
while (!line.toLowerCase().startsWith("nonincludedreactionlist")) {
// Read in the forward rxn
String[] reactsANDprods = line.split("\\-->");
PDepIsomer Reactants = null;
String reacts = reactsANDprods[0].trim();
if (reacts.contains("+")) {
String[] indivReacts = reacts.split("[+]");
String name = indivReacts[0].trim();
Species spc1 = sd.getSpeciesFromChemkinName(name);
if (spc1 == null) {
spc1 = getSpeciesBySPCName(name,sd);
}
name = indivReacts[1].trim();
Species spc2 = sd.getSpeciesFromChemkinName(name);
if (spc2 == null) {
spc2 = getSpeciesBySPCName(name,sd);
}
Reactants = new PDepIsomer(spc1,spc2);
} else {
String name = reacts.trim();
Species spc = sd.getSpeciesFromChemkinName(name);
if (spc == null) {
spc = getSpeciesBySPCName(name,sd);
}
Reactants = new PDepIsomer(spc);
}
PDepIsomer Products = null;
String prods = reactsANDprods[1].trim();
if (prods.contains("+")) {
String[] indivProds = prods.split("[+]");
String name = indivProds[0].trim();
Species spc1 = sd.getSpeciesFromChemkinName(name);
if (spc1 == null) {
spc1 = getSpeciesBySPCName(name,sd);
}
name = indivProds[1].trim();
Species spc2 = sd.getSpeciesFromChemkinName(name);
if (spc2 == null) {
spc2 = getSpeciesBySPCName(name,sd);
}
Products = new PDepIsomer(spc1,spc2);
} else {
String name = prods.trim();
Species spc = sd.getSpeciesFromChemkinName(name);
if (spc == null) {
spc = getSpeciesBySPCName(name,sd);
}
Products = new PDepIsomer(spc);
}
newNetwork.addIsomer(Reactants);
newNetwork.addIsomer(Products);
for (int i=0; i<numFameTs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
for (int j=0; j<numFamePs; j++) {
rateCoefficients[i][j] = Double.parseDouble(st.nextToken());
}
}
PDepRateConstant pdepk = null;
if (numChebyTs > 0) {
for (int i=0; i<numChebyTs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
for (int j=0; j<numChebyPs; j++) {
chebyPolys[i][j] = Double.parseDouble(st.nextToken());
}
}
ChebyshevPolynomials chebyshev = new ChebyshevPolynomials(numChebyTs,
ChebyshevPolynomials.getTlow(), ChebyshevPolynomials.getTup(),
numChebyPs, ChebyshevPolynomials.getPlow(), ChebyshevPolynomials.getPup(),
chebyPolys);
pdepk = new PDepRateConstant(rateCoefficients,chebyshev);
} else if (numPlogs > 0) {
for (int i=0; i<numPlogs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
Pressure p = new Pressure(Double.parseDouble(st.nextToken()),"Pa");
UncertainDouble dA = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
UncertainDouble dn = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
double Ea = Double.parseDouble(st.nextToken());
if (EaUnits.equals("cal/mol"))
Ea = Ea / 1000;
else if (EaUnits.equals("J/mol"))
Ea = Ea / 4.184 / 1000;
else if (EaUnits.equals("kJ/mol"))
Ea = Ea / 4.184;
else if (EaUnits.equals("Kelvins"))
Ea = Ea * 1.987;
UncertainDouble dE = new UncertainDouble(Ea,0.0,"A");
ArrheniusKinetics k = new ArrheniusKinetics(dA, dn, dE, "", 1, "", "");
PDepArrheniusKinetics pdepAK = new PDepArrheniusKinetics(i);
pdepAK.setKinetics(i, p, k);
pdepk = new PDepRateConstant(rateCoefficients,pdepAK);
}
}
PDepReaction forward = new PDepReaction(Reactants, Products, pdepk);
// Read in the reverse reaction
line = ChemParser.readMeaningfulLine(reader);
for (int i=0; i<numFameTs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
for (int j=0; j<numFamePs; j++) {
rateCoefficients[i][j] = Double.parseDouble(st.nextToken());
}
}
pdepk = null;
if (numChebyTs > 0) {
for (int i=0; i<numChebyTs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
for (int j=0; j<numChebyPs; j++) {
chebyPolys[i][j] = Double.parseDouble(st.nextToken());
}
}
ChebyshevPolynomials chebyshev = new ChebyshevPolynomials(numChebyTs,
ChebyshevPolynomials.getTlow(), ChebyshevPolynomials.getTup(),
numChebyPs, ChebyshevPolynomials.getPlow(), ChebyshevPolynomials.getPup(),
chebyPolys);
pdepk = new PDepRateConstant(rateCoefficients,chebyshev);
} else if (numPlogs > 0) {
for (int i=0; i<numPlogs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
Pressure p = new Pressure(Double.parseDouble(st.nextToken()),"Pa");
UncertainDouble dA = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
UncertainDouble dn = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
double Ea = Double.parseDouble(st.nextToken());
if (EaUnits.equals("cal/mol"))
Ea = Ea / 1000;
else if (EaUnits.equals("J/mol"))
Ea = Ea / 4.184 / 1000;
else if (EaUnits.equals("kJ/mol"))
Ea = Ea / 4.184;
else if (EaUnits.equals("Kelvins"))
Ea = Ea * 1.987;
UncertainDouble dE = new UncertainDouble(Ea,0.0,"A");
ArrheniusKinetics k = new ArrheniusKinetics(dA, dn, dE, "", 1, "", "");
PDepArrheniusKinetics pdepAK = new PDepArrheniusKinetics(i);
pdepAK.setKinetics(i, p, k);
pdepk = new PDepRateConstant(rateCoefficients,pdepAK);
}
}
PDepReaction reverse = new PDepReaction(Products, Reactants, pdepk);
reverse.setReverseReaction(forward);
forward.setReverseReaction(reverse);
netRxns.add(forward);
line = ChemParser.readMeaningfulLine(reader);
}
}
// This loop ends once line == "nonIncludedReactionList"
line = ChemParser.readMeaningfulLine(reader); // line is either data or "pathReactionList"
if (!line.toLowerCase().startsWith("pathreactionList")) {
while (!line.toLowerCase().startsWith("pathreactionlist")) {
// Read in the forward rxn
String[] reactsANDprods = line.split("\\-->");
PDepIsomer Reactants = null;
String reacts = reactsANDprods[0].trim();
if (reacts.contains("+")) {
String[] indivReacts = reacts.split("[+]");
String name = indivReacts[0].trim();
Species spc1 = sd.getSpeciesFromChemkinName(name);
if (spc1 == null) {
spc1 = getSpeciesBySPCName(name,sd);
}
name = indivReacts[1].trim();
Species spc2 = sd.getSpeciesFromChemkinName(name);
if (spc2 == null) {
spc2 = getSpeciesBySPCName(name,sd);
}
Reactants = new PDepIsomer(spc1,spc2);
} else {
String name = reacts.trim();
Species spc = sd.getSpeciesFromChemkinName(name);
if (spc == null) {
spc = getSpeciesBySPCName(name,sd);
}
Reactants = new PDepIsomer(spc);
}
PDepIsomer Products = null;
String prods = reactsANDprods[1].trim();
if (prods.contains("+")) {
String[] indivProds = prods.split("[+]");
String name = indivProds[0].trim();
Species spc1 = sd.getSpeciesFromChemkinName(name);
if (spc1 == null) {
spc1 = getSpeciesBySPCName(name,sd);
}
name = indivProds[1].trim();
Species spc2 = sd.getSpeciesFromChemkinName(name);
if (spc2 == null) {
spc2 = getSpeciesBySPCName(name,sd);
}
Products = new PDepIsomer(spc1,spc2);
} else {
String name = prods.trim();
Species spc = sd.getSpeciesFromChemkinName(name);
if (spc == null) {
spc = getSpeciesBySPCName(name,sd);
}
Products = new PDepIsomer(spc);
}
newNetwork.addIsomer(Reactants);
newNetwork.addIsomer(Products);
for (int i=0; i<numFameTs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
for (int j=0; j<numFamePs; j++) {
rateCoefficients[i][j] = Double.parseDouble(st.nextToken());
}
}
PDepRateConstant pdepk = null;
if (numChebyTs > 0) {
for (int i=0; i<numChebyTs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
for (int j=0; j<numChebyPs; j++) {
chebyPolys[i][j] = Double.parseDouble(st.nextToken());
}
}
ChebyshevPolynomials chebyshev = new ChebyshevPolynomials(numChebyTs,
ChebyshevPolynomials.getTlow(), ChebyshevPolynomials.getTup(),
numChebyPs, ChebyshevPolynomials.getPlow(), ChebyshevPolynomials.getPup(),
chebyPolys);
pdepk = new PDepRateConstant(rateCoefficients,chebyshev);
} else if (numPlogs > 0) {
for (int i=0; i<numPlogs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
Pressure p = new Pressure(Double.parseDouble(st.nextToken()),"Pa");
UncertainDouble dA = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
UncertainDouble dn = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
double Ea = Double.parseDouble(st.nextToken());
if (EaUnits.equals("cal/mol"))
Ea = Ea / 1000;
else if (EaUnits.equals("J/mol"))
Ea = Ea / 4.184 / 1000;
else if (EaUnits.equals("kJ/mol"))
Ea = Ea / 4.184;
else if (EaUnits.equals("Kelvins"))
Ea = Ea * 1.987;
UncertainDouble dE = new UncertainDouble(Ea,0.0,"A");
ArrheniusKinetics k = new ArrheniusKinetics(dA, dn, dE, "", 1, "", "");
PDepArrheniusKinetics pdepAK = new PDepArrheniusKinetics(i);
pdepAK.setKinetics(i, p, k);
pdepk = new PDepRateConstant(rateCoefficients,pdepAK);
}
}
PDepReaction forward = new PDepReaction(Reactants, Products, pdepk);
// Read in the reverse reaction
line = ChemParser.readMeaningfulLine(reader);
for (int i=0; i<numFameTs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
for (int j=0; j<numFamePs; j++) {
rateCoefficients[i][j] = Double.parseDouble(st.nextToken());
}
}
pdepk = null;
if (numChebyTs > 0) {
for (int i=0; i<numChebyTs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
for (int j=0; j<numChebyPs; j++) {
chebyPolys[i][j] = Double.parseDouble(st.nextToken());
}
}
ChebyshevPolynomials chebyshev = new ChebyshevPolynomials(numChebyTs,
ChebyshevPolynomials.getTlow(), ChebyshevPolynomials.getTup(),
numChebyPs, ChebyshevPolynomials.getPlow(), ChebyshevPolynomials.getPup(),
chebyPolys);
pdepk = new PDepRateConstant(rateCoefficients,chebyshev);
} else if (numPlogs > 0) {
for (int i=0; i<numPlogs; i++) {
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader));
Pressure p = new Pressure(Double.parseDouble(st.nextToken()),"Pa");
UncertainDouble dA = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
UncertainDouble dn = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
double Ea = Double.parseDouble(st.nextToken());
if (EaUnits.equals("cal/mol"))
Ea = Ea / 1000;
else if (EaUnits.equals("J/mol"))
Ea = Ea / 4.184 / 1000;
else if (EaUnits.equals("kJ/mol"))
Ea = Ea / 4.184;
else if (EaUnits.equals("Kelvins"))
Ea = Ea * 1.987;
UncertainDouble dE = new UncertainDouble(Ea,0.0,"A");
ArrheniusKinetics k = new ArrheniusKinetics(dA, dn, dE, "", 1, "", "");
PDepArrheniusKinetics pdepAK = new PDepArrheniusKinetics(i);
pdepAK.setKinetics(i, p, k);
pdepk = new PDepRateConstant(rateCoefficients,pdepAK);
}
}
PDepReaction reverse = new PDepReaction(Products, Reactants, pdepk);
reverse.setReverseReaction(forward);
forward.setReverseReaction(reverse);
nonincludeRxns.add(forward);
line = ChemParser.readMeaningfulLine(reader);
}
}
// This loop ends once line == "pathReactionList"
line = ChemParser.readMeaningfulLine(reader); // line is either data or "PDepNetwork #_" or null (end of file)
while (line != null && !line.toLowerCase().startsWith("pdepnetwork")) {
st = new StringTokenizer(line);
int direction = Integer.parseInt(st.nextToken());
// First token is the rxn structure: A+B=C+D
// Note: Up to 3 reactants/products allowed
// : Either "=" or "=>" will separate reactants and products
String structure = st.nextToken();
// Separate the reactants from the products
boolean generateReverse = false;
String[] reactsANDprods = structure.split("\\=>");
if (reactsANDprods.length == 1) {
reactsANDprods = structure.split("[=]");
generateReverse = true;
}
sd = SpeciesDictionary.getInstance();
LinkedList r = ChemParser.parseReactionSpecies(sd, reactsANDprods[0]);
LinkedList p = ChemParser.parseReactionSpecies(sd, reactsANDprods[1]);
Structure s = new Structure(r,p);
s.setDirection(direction);
// Next three tokens are the modified Arrhenius parameters
double rxn_A = Double.parseDouble(st.nextToken());
double rxn_n = Double.parseDouble(st.nextToken());
double rxn_E = Double.parseDouble(st.nextToken());
if (EaUnits.equals("cal/mol"))
rxn_E = rxn_E / 1000;
else if (EaUnits.equals("J/mol"))
rxn_E = rxn_E / 4.184 / 1000;
else if (EaUnits.equals("kJ/mol"))
rxn_E = rxn_E / 4.184;
else if (EaUnits.equals("Kelvins"))
rxn_E = rxn_E * 1.987;
UncertainDouble uA = new UncertainDouble(rxn_A,0.0,"A");
UncertainDouble un = new UncertainDouble(rxn_n,0.0,"A");
UncertainDouble uE = new UncertainDouble(rxn_E,0.0,"A");
// The remaining tokens are comments
String comments = "";
while (st.hasMoreTokens()) {
comments += st.nextToken();
}
ArrheniusKinetics k = new ArrheniusKinetics(uA,un,uE,"",1,"",comments);
Reaction pathRxn = new Reaction();
// if (direction == 1)
// pathRxn = Reaction.makeReaction(s,k,generateReverse);
// else
// pathRxn = Reaction.makeReaction(s.generateReverseStructure(),k,generateReverse);
pathRxn = Reaction.makeReaction(s,k,generateReverse);
PDepIsomer Reactants = new PDepIsomer(r);
PDepIsomer Products = new PDepIsomer(p);
PDepReaction pdeppathrxn = new PDepReaction(Reactants,Products,pathRxn);
newNetwork.addReaction(pdeppathrxn);
line = ChemParser.readMeaningfulLine(reader);
}
PDepNetwork.getNetworks().add(newNetwork);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* MRH 14Jan2010
*
* getSpeciesBySPCName
*
* Input: String name - Name of species, normally chemical formula followed
* by "J"s for radicals, and then (#)
* SpeciesDictionary sd
*
* This method was originally written as a complement to the method readPDepNetworks.
* jdmo found a bug with the readrestart option. The bug was that the method was
* attempting to add a null species to the Isomer list. The null species resulted
* from searching the SpeciesDictionary by chemkinName (e.g. C4H8OJJ(48)), when the
* chemkinName present in the dictionary was SPC(48).
*
*/
public Species getSpeciesBySPCName(String name, SpeciesDictionary sd) {
String[] nameFromNumber = name.split("\\(");
String newName = "SPC(" + nameFromNumber[1];
return sd.getSpeciesFromChemkinName(newName);
}
/**
* MRH 12-Jun-2009
*
* Function initializes the model's core and edge.
* The initial core species always consists of the species contained
* in the condition.txt file. If seed mechanisms exist, those species
* (and the reactions given in the seed mechanism) are also added to
* the core.
* The initial edge species/reactions are determined by reacting the core
* species by one full iteration.
*/
public void initializeCoreEdgeModel() {
LinkedHashSet allInitialCoreSpecies = new LinkedHashSet();
LinkedHashSet allInitialCoreRxns = new LinkedHashSet();
if (readrestart) {
readRestartReactions();
if (PDepNetwork.generateNetworks) readPDepNetworks();
allInitialCoreSpecies.addAll(restartCoreSpcs);
allInitialCoreRxns.addAll(restartCoreRxns);
}
// Add the species from the condition.txt (input) file
allInitialCoreSpecies.addAll(getSpeciesSeed());
// Add the species from the seed mechanisms, if they exist
if (hasSeedMechanisms()) {
allInitialCoreSpecies.addAll(getSeedMechanism().getSpeciesSet());
allInitialCoreRxns.addAll(getSeedMechanism().getReactionSet());
}
CoreEdgeReactionModel cerm = new CoreEdgeReactionModel(allInitialCoreSpecies, allInitialCoreRxns);
if (readrestart) {
cerm.addUnreactedSpeciesSet(restartEdgeSpcs);
cerm.addUnreactedReactionSet(restartEdgeRxns);
}
setReactionModel(cerm);
PDepNetwork.reactionModel = getReactionModel();
PDepNetwork.reactionSystem = (ReactionSystem) getReactionSystemList().get(0);
// Determine initial set of reactions and edge species using only the
// species enumerated in the input file and the seed mechanisms as the core
if (!readrestart) {
LinkedHashSet reactionSet;
if (hasSeedMechanisms() && getSeedMechanism().shouldGenerateReactions()) {
reactionSet = getReactionGenerator().react(allInitialCoreSpecies);
}
else {
reactionSet = new LinkedHashSet();
for (Iterator iter = speciesSeed.iterator(); iter.hasNext(); ) {
Species spec = (Species) iter.next();
reactionSet.addAll(getReactionGenerator().react(allInitialCoreSpecies, spec));
}
}
reactionSet.addAll(getLibraryReactionGenerator().react(allInitialCoreSpecies));
// Set initial core-edge reaction model based on above results
if (reactionModelEnlarger instanceof RateBasedRME) {
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
cerm.addReaction(r);
}
}
else {
// Only keep the reactions involving bimolecular reactants and bimolecular products
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
if (r.getReactantNumber() > 1 && r.getProductNumber() > 1){
cerm.addReaction(r);
}
else {
cerm.categorizeReaction(r.getStructure());
PDepNetwork.addReactionToNetworks(r);
}
}
}
}
for (Integer i = 0; i < reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i);
rs.setReactionModel(getReactionModel());
}
// We cannot return a system with no core reactions, so if this is a case we must add to the core
while (getReactionModel().isEmpty() && !PDepNetwork.hasCoreReactions((CoreEdgeReactionModel) getReactionModel())) {
for (Integer i = 0; i < reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i);
if (reactionModelEnlarger instanceof RateBasedPDepRME)
rs.initializePDepNetwork();
rs.appendUnreactedSpeciesStatus((InitialStatus)initialStatusList.get(i), rs.getPresentTemperature());
}
enlargeReactionModel();
}
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
rs.setReactionModel(getReactionModel());
}
return;
}
//## operation initializeCoreEdgeModelWithPRL()
//9/24/07 gmagoon: moved from ReactionSystem.java
public void initializeCoreEdgeModelWithPRL() {
//#[ operation initializeCoreEdgeModelWithPRL()
initializeCoreEdgeModelWithoutPRL();
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)getReactionModel();
LinkedHashSet primarySpeciesSet = getPrimaryReactionLibrary().getSpeciesSet(); //10/14/07 gmagoon: changed to use getPrimaryReactionLibrary
LinkedHashSet primaryReactionSet = getPrimaryReactionLibrary().getReactionSet();
cerm.addReactedSpeciesSet(primarySpeciesSet);
cerm.addPrimaryReactionSet(primaryReactionSet);
LinkedHashSet newReactions = getReactionGenerator().react(cerm.getReactedSpeciesSet());
if (reactionModelEnlarger instanceof RateBasedRME)
cerm.addReactionSet(newReactions);
else {
Iterator iter = newReactions.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
if (r.getReactantNumber() == 2 && r.getProductNumber() == 2){
cerm.addReaction(r);
}
}
}
return;
//#]
}
//## operation initializeCoreEdgeModelWithoutPRL()
//9/24/07 gmagoon: moved from ReactionSystem.java
protected void initializeCoreEdgeModelWithoutPRL() {
//#[ operation initializeCoreEdgeModelWithoutPRL()
CoreEdgeReactionModel cerm = new CoreEdgeReactionModel(new LinkedHashSet(getSpeciesSeed()));
setReactionModel(cerm);
PDepNetwork.reactionModel = getReactionModel();
PDepNetwork.reactionSystem = (ReactionSystem) getReactionSystemList().get(0);
// Determine initial set of reactions and edge species using only the
// species enumerated in the input file as the core
LinkedHashSet reactionSet = getReactionGenerator().react(getSpeciesSeed());
reactionSet.addAll(getLibraryReactionGenerator().react(getSpeciesSeed()));
// Set initial core-edge reaction model based on above results
if (reactionModelEnlarger instanceof RateBasedRME) {
// Only keep the reactions involving bimolecular reactants and bimolecular products
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
cerm.addReaction(r);
}
}
else {
// Only keep the reactions involving bimolecular reactants and bimolecular products
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
if (r.getReactantNumber() > 1 && r.getProductNumber() > 1){
cerm.addReaction(r);
}
else {
cerm.categorizeReaction(r.getStructure());
PDepNetwork.addReactionToNetworks(r);
}
}
}
//10/9/07 gmagoon: copy reactionModel to reactionSystem; there may still be scope problems, particularly in above elseif statement
//10/24/07 gmagoon: want to copy same reaction model to all reactionSystem variables; should probably also make similar modifications elsewhere; may or may not need to copy in ...WithPRL function
for (Integer i = 0; i < reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i);
rs.setReactionModel(getReactionModel());
}
//reactionSystem.setReactionModel(getReactionModel());
// We cannot return a system with no core reactions, so if this is a case we must add to the core
while (getReactionModel().isEmpty()&&!PDepNetwork.hasCoreReactions((CoreEdgeReactionModel) getReactionModel())) {
for (Integer i = 0; i < reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i);
if (reactionModelEnlarger instanceof RateBasedPDepRME)
rs.initializePDepNetwork();
rs.appendUnreactedSpeciesStatus((InitialStatus)initialStatusList.get(i), rs.getPresentTemperature());
}
enlargeReactionModel();
}
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
rs.setReactionModel(getReactionModel());
}
return;
//#]
}
//## operation initializeCoreEdgeReactionModel()
//9/24/07 gmagoon: moved from ReactionSystem.java
public void initializeCoreEdgeReactionModel() {
System.out.println("\nInitializing core-edge reaction model");
// setSpeciesSeed(new LinkedHashSet());//10/4/07 gmagoon:moved from initializeReactionSystem; later moved to modelGeneration()
//#[ operation initializeCoreEdgeReactionModel()
// if (hasPrimaryReactionLibrary()) initializeCoreEdgeModelWithPRL();
// else initializeCoreEdgeModelWithoutPRL();
/*
* MRH 12-Jun-2009
*
* I've lumped the initializeCoreEdgeModel w/ and w/o a seed mechanism
* (which used to be the PRL) into one function. Before, RMG would
* complete one iteration (construct the edge species/rxns) before adding
* the seed mechanism to the rxn, thereby possibly estimating kinetic
* parameters for a rxn that exists in a seed mechanism
*/
initializeCoreEdgeModel();
//#]
}
//9/24/07 gmagoon: copied from ReactionSystem.java
public ReactionGenerator getReactionGenerator() {
return reactionGenerator;
}
//10/4/07 gmagoon: moved from ReactionSystem.java
public void setReactionGenerator(ReactionGenerator p_ReactionGenerator) {
reactionGenerator = p_ReactionGenerator;
}
//9/25/07 gmagoon: moved from ReactionSystem.java
//10/24/07 gmagoon: changed to use reactionSystemList
//## operation enlargeReactionModel()
public void enlargeReactionModel() {
//#[ operation enlargeReactionModel()
if (reactionModelEnlarger == null) throw new NullPointerException("ReactionModelEnlarger");
System.out.println("\nEnlarging reaction model");
reactionModelEnlarger.enlargeReactionModel(reactionSystemList, reactionModel, validList);
return;
//#]
}
//9/25/07 gmagoon: moved from ReactionSystem.java
//## operation hasPrimaryReactionLibrary()
public boolean hasPrimaryReactionLibrary() {
//#[ operation hasPrimaryReactionLibrary()
if (primaryReactionLibrary == null) return false;
return (primaryReactionLibrary.size() > 0);
//#]
}
public boolean hasSeedMechanisms() {
if (getSeedMechanism() == null) return false;
return (seedMechanism.size() > 0);
}
//9/25/07 gmagoon: moved from ReactionSystem.java
public PrimaryReactionLibrary getPrimaryReactionLibrary() {
return primaryReactionLibrary;
}
//9/25/07 gmagoon: moved from ReactionSystem.java
public void setPrimaryReactionLibrary(PrimaryReactionLibrary p_PrimaryReactionLibrary) {
primaryReactionLibrary = p_PrimaryReactionLibrary;
}
//10/4/07 gmagoon: added
public LinkedHashSet getSpeciesSeed() {
return speciesSeed;
}
//10/4/07 gmagoon: added
public void setSpeciesSeed(LinkedHashSet p_speciesSeed) {
speciesSeed = p_speciesSeed;
}
//10/4/07 gmagoon: added
public LibraryReactionGenerator getLibraryReactionGenerator() {
return lrg;
}
//10/4/07 gmagoon: added
public void setLibraryReactionGenerator(LibraryReactionGenerator p_lrg) {
lrg = p_lrg;
}
public static Temperature getTemp4BestKinetics() {
return temp4BestKinetics;
}
public static void setTemp4BestKinetics(Temperature firstSysTemp) {
temp4BestKinetics = firstSysTemp;
}
public SeedMechanism getSeedMechanism() {
return seedMechanism;
}
public void setSeedMechanism(SeedMechanism p_seedMechanism) {
seedMechanism = p_seedMechanism;
}
public PrimaryThermoLibrary getPrimaryThermoLibrary() {
return primaryThermoLibrary;
}
public void setPrimaryThermoLibrary(PrimaryThermoLibrary p_primaryThermoLibrary) {
primaryThermoLibrary = p_primaryThermoLibrary;
}
public static double getAtol(){
return atol;
}
public boolean runKillableToPreventInfiniteLoop(boolean intermediateSteps, int iterationNumber) {
ReactionSystem rs0 = (ReactionSystem)reactionSystemList.get(0);
if (!intermediateSteps)//if there are no intermediate steps (for example when using AUTO method), return true;
return true;
//if there are intermediate steps, the run is killable if the iteration number exceeds the number of time steps / conversions
else if (rs0.finishController.terminationTester instanceof ReactionTimeTT){
if (iterationNumber - 1 > timeStep.size()){ //-1 correction needed since when this is called, iteration number has been incremented
return true;
}
}
else //the case where intermediate conversions are specified
if (iterationNumber - 1 > numConversions){ //see above; it is possible there is an off-by-one error here, so further testing will be needed
return true;
}
return false; //return false if none of the above criteria are met
}
public void readAndMakePRL(BufferedReader reader) throws IOException {
int Ilib = 0;
String line = ChemParser.readMeaningfulLine(reader);
while (!line.equals("END")) {
String[] tempString = line.split("Name: ");
String name = tempString[tempString.length-1].trim();
line = ChemParser.readMeaningfulLine(reader);
tempString = line.split("Location: ");
String location = tempString[tempString.length-1].trim();
String path = System.getProperty("jing.rxn.ReactionLibrary.pathName");
path += "/" + location;
if (Ilib==0) {
setPrimaryReactionLibrary(new PrimaryReactionLibrary(name, path));
Ilib++;
}
else {
getPrimaryReactionLibrary().appendPrimaryReactionLibrary(name, path);
Ilib++;
}
line = ChemParser.readMeaningfulLine(reader);
}
if (Ilib==0) {
setPrimaryReactionLibrary(null);
}
else System.out.println("Primary Reaction Libraries in use: " + getPrimaryReactionLibrary().getName());
}
public void readAndMakePTL(BufferedReader reader) {
int numPTLs = 0;
String line = ChemParser.readMeaningfulLine(reader);
while (!line.equals("END")) {
String[] tempString = line.split("Name: ");
String name = tempString[tempString.length-1].trim();
line = ChemParser.readMeaningfulLine(reader);
tempString = line.split("Location: ");
String path = tempString[tempString.length-1].trim();
if (numPTLs==0) {
setPrimaryThermoLibrary(new PrimaryThermoLibrary(name,path));
++numPTLs;
}
else {
getPrimaryThermoLibrary().appendPrimaryThermoLibrary(name,path);
++numPTLs;
}
line = ChemParser.readMeaningfulLine(reader);
}
if (numPTLs == 0) setPrimaryThermoLibrary(null);
}
public void readExtraForbiddenStructures(BufferedReader reader) throws IOException {
System.out.println("Reading extra forbidden structures from input file.");
String line = ChemParser.readMeaningfulLine(reader);
while (!line.equals("END")) {
StringTokenizer token = new StringTokenizer(line);
String fgname = token.nextToken();
Graph fgGraph = null;
try {
fgGraph = ChemParser.readFGGraph(reader);
}
catch (InvalidGraphFormatException e) {
System.out.println("Invalid functional group in "+fgname);
throw new InvalidFunctionalGroupException(fgname + ": " + e.getMessage());
}
if (fgGraph == null) throw new InvalidFunctionalGroupException(fgname);
FunctionalGroup fg = FunctionalGroup.makeForbiddenStructureFG(fgname, fgGraph);
ChemGraph.addForbiddenStructure(fg);
line = ChemParser.readMeaningfulLine(reader);
System.out.println(" Forbidden structure: "+fgname);
}
}
public void setSpectroscopicDataMode(String line) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String sdeType = st.nextToken().toLowerCase();
if (sdeType.equals("frequencygroups") || sdeType.equals("default")) {
SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
}
else if (sdeType.equals("therfit") || sdeType.equals("threefrequencymodel")) {
SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
}
else if (sdeType.equals("off") || sdeType.equals("none")) {
SpectroscopicData.mode = SpectroscopicData.Mode.OFF;
}
else throw new InvalidSymbolException("condition.txt: Unknown SpectroscopicDataEstimator = " + sdeType);
}
/**
* Sets the pressure dependence options to on or off. If on, checks for
* more options and sets them as well.
* @param line The current line in the condition file; should start with "PressureDependence:"
* @param reader The reader currently being used to parse the condition file
*/
public String setPressureDependenceOptions(String line, BufferedReader reader) throws InvalidSymbolException {
// Determine pressure dependence mode
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken(); // Should be "PressureDependence:"
String pDepType = st.nextToken();
if (pDepType.toLowerCase().equals("off")) {
// No pressure dependence
reactionModelEnlarger = new RateBasedRME();
PDepNetwork.generateNetworks = false;
line = ChemParser.readMeaningfulLine(reader);
}
else if (pDepType.toLowerCase().equals("modifiedstrongcollision") ||
pDepType.toLowerCase().equals("reservoirstate") ||
pDepType.toLowerCase().equals("chemdis")) {
reactionModelEnlarger = new RateBasedPDepRME();
PDepNetwork.generateNetworks = true;
// Set pressure dependence method
if (pDepType.toLowerCase().equals("reservoirstate"))
((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new FastMasterEqn(FastMasterEqn.Mode.RESERVOIRSTATE));
else if (pDepType.toLowerCase().equals("modifiedstrongcollision"))
((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new FastMasterEqn(FastMasterEqn.Mode.STRONGCOLLISION));
//else if (pDepType.toLowerCase().equals("chemdis"))
// ((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new Chemdis());
else
throw new InvalidSymbolException("condition.txt: Unknown PressureDependence mode = " + pDepType);
RateBasedPDepRME pdepModelEnlarger = (RateBasedPDepRME) reactionModelEnlarger;
// Turn on spectroscopic data estimation if not already on
if (pdepModelEnlarger.getPDepKineticsEstimator() instanceof FastMasterEqn && SpectroscopicData.mode == SpectroscopicData.Mode.OFF) {
System.out.println("Warning: Spectroscopic data needed for pressure dependence; switching SpectroscopicDataEstimator to FrequencyGroups.");
SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
}
else if (pdepModelEnlarger.getPDepKineticsEstimator() instanceof Chemdis && SpectroscopicData.mode != SpectroscopicData.Mode.THREEFREQUENCY) {
System.out.println("Warning: Switching SpectroscopicDataEstimator to three-frequency model.");
SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
}
// Next line must be PDepKineticsModel
line = ChemParser.readMeaningfulLine(reader);
if (line.toLowerCase().startsWith("pdepkineticsmodel:")) {
st = new StringTokenizer(line);
name = st.nextToken();
String pDepKinType = st.nextToken();
if (pDepKinType.toLowerCase().equals("chebyshev")) {
PDepRateConstant.setMode(PDepRateConstant.Mode.CHEBYSHEV);
// Default is to cubic order for basis functions
FastMasterEqn.setNumTBasisFuncs(4);
FastMasterEqn.setNumPBasisFuncs(4);
}
else if (pDepKinType.toLowerCase().equals("pdeparrhenius"))
PDepRateConstant.setMode(PDepRateConstant.Mode.PDEPARRHENIUS);
else if (pDepKinType.toLowerCase().equals("rate"))
PDepRateConstant.setMode(PDepRateConstant.Mode.RATE);
else
throw new InvalidSymbolException("condition.txt: Unknown PDepKineticsModel = " + pDepKinType);
// For Chebyshev polynomials, optionally specify the number of
// temperature and pressure basis functions
// Such a line would read, e.g.: "PDepKineticsModel: Chebyshev 4 4"
if (st.hasMoreTokens() && PDepRateConstant.getMode() == PDepRateConstant.Mode.CHEBYSHEV) {
try {
int numTBasisFuncs = Integer.parseInt(st.nextToken());
int numPBasisFuncs = Integer.parseInt(st.nextToken());
FastMasterEqn.setNumTBasisFuncs(numTBasisFuncs);
FastMasterEqn.setNumPBasisFuncs(numPBasisFuncs);
}
catch (NoSuchElementException e) {
throw new InvalidSymbolException("condition.txt: Missing number of pressure basis functions for Chebyshev polynomials.");
}
}
}
else
throw new InvalidSymbolException("condition.txt: Missing PDepKineticsModel after PressureDependence line.");
// Determine temperatures and pressures to use
// These can be specified automatically using TRange and PRange or
// manually using Temperatures and Pressures
Temperature[] temperatures = null;
Pressure[] pressures = null;
String Tunits = "K";
Temperature Tmin = new Temperature(300.0, "K");
Temperature Tmax = new Temperature(2000.0, "K");
int Tnumber = 8;
String Punits = "bar";
Pressure Pmin = new Pressure(0.01, "bar");
Pressure Pmax = new Pressure(100.0, "bar");
int Pnumber = 5;
// Read next line of input
line = ChemParser.readMeaningfulLine(reader);
boolean done = !(line.toLowerCase().startsWith("trange:") ||
line.toLowerCase().startsWith("prange:") ||
line.toLowerCase().startsWith("temperatures:") ||
line.toLowerCase().startsWith("pressures:"));
// Parse lines containing pressure dependence options
// Possible options are "TRange:", "PRange:", "Temperatures:", and "Pressures:"
// You must specify either TRange or Temperatures and either PRange or Pressures
// The order does not matter
while (!done) {
st = new StringTokenizer(line);
name = st.nextToken();
if (line.toLowerCase().startsWith("trange:")) {
Tunits = ChemParser.removeBrace(st.nextToken());
Tmin = new Temperature(Double.parseDouble(st.nextToken()), Tunits);
Tmax = new Temperature(Double.parseDouble(st.nextToken()), Tunits);
Tnumber = Integer.parseInt(st.nextToken());
}
else if (line.toLowerCase().startsWith("prange:")) {
Punits = ChemParser.removeBrace(st.nextToken());
Pmin = new Pressure(Double.parseDouble(st.nextToken()), Punits);
Pmax = new Pressure(Double.parseDouble(st.nextToken()), Punits);
Pnumber = Integer.parseInt(st.nextToken());
}
else if (line.toLowerCase().startsWith("temperatures:")) {
Tnumber = Integer.parseInt(st.nextToken());
Tunits = ChemParser.removeBrace(st.nextToken());
temperatures = new Temperature[Tnumber];
for (int i = 0; i < Tnumber; i++) {
temperatures[i] = new Temperature(Double.parseDouble(st.nextToken()), Tunits);
}
Tmin = temperatures[0];
Tmax = temperatures[Tnumber-1];
}
else if (line.toLowerCase().startsWith("pressures:")) {
Pnumber = Integer.parseInt(st.nextToken());
Punits = ChemParser.removeBrace(st.nextToken());
pressures = new Pressure[Pnumber];
for (int i = 0; i < Pnumber; i++) {
pressures[i] = new Pressure(Double.parseDouble(st.nextToken()), Punits);
}
Pmin = pressures[0];
Pmax = pressures[Pnumber-1];
}
// Read next line of input
line = ChemParser.readMeaningfulLine(reader);
done = !(line.toLowerCase().startsWith("trange:") ||
line.toLowerCase().startsWith("prange:") ||
line.toLowerCase().startsWith("temperatures:") ||
line.toLowerCase().startsWith("pressures:"));
}
// Set temperatures and pressures (if not already set manually)
if (temperatures == null) {
temperatures = new Temperature[Tnumber];
if (PDepRateConstant.getMode() == PDepRateConstant.Mode.CHEBYSHEV) {
// Use the Gauss-Chebyshev points
// The formula for the Gauss-Chebyshev points was taken from
// the Chemkin theory manual
for (int i = 1; i <= Tnumber; i++) {
double T = -Math.cos((2 * i - 1) * Math.PI / (2 * Tnumber));
T = 2.0 / ((1.0/Tmax.getK() - 1.0/Tmin.getK()) * T + 1.0/Tmax.getK() + 1.0/Tmin.getK());
temperatures[i-1] = new Temperature(T, "K");
}
}
else {
// Distribute equally on a 1/T basis
double slope = (1.0/Tmax.getK() - 1.0/Tmin.getK()) / (Tnumber - 1);
for (int i = 0; i < Tnumber; i++) {
double T = 1.0/(slope * i + 1.0/Tmin.getK());
temperatures[i] = new Temperature(T, "K");
}
}
}
if (pressures == null) {
pressures = new Pressure[Pnumber];
if (PDepRateConstant.getMode() == PDepRateConstant.Mode.CHEBYSHEV) {
// Use the Gauss-Chebyshev points
// The formula for the Gauss-Chebyshev points was taken from
// the Chemkin theory manual
for (int i = 1; i <= Pnumber; i++) {
double P = -Math.cos((2 * i - 1) * Math.PI / (2 * Pnumber));
P = Math.pow(10, 0.5 * ((Math.log10(Pmax.getBar()) - Math.log10(Pmin.getBar())) * P + Math.log10(Pmax.getBar()) + Math.log10(Pmin.getBar())));
pressures[i-1] = new Pressure(P, "bar");
}
}
else {
// Distribute equally on a log P basis
double slope = (Math.log10(Pmax.getBar()) - Math.log10(Pmin.getBar())) / (Pnumber - 1);
for (int i = 0; i < Pnumber; i++) {
double P = Math.pow(10, slope * i + Math.log10(Pmin.getBar()));
pressures[i] = new Pressure(P, "bar");
}
}
}
FastMasterEqn.setTemperatures(temperatures);
PDepRateConstant.setTemperatures(temperatures);
PDepRateConstant.setTMin(Tmin);
PDepRateConstant.setTMax(Tmax);
ChebyshevPolynomials.setTlow(Tmin);
ChebyshevPolynomials.setTup(Tmax);
FastMasterEqn.setPressures(pressures);
PDepRateConstant.setPressures(pressures);
PDepRateConstant.setPMin(Pmin);
PDepRateConstant.setPMax(Pmax);
ChebyshevPolynomials.setPlow(Pmin);
ChebyshevPolynomials.setPup(Pmax);
}
else {
throw new InvalidSymbolException("condition.txt: Unknown PressureDependence = " + pDepType);
}
return line;
}
public ReactionModelEnlarger getReactionModelEnlarger() {
return reactionModelEnlarger;
}
}
/*********************************************************************
File Path : RMG\RMG\jing\rxnSys\ReactionModelGenerator.java
*********************************************************************/
| true | true | public void initializeReactionSystems() throws InvalidSymbolException, IOException {
//#[ operation initializeReactionSystem()
try {
String initialConditionFile = System.getProperty("jing.rxnSys.ReactionModelGenerator.conditionFile");
if (initialConditionFile == null) {
System.out.println("undefined system property: jing.rxnSys.ReactionModelGenerator.conditionFile");
System.exit(0);
}
//double sandeep = getCpuTime();
//System.out.println(getCpuTime()/1e9/60);
FileReader in = new FileReader(initialConditionFile);
BufferedReader reader = new BufferedReader(in);
//TemperatureModel temperatureModel = null;//10/27/07 gmagoon: commented out
//PressureModel pressureModel = null;//10/27/07 gmagoon: commented out
// ReactionModelEnlarger reactionModelEnlarger = null;//10/9/07 gmagoon: commented out: unneeded now and causes scope problems
FinishController finishController = null;
//DynamicSimulator dynamicSimulator = null;//10/27/07 gmagoon: commented out and replaced with following line
LinkedList dynamicSimulatorList = new LinkedList();
//PrimaryReactionLibrary primaryReactionLibrary = null;//10/14/07 gmagoon: see below
setPrimaryReactionLibrary(null);//10/14/07 gmagoon: changed to use setPrimaryReactionLibrary
double [] conversionSet = new double[50];
String line = ChemParser.readMeaningfulLine(reader);
/*if (line.startsWith("Restart")){
StringTokenizer st = new StringTokenizer(line);
String token = st.nextToken();
token = st.nextToken();
if (token.equalsIgnoreCase("true")) {
//Runtime.getRuntime().exec("cp Restart/allSpecies.txt Restart/allSpecies1.txt");
//Runtime.getRuntime().exec("echo >> allSpecies.txt");
restart = true;
}
else if (token.equalsIgnoreCase("false")) {
Runtime.getRuntime().exec("rm Restart/allSpecies.txt");
restart = false;
}
else throw new InvalidSymbolException("UnIdentified Symbol "+token+" after Restart:");
}
else throw new InvalidSymbolException("Can't find Restart!");*/
//line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Database")){//svp
line = ChemParser.readMeaningfulLine(reader);
}
else throw new InvalidSymbolException("Can't find database!");
// if (line.startsWith("PrimaryThermoLibrary")){//svp
// line = ChemParser.readMeaningfulLine(reader);
// }
// else throw new InvalidSymbolException("Can't find primary thermo library!");
/*
* Added by MRH on 15-Jun-2009
* Give user the option to change the maximum carbon, oxygen,
* and/or radical number for all species. These lines will be
* optional in the condition.txt file. Values are hard-
* coded into RMG (in ChemGraph.java), but any user-
* defined input will override these values.
*/
/*
* Moved from before InitialStatus to before PrimaryThermoLibary
* by MRH on 27-Oct-2009
* Overriding default values of maximum number of "X" per
* chemgraph should come before RMG attempts to make any
* chemgraph. The first instance RMG will attempt to make a
* chemgraph is in reading the primary thermo library.
*/
if (line.startsWith("MaxCarbonNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxCarbonNumberPerSpecies:"
int maxCNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxCarbonNumber(maxCNum);
System.out.println("Note: Overriding RMG-defined MAX_CARBON_NUM with user-defined value: " + maxCNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxOxygenNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxOxygenNumberPerSpecies:"
int maxONum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxOxygenNumber(maxONum);
System.out.println("Note: Overriding RMG-defined MAX_OXYGEN_NUM with user-defined value: " + maxONum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxRadicalNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxRadicalNumberPerSpecies:"
int maxRadNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxRadicalNumber(maxRadNum);
System.out.println("Note: Overriding RMG-defined MAX_RADICAL_NUM with user-defined value: " + maxRadNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxSulfurNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxSulfurNumberPerSpecies:"
int maxSNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxSulfurNumber(maxSNum);
System.out.println("Note: Overriding RMG-defined MAX_SULFUR_NUM with user-defined value: " + maxSNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxSiliconNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxSiliconNumberPerSpecies:"
int maxSiNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxSiliconNumber(maxSiNum);
System.out.println("Note: Overriding RMG-defined MAX_SILICON_NUM with user-defined value: " + maxSiNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxHeavyAtom")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxHeavyAtomPerSpecies:"
int maxHANum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxHeavyAtomNumber(maxHANum);
System.out.println("Note: Overriding RMG-defined MAX_HEAVYATOM_NUM with user-defined value: " + maxHANum);
line = ChemParser.readMeaningfulLine(reader);
}
/*
* Read in the Primary Thermo Library
* MRH 7-Jul-2009
*/
if (line.startsWith("PrimaryThermoLibrary:")) {
/*
* MRH 27Feb2010:
* Changing the "read in Primary Thermo Library information" code
* into it's own method.
*
* Other modules (e.g. PopulateReactions) will be utilizing the exact code.
* Rather than copying and pasting code into other modules, just have
* everything call this new method: readAndMakePTL
*/
readAndMakePTL(reader);
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate PrimaryThermoLibrary field");
line = ChemParser.readMeaningfulLine(reader);
// Extra forbidden structures may be specified after the Primary Thermo Library
if (line.startsWith("ForbiddenStructures:")) {
readExtraForbiddenStructures(reader);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.toLowerCase().startsWith("readrestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "ReadRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes")) {
readrestart = true;
readRestartSpecies();
} else readrestart = false;
line = ChemParser.readMeaningfulLine(reader);
} else throw new InvalidSymbolException("Cannot locate ReadRestart field");
if (line.toLowerCase().startsWith("writerestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "WriteRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes"))
writerestart = true;
else writerestart = false;
line = ChemParser.readMeaningfulLine(reader);
} else throw new InvalidSymbolException("Cannot locate WriteRestart field");
// read temperature model
//gmagoon 10/23/07: modified to handle multiple temperatures; note that this requires different formatting of units in condition.txt
if (line.startsWith("TemperatureModel:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String modelType = st.nextToken();
//String t = st.nextToken();
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (modelType.equals("Constant")) {
tempList = new LinkedList();
//read first temperature
double t = Double.parseDouble(st.nextToken());
tempList.add(new ConstantTM(t, unit));
Temperature temp = new Temperature(t, unit);//10/29/07 gmagoon: added this line and next two lines to set Global.lowTemperature and Global.highTemperature
Global.lowTemperature = (Temperature)temp.clone();
Global.highTemperature = (Temperature)temp.clone();
//read remaining temperatures
while (st.hasMoreTokens()) {
t = Double.parseDouble(st.nextToken());
tempList.add(new ConstantTM(t, unit));
temp = new Temperature(t,unit);//10/29/07 gmagoon: added this line and next two "if" statements to set Global.lowTemperature and Global.highTemperature
if(temp.getK() < Global.lowTemperature.getK())
Global.lowTemperature = (Temperature)temp.clone();
if(temp.getK() > Global.highTemperature.getK())
Global.highTemperature = (Temperature)temp.clone();
}
// Global.temperature = new Temperature(t,unit);
}
//10/23/07 gmagoon: commenting out; further updates needed to get this to work
//else if (modelType.equals("Curved")) {
// String t = st.nextToken();
// // add reading curved temperature function here
// temperatureModel = new CurvedTM(new LinkedList());
//}
else {
throw new InvalidSymbolException("condition.txt: Unknown TemperatureModel = " + modelType);
}
}
else throw new InvalidSymbolException("condition.txt: can't find TemperatureModel!");
// read in pressure model
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("PressureModel:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String modelType = st.nextToken();
//String p = st.nextToken();
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (modelType.equals("Constant")) {
presList = new LinkedList();
//read first pressure
double p = Double.parseDouble(st.nextToken());
Pressure pres = new Pressure(p, unit);
Global.lowPressure = (Pressure)pres.clone();
Global.highPressure = (Pressure)pres.clone();
presList.add(new ConstantPM(p, unit));
//read remaining temperatures
while (st.hasMoreTokens()) {
p = Double.parseDouble(st.nextToken());
presList.add(new ConstantPM(p, unit));
pres = new Pressure(p, unit);
if(pres.getBar() < Global.lowPressure.getBar())
Global.lowPressure = (Pressure)pres.clone();
if(pres.getBar() > Global.lowPressure.getBar())
Global.highPressure = (Pressure)pres.clone();
}
//Global.pressure = new Pressure(p, unit);
}
//10/23/07 gmagoon: commenting out; further updates needed to get this to work
//else if (modelType.equals("Curved")) {
// // add reading curved pressure function here
// pressureModel = new CurvedPM(new LinkedList());
//}
else {
throw new InvalidSymbolException("condition.txt: Unknown PressureModel = " + modelType);
}
}
else throw new InvalidSymbolException("condition.txt: can't find PressureModel!");
// after PressureModel comes an optional line EquationOfState
// if "EquationOfState: Liquid" is found then initial concentrations are assumed to be correct
// if it is ommited, then initial concentrations are normalised to ensure PV=NRT (ideal gas law)
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("EquationOfState")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String eosType = st.nextToken();
if (eosType.equals("Liquid")) {
equationOfState="Liquid";
System.out.println("Equation of state: Liquid. Relying on concentrations in input file to get density correct; not checking PV=NRT");
}
line = ChemParser.readMeaningfulLine(reader);
}
// Read in InChI generation
if (line.startsWith("InChIGeneration:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String inchiOnOff = st.nextToken().toLowerCase();
if (inchiOnOff.equals("on")) {
Species.useInChI = true;
} else if (inchiOnOff.equals("off")) {
Species.useInChI = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown InChIGeneration flag: " + inchiOnOff);
line = ChemParser.readMeaningfulLine(reader);
}
// Read in Solvation effects
if (line.startsWith("Solvation:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String solvationOnOff = st.nextToken().toLowerCase();
if (solvationOnOff.equals("on")) {
Species.useSolvation = true;
} else if (solvationOnOff.equals("off")) {
Species.useSolvation = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
line = ChemParser.readMeaningfulLine(reader);
}
//line = ChemParser.readMeaningfulLine(reader);//read in reactants or thermo line
// Read in optional QM thermo generation
if (line.startsWith("ThermoMethod:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String thermoMethod = st.nextToken().toLowerCase();
if (thermoMethod.equals("qm")) {
ChemGraph.useQM = true;
line=ChemParser.readMeaningfulLine(reader);
if(line.startsWith("QMForCyclicsOnly:")){
StringTokenizer st2 = new StringTokenizer(line);
String nameCyc = st2.nextToken();
String option = st2.nextToken().toLowerCase();
if (option.equals("on")) {
ChemGraph.useQMonCyclicsOnly = true;
}
}
else{
System.out.println("condition.txt: Can't find 'QMForCyclicsOnly:' field");
System.exit(0);
}
line=ChemParser.readMeaningfulLine(reader);
if(line.startsWith("MaxRadNumForQM:")){
StringTokenizer st3 = new StringTokenizer(line);
String nameRadNum = st3.nextToken();
Global.maxRadNumForQM = Integer.parseInt(st3.nextToken());
}
else{
System.out.println("condition.txt: Can't find 'MaxRadNumForQM:' field");
System.exit(0);
}
}//otherwise, the flag useQM will remain false by default and the traditional group additivity approach will be used
line = ChemParser.readMeaningfulLine(reader);//read in reactants
}
// // Read in Solvation effects
// if (line.startsWith("Solvation:")) {
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String solvationOnOff = st.nextToken().toLowerCase();
// if (solvationOnOff.equals("on")) {
// Species.useSolvation = true;
// } else if (solvationOnOff.equals("off")) {
// Species.useSolvation = false;
// }
// else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
// }
// else throw new InvalidSymbolException("condition.txt: Cannot find solvation flag.");
// read in reactants
//
//10/4/07 gmagoon: moved to initializeCoreEdgeReactionModel
//LinkedHashSet p_speciesSeed = new LinkedHashSet();//gmagoon 10/4/07: changed to p_speciesSeed
//setSpeciesSeed(p_speciesSeed);//gmagoon 10/4/07: added
LinkedHashMap speciesSet = new LinkedHashMap();
LinkedHashMap speciesStatus = new LinkedHashMap();
int speciesnum = 1;
//System.out.println(line);
if (line.startsWith("InitialStatus")) {
line = ChemParser.readMeaningfulLine(reader);
while (!line.equals("END")) {
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String name = null;
if (!index.startsWith("(")) name = index;
else name = st.nextToken();
//if (restart) name += "("+speciesnum+")";
// 24Jun2009: MRH
// Check if the species name begins with a number.
// If so, terminate the program and inform the user to choose
// a different name. This is implemented so that the chem.inp
// file generated will be valid when run in Chemkin
try {
int doesNameBeginWithNumber = Integer.parseInt(name.substring(0,1));
System.out.println("\nA species name should not begin with a number." +
" Please rename species: " + name + "\n");
System.exit(0);
} catch (NumberFormatException e) {
// We're good
}
speciesnum ++;
if (!(st.hasMoreTokens())) throw new InvalidSymbolException("Couldn't find concentration of species: "+name);
String conc = st.nextToken();
double concentration = Double.parseDouble(conc);
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
concentration /= 1000;
unit = "mol/cm3";
}
else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
concentration /= 1000000;
unit = "mol/cm3";
}
else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
concentration /= 6.022e23;
}
else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
throw new InvalidUnitException("Species Concentration in condition.txt!");
}
//GJB to allow "unreactive" species that only follow user-defined library reactions.
// They will not react according to RMG reaction families
boolean IsReactive = true;
boolean IsConstantConcentration = false;
while (st.hasMoreTokens()) {
String reactive = st.nextToken().trim();
if (reactive.equalsIgnoreCase("unreactive"))
IsReactive = false;
if (reactive.equalsIgnoreCase("constantconcentration"))
IsConstantConcentration=true;
}
Graph g = ChemParser.readChemGraph(reader);
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
}
catch (ForbiddenStructureException e) {
System.out.println("Forbidden Structure:\n" + e.getMessage());
throw new InvalidSymbolException("A species in the input file has a forbidden structure.");
}
//System.out.println(name);
Species species = Species.make(name,cg);
species.setReactivity(IsReactive); // GJB
species.setConstantConcentration(IsConstantConcentration);
speciesSet.put(name, species);
getSpeciesSeed().add(species);
double flux = 0;
int species_type = 1; // reacted species
SpeciesStatus ss = new SpeciesStatus(species,species_type,concentration,flux);
speciesStatus.put(species, ss);
line = ChemParser.readMeaningfulLine(reader);
}
ReactionTime initial = new ReactionTime(0,"S");
//10/23/07 gmagoon: modified for handling multiple temperature, pressure conditions; note: concentration within speciesStatus (and list of conversion values) should not need to be modified for each T,P since this is done within isTPCconsistent in ReactionSystem
initialStatusList = new LinkedList();
for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
TemperatureModel tm = (TemperatureModel)iter.next();
for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
PressureModel pm = (PressureModel)iter2.next();
// LinkedHashMap speStat = (LinkedHashMap)speciesStatus.clone();//10/31/07 gmagoon: trying creating multiple instances of speciesStatus to address issues with concentration normalization (last normalization seems to apply to all)
Set ks = speciesStatus.keySet();
LinkedHashMap speStat = new LinkedHashMap();
for (Iterator iter3 = ks.iterator(); iter3.hasNext();){//11/1/07 gmagoon: perform deep copy; (is there an easier or more elegant way to do this?)
SpeciesStatus ssCopy = (SpeciesStatus)speciesStatus.get(iter3.next());
speStat.put(ssCopy.getSpecies(),new SpeciesStatus(ssCopy.getSpecies(),ssCopy.getSpeciesType(),ssCopy.getConcentration(),ssCopy.getFlux()));
}
initialStatusList.add(new InitialStatus(speStat,tm.getTemperature(initial),pm.getPressure(initial)));
}
}
}
else throw new InvalidSymbolException("condition.txt: can't find InitialStatus!");
// read in inert gas concentration
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("InertGas:")) {
line = ChemParser.readMeaningfulLine(reader);
while (!line.equals("END")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken().trim();
String conc = st.nextToken();
double inertConc = Double.parseDouble(conc);
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
inertConc /= 1000;
unit = "mol/cm3";
}
else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
inertConc /= 1000000;
unit = "mol/cm3";
}
else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
inertConc /= 6.022e23;
unit = "mol/cm3";
}
else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
throw new InvalidUnitException("Inert Gas Concentration not recognized: " + unit);
}
//SystemSnapshot.putInertGas(name,inertConc);
for(Iterator iter=initialStatusList.iterator();iter.hasNext(); ){//6/23/09 gmagoon: needed to change this to accommodate non-static inertConc
((InitialStatus)iter.next()).putInertGas(name,inertConc);
}
line = ChemParser.readMeaningfulLine(reader);
}
}
else throw new InvalidSymbolException("condition.txt: can't find Inert gas concentration!");
// read in spectroscopic data estimator
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("SpectroscopicDataEstimator:")) {
setSpectroscopicDataMode(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String sdeType = st.nextToken().toLowerCase();
// if (sdeType.equals("frequencygroups") || sdeType.equals("default")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
// }
// else if (sdeType.equals("therfit") || sdeType.equals("threefrequencymodel")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
// }
// else if (sdeType.equals("off") || sdeType.equals("none")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.OFF;
// }
// else throw new InvalidSymbolException("condition.txt: Unknown SpectroscopicDataEstimator = " + sdeType);
}
else throw new InvalidSymbolException("condition.txt: can't find SpectroscopicDataEstimator!");
// pressure dependence and related flags
line = ChemParser.readMeaningfulLine(reader);
if (line.toLowerCase().startsWith("pressuredependence:"))
line = setPressureDependenceOptions(line,reader);
else
throw new InvalidSymbolException("condition.txt: can't find PressureDependence flag!");
// include species (optional)
if (!PDepRateConstant.getMode().name().equals("CHEBYSHEV") &&
!PDepRateConstant.getMode().name().equals("PDEPARRHENIUS"))
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("IncludeSpecies")) {
StringTokenizer st = new StringTokenizer(line);
String iS = st.nextToken();
String fileName = st.nextToken();
HashSet includeSpecies = readIncludeSpecies(fileName);
((RateBasedRME)reactionModelEnlarger).addIncludeSpecies(includeSpecies);
line = ChemParser.readMeaningfulLine(reader);
}
// read in finish controller
if (line.startsWith("FinishController")) {
line = ChemParser.readMeaningfulLine(reader);
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String goal = st.nextToken();
String type = st.nextToken();
TerminationTester tt;
if (type.startsWith("Conversion")) {
LinkedList spc = new LinkedList();
while (st.hasMoreTokens()) {
String name = st.nextToken();
Species spe = (Species)speciesSet.get(name);
if (spe == null) throw new InvalidConversionException("Unknown reactant: " + name);
String conv = st.nextToken();
double conversion;
try {
if (conv.endsWith("%")) {
conversion = Double.parseDouble(conv.substring(0,conv.length()-1))/100;
}
else {
conversion = Double.parseDouble(conv);
}
conversionSet[49] = conversion;
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
SpeciesConversion sc = new SpeciesConversion(spe, conversion);
spc.add(sc);
}
tt = new ConversionTT(spc);
}
else if (type.startsWith("ReactionTime")) {
double time = Double.parseDouble(st.nextToken());
String unit = ChemParser.removeBrace(st.nextToken());
ReactionTime rt = new ReactionTime(time, unit);
tt = new ReactionTimeTT(rt);
}
else {
throw new InvalidSymbolException("condition.txt: Unknown FinishController = " + type);
}
line = ChemParser.readMeaningfulLine(reader);
st = new StringTokenizer(line, ":");
String temp = st.nextToken();
String tol = st.nextToken();
double tolerance;
try {
if (tol.endsWith("%")) {
tolerance = Double.parseDouble(tol.substring(0,tol.length()-1))/100;
}
else {
tolerance = Double.parseDouble(tol);
}
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
ValidityTester vt = null;
if (reactionModelEnlarger instanceof RateBasedRME) vt = new RateBasedVT(tolerance);
else if (reactionModelEnlarger instanceof RateBasedPDepRME) vt = new RateBasedPDepVT(tolerance);
else throw new InvalidReactionModelEnlargerException();
finishController = new FinishController(tt, vt);
}
else throw new InvalidSymbolException("condition.txt: can't find FinishController!");
// read in dynamic simulator
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("DynamicSimulator")) {
StringTokenizer st = new StringTokenizer(line,":");
String temp = st.nextToken();
String simulator = st.nextToken().trim();
//read in non-negative option if it exists: syntax would be something like this: "DynamicSimulator: DASSL: non-negative"
if (st.hasMoreTokens()){
if (st.nextToken().trim().toLowerCase().equals("non-negative")){
if(simulator.toLowerCase().equals("dassl")) JDAS.nonnegative = true;
else{
System.err.println("Non-negative option is currently only supported for DASSL. Switch to DASSL solver or remove non-negative option.");
System.exit(0);
}
}
}
numConversions = 0;//5/6/08 gmagoon: moved declaration from initializeReactionSystem() to be an attribute so it can be accessed by modelGenerator()
//int numConversions = 0;
boolean autoflag = false;//5/2/08 gmagoon: updating the following if/else-if block to consider input where we want to check model validity within the ODE solver at each time step; this will be indicated by the use of a string beginning with "AUTO" after the "TimeStep" or "Conversions" line
// read in time step
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("TimeStep:") && finishController.terminationTester instanceof ReactionTimeTT) {
st = new StringTokenizer(line);
temp = st.nextToken();
while (st.hasMoreTokens()) {
temp = st.nextToken();
if (temp.startsWith("AUTO")){//note potential opportunity for making case insensitive by using: temp.toUpperCase().startsWith("AUTO")
autoflag=true;
}
else if (!autoflag){//use "else if" to make sure additional numbers are not read in case numbers are erroneously used following AUTO; note that there could still be a problem if numbers come before "AUTO"
double tStep = Double.parseDouble(temp);
String unit = "sec";
setTimeStep(new ReactionTime(tStep, unit));
}
}
((ReactionTimeTT)finishController.terminationTester).setTimeSteps(timeStep);
}
else if (line.startsWith("Conversions:") && finishController.terminationTester instanceof ConversionTT){
st = new StringTokenizer(line);
temp = st.nextToken();
int i=0;
SpeciesConversion sc = (SpeciesConversion)((ConversionTT)finishController.terminationTester).speciesGoalConversionSet.get(0);
Species convSpecies = sc.species;
Iterator iter = ((InitialStatus)(initialStatusList.get(0))).getSpeciesStatus();//10/23/07 gmagoon: changed to use first element of initialStatusList, as subsequent operations should not be affected by which one is chosen
double initialConc = 0;
while (iter.hasNext()){
SpeciesStatus sps = (SpeciesStatus)iter.next();
if (sps.species.equals(convSpecies)) initialConc = sps.concentration;
}
while (st.hasMoreTokens()){
temp=st.nextToken();
if (temp.startsWith("AUTO")){
autoflag=true;
}
else if (!autoflag){
double conv = Double.parseDouble(temp);
conversionSet[i] = (1-conv) * initialConc;
i++;
}
}
conversionSet[i] = (1 - conversionSet[49])* initialConc;
numConversions = i+1;
}
else throw new InvalidSymbolException("condition.txt: can't find time step for dynamic simulator!");
// read in atol
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Atol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
atol = Double.parseDouble(st.nextToken());
}
else throw new InvalidSymbolException("condition.txt: can't find Atol for dynamic simulator!");
// read in rtol
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Rtol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
String rel_tol = st.nextToken();
if (rel_tol.endsWith("%"))
rtol = Double.parseDouble(rel_tol.substring(0,rel_tol.length()-1));
else
rtol = Double.parseDouble(rel_tol);
}
else throw new InvalidSymbolException("condition.txt: can't find Rtol for dynamic simulator!");
if (simulator.equals("DASPK")) {
paraInfor = 0;//svp
// read in SA
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Error bars")) {//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0) {
paraInfor = 1;
error = true;
}
else if (sa.compareToIgnoreCase("off")==0) {
paraInfor = 0;
error = false;
}
else throw new InvalidSymbolException("condition.txt: can't find error on/off information!");
}
else throw new InvalidSymbolException("condition.txt: can't find SA information!");
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Display sensitivity coefficients")){//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0){
paraInfor = 1;
sensitivity = true;
}
else if (sa.compareToIgnoreCase("off")==0){
if (paraInfor != 1){
paraInfor = 0;
}
sensitivity = false;
}
else throw new InvalidSymbolException("condition.txt: can't find SA on/off information!");
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
//6/25/08 gmagoon: changed loop to use i index, and updated DASPK constructor to pass i (mirroring changes to DASSL
//6/25/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i,finishController.getValidityTester(), autoflag));
}
}
species = new LinkedList();
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Display sensitivity information") ){
line = ChemParser.readMeaningfulLine(reader);
System.out.println(line);
while (!line.equals("END")){
st = new StringTokenizer(line);
String name = st.nextToken();
if (name.toUpperCase().equals("ALL")) ReactionSystem.printAllSens = true; //gmagoon 12/22/09: if the line contains the word "all", turn on the flag to print out sensitivity information for everything
species.add(name);
line = ChemParser.readMeaningfulLine(reader);
}
}
}
else if (simulator.equals("DASSL")) {
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
// for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
// dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)iter.next()));
// }
//11/1/07 gmagoon: changed loop to use i index, and updated DASSL constructor to pass i
//5/5/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i, finishController.getValidityTester(), autoflag));
}
}
else if (simulator.equals("Chemkin")) {
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("ReactorType")) {
st = new StringTokenizer(line, ":");
temp = st.nextToken();
String reactorType = st.nextToken().trim();
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
//dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)iter.next()));
dynamicSimulatorList.add(new Chemkin(rtol, atol, reactorType));//11/4/07 gmagoon: fixing apparent cut/paste error
}
}
}
else throw new InvalidSymbolException("condition.txt: Unknown DynamicSimulator = " + simulator);
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList; note: although conversionSet should actually be different for each T,P condition, it will be modified in isTPCconsistent within ReactionSystem
for (Iterator iter = dynamicSimulatorList.iterator(); iter.hasNext(); ) {
double [] cs = conversionSet.clone();//11/1/07 gmagoon: trying to make sure multiple instances of conversionSet are used
((DynamicSimulator)(iter.next())).addConversion(cs, numConversions);
}
}
| public void initializeReactionSystems() throws InvalidSymbolException, IOException {
//#[ operation initializeReactionSystem()
try {
String initialConditionFile = System.getProperty("jing.rxnSys.ReactionModelGenerator.conditionFile");
if (initialConditionFile == null) {
System.out.println("undefined system property: jing.rxnSys.ReactionModelGenerator.conditionFile");
System.exit(0);
}
//double sandeep = getCpuTime();
//System.out.println(getCpuTime()/1e9/60);
FileReader in = new FileReader(initialConditionFile);
BufferedReader reader = new BufferedReader(in);
//TemperatureModel temperatureModel = null;//10/27/07 gmagoon: commented out
//PressureModel pressureModel = null;//10/27/07 gmagoon: commented out
// ReactionModelEnlarger reactionModelEnlarger = null;//10/9/07 gmagoon: commented out: unneeded now and causes scope problems
FinishController finishController = null;
//DynamicSimulator dynamicSimulator = null;//10/27/07 gmagoon: commented out and replaced with following line
LinkedList dynamicSimulatorList = new LinkedList();
//PrimaryReactionLibrary primaryReactionLibrary = null;//10/14/07 gmagoon: see below
setPrimaryReactionLibrary(null);//10/14/07 gmagoon: changed to use setPrimaryReactionLibrary
double [] conversionSet = new double[50];
String line = ChemParser.readMeaningfulLine(reader);
/*if (line.startsWith("Restart")){
StringTokenizer st = new StringTokenizer(line);
String token = st.nextToken();
token = st.nextToken();
if (token.equalsIgnoreCase("true")) {
//Runtime.getRuntime().exec("cp Restart/allSpecies.txt Restart/allSpecies1.txt");
//Runtime.getRuntime().exec("echo >> allSpecies.txt");
restart = true;
}
else if (token.equalsIgnoreCase("false")) {
Runtime.getRuntime().exec("rm Restart/allSpecies.txt");
restart = false;
}
else throw new InvalidSymbolException("UnIdentified Symbol "+token+" after Restart:");
}
else throw new InvalidSymbolException("Can't find Restart!");*/
//line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Database")){//svp
line = ChemParser.readMeaningfulLine(reader);
}
else throw new InvalidSymbolException("Can't find database!");
// if (line.startsWith("PrimaryThermoLibrary")){//svp
// line = ChemParser.readMeaningfulLine(reader);
// }
// else throw new InvalidSymbolException("Can't find primary thermo library!");
/*
* Added by MRH on 15-Jun-2009
* Give user the option to change the maximum carbon, oxygen,
* and/or radical number for all species. These lines will be
* optional in the condition.txt file. Values are hard-
* coded into RMG (in ChemGraph.java), but any user-
* defined input will override these values.
*/
/*
* Moved from before InitialStatus to before PrimaryThermoLibary
* by MRH on 27-Oct-2009
* Overriding default values of maximum number of "X" per
* chemgraph should come before RMG attempts to make any
* chemgraph. The first instance RMG will attempt to make a
* chemgraph is in reading the primary thermo library.
*/
if (line.startsWith("MaxCarbonNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxCarbonNumberPerSpecies:"
int maxCNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxCarbonNumber(maxCNum);
System.out.println("Note: Overriding RMG-defined MAX_CARBON_NUM with user-defined value: " + maxCNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxOxygenNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxOxygenNumberPerSpecies:"
int maxONum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxOxygenNumber(maxONum);
System.out.println("Note: Overriding RMG-defined MAX_OXYGEN_NUM with user-defined value: " + maxONum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxRadicalNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxRadicalNumberPerSpecies:"
int maxRadNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxRadicalNumber(maxRadNum);
System.out.println("Note: Overriding RMG-defined MAX_RADICAL_NUM with user-defined value: " + maxRadNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxSulfurNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxSulfurNumberPerSpecies:"
int maxSNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxSulfurNumber(maxSNum);
System.out.println("Note: Overriding RMG-defined MAX_SULFUR_NUM with user-defined value: " + maxSNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxSiliconNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxSiliconNumberPerSpecies:"
int maxSiNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxSiliconNumber(maxSiNum);
System.out.println("Note: Overriding RMG-defined MAX_SILICON_NUM with user-defined value: " + maxSiNum);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.startsWith("MaxHeavyAtom")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxHeavyAtomPerSpecies:"
int maxHANum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxHeavyAtomNumber(maxHANum);
System.out.println("Note: Overriding RMG-defined MAX_HEAVYATOM_NUM with user-defined value: " + maxHANum);
line = ChemParser.readMeaningfulLine(reader);
}
/*
* Read in the Primary Thermo Library
* MRH 7-Jul-2009
*/
if (line.startsWith("PrimaryThermoLibrary:")) {
/*
* MRH 27Feb2010:
* Changing the "read in Primary Thermo Library information" code
* into it's own method.
*
* Other modules (e.g. PopulateReactions) will be utilizing the exact code.
* Rather than copying and pasting code into other modules, just have
* everything call this new method: readAndMakePTL
*/
readAndMakePTL(reader);
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate PrimaryThermoLibrary field");
line = ChemParser.readMeaningfulLine(reader);
// Extra forbidden structures may be specified after the Primary Thermo Library
if (line.startsWith("ForbiddenStructures:")) {
readExtraForbiddenStructures(reader);
line = ChemParser.readMeaningfulLine(reader);
}
if (line.toLowerCase().startsWith("readrestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "ReadRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes")) {
readrestart = true;
readRestartSpecies();
} else readrestart = false;
line = ChemParser.readMeaningfulLine(reader);
} else throw new InvalidSymbolException("Cannot locate ReadRestart field");
if (line.toLowerCase().startsWith("writerestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "WriteRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes"))
writerestart = true;
else writerestart = false;
line = ChemParser.readMeaningfulLine(reader);
} else throw new InvalidSymbolException("Cannot locate WriteRestart field");
// read temperature model
//gmagoon 10/23/07: modified to handle multiple temperatures; note that this requires different formatting of units in condition.txt
if (line.startsWith("TemperatureModel:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String modelType = st.nextToken();
//String t = st.nextToken();
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (modelType.equals("Constant")) {
tempList = new LinkedList();
//read first temperature
double t = Double.parseDouble(st.nextToken());
tempList.add(new ConstantTM(t, unit));
Temperature temp = new Temperature(t, unit);//10/29/07 gmagoon: added this line and next two lines to set Global.lowTemperature and Global.highTemperature
Global.lowTemperature = (Temperature)temp.clone();
Global.highTemperature = (Temperature)temp.clone();
//read remaining temperatures
while (st.hasMoreTokens()) {
t = Double.parseDouble(st.nextToken());
tempList.add(new ConstantTM(t, unit));
temp = new Temperature(t,unit);//10/29/07 gmagoon: added this line and next two "if" statements to set Global.lowTemperature and Global.highTemperature
if(temp.getK() < Global.lowTemperature.getK())
Global.lowTemperature = (Temperature)temp.clone();
if(temp.getK() > Global.highTemperature.getK())
Global.highTemperature = (Temperature)temp.clone();
}
// Global.temperature = new Temperature(t,unit);
}
//10/23/07 gmagoon: commenting out; further updates needed to get this to work
//else if (modelType.equals("Curved")) {
// String t = st.nextToken();
// // add reading curved temperature function here
// temperatureModel = new CurvedTM(new LinkedList());
//}
else {
throw new InvalidSymbolException("condition.txt: Unknown TemperatureModel = " + modelType);
}
}
else throw new InvalidSymbolException("condition.txt: can't find TemperatureModel!");
// read in pressure model
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("PressureModel:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String modelType = st.nextToken();
//String p = st.nextToken();
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (modelType.equals("Constant")) {
presList = new LinkedList();
//read first pressure
double p = Double.parseDouble(st.nextToken());
Pressure pres = new Pressure(p, unit);
Global.lowPressure = (Pressure)pres.clone();
Global.highPressure = (Pressure)pres.clone();
presList.add(new ConstantPM(p, unit));
//read remaining temperatures
while (st.hasMoreTokens()) {
p = Double.parseDouble(st.nextToken());
presList.add(new ConstantPM(p, unit));
pres = new Pressure(p, unit);
if(pres.getBar() < Global.lowPressure.getBar())
Global.lowPressure = (Pressure)pres.clone();
if(pres.getBar() > Global.lowPressure.getBar())
Global.highPressure = (Pressure)pres.clone();
}
//Global.pressure = new Pressure(p, unit);
}
//10/23/07 gmagoon: commenting out; further updates needed to get this to work
//else if (modelType.equals("Curved")) {
// // add reading curved pressure function here
// pressureModel = new CurvedPM(new LinkedList());
//}
else {
throw new InvalidSymbolException("condition.txt: Unknown PressureModel = " + modelType);
}
}
else throw new InvalidSymbolException("condition.txt: can't find PressureModel!");
// after PressureModel comes an optional line EquationOfState
// if "EquationOfState: Liquid" is found then initial concentrations are assumed to be correct
// if it is ommited, then initial concentrations are normalised to ensure PV=NRT (ideal gas law)
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("EquationOfState")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String eosType = st.nextToken();
if (eosType.equals("Liquid")) {
equationOfState="Liquid";
System.out.println("Equation of state: Liquid. Relying on concentrations in input file to get density correct; not checking PV=NRT");
}
line = ChemParser.readMeaningfulLine(reader);
}
// Read in InChI generation
if (line.startsWith("InChIGeneration:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String inchiOnOff = st.nextToken().toLowerCase();
if (inchiOnOff.equals("on")) {
Species.useInChI = true;
} else if (inchiOnOff.equals("off")) {
Species.useInChI = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown InChIGeneration flag: " + inchiOnOff);
line = ChemParser.readMeaningfulLine(reader);
}
// Read in Solvation effects
if (line.startsWith("Solvation:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String solvationOnOff = st.nextToken().toLowerCase();
if (solvationOnOff.equals("on")) {
Species.useSolvation = true;
} else if (solvationOnOff.equals("off")) {
Species.useSolvation = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
line = ChemParser.readMeaningfulLine(reader);
}
//line = ChemParser.readMeaningfulLine(reader);//read in reactants or thermo line
// Read in optional QM thermo generation
if (line.startsWith("ThermoMethod:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String thermoMethod = st.nextToken().toLowerCase();
if (thermoMethod.equals("qm")) {
ChemGraph.useQM = true;
line=ChemParser.readMeaningfulLine(reader);
if(line.startsWith("QMForCyclicsOnly:")){
StringTokenizer st2 = new StringTokenizer(line);
String nameCyc = st2.nextToken();
String option = st2.nextToken().toLowerCase();
if (option.equals("on")) {
ChemGraph.useQMonCyclicsOnly = true;
}
}
else{
System.out.println("condition.txt: Can't find 'QMForCyclicsOnly:' field");
System.exit(0);
}
line=ChemParser.readMeaningfulLine(reader);
if(line.startsWith("MaxRadNumForQM:")){
StringTokenizer st3 = new StringTokenizer(line);
String nameRadNum = st3.nextToken();
Global.maxRadNumForQM = Integer.parseInt(st3.nextToken());
}
else{
System.out.println("condition.txt: Can't find 'MaxRadNumForQM:' field");
System.exit(0);
}
}//otherwise, the flag useQM will remain false by default and the traditional group additivity approach will be used
line = ChemParser.readMeaningfulLine(reader);//read in reactants
}
// // Read in Solvation effects
// if (line.startsWith("Solvation:")) {
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String solvationOnOff = st.nextToken().toLowerCase();
// if (solvationOnOff.equals("on")) {
// Species.useSolvation = true;
// } else if (solvationOnOff.equals("off")) {
// Species.useSolvation = false;
// }
// else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
// }
// else throw new InvalidSymbolException("condition.txt: Cannot find solvation flag.");
// read in reactants
//
//10/4/07 gmagoon: moved to initializeCoreEdgeReactionModel
//LinkedHashSet p_speciesSeed = new LinkedHashSet();//gmagoon 10/4/07: changed to p_speciesSeed
//setSpeciesSeed(p_speciesSeed);//gmagoon 10/4/07: added
LinkedHashMap speciesSet = new LinkedHashMap();
LinkedHashMap speciesStatus = new LinkedHashMap();
int speciesnum = 1;
//System.out.println(line);
if (line.startsWith("InitialStatus")) {
line = ChemParser.readMeaningfulLine(reader);
while (!line.equals("END")) {
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String name = null;
if (!index.startsWith("(")) name = index;
else name = st.nextToken();
//if (restart) name += "("+speciesnum+")";
// 24Jun2009: MRH
// Check if the species name begins with a number.
// If so, terminate the program and inform the user to choose
// a different name. This is implemented so that the chem.inp
// file generated will be valid when run in Chemkin
try {
int doesNameBeginWithNumber = Integer.parseInt(name.substring(0,1));
System.out.println("\nA species name should not begin with a number." +
" Please rename species: " + name + "\n");
System.exit(0);
} catch (NumberFormatException e) {
// We're good
}
speciesnum ++;
if (!(st.hasMoreTokens())) throw new InvalidSymbolException("Couldn't find concentration of species: "+name);
String conc = st.nextToken();
double concentration = Double.parseDouble(conc);
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
concentration /= 1000;
unit = "mol/cm3";
}
else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
concentration /= 1000000;
unit = "mol/cm3";
}
else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
concentration /= 6.022e23;
}
else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
throw new InvalidUnitException("Species Concentration in condition.txt!");
}
//GJB to allow "unreactive" species that only follow user-defined library reactions.
// They will not react according to RMG reaction families
boolean IsReactive = true;
boolean IsConstantConcentration = false;
while (st.hasMoreTokens()) {
String reactive = st.nextToken().trim();
if (reactive.equalsIgnoreCase("unreactive"))
IsReactive = false;
if (reactive.equalsIgnoreCase("constantconcentration"))
IsConstantConcentration=true;
}
Graph g = ChemParser.readChemGraph(reader);
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
}
catch (ForbiddenStructureException e) {
System.out.println("Forbidden Structure:\n" + e.getMessage());
throw new InvalidSymbolException("A species in the input file has a forbidden structure.");
}
//System.out.println(name);
Species species = Species.make(name,cg);
species.setReactivity(IsReactive); // GJB
species.setConstantConcentration(IsConstantConcentration);
speciesSet.put(name, species);
getSpeciesSeed().add(species);
double flux = 0;
int species_type = 1; // reacted species
SpeciesStatus ss = new SpeciesStatus(species,species_type,concentration,flux);
speciesStatus.put(species, ss);
line = ChemParser.readMeaningfulLine(reader);
}
ReactionTime initial = new ReactionTime(0,"S");
//10/23/07 gmagoon: modified for handling multiple temperature, pressure conditions; note: concentration within speciesStatus (and list of conversion values) should not need to be modified for each T,P since this is done within isTPCconsistent in ReactionSystem
initialStatusList = new LinkedList();
for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
TemperatureModel tm = (TemperatureModel)iter.next();
for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
PressureModel pm = (PressureModel)iter2.next();
// LinkedHashMap speStat = (LinkedHashMap)speciesStatus.clone();//10/31/07 gmagoon: trying creating multiple instances of speciesStatus to address issues with concentration normalization (last normalization seems to apply to all)
Set ks = speciesStatus.keySet();
LinkedHashMap speStat = new LinkedHashMap();
for (Iterator iter3 = ks.iterator(); iter3.hasNext();){//11/1/07 gmagoon: perform deep copy; (is there an easier or more elegant way to do this?)
SpeciesStatus ssCopy = (SpeciesStatus)speciesStatus.get(iter3.next());
speStat.put(ssCopy.getSpecies(),new SpeciesStatus(ssCopy.getSpecies(),ssCopy.getSpeciesType(),ssCopy.getConcentration(),ssCopy.getFlux()));
}
initialStatusList.add(new InitialStatus(speStat,tm.getTemperature(initial),pm.getPressure(initial)));
}
}
}
else throw new InvalidSymbolException("condition.txt: can't find InitialStatus!");
// read in inert gas concentration
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("InertGas:")) {
line = ChemParser.readMeaningfulLine(reader);
while (!line.equals("END")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken().trim();
String conc = st.nextToken();
double inertConc = Double.parseDouble(conc);
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
inertConc /= 1000;
unit = "mol/cm3";
}
else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
inertConc /= 1000000;
unit = "mol/cm3";
}
else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
inertConc /= 6.022e23;
unit = "mol/cm3";
}
else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
throw new InvalidUnitException("Inert Gas Concentration not recognized: " + unit);
}
//SystemSnapshot.putInertGas(name,inertConc);
for(Iterator iter=initialStatusList.iterator();iter.hasNext(); ){//6/23/09 gmagoon: needed to change this to accommodate non-static inertConc
((InitialStatus)iter.next()).putInertGas(name,inertConc);
}
line = ChemParser.readMeaningfulLine(reader);
}
}
else throw new InvalidSymbolException("condition.txt: can't find Inert gas concentration!");
// read in spectroscopic data estimator
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("SpectroscopicDataEstimator:")) {
setSpectroscopicDataMode(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String sdeType = st.nextToken().toLowerCase();
// if (sdeType.equals("frequencygroups") || sdeType.equals("default")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
// }
// else if (sdeType.equals("therfit") || sdeType.equals("threefrequencymodel")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
// }
// else if (sdeType.equals("off") || sdeType.equals("none")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.OFF;
// }
// else throw new InvalidSymbolException("condition.txt: Unknown SpectroscopicDataEstimator = " + sdeType);
}
else throw new InvalidSymbolException("condition.txt: can't find SpectroscopicDataEstimator!");
// pressure dependence and related flags
line = ChemParser.readMeaningfulLine(reader);
if (line.toLowerCase().startsWith("pressuredependence:"))
line = setPressureDependenceOptions(line,reader);
else
throw new InvalidSymbolException("condition.txt: can't find PressureDependence flag!");
// include species (optional)
/*
*
* MRH 3-APR-2010:
* This if statement is no longer necessary and was causing an error
* when the PressureDependence field was set to "off"
*/
// if (!PDepRateConstant.getMode().name().equals("CHEBYSHEV") &&
// !PDepRateConstant.getMode().name().equals("PDEPARRHENIUS"))
// line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("IncludeSpecies")) {
StringTokenizer st = new StringTokenizer(line);
String iS = st.nextToken();
String fileName = st.nextToken();
HashSet includeSpecies = readIncludeSpecies(fileName);
((RateBasedRME)reactionModelEnlarger).addIncludeSpecies(includeSpecies);
line = ChemParser.readMeaningfulLine(reader);
}
// read in finish controller
if (line.startsWith("FinishController")) {
line = ChemParser.readMeaningfulLine(reader);
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String goal = st.nextToken();
String type = st.nextToken();
TerminationTester tt;
if (type.startsWith("Conversion")) {
LinkedList spc = new LinkedList();
while (st.hasMoreTokens()) {
String name = st.nextToken();
Species spe = (Species)speciesSet.get(name);
if (spe == null) throw new InvalidConversionException("Unknown reactant: " + name);
String conv = st.nextToken();
double conversion;
try {
if (conv.endsWith("%")) {
conversion = Double.parseDouble(conv.substring(0,conv.length()-1))/100;
}
else {
conversion = Double.parseDouble(conv);
}
conversionSet[49] = conversion;
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
SpeciesConversion sc = new SpeciesConversion(spe, conversion);
spc.add(sc);
}
tt = new ConversionTT(spc);
}
else if (type.startsWith("ReactionTime")) {
double time = Double.parseDouble(st.nextToken());
String unit = ChemParser.removeBrace(st.nextToken());
ReactionTime rt = new ReactionTime(time, unit);
tt = new ReactionTimeTT(rt);
}
else {
throw new InvalidSymbolException("condition.txt: Unknown FinishController = " + type);
}
line = ChemParser.readMeaningfulLine(reader);
st = new StringTokenizer(line, ":");
String temp = st.nextToken();
String tol = st.nextToken();
double tolerance;
try {
if (tol.endsWith("%")) {
tolerance = Double.parseDouble(tol.substring(0,tol.length()-1))/100;
}
else {
tolerance = Double.parseDouble(tol);
}
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
ValidityTester vt = null;
if (reactionModelEnlarger instanceof RateBasedRME) vt = new RateBasedVT(tolerance);
else if (reactionModelEnlarger instanceof RateBasedPDepRME) vt = new RateBasedPDepVT(tolerance);
else throw new InvalidReactionModelEnlargerException();
finishController = new FinishController(tt, vt);
}
else throw new InvalidSymbolException("condition.txt: can't find FinishController!");
// read in dynamic simulator
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("DynamicSimulator")) {
StringTokenizer st = new StringTokenizer(line,":");
String temp = st.nextToken();
String simulator = st.nextToken().trim();
//read in non-negative option if it exists: syntax would be something like this: "DynamicSimulator: DASSL: non-negative"
if (st.hasMoreTokens()){
if (st.nextToken().trim().toLowerCase().equals("non-negative")){
if(simulator.toLowerCase().equals("dassl")) JDAS.nonnegative = true;
else{
System.err.println("Non-negative option is currently only supported for DASSL. Switch to DASSL solver or remove non-negative option.");
System.exit(0);
}
}
}
numConversions = 0;//5/6/08 gmagoon: moved declaration from initializeReactionSystem() to be an attribute so it can be accessed by modelGenerator()
//int numConversions = 0;
boolean autoflag = false;//5/2/08 gmagoon: updating the following if/else-if block to consider input where we want to check model validity within the ODE solver at each time step; this will be indicated by the use of a string beginning with "AUTO" after the "TimeStep" or "Conversions" line
// read in time step
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("TimeStep:") && finishController.terminationTester instanceof ReactionTimeTT) {
st = new StringTokenizer(line);
temp = st.nextToken();
while (st.hasMoreTokens()) {
temp = st.nextToken();
if (temp.startsWith("AUTO")){//note potential opportunity for making case insensitive by using: temp.toUpperCase().startsWith("AUTO")
autoflag=true;
}
else if (!autoflag){//use "else if" to make sure additional numbers are not read in case numbers are erroneously used following AUTO; note that there could still be a problem if numbers come before "AUTO"
double tStep = Double.parseDouble(temp);
String unit = "sec";
setTimeStep(new ReactionTime(tStep, unit));
}
}
((ReactionTimeTT)finishController.terminationTester).setTimeSteps(timeStep);
}
else if (line.startsWith("Conversions:") && finishController.terminationTester instanceof ConversionTT){
st = new StringTokenizer(line);
temp = st.nextToken();
int i=0;
SpeciesConversion sc = (SpeciesConversion)((ConversionTT)finishController.terminationTester).speciesGoalConversionSet.get(0);
Species convSpecies = sc.species;
Iterator iter = ((InitialStatus)(initialStatusList.get(0))).getSpeciesStatus();//10/23/07 gmagoon: changed to use first element of initialStatusList, as subsequent operations should not be affected by which one is chosen
double initialConc = 0;
while (iter.hasNext()){
SpeciesStatus sps = (SpeciesStatus)iter.next();
if (sps.species.equals(convSpecies)) initialConc = sps.concentration;
}
while (st.hasMoreTokens()){
temp=st.nextToken();
if (temp.startsWith("AUTO")){
autoflag=true;
}
else if (!autoflag){
double conv = Double.parseDouble(temp);
conversionSet[i] = (1-conv) * initialConc;
i++;
}
}
conversionSet[i] = (1 - conversionSet[49])* initialConc;
numConversions = i+1;
}
else throw new InvalidSymbolException("condition.txt: can't find time step for dynamic simulator!");
// read in atol
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Atol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
atol = Double.parseDouble(st.nextToken());
}
else throw new InvalidSymbolException("condition.txt: can't find Atol for dynamic simulator!");
// read in rtol
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Rtol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
String rel_tol = st.nextToken();
if (rel_tol.endsWith("%"))
rtol = Double.parseDouble(rel_tol.substring(0,rel_tol.length()-1));
else
rtol = Double.parseDouble(rel_tol);
}
else throw new InvalidSymbolException("condition.txt: can't find Rtol for dynamic simulator!");
if (simulator.equals("DASPK")) {
paraInfor = 0;//svp
// read in SA
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Error bars")) {//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0) {
paraInfor = 1;
error = true;
}
else if (sa.compareToIgnoreCase("off")==0) {
paraInfor = 0;
error = false;
}
else throw new InvalidSymbolException("condition.txt: can't find error on/off information!");
}
else throw new InvalidSymbolException("condition.txt: can't find SA information!");
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Display sensitivity coefficients")){//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0){
paraInfor = 1;
sensitivity = true;
}
else if (sa.compareToIgnoreCase("off")==0){
if (paraInfor != 1){
paraInfor = 0;
}
sensitivity = false;
}
else throw new InvalidSymbolException("condition.txt: can't find SA on/off information!");
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
//6/25/08 gmagoon: changed loop to use i index, and updated DASPK constructor to pass i (mirroring changes to DASSL
//6/25/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i,finishController.getValidityTester(), autoflag));
}
}
species = new LinkedList();
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Display sensitivity information") ){
line = ChemParser.readMeaningfulLine(reader);
System.out.println(line);
while (!line.equals("END")){
st = new StringTokenizer(line);
String name = st.nextToken();
if (name.toUpperCase().equals("ALL")) ReactionSystem.printAllSens = true; //gmagoon 12/22/09: if the line contains the word "all", turn on the flag to print out sensitivity information for everything
species.add(name);
line = ChemParser.readMeaningfulLine(reader);
}
}
}
else if (simulator.equals("DASSL")) {
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
// for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
// dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)iter.next()));
// }
//11/1/07 gmagoon: changed loop to use i index, and updated DASSL constructor to pass i
//5/5/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i, finishController.getValidityTester(), autoflag));
}
}
else if (simulator.equals("Chemkin")) {
line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("ReactorType")) {
st = new StringTokenizer(line, ":");
temp = st.nextToken();
String reactorType = st.nextToken().trim();
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
//dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)iter.next()));
dynamicSimulatorList.add(new Chemkin(rtol, atol, reactorType));//11/4/07 gmagoon: fixing apparent cut/paste error
}
}
}
else throw new InvalidSymbolException("condition.txt: Unknown DynamicSimulator = " + simulator);
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList; note: although conversionSet should actually be different for each T,P condition, it will be modified in isTPCconsistent within ReactionSystem
for (Iterator iter = dynamicSimulatorList.iterator(); iter.hasNext(); ) {
double [] cs = conversionSet.clone();//11/1/07 gmagoon: trying to make sure multiple instances of conversionSet are used
((DynamicSimulator)(iter.next())).addConversion(cs, numConversions);
}
}
|
diff --git a/calendar-service/src/main/java/org/exoplatform/calendar/service/CalendarSetting.java b/calendar-service/src/main/java/org/exoplatform/calendar/service/CalendarSetting.java
index a9cbe2fa..bc142c0a 100644
--- a/calendar-service/src/main/java/org/exoplatform/calendar/service/CalendarSetting.java
+++ b/calendar-service/src/main/java/org/exoplatform/calendar/service/CalendarSetting.java
@@ -1,256 +1,256 @@
/**
* Copyright (C) 2003-2007 eXo Platform SAS.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see<http://www.gnu.org/licenses/>.
**/
package org.exoplatform.calendar.service;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
/**
* Created by The eXo Platform SARL
* Author : Hung Nguyen
* [email protected]
* Jul 16, 2007
*/
public class CalendarSetting {
// view types
public static String DAY_VIEW = "0";
public static String WEEK_VIEW = "1";
public static String MONTH_VIEW = "2";
public static String LIST_VIEW = "3";
public static String WORKING_VIEW = "4";
/**
* default value for one moving of event, task on UI. used when drag and drop.
*/
public final static long DEFAULT_TIME_INTERVAL = 30;
// time weekStartOn types
public static String SUNDAY = "1";
public static String MONDAY = "2";
public static String TUESDAY = "3";
public static String WENDNESDAY = "4";
public static String THURSDAY = "5";
public static String FRIDAY = "6";
public static String SATURDAY = "7";
public static String ACTION_ALWAYS = "always";
public static String ACTION_NEVER = "never";
public static String ACTION_ASK = "ask";
public static String ACTION_BYSETTING = "setting";
private String viewType;
private long timeInterval;
private String weekStartOn;
private String dateFormat;
private String timeFormat;
private String timeZone;
private String baseURL;
private boolean isShowWorkingTime = true;
private String workingTimeBegin;
private String workingTimeEnd;
private String[] sharedCalendarsColors;
private String[] filterPrivateCalendars;
private String[] filterPublicCalendars;
private String[] filterSharedCalendars;
private String sendOption;
public CalendarSetting() {
viewType = WORKING_VIEW;
timeInterval = DEFAULT_TIME_INTERVAL;
weekStartOn = String.valueOf(Calendar.SUNDAY);
dateFormat = "MM/dd/yyyy";
timeFormat = "hh:mm a";
isShowWorkingTime = true;
timeZone = TimeZone.getDefault().getID();
filterPrivateCalendars = new String[] {};
filterPublicCalendars = new String[] {};
filterSharedCalendars = new String[] {};
sharedCalendarsColors = new String[] {};
- sendOption = ACTION_ASK;
+ sendOption = ACTION_NEVER;
}
public void setViewType(String viewType) {
this.viewType = viewType;
}
public String getViewType() {
return viewType;
}
public void setTimeInterval(long timeInterval) {
this.timeInterval = timeInterval;
}
public long getTimeInterval() {
return timeInterval;
}
public void setWeekStartOn(String weekStartOn) {
this.weekStartOn = weekStartOn;
}
public String getWeekStartOn() {
return weekStartOn;
}
public void setDateFormat(String dFormat) {
dateFormat = dFormat;
}
public String getDateFormat() {
return dateFormat;
}
public void setTimeFormat(String timeFormat) {
this.timeFormat = timeFormat;
}
public String getTimeFormat() {
return timeFormat;
}
public void setBaseURL(String url) {
this.baseURL = url;
}
public String getBaseURL() {
return baseURL;
}
public void setFilterPrivateCalendars(String[] defaultCalendars) {
this.filterPrivateCalendars = defaultCalendars;
}
public String[] getFilterPrivateCalendars() {
return filterPrivateCalendars;
}
public void setFilterPublicCalendars(String[] defaultCalendars) {
this.filterPublicCalendars = defaultCalendars;
}
public String[] getFilterPublicCalendars() {
return filterPublicCalendars;
}
public void setShowWorkingTime(boolean isShowWorkingTime) {
this.isShowWorkingTime = isShowWorkingTime;
}
public boolean isShowWorkingTime() {
return isShowWorkingTime;
}
public void setWorkingTimeBegin(String workingTimeBegin) {
this.workingTimeBegin = workingTimeBegin;
}
public String getWorkingTimeBegin() {
return workingTimeBegin;
}
public void setWorkingTimeEnd(String workingTimeEnd) {
this.workingTimeEnd = workingTimeEnd;
}
public String getWorkingTimeEnd() {
return workingTimeEnd;
}
public void setTimeZone(String timeZone) {
this.timeZone = timeZone;
}
public String getTimeZone() {
return timeZone;
}
public void setSharedCalendarsColors(String[] sharedCalendarColor) {
sharedCalendarsColors = sharedCalendarColor;
}
public String[] getSharedCalendarsColors() {
return sharedCalendarsColors;
}
public void setFilterSharedCalendars(String[] sharedCalendars) {
filterSharedCalendars = sharedCalendars;
}
public String[] getFilterSharedCalendars() {
return filterSharedCalendars;
}
public void setSendOption(String option) {
sendOption = option;
}
public String getSendOption() {
return sendOption;
}
/**
* Create Calendar object which has the user preference (timezone, firstdayofweek, ...)
* @param time time in long
* @return calendar object
*/
public Calendar createCalendar(long time) {
Calendar c = GregorianCalendar.getInstance(TimeZone.getTimeZone(timeZone));
c.setFirstDayOfWeek(Integer.parseInt(weekStartOn));
c.setTimeInMillis(time);
c.setMinimalDaysInFirstWeek(4);
return c;
}
/**
* Create Calendar object which has the user preference (timezone, firstdayofweek, ...)
* @param time
* @return calendar object
*/
public Calendar createCalendar(Date time) {
return time != null ? createCalendar(time.getTime()) : null;
}
}
| true | true | public CalendarSetting() {
viewType = WORKING_VIEW;
timeInterval = DEFAULT_TIME_INTERVAL;
weekStartOn = String.valueOf(Calendar.SUNDAY);
dateFormat = "MM/dd/yyyy";
timeFormat = "hh:mm a";
isShowWorkingTime = true;
timeZone = TimeZone.getDefault().getID();
filterPrivateCalendars = new String[] {};
filterPublicCalendars = new String[] {};
filterSharedCalendars = new String[] {};
sharedCalendarsColors = new String[] {};
sendOption = ACTION_ASK;
}
| public CalendarSetting() {
viewType = WORKING_VIEW;
timeInterval = DEFAULT_TIME_INTERVAL;
weekStartOn = String.valueOf(Calendar.SUNDAY);
dateFormat = "MM/dd/yyyy";
timeFormat = "hh:mm a";
isShowWorkingTime = true;
timeZone = TimeZone.getDefault().getID();
filterPrivateCalendars = new String[] {};
filterPublicCalendars = new String[] {};
filterSharedCalendars = new String[] {};
sharedCalendarsColors = new String[] {};
sendOption = ACTION_NEVER;
}
|
diff --git a/org.rubypeople.rdt.ui/src/org/rubypeople/rdt/internal/ui/wizards/buildpaths/EditVariableEntryDialog.java b/org.rubypeople.rdt.ui/src/org/rubypeople/rdt/internal/ui/wizards/buildpaths/EditVariableEntryDialog.java
index 1214a6bb..b3b88d15 100644
--- a/org.rubypeople.rdt.ui/src/org/rubypeople/rdt/internal/ui/wizards/buildpaths/EditVariableEntryDialog.java
+++ b/org.rubypeople.rdt.ui/src/org/rubypeople/rdt/internal/ui/wizards/buildpaths/EditVariableEntryDialog.java
@@ -1,299 +1,299 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.rubypeople.rdt.internal.ui.wizards.buildpaths;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.StatusDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.rubypeople.rdt.core.RubyCore;
import org.rubypeople.rdt.internal.corext.util.Messages;
import org.rubypeople.rdt.internal.ui.IRubyHelpContextIds;
import org.rubypeople.rdt.internal.ui.dialogs.StatusInfo;
import org.rubypeople.rdt.internal.ui.wizards.NewWizardMessages;
import org.rubypeople.rdt.internal.ui.wizards.dialogfields.DialogField;
import org.rubypeople.rdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.rubypeople.rdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
import org.rubypeople.rdt.internal.ui.wizards.dialogfields.LayoutUtil;
/**
*/
public class EditVariableEntryDialog extends StatusDialog {
/**
* The path to which the archive variable points.
* Null if invalid path or not resolvable. Must not exist.
*/
private IPath fFileVariablePath;
private IStatus fNameStatus;
private Set fExistingEntries;
private VariablePathDialogField fFileNameField;
private CLabel fFullPathResolvedLabel;
/**
* Constructor for EditVariableEntryDialog.
* @param parent
*/
public EditVariableEntryDialog(Shell parent, IPath initialEntry, IPath[] existingEntries) {
super(parent);
setTitle(NewWizardMessages.EditVariableEntryDialog_title);
fExistingEntries= new HashSet();
if (existingEntries != null) {
for (int i = 0; i < existingEntries.length; i++) {
IPath curr= existingEntries[i];
if (!curr.equals(initialEntry)) {
fExistingEntries.add(curr);
}
}
}
SourceAttachmentAdapter adapter= new SourceAttachmentAdapter();
fFileNameField= new VariablePathDialogField(adapter);
fFileNameField.setDialogFieldListener(adapter);
fFileNameField.setLabelText(NewWizardMessages.EditVariableEntryDialog_filename_varlabel);
fFileNameField.setButtonLabel(NewWizardMessages.EditVariableEntryDialog_filename_external_varbutton);
fFileNameField.setVariableButtonLabel(NewWizardMessages.EditVariableEntryDialog_filename_variable_button);
String initialString= initialEntry != null ? initialEntry.toString() : ""; //$NON-NLS-1$
fFileNameField.setText(initialString);
}
public IPath getPath() {
return Path.fromOSString(fFileNameField.getText());
}
/* (non-Rubydoc)
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
protected Control createDialogArea(Composite parent) {
initializeDialogUnits(parent);
Composite composite= (Composite) super.createDialogArea(parent);
GridLayout layout= (GridLayout) composite.getLayout();
layout.numColumns= 3;
int widthHint= convertWidthInCharsToPixels(50);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 3;
// archive name field
fFileNameField.doFillIntoGrid(composite, 4);
LayoutUtil.setHorizontalSpan(fFileNameField.getLabelControl(null), 3);
LayoutUtil.setWidthHint(fFileNameField.getTextControl(null), widthHint);
LayoutUtil.setHorizontalGrabbing(fFileNameField.getTextControl(null));
// label that shows the resolved path for variable jars
//DialogField.createEmptySpace(composite, 1);
fFullPathResolvedLabel= new CLabel(composite, SWT.LEFT);
fFullPathResolvedLabel.setText(getResolvedLabelString());
fFullPathResolvedLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
DialogField.createEmptySpace(composite, 2);
fFileNameField.postSetFocusOnDialogField(parent.getDisplay());
PlatformUI.getWorkbench().getHelpSystem().setHelp(composite, IRubyHelpContextIds.SOURCE_ATTACHMENT_BLOCK);
applyDialogFont(composite);
return composite;
}
private class SourceAttachmentAdapter implements IStringButtonAdapter, IDialogFieldListener {
// -------- IStringButtonAdapter --------
public void changeControlPressed(DialogField field) {
attachmentChangeControlPressed(field);
}
// ---------- IDialogFieldListener --------
public void dialogFieldChanged(DialogField field) {
attachmentDialogFieldChanged(field);
}
}
private void attachmentChangeControlPressed(DialogField field) {
// if (field == fFileNameField) {
// IPath jarFilePath= chooseExtJarFile();
// if (jarFilePath != null) {
// fFileNameField.setText(jarFilePath.toString());
// }
// }
}
// ---------- IDialogFieldListener --------
private void attachmentDialogFieldChanged(DialogField field) {
if (field == fFileNameField) {
fNameStatus= updateFileNameStatus();
}
doStatusLineUpdate();
}
// private IPath chooseExtJarFile() {
// IPath currPath= getPath();
// IPath resolvedPath= getResolvedPath(currPath);
// File initialSelection= resolvedPath != null ? resolvedPath.toFile() : null;
//
// String currVariable= currPath.segment(0);
// JARFileSelectionDialog dialog= new JARFileSelectionDialog(getShell(), false, false);
// dialog.setTitle(NewWizardMessages.EditVariableEntryDialog_extvardialog_title);
// dialog.setMessage(NewWizardMessages.EditVariableEntryDialog_extvardialog_description);
// dialog.setInput(fFileVariablePath.toFile());
// dialog.setInitialSelection(initialSelection);
// if (dialog.open() == Window.OK) {
// File result= (File) dialog.getResult()[0];
// IPath returnPath= Path.fromOSString(result.getPath()).makeAbsolute();
// return modifyPath(returnPath, currVariable);
// }
// return null;
// }
private IPath getResolvedPath(IPath path) {
if (path != null) {
String varName= path.segment(0);
if (varName != null) {
IPath varPath= RubyCore.getLoadpathVariable(varName);
if (varPath != null) {
return varPath.append(path.removeFirstSegments(1));
}
}
}
return null;
}
/**
* Takes a path and replaces the beginning with a variable name
* (if the beginning matches with the variables value)
*/
private IPath modifyPath(IPath path, String varName) {
if (varName == null || path == null) {
return null;
}
if (path.isEmpty()) {
return new Path(varName);
}
IPath varPath= RubyCore.getLoadpathVariable(varName);
if (varPath != null) {
if (varPath.isPrefixOf(path)) {
path= path.removeFirstSegments(varPath.segmentCount());
} else {
path= new Path(path.lastSegment());
}
} else {
path= new Path(path.lastSegment());
}
return new Path(varName).append(path);
}
private IStatus updateFileNameStatus() {
StatusInfo status= new StatusInfo();
fFileVariablePath= null;
String fileName= fFileNameField.getText();
if (fileName.length() == 0) {
status.setError(NewWizardMessages.EditVariableEntryDialog_filename_empty);
return status;
} else {
if (!Path.EMPTY.isValidPath(fileName)) {
status.setError(NewWizardMessages.EditVariableEntryDialog_filename_error_notvalid);
return status;
}
IPath filePath= Path.fromOSString(fileName);
IPath resolvedPath;
if (filePath.getDevice() != null) {
status.setError(NewWizardMessages.EditVariableEntryDialog_filename_error_deviceinpath);
return status;
}
String varName= filePath.segment(0);
if (varName == null) {
status.setError(NewWizardMessages.EditVariableEntryDialog_filename_error_notvalid);
return status;
}
fFileVariablePath= RubyCore.getLoadpathVariable(varName);
if (fFileVariablePath == null) {
status.setError(NewWizardMessages.EditVariableEntryDialog_filename_error_varnotexists);
return status;
}
resolvedPath= fFileVariablePath.append(filePath.removeFirstSegments(1));
if (resolvedPath.isEmpty()) {
status.setWarning(NewWizardMessages.EditVariableEntryDialog_filename_warning_varempty);
return status;
}
File file= resolvedPath.toFile();
- if (!file.isFile()) {
+ if (!file.isDirectory()) {
String message= Messages.format(NewWizardMessages.EditVariableEntryDialog_filename_error_filenotexists, resolvedPath.toOSString());
status.setInfo(message);
return status;
}
}
return status;
}
private String getResolvedLabelString() {
IPath resolvedPath= getResolvedPath(getPath());
if (resolvedPath != null) {
return resolvedPath.toOSString();
}
return ""; //$NON-NLS-1$
}
private boolean canBrowseFileName() {
// to browse with a variable JAR, the variable name must point to a directory
if (fFileVariablePath != null) {
return fFileVariablePath.toFile().isDirectory();
}
return false;
}
private void doStatusLineUpdate() {
fFileNameField.enableButton(canBrowseFileName());
// set the resolved path for variable jars
if (fFullPathResolvedLabel != null) {
fFullPathResolvedLabel.setText(getResolvedLabelString());
}
IStatus status= fNameStatus;
if (!status.matches(IStatus.ERROR)) {
IPath path= getPath();
if (fExistingEntries.contains(path)) {
String message= NewWizardMessages.EditVariableEntryDialog_filename_error_alreadyexists;
status= new StatusInfo(IStatus.ERROR, message);
}
}
updateStatus(status);
}
}
| true | true | private IStatus updateFileNameStatus() {
StatusInfo status= new StatusInfo();
fFileVariablePath= null;
String fileName= fFileNameField.getText();
if (fileName.length() == 0) {
status.setError(NewWizardMessages.EditVariableEntryDialog_filename_empty);
return status;
} else {
if (!Path.EMPTY.isValidPath(fileName)) {
status.setError(NewWizardMessages.EditVariableEntryDialog_filename_error_notvalid);
return status;
}
IPath filePath= Path.fromOSString(fileName);
IPath resolvedPath;
if (filePath.getDevice() != null) {
status.setError(NewWizardMessages.EditVariableEntryDialog_filename_error_deviceinpath);
return status;
}
String varName= filePath.segment(0);
if (varName == null) {
status.setError(NewWizardMessages.EditVariableEntryDialog_filename_error_notvalid);
return status;
}
fFileVariablePath= RubyCore.getLoadpathVariable(varName);
if (fFileVariablePath == null) {
status.setError(NewWizardMessages.EditVariableEntryDialog_filename_error_varnotexists);
return status;
}
resolvedPath= fFileVariablePath.append(filePath.removeFirstSegments(1));
if (resolvedPath.isEmpty()) {
status.setWarning(NewWizardMessages.EditVariableEntryDialog_filename_warning_varempty);
return status;
}
File file= resolvedPath.toFile();
if (!file.isFile()) {
String message= Messages.format(NewWizardMessages.EditVariableEntryDialog_filename_error_filenotexists, resolvedPath.toOSString());
status.setInfo(message);
return status;
}
}
return status;
}
| private IStatus updateFileNameStatus() {
StatusInfo status= new StatusInfo();
fFileVariablePath= null;
String fileName= fFileNameField.getText();
if (fileName.length() == 0) {
status.setError(NewWizardMessages.EditVariableEntryDialog_filename_empty);
return status;
} else {
if (!Path.EMPTY.isValidPath(fileName)) {
status.setError(NewWizardMessages.EditVariableEntryDialog_filename_error_notvalid);
return status;
}
IPath filePath= Path.fromOSString(fileName);
IPath resolvedPath;
if (filePath.getDevice() != null) {
status.setError(NewWizardMessages.EditVariableEntryDialog_filename_error_deviceinpath);
return status;
}
String varName= filePath.segment(0);
if (varName == null) {
status.setError(NewWizardMessages.EditVariableEntryDialog_filename_error_notvalid);
return status;
}
fFileVariablePath= RubyCore.getLoadpathVariable(varName);
if (fFileVariablePath == null) {
status.setError(NewWizardMessages.EditVariableEntryDialog_filename_error_varnotexists);
return status;
}
resolvedPath= fFileVariablePath.append(filePath.removeFirstSegments(1));
if (resolvedPath.isEmpty()) {
status.setWarning(NewWizardMessages.EditVariableEntryDialog_filename_warning_varempty);
return status;
}
File file= resolvedPath.toFile();
if (!file.isDirectory()) {
String message= Messages.format(NewWizardMessages.EditVariableEntryDialog_filename_error_filenotexists, resolvedPath.toOSString());
status.setInfo(message);
return status;
}
}
return status;
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/launcher/RuntimeClasspathAdvancedDialog.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/launcher/RuntimeClasspathAdvancedDialog.java
index 88f052df0..942d44ea5 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/launcher/RuntimeClasspathAdvancedDialog.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/launcher/RuntimeClasspathAdvancedDialog.java
@@ -1,181 +1,187 @@
package org.eclipse.jdt.internal.debug.ui.launcher;
/*******************************************************************************
* Copyright (c) 2001, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin;
import org.eclipse.jdt.internal.debug.ui.actions.RuntimeClasspathAction;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.ClasspathContainerDescriptor;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.ClasspathContainerWizard;
import org.eclipse.jdt.launching.IRuntimeClasspathEntry;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
/**
* Dialog of radio buttons/actions for advanced classpath options.
*/
public class RuntimeClasspathAdvancedDialog extends Dialog {
private IAction[] fActions;
private Button[] fButtons;
private Button fAddContainerButton;
private Combo fContainerCombo;
private ClasspathContainerDescriptor[] fDescriptors;
private RuntimeClasspathViewer fViewer;
/**
* Constructs a new dialog on the given shell, with the specified
* set of actions.
*
* @param parentShell
* @param actions advanced actions
*/
public RuntimeClasspathAdvancedDialog(Shell parentShell, IAction[] actions, RuntimeClasspathViewer viewer) {
super(parentShell);
fActions = actions;
fViewer = viewer;
}
/**
* @see Dialog#createDialogArea(Composite)
*/
protected Control createDialogArea(Composite parent) {
Font font = parent.getFont();
initializeDialogUnits(parent);
Composite composite= (Composite) super.createDialogArea(parent);
Composite inner= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.makeColumnsEqualWidth = false;
layout.numColumns = 2;
layout.marginHeight= 0;
layout.marginWidth= 0;
inner.setLayout(layout);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
inner.setLayoutData(gd);
Label l = new Label(inner, SWT.NONE);
l.setText(LauncherMessages.getString("RuntimeClasspathAdvancedDialog.Select_an_advanced_option__1")); //$NON-NLS-1$
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 2;
l.setLayoutData(gd);
l.setFont(font);
fButtons = new Button[fActions.length];
for (int i = 0; i < fActions.length; i++) {
IAction action= fActions[i];
fButtons[i] = new Button(inner, SWT.RADIO);
fButtons[i].setText(action.getText());
fButtons[i].setData(action);
fButtons[i].setEnabled(action.isEnabled());
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 2;
fButtons[i].setLayoutData(gd);
fButtons[i].setFont(font);
}
fAddContainerButton = new Button(inner, SWT.RADIO);
fAddContainerButton.setText(LauncherMessages.getString("RuntimeClasspathAdvancedDialog.Add_&Container__1")); //$NON-NLS-1$
fAddContainerButton.setFont(font);
fContainerCombo = new Combo(inner, SWT.READ_ONLY);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.grabExcessHorizontalSpace = true;
- fContainerCombo.setLayoutData(gd);
fContainerCombo.setFont(font);
fDescriptors= ClasspathContainerDescriptor.getDescriptors();
String[] names= new String[fDescriptors.length];
+ int maxLength = 0;
for (int i = 0; i < names.length; i++) {
names[i]= fDescriptors[i].getName();
+ int length = names[i].length();
+ if (length > maxLength) {
+ maxLength = length;
+ }
}
fContainerCombo.setItems(names);
fContainerCombo.select(0);
+ gd = new GridData(GridData.FILL_HORIZONTAL);
+ gd.grabExcessHorizontalSpace = true;
+ gd.widthHint = convertWidthInCharsToPixels(maxLength + 5);
+ fContainerCombo.setLayoutData(gd);
new Label(inner, SWT.NONE);
getShell().setText(LauncherMessages.getString("RuntimeClasspathAdvancedDialog.Advanced_Options_1")); //$NON-NLS-1$
return composite;
}
/**
* @see Dialog#okPressed()
*/
protected void okPressed() {
if (fAddContainerButton.getSelection()) {
int index = fContainerCombo.getSelectionIndex();
IRuntimeClasspathEntry entry = chooseContainerEntry(fDescriptors[index]);
if (entry != null) {
// check if duplicate
int pos = fViewer.indexOf(entry);
if (pos == -1) {
fViewer.addEntries(new IRuntimeClasspathEntry[]{entry});
}
}
} else {
for (int i = 0; i < fButtons.length; i++) {
if (fButtons[i].getSelection()) {
IAction action = (IAction)fButtons[i].getData();
if (action instanceof RuntimeClasspathAction) {
((RuntimeClasspathAction)action).setShell(getShell());
}
action.run();
break;
}
}
}
super.okPressed();
}
private IRuntimeClasspathEntry chooseContainerEntry(ClasspathContainerDescriptor desc) {
IRuntimeClasspathEntry[] currentEntries = fViewer.getEntries();
IClasspathEntry[] entries = new IClasspathEntry[currentEntries.length];
for (int i = 0; i < entries.length; i++) {
entries[i]= currentEntries[i].getClasspathEntry();
}
ClasspathContainerWizard wizard= new ClasspathContainerWizard(desc, null, entries);
WizardDialog dialog= new WizardDialog(getShell(), wizard);
dialog.setMinimumPageSize(convertWidthInCharsToPixels(40), convertHeightInCharsToPixels(20));
dialog.create();
dialog.getShell().setText(LauncherMessages.getString("RuntimeClasspathAdvancedDialog.Select_Container_2")); //$NON-NLS-1$
if (dialog.open() == WizardDialog.OK) {
IClasspathEntry created= wizard.getNewEntry();
if (created != null) {
// XXX: kind needs to be resolved
try {
return JavaRuntime.newRuntimeContainerClasspathEntry(created.getPath(), IRuntimeClasspathEntry.STANDARD_CLASSES);
} catch (CoreException e) {
JDIDebugUIPlugin.errorDialog(LauncherMessages.getString("RuntimeClasspathAdvancedDialog.Unable_to_create_new_entry._3"), e); //$NON-NLS-1$
}
}
}
return null;
}
}
| false | true | protected Control createDialogArea(Composite parent) {
Font font = parent.getFont();
initializeDialogUnits(parent);
Composite composite= (Composite) super.createDialogArea(parent);
Composite inner= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.makeColumnsEqualWidth = false;
layout.numColumns = 2;
layout.marginHeight= 0;
layout.marginWidth= 0;
inner.setLayout(layout);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
inner.setLayoutData(gd);
Label l = new Label(inner, SWT.NONE);
l.setText(LauncherMessages.getString("RuntimeClasspathAdvancedDialog.Select_an_advanced_option__1")); //$NON-NLS-1$
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 2;
l.setLayoutData(gd);
l.setFont(font);
fButtons = new Button[fActions.length];
for (int i = 0; i < fActions.length; i++) {
IAction action= fActions[i];
fButtons[i] = new Button(inner, SWT.RADIO);
fButtons[i].setText(action.getText());
fButtons[i].setData(action);
fButtons[i].setEnabled(action.isEnabled());
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 2;
fButtons[i].setLayoutData(gd);
fButtons[i].setFont(font);
}
fAddContainerButton = new Button(inner, SWT.RADIO);
fAddContainerButton.setText(LauncherMessages.getString("RuntimeClasspathAdvancedDialog.Add_&Container__1")); //$NON-NLS-1$
fAddContainerButton.setFont(font);
fContainerCombo = new Combo(inner, SWT.READ_ONLY);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.grabExcessHorizontalSpace = true;
fContainerCombo.setLayoutData(gd);
fContainerCombo.setFont(font);
fDescriptors= ClasspathContainerDescriptor.getDescriptors();
String[] names= new String[fDescriptors.length];
for (int i = 0; i < names.length; i++) {
names[i]= fDescriptors[i].getName();
}
fContainerCombo.setItems(names);
fContainerCombo.select(0);
new Label(inner, SWT.NONE);
getShell().setText(LauncherMessages.getString("RuntimeClasspathAdvancedDialog.Advanced_Options_1")); //$NON-NLS-1$
return composite;
}
| protected Control createDialogArea(Composite parent) {
Font font = parent.getFont();
initializeDialogUnits(parent);
Composite composite= (Composite) super.createDialogArea(parent);
Composite inner= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.makeColumnsEqualWidth = false;
layout.numColumns = 2;
layout.marginHeight= 0;
layout.marginWidth= 0;
inner.setLayout(layout);
GridData gd = new GridData(GridData.FILL_HORIZONTAL);
inner.setLayoutData(gd);
Label l = new Label(inner, SWT.NONE);
l.setText(LauncherMessages.getString("RuntimeClasspathAdvancedDialog.Select_an_advanced_option__1")); //$NON-NLS-1$
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 2;
l.setLayoutData(gd);
l.setFont(font);
fButtons = new Button[fActions.length];
for (int i = 0; i < fActions.length; i++) {
IAction action= fActions[i];
fButtons[i] = new Button(inner, SWT.RADIO);
fButtons[i].setText(action.getText());
fButtons[i].setData(action);
fButtons[i].setEnabled(action.isEnabled());
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 2;
fButtons[i].setLayoutData(gd);
fButtons[i].setFont(font);
}
fAddContainerButton = new Button(inner, SWT.RADIO);
fAddContainerButton.setText(LauncherMessages.getString("RuntimeClasspathAdvancedDialog.Add_&Container__1")); //$NON-NLS-1$
fAddContainerButton.setFont(font);
fContainerCombo = new Combo(inner, SWT.READ_ONLY);
fContainerCombo.setFont(font);
fDescriptors= ClasspathContainerDescriptor.getDescriptors();
String[] names= new String[fDescriptors.length];
int maxLength = 0;
for (int i = 0; i < names.length; i++) {
names[i]= fDescriptors[i].getName();
int length = names[i].length();
if (length > maxLength) {
maxLength = length;
}
}
fContainerCombo.setItems(names);
fContainerCombo.select(0);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.grabExcessHorizontalSpace = true;
gd.widthHint = convertWidthInCharsToPixels(maxLength + 5);
fContainerCombo.setLayoutData(gd);
new Label(inner, SWT.NONE);
getShell().setText(LauncherMessages.getString("RuntimeClasspathAdvancedDialog.Advanced_Options_1")); //$NON-NLS-1$
return composite;
}
|
diff --git a/nuxeo-platform-forum/src/main/java/org/nuxeo/ecm/platform/forum/web/PostActionBean.java b/nuxeo-platform-forum/src/main/java/org/nuxeo/ecm/platform/forum/web/PostActionBean.java
index e95949fdd..7a8ad9a4a 100644
--- a/nuxeo-platform-forum/src/main/java/org/nuxeo/ecm/platform/forum/web/PostActionBean.java
+++ b/nuxeo-platform-forum/src/main/java/org/nuxeo/ecm/platform/forum/web/PostActionBean.java
@@ -1,625 +1,626 @@
/*
* (C) Copyright 2006-2007 Nuxeo SAS (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* ${user}
*
* $Id
*/
package org.nuxeo.ecm.platform.forum.web;
import java.io.Serializable;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.faces.application.FacesMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.RequestParameter;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.core.Events;
import org.nuxeo.ecm.core.api.Blob;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.CoreInstance;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentRef;
import org.nuxeo.ecm.core.api.IdRef;
import org.nuxeo.ecm.core.api.NuxeoPrincipal;
import org.nuxeo.ecm.core.api.event.CoreEvent;
import org.nuxeo.ecm.core.api.event.CoreEventConstants;
import org.nuxeo.ecm.core.api.event.impl.CoreEventImpl;
import org.nuxeo.ecm.core.api.security.SecurityConstants;
import org.nuxeo.ecm.platform.api.ECM;
import org.nuxeo.ecm.platform.api.login.SystemSession;
import org.nuxeo.ecm.platform.comment.web.CommentManagerActions;
import org.nuxeo.ecm.platform.events.api.DocumentMessage;
import org.nuxeo.ecm.platform.events.api.DocumentMessageProducer;
import org.nuxeo.ecm.platform.events.api.impl.DocumentMessageImpl;
import org.nuxeo.ecm.platform.forum.web.api.PostAction;
import org.nuxeo.ecm.platform.forum.web.api.ThreadAction;
import org.nuxeo.ecm.platform.forum.workflow.ForumConstants;
import org.nuxeo.ecm.platform.ui.web.api.NavigationContext;
import org.nuxeo.ecm.platform.util.RepositoryLocation;
import org.nuxeo.ecm.platform.workflow.api.client.events.EventNames;
import org.nuxeo.ecm.platform.workflow.api.client.wfmc.WAPI;
import org.nuxeo.ecm.platform.workflow.api.client.wfmc.WMActivityInstance;
import org.nuxeo.ecm.platform.workflow.api.client.wfmc.WMProcessDefinition;
import org.nuxeo.ecm.platform.workflow.api.client.wfmc.WMWorkItemInstance;
import org.nuxeo.ecm.platform.workflow.api.client.wfmc.WMWorkflowException;
import org.nuxeo.ecm.platform.workflow.api.client.wfmc.impl.WMParticipantImpl;
import org.nuxeo.ecm.platform.workflow.api.common.WorkflowConstants;
import org.nuxeo.ecm.platform.workflow.api.common.WorkflowEventCategories;
import org.nuxeo.ecm.platform.workflow.api.common.WorkflowEventTypes;
import org.nuxeo.ecm.platform.workflow.web.api.WorkflowBeansDelegate;
import org.nuxeo.ecm.webapp.base.InputController;
import org.nuxeo.ecm.webapp.dashboard.DashboardActions;
/**
* This action listener is used to create a Post inside a Thread and also to
* handle the moderation cycle on Post.
*
* @author <a href="[email protected]">Brice Chaffangeon</a>
*/
@Name("postAction")
@Scope(ScopeType.CONVERSATION)
public class PostActionBean extends InputController implements PostAction {
private static final long serialVersionUID = 1L;
private static final Log log = LogFactory.getLog(PostActionBean.class);
@In(required = false)
protected RepositoryLocation currentServerLocation;
@In(create = true)
protected WorkflowBeansDelegate workflowBeansDelegate;
@In(create = true)
protected NavigationContext navigationContext;
@In(create = true)
protected Principal currentUser;
@In(create = true)
protected CommentManagerActions commentManagerActions;
@In(create = true, required = false)
protected CoreSession documentManager;
@In(create = true)
protected ThreadAction threadAction;
// NXP-1360 need it to invalidate Dashboard
@In(required = false)
protected transient DashboardActions dashboardActions;
// the id of the comment to delete
@RequestParameter
protected String deletePostId;
private String title;
private String text;
private String filename;
private Blob fileContent;
static final String WRITE = "ReadWrite";
@Destroy
public void destroy() {
log.debug("Removing Seam action listener...");
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public Blob getFileContent() {
return fileContent;
}
public void setFileContent(Blob fileContent) {
this.fileContent = fileContent;
}
public boolean checkWritePermissionOnThread() {
boolean allowed;
try {
allowed = documentManager.hasPermission(
navigationContext.getCurrentDocument().getRef(), WRITE);
} catch (ClientException e) {
e.printStackTrace();
allowed = false;
}
return allowed;
}
/**
* Add the post to the thread and start the WF the moderation on the post
* created.
*/
public String addPost() throws ClientException, WMWorkflowException {
DocumentModel dm = documentManager.createDocumentModel("Post");
dm.setProperty("post", "author",
commentManagerActions.getPrincipalName());
dm.setProperty("post", "title", title);
dm.setProperty("post", "text", text);
dm.setProperty("post", "creationDate", new Date());
dm.setProperty("post", "filename", filename);
dm.setProperty("post", "fileContent", fileContent);
// this is the post we've just created
dm = commentManagerActions.addComment(dm);
/*
* NXP-1262 display the message only when about to publish
* facesMessages.add(FacesMessage.SEVERITY_INFO,
* resourcesAccessor.getMessages().get( "label.comment.added.sucess"));
*/
boolean publish = false;
// We start the moderation, only if the thread has the moderated
if (threadAction.isCurrentThreadModerated()) {
// if the user is not a moderator we warn him that his post won't be
// displayed
if (!threadAction.isPrincipalModerator()) {
// This will start the WF on our post
startModeration(dm);
facesMessages.add(FacesMessage.SEVERITY_INFO,
resourcesAccessor.getMessages().get(
"label.comment.waiting_approval"));
} else {
// If the user is a moderator, his post is automatically
// published
publish = true;
}
} else {
publish = true;
}
dm = documentManager.getDocument(dm.getRef());
if (publish) {
// NXP-1262 display the message only when about to publish
facesMessages.add(FacesMessage.SEVERITY_INFO,
resourcesAccessor.getMessages().get(
"label.comment.added.sucess"));
if (documentManager.hasPermission(dm.getRef(),
SecurityConstants.WRITE_LIFE_CYCLE)) {
documentManager.followTransition(dm.getRef(),
ForumConstants.TRANSITION_TO_PUBLISHED_STATE);
documentManager.save();
} else {
try {
// Here user only granted with read rights should be able to
// create a post.
SystemSession session = new SystemSession();
session.login();
// Open a new repository session which will be
// unrestricted. We need to do this here since the
// document manager in Seam context has been initialized
// with caller principal rights.
CoreSession unrestrictedSession = ECM.getPlatform().openRepository(
currentServerLocation.getName());
// Follow transition
unrestrictedSession.followTransition(dm.getRef(),
ForumConstants.TRANSITION_TO_PUBLISHED_STATE);
+ unrestrictedSession.save();
// Close the unrestricted session.
CoreInstance.getInstance().close(unrestrictedSession);
// Logout the system session.
// Note, this is not necessary to take further actions
// here regarding the user session.
session.logout();
} catch (Exception e) {
throw new ClientException(e.getMessage());
}
}
}
// To force comment manager to reload posts
Events.instance().raiseEvent(
org.nuxeo.ecm.webapp.helpers.EventNames.DOCUMENT_SELECTION_CHANGED);
cleanContextVariables();
return navigationContext.navigateToDocument(getParentThread());
}
public String deletePost() throws ClientException, WMWorkflowException {
DocumentModel post = documentManager.getDocument(new IdRef(deletePostId));
boolean deletionModerated = false;
if (threadAction.isCurrentThreadModerated()
&& ForumConstants.PENDING_STATE.equals(post.getCurrentLifeCycleState())) {
String pid = getPidFor(post);
if (pid != null) {
WAPI wapi = workflowBeansDelegate.getWAPIBean();
wapi.terminateProcessInstance(pid);
}
deletionModerated = true;
}
commentManagerActions.deleteComment(post.getRef().toString());
// NXP-1360 if moderation on
if (deletionModerated) {
// NXP-1360 signal post was deleted, invalidate user dashboard items
if (dashboardActions != null) {
try {
dashboardActions.invalidateDashboardItems();
} catch (ClientException e) {
throw new WMWorkflowException(e.getMessage());
}
}
}
return navigationContext.navigateToDocument(getParentThread());
}
public String cancelPost() throws ClientException {
cleanContextVariables();
commentManagerActions.cancelComment();
return navigationContext.navigateToDocument(getParentThread());
}
private void cleanContextVariables() {
fileContent = null;
filename = null;
text = null;
title = null;
}
/**
* Start the moderation on given Post.
*
* @param post
* @return
* @throws WMWorkflowException
* @throws ClientException
*/
public WMActivityInstance startModeration(DocumentModel post)
throws WMWorkflowException, ClientException {
List<String> moderators = getModeratorsOnParentThread();
WMActivityInstance workflowPath = null;
WAPI wapi = workflowBeansDelegate.getWAPIBean();
String processId = getModerationWorkflowId();
if (moderators == null || moderators.isEmpty()) {
log.error("Error : No moderators are defined on parent thread. Moderation won't start");
return null;
}
try {
Map<String, Serializable> vars = new HashMap<String, Serializable>();
vars.put(WorkflowConstants.DOCUMENT_REF, post.getRef());
vars.put(ForumConstants.THREAD_REF, getParentThread().getRef());
vars.put(ForumConstants.FORUM_MODERATORS_LIST,
threadAction.getModerators().toArray());
vars.put(WorkflowConstants.WORKFLOW_CREATOR, currentUser.getName());
vars.put(WorkflowConstants.DOCUMENT_LOCATION_URI,
post.getRepositoryName());
workflowPath = wapi.startProcess(processId, vars, null);
} catch (WMWorkflowException we) {
log.error("An error occurred while grabbing workflow definitions");
we.printStackTrace();
}
if (workflowPath != null) {
WMProcessDefinition def = wapi.getProcessDefinitionById(processId);
String name = def.getName();
notifyEvent(post, WorkflowEventTypes.WORKFLOW_STARTED, name, name);
Events.instance().raiseEvent(EventNames.WORKFLOW_NEW_STARTED);
}
return workflowPath;
}
/**
* Get the WF id associated to the moderation process.
*/
public String getModerationWorkflowId() throws WMWorkflowException {
WAPI wapi = workflowBeansDelegate.getWAPIBean();
return wapi.getProcessDefinitionByName(
ForumConstants.PROCESS_INSTANCE_NAME).getId();
}
/**
* Get the current task Id.
*
* @return
* @throws WMWorkflowException
*/
public Collection<WMWorkItemInstance> getCurrentTasksForPrincipal(
String name) throws WMWorkflowException {
WAPI wapi = workflowBeansDelegate.getWAPIBean();
Collection<WMWorkItemInstance> currentTasks = null;
if (name != null && !"".equals(name)) {
currentTasks = wapi.getWorkItemsFor(new WMParticipantImpl(
wapi.getParticipant().getName()), name);
}
return currentTasks;
}
public Collection<WMWorkItemInstance> getPublishTasksForPrincipal()
throws WMWorkflowException {
return getCurrentTasksForPrincipal(ForumConstants.PUBLISHED_STATE);
}
public Collection<WMWorkItemInstance> getPendingTasksForPrincipal()
throws WMWorkflowException {
return getCurrentTasksForPrincipal(ForumConstants.PENDING_STATE);
}
/**
* Ends the task on a post.
*/
public String approvePost(DocumentModel post) throws WMWorkflowException,
ClientException {
WAPI wapi = workflowBeansDelegate.getWAPIBean();
if (post != null) {
String weed = getWorkItemIdFor(post);
if (weed != null) {
wapi.endWorkItem(weed,
ForumConstants.PROCESS_TRANSITION_TO_PUBLISH);
}
}
// To force comment manager to reload posts
Events.instance().raiseEvent(
org.nuxeo.ecm.webapp.helpers.EventNames.DOCUMENT_SELECTION_CHANGED);
// NXP-1360 signal post was approved, invalidate user dashboard items
if (dashboardActions != null) {
try {
dashboardActions.invalidateDashboardItems();
} catch (ClientException e) {
throw new WMWorkflowException(e.getMessage());
}
}
return navigationContext.navigateToDocument(getParentThread());
}
public DocumentModel getParentThread() {
return navigationContext.getCurrentDocument();
}
public List<String> getModeratorsOnParentThread() {
ArrayList<String> moderators = (ArrayList<String>) getParentThread().getProperty(
"thread", "moderators");
if (moderators != null) {
return moderators;
}
return null;
}
/**
* Notify event to Core.
*
* @param doc
* @param eventId
* @param comment
* @param category
* @throws WMWorkflowException
* @throws ClientException
*/
protected void notifyEvent(DocumentModel doc, String eventId,
String comment, String category) throws WMWorkflowException,
ClientException {
log.info("NotifyEvent for post moderation");
DocumentMessageProducer producer = workflowBeansDelegate.getDocumentMessageProducer();
Map<String, Serializable> props = new HashMap<String, Serializable>();
props.put(CoreEventConstants.DOC_LIFE_CYCLE,
doc.getCurrentLifeCycleState());
CoreEvent event = new CoreEventImpl(eventId, doc, props, currentUser,
category != null ? category
: WorkflowEventCategories.EVENT_WORKFLOW_CATEGORY,
comment);
DocumentMessage msg = new DocumentMessageImpl(doc, event);
producer.produce(msg);
}
public boolean isPostPublished(DocumentModel post) throws ClientException {
boolean published = false;
if (post != null
&& ForumConstants.PUBLISHED_STATE.equals(post.getCurrentLifeCycleState())) {
published = true;
}
return published;
}
/**
* Get the title of the post for creation purpose. If the post to be created
* reply to a previous post, the title of the new post comes with the
* previous title, and a prefix (i.e : Re : Previous Title)
*/
public String getTitle() throws ClientException {
String previousId = commentManagerActions.getSavedReplyCommentId();
if (previousId != null && !"".equals(previousId)) {
DocumentModel previousPost = documentManager.getDocument(new IdRef(
previousId));
// Test to ensure that previous comment got the "post" schema
if (previousPost.getDataModel("post") != null) {
String previousTitle = (String) previousPost.getProperty(
"post", "title");
String prefix = resourcesAccessor.getMessages().get(
"label.forum.post.title.prefix");
title = prefix + previousTitle;
}
}
return title;
}
public void setTitle(String title) {
this.title = title;
}
private WMWorkItemInstance getWorkItemsForUserFrom(
Collection<WMWorkItemInstance> witems, DocumentModel post,
String principalName) throws WMWorkflowException {
WMWorkItemInstance witem = null;
WAPI wapi = workflowBeansDelegate.getWAPIBean();
for (WMWorkItemInstance item : witems) {
String pid = item.getProcessInstance().getId();
Map<String, Serializable> props = wapi.listProcessInstanceAttributes(pid);
DocumentRef ref = (DocumentRef) props.get(WorkflowConstants.DOCUMENT_REF);
if (ref != null && ref.equals(post.getRef())) {
witem = item;
break;
}
}
return witem;
}
private WMWorkItemInstance getWorkItemFor(DocumentModel post)
throws WMWorkflowException {
if (post == null) {
return null;
}
WAPI wapi = workflowBeansDelegate.getWAPIBean();
Collection<WMWorkItemInstance> witems = wapi.getWorkItemsFor(
new WMParticipantImpl(currentUser.getName()), null);
WMWorkItemInstance witem = getWorkItemsForUserFrom(witems, post,
currentUser.getName());
if (witem == null) {
// Group resolution.
if (currentUser instanceof NuxeoPrincipal) {
List<String> groupNames = ((NuxeoPrincipal) currentUser).getAllGroups();
for (String groupName : groupNames) {
witems = wapi.getWorkItemsFor(new WMParticipantImpl(
groupName), null);
witem = getWorkItemsForUserFrom(witems, post, groupName);
if (witem != null) {
break;
}
}
}
}
return witem;
}
private String getWorkItemIdFor(DocumentModel post)
throws WMWorkflowException {
String weed = null;
if (post == null) {
return weed;
}
WMWorkItemInstance item = getWorkItemFor(post);
if (item != null) {
weed = item.getId();
}
return weed;
}
private String getPidFor(DocumentModel post) throws WMWorkflowException {
String pid = null;
WMWorkItemInstance item = getWorkItemFor(post);
if (item != null) {
pid = item.getProcessInstance().getId();
}
return pid;
}
public String rejectPost(DocumentModel post) throws WMWorkflowException,
ClientException {
WAPI wapi = workflowBeansDelegate.getWAPIBean();
if (post != null) {
String weed = getWorkItemIdFor(post);
if (weed != null) {
wapi.endWorkItem(weed,
ForumConstants.PROCESS_TRANSITION_TO_REJECTED);
}
}
// To force comment manager to reload posts
Events.instance().raiseEvent(
org.nuxeo.ecm.webapp.helpers.EventNames.DOCUMENT_SELECTION_CHANGED);
// NXP-1360 signal post was rejected, invalidate user dashboard items
if (dashboardActions != null) {
try {
dashboardActions.invalidateDashboardItems();
} catch (ClientException e) {
throw new WMWorkflowException(e.getMessage());
}
}
return navigationContext.navigateToDocument(getParentThread());
}
}
| true | true | public String addPost() throws ClientException, WMWorkflowException {
DocumentModel dm = documentManager.createDocumentModel("Post");
dm.setProperty("post", "author",
commentManagerActions.getPrincipalName());
dm.setProperty("post", "title", title);
dm.setProperty("post", "text", text);
dm.setProperty("post", "creationDate", new Date());
dm.setProperty("post", "filename", filename);
dm.setProperty("post", "fileContent", fileContent);
// this is the post we've just created
dm = commentManagerActions.addComment(dm);
/*
* NXP-1262 display the message only when about to publish
* facesMessages.add(FacesMessage.SEVERITY_INFO,
* resourcesAccessor.getMessages().get( "label.comment.added.sucess"));
*/
boolean publish = false;
// We start the moderation, only if the thread has the moderated
if (threadAction.isCurrentThreadModerated()) {
// if the user is not a moderator we warn him that his post won't be
// displayed
if (!threadAction.isPrincipalModerator()) {
// This will start the WF on our post
startModeration(dm);
facesMessages.add(FacesMessage.SEVERITY_INFO,
resourcesAccessor.getMessages().get(
"label.comment.waiting_approval"));
} else {
// If the user is a moderator, his post is automatically
// published
publish = true;
}
} else {
publish = true;
}
dm = documentManager.getDocument(dm.getRef());
if (publish) {
// NXP-1262 display the message only when about to publish
facesMessages.add(FacesMessage.SEVERITY_INFO,
resourcesAccessor.getMessages().get(
"label.comment.added.sucess"));
if (documentManager.hasPermission(dm.getRef(),
SecurityConstants.WRITE_LIFE_CYCLE)) {
documentManager.followTransition(dm.getRef(),
ForumConstants.TRANSITION_TO_PUBLISHED_STATE);
documentManager.save();
} else {
try {
// Here user only granted with read rights should be able to
// create a post.
SystemSession session = new SystemSession();
session.login();
// Open a new repository session which will be
// unrestricted. We need to do this here since the
// document manager in Seam context has been initialized
// with caller principal rights.
CoreSession unrestrictedSession = ECM.getPlatform().openRepository(
currentServerLocation.getName());
// Follow transition
unrestrictedSession.followTransition(dm.getRef(),
ForumConstants.TRANSITION_TO_PUBLISHED_STATE);
// Close the unrestricted session.
CoreInstance.getInstance().close(unrestrictedSession);
// Logout the system session.
// Note, this is not necessary to take further actions
// here regarding the user session.
session.logout();
} catch (Exception e) {
throw new ClientException(e.getMessage());
}
}
}
// To force comment manager to reload posts
Events.instance().raiseEvent(
org.nuxeo.ecm.webapp.helpers.EventNames.DOCUMENT_SELECTION_CHANGED);
cleanContextVariables();
return navigationContext.navigateToDocument(getParentThread());
}
| public String addPost() throws ClientException, WMWorkflowException {
DocumentModel dm = documentManager.createDocumentModel("Post");
dm.setProperty("post", "author",
commentManagerActions.getPrincipalName());
dm.setProperty("post", "title", title);
dm.setProperty("post", "text", text);
dm.setProperty("post", "creationDate", new Date());
dm.setProperty("post", "filename", filename);
dm.setProperty("post", "fileContent", fileContent);
// this is the post we've just created
dm = commentManagerActions.addComment(dm);
/*
* NXP-1262 display the message only when about to publish
* facesMessages.add(FacesMessage.SEVERITY_INFO,
* resourcesAccessor.getMessages().get( "label.comment.added.sucess"));
*/
boolean publish = false;
// We start the moderation, only if the thread has the moderated
if (threadAction.isCurrentThreadModerated()) {
// if the user is not a moderator we warn him that his post won't be
// displayed
if (!threadAction.isPrincipalModerator()) {
// This will start the WF on our post
startModeration(dm);
facesMessages.add(FacesMessage.SEVERITY_INFO,
resourcesAccessor.getMessages().get(
"label.comment.waiting_approval"));
} else {
// If the user is a moderator, his post is automatically
// published
publish = true;
}
} else {
publish = true;
}
dm = documentManager.getDocument(dm.getRef());
if (publish) {
// NXP-1262 display the message only when about to publish
facesMessages.add(FacesMessage.SEVERITY_INFO,
resourcesAccessor.getMessages().get(
"label.comment.added.sucess"));
if (documentManager.hasPermission(dm.getRef(),
SecurityConstants.WRITE_LIFE_CYCLE)) {
documentManager.followTransition(dm.getRef(),
ForumConstants.TRANSITION_TO_PUBLISHED_STATE);
documentManager.save();
} else {
try {
// Here user only granted with read rights should be able to
// create a post.
SystemSession session = new SystemSession();
session.login();
// Open a new repository session which will be
// unrestricted. We need to do this here since the
// document manager in Seam context has been initialized
// with caller principal rights.
CoreSession unrestrictedSession = ECM.getPlatform().openRepository(
currentServerLocation.getName());
// Follow transition
unrestrictedSession.followTransition(dm.getRef(),
ForumConstants.TRANSITION_TO_PUBLISHED_STATE);
unrestrictedSession.save();
// Close the unrestricted session.
CoreInstance.getInstance().close(unrestrictedSession);
// Logout the system session.
// Note, this is not necessary to take further actions
// here regarding the user session.
session.logout();
} catch (Exception e) {
throw new ClientException(e.getMessage());
}
}
}
// To force comment manager to reload posts
Events.instance().raiseEvent(
org.nuxeo.ecm.webapp.helpers.EventNames.DOCUMENT_SELECTION_CHANGED);
cleanContextVariables();
return navigationContext.navigateToDocument(getParentThread());
}
|
diff --git a/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/BrowserVersion.java b/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/BrowserVersion.java
index 4a6f5e56c..d3a0ccc63 100644
--- a/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/BrowserVersion.java
+++ b/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/BrowserVersion.java
@@ -1,505 +1,507 @@
/*
* Copyright (c) 2002-2010 Gargoyle Software 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.gargoylesoftware.htmlunit;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
/**
* Objects of this class represent one specific version of a given browser. Predefined
* constants are provided for common browser versions.
*
* If you wish to create a BrowserVersion for a browser that doesn't have a constant defined
* but aren't sure what values to pass into the constructor then point your browser at
* <a href="http://htmlunit.sourceforge.net/cgi-bin/browserVersion">
* http://htmlunit.sourceforge.net/cgi-bin/browserVersion</a>
* and the code will be generated for you.
*
* @version $Revision$
* @author <a href="mailto:[email protected]">Mike Bowler</a>
* @author Daniel Gredler
* @author Marc Guillemot
* @author Chris Erskine
* @author Ahmed Ashour
*/
public class BrowserVersion implements Serializable {
private String applicationCodeName_ = APP_CODE_NAME;
private String applicationMinorVersion_ = "0";
private String applicationName_;
private String applicationVersion_;
private String browserLanguage_ = LANGUAGE_ENGLISH_US;
private String cpuClass_ = CPU_CLASS_X86;
private boolean onLine_ = true;
private String platform_ = PLATFORM_WIN32;
private String systemLanguage_ = LANGUAGE_ENGLISH_US;
private String userAgent_;
private String userLanguage_ = LANGUAGE_ENGLISH_US;
private float browserVersionNumeric_;
private Set<PluginConfiguration> plugins_ = new HashSet<PluginConfiguration>();
private final List<BrowserVersionFeatures> features_ = new ArrayList<BrowserVersionFeatures>();
private final String nickname_;
/**
* Application code name for both Internet Explorer and Netscape series.
* @deprecated as of 2.8, without replacement
*/
@Deprecated
public static final String APP_CODE_NAME = "Mozilla";
/**
* Application name for the Internet Explorer series of browsers.
* @deprecated as of 2.8, without replacement
*/
@Deprecated
public static final String INTERNET_EXPLORER = "Microsoft Internet Explorer";
/**
* Application name the Netscape navigator series of browsers.
* @deprecated as of 2.8, without replacement
*/
@Deprecated
public static final String NETSCAPE = "Netscape";
/**
* United States English language identifier.
* @deprecated as of 2.8, without replacement
*/
@Deprecated
public static final String LANGUAGE_ENGLISH_US = "en-us";
/**
* The X86 CPU class.
* @deprecated as of 2.8, without replacement
*/
@Deprecated
public static final String CPU_CLASS_X86 = "x86";
/**
* The WIN32 platform.
* @deprecated as of 2.8, without replacement
*/
@Deprecated
public static final String PLATFORM_WIN32 = "Win32";
/**
* Firefox 3.0.
* @deprecated since HtmlUnit-2.9. This means that no effort will be made to improve
* simulation for this browser version until it is definitely removed.
*/
@Deprecated
public static final BrowserVersion FIREFOX_3 = new BrowserVersion(
NETSCAPE, "5.0 (Windows; en-US)",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.19) Gecko/2010031422 Firefox/3.0.19",
3, "FF3", null);
/** Firefox 3.6. */
public static final BrowserVersion FIREFOX_3_6 = new BrowserVersion(
NETSCAPE, "5.0 (Windows; en-US)",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8",
(float) 3.6, "FF3.6", null);
/** Internet Explorer 6. */
public static final BrowserVersion INTERNET_EXPLORER_6 = new BrowserVersion(
INTERNET_EXPLORER, "4.0 (compatible; MSIE 6.0b; Windows 98)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows 98)", 6, "IE6", null);
/** Internet Explorer 7. */
public static final BrowserVersion INTERNET_EXPLORER_7 = new BrowserVersion(
INTERNET_EXPLORER, "4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)", 7, "IE7", null);
/** Internet Explorer 8. */
public static final BrowserVersion INTERNET_EXPLORER_8 = new BrowserVersion(
INTERNET_EXPLORER, "4.0 (compatible; MSIE 8.0; Windows NT 6.0)",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)", 8, "IE8", null);
/** The default browser version. */
private static BrowserVersion DefaultBrowserVersion_ = INTERNET_EXPLORER_7;
/** Register plugins for the Firefox browser versions. */
static {
INTERNET_EXPLORER_6.initDefaultFeatures();
INTERNET_EXPLORER_7.initDefaultFeatures();
INTERNET_EXPLORER_8.initDefaultFeatures();
FIREFOX_3.initDefaultFeatures();
FIREFOX_3_6.initDefaultFeatures();
final PluginConfiguration flash = new PluginConfiguration("Shockwave Flash",
"Shockwave Flash 9.0 r31", "libflashplayer.so");
flash.getMimeTypes().add(new PluginConfiguration.MimeType("application/x-shockwave-flash",
"Shockwave Flash", "swf"));
FIREFOX_3.getPlugins().add(flash);
FIREFOX_3_6.getPlugins().add(flash);
}
/**
* Instantiates one.
*
* @param applicationName the name of the application
* @param applicationVersion the version string of the application
* @param userAgent the user agent string that will be sent to the server
* @param browserVersionNumeric the floating number version of the browser
*/
public BrowserVersion(final String applicationName, final String applicationVersion,
final String userAgent, final float browserVersionNumeric) {
this(applicationName, applicationVersion, userAgent,
browserVersionNumeric, applicationName + browserVersionNumeric, null);
}
/**
* Instantiates one.
*
* @param applicationName the name of the application
* @param applicationVersion the version string of the application
* @param userAgent the user agent string that will be sent to the server
* @param browserVersionNumeric the floating number version of the browser
* @param features the browser features
*/
public BrowserVersion(final String applicationName, final String applicationVersion,
final String userAgent, final float browserVersionNumeric,
final BrowserVersionFeatures[] features) {
this(applicationName, applicationVersion, userAgent,
browserVersionNumeric, applicationName + browserVersionNumeric, features);
}
/**
* Creates a new browser version instance.
*
* @param applicationName the name of the application
* @param applicationVersion the version string of the application
* @param userAgent the user agent string that will be sent to the server
* @param javaScriptVersion the version of JavaScript
* @param browserVersionNumeric the floating number version of the browser
* @param nickname the short name of the browser (like "FF2", "FF3", "IE6", ...)
* @param features the browser features
*/
private BrowserVersion(final String applicationName, final String applicationVersion,
final String userAgent, final float browserVersionNumeric,
final String nickname, final BrowserVersionFeatures[] features) {
applicationName_ = applicationName;
setApplicationVersion(applicationVersion);
userAgent_ = userAgent;
browserVersionNumeric_ = browserVersionNumeric;
nickname_ = nickname;
if (features != null) {
features_.addAll(Arrays.asList(features));
}
}
private void initDefaultFeatures() {
try {
final Properties props = new Properties();
props.load(getClass().getResourceAsStream("/com/gargoylesoftware/htmlunit/javascript/configuration/"
+ nickname_ + ".properties"));
for (final Object key : props.keySet()) {
- features_.add(BrowserVersionFeatures.valueOf(key.toString()));
+ try {
+ features_.add(BrowserVersionFeatures.valueOf(key.toString()));
+ }
+ catch (final IllegalArgumentException iae) {
+ throw new RuntimeException("Invalid entry '" + key.toString() + "' found in configuration file for BrowserVersion: " + nickname_);
+ }
}
}
- catch (final IllegalArgumentException iae) {
- throw new RuntimeException("Invalid entry found in configuration file for BrowserVersion: " + nickname_);
- }
catch (final Exception e) {
throw new RuntimeException("Configuration file not found for BrowserVersion: " + nickname_);
}
}
/**
* Returns the default browser version that is used whenever a specific version isn't specified.
* Defaults to {@link #INTERNET_EXPLORER_7}.
* @return the default browser version
*/
public static BrowserVersion getDefault() {
return DefaultBrowserVersion_;
}
/**
* Sets the default browser version that is used whenever a specific version isn't specified.
* @param newBrowserVersion the new default browser version
*/
public static void setDefault(final BrowserVersion newBrowserVersion) {
WebAssert.notNull("newBrowserVersion", newBrowserVersion);
DefaultBrowserVersion_ = newBrowserVersion;
}
/**
* Returns <tt>true</tt> if this <tt>BrowserVersion</tt> instance represents some
* version of Internet Explorer.
* @return whether or not this version is a version of IE
*/
public final boolean isIE() {
return INTERNET_EXPLORER.equals(getApplicationName());
}
/**
* Returns <tt>true</tt> if this <tt>BrowserVersion</tt> instance represents some
* version of Firefox like {@link #FIREFOX_2} or {@link #FIREFOX_3}.
* @return whether or not this version is a version of a Firefox browser
*/
public final boolean isFirefox() {
return NETSCAPE.equals(getApplicationName());
}
/**
* Returns the application code name, for example "Mozilla".
* Default value is {@link #APP_CODE_NAME} if not explicitly configured.
* @return the application code name
* @see <a href="http://msdn.microsoft.com/en-us/library/ms533077.aspx">MSDN documentation</a>
*/
public String getApplicationCodeName() {
return applicationCodeName_;
}
/**
* Returns the application minor version, for example "0".
* Default value is "0" if not explicitly configured.
* @return the application minor version
* @see <a href="http://msdn.microsoft.com/en-us/library/ms533078.aspx">MSDN documentation</a>
*/
public String getApplicationMinorVersion() {
return applicationMinorVersion_;
}
/**
* Returns the application name, for example "Microsoft Internet Explorer".
* @return the application name
* @see <a href="http://msdn.microsoft.com/en-us/library/ms533079.aspx">MSDN documentation</a>
*/
public String getApplicationName() {
return applicationName_;
}
/**
* Returns the application version, for example "4.0 (compatible; MSIE 6.0b; Windows 98)".
* @return the application version
* @see <a href="http://msdn.microsoft.com/en-us/library/ms533080.aspx">MSDN documentation</a>
*/
public String getApplicationVersion() {
return applicationVersion_;
}
/**
* Returns the browser application language, for example "en-us".
* Default value is {@link #LANGUAGE_ENGLISH_US} if not explicitly configured.
* @return the browser application language
* @see <a href="http://msdn.microsoft.com/en-us/library/ms533542.aspx">MSDN documentation</a>
*/
public String getBrowserLanguage() {
return browserLanguage_;
}
/**
* Returns the type of CPU in the machine, for example "x86".
* Default value is {@link #CPU_CLASS_X86} if not explicitly configured.
* @return the type of CPU in the machine
* @see <a href="http://msdn.microsoft.com/en-us/library/ms533697.aspx">MSDN documentation</a>
*/
public String getCpuClass() {
return cpuClass_;
}
/**
* Returns <tt>true</tt> if the browser is currently online.
* Default value is <code>true</code> if not explicitly configured.
* @return <tt>true</tt> if the browser is currently online
* @see <a href="http://msdn.microsoft.com/en-us/library/ms534307.aspx">MSDN documentation</a>
*/
public boolean isOnLine() {
return onLine_;
}
/**
* Returns the platform on which the application is running, for example "Win32".
* Default value is {@link #PLATFORM_WIN32} if not explicitly configured.
* @return the platform on which the application is running
* @see <a href="http://msdn.microsoft.com/en-us/library/ms534340.aspx">MSDN documentation</a>
*/
public String getPlatform() {
return platform_;
}
/**
* Returns the system language, for example "en-us".
* Default value is {@link #LANGUAGE_ENGLISH_US} if not explicitly configured.
* @return the system language
* @see <a href="http://msdn.microsoft.com/en-us/library/ms534653.aspx">MSDN documentation</a>
*/
public String getSystemLanguage() {
return systemLanguage_;
}
/**
* Returns the user agent string, for example "Mozilla/4.0 (compatible; MSIE 6.0b; Windows 98)".
* @return the user agent string
*/
public String getUserAgent() {
return userAgent_;
}
/**
* Returns the user language, for example "en-us".
* Default value is {@link #LANGUAGE_ENGLISH_US} if not explicitly configured.
* @return the user language
* @see <a href="http://msdn.microsoft.com/en-us/library/ms534713.aspx">MSDN documentation</a>
*/
public String getUserLanguage() {
return userLanguage_;
}
/**
* @param applicationCodeName the applicationCodeName to set
*/
public void setApplicationCodeName(final String applicationCodeName) {
applicationCodeName_ = applicationCodeName;
}
/**
* @param applicationMinorVersion the applicationMinorVersion to set
*/
public void setApplicationMinorVersion(final String applicationMinorVersion) {
applicationMinorVersion_ = applicationMinorVersion;
}
/**
* @param applicationName the applicationName to set
*/
public void setApplicationName(final String applicationName) {
applicationName_ = applicationName;
}
/**
* @param applicationVersion the applicationVersion to set
*/
public void setApplicationVersion(final String applicationVersion) {
applicationVersion_ = applicationVersion;
}
/**
* @param browserLanguage the browserLanguage to set
*/
public void setBrowserLanguage(final String browserLanguage) {
browserLanguage_ = browserLanguage;
}
/**
* @param cpuClass the cpuClass to set
*/
public void setCpuClass(final String cpuClass) {
cpuClass_ = cpuClass;
}
/**
* @param onLine the onLine to set
*/
public void setOnLine(final boolean onLine) {
onLine_ = onLine;
}
/**
* @param platform the platform to set
*/
public void setPlatform(final String platform) {
platform_ = platform;
}
/**
* @param systemLanguage the systemLanguage to set
*/
public void setSystemLanguage(final String systemLanguage) {
systemLanguage_ = systemLanguage;
}
/**
* @param userAgent the userAgent to set
*/
public void setUserAgent(final String userAgent) {
userAgent_ = userAgent;
}
/**
* @param userLanguage the userLanguage to set
*/
public void setUserLanguage(final String userLanguage) {
userLanguage_ = userLanguage;
}
/**
* @param browserVersion the browserVersion to set
*/
public void setBrowserVersion(final float browserVersion) {
browserVersionNumeric_ = browserVersion;
}
/**
* @return the browserVersionNumeric
*/
public float getBrowserVersionNumeric() {
return browserVersionNumeric_;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(final Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
/**
* Returns the available plugins. This makes only sense for Firefox as only this
* browser makes this kind of information available via JavaScript.
* @return the available plugins
*/
public Set<PluginConfiguration> getPlugins() {
return plugins_;
}
/**
* Indicates if this instance has the given feature. Used for HtmlUnit internal processing.
* @param property the property name
* @return <code>false</code> if this browser doesn't have this feature
*/
public boolean hasFeature(final BrowserVersionFeatures property) {
return features_.contains(property);
}
/**
* Returns the short name of the browser like "FF3", "IE7", ...
* This is used in different tests to reference the browser to which it applies.
* @return the short name (if any)
*/
public String getNickname() {
return nickname_;
}
}
| false | true | private void initDefaultFeatures() {
try {
final Properties props = new Properties();
props.load(getClass().getResourceAsStream("/com/gargoylesoftware/htmlunit/javascript/configuration/"
+ nickname_ + ".properties"));
for (final Object key : props.keySet()) {
features_.add(BrowserVersionFeatures.valueOf(key.toString()));
}
}
catch (final IllegalArgumentException iae) {
throw new RuntimeException("Invalid entry found in configuration file for BrowserVersion: " + nickname_);
}
catch (final Exception e) {
throw new RuntimeException("Configuration file not found for BrowserVersion: " + nickname_);
}
}
| private void initDefaultFeatures() {
try {
final Properties props = new Properties();
props.load(getClass().getResourceAsStream("/com/gargoylesoftware/htmlunit/javascript/configuration/"
+ nickname_ + ".properties"));
for (final Object key : props.keySet()) {
try {
features_.add(BrowserVersionFeatures.valueOf(key.toString()));
}
catch (final IllegalArgumentException iae) {
throw new RuntimeException("Invalid entry '" + key.toString() + "' found in configuration file for BrowserVersion: " + nickname_);
}
}
}
catch (final Exception e) {
throw new RuntimeException("Configuration file not found for BrowserVersion: " + nickname_);
}
}
|
diff --git a/central/plugins/org.jboss.tools.central/src/org/jboss/tools/central/actions/FavoriteAtEclipseMarketplaceHandler.java b/central/plugins/org.jboss.tools.central/src/org/jboss/tools/central/actions/FavoriteAtEclipseMarketplaceHandler.java
index fb99d448..7125150e 100644
--- a/central/plugins/org.jboss.tools.central/src/org/jboss/tools/central/actions/FavoriteAtEclipseMarketplaceHandler.java
+++ b/central/plugins/org.jboss.tools.central/src/org/jboss/tools/central/actions/FavoriteAtEclipseMarketplaceHandler.java
@@ -1,26 +1,26 @@
/*************************************************************************************
* Copyright (c) 2008-2011 Red Hat, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* JBoss by Red Hat - Initial implementation.
************************************************************************************/
package org.jboss.tools.central.actions;
/**
*
* @author snjeza
*
*/
public class FavoriteAtEclipseMarketplaceHandler extends OpenWithBrowserHandler {
@Override
public String getLocation() {
- return "http://marketplace.eclipse.org/node/15557";
+ return "http://marketplace.eclipse.org/node/121986";
}
}
| true | true | public String getLocation() {
return "http://marketplace.eclipse.org/node/15557";
}
| public String getLocation() {
return "http://marketplace.eclipse.org/node/121986";
}
|
diff --git a/src/engine/agent/tim/agents/PopUpAgent.java b/src/engine/agent/tim/agents/PopUpAgent.java
index a8d41e2..09f2297 100644
--- a/src/engine/agent/tim/agents/PopUpAgent.java
+++ b/src/engine/agent/tim/agents/PopUpAgent.java
@@ -1,569 +1,569 @@
package engine.agent.tim.agents;
import java.util.*;
import java.util.concurrent.Semaphore;
import engine.agent.Agent;
import engine.agent.OfflineWorkstationAgent;
import engine.agent.tim.interfaces.Machine;
import engine.agent.tim.interfaces.PopUp;
import engine.agent.tim.misc.ConveyorEvent;
import engine.agent.tim.misc.ConveyorFamilyImp;
import engine.agent.tim.misc.MachineCom;
import engine.agent.tim.misc.MyGlassPopUp;
import engine.agent.tim.misc.MyGlassPopUp.processState;
import shared.Glass;
import shared.enums.MachineType;
import shared.interfaces.NonnormBreakInteraction;
import shared.interfaces.OfflineConveyorFamily;
import transducer.TChannel;
import transducer.TEvent;
import transducer.Transducer;
public class PopUpAgent extends Agent implements PopUp {
// Name: PopUpAgent
// Description: Will act as a mediator between the conveyor agent and the robot agents for getting glass to the processing machines, if necessary.
// Of course, this agent may not be needed because there is NO ROBOT in the animation. but I will leave it in for now.
// Data:
private List<MyGlassPopUp> glassToBeProcessed; // This name will be abbreviated as glassToBeProcessed in many functions to save on space and complexity
private List<MachineCom> machineComs; // Channels for communicating with the machines, since there will most likely be two per offline process
// Positional variable for whether the Pop-Up in the GUI is up or down, and it will be changed through the transducer and checked within one of the scheduler rules
private boolean popUpDown; // Is this value is true, then the associated popUp is down (will be changed through the appropriate transducer eventFired(args[]) function.
private ConveyorFamilyImp cf; // Reference to the current conveyor family
private MachineType processType; // Will hold what the concurrent workstation agents can process for any given popUp � it is safe to assume that the workstations process the same thing
private boolean passNextCF; // Is it possible to pass to the next conveyor family yet?
int guiIndex; // Needed to communicate with the transducer
// Add semaphores to delay the popUp agent accordingly between GUI transitions
private List<Semaphore> animationSemaphores;
// Add list for tickets that allow the glass to move on to the next conveyor family
private List<Boolean> tickets;
private enum GUIBreakState {stop, stopped, restart, running};
GUIBreakState guiBreakState = GUIBreakState.running; // Value that determines whether the GUI conveyor is broken or not
// Add an event queue, so that GUI events can be processed as soon as the PopUp is unBroken
List<TEvent> queuedEvents;
// Make a timer to wake up the scheduler if glass could not be passed to next conveyor
Timer timer = new Timer();
// Constructors:
public PopUpAgent(String name, Transducer transducer, List<OfflineWorkstationAgent> machines, int guiIndex) {
// Set the passed in values first
super(name, transducer);
// Then set the values that need to be initialized within this class, specifically
glassToBeProcessed = Collections.synchronizedList(new ArrayList<MyGlassPopUp>());
machineComs = Collections.synchronizedList(new ArrayList<MachineCom>());
animationSemaphores = Collections.synchronizedList(new ArrayList<Semaphore>());
tickets = Collections.synchronizedList(new ArrayList<Boolean>());
tickets.add(new Boolean(true)); // Make sure to have an initial ticket, or else the glass will never go through
// This loop will go for the number of machines that are in the machines argument
int i = 0; // Machine indexes related to the GUI machinea
for (OfflineWorkstationAgent m: machines) {
machineComs.add(new MachineCom(m, i));
i++;
}
processType = machineComs.get(0).machine.getType(); // Set the correct process type
popUpDown = true; // The popUp has to be down when the system starts...
passNextCF = true; // The next conveyor will always be available when the system starts
this.guiIndex = guiIndex;
// Initialize the semaphores as binary semaphores with value 0
for (int j = 0; j < 5; j++) {
animationSemaphores.add(new Semaphore(0));
}
queuedEvents = Collections.synchronizedList(new ArrayList<TEvent>()); // Set up the queued events list
initializeTransducerChannels();
}
// alternate constructor that accepts a machine array versus an arrayList:
public PopUpAgent(String name, Transducer transducer, OfflineWorkstationAgent[] machines, int guiIndex) {
// Set the passed in values first
super(name, transducer);
// Then set the values that need to be initialized within this class, specifically
glassToBeProcessed = Collections.synchronizedList(new ArrayList<MyGlassPopUp>());
machineComs = Collections.synchronizedList(new ArrayList<MachineCom>());
animationSemaphores = Collections.synchronizedList(new ArrayList<Semaphore>());
tickets = Collections.synchronizedList(new ArrayList<Boolean>());
tickets.add(new Boolean(true)); // Make sure to have an initial ticket, or else the glass will never go through
// This loop will go for the number of machines that are in the machines argument
int i = 0; // Machine indexes related to the GUI machinea
for (OfflineWorkstationAgent m: machines) {
machineComs.add(new MachineCom(m, i));
i++;
}
processType = machineComs.get(0).machine.getType(); // Set the correct process type
popUpDown = true; // The popUp has to be down when the system starts...
passNextCF = true; // The next conveyor will always be available when the system starts
this.guiIndex = guiIndex;
// Initialize the semaphores as binary semaphores with value 0
for (int j = 0; j < 5; j++) {
animationSemaphores.add(new Semaphore(0));
}
queuedEvents = Collections.synchronizedList(new ArrayList<TEvent>()); // Set up the queued events list
initializeTransducerChannels();
}
private void initializeTransducerChannels() { // Initialize the transducer channels and everything else related to it
// Register any appropriate channels
transducer.register(this, TChannel.POPUP); // Set this agent to listen to the POPUP channel of the transducer
transducer.register(this, processType.getChannel()); // Set this agent to listen to the processType channel of the transducer
}
//Messages:
public void msgGiveGlassToPopUp(Glass g) { // Get Glass from conveyor to PopUp
// Check to see that g does not already exist in the popUp agent
boolean glassInPopUp = false;
synchronized (glassToBeProcessed) {
for (MyGlassPopUp glass: glassToBeProcessed) {
if (glass.glass.equals(g)) {
glassInPopUp = true;
break;
}
}
}
if (glassInPopUp == false) {
glassToBeProcessed.add(new MyGlassPopUp(g, processState.awaitingArrival));
print("Glass with ID (" + g.getID() + ") added");
}
stateChanged();
}
public void msgGlassDone(Glass g, int index) { // Adds glass back from a machine and then resets the machine channel to be free
synchronized (glassToBeProcessed) {
for (MyGlassPopUp glass: glassToBeProcessed) {
if (glass.glass.getID() == g.getID()) {
glass.processState = processState.doneProcessing;
stateChanged();
break;
}
}
// Should never get here
}
}
public void msgPositionFree() {
passNextCF = true;
tickets.add(new Boolean(true));
print("Got msgPositionFree() " + tickets.size());
stateChanged();
}
/* This message is from the GUI to stop or restart. */
public void msgGUIBreak(boolean stop) {
if (stop && guiBreakState == GUIBreakState.running) {
guiBreakState = GUIBreakState.stop;
stateChanged();
}
else if (!stop && guiBreakState == GUIBreakState.stopped) {
guiBreakState = GUIBreakState.restart;
stateChanged();
}
}
/*This message will come from the GUI to break a certain workstation*/
public void msgGUIBreakWorkstation(boolean stop, int machineIndex) {
if (stop) { // Then halt communication through this machineCom
if (machineComs.get(machineIndex % 2).isBroken == false) {
machineComs.get(machineIndex % 2).isBroken = true;
stateChanged();
}
}
else { // Then Re-set up communication through this machineCom
if (machineComs.get(machineIndex % 2).isBroken == true) {
machineComs.get(machineIndex % 2).isBroken = false;
stateChanged();
}
}
}
@Override
public void msgGUIBreakRemovedGlassFromWorkstation(int index) { // Index is the index of the machine that removed the glass
synchronized (glassToBeProcessed) {
for (MyGlassPopUp g: glassToBeProcessed) {
if (g.machineIndex == index && g.processState == processState.processing) {
print("Removed glass (" + g.glass.getID() + ") from the popUp.");
glassToBeProcessed.remove(g);
break;
}
}
}
}
//Scheduler:
public boolean pickAndExecuteAnAction() {
// Check to see if a GUI break message came in
if (guiBreakState == GUIBreakState.stop) {
actBreakPopUpOff();
return false; // Make sure the method does not call again
}
else if (guiBreakState == GUIBreakState.restart) {
actBreakPopUpOn();
return true;
}
else if (guiBreakState == GUIBreakState.stopped) {
return false; // C'mon the PopUp is broken! It shouldn't run until this state is changed
}
// Use null variables for determining is value is found from synchronized loop
MyGlassPopUp glass = null;
MachineCom machCom = null;
synchronized(glassToBeProcessed) {
for (MyGlassPopUp g: glassToBeProcessed) {
if (g.processState == processState.awaitingRemoval) { // If glass needs to be sent out to next conveyor and a position is available
if (!tickets.isEmpty() || passNextCF) { // If there is a ticket for the glass to go to the next conveyor family
glass = g;
break;
}
else {
print("Glass needs to be removed, but no position free");
// timer.schedule(new TimerTask() {
// public void run() {
// pickAndExecuteAnAction();
// }
// }, 1000);
// print("Here");
return false; // Do not want another piece of glass to collide, so shut the agent down until positionFree() is called
}
}
}
}
if (glass != null) {
actPassGlassToNextCF(glass); return true;
}
synchronized(glassToBeProcessed) {
for (MyGlassPopUp g: glassToBeProcessed) {
if (g.processState == processState.unprocessed) { // If glass needs to be sent out to a machine and a position is available
synchronized(machineComs) {
for (MachineCom com: machineComs) {
if ((com.inUse == false && popUpDown == true && com.isBroken == false)) { // If there is an available machine and the popUp is down and machine is not broken
glass = g;
machCom = com;
break;
}
}
}
}
}
}
if (glass != null && machCom != null) {
actPassGlassToMachine(glass, machCom); return true;
}
synchronized(glassToBeProcessed) {
for (MyGlassPopUp g: glassToBeProcessed) {
if (g.processState == processState.doneProcessing && machineComs.get(g.machineIndex).isBroken == false) { // If glass needs to be sent out to next conveyor and a position is available
glass = g;
break;
}
}
}
if (glass != null) {
actRemoveGlassFromMachine(glass); return true;
}
synchronized(glassToBeProcessed) {
for (MyGlassPopUp g: glassToBeProcessed) {
if (g.processState == processState.awaitingArrival) { // If glass needs to be sent out to next conveyor and a position is available
synchronized(machineComs) {
for (MachineCom com: machineComs) {
- if (((com.inUse == false && com.isBroken == false) || !g.glass.getNeedsProcessing(processType)) && !isGlassOnPopUp()) { // If there is an available machine and it is not broken or glass does not need processing
+ if (((com.inUse == false && g.glass.getNeedsProcessing(processType)/*&& com.isBroken == false*/) || ( !g.glass.getNeedsProcessing(processType) && !isGlassOnPopUp() ))) { // If there is an available machine and it is not broken or glass does not need processing
glass = g;
machCom = com;
break;
}
}
}
}
}
}
if (glass != null && machCom != null) {
actSendForGlass(glass); return true;
}
return false;
}
//Actions:
private void actSendForGlass(MyGlassPopUp glass) {
// Fire transducer event to move the popUp down here index � make sure to stall the agent until the right time to prevent any weird synchronization issues
doMovePopUpDown();
cf.getConveyor().msgPositionFree(); // Tell conveyor to send down the glass
print("Conveyor sent msgPositionFree()");
// Wait until the glass is loaded to continue further action
doDelayForAnimation(0);
// Send back message to conveyor that message was received
cf.getConveyor().msgUpdateGlass(ConveyorEvent.onPopUp);
if (glass.glass.getNeedsProcessing(processType))
glass.processState = processState.unprocessed;
else
glass.processState = processState.awaitingRemoval;
print("Glass " + glass.glass.getID() + " added to queue for processing. Glass state: " + glass.processState);
}
private void actPassGlassToNextCF(MyGlassPopUp glass) {
cf.getNextCF().msgHereIsGlass(glass.glass);
print("Glass " + glass.glass.getID() + " soon to be passed to nextCF");
if (!tickets.isEmpty())
tickets.remove(0); // Make sure to remove the ticket, as it has already been used
// // Fire the transducer to turn off this CF's conveyor if there is no glass on it
// if (cf.getConveyor().getGlassSheets().size() == 0) { // Turn off the conveyor, there is no glass on it
// Integer[] args = {cf.getConveyor().getGUIIndex()};
// transducer.fireEvent(TChannel.CONVEYOR, TEvent.CONVEYOR_DO_STOP, args);
// }
// Fire transducer event to release glass index � make sure to stall the agent until the glass arrives to prevent any weird synchronization issues
doReleaseGlassPopUp();
passNextCF = false;
glassToBeProcessed.remove(glass);
print("Glass " + glass.glass.getID() + " passed to nextCF");
}
private void actRemoveGlassFromMachine(MyGlassPopUp glass) {
// Make sure to call Transducer events:
// Move PopUp up,
doMovePopUpUp();
// Machine Release Glass,
doReleaseGlassWorkstation(glass.machineIndex);
// Move PopUp Down
doMovePopUpDown();
// all with the correct timing so nothing is funky
glass.processState = processState.awaitingRemoval;
print("Glass " + glass.glass.getID() + " removed from machine");
}
private void actPassGlassToMachine(MyGlassPopUp glass, MachineCom com) {
glass.processState = processState.processing;
glass.machineIndex = com.machineIndex;
// Fire the transducer to turn off this CF's conveyor if there is no glass on it
// if (cf.getConveyor().getGlassSheets().size() == 0) { // Turn off the conveyor, there is no glass on it
// Integer[] args = {cf.getConveyor().getGUIIndex()};
// transducer.fireEvent(TChannel.CONVEYOR, TEvent.CONVEYOR_DO_STOP, args);
// }
// Fire the PopUp up transducer event index � make sure to stall the agent until the glass arrives to prevent any weird synchronization issues
doMovePopUpUp();
com.machine.msgHereIsGlass(glass.glass);
// Machine Load glass transducer events w/right index (can be attained from the machineCom machineIndex) � make sure to stall the agent until the glass arrives to prevent any weird synchronization issues
doLoadGlassWorkStation(com.machineIndex);
print("Glass " + glass.glass.getID() + " passed to machine " + com.machine.getName());
}
// New Non-norm GUI actions
private void actBreakPopUpOff() {
// Does the popUp just keep it's previous state while broken, or will something else change here?
guiBreakState = GUIBreakState.stopped;
}
private void actBreakPopUpOn() {
// Does the popUp just keep it's previous state while broken, or will something else change here?
guiBreakState = GUIBreakState.running;
// Process all of the pending events
while (!queuedEvents.isEmpty()) { // Fire all of the events in the order they were received -- this will unblock all of the animation semaphores in the correct order
Integer[] args = {guiIndex};
TEvent event = queuedEvents.remove(0);
if (event == TEvent.WORKSTATION_LOAD_FINISHED) // Send this event as it would come from the workStation
transducer.fireEvent(processType.getChannel(), event, null); // Only channel is checked, not machineIndex
else // Send it as if it came from the popUp
transducer.fireEvent(TChannel.POPUP, event, args);
}
}
//Other Methods:
@Override
public void eventFired(TChannel channel, TEvent event, Object[] args) {
//if (guiBreakState != GUIBreakState.running) { queuedEvents.add(event); return; } // If broken, do not receive messages, but queue the messages to be processed later so the semaphores will be released when the machine is online
// Catch all of the animation events and open up the correct semaphores to continue the processing of the glass on the PopUp or workstation
if ((channel == TChannel.POPUP && (Integer) args[0] == guiIndex ) || channel == processType.getChannel()) {
if (event == TEvent.POPUP_GUI_LOAD_FINISHED) {
animationSemaphores.get(0).release();
print("Animation semaphore 0 released");
}
else if (event == TEvent.POPUP_GUI_MOVED_DOWN) {
animationSemaphores.get(1).release();
print("Animation semaphore 1 released");
}
else if (event == TEvent.POPUP_GUI_MOVED_UP) {
animationSemaphores.get(2).release();
print("Animation semaphore 2 released");
}
else if (event == TEvent.POPUP_GUI_RELEASE_FINISHED) {
animationSemaphores.get(3).release();
print("Animation semaphore 3 released");
}
else if (event == TEvent.WORKSTATION_LOAD_FINISHED) {
animationSemaphores.get(4).release();
print("Animation semaphore 4 released");
}
}
}
// Special Animation Methods Below ("do" methods):
private void doMovePopUpUp() { // Make the GUI PopUp move up
if (popUpDown == true) { // Only do this action if the popUp is down
Integer args[] = {guiIndex};
transducer.fireEvent(TChannel.POPUP, TEvent.POPUP_DO_MOVE_UP, args);
doDelayForAnimation(2); // Wait for the popUp to move up
popUpDown = false;
}
}
private void doMovePopUpDown() { // Make the GUI PopUp move down
if (popUpDown == false) { // Only do this action if the popUp is up
Integer args[] = {guiIndex};
transducer.fireEvent(TChannel.POPUP, TEvent.POPUP_DO_MOVE_DOWN, args);
doDelayForAnimation(1); // Wait for the popUp to move down
popUpDown = true;
}
}
private void doReleaseGlassPopUp() { // Make the GUI PopUp release it's glass
Integer args[] = {guiIndex};
transducer.fireEvent(TChannel.POPUP, TEvent.POPUP_RELEASE_GLASS, args);
doDelayForAnimation(3); // Wait for the popUp to release the glass
}
private void doLoadGlassWorkStation(int index) { // Make the GUI Workstation (index) next to the popUp load glass
Integer args[] = {index};
transducer.fireEvent(processType.getChannel(), TEvent.WORKSTATION_DO_LOAD_GLASS, args);
doDelayForAnimation(4); // wait for popup load to finish
machineComs.get(index).inUse = true; // Make sure to set the machineCom to isUse, or else other glasses will be able to access machine
}
private void doReleaseGlassWorkstation(int index) { // Make the GUI Workstation (index) next to the popUp release its glass
Integer args[] = {index};
transducer.fireEvent(processType.getChannel(), TEvent.WORKSTATION_RELEASE_GLASS, args);
doDelayForAnimation(0); // wait for popup load to finish
machineComs.get(index).inUse = false; // Make sure to make the machineCom available again
}
private void doDelayForAnimation(int index) { // Depending on what index is passed in, a certain animation semaphore will block until the animation is done
try {
animationSemaphores.get(index).acquire();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
// Getters and Setters
public int getFreeChannels() {
int freeChannels = 0;
synchronized(machineComs) {
for (MachineCom com: machineComs) {
if (com.inUse == false)
freeChannels++;
}
}
// Make sure to augment the free channels number by the amount of glasses that are currently within the popUp, so that two glasses do not come up when there shoulkd only be one
freeChannels -= glassToBeProcessed.size();
return freeChannels;
}
/**
* @return the glassToBeProcessed
*/
public List<MyGlassPopUp> getGlassToBeProcessed() {
return glassToBeProcessed;
}
/**
* @return the popUpDown
*/
public boolean isPopUpDown() {
return popUpDown;
}
@Override
public void setCF(OfflineConveyorFamily conveyorFamilyImp) {
cf = (ConveyorFamilyImp) conveyorFamilyImp;
}
@Override
public void runScheduler() {
pickAndExecuteAnAction();
}
@Override
public boolean doesGlassNeedProcessing(Glass glass) { // Method invoked by the conveyor for a special case of sending glass down the popUp in the line
if (glass.getNeedsProcessing(processType)) { // Both machines on every offline process do the same process
return true;
}
else {
return false;
}
}
/**
* @return the passNextCF
*/
public boolean isPassNextCF() {
return passNextCF;
}
public List<Semaphore> getAnimationSemaphores() {
return animationSemaphores;
}
/**
* @return the machineComs
*/
public List<MachineCom> getMachineComs() {
return machineComs;
}
public boolean isGlassOnPopUp() {
synchronized (glassToBeProcessed) {
for (MyGlassPopUp g: glassToBeProcessed) {
if (g.processState == processState.unprocessed ||
g.processState == processState.awaitingRemoval /*||
g.processState == processState.doneProcessing*/) { // If glass is on or transitioning to/from popUp
return true;
}
if (g.processState == processState.awaitingArrival) { // If there is a piece of glass already moving towards the popUp
for (MyGlassPopUp gl: glassToBeProcessed) {
if (gl != g && gl.processState == processState.awaitingArrival) {
return true;
}
}
}
}
}
return false;
}
}
| true | true | public boolean pickAndExecuteAnAction() {
// Check to see if a GUI break message came in
if (guiBreakState == GUIBreakState.stop) {
actBreakPopUpOff();
return false; // Make sure the method does not call again
}
else if (guiBreakState == GUIBreakState.restart) {
actBreakPopUpOn();
return true;
}
else if (guiBreakState == GUIBreakState.stopped) {
return false; // C'mon the PopUp is broken! It shouldn't run until this state is changed
}
// Use null variables for determining is value is found from synchronized loop
MyGlassPopUp glass = null;
MachineCom machCom = null;
synchronized(glassToBeProcessed) {
for (MyGlassPopUp g: glassToBeProcessed) {
if (g.processState == processState.awaitingRemoval) { // If glass needs to be sent out to next conveyor and a position is available
if (!tickets.isEmpty() || passNextCF) { // If there is a ticket for the glass to go to the next conveyor family
glass = g;
break;
}
else {
print("Glass needs to be removed, but no position free");
// timer.schedule(new TimerTask() {
// public void run() {
// pickAndExecuteAnAction();
// }
// }, 1000);
// print("Here");
return false; // Do not want another piece of glass to collide, so shut the agent down until positionFree() is called
}
}
}
}
if (glass != null) {
actPassGlassToNextCF(glass); return true;
}
synchronized(glassToBeProcessed) {
for (MyGlassPopUp g: glassToBeProcessed) {
if (g.processState == processState.unprocessed) { // If glass needs to be sent out to a machine and a position is available
synchronized(machineComs) {
for (MachineCom com: machineComs) {
if ((com.inUse == false && popUpDown == true && com.isBroken == false)) { // If there is an available machine and the popUp is down and machine is not broken
glass = g;
machCom = com;
break;
}
}
}
}
}
}
if (glass != null && machCom != null) {
actPassGlassToMachine(glass, machCom); return true;
}
synchronized(glassToBeProcessed) {
for (MyGlassPopUp g: glassToBeProcessed) {
if (g.processState == processState.doneProcessing && machineComs.get(g.machineIndex).isBroken == false) { // If glass needs to be sent out to next conveyor and a position is available
glass = g;
break;
}
}
}
if (glass != null) {
actRemoveGlassFromMachine(glass); return true;
}
synchronized(glassToBeProcessed) {
for (MyGlassPopUp g: glassToBeProcessed) {
if (g.processState == processState.awaitingArrival) { // If glass needs to be sent out to next conveyor and a position is available
synchronized(machineComs) {
for (MachineCom com: machineComs) {
if (((com.inUse == false && com.isBroken == false) || !g.glass.getNeedsProcessing(processType)) && !isGlassOnPopUp()) { // If there is an available machine and it is not broken or glass does not need processing
glass = g;
machCom = com;
break;
}
}
}
}
}
}
if (glass != null && machCom != null) {
actSendForGlass(glass); return true;
}
return false;
}
| public boolean pickAndExecuteAnAction() {
// Check to see if a GUI break message came in
if (guiBreakState == GUIBreakState.stop) {
actBreakPopUpOff();
return false; // Make sure the method does not call again
}
else if (guiBreakState == GUIBreakState.restart) {
actBreakPopUpOn();
return true;
}
else if (guiBreakState == GUIBreakState.stopped) {
return false; // C'mon the PopUp is broken! It shouldn't run until this state is changed
}
// Use null variables for determining is value is found from synchronized loop
MyGlassPopUp glass = null;
MachineCom machCom = null;
synchronized(glassToBeProcessed) {
for (MyGlassPopUp g: glassToBeProcessed) {
if (g.processState == processState.awaitingRemoval) { // If glass needs to be sent out to next conveyor and a position is available
if (!tickets.isEmpty() || passNextCF) { // If there is a ticket for the glass to go to the next conveyor family
glass = g;
break;
}
else {
print("Glass needs to be removed, but no position free");
// timer.schedule(new TimerTask() {
// public void run() {
// pickAndExecuteAnAction();
// }
// }, 1000);
// print("Here");
return false; // Do not want another piece of glass to collide, so shut the agent down until positionFree() is called
}
}
}
}
if (glass != null) {
actPassGlassToNextCF(glass); return true;
}
synchronized(glassToBeProcessed) {
for (MyGlassPopUp g: glassToBeProcessed) {
if (g.processState == processState.unprocessed) { // If glass needs to be sent out to a machine and a position is available
synchronized(machineComs) {
for (MachineCom com: machineComs) {
if ((com.inUse == false && popUpDown == true && com.isBroken == false)) { // If there is an available machine and the popUp is down and machine is not broken
glass = g;
machCom = com;
break;
}
}
}
}
}
}
if (glass != null && machCom != null) {
actPassGlassToMachine(glass, machCom); return true;
}
synchronized(glassToBeProcessed) {
for (MyGlassPopUp g: glassToBeProcessed) {
if (g.processState == processState.doneProcessing && machineComs.get(g.machineIndex).isBroken == false) { // If glass needs to be sent out to next conveyor and a position is available
glass = g;
break;
}
}
}
if (glass != null) {
actRemoveGlassFromMachine(glass); return true;
}
synchronized(glassToBeProcessed) {
for (MyGlassPopUp g: glassToBeProcessed) {
if (g.processState == processState.awaitingArrival) { // If glass needs to be sent out to next conveyor and a position is available
synchronized(machineComs) {
for (MachineCom com: machineComs) {
if (((com.inUse == false && g.glass.getNeedsProcessing(processType)/*&& com.isBroken == false*/) || ( !g.glass.getNeedsProcessing(processType) && !isGlassOnPopUp() ))) { // If there is an available machine and it is not broken or glass does not need processing
glass = g;
machCom = com;
break;
}
}
}
}
}
}
if (glass != null && machCom != null) {
actSendForGlass(glass); return true;
}
return false;
}
|
diff --git a/pmd/src/net/sourceforge/pmd/lang/xml/ast/XmlParser.java b/pmd/src/net/sourceforge/pmd/lang/xml/ast/XmlParser.java
index 70f18b692..e685194e4 100644
--- a/pmd/src/net/sourceforge/pmd/lang/xml/ast/XmlParser.java
+++ b/pmd/src/net/sourceforge/pmd/lang/xml/ast/XmlParser.java
@@ -1,158 +1,158 @@
/**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.xml.ast;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import net.sourceforge.pmd.lang.ast.ParseException;
import net.sourceforge.pmd.lang.ast.RootNode;
import net.sourceforge.pmd.lang.ast.xpath.Attribute;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class XmlParser {
protected Map<Node, XmlNode> nodeCache = new HashMap<Node, XmlNode>();
protected Document parseDocument(Reader reader) throws ParseException {
nodeCache.clear();
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(new InputSource(reader));
return document;
} catch (ParserConfigurationException e) {
throw new ParseException(e);
} catch (SAXException e) {
throw new ParseException(e);
} catch (IOException e) {
throw new ParseException(e);
}
}
public XmlNode parse(Reader reader) {
Document document = parseDocument(reader);
return createProxy(document.getDocumentElement());
}
public XmlNode createProxy(Node node) {
XmlNode proxy = nodeCache.get(node);
if (proxy != null) {
return proxy;
}
// TODO Change Parser interface to take ClassLoader?
LinkedHashSet<Class<?>> interfaces = new LinkedHashSet<Class<?>>();
interfaces.add(XmlNode.class);
if (node.getParentNode() instanceof Document) {
interfaces.add(RootNode.class);
}
addAllInterfaces(interfaces, node.getClass());
proxy = (XmlNode) Proxy.newProxyInstance(XmlParser.class.getClassLoader(), interfaces
.toArray(new Class[interfaces.size()]), new XmlNodeInvocationHandler(node));
nodeCache.put(node, proxy);
return proxy;
}
public void addAllInterfaces(Set<Class<?>> interfaces, Class<?> clazz) {
interfaces.addAll(Arrays.asList((Class<?>[]) clazz.getInterfaces()));
if (clazz.getSuperclass() != null) {
addAllInterfaces(interfaces, clazz.getSuperclass());
}
}
public class XmlNodeInvocationHandler implements InvocationHandler {
private final Node node;
public XmlNodeInvocationHandler(Node node) {
this.node = node;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// XmlNode method?
if (method.getDeclaringClass().isAssignableFrom(XmlNode.class)
&& !"java.lang.Object".equals(method.getDeclaringClass().getName())) {
if ("jjtGetNumChildren".equals(method.getName())) {
return node.hasChildNodes() ? node.getChildNodes().getLength() : 0;
} else if ("jjtGetChild".equals(method.getName())) {
return createProxy(node.getChildNodes().item(((Integer) args[0]).intValue()));
} else if ("getImage".equals(method.getName())) {
if (node instanceof Text) {
- return ((Text) node).getTextContent();
+ return ((Text) node).getData();
} else {
return null;
}
} else if ("jjtGetParent".equals(method.getName())) {
Node parent = node.getParentNode();
if (parent != null && !(parent instanceof Document)) {
return createProxy(parent);
} else {
return null;
}
} else if ("getAttributeIterator".equals(method.getName())) {
final NamedNodeMap attributes = node.getAttributes();
return new Iterator<Attribute>() {
private int index;
public boolean hasNext() {
return attributes != null && index < attributes.getLength();
}
public Attribute next() {
Node attributeNode = attributes.item(index++);
return new Attribute(createProxy(node), attributeNode.getNodeName(), attributeNode
.getNodeValue());
}
public void remove() {
throw new UnsupportedOperationException();
}
};
} else if ("getBeginLine".equals(method.getName())) {
return new Integer(-1);
} else if ("getBeginColumn".equals(method.getName())) {
return new Integer(-1);
} else if ("getEndLine".equals(method.getName())) {
return new Integer(-1);
} else if ("getEndColumn".equals(method.getName())) {
return new Integer(-1);
} else if ("getNode".equals(method.getName())) {
return node;
}
throw new UnsupportedOperationException("Method not supported for XmlNode: " + method);
}
// Delegate method
else {
if ("toString".equals(method.getName())) {
if (node instanceof Element) {
return ((Element) node).getNodeName();
}
}
Object result = method.invoke(node, args);
return result;
}
}
}
}
| true | true | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// XmlNode method?
if (method.getDeclaringClass().isAssignableFrom(XmlNode.class)
&& !"java.lang.Object".equals(method.getDeclaringClass().getName())) {
if ("jjtGetNumChildren".equals(method.getName())) {
return node.hasChildNodes() ? node.getChildNodes().getLength() : 0;
} else if ("jjtGetChild".equals(method.getName())) {
return createProxy(node.getChildNodes().item(((Integer) args[0]).intValue()));
} else if ("getImage".equals(method.getName())) {
if (node instanceof Text) {
return ((Text) node).getTextContent();
} else {
return null;
}
} else if ("jjtGetParent".equals(method.getName())) {
Node parent = node.getParentNode();
if (parent != null && !(parent instanceof Document)) {
return createProxy(parent);
} else {
return null;
}
} else if ("getAttributeIterator".equals(method.getName())) {
final NamedNodeMap attributes = node.getAttributes();
return new Iterator<Attribute>() {
private int index;
public boolean hasNext() {
return attributes != null && index < attributes.getLength();
}
public Attribute next() {
Node attributeNode = attributes.item(index++);
return new Attribute(createProxy(node), attributeNode.getNodeName(), attributeNode
.getNodeValue());
}
public void remove() {
throw new UnsupportedOperationException();
}
};
} else if ("getBeginLine".equals(method.getName())) {
return new Integer(-1);
} else if ("getBeginColumn".equals(method.getName())) {
return new Integer(-1);
} else if ("getEndLine".equals(method.getName())) {
return new Integer(-1);
} else if ("getEndColumn".equals(method.getName())) {
return new Integer(-1);
} else if ("getNode".equals(method.getName())) {
return node;
}
throw new UnsupportedOperationException("Method not supported for XmlNode: " + method);
}
// Delegate method
else {
if ("toString".equals(method.getName())) {
if (node instanceof Element) {
return ((Element) node).getNodeName();
}
}
Object result = method.invoke(node, args);
return result;
}
}
| public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// XmlNode method?
if (method.getDeclaringClass().isAssignableFrom(XmlNode.class)
&& !"java.lang.Object".equals(method.getDeclaringClass().getName())) {
if ("jjtGetNumChildren".equals(method.getName())) {
return node.hasChildNodes() ? node.getChildNodes().getLength() : 0;
} else if ("jjtGetChild".equals(method.getName())) {
return createProxy(node.getChildNodes().item(((Integer) args[0]).intValue()));
} else if ("getImage".equals(method.getName())) {
if (node instanceof Text) {
return ((Text) node).getData();
} else {
return null;
}
} else if ("jjtGetParent".equals(method.getName())) {
Node parent = node.getParentNode();
if (parent != null && !(parent instanceof Document)) {
return createProxy(parent);
} else {
return null;
}
} else if ("getAttributeIterator".equals(method.getName())) {
final NamedNodeMap attributes = node.getAttributes();
return new Iterator<Attribute>() {
private int index;
public boolean hasNext() {
return attributes != null && index < attributes.getLength();
}
public Attribute next() {
Node attributeNode = attributes.item(index++);
return new Attribute(createProxy(node), attributeNode.getNodeName(), attributeNode
.getNodeValue());
}
public void remove() {
throw new UnsupportedOperationException();
}
};
} else if ("getBeginLine".equals(method.getName())) {
return new Integer(-1);
} else if ("getBeginColumn".equals(method.getName())) {
return new Integer(-1);
} else if ("getEndLine".equals(method.getName())) {
return new Integer(-1);
} else if ("getEndColumn".equals(method.getName())) {
return new Integer(-1);
} else if ("getNode".equals(method.getName())) {
return node;
}
throw new UnsupportedOperationException("Method not supported for XmlNode: " + method);
}
// Delegate method
else {
if ("toString".equals(method.getName())) {
if (node instanceof Element) {
return ((Element) node).getNodeName();
}
}
Object result = method.invoke(node, args);
return result;
}
}
|
diff --git a/src/za/co/rational/OpenGlEsPolygon/OpenGlEsPolygon.java b/src/za/co/rational/OpenGlEsPolygon/OpenGlEsPolygon.java
index 9cb0803..13e7d5e 100644
--- a/src/za/co/rational/OpenGlEsPolygon/OpenGlEsPolygon.java
+++ b/src/za/co/rational/OpenGlEsPolygon/OpenGlEsPolygon.java
@@ -1,73 +1,73 @@
/* Copyright (C) 2011 Nic Roets. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY Nic Roets ``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 <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.
The views and conclusions contained in the software and documentation are those of the
authors and should not be interpreted as representing official policies, either expressed
or implied, of Nic Roets.
*/
package za.co.rational.OpenGlEsPolygon;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.app.Activity;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
public class OpenGlEsPolygon extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GLSurfaceView mGLView = new OpenGlEsPolygonView(this);
setContentView(mGLView);
- }
+ }
static {
System.loadLibrary("openglespolygon");
}
}
class OpenGlEsPolygonView extends GLSurfaceView {
public OpenGlEsPolygonView(Context context) {
super(context);
OpenGlEsPolygonRenderer mRenderer = new OpenGlEsPolygonRenderer();//context);
setRenderer(mRenderer);
}
}
class OpenGlEsPolygonRenderer implements GLSurfaceView.Renderer {
private int width, height;
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
gl.glClearColor(.5f, .2f, .5f, 1);
}
public void onSurfaceChanged(GL10 gl, int w, int h) {
width = w;
height = h;
gl.glViewport(0, 0, w, h);
}
public void onDrawFrame(GL10 gl) {
nativeRender(width, height);
}
private static native void nativeRender(int w, int h);
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GLSurfaceView mGLView = new OpenGlEsPolygonView(this);
setContentView(mGLView);
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GLSurfaceView mGLView = new OpenGlEsPolygonView(this);
setContentView(mGLView);
}
|
diff --git a/app/net/sparkmuse/task/UpdateUserStatisticsTask.java b/app/net/sparkmuse/task/UpdateUserStatisticsTask.java
index 587561f..e4f4884 100644
--- a/app/net/sparkmuse/task/UpdateUserStatisticsTask.java
+++ b/app/net/sparkmuse/task/UpdateUserStatisticsTask.java
@@ -1,50 +1,50 @@
package net.sparkmuse.task;
import net.sparkmuse.common.Cache;
import net.sparkmuse.data.twig.BatchDatastoreService;
import net.sparkmuse.data.entity.UserVO;
import net.sparkmuse.data.entity.Post;
import net.sparkmuse.data.entity.SparkVO;
import com.google.inject.Inject;
import com.google.code.twig.ObjectDatastore;
import com.google.appengine.api.datastore.Query;
import play.Logger;
/**
* @author neteller
* @created: Jan 22, 2011
*/
public class UpdateUserStatisticsTask extends Task<UserVO> {
private final ObjectDatastore datastore;
@Inject
public UpdateUserStatisticsTask(Cache cache, BatchDatastoreService batchService, ObjectDatastore datastore) {
super(cache, batchService);
this.datastore = datastore;
}
public UserVO transform(UserVO userVO) {
final Integer posts = datastore.find().type(Post.class)
- .addFilter("author", Query.FilterOperator.EQUAL, userVO)
+ .addFilter("authorUserId", Query.FilterOperator.EQUAL, userVO.getId())
.returnCount()
.now();
final Integer sparks = datastore.find().type(SparkVO.class)
- .addFilter("author", Query.FilterOperator.EQUAL, userVO)
+ .addFilter("authorUserId", Query.FilterOperator.EQUAL, userVO.getId())
.returnCount()
.now();
if (userVO.getSparks() != sparks) {
Logger.error("User [" + userVO + "] reported a spark count of [" + userVO.getSparks() + "] but had [" + sparks + "] sparks.");
}
if (userVO.getPosts() != posts) {
Logger.error("User [" + userVO + "] reported a post count of [" + userVO.getPosts() + "] but had [" + posts + "] posts.");
}
userVO.setSparks(sparks);
userVO.setPosts(posts);
return userVO;
}
}
| false | true | public UserVO transform(UserVO userVO) {
final Integer posts = datastore.find().type(Post.class)
.addFilter("author", Query.FilterOperator.EQUAL, userVO)
.returnCount()
.now();
final Integer sparks = datastore.find().type(SparkVO.class)
.addFilter("author", Query.FilterOperator.EQUAL, userVO)
.returnCount()
.now();
if (userVO.getSparks() != sparks) {
Logger.error("User [" + userVO + "] reported a spark count of [" + userVO.getSparks() + "] but had [" + sparks + "] sparks.");
}
if (userVO.getPosts() != posts) {
Logger.error("User [" + userVO + "] reported a post count of [" + userVO.getPosts() + "] but had [" + posts + "] posts.");
}
userVO.setSparks(sparks);
userVO.setPosts(posts);
return userVO;
}
| public UserVO transform(UserVO userVO) {
final Integer posts = datastore.find().type(Post.class)
.addFilter("authorUserId", Query.FilterOperator.EQUAL, userVO.getId())
.returnCount()
.now();
final Integer sparks = datastore.find().type(SparkVO.class)
.addFilter("authorUserId", Query.FilterOperator.EQUAL, userVO.getId())
.returnCount()
.now();
if (userVO.getSparks() != sparks) {
Logger.error("User [" + userVO + "] reported a spark count of [" + userVO.getSparks() + "] but had [" + sparks + "] sparks.");
}
if (userVO.getPosts() != posts) {
Logger.error("User [" + userVO + "] reported a post count of [" + userVO.getPosts() + "] but had [" + posts + "] posts.");
}
userVO.setSparks(sparks);
userVO.setPosts(posts);
return userVO;
}
|
diff --git a/plugins/org.eclipse.gmf.map.edit/src/org/eclipse/gmf/mappings/provider/FeatureLabelMappingItemProvider.java b/plugins/org.eclipse.gmf.map.edit/src/org/eclipse/gmf/mappings/provider/FeatureLabelMappingItemProvider.java
index e4ac0c1af..27b817ee3 100644
--- a/plugins/org.eclipse.gmf.map.edit/src/org/eclipse/gmf/mappings/provider/FeatureLabelMappingItemProvider.java
+++ b/plugins/org.eclipse.gmf.map.edit/src/org/eclipse/gmf/mappings/provider/FeatureLabelMappingItemProvider.java
@@ -1,293 +1,293 @@
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.eclipse.gmf.mappings.provider;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ViewerNotification;
import org.eclipse.gmf.mappings.FeatureLabelMapping;
import org.eclipse.gmf.mappings.GMFMapPackage;
import org.eclipse.gmf.mappings.presentation.FilterUtil;
/**
* This is the item provider adapter for a {@link org.eclipse.gmf.mappings.FeatureLabelMapping} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class FeatureLabelMappingItemProvider
extends LabelMappingItemProvider
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public FeatureLabelMappingItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addFeaturesPropertyDescriptor(object);
addEditableFeaturesPropertyDescriptor(object);
addViewPatternPropertyDescriptor(object);
addEditorPatternPropertyDescriptor(object);
addEditPatternPropertyDescriptor(object);
addViewMethodPropertyDescriptor(object);
addEditMethodPropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Features feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
protected void addFeaturesPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(new ItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureLabelMapping_features_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureLabelMapping_features_feature", "_UI_FeatureLabelMapping_type"),
GMFMapPackage.eINSTANCE.getFeatureLabelMapping_Features(),
true,
false,
true,
null,
- null,
+ getString("_UI_DomainmetainformationPropertyCategory"),
null) {
protected Collection<?> getComboBoxObjects(Object object) {
@SuppressWarnings("unchecked")
Collection<EStructuralFeature> original = (Collection<EStructuralFeature>) super.getComboBoxObjects(object);
return FilterUtil.filterByContainerMetaclass(original, ((FeatureLabelMapping) object).getMapEntry());
}
});
}
/**
* This adds a property descriptor for the Editable Features feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addEditableFeaturesPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureLabelMapping_editableFeatures_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureLabelMapping_editableFeatures_feature", "_UI_FeatureLabelMapping_type"),
GMFMapPackage.eINSTANCE.getFeatureLabelMapping_EditableFeatures(),
true,
false,
true,
null,
getString("_UI_DomainmetainformationPropertyCategory"),
null));
}
/**
* This adds a property descriptor for the View Pattern feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addViewPatternPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureLabelMapping_viewPattern_feature"),
getString("_UI_FeatureLabelMapping_viewPattern_description"),
GMFMapPackage.eINSTANCE.getFeatureLabelMapping_ViewPattern(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
getString("_UI_VisualrepresentationPropertyCategory"),
null));
}
/**
* This adds a property descriptor for the Editor Pattern feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addEditorPatternPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureLabelMapping_editorPattern_feature"),
getString("_UI_FeatureLabelMapping_editorPattern_description"),
GMFMapPackage.eINSTANCE.getFeatureLabelMapping_EditorPattern(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
getString("_UI_VisualrepresentationPropertyCategory"),
null));
}
/**
* This adds a property descriptor for the View Method feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addViewMethodPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureLabelMapping_viewMethod_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureLabelMapping_viewMethod_feature", "_UI_FeatureLabelMapping_type"),
GMFMapPackage.eINSTANCE.getFeatureLabelMapping_ViewMethod(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
getString("_UI_VisualrepresentationPropertyCategory"),
null));
}
/**
* This adds a property descriptor for the Edit Pattern feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addEditPatternPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureLabelMapping_editPattern_feature"),
getString("_UI_FeatureLabelMapping_editPattern_description"),
GMFMapPackage.eINSTANCE.getFeatureLabelMapping_EditPattern(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
getString("_UI_VisualrepresentationPropertyCategory"),
null));
}
/**
* This adds a property descriptor for the Edit Method feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addEditMethodPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureLabelMapping_editMethod_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureLabelMapping_editMethod_feature", "_UI_FeatureLabelMapping_type"),
GMFMapPackage.eINSTANCE.getFeatureLabelMapping_EditMethod(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
getString("_UI_VisualrepresentationPropertyCategory"),
null));
}
/**
* This returns FeatureLabelMapping.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/FeatureLabelMapping"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
FeatureLabelMapping featureLabelMapping = (FeatureLabelMapping)object;
return getString("_UI_FeatureLabelMapping_type") + " " + featureLabelMapping.isReadOnly();
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(FeatureLabelMapping.class)) {
case GMFMapPackage.FEATURE_LABEL_MAPPING__VIEW_PATTERN:
case GMFMapPackage.FEATURE_LABEL_MAPPING__EDITOR_PATTERN:
case GMFMapPackage.FEATURE_LABEL_MAPPING__EDIT_PATTERN:
case GMFMapPackage.FEATURE_LABEL_MAPPING__VIEW_METHOD:
case GMFMapPackage.FEATURE_LABEL_MAPPING__EDIT_METHOD:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
}
| true | true | protected void addFeaturesPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(new ItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureLabelMapping_features_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureLabelMapping_features_feature", "_UI_FeatureLabelMapping_type"),
GMFMapPackage.eINSTANCE.getFeatureLabelMapping_Features(),
true,
false,
true,
null,
null,
null) {
protected Collection<?> getComboBoxObjects(Object object) {
@SuppressWarnings("unchecked")
Collection<EStructuralFeature> original = (Collection<EStructuralFeature>) super.getComboBoxObjects(object);
return FilterUtil.filterByContainerMetaclass(original, ((FeatureLabelMapping) object).getMapEntry());
}
});
}
| protected void addFeaturesPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(new ItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_FeatureLabelMapping_features_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_FeatureLabelMapping_features_feature", "_UI_FeatureLabelMapping_type"),
GMFMapPackage.eINSTANCE.getFeatureLabelMapping_Features(),
true,
false,
true,
null,
getString("_UI_DomainmetainformationPropertyCategory"),
null) {
protected Collection<?> getComboBoxObjects(Object object) {
@SuppressWarnings("unchecked")
Collection<EStructuralFeature> original = (Collection<EStructuralFeature>) super.getComboBoxObjects(object);
return FilterUtil.filterByContainerMetaclass(original, ((FeatureLabelMapping) object).getMapEntry());
}
});
}
|
diff --git a/regression/jvm/ObjectCreationAndManipulationTest.java b/regression/jvm/ObjectCreationAndManipulationTest.java
index e87c3267..9d73ece9 100644
--- a/regression/jvm/ObjectCreationAndManipulationTest.java
+++ b/regression/jvm/ObjectCreationAndManipulationTest.java
@@ -1,177 +1,175 @@
/*
* Copyright (C) 2006 Pekka Enberg
*
* This file is released under the GPL version 2 with the following
* clarification and special exception:
*
* Linking this library statically or dynamically with other modules is
* making a combined work based on this library. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent
* modules, and to copy and distribute the resulting executable under terms
* of your choice, provided that you also meet, for each linked independent
* module, the terms and conditions of the license of that module. An
* independent module is a module which is not derived from or based on
* this library. If you modify this library, you may extend this exception
* to your version of the library, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
* Please refer to the file LICENSE for details.
*/
package jvm;
/**
* @author Pekka Enberg
*/
public class ObjectCreationAndManipulationTest extends TestCase {
public static void testNewObject() {
Object obj = null;
assertNull(obj);
obj = new Object();
assertNotNull(obj);
}
public static void testObjectInitialization() {
InitializingClass obj = new InitializingClass(1);
assertEquals(1, obj.value);
}
public static void testInstanceFieldAccess() {
InstanceFields fields = new InstanceFields();
assertEquals(0, fields.field);
fields.field = 1;
assertEquals(1, fields.field);
}
public static void testNewArray() {
int[] array = null;
assertNull(array);
array = new int[5];
assertNotNull(array);
}
public static void testANewArray() {
Object[] array = null;
assertNull(array);
array = new Object[255];
assertNotNull(array);
}
public static void testArrayLength() {
Object[] array = new Object[255];
assertEquals(255, array.length);
}
public static void testMultiANewArray() {
Object[][] array = null;
assertNull(array);
array = new Object[5][4];
assertNotNull(array);
assertEquals(5, array.length);
}
public static void testIsInstanceOf() {
ClassFields obj = new ClassFields();
assertTrue(obj instanceof ClassFields);
assertTrue(obj instanceof Object);
assertFalse(null instanceof Object);
}
public static void testByteArrayLoadAndStore() {
byte[] array = new byte[5];
array[1] = 1;
assertEquals(array[1], 1);
}
public static void testCharArrayLoadAndStore() {
char[] array = new char[5];
array[1] = 65535;
assertEquals(array[1], 65535);
}
public static void testShortArrayLoadAndStore() {
short[] array = new short[5];
array[3] = 1;
assertEquals(array[3], 1);
}
public static void testIntArrayLoadAndStore() {
int[] array = new int[5];
array[1] = 1;
assertEquals(1, array[1]);
}
public static void testObjectArrayLoadAndStore() {
InitializingClass[] array = new InitializingClass[5];
InitializingClass obj = new InitializingClass(1);
array[2] = obj;
assertEquals(array[2], obj);
}
public static void testMultiDimensionalArrayLoadAndStore() {
int[][] array = new int[5][5];
array[0][0] = 0;
}
public static void testCheckCast() {
Object object = new InstanceFields();
InstanceFields instanceFields = (InstanceFields) null;
assertNull(instanceFields);
instanceFields = (InstanceFields) object;
assertNotNull(instanceFields);
//Following test will fail.
/*
ClassFields classField = new ClassFields();
object = classField;
instanceFields = (InstanceFields) object;
*/
}
public static void main(String[] args) {
testNewObject();
testObjectInitialization();
testInstanceFieldAccess();
testNewArray();
testANewArray();
testArrayLength();
testMultiANewArray();
testIsInstanceOf();
-/* FIXME:
testIntArrayLoadAndStore();
testCharArrayLoadAndStore();
testByteArrayLoadAndStore();
testShortArrayLoadAndStore();
testObjectArrayLoadAndStore();
testMultiDimensionalArrayLoadAndStore();
-*/
testCheckCast();
exit();
}
private static class InitializingClass {
public int value;
public InitializingClass(int value) {
this.value = value;
}
};
private static class ClassFields {
public static int field;
};
private static class InstanceFields {
public int field;
};
}
| false | true | public static void main(String[] args) {
testNewObject();
testObjectInitialization();
testInstanceFieldAccess();
testNewArray();
testANewArray();
testArrayLength();
testMultiANewArray();
testIsInstanceOf();
/* FIXME:
testIntArrayLoadAndStore();
testCharArrayLoadAndStore();
testByteArrayLoadAndStore();
testShortArrayLoadAndStore();
testObjectArrayLoadAndStore();
testMultiDimensionalArrayLoadAndStore();
*/
testCheckCast();
exit();
}
| public static void main(String[] args) {
testNewObject();
testObjectInitialization();
testInstanceFieldAccess();
testNewArray();
testANewArray();
testArrayLength();
testMultiANewArray();
testIsInstanceOf();
testIntArrayLoadAndStore();
testCharArrayLoadAndStore();
testByteArrayLoadAndStore();
testShortArrayLoadAndStore();
testObjectArrayLoadAndStore();
testMultiDimensionalArrayLoadAndStore();
testCheckCast();
exit();
}
|
diff --git a/eu.alert-project.iccs.stardom.core/eu.alert-project.iccs.stardom.alert-connector/src/main/java/eu/alertproject/iccs/stardom/activemqconnector/internal/MailNewMailListener.java b/eu.alert-project.iccs.stardom.core/eu.alert-project.iccs.stardom.alert-connector/src/main/java/eu/alertproject/iccs/stardom/activemqconnector/internal/MailNewMailListener.java
index 2c006cd..729f0f3 100644
--- a/eu.alert-project.iccs.stardom.core/eu.alert-project.iccs.stardom.alert-connector/src/main/java/eu/alertproject/iccs/stardom/activemqconnector/internal/MailNewMailListener.java
+++ b/eu.alert-project.iccs.stardom.core/eu.alert-project.iccs.stardom.alert-connector/src/main/java/eu/alertproject/iccs/stardom/activemqconnector/internal/MailNewMailListener.java
@@ -1,82 +1,83 @@
package eu.alertproject.iccs.stardom.activemqconnector.internal;
import eu.alertproject.iccs.stardom.activemqconnector.api.AbstractActiveMQListener;
import eu.alertproject.iccs.stardom.analyzers.mailing.bus.MailingEvent;
import eu.alertproject.iccs.stardom.analyzers.mailing.connector.MailingListConnectorContext;
import eu.alertproject.iccs.stardom.bus.api.Bus;
import eu.alertproject.iccs.stardom.connector.api.Subscriber;
import org.apache.activemq.command.ActiveMQMessage;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
/**
* User: fotis
* Date: 05/11/11
* Time: 19:12
*/
@Component("mailNewMailListener")
public class MailNewMailListener extends AbstractActiveMQListener{
private Logger logger = LoggerFactory.getLogger(MailNewMailListener.class);
@Autowired
Properties systemProperties;
@Override
public void process(Message message) throws IOException, JMSException {
MailingListConnectorContext context = null;
ObjectMapper mapper = new ObjectMapper();
String text = ((TextMessage) message).getText();
if(StringUtils.isEmpty(text)){
logger.warn("A message received doesn't contain no information so I am ignoring");
return;
}
logger.trace("void onMessage() Text to parse {} ",text);
context= mapper.readValue(IOUtils.toInputStream(text),MailingListConnectorContext.class);
String filterDate = systemProperties.getProperty("analyzers.filterDate");
Date when = null;
try {
when = DateUtils.parseDate(filterDate, new String[]{"yyyy-MM-dd"});
} catch (ParseException e) {
//nothing
+ logger.error("void process() Couldn't parse filterDate = ({}) ",filterDate);
}
if (when == null || ( context.getAction().getDate() != null && context.getAction().getDate().before(when) ) ) {
logger.trace("void action() Ignoring action because date {} is before {}", context.getAction().getDate(), when);
return;
}
fixProfile(context);
MailingEvent mailEvent = new MailingEvent(this,context);
logger.trace("void onMessage() {} ",mailEvent);
Bus.publish(mailEvent);
}
}
| true | true | public void process(Message message) throws IOException, JMSException {
MailingListConnectorContext context = null;
ObjectMapper mapper = new ObjectMapper();
String text = ((TextMessage) message).getText();
if(StringUtils.isEmpty(text)){
logger.warn("A message received doesn't contain no information so I am ignoring");
return;
}
logger.trace("void onMessage() Text to parse {} ",text);
context= mapper.readValue(IOUtils.toInputStream(text),MailingListConnectorContext.class);
String filterDate = systemProperties.getProperty("analyzers.filterDate");
Date when = null;
try {
when = DateUtils.parseDate(filterDate, new String[]{"yyyy-MM-dd"});
} catch (ParseException e) {
//nothing
}
if (when == null || ( context.getAction().getDate() != null && context.getAction().getDate().before(when) ) ) {
logger.trace("void action() Ignoring action because date {} is before {}", context.getAction().getDate(), when);
return;
}
fixProfile(context);
MailingEvent mailEvent = new MailingEvent(this,context);
logger.trace("void onMessage() {} ",mailEvent);
Bus.publish(mailEvent);
}
| public void process(Message message) throws IOException, JMSException {
MailingListConnectorContext context = null;
ObjectMapper mapper = new ObjectMapper();
String text = ((TextMessage) message).getText();
if(StringUtils.isEmpty(text)){
logger.warn("A message received doesn't contain no information so I am ignoring");
return;
}
logger.trace("void onMessage() Text to parse {} ",text);
context= mapper.readValue(IOUtils.toInputStream(text),MailingListConnectorContext.class);
String filterDate = systemProperties.getProperty("analyzers.filterDate");
Date when = null;
try {
when = DateUtils.parseDate(filterDate, new String[]{"yyyy-MM-dd"});
} catch (ParseException e) {
//nothing
logger.error("void process() Couldn't parse filterDate = ({}) ",filterDate);
}
if (when == null || ( context.getAction().getDate() != null && context.getAction().getDate().before(when) ) ) {
logger.trace("void action() Ignoring action because date {} is before {}", context.getAction().getDate(), when);
return;
}
fixProfile(context);
MailingEvent mailEvent = new MailingEvent(this,context);
logger.trace("void onMessage() {} ",mailEvent);
Bus.publish(mailEvent);
}
|
diff --git a/jsf-ri/src/main/java/com/sun/faces/renderkit/html_basic/StylesheetRenderer.java b/jsf-ri/src/main/java/com/sun/faces/renderkit/html_basic/StylesheetRenderer.java
index 4c72edc2d..98c9a792c 100644
--- a/jsf-ri/src/main/java/com/sun/faces/renderkit/html_basic/StylesheetRenderer.java
+++ b/jsf-ri/src/main/java/com/sun/faces/renderkit/html_basic/StylesheetRenderer.java
@@ -1,115 +1,115 @@
/*
* 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.faces.renderkit.html_basic;
import java.io.IOException;
import java.util.Map;
import javax.faces.application.Resource;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
/**
* <p>This <code>Renderer</code> handles the rendering of external <code>stylesheet</code>
* references.</p>
*/
public class StylesheetRenderer extends ScriptStyleBaseRenderer {
@Override
protected void startElement(ResponseWriter writer, UIComponent component) throws IOException {
writer.startElement("style", component);
writer.writeAttribute("type", "text/css", "type");
}
@Override
protected void endElement(ResponseWriter writer) throws IOException {
writer.endElement("style");
}
@Override
protected String verifyTarget(String toVerify) {
return "head";
}
@Override
public void encodeEnd(FacesContext context, UIComponent component)
throws IOException {
Map<String,Object> attributes = component.getAttributes();
Map<Object, Object> contextMap = context.getAttributes();
String name = (String) attributes.get("name");
String library = (String) attributes.get("library");
String key = name + library;
String media = (String) attributes.get("media");
if (null == name) {
return;
}
// Ensure this stylesheet is not rendered more than once per request
if (contextMap.containsKey(key)) {
return;
}
contextMap.put(key, Boolean.TRUE);
Resource resource = context.getApplication().getResourceHandler()
.createResource(name, library);
ResponseWriter writer = context.getResponseWriter();
writer.startElement("link", component);
writer.writeAttribute("type", "text/css", "type");
writer.writeAttribute("rel", "stylesheet", "rel");
- writer.writeURIAttribute("href",
- ((resource != null)
- ? resource.getRequestPath()
- : "RES_NOT_FOUND"),
- "href");
+ String resourceUrl = "RES_NOT_FOUND";
+ if (resource != null) {
+ resourceUrl = context.getExternalContext().encodeResourceURL(resource.getRequestPath());
+ }
+ writer.writeURIAttribute("href", resourceUrl, "href");
if (media != null) {
writer.writeAttribute("media", media, "media");
}
writer.endElement("link");
super.encodeEnd(context, component);
}
}
| true | true | public void encodeEnd(FacesContext context, UIComponent component)
throws IOException {
Map<String,Object> attributes = component.getAttributes();
Map<Object, Object> contextMap = context.getAttributes();
String name = (String) attributes.get("name");
String library = (String) attributes.get("library");
String key = name + library;
String media = (String) attributes.get("media");
if (null == name) {
return;
}
// Ensure this stylesheet is not rendered more than once per request
if (contextMap.containsKey(key)) {
return;
}
contextMap.put(key, Boolean.TRUE);
Resource resource = context.getApplication().getResourceHandler()
.createResource(name, library);
ResponseWriter writer = context.getResponseWriter();
writer.startElement("link", component);
writer.writeAttribute("type", "text/css", "type");
writer.writeAttribute("rel", "stylesheet", "rel");
writer.writeURIAttribute("href",
((resource != null)
? resource.getRequestPath()
: "RES_NOT_FOUND"),
"href");
if (media != null) {
writer.writeAttribute("media", media, "media");
}
writer.endElement("link");
super.encodeEnd(context, component);
}
| public void encodeEnd(FacesContext context, UIComponent component)
throws IOException {
Map<String,Object> attributes = component.getAttributes();
Map<Object, Object> contextMap = context.getAttributes();
String name = (String) attributes.get("name");
String library = (String) attributes.get("library");
String key = name + library;
String media = (String) attributes.get("media");
if (null == name) {
return;
}
// Ensure this stylesheet is not rendered more than once per request
if (contextMap.containsKey(key)) {
return;
}
contextMap.put(key, Boolean.TRUE);
Resource resource = context.getApplication().getResourceHandler()
.createResource(name, library);
ResponseWriter writer = context.getResponseWriter();
writer.startElement("link", component);
writer.writeAttribute("type", "text/css", "type");
writer.writeAttribute("rel", "stylesheet", "rel");
String resourceUrl = "RES_NOT_FOUND";
if (resource != null) {
resourceUrl = context.getExternalContext().encodeResourceURL(resource.getRequestPath());
}
writer.writeURIAttribute("href", resourceUrl, "href");
if (media != null) {
writer.writeAttribute("media", media, "media");
}
writer.endElement("link");
super.encodeEnd(context, component);
}
|
diff --git a/src/main/java/org/spoutcraft/client/inventory/InventoryUtil.java b/src/main/java/org/spoutcraft/client/inventory/InventoryUtil.java
index 224c2fca..63551a2c 100644
--- a/src/main/java/org/spoutcraft/client/inventory/InventoryUtil.java
+++ b/src/main/java/org/spoutcraft/client/inventory/InventoryUtil.java
@@ -1,74 +1,76 @@
/*
* This file is part of Spoutcraft.
*
* Copyright (c) 2011-2012, SpoutDev <http://www.spout.org/>
* Spoutcraft is licensed under the GNU Lesser General Public License.
*
* Spoutcraft 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.
*
* Spoutcraft is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.spoutcraft.client.inventory;
import net.minecraft.client.Minecraft;
import net.minecraft.src.Container;
import net.minecraft.src.EntityClientPlayerMP;
import net.minecraft.src.InventoryPlayer;
import net.minecraft.src.ItemStack;
import net.minecraft.src.Packet101CloseWindow;
import net.minecraft.src.Slot;
public class InventoryUtil {
public static void replaceItem(int id, int damage) {
int slot = -1;
InventoryPlayer inventory = Minecraft.theMinecraft.thePlayer.inventory;
for (int i = 0; i < inventory.mainInventory.length; i++) {
if (inventory.mainInventory[i] != null && i != inventory.currentItem) {
if (inventory.mainInventory[i].itemID == id && (damage == -1 || (damage == inventory.mainInventory[i].getItemDamage()))) {
if (!Minecraft.theMinecraft.isMultiplayerWorld()) {
inventory.mainInventory[inventory.currentItem].stackSize = inventory.mainInventory[i].stackSize;
inventory.mainInventory[inventory.currentItem].setItemDamage(inventory.mainInventory[i].getItemDamage());
inventory.mainInventory[i] = null;
}
slot = i;
break;
}
}
}
if (Minecraft.theMinecraft.isMultiplayerWorld() && slot > -1) {
int window = Minecraft.theMinecraft.thePlayer.craftingInventory.windowId;
ItemStack replacement = inventory.mainInventory[slot].copy();
Minecraft.theMinecraft.playerController.windowClick(window, slot < 9 ? slot + 36 : slot, 0, false, Minecraft.theMinecraft.thePlayer);
Minecraft.theMinecraft.playerController.windowClick(window, inventory.currentItem + 36, 0, false, Minecraft.theMinecraft.thePlayer);
((EntityClientPlayerMP)Minecraft.theMinecraft.thePlayer).sendQueue.addToSendQueue(new Packet101CloseWindow(window));
((EntityClientPlayerMP)Minecraft.theMinecraft.thePlayer).sendQueue.queued = true;
((EntityClientPlayerMP)Minecraft.theMinecraft.thePlayer).sendQueue.packetQueueTime = System.currentTimeMillis() + 30L;
ItemStack current = inventory.mainInventory[inventory.currentItem];
- current.stackSize = replacement.stackSize;
- current.setItemDamage(replacement.getItemDamage());
+ if(replacement != null && current != null) {
+ current.stackSize = replacement.stackSize;
+ current.setItemDamage(replacement.getItemDamage());
+ }
inventory.mainInventory[slot] = null;
}
}
public static Slot getSlotFromPosition(int pos, Container inventorySlots) {
for (int i = 0; i < inventorySlots.inventorySlots.size(); i++) {
if (inventorySlots.inventorySlots.get(i) != null) {
if (((Slot)inventorySlots.inventorySlots.get(i)).slotIndex == pos) {
return ((Slot)inventorySlots.inventorySlots.get(i));
}
}
}
return null;
}
}
| true | true | public static void replaceItem(int id, int damage) {
int slot = -1;
InventoryPlayer inventory = Minecraft.theMinecraft.thePlayer.inventory;
for (int i = 0; i < inventory.mainInventory.length; i++) {
if (inventory.mainInventory[i] != null && i != inventory.currentItem) {
if (inventory.mainInventory[i].itemID == id && (damage == -1 || (damage == inventory.mainInventory[i].getItemDamage()))) {
if (!Minecraft.theMinecraft.isMultiplayerWorld()) {
inventory.mainInventory[inventory.currentItem].stackSize = inventory.mainInventory[i].stackSize;
inventory.mainInventory[inventory.currentItem].setItemDamage(inventory.mainInventory[i].getItemDamage());
inventory.mainInventory[i] = null;
}
slot = i;
break;
}
}
}
if (Minecraft.theMinecraft.isMultiplayerWorld() && slot > -1) {
int window = Minecraft.theMinecraft.thePlayer.craftingInventory.windowId;
ItemStack replacement = inventory.mainInventory[slot].copy();
Minecraft.theMinecraft.playerController.windowClick(window, slot < 9 ? slot + 36 : slot, 0, false, Minecraft.theMinecraft.thePlayer);
Minecraft.theMinecraft.playerController.windowClick(window, inventory.currentItem + 36, 0, false, Minecraft.theMinecraft.thePlayer);
((EntityClientPlayerMP)Minecraft.theMinecraft.thePlayer).sendQueue.addToSendQueue(new Packet101CloseWindow(window));
((EntityClientPlayerMP)Minecraft.theMinecraft.thePlayer).sendQueue.queued = true;
((EntityClientPlayerMP)Minecraft.theMinecraft.thePlayer).sendQueue.packetQueueTime = System.currentTimeMillis() + 30L;
ItemStack current = inventory.mainInventory[inventory.currentItem];
current.stackSize = replacement.stackSize;
current.setItemDamage(replacement.getItemDamage());
inventory.mainInventory[slot] = null;
}
}
| public static void replaceItem(int id, int damage) {
int slot = -1;
InventoryPlayer inventory = Minecraft.theMinecraft.thePlayer.inventory;
for (int i = 0; i < inventory.mainInventory.length; i++) {
if (inventory.mainInventory[i] != null && i != inventory.currentItem) {
if (inventory.mainInventory[i].itemID == id && (damage == -1 || (damage == inventory.mainInventory[i].getItemDamage()))) {
if (!Minecraft.theMinecraft.isMultiplayerWorld()) {
inventory.mainInventory[inventory.currentItem].stackSize = inventory.mainInventory[i].stackSize;
inventory.mainInventory[inventory.currentItem].setItemDamage(inventory.mainInventory[i].getItemDamage());
inventory.mainInventory[i] = null;
}
slot = i;
break;
}
}
}
if (Minecraft.theMinecraft.isMultiplayerWorld() && slot > -1) {
int window = Minecraft.theMinecraft.thePlayer.craftingInventory.windowId;
ItemStack replacement = inventory.mainInventory[slot].copy();
Minecraft.theMinecraft.playerController.windowClick(window, slot < 9 ? slot + 36 : slot, 0, false, Minecraft.theMinecraft.thePlayer);
Minecraft.theMinecraft.playerController.windowClick(window, inventory.currentItem + 36, 0, false, Minecraft.theMinecraft.thePlayer);
((EntityClientPlayerMP)Minecraft.theMinecraft.thePlayer).sendQueue.addToSendQueue(new Packet101CloseWindow(window));
((EntityClientPlayerMP)Minecraft.theMinecraft.thePlayer).sendQueue.queued = true;
((EntityClientPlayerMP)Minecraft.theMinecraft.thePlayer).sendQueue.packetQueueTime = System.currentTimeMillis() + 30L;
ItemStack current = inventory.mainInventory[inventory.currentItem];
if(replacement != null && current != null) {
current.stackSize = replacement.stackSize;
current.setItemDamage(replacement.getItemDamage());
}
inventory.mainInventory[slot] = null;
}
}
|
diff --git a/arith/ModInteger.java b/arith/ModInteger.java
index 25bdd2f1..c7d8c605 100644
--- a/arith/ModInteger.java
+++ b/arith/ModInteger.java
@@ -1,699 +1,699 @@
/*
* $Id$
*/
package edu.jas.arith;
import java.util.Random;
import java.io.Reader;
import edu.jas.structure.GcdRingElem;
import edu.jas.structure.RingFactory;
import edu.jas.structure.PrettyPrint;
import edu.jas.util.StringUtil;
/**
* ModInteger class with RingElem interface
* and with the familiar SAC method names.
* Objects of this class are immutable.
* @author Heinz Kredel
* @see java.math.BigInteger
*/
public final class ModInteger implements GcdRingElem<ModInteger>,
RingFactory<ModInteger> {
/** Module part of the factory data structure.
*/
protected final java.math.BigInteger modul;
/** Value part of the element data structure.
*/
protected final java.math.BigInteger val;
private final static Random random = new Random();
/** Indicator if this ring is a field.
*/
protected int isField = -1; // initially unknown
/** Certainty if module is probable prime.
*/
protected int certainty = 10;
/** The constructor creates a ModInteger object
* from two BigInteger objects module and value part.
* @param m math.BigInteger.
* @param a math.BigInteger.
*/
public ModInteger(java.math.BigInteger m, java.math.BigInteger a) {
modul = m;
val = a.mod(modul);
}
/** The constructor creates a ModInteger object
* from two BigInteger objects module and value part.
* @param m math.BigInteger.
* @param a math.BigInteger.
* @param isField indicator if m is prime.
*/
public ModInteger(java.math.BigInteger m, java.math.BigInteger a,
boolean isField) {
modul = m;
val = a.mod(modul);
this.isField = ( isField ? 1 : 0 );
}
/** The constructor creates a ModInteger object
* from two longs objects module and value part.
* @param m long.
* @param a long.
*/
public ModInteger(long m, long a) {
this(
new java.math.BigInteger( String.valueOf(m) ),
new java.math.BigInteger( String.valueOf(a) )
);
}
/** The constructor creates a ModInteger object
* from two longs objects module and value part.
* @param m long.
* @param a long.
* @param isField indicator if m is prime.
*/
public ModInteger(long m, long a, boolean isField) {
this(
new java.math.BigInteger( String.valueOf(m) ),
new java.math.BigInteger( String.valueOf(a) ),
isField
);
}
/** The constructor creates a ModInteger object
* from two String objects module and value part.
* @param m String.
* @param s String.
*/
public ModInteger(String m, String s) {
this(
new java.math.BigInteger( m.trim() ),
new java.math.BigInteger( s.trim() )
);
}
/** The constructor creates a ModInteger object
* from a BigInteger object module and a String value part.
* @param m BigInteger.
* @param s String.
*/
public ModInteger(java.math.BigInteger m, String s) {
this( m, new java.math.BigInteger( s.trim() ) );
}
/** The constructor creates a ModInteger object
* from a BigInteger object module and a long value part.
* @param m BigInteger.
* @param s long.
*/
public ModInteger(java.math.BigInteger m, long s) {
this( m, new java.math.BigInteger( String.valueOf(s) ) );
}
/** The constructor creates a 0 ModInteger object
* from a BigInteger object module.
* @param m BigInteger.
*/
public ModInteger(java.math.BigInteger m) {
modul = m; // assert m != 0
val = java.math.BigInteger.ZERO;
}
/** The constructor creates a 0 ModInteger object
* from a BigInteger object module.
* @param m BigInteger.
* @param isField indicator if m is prime.
*/
public ModInteger(java.math.BigInteger m, boolean isField) {
modul = m; // assert m != 0
val = java.math.BigInteger.ZERO;
this.isField = ( isField ? 1 : 0 );
}
/** Get the value part.
* @return val.
*/
public java.math.BigInteger getVal() {
return val;
}
/** Get the module part.
* @return modul.
*/
public java.math.BigInteger getModul() {
return modul;
}
/** Clone this.
* @see java.lang.Object#clone()
*/
public ModInteger clone() {
return new ModInteger( modul, val );
}
/** Copy ModInteger element c.
* @param c
* @return a copy of c.
*/
public ModInteger copy(ModInteger c) {
return new ModInteger( c.modul, c.val );
}
/** Get the zero element.
* @return 0 as ModInteger.
*/
public ModInteger getZERO() {
return new ModInteger( modul, java.math.BigInteger.ZERO );
}
/** Get the one element.
* @return 1 as ModInteger.
*/
public ModInteger getONE() {
return new ModInteger( modul, java.math.BigInteger.ONE );
}
/**
* Query if this ring is commutative.
* @return true.
*/
public boolean isCommutative() {
return true;
}
/**
* Query if this ring is associative.
* @return true.
*/
public boolean isAssociative() {
return true;
}
/**
* Query if this ring is a field.
* @return true if module is prime, else false.
*/
public boolean isField() {
if ( isField > 0 ) {
return true;
}
if ( isField == 0 ) {
return false;
}
if ( modul.isProbablePrime(certainty) ) {
isField = 1;
return true;
}
isField = 0;
return false;
}
/** Get a ModInteger element from a BigInteger value.
* @param a BigInteger.
* @return a ModInteger.
*/
public ModInteger fromInteger(java.math.BigInteger a) {
return new ModInteger(modul,a);
}
/** Get a ModInteger element from a long value.
* @param a long.
* @return a ModInteger.
*/
public ModInteger fromInteger(long a) {
return new ModInteger(modul, a );
}
/** Is ModInteger number zero.
* @return If this is 0 then true is returned, else false.
* @see edu.jas.structure.RingElem#isZERO()
*/
public boolean isZERO() {
return val.equals( java.math.BigInteger.ZERO );
}
/** Is ModInteger number one.
* @return If this is 1 then true is returned, else false.
* @see edu.jas.structure.RingElem#isONE()
*/
public boolean isONE() {
return val.equals( java.math.BigInteger.ONE );
}
/** Is ModInteger number a unit.
* @return If this is a unit then true is returned, else false.
* @see edu.jas.structure.RingElem#isUnit()
*/
public boolean isUnit() {
if ( isZERO() ) {
return false;
}
if ( isField() ) {
return true;
}
java.math.BigInteger g = modul.gcd( val ).abs();
return ( g.equals( java.math.BigInteger.ONE ) );
}
/** Get the String representation.
* @see java.lang.Object#toString()
*/
public String toString() {
if ( PrettyPrint.isTrue() ) {
return val.toString();
} else {
return val.toString() + " mod(" + modul.toString() + ")";
}
}
/** ModInteger comparison.
* @param b ModInteger.
* @return sign(this-b).
*/
public int compareTo(ModInteger b) {
java.math.BigInteger v = b.val;
if ( modul != b.modul ) {
v = v.mod( modul );
}
return val.compareTo( v );
}
/** ModInteger comparison.
* @param A ModInteger.
* @param B ModInteger.
* @return sign(this-b).
*/
public static int MICOMP(ModInteger A, ModInteger B) {
if ( A == null ) return -B.signum();
return A.compareTo(B);
}
/** Comparison with any other object.
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object b) {
if ( ! ( b instanceof ModInteger ) ) {
return false;
}
return (0 == compareTo( (ModInteger)b) );
}
/** Hash code for this ModInteger.
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return 37 * val.hashCode() + modul.hashCode();
}
/** ModInteger absolute value.
* @return the absolute value of this.
* @see edu.jas.structure.RingElem#abs()
*/
public ModInteger abs() {
return new ModInteger( modul, val.abs() );
}
/** ModInteger absolute value.
* @param A ModInteger.
* @return the absolute value of A.
*/
public static ModInteger MIABS(ModInteger A) {
if ( A == null ) return null;
return A.abs();
}
/** ModInteger negative.
* @see edu.jas.structure.RingElem#negate()
* @return -this.
*/
public ModInteger negate() {
return new ModInteger( modul, val.negate() );
}
/** ModInteger negative.
* @param A ModInteger.
* @return -A.
*/
public static ModInteger MINEG(ModInteger A) {
if ( A == null ) return null;
return A.negate();
}
/** ModInteger signum.
* @see edu.jas.structure.RingElem#signum()
* @return signum(this).
*/
public int signum() {
return val.signum();
}
/** ModInteger signum.
* @param A ModInteger
* @return signum(A).
*/
public static int MISIGN(ModInteger A) {
if ( A == null ) return 0;
return A.signum();
}
/** ModInteger subtraction.
* @param S ModInteger.
* @return this-S.
*/
public ModInteger subtract(ModInteger S) {
return new ModInteger( modul, val.subtract( S.val ) );
}
/** ModInteger subtraction.
* @param A ModInteger.
* @param B ModInteger.
* @return A-B.
*/
public static ModInteger MIDIF(ModInteger A, ModInteger B) {
if ( A == null ) return B.negate();
return A.subtract(B);
}
/** ModInteger divide.
* @param S ModInteger.
* @return this/S.
*/
public ModInteger divide(ModInteger S) {
return multiply( S.inverse() );
}
/** ModInteger quotient.
* @param A ModInteger.
* @param B ModInteger.
* @return A/B.
*/
public static ModInteger MIQ(ModInteger A, ModInteger B) {
if ( A == null ) return null;
return A.divide(B);
}
/** ModInteger inverse.
* @see edu.jas.structure.RingElem#inverse()
* @return S with S=1/this if defined.
*/
public ModInteger inverse() {
return new ModInteger( modul, val.modInverse( modul ));
}
/** ModInteger inverse.
* @param A is a non-zero integer.
* @see edu.jas.structure.RingElem#inverse()
* @return S with S=1/A if defined.
*/
public static ModInteger MIINV(ModInteger A) {
if ( A == null ) return null;
return A.inverse();
}
/** ModInteger remainder.
* @param S ModInteger.
* @return remainder(this,S).
*/
public ModInteger remainder(ModInteger S) {
if ( S == null || S.isZERO()) {
throw new RuntimeException(this.getClass().getName()
+ " division by zero");
}
if ( S.isONE()) {
return getZERO();
}
if ( S.isUnit() ) {
return getZERO();
}
return new ModInteger( modul, val.remainder( S.val ) );
}
/** ModInteger remainder.
* @param A ModInteger.
* @param B ModInteger.
* @return A - (A/B)*B.
*/
public static ModInteger MIREM(ModInteger A, ModInteger B) {
if ( A == null ) return null;
return A.remainder(B);
}
/** ModInteger random.
* @param n such that 0 ≤ v ≤ (2<sup>n</sup>-1).
* @return a random integer mod modul.
*/
public ModInteger random(int n) {
return random( n, random );
}
/** ModInteger random.
* @param n such that 0 ≤ v ≤ (2<sup>n</sup>-1).
* @param rnd is a source for random bits.
* @return a random integer mod modul.
*/
public ModInteger random(int n, Random rnd) {
java.math.BigInteger v = new java.math.BigInteger( n, rnd );
return new ModInteger( modul, v );
}
/** ModInteger multiply.
* @param S ModInteger.
* @return this*S.
*/
public ModInteger multiply(ModInteger S) {
return new ModInteger( modul, val.multiply( S.val ) );
}
/** ModInteger product.
* @param A ModInteger.
* @param B ModInteger.
* @return A*B.
*/
public static ModInteger MIPROD(ModInteger A, ModInteger B) {
if ( A == null ) return null;
return A.multiply(B);
}
/** ModInteger summation.
* @param S ModInteger.
* @return this+S.
*/
public ModInteger sum(ModInteger S) {
return new ModInteger( modul, val.add( S.val ) );
}
/** ModInteger summation.
* @param A ModInteger.
* @param B ModInteger.
* @return A+B.
*/
public static ModInteger MISUM(ModInteger A, ModInteger B) {
if ( A == null ) return null;
return A.sum(B);
}
/** Parse ModInteger from String.
* @param s String.
* @return ModInteger from s.
*/
public ModInteger parse(String s) {
return new ModInteger(modul,s);
}
/** Parse ModInteger from Reader.
* @param r Reader.
* @return next ModInteger from r.
*/
public ModInteger parse(Reader r) {
return parse( StringUtil.nextString(r) );
}
/** ModInteger greatest common divisor.
* @param S ModInteger.
* @return gcd(this,S).
*/
public ModInteger gcd(ModInteger S) {
if ( S.isZERO() ) {
return this;
}
if ( isZERO() ) {
return S;
}
if ( isUnit() || S.isUnit() ) {
return getONE();
}
return new ModInteger( modul, val.gcd( S.val ) );
}
/**
* ModInteger extended greatest common divisor.
* @param S ModInteger.
* @return [ gcd(this,S), a, b ] with a*this + b*S = gcd(this,S).
*/
public ModInteger[] egcd(ModInteger S) {
ModInteger[] ret = new ModInteger[3];
ret[0] = null;
ret[1] = null;
ret[2] = null;
if ( S == null || S.isZERO() ) {
ret[0] = this;
return ret;
}
if ( isZERO() ) {
ret[0] = S;
return ret;
}
if ( this.isUnit() || S.isUnit() ) {
ret[0] = getONE();
if ( this.isUnit() && S.isUnit() ) {
ModInteger half = fromInteger(2).inverse();
ret[1] = this.inverse().multiply(half);
ret[2] = S.inverse().multiply(half);
return ret;
}
if ( this.isUnit() ) {
// oder inverse(S-1)?
ret[1] = this.inverse();
ret[2] = getZERO();
return ret;
}
// if ( S.isUnit() ) {
// oder inverse(this-1)?
ret[1] = getZERO();
ret[2] = S.inverse();
return ret;
//}
}
//System.out.println("this = " + this + ", S = " + S);
java.math.BigInteger[] qr;
java.math.BigInteger q = this.val;
java.math.BigInteger r = S.val;
java.math.BigInteger c1 = BigInteger.ONE.val;
java.math.BigInteger d1 = BigInteger.ZERO.val;
java.math.BigInteger c2 = BigInteger.ZERO.val;
java.math.BigInteger d2 = BigInteger.ONE.val;
java.math.BigInteger x1;
java.math.BigInteger x2;
- while ( r.equals(java.math.BigInteger.ZERO) ) {
+ while ( !r.equals(java.math.BigInteger.ZERO) ) {
qr = q.divideAndRemainder(r);
q = qr[0];
x1 = c1.subtract( q.multiply(d1) );
x2 = c2.subtract( q.multiply(d2) );
c1 = d1; c2 = d2;
d1 = x1; d2 = x2;
q = r;
r = qr[1];
}
//System.out.println("q = " + q + "\n c1 = " + c1 + "\n c2 = " + c2);
ret[0] = new ModInteger(modul,q);
ret[1] = new ModInteger(modul,c1);
ret[2] = new ModInteger(modul,c2);
return ret;
}
/** ModInteger chinese remainder algorithm.
* This is a factory method.
* Assert c.modul >= a.modul and c.modul * a.modul = this.modul.
* @param c ModInteger.
* @param ci inverse of c.modul in ring of a.
* @param a other ModInteger.
* @return cra(c,a).
*/
public ModInteger
chineseRemainder(ModInteger c,
ModInteger ci,
ModInteger a) {
if ( false ) { // debug
if ( c.modul.compareTo( a.modul ) < 1 ) {
System.out.println("ModInteger error " + c + ", " + a);
}
}
ModInteger b = a.fromInteger( c.val ); // c mod a.modul
ModInteger d = a.subtract( b ); // a-c mod a.modul
if ( d.isZERO() ) {
return fromInteger( c.val );
}
b = d.multiply( ci ); // b = (a-c)*ci mod a.modul
//java.math.BigInteger bv = b.val;
//if ( bv.add( bv ).compareTo( a.modul ) > 0 ) {
// b > m/2, make symmetric to 0, undone by fromInteger
// bv = bv.subtract( a.modul );
//}
// (c.modul*b)+c mod this.modul = c mod c.modul =
// (c.modul*ci*(a-c)+c) mod a.modul = a mod a.modul
java.math.BigInteger s = c.modul.multiply( b.val );
s = s.add( c.val );
return fromInteger( s );
}
}
| true | true | public ModInteger[] egcd(ModInteger S) {
ModInteger[] ret = new ModInteger[3];
ret[0] = null;
ret[1] = null;
ret[2] = null;
if ( S == null || S.isZERO() ) {
ret[0] = this;
return ret;
}
if ( isZERO() ) {
ret[0] = S;
return ret;
}
if ( this.isUnit() || S.isUnit() ) {
ret[0] = getONE();
if ( this.isUnit() && S.isUnit() ) {
ModInteger half = fromInteger(2).inverse();
ret[1] = this.inverse().multiply(half);
ret[2] = S.inverse().multiply(half);
return ret;
}
if ( this.isUnit() ) {
// oder inverse(S-1)?
ret[1] = this.inverse();
ret[2] = getZERO();
return ret;
}
// if ( S.isUnit() ) {
// oder inverse(this-1)?
ret[1] = getZERO();
ret[2] = S.inverse();
return ret;
//}
}
//System.out.println("this = " + this + ", S = " + S);
java.math.BigInteger[] qr;
java.math.BigInteger q = this.val;
java.math.BigInteger r = S.val;
java.math.BigInteger c1 = BigInteger.ONE.val;
java.math.BigInteger d1 = BigInteger.ZERO.val;
java.math.BigInteger c2 = BigInteger.ZERO.val;
java.math.BigInteger d2 = BigInteger.ONE.val;
java.math.BigInteger x1;
java.math.BigInteger x2;
while ( r.equals(java.math.BigInteger.ZERO) ) {
qr = q.divideAndRemainder(r);
q = qr[0];
x1 = c1.subtract( q.multiply(d1) );
x2 = c2.subtract( q.multiply(d2) );
c1 = d1; c2 = d2;
d1 = x1; d2 = x2;
q = r;
r = qr[1];
}
//System.out.println("q = " + q + "\n c1 = " + c1 + "\n c2 = " + c2);
ret[0] = new ModInteger(modul,q);
ret[1] = new ModInteger(modul,c1);
ret[2] = new ModInteger(modul,c2);
return ret;
}
| public ModInteger[] egcd(ModInteger S) {
ModInteger[] ret = new ModInteger[3];
ret[0] = null;
ret[1] = null;
ret[2] = null;
if ( S == null || S.isZERO() ) {
ret[0] = this;
return ret;
}
if ( isZERO() ) {
ret[0] = S;
return ret;
}
if ( this.isUnit() || S.isUnit() ) {
ret[0] = getONE();
if ( this.isUnit() && S.isUnit() ) {
ModInteger half = fromInteger(2).inverse();
ret[1] = this.inverse().multiply(half);
ret[2] = S.inverse().multiply(half);
return ret;
}
if ( this.isUnit() ) {
// oder inverse(S-1)?
ret[1] = this.inverse();
ret[2] = getZERO();
return ret;
}
// if ( S.isUnit() ) {
// oder inverse(this-1)?
ret[1] = getZERO();
ret[2] = S.inverse();
return ret;
//}
}
//System.out.println("this = " + this + ", S = " + S);
java.math.BigInteger[] qr;
java.math.BigInteger q = this.val;
java.math.BigInteger r = S.val;
java.math.BigInteger c1 = BigInteger.ONE.val;
java.math.BigInteger d1 = BigInteger.ZERO.val;
java.math.BigInteger c2 = BigInteger.ZERO.val;
java.math.BigInteger d2 = BigInteger.ONE.val;
java.math.BigInteger x1;
java.math.BigInteger x2;
while ( !r.equals(java.math.BigInteger.ZERO) ) {
qr = q.divideAndRemainder(r);
q = qr[0];
x1 = c1.subtract( q.multiply(d1) );
x2 = c2.subtract( q.multiply(d2) );
c1 = d1; c2 = d2;
d1 = x1; d2 = x2;
q = r;
r = qr[1];
}
//System.out.println("q = " + q + "\n c1 = " + c1 + "\n c2 = " + c2);
ret[0] = new ModInteger(modul,q);
ret[1] = new ModInteger(modul,c1);
ret[2] = new ModInteger(modul,c2);
return ret;
}
|
diff --git a/src/loci/slim/TwoDPane.java b/src/loci/slim/TwoDPane.java
index e6c11ae..105d701 100644
--- a/src/loci/slim/TwoDPane.java
+++ b/src/loci/slim/TwoDPane.java
@@ -1,839 +1,839 @@
//
// TwoDPane.java
//
/*
SLIM Plotter application and curve fitting library for
combined spectral lifetime visualization and analysis.
Copyright (C) 2006-@year@ Curtis Rueden and Eric Kjellman.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.slim;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import java.util.Vector;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JRadioButton;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import loci.slim.fit.BurnInRenderer;
import loci.slim.fit.CurveCollection;
import loci.slim.fit.ICurveFitter;
import loci.slim.fit.ICurveRenderer;
import loci.slim.fit.RendererSwitcher;
import visad.AnimationControl;
import visad.CellImpl;
import visad.ColorControl;
import visad.ConstantMap;
import visad.DataReferenceImpl;
import visad.DataRenderer;
import visad.DelaunayCustom;
import visad.Display;
import visad.DisplayEvent;
import visad.DisplayImpl;
import visad.DisplayListener;
import visad.DisplayRealType;
import visad.FlatField;
import visad.Gridded2DSet;
import visad.Irregular2DSet;
import visad.MouseBehavior;
import visad.Real;
import visad.RealTupleType;
import visad.RealType;
import visad.ScalarMap;
import visad.ScalarType;
import visad.UnionSet;
import visad.VisADException;
import visad.VisADRay;
import visad.bom.CurveManipulationRendererJ3D;
import visad.java3d.DisplayImplJ3D;
import visad.java3d.TwoDDisplayRendererJ3D;
import visad.util.Util;
/**
* SLIM Plotter's 2D image pane.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://dev.loci.wisc.edu/trac/java/browser/trunk/components/slim-plotter/src/loci/slim/TwoDPane.java">Trac</a>,
* <a href="http://dev.loci.wisc.edu/svn/java/trunk/components/slim-plotter/src/loci/slim/TwoDPane.java">SVN</a></dd></dl>
*
* @author Curtis Rueden ctrueden at wisc.edu
*/
public class TwoDPane extends JPanel
implements ActionListener, ChangeListener, DisplayListener, DocumentListener
{
// -- Constants --
/** Lifetime progress bar is updated every PROGRESS_RATE milliseconds. */
private static final int PROGRESS_RATE = 50;
/** Lifetime image is updated DEFAULT_FPS times per second by default. */
private static final int DEFAULT_FPS = 3;
// -- Fields --
private SlimPlotter slim;
private DisplayImpl iPlot;
private ScalarMap imageMap;
private DataReferenceImpl imageRef;
private AnimationControl ac;
// data parameters
private SlimData data;
private SlimTypes types;
// intensity parameters
private FlatField[] intensityFields;
// lifetime parameters
private FlatField[] lifetimeFields;
// ROI parameters
private float[][] roiGrid;
private UnionSet curveSet;
private Irregular2DSet roiSet;
private DataReferenceImpl roiRef;
private int roiCount;
private double roiPercent;
private int roiX, roiY;
private boolean[][] roiMask;
// GUI components
private MouseBehaviorButtons mbButtons;
private JProgressBar progress;
private JButton startStopButton;
private JSlider cSlider;
private JRadioButton intensityMode, lifetimeMode;
private JRadioButton projectionMode, emissionMode;
private JCheckBox cToggle;
private ColorWidget colorWidget;
private JTextField iterField, fpsField;
// parameters for multithreaded lifetime computation
private ICurveRenderer[] curveRenderers;
private float[][][] curveImages;
private RendererSwitcher switcher;
private Thread curveThread;
private Timer progressRefresh, lifetimeRefresh;
private boolean lifetimeActive;
// -- Constructor --
public TwoDPane(SlimPlotter slim, SlimData data, SlimTypes types)
throws VisADException, RemoteException
{
this.slim = slim;
this.data = data;
this.types = types;
roiCount = data.width * data.height;
roiPercent = 100;
// create 2D display
iPlot = new DisplayImplJ3D("image", new TwoDDisplayRendererJ3D());
iPlot.enableEvent(DisplayEvent.MOUSE_DRAGGED);
iPlot.addDisplayListener(this);
ScalarMap xMap = new ScalarMap(types.xType, Display.XAxis);
ScalarMap yMap = new ScalarMap(types.yType, Display.YAxis);
iPlot.addMap(xMap);
iPlot.addMap(yMap);
imageMap = new ScalarMap(types.vType, Display.RGB);
iPlot.addMap(imageMap);
iPlot.addMap(new ScalarMap(types.cType, Display.Animation));
imageRef = new DataReferenceImpl("image");
iPlot.addReference(imageRef);
// set image spatial ranges (disable spatial autoscaling)
xMap.setRange(0, data.width - 1);
yMap.setRange(0, data.height - 1);
// set up channel info label
DataReferenceImpl channelRef = new DataReferenceImpl("channel");
DataRenderer channelRend = iPlot.getDisplayRenderer().makeDefaultRenderer();
iPlot.addReferences(channelRend, channelRef);
channelRend.toggle(false);
FlatField channelData = new FlatField(types.cDummyFunc, types.cSet);
channelData.setSamples(new float[1][data.channels]);
channelRef.setData(channelData);
// set up curve manipulation renderer
roiGrid = new float[2][data.width * data.height];
roiMask = new boolean[data.height][data.width];
for (int y=0; y<data.height; y++) {
for (int x=0; x<data.width; x++) {
int ndx = y * data.width + x;
roiGrid[0][ndx] = x;
roiGrid[1][ndx] = y;
roiMask[y][x] = true;
}
}
final DataReferenceImpl curveRef = new DataReferenceImpl("curve");
- RealTupleType xy = new RealTupleType(types.xType, types.yType);
+ //RealTupleType xy = new RealTupleType(types.xType, types.yType);
UnionSet dummyCurve = new UnionSet(new Gridded2DSet[] {
new Gridded2DSet(types.xy, new float[][] {{0}, {0}}, 1)
});
curveRef.setData(dummyCurve);
CurveManipulationRendererJ3D curve =
new CurveManipulationRendererJ3D(0, 0, true);
iPlot.addReferences(curve, curveRef);
CellImpl cell = new CellImpl() {
public void doAction() throws VisADException, RemoteException {
// save latest drawn curve
curveSet = (UnionSet) curveRef.getData();
}
};
cell.addReference(curveRef);
roiRef = new DataReferenceImpl("roi");
roiRef.setData(new Real(0)); // dummy
iPlot.addReference(roiRef, new ConstantMap[] {
new ConstantMap(0, Display.Blue),
new ConstantMap(0.1, Display.Alpha)
});
ac = (AnimationControl) iPlot.getControl(AnimationControl.class);
iPlot.getProjectionControl().setMatrix(
iPlot.make_matrix(0, 0, 0, 0.7, 0, 0, 0));
// lay out components
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JPanel iPlotPane = new JPanel() {
private int height = 380;
public Dimension getMinimumSize() {
Dimension min = super.getMinimumSize();
return new Dimension(min.width, height);
}
public Dimension getPreferredSize() {
Dimension pref = super.getPreferredSize();
return new Dimension(pref.width, height);
}
public Dimension getMaximumSize() {
Dimension max = super.getMaximumSize();
return new Dimension(max.width, height);
}
};
iPlotPane.setLayout(new BorderLayout());
iPlotPane.add(iPlot.getComponent(), BorderLayout.CENTER);
add(iPlotPane);
mbButtons = new MouseBehaviorButtons(iPlot, false, true);
add(mbButtons);
progress = new JProgressBar();
progress.setStringPainted(true);
startStopButton = new JButton("Start");
startStopButton.addActionListener(this);
JPanel progressPanel = new JPanel();
progressPanel.setLayout(new BoxLayout(progressPanel, BoxLayout.X_AXIS));
progressPanel.add(progress);
progressPanel.add(startStopButton);
add(progressPanel);
JPanel sliderPane = new JPanel();
sliderPane.setLayout(new BoxLayout(sliderPane, BoxLayout.X_AXIS));
add(sliderPane);
cSlider = new JSlider(1, data.channels, 1);
cSlider.setToolTipText(
"Selects the channel to display in the 2D image plot above");
cSlider.setSnapToTicks(true);
cSlider.setMajorTickSpacing(data.channels / 4);
cSlider.setMinorTickSpacing(1);
cSlider.setPaintTicks(true);
cSlider.setBorder(new EmptyBorder(8, 5, 8, 5));
cSlider.setEnabled(data.channels > 1);
sliderPane.add(cSlider);
cToggle = new JCheckBox("", true);
cToggle.setToolTipText(
"Toggles the selected channel's visibility in the 3D data plot");
cToggle.addActionListener(this);
cToggle.setEnabled(data.channels > 1);
sliderPane.add(cToggle);
JPanel colorViewPane = new JPanel();
colorViewPane.setLayout(new BoxLayout(colorViewPane, BoxLayout.X_AXIS));
add(colorViewPane);
colorWidget = new ColorWidget(imageMap, "Intensity Color Mapping");
colorViewPane.add(colorWidget);
JPanel rightPane = new JPanel();
rightPane.setLayout(new BoxLayout(rightPane, BoxLayout.Y_AXIS));
colorViewPane.add(rightPane);
JPanel viewModePane = new JPanel();
viewModePane.setLayout(new BoxLayout(viewModePane, BoxLayout.Y_AXIS));
viewModePane.setBorder(new TitledBorder("View Mode"));
rightPane.add(viewModePane);
intensityMode = new JRadioButton("Intensity", true);
lifetimeMode = new JRadioButton("Lifetime");
emissionMode = new JRadioButton("Emission Spectra");
emissionMode.setToolTipText("<html>" +
"Displays an emission spectrum of the data.</html>");
emissionMode.setEnabled(false);
projectionMode = new JRadioButton("Spectral Projection");
projectionMode.setToolTipText("<html>" +
"Displays a \"spectral projection\" of the data.</html>");
projectionMode.setEnabled(false);
ButtonGroup group = new ButtonGroup();
group.add(intensityMode);
group.add(lifetimeMode);
group.add(projectionMode);
group.add(emissionMode);
intensityMode.addActionListener(this);
lifetimeMode.addActionListener(this);
projectionMode.addActionListener(this);
emissionMode.addActionListener(this);
viewModePane.setAlignmentX(Component.CENTER_ALIGNMENT);
viewModePane.add(intensityMode);
viewModePane.add(lifetimeMode);
viewModePane.add(projectionMode);
viewModePane.add(emissionMode);
JPanel lifetimePane = new JPanel();
lifetimePane.setLayout(new BoxLayout(lifetimePane, BoxLayout.Y_AXIS));
lifetimePane.setBorder(new TitledBorder("Lifetime"));
rightPane.add(lifetimePane);
JPanel iterPane = new JPanel();
iterPane.setLayout(new BoxLayout(iterPane, BoxLayout.X_AXIS));
lifetimePane.add(iterPane);
JLabel iterLabel = new JLabel("Iterations ");
iterLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
iterLabel.setHorizontalAlignment(SwingConstants.RIGHT);
iterPane.add(iterLabel);
iterField = new JTextField(4);
iterField.getDocument().addDocumentListener(this);
Util.adjustTextField(iterField);
iterPane.add(iterField);
JPanel fpsPane = new JPanel();
fpsPane.setLayout(new BoxLayout(fpsPane, BoxLayout.X_AXIS));
lifetimePane.add(fpsPane);
JLabel fpsLabel = new JLabel("FPS ");
fpsLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
fpsLabel.setHorizontalAlignment(SwingConstants.RIGHT);
fpsPane.add(fpsLabel);
fpsField = new JTextField("" + DEFAULT_FPS, 4);
fpsField.getDocument().addDocumentListener(this);
Util.adjustTextField(fpsField);
fpsPane.add(fpsField);
// standardize label sizes
fpsLabel.setMinimumSize(iterLabel.getPreferredSize());
fpsLabel.setPreferredSize(iterLabel.getPreferredSize());
fpsLabel.setMaximumSize(iterLabel.getPreferredSize());
// standardize panel widths
lifetimePane.setPreferredSize(new Dimension(
viewModePane.getPreferredSize().width,
lifetimePane.getPreferredSize().height));
cSlider.addChangeListener(this);
doIntensity(true);
// set up lifetime curve fitting renderers for per-pixel lifetime analysis
if (data.allowCurveFit) {
curveRenderers = new ICurveRenderer[data.channels];
for (int c=0; c<data.channels; c++) {
curveRenderers[c] = new BurnInRenderer(data.curves[c]);
curveRenderers[c].setComponentCount(data.numExp);
}
curveImages = new float[data.channels][][];
switcher = new RendererSwitcher(curveRenderers);
progressRefresh = new Timer(PROGRESS_RATE, this);
progressRefresh.start();
lifetimeRefresh = new Timer(1000 / DEFAULT_FPS, this);
lifetimeRefresh.start();
iterField.setText("" + switcher.getMaxIterations());
doProgressString();
}
}
// -- TwoDPane methods --
public int getROICount() { return roiCount; }
public double getROIPercent() { return roiPercent; }
public int getROIX() { return roiX; }
public int getROIY() { return roiY; }
public boolean[][] getROIMask() { return roiMask; }
public int getActiveC() { return cSlider.getValue() - 1; }
/**
* Gets the curve fitter for each spectral channel
* at the current ROI coordinates.
*/
public ICurveFitter[] getCurveFitters() {
if (!data.allowCurveFit) return null;
ICurveRenderer[] renderers = switcher.getCurveRenderers();
ICurveFitter[] cf = new ICurveFitter[data.channels];
for (int c=0; c<data.channels; c++) {
CurveCollection cc = renderers[c].getCurveCollection();
cf[c] = cc.getCurves()[roiY][roiX];
}
return cf;
}
// -- ActionListener methods --
/** Handles checkbox presses. */
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if (src == startStopButton) {
lifetimeActive = !lifetimeActive;
if (lifetimeActive) {
// begin lifetime computation
startStopButton.setText("Stop");
int c = getActiveC();
switcher.setCurrent(c);
curveThread = new Thread(switcher, "Lifetime");
curveThread.setPriority(Thread.MIN_PRIORITY);
curveThread.start();
}
else {
// terminate lifetime computation
startStopButton.setText("Start");
switcher.stop();
}
}
else if (src == cToggle) {
// toggle visibility of this channel
int c = getActiveC();
data.cVisible[c] = !data.cVisible[c];
slim.plotData(true, true, false);
}
else if (src == intensityMode) doIntensity(false);
else if (src == lifetimeMode) doLifetime();
else if (src == projectionMode) doSpectralProjection();
else if (src == emissionMode) doEmissionSpectrum();
else if (src == progressRefresh) {
// progress timer event - update progress bar
if (!lifetimeActive) return;
doProgressString();
}
else if (src == lifetimeRefresh) {
// lifetime timer event - update lifetime display
if (!lifetimeActive || !lifetimeMode.isSelected()) return;
int c = getActiveC();
// update VisAD display
double[][] lifetimeImage = curveRenderers[c].getImage();
if (curveImages[c] == null) {
// TEMP - only visualize first component of multi-component fit
curveImages[c] = new float[1][lifetimeImage[0].length];
}
// convert bins to ps
for (int j=0; j<curveImages[c].length; j++) {
for (int i=0; i<curveImages[c][j].length; i++) {
curveImages[c][j][i] =
data.binsToPico((float) (1 / lifetimeImage[j][i]));
}
}
if (SlimPlotter.DEBUG) {
System.gc();
Runtime r = Runtime.getRuntime();
long total = r.totalMemory();
long free = r.freeMemory();
long used = (total - free) / 1024 / 1024;
System.out.println("Memory used: " + used + " MB");
}
try {
lifetimeFields[c].setSamples(curveImages[c]);
imageRef.setData(lifetimeFields[c]);
colorWidget.updateColorScale();
}
catch (VisADException exc) { exc.printStackTrace(); }
catch (RemoteException exc) { exc.printStackTrace(); }
}
}
// -- ChangeListener methods --
/** Handles slider changes. */
public void stateChanged(ChangeEvent e) {
Object src = e.getSource();
if (src == cSlider) {
int c = getActiveC();
cToggle.removeActionListener(this);
cToggle.setSelected(data.cVisible[c]);
cToggle.addActionListener(this);
// update channel info in VisAD display
try { ac.setCurrent(c); }
catch (VisADException exc) { exc.printStackTrace(); }
catch (RemoteException exc) { exc.printStackTrace(); }
// update channel for per-pixel lifetime computation thread
if (switcher != null) {
switcher.setCurrent(c);
doProgressString();
}
// update displayed image and color scale
FlatField ff = null;
if (intensityMode.isSelected()) ff = intensityFields[c];
else if (lifetimeMode.isSelected()) ff = lifetimeFields[c];
if (ff != null) {
try {
imageRef.setData(ff);
colorWidget.updateColorScale();
}
catch (VisADException exc) { exc.printStackTrace(); }
catch (RemoteException exc) { exc.printStackTrace(); }
}
}
}
// -- DisplayListener methods --
private boolean drag = false;
public void displayChanged(DisplayEvent e) {
int id = e.getId();
boolean probe = mbButtons != null && mbButtons.isProbe();
boolean region = mbButtons != null && mbButtons.isRegion();
if (id == DisplayEvent.MOUSE_PRESSED) {
drag = true;
if (probe) {
// plot per-pixel lifetime without rescale or refit (i.e., fast)
doCursor(iPlot.getDisplayRenderer().getCursor(), true, true);
}
}
else if (id == DisplayEvent.MOUSE_RELEASED) {
drag = false;
if (region) {
// done drawing curve
try {
roiSet = DelaunayCustom.fillCheck(curveSet, false);
if (roiSet == null) {
roiRef.setData(new Real(0));
// plot single-pixel region with rescale and refit (i.e., not fast)
doCursor(pixelToCursor(iPlot, e.getX(), e.getY()), false, false);
iPlot.reAutoScale();
// update renderer to improve entire image
if (data.allowCurveFit) {
for (int c=0; c<curveRenderers.length; c++) {
curveRenderers[c].setMask(null);
}
}
}
else {
roiRef.setData(roiSet);
int[] tri = roiSet.valueToTri(roiGrid);
roiX = roiY = 0;
roiCount = 0;
for (int y=0; y<data.height; y++) {
for (int x=0; x<data.width; x++) {
int ndx = y * data.width + x;
roiMask[y][x] = tri[ndx] >= 0;
if (roiMask[y][x]) {
roiX = x;
roiY = y;
roiCount++;
}
}
}
roiPercent = 100000 * roiCount /
(data.width * data.height) / 1000.0;
slim.plotRegion(true, true, true);
// update renderer to improve only selected region
if (data.allowCurveFit) {
for (int c=0; c<curveRenderers.length; c++) {
curveRenderers[c].setMask(roiMask);
}
}
}
}
catch (VisADException exc) {
String msg = exc.getMessage();
if ("path self intersects".equals(msg)) {
JOptionPane.showMessageDialog(iPlot.getComponent(),
"Please draw a curve that does not intersect itself.",
SlimData.TITLE, JOptionPane.ERROR_MESSAGE);
}
else exc.printStackTrace();
}
catch (RemoteException exc) { exc.printStackTrace(); }
}
else if (probe) {
// plot per-pixel lifetime with rescale and refit (i.e., not fast)
doCursor(iPlot.getDisplayRenderer().getCursor(), true, false);
}
}
else if (id == DisplayEvent.MOUSE_DRAGGED) {
if (!drag) return; // not a center mouse drag
if (probe) {
// plot per-pixel lifetime without rescale or refit (i.e., fast)
doCursor(iPlot.getDisplayRenderer().getCursor(), true, true);
}
}
}
// -- DocumentListener methods --
public void insertUpdate(DocumentEvent e) { documentUpdate(e); }
public void removeUpdate(DocumentEvent e) { documentUpdate(e); }
public void changedUpdate(DocumentEvent e) { documentUpdate(e); }
private void documentUpdate(DocumentEvent e) {
Object src = e.getDocument();
if (src == iterField.getDocument()) {
try {
int iter = Integer.parseInt(iterField.getText());
switcher.setMaxIterations(iter);
}
catch (NumberFormatException exc) { }
}
else if (src == fpsField.getDocument()) {
try {
double fps = Double.parseDouble(fpsField.getText());
lifetimeRefresh.setDelay((int) (1000 / fps));
}
catch (NumberFormatException exc) { }
}
}
// -- Helper methods --
/** Handles cursor updates. */
private void doCursor(double[] cursor, boolean perPix, boolean fast) {
double[] domain = cursorToDomain(iPlot, cursor);
roiX = (int) Math.round(domain[0]);
roiY = (int) Math.round(domain[1]);
if (roiX < 0) roiX = 0;
if (roiX >= data.width) roiX = data.width - 1;
if (roiY < 0) roiY = 0;
if (roiY >= data.height) roiY = data.height - 1;
roiCount = 1;
boolean rescale = !fast, refit = !fast;
if (perPix) slim.plotProbe(rescale);
else slim.plotRegion(true, rescale, refit);
}
private void doIntensity(boolean adjustSlider) {
int maxChan = 0, intensityMax = 0;
try {
if (intensityFields == null) {
intensityFields = new FlatField[data.channels];
maxChan = 0;
for (int c=0; c<data.channels; c++) {
float[][] samples = new float[1][data.width * data.height];
for (int y=0; y<data.height; y++) {
for (int x=0; x<data.width; x++) {
int sum = 0;
for (int t=0; t<data.timeBins; t++) sum += data.data[c][y][x][t];
if (sum > intensityMax) {
intensityMax = sum;
maxChan = c;
}
samples[0][data.width * y + x] = sum;
}
}
intensityFields[c] = new FlatField(types.xyvFunc, types.xySet);
intensityFields[c].setSamples(samples, false);
}
}
int c = adjustSlider ? maxChan : getActiveC();
imageRef.setData(intensityFields[c]);
if (adjustSlider) cSlider.setValue(c + 1);
colorWidget.updateColorScale();
// reset to grayscale color map
ColorControl cc = (ColorControl) iPlot.getControl(ColorControl.class);
cc.setTable(ColorControl.initTableGreyWedge(new float[3][256]));
}
catch (VisADException exc) { exc.printStackTrace(); }
catch (RemoteException exc) { exc.printStackTrace(); }
}
private void doLifetime() {
try {
if (lifetimeFields == null) {
lifetimeFields = new FlatField[data.channels];
float[][] samples = new float[1][data.width * data.height];
for (int c=0; c<data.channels; c++) {
lifetimeFields[c] = new FlatField(types.xyvFunc, types.xySet);
lifetimeFields[c].setSamples(samples, false);
}
}
int c = getActiveC();
imageRef.setData(lifetimeFields[c]);
colorWidget.updateColorScale();
// reset to RGB color map
ColorControl cc = (ColorControl) iPlot.getControl(ColorControl.class);
cc.setTable(ColorControl.initTableVis5D(new float[3][256]));
}
catch (VisADException exc) { exc.printStackTrace(); }
catch (RemoteException exc) { exc.printStackTrace(); }
}
private void doSpectralProjection() {
// TODO
// http://dev.loci.wisc.edu/trac/java/ticket/86
}
private void doEmissionSpectrum() {
// TODO
// http://dev.loci.wisc.edu/trac/java/ticket/164
}
private void doProgressString() {
int c = getActiveC();
int curProg = curveRenderers[c].getCurrentProgress();
int maxProg = curveRenderers[c].getMaxProgress();
progress.setValue(curProg <= maxProg ? curProg : 0);
progress.setMaximum(maxProg);
if (!lifetimeActive && curProg == 0) {
progress.setString("Press Start to compute per-pixel lifetime");
}
else if (curProg == maxProg) {
int totalIter = curveRenderers[c].getTotalIterations();
long tRCSE = (long) (curveRenderers[c].getTotalRCSE() + 0.5);
double wRCSE = curveRenderers[c].getWorstRCSE();
// format worst RCSE string to two decimal places
String worst = "" + wRCSE;
int dot = worst.indexOf(".");
if (dot < 0) worst += ".00";
else {
int sig = worst.length() - dot - 1;
if (sig > 2) worst = worst.substring(0, dot + 3);
else for (int i=sig; i<2; i++) worst += "0";
}
String s = "Iter. #" + totalIter +
": worst=" + worst + ": total=" + tRCSE;
if (curveRenderers[c] instanceof BurnInRenderer) {//TEMP
BurnInRenderer bir = (BurnInRenderer) curveRenderers[c];//TEMP
s += "; stalled=" + bir.getStallCount();//TEMP
}//TEMP
progress.setString(s);
}
else {
int subLevel = curveRenderers[c].getSubsampleLevel();
if (subLevel < 0) {
double percent = (10000 * curProg / maxProg) / 100.0;
progress.setString("Initial pass: " + percent + "%");
}
else {
progress.setString("Estimating; " + (subLevel + 1) +
" step" + (subLevel > 0 ? "s" : "") + " until total burn-in");
}
}
}
// -- Utility methods --
/** Converts the given pixel coordinates to cursor coordinates. */
public static double[] pixelToCursor(DisplayImpl d, int x, int y) {
if (d == null) return null;
MouseBehavior mb = d.getDisplayRenderer().getMouseBehavior();
VisADRay ray = mb.findRay(x, y);
return ray.position;
}
/** Converts the given cursor coordinates to domain coordinates. */
public static double[] cursorToDomain(DisplayImpl d, double[] cursor) {
return cursorToDomain(d, null, cursor);
}
/** Converts the given cursor coordinates to domain coordinates. */
public static double[] cursorToDomain(DisplayImpl d,
RealType[] types, double[] cursor)
{
if (d == null) return null;
// locate x, y and z mappings
Vector maps = d.getMapVector();
int numMaps = maps.size();
ScalarMap mapX = null, mapY = null, mapZ = null;
for (int i=0; i<numMaps; i++) {
if (mapX != null && mapY != null && mapZ != null) break;
ScalarMap map = (ScalarMap) maps.elementAt(i);
if (types == null) {
DisplayRealType drt = map.getDisplayScalar();
if (drt.equals(Display.XAxis)) mapX = map;
else if (drt.equals(Display.YAxis)) mapY = map;
else if (drt.equals(Display.ZAxis)) mapZ = map;
}
else {
ScalarType st = map.getScalar();
if (st.equals(types[0])) mapX = map;
if (st.equals(types[1])) mapY = map;
if (st.equals(types[2])) mapZ = map;
}
}
// adjust for scale
double[] scaleOffset = new double[2];
double[] dummy = new double[2];
double[] values = new double[3];
if (mapX == null) values[0] = Double.NaN;
else {
mapX.getScale(scaleOffset, dummy, dummy);
values[0] = (cursor[0] - scaleOffset[1]) / scaleOffset[0];
}
if (mapY == null) values[1] = Double.NaN;
else {
mapY.getScale(scaleOffset, dummy, dummy);
values[1] = (cursor[1] - scaleOffset[1]) / scaleOffset[0];
}
if (mapZ == null) values[2] = Double.NaN;
else {
mapZ.getScale(scaleOffset, dummy, dummy);
values[2] = (cursor[2] - scaleOffset[1]) / scaleOffset[0];
}
return values;
}
}
| true | true | public TwoDPane(SlimPlotter slim, SlimData data, SlimTypes types)
throws VisADException, RemoteException
{
this.slim = slim;
this.data = data;
this.types = types;
roiCount = data.width * data.height;
roiPercent = 100;
// create 2D display
iPlot = new DisplayImplJ3D("image", new TwoDDisplayRendererJ3D());
iPlot.enableEvent(DisplayEvent.MOUSE_DRAGGED);
iPlot.addDisplayListener(this);
ScalarMap xMap = new ScalarMap(types.xType, Display.XAxis);
ScalarMap yMap = new ScalarMap(types.yType, Display.YAxis);
iPlot.addMap(xMap);
iPlot.addMap(yMap);
imageMap = new ScalarMap(types.vType, Display.RGB);
iPlot.addMap(imageMap);
iPlot.addMap(new ScalarMap(types.cType, Display.Animation));
imageRef = new DataReferenceImpl("image");
iPlot.addReference(imageRef);
// set image spatial ranges (disable spatial autoscaling)
xMap.setRange(0, data.width - 1);
yMap.setRange(0, data.height - 1);
// set up channel info label
DataReferenceImpl channelRef = new DataReferenceImpl("channel");
DataRenderer channelRend = iPlot.getDisplayRenderer().makeDefaultRenderer();
iPlot.addReferences(channelRend, channelRef);
channelRend.toggle(false);
FlatField channelData = new FlatField(types.cDummyFunc, types.cSet);
channelData.setSamples(new float[1][data.channels]);
channelRef.setData(channelData);
// set up curve manipulation renderer
roiGrid = new float[2][data.width * data.height];
roiMask = new boolean[data.height][data.width];
for (int y=0; y<data.height; y++) {
for (int x=0; x<data.width; x++) {
int ndx = y * data.width + x;
roiGrid[0][ndx] = x;
roiGrid[1][ndx] = y;
roiMask[y][x] = true;
}
}
final DataReferenceImpl curveRef = new DataReferenceImpl("curve");
RealTupleType xy = new RealTupleType(types.xType, types.yType);
UnionSet dummyCurve = new UnionSet(new Gridded2DSet[] {
new Gridded2DSet(types.xy, new float[][] {{0}, {0}}, 1)
});
curveRef.setData(dummyCurve);
CurveManipulationRendererJ3D curve =
new CurveManipulationRendererJ3D(0, 0, true);
iPlot.addReferences(curve, curveRef);
CellImpl cell = new CellImpl() {
public void doAction() throws VisADException, RemoteException {
// save latest drawn curve
curveSet = (UnionSet) curveRef.getData();
}
};
cell.addReference(curveRef);
roiRef = new DataReferenceImpl("roi");
roiRef.setData(new Real(0)); // dummy
iPlot.addReference(roiRef, new ConstantMap[] {
new ConstantMap(0, Display.Blue),
new ConstantMap(0.1, Display.Alpha)
});
ac = (AnimationControl) iPlot.getControl(AnimationControl.class);
iPlot.getProjectionControl().setMatrix(
iPlot.make_matrix(0, 0, 0, 0.7, 0, 0, 0));
// lay out components
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JPanel iPlotPane = new JPanel() {
private int height = 380;
public Dimension getMinimumSize() {
Dimension min = super.getMinimumSize();
return new Dimension(min.width, height);
}
public Dimension getPreferredSize() {
Dimension pref = super.getPreferredSize();
return new Dimension(pref.width, height);
}
public Dimension getMaximumSize() {
Dimension max = super.getMaximumSize();
return new Dimension(max.width, height);
}
};
iPlotPane.setLayout(new BorderLayout());
iPlotPane.add(iPlot.getComponent(), BorderLayout.CENTER);
add(iPlotPane);
mbButtons = new MouseBehaviorButtons(iPlot, false, true);
add(mbButtons);
progress = new JProgressBar();
progress.setStringPainted(true);
startStopButton = new JButton("Start");
startStopButton.addActionListener(this);
JPanel progressPanel = new JPanel();
progressPanel.setLayout(new BoxLayout(progressPanel, BoxLayout.X_AXIS));
progressPanel.add(progress);
progressPanel.add(startStopButton);
add(progressPanel);
JPanel sliderPane = new JPanel();
sliderPane.setLayout(new BoxLayout(sliderPane, BoxLayout.X_AXIS));
add(sliderPane);
cSlider = new JSlider(1, data.channels, 1);
cSlider.setToolTipText(
"Selects the channel to display in the 2D image plot above");
cSlider.setSnapToTicks(true);
cSlider.setMajorTickSpacing(data.channels / 4);
cSlider.setMinorTickSpacing(1);
cSlider.setPaintTicks(true);
cSlider.setBorder(new EmptyBorder(8, 5, 8, 5));
cSlider.setEnabled(data.channels > 1);
sliderPane.add(cSlider);
cToggle = new JCheckBox("", true);
cToggle.setToolTipText(
"Toggles the selected channel's visibility in the 3D data plot");
cToggle.addActionListener(this);
cToggle.setEnabled(data.channels > 1);
sliderPane.add(cToggle);
JPanel colorViewPane = new JPanel();
colorViewPane.setLayout(new BoxLayout(colorViewPane, BoxLayout.X_AXIS));
add(colorViewPane);
colorWidget = new ColorWidget(imageMap, "Intensity Color Mapping");
colorViewPane.add(colorWidget);
JPanel rightPane = new JPanel();
rightPane.setLayout(new BoxLayout(rightPane, BoxLayout.Y_AXIS));
colorViewPane.add(rightPane);
JPanel viewModePane = new JPanel();
viewModePane.setLayout(new BoxLayout(viewModePane, BoxLayout.Y_AXIS));
viewModePane.setBorder(new TitledBorder("View Mode"));
rightPane.add(viewModePane);
intensityMode = new JRadioButton("Intensity", true);
lifetimeMode = new JRadioButton("Lifetime");
emissionMode = new JRadioButton("Emission Spectra");
emissionMode.setToolTipText("<html>" +
"Displays an emission spectrum of the data.</html>");
emissionMode.setEnabled(false);
projectionMode = new JRadioButton("Spectral Projection");
projectionMode.setToolTipText("<html>" +
"Displays a \"spectral projection\" of the data.</html>");
projectionMode.setEnabled(false);
ButtonGroup group = new ButtonGroup();
group.add(intensityMode);
group.add(lifetimeMode);
group.add(projectionMode);
group.add(emissionMode);
intensityMode.addActionListener(this);
lifetimeMode.addActionListener(this);
projectionMode.addActionListener(this);
emissionMode.addActionListener(this);
viewModePane.setAlignmentX(Component.CENTER_ALIGNMENT);
viewModePane.add(intensityMode);
viewModePane.add(lifetimeMode);
viewModePane.add(projectionMode);
viewModePane.add(emissionMode);
JPanel lifetimePane = new JPanel();
lifetimePane.setLayout(new BoxLayout(lifetimePane, BoxLayout.Y_AXIS));
lifetimePane.setBorder(new TitledBorder("Lifetime"));
rightPane.add(lifetimePane);
JPanel iterPane = new JPanel();
iterPane.setLayout(new BoxLayout(iterPane, BoxLayout.X_AXIS));
lifetimePane.add(iterPane);
JLabel iterLabel = new JLabel("Iterations ");
iterLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
iterLabel.setHorizontalAlignment(SwingConstants.RIGHT);
iterPane.add(iterLabel);
iterField = new JTextField(4);
iterField.getDocument().addDocumentListener(this);
Util.adjustTextField(iterField);
iterPane.add(iterField);
JPanel fpsPane = new JPanel();
fpsPane.setLayout(new BoxLayout(fpsPane, BoxLayout.X_AXIS));
lifetimePane.add(fpsPane);
JLabel fpsLabel = new JLabel("FPS ");
fpsLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
fpsLabel.setHorizontalAlignment(SwingConstants.RIGHT);
fpsPane.add(fpsLabel);
fpsField = new JTextField("" + DEFAULT_FPS, 4);
fpsField.getDocument().addDocumentListener(this);
Util.adjustTextField(fpsField);
fpsPane.add(fpsField);
// standardize label sizes
fpsLabel.setMinimumSize(iterLabel.getPreferredSize());
fpsLabel.setPreferredSize(iterLabel.getPreferredSize());
fpsLabel.setMaximumSize(iterLabel.getPreferredSize());
// standardize panel widths
lifetimePane.setPreferredSize(new Dimension(
viewModePane.getPreferredSize().width,
lifetimePane.getPreferredSize().height));
cSlider.addChangeListener(this);
doIntensity(true);
// set up lifetime curve fitting renderers for per-pixel lifetime analysis
if (data.allowCurveFit) {
curveRenderers = new ICurveRenderer[data.channels];
for (int c=0; c<data.channels; c++) {
curveRenderers[c] = new BurnInRenderer(data.curves[c]);
curveRenderers[c].setComponentCount(data.numExp);
}
curveImages = new float[data.channels][][];
switcher = new RendererSwitcher(curveRenderers);
progressRefresh = new Timer(PROGRESS_RATE, this);
progressRefresh.start();
lifetimeRefresh = new Timer(1000 / DEFAULT_FPS, this);
lifetimeRefresh.start();
iterField.setText("" + switcher.getMaxIterations());
doProgressString();
}
}
| public TwoDPane(SlimPlotter slim, SlimData data, SlimTypes types)
throws VisADException, RemoteException
{
this.slim = slim;
this.data = data;
this.types = types;
roiCount = data.width * data.height;
roiPercent = 100;
// create 2D display
iPlot = new DisplayImplJ3D("image", new TwoDDisplayRendererJ3D());
iPlot.enableEvent(DisplayEvent.MOUSE_DRAGGED);
iPlot.addDisplayListener(this);
ScalarMap xMap = new ScalarMap(types.xType, Display.XAxis);
ScalarMap yMap = new ScalarMap(types.yType, Display.YAxis);
iPlot.addMap(xMap);
iPlot.addMap(yMap);
imageMap = new ScalarMap(types.vType, Display.RGB);
iPlot.addMap(imageMap);
iPlot.addMap(new ScalarMap(types.cType, Display.Animation));
imageRef = new DataReferenceImpl("image");
iPlot.addReference(imageRef);
// set image spatial ranges (disable spatial autoscaling)
xMap.setRange(0, data.width - 1);
yMap.setRange(0, data.height - 1);
// set up channel info label
DataReferenceImpl channelRef = new DataReferenceImpl("channel");
DataRenderer channelRend = iPlot.getDisplayRenderer().makeDefaultRenderer();
iPlot.addReferences(channelRend, channelRef);
channelRend.toggle(false);
FlatField channelData = new FlatField(types.cDummyFunc, types.cSet);
channelData.setSamples(new float[1][data.channels]);
channelRef.setData(channelData);
// set up curve manipulation renderer
roiGrid = new float[2][data.width * data.height];
roiMask = new boolean[data.height][data.width];
for (int y=0; y<data.height; y++) {
for (int x=0; x<data.width; x++) {
int ndx = y * data.width + x;
roiGrid[0][ndx] = x;
roiGrid[1][ndx] = y;
roiMask[y][x] = true;
}
}
final DataReferenceImpl curveRef = new DataReferenceImpl("curve");
//RealTupleType xy = new RealTupleType(types.xType, types.yType);
UnionSet dummyCurve = new UnionSet(new Gridded2DSet[] {
new Gridded2DSet(types.xy, new float[][] {{0}, {0}}, 1)
});
curveRef.setData(dummyCurve);
CurveManipulationRendererJ3D curve =
new CurveManipulationRendererJ3D(0, 0, true);
iPlot.addReferences(curve, curveRef);
CellImpl cell = new CellImpl() {
public void doAction() throws VisADException, RemoteException {
// save latest drawn curve
curveSet = (UnionSet) curveRef.getData();
}
};
cell.addReference(curveRef);
roiRef = new DataReferenceImpl("roi");
roiRef.setData(new Real(0)); // dummy
iPlot.addReference(roiRef, new ConstantMap[] {
new ConstantMap(0, Display.Blue),
new ConstantMap(0.1, Display.Alpha)
});
ac = (AnimationControl) iPlot.getControl(AnimationControl.class);
iPlot.getProjectionControl().setMatrix(
iPlot.make_matrix(0, 0, 0, 0.7, 0, 0, 0));
// lay out components
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JPanel iPlotPane = new JPanel() {
private int height = 380;
public Dimension getMinimumSize() {
Dimension min = super.getMinimumSize();
return new Dimension(min.width, height);
}
public Dimension getPreferredSize() {
Dimension pref = super.getPreferredSize();
return new Dimension(pref.width, height);
}
public Dimension getMaximumSize() {
Dimension max = super.getMaximumSize();
return new Dimension(max.width, height);
}
};
iPlotPane.setLayout(new BorderLayout());
iPlotPane.add(iPlot.getComponent(), BorderLayout.CENTER);
add(iPlotPane);
mbButtons = new MouseBehaviorButtons(iPlot, false, true);
add(mbButtons);
progress = new JProgressBar();
progress.setStringPainted(true);
startStopButton = new JButton("Start");
startStopButton.addActionListener(this);
JPanel progressPanel = new JPanel();
progressPanel.setLayout(new BoxLayout(progressPanel, BoxLayout.X_AXIS));
progressPanel.add(progress);
progressPanel.add(startStopButton);
add(progressPanel);
JPanel sliderPane = new JPanel();
sliderPane.setLayout(new BoxLayout(sliderPane, BoxLayout.X_AXIS));
add(sliderPane);
cSlider = new JSlider(1, data.channels, 1);
cSlider.setToolTipText(
"Selects the channel to display in the 2D image plot above");
cSlider.setSnapToTicks(true);
cSlider.setMajorTickSpacing(data.channels / 4);
cSlider.setMinorTickSpacing(1);
cSlider.setPaintTicks(true);
cSlider.setBorder(new EmptyBorder(8, 5, 8, 5));
cSlider.setEnabled(data.channels > 1);
sliderPane.add(cSlider);
cToggle = new JCheckBox("", true);
cToggle.setToolTipText(
"Toggles the selected channel's visibility in the 3D data plot");
cToggle.addActionListener(this);
cToggle.setEnabled(data.channels > 1);
sliderPane.add(cToggle);
JPanel colorViewPane = new JPanel();
colorViewPane.setLayout(new BoxLayout(colorViewPane, BoxLayout.X_AXIS));
add(colorViewPane);
colorWidget = new ColorWidget(imageMap, "Intensity Color Mapping");
colorViewPane.add(colorWidget);
JPanel rightPane = new JPanel();
rightPane.setLayout(new BoxLayout(rightPane, BoxLayout.Y_AXIS));
colorViewPane.add(rightPane);
JPanel viewModePane = new JPanel();
viewModePane.setLayout(new BoxLayout(viewModePane, BoxLayout.Y_AXIS));
viewModePane.setBorder(new TitledBorder("View Mode"));
rightPane.add(viewModePane);
intensityMode = new JRadioButton("Intensity", true);
lifetimeMode = new JRadioButton("Lifetime");
emissionMode = new JRadioButton("Emission Spectra");
emissionMode.setToolTipText("<html>" +
"Displays an emission spectrum of the data.</html>");
emissionMode.setEnabled(false);
projectionMode = new JRadioButton("Spectral Projection");
projectionMode.setToolTipText("<html>" +
"Displays a \"spectral projection\" of the data.</html>");
projectionMode.setEnabled(false);
ButtonGroup group = new ButtonGroup();
group.add(intensityMode);
group.add(lifetimeMode);
group.add(projectionMode);
group.add(emissionMode);
intensityMode.addActionListener(this);
lifetimeMode.addActionListener(this);
projectionMode.addActionListener(this);
emissionMode.addActionListener(this);
viewModePane.setAlignmentX(Component.CENTER_ALIGNMENT);
viewModePane.add(intensityMode);
viewModePane.add(lifetimeMode);
viewModePane.add(projectionMode);
viewModePane.add(emissionMode);
JPanel lifetimePane = new JPanel();
lifetimePane.setLayout(new BoxLayout(lifetimePane, BoxLayout.Y_AXIS));
lifetimePane.setBorder(new TitledBorder("Lifetime"));
rightPane.add(lifetimePane);
JPanel iterPane = new JPanel();
iterPane.setLayout(new BoxLayout(iterPane, BoxLayout.X_AXIS));
lifetimePane.add(iterPane);
JLabel iterLabel = new JLabel("Iterations ");
iterLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
iterLabel.setHorizontalAlignment(SwingConstants.RIGHT);
iterPane.add(iterLabel);
iterField = new JTextField(4);
iterField.getDocument().addDocumentListener(this);
Util.adjustTextField(iterField);
iterPane.add(iterField);
JPanel fpsPane = new JPanel();
fpsPane.setLayout(new BoxLayout(fpsPane, BoxLayout.X_AXIS));
lifetimePane.add(fpsPane);
JLabel fpsLabel = new JLabel("FPS ");
fpsLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
fpsLabel.setHorizontalAlignment(SwingConstants.RIGHT);
fpsPane.add(fpsLabel);
fpsField = new JTextField("" + DEFAULT_FPS, 4);
fpsField.getDocument().addDocumentListener(this);
Util.adjustTextField(fpsField);
fpsPane.add(fpsField);
// standardize label sizes
fpsLabel.setMinimumSize(iterLabel.getPreferredSize());
fpsLabel.setPreferredSize(iterLabel.getPreferredSize());
fpsLabel.setMaximumSize(iterLabel.getPreferredSize());
// standardize panel widths
lifetimePane.setPreferredSize(new Dimension(
viewModePane.getPreferredSize().width,
lifetimePane.getPreferredSize().height));
cSlider.addChangeListener(this);
doIntensity(true);
// set up lifetime curve fitting renderers for per-pixel lifetime analysis
if (data.allowCurveFit) {
curveRenderers = new ICurveRenderer[data.channels];
for (int c=0; c<data.channels; c++) {
curveRenderers[c] = new BurnInRenderer(data.curves[c]);
curveRenderers[c].setComponentCount(data.numExp);
}
curveImages = new float[data.channels][][];
switcher = new RendererSwitcher(curveRenderers);
progressRefresh = new Timer(PROGRESS_RATE, this);
progressRefresh.start();
lifetimeRefresh = new Timer(1000 / DEFAULT_FPS, this);
lifetimeRefresh.start();
iterField.setText("" + switcher.getMaxIterations());
doProgressString();
}
}
|
diff --git a/src/com/osastudio/newshub/data/AppProperties.java b/src/com/osastudio/newshub/data/AppProperties.java
index cc33ab6..9052a57 100644
--- a/src/com/osastudio/newshub/data/AppProperties.java
+++ b/src/com/osastudio/newshub/data/AppProperties.java
@@ -1,156 +1,156 @@
package com.osastudio.newshub.data;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.text.TextUtils;
import com.osastudio.newshub.data.user.UserStatus;
public class AppProperties extends NewsBaseObject implements UserStatus {
public static final String JSON_KEY_APK_URL = "android_url";
public static final String JSON_KEY_MIN_VERSION_CODE = "min_version_code";
public static final String JSON_KEY_SPLASH_IMAGE_URL = "picture_url";
public static final String JSON_KEY_RELEASE_NOTES = "update_note";
public static final String JSON_KEY_USER_IDS = "student_ids";
public static final String JSON_KEY_USER_STATUS = "user_status";
public static final String JSON_KEY_VERSION_CODE = "version_code";
public static final String JSON_KEY_VERSION_NAME = "version_id";
private String apkUrl;
private int minVersionCode;
private String releaseNotes;
private String splashImageUrl;
private List<String> userIds;
private int userStatus;
private int versionCode;
private String versionName;
public AppProperties() {
}
public AppProperties(JSONObject jsonObject) {
super(jsonObject);
if (isSuccess()) {
try {
if (!jsonObject.isNull(JSON_KEY_APK_URL)) {
setApkUrl(jsonObject.getString(JSON_KEY_APK_URL).trim());
}
if (!jsonObject.isNull(JSON_KEY_MIN_VERSION_CODE)) {
setMinVersionCode(jsonObject.getInt(JSON_KEY_MIN_VERSION_CODE));
}
if (!jsonObject.isNull(JSON_KEY_SPLASH_IMAGE_URL)) {
setSplashImageUrl(jsonObject
.getString(JSON_KEY_SPLASH_IMAGE_URL).trim());
}
if (!jsonObject.isNull(JSON_KEY_RELEASE_NOTES)) {
setReleaseNotes(jsonObject.getString(JSON_KEY_RELEASE_NOTES)
.trim());
}
if (!jsonObject.isNull(JSON_KEY_USER_IDS)) {
String idsString = jsonObject.getString(JSON_KEY_USER_IDS);
if (!TextUtils.isEmpty(idsString)) {
String[] ids = idsString.split(",");
if (ids != null && ids.length > 0) {
ArrayList<String> list = new ArrayList<String>();
Collections.addAll(list, ids);
- setUserIds(userIds);
+ setUserIds(list);
}
}
}
if (!jsonObject.isNull(JSON_KEY_USER_STATUS)) {
setUserStatus(jsonObject.getInt(JSON_KEY_USER_STATUS));
}
if (!jsonObject.isNull(JSON_KEY_VERSION_CODE)) {
setVersionCode(jsonObject.getInt(JSON_KEY_VERSION_CODE));
}
if (!jsonObject.isNull(JSON_KEY_VERSION_NAME)) {
setVersionName(jsonObject.getString(JSON_KEY_VERSION_NAME)
.trim());
}
} catch (JSONException e) {
}
}
}
public String getApkUrl() {
return this.apkUrl;
}
public AppProperties setApkUrl(String apkUrl) {
this.apkUrl = apkUrl;
return this;
}
public int getMinVersionCode() {
return minVersionCode;
}
public AppProperties setMinVersionCode(int minVersionCode) {
this.minVersionCode = minVersionCode;
return this;
}
public String getReleaseNotes() {
return this.releaseNotes;
}
public AppProperties setReleaseNotes(String releaseNotes) {
this.releaseNotes = releaseNotes;
return this;
}
public String getSplashImageUrl() {
return this.splashImageUrl;
}
public AppProperties setSplashImageUrl(String imageUrl) {
this.splashImageUrl = imageUrl;
return this;
}
public List<String> getUserIds() {
return userIds;
}
public AppProperties setUserIds(List<String> userIds) {
this.userIds = userIds;
return this;
}
public int getUserStatus() {
return this.userStatus;
}
public AppProperties setUserStatus(int userStatus) {
this.userStatus = userStatus;
return this;
}
public int getVersionCode() {
return versionCode;
}
public AppProperties setVersionCode(int versionCode) {
this.versionCode = versionCode;
return this;
}
public String getVersionName() {
return this.versionName;
}
public AppProperties setVersionName(String versionName) {
this.versionName = versionName;
return this;
}
}
| true | true | public AppProperties(JSONObject jsonObject) {
super(jsonObject);
if (isSuccess()) {
try {
if (!jsonObject.isNull(JSON_KEY_APK_URL)) {
setApkUrl(jsonObject.getString(JSON_KEY_APK_URL).trim());
}
if (!jsonObject.isNull(JSON_KEY_MIN_VERSION_CODE)) {
setMinVersionCode(jsonObject.getInt(JSON_KEY_MIN_VERSION_CODE));
}
if (!jsonObject.isNull(JSON_KEY_SPLASH_IMAGE_URL)) {
setSplashImageUrl(jsonObject
.getString(JSON_KEY_SPLASH_IMAGE_URL).trim());
}
if (!jsonObject.isNull(JSON_KEY_RELEASE_NOTES)) {
setReleaseNotes(jsonObject.getString(JSON_KEY_RELEASE_NOTES)
.trim());
}
if (!jsonObject.isNull(JSON_KEY_USER_IDS)) {
String idsString = jsonObject.getString(JSON_KEY_USER_IDS);
if (!TextUtils.isEmpty(idsString)) {
String[] ids = idsString.split(",");
if (ids != null && ids.length > 0) {
ArrayList<String> list = new ArrayList<String>();
Collections.addAll(list, ids);
setUserIds(userIds);
}
}
}
if (!jsonObject.isNull(JSON_KEY_USER_STATUS)) {
setUserStatus(jsonObject.getInt(JSON_KEY_USER_STATUS));
}
if (!jsonObject.isNull(JSON_KEY_VERSION_CODE)) {
setVersionCode(jsonObject.getInt(JSON_KEY_VERSION_CODE));
}
if (!jsonObject.isNull(JSON_KEY_VERSION_NAME)) {
setVersionName(jsonObject.getString(JSON_KEY_VERSION_NAME)
.trim());
}
} catch (JSONException e) {
}
}
}
| public AppProperties(JSONObject jsonObject) {
super(jsonObject);
if (isSuccess()) {
try {
if (!jsonObject.isNull(JSON_KEY_APK_URL)) {
setApkUrl(jsonObject.getString(JSON_KEY_APK_URL).trim());
}
if (!jsonObject.isNull(JSON_KEY_MIN_VERSION_CODE)) {
setMinVersionCode(jsonObject.getInt(JSON_KEY_MIN_VERSION_CODE));
}
if (!jsonObject.isNull(JSON_KEY_SPLASH_IMAGE_URL)) {
setSplashImageUrl(jsonObject
.getString(JSON_KEY_SPLASH_IMAGE_URL).trim());
}
if (!jsonObject.isNull(JSON_KEY_RELEASE_NOTES)) {
setReleaseNotes(jsonObject.getString(JSON_KEY_RELEASE_NOTES)
.trim());
}
if (!jsonObject.isNull(JSON_KEY_USER_IDS)) {
String idsString = jsonObject.getString(JSON_KEY_USER_IDS);
if (!TextUtils.isEmpty(idsString)) {
String[] ids = idsString.split(",");
if (ids != null && ids.length > 0) {
ArrayList<String> list = new ArrayList<String>();
Collections.addAll(list, ids);
setUserIds(list);
}
}
}
if (!jsonObject.isNull(JSON_KEY_USER_STATUS)) {
setUserStatus(jsonObject.getInt(JSON_KEY_USER_STATUS));
}
if (!jsonObject.isNull(JSON_KEY_VERSION_CODE)) {
setVersionCode(jsonObject.getInt(JSON_KEY_VERSION_CODE));
}
if (!jsonObject.isNull(JSON_KEY_VERSION_NAME)) {
setVersionName(jsonObject.getString(JSON_KEY_VERSION_NAME)
.trim());
}
} catch (JSONException e) {
}
}
}
|
diff --git a/driver/src/main/java/com/cloudbees/sdk/ArtifactInstallFactory.java b/driver/src/main/java/com/cloudbees/sdk/ArtifactInstallFactory.java
index f7a15de..0e090e0 100644
--- a/driver/src/main/java/com/cloudbees/sdk/ArtifactInstallFactory.java
+++ b/driver/src/main/java/com/cloudbees/sdk/ArtifactInstallFactory.java
@@ -1,319 +1,320 @@
package com.cloudbees.sdk;
import com.cloudbees.api.BeesClientConfiguration;
import com.cloudbees.sdk.cli.BeesCommand;
import com.cloudbees.sdk.cli.CLICommand;
import com.cloudbees.sdk.cli.DirectoryStructure;
import com.google.inject.AbstractModule;
import com.ning.http.client.providers.netty.NettyAsyncHttpProvider;
import com.thoughtworks.xstream.XStream;
import org.apache.commons.io.IOUtils;
import org.apache.maven.repository.internal.MavenRepositorySystemSession;
import org.apache.maven.settings.Server;
import org.codehaus.plexus.DefaultContainerConfiguration;
import org.codehaus.plexus.DefaultPlexusContainer;
import org.codehaus.plexus.PlexusContainerException;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.jboss.shrinkwrap.resolver.impl.maven.MavenDependencyResolverSettings;
import org.slf4j.LoggerFactory;
import org.sonatype.aether.RepositorySystem;
import org.sonatype.aether.artifact.Artifact;
import org.sonatype.aether.collection.CollectRequest;
import org.sonatype.aether.graph.Dependency;
import org.sonatype.aether.graph.DependencyFilter;
import org.sonatype.aether.impl.VersionResolver;
import org.sonatype.aether.installation.InstallRequest;
import org.sonatype.aether.repository.Authentication;
import org.sonatype.aether.repository.LocalRepository;
import org.sonatype.aether.repository.Proxy;
import org.sonatype.aether.repository.RemoteRepository;
import org.sonatype.aether.resolution.ArtifactResult;
import org.sonatype.aether.resolution.DependencyRequest;
import org.sonatype.aether.resolution.VersionRangeRequest;
import org.sonatype.aether.resolution.VersionRangeResult;
import org.sonatype.aether.util.artifact.DefaultArtifact;
import org.sonatype.aether.util.artifact.JavaScopes;
import org.sonatype.aether.util.artifact.SubArtifact;
import org.sonatype.aether.util.filter.DependencyFilterUtils;
import javax.inject.Inject;
import java.io.File;
import java.io.FileWriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Component that talks to {@link org.apache.maven.repository.internal.MavenRepositorySystemSession}, resolve artifacts,
* and install.
* <p/>
* <p/>
* This component is stateful.
*
* @author Fabian Donze
*/
public class ArtifactInstallFactory {
private static final Logger LOGGER = Logger.getLogger(ArtifactInstallFactory.class.getName());
MavenRepositorySystemSession sessionFactory;
RepositorySystem rs;
private LocalRepository localRepository;
@Inject
private DirectoryStructure directoryStructure;
private BeesClientConfiguration beesClientConfiguration;
public ArtifactInstallFactory() {
// NettyAsyncHttpProvider prints some INFO-level messages. suppress them
Logger.getLogger("com.ning.http.client.providers.netty.NettyAsyncHttpProvider").setLevel(Level.WARNING);
LoggerFactory.getLogger(NettyAsyncHttpProvider.class);
}
public void setBeesClientConfiguration(BeesClientConfiguration beesClientConfiguration) {
this.beesClientConfiguration = beesClientConfiguration;
}
private RepositorySystem getRs() {
if (rs == null) {
try {
DefaultPlexusContainer boot = new DefaultPlexusContainer(
new DefaultContainerConfiguration(),
new AbstractModule() {
@Override
protected void configure() {
bind(VersionResolver.class).to(VersionResolverImpl.class);
}
}
);
return boot.lookup(RepositorySystem.class);
} catch (ComponentLookupException e) {
throw new RuntimeException("Unable to lookup component RepositorySystem, cannot establish Aether dependency resolver.", e);
} catch (PlexusContainerException e) {
throw new RuntimeException("Unable to load RepositorySystem component by Plexus, cannot establish Aether dependency resolver.", e);
}
}
return rs;
}
private MavenRepositorySystemSession getSessionFactory() {
if (sessionFactory == null) {
sessionFactory = new MavenRepositorySystemSession();
LocalRepository localRepo = new LocalRepository(new File(new File(System.getProperty("user.home")), ".m2/repository"));
sessionFactory.setLocalRepositoryManager(getRs().newLocalRepositoryManager(localRepo));
}
return sessionFactory;
}
private List<RemoteRepository> getRepositories() {
List<RemoteRepository> repositories = new ArrayList<RemoteRepository>();
MavenDependencyResolverSettings resolverSettings = new MavenDependencyResolverSettings();
resolverSettings.setUseMavenCentral(true);
List<RemoteRepository> repos = resolverSettings.getRemoteRepositories();
for (RemoteRepository remoteRepository : repos) {
Server server = resolverSettings.getSettings().getServer(remoteRepository.getId());
if (server != null) {
remoteRepository.setAuthentication(new Authentication(server.getUsername(), server.getPassword(), server.getPrivateKey(), server.getPassphrase()));
}
setRemoteRepositoryProxy(remoteRepository);
repositories.add(remoteRepository);
}
RemoteRepository r = new RemoteRepository("cloudbees-public-release", "default", "https://repository-cloudbees.forge.cloudbees.com/public-release/");
setRemoteRepositoryProxy(r);
repositories.add(r);
return repositories;
}
private void setRemoteRepositoryProxy(RemoteRepository repo) {
if (beesClientConfiguration != null) {
if (beesClientConfiguration.getProxyHost() != null && beesClientConfiguration.getProxyPort() > 0) {
String proxyType = Proxy.TYPE_HTTP;
if (repo.getUrl().startsWith("https"))
proxyType = Proxy.TYPE_HTTPS;
Proxy proxy = new Proxy(proxyType, beesClientConfiguration.getProxyHost(), beesClientConfiguration.getProxyPort(), null);
if (beesClientConfiguration.getProxyUser() != null) {
Authentication authentication = new Authentication(beesClientConfiguration.getProxyUser(), beesClientConfiguration.getProxyPassword());
proxy.setAuthentication(authentication);
}
repo.setProxy(proxy);
}
}
}
public void setLocalRepository(String repository) {
localRepository = new LocalRepository(repository);
}
public VersionRangeResult findVersions(GAV gav) throws Exception {
GAV findGAV = new GAV(gav.groupId, gav.artifactId, "[0,)");
Artifact artifact = new DefaultArtifact( findGAV.toString() );
MavenRepositorySystemSession session = getSessionFactory();
if (localRepository != null)
session.setLocalRepositoryManager(getRs().newLocalRepositoryManager(localRepository));
VersionRangeRequest rangeRequest = new VersionRangeRequest();
rangeRequest.setArtifact(artifact);
rangeRequest.setRepositories(getRepositories());
VersionRangeResult rangeResult = getRs().resolveVersionRange(session, rangeRequest);
return rangeResult;
}
public GAV install(GAV gav) throws Exception {
return install(toArtifact(gav));
}
/**
* Installs the given artifact and all its transitive dependencies
*/
public GAV install(GAV gav, File jar, File pom) throws Exception {
Artifact jarArtifact = toArtifact(gav);
jarArtifact = jarArtifact.setFile(jar);
Artifact pomArtifact = new SubArtifact(jarArtifact, "", "pom");
pomArtifact = pomArtifact.setFile(pom);
InstallRequest installRequest = new InstallRequest();
installRequest.addArtifact(jarArtifact).addArtifact(pomArtifact);
MavenRepositorySystemSession session = getSessionFactory();
if (localRepository != null)
session.setLocalRepositoryManager(getRs().newLocalRepositoryManager(localRepository));
getRs().install(session, installRequest);
return install(gav);
}
/**
* Installs the given artifact and all its transitive dependencies
*/
private GAV install(Artifact a) throws Exception {
MavenRepositorySystemSession session = getSessionFactory();
if (localRepository != null)
session.setLocalRepositoryManager(getRs().newLocalRepositoryManager(localRepository));
// System.out.println("Local repo: " + session.getLocalRepositoryManager().getRepository().getBasedir());
DependencyFilter classpathFlter = DependencyFilterUtils.classpathFilter(JavaScopes.COMPILE);
CollectRequest collectRequest = new CollectRequest();
collectRequest.setRoot(new Dependency(a, JavaScopes.COMPILE));
collectRequest.setRepositories(getRepositories());
DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, classpathFlter);
List<ArtifactResult> artifactResults = getRs().resolveDependencies(session, dependencyRequest).getArtifactResults();
Plugin plugin = new Plugin();
List<CommandProperties> command = plugin.getProperties();
List<String> jars = plugin.getJars();
List<URL> urls = new ArrayList<URL>();
for (ArtifactResult artifactResult : artifactResults) {
URL artifactURL = artifactResult.getArtifact().getFile().toURI().toURL();
urls.add(artifactURL);
jars.add(artifactResult.getArtifact().getFile().getAbsolutePath());
}
ClassLoader cl = createClassLoader(urls, getClass().getClassLoader());
for (ArtifactResult artifactResult : artifactResults) {
if (toString(artifactResult.getArtifact()).equals(toString(a))) {
plugin.setArtifact(new GAV(artifactResult.getArtifact().toString()).toString());
// System.out.println("Analysing... " + plugin.getArtifact());
JarFile jarFile = new JarFile(artifactResult.getArtifact().getFile());
Enumeration<JarEntry> e = jarFile.entries();
while (e.hasMoreElements()) {
JarEntry entry = e.nextElement();
if (entry.getName().endsWith(".class")) {
String className = entry.getName().replace('/', '.').substring(0, entry.getName().length() - 6);
Class c = Class.forName(className, false, cl);
findCommand(true, command, c);
}
}
}
}
XStream xStream = new XStream();
xStream.processAnnotations(Plugin.class);
xStream.processAnnotations(CommandProperties.class);
// System.out.println(xStream.toXML(plugin));
File xmlFile = new File(directoryStructure.getPluginDir(), a.getArtifactId() + ".bees");
FileWriter fos = null;
try {
+ xmlFile.getParentFile().mkdirs();
fos = new FileWriter(xmlFile);
fos.write(xStream.toXML(plugin));
} finally {
IOUtils.closeQuietly(fos);
}
return new GAV(plugin.getArtifact());
}
private Artifact toArtifact(GAV gav) {
return new DefaultArtifact(gav.groupId, gav.artifactId, "jar", gav.version);
}
private String toString(Artifact a) {
return a.getGroupId() + ":" + a.getArtifactId();
}
/**
* Finds all the commands in the given injector.
*/
private void findCommand(boolean all, List<CommandProperties> list, Class<?> cmd) {
if (!cmd.isAnnotationPresent(CLICommand.class))
return;
CommandProperties commandProperties = new CommandProperties();
commandProperties.setClassName(cmd.getName());
commandProperties.setName(cmd.getAnnotation(CLICommand.class).value());
if (cmd.isAnnotationPresent(BeesCommand.class)) {
BeesCommand beesCommand = cmd.getAnnotation(BeesCommand.class);
if (beesCommand.experimental() && !all)
return;
commandProperties.setGroup(beesCommand.group());
if (beesCommand.description().length() > 0)
commandProperties.setDescription(beesCommand.description());
commandProperties.setPriority(beesCommand.priority());
if (beesCommand.pattern().length() > 0)
commandProperties.setPattern(beesCommand.pattern());
commandProperties.setExperimental(beesCommand.experimental());
} else {
try {
commandProperties.setGroup("CLI");
commandProperties.setPriority((Integer) BeesCommand.class.getMethod("priority").getDefaultValue());
commandProperties.setExperimental(false);
} catch (NoSuchMethodException e) {
LOGGER.log(Level.SEVERE, "Internal error", e);
}
}
list.add(commandProperties);
}
/**
* Creates a classloader from all the artifacts resolved thus far.
*/
private ClassLoader createClassLoader(List<URL> urls, ClassLoader parent) {
// if (urls.isEmpty()) return parent; // nothing to load // this makes it hard to differentiate newly loaded stuff from what's already visible
return new URLClassLoader(urls.toArray(new URL[urls.size()]), parent);
}
}
| true | true | private GAV install(Artifact a) throws Exception {
MavenRepositorySystemSession session = getSessionFactory();
if (localRepository != null)
session.setLocalRepositoryManager(getRs().newLocalRepositoryManager(localRepository));
// System.out.println("Local repo: " + session.getLocalRepositoryManager().getRepository().getBasedir());
DependencyFilter classpathFlter = DependencyFilterUtils.classpathFilter(JavaScopes.COMPILE);
CollectRequest collectRequest = new CollectRequest();
collectRequest.setRoot(new Dependency(a, JavaScopes.COMPILE));
collectRequest.setRepositories(getRepositories());
DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, classpathFlter);
List<ArtifactResult> artifactResults = getRs().resolveDependencies(session, dependencyRequest).getArtifactResults();
Plugin plugin = new Plugin();
List<CommandProperties> command = plugin.getProperties();
List<String> jars = plugin.getJars();
List<URL> urls = new ArrayList<URL>();
for (ArtifactResult artifactResult : artifactResults) {
URL artifactURL = artifactResult.getArtifact().getFile().toURI().toURL();
urls.add(artifactURL);
jars.add(artifactResult.getArtifact().getFile().getAbsolutePath());
}
ClassLoader cl = createClassLoader(urls, getClass().getClassLoader());
for (ArtifactResult artifactResult : artifactResults) {
if (toString(artifactResult.getArtifact()).equals(toString(a))) {
plugin.setArtifact(new GAV(artifactResult.getArtifact().toString()).toString());
// System.out.println("Analysing... " + plugin.getArtifact());
JarFile jarFile = new JarFile(artifactResult.getArtifact().getFile());
Enumeration<JarEntry> e = jarFile.entries();
while (e.hasMoreElements()) {
JarEntry entry = e.nextElement();
if (entry.getName().endsWith(".class")) {
String className = entry.getName().replace('/', '.').substring(0, entry.getName().length() - 6);
Class c = Class.forName(className, false, cl);
findCommand(true, command, c);
}
}
}
}
XStream xStream = new XStream();
xStream.processAnnotations(Plugin.class);
xStream.processAnnotations(CommandProperties.class);
// System.out.println(xStream.toXML(plugin));
File xmlFile = new File(directoryStructure.getPluginDir(), a.getArtifactId() + ".bees");
FileWriter fos = null;
try {
fos = new FileWriter(xmlFile);
fos.write(xStream.toXML(plugin));
} finally {
IOUtils.closeQuietly(fos);
}
return new GAV(plugin.getArtifact());
}
| private GAV install(Artifact a) throws Exception {
MavenRepositorySystemSession session = getSessionFactory();
if (localRepository != null)
session.setLocalRepositoryManager(getRs().newLocalRepositoryManager(localRepository));
// System.out.println("Local repo: " + session.getLocalRepositoryManager().getRepository().getBasedir());
DependencyFilter classpathFlter = DependencyFilterUtils.classpathFilter(JavaScopes.COMPILE);
CollectRequest collectRequest = new CollectRequest();
collectRequest.setRoot(new Dependency(a, JavaScopes.COMPILE));
collectRequest.setRepositories(getRepositories());
DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, classpathFlter);
List<ArtifactResult> artifactResults = getRs().resolveDependencies(session, dependencyRequest).getArtifactResults();
Plugin plugin = new Plugin();
List<CommandProperties> command = plugin.getProperties();
List<String> jars = plugin.getJars();
List<URL> urls = new ArrayList<URL>();
for (ArtifactResult artifactResult : artifactResults) {
URL artifactURL = artifactResult.getArtifact().getFile().toURI().toURL();
urls.add(artifactURL);
jars.add(artifactResult.getArtifact().getFile().getAbsolutePath());
}
ClassLoader cl = createClassLoader(urls, getClass().getClassLoader());
for (ArtifactResult artifactResult : artifactResults) {
if (toString(artifactResult.getArtifact()).equals(toString(a))) {
plugin.setArtifact(new GAV(artifactResult.getArtifact().toString()).toString());
// System.out.println("Analysing... " + plugin.getArtifact());
JarFile jarFile = new JarFile(artifactResult.getArtifact().getFile());
Enumeration<JarEntry> e = jarFile.entries();
while (e.hasMoreElements()) {
JarEntry entry = e.nextElement();
if (entry.getName().endsWith(".class")) {
String className = entry.getName().replace('/', '.').substring(0, entry.getName().length() - 6);
Class c = Class.forName(className, false, cl);
findCommand(true, command, c);
}
}
}
}
XStream xStream = new XStream();
xStream.processAnnotations(Plugin.class);
xStream.processAnnotations(CommandProperties.class);
// System.out.println(xStream.toXML(plugin));
File xmlFile = new File(directoryStructure.getPluginDir(), a.getArtifactId() + ".bees");
FileWriter fos = null;
try {
xmlFile.getParentFile().mkdirs();
fos = new FileWriter(xmlFile);
fos.write(xStream.toXML(plugin));
} finally {
IOUtils.closeQuietly(fos);
}
return new GAV(plugin.getArtifact());
}
|
diff --git a/tests/gdx-tests/src/com/badlogic/gdx/tests/OrthoCamBorderTest.java b/tests/gdx-tests/src/com/badlogic/gdx/tests/OrthoCamBorderTest.java
index fa655d67a..a9e1f5358 100644
--- a/tests/gdx-tests/src/com/badlogic/gdx/tests/OrthoCamBorderTest.java
+++ b/tests/gdx-tests/src/com/badlogic/gdx/tests/OrthoCamBorderTest.java
@@ -1,83 +1,83 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogic.gdx.tests;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.tests.utils.GdxTest;
public class OrthoCamBorderTest extends GdxTest {
@Override
public boolean needsGL20 () {
return false;
}
static final int WIDTH = 480;
static final int HEIGHT = 320;
com.badlogic.gdx.graphics.OrthographicCamera cam;
Rectangle glViewport;
Mesh mesh;
public void create () {
mesh = new Mesh(true, 4, 6, new VertexAttribute(Usage.Position, 2, "a_pos"), new VertexAttribute(Usage.Color, 4, "a_col"));
mesh.setVertices(new float[] {0, 0, 1, 0, 0, 1, WIDTH, 0, 0, 1, 0, 1, WIDTH, HEIGHT, 0, 0, 1, 1, 0, HEIGHT, 1, 0, 1, 1});
mesh.setIndices(new short[] {0, 1, 2, 2, 3, 0});
cam = new OrthographicCamera(WIDTH, HEIGHT);
cam.position.set(WIDTH / 2, HEIGHT / 2, 0);
glViewport = calculateGLViewport(WIDTH, HEIGHT);
}
private Rectangle calculateGLViewport (int desiredWidth, int desiredHeight) {
Rectangle viewport = new Rectangle();
if (Gdx.graphics.getWidth() > Gdx.graphics.getHeight()) {
- float aspect = (float)Gdx.graphics.getHeight() / HEIGHT;
- viewport.width = WIDTH * aspect;
+ float aspect = (float)Gdx.graphics.getHeight() / desiredHeight;
+ viewport.width = desiredWidth * aspect;
viewport.height = Gdx.graphics.getHeight();
viewport.x = Gdx.graphics.getWidth() / 2 - viewport.width / 2;
viewport.y = 0;
} else {
- float aspect = (float)Gdx.graphics.getWidth() / WIDTH;
+ float aspect = (float)Gdx.graphics.getWidth() / desiredWidth;
viewport.width = Gdx.graphics.getWidth();
- viewport.height = HEIGHT * aspect;
+ viewport.height = desiredHeight * aspect;
viewport.x = 0;
viewport.y = Gdx.graphics.getHeight() / 2 - viewport.height / 2;
}
return viewport;
}
public void resize (int width, int height) {
glViewport = calculateGLViewport(WIDTH, HEIGHT);
}
public void render () {
GL10 gl = Gdx.gl10;
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
gl.glViewport((int)glViewport.x, (int)glViewport.y, (int)glViewport.width, (int)glViewport.height);
cam.update();
cam.apply(gl);
mesh.render(GL10.GL_TRIANGLES);
}
}
| false | true | private Rectangle calculateGLViewport (int desiredWidth, int desiredHeight) {
Rectangle viewport = new Rectangle();
if (Gdx.graphics.getWidth() > Gdx.graphics.getHeight()) {
float aspect = (float)Gdx.graphics.getHeight() / HEIGHT;
viewport.width = WIDTH * aspect;
viewport.height = Gdx.graphics.getHeight();
viewport.x = Gdx.graphics.getWidth() / 2 - viewport.width / 2;
viewport.y = 0;
} else {
float aspect = (float)Gdx.graphics.getWidth() / WIDTH;
viewport.width = Gdx.graphics.getWidth();
viewport.height = HEIGHT * aspect;
viewport.x = 0;
viewport.y = Gdx.graphics.getHeight() / 2 - viewport.height / 2;
}
return viewport;
}
| private Rectangle calculateGLViewport (int desiredWidth, int desiredHeight) {
Rectangle viewport = new Rectangle();
if (Gdx.graphics.getWidth() > Gdx.graphics.getHeight()) {
float aspect = (float)Gdx.graphics.getHeight() / desiredHeight;
viewport.width = desiredWidth * aspect;
viewport.height = Gdx.graphics.getHeight();
viewport.x = Gdx.graphics.getWidth() / 2 - viewport.width / 2;
viewport.y = 0;
} else {
float aspect = (float)Gdx.graphics.getWidth() / desiredWidth;
viewport.width = Gdx.graphics.getWidth();
viewport.height = desiredHeight * aspect;
viewport.x = 0;
viewport.y = Gdx.graphics.getHeight() / 2 - viewport.height / 2;
}
return viewport;
}
|
diff --git a/domino/eclipse/plugins/com.ibm.xsp.sbtsdk/src/nsf/playground/playground/PreviewXPagesHandler.java b/domino/eclipse/plugins/com.ibm.xsp.sbtsdk/src/nsf/playground/playground/PreviewXPagesHandler.java
index a4a9f92ac..6528c3426 100644
--- a/domino/eclipse/plugins/com.ibm.xsp.sbtsdk/src/nsf/playground/playground/PreviewXPagesHandler.java
+++ b/domino/eclipse/plugins/com.ibm.xsp.sbtsdk/src/nsf/playground/playground/PreviewXPagesHandler.java
@@ -1,49 +1,50 @@
package nsf.playground.playground;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ibm.commons.runtime.util.UrlUtil;
public class PreviewXPagesHandler extends PreviewHandler {
private static final String LAST_REQUEST = "xpagessnippet.lastrequest";
public static class RequestParams implements Serializable {
private static final long serialVersionUID = 1L;
private String sOptions;
private String id;
public RequestParams(String sOptions, String id) {
this.sOptions = sOptions;
this.id = id;
}
public String getOptions() {
return sOptions;
}
public String getId() {
return id;
}
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String sOptions = req.getParameter("fm_options");
String id = req.getParameter("fm_id");
RequestParams requestParams = new RequestParams(sOptions,id);
req.getSession().setAttribute(LAST_REQUEST, requestParams);
- resp.sendRedirect("/SBTPlayground.nsf/_PreviewXPages.xsp");
+ String baseUrl = UrlUtil.getContextUrl(req);
+ resp.sendRedirect(baseUrl+"/_PreviewXPages.xsp");
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter pw = resp.getWriter();
pw.println("Social Business Tooolkit Playground - XPages Snippet Preview Servlet");
pw.flush();
}
}
| true | true | public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String sOptions = req.getParameter("fm_options");
String id = req.getParameter("fm_id");
RequestParams requestParams = new RequestParams(sOptions,id);
req.getSession().setAttribute(LAST_REQUEST, requestParams);
resp.sendRedirect("/SBTPlayground.nsf/_PreviewXPages.xsp");
}
| public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String sOptions = req.getParameter("fm_options");
String id = req.getParameter("fm_id");
RequestParams requestParams = new RequestParams(sOptions,id);
req.getSession().setAttribute(LAST_REQUEST, requestParams);
String baseUrl = UrlUtil.getContextUrl(req);
resp.sendRedirect(baseUrl+"/_PreviewXPages.xsp");
}
|
diff --git a/src/main/us/exultant/ahs/io/WorkTargetChannelCloser.java b/src/main/us/exultant/ahs/io/WorkTargetChannelCloser.java
index a3b252c..9ac16b3 100644
--- a/src/main/us/exultant/ahs/io/WorkTargetChannelCloser.java
+++ b/src/main/us/exultant/ahs/io/WorkTargetChannelCloser.java
@@ -1,27 +1,27 @@
package us.exultant.ahs.io;
import us.exultant.ahs.util.*;
import us.exultant.ahs.thread.*;
import java.io.*;
import java.nio.channels.*;
import org.slf4j.*;
class WorkTargetChannelCloser extends WorkTargetAdapterFollowup<Void> {
WorkTargetChannelCloser(InputSystem<?> $iosys) {
super($iosys.getFuture(), 0);
this.$channel = $iosys.getChannel();
}
WorkTargetChannelCloser(OutputSystem<?> $iosys) {
super($iosys.getFuture(), 0);
this.$channel = $iosys.getChannel();
}
private final Channel $channel;
protected Void run() throws IOException {
- assert new Loggar(LoggerFactory.getLogger(OutputSystem_WorkerChannelSelectable.class)).debug("closing channel {}", $channel);
+ assert new Loggar(LoggerFactory.getLogger(WorkTargetChannelCloser.class)).debug("closing channel {}", $channel);
$channel.close();
return null;
}
}
| true | true | protected Void run() throws IOException {
assert new Loggar(LoggerFactory.getLogger(OutputSystem_WorkerChannelSelectable.class)).debug("closing channel {}", $channel);
$channel.close();
return null;
}
| protected Void run() throws IOException {
assert new Loggar(LoggerFactory.getLogger(WorkTargetChannelCloser.class)).debug("closing channel {}", $channel);
$channel.close();
return null;
}
|
diff --git a/gnu/testlet/java/lang/Character/unicode.java b/gnu/testlet/java/lang/Character/unicode.java
index 41df7fcb..b6a76f26 100644
--- a/gnu/testlet/java/lang/Character/unicode.java
+++ b/gnu/testlet/java/lang/Character/unicode.java
@@ -1,622 +1,637 @@
// Tags: JDK1.1
// Uses: CharInfo
package gnu.testlet.java.lang.Character;
import java.io.*;
import gnu.testlet.Testlet;
import gnu.testlet.TestHarness;
import gnu.testlet.ResourceNotFoundException;
/*
MISSING:
Instance tests
( constructor, charValue, serialization): should be in other file
*/
public class unicode implements Testlet
{
public static boolean testDeprecated;
public static boolean verbose;
public static boolean benchmark;
public CharInfo[] chars = new CharInfo[0x10000];
public int failures;
public int tests;
TestHarness harness;
public unicode()
{
}
public unicode(TestHarness aHarness, String filename) throws IOException, ResourceNotFoundException
{
harness = aHarness;
Reader bir =
harness.getResourceReader ("gnu#testlet#java#lang#Character#"
+ filename);
harness.debug("Reading unicode database...");
while ( bir.ready() )
{
String str;
CharInfo ci = new CharInfo();
str = getNext(bir);
int code = (char)Integer.parseInt(str,16);
ci.name = getNext(bir);
ci.category = getNext(bir);
getNext(bir);
getNext(bir);
getNext(bir);
str = getNext(bir);
if ( !str.equals("") )
ci.digit = Integer.parseInt(str, 10 );
else
ci.digit = -1;
getNext(bir);
str = getNext(bir);
if ( str.equals("") )
{
ci.numericValue = -1;
}
else
{
try {
ci.numericValue = Integer.parseInt(str,10);
if ( ci.numericValue < 0 )
ci.numericValue = -2;
} catch ( NumberFormatException e )
{
ci.numericValue = -2;
}
}
getNext(bir);
getNext(bir);
getNext(bir);
str = getNext(bir);
if ( !str.equals("") )
ci.uppercase = (char)Integer.parseInt(str, 16);
str = getNext(bir);
if ( !str.equals("") )
ci.lowercase = (char)Integer.parseInt(str, 16);
str = getNext(bir);
if ( !str.equals("") )
ci.titlecase = (char)Integer.parseInt(str, 16);
chars[code] = ci;
}
CharInfo ch = new CharInfo();
ch.name = "CJK Ideograph";
ch.category = "Lo";
ch.digit = -1;
ch.numericValue = -1;
for ( int i = 0x4E01; i <= 0x9FA4; i++ )
{
chars[i] = ch;
}
ch = new CharInfo();
ch.name = "Hangul Syllable";
ch.category = "Lo";
ch.digit = -1;
ch.numericValue = -1;
for ( int i = 0xAC01; i <= 0xD7A2; i++ )
{
chars[i] = ch;
}
ch = new CharInfo();
ch.name = "CJK Compatibility Ideograph";
ch.category = "Lo";
ch.digit = -1;
ch.numericValue = -1;
for ( int i = 0xF901; i <= 0xFA2C; i++ )
{
chars[i] = ch;
}
ch = new CharInfo();
ch.name = "Surrogate";
ch.category= "Cs";
ch.digit = -1;
ch.numericValue = -1;
for ( int i = 0xD800; i <= 0xDFFFl; i++ )
{
chars[i] = ch;
}
ch = new CharInfo();
ch.name = "Private Use";
ch.category = "Co";
ch.digit = -1;
ch.numericValue = -1;
for ( int i = 0xE000; i <= 0xF8FF; i++ )
{
chars[i] = ch;
}
ch = new CharInfo();
ch.name = "UNDEFINED";
ch.category = "Cn";
ch.digit = -1;
ch.numericValue = -1;
for ( int i =0; i <= 0xFFFF; i++ )
{
if ( chars[i] == null )
chars[i] = ch;
}
/*
It is not stated that A-Z and a-z should
have getNumericValue() (as it is in digit())
*/
for ( int i = 'A'; i <= 'Z'; i++ )
{
chars[i].digit = i - 'A' + 10;
chars[i].numericValue = chars[i].digit; // ??
}
for ( int i = 'a'; i <= 'z'; i++ )
{
chars[i].digit = i - 'a' + 10;
chars[i].numericValue = chars[i].digit; // ??
}
/*
Following two ranges are not clearly stated in
spec, but they are reasonable;
*/
for ( int i = 0xFF21; i <= 0xFF3A; i++ )
{
chars[i].digit = i - 0xFF21 + 10;
chars[i].numericValue = chars[i].digit; // ??
}
for ( int i = 0xFF41; i <= 0xFF5A; i++ )
{
chars[i].digit = i - 0xFF41 + 10;
chars[i].numericValue = chars[i].digit; // ??
}
harness.debug("done");
}
private String getNext( Reader r ) throws IOException
{
StringBuffer sb = new StringBuffer();
while ( r.ready() )
{
char ch = (char)r.read();
if ( ch == '\r' )
{
continue;
}
else if (ch == ';' || ch == '\n' )
{
return sb.toString();
}
else
sb.append(ch);
}
return sb.toString();
}
public String stringChar(int ch )
{
return "Character " + Integer.toString(ch,16) + ":"
+ chars[ch].name;
}
private void reportError( String what )
{
harness.check(false,what);
}
private void reportError( int ch, String what )
{
harness.check(false,stringChar(ch) +" incorectly reported as " + what);
}
private void checkPassed()
{
harness.check(true);
}
public boolean range( int mid, int low, int high )
{
return (mid >= low && mid <= high);
}
public void performTests()
{
for ( int x =0; x <= 0xffff; x++ )
{
// isLowerCase
char i = (char)x;
if ( "Ll".equals(chars[i].category) !=
Character.isLowerCase((char)i) )
{
reportError(i,
(Character.isLowerCase((char)i) ? "lowercase" : "not-lowercase" ));
}
else checkPassed();
// isUpperCase
if ( "Lu".equals(chars[i].category) !=
Character.isUpperCase((char)i) )
{
reportError(i,
(Character.isUpperCase((char)i) ? "uppercase" : "not-uppercase" ) );
}
else checkPassed();
// isTitleCase
if ( "Lt".equals(chars[i].category) !=
Character.isTitleCase((char)i) )
{
reportError(i,
(Character.isTitleCase((char)i) ? "titlecase" : "not-titlecase" ) );
}
else checkPassed();
// isDigit
// if ( (chars[i].category.charAt(0) == 'N') !=
// Character.isDigit((char)i) )
if ((
(chars[i].name.indexOf("DIGIT") > -1) &&
!range(i,0x2000,0x2FFF)
) !=Character.isDigit((char)i) )
{
reportError(i,
(Character.isDigit((char)i) ? "digit" : "not-digit" ) );
}
else checkPassed();
// isDefined
/* if ( ((chars[i] != null) ||
(i >= 0xD800 && i <= 0xFA2D ) )*/
if ( !chars[i].category.equals("Cn")
!= Character.isDefined((char)i) )
{
reportError(i,
(Character.isDefined((char)i) ? "defined" : "not-defined" ) );
}
else checkPassed();
// isLetter
if ( (
(chars[i].category.charAt(0) == 'L')) !=
Character.isLetter((char)i) )
{
reportError(i,
(Character.isLetter((char)i) ? "letter" : "not-letter" ) );
}
else checkPassed();
// isLetterOrDigit
if ( Character.isLetterOrDigit(i) !=
(Character.isLetter(i) || Character.isDigit(i)) )
{
reportError(i,
(Character.isLetterOrDigit(i) ? "letterordigit" : "not-letterordigit") );
}
else checkPassed();
// isSpaceChar
if ( (
(chars[i].category.charAt(0) == 'Z')) !=
Character.isSpaceChar(i) )
{
reportError(i,
(Character.isSpaceChar(i) ? "spacechar" : "not-spacechar" ) );
}
else checkPassed();
// isWhiteSpace
boolean t = false;
if ( chars[i].category.charAt(0) == 'Z' && i !=0x00a0
&& i != 0xFEFF )
t = true;
if ( range(i,0x0009,0x000D)|| range(i,0x001C,0x001F) )
t = true;
if ( t != Character.isWhitespace(i) )
{
reportError(i,
Character.isWhitespace(i) ? "whitespace" : "not-whitespace" );
}
else checkPassed();
// isISOControl
if ( ((i <= 0x001F)
|| range(i,0x007F,0x009F) ) !=
Character.isISOControl(i) )
{
reportError(i,
Character.isISOControl(i) ? "isocontrol" : "not-isocontrol");
}
else checkPassed();
int type = Character.getType(i);
String typeStr = null;
switch (type)
{
case Character.UNASSIGNED: typeStr = "Cn"; break;
case Character.UPPERCASE_LETTER: typeStr = "Lu"; break;
case Character.LOWERCASE_LETTER: typeStr = "Ll"; break;
case Character.TITLECASE_LETTER: typeStr = "Lt"; break;
case Character.MODIFIER_LETTER: typeStr = "Lm"; break;
case Character.OTHER_LETTER: typeStr = "Lo"; break;
case Character.NON_SPACING_MARK: typeStr = "Mn"; break;
case Character.ENCLOSING_MARK: typeStr = "Me"; break;
case Character.COMBINING_SPACING_MARK: typeStr = "Mc"; break;
case Character.DECIMAL_DIGIT_NUMBER: typeStr = "Nd"; break;
case Character.LETTER_NUMBER: typeStr = "Nl"; break;
case Character.OTHER_NUMBER: typeStr = "No"; break;
case Character.SPACE_SEPARATOR: typeStr = "Zs"; break;
case Character.LINE_SEPARATOR: typeStr = "Zl"; break;
case Character.PARAGRAPH_SEPARATOR: typeStr = "Zp"; break;
case Character.CONTROL: typeStr = "Cc"; break;
case Character.FORMAT: typeStr = "Cf"; break;
case Character.PRIVATE_USE: typeStr = "Co"; break;
case Character.SURROGATE: typeStr = "Cs"; break;
case Character.DASH_PUNCTUATION: typeStr = "Pd"; break;
case Character.START_PUNCTUATION: typeStr = "Ps"; break;
case Character.END_PUNCTUATION: typeStr = "Pe"; break;
case Character.CONNECTOR_PUNCTUATION: typeStr = "Pc"; break;
case Character.OTHER_PUNCTUATION: typeStr = "Po"; break;
case Character.MATH_SYMBOL: typeStr = "Sm"; break;
case Character.CURRENCY_SYMBOL: typeStr = "Sc"; break;
case Character.MODIFIER_SYMBOL: typeStr = "Sk"; break;
case Character.OTHER_SYMBOL: typeStr = "So"; break;
default: typeStr = "ERROR"; break;
}
if ( !chars[i].category.equals(typeStr) )
{
reportError(
stringChar(i) + " is reported to be type " + typeStr +
" instead of " + chars[i].category);
}
else checkPassed();
// isJavaIdentifierStart
if ( ( (chars[i].category.charAt(0) == 'L') ||
chars[i].category.equals("Sc") ||
chars[i].category.equals("Pc") ) !=
Character.isJavaIdentifierStart(i) )
{
reportError(i,
Character.isJavaIdentifierStart(i) ? "javaindetifierstart" : "not-javaidentfierstart");
}
else checkPassed();
// isJavaIdentifierPart
boolean shouldbe = false;
typeStr = chars[i].category;
if (
(
typeStr.charAt(0) == 'L' ||
typeStr.equals("Sc") ||
typeStr.equals("Pc") ||
typeStr.equals("Nd") ||
typeStr.equals("Nl") ||
typeStr.equals("Mc") ||
typeStr.equals("Mn") ||
typeStr.equals("Cf") ||
- (typeStr.equals("Cc") &&
- !range(i,0x0009,0x000D) && !range(i,0x001C,0x001F))
+ (typeStr.equals("Cc")
+ // This test comes from JCL volume 1.
+ && (range (i, 0, 8)
+ || range (i, 0x0e, 0x1b)
+ || range (i, 0x200c, 0x200f)
+ // However, the JCL book has a typo which
+ // we fix on the next line.
+ || range (i, 0x202a, 0x202e)
+ || range (i, 0x206a, 0x206f)
+ || i == 0xfeff))
) != Character.isJavaIdentifierPart(i) )
{
reportError(i,
Character.isJavaIdentifierPart(i) ? "javaidentifierpart" : "not-javaidentifierpart" );
}
else checkPassed();
//isUnicodeIdentifierStart
if ( (chars[i].category.charAt(0) == 'L') !=
Character.isUnicodeIdentifierStart(i) )
{
reportError(i,
Character.isUnicodeIdentifierStart(i) ? "unicodeidentifierstart" : "not-unicodeidentifierstart" );
}
else checkPassed();
//isUnicodeIdentifierPart
shouldbe = false;
typeStr = chars[i].category;
if (
(
typeStr.charAt(0) == 'L' ||
typeStr.equals("Pc") ||
typeStr.equals("Nd") ||
typeStr.equals("Nl") ||
typeStr.equals("Mc") ||
typeStr.equals("Mn") ||
typeStr.equals("Cf") ||
- (typeStr.equals("Cc") &&
- !range(i,0x0009,0x000D) && !range(i,0x001C,0x001F))
+ (typeStr.equals("Cc")
+ // This test comes from JCL volume 1.
+ && (range (i, 0, 8)
+ || range (i, 0x0e, 0x1b)
+ || range (i, 0x200c, 0x200f)
+ // However, the JCL book has a typo which
+ // we fix on the next line.
+ || range (i, 0x202a, 0x202e)
+ || range (i, 0x206a, 0x206f)
+ || i == 0xfeff))
) != Character.isUnicodeIdentifierPart(i) )
{
reportError(i,
Character.isUnicodeIdentifierPart(i) ? "unicodeidentifierpart" : "not-unicodeidentifierpart" );
}
else checkPassed();
//isIdentifierIgnorable
if (
(
range(i,0x0000,0x0008) ||
range(i,0x000E,0x001B) ||
- range(i,0x007F,0x009F) ||
range(i,0x200C,0x200F) ||
range(i,0x202A,0x202E) ||
range(i,0x206A,0x206F) ||
i == 0xFEFF
) != Character.isIdentifierIgnorable(i) )
{
reportError(i,
Character.isIdentifierIgnorable(i)? "identifierignorable": "not-identifierignorable");
}
else checkPassed();
// toLowerCase
char cs = (chars[i].lowercase != 0 ? chars[i].lowercase : i);
if ( Character.toLowerCase(i) != cs )
{
reportError(stringChar(i) + " has wrong lowercase form of " +
stringChar(Character.toLowerCase(i)) +" instead of " +
stringChar(cs) );
}
else checkPassed();
// toUpperCase
cs =(chars[i].uppercase != 0 ? chars[i].uppercase : i);
if ( Character.toUpperCase(i) != cs )
{
reportError( stringChar(i) +
" has wrong uppercase form of " +
stringChar(Character.toUpperCase(i)) +
" instead of " +
stringChar(cs) );
}
else checkPassed();
// toTitleCase
cs = (chars[i].titlecase != 0 ? chars[i].titlecase :
chars[i].uppercase !=0 ? chars[i].uppercase : i);
if ( "Lt".equals(chars[i].category) )
{
cs = i;
}
if ( Character.toTitleCase(i) != cs )
{
reportError( stringChar(i) +
" has wrong titlecase form of " +
stringChar(Character.toTitleCase(i)) +
" instead of " +
stringChar(cs) );
}
else checkPassed();
// digit
int digit = chars[i].digit;
for ( int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++)
{
int sb = digit < radix ? digit : -1;
if ( Character.digit(i,radix) != sb )
{
reportError( stringChar(i) + " has wrong digit form of "
+ Character.digit(i,radix) + " for radix " + radix + " instead of "
+ sb );
}
else checkPassed();
}
// getNumericValue
if ( chars[i].numericValue !=
Character.getNumericValue(i) )
{
reportError( stringChar(i) + " has wrong numeric value of " +
Character.getNumericValue(i) + " instead of " + chars[i].numericValue);
}
if ( testDeprecated )
{
// isJavaLetter
if ( (i == '$' || i == '_' || Character.isLetter(i)) !=
Character.isJavaLetter(i) )
{
reportError(i,
(Character.isJavaLetter(i)? "javaletter" : "not-javaletter"));
}
else checkPassed();
// isJavaLetterOrDigit
if ((Character.isJavaLetter(i) || Character.isDigit(i) ||
i == '$' || i == '_') !=
Character.isJavaLetterOrDigit(i)
)
{
reportError(i,
(Character.isJavaLetterOrDigit(i) ? "javaletterordigit" : "not-javaletterordigit") );
}
else checkPassed();
// isSpace
if (((i == ' ' || i == '\t' || i == '\n' || i == '\r' ||
i == '\f')) != Character.isSpace(i) )
{
reportError(i,
(Character.isSpace(i) ? "space" : "non-space" ) );
}
else checkPassed();
} // testDeprecated
} // for
// forDigit
for ( int r = -100; r < 100; r++ )
{
for ( int d = -100; d < 100; d++ )
{
char dch = Character.forDigit(d,r);
char wantch = 0;
if ( range(r, Character.MIN_RADIX, Character.MAX_RADIX) &&
range(d,0,r-1) )
{
if ( d < 10 )
{
wantch = (char)('0' + (char)d);
}
else if ( d < 36 )
{
wantch = (char)('a' + d - 10);
}
}
if ( dch != wantch )
{
reportError( "Error in forDigit(" + d +
"," + r + "), got " + dch + " wanted " +
wantch );
}
else checkPassed();
}
}
}
public void test(TestHarness harness)
{
try {
long start = System.currentTimeMillis();
unicode t = new unicode(harness, "UnicodeData.txt");
long midtime = System.currentTimeMillis();
t.performTests();
harness.debug("Bechmark : load:" + (midtime-start) +
"ms tests:" + (System.currentTimeMillis() - midtime) + "ms");
}
catch ( Exception e )
{
harness.debug(e);
harness.check(false);
}
}
}
| false | true | public void performTests()
{
for ( int x =0; x <= 0xffff; x++ )
{
// isLowerCase
char i = (char)x;
if ( "Ll".equals(chars[i].category) !=
Character.isLowerCase((char)i) )
{
reportError(i,
(Character.isLowerCase((char)i) ? "lowercase" : "not-lowercase" ));
}
else checkPassed();
// isUpperCase
if ( "Lu".equals(chars[i].category) !=
Character.isUpperCase((char)i) )
{
reportError(i,
(Character.isUpperCase((char)i) ? "uppercase" : "not-uppercase" ) );
}
else checkPassed();
// isTitleCase
if ( "Lt".equals(chars[i].category) !=
Character.isTitleCase((char)i) )
{
reportError(i,
(Character.isTitleCase((char)i) ? "titlecase" : "not-titlecase" ) );
}
else checkPassed();
// isDigit
// if ( (chars[i].category.charAt(0) == 'N') !=
// Character.isDigit((char)i) )
if ((
(chars[i].name.indexOf("DIGIT") > -1) &&
!range(i,0x2000,0x2FFF)
) !=Character.isDigit((char)i) )
{
reportError(i,
(Character.isDigit((char)i) ? "digit" : "not-digit" ) );
}
else checkPassed();
// isDefined
/* if ( ((chars[i] != null) ||
(i >= 0xD800 && i <= 0xFA2D ) )*/
if ( !chars[i].category.equals("Cn")
!= Character.isDefined((char)i) )
{
reportError(i,
(Character.isDefined((char)i) ? "defined" : "not-defined" ) );
}
else checkPassed();
// isLetter
if ( (
(chars[i].category.charAt(0) == 'L')) !=
Character.isLetter((char)i) )
{
reportError(i,
(Character.isLetter((char)i) ? "letter" : "not-letter" ) );
}
else checkPassed();
// isLetterOrDigit
if ( Character.isLetterOrDigit(i) !=
(Character.isLetter(i) || Character.isDigit(i)) )
{
reportError(i,
(Character.isLetterOrDigit(i) ? "letterordigit" : "not-letterordigit") );
}
else checkPassed();
// isSpaceChar
if ( (
(chars[i].category.charAt(0) == 'Z')) !=
Character.isSpaceChar(i) )
{
reportError(i,
(Character.isSpaceChar(i) ? "spacechar" : "not-spacechar" ) );
}
else checkPassed();
// isWhiteSpace
boolean t = false;
if ( chars[i].category.charAt(0) == 'Z' && i !=0x00a0
&& i != 0xFEFF )
t = true;
if ( range(i,0x0009,0x000D)|| range(i,0x001C,0x001F) )
t = true;
if ( t != Character.isWhitespace(i) )
{
reportError(i,
Character.isWhitespace(i) ? "whitespace" : "not-whitespace" );
}
else checkPassed();
// isISOControl
if ( ((i <= 0x001F)
|| range(i,0x007F,0x009F) ) !=
Character.isISOControl(i) )
{
reportError(i,
Character.isISOControl(i) ? "isocontrol" : "not-isocontrol");
}
else checkPassed();
int type = Character.getType(i);
String typeStr = null;
switch (type)
{
case Character.UNASSIGNED: typeStr = "Cn"; break;
case Character.UPPERCASE_LETTER: typeStr = "Lu"; break;
case Character.LOWERCASE_LETTER: typeStr = "Ll"; break;
case Character.TITLECASE_LETTER: typeStr = "Lt"; break;
case Character.MODIFIER_LETTER: typeStr = "Lm"; break;
case Character.OTHER_LETTER: typeStr = "Lo"; break;
case Character.NON_SPACING_MARK: typeStr = "Mn"; break;
case Character.ENCLOSING_MARK: typeStr = "Me"; break;
case Character.COMBINING_SPACING_MARK: typeStr = "Mc"; break;
case Character.DECIMAL_DIGIT_NUMBER: typeStr = "Nd"; break;
case Character.LETTER_NUMBER: typeStr = "Nl"; break;
case Character.OTHER_NUMBER: typeStr = "No"; break;
case Character.SPACE_SEPARATOR: typeStr = "Zs"; break;
case Character.LINE_SEPARATOR: typeStr = "Zl"; break;
case Character.PARAGRAPH_SEPARATOR: typeStr = "Zp"; break;
case Character.CONTROL: typeStr = "Cc"; break;
case Character.FORMAT: typeStr = "Cf"; break;
case Character.PRIVATE_USE: typeStr = "Co"; break;
case Character.SURROGATE: typeStr = "Cs"; break;
case Character.DASH_PUNCTUATION: typeStr = "Pd"; break;
case Character.START_PUNCTUATION: typeStr = "Ps"; break;
case Character.END_PUNCTUATION: typeStr = "Pe"; break;
case Character.CONNECTOR_PUNCTUATION: typeStr = "Pc"; break;
case Character.OTHER_PUNCTUATION: typeStr = "Po"; break;
case Character.MATH_SYMBOL: typeStr = "Sm"; break;
case Character.CURRENCY_SYMBOL: typeStr = "Sc"; break;
case Character.MODIFIER_SYMBOL: typeStr = "Sk"; break;
case Character.OTHER_SYMBOL: typeStr = "So"; break;
default: typeStr = "ERROR"; break;
}
if ( !chars[i].category.equals(typeStr) )
{
reportError(
stringChar(i) + " is reported to be type " + typeStr +
" instead of " + chars[i].category);
}
else checkPassed();
// isJavaIdentifierStart
if ( ( (chars[i].category.charAt(0) == 'L') ||
chars[i].category.equals("Sc") ||
chars[i].category.equals("Pc") ) !=
Character.isJavaIdentifierStart(i) )
{
reportError(i,
Character.isJavaIdentifierStart(i) ? "javaindetifierstart" : "not-javaidentfierstart");
}
else checkPassed();
// isJavaIdentifierPart
boolean shouldbe = false;
typeStr = chars[i].category;
if (
(
typeStr.charAt(0) == 'L' ||
typeStr.equals("Sc") ||
typeStr.equals("Pc") ||
typeStr.equals("Nd") ||
typeStr.equals("Nl") ||
typeStr.equals("Mc") ||
typeStr.equals("Mn") ||
typeStr.equals("Cf") ||
(typeStr.equals("Cc") &&
!range(i,0x0009,0x000D) && !range(i,0x001C,0x001F))
) != Character.isJavaIdentifierPart(i) )
{
reportError(i,
Character.isJavaIdentifierPart(i) ? "javaidentifierpart" : "not-javaidentifierpart" );
}
else checkPassed();
//isUnicodeIdentifierStart
if ( (chars[i].category.charAt(0) == 'L') !=
Character.isUnicodeIdentifierStart(i) )
{
reportError(i,
Character.isUnicodeIdentifierStart(i) ? "unicodeidentifierstart" : "not-unicodeidentifierstart" );
}
else checkPassed();
//isUnicodeIdentifierPart
shouldbe = false;
typeStr = chars[i].category;
if (
(
typeStr.charAt(0) == 'L' ||
typeStr.equals("Pc") ||
typeStr.equals("Nd") ||
typeStr.equals("Nl") ||
typeStr.equals("Mc") ||
typeStr.equals("Mn") ||
typeStr.equals("Cf") ||
(typeStr.equals("Cc") &&
!range(i,0x0009,0x000D) && !range(i,0x001C,0x001F))
) != Character.isUnicodeIdentifierPart(i) )
{
reportError(i,
Character.isUnicodeIdentifierPart(i) ? "unicodeidentifierpart" : "not-unicodeidentifierpart" );
}
else checkPassed();
//isIdentifierIgnorable
if (
(
range(i,0x0000,0x0008) ||
range(i,0x000E,0x001B) ||
range(i,0x007F,0x009F) ||
range(i,0x200C,0x200F) ||
range(i,0x202A,0x202E) ||
range(i,0x206A,0x206F) ||
i == 0xFEFF
) != Character.isIdentifierIgnorable(i) )
{
reportError(i,
Character.isIdentifierIgnorable(i)? "identifierignorable": "not-identifierignorable");
}
else checkPassed();
// toLowerCase
char cs = (chars[i].lowercase != 0 ? chars[i].lowercase : i);
if ( Character.toLowerCase(i) != cs )
{
reportError(stringChar(i) + " has wrong lowercase form of " +
stringChar(Character.toLowerCase(i)) +" instead of " +
stringChar(cs) );
}
else checkPassed();
// toUpperCase
cs =(chars[i].uppercase != 0 ? chars[i].uppercase : i);
if ( Character.toUpperCase(i) != cs )
{
reportError( stringChar(i) +
" has wrong uppercase form of " +
stringChar(Character.toUpperCase(i)) +
" instead of " +
stringChar(cs) );
}
else checkPassed();
// toTitleCase
cs = (chars[i].titlecase != 0 ? chars[i].titlecase :
chars[i].uppercase !=0 ? chars[i].uppercase : i);
if ( "Lt".equals(chars[i].category) )
{
cs = i;
}
if ( Character.toTitleCase(i) != cs )
{
reportError( stringChar(i) +
" has wrong titlecase form of " +
stringChar(Character.toTitleCase(i)) +
" instead of " +
stringChar(cs) );
}
else checkPassed();
// digit
int digit = chars[i].digit;
for ( int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++)
{
int sb = digit < radix ? digit : -1;
if ( Character.digit(i,radix) != sb )
{
reportError( stringChar(i) + " has wrong digit form of "
+ Character.digit(i,radix) + " for radix " + radix + " instead of "
+ sb );
}
else checkPassed();
}
// getNumericValue
if ( chars[i].numericValue !=
Character.getNumericValue(i) )
{
reportError( stringChar(i) + " has wrong numeric value of " +
Character.getNumericValue(i) + " instead of " + chars[i].numericValue);
}
if ( testDeprecated )
{
// isJavaLetter
if ( (i == '$' || i == '_' || Character.isLetter(i)) !=
Character.isJavaLetter(i) )
{
reportError(i,
(Character.isJavaLetter(i)? "javaletter" : "not-javaletter"));
}
else checkPassed();
// isJavaLetterOrDigit
if ((Character.isJavaLetter(i) || Character.isDigit(i) ||
i == '$' || i == '_') !=
Character.isJavaLetterOrDigit(i)
)
{
reportError(i,
(Character.isJavaLetterOrDigit(i) ? "javaletterordigit" : "not-javaletterordigit") );
}
else checkPassed();
// isSpace
if (((i == ' ' || i == '\t' || i == '\n' || i == '\r' ||
i == '\f')) != Character.isSpace(i) )
{
reportError(i,
(Character.isSpace(i) ? "space" : "non-space" ) );
}
else checkPassed();
} // testDeprecated
} // for
// forDigit
for ( int r = -100; r < 100; r++ )
{
for ( int d = -100; d < 100; d++ )
{
char dch = Character.forDigit(d,r);
char wantch = 0;
if ( range(r, Character.MIN_RADIX, Character.MAX_RADIX) &&
range(d,0,r-1) )
{
if ( d < 10 )
{
wantch = (char)('0' + (char)d);
}
else if ( d < 36 )
{
wantch = (char)('a' + d - 10);
}
}
if ( dch != wantch )
{
reportError( "Error in forDigit(" + d +
"," + r + "), got " + dch + " wanted " +
wantch );
}
else checkPassed();
}
}
}
| public void performTests()
{
for ( int x =0; x <= 0xffff; x++ )
{
// isLowerCase
char i = (char)x;
if ( "Ll".equals(chars[i].category) !=
Character.isLowerCase((char)i) )
{
reportError(i,
(Character.isLowerCase((char)i) ? "lowercase" : "not-lowercase" ));
}
else checkPassed();
// isUpperCase
if ( "Lu".equals(chars[i].category) !=
Character.isUpperCase((char)i) )
{
reportError(i,
(Character.isUpperCase((char)i) ? "uppercase" : "not-uppercase" ) );
}
else checkPassed();
// isTitleCase
if ( "Lt".equals(chars[i].category) !=
Character.isTitleCase((char)i) )
{
reportError(i,
(Character.isTitleCase((char)i) ? "titlecase" : "not-titlecase" ) );
}
else checkPassed();
// isDigit
// if ( (chars[i].category.charAt(0) == 'N') !=
// Character.isDigit((char)i) )
if ((
(chars[i].name.indexOf("DIGIT") > -1) &&
!range(i,0x2000,0x2FFF)
) !=Character.isDigit((char)i) )
{
reportError(i,
(Character.isDigit((char)i) ? "digit" : "not-digit" ) );
}
else checkPassed();
// isDefined
/* if ( ((chars[i] != null) ||
(i >= 0xD800 && i <= 0xFA2D ) )*/
if ( !chars[i].category.equals("Cn")
!= Character.isDefined((char)i) )
{
reportError(i,
(Character.isDefined((char)i) ? "defined" : "not-defined" ) );
}
else checkPassed();
// isLetter
if ( (
(chars[i].category.charAt(0) == 'L')) !=
Character.isLetter((char)i) )
{
reportError(i,
(Character.isLetter((char)i) ? "letter" : "not-letter" ) );
}
else checkPassed();
// isLetterOrDigit
if ( Character.isLetterOrDigit(i) !=
(Character.isLetter(i) || Character.isDigit(i)) )
{
reportError(i,
(Character.isLetterOrDigit(i) ? "letterordigit" : "not-letterordigit") );
}
else checkPassed();
// isSpaceChar
if ( (
(chars[i].category.charAt(0) == 'Z')) !=
Character.isSpaceChar(i) )
{
reportError(i,
(Character.isSpaceChar(i) ? "spacechar" : "not-spacechar" ) );
}
else checkPassed();
// isWhiteSpace
boolean t = false;
if ( chars[i].category.charAt(0) == 'Z' && i !=0x00a0
&& i != 0xFEFF )
t = true;
if ( range(i,0x0009,0x000D)|| range(i,0x001C,0x001F) )
t = true;
if ( t != Character.isWhitespace(i) )
{
reportError(i,
Character.isWhitespace(i) ? "whitespace" : "not-whitespace" );
}
else checkPassed();
// isISOControl
if ( ((i <= 0x001F)
|| range(i,0x007F,0x009F) ) !=
Character.isISOControl(i) )
{
reportError(i,
Character.isISOControl(i) ? "isocontrol" : "not-isocontrol");
}
else checkPassed();
int type = Character.getType(i);
String typeStr = null;
switch (type)
{
case Character.UNASSIGNED: typeStr = "Cn"; break;
case Character.UPPERCASE_LETTER: typeStr = "Lu"; break;
case Character.LOWERCASE_LETTER: typeStr = "Ll"; break;
case Character.TITLECASE_LETTER: typeStr = "Lt"; break;
case Character.MODIFIER_LETTER: typeStr = "Lm"; break;
case Character.OTHER_LETTER: typeStr = "Lo"; break;
case Character.NON_SPACING_MARK: typeStr = "Mn"; break;
case Character.ENCLOSING_MARK: typeStr = "Me"; break;
case Character.COMBINING_SPACING_MARK: typeStr = "Mc"; break;
case Character.DECIMAL_DIGIT_NUMBER: typeStr = "Nd"; break;
case Character.LETTER_NUMBER: typeStr = "Nl"; break;
case Character.OTHER_NUMBER: typeStr = "No"; break;
case Character.SPACE_SEPARATOR: typeStr = "Zs"; break;
case Character.LINE_SEPARATOR: typeStr = "Zl"; break;
case Character.PARAGRAPH_SEPARATOR: typeStr = "Zp"; break;
case Character.CONTROL: typeStr = "Cc"; break;
case Character.FORMAT: typeStr = "Cf"; break;
case Character.PRIVATE_USE: typeStr = "Co"; break;
case Character.SURROGATE: typeStr = "Cs"; break;
case Character.DASH_PUNCTUATION: typeStr = "Pd"; break;
case Character.START_PUNCTUATION: typeStr = "Ps"; break;
case Character.END_PUNCTUATION: typeStr = "Pe"; break;
case Character.CONNECTOR_PUNCTUATION: typeStr = "Pc"; break;
case Character.OTHER_PUNCTUATION: typeStr = "Po"; break;
case Character.MATH_SYMBOL: typeStr = "Sm"; break;
case Character.CURRENCY_SYMBOL: typeStr = "Sc"; break;
case Character.MODIFIER_SYMBOL: typeStr = "Sk"; break;
case Character.OTHER_SYMBOL: typeStr = "So"; break;
default: typeStr = "ERROR"; break;
}
if ( !chars[i].category.equals(typeStr) )
{
reportError(
stringChar(i) + " is reported to be type " + typeStr +
" instead of " + chars[i].category);
}
else checkPassed();
// isJavaIdentifierStart
if ( ( (chars[i].category.charAt(0) == 'L') ||
chars[i].category.equals("Sc") ||
chars[i].category.equals("Pc") ) !=
Character.isJavaIdentifierStart(i) )
{
reportError(i,
Character.isJavaIdentifierStart(i) ? "javaindetifierstart" : "not-javaidentfierstart");
}
else checkPassed();
// isJavaIdentifierPart
boolean shouldbe = false;
typeStr = chars[i].category;
if (
(
typeStr.charAt(0) == 'L' ||
typeStr.equals("Sc") ||
typeStr.equals("Pc") ||
typeStr.equals("Nd") ||
typeStr.equals("Nl") ||
typeStr.equals("Mc") ||
typeStr.equals("Mn") ||
typeStr.equals("Cf") ||
(typeStr.equals("Cc")
// This test comes from JCL volume 1.
&& (range (i, 0, 8)
|| range (i, 0x0e, 0x1b)
|| range (i, 0x200c, 0x200f)
// However, the JCL book has a typo which
// we fix on the next line.
|| range (i, 0x202a, 0x202e)
|| range (i, 0x206a, 0x206f)
|| i == 0xfeff))
) != Character.isJavaIdentifierPart(i) )
{
reportError(i,
Character.isJavaIdentifierPart(i) ? "javaidentifierpart" : "not-javaidentifierpart" );
}
else checkPassed();
//isUnicodeIdentifierStart
if ( (chars[i].category.charAt(0) == 'L') !=
Character.isUnicodeIdentifierStart(i) )
{
reportError(i,
Character.isUnicodeIdentifierStart(i) ? "unicodeidentifierstart" : "not-unicodeidentifierstart" );
}
else checkPassed();
//isUnicodeIdentifierPart
shouldbe = false;
typeStr = chars[i].category;
if (
(
typeStr.charAt(0) == 'L' ||
typeStr.equals("Pc") ||
typeStr.equals("Nd") ||
typeStr.equals("Nl") ||
typeStr.equals("Mc") ||
typeStr.equals("Mn") ||
typeStr.equals("Cf") ||
(typeStr.equals("Cc")
// This test comes from JCL volume 1.
&& (range (i, 0, 8)
|| range (i, 0x0e, 0x1b)
|| range (i, 0x200c, 0x200f)
// However, the JCL book has a typo which
// we fix on the next line.
|| range (i, 0x202a, 0x202e)
|| range (i, 0x206a, 0x206f)
|| i == 0xfeff))
) != Character.isUnicodeIdentifierPart(i) )
{
reportError(i,
Character.isUnicodeIdentifierPart(i) ? "unicodeidentifierpart" : "not-unicodeidentifierpart" );
}
else checkPassed();
//isIdentifierIgnorable
if (
(
range(i,0x0000,0x0008) ||
range(i,0x000E,0x001B) ||
range(i,0x200C,0x200F) ||
range(i,0x202A,0x202E) ||
range(i,0x206A,0x206F) ||
i == 0xFEFF
) != Character.isIdentifierIgnorable(i) )
{
reportError(i,
Character.isIdentifierIgnorable(i)? "identifierignorable": "not-identifierignorable");
}
else checkPassed();
// toLowerCase
char cs = (chars[i].lowercase != 0 ? chars[i].lowercase : i);
if ( Character.toLowerCase(i) != cs )
{
reportError(stringChar(i) + " has wrong lowercase form of " +
stringChar(Character.toLowerCase(i)) +" instead of " +
stringChar(cs) );
}
else checkPassed();
// toUpperCase
cs =(chars[i].uppercase != 0 ? chars[i].uppercase : i);
if ( Character.toUpperCase(i) != cs )
{
reportError( stringChar(i) +
" has wrong uppercase form of " +
stringChar(Character.toUpperCase(i)) +
" instead of " +
stringChar(cs) );
}
else checkPassed();
// toTitleCase
cs = (chars[i].titlecase != 0 ? chars[i].titlecase :
chars[i].uppercase !=0 ? chars[i].uppercase : i);
if ( "Lt".equals(chars[i].category) )
{
cs = i;
}
if ( Character.toTitleCase(i) != cs )
{
reportError( stringChar(i) +
" has wrong titlecase form of " +
stringChar(Character.toTitleCase(i)) +
" instead of " +
stringChar(cs) );
}
else checkPassed();
// digit
int digit = chars[i].digit;
for ( int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++)
{
int sb = digit < radix ? digit : -1;
if ( Character.digit(i,radix) != sb )
{
reportError( stringChar(i) + " has wrong digit form of "
+ Character.digit(i,radix) + " for radix " + radix + " instead of "
+ sb );
}
else checkPassed();
}
// getNumericValue
if ( chars[i].numericValue !=
Character.getNumericValue(i) )
{
reportError( stringChar(i) + " has wrong numeric value of " +
Character.getNumericValue(i) + " instead of " + chars[i].numericValue);
}
if ( testDeprecated )
{
// isJavaLetter
if ( (i == '$' || i == '_' || Character.isLetter(i)) !=
Character.isJavaLetter(i) )
{
reportError(i,
(Character.isJavaLetter(i)? "javaletter" : "not-javaletter"));
}
else checkPassed();
// isJavaLetterOrDigit
if ((Character.isJavaLetter(i) || Character.isDigit(i) ||
i == '$' || i == '_') !=
Character.isJavaLetterOrDigit(i)
)
{
reportError(i,
(Character.isJavaLetterOrDigit(i) ? "javaletterordigit" : "not-javaletterordigit") );
}
else checkPassed();
// isSpace
if (((i == ' ' || i == '\t' || i == '\n' || i == '\r' ||
i == '\f')) != Character.isSpace(i) )
{
reportError(i,
(Character.isSpace(i) ? "space" : "non-space" ) );
}
else checkPassed();
} // testDeprecated
} // for
// forDigit
for ( int r = -100; r < 100; r++ )
{
for ( int d = -100; d < 100; d++ )
{
char dch = Character.forDigit(d,r);
char wantch = 0;
if ( range(r, Character.MIN_RADIX, Character.MAX_RADIX) &&
range(d,0,r-1) )
{
if ( d < 10 )
{
wantch = (char)('0' + (char)d);
}
else if ( d < 36 )
{
wantch = (char)('a' + d - 10);
}
}
if ( dch != wantch )
{
reportError( "Error in forDigit(" + d +
"," + r + "), got " + dch + " wanted " +
wantch );
}
else checkPassed();
}
}
}
|
diff --git a/src/com/github/nyao/gwtgithub/client/GitHubApi.java b/src/com/github/nyao/gwtgithub/client/GitHubApi.java
index 3a07459..1f90719 100644
--- a/src/com/github/nyao/gwtgithub/client/GitHubApi.java
+++ b/src/com/github/nyao/gwtgithub/client/GitHubApi.java
@@ -1,328 +1,328 @@
package com.github.nyao.gwtgithub.client;
import com.github.nyao.gwtgithub.client.models.AJSON;
import com.github.nyao.gwtgithub.client.models.JSONs;
import com.github.nyao.gwtgithub.client.models.repos.Content;
import com.github.nyao.gwtgithub.client.models.repos.Repo;
import com.github.nyao.gwtgithub.client.models.gitdata.Blob;
import com.github.nyao.gwtgithub.client.models.gitdata.BlobCreated;
import com.github.nyao.gwtgithub.client.models.gitdata.Commit;
import com.github.nyao.gwtgithub.client.models.gitdata.Reference;
import com.github.nyao.gwtgithub.client.models.gitdata.Tree;
import com.github.nyao.gwtgithub.client.models.issues.Issue;
import com.github.nyao.gwtgithub.client.models.issues.IssueComment;
import com.github.nyao.gwtgithub.client.models.issues.Label;
import com.github.nyao.gwtgithub.client.models.issues.Milestone;
import com.github.nyao.gwtgithub.client.models.users.GHUser;
import com.github.nyao.gwtgithub.client.values.GHValue;
import com.github.nyao.gwtgithub.client.values.RepoValue;
import com.github.nyao.gwtgithub.client.values.gitdata.BlobValue;
import com.github.nyao.gwtgithub.client.values.gitdata.CommitValue;
import com.github.nyao.gwtgithub.client.values.gitdata.ReferenceCreateValue;
import com.github.nyao.gwtgithub.client.values.gitdata.ReferenceUpdateValue;
import com.github.nyao.gwtgithub.client.values.gitdata.TreeValue;
import com.github.nyao.gwtgithub.client.values.issues.IssueCommentValue;
import com.github.nyao.gwtgithub.client.values.issues.IssueValue;
import com.github.nyao.gwtgithub.client.values.issues.LabelValue;
import com.github.nyao.gwtgithub.client.values.issues.MilestoneValue;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsonUtils;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.jsonp.client.JsonpRequestBuilder;
import com.google.gwt.user.client.rpc.AsyncCallback;
public class GitHubApi {
private String accessToken = null;
private String baseUrl = "https://api.github.com/";
private boolean authorized = false;
public void setGitHubURL(String url) {
this.baseUrl = url;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public boolean isAuthorized() {
return this.authorized;
}
// Users
public void getUser(String login, final AsyncCallback<AJSON<GHUser>> callback) {
get(baseUrl + "users/" + URL.encode(login), callback);
}
public void getUser(final AsyncCallback<AJSON<GHUser>> callback) {
get(baseUrl + "user", callback);
}
// Repos
public void getRepos(AsyncCallback<JSONs<Repo>> callback) {
get(baseUrl + "user/repos", callback);
}
public void getRepos(String user, AsyncCallback<JSONs<Repo>> callback) {
get(baseUrl + "users/" + URL.encode(user) + "/repos", callback);
}
public void getRepo(String login, String name, AsyncCallback<AJSON<Repo>> callback) {
get(baseUrl + "repos/" + URL.encode(login) + "/" + URL.encode(name), callback);
}
public void saveRepo(Repo r, RepoValue prop, AsyncCallback<Repo> callback) {
post(r.getUrl(), prop, callback);
}
// Contents
public void getContent(Repo repo, String path, String ref, AsyncCallback<AJSON<Content>> callback) {
get(repo.getUrl() + "/contents/" + path + "?ref=" + ref, callback);
}
// Orgs
public void getOrgs(String user, AsyncCallback<JSONs<GHUser>> callback) {
get(baseUrl + "users/" + user + "/orgs", callback);
}
public void getOrgs(AsyncCallback<JSONs<GHUser>> callback) {
get(baseUrl + "user/orgs", callback);
}
// Issues
public void getIssues(String user, String r, AsyncCallback<JSONs<Issue>> callback) {
get(baseUrl + "repos/" + user + "/" + r + "/issues", callback);
}
public void getIssues(Repo r, AsyncCallback<JSONs<Issue>> callback) {
get(r.getUrl() + "/issues", callback);
}
public void createIssue(Repo r, IssueValue prop, final AsyncCallback<Issue> callback) {
post(r.getUrl() + "/issues", prop, callback);
}
public void editIssue(Repo r, Issue issue, IssueValue prop,
final AsyncCallback<Issue> callback) {
if (issue == null) {
createIssue(r, prop, callback);
} else {
post(r.getUrl() + "/issues/" + issue.getNumber(), prop, callback);
}
}
// Comments
public void getIssueComments(Repo r, Issue issue, AsyncCallback<JSONs<IssueComment>> callback) {
get(r.getUrl() + "/issues/" + issue.getNumber() + "/comments", callback);
}
public void createIssueComment(Repo r, Issue issue, IssueCommentValue prop,
final AsyncCallback<IssueComment> callback) {
post(r.getUrl() + "/issues/" + issue.getNumber() + "/comments", prop, callback);
}
// Milestones
public void getMilestones(Repo r, AsyncCallback<JSONs<Milestone>> callback) {
get(r.getUrl() + "/milestones", callback);
}
public void createMilestone(Repo r, MilestoneValue prop,
final AsyncCallback<Milestone> callback) {
post(r.getUrl() + "/milestones", prop, callback);
}
public void saveMilestone(Repo r, Milestone m, MilestoneValue prop,
final AsyncCallback<Milestone> callback) {
if (m ==null) {
createMilestone(r, prop, callback);
} else {
post(r.getUrl() + "/milestones/" + m.getNumber(), prop, callback);
}
}
public void saveMilestone(Repo r, String number, MilestoneValue prop,
final AsyncCallback<Milestone> callback) {
if (number ==null) {
createMilestone(r, prop, callback);
} else {
post(r.getUrl() + "/milestones/" + URL.encode(number), prop, callback);
}
}
// Labels
public void getLabels(Repo r, AsyncCallback<JSONs<Label>> callback) {
get(r.getUrl() + "/labels", callback);
}
public void createLabel(Repo r, LabelValue prop,
final AsyncCallback<Label> callback) {
post(r.getUrl() + "/labels", prop, callback);
}
public void saveLabel(Repo r, String name, LabelValue prop,
final AsyncCallback<Label> callback) {
if (name == null) {
createLabel(r, prop, callback);
} else {
post(r.getUrl() + "/labels/" + URL.encode(name), prop, callback);
}
}
public void saveLabel(Repo r, Label label, LabelValue prop,
final AsyncCallback<Label> callback) {
if (label == null) {
createLabel(r, prop, callback);
} else {
post(r.getUrl() + "/labels/" + URL.encode(label.getName()), prop, callback);
}
}
// Blobs
public void getBlob(Repo r, String sha, AsyncCallback<AJSON<Blob>> callback) {
get(r.getUrl() + "/git/blobs/" + URL.encode(sha), callback);
}
public void getBlob(Repo repo, Reference ref, final String filename, final AsyncCallback<AJSON<Blob>> callback) {
new GitHubSimpleApi(this, repo).getBlob(ref, filename, callback);
}
public void createBlob(Repo r, BlobValue blob, AsyncCallback<BlobCreated> callback) {
post(r.getUrl() + "/git/blobs", blob, callback);
}
// Trees
public void getTree(Repo r, String sha, AsyncCallback<AJSON<Tree>> callback) {
get(r.getUrl() + "/git/trees/" + URL.encode(sha), callback);
}
public void createTree(Repo r, TreeValue tree, AsyncCallback<Tree> callback) {
post(r.getUrl() + "/git/trees", tree, callback);
}
// Commits
public void getCommit(Repo r, String sha, AsyncCallback<AJSON<Commit>> callback) {
get(r.getUrl() + "/commits/" + URL.encode(sha), callback);
}
public void getCommit(Reference ref, AsyncCallback<AJSON<Commit>> callback) {
get(ref.getObject().getUrl(), callback);
}
public void createCommit(Repo r, CommitValue commit, AsyncCallback<Commit> callback) {
post(r.getUrl() + "/git/commits", commit, callback);
}
public void createSimpleCommitAndPush(Repo r, Reference ref, String refName, String filename, String content, String message,
AsyncCallback<Reference> callback) {
new GitHubSimpleApi(this, r).createSimpleCommitAndPush(ref, refName, filename, content, message, callback);
}
public void createSimpleCommit(Repo r, String ref, String filename, String content, String message,
AsyncCallback<Commit> callback) {
new GitHubSimpleApi(this, r).createSimpleCommit(null, filename, content, message, callback);
}
// References
public void getReference(Repo r, String ref, AsyncCallback<JSONs<Reference>> callback) {
get(r.getUrl() + "/git/" + URL.encode(ref), callback);
}
public void getReferenceHead(Repo r, String ref, AsyncCallback<AJSON<Reference>> callback) {
get(r.getUrl() + "/git/refs/heads/" + URL.encode(ref), callback);
}
public void createReference(Repo r, ReferenceCreateValue ref, AsyncCallback<Reference> callback) {
post(r.getUrl() + "/git/refs", ref, callback);
}
public void updateReference(Repo r, Reference ref, ReferenceUpdateValue refValue, AsyncCallback<Reference> callback) {
post(r.getUrl() + "/git/" + ref.getRef(), refValue, callback);
}
// private methods
private <T extends JavaScriptObject> AsyncCallback<T> hookCallback(final AsyncCallback<T> callback) {
return new AsyncCallback<T>() {
@Override
public void onSuccess(T result) {
if (accessToken != null) authorized = true;
callback.onSuccess(result);
}
@Override
public void onFailure(Throwable caught) {
callback.onFailure(caught);
}
};
}
private <T extends JavaScriptObject> void get(String url, final AsyncCallback<T> callback) {
String requestUrl = makeRequestUrl(url);
GWT.log("[GET]" + requestUrl);
JsonpRequestBuilder jsonp = new JsonpRequestBuilder();
jsonp.requestObject(requestUrl, hookCallback(callback));
}
private <T extends JavaScriptObject> void post(String url, GHValue<?> request,
AsyncCallback<T> callback) {
String requestUrl = makeRequestUrl(url);
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, requestUrl);
String requestJson = request.toJson();
final AsyncCallback<T> hookedCallback = hookCallback(callback);
final StringBuilder log = new StringBuilder();
log.append("[POST]" + requestUrl + "\n" + requestJson);
try {
builder.sendRequest(requestJson, new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
- T result = JsonUtils.safeEval(response.getText());
+ T result = JsonUtils.<T>safeEval(response.getText());
log.append("\n\n--" + response.getStatusText() + ":" + response.getStatusCode() + "\n" + response.getText());
hookedCallback.onSuccess(result);
GWT.log(log.toString());
}
@Override
public void onError(Request request, Throwable e) {
log.append("\n\n--" + e.getStackTrace());
hookedCallback.onFailure(e);
GWT.log(log.toString());
}
});
} catch (RequestException e) {
log.append("\n\n--" + e.getStackTrace());
hookedCallback.onFailure(e);
GWT.log(log.toString());
}
}
private String makeRequestUrl(String url) {
String prefix = "?";
if (url.contains("?")) {
prefix = "&";
}
if (accessToken != null) {
url += prefix + "access_token=" + accessToken;
}
return url;
}
}
| true | true | private <T extends JavaScriptObject> void post(String url, GHValue<?> request,
AsyncCallback<T> callback) {
String requestUrl = makeRequestUrl(url);
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, requestUrl);
String requestJson = request.toJson();
final AsyncCallback<T> hookedCallback = hookCallback(callback);
final StringBuilder log = new StringBuilder();
log.append("[POST]" + requestUrl + "\n" + requestJson);
try {
builder.sendRequest(requestJson, new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
T result = JsonUtils.safeEval(response.getText());
log.append("\n\n--" + response.getStatusText() + ":" + response.getStatusCode() + "\n" + response.getText());
hookedCallback.onSuccess(result);
GWT.log(log.toString());
}
@Override
public void onError(Request request, Throwable e) {
log.append("\n\n--" + e.getStackTrace());
hookedCallback.onFailure(e);
GWT.log(log.toString());
}
});
} catch (RequestException e) {
log.append("\n\n--" + e.getStackTrace());
hookedCallback.onFailure(e);
GWT.log(log.toString());
}
}
| private <T extends JavaScriptObject> void post(String url, GHValue<?> request,
AsyncCallback<T> callback) {
String requestUrl = makeRequestUrl(url);
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, requestUrl);
String requestJson = request.toJson();
final AsyncCallback<T> hookedCallback = hookCallback(callback);
final StringBuilder log = new StringBuilder();
log.append("[POST]" + requestUrl + "\n" + requestJson);
try {
builder.sendRequest(requestJson, new RequestCallback() {
@Override
public void onResponseReceived(Request request, Response response) {
T result = JsonUtils.<T>safeEval(response.getText());
log.append("\n\n--" + response.getStatusText() + ":" + response.getStatusCode() + "\n" + response.getText());
hookedCallback.onSuccess(result);
GWT.log(log.toString());
}
@Override
public void onError(Request request, Throwable e) {
log.append("\n\n--" + e.getStackTrace());
hookedCallback.onFailure(e);
GWT.log(log.toString());
}
});
} catch (RequestException e) {
log.append("\n\n--" + e.getStackTrace());
hookedCallback.onFailure(e);
GWT.log(log.toString());
}
}
|
diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/Stage.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/Stage.java
index 340030daa..3d9ad63d7 100644
--- a/gdx/src/com/badlogic/gdx/scenes/scene2d/Stage.java
+++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/Stage.java
@@ -1,407 +1,407 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogic.gdx.scenes.scene2d;
import java.util.List;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Disposable;
/** <p>
* A Stage is a container for {@link Actor}s and handles distributing touch events, animating Actors and asking them to render
* themselves. A Stage is basically a 2D scenegraph with hierarchies of Actors.
* </p>
*
* <p>
* A Stage object fills the whole screen. It has a width and height given in device independent pixels. It will create a
* {@link Camera} that maps this viewport to the given real screen resolution. If the stretched attribute is set to true then the
* viewport is enforced no matter the difference in aspect ratio between the stage object and the screen dimensions. In case
* stretch is disabled then the viewport is extended in the bigger screen dimensions.
* </p>
*
* <p>
* Actors have a z-order which is equal to the order they were inserted into this Stage. Actors inserted later will be drawn on
* top of Actors added earlier. Touch events that will get distributed to later Actors first.
* </p>
*
* <p>
* Actors can get focused. When your game pauses and resumes make sure to call the {@link Stage#unfocusAll()} method so that the
* focus states get reset for each pointer id. You also have to make sure that the Actors that were focused reset their state if
* the depend on being focused, e.g. wait for a touch up event. An easier way to tackle this is to recreate the Stage if possible.
* </p>
*
* @author mzechner */
public class Stage extends InputAdapter implements Disposable {
protected float width;
protected float height;
protected float centerX;
protected float centerY;
protected boolean stretch;
protected final Group root;
protected final SpriteBatch batch;
protected Camera camera;
/** <p>
* Constructs a new Stage object with the given dimensions. If the device resolution does not equal the Stage objects
* dimensions the stage object will setup a projection matrix to guarantee a fixed coordinate system. If stretch is disabled
* then the bigger dimension of the Stage will be increased to accomodate the actual device resolution.
* </p>
*
* @param width the width of the viewport
* @param height the height of the viewport
* @param stretch whether to stretch the viewport to the real device resolution */
public Stage (float width, float height, boolean stretch) {
this.width = width;
this.height = height;
this.stretch = stretch;
this.root = new Group("root");
this.batch = new SpriteBatch();
this.camera = new OrthographicCamera();
setViewport(width, height, stretch);
}
/** Sets the viewport dimensions in device independent pixels. If stretch is false and the viewport aspect ratio is not equal to
* the device ratio then the bigger dimension of the viewport will be extended (device independent pixels stay quardatic
* instead of getting stretched).
*
* @param width thew width of the viewport in device independent pixels
* @param height the height of the viewport in device independent pixels
* @param stretch whether to stretch the viewport or not */
public void setViewport (float width, float height, boolean stretch) {
if (!stretch) {
if (width > height && width / (float)Gdx.graphics.getWidth() <= height / (float)Gdx.graphics.getHeight()) {
float toDeviceSpace = Gdx.graphics.getHeight() / height;
float toViewportSpace = height / Gdx.graphics.getHeight();
float deviceWidth = width * toDeviceSpace;
this.width = width + (Gdx.graphics.getWidth() - deviceWidth) * toViewportSpace;
this.height = height;
} else {
float toDeviceSpace = Gdx.graphics.getWidth() / width;
float toViewportSpace = width / Gdx.graphics.getWidth();
float deviceHeight = height * toDeviceSpace;
this.height = height + (Gdx.graphics.getHeight() - deviceHeight) * toViewportSpace;
this.width = width;
}
} else {
this.width = width;
this.height = height;
}
this.stretch = stretch;
- centerX = width / 2;
- centerY = height / 2;
+ centerX = this.width / 2;
+ centerY = this.height / 2;
camera.position.set(centerX, centerY, 0);
camera.viewportWidth = this.width;
camera.viewportHeight = this.height;
}
/** 8
* @return the width of the stage in dips */
public float width () {
return width;
}
/** @return the height of the stage in dips */
public float height () {
return height;
}
/** @return the x-coordinate of the left edge of the stage in dips */
public int left () {
return 0;
}
/** @return the x-coordinate of the right edge of the stage in dips */
public float right () {
return width - 1;
}
/** @return the y-coordinate of the top edge of the stage in dips */
public float top () {
return height - 1;
}
/** @return the y-coordinate of the bottom edge of the stage in dips */
public float bottom () {
return 0;
}
/** @return the center x-coordinate of the stage in dips */
public float centerX () {
return centerX;
}
/** @return the center y-coordinate of the stage in dips */
public float centerY () {
return centerY;
}
/** @return whether the stage is stretched */
public boolean isStretched () {
return stretch;
}
/** Finds the {@link Actor} with the given name in the stage hierarchy.
* @param name
* @return the Actor or null if it couldn't be found. */
public Actor findActor (String name) {
return root.findActor(name);
}
/** @return all top level {@link Actor}s */
public List<Actor> getActors () {
return root.getActors();
}
/** @return all top level {@link Group}s */
public List<Group> getGroups () {
return root.getGroups();
}
final Vector2 point = new Vector2();
final Vector2 coords = new Vector2();
/** Call this to distribute a touch down event to the stage.
* @param x the x coordinate of the touch in screen coordinates
* @param y the y coordinate of the touch in screen coordinates
* @param pointer the pointer index
* @param button the button that's been pressed
* @return whether an {@link Actor} in the scene processed the event or not */
@Override
public boolean touchDown (int x, int y, int pointer, int button) {
toStageCoordinates(x, y, coords);
Group.toChildCoordinates(root, coords.x, coords.y, point);
return root.touchDown(point.x, point.y, pointer);
}
/** Call this to distribute a touch Up event to the stage.
*
* @param x the x coordinate of the touch in screen coordinates
* @param y the y coordinate of the touch in screen coordinates
* @param pointer the pointer index
* @return whether an {@link Actor} in the scene processed the event or not */
@Override
public boolean touchUp (int x, int y, int pointer, int button) {
boolean foundFocusedActor = false;
for (int i = 0, n = root.focusedActor.length; i < n; i++) {
if (root.focusedActor[i] != null) {
foundFocusedActor = true;
break;
}
}
if (!foundFocusedActor) return false;
toStageCoordinates(x, y, coords);
Group.toChildCoordinates(root, coords.x, coords.y, point);
root.touchUp(point.x, point.y, pointer);
return true;
}
/** Call this to distribute a touch dragged event to the stage.
* @param x the x coordinate of the touch in screen coordinates
* @param y the y coordinate of the touch in screen coordinates
* @param pointer the pointer index
* @return whether an {@link Actor} in the scene processed the event or not */
@Override
public boolean touchDragged (int x, int y, int pointer) {
boolean foundFocusedActor = false;
for (int i = 0, n = root.focusedActor.length; i < n; i++) {
if (root.focusedActor[i] != null) {
foundFocusedActor = true;
break;
}
}
if (!foundFocusedActor) return false;
toStageCoordinates(x, y, coords);
Group.toChildCoordinates(root, coords.x, coords.y, point);
root.touchDragged(point.x, point.y, pointer);
return true;
}
/** Call this to distribute a touch moved event to the stage. This event will only ever appear on the desktop.
* @param x the x coordinate of the touch in screen coordinates
* @param y the y coordinate of the touch in screen coordinates
* @return whether an {@link Actor} in the scene processed the event or not */
@Override
public boolean touchMoved (int x, int y) {
toStageCoordinates(x, y, coords);
Group.toChildCoordinates(root, coords.x, coords.y, point);
return root.touchMoved(point.x, point.y);
}
/** Call this to distribute a mouse scroll event to the stage. This event will only ever appear on the desktop.
* @param amount the scroll amount.
* @return whether an {@link Actor} in the scene processed the event or not. */
@Override
public boolean scrolled (int amount) {
return root.scrolled(amount);
}
/** Called when a key was pressed
*
* @param keycode one of the constants in {@link Keys}
* @return whether the input was processed */
@Override
public boolean keyDown (int keycode) {
return root.keyDown(keycode);
}
/** Called when a key was released
*
* @param keycode one of the constants in {@link Keys}
* @return whether the input was processed */
@Override
public boolean keyUp (int keycode) {
return root.keyUp(keycode);
}
/** Called when a key was typed
*
* @param character The character
* @return whether the input was processed */
@Override
public boolean keyTyped (char character) {
return root.keyTyped(character);
}
/** Calls the {@link Actor#act(float)} method of all contained Actors. This will advance any {@link Action}s active for an
* Actor.
* @param delta the delta time in seconds since the last invocation */
public void act (float delta) {
root.act(delta);
}
/** Renders the stage */
public void draw () {
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
root.draw(batch, 1);
batch.end();
}
/** Disposes the stage */
public void dispose () {
batch.dispose();
}
/** Adds an {@link Actor} to this stage
* @param actor the Actor */
public void addActor (Actor actor) {
root.addActor(actor);
}
/** @return the Stage graph as a silly string */
public String graphToString () {
StringBuilder buffer = new StringBuilder();
graphToString(buffer, root, 0);
return buffer.toString();
}
private void graphToString (StringBuilder buffer, Actor actor, int level) {
for (int i = 0; i < level; i++)
buffer.append(' ');
buffer.append(actor);
buffer.append("\n");
if (actor instanceof Group) {
Group group = (Group)actor;
for (int i = 0; i < group.getActors().size(); i++)
graphToString(buffer, group.getActors().get(i), level + 1);
}
}
/** @return the root {@link Group} of this Stage. */
public Group getRoot () {
return root;
}
/** @return the {@link SpriteBatch} offers its {@link Actor}s for rendering. */
public SpriteBatch getSpriteBatch () {
return batch;
}
/** @return the {@link Camera} of this stage. */
public Camera getCamera () {
return camera;
}
/** Sets the {@link Camera} this stage uses. You are responsible for setting it up properly! The {@link Stage#draw()} will call
* the Camera's update() method and use it's combined matrix as the projection matrix for the SpriteBatch.
* @param camera the {@link Camera} */
public void setCamera (Camera camera) {
this.camera = camera;
}
/** @return the {@link Actor} last hit by a touch event. */
public Actor getLastTouchedChild () {
return root.lastTouchedChild;
}
/** Returns the {@link Actor} intersecting with the point (x,y) in stage coordinates. Hit testing is performed in the order the
* Actors were inserted into the Stage, last inserted Actors being tested first. To get stage coordinates from screen
* coordinates use {@link #toStageCoordinates(int, int, Vector2)}.
*
* @param x the x-coordinate in stage coordinates
* @param y the y-coordinate in stage coordinates
* @return the hit Actor or null */
public Actor hit (float x, float y) {
Group.toChildCoordinates(root, x, y, point);
return root.hit(point.x, point.y);
}
final Vector3 tmp = new Vector3();
/** Transforms the given screen coordinates to stage coordinates
* @param x the x-coordinate in screen coordinates
* @param y the y-coordinate in screen coordinates
* @param out the output {@link Vector2}. */
public void toStageCoordinates (int x, int y, Vector2 out) {
camera.unproject(tmp.set(x, y, 0));
out.x = tmp.x;
out.y = tmp.y;
}
/** Clears this stage, removing all {@link Actor}s and {@link Group}s. */
public void clear () {
root.clear();
}
/** Removes the given {@link Actor} from the stage by trying to find it recursively in the scenegraph.
* @param actor the actor */
public void removeActor (Actor actor) {
root.removeActorRecursive(actor);
}
/** Unfocues all {@link Actor} instance currently focused. You should call this in case your app resumes to clear up any pressed
* states. Make sure the Actors forget their states as well! */
public void unfocusAll () {
root.unfocusAll();
}
}
| true | true | public void setViewport (float width, float height, boolean stretch) {
if (!stretch) {
if (width > height && width / (float)Gdx.graphics.getWidth() <= height / (float)Gdx.graphics.getHeight()) {
float toDeviceSpace = Gdx.graphics.getHeight() / height;
float toViewportSpace = height / Gdx.graphics.getHeight();
float deviceWidth = width * toDeviceSpace;
this.width = width + (Gdx.graphics.getWidth() - deviceWidth) * toViewportSpace;
this.height = height;
} else {
float toDeviceSpace = Gdx.graphics.getWidth() / width;
float toViewportSpace = width / Gdx.graphics.getWidth();
float deviceHeight = height * toDeviceSpace;
this.height = height + (Gdx.graphics.getHeight() - deviceHeight) * toViewportSpace;
this.width = width;
}
} else {
this.width = width;
this.height = height;
}
this.stretch = stretch;
centerX = width / 2;
centerY = height / 2;
camera.position.set(centerX, centerY, 0);
camera.viewportWidth = this.width;
camera.viewportHeight = this.height;
}
| public void setViewport (float width, float height, boolean stretch) {
if (!stretch) {
if (width > height && width / (float)Gdx.graphics.getWidth() <= height / (float)Gdx.graphics.getHeight()) {
float toDeviceSpace = Gdx.graphics.getHeight() / height;
float toViewportSpace = height / Gdx.graphics.getHeight();
float deviceWidth = width * toDeviceSpace;
this.width = width + (Gdx.graphics.getWidth() - deviceWidth) * toViewportSpace;
this.height = height;
} else {
float toDeviceSpace = Gdx.graphics.getWidth() / width;
float toViewportSpace = width / Gdx.graphics.getWidth();
float deviceHeight = height * toDeviceSpace;
this.height = height + (Gdx.graphics.getHeight() - deviceHeight) * toViewportSpace;
this.width = width;
}
} else {
this.width = width;
this.height = height;
}
this.stretch = stretch;
centerX = this.width / 2;
centerY = this.height / 2;
camera.position.set(centerX, centerY, 0);
camera.viewportWidth = this.width;
camera.viewportHeight = this.height;
}
|
diff --git a/components/bio-formats/src/loci/formats/in/LeicaHandler.java b/components/bio-formats/src/loci/formats/in/LeicaHandler.java
index 8a11b3fc4..ca27ce315 100644
--- a/components/bio-formats/src/loci/formats/in/LeicaHandler.java
+++ b/components/bio-formats/src/loci/formats/in/LeicaHandler.java
@@ -1,992 +1,998 @@
//
// LeicaHandler.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats.in;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Vector;
import loci.common.DateTools;
import loci.formats.CoreMetadata;
import loci.formats.FormatTools;
import loci.formats.MetadataTools;
import loci.formats.meta.MetadataStore;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
/**
* SAX handler for parsing XML in Leica LIF and Leica TCS files.
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/LeicaHandler.java">Trac</a>,
* <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/LeicaHandler.java">SVN</a></dd></dl>
*
* @author Melissa Linkert linkert at wisc.edu
*/
public class LeicaHandler extends DefaultHandler {
// -- Fields --
private Stack<String> nameStack = new Stack<String>();
private String elementName, collection;
private int count = 0, numChannels, extras = 1;
private Vector<String> lutNames;
private Vector<Double> xPos, yPos, zPos;
private double physicalSizeX, physicalSizeY;
private int numDatasets = -1;
private Hashtable globalMetadata;
private MetadataStore store;
private int nextChannel = 0;
private Double zoom, pinhole;
private Vector<Integer> detectorIndices;
private String filterWheelName;
private int nextFilter = 0;
private int nextROI = 0;
private ROI roi;
private boolean alternateCenter = false;
private boolean linkedInstruments = false;
private int detectorChannel = 0;
private Vector<CoreMetadata> core;
private boolean canParse = true;
private long firstStamp = 0;
private Hashtable<Integer, String> bytesPerAxis;
private Vector<MultiBand> multiBands = new Vector<MultiBand>();
private Vector<Detector> detectors = new Vector<Detector>();
private Vector<Laser> lasers = new Vector<Laser>();
// -- Constructor --
public LeicaHandler(MetadataStore store) {
super();
globalMetadata = new Hashtable();
lutNames = new Vector<String>();
this.store = store;
core = new Vector<CoreMetadata>();
detectorIndices = new Vector<Integer>();
xPos = new Vector<Double>();
yPos = new Vector<Double>();
zPos = new Vector<Double>();
bytesPerAxis = new Hashtable<Integer, String>();
}
// -- LeicaHandler API methods --
public Vector<CoreMetadata> getCoreMetadata() { return core; }
public Hashtable getGlobalMetadata() { return globalMetadata; }
public Vector<String> getLutNames() { return lutNames; }
// -- DefaultHandler API methods --
public void endElement(String uri, String localName, String qName) {
if (!nameStack.empty() && nameStack.peek().equals(qName)) nameStack.pop();
if (qName.equals("ImageDescription")) {
CoreMetadata coreMeta = core.get(numDatasets);
if (numChannels == 0) numChannels = 1;
coreMeta.sizeC = numChannels;
if (extras > 1) {
if (coreMeta.sizeZ == 1) coreMeta.sizeZ = extras;
else {
if (coreMeta.sizeT == 0) coreMeta.sizeT = extras;
else coreMeta.sizeT *= extras;
}
}
if (coreMeta.sizeX == 0 && coreMeta.sizeY == 0) {
numDatasets--;
}
else {
if (coreMeta.sizeX == 0) coreMeta.sizeX = 1;
if (coreMeta.sizeZ == 0) coreMeta.sizeZ = 1;
if (coreMeta.sizeT == 0) coreMeta.sizeT = 1;
coreMeta.orderCertain = true;
coreMeta.metadataComplete = true;
coreMeta.littleEndian = true;
coreMeta.interleaved = coreMeta.rgb;
coreMeta.imageCount = coreMeta.sizeZ * coreMeta.sizeT;
if (!coreMeta.rgb) coreMeta.imageCount *= coreMeta.sizeC;
coreMeta.indexed = !coreMeta.rgb;
coreMeta.falseColor = true;
Integer[] bytes = bytesPerAxis.keySet().toArray(new Integer[0]);
Arrays.sort(bytes);
coreMeta.dimensionOrder = "XY";
for (Integer nBytes : bytes) {
String axis = bytesPerAxis.get(nBytes);
if (coreMeta.dimensionOrder.indexOf(axis) == -1) {
coreMeta.dimensionOrder += axis;
}
}
String[] axes = new String[] {"Z", "C", "T"};
for (String axis : axes) {
if (coreMeta.dimensionOrder.indexOf(axis) == -1) {
coreMeta.dimensionOrder += axis;
}
}
core.setElementAt(coreMeta, numDatasets);
}
int nChannels = coreMeta.rgb ? 0 : numChannels;
for (int c=0; c<nChannels; c++) {
store.setLogicalChannelPinholeSize(pinhole, numDatasets, c);
}
for (int i=0; i<xPos.size(); i++) {
int nPlanes = coreMeta.imageCount / (coreMeta.rgb ? 1 : coreMeta.sizeC);
for (int image=0; image<nPlanes; image++) {
int offset = image * nChannels + i;
store.setStagePositionPositionX(xPos.get(i), numDatasets, 0, offset);
store.setStagePositionPositionY(yPos.get(i), numDatasets, 0, offset);
store.setStagePositionPositionZ(zPos.get(i), numDatasets, 0, offset);
}
}
for (int c=0; c<nChannels; c++) {
int index = c < detectorIndices.size() ?
detectorIndices.get(c).intValue() : detectorIndices.size() - 1;
if (index < 0 || index >= nChannels || index >= 0) break;
String id = MetadataTools.createLSID("Detector", numDatasets, index);
store.setDetectorSettingsDetector(id, numDatasets, c);
}
xPos.clear();
yPos.clear();
zPos.clear();
detectorIndices.clear();
}
else if (qName.equals("Element")) {
multiBands.clear();
nextROI = 0;
int nChannels = core.get(numDatasets).rgb ? 1 : numChannels;
for (int c=0; c<detectorIndices.size(); c++) {
int index = detectorIndices.get(c).intValue();
if (c >= nChannels || index >= nChannels || index >= 0) break;
String id = MetadataTools.createLSID("Detector", numDatasets, index);
store.setDetectorSettingsDetector(id, numDatasets, index);
}
for (int c=0; c<nChannels; c++) {
store.setLogicalChannelPinholeSize(pinhole, numDatasets, c);
}
}
else if (qName.equals("ScannerSetting")) {
nextChannel = 0;
}
else if (qName.equals("FilterSetting")) {
nextChannel = 0;
}
else if (qName.equals("LDM_Block_Sequential_Master")) {
canParse = true;
}
else if (qName.equals("Annotation")) {
roi.storeROI(store, numDatasets, nextROI++);
}
}
public void startElement(String uri, String localName, String qName,
Attributes attributes)
{
if (attributes.getLength() > 0 && !qName.equals("Element") &&
!qName.equals("Attachment") && !qName.equals("LMSDataContainerHeader"))
{
nameStack.push(qName);
}
Hashtable h = getSeriesHashtable(numDatasets);
if (qName.equals("LDM_Block_Sequential_Master")) {
canParse = false;
}
else if (qName.startsWith("LDM")) {
linkedInstruments = true;
}
if (!canParse) return;
StringBuffer key = new StringBuffer();
for (String k : nameStack) {
key.append(k);
key.append("|");
}
String suffix = attributes.getValue("Identifier");
String value = attributes.getValue("Variant");
if (suffix == null) suffix = attributes.getValue("Description");
if (suffix != null && value != null) {
int index = 1;
while (h.get(key.toString() + suffix + " " + index) != null) index++;
h.put(key.toString() + suffix + " " + index, value);
}
else {
for (int i=0; i<attributes.getLength(); i++) {
int index = 1;
while (
h.get(key.toString() + attributes.getQName(i) + " " + index) != null)
{
index++;
}
h.put(key.toString() + attributes.getQName(i) + " " + index,
attributes.getValue(i));
}
}
if (qName.equals("Element")) {
elementName = attributes.getValue("Name");
}
else if (qName.equals("Collection")) {
collection = elementName;
}
else if (qName.equals("Image")) {
if (!linkedInstruments) {
int c = 0;
for (Detector d : detectors) {
String id = MetadataTools.createLSID(
"Detector", numDatasets, detectorChannel);
store.setDetectorID(id, numDatasets, detectorChannel);
store.setDetectorType(d.type, numDatasets, detectorChannel);
store.setDetectorModel(d.model, numDatasets, detectorChannel);
store.setDetectorZoom(d.zoom, numDatasets, detectorChannel);
store.setDetectorOffset(d.offset, numDatasets, detectorChannel);
store.setDetectorVoltage(d.voltage, numDatasets, detectorChannel);
if (c < numChannels) {
if (d.active) {
store.setDetectorSettingsOffset(d.offset, numDatasets, c);
store.setDetectorSettingsDetector(id, numDatasets, c);
c++;
}
}
detectorChannel++;
}
int filter = 0;
for (int i=0; i<nextFilter; i++) {
while (filter < detectors.size() && !detectors.get(filter).active) {
filter++;
}
if (filter >= detectors.size() || filter >= nextFilter) break;
String id = MetadataTools.createLSID("Filter", numDatasets, filter);
if (i < numChannels && detectors.get(filter).active) {
store.setLogicalChannelSecondaryEmissionFilter(
id, numDatasets, i);
}
filter++;
}
}
core.add(new CoreMetadata());
numDatasets++;
linkedInstruments = false;
detectorChannel = 0;
detectors.clear();
lasers.clear();
nextFilter = 0;
String name = elementName;
if (collection != null) name = collection + "/" + name;
store.setImageName(name, numDatasets);
String instrumentID = MetadataTools.createLSID("Instrument", numDatasets);
store.setInstrumentID(instrumentID, numDatasets);
store.setImageInstrumentRef(instrumentID, numDatasets);
numChannels = 0;
extras = 1;
}
else if (qName.equals("Attachment")) {
if ("ContextDescription".equals(attributes.getValue("Name"))) {
store.setImageDescription(attributes.getValue("Content"), numDatasets);
}
}
else if (qName.equals("ChannelDescription")) {
count++;
numChannels++;
lutNames.add(attributes.getValue("LUTName"));
String bytesInc = attributes.getValue("BytesInc");
int bytes = bytesInc == null ? 0 : Integer.parseInt(bytesInc);
if (bytes > 0) {
bytesPerAxis.put(new Integer(bytes), "C");
}
}
else if (qName.equals("DimensionDescription")) {
int len = Integer.parseInt(attributes.getValue("NumberOfElements"));
int id = Integer.parseInt(attributes.getValue("DimID"));
double physicalLen = Double.parseDouble(attributes.getValue("Length"));
String unit = attributes.getValue("Unit");
int nBytes = Integer.parseInt(attributes.getValue("BytesInc"));
physicalLen /= len;
if (unit.equals("Ks")) {
physicalLen /= 1000;
}
else if (unit.equals("m")) {
physicalLen *= 1000000;
}
Double physicalSize = new Double(physicalLen);
CoreMetadata coreMeta = core.get(core.size() - 1);
switch (id) {
case 1: // X axis
coreMeta.sizeX = len;
coreMeta.rgb = (nBytes % 3) == 0;
if (coreMeta.rgb) nBytes /= 3;
switch (nBytes) {
case 1:
coreMeta.pixelType = FormatTools.UINT8;
break;
case 2:
coreMeta.pixelType = FormatTools.UINT16;
break;
case 4:
coreMeta.pixelType = FormatTools.FLOAT;
break;
}
physicalSizeX = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeX(physicalSize, numDatasets, 0);
break;
case 2: // Y axis
if (coreMeta.sizeY != 0) {
if (coreMeta.sizeZ == 1) {
coreMeta.sizeZ = len;
bytesPerAxis.put(new Integer(nBytes), "Z");
}
else if (coreMeta.sizeT == 1) {
coreMeta.sizeT = len;
bytesPerAxis.put(new Integer(nBytes), "T");
}
}
else {
coreMeta.sizeY = len;
physicalSizeY = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeY(physicalSize, numDatasets, 0);
}
break;
case 3: // Z axis
if (coreMeta.sizeY == 0) {
// XZ scan - swap Y and Z
coreMeta.sizeY = len;
coreMeta.sizeZ = 1;
physicalSizeY = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeY(physicalSize, numDatasets, 0);
bytesPerAxis.put(new Integer(nBytes), "Y");
}
else {
coreMeta.sizeZ = len;
bytesPerAxis.put(new Integer(nBytes), "Z");
}
break;
case 4: // T axis
if (coreMeta.sizeY == 0) {
// XT scan - swap Y and T
coreMeta.sizeY = len;
coreMeta.sizeT = 1;
physicalSizeY = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeY(physicalSize, numDatasets, 0);
bytesPerAxis.put(new Integer(nBytes), "Y");
}
else {
coreMeta.sizeT = len;
bytesPerAxis.put(new Integer(nBytes), "T");
}
break;
default:
extras *= len;
}
count++;
}
else if (qName.equals("ScannerSettingRecord")) {
String id = attributes.getValue("Identifier");
if (id == null) id = "";
if (id.equals("SystemType")) {
store.setMicroscopeModel(value, numDatasets);
store.setMicroscopeType("Unknown", numDatasets);
}
else if (id.equals("dblPinhole")) {
pinhole = new Double(Double.parseDouble(value) * 1000000);
}
else if (id.equals("dblZoom")) {
zoom = new Double(value);
}
else if (id.equals("dblStepSize")) {
double zStep = Double.parseDouble(value) * 1000000;
store.setDimensionsPhysicalSizeZ(new Double(zStep), numDatasets, 0);
}
else if (id.equals("nDelayTime_s")) {
store.setDimensionsTimeIncrement(new Double(value), numDatasets, 0);
}
else if (id.equals("CameraName")) {
store.setDetectorModel(value, numDatasets, 0);
}
else if (id.indexOf("WFC") == 1) {
int c = 0;
try {
c = Integer.parseInt(id.replaceAll("\\D", ""));
}
catch (NumberFormatException e) { }
if (id.endsWith("ExposureTime")) {
store.setPlaneTimingExposureTime(new Double(value),
numDatasets, 0, c);
}
else if (id.endsWith("Gain")) {
store.setDetectorSettingsGain(new Double(value), numDatasets, c);
String detectorID =
MetadataTools.createLSID("Detector", numDatasets, 0);
store.setDetectorSettingsDetector(detectorID, numDatasets, c);
store.setDetectorID(detectorID, numDatasets, 0);
store.setDetectorType("CCD", numDatasets, 0);
}
else if (id.endsWith("WaveLength")) {
store.setLogicalChannelExWave(new Integer(value), numDatasets, c);
}
// NB: "UesrDefName" is not a typo.
else if (id.endsWith("UesrDefName") && !value.equals("None")) {
store.setLogicalChannelName(value, numDatasets, c);
}
}
}
else if (qName.equals("FilterSettingRecord")) {
String object = attributes.getValue("ObjectName");
String attribute = attributes.getValue("Attribute");
String objectClass = attributes.getValue("ClassName");
String variant = attributes.getValue("Variant");
CoreMetadata coreMeta = core.get(numDatasets);
if (attribute.equals("NumericalAperture")) {
store.setObjectiveLensNA(new Double(variant), numDatasets, 0);
store.setObjectiveCorrection("Unknown", numDatasets, 0);
store.setObjectiveImmersion("Unknown", numDatasets, 0);
}
else if (attribute.equals("OrderNumber")) {
store.setObjectiveSerialNumber(variant, numDatasets, 0);
store.setObjectiveCorrection("Unknown", numDatasets, 0);
store.setObjectiveImmersion("Unknown", numDatasets, 0);
}
else if (objectClass.equals("CDetectionUnit")) {
if (attribute.equals("State")) {
Detector d = new Detector();
String data = attributes.getValue("data");
d.channel = data == null ? 0 : Integer.parseInt(data);
d.type = "PMT";
d.model = object;
d.active = variant.equals("Active");
d.zoom = zoom;
detectors.add(d);
}
else if (attribute.equals("HighVoltage")) {
Detector d = detectors.get(detectors.size() - 1);
d.voltage = new Double(variant);
}
else if (attribute.equals("VideoOffset")) {
Detector d = detectors.get(detectors.size() - 1);
d.offset = new Double(variant);
}
}
else if (attribute.equals("Objective")) {
StringTokenizer tokens = new StringTokenizer(variant, " ");
boolean foundMag = false;
StringBuffer model = new StringBuffer();
while (!foundMag) {
String token = tokens.nextToken();
int x = token.indexOf("x");
if (x != -1) {
foundMag = true;
int mag = (int) Double.parseDouble(token.substring(0, x));
String na = token.substring(x + 1);
store.setObjectiveNominalMagnification(
new Integer(mag), numDatasets, 0);
store.setObjectiveLensNA(new Double(na), numDatasets, 0);
}
else {
model.append(token);
model.append(" ");
}
}
String immersion = "Unknown";
if (tokens.hasMoreTokens()) {
immersion = tokens.nextToken();
if (immersion == null || immersion.trim().equals("")) {
immersion = "Unknown";
}
}
store.setObjectiveImmersion(immersion, numDatasets, 0);
String correction = "Unknown";
if (tokens.hasMoreTokens()) {
correction = tokens.nextToken();
if (correction == null || correction.trim().equals("")) {
correction = "Unknown";
}
}
store.setObjectiveCorrection("Unknown", numDatasets, 0);
store.setObjectiveModel(model.toString().trim(), numDatasets, 0);
}
else if (attribute.equals("RefractionIndex")) {
String id = MetadataTools.createLSID("Objective", numDatasets, 0);
store.setObjectiveID(id, numDatasets, 0);
store.setObjectiveSettingsObjective(id, numDatasets);
store.setObjectiveSettingsRefractiveIndex(new Double(variant),
numDatasets);
}
else if (attribute.equals("XPos")) {
int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
int nPlanes = coreMeta.imageCount / c;
Double posX = new Double(variant);
for (int image=0; image<nPlanes; image++) {
int index = image * (coreMeta.rgb ? 1 : coreMeta.sizeC);
if (index >= nPlanes) continue;
store.setStagePositionPositionX(posX, numDatasets, 0, index);
}
if (numChannels == 0) xPos.add(posX);
}
else if (attribute.equals("YPos")) {
int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
int nPlanes = coreMeta.imageCount / c;
Double posY = new Double(variant);
for (int image=0; image<nPlanes; image++) {
int index = image * (coreMeta.rgb ? 1 : coreMeta.sizeC);
if (index >= nPlanes) continue;
store.setStagePositionPositionY(posY, numDatasets, 0, index);
}
if (numChannels == 0) yPos.add(posY);
}
else if (attribute.equals("ZPos")) {
int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
int nPlanes = coreMeta.imageCount / c;
Double posZ = new Double(variant);
for (int image=0; image<nPlanes; image++) {
int index = image * (coreMeta.rgb ? 1 : coreMeta.sizeC);
if (index >= nPlanes) continue;
store.setStagePositionPositionZ(posZ, numDatasets, 0, index);
}
if (numChannels == 0) zPos.add(posZ);
}
else if (objectClass.equals("CSpectrophotometerUnit")) {
Integer v = null;
try {
v = new Integer((int) Double.parseDouble(variant));
}
catch (NumberFormatException e) { }
if (attributes.getValue("Description").endsWith("(left)")) {
String id =
MetadataTools.createLSID("Filter", numDatasets, nextFilter);
store.setFilterID(id, numDatasets, nextFilter);
store.setFilterModel(object, numDatasets, nextFilter);
if (v != null) {
store.setTransmittanceRangeCutIn(v, numDatasets, nextFilter);
}
}
else if (attributes.getValue("Description").endsWith("(right)")) {
if (v != null) {
store.setTransmittanceRangeCutOut(v, numDatasets, nextFilter);
nextFilter++;
}
}
}
}
else if (qName.equals("Detector")) {
String v = attributes.getValue("Gain");
Double gain = v == null ? null : new Double(v);
v = attributes.getValue("Offset");
Double offset = v == null ? null : new Double(v);
boolean active = "1".equals(attributes.getValue("IsActive"));
if (active) {
// find the corresponding MultiBand and Detector
MultiBand m = null;
Detector detector = null;
Laser laser = lasers.size() == 0 ? null : lasers.get(lasers.size() - 1);
String c = attributes.getValue("Channel");
int channel = c == null ? 0 : Integer.parseInt(c);
for (MultiBand mb : multiBands) {
if (mb.channel == channel) {
m = mb;
break;
}
}
for (Detector d : detectors) {
if (d.channel == channel) {
detector = d;
break;
}
}
String id =
MetadataTools.createLSID("Detector", numDatasets, nextChannel);
if (m != null) {
store.setLogicalChannelName(m.dyeName, numDatasets, nextChannel);
String filter =
MetadataTools.createLSID("Filter", numDatasets, nextFilter);
store.setFilterID(filter, numDatasets, nextFilter);
store.setTransmittanceRangeCutIn(new Integer(m.cutIn), numDatasets,
nextFilter);
store.setTransmittanceRangeCutOut(new Integer(m.cutOut), numDatasets,
nextFilter);
store.setLogicalChannelSecondaryEmissionFilter(filter, numDatasets,
nextChannel);
nextFilter++;
store.setDetectorID(id, numDatasets, nextChannel);
store.setDetectorType("PMT", numDatasets, nextChannel);
store.setDetectorSettingsGain(gain, numDatasets, nextChannel);
store.setDetectorSettingsOffset(offset, numDatasets, nextChannel);
store.setDetectorSettingsDetector(id, numDatasets, nextChannel);
}
if (detector != null) {
store.setDetectorID(id, numDatasets, nextChannel);
store.setDetectorSettingsGain(gain, numDatasets, nextChannel);
store.setDetectorSettingsOffset(offset, numDatasets, nextChannel);
store.setDetectorSettingsDetector(id, numDatasets, nextChannel);
store.setDetectorType(detector.type, numDatasets, nextChannel);
store.setDetectorModel(detector.model, numDatasets, nextChannel);
store.setDetectorZoom(detector.zoom, numDatasets, nextChannel);
store.setDetectorOffset(detector.offset, numDatasets, nextChannel);
store.setDetectorVoltage(detector.voltage, numDatasets,
nextChannel);
}
if (laser != null && laser.intensity > 0) {
store.setLightSourceSettingsLightSource(laser.id, numDatasets,
nextChannel);
store.setLightSourceSettingsAttenuation(
new Double(laser.intensity / 100.0), numDatasets, nextChannel);
store.setLogicalChannelExWave(laser.wavelength, numDatasets,
nextChannel);
}
nextChannel++;
}
}
else if (qName.equals("LaserLineSetting")) {
Laser l = new Laser();
String lineIndex = attributes.getValue("LineIndex");
String qual = attributes.getValue("Qualifier");
l.index = lineIndex == null ? 0 : Integer.parseInt(lineIndex);
int qualifier = qual == null ? 0 : Integer.parseInt(qual);
l.index += (2 - (qualifier / 10));
if (l.index < 0) l.index = 0;
l.id = MetadataTools.createLSID("LightSource", numDatasets, l.index);
l.wavelength = new Integer(attributes.getValue("LaserLine"));
store.setLightSourceID(l.id, numDatasets, l.index);
store.setLaserWavelength(l.wavelength, numDatasets, l.index);
store.setLaserType("Unknown", numDatasets, l.index);
store.setLaserLaserMedium("Unknown", numDatasets, l.index);
String intensity = attributes.getValue("IntensityDev");
l.intensity = intensity == null ? 0d : Double.parseDouble(intensity);
if (l.intensity > 0) lasers.add(l);
}
else if (qName.equals("TimeStamp") && numDatasets >= 0) {
String stampHigh = attributes.getValue("HighInteger");
String stampLow = attributes.getValue("LowInteger");
long high = stampHigh == null ? 0 : Long.parseLong(stampHigh);
long low = stampLow == null ? 0 : Long.parseLong(stampLow);
long ms = DateTools.getMillisFromTicks(high, low);
if (count == 0) {
String date = DateTools.convertDate(ms, DateTools.COBOL);
if (DateTools.getTime(date, DateTools.ISO8601_FORMAT) <
System.currentTimeMillis())
{
store.setImageCreationDate(date, numDatasets);
}
firstStamp = ms;
store.setPlaneTimingDeltaT(new Double(0), numDatasets, 0, count);
}
else {
CoreMetadata coreMeta = core.get(numDatasets);
int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC;
if (count < nImages) {
ms -= firstStamp;
store.setPlaneTimingDeltaT(
new Double(ms / 1000.0), numDatasets, 0, count);
}
}
count++;
}
else if (qName.equals("RelTimeStamp")) {
CoreMetadata coreMeta = core.get(numDatasets);
int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC;
if (count < nImages) {
Double time = new Double(attributes.getValue("Time"));
store.setPlaneTimingDeltaT(time, numDatasets, 0, count++);
}
}
else if (qName.equals("Annotation")) {
roi = new ROI();
String type = attributes.getValue("type");
if (type != null) roi.type = Integer.parseInt(type);
String color = attributes.getValue("color");
if (color != null) roi.color = Integer.parseInt(color);
roi.name = attributes.getValue("name");
roi.fontName = attributes.getValue("fontName");
roi.fontSize = attributes.getValue("fontSize");
roi.transX = parseDouble(attributes.getValue("transTransX"));
roi.transY = parseDouble(attributes.getValue("transTransY"));
roi.scaleX = parseDouble(attributes.getValue("transScalingX"));
roi.scaleY = parseDouble(attributes.getValue("transScalingY"));
roi.rotation = parseDouble(attributes.getValue("transRotation"));
String linewidth = attributes.getValue("linewidth");
if (linewidth != null) roi.linewidth = Integer.parseInt(linewidth);
roi.text = attributes.getValue("text");
}
else if (qName.equals("Vertex")) {
- String x = attributes.getValue("x").replaceAll(",", ".");
- String y = attributes.getValue("y").replaceAll(",", ".");
- roi.x.add(new Double(x));
- roi.y.add(new Double(y));
+ String x = attributes.getValue("x");
+ String y = attributes.getValue("y");
+ if (x != null) {
+ x = x.replaceAll(",", ".");
+ roi.x.add(new Double(x));
+ }
+ if (y != null) {
+ y = y.replaceAll(",", ".");
+ roi.y.add(new Double(y));
+ }
}
else if (qName.equals("ROI")) {
alternateCenter = true;
}
else if (qName.equals("MultiBand")) {
MultiBand m = new MultiBand();
m.dyeName = attributes.getValue("DyeName");
m.channel = Integer.parseInt(attributes.getValue("Channel"));
m.cutIn = (int)
Math.round(Double.parseDouble(attributes.getValue("LeftWorld")));
m.cutOut = (int)
Math.round(Double.parseDouble(attributes.getValue("RightWorld")));
multiBands.add(m);
}
else count = 0;
storeSeriesHashtable(numDatasets, h);
}
// -- Helper methods --
private Hashtable getSeriesHashtable(int series) {
if (series < 0 || series >= core.size()) return new Hashtable();
return core.get(series).seriesMetadata;
}
private void storeSeriesHashtable(int series, Hashtable h) {
if (series < 0) return;
CoreMetadata coreMeta = core.get(series);
coreMeta.seriesMetadata = h;
core.setElementAt(coreMeta, series);
}
// -- Helper class --
class ROI {
// -- Constants --
public static final int TEXT = 512;
public static final int SCALE_BAR = 8192;
public static final int POLYGON = 32;
public static final int RECTANGLE = 16;
public static final int LINE = 256;
public static final int ARROW = 2;
// -- Fields --
public int type;
public Vector<Double> x = new Vector<Double>();
public Vector<Double> y = new Vector<Double>();
// center point of the ROI
public double transX, transY;
// transformation parameters
public double scaleX, scaleY;
public double rotation;
public int color;
public int linewidth;
public String text;
public String fontName;
public String fontSize;
public String name;
private boolean normalized = false;
// -- ROI API methods --
public void storeROI(MetadataStore store, int series, int roi) {
// keep in mind that vertices are given relative to the center
// point of the ROI and the transX/transY values are relative to
// the center point of the image
if (text != null) store.setShapeText(text, series, roi, 0);
if (fontName != null) store.setShapeFontFamily(fontName, series, roi, 0);
if (fontSize != null) {
store.setShapeFontSize(
new Integer((int) Double.parseDouble(fontSize)), series, roi, 0);
}
store.setShapeStrokeColor(String.valueOf(color), series, roi, 0);
store.setShapeStrokeWidth(new Integer(linewidth), series, roi, 0);
if (!normalized) normalize();
double cornerX = x.get(0).doubleValue();
double cornerY = y.get(0).doubleValue();
int centerX = (core.get(series).sizeX / 2) - 1;
int centerY = (core.get(series).sizeY / 2) - 1;
double roiX = centerX + transX;
double roiY = centerY + transY;
if (alternateCenter) {
roiX = transX - 2 * cornerX;
roiY = transY - 2 * cornerY;
}
// TODO : rotation/scaling not populated
switch (type) {
case POLYGON:
StringBuffer points = new StringBuffer();
for (int i=0; i<x.size(); i++) {
points.append(x.get(i).doubleValue() + roiX);
points.append(",");
points.append(y.get(i).doubleValue() + roiY);
if (i < x.size() - 1) points.append(" ");
}
store.setPolygonPoints(points.toString(), series, roi, 0);
break;
case TEXT:
case RECTANGLE:
store.setRectX(
String.valueOf(roiX - Math.abs(cornerX)), series, roi, 0);
store.setRectY(
String.valueOf(roiY - Math.abs(cornerY)), series, roi, 0);
double width = 2 * Math.abs(cornerX);
double height = 2 * Math.abs(cornerY);
store.setRectWidth(String.valueOf(width), series, roi, 0);
store.setRectHeight(String.valueOf(height), series, roi, 0);
break;
case SCALE_BAR:
case ARROW:
case LINE:
store.setLineX1(String.valueOf(roiX + x.get(0)), series, roi, 0);
store.setLineY1(String.valueOf(roiY + y.get(0)), series, roi, 0);
store.setLineX2(String.valueOf(roiX + x.get(1)), series, roi, 0);
store.setLineY2(String.valueOf(roiY + y.get(1)), series, roi, 0);
break;
}
}
// -- Helper methods --
/**
* Vertices and transformation values are not stored in pixel coordinates.
* We need to convert them from physical coordinates to pixel coordinates
* so that they can be stored in a MetadataStore.
*/
private void normalize() {
if (normalized) return;
// coordinates are in meters
transX *= 1000000;
transY *= 1000000;
transX *= (1 / physicalSizeX);
transY *= (1 / physicalSizeY);
for (int i=0; i<x.size(); i++) {
double coordinate = x.get(i).doubleValue() * 1000000;
coordinate *= (1 / physicalSizeX);
x.setElementAt(new Double(coordinate), i);
}
for (int i=0; i<y.size(); i++) {
double coordinate = y.get(i).doubleValue() * 1000000;
coordinate *= (1 / physicalSizeY);
y.setElementAt(new Double(coordinate), i);
}
normalized = true;
}
}
private double parseDouble(String number) {
if (number != null) {
number = number.replaceAll(",", ".");
return Double.parseDouble(number);
}
return 0;
}
// -- Helper classes --
class MultiBand {
public int channel;
public int cutIn;
public int cutOut;
public String dyeName;
}
class Detector {
public int channel;
public Double zoom;
public String type;
public String model;
public boolean active;
public Double voltage;
public Double offset;
}
class Laser {
public Integer wavelength;
public double intensity;
public String id;
public int index;
}
}
| true | true | public void startElement(String uri, String localName, String qName,
Attributes attributes)
{
if (attributes.getLength() > 0 && !qName.equals("Element") &&
!qName.equals("Attachment") && !qName.equals("LMSDataContainerHeader"))
{
nameStack.push(qName);
}
Hashtable h = getSeriesHashtable(numDatasets);
if (qName.equals("LDM_Block_Sequential_Master")) {
canParse = false;
}
else if (qName.startsWith("LDM")) {
linkedInstruments = true;
}
if (!canParse) return;
StringBuffer key = new StringBuffer();
for (String k : nameStack) {
key.append(k);
key.append("|");
}
String suffix = attributes.getValue("Identifier");
String value = attributes.getValue("Variant");
if (suffix == null) suffix = attributes.getValue("Description");
if (suffix != null && value != null) {
int index = 1;
while (h.get(key.toString() + suffix + " " + index) != null) index++;
h.put(key.toString() + suffix + " " + index, value);
}
else {
for (int i=0; i<attributes.getLength(); i++) {
int index = 1;
while (
h.get(key.toString() + attributes.getQName(i) + " " + index) != null)
{
index++;
}
h.put(key.toString() + attributes.getQName(i) + " " + index,
attributes.getValue(i));
}
}
if (qName.equals("Element")) {
elementName = attributes.getValue("Name");
}
else if (qName.equals("Collection")) {
collection = elementName;
}
else if (qName.equals("Image")) {
if (!linkedInstruments) {
int c = 0;
for (Detector d : detectors) {
String id = MetadataTools.createLSID(
"Detector", numDatasets, detectorChannel);
store.setDetectorID(id, numDatasets, detectorChannel);
store.setDetectorType(d.type, numDatasets, detectorChannel);
store.setDetectorModel(d.model, numDatasets, detectorChannel);
store.setDetectorZoom(d.zoom, numDatasets, detectorChannel);
store.setDetectorOffset(d.offset, numDatasets, detectorChannel);
store.setDetectorVoltage(d.voltage, numDatasets, detectorChannel);
if (c < numChannels) {
if (d.active) {
store.setDetectorSettingsOffset(d.offset, numDatasets, c);
store.setDetectorSettingsDetector(id, numDatasets, c);
c++;
}
}
detectorChannel++;
}
int filter = 0;
for (int i=0; i<nextFilter; i++) {
while (filter < detectors.size() && !detectors.get(filter).active) {
filter++;
}
if (filter >= detectors.size() || filter >= nextFilter) break;
String id = MetadataTools.createLSID("Filter", numDatasets, filter);
if (i < numChannels && detectors.get(filter).active) {
store.setLogicalChannelSecondaryEmissionFilter(
id, numDatasets, i);
}
filter++;
}
}
core.add(new CoreMetadata());
numDatasets++;
linkedInstruments = false;
detectorChannel = 0;
detectors.clear();
lasers.clear();
nextFilter = 0;
String name = elementName;
if (collection != null) name = collection + "/" + name;
store.setImageName(name, numDatasets);
String instrumentID = MetadataTools.createLSID("Instrument", numDatasets);
store.setInstrumentID(instrumentID, numDatasets);
store.setImageInstrumentRef(instrumentID, numDatasets);
numChannels = 0;
extras = 1;
}
else if (qName.equals("Attachment")) {
if ("ContextDescription".equals(attributes.getValue("Name"))) {
store.setImageDescription(attributes.getValue("Content"), numDatasets);
}
}
else if (qName.equals("ChannelDescription")) {
count++;
numChannels++;
lutNames.add(attributes.getValue("LUTName"));
String bytesInc = attributes.getValue("BytesInc");
int bytes = bytesInc == null ? 0 : Integer.parseInt(bytesInc);
if (bytes > 0) {
bytesPerAxis.put(new Integer(bytes), "C");
}
}
else if (qName.equals("DimensionDescription")) {
int len = Integer.parseInt(attributes.getValue("NumberOfElements"));
int id = Integer.parseInt(attributes.getValue("DimID"));
double physicalLen = Double.parseDouble(attributes.getValue("Length"));
String unit = attributes.getValue("Unit");
int nBytes = Integer.parseInt(attributes.getValue("BytesInc"));
physicalLen /= len;
if (unit.equals("Ks")) {
physicalLen /= 1000;
}
else if (unit.equals("m")) {
physicalLen *= 1000000;
}
Double physicalSize = new Double(physicalLen);
CoreMetadata coreMeta = core.get(core.size() - 1);
switch (id) {
case 1: // X axis
coreMeta.sizeX = len;
coreMeta.rgb = (nBytes % 3) == 0;
if (coreMeta.rgb) nBytes /= 3;
switch (nBytes) {
case 1:
coreMeta.pixelType = FormatTools.UINT8;
break;
case 2:
coreMeta.pixelType = FormatTools.UINT16;
break;
case 4:
coreMeta.pixelType = FormatTools.FLOAT;
break;
}
physicalSizeX = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeX(physicalSize, numDatasets, 0);
break;
case 2: // Y axis
if (coreMeta.sizeY != 0) {
if (coreMeta.sizeZ == 1) {
coreMeta.sizeZ = len;
bytesPerAxis.put(new Integer(nBytes), "Z");
}
else if (coreMeta.sizeT == 1) {
coreMeta.sizeT = len;
bytesPerAxis.put(new Integer(nBytes), "T");
}
}
else {
coreMeta.sizeY = len;
physicalSizeY = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeY(physicalSize, numDatasets, 0);
}
break;
case 3: // Z axis
if (coreMeta.sizeY == 0) {
// XZ scan - swap Y and Z
coreMeta.sizeY = len;
coreMeta.sizeZ = 1;
physicalSizeY = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeY(physicalSize, numDatasets, 0);
bytesPerAxis.put(new Integer(nBytes), "Y");
}
else {
coreMeta.sizeZ = len;
bytesPerAxis.put(new Integer(nBytes), "Z");
}
break;
case 4: // T axis
if (coreMeta.sizeY == 0) {
// XT scan - swap Y and T
coreMeta.sizeY = len;
coreMeta.sizeT = 1;
physicalSizeY = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeY(physicalSize, numDatasets, 0);
bytesPerAxis.put(new Integer(nBytes), "Y");
}
else {
coreMeta.sizeT = len;
bytesPerAxis.put(new Integer(nBytes), "T");
}
break;
default:
extras *= len;
}
count++;
}
else if (qName.equals("ScannerSettingRecord")) {
String id = attributes.getValue("Identifier");
if (id == null) id = "";
if (id.equals("SystemType")) {
store.setMicroscopeModel(value, numDatasets);
store.setMicroscopeType("Unknown", numDatasets);
}
else if (id.equals("dblPinhole")) {
pinhole = new Double(Double.parseDouble(value) * 1000000);
}
else if (id.equals("dblZoom")) {
zoom = new Double(value);
}
else if (id.equals("dblStepSize")) {
double zStep = Double.parseDouble(value) * 1000000;
store.setDimensionsPhysicalSizeZ(new Double(zStep), numDatasets, 0);
}
else if (id.equals("nDelayTime_s")) {
store.setDimensionsTimeIncrement(new Double(value), numDatasets, 0);
}
else if (id.equals("CameraName")) {
store.setDetectorModel(value, numDatasets, 0);
}
else if (id.indexOf("WFC") == 1) {
int c = 0;
try {
c = Integer.parseInt(id.replaceAll("\\D", ""));
}
catch (NumberFormatException e) { }
if (id.endsWith("ExposureTime")) {
store.setPlaneTimingExposureTime(new Double(value),
numDatasets, 0, c);
}
else if (id.endsWith("Gain")) {
store.setDetectorSettingsGain(new Double(value), numDatasets, c);
String detectorID =
MetadataTools.createLSID("Detector", numDatasets, 0);
store.setDetectorSettingsDetector(detectorID, numDatasets, c);
store.setDetectorID(detectorID, numDatasets, 0);
store.setDetectorType("CCD", numDatasets, 0);
}
else if (id.endsWith("WaveLength")) {
store.setLogicalChannelExWave(new Integer(value), numDatasets, c);
}
// NB: "UesrDefName" is not a typo.
else if (id.endsWith("UesrDefName") && !value.equals("None")) {
store.setLogicalChannelName(value, numDatasets, c);
}
}
}
else if (qName.equals("FilterSettingRecord")) {
String object = attributes.getValue("ObjectName");
String attribute = attributes.getValue("Attribute");
String objectClass = attributes.getValue("ClassName");
String variant = attributes.getValue("Variant");
CoreMetadata coreMeta = core.get(numDatasets);
if (attribute.equals("NumericalAperture")) {
store.setObjectiveLensNA(new Double(variant), numDatasets, 0);
store.setObjectiveCorrection("Unknown", numDatasets, 0);
store.setObjectiveImmersion("Unknown", numDatasets, 0);
}
else if (attribute.equals("OrderNumber")) {
store.setObjectiveSerialNumber(variant, numDatasets, 0);
store.setObjectiveCorrection("Unknown", numDatasets, 0);
store.setObjectiveImmersion("Unknown", numDatasets, 0);
}
else if (objectClass.equals("CDetectionUnit")) {
if (attribute.equals("State")) {
Detector d = new Detector();
String data = attributes.getValue("data");
d.channel = data == null ? 0 : Integer.parseInt(data);
d.type = "PMT";
d.model = object;
d.active = variant.equals("Active");
d.zoom = zoom;
detectors.add(d);
}
else if (attribute.equals("HighVoltage")) {
Detector d = detectors.get(detectors.size() - 1);
d.voltage = new Double(variant);
}
else if (attribute.equals("VideoOffset")) {
Detector d = detectors.get(detectors.size() - 1);
d.offset = new Double(variant);
}
}
else if (attribute.equals("Objective")) {
StringTokenizer tokens = new StringTokenizer(variant, " ");
boolean foundMag = false;
StringBuffer model = new StringBuffer();
while (!foundMag) {
String token = tokens.nextToken();
int x = token.indexOf("x");
if (x != -1) {
foundMag = true;
int mag = (int) Double.parseDouble(token.substring(0, x));
String na = token.substring(x + 1);
store.setObjectiveNominalMagnification(
new Integer(mag), numDatasets, 0);
store.setObjectiveLensNA(new Double(na), numDatasets, 0);
}
else {
model.append(token);
model.append(" ");
}
}
String immersion = "Unknown";
if (tokens.hasMoreTokens()) {
immersion = tokens.nextToken();
if (immersion == null || immersion.trim().equals("")) {
immersion = "Unknown";
}
}
store.setObjectiveImmersion(immersion, numDatasets, 0);
String correction = "Unknown";
if (tokens.hasMoreTokens()) {
correction = tokens.nextToken();
if (correction == null || correction.trim().equals("")) {
correction = "Unknown";
}
}
store.setObjectiveCorrection("Unknown", numDatasets, 0);
store.setObjectiveModel(model.toString().trim(), numDatasets, 0);
}
else if (attribute.equals("RefractionIndex")) {
String id = MetadataTools.createLSID("Objective", numDatasets, 0);
store.setObjectiveID(id, numDatasets, 0);
store.setObjectiveSettingsObjective(id, numDatasets);
store.setObjectiveSettingsRefractiveIndex(new Double(variant),
numDatasets);
}
else if (attribute.equals("XPos")) {
int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
int nPlanes = coreMeta.imageCount / c;
Double posX = new Double(variant);
for (int image=0; image<nPlanes; image++) {
int index = image * (coreMeta.rgb ? 1 : coreMeta.sizeC);
if (index >= nPlanes) continue;
store.setStagePositionPositionX(posX, numDatasets, 0, index);
}
if (numChannels == 0) xPos.add(posX);
}
else if (attribute.equals("YPos")) {
int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
int nPlanes = coreMeta.imageCount / c;
Double posY = new Double(variant);
for (int image=0; image<nPlanes; image++) {
int index = image * (coreMeta.rgb ? 1 : coreMeta.sizeC);
if (index >= nPlanes) continue;
store.setStagePositionPositionY(posY, numDatasets, 0, index);
}
if (numChannels == 0) yPos.add(posY);
}
else if (attribute.equals("ZPos")) {
int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
int nPlanes = coreMeta.imageCount / c;
Double posZ = new Double(variant);
for (int image=0; image<nPlanes; image++) {
int index = image * (coreMeta.rgb ? 1 : coreMeta.sizeC);
if (index >= nPlanes) continue;
store.setStagePositionPositionZ(posZ, numDatasets, 0, index);
}
if (numChannels == 0) zPos.add(posZ);
}
else if (objectClass.equals("CSpectrophotometerUnit")) {
Integer v = null;
try {
v = new Integer((int) Double.parseDouble(variant));
}
catch (NumberFormatException e) { }
if (attributes.getValue("Description").endsWith("(left)")) {
String id =
MetadataTools.createLSID("Filter", numDatasets, nextFilter);
store.setFilterID(id, numDatasets, nextFilter);
store.setFilterModel(object, numDatasets, nextFilter);
if (v != null) {
store.setTransmittanceRangeCutIn(v, numDatasets, nextFilter);
}
}
else if (attributes.getValue("Description").endsWith("(right)")) {
if (v != null) {
store.setTransmittanceRangeCutOut(v, numDatasets, nextFilter);
nextFilter++;
}
}
}
}
else if (qName.equals("Detector")) {
String v = attributes.getValue("Gain");
Double gain = v == null ? null : new Double(v);
v = attributes.getValue("Offset");
Double offset = v == null ? null : new Double(v);
boolean active = "1".equals(attributes.getValue("IsActive"));
if (active) {
// find the corresponding MultiBand and Detector
MultiBand m = null;
Detector detector = null;
Laser laser = lasers.size() == 0 ? null : lasers.get(lasers.size() - 1);
String c = attributes.getValue("Channel");
int channel = c == null ? 0 : Integer.parseInt(c);
for (MultiBand mb : multiBands) {
if (mb.channel == channel) {
m = mb;
break;
}
}
for (Detector d : detectors) {
if (d.channel == channel) {
detector = d;
break;
}
}
String id =
MetadataTools.createLSID("Detector", numDatasets, nextChannel);
if (m != null) {
store.setLogicalChannelName(m.dyeName, numDatasets, nextChannel);
String filter =
MetadataTools.createLSID("Filter", numDatasets, nextFilter);
store.setFilterID(filter, numDatasets, nextFilter);
store.setTransmittanceRangeCutIn(new Integer(m.cutIn), numDatasets,
nextFilter);
store.setTransmittanceRangeCutOut(new Integer(m.cutOut), numDatasets,
nextFilter);
store.setLogicalChannelSecondaryEmissionFilter(filter, numDatasets,
nextChannel);
nextFilter++;
store.setDetectorID(id, numDatasets, nextChannel);
store.setDetectorType("PMT", numDatasets, nextChannel);
store.setDetectorSettingsGain(gain, numDatasets, nextChannel);
store.setDetectorSettingsOffset(offset, numDatasets, nextChannel);
store.setDetectorSettingsDetector(id, numDatasets, nextChannel);
}
if (detector != null) {
store.setDetectorID(id, numDatasets, nextChannel);
store.setDetectorSettingsGain(gain, numDatasets, nextChannel);
store.setDetectorSettingsOffset(offset, numDatasets, nextChannel);
store.setDetectorSettingsDetector(id, numDatasets, nextChannel);
store.setDetectorType(detector.type, numDatasets, nextChannel);
store.setDetectorModel(detector.model, numDatasets, nextChannel);
store.setDetectorZoom(detector.zoom, numDatasets, nextChannel);
store.setDetectorOffset(detector.offset, numDatasets, nextChannel);
store.setDetectorVoltage(detector.voltage, numDatasets,
nextChannel);
}
if (laser != null && laser.intensity > 0) {
store.setLightSourceSettingsLightSource(laser.id, numDatasets,
nextChannel);
store.setLightSourceSettingsAttenuation(
new Double(laser.intensity / 100.0), numDatasets, nextChannel);
store.setLogicalChannelExWave(laser.wavelength, numDatasets,
nextChannel);
}
nextChannel++;
}
}
else if (qName.equals("LaserLineSetting")) {
Laser l = new Laser();
String lineIndex = attributes.getValue("LineIndex");
String qual = attributes.getValue("Qualifier");
l.index = lineIndex == null ? 0 : Integer.parseInt(lineIndex);
int qualifier = qual == null ? 0 : Integer.parseInt(qual);
l.index += (2 - (qualifier / 10));
if (l.index < 0) l.index = 0;
l.id = MetadataTools.createLSID("LightSource", numDatasets, l.index);
l.wavelength = new Integer(attributes.getValue("LaserLine"));
store.setLightSourceID(l.id, numDatasets, l.index);
store.setLaserWavelength(l.wavelength, numDatasets, l.index);
store.setLaserType("Unknown", numDatasets, l.index);
store.setLaserLaserMedium("Unknown", numDatasets, l.index);
String intensity = attributes.getValue("IntensityDev");
l.intensity = intensity == null ? 0d : Double.parseDouble(intensity);
if (l.intensity > 0) lasers.add(l);
}
else if (qName.equals("TimeStamp") && numDatasets >= 0) {
String stampHigh = attributes.getValue("HighInteger");
String stampLow = attributes.getValue("LowInteger");
long high = stampHigh == null ? 0 : Long.parseLong(stampHigh);
long low = stampLow == null ? 0 : Long.parseLong(stampLow);
long ms = DateTools.getMillisFromTicks(high, low);
if (count == 0) {
String date = DateTools.convertDate(ms, DateTools.COBOL);
if (DateTools.getTime(date, DateTools.ISO8601_FORMAT) <
System.currentTimeMillis())
{
store.setImageCreationDate(date, numDatasets);
}
firstStamp = ms;
store.setPlaneTimingDeltaT(new Double(0), numDatasets, 0, count);
}
else {
CoreMetadata coreMeta = core.get(numDatasets);
int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC;
if (count < nImages) {
ms -= firstStamp;
store.setPlaneTimingDeltaT(
new Double(ms / 1000.0), numDatasets, 0, count);
}
}
count++;
}
else if (qName.equals("RelTimeStamp")) {
CoreMetadata coreMeta = core.get(numDatasets);
int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC;
if (count < nImages) {
Double time = new Double(attributes.getValue("Time"));
store.setPlaneTimingDeltaT(time, numDatasets, 0, count++);
}
}
else if (qName.equals("Annotation")) {
roi = new ROI();
String type = attributes.getValue("type");
if (type != null) roi.type = Integer.parseInt(type);
String color = attributes.getValue("color");
if (color != null) roi.color = Integer.parseInt(color);
roi.name = attributes.getValue("name");
roi.fontName = attributes.getValue("fontName");
roi.fontSize = attributes.getValue("fontSize");
roi.transX = parseDouble(attributes.getValue("transTransX"));
roi.transY = parseDouble(attributes.getValue("transTransY"));
roi.scaleX = parseDouble(attributes.getValue("transScalingX"));
roi.scaleY = parseDouble(attributes.getValue("transScalingY"));
roi.rotation = parseDouble(attributes.getValue("transRotation"));
String linewidth = attributes.getValue("linewidth");
if (linewidth != null) roi.linewidth = Integer.parseInt(linewidth);
roi.text = attributes.getValue("text");
}
else if (qName.equals("Vertex")) {
String x = attributes.getValue("x").replaceAll(",", ".");
String y = attributes.getValue("y").replaceAll(",", ".");
roi.x.add(new Double(x));
roi.y.add(new Double(y));
}
else if (qName.equals("ROI")) {
alternateCenter = true;
}
else if (qName.equals("MultiBand")) {
MultiBand m = new MultiBand();
m.dyeName = attributes.getValue("DyeName");
m.channel = Integer.parseInt(attributes.getValue("Channel"));
m.cutIn = (int)
Math.round(Double.parseDouble(attributes.getValue("LeftWorld")));
m.cutOut = (int)
Math.round(Double.parseDouble(attributes.getValue("RightWorld")));
multiBands.add(m);
}
else count = 0;
storeSeriesHashtable(numDatasets, h);
}
| public void startElement(String uri, String localName, String qName,
Attributes attributes)
{
if (attributes.getLength() > 0 && !qName.equals("Element") &&
!qName.equals("Attachment") && !qName.equals("LMSDataContainerHeader"))
{
nameStack.push(qName);
}
Hashtable h = getSeriesHashtable(numDatasets);
if (qName.equals("LDM_Block_Sequential_Master")) {
canParse = false;
}
else if (qName.startsWith("LDM")) {
linkedInstruments = true;
}
if (!canParse) return;
StringBuffer key = new StringBuffer();
for (String k : nameStack) {
key.append(k);
key.append("|");
}
String suffix = attributes.getValue("Identifier");
String value = attributes.getValue("Variant");
if (suffix == null) suffix = attributes.getValue("Description");
if (suffix != null && value != null) {
int index = 1;
while (h.get(key.toString() + suffix + " " + index) != null) index++;
h.put(key.toString() + suffix + " " + index, value);
}
else {
for (int i=0; i<attributes.getLength(); i++) {
int index = 1;
while (
h.get(key.toString() + attributes.getQName(i) + " " + index) != null)
{
index++;
}
h.put(key.toString() + attributes.getQName(i) + " " + index,
attributes.getValue(i));
}
}
if (qName.equals("Element")) {
elementName = attributes.getValue("Name");
}
else if (qName.equals("Collection")) {
collection = elementName;
}
else if (qName.equals("Image")) {
if (!linkedInstruments) {
int c = 0;
for (Detector d : detectors) {
String id = MetadataTools.createLSID(
"Detector", numDatasets, detectorChannel);
store.setDetectorID(id, numDatasets, detectorChannel);
store.setDetectorType(d.type, numDatasets, detectorChannel);
store.setDetectorModel(d.model, numDatasets, detectorChannel);
store.setDetectorZoom(d.zoom, numDatasets, detectorChannel);
store.setDetectorOffset(d.offset, numDatasets, detectorChannel);
store.setDetectorVoltage(d.voltage, numDatasets, detectorChannel);
if (c < numChannels) {
if (d.active) {
store.setDetectorSettingsOffset(d.offset, numDatasets, c);
store.setDetectorSettingsDetector(id, numDatasets, c);
c++;
}
}
detectorChannel++;
}
int filter = 0;
for (int i=0; i<nextFilter; i++) {
while (filter < detectors.size() && !detectors.get(filter).active) {
filter++;
}
if (filter >= detectors.size() || filter >= nextFilter) break;
String id = MetadataTools.createLSID("Filter", numDatasets, filter);
if (i < numChannels && detectors.get(filter).active) {
store.setLogicalChannelSecondaryEmissionFilter(
id, numDatasets, i);
}
filter++;
}
}
core.add(new CoreMetadata());
numDatasets++;
linkedInstruments = false;
detectorChannel = 0;
detectors.clear();
lasers.clear();
nextFilter = 0;
String name = elementName;
if (collection != null) name = collection + "/" + name;
store.setImageName(name, numDatasets);
String instrumentID = MetadataTools.createLSID("Instrument", numDatasets);
store.setInstrumentID(instrumentID, numDatasets);
store.setImageInstrumentRef(instrumentID, numDatasets);
numChannels = 0;
extras = 1;
}
else if (qName.equals("Attachment")) {
if ("ContextDescription".equals(attributes.getValue("Name"))) {
store.setImageDescription(attributes.getValue("Content"), numDatasets);
}
}
else if (qName.equals("ChannelDescription")) {
count++;
numChannels++;
lutNames.add(attributes.getValue("LUTName"));
String bytesInc = attributes.getValue("BytesInc");
int bytes = bytesInc == null ? 0 : Integer.parseInt(bytesInc);
if (bytes > 0) {
bytesPerAxis.put(new Integer(bytes), "C");
}
}
else if (qName.equals("DimensionDescription")) {
int len = Integer.parseInt(attributes.getValue("NumberOfElements"));
int id = Integer.parseInt(attributes.getValue("DimID"));
double physicalLen = Double.parseDouble(attributes.getValue("Length"));
String unit = attributes.getValue("Unit");
int nBytes = Integer.parseInt(attributes.getValue("BytesInc"));
physicalLen /= len;
if (unit.equals("Ks")) {
physicalLen /= 1000;
}
else if (unit.equals("m")) {
physicalLen *= 1000000;
}
Double physicalSize = new Double(physicalLen);
CoreMetadata coreMeta = core.get(core.size() - 1);
switch (id) {
case 1: // X axis
coreMeta.sizeX = len;
coreMeta.rgb = (nBytes % 3) == 0;
if (coreMeta.rgb) nBytes /= 3;
switch (nBytes) {
case 1:
coreMeta.pixelType = FormatTools.UINT8;
break;
case 2:
coreMeta.pixelType = FormatTools.UINT16;
break;
case 4:
coreMeta.pixelType = FormatTools.FLOAT;
break;
}
physicalSizeX = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeX(physicalSize, numDatasets, 0);
break;
case 2: // Y axis
if (coreMeta.sizeY != 0) {
if (coreMeta.sizeZ == 1) {
coreMeta.sizeZ = len;
bytesPerAxis.put(new Integer(nBytes), "Z");
}
else if (coreMeta.sizeT == 1) {
coreMeta.sizeT = len;
bytesPerAxis.put(new Integer(nBytes), "T");
}
}
else {
coreMeta.sizeY = len;
physicalSizeY = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeY(physicalSize, numDatasets, 0);
}
break;
case 3: // Z axis
if (coreMeta.sizeY == 0) {
// XZ scan - swap Y and Z
coreMeta.sizeY = len;
coreMeta.sizeZ = 1;
physicalSizeY = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeY(physicalSize, numDatasets, 0);
bytesPerAxis.put(new Integer(nBytes), "Y");
}
else {
coreMeta.sizeZ = len;
bytesPerAxis.put(new Integer(nBytes), "Z");
}
break;
case 4: // T axis
if (coreMeta.sizeY == 0) {
// XT scan - swap Y and T
coreMeta.sizeY = len;
coreMeta.sizeT = 1;
physicalSizeY = physicalSize.doubleValue();
store.setDimensionsPhysicalSizeY(physicalSize, numDatasets, 0);
bytesPerAxis.put(new Integer(nBytes), "Y");
}
else {
coreMeta.sizeT = len;
bytesPerAxis.put(new Integer(nBytes), "T");
}
break;
default:
extras *= len;
}
count++;
}
else if (qName.equals("ScannerSettingRecord")) {
String id = attributes.getValue("Identifier");
if (id == null) id = "";
if (id.equals("SystemType")) {
store.setMicroscopeModel(value, numDatasets);
store.setMicroscopeType("Unknown", numDatasets);
}
else if (id.equals("dblPinhole")) {
pinhole = new Double(Double.parseDouble(value) * 1000000);
}
else if (id.equals("dblZoom")) {
zoom = new Double(value);
}
else if (id.equals("dblStepSize")) {
double zStep = Double.parseDouble(value) * 1000000;
store.setDimensionsPhysicalSizeZ(new Double(zStep), numDatasets, 0);
}
else if (id.equals("nDelayTime_s")) {
store.setDimensionsTimeIncrement(new Double(value), numDatasets, 0);
}
else if (id.equals("CameraName")) {
store.setDetectorModel(value, numDatasets, 0);
}
else if (id.indexOf("WFC") == 1) {
int c = 0;
try {
c = Integer.parseInt(id.replaceAll("\\D", ""));
}
catch (NumberFormatException e) { }
if (id.endsWith("ExposureTime")) {
store.setPlaneTimingExposureTime(new Double(value),
numDatasets, 0, c);
}
else if (id.endsWith("Gain")) {
store.setDetectorSettingsGain(new Double(value), numDatasets, c);
String detectorID =
MetadataTools.createLSID("Detector", numDatasets, 0);
store.setDetectorSettingsDetector(detectorID, numDatasets, c);
store.setDetectorID(detectorID, numDatasets, 0);
store.setDetectorType("CCD", numDatasets, 0);
}
else if (id.endsWith("WaveLength")) {
store.setLogicalChannelExWave(new Integer(value), numDatasets, c);
}
// NB: "UesrDefName" is not a typo.
else if (id.endsWith("UesrDefName") && !value.equals("None")) {
store.setLogicalChannelName(value, numDatasets, c);
}
}
}
else if (qName.equals("FilterSettingRecord")) {
String object = attributes.getValue("ObjectName");
String attribute = attributes.getValue("Attribute");
String objectClass = attributes.getValue("ClassName");
String variant = attributes.getValue("Variant");
CoreMetadata coreMeta = core.get(numDatasets);
if (attribute.equals("NumericalAperture")) {
store.setObjectiveLensNA(new Double(variant), numDatasets, 0);
store.setObjectiveCorrection("Unknown", numDatasets, 0);
store.setObjectiveImmersion("Unknown", numDatasets, 0);
}
else if (attribute.equals("OrderNumber")) {
store.setObjectiveSerialNumber(variant, numDatasets, 0);
store.setObjectiveCorrection("Unknown", numDatasets, 0);
store.setObjectiveImmersion("Unknown", numDatasets, 0);
}
else if (objectClass.equals("CDetectionUnit")) {
if (attribute.equals("State")) {
Detector d = new Detector();
String data = attributes.getValue("data");
d.channel = data == null ? 0 : Integer.parseInt(data);
d.type = "PMT";
d.model = object;
d.active = variant.equals("Active");
d.zoom = zoom;
detectors.add(d);
}
else if (attribute.equals("HighVoltage")) {
Detector d = detectors.get(detectors.size() - 1);
d.voltage = new Double(variant);
}
else if (attribute.equals("VideoOffset")) {
Detector d = detectors.get(detectors.size() - 1);
d.offset = new Double(variant);
}
}
else if (attribute.equals("Objective")) {
StringTokenizer tokens = new StringTokenizer(variant, " ");
boolean foundMag = false;
StringBuffer model = new StringBuffer();
while (!foundMag) {
String token = tokens.nextToken();
int x = token.indexOf("x");
if (x != -1) {
foundMag = true;
int mag = (int) Double.parseDouble(token.substring(0, x));
String na = token.substring(x + 1);
store.setObjectiveNominalMagnification(
new Integer(mag), numDatasets, 0);
store.setObjectiveLensNA(new Double(na), numDatasets, 0);
}
else {
model.append(token);
model.append(" ");
}
}
String immersion = "Unknown";
if (tokens.hasMoreTokens()) {
immersion = tokens.nextToken();
if (immersion == null || immersion.trim().equals("")) {
immersion = "Unknown";
}
}
store.setObjectiveImmersion(immersion, numDatasets, 0);
String correction = "Unknown";
if (tokens.hasMoreTokens()) {
correction = tokens.nextToken();
if (correction == null || correction.trim().equals("")) {
correction = "Unknown";
}
}
store.setObjectiveCorrection("Unknown", numDatasets, 0);
store.setObjectiveModel(model.toString().trim(), numDatasets, 0);
}
else if (attribute.equals("RefractionIndex")) {
String id = MetadataTools.createLSID("Objective", numDatasets, 0);
store.setObjectiveID(id, numDatasets, 0);
store.setObjectiveSettingsObjective(id, numDatasets);
store.setObjectiveSettingsRefractiveIndex(new Double(variant),
numDatasets);
}
else if (attribute.equals("XPos")) {
int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
int nPlanes = coreMeta.imageCount / c;
Double posX = new Double(variant);
for (int image=0; image<nPlanes; image++) {
int index = image * (coreMeta.rgb ? 1 : coreMeta.sizeC);
if (index >= nPlanes) continue;
store.setStagePositionPositionX(posX, numDatasets, 0, index);
}
if (numChannels == 0) xPos.add(posX);
}
else if (attribute.equals("YPos")) {
int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
int nPlanes = coreMeta.imageCount / c;
Double posY = new Double(variant);
for (int image=0; image<nPlanes; image++) {
int index = image * (coreMeta.rgb ? 1 : coreMeta.sizeC);
if (index >= nPlanes) continue;
store.setStagePositionPositionY(posY, numDatasets, 0, index);
}
if (numChannels == 0) yPos.add(posY);
}
else if (attribute.equals("ZPos")) {
int c = coreMeta.rgb || coreMeta.sizeC == 0 ? 1 : coreMeta.sizeC;
int nPlanes = coreMeta.imageCount / c;
Double posZ = new Double(variant);
for (int image=0; image<nPlanes; image++) {
int index = image * (coreMeta.rgb ? 1 : coreMeta.sizeC);
if (index >= nPlanes) continue;
store.setStagePositionPositionZ(posZ, numDatasets, 0, index);
}
if (numChannels == 0) zPos.add(posZ);
}
else if (objectClass.equals("CSpectrophotometerUnit")) {
Integer v = null;
try {
v = new Integer((int) Double.parseDouble(variant));
}
catch (NumberFormatException e) { }
if (attributes.getValue("Description").endsWith("(left)")) {
String id =
MetadataTools.createLSID("Filter", numDatasets, nextFilter);
store.setFilterID(id, numDatasets, nextFilter);
store.setFilterModel(object, numDatasets, nextFilter);
if (v != null) {
store.setTransmittanceRangeCutIn(v, numDatasets, nextFilter);
}
}
else if (attributes.getValue("Description").endsWith("(right)")) {
if (v != null) {
store.setTransmittanceRangeCutOut(v, numDatasets, nextFilter);
nextFilter++;
}
}
}
}
else if (qName.equals("Detector")) {
String v = attributes.getValue("Gain");
Double gain = v == null ? null : new Double(v);
v = attributes.getValue("Offset");
Double offset = v == null ? null : new Double(v);
boolean active = "1".equals(attributes.getValue("IsActive"));
if (active) {
// find the corresponding MultiBand and Detector
MultiBand m = null;
Detector detector = null;
Laser laser = lasers.size() == 0 ? null : lasers.get(lasers.size() - 1);
String c = attributes.getValue("Channel");
int channel = c == null ? 0 : Integer.parseInt(c);
for (MultiBand mb : multiBands) {
if (mb.channel == channel) {
m = mb;
break;
}
}
for (Detector d : detectors) {
if (d.channel == channel) {
detector = d;
break;
}
}
String id =
MetadataTools.createLSID("Detector", numDatasets, nextChannel);
if (m != null) {
store.setLogicalChannelName(m.dyeName, numDatasets, nextChannel);
String filter =
MetadataTools.createLSID("Filter", numDatasets, nextFilter);
store.setFilterID(filter, numDatasets, nextFilter);
store.setTransmittanceRangeCutIn(new Integer(m.cutIn), numDatasets,
nextFilter);
store.setTransmittanceRangeCutOut(new Integer(m.cutOut), numDatasets,
nextFilter);
store.setLogicalChannelSecondaryEmissionFilter(filter, numDatasets,
nextChannel);
nextFilter++;
store.setDetectorID(id, numDatasets, nextChannel);
store.setDetectorType("PMT", numDatasets, nextChannel);
store.setDetectorSettingsGain(gain, numDatasets, nextChannel);
store.setDetectorSettingsOffset(offset, numDatasets, nextChannel);
store.setDetectorSettingsDetector(id, numDatasets, nextChannel);
}
if (detector != null) {
store.setDetectorID(id, numDatasets, nextChannel);
store.setDetectorSettingsGain(gain, numDatasets, nextChannel);
store.setDetectorSettingsOffset(offset, numDatasets, nextChannel);
store.setDetectorSettingsDetector(id, numDatasets, nextChannel);
store.setDetectorType(detector.type, numDatasets, nextChannel);
store.setDetectorModel(detector.model, numDatasets, nextChannel);
store.setDetectorZoom(detector.zoom, numDatasets, nextChannel);
store.setDetectorOffset(detector.offset, numDatasets, nextChannel);
store.setDetectorVoltage(detector.voltage, numDatasets,
nextChannel);
}
if (laser != null && laser.intensity > 0) {
store.setLightSourceSettingsLightSource(laser.id, numDatasets,
nextChannel);
store.setLightSourceSettingsAttenuation(
new Double(laser.intensity / 100.0), numDatasets, nextChannel);
store.setLogicalChannelExWave(laser.wavelength, numDatasets,
nextChannel);
}
nextChannel++;
}
}
else if (qName.equals("LaserLineSetting")) {
Laser l = new Laser();
String lineIndex = attributes.getValue("LineIndex");
String qual = attributes.getValue("Qualifier");
l.index = lineIndex == null ? 0 : Integer.parseInt(lineIndex);
int qualifier = qual == null ? 0 : Integer.parseInt(qual);
l.index += (2 - (qualifier / 10));
if (l.index < 0) l.index = 0;
l.id = MetadataTools.createLSID("LightSource", numDatasets, l.index);
l.wavelength = new Integer(attributes.getValue("LaserLine"));
store.setLightSourceID(l.id, numDatasets, l.index);
store.setLaserWavelength(l.wavelength, numDatasets, l.index);
store.setLaserType("Unknown", numDatasets, l.index);
store.setLaserLaserMedium("Unknown", numDatasets, l.index);
String intensity = attributes.getValue("IntensityDev");
l.intensity = intensity == null ? 0d : Double.parseDouble(intensity);
if (l.intensity > 0) lasers.add(l);
}
else if (qName.equals("TimeStamp") && numDatasets >= 0) {
String stampHigh = attributes.getValue("HighInteger");
String stampLow = attributes.getValue("LowInteger");
long high = stampHigh == null ? 0 : Long.parseLong(stampHigh);
long low = stampLow == null ? 0 : Long.parseLong(stampLow);
long ms = DateTools.getMillisFromTicks(high, low);
if (count == 0) {
String date = DateTools.convertDate(ms, DateTools.COBOL);
if (DateTools.getTime(date, DateTools.ISO8601_FORMAT) <
System.currentTimeMillis())
{
store.setImageCreationDate(date, numDatasets);
}
firstStamp = ms;
store.setPlaneTimingDeltaT(new Double(0), numDatasets, 0, count);
}
else {
CoreMetadata coreMeta = core.get(numDatasets);
int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC;
if (count < nImages) {
ms -= firstStamp;
store.setPlaneTimingDeltaT(
new Double(ms / 1000.0), numDatasets, 0, count);
}
}
count++;
}
else if (qName.equals("RelTimeStamp")) {
CoreMetadata coreMeta = core.get(numDatasets);
int nImages = coreMeta.sizeZ * coreMeta.sizeT * coreMeta.sizeC;
if (count < nImages) {
Double time = new Double(attributes.getValue("Time"));
store.setPlaneTimingDeltaT(time, numDatasets, 0, count++);
}
}
else if (qName.equals("Annotation")) {
roi = new ROI();
String type = attributes.getValue("type");
if (type != null) roi.type = Integer.parseInt(type);
String color = attributes.getValue("color");
if (color != null) roi.color = Integer.parseInt(color);
roi.name = attributes.getValue("name");
roi.fontName = attributes.getValue("fontName");
roi.fontSize = attributes.getValue("fontSize");
roi.transX = parseDouble(attributes.getValue("transTransX"));
roi.transY = parseDouble(attributes.getValue("transTransY"));
roi.scaleX = parseDouble(attributes.getValue("transScalingX"));
roi.scaleY = parseDouble(attributes.getValue("transScalingY"));
roi.rotation = parseDouble(attributes.getValue("transRotation"));
String linewidth = attributes.getValue("linewidth");
if (linewidth != null) roi.linewidth = Integer.parseInt(linewidth);
roi.text = attributes.getValue("text");
}
else if (qName.equals("Vertex")) {
String x = attributes.getValue("x");
String y = attributes.getValue("y");
if (x != null) {
x = x.replaceAll(",", ".");
roi.x.add(new Double(x));
}
if (y != null) {
y = y.replaceAll(",", ".");
roi.y.add(new Double(y));
}
}
else if (qName.equals("ROI")) {
alternateCenter = true;
}
else if (qName.equals("MultiBand")) {
MultiBand m = new MultiBand();
m.dyeName = attributes.getValue("DyeName");
m.channel = Integer.parseInt(attributes.getValue("Channel"));
m.cutIn = (int)
Math.round(Double.parseDouble(attributes.getValue("LeftWorld")));
m.cutOut = (int)
Math.round(Double.parseDouble(attributes.getValue("RightWorld")));
multiBands.add(m);
}
else count = 0;
storeSeriesHashtable(numDatasets, h);
}
|
diff --git a/calendar/app/bootstrap/Bootstrap.java b/calendar/app/bootstrap/Bootstrap.java
index 0953283..3d5fa61 100644
--- a/calendar/app/bootstrap/Bootstrap.java
+++ b/calendar/app/bootstrap/Bootstrap.java
@@ -1,17 +1,18 @@
package bootstrap;
import models.User;
import play.jobs.Job;
import play.jobs.OnApplicationStart;
import play.test.Fixtures;
@OnApplicationStart
public class Bootstrap extends Job {
@Override
public void doJob() {
+ Fixtures.deleteAllModels();
if (User.count() == 0) {
Fixtures.loadModels("bootstrap-data.yml");
}
}
}
| true | true | public void doJob() {
if (User.count() == 0) {
Fixtures.loadModels("bootstrap-data.yml");
}
}
| public void doJob() {
Fixtures.deleteAllModels();
if (User.count() == 0) {
Fixtures.loadModels("bootstrap-data.yml");
}
}
|
diff --git a/src/main/ed/appserver/jxp/JxpSource.java b/src/main/ed/appserver/jxp/JxpSource.java
index ff9ad60e3..1081844dc 100644
--- a/src/main/ed/appserver/jxp/JxpSource.java
+++ b/src/main/ed/appserver/jxp/JxpSource.java
@@ -1,190 +1,190 @@
// Source.java
package ed.appserver.jxp;
import java.io.*;
import java.util.*;
import ed.io.*;
import ed.js.*;
import ed.js.engine.*;
import ed.lang.*;
import ed.util.*;
import ed.appserver.*;
import ed.appserver.templates.*;
import ed.appserver.templates.djang10.Djang10Source;
public abstract class JxpSource implements Dependency , DependencyTracker {
public static final String JXP_SOURCE_PROP = "_jxpSource";
static final File _tmpDir = new File( "/tmp/jxp/templates/" );
static {
_tmpDir.mkdirs();
}
public static JxpSource getSource( File f ){
return getSource( f , null );
}
public static JxpSource getSource( File f , JSFileLibrary lib ){
if ( f == null )
throw new NullPointerException( "can't have null file" );
if(f.getName().endsWith(".djang10"))
return new Djang10Source(f);
JxpSource s = new JxpFileSource( f );
s._lib = lib;
return s;
}
// -----
abstract String getContent() throws IOException;
abstract InputStream getInputStream() throws IOException ;
public abstract long lastUpdated();
abstract String getName();
/**
* @return File if it makes sense, otherwise nothing
*/
public abstract File getFile();
public void addDependency( Dependency d ){
_dependencies.add( d );
}
public synchronized JSFunction getFunction()
throws IOException {
_checkTime();
if ( _func != null )
return _func;
- _lastParse = lastUpdated();
+ _lastParse = Calendar.getInstance().getTimeInMillis();
_dependencies.clear();
Template t = new Template( getName() , getContent() , Language.find( getName() ) );
while ( ! t.getExtension().equals( "js" ) ){
TemplateConverter.Result result = TemplateEngine.oneConvert( t , this );
if ( result == null )
break;
if ( result.getLineMapping() != null )
StackTraceHolder.getInstance().set( result.getNewTemplate().getName() ,
new BasicLineNumberMapper( t.getName() , result.getNewTemplate().getName() , result.getLineMapping() ) );
t = result.getNewTemplate();
}
if ( ! t.getExtension().equals( "js" ) )
throw new RuntimeException( "don't know what do do with : " + t.getExtension() );
Convert convert = null;
try {
convert = new Convert( t.getName() , t.getContent() , false , t.getSourceLanguage() );
_func = convert.get();
_func.set(JXP_SOURCE_PROP, this);
return _func;
}
catch ( Exception e ){
String thing = e.toString();
if ( thing.indexOf( ":" ) >= 0 )
thing = thing.substring( thing.indexOf(":") + 1 );
String msg = "couldn't compile ";
if ( ! thing.contains( t.getName() ) )
msg += " [" + t.getName() + "] ";
msg += thing;
throw new RuntimeException( msg , e );
}
}
private String _getFileSafeName(){
return getName().replaceAll( "[^\\w]" , "_" );
}
public JxpServlet getServlet( AppContext context )
throws IOException {
_checkTime();
if ( _servlet == null ){
JSFunction f = getFunction();
_servlet = new JxpServlet( context , this , f );
JSFileLibrary.addPath( f.getClass() , _lib );
}
return _servlet;
}
private void _checkTime(){
if ( ! _needsParsing() )
return;
_func = null;
_servlet = null;
}
protected boolean _needsParsing(){
if ( _lastParse < lastUpdated() )
return true;
for ( Dependency d : _dependencies )
if ( _lastParse < d.lastUpdated() )
return true;
return false;
}
public String toString(){
return getName();
}
protected long _lastParse = 0;
protected List<Dependency> _dependencies = new ArrayList<Dependency>();
private JSFunction _func;
private JxpServlet _servlet;
private JSFileLibrary _lib;
// -------------------
public static class JxpFileSource extends JxpSource {
protected JxpFileSource( File f ){
_f = f;
}
String getName(){
return _f.toString();
}
protected String getContent()
throws IOException {
return StreamUtil.readFully( _f );
}
InputStream getInputStream()
throws IOException {
return new FileInputStream( _f );
}
public long lastUpdated(){
return _f.lastModified();
}
public File getFile(){
return _f;
}
final File _f;
}
}
| true | true | public synchronized JSFunction getFunction()
throws IOException {
_checkTime();
if ( _func != null )
return _func;
_lastParse = lastUpdated();
_dependencies.clear();
Template t = new Template( getName() , getContent() , Language.find( getName() ) );
while ( ! t.getExtension().equals( "js" ) ){
TemplateConverter.Result result = TemplateEngine.oneConvert( t , this );
if ( result == null )
break;
if ( result.getLineMapping() != null )
StackTraceHolder.getInstance().set( result.getNewTemplate().getName() ,
new BasicLineNumberMapper( t.getName() , result.getNewTemplate().getName() , result.getLineMapping() ) );
t = result.getNewTemplate();
}
if ( ! t.getExtension().equals( "js" ) )
throw new RuntimeException( "don't know what do do with : " + t.getExtension() );
Convert convert = null;
try {
convert = new Convert( t.getName() , t.getContent() , false , t.getSourceLanguage() );
_func = convert.get();
_func.set(JXP_SOURCE_PROP, this);
return _func;
}
catch ( Exception e ){
String thing = e.toString();
if ( thing.indexOf( ":" ) >= 0 )
thing = thing.substring( thing.indexOf(":") + 1 );
String msg = "couldn't compile ";
if ( ! thing.contains( t.getName() ) )
msg += " [" + t.getName() + "] ";
msg += thing;
throw new RuntimeException( msg , e );
}
}
| public synchronized JSFunction getFunction()
throws IOException {
_checkTime();
if ( _func != null )
return _func;
_lastParse = Calendar.getInstance().getTimeInMillis();
_dependencies.clear();
Template t = new Template( getName() , getContent() , Language.find( getName() ) );
while ( ! t.getExtension().equals( "js" ) ){
TemplateConverter.Result result = TemplateEngine.oneConvert( t , this );
if ( result == null )
break;
if ( result.getLineMapping() != null )
StackTraceHolder.getInstance().set( result.getNewTemplate().getName() ,
new BasicLineNumberMapper( t.getName() , result.getNewTemplate().getName() , result.getLineMapping() ) );
t = result.getNewTemplate();
}
if ( ! t.getExtension().equals( "js" ) )
throw new RuntimeException( "don't know what do do with : " + t.getExtension() );
Convert convert = null;
try {
convert = new Convert( t.getName() , t.getContent() , false , t.getSourceLanguage() );
_func = convert.get();
_func.set(JXP_SOURCE_PROP, this);
return _func;
}
catch ( Exception e ){
String thing = e.toString();
if ( thing.indexOf( ":" ) >= 0 )
thing = thing.substring( thing.indexOf(":") + 1 );
String msg = "couldn't compile ";
if ( ! thing.contains( t.getName() ) )
msg += " [" + t.getName() + "] ";
msg += thing;
throw new RuntimeException( msg , e );
}
}
|
diff --git a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/submission/workflow/PerformTaskStep.java b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/submission/workflow/PerformTaskStep.java
index d21012057..2c543cbf5 100644
--- a/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/submission/workflow/PerformTaskStep.java
+++ b/dspace-xmlui/dspace-xmlui-api/src/main/java/org/dspace/app/xmlui/aspect/submission/workflow/PerformTaskStep.java
@@ -1,243 +1,244 @@
/*
* PerformTaskStep.java
*
* Version: $Revision: 1.4 $
*
* Date: $Date: 2006/07/13 23:20:54 $
*
* Copyright (c) 2002, Hewlett-Packard Company and Massachusetts
* Institute of Technology. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of the Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package org.dspace.app.xmlui.aspect.submission.workflow;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.dspace.app.xmlui.aspect.submission.AbstractStep;
import org.dspace.app.xmlui.utils.UIException;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Body;
import org.dspace.app.xmlui.wing.element.Division;
import org.dspace.app.xmlui.wing.element.ReferenceSet;
import org.dspace.app.xmlui.wing.element.Row;
import org.dspace.app.xmlui.wing.element.Table;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Collection;
import org.dspace.content.Item;
import org.dspace.uri.IdentifierService;
import org.dspace.workflow.WorkflowItem;
import org.dspace.workflow.WorkflowManager;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.sql.SQLException;
/**
*
* This step displays a workfrow item to the user and and presents several
* possible actions that they may preform on the task.
*
* General the user may, accept the item, reject the item, or edit the item's
* metadata before accepting or rejecting. The user is also given the option
* of taking the task or returning it to the pool.
*
* @author Scott Phillips
*/
public class PerformTaskStep extends AbstractStep
{
/** Language Strings **/
protected static final Message T_info1=
message("xmlui.Submission.workflow.PerformTaskStep.info1");
protected static final Message T_take_help =
message("xmlui.Submission.workflow.PerformTaskStep.take_help");
protected static final Message T_take_submit =
message("xmlui.Submission.workflow.PerformTaskStep.take_submit");
protected static final Message T_leave_help =
message("xmlui.Submission.workflow.PerformTaskStep.leave_help");
protected static final Message T_leave_submit =
message("xmlui.Submission.workflow.PerformTaskStep.leave_submit");
protected static final Message T_approve_help =
message("xmlui.Submission.workflow.PerformTaskStep.approve_help");
protected static final Message T_approve_submit =
message("xmlui.Submission.workflow.PerformTaskStep.approve_submit");
protected static final Message T_commit_help =
message("xmlui.Submission.workflow.PerformTaskStep.commit_help");
protected static final Message T_commit_submit =
message("xmlui.Submission.workflow.PerformTaskStep.commit_submit");
protected static final Message T_reject_help =
message("xmlui.Submission.workflow.PerformTaskStep.reject_help");
protected static final Message T_reject_submit =
message("xmlui.Submission.workflow.PerformTaskStep.reject_submit");
protected static final Message T_edit_help =
message("xmlui.Submission.workflow.PerformTaskStep.edit_help");
protected static final Message T_edit_submit =
message("xmlui.Submission.workflow.PerformTaskStep.edit_submit");
protected static final Message T_return_help =
message("xmlui.Submission.workflow.PerformTaskStep.return_help");
protected static final Message T_return_submit =
message("xmlui.Submission.workflow.PerformTaskStep.return_submit");
protected static final Message T_cancel_submit =
message("xmlui.general.cancel");
/** Copy the workflow manager's state values so that we can refrence them easier. */
private static final int WFSTATE_STEP1POOL = WorkflowManager.WFSTATE_STEP1POOL;
private static final int WFSTATE_STEP1 = WorkflowManager.WFSTATE_STEP1;
private static final int WFSTATE_STEP2POOL = WorkflowManager.WFSTATE_STEP2POOL;
private static final int WFSTATE_STEP2 = WorkflowManager.WFSTATE_STEP2;
private static final int WFSTATE_STEP3POOL = WorkflowManager.WFSTATE_STEP3POOL;
private static final int WFSTATE_STEP3 = WorkflowManager.WFSTATE_STEP3;
/**
* Establish our required parameters, abstractStep will enforce these.
*/
public PerformTaskStep()
{
this.requireWorkflow = true;
}
public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// Get any metadata that may be removed by unselecting one of these options.
Item item = submission.getItem();
Collection collection = submission.getCollection();
String actionURL = IdentifierService.getURL(collection).toString() + "/workflow";
int state = ((WorkflowItem) submission).getState();
Request request = ObjectModelHelper.getRequest(objectModel);
String showfull = request.getParameter("showfull");
// if the user selected showsimple, remove showfull.
if (showfull != null && request.getParameter("showsimple") != null)
showfull = null;
// Generate a from asking the user two questions: multiple
// titles & published before.
Division div = body.addInteractiveDivision("perform-task", actionURL, Division.METHOD_POST, "primary workflow");
div.setHead(T_workflow_head);
if (showfull == null)
{
ReferenceSet referenceSet = div.addReferenceSet("narf",ReferenceSet.TYPE_SUMMARY_VIEW);
referenceSet.addReference(item);
div.addPara().addButton("showfull").setValue(T_showfull);
}
else
{
ReferenceSet referenceSet = div.addReferenceSet("narf",ReferenceSet.TYPE_DETAIL_VIEW);
referenceSet.addReference(item);
div.addPara().addButton("showsimple").setValue(T_showsimple);
div.addHidden("showfull").setValue("true");
}
//FIXME: set the correct table size.
Table table = div.addTable("workflow-actions", 1, 1);
table.setHead(T_info1);
// Header
Row row;
if (state == WFSTATE_STEP1POOL ||
state == WFSTATE_STEP2POOL ||
state == WFSTATE_STEP3POOL)
{
// Take task
row = table.addRow();
row.addCellContent(T_take_help);
row.addCell().addButton("submit_take_task").setValue(T_take_submit);
// Leave task
row = table.addRow();
row.addCellContent(T_leave_help);
row.addCell().addButton("submit_leave").setValue(T_leave_submit);
}
if (state == WFSTATE_STEP1 ||
state == WFSTATE_STEP2)
{
// Approve task
row = table.addRow();
row.addCellContent(T_approve_help);
row.addCell().addButton("submit_approve").setValue(T_approve_submit);
}
if (state == WFSTATE_STEP3)
{
// Commit to archive
row = table.addRow();
row.addCellContent(T_commit_help);
row.addCell().addButton("submit_approve").setValue(T_commit_submit);
}
if (state == WFSTATE_STEP1 ||
state == WFSTATE_STEP2)
{
// Reject item
row = table.addRow();
row.addCellContent(T_reject_help);
row.addCell().addButton("submit_reject").setValue(T_reject_submit);
}
- if (state == WFSTATE_STEP2)
+ if (state == WFSTATE_STEP2 ||
+ state == WFSTATE_STEP3 )
{
// Edit metadata
row = table.addRow();
row.addCellContent(T_edit_help);
row.addCell().addButton("submit_edit").setValue(T_edit_submit);
}
if (state == WFSTATE_STEP1 ||
state == WFSTATE_STEP2 ||
state == WFSTATE_STEP3 )
{
// Return to pool
row = table.addRow();
row.addCellContent(T_return_help);
row.addCell().addButton("submit_return").setValue(T_return_submit);
}
// Everyone can just cancel
row = table.addRow();
row.addCell(0, 2).addButton("submit_leave").setValue(T_cancel_submit);
div.addHidden("submission-continue").setValue(knot.getId());
}
}
| true | true | public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// Get any metadata that may be removed by unselecting one of these options.
Item item = submission.getItem();
Collection collection = submission.getCollection();
String actionURL = IdentifierService.getURL(collection).toString() + "/workflow";
int state = ((WorkflowItem) submission).getState();
Request request = ObjectModelHelper.getRequest(objectModel);
String showfull = request.getParameter("showfull");
// if the user selected showsimple, remove showfull.
if (showfull != null && request.getParameter("showsimple") != null)
showfull = null;
// Generate a from asking the user two questions: multiple
// titles & published before.
Division div = body.addInteractiveDivision("perform-task", actionURL, Division.METHOD_POST, "primary workflow");
div.setHead(T_workflow_head);
if (showfull == null)
{
ReferenceSet referenceSet = div.addReferenceSet("narf",ReferenceSet.TYPE_SUMMARY_VIEW);
referenceSet.addReference(item);
div.addPara().addButton("showfull").setValue(T_showfull);
}
else
{
ReferenceSet referenceSet = div.addReferenceSet("narf",ReferenceSet.TYPE_DETAIL_VIEW);
referenceSet.addReference(item);
div.addPara().addButton("showsimple").setValue(T_showsimple);
div.addHidden("showfull").setValue("true");
}
//FIXME: set the correct table size.
Table table = div.addTable("workflow-actions", 1, 1);
table.setHead(T_info1);
// Header
Row row;
if (state == WFSTATE_STEP1POOL ||
state == WFSTATE_STEP2POOL ||
state == WFSTATE_STEP3POOL)
{
// Take task
row = table.addRow();
row.addCellContent(T_take_help);
row.addCell().addButton("submit_take_task").setValue(T_take_submit);
// Leave task
row = table.addRow();
row.addCellContent(T_leave_help);
row.addCell().addButton("submit_leave").setValue(T_leave_submit);
}
if (state == WFSTATE_STEP1 ||
state == WFSTATE_STEP2)
{
// Approve task
row = table.addRow();
row.addCellContent(T_approve_help);
row.addCell().addButton("submit_approve").setValue(T_approve_submit);
}
if (state == WFSTATE_STEP3)
{
// Commit to archive
row = table.addRow();
row.addCellContent(T_commit_help);
row.addCell().addButton("submit_approve").setValue(T_commit_submit);
}
if (state == WFSTATE_STEP1 ||
state == WFSTATE_STEP2)
{
// Reject item
row = table.addRow();
row.addCellContent(T_reject_help);
row.addCell().addButton("submit_reject").setValue(T_reject_submit);
}
if (state == WFSTATE_STEP2)
{
// Edit metadata
row = table.addRow();
row.addCellContent(T_edit_help);
row.addCell().addButton("submit_edit").setValue(T_edit_submit);
}
if (state == WFSTATE_STEP1 ||
state == WFSTATE_STEP2 ||
state == WFSTATE_STEP3 )
{
// Return to pool
row = table.addRow();
row.addCellContent(T_return_help);
row.addCell().addButton("submit_return").setValue(T_return_submit);
}
// Everyone can just cancel
row = table.addRow();
row.addCell(0, 2).addButton("submit_leave").setValue(T_cancel_submit);
div.addHidden("submission-continue").setValue(knot.getId());
}
| public void addBody(Body body) throws SAXException, WingException,
UIException, SQLException, IOException, AuthorizeException
{
// Get any metadata that may be removed by unselecting one of these options.
Item item = submission.getItem();
Collection collection = submission.getCollection();
String actionURL = IdentifierService.getURL(collection).toString() + "/workflow";
int state = ((WorkflowItem) submission).getState();
Request request = ObjectModelHelper.getRequest(objectModel);
String showfull = request.getParameter("showfull");
// if the user selected showsimple, remove showfull.
if (showfull != null && request.getParameter("showsimple") != null)
showfull = null;
// Generate a from asking the user two questions: multiple
// titles & published before.
Division div = body.addInteractiveDivision("perform-task", actionURL, Division.METHOD_POST, "primary workflow");
div.setHead(T_workflow_head);
if (showfull == null)
{
ReferenceSet referenceSet = div.addReferenceSet("narf",ReferenceSet.TYPE_SUMMARY_VIEW);
referenceSet.addReference(item);
div.addPara().addButton("showfull").setValue(T_showfull);
}
else
{
ReferenceSet referenceSet = div.addReferenceSet("narf",ReferenceSet.TYPE_DETAIL_VIEW);
referenceSet.addReference(item);
div.addPara().addButton("showsimple").setValue(T_showsimple);
div.addHidden("showfull").setValue("true");
}
//FIXME: set the correct table size.
Table table = div.addTable("workflow-actions", 1, 1);
table.setHead(T_info1);
// Header
Row row;
if (state == WFSTATE_STEP1POOL ||
state == WFSTATE_STEP2POOL ||
state == WFSTATE_STEP3POOL)
{
// Take task
row = table.addRow();
row.addCellContent(T_take_help);
row.addCell().addButton("submit_take_task").setValue(T_take_submit);
// Leave task
row = table.addRow();
row.addCellContent(T_leave_help);
row.addCell().addButton("submit_leave").setValue(T_leave_submit);
}
if (state == WFSTATE_STEP1 ||
state == WFSTATE_STEP2)
{
// Approve task
row = table.addRow();
row.addCellContent(T_approve_help);
row.addCell().addButton("submit_approve").setValue(T_approve_submit);
}
if (state == WFSTATE_STEP3)
{
// Commit to archive
row = table.addRow();
row.addCellContent(T_commit_help);
row.addCell().addButton("submit_approve").setValue(T_commit_submit);
}
if (state == WFSTATE_STEP1 ||
state == WFSTATE_STEP2)
{
// Reject item
row = table.addRow();
row.addCellContent(T_reject_help);
row.addCell().addButton("submit_reject").setValue(T_reject_submit);
}
if (state == WFSTATE_STEP2 ||
state == WFSTATE_STEP3 )
{
// Edit metadata
row = table.addRow();
row.addCellContent(T_edit_help);
row.addCell().addButton("submit_edit").setValue(T_edit_submit);
}
if (state == WFSTATE_STEP1 ||
state == WFSTATE_STEP2 ||
state == WFSTATE_STEP3 )
{
// Return to pool
row = table.addRow();
row.addCellContent(T_return_help);
row.addCell().addButton("submit_return").setValue(T_return_submit);
}
// Everyone can just cancel
row = table.addRow();
row.addCell(0, 2).addButton("submit_leave").setValue(T_cancel_submit);
div.addHidden("submission-continue").setValue(knot.getId());
}
|
diff --git a/arffgenerator/src/AttTest.java b/arffgenerator/src/AttTest.java
index 3cfc815..6b8db35 100644
--- a/arffgenerator/src/AttTest.java
+++ b/arffgenerator/src/AttTest.java
@@ -1,52 +1,52 @@
import java.util.Random;
public class AttTest {
public static void main(String[] args) throws Exception {
System.out.println("@relation vreme" + "\n");
String[] opis = {"hladno", "toplo", "vetrovno", "de�evno", "sne�i"};
int temperatura = 0;
String[] veter = {"0", "5", "10", "20", "50"};
String[] moznost_padavin = {"0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"};
String zdruzi = "";
zdruzi = zdruzi + opis[0];
- for (int i=0; i<opis.length; i++){
+ for (int i=1; i<opis.length; i++){
if (i<opis.length)
zdruzi = zdruzi + ",";
zdruzi = zdruzi + opis[i];
}
System.out.println("@attribute opis {" + zdruzi + "}");
System.out.println("@attribute temperatura NUMERIC");
zdruzi = "";
zdruzi = zdruzi + veter[0];
- for (int i=0; i<veter.length; i++){
+ for (int i=1; i<veter.length; i++){
if (i<veter.length)
zdruzi = zdruzi + ",";
zdruzi = zdruzi + veter[i];
}
System.out.println("@attribute veter {" + zdruzi + "}");
zdruzi = "";
zdruzi = zdruzi + moznost_padavin[0];
for (int i=1; i<moznost_padavin.length; i++){
if (i<moznost_padavin.length)
zdruzi = zdruzi + ",";
zdruzi = zdruzi + moznost_padavin[i];
}
System.out.println("@attribute moznost_padavin {" + zdruzi + "}" + "\n" +
"\n" + "@data");
Random r = new Random();
for (int i=0; i<2000; i++){
temperatura = r.nextInt(35);
System.out.println(opis[r.nextInt(opis.length)] + "," + temperatura +
"," + veter[r.nextInt(veter.length)] + "," + moznost_padavin[r.nextInt(moznost_padavin.length)]);
}
}
}
| false | true | public static void main(String[] args) throws Exception {
System.out.println("@relation vreme" + "\n");
String[] opis = {"hladno", "toplo", "vetrovno", "de�evno", "sne�i"};
int temperatura = 0;
String[] veter = {"0", "5", "10", "20", "50"};
String[] moznost_padavin = {"0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"};
String zdruzi = "";
zdruzi = zdruzi + opis[0];
for (int i=0; i<opis.length; i++){
if (i<opis.length)
zdruzi = zdruzi + ",";
zdruzi = zdruzi + opis[i];
}
System.out.println("@attribute opis {" + zdruzi + "}");
System.out.println("@attribute temperatura NUMERIC");
zdruzi = "";
zdruzi = zdruzi + veter[0];
for (int i=0; i<veter.length; i++){
if (i<veter.length)
zdruzi = zdruzi + ",";
zdruzi = zdruzi + veter[i];
}
System.out.println("@attribute veter {" + zdruzi + "}");
zdruzi = "";
zdruzi = zdruzi + moznost_padavin[0];
for (int i=1; i<moznost_padavin.length; i++){
if (i<moznost_padavin.length)
zdruzi = zdruzi + ",";
zdruzi = zdruzi + moznost_padavin[i];
}
System.out.println("@attribute moznost_padavin {" + zdruzi + "}" + "\n" +
"\n" + "@data");
Random r = new Random();
for (int i=0; i<2000; i++){
temperatura = r.nextInt(35);
System.out.println(opis[r.nextInt(opis.length)] + "," + temperatura +
"," + veter[r.nextInt(veter.length)] + "," + moznost_padavin[r.nextInt(moznost_padavin.length)]);
}
}
| public static void main(String[] args) throws Exception {
System.out.println("@relation vreme" + "\n");
String[] opis = {"hladno", "toplo", "vetrovno", "de�evno", "sne�i"};
int temperatura = 0;
String[] veter = {"0", "5", "10", "20", "50"};
String[] moznost_padavin = {"0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"};
String zdruzi = "";
zdruzi = zdruzi + opis[0];
for (int i=1; i<opis.length; i++){
if (i<opis.length)
zdruzi = zdruzi + ",";
zdruzi = zdruzi + opis[i];
}
System.out.println("@attribute opis {" + zdruzi + "}");
System.out.println("@attribute temperatura NUMERIC");
zdruzi = "";
zdruzi = zdruzi + veter[0];
for (int i=1; i<veter.length; i++){
if (i<veter.length)
zdruzi = zdruzi + ",";
zdruzi = zdruzi + veter[i];
}
System.out.println("@attribute veter {" + zdruzi + "}");
zdruzi = "";
zdruzi = zdruzi + moznost_padavin[0];
for (int i=1; i<moznost_padavin.length; i++){
if (i<moznost_padavin.length)
zdruzi = zdruzi + ",";
zdruzi = zdruzi + moznost_padavin[i];
}
System.out.println("@attribute moznost_padavin {" + zdruzi + "}" + "\n" +
"\n" + "@data");
Random r = new Random();
for (int i=0; i<2000; i++){
temperatura = r.nextInt(35);
System.out.println(opis[r.nextInt(opis.length)] + "," + temperatura +
"," + veter[r.nextInt(veter.length)] + "," + moznost_padavin[r.nextInt(moznost_padavin.length)]);
}
}
|
diff --git a/bw-calendar-client-webcommon/src/main/java/org/bedework/webcommon/event/SuggestAction.java b/bw-calendar-client-webcommon/src/main/java/org/bedework/webcommon/event/SuggestAction.java
index a5a1e7b..500412f 100644
--- a/bw-calendar-client-webcommon/src/main/java/org/bedework/webcommon/event/SuggestAction.java
+++ b/bw-calendar-client-webcommon/src/main/java/org/bedework/webcommon/event/SuggestAction.java
@@ -1,152 +1,152 @@
/* ********************************************************************
Licensed to Jasig under one or more contributor license
agreements. See the NOTICE file distributed with this work
for additional information regarding copyright ownership.
Jasig licenses this file to you under the Apache License,
Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a
copy of the License at:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.bedework.webcommon.event;
import org.bedework.appcommon.ClientError;
import org.bedework.appcommon.client.Client;
import org.bedework.calfacade.BwCategory;
import org.bedework.calfacade.BwEvent;
import org.bedework.calfacade.BwXproperty;
import org.bedework.calfacade.RecurringRetrievalMode.Rmode;
import org.bedework.calfacade.exc.CalFacadeException;
import org.bedework.calfacade.svc.EventInfo;
import org.bedework.util.misc.Util;
import org.bedework.webcommon.BwActionFormBase;
import org.bedework.webcommon.BwRequest;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;
/**
* Action to update suggest status for an event
* <p>Request parameters:<ul>
* <li> colPath - collection href</li>.
* <li> eventName - name for event</li>.
* <li> accept | reject - only one must be present </li>.
* </ul>
* <p>Errors:<ul>
* <li>org.bedework.error.noaccess </li>
* <li>org.bedework.error.not.suggested - when
* not a suggested event</li>
* </ul>
*/
public class SuggestAction extends EventActionBase {
@Override
public int doAction(final BwRequest request,
final BwActionFormBase form) throws Throwable {
final Client cl = request.getClient();
final HttpServletResponse response = request.getResponse();
/** Check access
*/
final boolean publicAdmin = cl.getPublicAdmin();
if (cl.isGuest() || !publicAdmin || !form.getCurUserApproverUser()) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return forwardNull;
}
- final EventInfo ei = findEvent(request, Rmode.entityOnly);
+ final EventInfo ei = findEvent(request, Rmode.overrides);
if (ei == null) {
// Do nothing
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return forwardNull;
}
final BwEvent ev = ei.getEvent();
final boolean accept = request.present("accept");
final boolean reject = request.present("reject");
if ((reject && accept) || (!reject && !accept)) {
form.getErr().emit(ClientError.badRequest);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return forwardNull;
}
final String csHref = form.getCurrentCalSuite().getGroup().getPrincipalRef();
final List<BwXproperty> props =
ev.getXproperties(BwXproperty.bedeworkSuggestedTo);
if (Util.isEmpty(props)) {
form.getErr().emit(ClientError.notSuggested);
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return forwardNull;
}
BwXproperty theProp = null;
for (final BwXproperty prop: props) {
if (prop.getValue().substring(2).equals(csHref)) {
theProp = prop;
break;
}
}
if (theProp == null) {
form.getErr().emit(ClientError.notSuggested);
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return forwardNull;
}
String newStatus;
if (accept) {
newStatus = "A";
} else {
newStatus = "R";
}
newStatus+= ":" + csHref;
if (newStatus.equals(theProp.getValue())) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return forwardNull;
}
theProp.setValue(newStatus);
final Set<String> catuids = cl.getPreferences().getDefaultCategoryUids();
for (final String uid: catuids) {
- final BwCategory cat = cl.getCategory(uid);
+ final BwCategory cat = cl.getPersistentCategory(uid);
if (cat != null) {
if (accept) {
ev.addCategory(cat);
} else {
ev.removeCategory(cat);
}
}
}
try {
cl.updateEvent(ei, true, null);
} catch (final CalFacadeException cfe) {
cl.rollback();
throw cfe;
}
response.setStatus(HttpServletResponse.SC_OK);
return forwardNull;
}
}
| false | true | public int doAction(final BwRequest request,
final BwActionFormBase form) throws Throwable {
final Client cl = request.getClient();
final HttpServletResponse response = request.getResponse();
/** Check access
*/
final boolean publicAdmin = cl.getPublicAdmin();
if (cl.isGuest() || !publicAdmin || !form.getCurUserApproverUser()) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return forwardNull;
}
final EventInfo ei = findEvent(request, Rmode.entityOnly);
if (ei == null) {
// Do nothing
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return forwardNull;
}
final BwEvent ev = ei.getEvent();
final boolean accept = request.present("accept");
final boolean reject = request.present("reject");
if ((reject && accept) || (!reject && !accept)) {
form.getErr().emit(ClientError.badRequest);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return forwardNull;
}
final String csHref = form.getCurrentCalSuite().getGroup().getPrincipalRef();
final List<BwXproperty> props =
ev.getXproperties(BwXproperty.bedeworkSuggestedTo);
if (Util.isEmpty(props)) {
form.getErr().emit(ClientError.notSuggested);
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return forwardNull;
}
BwXproperty theProp = null;
for (final BwXproperty prop: props) {
if (prop.getValue().substring(2).equals(csHref)) {
theProp = prop;
break;
}
}
if (theProp == null) {
form.getErr().emit(ClientError.notSuggested);
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return forwardNull;
}
String newStatus;
if (accept) {
newStatus = "A";
} else {
newStatus = "R";
}
newStatus+= ":" + csHref;
if (newStatus.equals(theProp.getValue())) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return forwardNull;
}
theProp.setValue(newStatus);
final Set<String> catuids = cl.getPreferences().getDefaultCategoryUids();
for (final String uid: catuids) {
final BwCategory cat = cl.getCategory(uid);
if (cat != null) {
if (accept) {
ev.addCategory(cat);
} else {
ev.removeCategory(cat);
}
}
}
try {
cl.updateEvent(ei, true, null);
} catch (final CalFacadeException cfe) {
cl.rollback();
throw cfe;
}
response.setStatus(HttpServletResponse.SC_OK);
return forwardNull;
}
| public int doAction(final BwRequest request,
final BwActionFormBase form) throws Throwable {
final Client cl = request.getClient();
final HttpServletResponse response = request.getResponse();
/** Check access
*/
final boolean publicAdmin = cl.getPublicAdmin();
if (cl.isGuest() || !publicAdmin || !form.getCurUserApproverUser()) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return forwardNull;
}
final EventInfo ei = findEvent(request, Rmode.overrides);
if (ei == null) {
// Do nothing
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return forwardNull;
}
final BwEvent ev = ei.getEvent();
final boolean accept = request.present("accept");
final boolean reject = request.present("reject");
if ((reject && accept) || (!reject && !accept)) {
form.getErr().emit(ClientError.badRequest);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return forwardNull;
}
final String csHref = form.getCurrentCalSuite().getGroup().getPrincipalRef();
final List<BwXproperty> props =
ev.getXproperties(BwXproperty.bedeworkSuggestedTo);
if (Util.isEmpty(props)) {
form.getErr().emit(ClientError.notSuggested);
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return forwardNull;
}
BwXproperty theProp = null;
for (final BwXproperty prop: props) {
if (prop.getValue().substring(2).equals(csHref)) {
theProp = prop;
break;
}
}
if (theProp == null) {
form.getErr().emit(ClientError.notSuggested);
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return forwardNull;
}
String newStatus;
if (accept) {
newStatus = "A";
} else {
newStatus = "R";
}
newStatus+= ":" + csHref;
if (newStatus.equals(theProp.getValue())) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return forwardNull;
}
theProp.setValue(newStatus);
final Set<String> catuids = cl.getPreferences().getDefaultCategoryUids();
for (final String uid: catuids) {
final BwCategory cat = cl.getPersistentCategory(uid);
if (cat != null) {
if (accept) {
ev.addCategory(cat);
} else {
ev.removeCategory(cat);
}
}
}
try {
cl.updateEvent(ei, true, null);
} catch (final CalFacadeException cfe) {
cl.rollback();
throw cfe;
}
response.setStatus(HttpServletResponse.SC_OK);
return forwardNull;
}
|
diff --git a/src/org/rsbot/event/impl/TWebStatus.java b/src/org/rsbot/event/impl/TWebStatus.java
index 7da0c54d..f57a37aa 100644
--- a/src/org/rsbot/event/impl/TWebStatus.java
+++ b/src/org/rsbot/event/impl/TWebStatus.java
@@ -1,26 +1,26 @@
package org.rsbot.event.impl;
import org.rsbot.event.listeners.TextPaintListener;
import org.rsbot.service.WebQueue;
import org.rsbot.util.StringUtil;
import java.awt.*;
/**
* Draws the web cache and cache writer information.
*
* @author Timer
*/
public class TWebStatus implements TextPaintListener {
public TWebStatus() {
}
public int drawLine(final Graphics render, int idx) {
- final String[] items = {"Web Queue", "Buffering: " + WebQueue.weAreBuffering + ", " + WebQueue.bufferingCount + " nodes.", "Speed Buffering: " + WebQueue.speedBuffer,
+ final String[] items = {"Web Queue", "Buffering: " + WebQueue.weAreBuffering + ", " + WebQueue.bufferingCount + " nodes.",
"Cache Writer", "Queue Size: " + WebQueue.queueSize(0), "Remove queue size: " + WebQueue.queueSize(1), "Removing queue size: " + WebQueue.queueSize(2)};
for (final String item : items) {
StringUtil.drawLine(render, idx++, item);
}
return idx;
}
}
| true | true | public int drawLine(final Graphics render, int idx) {
final String[] items = {"Web Queue", "Buffering: " + WebQueue.weAreBuffering + ", " + WebQueue.bufferingCount + " nodes.", "Speed Buffering: " + WebQueue.speedBuffer,
"Cache Writer", "Queue Size: " + WebQueue.queueSize(0), "Remove queue size: " + WebQueue.queueSize(1), "Removing queue size: " + WebQueue.queueSize(2)};
for (final String item : items) {
StringUtil.drawLine(render, idx++, item);
}
return idx;
}
| public int drawLine(final Graphics render, int idx) {
final String[] items = {"Web Queue", "Buffering: " + WebQueue.weAreBuffering + ", " + WebQueue.bufferingCount + " nodes.",
"Cache Writer", "Queue Size: " + WebQueue.queueSize(0), "Remove queue size: " + WebQueue.queueSize(1), "Removing queue size: " + WebQueue.queueSize(2)};
for (final String item : items) {
StringUtil.drawLine(render, idx++, item);
}
return idx;
}
|
diff --git a/Model/src/java/fr/cg95/cvq/service/request/SubjectIdCheck.java b/Model/src/java/fr/cg95/cvq/service/request/SubjectIdCheck.java
index e11e6d4e4..b052c6646 100644
--- a/Model/src/java/fr/cg95/cvq/service/request/SubjectIdCheck.java
+++ b/Model/src/java/fr/cg95/cvq/service/request/SubjectIdCheck.java
@@ -1,59 +1,62 @@
package fr.cg95.cvq.service.request;
import java.math.BigInteger;
import net.sf.oval.Validator;
import net.sf.oval.configuration.annotation.AbstractAnnotationCheck;
import net.sf.oval.context.OValContext;
import net.sf.oval.exception.OValException;
import fr.cg95.cvq.business.request.RequestData;
import fr.cg95.cvq.business.request.RequestState;
import fr.cg95.cvq.dao.hibernate.HibernateUtil;
import fr.cg95.cvq.exception.CvqException;
public class SubjectIdCheck extends AbstractAnnotationCheck<LocalReferential> {
private static final long serialVersionUID = 1L;
private static IRequestServiceRegistry requestServiceRegistry;
private static IRequestWorkflowService requestWorkflowService;
@Override
public boolean isSatisfied(Object validatedObject, Object valueToValidate, OValContext context,
Validator validator) throws OValException {
RequestData requestData = (RequestData)validatedObject;
if (requestData.getId() != null) {
BigInteger subjectId = (BigInteger)HibernateUtil.getSession()
.createSQLQuery("select subject_id from request where id = :id")
.setLong("id", requestData.getId()).uniqueResult();
if (subjectId != null) {
if (Long.valueOf(subjectId.longValue()).equals(valueToValidate)) {
return true;
} else if (!RequestState.DRAFT.equals(requestData.getState())) {
return false;
}
}
}
+ HibernateUtil.getSession().evict(requestData);
try {
requestWorkflowService.checkSubjectPolicy(
(Long)valueToValidate,
requestData.getHomeFolderId(),
requestServiceRegistry.getRequestService(requestData.getRequestType().getLabel())
.getSubjectPolicy(),
requestData.getRequestType()
);
return true;
} catch (CvqException e) {
return false;
+ } finally {
+ HibernateUtil.getSession().merge(requestData);
}
}
public static void setRequestServiceRegistry(IRequestServiceRegistry requestServiceRegistry) {
SubjectIdCheck.requestServiceRegistry = requestServiceRegistry;
}
public static void setRequestWorkflowService(IRequestWorkflowService requestWorkflowService) {
SubjectIdCheck.requestWorkflowService = requestWorkflowService;
}
}
| false | true | public boolean isSatisfied(Object validatedObject, Object valueToValidate, OValContext context,
Validator validator) throws OValException {
RequestData requestData = (RequestData)validatedObject;
if (requestData.getId() != null) {
BigInteger subjectId = (BigInteger)HibernateUtil.getSession()
.createSQLQuery("select subject_id from request where id = :id")
.setLong("id", requestData.getId()).uniqueResult();
if (subjectId != null) {
if (Long.valueOf(subjectId.longValue()).equals(valueToValidate)) {
return true;
} else if (!RequestState.DRAFT.equals(requestData.getState())) {
return false;
}
}
}
try {
requestWorkflowService.checkSubjectPolicy(
(Long)valueToValidate,
requestData.getHomeFolderId(),
requestServiceRegistry.getRequestService(requestData.getRequestType().getLabel())
.getSubjectPolicy(),
requestData.getRequestType()
);
return true;
} catch (CvqException e) {
return false;
}
}
| public boolean isSatisfied(Object validatedObject, Object valueToValidate, OValContext context,
Validator validator) throws OValException {
RequestData requestData = (RequestData)validatedObject;
if (requestData.getId() != null) {
BigInteger subjectId = (BigInteger)HibernateUtil.getSession()
.createSQLQuery("select subject_id from request where id = :id")
.setLong("id", requestData.getId()).uniqueResult();
if (subjectId != null) {
if (Long.valueOf(subjectId.longValue()).equals(valueToValidate)) {
return true;
} else if (!RequestState.DRAFT.equals(requestData.getState())) {
return false;
}
}
}
HibernateUtil.getSession().evict(requestData);
try {
requestWorkflowService.checkSubjectPolicy(
(Long)valueToValidate,
requestData.getHomeFolderId(),
requestServiceRegistry.getRequestService(requestData.getRequestType().getLabel())
.getSubjectPolicy(),
requestData.getRequestType()
);
return true;
} catch (CvqException e) {
return false;
} finally {
HibernateUtil.getSession().merge(requestData);
}
}
|
diff --git a/src/main/java/db/SubTaskDb.java b/src/main/java/db/SubTaskDb.java
index c40ecb8..7ebffef 100644
--- a/src/main/java/db/SubTaskDb.java
+++ b/src/main/java/db/SubTaskDb.java
@@ -1,406 +1,406 @@
package db;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import crowdtrust.Bee;
import crowdtrust.BinaryR;
import crowdtrust.MultiValueSubTask;
import crowdtrust.Response;
import crowdtrust.Estimate;
import crowdtrust.BinarySubTask;
import crowdtrust.SubTask;
import crowdtrust.Task;
public class SubTaskDb {
public static boolean close(int id) {
String sql = "UPDATE subtasks SET active = FALSE WHERE subtasks.id = ?";
try {
PreparedStatement preparedStatement = DbAdaptor.connect().prepareStatement(sql);
preparedStatement.setInt(1, id);
preparedStatement.execute();
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on subtask close: PSQL driver not present");
e.printStackTrace();
return false;
} catch (SQLException e) {
System.err.println("SQL Error on subtask close");
e.printStackTrace();
return false;
}
return true;
}
public static Task getTask(int id) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT * FROM tasks JOIN subtasks ON tasks.id = subtasks.task ");
sql.append("WHERE subtasks.id = ?");
try {
PreparedStatement preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
if(!resultSet.next()) {
//task does not exist, grave error TODO log it
System.err.println("Subtask: " + id + " doesn't exist");
return null;
}
return TaskDb.map(resultSet);
} catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on get Subtask: PSQL driver not present");
e.printStackTrace();
return null;
} catch (SQLException e) {
System.err.println("SQL Error on get Subtask");
e.printStackTrace();
return null;
}
}
public static Map<Integer, Response> getBinaryResponses(int id) {
HashMap<Integer,Response> responses = new HashMap <Integer,Response>();
StringBuilder sql = new StringBuilder();
sql.append("SELECT account, response");
sql.append("FROM responses");
sql.append("WHERE subtask = ?");
PreparedStatement preparedStatement;
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
preparedStatement.setInt(1, id);
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on check finished: PSQL driver not present");
e.printStackTrace();
return null;
} catch (SQLException e) {
System.err.println("SQL Error on check finished");
e.printStackTrace();
return null;
}
ResultSet resultSet;
try {
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
BinaryR br = new BinaryR(resultSet.getBytes("response"));
responses.put(resultSet.getInt("account"), br);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//FINISH THIS!
return null;
}
public static SubTask getRandomBinarySubTask(int task) {
String sql = "SELECT subtasks.id AS s, tasks.accuracy AS a, tasks.max_labels AS m, " +
"COUNT(responses.id) AS r FROM subtasks JOIN tasks ON subtasks.task = tasks.id " +
"LEFT JOIN responses ON responses.subtask = subtasks.id WHERE tasks.id = ? " +
"GROUP BY s,a,m ORDER BY random() LIMIT 1";
PreparedStatement preparedStatement;
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql);
preparedStatement.setInt(1, task);
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on check finished: PSQL driver not present");
e.printStackTrace();
return null;
} catch (SQLException e) {
System.err.println("SQL Error on check finished");
e.printStackTrace();
return null;
}
try {
ResultSet rs = preparedStatement.executeQuery();
rs.next();
int taskAccuracy = rs.getInt("a");
int id = rs.getInt("s");
int responses = rs.getInt("r");
int maxLabels = rs.getInt("m");
return new BinarySubTask(id, taskAccuracy, responses, maxLabels);
}
catch(SQLException e) {
e.printStackTrace();
}
return null;
}
public static List<String> getImageSubtasks() {
StringBuilder sql = new StringBuilder();
sql.append("SELECT tasks.id, subtasks.file_name, tasks.date_created, tasks.submitter FROM tasks JOIN subtasks ON tasks.id = subtasks.task ");
- sql.append("WHERE tasks.media_type=1 ORDER BY tasks.date_created DES");
+ sql.append("WHERE tasks.media_type=1 ORDER BY tasks.date_created DESC");
List<String> list = new LinkedList<String>();
PreparedStatement preparedStatement;
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on get Subtask: PSQL driver not present");
e.printStackTrace();
return list;
} catch (SQLException e) {
System.err.println("SQL Error on connection during get image subtask");
e.printStackTrace();
return list;
}
try {
preparedStatement.execute();
} catch (SQLException e1) {
e1.printStackTrace();
}
ResultSet resultSet;
try{
resultSet = preparedStatement.getResultSet();
} catch (SQLException e) {
System.err.println("problem executing stement");
e.printStackTrace();
return list;
}
try{
for (int i = 0 ; resultSet.next() && i < 5 ; i++) {
String subtask = resultSet.getString(2);
int task = resultSet.getInt(1);
int submitter = resultSet.getInt(1); // may be useful to display uname of uploader
list.add(task + "/" + subtask);
resultSet.next();
}
} catch(SQLException e) {
System.err.println("problem with result set");
e.printStackTrace();
}
return list;
}
public static boolean addSubtask(String filename, int taskID) {
String insertQuery = "INSERT INTO subtasks VALUES (DEFAULT,?,?,?)";
PreparedStatement stmt;
try {
stmt = DbAdaptor.connect().prepareStatement(insertQuery);
stmt.setInt(1, taskID);
stmt.setString(2, filename);
stmt.setBoolean(3, true);
stmt.execute();
} catch (SQLException e1) {
System.err.println("some error with task fields: taskID not valid?");
System.err.println("taskID: " + taskID + ", filename: " + filename);
e1.printStackTrace();
return false;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
public static Map<Integer, Response> getMultiValueResponses(int id) {
// TODO Auto-generated method stub
return null;
}
public static Map<Integer, Response> getContinuousResponses(int id) {
// TODO Auto-generated method stub
return null;
}
public static int getSubTaskId(String name){
StringBuilder sql = new StringBuilder();
sql.append("SELECT id FROM subtasks\n");
sql.append("WHERE file_name = ?");
PreparedStatement preparedStatement;
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
} catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on get Task: PSQL driver not present");
e.printStackTrace();
return -1;
} catch (SQLException e) {
System.err.println("SQL Error on get Task");
e.printStackTrace();
return -1;
}
try {
preparedStatement.setString(1, name);
ResultSet resultSet = preparedStatement.executeQuery();
resultSet.next();
return resultSet.getInt(1);
} catch (SQLException e) {
System.err.println("SELECT task query invalid");
e.printStackTrace();
return -1;
}
}
public static BinarySubTask getBinarySubTask(int subTaskId) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT subtasks.id AS s, tasks.accuracy AS a,");
sql.append("tasks.max_labels AS m, COUNT(responses.id) AS r ");
sql.append("FROM subtasks JOIN tasks ON subtasks.task = tasks.id ");
sql.append("LEFT JOIN responses ON responses.id ");
sql.append("WHERE subtasks.id = ? ");
sql.append("GROUP BY s,a,m ");
PreparedStatement preparedStatement;
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
preparedStatement.setInt(1, subTaskId);
} catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on check finished: PSQL driver not present");
e.printStackTrace();
return null;
} catch (SQLException e) {
System.err.println("SQL Error on check finished");
e.printStackTrace();
return null;
}
try {
ResultSet rs = preparedStatement.executeQuery();
int taskAccuracy = rs.getInt("a");
int id = rs.getInt("s");
int responses = rs.getInt("r");
int maxLabels = rs.getInt("m");
return new BinarySubTask(id, taskAccuracy, responses, maxLabels);
}
catch(SQLException e) {
e.printStackTrace();
}
return null;
}
public static MultiValueSubTask getMultiValueSubtask(int subTaskId) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT subtasks.id AS s, tasks.accuracy AS a,");
sql.append("tasks.max_labels AS m, ranged.finish AS o, COUNT(responses.id) AS r");
sql.append("FROM subtasks JOIN tasks ON subtasks.task = tasks.id");
sql.append("LEFT JOIN ranged ON subtasks.id = ranged.id");
sql.append("LEFT JOIN responses ON responses.id");
sql.append("WHERE subtasks.id = ?");
sql.append("GROUP BY s,a,m,o");
PreparedStatement preparedStatement;
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
preparedStatement.setInt(1, subTaskId);
} catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on check finished: PSQL driver not present");
e.printStackTrace();
return null;
} catch (SQLException e) {
System.err.println("SQL Error on check finished");
e.printStackTrace();
return null;
}
try {
ResultSet rs = preparedStatement.executeQuery();
int taskAccuracy = rs.getInt("a");
int id = rs.getInt("s");
int responses = rs.getInt("r");
int maxLabels = rs.getInt("m");
int options = rs.getInt("o");
return new MultiValueSubTask(id, taskAccuracy, responses, maxLabels, options);
}
catch(SQLException e) {
e.printStackTrace();
}
return null;
}
public static Collection<Estimate> getBinaryEstimates(int id) {
String sql = "SELECT estimate, confidence " +
"FROM estimates " +
"WHERE subtask_id = ?";
PreparedStatement preparedStatement;
ArrayList<Estimate> state = new ArrayList<Estimate>();
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql);
preparedStatement.setInt(1, id);
} catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on check finished: PSQL driver not present");
e.printStackTrace();
return null;
} catch (SQLException e) {
System.err.println("SQL Error on check finished");
e.printStackTrace();
return null;
}
try {
ResultSet rs = preparedStatement.executeQuery();
while(rs.next()){
BinaryR r = new BinaryR(rs.getBytes("estimate"));
double c = rs.getFloat("confidence");
state.add(new Estimate(r,c));
}
}
catch(SQLException e) {
e.printStackTrace();
}
return state;
}
public static void updateBinaryEstimates(Collection<Estimate> state, int id) {
String query = "UPDATE estimates SET confidence = ? " +
"WHERE subtask_id = ? AND estimate = ?";
PreparedStatement preparedStatement;
try {
preparedStatement = DbAdaptor.connect().prepareStatement(query);
for (Estimate e : state){
preparedStatement.setFloat(1, (float) e.getConfidence());
preparedStatement.setInt(2, id);
preparedStatement.setString(3, e.getR().serialise());
preparedStatement.addBatch();
}
preparedStatement.executeBatch();
} catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on check finished: PSQL driver not present");
e.printStackTrace();
} catch (SQLException e) {
System.err.println("SQL Error on check finished");
e.printStackTrace();
System.out.println("-------------------");
e.getNextException().printStackTrace();
}
}
public static void addBinaryEstimate(Estimate est, int id) {
String query = "INSERT INTO estimates VALUES (DEFAULT,?,?,?)";
PreparedStatement preparedStatement;
try {
preparedStatement = DbAdaptor.connect().prepareStatement(query);
preparedStatement.setFloat(1, (float) est.getConfidence());
preparedStatement.setString(2, est.getR().serialise());
preparedStatement.setInt(3, id);
preparedStatement.execute();
} catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on check finished: PSQL driver not present");
e.printStackTrace();
} catch (SQLException e) {
System.err.println("SQL Error on check finished");
e.printStackTrace();
}
}
}
| true | true | public static List<String> getImageSubtasks() {
StringBuilder sql = new StringBuilder();
sql.append("SELECT tasks.id, subtasks.file_name, tasks.date_created, tasks.submitter FROM tasks JOIN subtasks ON tasks.id = subtasks.task ");
sql.append("WHERE tasks.media_type=1 ORDER BY tasks.date_created DES");
List<String> list = new LinkedList<String>();
PreparedStatement preparedStatement;
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on get Subtask: PSQL driver not present");
e.printStackTrace();
return list;
} catch (SQLException e) {
System.err.println("SQL Error on connection during get image subtask");
e.printStackTrace();
return list;
}
try {
preparedStatement.execute();
} catch (SQLException e1) {
e1.printStackTrace();
}
ResultSet resultSet;
try{
resultSet = preparedStatement.getResultSet();
} catch (SQLException e) {
System.err.println("problem executing stement");
e.printStackTrace();
return list;
}
try{
for (int i = 0 ; resultSet.next() && i < 5 ; i++) {
String subtask = resultSet.getString(2);
int task = resultSet.getInt(1);
int submitter = resultSet.getInt(1); // may be useful to display uname of uploader
list.add(task + "/" + subtask);
resultSet.next();
}
} catch(SQLException e) {
System.err.println("problem with result set");
e.printStackTrace();
}
return list;
}
| public static List<String> getImageSubtasks() {
StringBuilder sql = new StringBuilder();
sql.append("SELECT tasks.id, subtasks.file_name, tasks.date_created, tasks.submitter FROM tasks JOIN subtasks ON tasks.id = subtasks.task ");
sql.append("WHERE tasks.media_type=1 ORDER BY tasks.date_created DESC");
List<String> list = new LinkedList<String>();
PreparedStatement preparedStatement;
try {
preparedStatement = DbAdaptor.connect().prepareStatement(sql.toString());
}
catch (ClassNotFoundException e) {
System.err.println("Error connecting to DB on get Subtask: PSQL driver not present");
e.printStackTrace();
return list;
} catch (SQLException e) {
System.err.println("SQL Error on connection during get image subtask");
e.printStackTrace();
return list;
}
try {
preparedStatement.execute();
} catch (SQLException e1) {
e1.printStackTrace();
}
ResultSet resultSet;
try{
resultSet = preparedStatement.getResultSet();
} catch (SQLException e) {
System.err.println("problem executing stement");
e.printStackTrace();
return list;
}
try{
for (int i = 0 ; resultSet.next() && i < 5 ; i++) {
String subtask = resultSet.getString(2);
int task = resultSet.getInt(1);
int submitter = resultSet.getInt(1); // may be useful to display uname of uploader
list.add(task + "/" + subtask);
resultSet.next();
}
} catch(SQLException e) {
System.err.println("problem with result set");
e.printStackTrace();
}
return list;
}
|
diff --git a/core/src/visad/trunk/data/visad/object/BinaryDataArray.java b/core/src/visad/trunk/data/visad/object/BinaryDataArray.java
index de6f89540..0546b3292 100644
--- a/core/src/visad/trunk/data/visad/object/BinaryDataArray.java
+++ b/core/src/visad/trunk/data/visad/object/BinaryDataArray.java
@@ -1,86 +1,86 @@
package visad.data.visad.object;
import java.io.DataInput;
import java.io.DataOutputStream;
import java.io.IOException;
import visad.Data;
import visad.DataImpl;
import visad.VisADException;
import visad.data.visad.BinaryReader;
import visad.data.visad.BinaryWriter;
public class BinaryDataArray
implements BinaryObject
{
public static final int computeBytes(Data[] array)
{
int len = 4;
for (int i = 0; i < array.length; i++) {
len += BinaryGeneric.computeBytes((DataImpl )array[i]);
}
return len;
}
public static final Data[] read(BinaryReader reader)
throws IOException, VisADException
{
DataInput file = reader.getInput();
final int len = file.readInt();
if(DEBUG_RD_DATA)System.err.println("rdDataRA: len (" + len + ")");
if (len < 1) {
throw new IOException("Corrupted file (bad Data array length " +
len + ")");
}
long t = (DEBUG_RD_TIME ? System.currentTimeMillis() : 0);
Data[] array = new Data[len];
for (int i = 0; i < len; i++) {
if(DEBUG_WR_DATA)System.err.println("rdDataRA#"+i);
array[i] = BinaryGeneric.read(reader);
if(DEBUG_WR_DATA_DETAIL)System.err.println("rdDataRA: #" + i + " (" + array[i] + ")");
if(DEBUG_WR_DATA)System.err.println("rdDataRA#"+i+": "+array[i].getClass().getName());
}
-if(DEBUG_RD_TIME)System.err.println("rdDataRA: "+len+" arrays "+(System.currentTimeMillis()-t));
+if(DEBUG_RD_TIME)System.err.println("rdDataRA: "+len+" elements "+(System.currentTimeMillis()-t));
return array;
}
private static final void writeDependentData(BinaryWriter writer,
Data[] array)
throws IOException
{
if (array != null) {
for (int i = 0; i < array.length; i++) {
BinaryGeneric.write(writer, (DataImpl )array[i], SAVE_DEPEND);
}
}
}
public static final void write(BinaryWriter writer, Data[] array,
Object token)
throws IOException
{
writeDependentData(writer, array);
// if we only want to write dependent data, we're done
if (token == SAVE_DEPEND) {
return;
}
DataOutputStream file = writer.getOutputStream();
if(DEBUG_WR_DATA)System.err.println("wrDataRA: len (" + array.length + ")");
file.writeInt(array.length);
for (int i = 0; i < array.length; i++) {
if(DEBUG_WR_DATA_DETAIL)System.err.println("wrDataRA: #" + i + " (" + array[i] + ")");
if(DEBUG_WR_DATA)System.err.println("wrDataRA#"+i+": "+array[i].getClass().getName());
BinaryGeneric.write(writer, (DataImpl )array[i], token);
}
}
}
| true | true | public static final Data[] read(BinaryReader reader)
throws IOException, VisADException
{
DataInput file = reader.getInput();
final int len = file.readInt();
if(DEBUG_RD_DATA)System.err.println("rdDataRA: len (" + len + ")");
if (len < 1) {
throw new IOException("Corrupted file (bad Data array length " +
len + ")");
}
long t = (DEBUG_RD_TIME ? System.currentTimeMillis() : 0);
Data[] array = new Data[len];
for (int i = 0; i < len; i++) {
if(DEBUG_WR_DATA)System.err.println("rdDataRA#"+i);
array[i] = BinaryGeneric.read(reader);
if(DEBUG_WR_DATA_DETAIL)System.err.println("rdDataRA: #" + i + " (" + array[i] + ")");
if(DEBUG_WR_DATA)System.err.println("rdDataRA#"+i+": "+array[i].getClass().getName());
}
if(DEBUG_RD_TIME)System.err.println("rdDataRA: "+len+" arrays "+(System.currentTimeMillis()-t));
return array;
}
| public static final Data[] read(BinaryReader reader)
throws IOException, VisADException
{
DataInput file = reader.getInput();
final int len = file.readInt();
if(DEBUG_RD_DATA)System.err.println("rdDataRA: len (" + len + ")");
if (len < 1) {
throw new IOException("Corrupted file (bad Data array length " +
len + ")");
}
long t = (DEBUG_RD_TIME ? System.currentTimeMillis() : 0);
Data[] array = new Data[len];
for (int i = 0; i < len; i++) {
if(DEBUG_WR_DATA)System.err.println("rdDataRA#"+i);
array[i] = BinaryGeneric.read(reader);
if(DEBUG_WR_DATA_DETAIL)System.err.println("rdDataRA: #" + i + " (" + array[i] + ")");
if(DEBUG_WR_DATA)System.err.println("rdDataRA#"+i+": "+array[i].getClass().getName());
}
if(DEBUG_RD_TIME)System.err.println("rdDataRA: "+len+" elements "+(System.currentTimeMillis()-t));
return array;
}
|
diff --git a/src/edu/ucla/loni/server/FileServiceImpl.java b/src/edu/ucla/loni/server/FileServiceImpl.java
index 666e45b..4b0b9d6 100644
--- a/src/edu/ucla/loni/server/FileServiceImpl.java
+++ b/src/edu/ucla/loni/server/FileServiceImpl.java
@@ -1,519 +1,519 @@
package edu.ucla.loni.server;
import edu.ucla.loni.client.FileService;
import edu.ucla.loni.shared.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Timestamp;
import java.util.ArrayList;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.jdom2.Document;
@SuppressWarnings("serial")
public class FileServiceImpl extends RemoteServiceServlet implements FileService {
////////////////////////////////////////////////////////////
// Private Functions
////////////////////////////////////////////////////////////
/**
* Returns returns an ArrayList of all the pipefiles in the root directory
* Note: this functions only search two levels in
*
* @param dir, file representing root directory
*/
private ArrayList<File> getAllPipefiles(File dir){
// Level == 2, dir == root directory
// Level == 1, dir == package folder
// Level == 0, dir == type folder (do not look go any deeper)
return getAllPipefilesRecursive(dir, 2);
}
/**
* Recursively get all pipefiles
*/
private ArrayList<File> getAllPipefilesRecursive(File dir, int level){
ArrayList<File> files = new ArrayList<File>();
for (File file : dir.listFiles()){
if (file.isDirectory() && level > 0){
files.addAll( getAllPipefilesRecursive(file, (level - 1)) );
}
else {
String name = file.getName();
if (name.endsWith(".pipe")){
files.add(file);
}
}
}
return files;
}
/**
* Remove files from the database in the case that they were deleted
*/
private void cleanDatabase(Directory root) throws Exception{
Pipefile[] pipes = Database.selectPipefiles(root.dirId);
if (pipes != null){
for(Pipefile pipe : pipes){
File file = new File(pipe.absolutePath);
if (!file.exists()){
Database.deletePipefile(pipe);
}
}
}
}
/**
* Update the database for this root
*/
private void updateDatabase(Directory root) throws Exception {
// Clean the database
cleanDatabase(root);
// Get all the files
File rootDir = new File(root.absolutePath);
ArrayList<File> files = getAllPipefiles(rootDir);
// For each pipefile
for (File file : files){
Timestamp db_lastModified = Database.selectPipefileLastModified(file.getAbsolutePath());
// Determine if the row needs to be updated or inserted
boolean update = false;
boolean insert = false;
Timestamp fs_lastModified = new Timestamp(file.lastModified());
if (db_lastModified != null){
// If file has been modified
if ( !db_lastModified.equals(fs_lastModified) ){
update = true;
}
}
else {
insert = true;
}
// If we need to update or insert a row
if (update || insert){
Pipefile pipe = ServerUtils.parseXML(file);
pipe.lastModified = fs_lastModified;
if (insert){
Database.insertPipefile(root.dirId, pipe);
} else {
pipe.fileId = Database.selectPipefileId(file.getAbsolutePath());
Database.updatePipefile(pipe);
}
}
}
}
private void updateMonitorAndAccessFile(Directory root) throws Exception{
ServerUtils.touchMonitorFile(root);
ServerUtils.writeAccessFile(root);
}
/**
* Removes a file from the server
* @param filename absolute path of the file
*/
private void removeFile(Directory root, Pipefile pipe) throws Exception {
File f = new File(pipe.absolutePath);
if (f.exists()){
// Delete file on file-system
boolean success = f.delete();
if (!success){
throw new Exception("Failed to remove file " + pipe.absolutePath);
}
// Remove parent directory if it is empty
ServerUtils.removeEmptyDirectory(f.getParentFile());
// Delete file from database
Database.deletePipefile(pipe);
}
}
/**
* Copy a file from the server to the proper package
* @param filename absolute path of the file
* @param packageName absolute path of the package
*/
private void copyFile(Directory root, Pipefile pipe, String packageName) throws Exception {
copyOrMoveFile(root, pipe, packageName, true);
}
/**
* Move a file to another package
* @param filename absolute path of the file = source path of file
* @param packageName is the name of the package as it appears in the Database in column PACKAGENAME
* @throws Exception
*/
public void moveFile(Directory root, Pipefile pipe, String packageName) throws Exception{
copyOrMoveFile(root, pipe, packageName, false);
}
private void copyOrMoveFile(Directory root, Pipefile pipe, String packageName, boolean copy) throws Exception{
// Source
String oldAbsolutePath = pipe.absolutePath;
File src = new File(oldAbsolutePath);
// If the source does not exist
if (!src.exists()) {
throw new Exception("Soruce file does not exist");
}
// Destination
String destPath = ServerUtils.newAbsolutePath(root.absolutePath, packageName, pipe.type, pipe.name);
File dest = new File(destPath);
//check for duplicate file existence
//if duplicate exists, than above function "newAbsolutePath" will create new unique name of the form pipe.name + "_(" + INTEGERE + ")"
//in that case we also have to update name inside pipe class so that both Database and client's tree of pipefiles will correctly reflect
//new pipefile duplicate
- if( dest.getName().replaceAll(".pipe", "") != pipe.name )
- pipe.name = dest.getName().replaceAll(".pipe", "");
+ if( destPath.contains("_(") && destPath.contains(")") && destPath.lastIndexOf(")") > destPath.lastIndexOf("_(") )
+ pipe.name = pipe.name + "_(" + destPath.substring(destPath.lastIndexOf("_(") + 2, destPath.lastIndexOf(")")) + ")";
// If the destination directory does not exist, create it and necessary parent directories
File destDir = dest.getParentFile();
if (!destDir.exists()){
boolean success = destDir.mkdirs();
if (!success){
throw new Exception("Destination folders could not be created");
}
}
// Copy or Move the file
if (copy){
FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dest);
int length = 0;
byte[] buffer = new byte[8192];
while ((length = in.read(buffer)) != -1){
out.write(buffer, 0, length);
}
in.close();
out.flush();
out.close();
}
else {
boolean success = src.renameTo(dest);
if(!success) {
throw new Exception("File could not be moved");
}
}
// Remove parent directory if it is empty
ServerUtils.removeEmptyDirectory(src.getParentFile());
// Update Pipefile
pipe.packageName = packageName;
pipe.absolutePath = destPath;
// Update XML
Document doc = ServerUtils.readXML(dest);
doc = ServerUtils.updateXML(doc, pipe, true);
ServerUtils.writeXML(dest, doc);
// Update Database
pipe.lastModified = new Timestamp(dest.lastModified());
if (copy) {
Database.insertPipefile(root.dirId, pipe);
}
else {
Database.updatePipefile(pipe);
}
}
////////////////////////////////////////////////////////////
// Public Functions
////////////////////////////////////////////////////////////
/**
* Returns a FileTree that represents the root directory
* <br>
* Thus the children are the packages
* @param root the absolute path of the root directory
*/
public Directory getDirectory(String absolutePath) throws Exception {
try {
File rootDir = new File(absolutePath);
if (rootDir.exists() && rootDir.isDirectory()){
Directory root = Database.selectDirectory(rootDir.getAbsolutePath());
if (root == null){
// Get the time the monitor file was modified
Timestamp monitorModified = null;
File monitor = new File(absolutePath + File.separator + ".monitorfile");
if (monitor.exists()){
monitorModified = new Timestamp(monitor.lastModified());
}
// Get the time the access file was modified
Timestamp accessModified = null;
File access = new File(absolutePath + File.separator + ".access.xml");
if (access.exists()){
accessModified = new Timestamp(access.lastModified());
}
Database.insertDirectory(rootDir.getAbsolutePath(), monitorModified, accessModified);
root = Database.selectDirectory(rootDir.getAbsolutePath());
}
return root;
}
else {
return null;
}
}
catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
}
/**
* Returns a FileTree that represents the root directory
* <br>
* Thus the children are the packages
* @param root the absolute path of the root directory
*/
public Pipefile[] getFiles(Directory root) throws Exception {
try {
// Check monitorFile and if needed update the database
Timestamp monitorModified = null;
File monitorFile = ServerUtils.getMonitorFile(root);
if (monitorFile.exists()){
monitorModified = new Timestamp(monitorFile.lastModified());
}
if (monitorModified != null){
if (!monitorModified.equals(root.monitorModified)){
root.monitorModified = monitorModified;
Database.updateDirectory(root);
updateDatabase(root);
}
}
// Check accessFile and read or write it
Timestamp accessModified = null;
File accessFile = ServerUtils.getAccessFile(root);
if (accessFile.exists()){
accessModified = new Timestamp(accessFile.lastModified());
}
if (accessModified != null && !accessModified.equals(root.accessModified)){
ServerUtils.readAccessFile(root);
} else {
ServerUtils.writeAccessFile(root);
}
// Return all the pipefiles
return Database.selectPipefiles(root.dirId);
}
catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
}
/**
* Returns a FileTree where the children are all files and are the search results
* @param root the absolute path of the root directory
* @param query what the user is searching for
*/
public Pipefile[] getSearchResults(Directory root, String query) throws Exception{
try {
return Database.selectPipefilesSearch(root.dirId, query);
}
catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
}
/**
* Updates the file on the server
* @param pipe Pipefile representing the updated file
*/
public void updateFile(Directory root, Pipefile pipe) throws Exception{
try {
File file = new File(pipe.absolutePath);
// Update the XML
Document doc = ServerUtils.readXML(file);
doc = ServerUtils.updateXML(doc, pipe, false);
ServerUtils.writeXML(file, doc);
// Update the filename if the name changed
if (pipe.nameUpdated || pipe.packageUpdated){
String destPath = ServerUtils.newAbsolutePath(root.absolutePath, pipe.packageName, pipe.type, pipe.name);
File dest = new File(destPath);
// Create parent folders if needed
File destDir = dest.getParentFile();
if (!destDir.exists()){
boolean success = destDir.mkdirs();
if (!success){
throw new Exception("Destination folders could not be created");
}
}
// Move the file
boolean success = file.renameTo(dest);
if(!success) {
throw new Exception("Failed to rename file");
}
// Remove parent directory if it is empty
ServerUtils.removeEmptyDirectory(file.getParentFile());
// Update file and absolutePath
file = dest;
pipe.absolutePath = destPath;
}
// Update the database
pipe.lastModified = new Timestamp(file.lastModified());
Database.updatePipefile(pipe);
// Update monitor and access files
updateMonitorAndAccessFile(root);
}
catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
}
/**
* Removes files from the server
* @param filenames absolute paths of the files
* @throws SQLException
*/
public void removeFiles(Directory root, Pipefile[] pipes) throws Exception {
try {
// Remove each file
for (Pipefile pipe : pipes) {
removeFile(root, pipe);
}
// Update monitor and access files
updateMonitorAndAccessFile(root);
}
catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
}
/**
* Copies files from the server to the proper package
* @param filenames absolute paths of the files
* @param packageName absolute path of the package
*/
public void copyFiles(Directory root, Pipefile[] pipes, String packageName) throws Exception {
try {
// Copy each file
for (Pipefile pipe : pipes) {
copyFile(root, pipe, packageName);
}
// Update monitor and access files
updateMonitorAndAccessFile(root);
}
catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
}
/**
* Moves files from the server to the proper package
* @param filenames absolute paths of the files
* @param packageName absolute path of the package
* @throws Exception
*/
public void moveFiles(Directory root, Pipefile[] pipes, String packageName) throws Exception{
try {
// Move each file
for (Pipefile pipe : pipes) {
moveFile(root, pipe, packageName);
}
// Update monitor and access files
updateMonitorAndAccessFile(root);
}
catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
}
/**
* Returns an array of all the groups
*/
public Group[] getGroups(Directory root) throws Exception {
try {
return Database.selectGroups(root.dirId);
}
catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
}
/**
* Inserts or Updates a group on the server (also used for creating groups)
* @param group group to be updated
*/
public void updateGroup(Directory root, Group group) throws Exception{
try {
// Insert or update the group
if (group.groupId == -1){
Database.insertGroup(root.dirId, group);
} else {
Database.updateGroup(group);
}
// Write the access file
ServerUtils.writeAccessFile(root);
}
catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
}
/**
* Deletes groups on the server (also used for creating groups)
* @param group group to be updated
*/
public void removeGroups(Directory root, Group[] groups) throws Exception{
try {
// Delete each group
for (Group group: groups){
Database.deleteGroup(group);
}
// Write the access file
ServerUtils.writeAccessFile(root);
}
catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage());
}
}
}
| true | true | private void copyOrMoveFile(Directory root, Pipefile pipe, String packageName, boolean copy) throws Exception{
// Source
String oldAbsolutePath = pipe.absolutePath;
File src = new File(oldAbsolutePath);
// If the source does not exist
if (!src.exists()) {
throw new Exception("Soruce file does not exist");
}
// Destination
String destPath = ServerUtils.newAbsolutePath(root.absolutePath, packageName, pipe.type, pipe.name);
File dest = new File(destPath);
//check for duplicate file existence
//if duplicate exists, than above function "newAbsolutePath" will create new unique name of the form pipe.name + "_(" + INTEGERE + ")"
//in that case we also have to update name inside pipe class so that both Database and client's tree of pipefiles will correctly reflect
//new pipefile duplicate
if( dest.getName().replaceAll(".pipe", "") != pipe.name )
pipe.name = dest.getName().replaceAll(".pipe", "");
// If the destination directory does not exist, create it and necessary parent directories
File destDir = dest.getParentFile();
if (!destDir.exists()){
boolean success = destDir.mkdirs();
if (!success){
throw new Exception("Destination folders could not be created");
}
}
// Copy or Move the file
if (copy){
FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dest);
int length = 0;
byte[] buffer = new byte[8192];
while ((length = in.read(buffer)) != -1){
out.write(buffer, 0, length);
}
in.close();
out.flush();
out.close();
}
else {
boolean success = src.renameTo(dest);
if(!success) {
throw new Exception("File could not be moved");
}
}
// Remove parent directory if it is empty
ServerUtils.removeEmptyDirectory(src.getParentFile());
// Update Pipefile
pipe.packageName = packageName;
pipe.absolutePath = destPath;
// Update XML
Document doc = ServerUtils.readXML(dest);
doc = ServerUtils.updateXML(doc, pipe, true);
ServerUtils.writeXML(dest, doc);
// Update Database
pipe.lastModified = new Timestamp(dest.lastModified());
if (copy) {
Database.insertPipefile(root.dirId, pipe);
}
else {
Database.updatePipefile(pipe);
}
}
| private void copyOrMoveFile(Directory root, Pipefile pipe, String packageName, boolean copy) throws Exception{
// Source
String oldAbsolutePath = pipe.absolutePath;
File src = new File(oldAbsolutePath);
// If the source does not exist
if (!src.exists()) {
throw new Exception("Soruce file does not exist");
}
// Destination
String destPath = ServerUtils.newAbsolutePath(root.absolutePath, packageName, pipe.type, pipe.name);
File dest = new File(destPath);
//check for duplicate file existence
//if duplicate exists, than above function "newAbsolutePath" will create new unique name of the form pipe.name + "_(" + INTEGERE + ")"
//in that case we also have to update name inside pipe class so that both Database and client's tree of pipefiles will correctly reflect
//new pipefile duplicate
if( destPath.contains("_(") && destPath.contains(")") && destPath.lastIndexOf(")") > destPath.lastIndexOf("_(") )
pipe.name = pipe.name + "_(" + destPath.substring(destPath.lastIndexOf("_(") + 2, destPath.lastIndexOf(")")) + ")";
// If the destination directory does not exist, create it and necessary parent directories
File destDir = dest.getParentFile();
if (!destDir.exists()){
boolean success = destDir.mkdirs();
if (!success){
throw new Exception("Destination folders could not be created");
}
}
// Copy or Move the file
if (copy){
FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dest);
int length = 0;
byte[] buffer = new byte[8192];
while ((length = in.read(buffer)) != -1){
out.write(buffer, 0, length);
}
in.close();
out.flush();
out.close();
}
else {
boolean success = src.renameTo(dest);
if(!success) {
throw new Exception("File could not be moved");
}
}
// Remove parent directory if it is empty
ServerUtils.removeEmptyDirectory(src.getParentFile());
// Update Pipefile
pipe.packageName = packageName;
pipe.absolutePath = destPath;
// Update XML
Document doc = ServerUtils.readXML(dest);
doc = ServerUtils.updateXML(doc, pipe, true);
ServerUtils.writeXML(dest, doc);
// Update Database
pipe.lastModified = new Timestamp(dest.lastModified());
if (copy) {
Database.insertPipefile(root.dirId, pipe);
}
else {
Database.updatePipefile(pipe);
}
}
|
diff --git a/src/main/java/com/mollom/client/MollomClient.java b/src/main/java/com/mollom/client/MollomClient.java
index 07a446a..49cfbf7 100644
--- a/src/main/java/com/mollom/client/MollomClient.java
+++ b/src/main/java/com/mollom/client/MollomClient.java
@@ -1,604 +1,604 @@
package com.mollom.client;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Primary interaction point with all of the Mollom services.
*/
public class MollomClient {
private final static Logger logger = Logger.getLogger("com.mollom.client.MollomClient");
private final Client client;
private final int retries;
private final Unmarshaller unmarshaller;
private final DocumentBuilder documentBuilder;
private final WebResource contentResource;
private final WebResource captchaResource;
private final WebResource feedbackResource;
private final WebResource blacklistResource;
private final WebResource whitelistResource;
/**
* Constructs a new MollomClient instance.
*
* MollomClient instances are expensive resources. It is recommended to share
* a single MollomClient instance between multiple threads. Requests and
* responses are guaranteed to be thread-safe.
*/
MollomClient(Client client, WebResource contentResource, WebResource captchaResource,
WebResource feedbackResource, WebResource blacklistResource,
WebResource whitelistResource, int retries) {
this.client = client;
this.contentResource = contentResource;
this.captchaResource = captchaResource;
this.feedbackResource = feedbackResource;
this.blacklistResource = blacklistResource;
this.whitelistResource = whitelistResource;
this.retries = retries;
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Content.class, Captcha.class, BlacklistEntry.class, WhitelistEntry.class);
this.unmarshaller = jaxbContext.createUnmarshaller();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
this.documentBuilder = documentBuilderFactory.newDocumentBuilder();
} catch (JAXBException | ParserConfigurationException e) {
throw new MollomConfigurationException("Failed to initialize MollomClient.", e);
}
}
/**
* Checks content.
*
* Injects the Mollom classification scores into the given Content object.
*/
public void checkContent(Content content)
throws MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
MultivaluedMap<String, String> postParams = new MultivaluedMapImpl();
if (content.getAuthorIp() != null) {
postParams.putSingle("authorIp", content.getAuthorIp());
}
if (content.getAuthorId() != null) {
postParams.putSingle("authorId", content.getAuthorId());
}
if (content.getAuthorOpenIds() != null) {
// Exception: authorOpenID is the only API parameter that accepts multiple
// values as a space-separated list.
String openIds = "";
for (String authorOpenId : content.getAuthorOpenIds()) {
openIds += authorOpenId += " ";
}
postParams.putSingle("authorOpenid", openIds);
}
if (content.getAuthorName() != null) {
postParams.putSingle("authorName", content.getAuthorName());
}
if (content.getAuthorMail() != null) {
postParams.putSingle("authorMail", content.getAuthorMail());
}
if (content.getAuthorUrl() != null) {
postParams.putSingle("authorUrl", content.getAuthorUrl());
}
if (content.getHoneypot() != null) {
postParams.putSingle("honeypot", content.getHoneypot());
}
if (content.getPostTitle() != null) {
postParams.putSingle("postTitle", content.getPostTitle());
}
if (content.getPostBody() != null) {
postParams.putSingle("postBody", content.getPostBody());
}
if (content.getContextUrl() != null) {
postParams.putSingle("contextUrl", content.getContextUrl());
}
if (content.getContextTitle() != null) {
postParams.putSingle("contextTitle", content.getContextTitle());
}
if (content.getChecks() != null) {
List<String> checks = new ArrayList<>();
for (Check check : content.getChecks()) {
checks.add(check.toString());
}
postParams.put("checks", checks);
}
List<Check> requestedChecks = Arrays.asList(content.getChecks());
if (requestedChecks.contains(Check.SPAM)) {
if (!content.isAllowUnsure()) {
postParams.putSingle("unsure", "0");
}
- if (!content.getStrictness() != Strictness.NORMAL) {
+ if (content.getStrictness() != Strictness.NORMAL) {
postParams.putSingle("strictness", content.getStrictness().toString());
}
}
// Only send the stored parameter after the content was stored.
// @see Content.setStored()
if (content.getStored() != -1) {
postParams.putSingle("stored", Integer.toString(content.getStored()));
}
if (content.getUrl() != null) {
postParams.putSingle("url", content.getUrl());
}
// If the Content has an ID already (subsequent post after e.g. previewing
// the content or asking the user to solve a CAPTCHA), re-check the content.
ClientResponse response;
if (content.getId() == null) { // Check new content
response = request("POST", contentResource, postParams);
} else { // Recheck existing content
response = request("POST", contentResource.path(content.getId()), postParams);
}
// Parse the response into a new Content object.
Content returnedContent = parseBody(response.getEntity(String.class), "content", Content.class);
// Merge classification results into the original Content object.
content.setId(returnedContent.getId());
content.setReason(returnedContent.getReason());
if (requestedChecks.contains(Check.SPAM)) {
content.setSpamClassification(returnedContent.getSpamClassification());
content.setSpamScore(returnedContent.getSpamScore());
}
if (requestedChecks.contains(Check.QUALITY)) {
content.setQualityScore(returnedContent.getQualityScore());
}
if (requestedChecks.contains(Check.PROFANITY)) {
content.setProfanityScore(returnedContent.getProfanityScore());
}
if (requestedChecks.contains(Check.LANGUAGE)) {
content.setLanguages(returnedContent.getLanguages());
}
}
/**
* Creates a new CAPTCHA resource.
*
* Use this to create a standalone CAPTCHA that is not associated with a
* content.
*
* @return The created Captcha object, or null on failure.
*/
public Captcha createCaptcha(CaptchaType captchaType, boolean ssl)
throws MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
return createCaptcha(captchaType, ssl, null);
}
/**
* Creates a new CAPTCHA resource linked to an unsure content.
*
* The passed in Content object must have been classified as unsure. The newly
* created CAPTCHA is associated with that content.
*
* @return The created Captcha object, or null on failure.
*/
public Captcha createCaptcha(CaptchaType captchaType, boolean ssl, Content content)
throws MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
MultivaluedMap<String, String> postParams = new MultivaluedMapImpl();
postParams.putSingle("type", captchaType.toString());
postParams.putSingle("ssl", ssl ? "1" : "0");
if (content.getId() != null) {
postParams.putSingle("contentId", content.getId());
}
ClientResponse response = request("POST", captchaResource, postParams);
return parseBody(response.getEntity(String.class), "captcha", Captcha.class);
}
/**
* Checks a CAPTCHA solution.
*
* Injects the Mollom check results into the given Captcha object.
*/
public void checkCaptcha(Captcha captcha)
throws MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
MultivaluedMap<String, String> postParams = new MultivaluedMapImpl();
if (captcha.getSolution() == null) {
throw new MollomIllegalUsageException("Cannot check a CAPTCHA without a solution.");
}
postParams.putSingle("solution", captcha.getSolution());
if (captcha.getAuthorIp() != null) {
postParams.putSingle("authorIp", captcha.getAuthorIp());
}
if (captcha.getAuthorId() != null) {
postParams.putSingle("authorId", captcha.getAuthorId());
}
if (captcha.getAuthorOpenIds() != null) {
// Exception: authorOpenID is the only API parameter that accepts multiple
// values as a space-separated list.
String openIds = "";
for (String authorOpenId : captcha.getAuthorOpenIds()) {
openIds += authorOpenId += " ";
}
postParams.putSingle("authorOpenid", openIds);
}
if (captcha.getAuthorName() != null) {
postParams.putSingle("authorName", captcha.getAuthorName());
}
if (captcha.getAuthorMail() != null) {
postParams.putSingle("authorMail", captcha.getAuthorMail());
}
if (captcha.getAuthorUrl() != null) {
postParams.putSingle("authorUrl", captcha.getAuthorUrl());
}
if (captcha.getRateLimit() > -1) {
postParams.putSingle("rateLimit", Integer.toString(captcha.getRateLimit()));
}
ClientResponse response = request("POST", captchaResource.path(captcha.getId()), postParams);
Captcha returnedCaptcha = parseBody(response.getEntity(String.class), "captcha", Captcha.class);
captcha.setSolved(returnedCaptcha.isSolved() ? 1 : 0);
captcha.setReason(returnedCaptcha.getReason());
}
/**
* Sends feedback for a previously checked content.
*/
public void sendFeedback(Content content, FeedbackReason reason)
throws MollomIllegalUsageException, MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
sendFeedback(content, null, reason);
}
/**
* Sends feedback for a previously checked CAPTCHA.
*
* Only used for standalone CAPTCHAs. For CAPTCHAs pertaining to content that
* was classified as unsure, it is sufficient to send feedback for the content
* only.
*/
public void sendFeedback(Captcha captcha, FeedbackReason reason)
throws MollomIllegalUsageException, MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
sendFeedback(null, captcha, reason);
}
private void sendFeedback(Content content, Captcha captcha, FeedbackReason reason)
throws MollomIllegalUsageException, MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
if (content.getId() == null && captcha.getId() == null) {
throw new MollomIllegalUsageException("Cannot send feedback without a Content or Captcha ID.");
}
if (reason == null) {
throw new MollomIllegalUsageException("Cannot send feedback without a reason.");
}
MultivaluedMap<String, String> postParams = new MultivaluedMapImpl();
if (content != null) {
postParams.putSingle("contentId", content.getId());
}
if (captcha != null) {
postParams.putSingle("captchaId", captcha.getId());
}
postParams.putSingle("reason", reason.toString());
request("POST", feedbackResource, postParams);
}
/**
* Notify Mollom that the content has been stored on the client-side.
*
* @see MollomClient#markAsStored(Content, String, String, String)
*/
public void markAsStored(Content content)
throws MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
markAsStored(content, null, null, null);
}
/**
* Notify Mollom that the content has been stored on the client-side.
*/
public void markAsStored(Content content, String url, String contextUrl, String contextTitle)
throws MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
content.setChecks(); // Don't re-check anything
content.setStored(true);
// The final/resulting URL of a new content is typically known after
// accepting and storing a content only; supply it to Mollom.
if (url != null) {
content.setUrl(url);
}
// The context of a content is known before accepting and storing a content
// already and should thus be supplied with the regular checkContent() calls
// already.
if (contextUrl != null) {
content.setContextUrl(contextUrl);
}
if (contextTitle != null) {
content.setContextTitle(contextTitle);
}
checkContent(content);
}
/**
* Notify Mollom that the content has been deleted on the client-side.
*/
public void markAsDeleted(Content content)
throws MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
content.setChecks(); // Don't re-check anything
content.setStored(false);
// TODO: Ideally send the stored parameter only.
checkContent(content);
}
/**
* Saves a blacklist entry.
*
* If the entry already exists, update it with the new properties.
*/
public void saveBlacklistEntry(BlacklistEntry blacklistEntry)
throws MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
MultivaluedMap<String, String> postParams = new MultivaluedMapImpl();
if (blacklistEntry.getValue() == null) {
throw new MollomIllegalUsageException("Blacklist entries must have a value in order to be saved.");
}
postParams.putSingle("value", blacklistEntry.getValue());
postParams.putSingle("reason", blacklistEntry.getReason().toString());
postParams.putSingle("context", blacklistEntry.getContext().toString());
postParams.putSingle("match", blacklistEntry.getMatch().toString());
postParams.putSingle("status", blacklistEntry.isEnabled() ? "1" : "0");
if (blacklistEntry.getNote() != null) {
postParams.putSingle("note", blacklistEntry.getNote());
}
ClientResponse response;
if (blacklistEntry.getId() != null) { // Update existing entry
response = request("POST", blacklistResource.path(blacklistEntry.getId()), postParams);
} else { // Create new entry
response = request("POST", blacklistResource, postParams);
}
BlacklistEntry returnedBlacklistEntry = parseBody(response.getEntity(String.class), "entry", BlacklistEntry.class);
blacklistEntry.setId(returnedBlacklistEntry.getId());
blacklistEntry.setCreated(returnedBlacklistEntry.getCreated());
blacklistEntry.setStatus(returnedBlacklistEntry.isEnabled() ? 1 : 0);
// The stored value is not necessarily the given value; at minimum,
// converted to lowercase.
blacklistEntry.setValue(returnedBlacklistEntry.getValue());
}
/**
* Deletes a blacklist entry.
*/
public void deleteBlacklistEntry(BlacklistEntry blacklistEntry)
throws MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
request("POST", blacklistResource.path(blacklistEntry.getId()).path("delete"), new MultivaluedMapImpl());
}
/**
* Lists all blacklist entries for this public key.
*
* @return A list of all blacklist entries.
*/
public List<BlacklistEntry> listBlacklistEntries()
throws MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
ClientResponse response = request("GET", blacklistResource);
return parseList(response.getEntity(String.class), "entry", BlacklistEntry.class);
}
/**
* Retrieves a blacklist entry with a given ID.
*
* @return The blacklist entry or null if not found.
*/
public BlacklistEntry getBlacklistEntry(String blacklistEntryId)
throws MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
ClientResponse response = request("GET", blacklistResource.path(blacklistEntryId));
return parseBody(response.getEntity(String.class), "entry", BlacklistEntry.class);
}
/**
* Saves a whitelist entry.
*
* If the entry already exists, update it with the new properties.
*/
public void saveWhitelistEntry(WhitelistEntry whitelistEntry)
throws MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
if (whitelistEntry.getContext() == Context.ALLFIELDS
|| whitelistEntry.getContext() == Context.LINKS
|| whitelistEntry.getContext() == Context.POSTTITLE) {
throw new MollomConfigurationException("Given context not supported for WhitelistEntry.");
}
MultivaluedMap<String, String> postParams = new MultivaluedMapImpl();
if (whitelistEntry.getValue() == null) {
throw new MollomIllegalUsageException("Whitelist entries must have a value to be saved.");
}
postParams.putSingle("value", whitelistEntry.getValue());
postParams.putSingle("context", whitelistEntry.getContext().toString());
postParams.putSingle("status", whitelistEntry.isEnabled() ? "1" : "0");
if (whitelistEntry.getNote() != null) {
postParams.putSingle("note", whitelistEntry.getNote());
}
ClientResponse response;
if (whitelistEntry.getId() != null) { // Update existing entry
response = request("POST", whitelistResource.path(whitelistEntry.getId()), postParams);
} else { // Create new entry
response = request("POST", whitelistResource, postParams);
}
WhitelistEntry returnedWhitelistEntry = parseBody(response.getEntity(String.class), "entry", WhitelistEntry.class);
whitelistEntry.setId(returnedWhitelistEntry.getId());
whitelistEntry.setCreated(returnedWhitelistEntry.getCreated());
whitelistEntry.setStatus(returnedWhitelistEntry.isEnabled() ? 1 : 0);
// The stored value is not necessarily the given value; at minimum,
// converted to lowercase.
whitelistEntry.setValue(returnedWhitelistEntry.getValue());
}
/**
* Deletes a whitelist entry.
*/
public void deleteWhitelistEntry(WhitelistEntry whitelistEntry)
throws MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
request("POST", whitelistResource.path(whitelistEntry.getId()).path("delete"), new MultivaluedMapImpl());
}
/**
* Lists all whitelist entries for this public key.
*
* @return A list of all whitelist entries.
*/
public List<WhitelistEntry> listWhitelistEntries()
throws MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
ClientResponse response = request("GET", whitelistResource);
return parseList(response.getEntity(String.class), "entry", WhitelistEntry.class);
}
/**
* Retrieves a whitelist entry with a given ID.
*
* @return The whitelist entry or null if not found.
*/
public WhitelistEntry getWhitelistEntry(String whitelistEntryId)
throws MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
ClientResponse response = request("GET", whitelistResource.path(whitelistEntryId));
return parseBody(response.getEntity(String.class), "entry", WhitelistEntry.class);
}
/**
* Destroys the MollomClient object.
*
* Not doing this can cause connection leaks.
*
* The MollomClient instance must not be reused after this method is called;
* otherwise, undefined behavior will occur.
*/
public void destroy() {
client.destroy();
}
private ClientResponse request(String method, WebResource resource)
throws MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
return request(method, resource, null);
}
private ClientResponse request(String method, WebResource resource, MultivaluedMap<String, String> params)
throws MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
for (int retryAttemptNumber = 0; retryAttemptNumber <= retries; retryAttemptNumber++) {
try {
ClientResponse response;
if (params != null) {
response = resource
.accept(MediaType.APPLICATION_XML)
.type(MediaType.APPLICATION_FORM_URLENCODED)
.method(method, ClientResponse.class, params);
} else {
response = resource
.accept(MediaType.APPLICATION_XML)
.type(MediaType.APPLICATION_FORM_URLENCODED)
.method(method, ClientResponse.class);
}
if (response.getStatus() >= 400 && response.getStatus() < 500) {
throw new MollomRequestException(response.getEntity(String.class));
} else if (response.getStatus() < 200 || response.getStatus() >= 300) {
throw new MollomUnexpectedResponseException(response.getEntity(String.class));
}
return response;
} catch (ClientHandlerException e) {
logger.log(Level.WARNING, "Failed to contact Mollom service.", e);
}
}
throw new MollomNoResponseException("Failed to contact Mollom service after retries.");
}
/**
* Parses an object out of a response body.
*
* Expects XML in the format of:
* <response>
* <code>200</code>
* <bodyTag>...</bodyTag>
* </response>
*
* @return JAXB unmarshalled expectedType object from the response.
*
* @throws MollomUnexpectedResponseException
* Unable to parse the response from the Mollom server. Usually this means
* there is a version mismatch between the client library and the Mollom API.
*/
private <T> T parseBody(String xml, String bodyTag, Class<T> expectedType) throws MollomUnexpectedResponseException {
try {
// We have to parse the XML into a Document before passing it to JAXB to
// get the body, because the Mollom service response returns the object
// wrapped in a <Response> object.
Document document = documentBuilder.parse(new InputSource(new StringReader(xml)));
Node bodyNode = document.getElementsByTagName(bodyTag).item(0);
return unmarshaller.unmarshal(bodyNode, expectedType).getValue();
} catch (SAXException | IOException | JAXBException e) {
throw new MollomUnexpectedResponseException("Issue parsing response from Mollom server.", e);
}
}
/**
* Parses a list of objects out of a response body.
*
* Expects XML in the format of:
* <response>
* <code>200</code>
* <list>
* <bodyTag>...</bodyTag>
* ...
* </list>
* </response>
*
* @return List of JAXB unmarshalled expectedType objects from the response.
*
* @throws MollomUnexpectedResponseException
* Unable to parse the response from the Mollom server. Usually this means
* there is a version mismatch between the client library and the Mollom API.
*
* @todo Support the listCount, listOffset, listTotal response parameters
* (required for implementing client-side pagination of e.g. blacklist entries);
* cf. http://mollom.com/api#response-list
*/
private <T> List<T> parseList(String xml, String bodyTag, Class<T> expectedType) throws MollomUnexpectedResponseException {
try {
// We have to parse the XML into a Document before passing it to JAXB to
// get the body, because the Mollom service response returns the object
// wrapped in a <Response> object.
Document document = documentBuilder.parse(new InputSource(new StringReader(xml)));
List<T> list = new ArrayList<>();
NodeList bodyNodes = document.getElementsByTagName(bodyTag);
for (int i = 0; i < bodyNodes.getLength(); i++) {
Node bodyNode = bodyNodes.item(i);
list.add(unmarshaller.unmarshal(bodyNode, expectedType).getValue());
}
return list;
} catch (SAXException | IOException | JAXBException e) {
throw new MollomUnexpectedResponseException("Issue parsing response from Mollom server.", e);
}
}
}
| true | true | public void checkContent(Content content)
throws MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
MultivaluedMap<String, String> postParams = new MultivaluedMapImpl();
if (content.getAuthorIp() != null) {
postParams.putSingle("authorIp", content.getAuthorIp());
}
if (content.getAuthorId() != null) {
postParams.putSingle("authorId", content.getAuthorId());
}
if (content.getAuthorOpenIds() != null) {
// Exception: authorOpenID is the only API parameter that accepts multiple
// values as a space-separated list.
String openIds = "";
for (String authorOpenId : content.getAuthorOpenIds()) {
openIds += authorOpenId += " ";
}
postParams.putSingle("authorOpenid", openIds);
}
if (content.getAuthorName() != null) {
postParams.putSingle("authorName", content.getAuthorName());
}
if (content.getAuthorMail() != null) {
postParams.putSingle("authorMail", content.getAuthorMail());
}
if (content.getAuthorUrl() != null) {
postParams.putSingle("authorUrl", content.getAuthorUrl());
}
if (content.getHoneypot() != null) {
postParams.putSingle("honeypot", content.getHoneypot());
}
if (content.getPostTitle() != null) {
postParams.putSingle("postTitle", content.getPostTitle());
}
if (content.getPostBody() != null) {
postParams.putSingle("postBody", content.getPostBody());
}
if (content.getContextUrl() != null) {
postParams.putSingle("contextUrl", content.getContextUrl());
}
if (content.getContextTitle() != null) {
postParams.putSingle("contextTitle", content.getContextTitle());
}
if (content.getChecks() != null) {
List<String> checks = new ArrayList<>();
for (Check check : content.getChecks()) {
checks.add(check.toString());
}
postParams.put("checks", checks);
}
List<Check> requestedChecks = Arrays.asList(content.getChecks());
if (requestedChecks.contains(Check.SPAM)) {
if (!content.isAllowUnsure()) {
postParams.putSingle("unsure", "0");
}
if (!content.getStrictness() != Strictness.NORMAL) {
postParams.putSingle("strictness", content.getStrictness().toString());
}
}
// Only send the stored parameter after the content was stored.
// @see Content.setStored()
if (content.getStored() != -1) {
postParams.putSingle("stored", Integer.toString(content.getStored()));
}
if (content.getUrl() != null) {
postParams.putSingle("url", content.getUrl());
}
// If the Content has an ID already (subsequent post after e.g. previewing
// the content or asking the user to solve a CAPTCHA), re-check the content.
ClientResponse response;
if (content.getId() == null) { // Check new content
response = request("POST", contentResource, postParams);
} else { // Recheck existing content
response = request("POST", contentResource.path(content.getId()), postParams);
}
// Parse the response into a new Content object.
Content returnedContent = parseBody(response.getEntity(String.class), "content", Content.class);
// Merge classification results into the original Content object.
content.setId(returnedContent.getId());
content.setReason(returnedContent.getReason());
if (requestedChecks.contains(Check.SPAM)) {
content.setSpamClassification(returnedContent.getSpamClassification());
content.setSpamScore(returnedContent.getSpamScore());
}
if (requestedChecks.contains(Check.QUALITY)) {
content.setQualityScore(returnedContent.getQualityScore());
}
if (requestedChecks.contains(Check.PROFANITY)) {
content.setProfanityScore(returnedContent.getProfanityScore());
}
if (requestedChecks.contains(Check.LANGUAGE)) {
content.setLanguages(returnedContent.getLanguages());
}
}
| public void checkContent(Content content)
throws MollomRequestException, MollomUnexpectedResponseException, MollomNoResponseException {
MultivaluedMap<String, String> postParams = new MultivaluedMapImpl();
if (content.getAuthorIp() != null) {
postParams.putSingle("authorIp", content.getAuthorIp());
}
if (content.getAuthorId() != null) {
postParams.putSingle("authorId", content.getAuthorId());
}
if (content.getAuthorOpenIds() != null) {
// Exception: authorOpenID is the only API parameter that accepts multiple
// values as a space-separated list.
String openIds = "";
for (String authorOpenId : content.getAuthorOpenIds()) {
openIds += authorOpenId += " ";
}
postParams.putSingle("authorOpenid", openIds);
}
if (content.getAuthorName() != null) {
postParams.putSingle("authorName", content.getAuthorName());
}
if (content.getAuthorMail() != null) {
postParams.putSingle("authorMail", content.getAuthorMail());
}
if (content.getAuthorUrl() != null) {
postParams.putSingle("authorUrl", content.getAuthorUrl());
}
if (content.getHoneypot() != null) {
postParams.putSingle("honeypot", content.getHoneypot());
}
if (content.getPostTitle() != null) {
postParams.putSingle("postTitle", content.getPostTitle());
}
if (content.getPostBody() != null) {
postParams.putSingle("postBody", content.getPostBody());
}
if (content.getContextUrl() != null) {
postParams.putSingle("contextUrl", content.getContextUrl());
}
if (content.getContextTitle() != null) {
postParams.putSingle("contextTitle", content.getContextTitle());
}
if (content.getChecks() != null) {
List<String> checks = new ArrayList<>();
for (Check check : content.getChecks()) {
checks.add(check.toString());
}
postParams.put("checks", checks);
}
List<Check> requestedChecks = Arrays.asList(content.getChecks());
if (requestedChecks.contains(Check.SPAM)) {
if (!content.isAllowUnsure()) {
postParams.putSingle("unsure", "0");
}
if (content.getStrictness() != Strictness.NORMAL) {
postParams.putSingle("strictness", content.getStrictness().toString());
}
}
// Only send the stored parameter after the content was stored.
// @see Content.setStored()
if (content.getStored() != -1) {
postParams.putSingle("stored", Integer.toString(content.getStored()));
}
if (content.getUrl() != null) {
postParams.putSingle("url", content.getUrl());
}
// If the Content has an ID already (subsequent post after e.g. previewing
// the content or asking the user to solve a CAPTCHA), re-check the content.
ClientResponse response;
if (content.getId() == null) { // Check new content
response = request("POST", contentResource, postParams);
} else { // Recheck existing content
response = request("POST", contentResource.path(content.getId()), postParams);
}
// Parse the response into a new Content object.
Content returnedContent = parseBody(response.getEntity(String.class), "content", Content.class);
// Merge classification results into the original Content object.
content.setId(returnedContent.getId());
content.setReason(returnedContent.getReason());
if (requestedChecks.contains(Check.SPAM)) {
content.setSpamClassification(returnedContent.getSpamClassification());
content.setSpamScore(returnedContent.getSpamScore());
}
if (requestedChecks.contains(Check.QUALITY)) {
content.setQualityScore(returnedContent.getQualityScore());
}
if (requestedChecks.contains(Check.PROFANITY)) {
content.setProfanityScore(returnedContent.getProfanityScore());
}
if (requestedChecks.contains(Check.LANGUAGE)) {
content.setLanguages(returnedContent.getLanguages());
}
}
|
diff --git a/licanciator/src/ar/edu/utn/frsf/licenciator/gui/windows/EmitirGUI.java b/licanciator/src/ar/edu/utn/frsf/licenciator/gui/windows/EmitirGUI.java
index ddbbf68..9e53a05 100644
--- a/licanciator/src/ar/edu/utn/frsf/licenciator/gui/windows/EmitirGUI.java
+++ b/licanciator/src/ar/edu/utn/frsf/licenciator/gui/windows/EmitirGUI.java
@@ -1,404 +1,407 @@
package ar.edu.utn.frsf.licenciator.gui.windows;
import javax.swing.JDialog;
import javax.swing.JComboBox;
import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.JTextPane;
import java.awt.Insets;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JButton;
import java.awt.Component;
import javax.swing.Box;
import javax.swing.JOptionPane;
import javax.swing.JSlider;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.JSeparator;
import com.sun.xml.bind.v2.TODO;
import ar.edu.utn.frsf.licenciator.logica.EmitirLicencia;
import ar.edu.utn.frsf.licenciator.entidades.*;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class EmitirGUI extends JDialog{
private JTextField textApellido;
private JTextField textNombre;
private JTextField textDomicilio;
private JTextField textLocalidad;
private JTextField textNac;
private JTextField textDonante;
private JTextField textFactor;
private JTextField textFV;
private JTextField textFE;
private JTextField textNroLic;
private JTextField textObs;
private JTextField textNroDoc;
private JTextField textClase;
private Titular titular;
private Licencia licencia;
public EmitirGUI() {
setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\VICTORIA\\Downloads\\descarga (1).jpg"));
setTitle("Emitir Licencia");
final JComboBox textTipoDoc = new JComboBox();
textTipoDoc.addItem("DNI");
textTipoDoc.addItem("LC");
textTipoDoc.addItem("LE");
JButton btnBuscar = new JButton("Buscar");
btnBuscar.addActionListener(new ActionListener() {
/* Busqueda del titular */
public void actionPerformed(ActionEvent arg0) {
if (EmitirLicencia.dniValido(textNroDoc.getText())){
titular = EmitirLicencia.buscarTitular(textTipoDoc.getSelectedItem().toString(), Long.parseLong(textNroDoc.getText()));
if (titular != null){
textApellido.setText(titular.getApellido());
textNombre.setText(titular.getNombre());
textDomicilio.setText(titular.getDomicilio());
textLocalidad.setText(titular.getLocalidad());
textNac.setText(titular.getFechaNac().toString());
if (titular.getDonante()){
textDonante.setText("Si");
} else {
textDonante.setText("No");
}
textFactor.setText(titular.getTipoSanguineo().getGrupo() + titular.getTipoSanguineo().getFactor());
}
+ else{
+ JOptionPane.showMessageDialog(null, "El titular ingresado no existe.\nRevise los datos ingresados o vea la opci�n Dar de alta -> Alta Titular del men� principal", "Error", JOptionPane.ERROR_MESSAGE);
+ }
}
else
{
- JOptionPane.showMessageDialog(null, "El n�mero que ha ingresado es incorrecto", "N�mero de documento no v�lido", JOptionPane.ERROR_MESSAGE);
+ JOptionPane.showMessageDialog(null, "El n�mero de documento que ha ingresado no es v�lido", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
JLabel lblApellido = new JLabel("Apellido:");
lblApellido.setHorizontalAlignment(SwingConstants.LEFT);
JLabel lblNro = new JLabel("Nro Documento");
JLabel lblTipol = new JLabel("Tipo Documento");
JLabel lblNombre = new JLabel("Nombre:");
JLabel lblDomicilio = new JLabel("Domicilio:");
JLabel lblLocalidad = new JLabel("Localidad:");
JLabel lblFechaDeNacimiento = new JLabel("Fecha de Nacimiento:");
JLabel lblDonante = new JLabel("Donante:");
JLabel lblGrupoYFactor = new JLabel("Grupo y factor sanguineo:");
textApellido = new JTextField();
textApellido.setEditable(false);
textApellido.setColumns(10);
textNombre = new JTextField();
textNombre.setEditable(false);
textNombre.setColumns(10);
textDomicilio = new JTextField();
textDomicilio.setEditable(false);
textDomicilio.setColumns(10);
textLocalidad = new JTextField();
textLocalidad.setEditable(false);
textLocalidad.setColumns(10);
textNac = new JTextField();
textNac.setEditable(false);
textNac.setColumns(10);
textDonante = new JTextField();
textDonante.setEditable(false);
textDonante.setColumns(10);
textFactor = new JTextField();
textFactor.setEditable(false);
textFactor.setColumns(10);
JLabel lblClase = new JLabel("Clase:");
JLabel lblNro_1 = new JLabel("Nro:");
JLabel lblFechaEmisin = new JLabel("Fecha emisi\u00F3n:");
JLabel lblFechaDeVencimiento = new JLabel("Fecha de vencimiento:");
JLabel lblObservaciones = new JLabel("Observaciones:");
textFV = new JTextField();
textFV.setEditable(false);
textFV.setColumns(10);
textFE = new JTextField();
textFE.setEditable(false);
textFE.setColumns(10);
textNroLic = new JTextField();
textNroLic.setEditable(false);
textNroLic.setColumns(10);
textClase = new JTextField();
textClase.setColumns(10);
textObs = new JTextField();
textObs.setColumns(10);
JSeparator separator_1 = new JSeparator();
textNroDoc = new JTextField();
textNroDoc.setColumns(10);
JButton btnEmitir = new JButton("Emitir");
/* Cuando se pulsa el boton Emitir */
btnEmitir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String clase = textClase.getText();
if(EmitirLicencia.claseValida(clase))
{
licencia = EmitirLicencia.emitirLicencia(titular, textClase.getText(), textObs.getText());
if (licencia != null)
{
textNroLic.setText(licencia.getNrolicencia());
textFE.setText(licencia.getFechaEmision().toString());
textFV.setText(licencia.getFechaVencimiento().toString());
/*Deshabilitamos los campos editables*/
textTipoDoc.setEnabled(false);
textNroDoc.setEnabled(false);
textClase.setEnabled(false);
textObs.setEnabled(false);
} else {
- JOptionPane.showMessageDialog(null, "La licencia requerida no se puede emitir", "Licencia no v�lida", JOptionPane.ERROR_MESSAGE);
+ JOptionPane.showMessageDialog(null, "La licencia requerida no se puede emitir", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else
{
- JOptionPane.showMessageDialog(null, "La clase que ha ingresado no corresponde a una clase de licencia", "Clase de licencia no v�lida", JOptionPane.ERROR_MESSAGE);
+ JOptionPane.showMessageDialog(null, "La clase que ha ingresado no corresponde a una clase de licencia v�lida", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
JLabel lblDatosDelTitular = new JLabel("Datos del titular");
lblDatosDelTitular.setFont(new Font("Tahoma", Font.PLAIN, 17));
JLabel lblDatosDeLa = new JLabel("Datos de la licencia");
lblDatosDeLa.setFont(new Font("Tahoma", Font.PLAIN, 17));
JButton btnCancelar = new JButton("Cancelar");
btnCancelar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
JButton btnAceptar = new JButton("Aceptar");
btnAceptar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (licencia !=null)
{
EmitirLicencia.guardarLicencia(licencia);
}
}
});
GroupLayout groupLayout = new GroupLayout(getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(separator_1, GroupLayout.DEFAULT_SIZE, 493, Short.MAX_VALUE)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(lblDatosDelTitular)
.addContainerGap(363, Short.MAX_VALUE))
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(lblDatosDeLa)
.addContainerGap(338, Short.MAX_VALUE))
.addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(lblTipol)
.addComponent(lblNro)
.addComponent(lblApellido, GroupLayout.DEFAULT_SIZE, 179, Short.MAX_VALUE)
.addComponent(lblNombre)
.addComponent(lblDomicilio)
.addComponent(lblLocalidad))
.addPreferredGap(ComponentPlacement.RELATED))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblDonante)
.addGap(87)))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblFechaDeNacimiento)
.addGap(29)))
.addComponent(lblClase))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblNro_1)
.addPreferredGap(ComponentPlacement.RELATED)))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblFechaEmisin)
.addPreferredGap(ComponentPlacement.RELATED)))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblFechaDeVencimiento)
.addPreferredGap(ComponentPlacement.RELATED)))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblObservaciones)
.addPreferredGap(ComponentPlacement.RELATED)))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblGrupoYFactor)
.addGap(57)))
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(textFactor, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(textClase, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textNroLic, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textFE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textFV, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textObs, GroupLayout.PREFERRED_SIZE, 173, GroupLayout.PREFERRED_SIZE))
.addGap(37))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(btnAceptar)
.addPreferredGap(ComponentPlacement.UNRELATED)))
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(btnCancelar)
.addComponent(btnEmitir)))
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
.addComponent(textTipoDoc, Alignment.LEADING, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(textNroDoc, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE))
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnBuscar))
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
.addComponent(textLocalidad, Alignment.LEADING)
.addComponent(textDomicilio, Alignment.LEADING)
.addComponent(textNombre, Alignment.LEADING)
.addComponent(textApellido, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)))
.addGap(15))
.addComponent(textDonante)
.addComponent(textNac)))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblTipol)
.addComponent(textTipoDoc, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNro)
.addComponent(textNroDoc, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
.addGroup(groupLayout.createSequentialGroup()
.addGap(22)
.addComponent(btnBuscar)))
.addGap(21)
.addComponent(separator_1, GroupLayout.PREFERRED_SIZE, 2, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(lblDatosDelTitular)
.addGap(9)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblApellido)
.addComponent(textApellido, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNombre)
.addComponent(textNombre, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblDomicilio)
.addComponent(textDomicilio, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblLocalidad)
.addComponent(textLocalidad, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblDonante)
.addComponent(textNac, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblFechaDeNacimiento)
.addComponent(textDonante, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblGrupoYFactor)
.addComponent(textFactor, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED, 45, Short.MAX_VALUE)
.addComponent(lblDatosDeLa)
.addGap(38)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(btnEmitir)
.addGap(183)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(btnCancelar)
.addComponent(btnAceptar)))
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblClase)
.addComponent(textClase, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNro_1)
.addComponent(textNroLic, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblFechaEmisin)
.addComponent(textFE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblFechaDeVencimiento)
.addComponent(textFV, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(textObs, GroupLayout.PREFERRED_SIZE, 55, GroupLayout.PREFERRED_SIZE)
.addComponent(lblObservaciones))))
.addContainerGap())
);
getContentPane().setLayout(groupLayout);
}
public static void LanzarGUI() {
try {
EmitirGUI dialog = new EmitirGUI();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| false | true | public EmitirGUI() {
setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\VICTORIA\\Downloads\\descarga (1).jpg"));
setTitle("Emitir Licencia");
final JComboBox textTipoDoc = new JComboBox();
textTipoDoc.addItem("DNI");
textTipoDoc.addItem("LC");
textTipoDoc.addItem("LE");
JButton btnBuscar = new JButton("Buscar");
btnBuscar.addActionListener(new ActionListener() {
/* Busqueda del titular */
public void actionPerformed(ActionEvent arg0) {
if (EmitirLicencia.dniValido(textNroDoc.getText())){
titular = EmitirLicencia.buscarTitular(textTipoDoc.getSelectedItem().toString(), Long.parseLong(textNroDoc.getText()));
if (titular != null){
textApellido.setText(titular.getApellido());
textNombre.setText(titular.getNombre());
textDomicilio.setText(titular.getDomicilio());
textLocalidad.setText(titular.getLocalidad());
textNac.setText(titular.getFechaNac().toString());
if (titular.getDonante()){
textDonante.setText("Si");
} else {
textDonante.setText("No");
}
textFactor.setText(titular.getTipoSanguineo().getGrupo() + titular.getTipoSanguineo().getFactor());
}
}
else
{
JOptionPane.showMessageDialog(null, "El n�mero que ha ingresado es incorrecto", "N�mero de documento no v�lido", JOptionPane.ERROR_MESSAGE);
}
}
});
JLabel lblApellido = new JLabel("Apellido:");
lblApellido.setHorizontalAlignment(SwingConstants.LEFT);
JLabel lblNro = new JLabel("Nro Documento");
JLabel lblTipol = new JLabel("Tipo Documento");
JLabel lblNombre = new JLabel("Nombre:");
JLabel lblDomicilio = new JLabel("Domicilio:");
JLabel lblLocalidad = new JLabel("Localidad:");
JLabel lblFechaDeNacimiento = new JLabel("Fecha de Nacimiento:");
JLabel lblDonante = new JLabel("Donante:");
JLabel lblGrupoYFactor = new JLabel("Grupo y factor sanguineo:");
textApellido = new JTextField();
textApellido.setEditable(false);
textApellido.setColumns(10);
textNombre = new JTextField();
textNombre.setEditable(false);
textNombre.setColumns(10);
textDomicilio = new JTextField();
textDomicilio.setEditable(false);
textDomicilio.setColumns(10);
textLocalidad = new JTextField();
textLocalidad.setEditable(false);
textLocalidad.setColumns(10);
textNac = new JTextField();
textNac.setEditable(false);
textNac.setColumns(10);
textDonante = new JTextField();
textDonante.setEditable(false);
textDonante.setColumns(10);
textFactor = new JTextField();
textFactor.setEditable(false);
textFactor.setColumns(10);
JLabel lblClase = new JLabel("Clase:");
JLabel lblNro_1 = new JLabel("Nro:");
JLabel lblFechaEmisin = new JLabel("Fecha emisi\u00F3n:");
JLabel lblFechaDeVencimiento = new JLabel("Fecha de vencimiento:");
JLabel lblObservaciones = new JLabel("Observaciones:");
textFV = new JTextField();
textFV.setEditable(false);
textFV.setColumns(10);
textFE = new JTextField();
textFE.setEditable(false);
textFE.setColumns(10);
textNroLic = new JTextField();
textNroLic.setEditable(false);
textNroLic.setColumns(10);
textClase = new JTextField();
textClase.setColumns(10);
textObs = new JTextField();
textObs.setColumns(10);
JSeparator separator_1 = new JSeparator();
textNroDoc = new JTextField();
textNroDoc.setColumns(10);
JButton btnEmitir = new JButton("Emitir");
/* Cuando se pulsa el boton Emitir */
btnEmitir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String clase = textClase.getText();
if(EmitirLicencia.claseValida(clase))
{
licencia = EmitirLicencia.emitirLicencia(titular, textClase.getText(), textObs.getText());
if (licencia != null)
{
textNroLic.setText(licencia.getNrolicencia());
textFE.setText(licencia.getFechaEmision().toString());
textFV.setText(licencia.getFechaVencimiento().toString());
/*Deshabilitamos los campos editables*/
textTipoDoc.setEnabled(false);
textNroDoc.setEnabled(false);
textClase.setEnabled(false);
textObs.setEnabled(false);
} else {
JOptionPane.showMessageDialog(null, "La licencia requerida no se puede emitir", "Licencia no v�lida", JOptionPane.ERROR_MESSAGE);
}
}
else
{
JOptionPane.showMessageDialog(null, "La clase que ha ingresado no corresponde a una clase de licencia", "Clase de licencia no v�lida", JOptionPane.ERROR_MESSAGE);
}
}
});
JLabel lblDatosDelTitular = new JLabel("Datos del titular");
lblDatosDelTitular.setFont(new Font("Tahoma", Font.PLAIN, 17));
JLabel lblDatosDeLa = new JLabel("Datos de la licencia");
lblDatosDeLa.setFont(new Font("Tahoma", Font.PLAIN, 17));
JButton btnCancelar = new JButton("Cancelar");
btnCancelar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
JButton btnAceptar = new JButton("Aceptar");
btnAceptar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (licencia !=null)
{
EmitirLicencia.guardarLicencia(licencia);
}
}
});
GroupLayout groupLayout = new GroupLayout(getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(separator_1, GroupLayout.DEFAULT_SIZE, 493, Short.MAX_VALUE)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(lblDatosDelTitular)
.addContainerGap(363, Short.MAX_VALUE))
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(lblDatosDeLa)
.addContainerGap(338, Short.MAX_VALUE))
.addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(lblTipol)
.addComponent(lblNro)
.addComponent(lblApellido, GroupLayout.DEFAULT_SIZE, 179, Short.MAX_VALUE)
.addComponent(lblNombre)
.addComponent(lblDomicilio)
.addComponent(lblLocalidad))
.addPreferredGap(ComponentPlacement.RELATED))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblDonante)
.addGap(87)))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblFechaDeNacimiento)
.addGap(29)))
.addComponent(lblClase))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblNro_1)
.addPreferredGap(ComponentPlacement.RELATED)))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblFechaEmisin)
.addPreferredGap(ComponentPlacement.RELATED)))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblFechaDeVencimiento)
.addPreferredGap(ComponentPlacement.RELATED)))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblObservaciones)
.addPreferredGap(ComponentPlacement.RELATED)))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblGrupoYFactor)
.addGap(57)))
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(textFactor, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(textClase, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textNroLic, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textFE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textFV, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textObs, GroupLayout.PREFERRED_SIZE, 173, GroupLayout.PREFERRED_SIZE))
.addGap(37))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(btnAceptar)
.addPreferredGap(ComponentPlacement.UNRELATED)))
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(btnCancelar)
.addComponent(btnEmitir)))
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
.addComponent(textTipoDoc, Alignment.LEADING, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(textNroDoc, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE))
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnBuscar))
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
.addComponent(textLocalidad, Alignment.LEADING)
.addComponent(textDomicilio, Alignment.LEADING)
.addComponent(textNombre, Alignment.LEADING)
.addComponent(textApellido, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)))
.addGap(15))
.addComponent(textDonante)
.addComponent(textNac)))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblTipol)
.addComponent(textTipoDoc, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNro)
.addComponent(textNroDoc, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
.addGroup(groupLayout.createSequentialGroup()
.addGap(22)
.addComponent(btnBuscar)))
.addGap(21)
.addComponent(separator_1, GroupLayout.PREFERRED_SIZE, 2, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(lblDatosDelTitular)
.addGap(9)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblApellido)
.addComponent(textApellido, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNombre)
.addComponent(textNombre, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblDomicilio)
.addComponent(textDomicilio, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblLocalidad)
.addComponent(textLocalidad, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblDonante)
.addComponent(textNac, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblFechaDeNacimiento)
.addComponent(textDonante, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblGrupoYFactor)
.addComponent(textFactor, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED, 45, Short.MAX_VALUE)
.addComponent(lblDatosDeLa)
.addGap(38)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(btnEmitir)
.addGap(183)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(btnCancelar)
.addComponent(btnAceptar)))
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblClase)
.addComponent(textClase, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNro_1)
.addComponent(textNroLic, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblFechaEmisin)
.addComponent(textFE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblFechaDeVencimiento)
.addComponent(textFV, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(textObs, GroupLayout.PREFERRED_SIZE, 55, GroupLayout.PREFERRED_SIZE)
.addComponent(lblObservaciones))))
.addContainerGap())
);
getContentPane().setLayout(groupLayout);
}
| public EmitirGUI() {
setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\VICTORIA\\Downloads\\descarga (1).jpg"));
setTitle("Emitir Licencia");
final JComboBox textTipoDoc = new JComboBox();
textTipoDoc.addItem("DNI");
textTipoDoc.addItem("LC");
textTipoDoc.addItem("LE");
JButton btnBuscar = new JButton("Buscar");
btnBuscar.addActionListener(new ActionListener() {
/* Busqueda del titular */
public void actionPerformed(ActionEvent arg0) {
if (EmitirLicencia.dniValido(textNroDoc.getText())){
titular = EmitirLicencia.buscarTitular(textTipoDoc.getSelectedItem().toString(), Long.parseLong(textNroDoc.getText()));
if (titular != null){
textApellido.setText(titular.getApellido());
textNombre.setText(titular.getNombre());
textDomicilio.setText(titular.getDomicilio());
textLocalidad.setText(titular.getLocalidad());
textNac.setText(titular.getFechaNac().toString());
if (titular.getDonante()){
textDonante.setText("Si");
} else {
textDonante.setText("No");
}
textFactor.setText(titular.getTipoSanguineo().getGrupo() + titular.getTipoSanguineo().getFactor());
}
else{
JOptionPane.showMessageDialog(null, "El titular ingresado no existe.\nRevise los datos ingresados o vea la opci�n Dar de alta -> Alta Titular del men� principal", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else
{
JOptionPane.showMessageDialog(null, "El n�mero de documento que ha ingresado no es v�lido", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
JLabel lblApellido = new JLabel("Apellido:");
lblApellido.setHorizontalAlignment(SwingConstants.LEFT);
JLabel lblNro = new JLabel("Nro Documento");
JLabel lblTipol = new JLabel("Tipo Documento");
JLabel lblNombre = new JLabel("Nombre:");
JLabel lblDomicilio = new JLabel("Domicilio:");
JLabel lblLocalidad = new JLabel("Localidad:");
JLabel lblFechaDeNacimiento = new JLabel("Fecha de Nacimiento:");
JLabel lblDonante = new JLabel("Donante:");
JLabel lblGrupoYFactor = new JLabel("Grupo y factor sanguineo:");
textApellido = new JTextField();
textApellido.setEditable(false);
textApellido.setColumns(10);
textNombre = new JTextField();
textNombre.setEditable(false);
textNombre.setColumns(10);
textDomicilio = new JTextField();
textDomicilio.setEditable(false);
textDomicilio.setColumns(10);
textLocalidad = new JTextField();
textLocalidad.setEditable(false);
textLocalidad.setColumns(10);
textNac = new JTextField();
textNac.setEditable(false);
textNac.setColumns(10);
textDonante = new JTextField();
textDonante.setEditable(false);
textDonante.setColumns(10);
textFactor = new JTextField();
textFactor.setEditable(false);
textFactor.setColumns(10);
JLabel lblClase = new JLabel("Clase:");
JLabel lblNro_1 = new JLabel("Nro:");
JLabel lblFechaEmisin = new JLabel("Fecha emisi\u00F3n:");
JLabel lblFechaDeVencimiento = new JLabel("Fecha de vencimiento:");
JLabel lblObservaciones = new JLabel("Observaciones:");
textFV = new JTextField();
textFV.setEditable(false);
textFV.setColumns(10);
textFE = new JTextField();
textFE.setEditable(false);
textFE.setColumns(10);
textNroLic = new JTextField();
textNroLic.setEditable(false);
textNroLic.setColumns(10);
textClase = new JTextField();
textClase.setColumns(10);
textObs = new JTextField();
textObs.setColumns(10);
JSeparator separator_1 = new JSeparator();
textNroDoc = new JTextField();
textNroDoc.setColumns(10);
JButton btnEmitir = new JButton("Emitir");
/* Cuando se pulsa el boton Emitir */
btnEmitir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String clase = textClase.getText();
if(EmitirLicencia.claseValida(clase))
{
licencia = EmitirLicencia.emitirLicencia(titular, textClase.getText(), textObs.getText());
if (licencia != null)
{
textNroLic.setText(licencia.getNrolicencia());
textFE.setText(licencia.getFechaEmision().toString());
textFV.setText(licencia.getFechaVencimiento().toString());
/*Deshabilitamos los campos editables*/
textTipoDoc.setEnabled(false);
textNroDoc.setEnabled(false);
textClase.setEnabled(false);
textObs.setEnabled(false);
} else {
JOptionPane.showMessageDialog(null, "La licencia requerida no se puede emitir", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else
{
JOptionPane.showMessageDialog(null, "La clase que ha ingresado no corresponde a una clase de licencia v�lida", "Error", JOptionPane.ERROR_MESSAGE);
}
}
});
JLabel lblDatosDelTitular = new JLabel("Datos del titular");
lblDatosDelTitular.setFont(new Font("Tahoma", Font.PLAIN, 17));
JLabel lblDatosDeLa = new JLabel("Datos de la licencia");
lblDatosDeLa.setFont(new Font("Tahoma", Font.PLAIN, 17));
JButton btnCancelar = new JButton("Cancelar");
btnCancelar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
JButton btnAceptar = new JButton("Aceptar");
btnAceptar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (licencia !=null)
{
EmitirLicencia.guardarLicencia(licencia);
}
}
});
GroupLayout groupLayout = new GroupLayout(getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(separator_1, GroupLayout.DEFAULT_SIZE, 493, Short.MAX_VALUE)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(lblDatosDelTitular)
.addContainerGap(363, Short.MAX_VALUE))
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addComponent(lblDatosDeLa)
.addContainerGap(338, Short.MAX_VALUE))
.addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(lblTipol)
.addComponent(lblNro)
.addComponent(lblApellido, GroupLayout.DEFAULT_SIZE, 179, Short.MAX_VALUE)
.addComponent(lblNombre)
.addComponent(lblDomicilio)
.addComponent(lblLocalidad))
.addPreferredGap(ComponentPlacement.RELATED))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblDonante)
.addGap(87)))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblFechaDeNacimiento)
.addGap(29)))
.addComponent(lblClase))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblNro_1)
.addPreferredGap(ComponentPlacement.RELATED)))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblFechaEmisin)
.addPreferredGap(ComponentPlacement.RELATED)))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblFechaDeVencimiento)
.addPreferredGap(ComponentPlacement.RELATED)))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblObservaciones)
.addPreferredGap(ComponentPlacement.RELATED)))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(lblGrupoYFactor)
.addGap(57)))
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(textFactor, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(Alignment.TRAILING, groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(textClase, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textNroLic, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textFE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textFV, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(textObs, GroupLayout.PREFERRED_SIZE, 173, GroupLayout.PREFERRED_SIZE))
.addGap(37))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(btnAceptar)
.addPreferredGap(ComponentPlacement.UNRELATED)))
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(btnCancelar)
.addComponent(btnEmitir)))
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
.addComponent(textTipoDoc, Alignment.LEADING, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(textNroDoc, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE))
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnBuscar))
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
.addComponent(textLocalidad, Alignment.LEADING)
.addComponent(textDomicilio, Alignment.LEADING)
.addComponent(textNombre, Alignment.LEADING)
.addComponent(textApellido, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)))
.addGap(15))
.addComponent(textDonante)
.addComponent(textNac)))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addContainerGap()
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblTipol)
.addComponent(textTipoDoc, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNro)
.addComponent(textNroDoc, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
.addGroup(groupLayout.createSequentialGroup()
.addGap(22)
.addComponent(btnBuscar)))
.addGap(21)
.addComponent(separator_1, GroupLayout.PREFERRED_SIZE, 2, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(lblDatosDelTitular)
.addGap(9)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblApellido)
.addComponent(textApellido, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNombre)
.addComponent(textNombre, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblDomicilio)
.addComponent(textDomicilio, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblLocalidad)
.addComponent(textLocalidad, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblDonante)
.addComponent(textNac, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblFechaDeNacimiento)
.addComponent(textDonante, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblGrupoYFactor)
.addComponent(textFactor, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED, 45, Short.MAX_VALUE)
.addComponent(lblDatosDeLa)
.addGap(38)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(btnEmitir)
.addGap(183)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(btnCancelar)
.addComponent(btnAceptar)))
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblClase)
.addComponent(textClase, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNro_1)
.addComponent(textNroLic, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblFechaEmisin)
.addComponent(textFE, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
.addComponent(lblFechaDeVencimiento)
.addComponent(textFV, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(textObs, GroupLayout.PREFERRED_SIZE, 55, GroupLayout.PREFERRED_SIZE)
.addComponent(lblObservaciones))))
.addContainerGap())
);
getContentPane().setLayout(groupLayout);
}
|
diff --git a/src/java/com/android/internal/telephony/PhoneFactory.java b/src/java/com/android/internal/telephony/PhoneFactory.java
index ab28ff2..f46f828 100644
--- a/src/java/com/android/internal/telephony/PhoneFactory.java
+++ b/src/java/com/android/internal/telephony/PhoneFactory.java
@@ -1,230 +1,234 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.telephony;
import android.content.ComponentName;
import android.content.Context;
import android.net.LocalServerSocket;
import android.os.Looper;
import android.os.SystemProperties;
import android.provider.Settings;
import android.telephony.Rlog;
import android.telephony.TelephonyManager;
import com.android.internal.telephony.cdma.CDMALTEPhone;
import com.android.internal.telephony.cdma.CDMAPhone;
import com.android.internal.telephony.cdma.CdmaSubscriptionSourceManager;
import com.android.internal.telephony.gsm.GSMPhone;
import com.android.internal.telephony.sip.SipPhone;
import com.android.internal.telephony.sip.SipPhoneFactory;
import com.android.internal.telephony.uicc.UiccController;
import java.lang.reflect.Constructor;
/**
* {@hide}
*/
public class PhoneFactory {
static final String LOG_TAG = "PhoneFactory";
static final int SOCKET_OPEN_RETRY_MILLIS = 2 * 1000;
static final int SOCKET_OPEN_MAX_RETRY = 3;
//***** Class Variables
static private Phone sProxyPhone = null;
static private CommandsInterface sCommandsInterface = null;
static private boolean sMadeDefaults = false;
static private PhoneNotifier sPhoneNotifier;
static private Looper sLooper;
static private Context sContext;
//***** Class Methods
public static void makeDefaultPhones(Context context) {
makeDefaultPhone(context);
}
/**
* FIXME replace this with some other way of making these
* instances
*/
public static void makeDefaultPhone(Context context) {
synchronized(Phone.class) {
if (!sMadeDefaults) {
sLooper = Looper.myLooper();
sContext = context;
if (sLooper == null) {
throw new RuntimeException(
"PhoneFactory.makeDefaultPhone must be called from Looper thread");
}
int retryCount = 0;
for(;;) {
boolean hasException = false;
retryCount ++;
try {
// use UNIX domain socket to
// prevent subsequent initialization
new LocalServerSocket("com.android.internal.telephony");
} catch (java.io.IOException ex) {
hasException = true;
}
if ( !hasException ) {
break;
} else if (retryCount > SOCKET_OPEN_MAX_RETRY) {
throw new RuntimeException("PhoneFactory probably already running");
} else {
try {
Thread.sleep(SOCKET_OPEN_RETRY_MILLIS);
} catch (InterruptedException er) {
}
}
}
sPhoneNotifier = new DefaultPhoneNotifier();
// Get preferred network mode
int preferredNetworkMode = RILConstants.PREFERRED_NETWORK_MODE;
if (TelephonyManager.getLteOnCdmaModeStatic() == PhoneConstants.LTE_ON_CDMA_TRUE) {
preferredNetworkMode = Phone.NT_MODE_GLOBAL;
}
if (TelephonyManager.getLteOnGsmModeStatic() != 0) {
preferredNetworkMode = Phone.NT_MODE_LTE_GSM_WCDMA;
}
int networkMode = Settings.Global.getInt(context.getContentResolver(),
Settings.Global.PREFERRED_NETWORK_MODE, preferredNetworkMode);
Rlog.i(LOG_TAG, "Network Mode set to " + Integer.toString(networkMode));
int cdmaSubscription = CdmaSubscriptionSourceManager.getDefault(context);
Rlog.i(LOG_TAG, "Cdma Subscription set to " + cdmaSubscription);
//reads the system properties and makes commandsinterface
String sRILClassname = SystemProperties.get("ro.telephony.ril_class", "RIL").trim();
Rlog.i(LOG_TAG, "RILClassname is " + sRILClassname);
// Use reflection to construct the RIL class (defaults to RIL)
try {
sCommandsInterface = instantiateCustomRIL(
sRILClassname, context, networkMode, cdmaSubscription);
} catch (Exception e) {
// 6 different types of exceptions are thrown here that it's
// easier to just catch Exception as our "error handling" is the same.
- Rlog.e(LOG_TAG, "Unable to construct custom RIL class", e);
- sCommandsInterface = new RIL(context, networkMode, cdmaSubscription);
+ // Yes, we're blocking the whole thing and making the radio unusable. That's by design.
+ // The log message should make it clear why the radio is broken
+ while (true) {
+ Rlog.e(LOG_TAG, "Unable to construct custom RIL class", e);
+ try {Thread.sleep(10000);} catch (InterruptedException ie) {}
+ }
}
// Instantiate UiccController so that all other classes can just call getInstance()
UiccController.make(context, sCommandsInterface);
int phoneType = TelephonyManager.getPhoneType(networkMode);
if (phoneType == PhoneConstants.PHONE_TYPE_GSM) {
Rlog.i(LOG_TAG, "Creating GSMPhone");
sProxyPhone = new PhoneProxy(new GSMPhone(context,
sCommandsInterface, sPhoneNotifier));
} else if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
switch (TelephonyManager.getLteOnCdmaModeStatic()) {
case PhoneConstants.LTE_ON_CDMA_TRUE:
Rlog.i(LOG_TAG, "Creating CDMALTEPhone");
sProxyPhone = new PhoneProxy(new CDMALTEPhone(context,
sCommandsInterface, sPhoneNotifier));
break;
case PhoneConstants.LTE_ON_CDMA_FALSE:
default:
Rlog.i(LOG_TAG, "Creating CDMAPhone");
sProxyPhone = new PhoneProxy(new CDMAPhone(context,
sCommandsInterface, sPhoneNotifier));
break;
}
}
// Ensure that we have a default SMS app. Requesting the app with
// updateIfNeeded set to true is enough to configure a default SMS app.
ComponentName componentName =
SmsApplication.getDefaultSmsApplication(context, true /* updateIfNeeded */);
String packageName = "NONE";
if (componentName != null) {
packageName = componentName.getPackageName();
}
Rlog.i(LOG_TAG, "defaultSmsApplication: " + packageName);
// Set up monitor to watch for changes to SMS packages
SmsApplication.initSmsPackageMonitor(context);
sMadeDefaults = true;
}
}
}
private static <T> T instantiateCustomRIL(
String sRILClassname, Context context, int networkMode, int cdmaSubscription)
throws Exception {
Class<?> clazz = Class.forName("com.android.internal.telephony." + sRILClassname);
Constructor<?> constructor = clazz.getConstructor(Context.class, int.class, int.class);
return (T) clazz.cast(constructor.newInstance(context, networkMode, cdmaSubscription));
}
public static Phone getDefaultPhone() {
if (sLooper != Looper.myLooper()) {
throw new RuntimeException(
"PhoneFactory.getDefaultPhone must be called from Looper thread");
}
if (!sMadeDefaults) {
throw new IllegalStateException("Default phones haven't been made yet!");
}
return sProxyPhone;
}
public static Phone getCdmaPhone() {
Phone phone;
synchronized(PhoneProxy.lockForRadioTechnologyChange) {
switch (TelephonyManager.getLteOnCdmaModeStatic()) {
case PhoneConstants.LTE_ON_CDMA_TRUE: {
phone = new CDMALTEPhone(sContext, sCommandsInterface, sPhoneNotifier);
break;
}
case PhoneConstants.LTE_ON_CDMA_FALSE:
case PhoneConstants.LTE_ON_CDMA_UNKNOWN:
default: {
phone = new CDMAPhone(sContext, sCommandsInterface, sPhoneNotifier);
break;
}
}
}
return phone;
}
public static Phone getGsmPhone() {
synchronized(PhoneProxy.lockForRadioTechnologyChange) {
Phone phone = new GSMPhone(sContext, sCommandsInterface, sPhoneNotifier);
return phone;
}
}
/**
* Makes a {@link SipPhone} object.
* @param sipUri the local SIP URI the phone runs on
* @return the {@code SipPhone} object or null if the SIP URI is not valid
*/
public static SipPhone makeSipPhone(String sipUri) {
return SipPhoneFactory.makePhone(sipUri, sContext, sPhoneNotifier);
}
}
| true | true | public static void makeDefaultPhone(Context context) {
synchronized(Phone.class) {
if (!sMadeDefaults) {
sLooper = Looper.myLooper();
sContext = context;
if (sLooper == null) {
throw new RuntimeException(
"PhoneFactory.makeDefaultPhone must be called from Looper thread");
}
int retryCount = 0;
for(;;) {
boolean hasException = false;
retryCount ++;
try {
// use UNIX domain socket to
// prevent subsequent initialization
new LocalServerSocket("com.android.internal.telephony");
} catch (java.io.IOException ex) {
hasException = true;
}
if ( !hasException ) {
break;
} else if (retryCount > SOCKET_OPEN_MAX_RETRY) {
throw new RuntimeException("PhoneFactory probably already running");
} else {
try {
Thread.sleep(SOCKET_OPEN_RETRY_MILLIS);
} catch (InterruptedException er) {
}
}
}
sPhoneNotifier = new DefaultPhoneNotifier();
// Get preferred network mode
int preferredNetworkMode = RILConstants.PREFERRED_NETWORK_MODE;
if (TelephonyManager.getLteOnCdmaModeStatic() == PhoneConstants.LTE_ON_CDMA_TRUE) {
preferredNetworkMode = Phone.NT_MODE_GLOBAL;
}
if (TelephonyManager.getLteOnGsmModeStatic() != 0) {
preferredNetworkMode = Phone.NT_MODE_LTE_GSM_WCDMA;
}
int networkMode = Settings.Global.getInt(context.getContentResolver(),
Settings.Global.PREFERRED_NETWORK_MODE, preferredNetworkMode);
Rlog.i(LOG_TAG, "Network Mode set to " + Integer.toString(networkMode));
int cdmaSubscription = CdmaSubscriptionSourceManager.getDefault(context);
Rlog.i(LOG_TAG, "Cdma Subscription set to " + cdmaSubscription);
//reads the system properties and makes commandsinterface
String sRILClassname = SystemProperties.get("ro.telephony.ril_class", "RIL").trim();
Rlog.i(LOG_TAG, "RILClassname is " + sRILClassname);
// Use reflection to construct the RIL class (defaults to RIL)
try {
sCommandsInterface = instantiateCustomRIL(
sRILClassname, context, networkMode, cdmaSubscription);
} catch (Exception e) {
// 6 different types of exceptions are thrown here that it's
// easier to just catch Exception as our "error handling" is the same.
Rlog.e(LOG_TAG, "Unable to construct custom RIL class", e);
sCommandsInterface = new RIL(context, networkMode, cdmaSubscription);
}
// Instantiate UiccController so that all other classes can just call getInstance()
UiccController.make(context, sCommandsInterface);
int phoneType = TelephonyManager.getPhoneType(networkMode);
if (phoneType == PhoneConstants.PHONE_TYPE_GSM) {
Rlog.i(LOG_TAG, "Creating GSMPhone");
sProxyPhone = new PhoneProxy(new GSMPhone(context,
sCommandsInterface, sPhoneNotifier));
} else if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
switch (TelephonyManager.getLteOnCdmaModeStatic()) {
case PhoneConstants.LTE_ON_CDMA_TRUE:
Rlog.i(LOG_TAG, "Creating CDMALTEPhone");
sProxyPhone = new PhoneProxy(new CDMALTEPhone(context,
sCommandsInterface, sPhoneNotifier));
break;
case PhoneConstants.LTE_ON_CDMA_FALSE:
default:
Rlog.i(LOG_TAG, "Creating CDMAPhone");
sProxyPhone = new PhoneProxy(new CDMAPhone(context,
sCommandsInterface, sPhoneNotifier));
break;
}
}
// Ensure that we have a default SMS app. Requesting the app with
// updateIfNeeded set to true is enough to configure a default SMS app.
ComponentName componentName =
SmsApplication.getDefaultSmsApplication(context, true /* updateIfNeeded */);
String packageName = "NONE";
if (componentName != null) {
packageName = componentName.getPackageName();
}
Rlog.i(LOG_TAG, "defaultSmsApplication: " + packageName);
// Set up monitor to watch for changes to SMS packages
SmsApplication.initSmsPackageMonitor(context);
sMadeDefaults = true;
}
}
}
| public static void makeDefaultPhone(Context context) {
synchronized(Phone.class) {
if (!sMadeDefaults) {
sLooper = Looper.myLooper();
sContext = context;
if (sLooper == null) {
throw new RuntimeException(
"PhoneFactory.makeDefaultPhone must be called from Looper thread");
}
int retryCount = 0;
for(;;) {
boolean hasException = false;
retryCount ++;
try {
// use UNIX domain socket to
// prevent subsequent initialization
new LocalServerSocket("com.android.internal.telephony");
} catch (java.io.IOException ex) {
hasException = true;
}
if ( !hasException ) {
break;
} else if (retryCount > SOCKET_OPEN_MAX_RETRY) {
throw new RuntimeException("PhoneFactory probably already running");
} else {
try {
Thread.sleep(SOCKET_OPEN_RETRY_MILLIS);
} catch (InterruptedException er) {
}
}
}
sPhoneNotifier = new DefaultPhoneNotifier();
// Get preferred network mode
int preferredNetworkMode = RILConstants.PREFERRED_NETWORK_MODE;
if (TelephonyManager.getLteOnCdmaModeStatic() == PhoneConstants.LTE_ON_CDMA_TRUE) {
preferredNetworkMode = Phone.NT_MODE_GLOBAL;
}
if (TelephonyManager.getLteOnGsmModeStatic() != 0) {
preferredNetworkMode = Phone.NT_MODE_LTE_GSM_WCDMA;
}
int networkMode = Settings.Global.getInt(context.getContentResolver(),
Settings.Global.PREFERRED_NETWORK_MODE, preferredNetworkMode);
Rlog.i(LOG_TAG, "Network Mode set to " + Integer.toString(networkMode));
int cdmaSubscription = CdmaSubscriptionSourceManager.getDefault(context);
Rlog.i(LOG_TAG, "Cdma Subscription set to " + cdmaSubscription);
//reads the system properties and makes commandsinterface
String sRILClassname = SystemProperties.get("ro.telephony.ril_class", "RIL").trim();
Rlog.i(LOG_TAG, "RILClassname is " + sRILClassname);
// Use reflection to construct the RIL class (defaults to RIL)
try {
sCommandsInterface = instantiateCustomRIL(
sRILClassname, context, networkMode, cdmaSubscription);
} catch (Exception e) {
// 6 different types of exceptions are thrown here that it's
// easier to just catch Exception as our "error handling" is the same.
// Yes, we're blocking the whole thing and making the radio unusable. That's by design.
// The log message should make it clear why the radio is broken
while (true) {
Rlog.e(LOG_TAG, "Unable to construct custom RIL class", e);
try {Thread.sleep(10000);} catch (InterruptedException ie) {}
}
}
// Instantiate UiccController so that all other classes can just call getInstance()
UiccController.make(context, sCommandsInterface);
int phoneType = TelephonyManager.getPhoneType(networkMode);
if (phoneType == PhoneConstants.PHONE_TYPE_GSM) {
Rlog.i(LOG_TAG, "Creating GSMPhone");
sProxyPhone = new PhoneProxy(new GSMPhone(context,
sCommandsInterface, sPhoneNotifier));
} else if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
switch (TelephonyManager.getLteOnCdmaModeStatic()) {
case PhoneConstants.LTE_ON_CDMA_TRUE:
Rlog.i(LOG_TAG, "Creating CDMALTEPhone");
sProxyPhone = new PhoneProxy(new CDMALTEPhone(context,
sCommandsInterface, sPhoneNotifier));
break;
case PhoneConstants.LTE_ON_CDMA_FALSE:
default:
Rlog.i(LOG_TAG, "Creating CDMAPhone");
sProxyPhone = new PhoneProxy(new CDMAPhone(context,
sCommandsInterface, sPhoneNotifier));
break;
}
}
// Ensure that we have a default SMS app. Requesting the app with
// updateIfNeeded set to true is enough to configure a default SMS app.
ComponentName componentName =
SmsApplication.getDefaultSmsApplication(context, true /* updateIfNeeded */);
String packageName = "NONE";
if (componentName != null) {
packageName = componentName.getPackageName();
}
Rlog.i(LOG_TAG, "defaultSmsApplication: " + packageName);
// Set up monitor to watch for changes to SMS packages
SmsApplication.initSmsPackageMonitor(context);
sMadeDefaults = true;
}
}
}
|
diff --git a/source/de/anomic/crawler/Balancer.java b/source/de/anomic/crawler/Balancer.java
index 609d2cd15..2461ec4ac 100644
--- a/source/de/anomic/crawler/Balancer.java
+++ b/source/de/anomic/crawler/Balancer.java
@@ -1,516 +1,516 @@
// plasmaCrawlBalancer.java
// -----------------------
// part of YaCy
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2005
// created: 24.09.2005
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package de.anomic.crawler;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import de.anomic.crawler.retrieval.Request;
import de.anomic.http.client.Cache;
import de.anomic.kelondro.index.Row;
import de.anomic.kelondro.index.ObjectIndex;
import de.anomic.kelondro.order.CloneableIterator;
import de.anomic.kelondro.table.Table;
import de.anomic.yacy.logging.Log;
public class Balancer {
private static final String indexSuffix = "9.db";
private static final int EcoFSBufferSize = 200;
// class variables
private final ConcurrentHashMap<String, LinkedList<String>> domainStacks; // a map from domain name part to Lists with url hashs
private ConcurrentLinkedQueue<String> top;
private TreeMap<Long, String> delayed;
protected ObjectIndex urlFileIndex;
private final File cacheStacksPath;
private long minimumLocalDelta;
private long minimumGlobalDelta;
private long lastDomainStackFill;
public Balancer(
final File cachePath,
final String stackname,
final long minimumLocalDelta,
final long minimumGlobalDelta,
final boolean useTailCache,
final boolean exceed134217727) {
this.cacheStacksPath = cachePath;
this.domainStacks = new ConcurrentHashMap<String, LinkedList<String>>();
this.top = new ConcurrentLinkedQueue<String>();
this.delayed = new TreeMap<Long, String>();
this.minimumLocalDelta = minimumLocalDelta;
this.minimumGlobalDelta = minimumGlobalDelta;
// create a stack for newly entered entries
if (!(cachePath.exists())) cachePath.mkdir(); // make the path
cacheStacksPath.mkdirs();
File f = new File(cacheStacksPath, stackname + indexSuffix);
urlFileIndex = new Table(f, Request.rowdef, EcoFSBufferSize, 0, useTailCache, exceed134217727);
lastDomainStackFill = 0;
Log.logInfo("Balancer", "opened balancer file with " + urlFileIndex.size() + " entries from " + f.toString());
}
public long getMinimumLocalDelta() {
return this.minimumLocalDelta;
}
public long getMinimumGlobalDelta() {
return this.minimumGlobalDelta;
}
public void setMinimumDelta(final long minimumLocalDelta, final long minimumGlobalDelta) {
this.minimumLocalDelta = minimumLocalDelta;
this.minimumGlobalDelta = minimumGlobalDelta;
}
public synchronized void close() {
if (urlFileIndex != null) {
urlFileIndex.close();
urlFileIndex = null;
}
}
public void clear() {
Log.logInfo("Balancer", "cleaning balancer with " + urlFileIndex.size() + " entries from " + urlFileIndex.filename());
try {
urlFileIndex.clear();
} catch (IOException e) {
e.printStackTrace();
}
domainStacks.clear();
top.clear();
synchronized (this.delayed) {
delayed.clear();
}
}
public Request get(final String urlhash) throws IOException {
assert urlhash != null;
if (urlFileIndex == null) return null; // case occurs during shutdown
final Row.Entry entry = urlFileIndex.get(urlhash.getBytes());
if (entry == null) return null;
return new Request(entry);
}
public int removeAllByProfileHandle(final String profileHandle, final long timeout) throws IOException {
// removes all entries with a specific profile hash.
// this may last some time
// returns number of deletions
// first find a list of url hashes that shall be deleted
final HashSet<String> urlHashes = new HashSet<String>();
final long terminate = (timeout > 0) ? System.currentTimeMillis() + timeout : Long.MAX_VALUE;
synchronized (this) {
final Iterator<Row.Entry> i = urlFileIndex.rows();
Row.Entry rowEntry;
Request crawlEntry;
while (i.hasNext() && (System.currentTimeMillis() < terminate)) {
rowEntry = i.next();
crawlEntry = new Request(rowEntry);
if (crawlEntry.profileHandle().equals(profileHandle)) {
urlHashes.add(crawlEntry.url().hash());
}
}
}
// then delete all these urls from the queues and the file index
return this.remove(urlHashes);
}
/**
* this method is only here, because so many import/export methods need it
and it was implemented in the previous architecture
however, usage is not recommended
* @param urlHashes, a list of hashes that shall be removed
* @return number of entries that had been removed
* @throws IOException
*/
public synchronized int remove(final HashSet<String> urlHashes) throws IOException {
final int s = urlFileIndex.size();
int removedCounter = 0;
for (final String urlhash: urlHashes) {
final Row.Entry entry = urlFileIndex.remove(urlhash.getBytes());
if (entry != null) removedCounter++;
}
if (removedCounter == 0) return 0;
assert urlFileIndex.size() + removedCounter == s : "urlFileIndex.size() = " + urlFileIndex.size() + ", s = " + s;
// iterate through the top list
Iterator<String> j = top.iterator();
String urlhash;
while (j.hasNext()) {
urlhash = j.next();
if (urlHashes.contains(urlhash)) j.remove();
}
// remove from delayed
synchronized (this.delayed) {
Iterator<Map.Entry<Long, String>> k = this.delayed.entrySet().iterator();
while (k.hasNext()) {
if (urlHashes.contains(k.next().getValue())) k.remove();
}
}
// iterate through the domain stacks
final Iterator<Map.Entry<String, LinkedList<String>>> q = domainStacks.entrySet().iterator();
Map.Entry<String, LinkedList<String>> se;
LinkedList<String> stack;
while (q.hasNext()) {
se = q.next();
stack = se.getValue();
Iterator<String> i = stack.iterator();
while (i.hasNext()) {
if (urlHashes.contains(i.next())) i.remove();
}
if (stack.size() == 0) q.remove();
}
return removedCounter;
}
public boolean has(final String urlhash) {
return urlFileIndex.has(urlhash.getBytes());
}
public boolean notEmpty() {
// alternative method to the property size() > 0
// this is better because it may avoid synchronized access to domain stack summarization
return domainStacksNotEmpty();
}
public int size() {
return urlFileIndex.size();
}
private boolean domainStacksNotEmpty() {
if (domainStacks == null) return false;
synchronized (domainStacks) {
final Iterator<LinkedList<String>> i = domainStacks.values().iterator();
while (i.hasNext()) {
if (i.next().size() > 0) return true;
}
}
return false;
}
public void push(final Request entry) throws IOException {
assert entry != null;
String hash = entry.url().hash();
synchronized (this) {
if (urlFileIndex.has(hash.getBytes())) {
//Log.logWarning("BALANCER", "double-check has failed for urlhash " + entry.url().hash() + " in " + stackname + " - fixed");
return;
}
// add to index
int s = urlFileIndex.size();
urlFileIndex.put(entry.toRow());
assert s < urlFileIndex.size() : "hash = " + hash;
assert urlFileIndex.has(hash.getBytes()) : "hash = " + hash;
// add the hash to a queue
pushHashToDomainStacks(entry.url().hash(), 50);
}
}
private void pushHashToDomainStacks(final String hash, int maxstacksize) {
// extend domain stack
final String dom = hash.substring(6);
LinkedList<String> domainList = domainStacks.get(dom);
if (domainList == null) {
// create new list
domainList = new LinkedList<String>();
domainList.add(hash);
domainStacks.put(dom, domainList);
} else {
// extend existent domain list
if (domainList.size() < maxstacksize) domainList.addLast(hash);
}
}
private void removeHashFromDomainStacks(final String hash) {
// extend domain stack
final String dom = hash.substring(6);
LinkedList<String> domainList = domainStacks.get(dom);
if (domainList == null) return;
Iterator<String> i = domainList.iterator();
while (i.hasNext()) {
if (i.next().equals(hash)) {
i.remove();
return;
}
}
}
private String nextFromDelayed() {
if (this.delayed.size() == 0) return null;
if (this.delayed.size() == 0) return null;
Long first = this.delayed.firstKey();
if (first.longValue() < System.currentTimeMillis()) {
return this.delayed.remove(first);
}
return null;
}
/**
* get the next entry in this crawl queue in such a way that the domain access time delta is maximized
* and always above the given minimum delay time. An additional delay time is computed using the robots.txt
* crawl-delay time which is always respected. In case the minimum time cannot ensured, this method pauses
* the necessary time until the url is released and returned as CrawlEntry object. In case that a profile
* for the computed Entry does not exist, null is returned
* @param delay true if the requester demands forced delays using explicit thread sleep
* @param profile
* @return a url in a CrawlEntry object
* @throws IOException
*/
public Request pop(final boolean delay, final CrawlProfile profile) throws IOException {
// returns a crawl entry from the stack and ensures minimum delta times
filltop(delay, -600000, false);
filltop(delay, -60000, false);
filltop(delay, -10000, false);
filltop(delay, -6000, false);
filltop(delay, -4000, false);
filltop(delay, -3000, false);
filltop(delay, -2000, false);
filltop(delay, -1000, false);
filltop(delay, -500, false);
filltop(delay, 0, true);
long sleeptime = 0;
Request crawlEntry = null;
synchronized (this) {
String failhash = null;
while (this.urlFileIndex.size() > 0) {
// first simply take one of the entries in the top list, that should be one without any delay
String nexthash = nextFromDelayed();
//System.out.println("*** nextFromDelayed=" + nexthash);
if (nexthash == null && this.top.size() > 0) {
nexthash = top.remove();
//System.out.println("*** top.remove()=" + nexthash);
}
// check minimumDelta and if necessary force a sleep
//final int s = urlFileIndex.size();
Row.Entry rowEntry = (nexthash == null) ? null : urlFileIndex.remove(nexthash.getBytes());
if (rowEntry == null) {
//System.out.println("*** rowEntry=null, nexthash=" + nexthash);
rowEntry = urlFileIndex.removeOne();
if (rowEntry == null) {
nexthash = null;
} else {
nexthash = new String(rowEntry.getPrimaryKeyBytes());
//System.out.println("*** rowEntry.getPrimaryKeyBytes()=" + nexthash);
}
}
if (rowEntry == null) {
Log.logWarning("Balancer", "removeOne() failed - size = " + this.size());
return null;
}
//assert urlFileIndex.size() + 1 == s : "urlFileIndex.size() = " + urlFileIndex.size() + ", s = " + s + ", result = " + result;
crawlEntry = new Request(rowEntry);
//Log.logInfo("Balancer", "fetched next url: " + crawlEntry.url().toNormalform(true, false));
// at this point we must check if the crawlEntry has relevancy because the crawl profile still exists
// if not: return null. A calling method must handle the null value and try again
CrawlProfile.entry profileEntry = (profile == null) ? null : profile.getEntry(crawlEntry.profileHandle());
if (profileEntry == null) {
Log.logWarning("Balancer", "no profile entry for handle " + crawlEntry.profileHandle());
return null;
}
// depending on the caching policy we need sleep time to avoid DoS-like situations
sleeptime = (
profileEntry.cacheStrategy() == CrawlProfile.CACHE_STRATEGY_CACHEONLY ||
(profileEntry.cacheStrategy() == CrawlProfile.CACHE_STRATEGY_IFEXIST && Cache.has(crawlEntry.url()))
) ? 0 : Latency.waitingRemaining(crawlEntry.url(), minimumLocalDelta, minimumGlobalDelta); // this uses the robots.txt database and may cause a loading of robots.txt from the server
assert nexthash.equals(new String(rowEntry.getPrimaryKeyBytes())) : "result = " + nexthash + ", rowEntry.getPrimaryKeyBytes() = " + new String(rowEntry.getPrimaryKeyBytes());
assert nexthash.equals(crawlEntry.url().hash()) : "result = " + nexthash + ", crawlEntry.url().hash() = " + crawlEntry.url().hash();
if (this.domainStacks.size() <= 1) break;
if (failhash != null && failhash.equals(nexthash)) break; // prevent endless loops
if (delay && sleeptime > 0) {
//System.out.println("*** putback: nexthash=" + nexthash + ", failhash="+failhash);
// put that thing back to omit a delay here
if (!delayed.values().contains(nexthash)) {
//System.out.println("*** delayed +=" + nexthash);
this.delayed.put(new Long(System.currentTimeMillis() + sleeptime + 1), nexthash);
}
this.urlFileIndex.put(rowEntry);
this.domainStacks.remove(nexthash.substring(6));
failhash = nexthash;
continue;
}
break;
}
}
if (crawlEntry == null) return null;
if (delay && sleeptime > 0) {
// force a busy waiting here
// in best case, this should never happen if the balancer works propertly
// this is only to protection against the worst case, where the crawler could
// behave in a DoS-manner
Log.logInfo("BALANCER", "forcing crawl-delay of " + sleeptime + " milliseconds for " + crawlEntry.url().getHost() + ((sleeptime > Math.max(minimumLocalDelta, minimumGlobalDelta)) ? " (forced latency)" : ""));
long loops = sleeptime / 3000;
long rest = sleeptime % 3000;
if (loops < 2) {
rest = rest + 3000 * loops;
loops = 0;
}
- try {synchronized(this) { this.wait(rest); }} catch (final InterruptedException e) {}
+ if (rest > 0) {try {synchronized(this) { this.wait(rest); }} catch (final InterruptedException e) {}}
for (int i = 0; i < loops; i++) {
Log.logInfo("BALANCER", "waiting for " + crawlEntry.url().getHost() + ": " + ((loops - i) * 3) + " seconds remaining...");
try {synchronized(this) { this.wait(3000); }} catch (final InterruptedException e) {}
}
if (sleeptime > 3000 && this.domainStacks.size() > 1) this.domainStacks.remove(crawlEntry.url().hash().substring(6));
}
Latency.update(crawlEntry.url().hash().substring(6), crawlEntry.url().getHost());
return crawlEntry;
}
private void filltop(boolean delay, long maximumwaiting, boolean acceptonebest) {
if (this.top.size() > 0) return;
//System.out.println("*** DEBUG started filltop delay=" + ((delay) ? "true":"false") + ", maximumwaiting=" + maximumwaiting + ", acceptonebest=" + ((acceptonebest) ? "true":"false"));
// check if we need to get entries from the file index
try {
fillDomainStacks(800);
} catch (IOException e) {
e.printStackTrace();
}
// iterate over the domain stacks
Iterator<Map.Entry<String, LinkedList<String>>> i = this.domainStacks.entrySet().iterator();
Map.Entry<String, LinkedList<String>> entry;
long smallestWaiting = Long.MAX_VALUE;
String besthash = null;
while (i.hasNext()) {
entry = i.next();
if (entry.getValue().size() == 0) {
i.remove();
continue;
}
String n = entry.getValue().getFirst();
if (delay) {
long w = Latency.waitingRemainingGuessed(n, minimumLocalDelta, minimumGlobalDelta);
if (w > maximumwaiting) {
if (w < smallestWaiting) {
smallestWaiting = w;
besthash = n;
}
continue;
}
//System.out.println("*** accepting " + n + " : " + w);
}
n = entry.getValue().removeFirst();
this.top.add(n);
if (entry.getValue().size() == 0) i.remove();
}
// if we could not find any entry, then take the best we have seen so far
if (acceptonebest && this.top.size() > 0 && besthash != null) {
removeHashFromDomainStacks(besthash);
this.top.add(besthash);
}
}
private void fillDomainStacks(int maxdomstacksize) throws IOException {
if (this.domainStacks.size() > 0 && System.currentTimeMillis() - lastDomainStackFill < 200000L) return;
this.domainStacks.clear();
//synchronized (this.delayed) { delayed.clear(); }
this.lastDomainStackFill = System.currentTimeMillis();
CloneableIterator<byte[]> i = this.urlFileIndex.keys(true, null);
while (i.hasNext()) {
pushHashToDomainStacks(new String(i.next()), 50);
if (this.domainStacks.size() > maxdomstacksize) break;
}
}
public ArrayList<Request> top(int count) {
count = Math.min(count, top.size());
ArrayList<Request> cel = new ArrayList<Request>();
if (count == 0) return cel;
synchronized (this) {
for (String n: top) {
try {
Row.Entry rowEntry = urlFileIndex.get(n.getBytes());
if (rowEntry == null) continue;
final Request crawlEntry = new Request(rowEntry);
cel.add(crawlEntry);
count--;
if (count <= 0) break;
} catch (IOException e) {
}
}
}
return cel;
}
public Iterator<Request> iterator() throws IOException {
return new EntryIterator();
}
private class EntryIterator implements Iterator<Request> {
private Iterator<Row.Entry> rowIterator;
public EntryIterator() throws IOException {
rowIterator = urlFileIndex.rows();
}
public boolean hasNext() {
return (rowIterator == null) ? false : rowIterator.hasNext();
}
public Request next() {
final Row.Entry entry = rowIterator.next();
try {
return (entry == null) ? null : new Request(entry);
} catch (final IOException e) {
rowIterator = null;
return null;
}
}
public void remove() {
if (rowIterator != null) rowIterator.remove();
}
}
}
| true | true | public Request pop(final boolean delay, final CrawlProfile profile) throws IOException {
// returns a crawl entry from the stack and ensures minimum delta times
filltop(delay, -600000, false);
filltop(delay, -60000, false);
filltop(delay, -10000, false);
filltop(delay, -6000, false);
filltop(delay, -4000, false);
filltop(delay, -3000, false);
filltop(delay, -2000, false);
filltop(delay, -1000, false);
filltop(delay, -500, false);
filltop(delay, 0, true);
long sleeptime = 0;
Request crawlEntry = null;
synchronized (this) {
String failhash = null;
while (this.urlFileIndex.size() > 0) {
// first simply take one of the entries in the top list, that should be one without any delay
String nexthash = nextFromDelayed();
//System.out.println("*** nextFromDelayed=" + nexthash);
if (nexthash == null && this.top.size() > 0) {
nexthash = top.remove();
//System.out.println("*** top.remove()=" + nexthash);
}
// check minimumDelta and if necessary force a sleep
//final int s = urlFileIndex.size();
Row.Entry rowEntry = (nexthash == null) ? null : urlFileIndex.remove(nexthash.getBytes());
if (rowEntry == null) {
//System.out.println("*** rowEntry=null, nexthash=" + nexthash);
rowEntry = urlFileIndex.removeOne();
if (rowEntry == null) {
nexthash = null;
} else {
nexthash = new String(rowEntry.getPrimaryKeyBytes());
//System.out.println("*** rowEntry.getPrimaryKeyBytes()=" + nexthash);
}
}
if (rowEntry == null) {
Log.logWarning("Balancer", "removeOne() failed - size = " + this.size());
return null;
}
//assert urlFileIndex.size() + 1 == s : "urlFileIndex.size() = " + urlFileIndex.size() + ", s = " + s + ", result = " + result;
crawlEntry = new Request(rowEntry);
//Log.logInfo("Balancer", "fetched next url: " + crawlEntry.url().toNormalform(true, false));
// at this point we must check if the crawlEntry has relevancy because the crawl profile still exists
// if not: return null. A calling method must handle the null value and try again
CrawlProfile.entry profileEntry = (profile == null) ? null : profile.getEntry(crawlEntry.profileHandle());
if (profileEntry == null) {
Log.logWarning("Balancer", "no profile entry for handle " + crawlEntry.profileHandle());
return null;
}
// depending on the caching policy we need sleep time to avoid DoS-like situations
sleeptime = (
profileEntry.cacheStrategy() == CrawlProfile.CACHE_STRATEGY_CACHEONLY ||
(profileEntry.cacheStrategy() == CrawlProfile.CACHE_STRATEGY_IFEXIST && Cache.has(crawlEntry.url()))
) ? 0 : Latency.waitingRemaining(crawlEntry.url(), minimumLocalDelta, minimumGlobalDelta); // this uses the robots.txt database and may cause a loading of robots.txt from the server
assert nexthash.equals(new String(rowEntry.getPrimaryKeyBytes())) : "result = " + nexthash + ", rowEntry.getPrimaryKeyBytes() = " + new String(rowEntry.getPrimaryKeyBytes());
assert nexthash.equals(crawlEntry.url().hash()) : "result = " + nexthash + ", crawlEntry.url().hash() = " + crawlEntry.url().hash();
if (this.domainStacks.size() <= 1) break;
if (failhash != null && failhash.equals(nexthash)) break; // prevent endless loops
if (delay && sleeptime > 0) {
//System.out.println("*** putback: nexthash=" + nexthash + ", failhash="+failhash);
// put that thing back to omit a delay here
if (!delayed.values().contains(nexthash)) {
//System.out.println("*** delayed +=" + nexthash);
this.delayed.put(new Long(System.currentTimeMillis() + sleeptime + 1), nexthash);
}
this.urlFileIndex.put(rowEntry);
this.domainStacks.remove(nexthash.substring(6));
failhash = nexthash;
continue;
}
break;
}
}
if (crawlEntry == null) return null;
if (delay && sleeptime > 0) {
// force a busy waiting here
// in best case, this should never happen if the balancer works propertly
// this is only to protection against the worst case, where the crawler could
// behave in a DoS-manner
Log.logInfo("BALANCER", "forcing crawl-delay of " + sleeptime + " milliseconds for " + crawlEntry.url().getHost() + ((sleeptime > Math.max(minimumLocalDelta, minimumGlobalDelta)) ? " (forced latency)" : ""));
long loops = sleeptime / 3000;
long rest = sleeptime % 3000;
if (loops < 2) {
rest = rest + 3000 * loops;
loops = 0;
}
try {synchronized(this) { this.wait(rest); }} catch (final InterruptedException e) {}
for (int i = 0; i < loops; i++) {
Log.logInfo("BALANCER", "waiting for " + crawlEntry.url().getHost() + ": " + ((loops - i) * 3) + " seconds remaining...");
try {synchronized(this) { this.wait(3000); }} catch (final InterruptedException e) {}
}
if (sleeptime > 3000 && this.domainStacks.size() > 1) this.domainStacks.remove(crawlEntry.url().hash().substring(6));
}
Latency.update(crawlEntry.url().hash().substring(6), crawlEntry.url().getHost());
return crawlEntry;
}
| public Request pop(final boolean delay, final CrawlProfile profile) throws IOException {
// returns a crawl entry from the stack and ensures minimum delta times
filltop(delay, -600000, false);
filltop(delay, -60000, false);
filltop(delay, -10000, false);
filltop(delay, -6000, false);
filltop(delay, -4000, false);
filltop(delay, -3000, false);
filltop(delay, -2000, false);
filltop(delay, -1000, false);
filltop(delay, -500, false);
filltop(delay, 0, true);
long sleeptime = 0;
Request crawlEntry = null;
synchronized (this) {
String failhash = null;
while (this.urlFileIndex.size() > 0) {
// first simply take one of the entries in the top list, that should be one without any delay
String nexthash = nextFromDelayed();
//System.out.println("*** nextFromDelayed=" + nexthash);
if (nexthash == null && this.top.size() > 0) {
nexthash = top.remove();
//System.out.println("*** top.remove()=" + nexthash);
}
// check minimumDelta and if necessary force a sleep
//final int s = urlFileIndex.size();
Row.Entry rowEntry = (nexthash == null) ? null : urlFileIndex.remove(nexthash.getBytes());
if (rowEntry == null) {
//System.out.println("*** rowEntry=null, nexthash=" + nexthash);
rowEntry = urlFileIndex.removeOne();
if (rowEntry == null) {
nexthash = null;
} else {
nexthash = new String(rowEntry.getPrimaryKeyBytes());
//System.out.println("*** rowEntry.getPrimaryKeyBytes()=" + nexthash);
}
}
if (rowEntry == null) {
Log.logWarning("Balancer", "removeOne() failed - size = " + this.size());
return null;
}
//assert urlFileIndex.size() + 1 == s : "urlFileIndex.size() = " + urlFileIndex.size() + ", s = " + s + ", result = " + result;
crawlEntry = new Request(rowEntry);
//Log.logInfo("Balancer", "fetched next url: " + crawlEntry.url().toNormalform(true, false));
// at this point we must check if the crawlEntry has relevancy because the crawl profile still exists
// if not: return null. A calling method must handle the null value and try again
CrawlProfile.entry profileEntry = (profile == null) ? null : profile.getEntry(crawlEntry.profileHandle());
if (profileEntry == null) {
Log.logWarning("Balancer", "no profile entry for handle " + crawlEntry.profileHandle());
return null;
}
// depending on the caching policy we need sleep time to avoid DoS-like situations
sleeptime = (
profileEntry.cacheStrategy() == CrawlProfile.CACHE_STRATEGY_CACHEONLY ||
(profileEntry.cacheStrategy() == CrawlProfile.CACHE_STRATEGY_IFEXIST && Cache.has(crawlEntry.url()))
) ? 0 : Latency.waitingRemaining(crawlEntry.url(), minimumLocalDelta, minimumGlobalDelta); // this uses the robots.txt database and may cause a loading of robots.txt from the server
assert nexthash.equals(new String(rowEntry.getPrimaryKeyBytes())) : "result = " + nexthash + ", rowEntry.getPrimaryKeyBytes() = " + new String(rowEntry.getPrimaryKeyBytes());
assert nexthash.equals(crawlEntry.url().hash()) : "result = " + nexthash + ", crawlEntry.url().hash() = " + crawlEntry.url().hash();
if (this.domainStacks.size() <= 1) break;
if (failhash != null && failhash.equals(nexthash)) break; // prevent endless loops
if (delay && sleeptime > 0) {
//System.out.println("*** putback: nexthash=" + nexthash + ", failhash="+failhash);
// put that thing back to omit a delay here
if (!delayed.values().contains(nexthash)) {
//System.out.println("*** delayed +=" + nexthash);
this.delayed.put(new Long(System.currentTimeMillis() + sleeptime + 1), nexthash);
}
this.urlFileIndex.put(rowEntry);
this.domainStacks.remove(nexthash.substring(6));
failhash = nexthash;
continue;
}
break;
}
}
if (crawlEntry == null) return null;
if (delay && sleeptime > 0) {
// force a busy waiting here
// in best case, this should never happen if the balancer works propertly
// this is only to protection against the worst case, where the crawler could
// behave in a DoS-manner
Log.logInfo("BALANCER", "forcing crawl-delay of " + sleeptime + " milliseconds for " + crawlEntry.url().getHost() + ((sleeptime > Math.max(minimumLocalDelta, minimumGlobalDelta)) ? " (forced latency)" : ""));
long loops = sleeptime / 3000;
long rest = sleeptime % 3000;
if (loops < 2) {
rest = rest + 3000 * loops;
loops = 0;
}
if (rest > 0) {try {synchronized(this) { this.wait(rest); }} catch (final InterruptedException e) {}}
for (int i = 0; i < loops; i++) {
Log.logInfo("BALANCER", "waiting for " + crawlEntry.url().getHost() + ": " + ((loops - i) * 3) + " seconds remaining...");
try {synchronized(this) { this.wait(3000); }} catch (final InterruptedException e) {}
}
if (sleeptime > 3000 && this.domainStacks.size() > 1) this.domainStacks.remove(crawlEntry.url().hash().substring(6));
}
Latency.update(crawlEntry.url().hash().substring(6), crawlEntry.url().getHost());
return crawlEntry;
}
|
diff --git a/src/core/Tower.java b/src/core/Tower.java
index 4212433..e7b3ac2 100644
--- a/src/core/Tower.java
+++ b/src/core/Tower.java
@@ -1,146 +1,147 @@
package src.core;
import java.util.HashMap;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import src.core.XML.TowerXMLReader;
import src.ui.IDrawableTower;
/**
* Represents a tower and all of its attributes, including attack radius, which
* creeps to attack first, damage done, and how fast to fire.
*/
public class Tower implements IDrawableTower, IPurchasable {
private static HashMap<Type, Tower> templateTowers = null;
@Attribute
private Tower.Type type;
@Element
private Damage damage;
@Element
private double radius;
@Element
private double fireRate;
@Element
private double price;
@Element(required=false)
private TargetingInfo targeting;
private int x, y;
private double investment;
public static Tower createTower(Type t){
if (templateTowers == null) {
- templateTowers = TowerXMLReader.readXML("bin/src/core/XML/exampleTower.xml");
+ //templateTowers = TowerXMLReader.readXML("/src/core/XML/exampleTower.xml");
+ templateTowers = TowerXMLReader.readXML("/home/jqtran/course/cs032/cs32final/src/core/XML/exampleTower.xml");
}
Tower template = templateTowers.get(t);
Tower tower = new Tower();
tower.setDamage(template.getDamage());
tower.setFireRate(template.getFireRate());
tower.setPrice(template.getPrice());
tower.setRadius(template.getRadius());
tower.setType(t);
return tower;
}
public Tower() {
targeting = new TargetingInfo();
}
public double getFireRate() {
return fireRate;
}
public void setFireRate(double fireRate) {
this.fireRate = fireRate;
}
public TargetingInfo getTargeting() {
return targeting;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public enum Type {
GUN, ANTIAIR, SLOWING, MORTAR, FRIEND, FLAME, STASIS, HTA;
}
public Damage getDamage() {
return damage;
}
public void setDamage(Damage damage) {
this.damage = damage;
}
public double getOrientation() {
// TODO: stub
return 0;
}
public void setType(Tower.Type t){
type = t;
}
public Type getType() {
return type;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void setInvestment(double d) {
investment = d;
}
public double getInvestment() {
return investment;
}
// Applies an upgrade u onto this tower, modifying its Damage,
// TargetingInfo, and self
public void applyUpgrade(Upgrade u) {
u.updateDamage(damage); // all damage modifications
u.updateTargeting(targeting); // canHitFlying
u.updateTower(this); // radius, rate of fire, investment
}
public double getPrice() {
return price;
}
public void setPrice(double p) {
price = p;
}
}
| true | true | public static Tower createTower(Type t){
if (templateTowers == null) {
templateTowers = TowerXMLReader.readXML("bin/src/core/XML/exampleTower.xml");
}
Tower template = templateTowers.get(t);
Tower tower = new Tower();
tower.setDamage(template.getDamage());
tower.setFireRate(template.getFireRate());
tower.setPrice(template.getPrice());
tower.setRadius(template.getRadius());
tower.setType(t);
return tower;
}
| public static Tower createTower(Type t){
if (templateTowers == null) {
//templateTowers = TowerXMLReader.readXML("/src/core/XML/exampleTower.xml");
templateTowers = TowerXMLReader.readXML("/home/jqtran/course/cs032/cs32final/src/core/XML/exampleTower.xml");
}
Tower template = templateTowers.get(t);
Tower tower = new Tower();
tower.setDamage(template.getDamage());
tower.setFireRate(template.getFireRate());
tower.setPrice(template.getPrice());
tower.setRadius(template.getRadius());
tower.setType(t);
return tower;
}
|
diff --git a/api/src/test/java/org/openmrs/module/pacsintegration/component/HL7ListenerComponentTest.java b/api/src/test/java/org/openmrs/module/pacsintegration/component/HL7ListenerComponentTest.java
index 06b3187..499e4d5 100644
--- a/api/src/test/java/org/openmrs/module/pacsintegration/component/HL7ListenerComponentTest.java
+++ b/api/src/test/java/org/openmrs/module/pacsintegration/component/HL7ListenerComponentTest.java
@@ -1,174 +1,175 @@
/*
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.module.pacsintegration.component;
import org.junit.Before;
import org.junit.Test;
import org.openmrs.Encounter;
import org.openmrs.Patient;
import org.openmrs.api.EncounterService;
import org.openmrs.api.PatientService;
import org.openmrs.module.ModuleActivator;
import org.openmrs.module.emr.radiology.RadiologyProperties;
import org.openmrs.module.emrapi.EmrApiProperties;
import org.openmrs.module.pacsintegration.PacsIntegrationActivator;
import org.openmrs.test.BaseModuleContextSensitiveTest;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.StringContains.containsString;
import static org.junit.Assert.assertThat;
public class HL7ListenerComponentTest extends BaseModuleContextSensitiveTest {
protected static final String XML_DATASET = "org/openmrs/module/pacsintegration/include/pacsIntegrationTestDataset.xml";
private char header = '\u000B';
private char trailer = '\u001C';
@Autowired
private PatientService patientService;
@Autowired
private EncounterService encounterService;
@Autowired
private EmrApiProperties emrApiProperties;
@Autowired
private RadiologyProperties radiologyProperties;
@Before
public void setup() throws Exception {
executeDataSet(XML_DATASET);
}
@Test
public void shouldListenForAndParseORU_R01Message() throws Exception {
ModuleActivator activator = new PacsIntegrationActivator();
activator.started();
List<Patient> patients = patientService.getPatients(null, "101-6", Collections.singletonList(emrApiProperties.getPrimaryIdentifierType()), true);
assertThat(patients.size(), is(1)); // sanity check
Patient patient = patients.get(0);
List<Encounter> encounters = encounterService.getEncounters(patient, null, null, null, null, Collections.singletonList(radiologyProperties.getRadiologyReportEncounterType()),
null, null, null, false);
assertThat(encounters.size(), is(0)); // sanity check
try {
String message = "MSH|^~\\&|HMI|Mirebalais Hospital|RAD|REPORTS|20130228174549||ORU^R01|RTS01CE16055AAF5290|P|2.3|\r" +
"PID|1||101-6||Patient^Test^||19770222|M||||||||||\r" +
"PV1|1||||||||||||||||||\r" +
"OBR|1||0000001297|127689^SOME_X-RAY|||20130228170556||||||||||||MBL^CR||||||F|||||||M123&Goodrich&Mark&&&&||||20130228170556\r" +
"OBX|1|TX|127689^SOME_X-RAY||Clinical Indication: ||||||F\r";
Thread.sleep(1000); // give the simple server time to start
Socket socket = new Socket("127.0.0.1", 6662);
PrintStream writer = new PrintStream(socket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer.print(header);
writer.print(message);
writer.print(trailer +"\r");
writer.flush();
Thread.sleep(1000);
// confirm that report encounter has been created and has obs (we more thoroughly test the handler in the ORU_R01 handler and Radiology Service (in emr module) tests)
encounters = encounterService.getEncounters(patient, null, null, null, null, Collections.singletonList(radiologyProperties.getRadiologyReportEncounterType()),
null, null, null, false);
assertThat(encounters.size(), is(1));
assertThat(encounters.get(0).getObs().size(), is(4));
// confirm that the proper ack is sent out
String response = reader.readLine();
assertThat(response, containsString("|ACK|"));
}
finally {
activator.stopped();
}
}
@Test
public void shouldListenForAndParseORM_001Message() throws Exception {
ModuleActivator activator = new PacsIntegrationActivator();
activator.started();
List<Patient> patients = patientService.getPatients(null, "101-6", Collections.singletonList(emrApiProperties.getPrimaryIdentifierType()), true);
assertThat(patients.size(), is(1)); // sanity check
Patient patient = patients.get(0);
List<Encounter> encounters = encounterService.getEncounters(patient, null, null, null, null, Collections.singletonList(radiologyProperties.getRadiologyStudyEncounterType()),
null, null, null, false);
assertThat(encounters.size(), is(0)); // sanity check
try {
String message = "MSH|^~\\&|HMI||RAD|REPORTS|20130228174643||ORM^O01|RTS01CE16057B105AC0|P|2.3|\r" +
"PID|1||101-6||Patient^Test^||19770222|M||||||||||\r" +
"ORC|\r" +
"OBR|1||0000001297|127689^SOME_X-RAY|||20130228170350||||||||||||MBL^CR||||||P|||||||&Goodrich&Mark&&&&^||||20130228170350\r" +
"OBX|1|RP|||||||||F\r" +
"OBX|2|TX|EventType^EventType|1|REVIEWED\r" +
"OBX|3|CN|Technologist^Technologist|1|1435^Duck^Donald\r" +
"OBX|4|TX|ExamRoom^ExamRoom|1|100AcreWoods\r" +
"OBX|5|TS|StartDateTime^StartDateTime|1|20111009215317\r" +
"OBX|6|TS|StopDateTime^StopDateTime|1|20111009215817\r" +
+ "OBX|7|TX|ImagesAvailable^ImagesAvailable|1|1\r" +
"ZDS|2.16.840.1.113883.3.234.1.3.101.1.2.1013.2011.15607503.2^HMI^Application^DICOM\r";
Thread.sleep(1000); // give the simple server time to start
Socket socket = new Socket("127.0.0.1", 6662);
PrintStream writer = new PrintStream(socket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer.print(header);
writer.print(message);
writer.print(trailer +"\r");
writer.flush();
Thread.sleep(1000);
// confirm that report encounter has been created and has obs (we more thoroughly test the handler in the ORU_R01 handler and Radiology Service (in emr module) tests)
encounters = encounterService.getEncounters(patient, null, null, null, null, Collections.singletonList(radiologyProperties.getRadiologyStudyEncounterType()),
null, null, null, false);
assertThat(encounters.size(), is(1));
assertThat(encounters.get(0).getObs().size(), is(3));
// confirm that the proper ack is sent out
String response = reader.readLine();
assertThat(response, containsString("|ACK|"));
}
finally {
activator.stopped();
}
}
}
| true | true | public void shouldListenForAndParseORM_001Message() throws Exception {
ModuleActivator activator = new PacsIntegrationActivator();
activator.started();
List<Patient> patients = patientService.getPatients(null, "101-6", Collections.singletonList(emrApiProperties.getPrimaryIdentifierType()), true);
assertThat(patients.size(), is(1)); // sanity check
Patient patient = patients.get(0);
List<Encounter> encounters = encounterService.getEncounters(patient, null, null, null, null, Collections.singletonList(radiologyProperties.getRadiologyStudyEncounterType()),
null, null, null, false);
assertThat(encounters.size(), is(0)); // sanity check
try {
String message = "MSH|^~\\&|HMI||RAD|REPORTS|20130228174643||ORM^O01|RTS01CE16057B105AC0|P|2.3|\r" +
"PID|1||101-6||Patient^Test^||19770222|M||||||||||\r" +
"ORC|\r" +
"OBR|1||0000001297|127689^SOME_X-RAY|||20130228170350||||||||||||MBL^CR||||||P|||||||&Goodrich&Mark&&&&^||||20130228170350\r" +
"OBX|1|RP|||||||||F\r" +
"OBX|2|TX|EventType^EventType|1|REVIEWED\r" +
"OBX|3|CN|Technologist^Technologist|1|1435^Duck^Donald\r" +
"OBX|4|TX|ExamRoom^ExamRoom|1|100AcreWoods\r" +
"OBX|5|TS|StartDateTime^StartDateTime|1|20111009215317\r" +
"OBX|6|TS|StopDateTime^StopDateTime|1|20111009215817\r" +
"ZDS|2.16.840.1.113883.3.234.1.3.101.1.2.1013.2011.15607503.2^HMI^Application^DICOM\r";
Thread.sleep(1000); // give the simple server time to start
Socket socket = new Socket("127.0.0.1", 6662);
PrintStream writer = new PrintStream(socket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer.print(header);
writer.print(message);
writer.print(trailer +"\r");
writer.flush();
Thread.sleep(1000);
// confirm that report encounter has been created and has obs (we more thoroughly test the handler in the ORU_R01 handler and Radiology Service (in emr module) tests)
encounters = encounterService.getEncounters(patient, null, null, null, null, Collections.singletonList(radiologyProperties.getRadiologyStudyEncounterType()),
null, null, null, false);
assertThat(encounters.size(), is(1));
assertThat(encounters.get(0).getObs().size(), is(3));
// confirm that the proper ack is sent out
String response = reader.readLine();
assertThat(response, containsString("|ACK|"));
}
finally {
activator.stopped();
}
}
| public void shouldListenForAndParseORM_001Message() throws Exception {
ModuleActivator activator = new PacsIntegrationActivator();
activator.started();
List<Patient> patients = patientService.getPatients(null, "101-6", Collections.singletonList(emrApiProperties.getPrimaryIdentifierType()), true);
assertThat(patients.size(), is(1)); // sanity check
Patient patient = patients.get(0);
List<Encounter> encounters = encounterService.getEncounters(patient, null, null, null, null, Collections.singletonList(radiologyProperties.getRadiologyStudyEncounterType()),
null, null, null, false);
assertThat(encounters.size(), is(0)); // sanity check
try {
String message = "MSH|^~\\&|HMI||RAD|REPORTS|20130228174643||ORM^O01|RTS01CE16057B105AC0|P|2.3|\r" +
"PID|1||101-6||Patient^Test^||19770222|M||||||||||\r" +
"ORC|\r" +
"OBR|1||0000001297|127689^SOME_X-RAY|||20130228170350||||||||||||MBL^CR||||||P|||||||&Goodrich&Mark&&&&^||||20130228170350\r" +
"OBX|1|RP|||||||||F\r" +
"OBX|2|TX|EventType^EventType|1|REVIEWED\r" +
"OBX|3|CN|Technologist^Technologist|1|1435^Duck^Donald\r" +
"OBX|4|TX|ExamRoom^ExamRoom|1|100AcreWoods\r" +
"OBX|5|TS|StartDateTime^StartDateTime|1|20111009215317\r" +
"OBX|6|TS|StopDateTime^StopDateTime|1|20111009215817\r" +
"OBX|7|TX|ImagesAvailable^ImagesAvailable|1|1\r" +
"ZDS|2.16.840.1.113883.3.234.1.3.101.1.2.1013.2011.15607503.2^HMI^Application^DICOM\r";
Thread.sleep(1000); // give the simple server time to start
Socket socket = new Socket("127.0.0.1", 6662);
PrintStream writer = new PrintStream(socket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer.print(header);
writer.print(message);
writer.print(trailer +"\r");
writer.flush();
Thread.sleep(1000);
// confirm that report encounter has been created and has obs (we more thoroughly test the handler in the ORU_R01 handler and Radiology Service (in emr module) tests)
encounters = encounterService.getEncounters(patient, null, null, null, null, Collections.singletonList(radiologyProperties.getRadiologyStudyEncounterType()),
null, null, null, false);
assertThat(encounters.size(), is(1));
assertThat(encounters.get(0).getObs().size(), is(3));
// confirm that the proper ack is sent out
String response = reader.readLine();
assertThat(response, containsString("|ACK|"));
}
finally {
activator.stopped();
}
}
|
diff --git a/src/org/touchirc/irc/IrcBot.java b/src/org/touchirc/irc/IrcBot.java
index c77a879..db66593 100644
--- a/src/org/touchirc/irc/IrcBot.java
+++ b/src/org/touchirc/irc/IrcBot.java
@@ -1,140 +1,137 @@
package org.touchirc.irc;
import java.util.regex.Pattern;
import org.pircbotx.PircBotX;
import org.pircbotx.hooks.Event;
import org.pircbotx.hooks.Listener;
import org.pircbotx.hooks.events.ActionEvent;
import org.pircbotx.hooks.events.ConnectEvent;
import org.pircbotx.hooks.events.JoinEvent;
import org.pircbotx.hooks.events.KickEvent;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.events.ModeEvent;
import org.pircbotx.hooks.events.NickChangeEvent;
import org.pircbotx.hooks.events.PartEvent;
import org.pircbotx.hooks.events.PrivateMessageEvent;
import org.pircbotx.hooks.events.UserListEvent;
import org.pircbotx.hooks.events.UserModeEvent;
import org.touchirc.model.Conversation;
import org.touchirc.model.Message;
import org.touchirc.model.Server;
import android.content.Intent;
import android.util.Log;
public class IrcBot extends PircBotX implements Listener<IrcBot>{
private IrcService service;
private Server server;
public boolean isConnected;
private Pattern highlight;
public IrcBot(Server server, IrcService service) {
this.service = service;
this.server = server;
this.getListenerManager().addListener(this);
}
/**
* Set the Nick of the user
*
* @param nickName
*/
public void setNickName(String nickName){
//TODO Add security : the nickname can't have some caracters
this.setName(nickName);
}
/**
* Set the ident of the user
*
* @param ident
*/
public void setIdent(String ident)
{
this.setLogin(ident);
}
/**
* Set the real name of the user
*
* @param realName
*/
public void setRealName(String realName)
{
this.setVersion(realName);
}
@SuppressWarnings("rawtypes")
@Override
public void onEvent(Event rawevent) throws Exception {
if(rawevent instanceof MessageEvent){
MessageEvent event = (MessageEvent) rawevent;
if(highlight.matcher(event.getMessage()).find()){
- this.server.getConversation(event.getChannel().getName()).addMessage(new Message(event.getMessage(), event.getUser().getNick(), Message.TYPE_MENTION));
+ this.server.getConversation(event.getChannel().getName()).addMessage(new Message(event.getMessage(), event.getUser().getNick(), Message.TYPE_MENTION));
}else{
this.server.getConversation(event.getChannel().getName()).addMessage(new Message(event.getMessage(), event.getUser().getNick()));
}
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.newMessage"));
return;
}
if(rawevent instanceof PrivateMessageEvent){
PrivateMessageEvent event = (PrivateMessageEvent) rawevent;
String user = event.getUser().getNick();
if(!server.hasConversation(user)){
server.addConversation(new Conversation(user));
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.channellistUpdated"));
}
this.server.getConversation(user).addMessage(new Message(event.getMessage(), user));
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.newMessage"));
return;
}
if(rawevent instanceof ActionEvent){
ActionEvent event = (ActionEvent) rawevent;
this.server.getConversation(event.getChannel().getName()).addMessage(new Message(event.getMessage(), event.getUser().getNick(), Message.TYPE_ACTION));
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.newMessage"));
return;
}
if(rawevent instanceof JoinEvent){
JoinEvent event = (JoinEvent) rawevent;
- if(event.getUser().equals(event.getBot().getUserBot())){
- this.server.getConversation(event.getChannel().getName());
+ if(event.getUser().equals(event.getBot().getUserBot()) && this.server.getConversation(event.getChannel().getName()) == null){
this.server.addConversation(new Conversation(event.getChannel().getName()));
System.out.println("JoinEvent "+event.getChannel().getName());
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.channellistUpdated"));
- return;
}
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.userlistUpdated"));
return;
}
if(rawevent instanceof PartEvent){
PartEvent event = (PartEvent) rawevent;
if(event.getUser().equals(event.getBot().getUserBot()) && this.server.getConversation(event.getChannel().getName()) != null){
this.server.removeConversation(event.getChannel().getName());
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.channellistUpdated"));
- return;
}
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.userlistUpdated"));
return;
}
if(rawevent instanceof UserListEvent || rawevent instanceof ModeEvent || rawevent instanceof KickEvent || rawevent instanceof NickChangeEvent || rawevent instanceof UserModeEvent){
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.userlistUpdated"));
return;
}
if(rawevent instanceof ConnectEvent){
ConnectEvent event = (ConnectEvent) rawevent;
isConnected = true;
// TODO add some highlight preference
highlight = Pattern.compile(Pattern.quote(this.getNick()), Pattern.CASE_INSENSITIVE);
Log.i("[IrcBot - " + event.getBot().getName() + "]", "Connected");
return;
}
}
}
| false | true | public void onEvent(Event rawevent) throws Exception {
if(rawevent instanceof MessageEvent){
MessageEvent event = (MessageEvent) rawevent;
if(highlight.matcher(event.getMessage()).find()){
this.server.getConversation(event.getChannel().getName()).addMessage(new Message(event.getMessage(), event.getUser().getNick(), Message.TYPE_MENTION));
}else{
this.server.getConversation(event.getChannel().getName()).addMessage(new Message(event.getMessage(), event.getUser().getNick()));
}
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.newMessage"));
return;
}
if(rawevent instanceof PrivateMessageEvent){
PrivateMessageEvent event = (PrivateMessageEvent) rawevent;
String user = event.getUser().getNick();
if(!server.hasConversation(user)){
server.addConversation(new Conversation(user));
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.channellistUpdated"));
}
this.server.getConversation(user).addMessage(new Message(event.getMessage(), user));
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.newMessage"));
return;
}
if(rawevent instanceof ActionEvent){
ActionEvent event = (ActionEvent) rawevent;
this.server.getConversation(event.getChannel().getName()).addMessage(new Message(event.getMessage(), event.getUser().getNick(), Message.TYPE_ACTION));
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.newMessage"));
return;
}
if(rawevent instanceof JoinEvent){
JoinEvent event = (JoinEvent) rawevent;
if(event.getUser().equals(event.getBot().getUserBot())){
this.server.getConversation(event.getChannel().getName());
this.server.addConversation(new Conversation(event.getChannel().getName()));
System.out.println("JoinEvent "+event.getChannel().getName());
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.channellistUpdated"));
return;
}
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.userlistUpdated"));
return;
}
if(rawevent instanceof PartEvent){
PartEvent event = (PartEvent) rawevent;
if(event.getUser().equals(event.getBot().getUserBot()) && this.server.getConversation(event.getChannel().getName()) != null){
this.server.removeConversation(event.getChannel().getName());
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.channellistUpdated"));
return;
}
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.userlistUpdated"));
return;
}
if(rawevent instanceof UserListEvent || rawevent instanceof ModeEvent || rawevent instanceof KickEvent || rawevent instanceof NickChangeEvent || rawevent instanceof UserModeEvent){
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.userlistUpdated"));
return;
}
if(rawevent instanceof ConnectEvent){
ConnectEvent event = (ConnectEvent) rawevent;
isConnected = true;
// TODO add some highlight preference
highlight = Pattern.compile(Pattern.quote(this.getNick()), Pattern.CASE_INSENSITIVE);
Log.i("[IrcBot - " + event.getBot().getName() + "]", "Connected");
return;
}
}
| public void onEvent(Event rawevent) throws Exception {
if(rawevent instanceof MessageEvent){
MessageEvent event = (MessageEvent) rawevent;
if(highlight.matcher(event.getMessage()).find()){
this.server.getConversation(event.getChannel().getName()).addMessage(new Message(event.getMessage(), event.getUser().getNick(), Message.TYPE_MENTION));
}else{
this.server.getConversation(event.getChannel().getName()).addMessage(new Message(event.getMessage(), event.getUser().getNick()));
}
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.newMessage"));
return;
}
if(rawevent instanceof PrivateMessageEvent){
PrivateMessageEvent event = (PrivateMessageEvent) rawevent;
String user = event.getUser().getNick();
if(!server.hasConversation(user)){
server.addConversation(new Conversation(user));
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.channellistUpdated"));
}
this.server.getConversation(user).addMessage(new Message(event.getMessage(), user));
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.newMessage"));
return;
}
if(rawevent instanceof ActionEvent){
ActionEvent event = (ActionEvent) rawevent;
this.server.getConversation(event.getChannel().getName()).addMessage(new Message(event.getMessage(), event.getUser().getNick(), Message.TYPE_ACTION));
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.newMessage"));
return;
}
if(rawevent instanceof JoinEvent){
JoinEvent event = (JoinEvent) rawevent;
if(event.getUser().equals(event.getBot().getUserBot()) && this.server.getConversation(event.getChannel().getName()) == null){
this.server.addConversation(new Conversation(event.getChannel().getName()));
System.out.println("JoinEvent "+event.getChannel().getName());
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.channellistUpdated"));
}
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.userlistUpdated"));
return;
}
if(rawevent instanceof PartEvent){
PartEvent event = (PartEvent) rawevent;
if(event.getUser().equals(event.getBot().getUserBot()) && this.server.getConversation(event.getChannel().getName()) != null){
this.server.removeConversation(event.getChannel().getName());
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.channellistUpdated"));
}
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.userlistUpdated"));
return;
}
if(rawevent instanceof UserListEvent || rawevent instanceof ModeEvent || rawevent instanceof KickEvent || rawevent instanceof NickChangeEvent || rawevent instanceof UserModeEvent){
service.sendBroadcast(new Intent().setAction("org.touchirc.irc.userlistUpdated"));
return;
}
if(rawevent instanceof ConnectEvent){
ConnectEvent event = (ConnectEvent) rawevent;
isConnected = true;
// TODO add some highlight preference
highlight = Pattern.compile(Pattern.quote(this.getNick()), Pattern.CASE_INSENSITIVE);
Log.i("[IrcBot - " + event.getBot().getName() + "]", "Connected");
return;
}
}
|
diff --git a/ZONE-extractor/ZONE-TwitterReader/src/test/java/org/zoneproject/extractor/twitterreader/TwitterApiTest.java b/ZONE-extractor/ZONE-TwitterReader/src/test/java/org/zoneproject/extractor/twitterreader/TwitterApiTest.java
index e91bb17..1a565cf 100644
--- a/ZONE-extractor/ZONE-TwitterReader/src/test/java/org/zoneproject/extractor/twitterreader/TwitterApiTest.java
+++ b/ZONE-extractor/ZONE-TwitterReader/src/test/java/org/zoneproject/extractor/twitterreader/TwitterApiTest.java
@@ -1,54 +1,54 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.zoneproject.extractor.twitterreader;
import java.util.ArrayList;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Desclaux Christophe <[email protected]>
*/
public class TwitterApiTest {
public TwitterApiTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of getSources method, of class TwitterApi.
*/
@Test
public void testGetHashTags() {
System.out.println("getHashTags");
- String[] expResult = {"descl","you","nice"};
+ String[] expResult = {"#descl","#you","#nice"};
String[] result = TwitterApi.getHashTags("hello #descl how are #you in #nice?");
for(String r: result) {
System.out.println(r);
}
assertArrayEquals(expResult, result);
}
}
| true | true | public void testGetHashTags() {
System.out.println("getHashTags");
String[] expResult = {"descl","you","nice"};
String[] result = TwitterApi.getHashTags("hello #descl how are #you in #nice?");
for(String r: result) {
System.out.println(r);
}
assertArrayEquals(expResult, result);
}
| public void testGetHashTags() {
System.out.println("getHashTags");
String[] expResult = {"#descl","#you","#nice"};
String[] result = TwitterApi.getHashTags("hello #descl how are #you in #nice?");
for(String r: result) {
System.out.println(r);
}
assertArrayEquals(expResult, result);
}
|
diff --git a/src/Extensions/org/objectweb/proactive/extensions/scheduler/job/JobResultImpl.java b/src/Extensions/org/objectweb/proactive/extensions/scheduler/job/JobResultImpl.java
index 53bef9bd7..fc1635399 100644
--- a/src/Extensions/org/objectweb/proactive/extensions/scheduler/job/JobResultImpl.java
+++ b/src/Extensions/org/objectweb/proactive/extensions/scheduler/job/JobResultImpl.java
@@ -1,174 +1,174 @@
/*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis
* Contact: [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or 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
* General Public License for more details.
*
* You should have received a copy of the GNU 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
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
*/
package org.objectweb.proactive.extensions.scheduler.job;
import java.util.HashMap;
import org.objectweb.proactive.api.PAFuture;
import org.objectweb.proactive.extensions.scheduler.common.job.JobId;
import org.objectweb.proactive.extensions.scheduler.common.job.JobResult;
import org.objectweb.proactive.extensions.scheduler.common.task.TaskResult;
/**
* Class representing a job result. A job result is a map of task result. The
* key of the map is the name of the task on which to get the result. To
* identify the job result, it provides the id of the job in the scheduler and
* the job name.
*
* @author jlscheef - ProActiveTeam
* @version 3.9, Jul 5, 2007
* @since ProActive 3.9
*/
public class JobResultImpl implements JobResult {
private JobId id = null;
private String name = null;
private HashMap<String, TaskResult> allResults = null;
private HashMap<String, TaskResult> preciousResults = null;
private HashMap<String, TaskResult> exceptionResults = null;
/**
* ProActive empty constructor
*/
public JobResultImpl() {
}
/**
* Instantiate a new JobResult with a jobId and a result
*
* @param id
* the jobId associated with this result
* @param name
* the name of the job that has generate this result.
*/
public JobResultImpl(JobId id, String name) {
this.id = id;
this.name = name;
}
/**
* To get the id
*
* @return the id
*/
public JobId getId() {
return id;
}
/**
* To get the name of the job that has generate this result.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* @see org.objectweb.proactive.extensions.scheduler.common.job.JobResult#addTaskResult(java.lang.String, org.objectweb.proactive.extensions.scheduler.common.task.TaskResult, boolean)
*/
public void addTaskResult(String taskName, TaskResult taskResult, boolean isPrecious) {
//allResults
if (allResults == null) {
allResults = new HashMap<String, TaskResult>();
}
allResults.put(taskName, taskResult);
//preciousResult
if (isPrecious) {
if (preciousResults == null) {
preciousResults = new HashMap<String, TaskResult>();
}
- allResults.put(taskName, taskResult);
+ preciousResults.put(taskName, taskResult);
}
//exceptionResults
if (!PAFuture.isAwaited(taskResult) && taskResult.hadException()) {
if (exceptionResults == null) {
exceptionResults = new HashMap<String, TaskResult>();
}
exceptionResults.put(taskName, taskResult);
}
}
/**
* @see org.objectweb.proactive.extensions.scheduler.common.job.JobResult#getAllResults()
*/
public HashMap<String, TaskResult> getAllResults() {
return allResults;
}
/**
* @see org.objectweb.proactive.extensions.scheduler.common.job.JobResult#getExceptionResults()
*/
public HashMap<String, TaskResult> getExceptionResults() {
return exceptionResults;
}
/**
* @see org.objectweb.proactive.extensions.scheduler.common.job.JobResult#getPreciousResults()
*/
public HashMap<String, TaskResult> getPreciousResults() {
return preciousResults;
}
/**
* @see org.objectweb.proactive.extensions.scheduler.common.job.JobResult#hadException()
*/
public boolean hadException() {
return exceptionResults != null;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
if (allResults == null) {
return "No result available in this job !";
}
StringBuilder toReturn = new StringBuilder("\n");
for (TaskResult res : allResults.values()) {
try {
toReturn.append("\t" + res.value() + "\n");
} catch (Throwable e) {
toReturn.append("\t" + res.getException().getMessage() + "\n");
}
}
return toReturn.toString();
}
}
| true | true | public void addTaskResult(String taskName, TaskResult taskResult, boolean isPrecious) {
//allResults
if (allResults == null) {
allResults = new HashMap<String, TaskResult>();
}
allResults.put(taskName, taskResult);
//preciousResult
if (isPrecious) {
if (preciousResults == null) {
preciousResults = new HashMap<String, TaskResult>();
}
allResults.put(taskName, taskResult);
}
//exceptionResults
if (!PAFuture.isAwaited(taskResult) && taskResult.hadException()) {
if (exceptionResults == null) {
exceptionResults = new HashMap<String, TaskResult>();
}
exceptionResults.put(taskName, taskResult);
}
}
| public void addTaskResult(String taskName, TaskResult taskResult, boolean isPrecious) {
//allResults
if (allResults == null) {
allResults = new HashMap<String, TaskResult>();
}
allResults.put(taskName, taskResult);
//preciousResult
if (isPrecious) {
if (preciousResults == null) {
preciousResults = new HashMap<String, TaskResult>();
}
preciousResults.put(taskName, taskResult);
}
//exceptionResults
if (!PAFuture.isAwaited(taskResult) && taskResult.hadException()) {
if (exceptionResults == null) {
exceptionResults = new HashMap<String, TaskResult>();
}
exceptionResults.put(taskName, taskResult);
}
}
|
diff --git a/Hexiano/src/opensource/hexiano/CC.java b/Hexiano/src/opensource/hexiano/CC.java
index 6d912f3..e57da6d 100644
--- a/Hexiano/src/opensource/hexiano/CC.java
+++ b/Hexiano/src/opensource/hexiano/CC.java
@@ -1,115 +1,120 @@
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Hexiano, an isomorphic musical keyboard for Android *
* Copyleft 2013 Stephen Larroque *
* *
* FILE: CC.java *
* *
* This file is part of Hexiano, an open-source project hosted at: *
* https://gitorious.org/hexiano *
* *
* Hexiano 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. *
* *
* Hexiano 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 Hexiano. If not, see <http://www.gnu.org/licenses/>. *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
package opensource.hexiano;
import java.util.HashMap;
public class CC
{
protected int mOctave;
protected String mCCName;
protected int mMidiCCNumber;
protected int mKeyNumber; // Just for reference, can be shown as a label on the key, but useless otherwise for the Note
public CC(int midiNumber, int keyNumber)
{
mMidiCCNumber = midiNumber;
mKeyNumber = keyNumber;
mCCName = this.getModifierNameForNoteNumber(mMidiCCNumber);
mOctave = 1;
}
static final HashMap<Integer, String> mModifierForNumber;
static
{
mModifierForNumber = new HashMap<Integer, String>();
mModifierForNumber.put(1, "Mod");
mModifierForNumber.put(7, "Volume");
mModifierForNumber.put(10, "Pan");
mModifierForNumber.put(11, "Expression");
mModifierForNumber.put(64, "Sustain");
}
static final HashMap<String, Integer> mNumberForModifier;
static
{
mNumberForModifier = new HashMap<String, Integer>();
mNumberForModifier.put("Mod", 1);
mNumberForModifier.put("Volume", 7);
mNumberForModifier.put("Pan", 10);
mNumberForModifier.put("Expression", 11);
mNumberForModifier.put("Sustain", 64);
}
public String getCCName()
{
return mCCName + mOctave;
}
public int getMidiCCNumber()
{
return mMidiCCNumber;
}
public String getDisplayString(String labelType, boolean showOctave)
{
- String noteStr = "?";
+ String noteStr = "CC?";
if (labelType.equals("None"))
{
return "";
}
else if (labelType.equals("Key Number (DEV)"))
{
return("" + mKeyNumber);
}
else if (labelType.equals("MIDI Note Number"))
{
return("CC" + mMidiCCNumber);
}
else
{
- return(noteStr);
+ String name = getModifierNameForNoteNumber(mMidiCCNumber);
+ if (name.length() > 0) {
+ return name;
+ } else {
+ return(noteStr);
+ }
}
}
public static int getNoteNumber(String modifierName)
{
int CCNumber = mNumberForModifier.get(modifierName);
return CCNumber;
}
public String getModifierNameForNoteNumber(int midiNoteNumber)
{
return mModifierForNumber.get(midiNoteNumber);
}
public String getCCNameForNoteNumber(int midiNoteNumber)
{
int flatNumber = midiNoteNumber % 12;
return mModifierForNumber.get(flatNumber);
}
}
| false | true | public String getDisplayString(String labelType, boolean showOctave)
{
String noteStr = "?";
if (labelType.equals("None"))
{
return "";
}
else if (labelType.equals("Key Number (DEV)"))
{
return("" + mKeyNumber);
}
else if (labelType.equals("MIDI Note Number"))
{
return("CC" + mMidiCCNumber);
}
else
{
return(noteStr);
}
}
| public String getDisplayString(String labelType, boolean showOctave)
{
String noteStr = "CC?";
if (labelType.equals("None"))
{
return "";
}
else if (labelType.equals("Key Number (DEV)"))
{
return("" + mKeyNumber);
}
else if (labelType.equals("MIDI Note Number"))
{
return("CC" + mMidiCCNumber);
}
else
{
String name = getModifierNameForNoteNumber(mMidiCCNumber);
if (name.length() > 0) {
return name;
} else {
return(noteStr);
}
}
}
|
diff --git a/q-web/src/main/java/q/web/group/GetGroupFeedFrame.java b/q-web/src/main/java/q/web/group/GetGroupFeedFrame.java
index f59feaf9..7863aa4c 100644
--- a/q-web/src/main/java/q/web/group/GetGroupFeedFrame.java
+++ b/q-web/src/main/java/q/web/group/GetGroupFeedFrame.java
@@ -1,76 +1,78 @@
package q.web.group;
import java.util.List;
import q.dao.DaoHelper;
import q.dao.EventDao;
import q.dao.GroupDao;
import q.dao.PeopleDao;
import q.dao.WeiboDao;
import q.domain.Event;
import q.domain.Group;
import q.domain.People;
import q.domain.Weibo;
import q.util.CollectionKit;
import q.web.Resource;
import q.web.ResourceContext;
public class GetGroupFeedFrame extends Resource {
private GroupDao groupDao;
public void setGroupDao(GroupDao groupDao) {
this.groupDao = groupDao;
}
private PeopleDao peopleDao;
public void setPeopleDao(PeopleDao peopleDao) {
this.peopleDao = peopleDao;
}
private EventDao eventDao;
public void setEventDao(EventDao eventDao) {
this.eventDao = eventDao;
}
private WeiboDao weiboDao;
public void setWeiboDao(WeiboDao weiboDao) {
this.weiboDao = weiboDao;
}
@Override
public void execute(ResourceContext context) throws Exception {
long loginPeopleId = context.getCookiePeopleId();
+ People people = this.peopleDao.getPeopleById(loginPeopleId);
+ context.setModel("people", people);
List<Long> groupIds = this.groupDao.getGroupIdsByPeopleId(loginPeopleId);
if (CollectionKit.isNotEmpty(groupIds)) {
List<Group> groups = this.groupDao.getGroupsByIds(groupIds);
context.setModel("groups", groups);
List<Event> newEvents = this.eventDao.getEventsByGroupIds(groupIds, 4, 0);
context.setModel("newEvents", newEvents);
List<Long> newPeopleIds = this.groupDao.getPeopleIdsByGroupIds(groupIds, 3, 0);
List<People> newPeoples = this.peopleDao.getPeoplesByIds(newPeopleIds);
context.setModel("newPeoples", newPeoples);
List<Long> hotPeopleIds = this.groupDao.getHotGroupPeopleIds(groupIds, 3, 0);
List<People> hotPeoples = this.peopleDao.getPeoplesByIds(hotPeopleIds);
context.setModel("hotPeoples", hotPeoples);
List<Weibo> hotWeibos = this.weiboDao.getHotWeibosByGroupIds(groupIds, 3, 0);
DaoHelper.injectWeiboModelsWithPeople(peopleDao, hotWeibos);
context.setModel("hotWeibos", hotWeibos);
}
}
/* (non-Javadoc)
* @see q.web.Resource#validate(q.web.ResourceContext)
*/
@Override
public void validate(ResourceContext context) throws Exception {
// TODO Auto-generated method stub
}
}
| true | true | public void execute(ResourceContext context) throws Exception {
long loginPeopleId = context.getCookiePeopleId();
List<Long> groupIds = this.groupDao.getGroupIdsByPeopleId(loginPeopleId);
if (CollectionKit.isNotEmpty(groupIds)) {
List<Group> groups = this.groupDao.getGroupsByIds(groupIds);
context.setModel("groups", groups);
List<Event> newEvents = this.eventDao.getEventsByGroupIds(groupIds, 4, 0);
context.setModel("newEvents", newEvents);
List<Long> newPeopleIds = this.groupDao.getPeopleIdsByGroupIds(groupIds, 3, 0);
List<People> newPeoples = this.peopleDao.getPeoplesByIds(newPeopleIds);
context.setModel("newPeoples", newPeoples);
List<Long> hotPeopleIds = this.groupDao.getHotGroupPeopleIds(groupIds, 3, 0);
List<People> hotPeoples = this.peopleDao.getPeoplesByIds(hotPeopleIds);
context.setModel("hotPeoples", hotPeoples);
List<Weibo> hotWeibos = this.weiboDao.getHotWeibosByGroupIds(groupIds, 3, 0);
DaoHelper.injectWeiboModelsWithPeople(peopleDao, hotWeibos);
context.setModel("hotWeibos", hotWeibos);
}
}
| public void execute(ResourceContext context) throws Exception {
long loginPeopleId = context.getCookiePeopleId();
People people = this.peopleDao.getPeopleById(loginPeopleId);
context.setModel("people", people);
List<Long> groupIds = this.groupDao.getGroupIdsByPeopleId(loginPeopleId);
if (CollectionKit.isNotEmpty(groupIds)) {
List<Group> groups = this.groupDao.getGroupsByIds(groupIds);
context.setModel("groups", groups);
List<Event> newEvents = this.eventDao.getEventsByGroupIds(groupIds, 4, 0);
context.setModel("newEvents", newEvents);
List<Long> newPeopleIds = this.groupDao.getPeopleIdsByGroupIds(groupIds, 3, 0);
List<People> newPeoples = this.peopleDao.getPeoplesByIds(newPeopleIds);
context.setModel("newPeoples", newPeoples);
List<Long> hotPeopleIds = this.groupDao.getHotGroupPeopleIds(groupIds, 3, 0);
List<People> hotPeoples = this.peopleDao.getPeoplesByIds(hotPeopleIds);
context.setModel("hotPeoples", hotPeoples);
List<Weibo> hotWeibos = this.weiboDao.getHotWeibosByGroupIds(groupIds, 3, 0);
DaoHelper.injectWeiboModelsWithPeople(peopleDao, hotWeibos);
context.setModel("hotWeibos", hotWeibos);
}
}
|
diff --git a/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/KeywordSearchConfigurationPanel2.java b/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/KeywordSearchConfigurationPanel2.java
index 6f4039648..f7df7cd46 100644
--- a/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/KeywordSearchConfigurationPanel2.java
+++ b/KeywordSearch/src/org/sleuthkit/autopsy/keywordsearch/KeywordSearchConfigurationPanel2.java
@@ -1,146 +1,146 @@
/*
* Autopsy Forensic Browser
*
* Copyright 2012 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.keywordsearch;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.solr.client.solrj.SolrServerException;
/**
*
* General, not per list, keyword search configuration and status display widget
*/
public class KeywordSearchConfigurationPanel2 extends javax.swing.JPanel {
private static KeywordSearchConfigurationPanel2 instance = null;
private final Logger logger = Logger.getLogger(KeywordSearchConfigurationPanel2.class.getName());
/** Creates new form KeywordSearchConfigurationPanel2 */
public KeywordSearchConfigurationPanel2() {
initComponents();
customizeComponents();
}
public static KeywordSearchConfigurationPanel2 getDefault() {
if (instance == null) {
instance = new KeywordSearchConfigurationPanel2();
}
return instance;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
skipNSRLCheckBox = new javax.swing.JCheckBox();
filesIndexedLabel = new javax.swing.JLabel();
filesIndexedValue = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
skipNSRLCheckBox.setText(org.openide.util.NbBundle.getMessage(KeywordSearchConfigurationPanel2.class, "KeywordSearchConfigurationPanel2.skipNSRLCheckBox.text")); // NOI18N
skipNSRLCheckBox.setToolTipText(org.openide.util.NbBundle.getMessage(KeywordSearchConfigurationPanel2.class, "KeywordSearchConfigurationPanel2.skipNSRLCheckBox.toolTipText")); // NOI18N
skipNSRLCheckBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
skipNSRLCheckBoxActionPerformed(evt);
}
});
filesIndexedLabel.setText(org.openide.util.NbBundle.getMessage(KeywordSearchConfigurationPanel2.class, "KeywordSearchConfigurationPanel2.filesIndexedLabel.text")); // NOI18N
filesIndexedValue.setText(org.openide.util.NbBundle.getMessage(KeywordSearchConfigurationPanel2.class, "KeywordSearchConfigurationPanel2.filesIndexedValue.text")); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
- .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(filesIndexedLabel)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(filesIndexedValue, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(skipNSRLCheckBox))
.addContainerGap(165, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(skipNSRLCheckBox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(filesIndexedLabel)
.addComponent(filesIndexedValue))
.addContainerGap(226, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void skipNSRLCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_skipNSRLCheckBoxActionPerformed
KeywordSearchIngestService.getDefault().setSkipKnown(skipNSRLCheckBox.isSelected());
}//GEN-LAST:event_skipNSRLCheckBoxActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel filesIndexedLabel;
private javax.swing.JLabel filesIndexedValue;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JCheckBox skipNSRLCheckBox;
// End of variables declaration//GEN-END:variables
private void customizeComponents() {
this.skipNSRLCheckBox.setSelected(KeywordSearchIngestService.getDefault().getSkipKnown());
try {
filesIndexedValue.setText(Integer.toString(KeywordSearch.getServer().queryNumIndexedFiles()));
} catch (SolrServerException ex) {
logger.log(Level.WARNING, "Could not get number of indexed files");
} catch (NoOpenCoreException ex) {
logger.log(Level.WARNING, "Could not get number of indexed files");
}
KeywordSearch.changeSupport.addPropertyChangeListener(KeywordSearch.NUM_FILES_CHANGE_EVT,
new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
String changed = evt.getPropertyName();
Object newValue = evt.getNewValue();
if (changed.equals(KeywordSearch.NUM_FILES_CHANGE_EVT)) {
int newFilesIndexed = ((Integer) newValue).intValue();
filesIndexedValue.setText(Integer.toString(newFilesIndexed));
}
}
});
}
}
| false | true | private void initComponents() {
skipNSRLCheckBox = new javax.swing.JCheckBox();
filesIndexedLabel = new javax.swing.JLabel();
filesIndexedValue = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
skipNSRLCheckBox.setText(org.openide.util.NbBundle.getMessage(KeywordSearchConfigurationPanel2.class, "KeywordSearchConfigurationPanel2.skipNSRLCheckBox.text")); // NOI18N
skipNSRLCheckBox.setToolTipText(org.openide.util.NbBundle.getMessage(KeywordSearchConfigurationPanel2.class, "KeywordSearchConfigurationPanel2.skipNSRLCheckBox.toolTipText")); // NOI18N
skipNSRLCheckBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
skipNSRLCheckBoxActionPerformed(evt);
}
});
filesIndexedLabel.setText(org.openide.util.NbBundle.getMessage(KeywordSearchConfigurationPanel2.class, "KeywordSearchConfigurationPanel2.filesIndexedLabel.text")); // NOI18N
filesIndexedValue.setText(org.openide.util.NbBundle.getMessage(KeywordSearchConfigurationPanel2.class, "KeywordSearchConfigurationPanel2.filesIndexedValue.text")); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(filesIndexedLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(filesIndexedValue, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(skipNSRLCheckBox))
.addContainerGap(165, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(skipNSRLCheckBox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(filesIndexedLabel)
.addComponent(filesIndexedValue))
.addContainerGap(226, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
skipNSRLCheckBox = new javax.swing.JCheckBox();
filesIndexedLabel = new javax.swing.JLabel();
filesIndexedValue = new javax.swing.JLabel();
jSeparator1 = new javax.swing.JSeparator();
skipNSRLCheckBox.setText(org.openide.util.NbBundle.getMessage(KeywordSearchConfigurationPanel2.class, "KeywordSearchConfigurationPanel2.skipNSRLCheckBox.text")); // NOI18N
skipNSRLCheckBox.setToolTipText(org.openide.util.NbBundle.getMessage(KeywordSearchConfigurationPanel2.class, "KeywordSearchConfigurationPanel2.skipNSRLCheckBox.toolTipText")); // NOI18N
skipNSRLCheckBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
skipNSRLCheckBoxActionPerformed(evt);
}
});
filesIndexedLabel.setText(org.openide.util.NbBundle.getMessage(KeywordSearchConfigurationPanel2.class, "KeywordSearchConfigurationPanel2.filesIndexedLabel.text")); // NOI18N
filesIndexedValue.setText(org.openide.util.NbBundle.getMessage(KeywordSearchConfigurationPanel2.class, "KeywordSearchConfigurationPanel2.filesIndexedValue.text")); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(filesIndexedLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(filesIndexedValue, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(skipNSRLCheckBox))
.addContainerGap(165, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(skipNSRLCheckBox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(filesIndexedLabel)
.addComponent(filesIndexedValue))
.addContainerGap(226, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/main/com/iappsam/servlet/item/ViewItem.java b/src/main/com/iappsam/servlet/item/ViewItem.java
index 0374248..e6e68a8 100644
--- a/src/main/com/iappsam/servlet/item/ViewItem.java
+++ b/src/main/com/iappsam/servlet/item/ViewItem.java
@@ -1,87 +1,89 @@
package com.iappsam.servlet.item;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.iappsam.entities.Account;
import com.iappsam.entities.Contact;
import com.iappsam.entities.Employee;
import com.iappsam.entities.Item;
import com.iappsam.entities.Person;
import com.iappsam.managers.AccountManager;
import com.iappsam.managers.ContactManager;
import com.iappsam.managers.DivisionOfficeManager;
import com.iappsam.managers.ItemManager;
import com.iappsam.managers.PersonManager;
import com.iappsam.managers.exceptions.TransactionException;
import com.iappsam.managers.sessions.AccountManagerSession;
import com.iappsam.managers.sessions.ContactManagerSession;
import com.iappsam.managers.sessions.DivisionOfficeManagerSession;
import com.iappsam.managers.sessions.ItemManagerSession;
import com.iappsam.managers.sessions.PersonManagerSession;
/**
* Servlet implementation class ViewItem
*/
@WebServlet("/items/ViewItem.do")
public class ViewItem extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ViewItem() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ItemManager iManager = new ItemManagerSession();
- String description = (String)request.getParameter("description");
+ String description = (String) request.getParameter("description");
Item item = new Item();
try {
item = iManager.getItem(description);
} catch (TransactionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
- request.setAttribute("description", item.getDescription());
- request.setAttribute("unit", item.getUnit());
- request.setAttribute("category", item.getCategory());
- request.setAttribute("price", "" + item.getPrice());
- // request.setAttribute("", ); //date
- request.setAttribute("stockNumber", item.getStockNumber());
- request.setAttribute("inventoryItemNumber", "" + item.getInventoryItemNumber());
- request.setAttribute("propertyNumber", item.getPropertyNumber());
- request.setAttribute("status", item.getStatus());
- request.setAttribute("condition", item.getCondition());
+ if (item != null) {
+ request.setAttribute("description", item.getDescription());
+ request.setAttribute("unit", item.getUnit());
+ request.setAttribute("category", item.getCategory());
+ request.setAttribute("price", "" + item.getPrice());
+ // request.setAttribute("", ); //date
+ request.setAttribute("stockNumber", item.getStockNumber());
+ request.setAttribute("inventoryItemNumber", "" + item.getInventoryItemNumber());
+ request.setAttribute("propertyNumber", item.getPropertyNumber());
+ request.setAttribute("status", item.getStatus());
+ request.setAttribute("condition", item.getCondition());
+ }
RequestDispatcher view = request.getRequestDispatcher("../stocks/items/ViewItem.jsp");
view.forward(request, response);
}
}
| false | true | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ItemManager iManager = new ItemManagerSession();
String description = (String)request.getParameter("description");
Item item = new Item();
try {
item = iManager.getItem(description);
} catch (TransactionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
request.setAttribute("description", item.getDescription());
request.setAttribute("unit", item.getUnit());
request.setAttribute("category", item.getCategory());
request.setAttribute("price", "" + item.getPrice());
// request.setAttribute("", ); //date
request.setAttribute("stockNumber", item.getStockNumber());
request.setAttribute("inventoryItemNumber", "" + item.getInventoryItemNumber());
request.setAttribute("propertyNumber", item.getPropertyNumber());
request.setAttribute("status", item.getStatus());
request.setAttribute("condition", item.getCondition());
RequestDispatcher view = request.getRequestDispatcher("../stocks/items/ViewItem.jsp");
view.forward(request, response);
}
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ItemManager iManager = new ItemManagerSession();
String description = (String) request.getParameter("description");
Item item = new Item();
try {
item = iManager.getItem(description);
} catch (TransactionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (item != null) {
request.setAttribute("description", item.getDescription());
request.setAttribute("unit", item.getUnit());
request.setAttribute("category", item.getCategory());
request.setAttribute("price", "" + item.getPrice());
// request.setAttribute("", ); //date
request.setAttribute("stockNumber", item.getStockNumber());
request.setAttribute("inventoryItemNumber", "" + item.getInventoryItemNumber());
request.setAttribute("propertyNumber", item.getPropertyNumber());
request.setAttribute("status", item.getStatus());
request.setAttribute("condition", item.getCondition());
}
RequestDispatcher view = request.getRequestDispatcher("../stocks/items/ViewItem.jsp");
view.forward(request, response);
}
|
diff --git a/src/spielfigur/Spielfigur.java b/src/spielfigur/Spielfigur.java
index 1549c8e..5a422e1 100644
--- a/src/spielfigur/Spielfigur.java
+++ b/src/spielfigur/Spielfigur.java
@@ -1,213 +1,214 @@
package spielfigur;
import game.Game;
import spielfeld.Spielfeld;
import spielfeld.Spielflaeche;
import bombe.BombType;
import bombe.Bombe;
import bombe.NormalBomb;
public class Spielfigur {
// Initialisierung von Variabeln
public int xPosition; // aktuelle Position auf der "x-Achse" der
// Spielfläche
public int yPosition; // aktuelle Position auf der "y-Achse" der
// Spielfläche
public int dimension;
protected int width;
protected int height;
protected String pic;
private int bombPlanted = 3;
private int playerNumber;
private BombType bomb = new NormalBomb();
public Spielfigur(int xPosition, int yPosition, int dimension, int player) {
this.yPosition = yPosition;
this.xPosition = xPosition;
this.dimension = dimension;
this.playerNumber = player;
}
// get und set methoden
public int getPlayerNumber() {
return playerNumber;
}
public void setPlayerNumber(int playerNumber) {
this.playerNumber = playerNumber;
}
public int getxPosition() {
return xPosition;
}
public void setxPosition(int xPosition) {
this.xPosition = xPosition;
}
public int getyPosition() {
return yPosition;
}
public int getBombPlanted() {
return bombPlanted;
}
public void setyPosition(int yPosition) {
this.yPosition = yPosition;
}
public BombType getBombType() {
return bomb;
}
public void setBombType(BombType bomb) {
this.bomb = bomb;
}
public void setBombPlanted(int b) {
bombPlanted = b;
}
/*
* �berpr�ft ob Bomberman an einer bestimmten Stelle ist.
*/
public boolean istPos(int x, int y) {
if ((x == xPosition && y == yPosition))
return true;
else
return false;
}
// Bombe
public void bombeLegen() {
if (bombPlanted > 0) {
new Bombe(xPosition, yPosition, width, height, bomb, playerNumber)
.start();
Spielflaeche.play.fill(xPosition, yPosition, 4, Spielfeld.Bombe);
bombPlanted -= 1;
}
}
/*
* Die Methode move bzw. move2 regeln die Bewegungen der Figuren "man" und
* "man2. Benutzt werden diese Methoden vom gamekeylistener. Die Bewegung
* wird durch Abfragen , der in der jeweiligen Bewegungsrichtung vorhandenen
* Objekte realisiert. Es wird abgefragt, was sich auf dem jeweiligen Feld
* befindet und falls Bewegung logisch erscheint, wird die jeweilige Figur
* auf dieses Feld bewegt. (Änderung der Variablen xPosition und yPosition
* des jeweiligen Spielfigurenobjektes
*/
public void move(int x, int y) {
/*
* Das Spiel wird neu gestartet wenn Bomberman und Ausgang sich auf den
* selben Koordinaten befinden.
*/
if (Spielflaeche.play.getObj(xPosition + x, yPosition + y, 1) == Spielfeld.Ausgang
&& Spielflaeche.play.getObj(xPosition + x, yPosition + y, 2) != Spielfeld.Kiste) {
xPosition = xPosition + x;
yPosition = yPosition + y;
Game.restartGame();
}
/*
* wenn das angepeilte Feld eine Explosion ist, dann wird die Figur
* dorthin bewegt. Allerdings stirbt diese dann --> Spieler2 hat
* gewonnen --> Spiel startet neu
*/
else if (Spielflaeche.play.equalsExplosion(xPosition + x,
yPosition + y, 3)
|| (Spielflaeche.play.equalsExplosion(xPosition, yPosition, 3))) {
Spielflaeche.play.fill(xPosition, yPosition, 3, Spielfeld.Gras);
xPosition = xPosition + x;
yPosition = yPosition + y;
System.out.println("Player 2 siegt");
+ Game.restartGame();
// Label soll erstellt werden // Tot - wanna restart?
}
/*
* Es wird festgestellt, ob das angepeilte Feld bereits mit einem
* Objekt, das unpassierbarist, belegt ist. Wenn es passierbar ist geht
* die Abfrage weiter.
*/
else if (Spielflaeche.play.getObj(xPosition + x, yPosition + y, 2) == null
&& Spielflaeche.play.getObj(xPosition + x, yPosition + y, 4) == null
&& Spielflaeche.play.equalsMauer(xPosition + x, yPosition + y) == false) {
/*
* Es wird abgefragt ob eine Bombe gelegt wurde. Wenn eine Bombe
* gelegt wurde, dann wird auf den Variablen xPostítion und
* yPosition des Spielfigurenobjektes eine Bombe gezeichnet.
*/
Spielflaeche.play.fill(xPosition, yPosition, 3, Spielfeld.Gras);
/*
* if (Spielflaeche.bman.bombeLiegt) { Spielflaeche.play
* .fill(xPosition, yPosition, 4, Spielfeld.Bombe); bombeLiegt =
* false; // Noch eine Bedingung ( Wenn Explo --> Bman // auf explo
* // sieht verkohlt aus
*
* }
*/
/*
* Bewegung der Figur
*/
xPosition = xPosition + x;
yPosition = yPosition + y;
}
}// move
public void move2(int x, int y) {
/*
*
* Diese Methode funktioniert analog zu move ausser ,dass hierbei nicht
* das Objekt"man" angesprochen wird sondern "man2"
*/
if (Spielflaeche.play.getObj(xPosition + x, yPosition + y, 1) == Spielfeld.Ausgang
&& Spielflaeche.play.getObj(xPosition + x, yPosition + y, 2) != Spielfeld.Kiste) {
xPosition = xPosition + x;
yPosition = yPosition + y;
Game.restartGame();
}
/*
* Checkt ob Spieler 2 in eine Explo rennt
*/
else if (Spielflaeche.play.equalsExplosion(xPosition + x,
yPosition + y, 3)) {
Spielflaeche.play.fill(xPosition, yPosition, 3, Spielfeld.Gras);
xPosition = xPosition + x;
yPosition = yPosition + y;
System.out.println("Player1 siegt");
}
// Label soll erstellt werden // Tot - wanna restart?
/*
*
* Checkt ob das Feld auf das Player 2 rennen soll leer ist
*/
else if (Spielflaeche.play.getObj(xPosition + x, yPosition + y, 2) == null
&& Spielflaeche.play.getObj(xPosition + x, yPosition + y, 4) == null
&& Spielflaeche.play.equalsMauer(xPosition + x, yPosition + y) == false) {
Spielflaeche.play.fill(xPosition, yPosition, 3, Spielfeld.Gras);
// Spielflaeche.play
// .fill(xPosition, yPosition, 4, Spielfeld.Bombe);
xPosition = xPosition + x;
yPosition = yPosition + y;
}
}
}// move2
| true | true | public void move(int x, int y) {
/*
* Das Spiel wird neu gestartet wenn Bomberman und Ausgang sich auf den
* selben Koordinaten befinden.
*/
if (Spielflaeche.play.getObj(xPosition + x, yPosition + y, 1) == Spielfeld.Ausgang
&& Spielflaeche.play.getObj(xPosition + x, yPosition + y, 2) != Spielfeld.Kiste) {
xPosition = xPosition + x;
yPosition = yPosition + y;
Game.restartGame();
}
/*
* wenn das angepeilte Feld eine Explosion ist, dann wird die Figur
* dorthin bewegt. Allerdings stirbt diese dann --> Spieler2 hat
* gewonnen --> Spiel startet neu
*/
else if (Spielflaeche.play.equalsExplosion(xPosition + x,
yPosition + y, 3)
|| (Spielflaeche.play.equalsExplosion(xPosition, yPosition, 3))) {
Spielflaeche.play.fill(xPosition, yPosition, 3, Spielfeld.Gras);
xPosition = xPosition + x;
yPosition = yPosition + y;
System.out.println("Player 2 siegt");
// Label soll erstellt werden // Tot - wanna restart?
}
/*
* Es wird festgestellt, ob das angepeilte Feld bereits mit einem
* Objekt, das unpassierbarist, belegt ist. Wenn es passierbar ist geht
* die Abfrage weiter.
*/
else if (Spielflaeche.play.getObj(xPosition + x, yPosition + y, 2) == null
&& Spielflaeche.play.getObj(xPosition + x, yPosition + y, 4) == null
&& Spielflaeche.play.equalsMauer(xPosition + x, yPosition + y) == false) {
/*
* Es wird abgefragt ob eine Bombe gelegt wurde. Wenn eine Bombe
* gelegt wurde, dann wird auf den Variablen xPostítion und
* yPosition des Spielfigurenobjektes eine Bombe gezeichnet.
*/
Spielflaeche.play.fill(xPosition, yPosition, 3, Spielfeld.Gras);
/*
* if (Spielflaeche.bman.bombeLiegt) { Spielflaeche.play
* .fill(xPosition, yPosition, 4, Spielfeld.Bombe); bombeLiegt =
* false; // Noch eine Bedingung ( Wenn Explo --> Bman // auf explo
* // sieht verkohlt aus
*
* }
*/
/*
* Bewegung der Figur
*/
xPosition = xPosition + x;
yPosition = yPosition + y;
}
}// move
| public void move(int x, int y) {
/*
* Das Spiel wird neu gestartet wenn Bomberman und Ausgang sich auf den
* selben Koordinaten befinden.
*/
if (Spielflaeche.play.getObj(xPosition + x, yPosition + y, 1) == Spielfeld.Ausgang
&& Spielflaeche.play.getObj(xPosition + x, yPosition + y, 2) != Spielfeld.Kiste) {
xPosition = xPosition + x;
yPosition = yPosition + y;
Game.restartGame();
}
/*
* wenn das angepeilte Feld eine Explosion ist, dann wird die Figur
* dorthin bewegt. Allerdings stirbt diese dann --> Spieler2 hat
* gewonnen --> Spiel startet neu
*/
else if (Spielflaeche.play.equalsExplosion(xPosition + x,
yPosition + y, 3)
|| (Spielflaeche.play.equalsExplosion(xPosition, yPosition, 3))) {
Spielflaeche.play.fill(xPosition, yPosition, 3, Spielfeld.Gras);
xPosition = xPosition + x;
yPosition = yPosition + y;
System.out.println("Player 2 siegt");
Game.restartGame();
// Label soll erstellt werden // Tot - wanna restart?
}
/*
* Es wird festgestellt, ob das angepeilte Feld bereits mit einem
* Objekt, das unpassierbarist, belegt ist. Wenn es passierbar ist geht
* die Abfrage weiter.
*/
else if (Spielflaeche.play.getObj(xPosition + x, yPosition + y, 2) == null
&& Spielflaeche.play.getObj(xPosition + x, yPosition + y, 4) == null
&& Spielflaeche.play.equalsMauer(xPosition + x, yPosition + y) == false) {
/*
* Es wird abgefragt ob eine Bombe gelegt wurde. Wenn eine Bombe
* gelegt wurde, dann wird auf den Variablen xPostítion und
* yPosition des Spielfigurenobjektes eine Bombe gezeichnet.
*/
Spielflaeche.play.fill(xPosition, yPosition, 3, Spielfeld.Gras);
/*
* if (Spielflaeche.bman.bombeLiegt) { Spielflaeche.play
* .fill(xPosition, yPosition, 4, Spielfeld.Bombe); bombeLiegt =
* false; // Noch eine Bedingung ( Wenn Explo --> Bman // auf explo
* // sieht verkohlt aus
*
* }
*/
/*
* Bewegung der Figur
*/
xPosition = xPosition + x;
yPosition = yPosition + y;
}
}// move
|
diff --git a/src/com/github/grandmarket/market/Market.java b/src/com/github/grandmarket/market/Market.java
index 70b036c..3b91226 100644
--- a/src/com/github/grandmarket/market/Market.java
+++ b/src/com/github/grandmarket/market/Market.java
@@ -1,67 +1,69 @@
package com.github.grandmarket.market;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.plugin.java.JavaPlugin;
import lib.PatPeter.SQLibrary.*;
public class Market extends JavaPlugin implements Listener {
public SQLite dbconn;
public Logger logger;
public void onEnable() {
logger = Logger.getLogger("Minecraft");
dbconn = new SQLite(logger, "", "GrandMarket", "./plugins/GrandMarket/");
dbconn.open();
if(!dbconn.checkTable("settings")) {
logger.log(Level.INFO, "GrandMarket: Creating table \"settings\" in database \""+dbconn.name+"\"");
dbconn.createTable("CREATE TABLE settings (id INTEGER NOT NULL PRIMARY KEY, setting TEXT, value BLOB)");
}
try {
if(!dbconn.query("SELECT * FROM settings WHERE setting='setup' LIMIT 1").next()) {
getLogger().log(Level.WARNING, "GrandMarket: The setup has not been completed. We recomend that this be done ASAP.");
}
}
catch (SQLException e) {
e.printStackTrace();
}
getLogger().info("The market plugin has been enabled.");
}
public void onDisable() {
getLogger().info("The market plugin has been disabled.");
}
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if(cmd.getName().equalsIgnoreCase("market")) {
if(args.length < 1) {
try {
ResultSet query = dbconn.query("SELECT * FROM settings WHERE setting='mainText' LIMIT 1");
if(query.first()) {
sender.sendMessage(query.getString("value"));
}
else {
if(sender.isOp()) {
sender.sendMessage("The market is a marketplace where people can buy and sell items.");
sender.sendMessage("This message is the default help message. Change the plugin settings (or go through the setup) to change this message.");
}
}
}
catch (SQLException e) {
e.printStackTrace();
+ getLogger().log(Level.SEVERE, "SQLException onCommand market.main");
}
+ return true;
}
}
return false;
}
@EventHandler
public void onPlayerLogin(PlayerLoginEvent event) {
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if(cmd.getName().equalsIgnoreCase("market")) {
if(args.length < 1) {
try {
ResultSet query = dbconn.query("SELECT * FROM settings WHERE setting='mainText' LIMIT 1");
if(query.first()) {
sender.sendMessage(query.getString("value"));
}
else {
if(sender.isOp()) {
sender.sendMessage("The market is a marketplace where people can buy and sell items.");
sender.sendMessage("This message is the default help message. Change the plugin settings (or go through the setup) to change this message.");
}
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if(cmd.getName().equalsIgnoreCase("market")) {
if(args.length < 1) {
try {
ResultSet query = dbconn.query("SELECT * FROM settings WHERE setting='mainText' LIMIT 1");
if(query.first()) {
sender.sendMessage(query.getString("value"));
}
else {
if(sender.isOp()) {
sender.sendMessage("The market is a marketplace where people can buy and sell items.");
sender.sendMessage("This message is the default help message. Change the plugin settings (or go through the setup) to change this message.");
}
}
}
catch (SQLException e) {
e.printStackTrace();
getLogger().log(Level.SEVERE, "SQLException onCommand market.main");
}
return true;
}
}
return false;
}
|
diff --git a/labs/elb/src/main/java/org/jclouds/elb/loadbalancer/strategy/ELBLoadBalanceNodesStrategy.java b/labs/elb/src/main/java/org/jclouds/elb/loadbalancer/strategy/ELBLoadBalanceNodesStrategy.java
index ec5cd27ba3..d53184f745 100644
--- a/labs/elb/src/main/java/org/jclouds/elb/loadbalancer/strategy/ELBLoadBalanceNodesStrategy.java
+++ b/labs/elb/src/main/java/org/jclouds/elb/loadbalancer/strategy/ELBLoadBalanceNodesStrategy.java
@@ -1,122 +1,122 @@
/**
* Licensed to jclouds, Inc. (jclouds) under one or more
* contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. jclouds 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.jclouds.elb.loadbalancer.strategy;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.in;
import static com.google.common.base.Predicates.not;
import static com.google.common.collect.Iterables.transform;
import static com.google.common.collect.Sets.filter;
import static org.jclouds.aws.util.AWSUtils.getRegionFromLocationOrNull;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.domain.Location;
import org.jclouds.elb.ELBClient;
import org.jclouds.elb.domain.Listener;
import org.jclouds.elb.domain.Protocol;
import org.jclouds.elb.domain.regionscoped.LoadBalancerInRegion;
import org.jclouds.loadbalancer.domain.LoadBalancerMetadata;
import org.jclouds.loadbalancer.reference.LoadBalancerConstants;
import org.jclouds.loadbalancer.strategy.LoadBalanceNodesStrategy;
import org.jclouds.logging.Logger;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
/**
*
* @author Adrian Cole
*/
@Singleton
public class ELBLoadBalanceNodesStrategy implements LoadBalanceNodesStrategy {
@Resource
@Named(LoadBalancerConstants.LOADBALANCER_LOGGER)
protected Logger logger = Logger.NULL;
protected final ELBClient client;
protected final Function<LoadBalancerInRegion, LoadBalancerMetadata> converter;
@Inject
protected ELBLoadBalanceNodesStrategy(ELBClient client,
Function<LoadBalancerInRegion, LoadBalancerMetadata> converter) {
this.client = checkNotNull(client, "client");
this.converter = checkNotNull(converter, "converter");
}
@Override
public LoadBalancerMetadata createLoadBalancerInLocation(Location location, String name, String protocol,
int loadBalancerPort, int instancePort, Iterable<? extends NodeMetadata> nodes) {
checkNotNull(location, "location");
String region = getRegionFromLocationOrNull(location);
Set<String> zonesDesired = ImmutableSet.copyOf(transform(nodes, new Function<NodeMetadata, String>() {
@Override
public String apply(NodeMetadata from) {
return from.getLocation().getId();
}
}));
logger.debug(">> creating loadBalancer(%s) in zones(%s)", name, zonesDesired);
try {
String dnsName = client.getLoadBalancerClientForRegion(region).createLoadBalancerListeningInAvailabilityZones(
name,
ImmutableSet.of(Listener.builder().port(loadBalancerPort).instancePort(instancePort)
.protocol(Protocol.valueOf(protocol)).build()), zonesDesired);
logger.debug("<< created loadBalancer(%s) dnsName(%s)", name, dnsName);
} catch (IllegalStateException e) {
logger.debug("<< converging zones(%s) in loadBalancer(%s)", zonesDesired, name);
Set<String> currentZones = client.getLoadBalancerClient().get(name).getAvailabilityZones();
Set<String> zonesToAdd = Sets.difference(zonesDesired, currentZones);
if (zonesToAdd.size() > 0)
currentZones = client.getAvailabilityZoneClient().addAvailabilityZonesToLoadBalancer(zonesToAdd, name);
Set<String> zonesToRemove = Sets.difference(currentZones, zonesDesired);
if (zonesToRemove.size() > 0)
- client.getAvailabilityZoneClient().addAvailabilityZonesToLoadBalancer(zonesToRemove, name);
+ client.getAvailabilityZoneClient().removeAvailabilityZonesFromLoadBalancer(zonesToRemove, name);
}
Set<String> instanceIds = ImmutableSet.copyOf(transform(nodes, new Function<NodeMetadata, String>() {
@Override
public String apply(NodeMetadata from) {
return from.getProviderId();
}
}));
logger.debug(">> converging loadBalancer(%s) to instances(%s)", name, instanceIds);
Set<String> registeredInstanceIds = client.getInstanceClientForRegion(region).registerInstancesWithLoadBalancer(
instanceIds, name);
Set<String> instancesToRemove = filter(registeredInstanceIds, not(in(instanceIds)));
if (instancesToRemove.size() > 0) {
logger.debug(">> deregistering instances(%s) from loadBalancer(%s)", instancesToRemove, name);
client.getInstanceClientForRegion(region).deregisterInstancesFromLoadBalancer(instancesToRemove, name);
}
logger.debug("<< converged loadBalancer(%s) ", name);
return converter.apply(new LoadBalancerInRegion(client.getLoadBalancerClientForRegion(region).get(name), region));
}
}
| true | true | public LoadBalancerMetadata createLoadBalancerInLocation(Location location, String name, String protocol,
int loadBalancerPort, int instancePort, Iterable<? extends NodeMetadata> nodes) {
checkNotNull(location, "location");
String region = getRegionFromLocationOrNull(location);
Set<String> zonesDesired = ImmutableSet.copyOf(transform(nodes, new Function<NodeMetadata, String>() {
@Override
public String apply(NodeMetadata from) {
return from.getLocation().getId();
}
}));
logger.debug(">> creating loadBalancer(%s) in zones(%s)", name, zonesDesired);
try {
String dnsName = client.getLoadBalancerClientForRegion(region).createLoadBalancerListeningInAvailabilityZones(
name,
ImmutableSet.of(Listener.builder().port(loadBalancerPort).instancePort(instancePort)
.protocol(Protocol.valueOf(protocol)).build()), zonesDesired);
logger.debug("<< created loadBalancer(%s) dnsName(%s)", name, dnsName);
} catch (IllegalStateException e) {
logger.debug("<< converging zones(%s) in loadBalancer(%s)", zonesDesired, name);
Set<String> currentZones = client.getLoadBalancerClient().get(name).getAvailabilityZones();
Set<String> zonesToAdd = Sets.difference(zonesDesired, currentZones);
if (zonesToAdd.size() > 0)
currentZones = client.getAvailabilityZoneClient().addAvailabilityZonesToLoadBalancer(zonesToAdd, name);
Set<String> zonesToRemove = Sets.difference(currentZones, zonesDesired);
if (zonesToRemove.size() > 0)
client.getAvailabilityZoneClient().addAvailabilityZonesToLoadBalancer(zonesToRemove, name);
}
Set<String> instanceIds = ImmutableSet.copyOf(transform(nodes, new Function<NodeMetadata, String>() {
@Override
public String apply(NodeMetadata from) {
return from.getProviderId();
}
}));
logger.debug(">> converging loadBalancer(%s) to instances(%s)", name, instanceIds);
Set<String> registeredInstanceIds = client.getInstanceClientForRegion(region).registerInstancesWithLoadBalancer(
instanceIds, name);
Set<String> instancesToRemove = filter(registeredInstanceIds, not(in(instanceIds)));
if (instancesToRemove.size() > 0) {
logger.debug(">> deregistering instances(%s) from loadBalancer(%s)", instancesToRemove, name);
client.getInstanceClientForRegion(region).deregisterInstancesFromLoadBalancer(instancesToRemove, name);
}
logger.debug("<< converged loadBalancer(%s) ", name);
return converter.apply(new LoadBalancerInRegion(client.getLoadBalancerClientForRegion(region).get(name), region));
}
| public LoadBalancerMetadata createLoadBalancerInLocation(Location location, String name, String protocol,
int loadBalancerPort, int instancePort, Iterable<? extends NodeMetadata> nodes) {
checkNotNull(location, "location");
String region = getRegionFromLocationOrNull(location);
Set<String> zonesDesired = ImmutableSet.copyOf(transform(nodes, new Function<NodeMetadata, String>() {
@Override
public String apply(NodeMetadata from) {
return from.getLocation().getId();
}
}));
logger.debug(">> creating loadBalancer(%s) in zones(%s)", name, zonesDesired);
try {
String dnsName = client.getLoadBalancerClientForRegion(region).createLoadBalancerListeningInAvailabilityZones(
name,
ImmutableSet.of(Listener.builder().port(loadBalancerPort).instancePort(instancePort)
.protocol(Protocol.valueOf(protocol)).build()), zonesDesired);
logger.debug("<< created loadBalancer(%s) dnsName(%s)", name, dnsName);
} catch (IllegalStateException e) {
logger.debug("<< converging zones(%s) in loadBalancer(%s)", zonesDesired, name);
Set<String> currentZones = client.getLoadBalancerClient().get(name).getAvailabilityZones();
Set<String> zonesToAdd = Sets.difference(zonesDesired, currentZones);
if (zonesToAdd.size() > 0)
currentZones = client.getAvailabilityZoneClient().addAvailabilityZonesToLoadBalancer(zonesToAdd, name);
Set<String> zonesToRemove = Sets.difference(currentZones, zonesDesired);
if (zonesToRemove.size() > 0)
client.getAvailabilityZoneClient().removeAvailabilityZonesFromLoadBalancer(zonesToRemove, name);
}
Set<String> instanceIds = ImmutableSet.copyOf(transform(nodes, new Function<NodeMetadata, String>() {
@Override
public String apply(NodeMetadata from) {
return from.getProviderId();
}
}));
logger.debug(">> converging loadBalancer(%s) to instances(%s)", name, instanceIds);
Set<String> registeredInstanceIds = client.getInstanceClientForRegion(region).registerInstancesWithLoadBalancer(
instanceIds, name);
Set<String> instancesToRemove = filter(registeredInstanceIds, not(in(instanceIds)));
if (instancesToRemove.size() > 0) {
logger.debug(">> deregistering instances(%s) from loadBalancer(%s)", instancesToRemove, name);
client.getInstanceClientForRegion(region).deregisterInstancesFromLoadBalancer(instancesToRemove, name);
}
logger.debug("<< converged loadBalancer(%s) ", name);
return converter.apply(new LoadBalancerInRegion(client.getLoadBalancerClientForRegion(region).get(name), region));
}
|
diff --git a/src/org/ojim/logic/actions/ActionFetchCard.java b/src/org/ojim/logic/actions/ActionFetchCard.java
index 98ed6b7..ee2d578 100644
--- a/src/org/ojim/logic/actions/ActionFetchCard.java
+++ b/src/org/ojim/logic/actions/ActionFetchCard.java
@@ -1,26 +1,26 @@
package org.ojim.logic.actions;
import org.ojim.logic.ServerLogic;
import org.ojim.logic.state.Card;
import org.ojim.logic.state.CardStack;
public class ActionFetchCard implements Action {
private final ServerLogic logic;
private final CardStack stack;
public ActionFetchCard(ServerLogic logic, CardStack stack) {
this.logic = logic;
this.stack = stack;
}
@Override
public void execute() {
- if (this.stack.isEmpty()) {
+ if (!this.stack.isEmpty()) {
Card topCard = this.stack.getPointedCard();
this.stack.step();
topCard.fetch();
}
}
}
| true | true | public void execute() {
if (this.stack.isEmpty()) {
Card topCard = this.stack.getPointedCard();
this.stack.step();
topCard.fetch();
}
}
| public void execute() {
if (!this.stack.isEmpty()) {
Card topCard = this.stack.getPointedCard();
this.stack.step();
topCard.fetch();
}
}
|
diff --git a/org.orbisgis.core-ui/src/main/java/org/orbisgis/editors/map/tools/ToolValidationUtilities.java b/org.orbisgis.core-ui/src/main/java/org/orbisgis/editors/map/tools/ToolValidationUtilities.java
index bbac52215..ff76669fc 100644
--- a/org.orbisgis.core-ui/src/main/java/org/orbisgis/editors/map/tools/ToolValidationUtilities.java
+++ b/org.orbisgis.core-ui/src/main/java/org/orbisgis/editors/map/tools/ToolValidationUtilities.java
@@ -1,99 +1,103 @@
/*
* OrbisGIS is a GIS application dedicated to scientific spatial simulation.
* This cross-platform GIS is developed at French IRSTV institute and is able
* to manipulate and create vector and raster spatial information. OrbisGIS
* is distributed under GPL 3 license. It is produced by the geo-informatic team of
* the IRSTV Institute <http://www.irstv.cnrs.fr/>, CNRS FR 2488:
* Erwan BOCHER, scientific researcher,
* Thomas LEDUC, scientific researcher,
* Fernando GONZALEZ CORTES, computer engineer.
*
* Copyright (C) 2007 Erwan BOCHER, Fernando GONZALEZ CORTES, Thomas LEDUC
*
* This file is part of OrbisGIS.
*
* OrbisGIS 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.
*
* OrbisGIS 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 OrbisGIS. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, please consult:
* <http://orbisgis.cerma.archi.fr/>
* <http://sourcesup.cru.fr/projects/orbisgis/>
*
* or contact directly:
* erwan.bocher _at_ ec-nantes.fr
* fergonco _at_ gmail.com
* thomas.leduc _at_ cerma.archi.fr
*/
package org.orbisgis.editors.map.tools;
import org.gdms.data.SpatialDataSourceDecorator;
import org.gdms.data.types.Constraint;
import org.gdms.data.types.Type;
import org.gdms.driver.DriverException;
import org.orbisgis.layerModel.ILayer;
import org.orbisgis.layerModel.MapContext;
public class ToolValidationUtilities {
public static boolean isActiveLayerEditable(MapContext vc) {
ILayer activeLayer = vc.getActiveLayer();
if (activeLayer == null) {
return false;
} else {
return activeLayer.getDataSource().isEditable();
}
}
public static boolean isActiveLayerVisible(MapContext vc) {
ILayer activeLayer = vc.getActiveLayer();
if (activeLayer == null) {
return false;
} else {
return activeLayer.isVisible();
}
}
public static boolean activeSelectionGreaterThan(MapContext vc, int i) {
ILayer activeLayer = vc.getActiveLayer();
if (activeLayer == null) {
return false;
} else {
return activeLayer.getSelection().length >= i;
}
}
public static boolean geometryTypeIs(MapContext vc, int... geometryTypes) {
ILayer activeLayer = vc.getActiveLayer();
if (activeLayer == null) {
return false;
} else {
try {
SpatialDataSourceDecorator sds = activeLayer.getDataSource();
Type type = sds.getFieldType(sds.getSpatialFieldIndex());
int geometryType = type
.getIntConstraint(Constraint.GEOMETRY_TYPE);
- for (int geomType : geometryTypes) {
- if (geomType == geometryType) {
- return true;
+ if (geometryType == -1) {
+ return true;
+ } else {
+ for (int geomType : geometryTypes) {
+ if (geomType == geometryType) {
+ return true;
+ }
}
}
} catch (DriverException e) {
}
return false;
}
}
public static boolean layerCountGreaterThan(MapContext vc, int i) {
return vc.getLayerModel().getLayersRecursively().length > i;
}
}
| true | true | public static boolean geometryTypeIs(MapContext vc, int... geometryTypes) {
ILayer activeLayer = vc.getActiveLayer();
if (activeLayer == null) {
return false;
} else {
try {
SpatialDataSourceDecorator sds = activeLayer.getDataSource();
Type type = sds.getFieldType(sds.getSpatialFieldIndex());
int geometryType = type
.getIntConstraint(Constraint.GEOMETRY_TYPE);
for (int geomType : geometryTypes) {
if (geomType == geometryType) {
return true;
}
}
} catch (DriverException e) {
}
return false;
}
}
| public static boolean geometryTypeIs(MapContext vc, int... geometryTypes) {
ILayer activeLayer = vc.getActiveLayer();
if (activeLayer == null) {
return false;
} else {
try {
SpatialDataSourceDecorator sds = activeLayer.getDataSource();
Type type = sds.getFieldType(sds.getSpatialFieldIndex());
int geometryType = type
.getIntConstraint(Constraint.GEOMETRY_TYPE);
if (geometryType == -1) {
return true;
} else {
for (int geomType : geometryTypes) {
if (geomType == geometryType) {
return true;
}
}
}
} catch (DriverException e) {
}
return false;
}
}
|
diff --git a/de.walware.statet.r.core/src/de/walware/statet/r/core/model/RElementName.java b/de.walware.statet.r.core/src/de/walware/statet/r/core/model/RElementName.java
index 9627fc92..e4e7bb21 100644
--- a/de.walware.statet.r.core/src/de/walware/statet/r/core/model/RElementName.java
+++ b/de.walware.statet.r.core/src/de/walware/statet/r/core/model/RElementName.java
@@ -1,783 +1,784 @@
/*******************************************************************************
* Copyright (c) 2008-2012 WalWare/StatET-Project (www.walware.de/goto/statet).
* 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:
* Stephan Wahlbrink - initial API and implementation
*******************************************************************************/
package de.walware.statet.r.core.model;
import static de.walware.statet.r.core.rsource.IRSourceConstants.STATUS2_SYNTAX_TOKEN_NOT_CLOSED;
import static de.walware.statet.r.core.rsource.IRSourceConstants.STATUS_MASK_12;
import static de.walware.statet.r.core.rsource.IRSourceConstants.STATUS_OK;
import java.io.Serializable;
import java.util.Comparator;
import java.util.List;
import com.ibm.icu.text.Collator;
import de.walware.ecommons.ltk.IElementName;
import de.walware.ecommons.text.SourceParseInput;
import de.walware.ecommons.text.StringParseInput;
import de.walware.statet.r.core.RSymbolComparator;
import de.walware.statet.r.core.rlang.RTerminal;
import de.walware.statet.r.core.rsource.RLexer;
/**
* Base class for R element names
*
* Defines type constants and provides static utility methods.
*/
public abstract class RElementName implements IElementName {
public static final int RESOURCE = 0x00f;
public static final int MAIN_OTHER = 0x010;
public static final int MAIN_DEFAULT = 0x011;
public static final int MAIN_CLASS = 0x013;
public static final int MAIN_SEARCH_ENV = 0x015;
public static final int MAIN_PACKAGE = 0x016;
public static final int MAIN_SYSFRAME = 0x017;
public static final int MAIN_PROJECT = 0x018;
public static final int SUB_NAMEDSLOT = 0x01a;
public static final int SUB_NAMEDPART = 0x01b;
public static final int SUB_INDEXED_S = 0x01d;
public static final int SUB_INDEXED_D = 0x01e;
public static final int ANONYMOUS = 0x020;
public static final int DISPLAY_NS_PREFIX = 0x1;
public static final int DISPLAY_EXACT = 0x2;
/**
* Element names providing the exact index as number (for SUB_INDEXED_D).
*/
public static interface IndexElementName extends IElementName {
int getIndex();
}
public static String createDisplayName(RElementName a, final int options) {
StringBuilder sb = null;
if ((options & DISPLAY_NS_PREFIX) != 0) {
final RElementName namespace = a.getNamespace();
if (namespace != null) {
sb = new StringBuilder(32);
if (!appendEnvAccess(namespace, sb, options)
|| a.getType() != MAIN_DEFAULT) {
return null;
}
}
else if (a.getType() == MAIN_SEARCH_ENV
|| a.getType() == MAIN_PACKAGE
|| a.getType() == MAIN_SYSFRAME) {
sb = new StringBuilder(32);
if (!appendEnvAccess(a, sb, options)
|| (a = a.getNextSegment()) != null && a.getType() != MAIN_DEFAULT) {
return null;
}
}
if (sb != null && a != null) {
sb.append('$');
final String name = a.getSegmentName();
if (name != null) {
appendSymbol(sb, name);
}
a = a.getNextSegment();
}
}
if (sb == null) {
String firstName;
final int type = a.getType();
switch (type) {
case MAIN_DEFAULT:
case MAIN_CLASS:
case SUB_NAMEDPART:
case SUB_NAMEDSLOT:
firstName = a.getSegmentName();
if (firstName != null) {
sb = appendSymbol(sb, firstName);
}
else {
firstName = ""; //$NON-NLS-1$
}
a = a.getNextSegment();
if (a == null) {
return (sb != null) ? sb.toString() : firstName;
}
if (sb == null) {
sb = new StringBuilder(firstName);
}
break;
case MAIN_SEARCH_ENV:
firstName = a.getSegmentName();
if (firstName != null) {
return firstName;
}
return null;
case MAIN_SYSFRAME:
firstName = a.getSegmentName();
if (firstName != null) {
return "frame:"+firstName;
}
return null;
case MAIN_PACKAGE:
firstName = a.getSegmentName();
if (firstName != null) {
return "package:"+firstName;
}
else if ((options & DISPLAY_EXACT) == 0) {
return "package:<unknown>";
}
else {
return null;
}
case MAIN_PROJECT:
firstName = a.getSegmentName();
if (firstName != null) {
return "project:"+firstName;
}
else if ((options & DISPLAY_EXACT) == 0) {
return "project:<unknown>";
}
else {
return null;
}
case SUB_INDEXED_D:
if (a instanceof DefaultImpl) {
sb = new StringBuilder("[["); //$NON-NLS-1$
sb.append(a.getSegmentName());
sb.append("]]"); //$NON-NLS-1$
a = a.getNextSegment();
break;
}
return null;
case RESOURCE:
case MAIN_OTHER:
return a.getSegmentName();
case ANONYMOUS:
if ((options & DISPLAY_EXACT) == 0) {
return "<anonymous>";
}
return null;
default:
return null;
}
}
APPEND_SUB : while (a != null) {
String name;
switch (a.getType()) {
case MAIN_DEFAULT:
case MAIN_CLASS:
case SUB_NAMEDPART:
if (((options & DISPLAY_EXACT) != 0) && a instanceof IndexElementName) {
sb.append("[[");
sb.append(((IndexElementName) a).getIndex());
sb.append("L]]");
}
else {
sb.append('$');
name = a.getSegmentName();
if (name != null) {
appendSymbol(sb, name);
}
}
a = a.getNextSegment();
continue APPEND_SUB;
case SUB_NAMEDSLOT:
sb.append('@');
name = a.getSegmentName();
if (name != null) {
appendSymbol(sb, name);
}
a = a.getNextSegment();
continue APPEND_SUB;
case SUB_INDEXED_S:
if (((options & DISPLAY_EXACT) != 0)) {
return null;
}
sb.append("[…]"); //$NON-NLS-1$
break APPEND_SUB;
case SUB_INDEXED_D:
if (a instanceof DefaultImpl) {
sb.append("[["); //$NON-NLS-1$
sb.append(a.getSegmentName());
sb.append("]]"); //$NON-NLS-1$
a = a.getNextSegment();
continue APPEND_SUB;
}
else if ((options & DISPLAY_EXACT) == 0) {
sb.append("[[…]]"); //$NON-NLS-1$
+ a = a.getNextSegment();
continue APPEND_SUB;
}
else {
return null;
}
default:
if (((options & DISPLAY_EXACT) == 0)) {
sb.append(" …"); //$NON-NLS-1$
break APPEND_SUB;
}
return null;
}
}
return sb.toString();
}
private static boolean appendEnvAccess(final RElementName a, StringBuilder sb, final int options) {
final String namespaceName;
switch (a.getType()) {
case MAIN_SEARCH_ENV:
namespaceName = a.getSegmentName();
if (namespaceName == null) {
return false;
}
sb.append("as.environment(\""); //$NON-NLS-1$
sb.append(namespaceName);
sb.append("\")"); //$NON-NLS-1$
return true;
case MAIN_PACKAGE:
namespaceName = a.getSegmentName();
if (namespaceName == null) {
return false;
}
sb.append("as.environment(\"package:"); //$NON-NLS-1$
sb.append(namespaceName);
sb.append("\")"); //$NON-NLS-1$
return true;
case MAIN_SYSFRAME:
namespaceName = a.getSegmentName();
if (namespaceName == null) {
return false;
}
sb.append("sys.frame("); //$NON-NLS-1$
sb.append(namespaceName);
sb.append(((options & DISPLAY_EXACT) != 0) ? "L)" : ")"); //$NON-NLS-1$
return true;
case MAIN_PROJECT:
sb = new StringBuilder(44);
sb.append("as.environment(\".GlobalEnv\")"); //$NON-NLS-1$
return true;
default:
return false;
}
}
private static StringBuilder appendSymbol(StringBuilder sb, final String name) {
if (name == null) {
return null;
}
final int l = name.length();
if (l == 0) {
return (sb != null) ? sb.append("``") : new StringBuilder("``"); //$NON-NLS-1$ //$NON-NLS-2$
}
final char c0 = name.charAt(0);
int check;
if (Character.isLetter(c0)) {
check = 1;
}
else if (c0 == '.') {
if (l == 1) {
check = 1;
}
else {
final char c1 = name.charAt(1);
if (c1 == '.' || c1 == '_' || Character.isLetter(c1)) {
check = 2;
}
else {
check = -1;
}
}
}
else {
check = -1;
}
VALID : if (check >= 0) {
for (; check < l; check++) {
final char cn = name.charAt(check);
if ((cn < 'a' || cn > 'z') && cn != '.' && cn != '_' && !Character.isLetterOrDigit(cn)) {
break VALID;
}
}
return (sb != null) ? sb.append(name) : null;
}
// no valid
if (sb == null) {
sb = new StringBuilder(name.length()+18);
}
sb.append('`');
sb.append(name);
sb.append('`');
return sb;
}
private static final Collator NAME_COLLATOR = RSymbolComparator.R_NAMES_COLLATOR;
public static final Comparator<IElementName> NAMEONLY_COMPARATOR = new Comparator<IElementName>() {
@Override
public int compare(IElementName o1, IElementName o2) {
final String n1 = o1.getSegmentName();
final String n2 = o2.getSegmentName();
if (n1 != null) {
if (n2 != null) {
final int diff = NAME_COLLATOR.compare(n1, n2);
if (diff != 0) {
return diff;
}
}
else {
return Integer.MIN_VALUE;
}
}
else if (n2 != null) {
return Integer.MAX_VALUE;
}
o1 = o1.getNextSegment();
o2 = o2.getNextSegment();
if (o1 != null) {
if (o2 != null) {
final int diff = o1.getType() - o2.getType();
if (diff != 0) {
return diff;
}
return compare(o1, o2);
}
else {
return Integer.MIN_VALUE+100;
}
}
else if (n2 != null) {
return Integer.MAX_VALUE-100;
}
return 0;
}
};
private static class DefaultImpl extends RElementName implements Serializable {
private static final long serialVersionUID = 315497720879434929L;
private final int fType;
private final String fSegmentName;
private RElementName fNamespace;
private RElementName fNextSegment;
public DefaultImpl(final int type, final String segmentName) {
fType = type;
fSegmentName = segmentName;
fNextSegment = null;
}
public DefaultImpl(final int type, final RElementName namespace, final String segmentName, final RElementName next) {
fType = type;
fSegmentName = segmentName;
fNamespace = namespace;
fNextSegment = next;
}
public DefaultImpl(final int type, final String segmentName, final RElementName next) {
fType = type;
fSegmentName = segmentName;
fNextSegment = next;
}
@Override
public int getType() {
return fType;
}
@Override
public String getSegmentName() {
return fSegmentName;
}
@Override
public RElementName getNamespace() {
return fNamespace;
}
@Override
public RElementName getNextSegment() {
return fNextSegment;
}
}
private static class DualImpl extends DefaultImpl implements IndexElementName {
private static final long serialVersionUID = 7040207683623992047L;
private final int fIdx;
public DualImpl(final int type, final String segmentName, final int idx) {
super(type, segmentName);
fIdx = idx;
}
public DualImpl(final int type, final String segmentName, final int idx,
final RElementName next) {
super(type, segmentName, next);
fIdx = idx;
}
@Override
protected DefaultImpl cloneSegment0(final RElementName next) {
return new DualImpl(getType(), getSegmentName(), fIdx, next);
}
@Override
public int getIndex() {
return fIdx;
}
}
/**
* Lexer for RScanner.
*/
private static class ParseLexer extends RLexer {
public ParseLexer(final SourceParseInput input) {
super(input);
}
@Override
protected void createSymbolToken() {
fFoundType = RTerminal.SYMBOL;
fFoundText = fInput.substring(1, fFoundNum);
fFoundStatus = STATUS_OK;
}
@Override
protected void createQuotedSymbolToken(final RTerminal type, final int status) {
fFoundType = type;
fFoundText = ((status & STATUS_MASK_12) != STATUS2_SYNTAX_TOKEN_NOT_CLOSED) ?
fInput.substring(2, fFoundNum-2) : fInput.substring(2, fFoundNum-1);
fFoundStatus = status;
}
@Override
protected void createStringToken(final RTerminal type, final int status) {
fFoundType = type;
fFoundText = ((status & STATUS_MASK_12) != STATUS2_SYNTAX_TOKEN_NOT_CLOSED) ?
fInput.substring(2, fFoundNum-2) : fInput.substring(2, fFoundNum-1);
fFoundStatus = status;
}
@Override
protected void createNumberToken(final RTerminal type, final int status) {
fFoundType = type;
fFoundText = fInput.substring(1, fFoundNum);
fFoundStatus = status;
}
@Override
protected void createWhitespaceToken() {
fFoundType = null;
}
@Override
protected void createCommentToken(final RTerminal type) {
fFoundType = null;
}
@Override
protected void createLinebreakToken(final String text) {
fFoundType = null;
}
@Override
protected void createUnknownToken(final String text) {
fFoundType = RTerminal.UNKNOWN;
fFoundText = text;
fFoundStatus = STATUS_OK;
}
}
public static RElementName create(final int type, final String segmentName) {
return new DefaultImpl(type, segmentName);
}
public static RElementName create(final int type, final String segmentName, final int idx) {
if (!(type == SUB_NAMEDPART || type == SUB_INDEXED_D)) {
throw new IllegalArgumentException();
}
return new DualImpl(type, segmentName, idx);
}
public static RElementName parseDefault(final String code) {
final ParseLexer lexer = new ParseLexer(new StringParseInput(code));
lexer.setFull();
int mode = MAIN_DEFAULT;
DefaultImpl main = null;
DefaultImpl last = null;
while (true) {
DefaultImpl tmp = null;
RTerminal type = lexer.next();
if (type == null || type == RTerminal.EOF) {
if (mode >= 0) {
tmp = new DefaultImpl(mode, ""); //$NON-NLS-1$
if (main == null) {
main = last = tmp;
}
else {
last.fNextSegment = tmp;
last = tmp;
}
}
return main;
}
else {
switch(type) {
case IF:
case ELSE:
case FOR:
case IN:
case WHILE:
case REPEAT:
case NEXT:
case BREAK:
case FUNCTION:
case TRUE:
case FALSE:
case NA:
case NA_INT:
case NA_REAL:
case NA_CPLX:
case NA_CHAR:
case NULL:
case NAN:
case INF:
if (mode != MAIN_DEFAULT && mode != MAIN_PACKAGE
&& mode != SUB_NAMEDPART && mode != SUB_NAMEDSLOT) {
return null;
}
tmp = new DefaultImpl(mode, type.text);
if (main == null) {
main = last = tmp;
}
else {
last.fNextSegment = tmp;
last = tmp;
}
type = lexer.next();
if (type == null || type == RTerminal.EOF) {
return main; // valid prefix
}
else {
return null; // invalid
}
case SYMBOL:
case SYMBOL_G:
if (mode != MAIN_DEFAULT && mode != MAIN_PACKAGE
&& mode != SUB_NAMEDPART && mode != SUB_NAMEDSLOT) {
return null;
}
tmp = new DefaultImpl(mode, lexer.getText());
if (main == null) {
main = last = tmp;
}
else {
last.fNextSegment = tmp;
last = tmp;
}
mode = -1;
continue;
case NUM_INT:
case NUM_NUM:
if (mode != SUB_INDEXED_S && mode != SUB_INDEXED_D) {
return null;
}
tmp = new DefaultImpl(mode, lexer.getText());
type = lexer.next();
if (type != RTerminal.SUB_INDEXED_CLOSE) {
return null;
}
if (main == null) {
main = last = tmp;
}
else {
last.fNextSegment = tmp;
last = tmp;
}
mode = -2;
continue;
case SUB_NAMED_PART:
if (main == null || mode >= 0) {
return null;
}
mode = SUB_NAMEDPART;
continue;
case SUB_NAMED_SLOT:
if (main == null || mode >= 0) {
return null;
}
mode = SUB_NAMEDSLOT;
continue;
case SUB_INDEXED_S_OPEN:
if (main == null || mode >= 0) {
return null;
}
mode = SUB_INDEXED_S;
continue;
case SUB_INDEXED_D_OPEN:
if (main == null || mode >= 0) {
return null;
}
mode = SUB_INDEXED_S;
continue;
case SUB_INDEXED_CLOSE:
if (mode != -2) {
return null;
}
continue;
case NS_GET:
case NS_GET_INT:
if (main != null || mode >= 0) {
return null;
}
mode = MAIN_PACKAGE;
continue;
default:
return null;
}
}
}
}
public static RElementName cloneName(RElementName name, final boolean withNamespace) {
if (name == null) {
return null;
}
RElementName namespace = (withNamespace) ? name.getNamespace() : null;
if (namespace != null) {
namespace = new DefaultImpl(namespace.getType(), namespace.getSegmentName(), null);
}
final DefaultImpl main = new DefaultImpl(name.getType(), namespace, name.getSegmentName(), null);
DefaultImpl last = main;
name = name.getNextSegment();
while (name != null) {
final DefaultImpl copy = name.cloneSegment0(null);
last.fNextSegment = copy;
last = copy;
name = name.getNextSegment();
}
return main;
}
public static RElementName cloneSegment(final RElementName name) {
return name.cloneSegment0(null);
}
public static RElementName concat(final List<RElementName> segments) {
if (segments.size() > 0) {
int first = 0;
RElementName namespace = segments.get(first);
switch (namespace.getType()) {
case MAIN_SEARCH_ENV:
case MAIN_PACKAGE:
case MAIN_SYSFRAME:
case MAIN_PROJECT:
first++;
break;
default:
namespace = null;
break;
}
if (segments.size() > first) {
RElementName next = null;
for (int i = segments.size()-1; i > first; i--) {
next = segments.get(i).cloneSegment0(next);
}
next = new DefaultImpl(segments.get(first).getType(), namespace, segments.get(first).getSegmentName(), next);
return next;
}
}
return null;
}
protected RElementName() {
}
public abstract RElementName getNamespace();
@Override
public abstract RElementName getNextSegment();
@Override
public String getDisplayName() {
return createDisplayName(this, 0);
}
public String getDisplayName(final int options) {
return createDisplayName(this, options);
}
protected RElementName.DefaultImpl cloneSegment0(final RElementName next) {
return new DefaultImpl(getType(), getSegmentName(), next);
}
@Override
public final int hashCode() {
final String name = getSegmentName();
final IElementName next = getNextSegment();
if (next != null) {
return getType() * ((name != null) ? name.hashCode() : 1) * (next.hashCode()+7);
}
else {
return getType() * ((name != null) ? name.hashCode() : 1);
}
}
@Override
public final boolean equals(final Object obj) {
if (!(obj instanceof RElementName)) {
return false;
}
final IElementName other = (RElementName) obj;
final String thisName = getSegmentName();
final String otherName = other.getSegmentName();
return ((getType() == other.getType())
&& ((thisName != null) ?
(thisName == otherName || (otherName != null && thisName.hashCode() == otherName.hashCode() && thisName.equals(otherName)) ) :
(null == other.getSegmentName()) )
&& ((getNextSegment() != null) ?
(getNextSegment().equals(other.getNextSegment())) :
(null == other.getNextSegment()) ) );
}
@Override
public String toString() {
return getDisplayName();
}
}
| true | true | public static String createDisplayName(RElementName a, final int options) {
StringBuilder sb = null;
if ((options & DISPLAY_NS_PREFIX) != 0) {
final RElementName namespace = a.getNamespace();
if (namespace != null) {
sb = new StringBuilder(32);
if (!appendEnvAccess(namespace, sb, options)
|| a.getType() != MAIN_DEFAULT) {
return null;
}
}
else if (a.getType() == MAIN_SEARCH_ENV
|| a.getType() == MAIN_PACKAGE
|| a.getType() == MAIN_SYSFRAME) {
sb = new StringBuilder(32);
if (!appendEnvAccess(a, sb, options)
|| (a = a.getNextSegment()) != null && a.getType() != MAIN_DEFAULT) {
return null;
}
}
if (sb != null && a != null) {
sb.append('$');
final String name = a.getSegmentName();
if (name != null) {
appendSymbol(sb, name);
}
a = a.getNextSegment();
}
}
if (sb == null) {
String firstName;
final int type = a.getType();
switch (type) {
case MAIN_DEFAULT:
case MAIN_CLASS:
case SUB_NAMEDPART:
case SUB_NAMEDSLOT:
firstName = a.getSegmentName();
if (firstName != null) {
sb = appendSymbol(sb, firstName);
}
else {
firstName = ""; //$NON-NLS-1$
}
a = a.getNextSegment();
if (a == null) {
return (sb != null) ? sb.toString() : firstName;
}
if (sb == null) {
sb = new StringBuilder(firstName);
}
break;
case MAIN_SEARCH_ENV:
firstName = a.getSegmentName();
if (firstName != null) {
return firstName;
}
return null;
case MAIN_SYSFRAME:
firstName = a.getSegmentName();
if (firstName != null) {
return "frame:"+firstName;
}
return null;
case MAIN_PACKAGE:
firstName = a.getSegmentName();
if (firstName != null) {
return "package:"+firstName;
}
else if ((options & DISPLAY_EXACT) == 0) {
return "package:<unknown>";
}
else {
return null;
}
case MAIN_PROJECT:
firstName = a.getSegmentName();
if (firstName != null) {
return "project:"+firstName;
}
else if ((options & DISPLAY_EXACT) == 0) {
return "project:<unknown>";
}
else {
return null;
}
case SUB_INDEXED_D:
if (a instanceof DefaultImpl) {
sb = new StringBuilder("[["); //$NON-NLS-1$
sb.append(a.getSegmentName());
sb.append("]]"); //$NON-NLS-1$
a = a.getNextSegment();
break;
}
return null;
case RESOURCE:
case MAIN_OTHER:
return a.getSegmentName();
case ANONYMOUS:
if ((options & DISPLAY_EXACT) == 0) {
return "<anonymous>";
}
return null;
default:
return null;
}
}
APPEND_SUB : while (a != null) {
String name;
switch (a.getType()) {
case MAIN_DEFAULT:
case MAIN_CLASS:
case SUB_NAMEDPART:
if (((options & DISPLAY_EXACT) != 0) && a instanceof IndexElementName) {
sb.append("[[");
sb.append(((IndexElementName) a).getIndex());
sb.append("L]]");
}
else {
sb.append('$');
name = a.getSegmentName();
if (name != null) {
appendSymbol(sb, name);
}
}
a = a.getNextSegment();
continue APPEND_SUB;
case SUB_NAMEDSLOT:
sb.append('@');
name = a.getSegmentName();
if (name != null) {
appendSymbol(sb, name);
}
a = a.getNextSegment();
continue APPEND_SUB;
case SUB_INDEXED_S:
if (((options & DISPLAY_EXACT) != 0)) {
return null;
}
sb.append("[…]"); //$NON-NLS-1$
break APPEND_SUB;
case SUB_INDEXED_D:
if (a instanceof DefaultImpl) {
sb.append("[["); //$NON-NLS-1$
sb.append(a.getSegmentName());
sb.append("]]"); //$NON-NLS-1$
a = a.getNextSegment();
continue APPEND_SUB;
}
else if ((options & DISPLAY_EXACT) == 0) {
sb.append("[[…]]"); //$NON-NLS-1$
continue APPEND_SUB;
}
else {
return null;
}
default:
if (((options & DISPLAY_EXACT) == 0)) {
sb.append(" …"); //$NON-NLS-1$
break APPEND_SUB;
}
return null;
}
}
return sb.toString();
}
| public static String createDisplayName(RElementName a, final int options) {
StringBuilder sb = null;
if ((options & DISPLAY_NS_PREFIX) != 0) {
final RElementName namespace = a.getNamespace();
if (namespace != null) {
sb = new StringBuilder(32);
if (!appendEnvAccess(namespace, sb, options)
|| a.getType() != MAIN_DEFAULT) {
return null;
}
}
else if (a.getType() == MAIN_SEARCH_ENV
|| a.getType() == MAIN_PACKAGE
|| a.getType() == MAIN_SYSFRAME) {
sb = new StringBuilder(32);
if (!appendEnvAccess(a, sb, options)
|| (a = a.getNextSegment()) != null && a.getType() != MAIN_DEFAULT) {
return null;
}
}
if (sb != null && a != null) {
sb.append('$');
final String name = a.getSegmentName();
if (name != null) {
appendSymbol(sb, name);
}
a = a.getNextSegment();
}
}
if (sb == null) {
String firstName;
final int type = a.getType();
switch (type) {
case MAIN_DEFAULT:
case MAIN_CLASS:
case SUB_NAMEDPART:
case SUB_NAMEDSLOT:
firstName = a.getSegmentName();
if (firstName != null) {
sb = appendSymbol(sb, firstName);
}
else {
firstName = ""; //$NON-NLS-1$
}
a = a.getNextSegment();
if (a == null) {
return (sb != null) ? sb.toString() : firstName;
}
if (sb == null) {
sb = new StringBuilder(firstName);
}
break;
case MAIN_SEARCH_ENV:
firstName = a.getSegmentName();
if (firstName != null) {
return firstName;
}
return null;
case MAIN_SYSFRAME:
firstName = a.getSegmentName();
if (firstName != null) {
return "frame:"+firstName;
}
return null;
case MAIN_PACKAGE:
firstName = a.getSegmentName();
if (firstName != null) {
return "package:"+firstName;
}
else if ((options & DISPLAY_EXACT) == 0) {
return "package:<unknown>";
}
else {
return null;
}
case MAIN_PROJECT:
firstName = a.getSegmentName();
if (firstName != null) {
return "project:"+firstName;
}
else if ((options & DISPLAY_EXACT) == 0) {
return "project:<unknown>";
}
else {
return null;
}
case SUB_INDEXED_D:
if (a instanceof DefaultImpl) {
sb = new StringBuilder("[["); //$NON-NLS-1$
sb.append(a.getSegmentName());
sb.append("]]"); //$NON-NLS-1$
a = a.getNextSegment();
break;
}
return null;
case RESOURCE:
case MAIN_OTHER:
return a.getSegmentName();
case ANONYMOUS:
if ((options & DISPLAY_EXACT) == 0) {
return "<anonymous>";
}
return null;
default:
return null;
}
}
APPEND_SUB : while (a != null) {
String name;
switch (a.getType()) {
case MAIN_DEFAULT:
case MAIN_CLASS:
case SUB_NAMEDPART:
if (((options & DISPLAY_EXACT) != 0) && a instanceof IndexElementName) {
sb.append("[[");
sb.append(((IndexElementName) a).getIndex());
sb.append("L]]");
}
else {
sb.append('$');
name = a.getSegmentName();
if (name != null) {
appendSymbol(sb, name);
}
}
a = a.getNextSegment();
continue APPEND_SUB;
case SUB_NAMEDSLOT:
sb.append('@');
name = a.getSegmentName();
if (name != null) {
appendSymbol(sb, name);
}
a = a.getNextSegment();
continue APPEND_SUB;
case SUB_INDEXED_S:
if (((options & DISPLAY_EXACT) != 0)) {
return null;
}
sb.append("[…]"); //$NON-NLS-1$
break APPEND_SUB;
case SUB_INDEXED_D:
if (a instanceof DefaultImpl) {
sb.append("[["); //$NON-NLS-1$
sb.append(a.getSegmentName());
sb.append("]]"); //$NON-NLS-1$
a = a.getNextSegment();
continue APPEND_SUB;
}
else if ((options & DISPLAY_EXACT) == 0) {
sb.append("[[…]]"); //$NON-NLS-1$
a = a.getNextSegment();
continue APPEND_SUB;
}
else {
return null;
}
default:
if (((options & DISPLAY_EXACT) == 0)) {
sb.append(" …"); //$NON-NLS-1$
break APPEND_SUB;
}
return null;
}
}
return sb.toString();
}
|
diff --git a/guma/simulator/AbstractSimulator.java b/guma/simulator/AbstractSimulator.java
index 0244553..692651f 100644
--- a/guma/simulator/AbstractSimulator.java
+++ b/guma/simulator/AbstractSimulator.java
@@ -1,407 +1,407 @@
/**
*GUMA a simple math game for elementary school students
* Copyright (C) 2012-2013 Dimitrios Desyllas (pc_magas)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*Contact with me by main at thes address: [email protected]
*/
package guma.simulator;
import java.util.*;
import guma.arithmetic.Praxis;
import guma.simulator.*;
public abstract class AbstractSimulator
{
/**
*The first number with seperated Digits that we will simulate the arithmetic operation
*/
protected byte telestis1[]=null;
/**
*The second number with seperated Digits that we will simulate the arithmetic operation
*/
protected byte telestis2[]=null;
/**
*Arraylist that we will keep the carry
*/
protected byte kratoumeno=0;
/**
*Array that will keep the final result
*/
protected byte[] result=null;
/**
*Flag that positions in what digit we will apply the arithmetic operation
*/
protected int telestis1Index;
/**
*Flag that positions in what digit we will apply the arithmetic operation
*/
protected int telestis2Index;
/**
*Flag that positions in what digit we will apply the arithmetic operation
*/
protected int resultIndex;
/**
*Stores temporaly the result
*/
protected int temp=0;
/**
*Show a messages to be displayed during the simulation
*/
protected String message="";
/**
*Variable that tells what type of operation simulates
*/
protected char type;
/**
*Method that seperates the digits from a Number
*/
public static byte[] seperateDigits(int number)
{
byte[] intermediate=new byte[String.valueOf(number).length()];
for(int i=0;i<intermediate.length;i++)
{
intermediate[intermediate.length-1-i]=(byte)(number%10);
number/=10;
}
return intermediate;
}
/**
*Method that merges a number with seperated digits
*@param digits: Number with seperated ditits
*/
public static int mergeDigits(byte[] digits)
{
int merged=0;
for(int i=0;i<digits.length;i++)
{
int pow=digits.length-1-i;
merged+=digits[i]*(long)Math.pow(10,pow);
}
return merged;
}
/**
*Constructor Method
*@param telestis1: the first operator of the number that we will simulate the first operation
*@param telestis2: the second operator of the number that we will simulate the first operation
*/
public AbstractSimulator(int telestis1, int telestis2)
{
this.telestis1= AbstractSimulator.seperateDigits(telestis1);
this.telestis2= AbstractSimulator.seperateDigits(telestis2);
telestis1Index=this.telestis1.length-1;
telestis2Index=this.telestis2.length-1;
temp=0;
}
/**
*Counts how many zeros has on the end a number with seperated digits.
*If parameter num is null then it returns -1
*@param num: number with seperated digits
*/
public static int zeroEndCount(byte[] num)
{
int zeros=0;
try
{
for(int i=num.length-1;i>=0;i--)
{
if(num[i]==0)
{
zeros++;
}
else
{
break;
}
}
}
catch(NullPointerException n)
{
zeros=-1;
}
return zeros;
}
/**
*Returns the carry
*/
public int getCarry()
{
return kratoumeno;
}
/**
*Returns the message
*/
public String getMessage()
{
return message;
}
/**
*Returns the position of the result digit
*/
public int getResDigit()
{
return resultIndex;
}
/**
*Returns the position of the digit of first Operator
*/
public int getTelests1Digit()
{
return telestis1Index;
}
/**
*Returns the position of the digit of second Operator
*/
public int getTelests2Digit()
{
return telestis2Index;
}
/**
*A way to return the operatos as String with distinct space (tab) between tht digits
*@param num: the number with seperated Digits
*/
public static String getTelestis(byte[] num)
{
return getTelestis(num,"\t","");
}
/**
*A way to return the operatos as String with distinct space between tht digits
*@param num: the number with seperated Digits
*@param front: The sting you want to be be th the front of a digit
*@param back: The string you want to be at the back of a digit
*/
public static String getTelestis(byte[] num,String front, String back)
{
return getTelestis(num,front,back,0,front,back);
}
/**
*A way to return the operatos as String with distinct space between tht digits
*@param num: the number with seperated Digits
*@param front: The sting you want to be on the front of a digit
*@param back: The string you want to be at the back of a digit
*@param pos: select a specified position that will have seperate texnt on the front and back
*@param posFront: The sting you want to be on the front of a digit at specified positions, given by pos paramenter
*@param posBack: The sting you want to be at the back of a digit at specified positions, given by pos parameter
*/
public static String getTelestis(byte[] num,String front, String back, int pos, String posFront, String posBack)
{
String s="";
for(int i=0;i<num.length;i++)
{
if(i==pos)
{
s+=posFront+num[i]+posBack;
}
else
{
s+=front+num[i]+back;
}
}
return s;
}
/**
*Returns the first operator
*/
public String getTelestis1()
{
return getTelestis(telestis1);
}
/**
*Returns the first operator
*@param front: The sting you want to be be th the front of a digit
*@param back: The string you want to be at the back of a digit
*/
public String getTelestis1(String front, String back)
{
return getTelestis(telestis1,front,back);
}
/**
*Returns the first operator
*@param front: The sting you want to be be th the front of a digit
*@param back: The string you want to be at the back of a digit
*@param pos: select a specified position that will have seperate texnt on the front and back
*@param posFront: The sting you want to be on the front of a digit at specified positions, given by pos paramenter
*@param posBack: The sting you want to be at the back of a digit at specified positions, given by pos parameter
*/
public String getTelestis1(String front, String back, String posFront, String posBack)
{
return getTelestis(telestis1,front,back,telestis1Index, posFront, posBack);
}
/**
*Returns the second operator
*/
public String getTelestis2()
{
return getTelestis2("","");
}
/**
*Returns the second operator
*/
public String getTelestis2(String front, String back)
{
return getTelestis2(front,back,front,back);
}
/**
*Returns the first operator
*@param front: The sting you want to be be th the front of a digit
*@param back: The string you want to be at the back of a digit
*@param pos: select a specified position that will have seperate texnt on the front and back
*@param posFront: The sting you want to be on the front of a digit at specified positions, given by pos paramenter
*@param posBack: The sting you want to be at the back of a digit at specified positions, given by pos parameter
*/
public String getTelestis2(String front, String back, String posFront, String posBack)
{
if(telestis2!=null)
{
return getTelestis(telestis2,front,back,telestis2Index, posFront, posBack);
}
else
{
return front+"0"+back;
}
}
/**
*Returns as String the result
*/
public String getResult()
{
return getResult("","");
}
/**
*Returns as String the result
*@param front: The sting you want to be be th the front of a digit
*@param back: The string you want to be at the back of a digit
*/
public String getResult(String front, String back)
{
return getResult(front,back,front,back);
}
/**
*Returns the first operator
*@param front: The sting you want to be be th the front of a digit
*@param back: The string you want to be at the back of a digit
*@param pos: select a specified position that will have seperate texnt on the front and back
*@param posFront: The sting you want to be on the front of a digit at specified positions, given by pos paramenter
*@param posBack: The sting you want to be at the back of a digit at specified positions, given by pos parameter
*/
public String getResult(String front, String back, String posFront, String posBack)
{
if(result!=null)
{
return getTelestis(result,front,back,resultIndex, posFront, posBack);
}
else
{
return front+"0"+back;
}
}
/**
*Creates a Simulator Bazed on the praxisType is given on Praxis Type
*@param telestis1: the first operator (depending in the operation) of the operation we want to simulate
*@param telesits2: the second operator (depending in the operation) of the operation we want to simulate
*@param praxisType: The type of Operation that tells what kind of simulator we want
*/
public static AbstractSimulator makeSimulator(int telestis1, int telestis2,char praxisType)
{
AbstractSimulator a=null;
switch(praxisType)
{
case Praxis.ADDING: a= new AddingSimulator(telestis1,telestis2);
break;
case Praxis.SUBSTRACTION:
if(telestis1>telestis2)
{
a= new SubstractionSimulator(telestis1,telestis2);
}
else
{
- a= new SubstractionSimulator(telestis1,telestis2);
+ a= new SubstractionSimulator(telestis2,telestis1);
}
break;
case Praxis.DIVISION:
if(telestis1>telestis2)
{
a= new DivisionSimulator(telestis1,telestis2);
}
else
{
- a= new DivisionSimulator(telestis1,telestis2);
+ a= new DivisionSimulator(telestis2,telestis1);
}
break;
case Praxis.MULTIPLICATION: a= new MultiplicationSimulator(telestis1,telestis2,false);
break;
default: a=null;
}
return a;
}
/**
*This Method does the next step of an arithmetic praxis Simulation
*Returns true if it has next step to do
*/
public abstract boolean next();
/**
*This method shows tas String the operation of simulator
*@param: html: Shows if the utput will be html or not
*/
public abstract String toString(boolean html);
}
| false | true | public static AbstractSimulator makeSimulator(int telestis1, int telestis2,char praxisType)
{
AbstractSimulator a=null;
switch(praxisType)
{
case Praxis.ADDING: a= new AddingSimulator(telestis1,telestis2);
break;
case Praxis.SUBSTRACTION:
if(telestis1>telestis2)
{
a= new SubstractionSimulator(telestis1,telestis2);
}
else
{
a= new SubstractionSimulator(telestis1,telestis2);
}
break;
case Praxis.DIVISION:
if(telestis1>telestis2)
{
a= new DivisionSimulator(telestis1,telestis2);
}
else
{
a= new DivisionSimulator(telestis1,telestis2);
}
break;
case Praxis.MULTIPLICATION: a= new MultiplicationSimulator(telestis1,telestis2,false);
break;
default: a=null;
}
return a;
}
| public static AbstractSimulator makeSimulator(int telestis1, int telestis2,char praxisType)
{
AbstractSimulator a=null;
switch(praxisType)
{
case Praxis.ADDING: a= new AddingSimulator(telestis1,telestis2);
break;
case Praxis.SUBSTRACTION:
if(telestis1>telestis2)
{
a= new SubstractionSimulator(telestis1,telestis2);
}
else
{
a= new SubstractionSimulator(telestis2,telestis1);
}
break;
case Praxis.DIVISION:
if(telestis1>telestis2)
{
a= new DivisionSimulator(telestis1,telestis2);
}
else
{
a= new DivisionSimulator(telestis2,telestis1);
}
break;
case Praxis.MULTIPLICATION: a= new MultiplicationSimulator(telestis1,telestis2,false);
break;
default: a=null;
}
return a;
}
|
diff --git a/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderWat.java b/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderWat.java
index a43dd2d..853e1f6 100644
--- a/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderWat.java
+++ b/src/main/java/net/nexisonline/spade/chunkproviders/ChunkProviderWat.java
@@ -1,178 +1,178 @@
/**
* Pony's Handy Dandy Rape Generator
*
* INSERT BSD HERE
*/
package net.nexisonline.spade.chunkproviders;
import java.util.logging.Logger;
import libnoiseforjava.module.ModuleBase;
import libnoiseforjava.module.Multiply;
import libnoiseforjava.module.Perlin;
import libnoiseforjava.module.RidgedMulti;
import libnoiseforjava.module.Turbulence;
import org.bukkit.ChunkProvider;
import org.bukkit.World;
import org.bukkit.block.Biome;
/**
* @author PrettyPonyyy
*
*/
public class ChunkProviderWat extends ChunkProvider
{
private ModuleBase m_perlinGenerator1;
private ModuleBase m_perlinGenerator2;
private Multiply m_multiplier;
private Turbulence m_turbulence;
/*
* (non-Javadoc)
*
* @see org.bukkit.ChunkProvider#onLoad(org.bukkit.World, long)
*/
@Override
public void onLoad(World world, long seed)
{
this.setHasCustomTerrain(true);
try
{
m_perlinGenerator1 = new RidgedMulti(); //new Perlin();
m_perlinGenerator2 = new RidgedMulti(); //new Perlin();
m_multiplier = new Multiply(m_perlinGenerator1, m_perlinGenerator2);
m_turbulence = new Turbulence(m_perlinGenerator1);
((RidgedMulti)m_perlinGenerator1).setSeed((int)(seed*1024));
((RidgedMulti)m_perlinGenerator1).setOctaveCount(1);
((RidgedMulti)m_perlinGenerator1).setFrequency(1f);//1.0f);
((RidgedMulti)m_perlinGenerator1).setLacunarity(0.25f);
((RidgedMulti)m_perlinGenerator2).setSeed((int)(seed));
((RidgedMulti)m_perlinGenerator2).setOctaveCount(1);
m_turbulence.setSeed(135);
m_turbulence.setPower(0.125);
}
catch (Exception e)
{
}
}
private static double lerp(double a, double b, double f)
{
return (a + (b - a) * f);
}
/*
* (non-Javadoc)
*
* @see org.bukkit.ChunkProvider#generateChunk(int, int, byte[],
* org.bukkit.block.Biome[], double[])
*/
@Override
public void generateChunk(World world, int X, int Z, byte[] abyte, Biome[] biomes, double[] temperature)
{
double density[][][] = new double[16][128][16];
for (int x = 0; x < 16; x += 3)
{
for (int y = 0; y < 128; y += 3)
{
for (int z = 0; z < 16; z += 3)
{
double posX = x + (X*16);
double posY = y - 64;
double posZ = z + (Z*16);
- final double warp = 0.04;
+ final double warp = 0.004;
double warpMod = m_perlinGenerator2.getValue(posX * warp, posY * warp, posZ * warp) * 5;
double warpPosX = posX * warpMod;
double warpPosY = posY * warpMod;
double warpPosZ = posZ * warpMod;
double mod = m_perlinGenerator1.getValue(warpPosX * 0.0005, warpPosY * 0.0005, warpPosZ * 0.0005);
density[x][y][z] = -(y - 64);
density[x][y][z] += mod * 100;
}
}
}
for (int x = 0; x < 16; x += 3)
{
for (int y = 0; y < 128; y += 3)
{
for (int z = 0; z < 16; z += 3)
{
if (y != 126)
{
density[x][y+1][z] = lerp(density[x][y][z], density[x][y+3][z], 0.2);
density[x][y+2][z] = lerp(density[x][y][z], density[x][y+3][z], 0.8);
}
}
}
}
for (int x = 0; x < 16; x += 3)
{
for (int y = 0; y < 128; y++)
{
for (int z = 0; z < 16; z += 3)
{
if (x == 0 && z > 0)
{
density[x][y][z-1] = lerp(density[x][y][z], density[x][y][z-3], 0.25);
density[x][y][z-2] = lerp(density[x][y][z], density[x][y][z-3], 0.85);
}
else if (x > 0 && z > 0)
{
density[x-1][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.25);
density[x-2][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.85);
density[x][y][z-1] = lerp(density[x][y][z], density[x][y][z-3], 0.25);
density[x-1][y][z-1] = lerp(density[x][y][z], density[x-3][y][z-3], 0.25);
density[x-2][y][z-1] = lerp(density[x][y][z], density[x-3][y][z-3], 0.85);
density[x][y][z-2] = lerp(density[x][y][z], density[x][y][z-3], 0.25);
density[x-1][y][z-2] = lerp(density[x][y][z], density[x-3][y][z-3], 0.85);
density[x-2][y][z-2] = lerp(density[x][y][z], density[x-3][y][z-3], 0.85);
}
else if (x > 0 && z == 0)
{
density[x-1][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.25);
density[x-2][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.85);
}
}
}
}
for (int x = 0; x < 16; x++)
{
for (int y = 0; y < 128; y++)
{
for (int z = 0; z < 16; z++)
{
if (density[x][y][z] > 0)
{
abyte[getBlockIndex(x,y,z)] = 1;
}
else
{
abyte[getBlockIndex(x,y,z)] = 0;
}
// Origin point + sand to prevent 5000 years of loading.
if ((x == 0) && (z == 0) && (X == x) && (Z == z) && (y <= 63)) {
abyte[getBlockIndex(x,y,z)] = (byte) ((y == 125) ? 12 : 7);
}
if(y==1)
abyte[getBlockIndex(x,y,z)]=7;
}
}
}
Logger.getLogger("Minecraft").info(String.format("[wat] Chunk (%d,%d)",X,Z));
}
}
| true | true | public void generateChunk(World world, int X, int Z, byte[] abyte, Biome[] biomes, double[] temperature)
{
double density[][][] = new double[16][128][16];
for (int x = 0; x < 16; x += 3)
{
for (int y = 0; y < 128; y += 3)
{
for (int z = 0; z < 16; z += 3)
{
double posX = x + (X*16);
double posY = y - 64;
double posZ = z + (Z*16);
final double warp = 0.04;
double warpMod = m_perlinGenerator2.getValue(posX * warp, posY * warp, posZ * warp) * 5;
double warpPosX = posX * warpMod;
double warpPosY = posY * warpMod;
double warpPosZ = posZ * warpMod;
double mod = m_perlinGenerator1.getValue(warpPosX * 0.0005, warpPosY * 0.0005, warpPosZ * 0.0005);
density[x][y][z] = -(y - 64);
density[x][y][z] += mod * 100;
}
}
}
for (int x = 0; x < 16; x += 3)
{
for (int y = 0; y < 128; y += 3)
{
for (int z = 0; z < 16; z += 3)
{
if (y != 126)
{
density[x][y+1][z] = lerp(density[x][y][z], density[x][y+3][z], 0.2);
density[x][y+2][z] = lerp(density[x][y][z], density[x][y+3][z], 0.8);
}
}
}
}
for (int x = 0; x < 16; x += 3)
{
for (int y = 0; y < 128; y++)
{
for (int z = 0; z < 16; z += 3)
{
if (x == 0 && z > 0)
{
density[x][y][z-1] = lerp(density[x][y][z], density[x][y][z-3], 0.25);
density[x][y][z-2] = lerp(density[x][y][z], density[x][y][z-3], 0.85);
}
else if (x > 0 && z > 0)
{
density[x-1][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.25);
density[x-2][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.85);
density[x][y][z-1] = lerp(density[x][y][z], density[x][y][z-3], 0.25);
density[x-1][y][z-1] = lerp(density[x][y][z], density[x-3][y][z-3], 0.25);
density[x-2][y][z-1] = lerp(density[x][y][z], density[x-3][y][z-3], 0.85);
density[x][y][z-2] = lerp(density[x][y][z], density[x][y][z-3], 0.25);
density[x-1][y][z-2] = lerp(density[x][y][z], density[x-3][y][z-3], 0.85);
density[x-2][y][z-2] = lerp(density[x][y][z], density[x-3][y][z-3], 0.85);
}
else if (x > 0 && z == 0)
{
density[x-1][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.25);
density[x-2][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.85);
}
}
}
}
for (int x = 0; x < 16; x++)
{
for (int y = 0; y < 128; y++)
{
for (int z = 0; z < 16; z++)
{
if (density[x][y][z] > 0)
{
abyte[getBlockIndex(x,y,z)] = 1;
}
else
{
abyte[getBlockIndex(x,y,z)] = 0;
}
// Origin point + sand to prevent 5000 years of loading.
if ((x == 0) && (z == 0) && (X == x) && (Z == z) && (y <= 63)) {
abyte[getBlockIndex(x,y,z)] = (byte) ((y == 125) ? 12 : 7);
}
if(y==1)
abyte[getBlockIndex(x,y,z)]=7;
}
}
}
Logger.getLogger("Minecraft").info(String.format("[wat] Chunk (%d,%d)",X,Z));
}
| public void generateChunk(World world, int X, int Z, byte[] abyte, Biome[] biomes, double[] temperature)
{
double density[][][] = new double[16][128][16];
for (int x = 0; x < 16; x += 3)
{
for (int y = 0; y < 128; y += 3)
{
for (int z = 0; z < 16; z += 3)
{
double posX = x + (X*16);
double posY = y - 64;
double posZ = z + (Z*16);
final double warp = 0.004;
double warpMod = m_perlinGenerator2.getValue(posX * warp, posY * warp, posZ * warp) * 5;
double warpPosX = posX * warpMod;
double warpPosY = posY * warpMod;
double warpPosZ = posZ * warpMod;
double mod = m_perlinGenerator1.getValue(warpPosX * 0.0005, warpPosY * 0.0005, warpPosZ * 0.0005);
density[x][y][z] = -(y - 64);
density[x][y][z] += mod * 100;
}
}
}
for (int x = 0; x < 16; x += 3)
{
for (int y = 0; y < 128; y += 3)
{
for (int z = 0; z < 16; z += 3)
{
if (y != 126)
{
density[x][y+1][z] = lerp(density[x][y][z], density[x][y+3][z], 0.2);
density[x][y+2][z] = lerp(density[x][y][z], density[x][y+3][z], 0.8);
}
}
}
}
for (int x = 0; x < 16; x += 3)
{
for (int y = 0; y < 128; y++)
{
for (int z = 0; z < 16; z += 3)
{
if (x == 0 && z > 0)
{
density[x][y][z-1] = lerp(density[x][y][z], density[x][y][z-3], 0.25);
density[x][y][z-2] = lerp(density[x][y][z], density[x][y][z-3], 0.85);
}
else if (x > 0 && z > 0)
{
density[x-1][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.25);
density[x-2][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.85);
density[x][y][z-1] = lerp(density[x][y][z], density[x][y][z-3], 0.25);
density[x-1][y][z-1] = lerp(density[x][y][z], density[x-3][y][z-3], 0.25);
density[x-2][y][z-1] = lerp(density[x][y][z], density[x-3][y][z-3], 0.85);
density[x][y][z-2] = lerp(density[x][y][z], density[x][y][z-3], 0.25);
density[x-1][y][z-2] = lerp(density[x][y][z], density[x-3][y][z-3], 0.85);
density[x-2][y][z-2] = lerp(density[x][y][z], density[x-3][y][z-3], 0.85);
}
else if (x > 0 && z == 0)
{
density[x-1][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.25);
density[x-2][y][z] = lerp(density[x][y][z], density[x-3][y][z], 0.85);
}
}
}
}
for (int x = 0; x < 16; x++)
{
for (int y = 0; y < 128; y++)
{
for (int z = 0; z < 16; z++)
{
if (density[x][y][z] > 0)
{
abyte[getBlockIndex(x,y,z)] = 1;
}
else
{
abyte[getBlockIndex(x,y,z)] = 0;
}
// Origin point + sand to prevent 5000 years of loading.
if ((x == 0) && (z == 0) && (X == x) && (Z == z) && (y <= 63)) {
abyte[getBlockIndex(x,y,z)] = (byte) ((y == 125) ? 12 : 7);
}
if(y==1)
abyte[getBlockIndex(x,y,z)]=7;
}
}
}
Logger.getLogger("Minecraft").info(String.format("[wat] Chunk (%d,%d)",X,Z));
}
|
diff --git a/src/org/geometerplus/android/fbreader/api/ApiImplementation.java b/src/org/geometerplus/android/fbreader/api/ApiImplementation.java
index 1f013adb..caf6b7b9 100644
--- a/src/org/geometerplus/android/fbreader/api/ApiImplementation.java
+++ b/src/org/geometerplus/android/fbreader/api/ApiImplementation.java
@@ -1,104 +1,104 @@
/*
* Copyright (C) 2009-2011 Geometer Plus <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.android.fbreader.api;
import org.geometerplus.zlibrary.text.view.*;
import org.geometerplus.fbreader.fbreader.FBReaderApp;
public class ApiImplementation extends ApiInterface.Stub implements ApiMethods {
private final FBReaderApp myReader = (FBReaderApp)FBReaderApp.Instance();
@Override
public ApiObject request(int method, ApiObject[] parameters) {
try {
switch (method) {
case GET_BOOK_LANGUAGE:
return ApiObject.envelope(getBookLanguage());
case GET_PARAGRAPHS_NUMBER:
return ApiObject.envelope(getParagraphsNumber());
case GET_ELEMENTS_NUMBER:
return ApiObject.envelope(getElementsNumber(
((ApiObject.Integer)parameters[0]).Value
));
case GET_PARAGRAPH_TEXT:
return ApiObject.envelope(getParagraphText(
((ApiObject.Integer)parameters[0]).Value
));
case GET_PAGE_START:
return getTextPosition(myReader.getTextView().getStartCursor());
case GET_PAGE_END:
return getTextPosition(myReader.getTextView().getEndCursor());
case SET_PAGE_START:
setPageStart(
(TextPosition)parameters[0]
);
return ApiObject.Void.Instance;
default:
return new ApiObject.Error("Unsupported method code: " + method);
}
} catch (Throwable e) {
- return new ApiObject.Error("Exception in method " + method + ": " + e.getMessage());
+ return new ApiObject.Error("Exception in method " + method + ": " + e);
}
}
private String getBookLanguage() {
return myReader.Model.Book.getLanguage();
}
private TextPosition getTextPosition(ZLTextWordCursor cursor) {
return new TextPosition(
cursor.getParagraphIndex(),
cursor.getElementIndex(),
cursor.getCharIndex()
);
}
private void setPageStart(TextPosition position) {
myReader.getTextView().gotoPosition(position.ParagraphIndex, position.ElementIndex, position.CharIndex);
myReader.getViewWidget().repaint();
}
private int getParagraphsNumber() {
return myReader.Model.BookTextModel.getParagraphsNumber();
}
private int getElementsNumber(int paragraphIndex) {
final ZLTextWordCursor cursor = new ZLTextWordCursor(myReader.getTextView().getStartCursor());
cursor.moveToParagraph(paragraphIndex);
cursor.moveToParagraphEnd();
return cursor.getElementIndex();
}
private String getParagraphText(int paragraphIndex) {
final StringBuffer sb = new StringBuffer();
final ZLTextWordCursor cursor = new ZLTextWordCursor(myReader.getTextView().getStartCursor());
cursor.moveToParagraph(paragraphIndex);
cursor.moveToParagraphStart();
while (!cursor.isEndOfParagraph()) {
ZLTextElement element = cursor.getElement();
if (element instanceof ZLTextWord) {
sb.append(element.toString() + " ");
}
cursor.nextWord();
}
return sb.toString();
}
}
| true | true | public ApiObject request(int method, ApiObject[] parameters) {
try {
switch (method) {
case GET_BOOK_LANGUAGE:
return ApiObject.envelope(getBookLanguage());
case GET_PARAGRAPHS_NUMBER:
return ApiObject.envelope(getParagraphsNumber());
case GET_ELEMENTS_NUMBER:
return ApiObject.envelope(getElementsNumber(
((ApiObject.Integer)parameters[0]).Value
));
case GET_PARAGRAPH_TEXT:
return ApiObject.envelope(getParagraphText(
((ApiObject.Integer)parameters[0]).Value
));
case GET_PAGE_START:
return getTextPosition(myReader.getTextView().getStartCursor());
case GET_PAGE_END:
return getTextPosition(myReader.getTextView().getEndCursor());
case SET_PAGE_START:
setPageStart(
(TextPosition)parameters[0]
);
return ApiObject.Void.Instance;
default:
return new ApiObject.Error("Unsupported method code: " + method);
}
} catch (Throwable e) {
return new ApiObject.Error("Exception in method " + method + ": " + e.getMessage());
}
}
| public ApiObject request(int method, ApiObject[] parameters) {
try {
switch (method) {
case GET_BOOK_LANGUAGE:
return ApiObject.envelope(getBookLanguage());
case GET_PARAGRAPHS_NUMBER:
return ApiObject.envelope(getParagraphsNumber());
case GET_ELEMENTS_NUMBER:
return ApiObject.envelope(getElementsNumber(
((ApiObject.Integer)parameters[0]).Value
));
case GET_PARAGRAPH_TEXT:
return ApiObject.envelope(getParagraphText(
((ApiObject.Integer)parameters[0]).Value
));
case GET_PAGE_START:
return getTextPosition(myReader.getTextView().getStartCursor());
case GET_PAGE_END:
return getTextPosition(myReader.getTextView().getEndCursor());
case SET_PAGE_START:
setPageStart(
(TextPosition)parameters[0]
);
return ApiObject.Void.Instance;
default:
return new ApiObject.Error("Unsupported method code: " + method);
}
} catch (Throwable e) {
return new ApiObject.Error("Exception in method " + method + ": " + e);
}
}
|
diff --git a/src/main/java/me/iffa/bananaspace/api/SpaceWorldHandler.java b/src/main/java/me/iffa/bananaspace/api/SpaceWorldHandler.java
index be140f8..6f5da0e 100644
--- a/src/main/java/me/iffa/bananaspace/api/SpaceWorldHandler.java
+++ b/src/main/java/me/iffa/bananaspace/api/SpaceWorldHandler.java
@@ -1,282 +1,282 @@
// Package Declaration
package me.iffa.bananaspace.api;
// Java Imports
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
// BananaSpace Imports
import me.iffa.bananaspace.BananaSpace;
import me.iffa.bananaspace.wgen.planets.PlanetsChunkGenerator;
import me.iffa.bananaspace.runnables.SpaceRunnable;
import me.iffa.bananaspace.wgen.SpaceChunkGenerator;
import me.iffa.bananaspace.config.SpaceConfig;
import me.iffa.bananaspace.config.SpacePlanetConfig;
// Bukkit Imports
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
/**
* Class that handles space worlds.
*
* @author iffa
*/
public class SpaceWorldHandler {
// Variables
public static List<World> spaceWorlds = new ArrayList<World>();
private BananaSpace plugin;
private Map<World, Integer> forcenightId = new HashMap<World, Integer>();
private boolean startupLoaded;
private boolean usingMV;
/**
* Constructor of SpaceWorldHandler.
*
* @param plugin BananaSpace
*/
public SpaceWorldHandler(BananaSpace plugin) {
this.plugin = plugin;
if (plugin.getServer().getPluginManager().getPlugin("Multiverse-Core") != null) {
usingMV = true;
}
}
/**
* Loads the space worlds into <code>spaceWorlds</code> and creates them if Multiverse is not there.
*/
public void loadSpaceWorlds() {
Set<String> worlds;
try {
worlds = SpaceConfig.getConfig().getConfigurationSection("worlds").getKeys(false);
} catch (NullPointerException ex) {
worlds = null;
}
if (worlds == null) {
SpaceMessageHandler.print(Level.SEVERE, "Your configuration file has no worlds! Cancelling world generation process.");
startupLoaded = false;
return;
}
for (String world : worlds) {
if (plugin.getServer().getWorld(world) == null) {
if (!usingMV) {
World.Environment env;
if (SpaceConfig.getConfig().getBoolean("worlds." + world + ".nethermode", false)) {
env = World.Environment.NETHER;
} else {
env = World.Environment.NORMAL;
}
// Choosing which chunk generator to use
if (!SpaceConfig.getConfig().getBoolean("worlds." + world + ".generation.generateplanets", true)) {
SpaceMessageHandler.debugPrint(Level.INFO, "Creating startup world '" + world + "' with normal generator.");
- WorldCreator.name(world).environment(env).generator(new SpaceChunkGenerator());
+ plugin.getServer().createWorld(WorldCreator.name(world).environment(env).generator(new SpaceChunkGenerator()));
} else {
SpaceMessageHandler.debugPrint(Level.INFO, "Creating startup world '" + world + "' with planet generator.");
- WorldCreator.name(world).environment(env).generator(new PlanetsChunkGenerator(SpacePlanetConfig.getConfig(), plugin));
+ plugin.getServer().createWorld(WorldCreator.name(world).environment(env).generator(new PlanetsChunkGenerator(SpacePlanetConfig.getConfig(), plugin)));
}
}
}
if (plugin.getServer().getWorld(world) != null) {
spaceWorlds.add(Bukkit.getServer().getWorld(world));
}
startupLoaded = true;
}
}
/**
* Checks if any worlds were created/loaded on plugin startup.
*
* @return true if any spaceworld was loaded from the config
*/
public boolean getStartupLoaded() {
if (startupLoaded) {
return true;
}
return false;
}
/**
* Checks if MultiVerse is being used for world generation.
*
* @return true if MultiVerse is used
*/
public boolean getUsingMV() {
if (usingMV) {
return true;
}
return false;
}
/**
* Creates a spaceworld with the default settings and the given name. I suggest you to do the if worldname exists-check yourself aswell, <b>if you do not want BananaSpace to nag about it.</b>. I suggest you also turn logging on so users know an error was your fault, not mine.
*
* @param plugin Your plugin
* @param worldname Name for new spaceworld
* @param log True if the console should be informed that an external plugin created a spaceworld.
*/
public void createSpaceWorld(Plugin plugin, String worldname, boolean log) {
if (plugin.getServer().getWorld(worldname) != null) {
SpaceMessageHandler.print(Level.WARNING, "Plugin '" + plugin.getDescription().getName() + "' tried to create a new spaceworld with a name that is already a world! Nag to author(s) '" + plugin.getDescription().getAuthors() + "'!");
return;
}
SpaceConfig.getConfig().set("worlds." + worldname + ".generation.generateplanets", true);
SpaceConfig.getConfig().set("worlds." + worldname + ".generation.glowstonechance", 1);
SpaceConfig.getConfig().set("worlds." + worldname + ".generation.asteroidchance", 3);
SpaceConfig.getConfig().set("worlds." + worldname + ".suit.required", false);
SpaceConfig.getConfig().set("worlds." + worldname + ".helmet.required", false);
SpaceConfig.getConfig().set("worlds." + worldname + ".breathingarea.maxroomheight", 5);
SpaceConfig.getConfig().set("worlds." + worldname + ".weather", false);
SpaceConfig.getConfig().set("worlds." + worldname + ".nethermode", false);
SpaceConfig.getConfig().set("worlds." + worldname + ".alwaysnight", true);
SpaceConfig.getConfig().set("worlds." + worldname + ".neutralmobs", true);
SpaceConfig.getConfig().set("worlds." + worldname + ".hostilemobs", false);
try {
SpaceConfig.getConfig().save(SpaceConfig.getConfigFile());
} catch (IOException ex) {
SpaceMessageHandler.print(Level.WARNING, ex.getMessage());
}
if (log) {
SpaceMessageHandler.print(Level.INFO, "Plugin '" + plugin.getDescription().getName() + "' starting to create spaceworld '" + worldname + "'");
}
WorldCreator.name(worldname).environment(World.Environment.NORMAL).generator(new PlanetsChunkGenerator(SpacePlanetConfig.getConfig(), plugin));
World world = plugin.getServer().getWorld(worldname);
spaceWorlds.add(world);
BananaSpace.pailInt.addSpaceList(worldname);
if (log) {
SpaceMessageHandler.print(Level.INFO, "Plugin '" + plugin.getDescription().getName() + "' created spaceworld '" + worldname + "'");
}
}
/**
* Removes a spaceworld with the default settings and the given name. I suggest you to do the if worldname exists-check yourself aswell, <b>if you do not want BananaSpace to nag about it.</b>. I suggest you also turn logging on so users know an error was your fault, not mine.
*
* @param plugin Your plugin
* @param worldname Name of spaceworld
* @param log True if the console should be informed that an external plugin removed a spaceworld.
*/
public void removeSpaceWorld(Plugin plugin, String worldname, boolean log) {
if (plugin.getServer().getWorld(worldname) == null) {
SpaceMessageHandler.print(Level.WARNING, "Plugin '" + plugin.getDescription().getName() + "' tried to remove a spaceworld with a name that doesn't exist! Nag to author(s) '" + plugin.getDescription().getAuthors() + "'!");
return;
}
if (!this.isSpaceWorld(plugin.getServer().getWorld(worldname))) {
SpaceMessageHandler.print(Level.WARNING, "Plugin '" + plugin.getDescription().getName() + "' tried to remove a spaceworld that is not a spaceworld! Nag to author(s) '" + plugin.getDescription().getAuthors() + "'!");
return;
}
spaceWorlds.remove(plugin.getServer().getWorld(worldname));
SpaceConfig.getConfig().set("worlds." + worldname, null);
try {
SpaceConfig.getConfig().save(SpaceConfig.getConfigFile());
} catch (IOException ex) {
SpaceMessageHandler.print(Level.WARNING, ex.getMessage());
}
/*
* Removing a few properties that in most cases WILL be left over because of the Configuration-class.
*/
SpaceConfig.getConfig().set("worlds." + worldname + "generation", null);
SpaceConfig.getConfig().set("worlds" + worldname, null);
try {
SpaceConfig.getConfig().save(SpaceConfig.getConfigFile());
} catch (IOException ex) {
SpaceMessageHandler.print(Level.WARNING, ex.getMessage());
}
plugin.getServer().unloadWorld(worldname, true);
if (log) {
SpaceMessageHandler.print(Level.INFO, "Plugin '" + plugin.getDescription().getName() + "' removed spaceworld '" + worldname + "'");
}
}
/**
* Starts the force night task if required.
*
* @param world World
*/
public void startForceNightTask(World world) {
SpaceRunnable task = new SpaceRunnable(world);
forcenightId.put(world, BananaSpace.scheduler.scheduleSyncRepeatingTask(plugin, task, 60, 8399));
}
/**
* Stops the force night task. No safety checks made, explosions may occur.
*
* @param world World
*/
public void stopForceNightTask(World world) {
BananaSpace.scheduler.cancelTask(forcenightId.get(world));
}
/**
* Gives all the space worlds of the server.
*
* @return all space worlds as a List
*/
public List<World> getSpaceWorlds() {
return spaceWorlds;
}
/**
* Checks if a world is a space world.
*
* @param world World to check
*
* @return true if the world is a space world
*/
public boolean isSpaceWorld(World world) {
if (spaceWorlds.contains(world)) {
return true;
}
return false;
}
/**
* Checks if a player is in a space world.
*
* @param player Player to check
* @param world Space world
*
* @return true if the player is in the specified space world
*/
public boolean isInSpace(Player player, World world) {
return (spaceWorlds.contains(world) && player.getWorld() == world);
}
/**
* Checks if a player is in any space world.
*
* @param player Player
*
* @return true if the player is in a space world
*/
public boolean isInAnySpace(Player player) {
for (World world : spaceWorlds) {
if (player.getWorld() == world) {
return true;
}
}
return false;
}
/**
* Gets the space world a player is in.
*
* @param player Player
*
* @return Null if not in a space world
*/
public World getSpaceWorld(Player player) {
if (getSpaceWorlds().contains(player.getWorld())) {
return getSpaceWorlds().get(getSpaceWorlds().indexOf(player.getWorld()));
}
return null;
}
}
| false | true | public void loadSpaceWorlds() {
Set<String> worlds;
try {
worlds = SpaceConfig.getConfig().getConfigurationSection("worlds").getKeys(false);
} catch (NullPointerException ex) {
worlds = null;
}
if (worlds == null) {
SpaceMessageHandler.print(Level.SEVERE, "Your configuration file has no worlds! Cancelling world generation process.");
startupLoaded = false;
return;
}
for (String world : worlds) {
if (plugin.getServer().getWorld(world) == null) {
if (!usingMV) {
World.Environment env;
if (SpaceConfig.getConfig().getBoolean("worlds." + world + ".nethermode", false)) {
env = World.Environment.NETHER;
} else {
env = World.Environment.NORMAL;
}
// Choosing which chunk generator to use
if (!SpaceConfig.getConfig().getBoolean("worlds." + world + ".generation.generateplanets", true)) {
SpaceMessageHandler.debugPrint(Level.INFO, "Creating startup world '" + world + "' with normal generator.");
WorldCreator.name(world).environment(env).generator(new SpaceChunkGenerator());
} else {
SpaceMessageHandler.debugPrint(Level.INFO, "Creating startup world '" + world + "' with planet generator.");
WorldCreator.name(world).environment(env).generator(new PlanetsChunkGenerator(SpacePlanetConfig.getConfig(), plugin));
}
}
}
if (plugin.getServer().getWorld(world) != null) {
spaceWorlds.add(Bukkit.getServer().getWorld(world));
}
startupLoaded = true;
}
}
| public void loadSpaceWorlds() {
Set<String> worlds;
try {
worlds = SpaceConfig.getConfig().getConfigurationSection("worlds").getKeys(false);
} catch (NullPointerException ex) {
worlds = null;
}
if (worlds == null) {
SpaceMessageHandler.print(Level.SEVERE, "Your configuration file has no worlds! Cancelling world generation process.");
startupLoaded = false;
return;
}
for (String world : worlds) {
if (plugin.getServer().getWorld(world) == null) {
if (!usingMV) {
World.Environment env;
if (SpaceConfig.getConfig().getBoolean("worlds." + world + ".nethermode", false)) {
env = World.Environment.NETHER;
} else {
env = World.Environment.NORMAL;
}
// Choosing which chunk generator to use
if (!SpaceConfig.getConfig().getBoolean("worlds." + world + ".generation.generateplanets", true)) {
SpaceMessageHandler.debugPrint(Level.INFO, "Creating startup world '" + world + "' with normal generator.");
plugin.getServer().createWorld(WorldCreator.name(world).environment(env).generator(new SpaceChunkGenerator()));
} else {
SpaceMessageHandler.debugPrint(Level.INFO, "Creating startup world '" + world + "' with planet generator.");
plugin.getServer().createWorld(WorldCreator.name(world).environment(env).generator(new PlanetsChunkGenerator(SpacePlanetConfig.getConfig(), plugin)));
}
}
}
if (plugin.getServer().getWorld(world) != null) {
spaceWorlds.add(Bukkit.getServer().getWorld(world));
}
startupLoaded = true;
}
}
|
diff --git a/ics-xmpp/src/main/java/com/jakeapp/jake/ics/impl/xmpp/status/XmppStatusService.java b/ics-xmpp/src/main/java/com/jakeapp/jake/ics/impl/xmpp/status/XmppStatusService.java
index 47ca13eb..e5bdae19 100644
--- a/ics-xmpp/src/main/java/com/jakeapp/jake/ics/impl/xmpp/status/XmppStatusService.java
+++ b/ics-xmpp/src/main/java/com/jakeapp/jake/ics/impl/xmpp/status/XmppStatusService.java
@@ -1,217 +1,217 @@
package com.jakeapp.jake.ics.impl.xmpp.status;
import com.jakeapp.jake.ics.UserId;
import com.jakeapp.jake.ics.exceptions.*;
import com.jakeapp.jake.ics.impl.xmpp.XmppConnectionData;
import com.jakeapp.jake.ics.impl.xmpp.XmppUserId;
import com.jakeapp.jake.ics.impl.xmpp.helper.RosterPresenceChangeListener;
import com.jakeapp.jake.ics.impl.xmpp.helper.XmppCommons;
import com.jakeapp.jake.ics.status.ILoginStateListener;
import com.jakeapp.jake.ics.status.IStatusService;
import org.apache.log4j.Logger;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
public class XmppStatusService implements IStatusService {
private static final Logger log = Logger.getLogger(XmppStatusService.class);
private XmppConnectionData con;
private List<ILoginStateListener> lsll = new LinkedList<ILoginStateListener>();
public XmppStatusService(XmppConnectionData connection) {
this.con = connection;
}
private void addDiscoveryFeature() {
// Obtain the ServiceDiscoveryManager associated with my XMPPConnection
ServiceDiscoveryManager discoManager = ServiceDiscoveryManager
.getInstanceFor(this.con.getConnection());
// Register that a new feature is supported by this XMPP entity
discoManager.addFeature(this.con.getNamespace());
}
@Override
public String getFirstname(UserId userid) throws NoSuchUseridException,
OtherUserOfflineException {
// TODO replace with real implementation (VCard)
XmppUserId xid = new XmppUserId(userid);
if (!xid.isOfCorrectUseridFormat())
throw new NoSuchUseridException();
if (!xid.getUsername().contains(".")) {
return "";
}
return xid.getUsername().substring(0, xid.getUsername().indexOf("."));
}
@Override
public String getLastname(UserId userid) throws NoSuchUseridException,
OtherUserOfflineException {
// TODO replace with real implementation (VCard)
XmppUserId xid = new XmppUserId(userid);
if (!xid.isOfCorrectUseridFormat())
throw new NoSuchUseridException();
if (!xid.getUsername().contains(".")) {
return "";
}
return xid.getUsername().substring(
xid.getUsername().indexOf(".") + 1);
}
@Override
public UserId getUserId(String userid) {
UserId ui = new XmppUserId(userid);
if (ui.isOfCorrectUseridFormat())
return ui;
else
return null;
}
@Override
public XmppUserId getUserid() throws NotLoggedInException {
if (!isLoggedIn())
throw new NotLoggedInException();
return this.con.getUserId();
}
@Override
public Boolean isLoggedIn() {
return XmppCommons.isLoggedIn(this.con.getConnection());
}
@Override
public Boolean isLoggedIn(UserId userid) throws NoSuchUseridException,
NetworkException, NotLoggedInException, TimeoutException {
if (!new XmppUserId(userid).isOfCorrectUseridFormat())
throw new NoSuchUseridException();
if (XmppUserId.isSameUser(getUserid(), userid))
return isLoggedIn();
if (!isLoggedIn())
throw new NotLoggedInException();
if (getRoster().getEntry(userid.toString()) != null) {
log.debug("Type for " + userid + ": "
+ getRoster().getEntry(userid.toString()).getType());
log.debug("Status for " + userid + ": "
+ getRoster().getEntry(userid.toString()).getStatus());
}
Presence p = getRoster().getPresence(userid.toString());
log.debug("Presence for " + userid + ": " + p);
if (p.isAvailable())
return true;
else
return false;
}
private Roster getRoster() throws NotLoggedInException {
if (!this.con.getService().getStatusService().isLoggedIn())
throw new NotLoggedInException();
return this.con.getConnection().getRoster();
}
@Override
public Boolean login(UserId userid, String pw) throws NetworkException,
TimeoutException {
XmppUserId xuid = new XmppUserId(userid);
if (!xuid.isOfCorrectUseridFormat())
throw new NoSuchUseridException();
if (isLoggedIn())
logout();
this.con.setConnection(null);
XMPPConnection connection;
try {
connection = XmppCommons.login(xuid.getUserId(), pw, xuid.getResource());
} catch (IOException e) {
- log.debug("login failed (wrong pw)");
+ log.debug("connecting failed");
throw new NetworkException(e);
}
if (connection == null) {
return false;
}
connection.sendPacket(new Presence(Presence.Type.available));
this.con.setConnection(connection);
addDiscoveryFeature();
registerForEvents();
getRoster().setSubscriptionMode(Roster.SubscriptionMode.accept_all);
for (ILoginStateListener lsl : lsll) {
lsl.loginHappened();
}
return true;
}
private void registerForEvents() throws NotLoggedInException {
getRoster().addRosterListener(new RosterPresenceChangeListener() {
public void presenceChanged(Presence presence) {
final String xmppid = presence.getFrom();
XmppStatusService.log.debug("presenceChanged: " + xmppid
+ " - " + presence);
if (isLoggedIn()) {
try {
XmppStatusService.this.con.getService()
.getUsersService().requestOnlineNotification(
new XmppUserId(xmppid));
} catch (NotLoggedInException e) {
log.debug("Shouldn't happen", e);
}
} else {
// skip. We don't want notifications after we logout.
}
}
});
}
@Override
public void logout() throws NetworkException, TimeoutException {
XmppCommons.logout(this.con.getConnection());
this.con.setConnection(null);
for (ILoginStateListener lsl : lsll) {
lsl.logoutHappened();
}
}
@Override
public void createAccount(UserId userid, String pw) throws NetworkException,
TimeoutException {
if (!new XmppUserId(userid).isOfCorrectUseridFormat())
throw new NoSuchUseridException();
if (isLoggedIn())
logout();
this.con.setConnection(null);
XMPPConnection connection;
try {
connection = XmppCommons.createAccount(userid.getUserId(), pw);
} catch (IOException e) {
log.debug("create failed: " + e.getMessage());
throw new NetworkException(e);
}
if (connection == null) {
throw new RuntimeException("Connection is null!");
}
XmppCommons.logout(connection);
}
@Override
public void registerLoginStateListener(ILoginStateListener lsl) {
lsll.add(lsl);
}
}
| true | true | public Boolean login(UserId userid, String pw) throws NetworkException,
TimeoutException {
XmppUserId xuid = new XmppUserId(userid);
if (!xuid.isOfCorrectUseridFormat())
throw new NoSuchUseridException();
if (isLoggedIn())
logout();
this.con.setConnection(null);
XMPPConnection connection;
try {
connection = XmppCommons.login(xuid.getUserId(), pw, xuid.getResource());
} catch (IOException e) {
log.debug("login failed (wrong pw)");
throw new NetworkException(e);
}
if (connection == null) {
return false;
}
connection.sendPacket(new Presence(Presence.Type.available));
this.con.setConnection(connection);
addDiscoveryFeature();
registerForEvents();
getRoster().setSubscriptionMode(Roster.SubscriptionMode.accept_all);
for (ILoginStateListener lsl : lsll) {
lsl.loginHappened();
}
return true;
}
| public Boolean login(UserId userid, String pw) throws NetworkException,
TimeoutException {
XmppUserId xuid = new XmppUserId(userid);
if (!xuid.isOfCorrectUseridFormat())
throw new NoSuchUseridException();
if (isLoggedIn())
logout();
this.con.setConnection(null);
XMPPConnection connection;
try {
connection = XmppCommons.login(xuid.getUserId(), pw, xuid.getResource());
} catch (IOException e) {
log.debug("connecting failed");
throw new NetworkException(e);
}
if (connection == null) {
return false;
}
connection.sendPacket(new Presence(Presence.Type.available));
this.con.setConnection(connection);
addDiscoveryFeature();
registerForEvents();
getRoster().setSubscriptionMode(Roster.SubscriptionMode.accept_all);
for (ILoginStateListener lsl : lsll) {
lsl.loginHappened();
}
return true;
}
|
diff --git a/src/main/java/edu/northwestern/bioinformatics/studycalendar/restlets/WadlHtmlResource.java b/src/main/java/edu/northwestern/bioinformatics/studycalendar/restlets/WadlHtmlResource.java
index 9f6802ff6..60b886d8f 100644
--- a/src/main/java/edu/northwestern/bioinformatics/studycalendar/restlets/WadlHtmlResource.java
+++ b/src/main/java/edu/northwestern/bioinformatics/studycalendar/restlets/WadlHtmlResource.java
@@ -1,44 +1,46 @@
package edu.northwestern.bioinformatics.studycalendar.restlets;
import org.restlet.resource.Resource;
import org.restlet.resource.TransformRepresentation;
import org.restlet.resource.Representation;
import org.restlet.resource.ResourceException;
import org.restlet.resource.Variant;
import org.restlet.Context;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.MediaType;
import freemarker.template.Configuration;
/**
* @author Rhett Sutphin
*/
public class WadlHtmlResource extends Resource {
private static final String WSDL_DOC_XSLT = "/edu/northwestern/bioinformatics/studycalendar/restlets/wadl_documentation.xsl";
private Configuration freemarkerConfiguration;
@Override
public void init(Context context, Request request, Response response) {
super.init(context, request, response);
getVariants().add(new Variant(MediaType.TEXT_HTML));
}
@Override
public Representation represent(Variant variant) throws ResourceException {
if (MediaType.TEXT_HTML.includes(variant.getMediaType())) {
- return new TransformRepresentation(null,
+ TransformRepresentation transform = new TransformRepresentation(null,
PscWadlRepresentation.create(freemarkerConfiguration, getRequest()),
new ClasspathResourceRepresentation(MediaType.TEXT_XML, WSDL_DOC_XSLT)
);
+ transform.setMediaType(MediaType.TEXT_HTML);
+ return transform;
} else {
return null;
}
}
public void setFreemarkerConfiguration(Configuration freemarkerConfiguration) {
this.freemarkerConfiguration = freemarkerConfiguration;
}
}
| false | true | public Representation represent(Variant variant) throws ResourceException {
if (MediaType.TEXT_HTML.includes(variant.getMediaType())) {
return new TransformRepresentation(null,
PscWadlRepresentation.create(freemarkerConfiguration, getRequest()),
new ClasspathResourceRepresentation(MediaType.TEXT_XML, WSDL_DOC_XSLT)
);
} else {
return null;
}
}
| public Representation represent(Variant variant) throws ResourceException {
if (MediaType.TEXT_HTML.includes(variant.getMediaType())) {
TransformRepresentation transform = new TransformRepresentation(null,
PscWadlRepresentation.create(freemarkerConfiguration, getRequest()),
new ClasspathResourceRepresentation(MediaType.TEXT_XML, WSDL_DOC_XSLT)
);
transform.setMediaType(MediaType.TEXT_HTML);
return transform;
} else {
return null;
}
}
|
diff --git a/evf-data/src/java/com/evinceframework/data/warehouse/query/QueryEngine.java b/evf-data/src/java/com/evinceframework/data/warehouse/query/QueryEngine.java
index 8259f00..836fa3a 100644
--- a/evf-data/src/java/com/evinceframework/data/warehouse/query/QueryEngine.java
+++ b/evf-data/src/java/com/evinceframework/data/warehouse/query/QueryEngine.java
@@ -1,49 +1,49 @@
/*
* Copyright 2013 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 com.evinceframework.data.warehouse.query;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import com.evinceframework.core.factory.MapBackedClassLookupFactory;
import com.evinceframework.data.warehouse.FactTable;
import com.evinceframework.data.warehouse.impl.FactTableImpl;
public class QueryEngine extends MapBackedClassLookupFactory<QueryCommand<Query, QueryResult>> {
private FactTable[] factTables = new FactTable[] {};
public QueryResult query(Query query) throws QueryException {
if(query == null)
return null;
- QueryCommand<Query, QueryResult> cmd = findImplementation(query.getClass());
+ QueryCommand<Query, QueryResult> cmd = lookup(query.getClass());
if(cmd == null) {
throw new QueryException(String.format("Unknown query: %s", query.getClass().getName())); // TODO i18n
}
return cmd.query(query);
}
/*package*/ public void addFactTable(FactTableImpl factTable) {
List<FactTable> f = new LinkedList<FactTable>(Arrays.asList(factTables));
assert(factTable.getQueryEngine().equals(this));
f.add(factTable);
factTables = f.toArray(new FactTable[]{});
}
}
| true | true | public QueryResult query(Query query) throws QueryException {
if(query == null)
return null;
QueryCommand<Query, QueryResult> cmd = findImplementation(query.getClass());
if(cmd == null) {
throw new QueryException(String.format("Unknown query: %s", query.getClass().getName())); // TODO i18n
}
return cmd.query(query);
}
| public QueryResult query(Query query) throws QueryException {
if(query == null)
return null;
QueryCommand<Query, QueryResult> cmd = lookup(query.getClass());
if(cmd == null) {
throw new QueryException(String.format("Unknown query: %s", query.getClass().getName())); // TODO i18n
}
return cmd.query(query);
}
|
diff --git a/blocks/sublima-app/src/main/java/com/computas/sublima/app/controller/admin/AdminController.java b/blocks/sublima-app/src/main/java/com/computas/sublima/app/controller/admin/AdminController.java
index 8975ccee..b1f24354 100644
--- a/blocks/sublima-app/src/main/java/com/computas/sublima/app/controller/admin/AdminController.java
+++ b/blocks/sublima-app/src/main/java/com/computas/sublima/app/controller/admin/AdminController.java
@@ -1,194 +1,192 @@
package com.computas.sublima.app.controller.admin;
import com.computas.sublima.app.adhoc.ConvertSublimaResources;
import com.computas.sublima.app.adhoc.ImportData;
import com.computas.sublima.app.service.AdminService;
import com.computas.sublima.app.service.IndexService;
import com.computas.sublima.app.service.LanguageService;
import com.computas.sublima.query.SparulDispatcher;
import com.computas.sublima.query.service.SettingsService;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.sparql.util.StringUtils;
import org.apache.cocoon.auth.ApplicationUtil;
import org.apache.cocoon.auth.User;
import org.apache.cocoon.components.flow.apples.AppleRequest;
import org.apache.cocoon.components.flow.apples.AppleResponse;
import org.apache.cocoon.components.flow.apples.StatelessAppleController;
import org.apache.log4j.Logger;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.net.URLEncoder;
import java.net.URL;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;
/**
* @author: mha
* Date: 31.mar.2008
*/
public class AdminController implements StatelessAppleController {
private SparulDispatcher sparulDispatcher;
AdminService adminService = new AdminService();
private ApplicationUtil appUtil = new ApplicationUtil();
private User user;
private String userPrivileges = "<empty/>";
String[] completePrefixArray = {
"PREFIX dct: <http://purl.org/dc/terms/>",
"PREFIX foaf: <http://xmlns.com/foaf/0.1/>",
"PREFIX sub: <http://xmlns.computas.com/sublima#>",
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"PREFIX wdr: <http://www.w3.org/2007/05/powder#>",
"PREFIX skos: <http://www.w3.org/2004/02/skos/core#>",
"PREFIX lingvoj: <http://www.lingvoj.org/ontology#>"};
String completePrefixes = StringUtils.join("\n", completePrefixArray);
private static Logger logger = Logger.getLogger(AdminController.class);
ConvertSublimaResources convert = new ConvertSublimaResources();
@SuppressWarnings("unchecked")
public void process(AppleRequest req, AppleResponse res) throws Exception {
String mode = req.getSitemapParameter("mode");
String submode = req.getSitemapParameter("submode");
if (appUtil.getUser() != null) {
user = appUtil.getUser();
userPrivileges = adminService.getRolePrivilegesAsXML(user.getAttribute("role").toString());
}
LanguageService langServ = new LanguageService();
String language = langServ.checkLanguage(req, res);
logger.trace("AdminController: Language from sitemap is " + req.getSitemapParameter("interface-language"));
logger.trace("AdminController: Language from service is " + language);
if ("".equalsIgnoreCase(mode)) {
Map<String, Object> bizData = new HashMap<String, Object>();
bizData.put("facets", adminService.getMostOfTheRequestXMLWithPrefix(req) + "</c:request>");
System.gc();
res.sendPage("xml2/admin", bizData);
} else if ("testsparql".equalsIgnoreCase(mode)) {
if ("".equalsIgnoreCase(submode)) {
System.gc();
res.sendPage("xhtml/testsparql", null);
} else {
String query = req.getCocoonRequest().getParameter("query");
res.redirectTo(req.getCocoonRequest().getContextPath() + "/sparql?query=" + URLEncoder.encode(query, "UTF-8"));
}
} else if ("testsparul".equalsIgnoreCase(mode)) {
if ("".equalsIgnoreCase(submode)) {
System.gc();
res.sendPage("xhtml/testsparul", null);
} else {
String query = req.getCocoonRequest().getParameter("query");
boolean deleteResourceSuccess = sparulDispatcher.query(query);
logger.trace("TestSparul:\n" + query);
logger.trace("TestSparul result: " + deleteResourceSuccess);
System.gc();
res.sendPage("xhtml/testsparul", null);
}
} else if ("database".equalsIgnoreCase(mode)) {
if ("".equalsIgnoreCase(submode)) {
uploadForm(res, req);
} else if ("upload".equalsIgnoreCase(submode)) {
uploadForm(res, req);
} else if ("export".equalsIgnoreCase(submode)) {
exportOntologyToXML(res, req);
}
} else if ("index".equalsIgnoreCase(mode)) {
- if ("index".equals(submode)) {
if (req.getCocoonRequest().getMethod().equalsIgnoreCase("POST")) {
index(res, req);
} else if (req.getCocoonRequest().getMethod().equalsIgnoreCase("GET")) {
showIndexStatus(res, req);
- }
}
} else {
res.sendStatus(404);
}
}
private void showIndexStatus(AppleResponse res, AppleRequest req) {
// Les indexstatistikk fra databasen
Map<String, Object> bizData = new HashMap<String, Object>();
bizData.put("index", adminService.getIndexStatisticsAsXML());
bizData.put("facets", adminService.getMostOfTheRequestXMLWithPrefix(req) + "</c:request>");
bizData.put("userprivileges", userPrivileges);
res.sendPage("xml2/index", bizData);
}
private void index(AppleResponse res, AppleRequest req) {
IndexService is = new IndexService();
is.createResourceIndex();
is.createTopicIndex();
showIndexStatus(res, req);
}
private void exportOntologyToXML(AppleResponse res, AppleRequest req) throws Exception {
adminService.insertSubjectOf();
Map<String, Object> bizData = new HashMap<String, Object>();
String type = req.getCocoonRequest().getParameter("type");
String query ="CONSTRUCT {?s ?p ?o} FROM <" + SettingsService.getProperty("sublima.basegraph") + "> WHERE {?s ?p ?o}";
String url = SettingsService.getProperty("sublima.sparql.endpoint") + "?query=" + URLEncoder.encode(query, "UTF-8");
URL u = new URL(url);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
Model model = ModelFactory.createDefaultModel();
ByteArrayOutputStream out = new ByteArrayOutputStream();
model.read(con.getInputStream(), "");
model.write(out, type);
bizData.put("ontology", out.toString());
out.close();
model.close();
System.gc();
res.sendPage("nostyle/export", bizData);
adminService.deleteSubjectOf();
}
private void uploadForm(AppleResponse res, AppleRequest req) {
Map<String, Object> bizData = new HashMap<String, Object>();
bizData.put("facets", adminService.getMostOfTheRequestXMLWithPrefix(req) + "</c:request>");
bizData.put("userprivileges", userPrivileges);
if (req.getCocoonRequest().getMethod().equalsIgnoreCase("GET")) {
System.gc();
res.sendPage("xml2/upload", bizData);
} else if (req.getCocoonRequest().getMethod().equalsIgnoreCase("POST")) {
if (req.getCocoonRequest().getParameter("location") != null) {
String type = req.getCocoonRequest().getParameter("type");
File file = new File(req.getCocoonRequest().getParameter("location"));
ImportData id = new ImportData();
try {
ConvertSublimaResources.applyRules(file.toURL().toString(), type, file.getCanonicalPath(), type);
id.load(file.toURL().toString(), type);
} catch (Exception e) {
logger.trace("AdminController.uploadForm --> Error during loading of resource");
e.printStackTrace();
}
}
System.gc();
res.sendPage("xml2/upload", bizData);
adminService.deleteSubjectOf();
}
}
public void setSparulDispatcher(SparulDispatcher sparulDispatcher) {
this.sparulDispatcher = sparulDispatcher;
}
}
| false | true | public void process(AppleRequest req, AppleResponse res) throws Exception {
String mode = req.getSitemapParameter("mode");
String submode = req.getSitemapParameter("submode");
if (appUtil.getUser() != null) {
user = appUtil.getUser();
userPrivileges = adminService.getRolePrivilegesAsXML(user.getAttribute("role").toString());
}
LanguageService langServ = new LanguageService();
String language = langServ.checkLanguage(req, res);
logger.trace("AdminController: Language from sitemap is " + req.getSitemapParameter("interface-language"));
logger.trace("AdminController: Language from service is " + language);
if ("".equalsIgnoreCase(mode)) {
Map<String, Object> bizData = new HashMap<String, Object>();
bizData.put("facets", adminService.getMostOfTheRequestXMLWithPrefix(req) + "</c:request>");
System.gc();
res.sendPage("xml2/admin", bizData);
} else if ("testsparql".equalsIgnoreCase(mode)) {
if ("".equalsIgnoreCase(submode)) {
System.gc();
res.sendPage("xhtml/testsparql", null);
} else {
String query = req.getCocoonRequest().getParameter("query");
res.redirectTo(req.getCocoonRequest().getContextPath() + "/sparql?query=" + URLEncoder.encode(query, "UTF-8"));
}
} else if ("testsparul".equalsIgnoreCase(mode)) {
if ("".equalsIgnoreCase(submode)) {
System.gc();
res.sendPage("xhtml/testsparul", null);
} else {
String query = req.getCocoonRequest().getParameter("query");
boolean deleteResourceSuccess = sparulDispatcher.query(query);
logger.trace("TestSparul:\n" + query);
logger.trace("TestSparul result: " + deleteResourceSuccess);
System.gc();
res.sendPage("xhtml/testsparul", null);
}
} else if ("database".equalsIgnoreCase(mode)) {
if ("".equalsIgnoreCase(submode)) {
uploadForm(res, req);
} else if ("upload".equalsIgnoreCase(submode)) {
uploadForm(res, req);
} else if ("export".equalsIgnoreCase(submode)) {
exportOntologyToXML(res, req);
}
} else if ("index".equalsIgnoreCase(mode)) {
if ("index".equals(submode)) {
if (req.getCocoonRequest().getMethod().equalsIgnoreCase("POST")) {
index(res, req);
} else if (req.getCocoonRequest().getMethod().equalsIgnoreCase("GET")) {
showIndexStatus(res, req);
}
}
} else {
res.sendStatus(404);
}
}
| public void process(AppleRequest req, AppleResponse res) throws Exception {
String mode = req.getSitemapParameter("mode");
String submode = req.getSitemapParameter("submode");
if (appUtil.getUser() != null) {
user = appUtil.getUser();
userPrivileges = adminService.getRolePrivilegesAsXML(user.getAttribute("role").toString());
}
LanguageService langServ = new LanguageService();
String language = langServ.checkLanguage(req, res);
logger.trace("AdminController: Language from sitemap is " + req.getSitemapParameter("interface-language"));
logger.trace("AdminController: Language from service is " + language);
if ("".equalsIgnoreCase(mode)) {
Map<String, Object> bizData = new HashMap<String, Object>();
bizData.put("facets", adminService.getMostOfTheRequestXMLWithPrefix(req) + "</c:request>");
System.gc();
res.sendPage("xml2/admin", bizData);
} else if ("testsparql".equalsIgnoreCase(mode)) {
if ("".equalsIgnoreCase(submode)) {
System.gc();
res.sendPage("xhtml/testsparql", null);
} else {
String query = req.getCocoonRequest().getParameter("query");
res.redirectTo(req.getCocoonRequest().getContextPath() + "/sparql?query=" + URLEncoder.encode(query, "UTF-8"));
}
} else if ("testsparul".equalsIgnoreCase(mode)) {
if ("".equalsIgnoreCase(submode)) {
System.gc();
res.sendPage("xhtml/testsparul", null);
} else {
String query = req.getCocoonRequest().getParameter("query");
boolean deleteResourceSuccess = sparulDispatcher.query(query);
logger.trace("TestSparul:\n" + query);
logger.trace("TestSparul result: " + deleteResourceSuccess);
System.gc();
res.sendPage("xhtml/testsparul", null);
}
} else if ("database".equalsIgnoreCase(mode)) {
if ("".equalsIgnoreCase(submode)) {
uploadForm(res, req);
} else if ("upload".equalsIgnoreCase(submode)) {
uploadForm(res, req);
} else if ("export".equalsIgnoreCase(submode)) {
exportOntologyToXML(res, req);
}
} else if ("index".equalsIgnoreCase(mode)) {
if (req.getCocoonRequest().getMethod().equalsIgnoreCase("POST")) {
index(res, req);
} else if (req.getCocoonRequest().getMethod().equalsIgnoreCase("GET")) {
showIndexStatus(res, req);
}
} else {
res.sendStatus(404);
}
}
|
diff --git a/src/eclipse/net.vtst.ow.eclipse.less/src/net/vtst/ow/eclipse/less/less/LessUtils.java b/src/eclipse/net.vtst.ow.eclipse.less/src/net/vtst/ow/eclipse/less/less/LessUtils.java
index 3e4f66a..6f5c89f 100644
--- a/src/eclipse/net.vtst.ow.eclipse.less/src/net/vtst/ow/eclipse/less/less/LessUtils.java
+++ b/src/eclipse/net.vtst.ow.eclipse.less/src/net/vtst/ow/eclipse/less/less/LessUtils.java
@@ -1,14 +1,15 @@
package net.vtst.ow.eclipse.less.less;
import org.eclipse.emf.ecore.EObject;
public class LessUtils {
public static EObject getNthAncestor(EObject obj, int nth) {
while (nth > 0 && obj != null) {
obj = obj.eContainer();
+ --nth;
}
return obj;
}
}
| true | true | public static EObject getNthAncestor(EObject obj, int nth) {
while (nth > 0 && obj != null) {
obj = obj.eContainer();
}
return obj;
}
| public static EObject getNthAncestor(EObject obj, int nth) {
while (nth > 0 && obj != null) {
obj = obj.eContainer();
--nth;
}
return obj;
}
|
diff --git a/src/main/java/agaricus/mods/highlighttips/HighlightTips.java b/src/main/java/agaricus/mods/highlighttips/HighlightTips.java
index ca00909..1ec1632 100644
--- a/src/main/java/agaricus/mods/highlighttips/HighlightTips.java
+++ b/src/main/java/agaricus/mods/highlighttips/HighlightTips.java
@@ -1,271 +1,272 @@
package agaricus.mods.highlighttips;
import cpw.mods.fml.client.registry.KeyBindingRegistry;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.ITickHandler;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.TickType;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.registry.TickRegistry;
import cpw.mods.fml.relauncher.FMLRelauncher;
import cpw.mods.fml.relauncher.Side;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityFurnace;
import net.minecraft.util.*;
import net.minecraft.world.World;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.liquids.ILiquidTank;
import net.minecraftforge.liquids.ITankContainer;
import net.minecraftforge.liquids.LiquidStack;
import java.util.EnumSet;
import java.util.logging.Level;
@Mod(modid = "HighlightTips", name = "HighlightTips", version = "1.0-SNAPSHOT") // TODO: version from resource
@NetworkMod(clientSideRequired = false, serverSideRequired = false)
public class HighlightTips implements ITickHandler {
private static final int DEFAULT_KEY_TOGGLE = 62; // F4 - see http://www.minecraftwiki.net/wiki/Key_codes
private static final double DEFAULT_RANGE = 300;
private static final int DEFAULT_X = 0;
private static final int DEFAULT_Y = 0;
private static final int DEFAULT_COLOR = 0xffffff;
private boolean enable = true;
private int keyToggle = DEFAULT_KEY_TOGGLE;
private double range = DEFAULT_RANGE;
private int x = DEFAULT_X;
private int y = DEFAULT_Y;
private int color = DEFAULT_COLOR;
private ToggleKeyHandler toggleKeyHandler;
@Mod.PreInit
public void preInit(FMLPreInitializationEvent event) {
Configuration cfg = new Configuration(event.getSuggestedConfigurationFile());
try {
cfg.load();
enable = cfg.get(Configuration.CATEGORY_GENERAL, "enable", true).getBoolean(true);
keyToggle = cfg.get(Configuration.CATEGORY_GENERAL, "key.toggle", DEFAULT_KEY_TOGGLE).getInt(DEFAULT_KEY_TOGGLE);
range = cfg.get(Configuration.CATEGORY_GENERAL, "range", DEFAULT_RANGE).getDouble(DEFAULT_RANGE);
x = cfg.get(Configuration.CATEGORY_GENERAL, "x", DEFAULT_X).getInt(DEFAULT_X);
y = cfg.get(Configuration.CATEGORY_GENERAL, "y", DEFAULT_Y).getInt(DEFAULT_Y);
color = cfg.get(Configuration.CATEGORY_GENERAL, "color", DEFAULT_COLOR).getInt(DEFAULT_COLOR);
} catch (Exception e) {
FMLLog.log(Level.SEVERE, e, "HighlightTips had a problem loading it's configuration");
} finally {
cfg.save();
}
if (!FMLRelauncher.side().equals("CLIENT")) {
// gracefully disable on non-client (= server) instead of crashing
enable = false;
}
if (!enable) {
FMLLog.log(Level.INFO, "HighlightTips disabled");
return;
}
TickRegistry.registerTickHandler(this, Side.CLIENT);
KeyBindingRegistry.registerKeyBinding(toggleKeyHandler = new ToggleKeyHandler(keyToggle));
}
private String describeBlock(int id, int meta, TileEntity tileEntity) {
StringBuilder sb = new StringBuilder();
describeBlockID(sb, id, meta);
describeTileEntity(sb, tileEntity);
return sb.toString();
}
private void describeTileEntity(StringBuilder sb, TileEntity te) {
if (te == null) return;
if (te instanceof ITankContainer) {
sb.append(" ITankContainer: ");
ILiquidTank[] tanks = ((ITankContainer) te).getTanks(ForgeDirection.UP);
for (ILiquidTank tank : tanks) {
sb.append(describeLiquidStack(tank.getLiquid()));
sb.append(' ');
//sb.append(tank.getTankPressure()); // TODO: tank capacity *used*? this is not it..
//sb.append('/');
sb.append(tank.getCapacity());
int pressure = tank.getTankPressure();
if (pressure < 0) {
sb.append(pressure);
} else {
sb.append('+');
sb.append(pressure);
}
sb.append(' ');
}
}
if (te instanceof IInventory) {
IInventory inventory = (IInventory) te;
sb.append(" IInventory: ");
sb.append(inventoryName(inventory));
sb.append(" (");
sb.append(inventory.getSizeInventory());
sb.append(" slots)");
}
sb.append(' ');
sb.append(te.getClass().getName());
}
private String inventoryName(IInventory inventory) {
if (!inventory.isInvNameLocalized()) {
return StatCollector.translateToLocal(inventory.getInvName());
} else {
return inventory.getInvName();
}
}
private String describeLiquidStack(LiquidStack liquidStack) {
if (liquidStack == null) return "Empty";
ItemStack itemStack = liquidStack.canonical().asItemStack();
if (itemStack == null) return "Empty";
return itemStack.getDisplayName();
}
private void describeBlockID(StringBuilder sb, int id, int meta) {
Block block = Block.blocksList[id];
if (block == null) {
sb.append("block #"+id);
return;
}
// block info
sb.append(id);
sb.append(':');
sb.append(meta);
sb.append(' ');
String blockName = block.getLocalizedName();
- sb.append(blockName);
+ if (!blockName.startsWith("You ran into")) // a serious Bug, if you have legitly acquired this Block, please report it immidietly"
+ sb.append(blockName);
// item info, if it was mined (this often has more user-friendly information, but sometimes is identical)
sb.append(" ");
int itemDropDamage = block.damageDropped(meta);
if (Item.itemsList[id + 256] != null) {
ItemStack itemDropStack = new ItemStack(id, 1, itemDropDamage);
String itemDropName = itemDropStack.getDisplayName();
if (!blockName.equals(itemDropName)) {
sb.append(itemDropName);
}
// item info guess if item damage corresponds to block metadata, not necessarily if mined - sometimes more informative
try {
ItemStack itemMetaStack = new ItemStack(id, 1, meta);
String itemMetaName = itemMetaStack.getDisplayName();
if (itemMetaName != null && !blockName.equals(itemMetaName) && !itemDropName.equals(itemMetaName)) {
sb.append(' ');
sb.append(itemMetaName);
}
} catch (Throwable t) {
}
}
if (itemDropDamage != meta) {
sb.append(' ');
sb.append(itemDropDamage);
}
}
// based on net/minecraft/item/Item, copied since it is needlessly protected
protected MovingObjectPosition getMovingObjectPositionFromPlayer(World par1World, EntityPlayer par2EntityPlayer)
{
float f = 1.0F;
float f1 = par2EntityPlayer.prevRotationPitch + (par2EntityPlayer.rotationPitch - par2EntityPlayer.prevRotationPitch) * f;
float f2 = par2EntityPlayer.prevRotationYaw + (par2EntityPlayer.rotationYaw - par2EntityPlayer.prevRotationYaw) * f;
double d0 = par2EntityPlayer.prevPosX + (par2EntityPlayer.posX - par2EntityPlayer.prevPosX) * (double)f;
double d1 = par2EntityPlayer.prevPosY + (par2EntityPlayer.posY - par2EntityPlayer.prevPosY) * (double)f + 1.62D - (double)par2EntityPlayer.yOffset;
double d2 = par2EntityPlayer.prevPosZ + (par2EntityPlayer.posZ - par2EntityPlayer.prevPosZ) * (double)f;
Vec3 vec3 = par1World.getWorldVec3Pool().getVecFromPool(d0, d1, d2);
float f3 = MathHelper.cos(-f2 * 0.017453292F - (float) Math.PI);
float f4 = MathHelper.sin(-f2 * 0.017453292F - (float) Math.PI);
float f5 = -MathHelper.cos(-f1 * 0.017453292F);
float f6 = MathHelper.sin(-f1 * 0.017453292F);
float f7 = f4 * f5;
float f8 = f3 * f5;
double d3 = 5.0D;
if (par2EntityPlayer instanceof EntityPlayerMP)
{
d3 = ((EntityPlayerMP)par2EntityPlayer).theItemInWorldManager.getBlockReachDistance();
}
Vec3 vec31 = vec3.addVector((double)f7 * d3, (double)f6 * d3, (double)f8 * d3);
return par1World.rayTraceBlocks_do_do(vec3, vec31, false, false); // "ray traces all blocks, including non-collideable ones"
}
@Override
public void tickEnd(EnumSet<TickType> type, Object... tickData) {
if (!toggleKeyHandler.showInfo) return;
Minecraft mc = Minecraft.getMinecraft();
GuiScreen screen = mc.currentScreen;
if (screen != null) return;
float partialTickTime = 1;
MovingObjectPosition mop = getMovingObjectPositionFromPlayer(mc.theWorld, mc.thePlayer);
String s;
if (mop == null) {
return;
} else if (mop.typeOfHit == EnumMovingObjectType.ENTITY) {
// TODO: find out why this apparently never triggers
s = "entity " + mop.entityHit.getClass().getName();
} else if (mop.typeOfHit == EnumMovingObjectType.TILE) {
int id = mc.thePlayer.worldObj.getBlockId(mop.blockX, mop.blockY, mop.blockZ);
int meta = mc.thePlayer.worldObj.getBlockMetadata(mop.blockX, mop.blockY, mop.blockZ);
TileEntity tileEntity = mc.thePlayer.worldObj.blockHasTileEntity(mop.blockX, mop.blockY, mop.blockZ) ? mc.thePlayer.worldObj.getBlockTileEntity(mop.blockX, mop.blockY, mop.blockZ) : null;
try {
s = describeBlock(id, meta, tileEntity);
} catch (Throwable t) {
s = id + ":" + meta + " - " + t;
t.printStackTrace();
}
} else {
s = "unknown";
}
mc.fontRenderer.drawStringWithShadow(s, x, y, color);
}
@Override
public void tickStart(EnumSet<TickType> type, Object... tickData) {
}
@Override
public EnumSet<TickType> ticks() {
return EnumSet.of(TickType.RENDER);
}
@Override
public String getLabel() {
return "HighlightTips";
}
}
| true | true | private void describeBlockID(StringBuilder sb, int id, int meta) {
Block block = Block.blocksList[id];
if (block == null) {
sb.append("block #"+id);
return;
}
// block info
sb.append(id);
sb.append(':');
sb.append(meta);
sb.append(' ');
String blockName = block.getLocalizedName();
sb.append(blockName);
// item info, if it was mined (this often has more user-friendly information, but sometimes is identical)
sb.append(" ");
int itemDropDamage = block.damageDropped(meta);
if (Item.itemsList[id + 256] != null) {
ItemStack itemDropStack = new ItemStack(id, 1, itemDropDamage);
String itemDropName = itemDropStack.getDisplayName();
if (!blockName.equals(itemDropName)) {
sb.append(itemDropName);
}
// item info guess if item damage corresponds to block metadata, not necessarily if mined - sometimes more informative
try {
ItemStack itemMetaStack = new ItemStack(id, 1, meta);
String itemMetaName = itemMetaStack.getDisplayName();
if (itemMetaName != null && !blockName.equals(itemMetaName) && !itemDropName.equals(itemMetaName)) {
sb.append(' ');
sb.append(itemMetaName);
}
} catch (Throwable t) {
}
}
if (itemDropDamage != meta) {
sb.append(' ');
sb.append(itemDropDamage);
}
}
| private void describeBlockID(StringBuilder sb, int id, int meta) {
Block block = Block.blocksList[id];
if (block == null) {
sb.append("block #"+id);
return;
}
// block info
sb.append(id);
sb.append(':');
sb.append(meta);
sb.append(' ');
String blockName = block.getLocalizedName();
if (!blockName.startsWith("You ran into")) // a serious Bug, if you have legitly acquired this Block, please report it immidietly"
sb.append(blockName);
// item info, if it was mined (this often has more user-friendly information, but sometimes is identical)
sb.append(" ");
int itemDropDamage = block.damageDropped(meta);
if (Item.itemsList[id + 256] != null) {
ItemStack itemDropStack = new ItemStack(id, 1, itemDropDamage);
String itemDropName = itemDropStack.getDisplayName();
if (!blockName.equals(itemDropName)) {
sb.append(itemDropName);
}
// item info guess if item damage corresponds to block metadata, not necessarily if mined - sometimes more informative
try {
ItemStack itemMetaStack = new ItemStack(id, 1, meta);
String itemMetaName = itemMetaStack.getDisplayName();
if (itemMetaName != null && !blockName.equals(itemMetaName) && !itemDropName.equals(itemMetaName)) {
sb.append(' ');
sb.append(itemMetaName);
}
} catch (Throwable t) {
}
}
if (itemDropDamage != meta) {
sb.append(' ');
sb.append(itemDropDamage);
}
}
|
diff --git a/main/src/cgeo/geocaching/cgeoinit.java b/main/src/cgeo/geocaching/cgeoinit.java
index 9743ff2b5..d931f6743 100644
--- a/main/src/cgeo/geocaching/cgeoinit.java
+++ b/main/src/cgeo/geocaching/cgeoinit.java
@@ -1,762 +1,762 @@
package cgeo.geocaching;
import cgeo.geocaching.LogTemplateProvider.LogTemplate;
import cgeo.geocaching.activity.AbstractActivity;
import cgeo.geocaching.compatibility.Compatibility;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.StatusCode;
import cgeo.geocaching.maps.MapProviderFactory;
import cgeo.geocaching.twitter.TwitterAuthorizationActivity;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.http.HttpResponse;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import java.io.File;
import java.util.SortedMap;
import java.util.concurrent.atomic.AtomicReference;
public class cgeoinit extends AbstractActivity {
private final static int SELECT_MAPFILE_REQUEST = 1;
private ProgressDialog loginDialog = null;
private ProgressDialog webDialog = null;
private Handler logInHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
try {
if (loginDialog != null && loginDialog.isShowing()) {
loginDialog.dismiss();
}
if (msg.obj == null || (msg.obj instanceof Drawable)) {
helpDialog(res.getString(R.string.init_login_popup), res.getString(R.string.init_login_popup_ok),
(Drawable) msg.obj);
} else {
helpDialog(res.getString(R.string.init_login_popup),
res.getString(R.string.init_login_popup_failed_reason) + " " +
((StatusCode) msg.obj).getErrorString(res) + ".");
}
} catch (Exception e) {
showToast(res.getString(R.string.err_login_failed));
Log.e(Settings.tag, "cgeoinit.logInHandler: " + e.toString());
}
if (loginDialog != null && loginDialog.isShowing()) {
loginDialog.dismiss();
}
init();
}
};
private Handler webAuthHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
try {
if (webDialog != null && webDialog.isShowing()) {
webDialog.dismiss();
}
if (msg.what > 0) {
helpDialog(res.getString(R.string.init_sendToCgeo), res.getString(R.string.init_sendToCgeo_register_ok).replace("####", "" + msg.what));
} else {
helpDialog(res.getString(R.string.init_sendToCgeo), res.getString(R.string.init_sendToCgeo_register_fail));
}
} catch (Exception e) {
showToast(res.getString(R.string.init_sendToCgeo_register_fail));
Log.e(Settings.tag, "cgeoinit.webHandler: " + e.toString());
}
if (webDialog != null && webDialog.isShowing()) {
webDialog.dismiss();
}
init();
}
};
protected boolean enableTemplatesMenu = false;
public cgeoinit() {
super("c:geo-configuration");
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// init
setTheme();
setContentView(R.layout.init);
setTitle(res.getString(R.string.settings));
init();
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
init();
}
@Override
public void onPause() {
saveValues();
super.onPause();
}
@Override
public void onStop() {
saveValues();
Compatibility.dataChanged(getPackageName());
super.onStop();
}
@Override
public void onDestroy() {
saveValues();
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, res.getString(R.string.init_clear)).setIcon(android.R.drawable.ic_menu_delete);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == 0) {
boolean status = false;
((EditText) findViewById(R.id.username)).setText("");
((EditText) findViewById(R.id.password)).setText("");
((EditText) findViewById(R.id.passvote)).setText("");
status = saveValues();
if (status) {
showToast(res.getString(R.string.init_cleared));
} else {
showToast(res.getString(R.string.err_init_cleared));
}
finish();
}
return false;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (enableTemplatesMenu) {
menu.setHeaderTitle(R.string.init_signature_template_button);
for (LogTemplate template : LogTemplateProvider.getTemplates()) {
menu.add(0, template.getItemId(), 0, template.getResourceId());
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
LogTemplate template = LogTemplateProvider.getTemplate(item.getItemId());
if (template != null) {
return insertSignatureTemplate(template);
}
return super.onContextItemSelected(item);
}
private boolean insertSignatureTemplate(final LogTemplate template) {
EditText sig = (EditText) findViewById(R.id.signature);
String insertText = "[" + template.getTemplateString() + "]";
cgBase.insertAtPosition(sig, insertText, true);
return true;
}
public void init() {
// geocaching.com settings
- ImmutablePair<String, String> login = Settings.getLogin();
+ final ImmutablePair<String, String> login = Settings.getLogin();
if (login != null) {
((EditText) findViewById(R.id.username)).setText(login.left);
((EditText) findViewById(R.id.password)).setText(login.right);
}
Button logMeIn = (Button) findViewById(R.id.log_me_in);
logMeIn.setOnClickListener(new logIn());
TextView legalNote = (TextView) findViewById(R.id.legal_note);
legalNote.setClickable(true);
legalNote.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/about/termsofuse.aspx")));
}
});
// gcvote settings
- String passvoteNow = Settings.getGCvoteLogin().right;
- if (passvoteNow != null) {
- ((EditText) findViewById(R.id.passvote)).setText(passvoteNow);
+ final ImmutablePair<String, String> gcvoteLogin = Settings.getGCvoteLogin();
+ if (null != gcvoteLogin && null != gcvoteLogin.right) {
+ ((EditText) findViewById(R.id.passvote)).setText(gcvoteLogin.right);
}
// go4cache settings
TextView go4cache = (TextView) findViewById(R.id.about_go4cache);
go4cache.setClickable(true);
go4cache.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://go4cache.com/")));
}
});
final CheckBox publicButton = (CheckBox) findViewById(R.id.publicloc);
publicButton.setChecked(Settings.isPublicLoc());
publicButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setPublicLoc(publicButton.isChecked());
}
});
// Twitter settings
Button authorizeTwitter = (Button) findViewById(R.id.authorize_twitter);
authorizeTwitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent authIntent = new Intent(cgeoinit.this, TwitterAuthorizationActivity.class);
startActivity(authIntent);
}
});
final CheckBox twitterButton = (CheckBox) findViewById(R.id.twitter_option);
twitterButton.setChecked(Settings.isUseTwitter() && Settings.isTwitterLoginValid());
twitterButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setUseTwitter(twitterButton.isChecked());
if (Settings.isUseTwitter() && !Settings.isTwitterLoginValid()) {
Intent authIntent = new Intent(cgeoinit.this, TwitterAuthorizationActivity.class);
startActivity(authIntent);
}
twitterButton.setChecked(Settings.isUseTwitter());
}
});
// Signature settings
EditText sigEdit = (EditText) findViewById(R.id.signature);
if (sigEdit.getText().length() == 0) {
sigEdit.setText(Settings.getSignature());
}
Button sigBtn = (Button) findViewById(R.id.signature_help);
sigBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
helpDialog(res.getString(R.string.init_signature_help_title), res.getString(R.string.init_signature_help_text));
}
});
Button templates = (Button) findViewById(R.id.signature_template);
registerForContextMenu(templates);
templates.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
enableTemplatesMenu = true;
openContextMenu(v);
enableTemplatesMenu = false;
}
});
final CheckBox autoinsertButton = (CheckBox) findViewById(R.id.sigautoinsert);
autoinsertButton.setChecked(Settings.isAutoInsertSignature());
autoinsertButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setAutoInsertSignature(autoinsertButton.isChecked());
}
});
// Cache details
final CheckBox autoloadButton = (CheckBox) findViewById(R.id.autoload);
autoloadButton.setChecked(Settings.isAutoLoadDescription());
autoloadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setAutoLoadDesc(autoloadButton.isChecked());
}
});
final CheckBox ratingWantedButton = (CheckBox) findViewById(R.id.ratingwanted);
ratingWantedButton.setChecked(Settings.isRatingWanted());
ratingWantedButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setRatingWanted(ratingWantedButton.isChecked());
}
});
final CheckBox elevationWantedButton = (CheckBox) findViewById(R.id.elevationwanted);
elevationWantedButton.setChecked(Settings.isElevationWanted());
elevationWantedButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setElevationWanted(elevationWantedButton.isChecked());
}
});
// Other settings
final CheckBox skinButton = (CheckBox) findViewById(R.id.skin);
skinButton.setChecked(Settings.isLightSkin());
skinButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setLightSkin(skinButton.isChecked());
}
});
final CheckBox addressButton = (CheckBox) findViewById(R.id.address);
addressButton.setChecked(Settings.isShowAddress());
addressButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setShowAddress(addressButton.isChecked());
}
});
final CheckBox captchaButton = (CheckBox) findViewById(R.id.captcha);
captchaButton.setChecked(Settings.isShowCaptcha());
captchaButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setShowCaptcha(captchaButton.isChecked());
}
});
final CheckBox dirImgButton = (CheckBox) findViewById(R.id.loaddirectionimg);
dirImgButton.setChecked(Settings.getLoadDirImg());
dirImgButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setLoadDirImg(!Settings.getLoadDirImg());
dirImgButton.setChecked(Settings.getLoadDirImg());
}
});
final CheckBox useEnglishButton = (CheckBox) findViewById(R.id.useenglish);
useEnglishButton.setChecked(Settings.isUseEnglish());
useEnglishButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setUseEnglish(useEnglishButton.isChecked());
}
});
final CheckBox excludeButton = (CheckBox) findViewById(R.id.exclude);
excludeButton.setChecked(Settings.isExcludeMyCaches());
excludeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setExcludeMine(excludeButton.isChecked());
}
});
final CheckBox disabledButton = (CheckBox) findViewById(R.id.disabled);
disabledButton.setChecked(Settings.isExcludeDisabledCaches());
disabledButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setExcludeDisabledCaches(disabledButton.isChecked());
}
});
TextView showWaypointsThreshold = (TextView) findViewById(R.id.showwaypointsthreshold);
showWaypointsThreshold.setText(String.valueOf(Settings.getWayPointsThreshold()));
final CheckBox autovisitButton = (CheckBox) findViewById(R.id.trackautovisit);
autovisitButton.setChecked(Settings.isTrackableAutoVisit());
autovisitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setTrackableAutoVisit(autovisitButton.isChecked());
}
});
final CheckBox offlineButton = (CheckBox) findViewById(R.id.offline);
offlineButton.setChecked(Settings.isStoreOfflineMaps());
offlineButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setStoreOfflineMaps(offlineButton.isChecked());
}
});
final CheckBox saveLogImgButton = (CheckBox) findViewById(R.id.save_log_img);
saveLogImgButton.setChecked(Settings.isStoreLogImages());
saveLogImgButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setStoreLogImages(saveLogImgButton.isChecked());
}
});
final CheckBox livelistButton = (CheckBox) findViewById(R.id.livelist);
livelistButton.setChecked(Settings.isLiveList());
livelistButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setLiveList(livelistButton.isChecked());
}
});
final CheckBox unitsButton = (CheckBox) findViewById(R.id.units);
unitsButton.setChecked(!Settings.isUseMetricUnits());
unitsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setUseMetricUnits(!unitsButton.isChecked());
}
});
final CheckBox gnavButton = (CheckBox) findViewById(R.id.gnav);
gnavButton.setChecked(Settings.isUseGoogleNavigation());
gnavButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setUseGoogleNavigation(gnavButton.isChecked());
}
});
final CheckBox logOffline = (CheckBox) findViewById(R.id.log_offline);
logOffline.setChecked(Settings.getLogOffline());
logOffline.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setLogOffline(!Settings.getLogOffline());
logOffline.setChecked(Settings.getLogOffline());
}
});
final CheckBox browserButton = (CheckBox) findViewById(R.id.browser);
browserButton.setChecked(Settings.isBrowser());
browserButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setAsBrowser(browserButton.isChecked());
}
});
// Altitude settings
EditText altitudeEdit = (EditText) findViewById(R.id.altitude);
altitudeEdit.setText(String.valueOf(Settings.getAltCorrection()));
//Send2cgeo settings
String webDeviceName = Settings.getWebDeviceName();
if (StringUtils.isNotBlank(webDeviceName)) {
((EditText) findViewById(R.id.webDeviceName)).setText(webDeviceName);
} else {
String s = android.os.Build.MODEL;
((EditText) findViewById(R.id.webDeviceName)).setText(s);
}
Button webAuth = (Button) findViewById(R.id.sendToCgeo_register);
webAuth.setOnClickListener(new webAuth());
// Map source settings
SortedMap<Integer, String> mapSources = MapProviderFactory.getMapSources();
Spinner mapSourceSelector = (Spinner) findViewById(R.id.mapsource);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, mapSources.values().toArray(new String[] {}));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mapSourceSelector.setAdapter(adapter);
int mapsource = Settings.getMapSource();
mapSourceSelector.setSelection(MapProviderFactory.getSourceOrdinalFromId(mapsource));
mapSourceSelector.setOnItemSelectedListener(new cgeoChangeMapSource());
initMapfileEdittext(false);
Button selectMapfile = (Button) findViewById(R.id.select_mapfile);
selectMapfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent selectIntent = new Intent(cgeoinit.this, cgSelectMapfile.class);
startActivityForResult(selectIntent, SELECT_MAPFILE_REQUEST);
}
});
refreshBackupLabel();
}
private void initMapfileEdittext(boolean setFocus) {
EditText mfmapFileEdit = (EditText) findViewById(R.id.mapfile);
mfmapFileEdit.setText(Settings.getMapFile());
if (setFocus) {
mfmapFileEdit.requestFocus();
}
}
/**
* @param view
* unused here but needed since this method is referenced from XML layout
*/
public void backup(View view) {
// avoid overwriting an existing backup with an empty database (can happen directly after reinstalling the app)
if (app.getAllStoredCachesCount(true, CacheType.ALL, null) == 0) {
helpDialog(res.getString(R.string.init_backup), res.getString(R.string.init_backup_unnecessary));
return;
}
final AtomicReference<String> fileRef = new AtomicReference<String>(null);
final ProgressDialog dialog = ProgressDialog.show(this, res.getString(R.string.init_backup), res.getString(R.string.init_backup_running), true, false);
Thread backupThread = new Thread() {
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
dialog.dismiss();
final String file = fileRef.get();
if (file != null) {
helpDialog(res.getString(R.string.init_backup_backup), res.getString(R.string.init_backup_success) + "\n" + file);
} else {
helpDialog(res.getString(R.string.init_backup_backup), res.getString(R.string.init_backup_failed));
}
refreshBackupLabel();
}
};
@Override
public void run() {
fileRef.set(app.backupDatabase());
handler.sendMessage(handler.obtainMessage());
}
};
backupThread.start();
}
private void refreshBackupLabel() {
TextView lastBackup = (TextView) findViewById(R.id.backup_last);
File lastBackupFile = cgeoapplication.isRestoreFile();
if (lastBackupFile != null) {
lastBackup.setText(res.getString(R.string.init_backup_last) + " " + cgBase.formatTime(lastBackupFile.lastModified()) + ", " + cgBase.formatDate(lastBackupFile.lastModified()));
} else {
lastBackup.setText(res.getString(R.string.init_backup_last_no));
}
}
/**
* @param view
* unused here but needed since this method is referenced from XML layout
*/
public void restore(View view) {
app.restoreDatabase(this);
}
public boolean saveValues() {
String usernameNew = StringUtils.trimToEmpty(((EditText) findViewById(R.id.username)).getText().toString());
String passwordNew = StringUtils.trimToEmpty(((EditText) findViewById(R.id.password)).getText().toString());
String passvoteNew = StringUtils.trimToEmpty(((EditText) findViewById(R.id.passvote)).getText().toString());
// don't trim signature, user may want to have whitespace at the beginning
String signatureNew = ((EditText) findViewById(R.id.signature)).getText().toString();
String altitudeNew = StringUtils.trimToNull(((EditText) findViewById(R.id.altitude)).getText().toString());
String mfmapFileNew = StringUtils.trimToEmpty(((EditText) findViewById(R.id.mapfile)).getText().toString());
int altitudeNewInt = 0;
if (altitudeNew != null) {
try {
altitudeNewInt = Integer.parseInt(altitudeNew);
} catch (NumberFormatException e) {
altitudeNewInt = 0;
}
}
final boolean status1 = Settings.setLogin(usernameNew, passwordNew);
final boolean status2 = Settings.setGCvoteLogin(passvoteNew);
final boolean status3 = Settings.setSignature(signatureNew);
final boolean status4 = Settings.setAltCorrection(altitudeNewInt);
final boolean status5 = Settings.setMapFile(mfmapFileNew);
TextView field = (TextView) findViewById(R.id.showwaypointsthreshold);
Settings.setShowWaypointsThreshold(safeParse(field, 5));
return status1 && status2 && status3 && status4 && status5;
}
/**
* Returns the Int Value in the Field
*
* @param field
* the field to retrieve the integer value from
* @param defaultValue
* the default value
* @return either the field content or the default value
*/
static private int safeParse(final TextView field, int defaultValue) {
try {
return Integer.parseInt(field.getText().toString());
} catch (NumberFormatException e) {
return defaultValue;
}
}
private static class cgeoChangeMapSource implements OnItemSelectedListener {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Settings.setMapSource(MapProviderFactory.getSourceIdFromOrdinal(arg2));
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
arg0.setSelection(MapProviderFactory.getSourceIdFromOrdinal(Settings.getMapSource()));
}
}
private class logIn implements View.OnClickListener {
public void onClick(View arg0) {
final String username = ((EditText) findViewById(R.id.username)).getText().toString();
final String password = ((EditText) findViewById(R.id.password)).getText().toString();
if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
showToast(res.getString(R.string.err_missing_auth));
return;
}
loginDialog = ProgressDialog.show(cgeoinit.this, res.getString(R.string.init_login_popup), res.getString(R.string.init_login_popup_working), true);
loginDialog.setCancelable(false);
Settings.setLogin(username, password);
cgBase.clearCookies();
(new Thread() {
@Override
public void run() {
final StatusCode loginResult = cgBase.login();
Object payload = loginResult;
if (loginResult == StatusCode.NO_ERROR) {
cgBase.detectGcCustomDate();
payload = cgBase.downloadAvatar(cgeoinit.this);
}
logInHandler.obtainMessage(0, payload).sendToTarget();
}
}).start();
}
}
private class webAuth implements View.OnClickListener {
public void onClick(View arg0) {
final String deviceName = ((EditText) findViewById(R.id.webDeviceName)).getText().toString();
final String deviceCode = Settings.getWebDeviceCode();
if (StringUtils.isBlank(deviceName)) {
showToast(res.getString(R.string.err_missing_device_name));
return;
}
webDialog = ProgressDialog.show(cgeoinit.this, res.getString(R.string.init_sendToCgeo), res.getString(R.string.init_sendToCgeo_registering), true);
webDialog.setCancelable(false);
(new Thread() {
@Override
public void run() {
int pin = 0;
final String nam = StringUtils.defaultString(deviceName);
final String cod = StringUtils.defaultString(deviceCode);
final Parameters params = new Parameters("name", nam, "code", cod);
HttpResponse response = cgBase.request("http://send2.cgeo.org/auth.html", params, true);
if (response != null && response.getStatusLine().getStatusCode() == 200)
{
//response was OK
String[] strings = cgBase.getResponseData(response).split(",");
try {
pin = Integer.parseInt(strings[1].trim());
} catch (Exception e) {
Log.e(Settings.tag, "webDialog: " + e.toString());
}
String code = strings[0];
Settings.setWebNameCode(nam, code);
}
webAuthHandler.sendEmptyMessage(pin);
}
}).start();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_MAPFILE_REQUEST) {
if (resultCode == RESULT_OK) {
if (data.hasExtra("mapfile")) {
Settings.setMapFile(data.getStringExtra("mapfile"));
}
}
initMapfileEdittext(true);
}
}
}
| false | true | public void init() {
// geocaching.com settings
ImmutablePair<String, String> login = Settings.getLogin();
if (login != null) {
((EditText) findViewById(R.id.username)).setText(login.left);
((EditText) findViewById(R.id.password)).setText(login.right);
}
Button logMeIn = (Button) findViewById(R.id.log_me_in);
logMeIn.setOnClickListener(new logIn());
TextView legalNote = (TextView) findViewById(R.id.legal_note);
legalNote.setClickable(true);
legalNote.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/about/termsofuse.aspx")));
}
});
// gcvote settings
String passvoteNow = Settings.getGCvoteLogin().right;
if (passvoteNow != null) {
((EditText) findViewById(R.id.passvote)).setText(passvoteNow);
}
// go4cache settings
TextView go4cache = (TextView) findViewById(R.id.about_go4cache);
go4cache.setClickable(true);
go4cache.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://go4cache.com/")));
}
});
final CheckBox publicButton = (CheckBox) findViewById(R.id.publicloc);
publicButton.setChecked(Settings.isPublicLoc());
publicButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setPublicLoc(publicButton.isChecked());
}
});
// Twitter settings
Button authorizeTwitter = (Button) findViewById(R.id.authorize_twitter);
authorizeTwitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent authIntent = new Intent(cgeoinit.this, TwitterAuthorizationActivity.class);
startActivity(authIntent);
}
});
final CheckBox twitterButton = (CheckBox) findViewById(R.id.twitter_option);
twitterButton.setChecked(Settings.isUseTwitter() && Settings.isTwitterLoginValid());
twitterButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setUseTwitter(twitterButton.isChecked());
if (Settings.isUseTwitter() && !Settings.isTwitterLoginValid()) {
Intent authIntent = new Intent(cgeoinit.this, TwitterAuthorizationActivity.class);
startActivity(authIntent);
}
twitterButton.setChecked(Settings.isUseTwitter());
}
});
// Signature settings
EditText sigEdit = (EditText) findViewById(R.id.signature);
if (sigEdit.getText().length() == 0) {
sigEdit.setText(Settings.getSignature());
}
Button sigBtn = (Button) findViewById(R.id.signature_help);
sigBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
helpDialog(res.getString(R.string.init_signature_help_title), res.getString(R.string.init_signature_help_text));
}
});
Button templates = (Button) findViewById(R.id.signature_template);
registerForContextMenu(templates);
templates.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
enableTemplatesMenu = true;
openContextMenu(v);
enableTemplatesMenu = false;
}
});
final CheckBox autoinsertButton = (CheckBox) findViewById(R.id.sigautoinsert);
autoinsertButton.setChecked(Settings.isAutoInsertSignature());
autoinsertButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setAutoInsertSignature(autoinsertButton.isChecked());
}
});
// Cache details
final CheckBox autoloadButton = (CheckBox) findViewById(R.id.autoload);
autoloadButton.setChecked(Settings.isAutoLoadDescription());
autoloadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setAutoLoadDesc(autoloadButton.isChecked());
}
});
final CheckBox ratingWantedButton = (CheckBox) findViewById(R.id.ratingwanted);
ratingWantedButton.setChecked(Settings.isRatingWanted());
ratingWantedButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setRatingWanted(ratingWantedButton.isChecked());
}
});
final CheckBox elevationWantedButton = (CheckBox) findViewById(R.id.elevationwanted);
elevationWantedButton.setChecked(Settings.isElevationWanted());
elevationWantedButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setElevationWanted(elevationWantedButton.isChecked());
}
});
// Other settings
final CheckBox skinButton = (CheckBox) findViewById(R.id.skin);
skinButton.setChecked(Settings.isLightSkin());
skinButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setLightSkin(skinButton.isChecked());
}
});
final CheckBox addressButton = (CheckBox) findViewById(R.id.address);
addressButton.setChecked(Settings.isShowAddress());
addressButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setShowAddress(addressButton.isChecked());
}
});
final CheckBox captchaButton = (CheckBox) findViewById(R.id.captcha);
captchaButton.setChecked(Settings.isShowCaptcha());
captchaButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setShowCaptcha(captchaButton.isChecked());
}
});
final CheckBox dirImgButton = (CheckBox) findViewById(R.id.loaddirectionimg);
dirImgButton.setChecked(Settings.getLoadDirImg());
dirImgButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setLoadDirImg(!Settings.getLoadDirImg());
dirImgButton.setChecked(Settings.getLoadDirImg());
}
});
final CheckBox useEnglishButton = (CheckBox) findViewById(R.id.useenglish);
useEnglishButton.setChecked(Settings.isUseEnglish());
useEnglishButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setUseEnglish(useEnglishButton.isChecked());
}
});
final CheckBox excludeButton = (CheckBox) findViewById(R.id.exclude);
excludeButton.setChecked(Settings.isExcludeMyCaches());
excludeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setExcludeMine(excludeButton.isChecked());
}
});
final CheckBox disabledButton = (CheckBox) findViewById(R.id.disabled);
disabledButton.setChecked(Settings.isExcludeDisabledCaches());
disabledButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setExcludeDisabledCaches(disabledButton.isChecked());
}
});
TextView showWaypointsThreshold = (TextView) findViewById(R.id.showwaypointsthreshold);
showWaypointsThreshold.setText(String.valueOf(Settings.getWayPointsThreshold()));
final CheckBox autovisitButton = (CheckBox) findViewById(R.id.trackautovisit);
autovisitButton.setChecked(Settings.isTrackableAutoVisit());
autovisitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setTrackableAutoVisit(autovisitButton.isChecked());
}
});
final CheckBox offlineButton = (CheckBox) findViewById(R.id.offline);
offlineButton.setChecked(Settings.isStoreOfflineMaps());
offlineButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setStoreOfflineMaps(offlineButton.isChecked());
}
});
final CheckBox saveLogImgButton = (CheckBox) findViewById(R.id.save_log_img);
saveLogImgButton.setChecked(Settings.isStoreLogImages());
saveLogImgButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setStoreLogImages(saveLogImgButton.isChecked());
}
});
final CheckBox livelistButton = (CheckBox) findViewById(R.id.livelist);
livelistButton.setChecked(Settings.isLiveList());
livelistButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setLiveList(livelistButton.isChecked());
}
});
final CheckBox unitsButton = (CheckBox) findViewById(R.id.units);
unitsButton.setChecked(!Settings.isUseMetricUnits());
unitsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setUseMetricUnits(!unitsButton.isChecked());
}
});
final CheckBox gnavButton = (CheckBox) findViewById(R.id.gnav);
gnavButton.setChecked(Settings.isUseGoogleNavigation());
gnavButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setUseGoogleNavigation(gnavButton.isChecked());
}
});
final CheckBox logOffline = (CheckBox) findViewById(R.id.log_offline);
logOffline.setChecked(Settings.getLogOffline());
logOffline.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setLogOffline(!Settings.getLogOffline());
logOffline.setChecked(Settings.getLogOffline());
}
});
final CheckBox browserButton = (CheckBox) findViewById(R.id.browser);
browserButton.setChecked(Settings.isBrowser());
browserButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setAsBrowser(browserButton.isChecked());
}
});
// Altitude settings
EditText altitudeEdit = (EditText) findViewById(R.id.altitude);
altitudeEdit.setText(String.valueOf(Settings.getAltCorrection()));
//Send2cgeo settings
String webDeviceName = Settings.getWebDeviceName();
if (StringUtils.isNotBlank(webDeviceName)) {
((EditText) findViewById(R.id.webDeviceName)).setText(webDeviceName);
} else {
String s = android.os.Build.MODEL;
((EditText) findViewById(R.id.webDeviceName)).setText(s);
}
Button webAuth = (Button) findViewById(R.id.sendToCgeo_register);
webAuth.setOnClickListener(new webAuth());
// Map source settings
SortedMap<Integer, String> mapSources = MapProviderFactory.getMapSources();
Spinner mapSourceSelector = (Spinner) findViewById(R.id.mapsource);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, mapSources.values().toArray(new String[] {}));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mapSourceSelector.setAdapter(adapter);
int mapsource = Settings.getMapSource();
mapSourceSelector.setSelection(MapProviderFactory.getSourceOrdinalFromId(mapsource));
mapSourceSelector.setOnItemSelectedListener(new cgeoChangeMapSource());
initMapfileEdittext(false);
Button selectMapfile = (Button) findViewById(R.id.select_mapfile);
selectMapfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent selectIntent = new Intent(cgeoinit.this, cgSelectMapfile.class);
startActivityForResult(selectIntent, SELECT_MAPFILE_REQUEST);
}
});
refreshBackupLabel();
}
| public void init() {
// geocaching.com settings
final ImmutablePair<String, String> login = Settings.getLogin();
if (login != null) {
((EditText) findViewById(R.id.username)).setText(login.left);
((EditText) findViewById(R.id.password)).setText(login.right);
}
Button logMeIn = (Button) findViewById(R.id.log_me_in);
logMeIn.setOnClickListener(new logIn());
TextView legalNote = (TextView) findViewById(R.id.legal_note);
legalNote.setClickable(true);
legalNote.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/about/termsofuse.aspx")));
}
});
// gcvote settings
final ImmutablePair<String, String> gcvoteLogin = Settings.getGCvoteLogin();
if (null != gcvoteLogin && null != gcvoteLogin.right) {
((EditText) findViewById(R.id.passvote)).setText(gcvoteLogin.right);
}
// go4cache settings
TextView go4cache = (TextView) findViewById(R.id.about_go4cache);
go4cache.setClickable(true);
go4cache.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://go4cache.com/")));
}
});
final CheckBox publicButton = (CheckBox) findViewById(R.id.publicloc);
publicButton.setChecked(Settings.isPublicLoc());
publicButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setPublicLoc(publicButton.isChecked());
}
});
// Twitter settings
Button authorizeTwitter = (Button) findViewById(R.id.authorize_twitter);
authorizeTwitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent authIntent = new Intent(cgeoinit.this, TwitterAuthorizationActivity.class);
startActivity(authIntent);
}
});
final CheckBox twitterButton = (CheckBox) findViewById(R.id.twitter_option);
twitterButton.setChecked(Settings.isUseTwitter() && Settings.isTwitterLoginValid());
twitterButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setUseTwitter(twitterButton.isChecked());
if (Settings.isUseTwitter() && !Settings.isTwitterLoginValid()) {
Intent authIntent = new Intent(cgeoinit.this, TwitterAuthorizationActivity.class);
startActivity(authIntent);
}
twitterButton.setChecked(Settings.isUseTwitter());
}
});
// Signature settings
EditText sigEdit = (EditText) findViewById(R.id.signature);
if (sigEdit.getText().length() == 0) {
sigEdit.setText(Settings.getSignature());
}
Button sigBtn = (Button) findViewById(R.id.signature_help);
sigBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
helpDialog(res.getString(R.string.init_signature_help_title), res.getString(R.string.init_signature_help_text));
}
});
Button templates = (Button) findViewById(R.id.signature_template);
registerForContextMenu(templates);
templates.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
enableTemplatesMenu = true;
openContextMenu(v);
enableTemplatesMenu = false;
}
});
final CheckBox autoinsertButton = (CheckBox) findViewById(R.id.sigautoinsert);
autoinsertButton.setChecked(Settings.isAutoInsertSignature());
autoinsertButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setAutoInsertSignature(autoinsertButton.isChecked());
}
});
// Cache details
final CheckBox autoloadButton = (CheckBox) findViewById(R.id.autoload);
autoloadButton.setChecked(Settings.isAutoLoadDescription());
autoloadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setAutoLoadDesc(autoloadButton.isChecked());
}
});
final CheckBox ratingWantedButton = (CheckBox) findViewById(R.id.ratingwanted);
ratingWantedButton.setChecked(Settings.isRatingWanted());
ratingWantedButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setRatingWanted(ratingWantedButton.isChecked());
}
});
final CheckBox elevationWantedButton = (CheckBox) findViewById(R.id.elevationwanted);
elevationWantedButton.setChecked(Settings.isElevationWanted());
elevationWantedButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setElevationWanted(elevationWantedButton.isChecked());
}
});
// Other settings
final CheckBox skinButton = (CheckBox) findViewById(R.id.skin);
skinButton.setChecked(Settings.isLightSkin());
skinButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setLightSkin(skinButton.isChecked());
}
});
final CheckBox addressButton = (CheckBox) findViewById(R.id.address);
addressButton.setChecked(Settings.isShowAddress());
addressButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setShowAddress(addressButton.isChecked());
}
});
final CheckBox captchaButton = (CheckBox) findViewById(R.id.captcha);
captchaButton.setChecked(Settings.isShowCaptcha());
captchaButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setShowCaptcha(captchaButton.isChecked());
}
});
final CheckBox dirImgButton = (CheckBox) findViewById(R.id.loaddirectionimg);
dirImgButton.setChecked(Settings.getLoadDirImg());
dirImgButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setLoadDirImg(!Settings.getLoadDirImg());
dirImgButton.setChecked(Settings.getLoadDirImg());
}
});
final CheckBox useEnglishButton = (CheckBox) findViewById(R.id.useenglish);
useEnglishButton.setChecked(Settings.isUseEnglish());
useEnglishButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setUseEnglish(useEnglishButton.isChecked());
}
});
final CheckBox excludeButton = (CheckBox) findViewById(R.id.exclude);
excludeButton.setChecked(Settings.isExcludeMyCaches());
excludeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setExcludeMine(excludeButton.isChecked());
}
});
final CheckBox disabledButton = (CheckBox) findViewById(R.id.disabled);
disabledButton.setChecked(Settings.isExcludeDisabledCaches());
disabledButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setExcludeDisabledCaches(disabledButton.isChecked());
}
});
TextView showWaypointsThreshold = (TextView) findViewById(R.id.showwaypointsthreshold);
showWaypointsThreshold.setText(String.valueOf(Settings.getWayPointsThreshold()));
final CheckBox autovisitButton = (CheckBox) findViewById(R.id.trackautovisit);
autovisitButton.setChecked(Settings.isTrackableAutoVisit());
autovisitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setTrackableAutoVisit(autovisitButton.isChecked());
}
});
final CheckBox offlineButton = (CheckBox) findViewById(R.id.offline);
offlineButton.setChecked(Settings.isStoreOfflineMaps());
offlineButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setStoreOfflineMaps(offlineButton.isChecked());
}
});
final CheckBox saveLogImgButton = (CheckBox) findViewById(R.id.save_log_img);
saveLogImgButton.setChecked(Settings.isStoreLogImages());
saveLogImgButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setStoreLogImages(saveLogImgButton.isChecked());
}
});
final CheckBox livelistButton = (CheckBox) findViewById(R.id.livelist);
livelistButton.setChecked(Settings.isLiveList());
livelistButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setLiveList(livelistButton.isChecked());
}
});
final CheckBox unitsButton = (CheckBox) findViewById(R.id.units);
unitsButton.setChecked(!Settings.isUseMetricUnits());
unitsButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setUseMetricUnits(!unitsButton.isChecked());
}
});
final CheckBox gnavButton = (CheckBox) findViewById(R.id.gnav);
gnavButton.setChecked(Settings.isUseGoogleNavigation());
gnavButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setUseGoogleNavigation(gnavButton.isChecked());
}
});
final CheckBox logOffline = (CheckBox) findViewById(R.id.log_offline);
logOffline.setChecked(Settings.getLogOffline());
logOffline.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setLogOffline(!Settings.getLogOffline());
logOffline.setChecked(Settings.getLogOffline());
}
});
final CheckBox browserButton = (CheckBox) findViewById(R.id.browser);
browserButton.setChecked(Settings.isBrowser());
browserButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Settings.setAsBrowser(browserButton.isChecked());
}
});
// Altitude settings
EditText altitudeEdit = (EditText) findViewById(R.id.altitude);
altitudeEdit.setText(String.valueOf(Settings.getAltCorrection()));
//Send2cgeo settings
String webDeviceName = Settings.getWebDeviceName();
if (StringUtils.isNotBlank(webDeviceName)) {
((EditText) findViewById(R.id.webDeviceName)).setText(webDeviceName);
} else {
String s = android.os.Build.MODEL;
((EditText) findViewById(R.id.webDeviceName)).setText(s);
}
Button webAuth = (Button) findViewById(R.id.sendToCgeo_register);
webAuth.setOnClickListener(new webAuth());
// Map source settings
SortedMap<Integer, String> mapSources = MapProviderFactory.getMapSources();
Spinner mapSourceSelector = (Spinner) findViewById(R.id.mapsource);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, mapSources.values().toArray(new String[] {}));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mapSourceSelector.setAdapter(adapter);
int mapsource = Settings.getMapSource();
mapSourceSelector.setSelection(MapProviderFactory.getSourceOrdinalFromId(mapsource));
mapSourceSelector.setOnItemSelectedListener(new cgeoChangeMapSource());
initMapfileEdittext(false);
Button selectMapfile = (Button) findViewById(R.id.select_mapfile);
selectMapfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent selectIntent = new Intent(cgeoinit.this, cgSelectMapfile.class);
startActivityForResult(selectIntent, SELECT_MAPFILE_REQUEST);
}
});
refreshBackupLabel();
}
|
diff --git a/wikAPIdia-phrases/src/main/java/org/wikapidia/phrases/LucenePhraseAnalyzer.java b/wikAPIdia-phrases/src/main/java/org/wikapidia/phrases/LucenePhraseAnalyzer.java
index 38e38c26..f60a6b8e 100644
--- a/wikAPIdia-phrases/src/main/java/org/wikapidia/phrases/LucenePhraseAnalyzer.java
+++ b/wikAPIdia-phrases/src/main/java/org/wikapidia/phrases/LucenePhraseAnalyzer.java
@@ -1,111 +1,111 @@
package org.wikapidia.phrases;
import com.typesafe.config.Config;
import org.wikapidia.conf.Configuration;
import org.wikapidia.conf.ConfigurationException;
import org.wikapidia.conf.Configurator;
import org.wikapidia.core.dao.DaoException;
import org.wikapidia.core.dao.LocalPageDao;
import org.wikapidia.core.lang.Language;
import org.wikapidia.core.lang.LanguageSet;
import org.wikapidia.core.model.LocalPage;
import org.wikapidia.core.model.UniversalPage;
import org.wikapidia.lucene.*;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.logging.Logger;
/**
* Using Lucene in a phrase analyzer.
* @author Yulun Li
*/
public class LucenePhraseAnalyzer implements PhraseAnalyzer {
private static final Logger LOG = Logger.getLogger(PhraseAnalyzer.class.getName());
private final LuceneSearcher searcher;
protected LocalPageDao localPageDao;
public LucenePhraseAnalyzer(LocalPageDao localPageDao, LuceneSearcher searcher) {
this.localPageDao = localPageDao;
this.searcher = searcher;
}
@Override
public LinkedHashMap<LocalPage, Float> resolveLocal(Language language, String phrase, int maxPages) throws DaoException {
LinkedHashMap<LocalPage, Float> result = new LinkedHashMap<LocalPage, Float>();
WikapidiaScoreDoc[] wikapidiaScoreDocs = searcher.getQueryBuilderByLanguage(language)
.setPhraseQuery(phrase)
.setNumHits(10)
.search();
- if (wikapidiaScoreDocs.length == 0 && phrase.indexOf(" ") < 0) {
+ if (wikapidiaScoreDocs.length == 0 && phrase.indexOf(" ") < 0 && phrase.length() > 3) {
String phraseMultiVersion = "";
for (int i = 1; i < phrase.length(); i++) {
phraseMultiVersion += (i > 2 ? phrase.substring(0, i) + " " : "");
phraseMultiVersion += (phrase.length() - i > 2 ? phrase.substring(i, phrase.length()) + " " : "");
}
wikapidiaScoreDocs = searcher.getQueryBuilderByLanguage(language)
.setPhraseQuery(phraseMultiVersion)
.setNumHits(10)
.search();
}
float totalScore = 0;
for (WikapidiaScoreDoc wikapidiaScoreDoc : wikapidiaScoreDocs) {
totalScore += wikapidiaScoreDoc.score;
}
for (WikapidiaScoreDoc wikapidiaScoreDoc : wikapidiaScoreDocs) {
int localPageId = searcher.getLocalIdFromDocId(wikapidiaScoreDoc.doc, language);
LocalPage localPage = localPageDao.getById(language, localPageId);
result.put(localPage, wikapidiaScoreDoc.score / totalScore);
}
return result;
}
public static class Provider extends org.wikapidia.conf.Provider<PhraseAnalyzer> {
public Provider(Configurator configurator, Configuration config) throws ConfigurationException {
super(configurator, config);
}
@Override
public Class<PhraseAnalyzer> getType() {
return PhraseAnalyzer.class;
}
@Override
public String getPath() {
return "phrases.analyzer";
}
@Override
public PhraseAnalyzer get(String name, Config config) throws ConfigurationException {
if (!config.getString("type").equals("luceneAnalyzer")) {
return null;
}
LocalPageDao localPageDao = getConfigurator().get(LocalPageDao.class, config.getString("localPageDao"));
LuceneSearcher searcher = new LuceneSearcher(new LanguageSet(getConfig().get().getStringList("languages")),
getConfigurator().get(LuceneOptions.class));
return new LucenePhraseAnalyzer(localPageDao, searcher);
}
}
@Override
public LinkedHashMap<UniversalPage, Float> resolveUniversal(Language language, String phrase, int algorithmId, int maxPages) {
return null;
}
@Override
public LinkedHashMap<String, Float> describeUniversal(Language language, UniversalPage page, int maxPhrases) {
return null;
}
@Override
public LinkedHashMap<String, Float> describeLocal(Language language, LocalPage page, int maxPhrases) throws DaoException {
return null;
}
@Override
public void loadCorpus(LanguageSet langs) throws DaoException, IOException {
}
}
| true | true | public LinkedHashMap<LocalPage, Float> resolveLocal(Language language, String phrase, int maxPages) throws DaoException {
LinkedHashMap<LocalPage, Float> result = new LinkedHashMap<LocalPage, Float>();
WikapidiaScoreDoc[] wikapidiaScoreDocs = searcher.getQueryBuilderByLanguage(language)
.setPhraseQuery(phrase)
.setNumHits(10)
.search();
if (wikapidiaScoreDocs.length == 0 && phrase.indexOf(" ") < 0) {
String phraseMultiVersion = "";
for (int i = 1; i < phrase.length(); i++) {
phraseMultiVersion += (i > 2 ? phrase.substring(0, i) + " " : "");
phraseMultiVersion += (phrase.length() - i > 2 ? phrase.substring(i, phrase.length()) + " " : "");
}
wikapidiaScoreDocs = searcher.getQueryBuilderByLanguage(language)
.setPhraseQuery(phraseMultiVersion)
.setNumHits(10)
.search();
}
float totalScore = 0;
for (WikapidiaScoreDoc wikapidiaScoreDoc : wikapidiaScoreDocs) {
totalScore += wikapidiaScoreDoc.score;
}
for (WikapidiaScoreDoc wikapidiaScoreDoc : wikapidiaScoreDocs) {
int localPageId = searcher.getLocalIdFromDocId(wikapidiaScoreDoc.doc, language);
LocalPage localPage = localPageDao.getById(language, localPageId);
result.put(localPage, wikapidiaScoreDoc.score / totalScore);
}
return result;
}
| public LinkedHashMap<LocalPage, Float> resolveLocal(Language language, String phrase, int maxPages) throws DaoException {
LinkedHashMap<LocalPage, Float> result = new LinkedHashMap<LocalPage, Float>();
WikapidiaScoreDoc[] wikapidiaScoreDocs = searcher.getQueryBuilderByLanguage(language)
.setPhraseQuery(phrase)
.setNumHits(10)
.search();
if (wikapidiaScoreDocs.length == 0 && phrase.indexOf(" ") < 0 && phrase.length() > 3) {
String phraseMultiVersion = "";
for (int i = 1; i < phrase.length(); i++) {
phraseMultiVersion += (i > 2 ? phrase.substring(0, i) + " " : "");
phraseMultiVersion += (phrase.length() - i > 2 ? phrase.substring(i, phrase.length()) + " " : "");
}
wikapidiaScoreDocs = searcher.getQueryBuilderByLanguage(language)
.setPhraseQuery(phraseMultiVersion)
.setNumHits(10)
.search();
}
float totalScore = 0;
for (WikapidiaScoreDoc wikapidiaScoreDoc : wikapidiaScoreDocs) {
totalScore += wikapidiaScoreDoc.score;
}
for (WikapidiaScoreDoc wikapidiaScoreDoc : wikapidiaScoreDocs) {
int localPageId = searcher.getLocalIdFromDocId(wikapidiaScoreDoc.doc, language);
LocalPage localPage = localPageDao.getById(language, localPageId);
result.put(localPage, wikapidiaScoreDoc.score / totalScore);
}
return result;
}
|
diff --git a/projects/connector-manager/source/java/com/google/enterprise/connector/common/WorkQueue.java b/projects/connector-manager/source/java/com/google/enterprise/connector/common/WorkQueue.java
index 0a499e2e..288c3c7a 100644
--- a/projects/connector-manager/source/java/com/google/enterprise/connector/common/WorkQueue.java
+++ b/projects/connector-manager/source/java/com/google/enterprise/connector/common/WorkQueue.java
@@ -1,135 +1,134 @@
// Copyright 2006 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.enterprise.connector.common;
import java.util.LinkedList;
import java.util.logging.Logger;
/**
* The WorkQueue provides a way for callers to issue non-blocking work
* requests. This class is multi-thread safe.
*/
public class WorkQueue {
private static final Logger logger =
Logger.getLogger(WorkQueue.class.getName());
// Queue used for added work.
private LinkedList workQueue;
private int numThreads;
private Thread[] threads;
private boolean isInitialized;
/**
* Creates a WorkQueue with a given number of worker threads.
* @param numThreads the number of threads to execute work on the WorkQueue.
* This number should be at least 1.
*/
public WorkQueue(int numThreads) {
if (numThreads <= 0) {
throw new IllegalArgumentException("numThreads must be > 0");
}
this.workQueue = new LinkedList();
this.numThreads = numThreads;
this.threads = new Thread[this.numThreads];
isInitialized = false;
}
/**
* Initialize work queue by starting worker threads.
*/
public synchronized void init() {
if (isInitialized) {
return;
}
for (int i = 0; i < numThreads; i++) {
threads[i] = new WorkQueueThread();
threads[i].start();
}
isInitialized = true;
}
/**
* Shutdown the work queue by interrupting any work in progress. All work
* that was added is discarded.
*/
public synchronized void shutdown() {
if (isInitialized) {
// TODO: instead of just calling Thread.interrupt, call a work specific
// interrupt/cancellation.
for (int i = 0; i < numThreads; i++) {
threads[i].interrupt();
}
}
workQueue.clear();
isInitialized = false;
}
/**
* Add a piece of work that will be executed.
* @param work one piece of work
*/
public synchronized void addWork(Runnable work) {
if (!isInitialized) {
throw new IllegalStateException(
"Must init() WorkQueue object before adding work.");
}
workQueue.addLast(work);
notifyAll();
}
/**
* Determine the number of pieces of work that are in the queue.
* @return the number of pieces of work in the queue.
*/
public synchronized int getWorkCount() {
if (!isInitialized) {
throw new IllegalStateException(
"Must init() WorkQueue object before getWorkCount().");
}
return workQueue.size();
}
/**
* A WorkQueueThread executes work in the WorkQueue and calls the associated
* callback method when the work is complete.
*/
private class WorkQueueThread extends Thread {
public void run() {
while (true) {
synchronized (WorkQueue.this) {
while (workQueue.isEmpty()) {
try {
WorkQueue.this.wait();
} catch (InterruptedException ie) {
- logger.warning("WorkQueueThread was interrupted: "
- + ie.getMessage());
+ // thread exits when shutdown of WorkQueue occurs
return;
}
}
Runnable work = (Runnable) workQueue.removeFirst();
try {
work.run();
} catch (RuntimeException e) {
logger.warning("WorkQueueThread work had problems: "
+ e.getMessage());
continue;
}
}
}
}
}
}
| true | true | public void run() {
while (true) {
synchronized (WorkQueue.this) {
while (workQueue.isEmpty()) {
try {
WorkQueue.this.wait();
} catch (InterruptedException ie) {
logger.warning("WorkQueueThread was interrupted: "
+ ie.getMessage());
return;
}
}
Runnable work = (Runnable) workQueue.removeFirst();
try {
work.run();
} catch (RuntimeException e) {
logger.warning("WorkQueueThread work had problems: "
+ e.getMessage());
continue;
}
}
}
}
| public void run() {
while (true) {
synchronized (WorkQueue.this) {
while (workQueue.isEmpty()) {
try {
WorkQueue.this.wait();
} catch (InterruptedException ie) {
// thread exits when shutdown of WorkQueue occurs
return;
}
}
Runnable work = (Runnable) workQueue.removeFirst();
try {
work.run();
} catch (RuntimeException e) {
logger.warning("WorkQueueThread work had problems: "
+ e.getMessage());
continue;
}
}
}
}
|
diff --git a/src/net/colar/netbeans/fan/FanParserTask.java b/src/net/colar/netbeans/fan/FanParserTask.java
index e4fe093..26999ed 100644
--- a/src/net/colar/netbeans/fan/FanParserTask.java
+++ b/src/net/colar/netbeans/fan/FanParserTask.java
@@ -1,713 +1,713 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.colar.netbeans.fan;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.text.Document;
import net.colar.netbeans.fan.indexer.model.FanSlot;
import net.colar.netbeans.fan.scope.FanAstScopeVar;
import net.colar.netbeans.fan.parboiled.FanLexAstUtils;
import net.colar.netbeans.fan.indexer.model.FanType;
import net.colar.netbeans.fan.parboiled.AstKind;
import net.colar.netbeans.fan.parboiled.AstNode;
import net.colar.netbeans.fan.parboiled.FantomParser;
import net.colar.netbeans.fan.parboiled.FantomParserTokens.TokenName;
import net.colar.netbeans.fan.parboiled.pred.NodeKindPredicate;
import net.colar.netbeans.fan.scope.FanAstScopeVarBase;
import net.colar.netbeans.fan.scope.FanAstScopeVarBase.VarKind;
import net.colar.netbeans.fan.scope.FanLocalScopeVar;
import net.colar.netbeans.fan.scope.FanTypeScopeVar;
import net.colar.netbeans.fan.types.FanResolvedListType;
import net.colar.netbeans.fan.types.FanResolvedMapType;
import net.colar.netbeans.fan.types.FanResolvedNullType;
import net.colar.netbeans.fan.types.FanResolvedType;
import org.netbeans.modules.csl.api.Error;
import org.netbeans.modules.csl.api.OffsetRange;
import org.netbeans.modules.csl.api.Severity;
import org.netbeans.modules.csl.spi.DefaultError;
import org.netbeans.modules.csl.spi.ParserResult;
import org.netbeans.modules.parsing.api.Snapshot;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.parboiled.Node;
import org.parboiled.Parboiled;
import org.parboiled.RecoveringParseRunner;
import org.parboiled.errors.ErrorUtils;
import org.parboiled.errors.ParseError;
import org.parboiled.support.ParseTreeUtils;
import org.parboiled.support.ParsingResult;
/**
* Parse a fan file and holds the results
* parse() parses the file
* parseScope() adds to the tree scope vraiables etc...
* @author tcolar
*/
public class FanParserTask extends ParserResult
{
List<Error> errors = new Vector<Error>(); // -> use parsingResult.errors ?
// full path of the source file
private final FileObject sourceFile;
// simple name of the source file
private final String sourceName;
// pod name
private final String pod;
// once parse() is called, will contain the parboiled parsing result
private ParsingResult<AstNode> parsingResult;
private AstNode astRoot;
public FanParserTask(Snapshot snapshot)
{
super(snapshot);
sourceName = snapshot.getSource().getFileObject().getName();
sourceFile = FileUtil.toFileObject(new File(snapshot.getSource().getFileObject().getPath()));
pod = FanUtilities.getPodForPath(sourceFile.getPath());
}
@Override
public List<? extends Error> getDiagnostics()
{
return errors;
}
@Override
protected void invalidate()
{
// what should this do ?
}
/**
* Return AST tree generated by this parsing
* @return
*/
public Node getParseNodeTree()
{
if (parsingResult != null)
{
return parsingResult.parseTreeRoot;
}
return null;
}
public AstNode getAstTree()
{
Node<AstNode> nd = getParseNodeTree();
return nd == null ? null : nd.getValue();
}
/**
* Dump AST tree
*/
public void dumpTree()
{
FanUtilities.GENERIC_LOGGER.trace("-------------------Start AST Tree dump-----------------------");
ParseTreeUtils.printNodeTree(parsingResult);
FanUtilities.GENERIC_LOGGER.trace("-------------------End AST Tree dump-----------------------");
}
/**
* Shotcut method for getSnapshot().getSource().getDocument(true);
* @return
*/
public Document getDocument()
{
return getSnapshot().getSource().getDocument(true);
}
public void addError(String title, Throwable t)
{
// "High level error"
Error error = DefaultError.createDefaultError(title, title, title, null, 0, 0, true, Severity.ERROR);
errors.add(error);
}
/**
* The root scope
* @return
*/
public AstNode getRootScope()
{
return astRoot;
}
public FileObject getSourceFile()
{
return sourceFile;
}
/**
* Add an error (not the parser errors, but others like semantic etc..)
* @param info
* @param node
*/
public void addError(String info, AstNode node)
{
if (node == null)
{
return;
}
String key = "FanParserTask";
OffsetRange range = FanLexAstUtils.getNodeRange(node);
int start = range.getStart();
int end = range.getEnd();
//System.out.println("Start: "+start+"End:"+end);
Error error = DefaultError.createDefaultError(key, info, "Syntax Error", sourceFile, start, end, true, Severity.ERROR);
errors.add(error);
}
/**
* Parse the file (using parboiled FantomParser)
*/
public void parse()
{
FantomParser parser = Parboiled.createParser(FantomParser.class, this);
try
{
parsingResult = RecoveringParseRunner.run(parser.compilationUnit(), getSnapshot().getText().toString());
// Copy parboiled parse error into a CSL errrors
for (ParseError err : parsingResult.parseErrors)
{
// key, displayName, description, file, start, end, lineError?, severity
String msg = ErrorUtils.printParseError(err, parsingResult.inputBuffer);
Error error = DefaultError.createDefaultError(msg, msg, msg,
sourceFile, err.getErrorLocation().getIndex(), err.getErrorLocation().getIndex() + err.getErrorCharCount(),
false, Severity.ERROR);
errors.add(error);
}
if (parsingResult.parseTreeRoot != null)
{
astRoot = parsingResult.parseTreeRoot.getValue();
// Removed orphaned(backtracked) AST nodes.
prune(astRoot);
}
} catch (Exception e)
{
addError("Parser error", e);
e.printStackTrace();
}
}
/**
* Call after parsing to add scope variables / type resolution to the AST tree
*/
public void parseScope()
{
if (astRoot == null)
{
return;
}
// First run : lookup using statements
for (AstNode node : astRoot.getChildren())
{
switch (node.getKind())
{
case AST_INC_USING:
addError("Incomplete import statement", node);
break;
case AST_USING:
addUsing(node);
break;
}
}
// Second pass, lookup types and slots
for (AstNode node : astRoot.getChildren())
{
switch (node.getKind())
{
case AST_TYPE_DEF:
String name = FanLexAstUtils.getFirstChildText(node, new NodeKindPredicate(AstKind.AST_ID));
FanTypeScopeVar var = new FanTypeScopeVar(node, name);
AstNode scopeNode = FanLexAstUtils.getScopeNode(node.getRoot());
// We parse the type base first and add it to scope right away
// So that parseSlots() can later resolve this & super.
var.parse();
if (scopeNode.getAllScopeVars().containsKey(name))
{
addError("Duplicated type name", node);
} else
{
scopeNode.getLocalScopeVars().put(name, var);
}
// Parse the slots
var.parseSlots();
break;
}
}
// Now do all the local scopes / variables
for (AstNode node : astRoot.getChildren())
{
if (node.getKind() == AstKind.AST_TYPE_DEF)
{
for (FanAstScopeVarBase var : node.getLocalScopeVars().values())
{
// should be slots
AstNode bkNode = var.getNode();
AstNode blockNode = FanLexAstUtils.getFirstChild(bkNode, new NodeKindPredicate(AstKind.AST_BLOCK));
if (blockNode != null)
{
parseVars(blockNode, null);
}
}
}
}
FanLexAstUtils.dumpTree(astRoot, 0);
}
//TODO: don't show the whole stack of errors, but just the base.
// esp. for expressions, calls etc...
private void parseVars(AstNode node, FanResolvedType type)
{
if (node == null)
{
return;
}
String text = node.getNodeText(true);
List<AstNode> children = node.getChildren();
switch (node.getKind())
{
case AST_CLOSURE:
AstNode closureBlock = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_BLOCK));
FanResolvedType retType = FanResolvedType.makeFromDbType(node, "sys::Void");
for (AstNode child : children)
{
if (child.getKind() == AstKind.AST_FORMAL)
{
AstNode formalName = FanLexAstUtils.getFirstChild(child, new NodeKindPredicate(AstKind.AST_ID));
AstNode formalTypeAndId = FanLexAstUtils.getFirstChild(child, new NodeKindPredicate(AstKind.AST_TYPE_AND_ID));
// TODO: try to deal with inference ??
FanResolvedType fType = FanResolvedType.makeFromDbType(child, "sys::Obj");
if (formalTypeAndId != null)
{ // if inferred this is null
formalName = FanLexAstUtils.getFirstChild(formalTypeAndId, new NodeKindPredicate(AstKind.AST_ID));
AstNode formalType = FanLexAstUtils.getFirstChild(formalTypeAndId, new NodeKindPredicate(AstKind.AST_TYPE));
parseVars(formalType, null);
fType = formalType.getType();
}
// add the formals vars to the closure block scope
closureBlock.addScopeVar(formalName.getNodeText(true), VarKind.LOCAL, fType, true);
}
if (child.getKind() == AstKind.AST_TYPE)
{
// save the returned type
parseVars(child, type);
retType = child.getType();
}
if (child.getKind() == AstKind.AST_BLOCK)
{
// parse the block content
parseVars(child, type);
}
}
type = retType;
break;
case AST_EXPR_INDEX:
parseChildren(node);
FanResolvedType slotType = FanResolvedType.resolveSlotType(type, "get");
if (type instanceof FanResolvedListType)
{
type = ((FanResolvedListType) type).getItemType();
} else if (type instanceof FanResolvedMapType)
{
type = ((FanResolvedMapType) type).getValType();
} //Can also use index expression on any type with a get method
else if (slotType != null && slotType.isResolved())
{
type = slotType;
} else
{
type = null;
node.getRoot().getParserTask().addError("Index expression only valid on lists, maps -> " + text, node);
}
// TODO: check if list/map index key type is valid ?
break;
case AST_EXPR:
case AST_EXPR_ASSIGN: // with the assignment we need reset type to null (start a new expression)
case AST_EXPR_MULT:
case AST_EXPR_ADD:
// TODO: validate assignment type is compatible.
boolean first = true;
type = null;
for (AstNode child : children)
{
parseVars(child, type);
// Those kinds take the right hand side type
// It block chnages the type because it makes it NOT staticContext
if (first || child.getKind() == AstKind.AST_EXPR_CALL || child.getKind() == AstKind.AST_EXPR_TYPE_CHECK
|| child.getKind() == AstKind.AST_EXPR_RANGE || child.getKind() == AstKind.AST_EXPR_ASSIGN || child.getKind()==AstKind.AST_EXPR_LIT_BASE
|| child.getKind() == AstKind.AST_IT_BLOCK)
{
type = child.getType();
}
first = false;
}
break;
case AST_EXPR_CALL:
AstNode callChild = children.get(0);
String slotName = callChild.getNodeText(true);
//if a direct call like doThis(), then use this type as base
if (type == null)
{
type = FanResolvedType.makeFromLocalID(callChild, slotName);
} else
// otherwise a slot of the base type like var.toStr()
{
type = FanResolvedType.resolveSlotType(type, slotName);
}
List<AstNode> args = FanLexAstUtils.getChildren(node, new NodeKindPredicate(AstKind.AST_ARG));
for (AstNode arg : args)
{
parseVars(arg, null);
}
//TODO: Check that param types matches slot declaration
AstNode closure = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_CLOSURE));
if (closure != null)
{
- parseVars(closure, null);
+ parseVars(closure, type);
}
break;
case AST_ARG:
// arg contains one expression - parse it to check for errors
AstNode argExprNode = node.getChildren().get(0);
parseVars(argExprNode, null);
type = argExprNode.getType();
break;
case AST_EXR_CAST:
parseChildren(node);
AstNode castTypeNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_TYPE));
type = castTypeNode.getType();
//TODO: check if cast is valid
break;
case AST_EXPR_TYPE_CHECK:
parseChildren(node);
AstNode checkType = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_TYPE));
if(text.startsWith("as")) // (cast)
type = checkType.getType();
else if(text.startsWith("is")) // is or isnot -> boolean
type = FanResolvedType.makeFromDbType(node, "sys::Bool");
else
type = null; // shouldn't happen
break;
case AST_EXPR_RANGE:
parseChildren(node);
AstNode rangeType = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_CHILD));
type = new FanResolvedListType(node, rangeType.getType()); // list of
break;
case AST_IT_BLOCK:
// introduce itblock scope variables
if (type != null && type.getDbType() != null)
{
type.setStaticContext(false);
List<FanSlot> itSlots = FanSlot.getAllSlotsForType(type.getDbType().getQualifiedName(), false);
for (FanSlot itSlot : itSlots)
{
FanAstScopeVarBase newVar = new FanLocalScopeVar(node, itSlot, itSlot.getName());
node.addScopeVar(newVar, true);
}
// add "it" to scope
FanAstScopeVarBase itVar = new FanLocalScopeVar(node, VarKind.IMPLIED, "it", type);
node.addScopeVar(itVar, true);
}
parseChildren(node);
break;
case AST_EXPR_LIT_BASE:
Node<AstNode> parseNode = node.getParseNode().getChildren().get(0); // firstOf
type = resolveLitteral(node, parseNode);
break;
case AST_ID:
type = FanResolvedType.makeFromLocalID(node, text);
break;
case AST_TYPE:
type = FanResolvedType.fromTypeSig(node, text);
break;
case AST_LOCAL_DEF: // special case, since it introduces scope vars
AstNode typeAndIdNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_TYPE_AND_ID));
AstNode idNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_ID));
AstNode exprNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_EXPR));
if (typeAndIdNode != null)
{
idNode = FanLexAstUtils.getFirstChild(typeAndIdNode, new NodeKindPredicate(AstKind.AST_ID));
AstNode typeNode = FanLexAstUtils.getFirstChild(typeAndIdNode, new NodeKindPredicate(AstKind.AST_TYPE));
parseVars(typeNode, null);
type = typeNode.getType();
}
String name = idNode.getNodeText(true);
if (exprNode != null)
{
parseVars(exprNode, null);
if (type == null) // Prefer the type in TypeNode if specified
{
type = exprNode.getType();
//TODO: check types are compatible
}
}
if (type != null)
{
type.setStaticContext(false);
}
node.addScopeVar(new FanLocalScopeVar(node, VarKind.LOCAL, name, type), false);
break;
default:
// recurse into children
parseChildren(node);
}
//TODO: always parse children rather than in individual cases.
System.out.println("ND_TYPE:" + node + " -> " + type);
node.setType(type);
if (type != null && !type.isResolved())
{
node.getRoot().getParserTask().addError("Could not resolve item -> " + text, node);
}
}
private void parseChildren(AstNode node)
{
for (AstNode child : node.getChildren())
{
parseVars(child, null);
}
}
public FanResolvedType resolveLitteral(AstNode astNode, Node<AstNode> parseNode)
{
FanResolvedType type = FanResolvedType.makeUnresolved(astNode);
String lbl = parseNode.getLabel();
String txt = astNode.getNodeText(true);
if (lbl.equalsIgnoreCase(TokenName.ID.name()))
{
type = FanResolvedType.makeFromLocalID(astNode, txt);
} else if (lbl.equalsIgnoreCase(TokenName.CHAR_.name()))
{
type = FanResolvedType.fromTypeSig(astNode, "sys::Int");
} else if (lbl.equalsIgnoreCase(TokenName.NUMBER.name()))
{
char lastChar = txt.charAt(txt.length() - 1);
if (lastChar == 'f' || lastChar == 'F')
{
type = FanResolvedType.fromTypeSig(astNode, "sys::Float");
} else if (lastChar == 'd' || lastChar == 'D')
{
type = FanResolvedType.fromTypeSig(astNode, "sys::Decimal");
} else if (Character.isLetter(lastChar) && lastChar != '_')
{
type = FanResolvedType.fromTypeSig(astNode, "sys::Duration");
} else if (txt.indexOf(".") != -1)
{
type = FanResolvedType.fromTypeSig(astNode, "sys::Float");
} else
{
type = FanResolvedType.fromTypeSig(astNode, "sys::Int"); // Default
}
} else if (lbl.equalsIgnoreCase(TokenName.STRS.name()))
{
type = FanResolvedType.fromTypeSig(astNode, "sys::Str");
} else if (lbl.equalsIgnoreCase(TokenName.URI.name()))
{
type = FanResolvedType.fromTypeSig(astNode, "sys::Uri");
} else if (lbl.equals("true") || lbl.equals("false"))
{
type = FanResolvedType.fromTypeSig(astNode, "sys::Bool");
}
else if (lbl.equals("null"))
{
type = new FanResolvedNullType(astNode);
}
else if (lbl.equals("it"))
{
FanAstScopeVarBase var = astNode.getAllScopeVars().get("it");
if(var!=null)
type = var.getType();
type.setStaticContext(false);
}
else if (lbl.equals("this"))
{
type = FanResolvedType.resolveThisType(astNode);
type.setStaticContext(false);
}
else if (lbl.equals("super"))
{
type = FanResolvedType.resolveSuper(astNode);
type.setStaticContext(false);
}
return type;
}
private void addUsing(AstNode usingNode)
{
String type = FanLexAstUtils.getFirstChildText(usingNode, new NodeKindPredicate(AstKind.AST_ID));
String as = FanLexAstUtils.getFirstChildText(usingNode, new NodeKindPredicate(AstKind.AST_USING_AS));
String ffi = FanLexAstUtils.getFirstChildText(usingNode, new NodeKindPredicate(AstKind.AST_USING_FFI));
String name = as != null ? as : type;
if (name.indexOf("::") > -1)
{
name = name.substring(name.indexOf("::") + 2);
}
if (ffi != null && ffi.toLowerCase().equals("java"))
{
if (type.indexOf("::") != -1)
{
// Individual Item
String qname = type.replaceAll("::", "\\.");
if (FanType.findByQualifiedName(qname) == null)
{
addError("Unresolved Java Item: " + qname, usingNode);
} else
{
addUsing(name, qname, usingNode);
}
} else
{
// whole package
if (!FanType.hasPod(name))
{
addError("Unresolved Java package: " + name, usingNode);
} else
{
Vector<FanType> items = FanType.findPodTypes(name, "");
for (FanType t : items)
{
addUsing(t.getSimpleName(), t.getQualifiedName(), usingNode);
}
}
}
} else
{
if (type.indexOf("::") > 0)
{
// Adding a specific type
String[] data = type.split("::");
if (!FanType.hasPod(data[0]))
{
addError("Unresolved Pod: " + data[0], usingNode);
} else if (FanType.findByQualifiedName(type) == null)
{
addError("Unresolved Type: " + type, usingNode);
}
//Type t = FanPodIndexer.getInstance().getPodType(data[0], data[1]);
addUsing(name, type, usingNode);
} else
{
// Adding all the types of a Pod
if (name.equalsIgnoreCase("sys")) // sys is always avail.
{
return;
}
if (!FanType.hasPod(name))
{
addError("Unresolved Pod: " + name, usingNode);
} else
{
Vector<FanType> items = FanType.findPodTypes(name, "");
for (FanType t : items)
{
addUsing(t.getSimpleName(), t.getQualifiedName(), usingNode);
}
}
}
}
}
private void addUsing(String name, String qType, AstNode node)
{
AstNode scopeNode = FanLexAstUtils.getScopeNode(node);
if (scopeNode == null)
{
return;
}
if (scopeNode.getLocalScopeVars().containsKey(name))
{
// This is 'legal' ... maybe show a warning later ?
//addError("Duplicated using: " + qType + " / " + scopeNode.getLocalScopeVars().get(name), node);
System.out.println("Already have a using called: " + qType + " (" + scopeNode.getLocalScopeVars().get(name) + ")");
// Note: only keeping the 'last' definition (ie: override)
}
FanType type = FanType.findByPodAndType("sys", name);
if (type != null)
{
/*if (type.getPod().equals("sys"))
{
addError("Duplicated using: " + qType + " / " + "sys::" + name, node);
}*/
}
FanResolvedType rType = FanResolvedType.makeFromDbType(node, qType);
rType.setStaticContext(true);
scopeNode.addScopeVar(name, FanAstScopeVar.VarKind.IMPORT, rType, true);
}
public ParsingResult<AstNode> getParsingResult()
{
return parsingResult;
}
public String getPod()
{
return pod;
}
/**
* TODO: this whole prunning stuff is a bit ugly
* Should try to buod the AST properly using technizues here:
* http://parboiled.hostingdelivered.com/viewtopic.php?f=3&t=9
*
* During ParseNode construction, some astNodes that migth have been constructed from
* some parseNode that where then "backtracked" (not the whoel sequence matched)
* This looks for and remove those unwanted nodes.
* @param node
*/
private void prune(AstNode node)
{
Node<AstNode> rtNode=astRoot.getParseNode();
String rootLabel = "n/a";
while(rtNode!=null)
{
rootLabel = rtNode.getLabel();
rtNode=rtNode.getParent();
}
List<AstNode> children = node.getChildren();
List<AstNode> toBepruned = new ArrayList<AstNode>();
for (AstNode child : children)
{
Node<AstNode> parseNode = child.getParseNode();
// If the node is orphaned (no link back to the root), that means it was backtracked out of.
String label = "N/A";
while(parseNode!=null)
{
label = parseNode.getLabel();
parseNode = parseNode.getParent();
}
if ( ! rootLabel.equals(label))
{
toBepruned.add(child);
} else
{
// recurse into children
prune(child);
}
}
// Drop the orphaned nodes
for (AstNode nd : toBepruned)
{
children.remove(nd);
}
}
}
| true | true | private void parseVars(AstNode node, FanResolvedType type)
{
if (node == null)
{
return;
}
String text = node.getNodeText(true);
List<AstNode> children = node.getChildren();
switch (node.getKind())
{
case AST_CLOSURE:
AstNode closureBlock = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_BLOCK));
FanResolvedType retType = FanResolvedType.makeFromDbType(node, "sys::Void");
for (AstNode child : children)
{
if (child.getKind() == AstKind.AST_FORMAL)
{
AstNode formalName = FanLexAstUtils.getFirstChild(child, new NodeKindPredicate(AstKind.AST_ID));
AstNode formalTypeAndId = FanLexAstUtils.getFirstChild(child, new NodeKindPredicate(AstKind.AST_TYPE_AND_ID));
// TODO: try to deal with inference ??
FanResolvedType fType = FanResolvedType.makeFromDbType(child, "sys::Obj");
if (formalTypeAndId != null)
{ // if inferred this is null
formalName = FanLexAstUtils.getFirstChild(formalTypeAndId, new NodeKindPredicate(AstKind.AST_ID));
AstNode formalType = FanLexAstUtils.getFirstChild(formalTypeAndId, new NodeKindPredicate(AstKind.AST_TYPE));
parseVars(formalType, null);
fType = formalType.getType();
}
// add the formals vars to the closure block scope
closureBlock.addScopeVar(formalName.getNodeText(true), VarKind.LOCAL, fType, true);
}
if (child.getKind() == AstKind.AST_TYPE)
{
// save the returned type
parseVars(child, type);
retType = child.getType();
}
if (child.getKind() == AstKind.AST_BLOCK)
{
// parse the block content
parseVars(child, type);
}
}
type = retType;
break;
case AST_EXPR_INDEX:
parseChildren(node);
FanResolvedType slotType = FanResolvedType.resolveSlotType(type, "get");
if (type instanceof FanResolvedListType)
{
type = ((FanResolvedListType) type).getItemType();
} else if (type instanceof FanResolvedMapType)
{
type = ((FanResolvedMapType) type).getValType();
} //Can also use index expression on any type with a get method
else if (slotType != null && slotType.isResolved())
{
type = slotType;
} else
{
type = null;
node.getRoot().getParserTask().addError("Index expression only valid on lists, maps -> " + text, node);
}
// TODO: check if list/map index key type is valid ?
break;
case AST_EXPR:
case AST_EXPR_ASSIGN: // with the assignment we need reset type to null (start a new expression)
case AST_EXPR_MULT:
case AST_EXPR_ADD:
// TODO: validate assignment type is compatible.
boolean first = true;
type = null;
for (AstNode child : children)
{
parseVars(child, type);
// Those kinds take the right hand side type
// It block chnages the type because it makes it NOT staticContext
if (first || child.getKind() == AstKind.AST_EXPR_CALL || child.getKind() == AstKind.AST_EXPR_TYPE_CHECK
|| child.getKind() == AstKind.AST_EXPR_RANGE || child.getKind() == AstKind.AST_EXPR_ASSIGN || child.getKind()==AstKind.AST_EXPR_LIT_BASE
|| child.getKind() == AstKind.AST_IT_BLOCK)
{
type = child.getType();
}
first = false;
}
break;
case AST_EXPR_CALL:
AstNode callChild = children.get(0);
String slotName = callChild.getNodeText(true);
//if a direct call like doThis(), then use this type as base
if (type == null)
{
type = FanResolvedType.makeFromLocalID(callChild, slotName);
} else
// otherwise a slot of the base type like var.toStr()
{
type = FanResolvedType.resolveSlotType(type, slotName);
}
List<AstNode> args = FanLexAstUtils.getChildren(node, new NodeKindPredicate(AstKind.AST_ARG));
for (AstNode arg : args)
{
parseVars(arg, null);
}
//TODO: Check that param types matches slot declaration
AstNode closure = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_CLOSURE));
if (closure != null)
{
parseVars(closure, null);
}
break;
case AST_ARG:
// arg contains one expression - parse it to check for errors
AstNode argExprNode = node.getChildren().get(0);
parseVars(argExprNode, null);
type = argExprNode.getType();
break;
case AST_EXR_CAST:
parseChildren(node);
AstNode castTypeNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_TYPE));
type = castTypeNode.getType();
//TODO: check if cast is valid
break;
case AST_EXPR_TYPE_CHECK:
parseChildren(node);
AstNode checkType = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_TYPE));
if(text.startsWith("as")) // (cast)
type = checkType.getType();
else if(text.startsWith("is")) // is or isnot -> boolean
type = FanResolvedType.makeFromDbType(node, "sys::Bool");
else
type = null; // shouldn't happen
break;
case AST_EXPR_RANGE:
parseChildren(node);
AstNode rangeType = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_CHILD));
type = new FanResolvedListType(node, rangeType.getType()); // list of
break;
case AST_IT_BLOCK:
// introduce itblock scope variables
if (type != null && type.getDbType() != null)
{
type.setStaticContext(false);
List<FanSlot> itSlots = FanSlot.getAllSlotsForType(type.getDbType().getQualifiedName(), false);
for (FanSlot itSlot : itSlots)
{
FanAstScopeVarBase newVar = new FanLocalScopeVar(node, itSlot, itSlot.getName());
node.addScopeVar(newVar, true);
}
// add "it" to scope
FanAstScopeVarBase itVar = new FanLocalScopeVar(node, VarKind.IMPLIED, "it", type);
node.addScopeVar(itVar, true);
}
parseChildren(node);
break;
case AST_EXPR_LIT_BASE:
Node<AstNode> parseNode = node.getParseNode().getChildren().get(0); // firstOf
type = resolveLitteral(node, parseNode);
break;
case AST_ID:
type = FanResolvedType.makeFromLocalID(node, text);
break;
case AST_TYPE:
type = FanResolvedType.fromTypeSig(node, text);
break;
case AST_LOCAL_DEF: // special case, since it introduces scope vars
AstNode typeAndIdNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_TYPE_AND_ID));
AstNode idNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_ID));
AstNode exprNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_EXPR));
if (typeAndIdNode != null)
{
idNode = FanLexAstUtils.getFirstChild(typeAndIdNode, new NodeKindPredicate(AstKind.AST_ID));
AstNode typeNode = FanLexAstUtils.getFirstChild(typeAndIdNode, new NodeKindPredicate(AstKind.AST_TYPE));
parseVars(typeNode, null);
type = typeNode.getType();
}
String name = idNode.getNodeText(true);
if (exprNode != null)
{
parseVars(exprNode, null);
if (type == null) // Prefer the type in TypeNode if specified
{
type = exprNode.getType();
//TODO: check types are compatible
}
}
if (type != null)
{
type.setStaticContext(false);
}
node.addScopeVar(new FanLocalScopeVar(node, VarKind.LOCAL, name, type), false);
break;
default:
// recurse into children
parseChildren(node);
}
//TODO: always parse children rather than in individual cases.
System.out.println("ND_TYPE:" + node + " -> " + type);
node.setType(type);
if (type != null && !type.isResolved())
{
node.getRoot().getParserTask().addError("Could not resolve item -> " + text, node);
}
}
| private void parseVars(AstNode node, FanResolvedType type)
{
if (node == null)
{
return;
}
String text = node.getNodeText(true);
List<AstNode> children = node.getChildren();
switch (node.getKind())
{
case AST_CLOSURE:
AstNode closureBlock = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_BLOCK));
FanResolvedType retType = FanResolvedType.makeFromDbType(node, "sys::Void");
for (AstNode child : children)
{
if (child.getKind() == AstKind.AST_FORMAL)
{
AstNode formalName = FanLexAstUtils.getFirstChild(child, new NodeKindPredicate(AstKind.AST_ID));
AstNode formalTypeAndId = FanLexAstUtils.getFirstChild(child, new NodeKindPredicate(AstKind.AST_TYPE_AND_ID));
// TODO: try to deal with inference ??
FanResolvedType fType = FanResolvedType.makeFromDbType(child, "sys::Obj");
if (formalTypeAndId != null)
{ // if inferred this is null
formalName = FanLexAstUtils.getFirstChild(formalTypeAndId, new NodeKindPredicate(AstKind.AST_ID));
AstNode formalType = FanLexAstUtils.getFirstChild(formalTypeAndId, new NodeKindPredicate(AstKind.AST_TYPE));
parseVars(formalType, null);
fType = formalType.getType();
}
// add the formals vars to the closure block scope
closureBlock.addScopeVar(formalName.getNodeText(true), VarKind.LOCAL, fType, true);
}
if (child.getKind() == AstKind.AST_TYPE)
{
// save the returned type
parseVars(child, type);
retType = child.getType();
}
if (child.getKind() == AstKind.AST_BLOCK)
{
// parse the block content
parseVars(child, type);
}
}
type = retType;
break;
case AST_EXPR_INDEX:
parseChildren(node);
FanResolvedType slotType = FanResolvedType.resolveSlotType(type, "get");
if (type instanceof FanResolvedListType)
{
type = ((FanResolvedListType) type).getItemType();
} else if (type instanceof FanResolvedMapType)
{
type = ((FanResolvedMapType) type).getValType();
} //Can also use index expression on any type with a get method
else if (slotType != null && slotType.isResolved())
{
type = slotType;
} else
{
type = null;
node.getRoot().getParserTask().addError("Index expression only valid on lists, maps -> " + text, node);
}
// TODO: check if list/map index key type is valid ?
break;
case AST_EXPR:
case AST_EXPR_ASSIGN: // with the assignment we need reset type to null (start a new expression)
case AST_EXPR_MULT:
case AST_EXPR_ADD:
// TODO: validate assignment type is compatible.
boolean first = true;
type = null;
for (AstNode child : children)
{
parseVars(child, type);
// Those kinds take the right hand side type
// It block chnages the type because it makes it NOT staticContext
if (first || child.getKind() == AstKind.AST_EXPR_CALL || child.getKind() == AstKind.AST_EXPR_TYPE_CHECK
|| child.getKind() == AstKind.AST_EXPR_RANGE || child.getKind() == AstKind.AST_EXPR_ASSIGN || child.getKind()==AstKind.AST_EXPR_LIT_BASE
|| child.getKind() == AstKind.AST_IT_BLOCK)
{
type = child.getType();
}
first = false;
}
break;
case AST_EXPR_CALL:
AstNode callChild = children.get(0);
String slotName = callChild.getNodeText(true);
//if a direct call like doThis(), then use this type as base
if (type == null)
{
type = FanResolvedType.makeFromLocalID(callChild, slotName);
} else
// otherwise a slot of the base type like var.toStr()
{
type = FanResolvedType.resolveSlotType(type, slotName);
}
List<AstNode> args = FanLexAstUtils.getChildren(node, new NodeKindPredicate(AstKind.AST_ARG));
for (AstNode arg : args)
{
parseVars(arg, null);
}
//TODO: Check that param types matches slot declaration
AstNode closure = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_CLOSURE));
if (closure != null)
{
parseVars(closure, type);
}
break;
case AST_ARG:
// arg contains one expression - parse it to check for errors
AstNode argExprNode = node.getChildren().get(0);
parseVars(argExprNode, null);
type = argExprNode.getType();
break;
case AST_EXR_CAST:
parseChildren(node);
AstNode castTypeNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_TYPE));
type = castTypeNode.getType();
//TODO: check if cast is valid
break;
case AST_EXPR_TYPE_CHECK:
parseChildren(node);
AstNode checkType = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_TYPE));
if(text.startsWith("as")) // (cast)
type = checkType.getType();
else if(text.startsWith("is")) // is or isnot -> boolean
type = FanResolvedType.makeFromDbType(node, "sys::Bool");
else
type = null; // shouldn't happen
break;
case AST_EXPR_RANGE:
parseChildren(node);
AstNode rangeType = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_CHILD));
type = new FanResolvedListType(node, rangeType.getType()); // list of
break;
case AST_IT_BLOCK:
// introduce itblock scope variables
if (type != null && type.getDbType() != null)
{
type.setStaticContext(false);
List<FanSlot> itSlots = FanSlot.getAllSlotsForType(type.getDbType().getQualifiedName(), false);
for (FanSlot itSlot : itSlots)
{
FanAstScopeVarBase newVar = new FanLocalScopeVar(node, itSlot, itSlot.getName());
node.addScopeVar(newVar, true);
}
// add "it" to scope
FanAstScopeVarBase itVar = new FanLocalScopeVar(node, VarKind.IMPLIED, "it", type);
node.addScopeVar(itVar, true);
}
parseChildren(node);
break;
case AST_EXPR_LIT_BASE:
Node<AstNode> parseNode = node.getParseNode().getChildren().get(0); // firstOf
type = resolveLitteral(node, parseNode);
break;
case AST_ID:
type = FanResolvedType.makeFromLocalID(node, text);
break;
case AST_TYPE:
type = FanResolvedType.fromTypeSig(node, text);
break;
case AST_LOCAL_DEF: // special case, since it introduces scope vars
AstNode typeAndIdNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_TYPE_AND_ID));
AstNode idNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_ID));
AstNode exprNode = FanLexAstUtils.getFirstChild(node, new NodeKindPredicate(AstKind.AST_EXPR));
if (typeAndIdNode != null)
{
idNode = FanLexAstUtils.getFirstChild(typeAndIdNode, new NodeKindPredicate(AstKind.AST_ID));
AstNode typeNode = FanLexAstUtils.getFirstChild(typeAndIdNode, new NodeKindPredicate(AstKind.AST_TYPE));
parseVars(typeNode, null);
type = typeNode.getType();
}
String name = idNode.getNodeText(true);
if (exprNode != null)
{
parseVars(exprNode, null);
if (type == null) // Prefer the type in TypeNode if specified
{
type = exprNode.getType();
//TODO: check types are compatible
}
}
if (type != null)
{
type.setStaticContext(false);
}
node.addScopeVar(new FanLocalScopeVar(node, VarKind.LOCAL, name, type), false);
break;
default:
// recurse into children
parseChildren(node);
}
//TODO: always parse children rather than in individual cases.
System.out.println("ND_TYPE:" + node + " -> " + type);
node.setType(type);
if (type != null && !type.isResolved())
{
node.getRoot().getParserTask().addError("Could not resolve item -> " + text, node);
}
}
|
diff --git a/src/org/gearman/Main.java b/src/org/gearman/Main.java
index b65ddcd..7bf02b7 100755
--- a/src/org/gearman/Main.java
+++ b/src/org/gearman/Main.java
@@ -1,105 +1,105 @@
package org.gearman;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import org.gearman.util.ArgumentParser;
import org.gearman.util.ArgumentParser.Option;
/**
* The class that starts the standalone server
* @author isaiah.v
*/
class Main {
private static String VERSION = "java-gearman-service-0.1";
private static String HELP =
VERSION + "\n" +
"\n" +
"usage:\n" +
"java [jvm options] -jar "+VERSION+".jar [server options]\n" +
"\n" +
"Options:\n" +
" -p PORT --port=PORT Defines what port number the server will listen on (Default: 4730)\n" +
" -v --version Display the version of java gearman service and exit\n" +
" -? --help Print this help menu and exit";
/**
* Prints the current version and
* @param out
*/
private static final void printHelp(PrintStream out) {
out.println(HELP);
System.exit(0);
}
private static final void printVersion() {
System.out.println(VERSION);
System.exit(0);
}
/**
* Starts the standalone gearman job server.
* @throws IOException
*/
public static void main(final String[] args) {
try {
Gearman gearman = new Gearman();
gearman.createGearmanServer().openPort(new Main(args).getPort());
} catch (Throwable th) {
System.err.println(th.getMessage());
System.err.println();
printHelp(System.err);
}
}
private int port = 4730;
private Main(final String[] args) {
final ArgumentParser ap = new ArgumentParser();
boolean t1, t2, t3;
t1 = ap.addOption('p', "port", true);
t2 = ap.addOption('v', "version", false);
t3 = ap.addOption('?', "help", false);
assert t1&&t2&&t3;
ArrayList<String> arguments = ap.parse(args);
if(arguments==null) {
System.err.println("argument parsing failed");
System.err.println();
printHelp(System.err);
} else if(!arguments.isEmpty()) {
- System.err.print("recived unexspected arguments:");
+ System.err.print("received unexpected arguments:");
for(String arg : arguments) {
System.err.print(" "+arg);
}
System.err.println('\n');
printHelp(System.err);
}
for(Option op : ap) {
switch(op.getShortName()) {
case 'p':
try {
this.port = Integer.parseInt(op.getValue());
} catch(NumberFormatException nfe) {
System.err.println("failed to parse port to integer: "+op.getValue());
System.err.println();
printHelp(System.err);
}
break;
case 'v':
printVersion();
case 'h':
printHelp(System.out);
}
}
}
private int getPort() {
return this.port;
}
}
| true | true | private Main(final String[] args) {
final ArgumentParser ap = new ArgumentParser();
boolean t1, t2, t3;
t1 = ap.addOption('p', "port", true);
t2 = ap.addOption('v', "version", false);
t3 = ap.addOption('?', "help", false);
assert t1&&t2&&t3;
ArrayList<String> arguments = ap.parse(args);
if(arguments==null) {
System.err.println("argument parsing failed");
System.err.println();
printHelp(System.err);
} else if(!arguments.isEmpty()) {
System.err.print("recived unexspected arguments:");
for(String arg : arguments) {
System.err.print(" "+arg);
}
System.err.println('\n');
printHelp(System.err);
}
for(Option op : ap) {
switch(op.getShortName()) {
case 'p':
try {
this.port = Integer.parseInt(op.getValue());
} catch(NumberFormatException nfe) {
System.err.println("failed to parse port to integer: "+op.getValue());
System.err.println();
printHelp(System.err);
}
break;
case 'v':
printVersion();
case 'h':
printHelp(System.out);
}
}
}
| private Main(final String[] args) {
final ArgumentParser ap = new ArgumentParser();
boolean t1, t2, t3;
t1 = ap.addOption('p', "port", true);
t2 = ap.addOption('v', "version", false);
t3 = ap.addOption('?', "help", false);
assert t1&&t2&&t3;
ArrayList<String> arguments = ap.parse(args);
if(arguments==null) {
System.err.println("argument parsing failed");
System.err.println();
printHelp(System.err);
} else if(!arguments.isEmpty()) {
System.err.print("received unexpected arguments:");
for(String arg : arguments) {
System.err.print(" "+arg);
}
System.err.println('\n');
printHelp(System.err);
}
for(Option op : ap) {
switch(op.getShortName()) {
case 'p':
try {
this.port = Integer.parseInt(op.getValue());
} catch(NumberFormatException nfe) {
System.err.println("failed to parse port to integer: "+op.getValue());
System.err.println();
printHelp(System.err);
}
break;
case 'v':
printVersion();
case 'h':
printHelp(System.out);
}
}
}
|
diff --git a/caintegrator2-war/src/gov/nih/nci/caintegrator2/external/ncia/NCIADicomJobRunnerImpl.java b/caintegrator2-war/src/gov/nih/nci/caintegrator2/external/ncia/NCIADicomJobRunnerImpl.java
index 8b2a257f4..219287cfd 100644
--- a/caintegrator2-war/src/gov/nih/nci/caintegrator2/external/ncia/NCIADicomJobRunnerImpl.java
+++ b/caintegrator2-war/src/gov/nih/nci/caintegrator2/external/ncia/NCIADicomJobRunnerImpl.java
@@ -1,235 +1,235 @@
/**
* The software subject to this notice and license includes both human readable
* source code form and machine readable, binary, object code form. The caArray
* Software was developed in conjunction with the National Cancer Institute
* (NCI) by NCI employees, 5AM Solutions, Inc. (5AM), ScenPro, Inc. (ScenPro)
* and Science Applications International Corporation (SAIC). To the extent
* government employees are authors, any rights in such works shall be subject
* to Title 17 of the United States Code, section 105.
*
* This caArray Software License (the License) is between NCI and You. You (or
* Your) shall mean a person or an entity, and all other entities that control,
* are controlled by, or are under common control with the entity. Control for
* purposes of this definition means (i) the direct or indirect power to cause
* the direction or management of such entity, whether by contract or otherwise,
* or (ii) ownership of fifty percent (50%) or more of the outstanding shares,
* or (iii) beneficial ownership of such entity.
*
* This License is granted provided that You agree to the conditions described
* below. NCI grants You a non-exclusive, worldwide, perpetual, fully-paid-up,
* no-charge, irrevocable, transferable and royalty-free right and license in
* its rights in the caArray Software to (i) use, install, access, operate,
* execute, copy, modify, translate, market, publicly display, publicly perform,
* and prepare derivative works of the caArray Software; (ii) distribute and
* have distributed to and by third parties the caIntegrator Software and any
* modifications and derivative works thereof; and (iii) sublicense the
* foregoing rights set out in (i) and (ii) to third parties, including the
* right to license such rights to further third parties. For sake of clarity,
* and not by way of limitation, NCI shall have no right of accounting or right
* of payment from You or Your sub-licensees for the rights granted under this
* License. This License is granted at no charge to You.
*
* Your redistributions of the source code for the Software must retain the
* above copyright notice, this list of conditions and the disclaimer and
* limitation of liability of Article 6, below. Your redistributions in object
* code form must reproduce the above copyright notice, this list of conditions
* and the disclaimer of Article 6 in the documentation and/or other materials
* provided with the distribution, if any.
*
* Your end-user documentation included with the redistribution, if any, must
* include the following acknowledgment: This product includes software
* developed by 5AM, ScenPro, SAIC and the National Cancer Institute. If You do
* not include such end-user documentation, You shall include this acknowledgment
* in the Software itself, wherever such third-party acknowledgments normally
* appear.
*
* You may not use the names "The National Cancer Institute", "NCI", "ScenPro",
* "SAIC" or "5AM" to endorse or promote products derived from this Software.
* This License does not authorize You to use any trademarks, service marks,
* trade names, logos or product names of either NCI, ScenPro, SAID or 5AM,
* except as required to comply with the terms of this License.
*
* For sake of clarity, and not by way of limitation, You may incorporate this
* Software into Your proprietary programs and into any third party proprietary
* programs. However, if You incorporate the Software into third party
* proprietary programs, You agree that You are solely responsible for obtaining
* any permission from such third parties required to incorporate the Software
* into such third party proprietary programs and for informing Your a
* sub-licensees, including without limitation Your end-users, of their
* obligation to secure any required permissions from such third parties before
* incorporating the Software into such third party proprietary software
* programs. In the event that You fail to obtain such permissions, You agree
* to indemnify NCI for any claims against NCI by such third parties, except to
* the extent prohibited by law, resulting from Your failure to obtain such
* permissions.
*
* For sake of clarity, and not by way of limitation, You may add Your own
* copyright statement to Your modifications and to the derivative works, and
* You may provide additional or different license terms and conditions in Your
* sublicenses of modifications of the Software, or any derivative works of the
* Software as a whole, provided Your use, reproduction, and distribution of the
* Work otherwise complies with the conditions stated in this License.
*
* THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES,
* (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO
* EVENT SHALL THE NATIONAL CANCER INSTITUTE, 5AM SOLUTIONS, INC., SCENPRO, INC.,
* SCIENCE APPLICATIONS INTERNATIONAL CORPORATION OR THEIR
* AFFILIATES 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 gov.nih.nci.caintegrator2.external.ncia;
import gov.nih.nci.cagrid.ncia.client.NCIACoreServiceClient;
import gov.nih.nci.caintegrator2.common.Cai2Util;
import gov.nih.nci.caintegrator2.external.ConnectionException;
import gov.nih.nci.caintegrator2.file.FileManager;
import gov.nih.nci.ivi.utils.ZipEntryInputStream;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.rmi.RemoteException;
import java.util.zip.ZipInputStream;
import org.apache.axis.types.URI.MalformedURIException;
import org.cagrid.transfer.context.client.TransferServiceContextClient;
import org.cagrid.transfer.context.client.helper.TransferClientHelper;
import org.cagrid.transfer.context.stubs.types.TransferServiceContextReference;
/**
* Class to deal with retrieving and temporarily storing DICOM files from NCIA through the grid.
*/
public class NCIADicomJobRunnerImpl implements NCIADicomJobRunner {
private static final Integer BUFFER_SIZE = 8192;
private static final String REMOTE_CONNECTION_FAILED = "Remote Connection Failed.";
private static final String IMAGE_SERIES_DIR = "SERIES_";
private static final String IMAGE_STUDY_DIR = "STUDY_";
private final File temporaryStorageDirectory;
private final NCIADicomJob job;
/**
* Public Constructor.
* @param fileManager determines where to place the temporary storage directory.
* @param job task that needs to run.
*/
public NCIADicomJobRunnerImpl(FileManager fileManager, NCIADicomJob job) {
temporaryStorageDirectory = fileManager.getNewTemporaryDirectory(job.getJobId());
this.job = job;
}
/**
* {@inheritDoc}
*/
public File retrieveDicomFiles() throws ConnectionException {
if (!job.hasData()) {
return null;
}
try {
NCIACoreServiceClient client = new NCIACoreServiceClient(job.getServerConnection().getUrl());
parseImageSeriesFromJob(client);
parseImageStudyFromJob(client);
} catch (MalformedURIException e) {
throw new ConnectionException("Malformed URI.", e);
} catch (RemoteException e) {
throw new ConnectionException(REMOTE_CONNECTION_FAILED, e);
}
job.setCompleted(true);
try {
return Cai2Util.zipAndDeleteDirectory(temporaryStorageDirectory.getCanonicalPath());
} catch (IOException e) {
return null;
}
}
private void parseImageSeriesFromJob(NCIACoreServiceClient client) throws ConnectionException {
if (!job.getImageSeriesIDs().isEmpty()) {
for (String imageSeriesId : job.getImageSeriesIDs()) {
retrieveImageSeriesDicomFiles(client, imageSeriesId);
}
}
}
private void parseImageStudyFromJob(NCIACoreServiceClient client) throws ConnectionException {
if (!job.getImageStudyIDs().isEmpty()) {
for (String imageStudyId : job.getImageStudyIDs()) {
retrieveImageStudyDicomFiles(client, imageStudyId);
}
}
}
private void retrieveImageSeriesDicomFiles(NCIACoreServiceClient client, String imageSeriesUID)
throws ConnectionException {
try {
TransferServiceContextReference tscr = client.retrieveDicomDataBySeriesUID(imageSeriesUID);
gridTransferDicomData(tscr, IMAGE_SERIES_DIR + imageSeriesUID);
} catch (RemoteException e) {
throw new ConnectionException(REMOTE_CONNECTION_FAILED, e);
}
}
private void retrieveImageStudyDicomFiles(NCIACoreServiceClient client, String studyInstanceUID)
throws ConnectionException {
TransferServiceContextReference tscr;
try {
tscr = client.retrieveDicomDataByStudyUID(studyInstanceUID);
gridTransferDicomData(tscr, IMAGE_STUDY_DIR + studyInstanceUID);
} catch (RemoteException e) {
throw new ConnectionException(REMOTE_CONNECTION_FAILED, e);
}
}
private void gridTransferDicomData(TransferServiceContextReference tscr, String parentDir)
throws ConnectionException {
try {
TransferServiceContextClient tclient = new TransferServiceContextClient(tscr.getEndpointReference());
InputStream istream = TransferClientHelper.getData(tclient.getDataTransferDescriptor());
storeDicomFiles(istream, parentDir);
tclient.destroy();
} catch (MalformedURIException e) {
throw new ConnectionException("Malformed URI.", e);
} catch (RemoteException e) {
throw new ConnectionException(REMOTE_CONNECTION_FAILED, e);
} catch (Exception e) {
throw new ConnectionException("Unable to get dicom data from Transfer Client.", e);
}
}
private void storeDicomFiles(InputStream istream, String parentDir) throws IOException {
File dicomDirectory = new File(temporaryStorageDirectory, parentDir);
dicomDirectory.mkdir();
ZipInputStream zis = new ZipInputStream(istream);
ZipEntryInputStream zeis = null;
while (true) {
try {
zeis = new ZipEntryInputStream(zis);
} catch (EOFException e) {
break;
} catch (IOException e) {
break;
}
BufferedInputStream bis = new BufferedInputStream(zeis);
byte[] data = new byte[BUFFER_SIZE];
int bytesRead = 0;
File dicomFile = new File(dicomDirectory, zeis.getName());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dicomFile));
while ((bytesRead = (bis.read(data, 0, data.length))) > 0) {
bos.write(data, 0, bytesRead);
}
bos.flush();
bos.close();
- zis.close();
}
+ zis.close();
}
}
| false | true | private void storeDicomFiles(InputStream istream, String parentDir) throws IOException {
File dicomDirectory = new File(temporaryStorageDirectory, parentDir);
dicomDirectory.mkdir();
ZipInputStream zis = new ZipInputStream(istream);
ZipEntryInputStream zeis = null;
while (true) {
try {
zeis = new ZipEntryInputStream(zis);
} catch (EOFException e) {
break;
} catch (IOException e) {
break;
}
BufferedInputStream bis = new BufferedInputStream(zeis);
byte[] data = new byte[BUFFER_SIZE];
int bytesRead = 0;
File dicomFile = new File(dicomDirectory, zeis.getName());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dicomFile));
while ((bytesRead = (bis.read(data, 0, data.length))) > 0) {
bos.write(data, 0, bytesRead);
}
bos.flush();
bos.close();
zis.close();
}
}
| private void storeDicomFiles(InputStream istream, String parentDir) throws IOException {
File dicomDirectory = new File(temporaryStorageDirectory, parentDir);
dicomDirectory.mkdir();
ZipInputStream zis = new ZipInputStream(istream);
ZipEntryInputStream zeis = null;
while (true) {
try {
zeis = new ZipEntryInputStream(zis);
} catch (EOFException e) {
break;
} catch (IOException e) {
break;
}
BufferedInputStream bis = new BufferedInputStream(zeis);
byte[] data = new byte[BUFFER_SIZE];
int bytesRead = 0;
File dicomFile = new File(dicomDirectory, zeis.getName());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dicomFile));
while ((bytesRead = (bis.read(data, 0, data.length))) > 0) {
bos.write(data, 0, bytesRead);
}
bos.flush();
bos.close();
}
zis.close();
}
|
diff --git a/src/to/joe/j2mc/info/command/PlayerListCommand.java b/src/to/joe/j2mc/info/command/PlayerListCommand.java
index b49613d..9da1119 100644
--- a/src/to/joe/j2mc/info/command/PlayerListCommand.java
+++ b/src/to/joe/j2mc/info/command/PlayerListCommand.java
@@ -1,82 +1,86 @@
package to.joe.j2mc.info.command;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import to.joe.j2mc.core.J2MC_Manager;
import to.joe.j2mc.core.command.MasterCommand;
import to.joe.j2mc.info.J2MC_Info;
public class PlayerListCommand extends MasterCommand {
J2MC_Info plugin;
public PlayerListCommand(J2MC_Info Info) {
super(Info);
this.plugin = Info;
}
@Override
public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) {
if (!sender.hasPermission("j2mc.core.admin")) {
int total = 0;
for(Player derp : plugin.getServer().getOnlinePlayers()){
if(!J2MC_Manager.getVisibility().isVanished(derp)){
total++;
}
}
sender.sendMessage(ChatColor.AQUA + "Players (" + total + "/" + plugin.getServer().getMaxPlayers() + "):");
StringBuilder builder = new StringBuilder();
for (Player pl : plugin.getServer().getOnlinePlayers()) {
if (!J2MC_Manager.getVisibility().isVanished(pl)) {
- String playerName = pl.getDisplayName();
- builder.append(playerName + ChatColor.WHITE + ", ");
+ String toAdd;
+ toAdd = pl.getDisplayName();
+ if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'd')){
+ toAdd = ChatColor.GOLD + pl.getName();
+ }
+ builder.append(toAdd + ChatColor.WHITE + ", ");
if (builder.length() > 119) {
- builder.substring(0, (builder.length() - ((playerName + ChatColor.WHITE + ", ").length())));
+ builder.substring(0, (builder.length() - ((toAdd + ChatColor.WHITE + ", ").length())));
sender.sendMessage(builder.toString());
builder = new StringBuilder();
- builder.append(playerName + ChatColor.WHITE + ", ");
+ builder.append(toAdd + ChatColor.WHITE + ", ");
}
}
}
builder.setLength(builder.length() - 2);
sender.sendMessage(builder.toString());
} else {
sender.sendMessage(ChatColor.AQUA + "Players (" + plugin.getServer().getOnlinePlayers().length + "/" + plugin.getServer().getMaxPlayers() + "):");
StringBuilder builder = new StringBuilder();
for (Player pl : plugin.getServer().getOnlinePlayers()) {
String toAdd = "";
toAdd = ChatColor.GREEN + pl.getName();
if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 't')){
toAdd = ChatColor.DARK_GREEN + pl.getName();
}
- else if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'd')){
+ if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'd')){
toAdd = ChatColor.GOLD + pl.getName();
}
- else if(pl.hasPermission("j2mc-chat.mute")){
+ if(pl.hasPermission("j2mc-chat.mute")){
toAdd = ChatColor.YELLOW + pl.getName();
}
- else if(pl.hasPermission("j2mc.core.admin")){
+ if(pl.hasPermission("j2mc.core.admin")){
toAdd = ChatColor.RED + pl.getName();
}
- else if(J2MC_Manager.getVisibility().isVanished(pl)){
+ if(J2MC_Manager.getVisibility().isVanished(pl)){
toAdd = ChatColor.AQUA + pl.getName();
}
- else if(pl.hasPermission("j2mc-chat.admin.nsa")){
+ if(pl.hasPermission("j2mc-chat.admin.nsa")){
toAdd += ChatColor.DARK_AQUA + "��";
}
builder.append(toAdd + ChatColor.WHITE + ", ");
if (builder.length() > 119) {
builder.substring(0, (builder.length() - (toAdd + ChatColor.WHITE + ", ").length()));
sender.sendMessage(builder.toString());
builder = new StringBuilder();
builder.append(toAdd + ChatColor.WHITE + ", ");
}
}
builder.setLength(builder.length() - 2);
sender.sendMessage(builder.toString());
}
}
}
| false | true | public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) {
if (!sender.hasPermission("j2mc.core.admin")) {
int total = 0;
for(Player derp : plugin.getServer().getOnlinePlayers()){
if(!J2MC_Manager.getVisibility().isVanished(derp)){
total++;
}
}
sender.sendMessage(ChatColor.AQUA + "Players (" + total + "/" + plugin.getServer().getMaxPlayers() + "):");
StringBuilder builder = new StringBuilder();
for (Player pl : plugin.getServer().getOnlinePlayers()) {
if (!J2MC_Manager.getVisibility().isVanished(pl)) {
String playerName = pl.getDisplayName();
builder.append(playerName + ChatColor.WHITE + ", ");
if (builder.length() > 119) {
builder.substring(0, (builder.length() - ((playerName + ChatColor.WHITE + ", ").length())));
sender.sendMessage(builder.toString());
builder = new StringBuilder();
builder.append(playerName + ChatColor.WHITE + ", ");
}
}
}
builder.setLength(builder.length() - 2);
sender.sendMessage(builder.toString());
} else {
sender.sendMessage(ChatColor.AQUA + "Players (" + plugin.getServer().getOnlinePlayers().length + "/" + plugin.getServer().getMaxPlayers() + "):");
StringBuilder builder = new StringBuilder();
for (Player pl : plugin.getServer().getOnlinePlayers()) {
String toAdd = "";
toAdd = ChatColor.GREEN + pl.getName();
if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 't')){
toAdd = ChatColor.DARK_GREEN + pl.getName();
}
else if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'd')){
toAdd = ChatColor.GOLD + pl.getName();
}
else if(pl.hasPermission("j2mc-chat.mute")){
toAdd = ChatColor.YELLOW + pl.getName();
}
else if(pl.hasPermission("j2mc.core.admin")){
toAdd = ChatColor.RED + pl.getName();
}
else if(J2MC_Manager.getVisibility().isVanished(pl)){
toAdd = ChatColor.AQUA + pl.getName();
}
else if(pl.hasPermission("j2mc-chat.admin.nsa")){
toAdd += ChatColor.DARK_AQUA + "��";
}
builder.append(toAdd + ChatColor.WHITE + ", ");
if (builder.length() > 119) {
builder.substring(0, (builder.length() - (toAdd + ChatColor.WHITE + ", ").length()));
sender.sendMessage(builder.toString());
builder = new StringBuilder();
builder.append(toAdd + ChatColor.WHITE + ", ");
}
}
builder.setLength(builder.length() - 2);
sender.sendMessage(builder.toString());
}
}
| public void exec(CommandSender sender, String commandName, String[] args, Player player, boolean isPlayer) {
if (!sender.hasPermission("j2mc.core.admin")) {
int total = 0;
for(Player derp : plugin.getServer().getOnlinePlayers()){
if(!J2MC_Manager.getVisibility().isVanished(derp)){
total++;
}
}
sender.sendMessage(ChatColor.AQUA + "Players (" + total + "/" + plugin.getServer().getMaxPlayers() + "):");
StringBuilder builder = new StringBuilder();
for (Player pl : plugin.getServer().getOnlinePlayers()) {
if (!J2MC_Manager.getVisibility().isVanished(pl)) {
String toAdd;
toAdd = pl.getDisplayName();
if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'd')){
toAdd = ChatColor.GOLD + pl.getName();
}
builder.append(toAdd + ChatColor.WHITE + ", ");
if (builder.length() > 119) {
builder.substring(0, (builder.length() - ((toAdd + ChatColor.WHITE + ", ").length())));
sender.sendMessage(builder.toString());
builder = new StringBuilder();
builder.append(toAdd + ChatColor.WHITE + ", ");
}
}
}
builder.setLength(builder.length() - 2);
sender.sendMessage(builder.toString());
} else {
sender.sendMessage(ChatColor.AQUA + "Players (" + plugin.getServer().getOnlinePlayers().length + "/" + plugin.getServer().getMaxPlayers() + "):");
StringBuilder builder = new StringBuilder();
for (Player pl : plugin.getServer().getOnlinePlayers()) {
String toAdd = "";
toAdd = ChatColor.GREEN + pl.getName();
if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 't')){
toAdd = ChatColor.DARK_GREEN + pl.getName();
}
if(J2MC_Manager.getPermissions().hasFlag(pl.getName(), 'd')){
toAdd = ChatColor.GOLD + pl.getName();
}
if(pl.hasPermission("j2mc-chat.mute")){
toAdd = ChatColor.YELLOW + pl.getName();
}
if(pl.hasPermission("j2mc.core.admin")){
toAdd = ChatColor.RED + pl.getName();
}
if(J2MC_Manager.getVisibility().isVanished(pl)){
toAdd = ChatColor.AQUA + pl.getName();
}
if(pl.hasPermission("j2mc-chat.admin.nsa")){
toAdd += ChatColor.DARK_AQUA + "��";
}
builder.append(toAdd + ChatColor.WHITE + ", ");
if (builder.length() > 119) {
builder.substring(0, (builder.length() - (toAdd + ChatColor.WHITE + ", ").length()));
sender.sendMessage(builder.toString());
builder = new StringBuilder();
builder.append(toAdd + ChatColor.WHITE + ", ");
}
}
builder.setLength(builder.length() - 2);
sender.sendMessage(builder.toString());
}
}
|
diff --git a/src/de/azapps/mirakel/main_activity/tasks_fragment/TasksFragment.java b/src/de/azapps/mirakel/main_activity/tasks_fragment/TasksFragment.java
index ba744f64..55746001 100644
--- a/src/de/azapps/mirakel/main_activity/tasks_fragment/TasksFragment.java
+++ b/src/de/azapps/mirakel/main_activity/tasks_fragment/TasksFragment.java
@@ -1,698 +1,701 @@
/*******************************************************************************
* Mirakel is an Android App for managing your ToDo-Lists
*
* Copyright (c) 2013-2014 Anatolij Zelenin, Georg Semmler.
*
* 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
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package de.azapps.mirakel.main_activity.tasks_fragment;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.speech.RecognizerIntent;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.ActionMode;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import de.azapps.mirakel.DefenitionsModel.ExecInterfaceWithTask;
import de.azapps.mirakel.DefinitionsHelper;
import de.azapps.mirakel.custom_views.BaseTaskDetailRow.OnTaskChangedListner;
import de.azapps.mirakel.helper.Helpers;
import de.azapps.mirakel.helper.MirakelCommonPreferences;
import de.azapps.mirakel.helper.TaskDialogHelpers;
import de.azapps.mirakel.main_activity.MainActivity;
import de.azapps.mirakel.model.DatabaseHelper;
import de.azapps.mirakel.model.list.ListMirakel;
import de.azapps.mirakel.model.semantic.Semantic;
import de.azapps.mirakel.model.task.Task;
import de.azapps.mirakelandroid.R;
import de.azapps.tools.FileUtils;
import de.azapps.tools.Log;
public class TasksFragment extends android.support.v4.app.Fragment implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = "TasksFragment";
private static final int TASK_RENAME = 0, TASK_MOVE = 1, TASK_DESTROY = 2;
protected TaskAdapter adapter;
protected boolean created = false;
protected boolean finishLoad;
protected int ItemCount;
protected int listId;
protected ListView listView;
protected boolean loadMore;
protected ActionMode mActionMode = null;
protected MainActivity main;
final Handler mHandler = new Handler();
protected EditText newTask;
private boolean showDone = true;
View view;
public void clearFocus() {
if (this.newTask != null) {
this.newTask.postDelayed(new Runnable() {
@Override
public void run() {
if (TasksFragment.this.newTask == null) {
return;
}
TasksFragment.this.newTask.setOnFocusChangeListener(null);
TasksFragment.this.newTask.clearFocus();
if (getActivity() == null) {
return;
}
final InputMethodManager imm = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(
TasksFragment.this.newTask.getWindowToken(), 0);
getActivity().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
}, 10);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void closeActionMode() {
if (this.mActionMode != null
&& Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
this.mActionMode.finish();
}
}
public void focusNew(final boolean request_focus) {
if (this.newTask == null) {
return;
}
this.newTask.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(final View v, final boolean hasFocus) {
if (TasksFragment.this.main.getCurrentPosition() != MainActivity
.getTasksFragmentPosition()) {
return;
}
TasksFragment.this.newTask.post(new Runnable() {
@Override
public void run() {
final InputMethodManager imm = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm == null) {
Log.w(TasksFragment.TAG, "Inputmanager==null");
return;
}
imm.restartInput(TasksFragment.this.newTask);
if (request_focus && hasFocus) {
getActivity()
.getWindow()
.setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
imm.showSoftInput(TasksFragment.this.newTask,
InputMethodManager.SHOW_IMPLICIT);
getActivity()
.getWindow()
.setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
} else if (!hasFocus) {
TasksFragment.this.newTask.requestFocus();
imm.showSoftInput(TasksFragment.this.newTask,
InputMethodManager.SHOW_IMPLICIT);
} else if (!request_focus) {
clearFocus();
}
}
});
}
});
this.newTask.requestFocus();
}
public TaskAdapter getAdapter() {
return this.adapter;
}
public View getFragmentView() {
return this.view;
}
public ListView getListView() {
return this.listView;
}
public boolean isReady() {
return this.newTask != null;
}
protected boolean newTask(final String name) {
this.newTask.setText(null);
final InputMethodManager imm = (InputMethodManager) this.main
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(this.newTask.getWindowToken(), 0);
this.newTask.clearFocus();
if (name.equals("")) {
this.newTask.setOnFocusChangeListener(null);
imm.showSoftInput(this.newTask,
InputMethodManager.HIDE_IMPLICIT_ONLY);
return true;
}
final ListMirakel list = this.main.getCurrentList();
Semantic.createTask(name, list,
MirakelCommonPreferences.useSemanticNewTask(), getActivity());
getLoaderManager().restartLoader(0, null, this);
this.main.getListFragment().update();
if (!MirakelCommonPreferences.hideKeyboard()) {
focusNew(true);
}
this.main.updateShare();
return true;
}
@Override
public View onCreateView(final LayoutInflater inflater,
final ViewGroup container, final Bundle savedInstanceState) {
// Inflate the layout for this fragment
this.finishLoad = false;
this.loadMore = false;
this.ItemCount = 0;
this.main = (MainActivity) getActivity();
this.showDone = MirakelCommonPreferences.showDoneMain();
this.listId = this.main.getCurrentList().getId();
this.view = inflater.inflate(R.layout.layout_tasks_fragment, container,
false);
this.adapter = null;
this.created = true;
this.listView = (ListView) this.view.findViewById(R.id.tasks_list);
this.listView
.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
// Events
this.newTask = (EditText) this.view.findViewById(R.id.tasks_new);
if (MirakelCommonPreferences.isTablet()) {
this.newTask.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
}
this.newTask.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(final TextView v, final int actionId,
final KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEND
|| actionId == EditorInfo.IME_NULL
&& event.getAction() == KeyEvent.ACTION_DOWN) {
newTask(v.getText().toString());
v.setText(null);
}
return false;
}
});
this.newTask.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(final Editable s) {
final ImageButton send = (ImageButton) TasksFragment.this.view
.findViewById(R.id.btnEnter);
if (s.length() > 0) {
send.setVisibility(View.VISIBLE);
} else {
send.setVisibility(View.GONE);
}
}
@Override
public void beforeTextChanged(final CharSequence s,
final int start, final int count, final int after) {
// Nothing
}
@Override
public void onTextChanged(final CharSequence s, final int start,
final int before, final int count) {
// Nothing
}
});
update(true);
final ImageButton btnEnter = (ImageButton) this.view
.findViewById(R.id.btnEnter);
btnEnter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
newTask(TasksFragment.this.newTask.getText().toString());
TasksFragment.this.newTask.setText(null);
}
});
updateButtons();
return this.view;
}
@Override
public void onResume() {
super.onResume();
this.showDone = MirakelCommonPreferences.showDoneMain();
}
public void setActivity(final MainActivity activity) {
this.main = activity;
}
public void setListID(final int listID) {
this.listId = listID;
update(true);
}
public void setScrollPosition(final int pos) {
if (this.listView == null || this.main == null) {
return;
}
this.main.runOnUiThread(new Runnable() {
@Override
public void run() {
if (TasksFragment.this.listView.getCount() > pos) {
TasksFragment.this.listView.setSelectionFromTop(pos, 0);
} else {
TasksFragment.this.listView.setSelectionFromTop(0, 0);
}
}
});
}
@SuppressLint("NewApi")
protected void update(final boolean reset) {
if (!this.created) {
return;
}
this.listView = (ListView) this.view.findViewById(R.id.tasks_list);
this.adapter = new TaskAdapter(getActivity(),
new OnTaskChangedListner() {
@Override
public void onTaskChanged(final Task newTask) {
if (MirakelCommonPreferences.isTablet()
&& TasksFragment.this.main != null
&& TasksFragment.this.main.getCurrentTask()
.getId() == newTask.getId()) {
getLoaderManager().restartLoader(0, null,
TasksFragment.this);
}
}
});
this.listView.setAdapter(this.adapter);
getLoaderManager().initLoader(0, null, this);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
this.listView
.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(
final AdapterView<?> parent, final View item,
final int position, final long id) {
final AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity());
final Task task = Task.get((Long) item.getTag());
builder.setTitle(task.getName());
final List<CharSequence> items = new ArrayList<CharSequence>(
Arrays.asList(getActivity().getResources()
.getStringArray(
R.array.task_actions_items)));
builder.setItems(items
.toArray(new CharSequence[items.size()]),
new DialogInterface.OnClickListener() {
@Override
public void onClick(
final DialogInterface dialog,
final int item) {
switch (item) {
case TASK_RENAME:
TasksFragment.this.main
.setCurrentTask(task);
break;
case TASK_MOVE:
TasksFragment.this.main
.handleMoveTask(task);
break;
case TASK_DESTROY:
TasksFragment.this.main
.handleDestroyTask(task);
break;
default:
break;
}
}
});
final AlertDialog dialog = builder.create();
dialog.show();
return true;
}
});
} else {
this.listView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
this.listView.setHapticFeedbackEnabled(true);
this.listView
.setMultiChoiceModeListener(new MultiChoiceModeListener() {
@Override
public boolean onActionItemClicked(
final ActionMode mode, final MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete:
TasksFragment.this.main
.handleDestroyTask(TasksFragment.this.selectedTasks);
break;
case R.id.menu_move:
TasksFragment.this.main
.handleMoveTask(TasksFragment.this.selectedTasks);
break;
case R.id.edit_task:
TasksFragment.this.main.setCurrentTask(
TasksFragment.this.selectedTasks.get(0),
true);
break;
case R.id.done_task:
for (final Task t : TasksFragment.this.selectedTasks) {
t.setDone(true);
t.safeSave();
}
TasksFragment.this.adapter
.notifyDataSetChanged();
break;
default:
break;
}
mode.finish();
return false;
}
@Override
public boolean onCreateActionMode(
final ActionMode mode, final Menu menu) {
final MenuInflater inflater = mode
.getMenuInflater();
inflater.inflate(R.menu.context_tasks, menu);
TasksFragment.this.mActionMode = mode;
clearFocus();
TasksFragment.this.selectedTasks = new ArrayList<Task>();
return true;
}
@Override
public void onDestroyActionMode(final ActionMode mode) {
TasksFragment.this.selectedTasks = new ArrayList<Task>();
}
@Override
public void onItemCheckedStateChanged(
final ActionMode mode, final int position,
final long id, final boolean checked) {
final View v = TasksFragment.this.listView
.getChildAt(position);
+ if (v == null) {
+ return;
+ }
final Task t = Task.get((Long) v.getTag());
if (!TasksFragment.this.selectedTasks.contains(t)
&& checked) {
TasksFragment.this.selectedTasks.add(t);
} else if (checked) {
TasksFragment.this.selectedTasks.remove(t);
}
if (!checked) {
v.setBackgroundColor(getActivity()
.getResources().getColor(
android.R.color.transparent));
} else {
if (TasksFragment.this.selectedTasks.size() == 1) {
TasksFragment.this.listView.postDelayed(
new Runnable() {
@Override
public void run() {
v.setBackgroundColor(Helpers
.getHighlightedColor(getActivity()));
}
}, 10);
} else {
v.setBackgroundColor(Helpers
.getHighlightedColor(getActivity()));
}
}
}
@Override
public boolean onPrepareActionMode(
final ActionMode mode, final Menu menu) {
menu.findItem(R.id.edit_task)
.setVisible(
TasksFragment.this.selectedTasks
.size() <= 1);
return false;
}
});
}
this.listView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(final AdapterView<?> parent,
final View item, final int position, final long id) {
final Task t = Task.get((Long) item.getTag());
TasksFragment.this.main.setCurrentTask(t, true);
}
});
}
protected List<Task> selectedTasks;
private String query;
public void search(final String query) {
this.query = query;
try {
getLoaderManager().restartLoader(0, null, this);
} catch (final Exception e) {
// eat it
}
}
public void updateButtons() {
// a) Android 2.3 dosen't support speech toText
// b) The user can switch off the button
if (this.view == null) {
return;
}
if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.HONEYCOMB
|| !MirakelCommonPreferences.useBtnSpeak()) {
this.view.findViewById(R.id.btnSpeak_tasks)
.setVisibility(View.GONE);
} else {
final ImageButton btnSpeak = (ImageButton) this.view
.findViewById(R.id.btnSpeak_tasks);
// txtText = newTask;
btnSpeak.setVisibility(View.VISIBLE);
btnSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
final Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
TasksFragment.this.main
.getString(R.string.speak_lang_code));
try {
getActivity().startActivityForResult(intent,
MainActivity.RESULT_SPEECH);
TasksFragment.this.newTask.setText("");
} catch (final ActivityNotFoundException a) {
final Toast t = Toast
.makeText(
TasksFragment.this.main,
"Opps! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
}
});
}
if (!MirakelCommonPreferences.useBtnAudioRecord()) {
this.view.findViewById(R.id.btnAudio_tasks)
.setVisibility(View.GONE);
} else {
final ImageButton btnAudio = (ImageButton) this.view
.findViewById(R.id.btnAudio_tasks);
btnAudio.setVisibility(View.VISIBLE);
btnAudio.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
// TODO BAHHHH this is ugly!
final Task task = new Task("");
task.setList(TasksFragment.this.main.getCurrentList(), true);
task.setId(0);
TaskDialogHelpers.handleAudioRecord(
TasksFragment.this.main, task,
new ExecInterfaceWithTask() {
@Override
public void exec(final Task t) {
TasksFragment.this.main.setCurrentList(t
.getList());
TasksFragment.this.main.setCurrentTask(t,
true);
}
});
}
});
}
if (!MirakelCommonPreferences.useBtnCamera()
|| !Helpers.isIntentAvailable(this.main,
MediaStore.ACTION_IMAGE_CAPTURE)) {
this.view.findViewById(R.id.btnCamera).setVisibility(View.GONE);
} else {
final ImageButton btnCamera = (ImageButton) this.view
.findViewById(R.id.btnCamera);
btnCamera.setVisibility(View.VISIBLE);
btnCamera.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
try {
final Intent cameraIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
final Uri fileUri = FileUtils
.getOutputMediaFileUri(FileUtils.MEDIA_TYPE_IMAGE);
if (fileUri == null) {
return;
}
TasksFragment.this.main.setFileUri(fileUri);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
getActivity().startActivityForResult(cameraIntent,
MainActivity.RESULT_CAMERA);
} catch (final ActivityNotFoundException a) {
Toast.makeText(
TasksFragment.this.main,
"Opps! Your device doesn't support taking photos",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
public void updateList(final boolean reset) {
this.listId = this.main.getCurrentList().getId();
this.query = null;
try {
getLoaderManager().restartLoader(0, null, this);
} catch (final Exception e) {
// ignore it
}
}
@Override
public Loader<Cursor> onCreateLoader(final int arg0, final Bundle arg1) {
final ListMirakel list = ListMirakel.getList(this.listId);
final Uri u = Uri.parse("content://"
+ DefinitionsHelper.AUTHORITY_INTERNAL + "/" + "tasks");
String dbQuery = list.getWhereQueryForTasks(true);
if (this.query != null) {
if (dbQuery != null && dbQuery.trim() != "" && dbQuery.length() > 0) {
dbQuery = "(" + dbQuery + ") AND ";
}
dbQuery += DatabaseHelper.NAME + " LIKE '%" + this.query + "%'";
}
return new CursorLoader(getActivity(), u, Task.allColumns, dbQuery,
null, Task.getSorting(list.getSortBy()));
}
@Override
public void onLoadFinished(final Loader<Cursor> loader,
final Cursor newCursor) {
this.adapter.swapCursor(newCursor);
}
@Override
public void onLoaderReset(final Loader<Cursor> loader) {
this.adapter.swapCursor(null);
}
public Task getLastTouched() {
if (this.adapter != null
&& this.listView != null
&& this.listView.getChildAt(this.adapter.getLastTouched()) != null) {
return Task.get((Long) this.listView.getChildAt(
this.adapter.getLastTouched()).getTag());
}
return null;
}
public View getViewForTask(final Task task) {
return getListView().findViewWithTag(task.getId());
}
}
| true | true | protected void update(final boolean reset) {
if (!this.created) {
return;
}
this.listView = (ListView) this.view.findViewById(R.id.tasks_list);
this.adapter = new TaskAdapter(getActivity(),
new OnTaskChangedListner() {
@Override
public void onTaskChanged(final Task newTask) {
if (MirakelCommonPreferences.isTablet()
&& TasksFragment.this.main != null
&& TasksFragment.this.main.getCurrentTask()
.getId() == newTask.getId()) {
getLoaderManager().restartLoader(0, null,
TasksFragment.this);
}
}
});
this.listView.setAdapter(this.adapter);
getLoaderManager().initLoader(0, null, this);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
this.listView
.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(
final AdapterView<?> parent, final View item,
final int position, final long id) {
final AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity());
final Task task = Task.get((Long) item.getTag());
builder.setTitle(task.getName());
final List<CharSequence> items = new ArrayList<CharSequence>(
Arrays.asList(getActivity().getResources()
.getStringArray(
R.array.task_actions_items)));
builder.setItems(items
.toArray(new CharSequence[items.size()]),
new DialogInterface.OnClickListener() {
@Override
public void onClick(
final DialogInterface dialog,
final int item) {
switch (item) {
case TASK_RENAME:
TasksFragment.this.main
.setCurrentTask(task);
break;
case TASK_MOVE:
TasksFragment.this.main
.handleMoveTask(task);
break;
case TASK_DESTROY:
TasksFragment.this.main
.handleDestroyTask(task);
break;
default:
break;
}
}
});
final AlertDialog dialog = builder.create();
dialog.show();
return true;
}
});
} else {
this.listView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
this.listView.setHapticFeedbackEnabled(true);
this.listView
.setMultiChoiceModeListener(new MultiChoiceModeListener() {
@Override
public boolean onActionItemClicked(
final ActionMode mode, final MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete:
TasksFragment.this.main
.handleDestroyTask(TasksFragment.this.selectedTasks);
break;
case R.id.menu_move:
TasksFragment.this.main
.handleMoveTask(TasksFragment.this.selectedTasks);
break;
case R.id.edit_task:
TasksFragment.this.main.setCurrentTask(
TasksFragment.this.selectedTasks.get(0),
true);
break;
case R.id.done_task:
for (final Task t : TasksFragment.this.selectedTasks) {
t.setDone(true);
t.safeSave();
}
TasksFragment.this.adapter
.notifyDataSetChanged();
break;
default:
break;
}
mode.finish();
return false;
}
@Override
public boolean onCreateActionMode(
final ActionMode mode, final Menu menu) {
final MenuInflater inflater = mode
.getMenuInflater();
inflater.inflate(R.menu.context_tasks, menu);
TasksFragment.this.mActionMode = mode;
clearFocus();
TasksFragment.this.selectedTasks = new ArrayList<Task>();
return true;
}
@Override
public void onDestroyActionMode(final ActionMode mode) {
TasksFragment.this.selectedTasks = new ArrayList<Task>();
}
@Override
public void onItemCheckedStateChanged(
final ActionMode mode, final int position,
final long id, final boolean checked) {
final View v = TasksFragment.this.listView
.getChildAt(position);
final Task t = Task.get((Long) v.getTag());
if (!TasksFragment.this.selectedTasks.contains(t)
&& checked) {
TasksFragment.this.selectedTasks.add(t);
} else if (checked) {
TasksFragment.this.selectedTasks.remove(t);
}
if (!checked) {
v.setBackgroundColor(getActivity()
.getResources().getColor(
android.R.color.transparent));
} else {
if (TasksFragment.this.selectedTasks.size() == 1) {
TasksFragment.this.listView.postDelayed(
new Runnable() {
@Override
public void run() {
v.setBackgroundColor(Helpers
.getHighlightedColor(getActivity()));
}
}, 10);
} else {
v.setBackgroundColor(Helpers
.getHighlightedColor(getActivity()));
}
}
}
@Override
public boolean onPrepareActionMode(
final ActionMode mode, final Menu menu) {
menu.findItem(R.id.edit_task)
.setVisible(
TasksFragment.this.selectedTasks
.size() <= 1);
return false;
}
});
}
this.listView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(final AdapterView<?> parent,
final View item, final int position, final long id) {
final Task t = Task.get((Long) item.getTag());
TasksFragment.this.main.setCurrentTask(t, true);
}
});
}
| protected void update(final boolean reset) {
if (!this.created) {
return;
}
this.listView = (ListView) this.view.findViewById(R.id.tasks_list);
this.adapter = new TaskAdapter(getActivity(),
new OnTaskChangedListner() {
@Override
public void onTaskChanged(final Task newTask) {
if (MirakelCommonPreferences.isTablet()
&& TasksFragment.this.main != null
&& TasksFragment.this.main.getCurrentTask()
.getId() == newTask.getId()) {
getLoaderManager().restartLoader(0, null,
TasksFragment.this);
}
}
});
this.listView.setAdapter(this.adapter);
getLoaderManager().initLoader(0, null, this);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
this.listView
.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(
final AdapterView<?> parent, final View item,
final int position, final long id) {
final AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity());
final Task task = Task.get((Long) item.getTag());
builder.setTitle(task.getName());
final List<CharSequence> items = new ArrayList<CharSequence>(
Arrays.asList(getActivity().getResources()
.getStringArray(
R.array.task_actions_items)));
builder.setItems(items
.toArray(new CharSequence[items.size()]),
new DialogInterface.OnClickListener() {
@Override
public void onClick(
final DialogInterface dialog,
final int item) {
switch (item) {
case TASK_RENAME:
TasksFragment.this.main
.setCurrentTask(task);
break;
case TASK_MOVE:
TasksFragment.this.main
.handleMoveTask(task);
break;
case TASK_DESTROY:
TasksFragment.this.main
.handleDestroyTask(task);
break;
default:
break;
}
}
});
final AlertDialog dialog = builder.create();
dialog.show();
return true;
}
});
} else {
this.listView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE_MODAL);
this.listView.setHapticFeedbackEnabled(true);
this.listView
.setMultiChoiceModeListener(new MultiChoiceModeListener() {
@Override
public boolean onActionItemClicked(
final ActionMode mode, final MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete:
TasksFragment.this.main
.handleDestroyTask(TasksFragment.this.selectedTasks);
break;
case R.id.menu_move:
TasksFragment.this.main
.handleMoveTask(TasksFragment.this.selectedTasks);
break;
case R.id.edit_task:
TasksFragment.this.main.setCurrentTask(
TasksFragment.this.selectedTasks.get(0),
true);
break;
case R.id.done_task:
for (final Task t : TasksFragment.this.selectedTasks) {
t.setDone(true);
t.safeSave();
}
TasksFragment.this.adapter
.notifyDataSetChanged();
break;
default:
break;
}
mode.finish();
return false;
}
@Override
public boolean onCreateActionMode(
final ActionMode mode, final Menu menu) {
final MenuInflater inflater = mode
.getMenuInflater();
inflater.inflate(R.menu.context_tasks, menu);
TasksFragment.this.mActionMode = mode;
clearFocus();
TasksFragment.this.selectedTasks = new ArrayList<Task>();
return true;
}
@Override
public void onDestroyActionMode(final ActionMode mode) {
TasksFragment.this.selectedTasks = new ArrayList<Task>();
}
@Override
public void onItemCheckedStateChanged(
final ActionMode mode, final int position,
final long id, final boolean checked) {
final View v = TasksFragment.this.listView
.getChildAt(position);
if (v == null) {
return;
}
final Task t = Task.get((Long) v.getTag());
if (!TasksFragment.this.selectedTasks.contains(t)
&& checked) {
TasksFragment.this.selectedTasks.add(t);
} else if (checked) {
TasksFragment.this.selectedTasks.remove(t);
}
if (!checked) {
v.setBackgroundColor(getActivity()
.getResources().getColor(
android.R.color.transparent));
} else {
if (TasksFragment.this.selectedTasks.size() == 1) {
TasksFragment.this.listView.postDelayed(
new Runnable() {
@Override
public void run() {
v.setBackgroundColor(Helpers
.getHighlightedColor(getActivity()));
}
}, 10);
} else {
v.setBackgroundColor(Helpers
.getHighlightedColor(getActivity()));
}
}
}
@Override
public boolean onPrepareActionMode(
final ActionMode mode, final Menu menu) {
menu.findItem(R.id.edit_task)
.setVisible(
TasksFragment.this.selectedTasks
.size() <= 1);
return false;
}
});
}
this.listView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(final AdapterView<?> parent,
final View item, final int position, final long id) {
final Task t = Task.get((Long) item.getTag());
TasksFragment.this.main.setCurrentTask(t, true);
}
});
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskListView.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskListView.java
index 868abfcc3..98477c0a5 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskListView.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskListView.java
@@ -1,1581 +1,1581 @@
/*******************************************************************************
* 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.tasks.ui.views;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IMenuCreator;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.CheckboxCellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.window.Window;
import org.eclipse.mylar.context.core.MylarStatusHandler;
import org.eclipse.mylar.internal.tasks.core.WebTask;
import org.eclipse.mylar.internal.tasks.ui.AbstractTaskListFilter;
import org.eclipse.mylar.internal.tasks.ui.IDynamicSubMenuContributor;
import org.eclipse.mylar.internal.tasks.ui.TaskArchiveFilter;
import org.eclipse.mylar.internal.tasks.ui.TaskCompletionFilter;
import org.eclipse.mylar.internal.tasks.ui.TaskListColorsAndFonts;
import org.eclipse.mylar.internal.tasks.ui.TaskListImages;
import org.eclipse.mylar.internal.tasks.ui.TaskListPatternFilter;
import org.eclipse.mylar.internal.tasks.ui.TaskListPreferenceConstants;
import org.eclipse.mylar.internal.tasks.ui.TaskPriorityFilter;
import org.eclipse.mylar.internal.tasks.ui.TaskUiUtil;
import org.eclipse.mylar.internal.tasks.ui.actions.CollapseAllAction;
import org.eclipse.mylar.internal.tasks.ui.actions.CopyDetailsAction;
import org.eclipse.mylar.internal.tasks.ui.actions.DeleteAction;
import org.eclipse.mylar.internal.tasks.ui.actions.ExpandAllAction;
import org.eclipse.mylar.internal.tasks.ui.actions.FilterArchiveContainerAction;
import org.eclipse.mylar.internal.tasks.ui.actions.FilterCompletedTasksAction;
import org.eclipse.mylar.internal.tasks.ui.actions.GoIntoAction;
import org.eclipse.mylar.internal.tasks.ui.actions.GoUpAction;
import org.eclipse.mylar.internal.tasks.ui.actions.MarkTaskCompleteAction;
import org.eclipse.mylar.internal.tasks.ui.actions.MarkTaskIncompleteAction;
import org.eclipse.mylar.internal.tasks.ui.actions.NewCategoryAction;
import org.eclipse.mylar.internal.tasks.ui.actions.NewLocalTaskAction;
import org.eclipse.mylar.internal.tasks.ui.actions.OpenTaskListElementAction;
import org.eclipse.mylar.internal.tasks.ui.actions.OpenWithBrowserAction;
import org.eclipse.mylar.internal.tasks.ui.actions.PreviousTaskDropDownAction;
import org.eclipse.mylar.internal.tasks.ui.actions.RemoveFromCategoryAction;
import org.eclipse.mylar.internal.tasks.ui.actions.RenameAction;
import org.eclipse.mylar.internal.tasks.ui.actions.TaskActivateAction;
import org.eclipse.mylar.internal.tasks.ui.actions.TaskDeactivateAction;
import org.eclipse.mylar.tasks.core.AbstractQueryHit;
import org.eclipse.mylar.tasks.core.AbstractRepositoryQuery;
import org.eclipse.mylar.tasks.core.AbstractRepositoryTask;
import org.eclipse.mylar.tasks.core.AbstractTaskContainer;
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.core.ITaskListChangeListener;
import org.eclipse.mylar.tasks.core.ITaskListElement;
import org.eclipse.mylar.tasks.core.Task;
import org.eclipse.mylar.tasks.core.TaskArchive;
import org.eclipse.mylar.tasks.core.TaskCategory;
import org.eclipse.mylar.tasks.ui.TaskTransfer;
import org.eclipse.mylar.tasks.ui.TasksUiPlugin;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.RTFTransfer;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.DrillDownAdapter;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.themes.IThemeManager;
/**
* @author Mik Kersten
* @author Ken Sueda
*/
public class TaskListView extends ViewPart {
public static final String ID = "org.eclipse.mylar.tasks.ui.views.TaskListView";
public static final String LABEL_VIEW = "Task List";
private static final String MEMENTO_KEY_SORT_DIRECTION = "sortDirection";
private static final String MEMENTO_KEY_SORTER = "sorter";
private static final String MEMENTO_KEY_SORT_INDEX = "sortIndex";
private static final String MEMENTO_KEY_WIDTH = "width";
private static final String SEPARATOR_LOCAL = "local";
private static final String SEPARATOR_CONTEXT = "context";
private static final String SEPARATOR_FILTERS = "filters";
private static final String SEPARATOR_REPORTS = "reports";
private static final String LABEL_NO_TASKS = "no task active";
static final String[] PRIORITY_LEVELS = { Task.PriorityLevel.P1.toString(), Task.PriorityLevel.P2.toString(),
Task.PriorityLevel.P3.toString(), Task.PriorityLevel.P4.toString(), Task.PriorityLevel.P5.toString() };
public static final String[] PRIORITY_LEVEL_DESCRIPTIONS = { Task.PriorityLevel.P1.getDescription(),
Task.PriorityLevel.P2.getDescription(), Task.PriorityLevel.P3.getDescription(),
Task.PriorityLevel.P4.getDescription(), Task.PriorityLevel.P5.getDescription() };
private static final String SEPARATOR_ID_REPORTS = SEPARATOR_REPORTS;
private static final String PART_NAME = "Mylar Tasks";
private IThemeManager themeManager;
private TaskListFilteredTree filteredTree;
private DrillDownAdapter drillDownAdapter;
private AbstractTaskContainer drilledIntoCategory = null;
private GoIntoAction goIntoAction;
private GoUpAction goUpAction;
private CopyDetailsAction copyDetailsAction;
private OpenTaskListElementAction openTaskEditor;
private OpenWithBrowserAction openWithBrowser;
private NewLocalTaskAction newLocalTaskAction;
private NewCategoryAction newCategoryAction;
private RenameAction renameAction;
private CollapseAllAction collapseAll;
private ExpandAllAction expandAll;
private DeleteAction deleteAction;
private RemoveFromCategoryAction removeFromCategoryAction;
private TaskActivateAction activateAction = new TaskActivateAction();
private TaskDeactivateAction deactivateAction = new TaskDeactivateAction();
private MarkTaskCompleteAction markIncompleteAction;
private MarkTaskIncompleteAction markCompleteAction;
private FilterCompletedTasksAction filterCompleteTask;
private FilterArchiveContainerAction filterArchiveCategory;
private PriorityDropDownAction filterOnPriority;
private PreviousTaskDropDownAction previousTaskAction;
// private NextTaskDropDownAction nextTaskAction;
private static TaskPriorityFilter FILTER_PRIORITY = new TaskPriorityFilter();
private static TaskCompletionFilter FILTER_COMPLETE = new TaskCompletionFilter();
private static TaskArchiveFilter FILTER_ARCHIVE = new TaskArchiveFilter();
private Set<AbstractTaskListFilter> filters = new HashSet<AbstractTaskListFilter>();
static final String FILTER_LABEL = "<filter>";
protected String[] columnNames = new String[] { "", "", " !", " ", "Description" };
protected int[] columnWidths = new int[] { 53, 20, 12, 12, 160 };
private TreeColumn[] columns;
private IMemento taskListMemento;
public static final String columnWidthIdentifier = "org.eclipse.mylar.tasklist.ui.views.tasklist.columnwidth";
public static final String tableSortIdentifier = "org.eclipse.mylar.tasklist.ui.views.tasklist.sortIndex";
private static final int DEFAULT_SORT_DIRECTION = -1;
private int sortIndex = 2;
int sortDirection = DEFAULT_SORT_DIRECTION;
/**
* True if the view should indicate that interaction monitoring is paused
*/
protected boolean isPaused = false;
private final ITaskActivityListener TASK_ACTIVITY_LISTENER = new ITaskActivityListener() {
public void taskActivated(final ITask task) {
if (task != null) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
updateDescription(task);
selectedAndFocusTask(task);
filteredTree.indicateActiveTask(task);
}
});
}
}
public void tasksActivated(List<ITask> tasks) {
if (tasks.size() == 1) {
taskActivated(tasks.get(0));
}
}
public void taskDeactivated(final ITask task) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
refreshTask(task);
updateDescription(null);
filteredTree.indicateNoActiveTask();
}
});
}
public void activityChanged(DateRangeContainer week) {
// ignore
}
public void taskListRead() {
refresh(null);
}
public void calendarChanged() {
refresh(null);
}
};
private final ITaskListChangeListener TASK_REFERESH_LISTENER = new ITaskListChangeListener() {
public void localInfoChanged(final ITask task) {
refreshTask(task);
if (task.getContainer() != null) {
refresh(task.getContainer());
}
if (task instanceof AbstractRepositoryTask) {
Set<AbstractRepositoryQuery> queries = TasksUiPlugin.getTaskListManager().getTaskList()
.getQueriesForHandle(task.getHandleIdentifier());
for (AbstractRepositoryQuery query : queries) {
refresh(query);
}
}
if (task.isActive()) {
// TODO: only do this if description changes
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
filteredTree.indicateActiveTask(task);
}
});
}
}
public void repositoryInfoChanged(ITask task) {
localInfoChanged(task);
}
public void taskMoved(ITask task, AbstractTaskContainer fromContainer, AbstractTaskContainer toContainer) {
AbstractTaskContainer rootCategory = TasksUiPlugin.getTaskListManager().getTaskList().getRootCategory();
if (rootCategory.equals(fromContainer) || rootCategory.equals(toContainer)) {
refresh(null);
} else {
refresh(toContainer);
refresh(task);
refresh(fromContainer);
}
}
public void taskDeleted(ITask task) {
refresh(null);
}
public void containerAdded(AbstractTaskContainer container) {
refresh(null);
}
public void containerDeleted(AbstractTaskContainer container) {
refresh(null);
}
public void taskAdded(ITask task) {
refresh(null);
}
public void containerInfoChanged(AbstractTaskContainer container) {
if (container.equals(TasksUiPlugin.getTaskListManager().getTaskList().getRootCategory())) {
refresh(null);
} else {
refresh(container);
}
}
};
private final IPropertyChangeListener THEME_CHANGE_LISTENER = new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(IThemeManager.CHANGE_CURRENT_THEME)
|| TaskListColorsAndFonts.isTaskListTheme(event.getProperty())) {
taskListTableLabelProvider.setCategoryBackgroundColor(themeManager.getCurrentTheme().getColorRegistry()
.get(TaskListColorsAndFonts.THEME_COLOR_TASKLIST_CATEGORY));
getViewer().refresh();
}
}
};
private TaskListTableLabelProvider taskListTableLabelProvider;
private TaskListTableSorter tableSorter;
private final class PriorityDropDownAction extends Action implements IMenuCreator {
private Menu dropDownMenu = null;
public PriorityDropDownAction() {
super();
setText("Priority Filter");
setToolTipText("Filter Priority Lower Than");
setImageDescriptor(TaskListImages.FILTER_PRIORITY);
setMenuCreator(this);
}
public void dispose() {
if (dropDownMenu != null) {
dropDownMenu.dispose();
dropDownMenu = null;
}
}
public Menu getMenu(Control parent) {
if (dropDownMenu != null) {
dropDownMenu.dispose();
}
dropDownMenu = new Menu(parent);
addActionsToMenu();
return dropDownMenu;
}
public Menu getMenu(Menu parent) {
if (dropDownMenu != null) {
dropDownMenu.dispose();
}
dropDownMenu = new Menu(parent);
addActionsToMenu();
return dropDownMenu;
}
public void addActionsToMenu() {
Action P1 = new Action("", AS_CHECK_BOX) {
@Override
public void run() {
TasksUiPlugin.getDefault().getPreferenceStore().setValue(
TaskListPreferenceConstants.SELECTED_PRIORITY, Task.PriorityLevel.P1.toString());
// MylarTaskListPlugin.setCurrentPriorityLevel(Task.PriorityLevel.P1);
FILTER_PRIORITY.displayPrioritiesAbove(PRIORITY_LEVELS[0]);
getViewer().refresh();
}
};
P1.setEnabled(true);
P1.setText(Task.PriorityLevel.P1.getDescription());
P1.setImageDescriptor(TaskListImages.PRIORITY_1);
ActionContributionItem item = new ActionContributionItem(P1);
item.fill(dropDownMenu, -1);
Action P2 = new Action("", AS_CHECK_BOX) {
@Override
public void run() {
TasksUiPlugin.getDefault().getPreferenceStore().setValue(
TaskListPreferenceConstants.SELECTED_PRIORITY, Task.PriorityLevel.P2.toString());
// MylarTaskListPlugin.setCurrentPriorityLevel(Task.PriorityLevel.P2);
FILTER_PRIORITY.displayPrioritiesAbove(PRIORITY_LEVELS[1]);
getViewer().refresh();
}
};
P2.setEnabled(true);
P2.setText(Task.PriorityLevel.P2.getDescription());
P2.setImageDescriptor(TaskListImages.PRIORITY_2);
item = new ActionContributionItem(P2);
item.fill(dropDownMenu, -1);
Action P3 = new Action("", AS_CHECK_BOX) {
@Override
public void run() {
TasksUiPlugin.getDefault().getPreferenceStore().setValue(
TaskListPreferenceConstants.SELECTED_PRIORITY, Task.PriorityLevel.P3.toString());
// MylarTaskListPlugin.setCurrentPriorityLevel(Task.PriorityLevel.P3);
FILTER_PRIORITY.displayPrioritiesAbove(PRIORITY_LEVELS[2]);
getViewer().refresh();
}
};
P3.setEnabled(true);
P3.setText(Task.PriorityLevel.P3.getDescription());
P3.setImageDescriptor(TaskListImages.PRIORITY_3);
item = new ActionContributionItem(P3);
item.fill(dropDownMenu, -1);
Action P4 = new Action("", AS_CHECK_BOX) {
@Override
public void run() {
TasksUiPlugin.getDefault().getPreferenceStore().setValue(
TaskListPreferenceConstants.SELECTED_PRIORITY, Task.PriorityLevel.P4.toString());
// MylarTaskListPlugin.setCurrentPriorityLevel(Task.PriorityLevel.P4);
FILTER_PRIORITY.displayPrioritiesAbove(PRIORITY_LEVELS[3]);
getViewer().refresh();
}
};
P4.setEnabled(true);
P4.setText(Task.PriorityLevel.P4.getDescription());
P4.setImageDescriptor(TaskListImages.PRIORITY_4);
item = new ActionContributionItem(P4);
item.fill(dropDownMenu, -1);
Action P5 = new Action("", AS_CHECK_BOX) {
@Override
public void run() {
TasksUiPlugin.getDefault().getPreferenceStore().setValue(
TaskListPreferenceConstants.SELECTED_PRIORITY, Task.PriorityLevel.P5.toString());
// MylarTaskListPlugin.setCurrentPriorityLevel(Task.PriorityLevel.P5);
FILTER_PRIORITY.displayPrioritiesAbove(PRIORITY_LEVELS[4]);
getViewer().refresh();
}
};
P5.setEnabled(true);
P5.setImageDescriptor(TaskListImages.PRIORITY_5);
P5.setText(Task.PriorityLevel.P5.getDescription());
item = new ActionContributionItem(P5);
item.fill(dropDownMenu, -1);
String priority = getCurrentPriorityLevel();
if (priority.equals(PRIORITY_LEVELS[0])) {
P1.setChecked(true);
} else if (priority.equals(PRIORITY_LEVELS[1])) {
P1.setChecked(true);
P2.setChecked(true);
} else if (priority.equals(PRIORITY_LEVELS[2])) {
P1.setChecked(true);
P2.setChecked(true);
P3.setChecked(true);
} else if (priority.equals(PRIORITY_LEVELS[3])) {
P1.setChecked(true);
P2.setChecked(true);
P3.setChecked(true);
P4.setChecked(true);
} else if (priority.equals(PRIORITY_LEVELS[4])) {
P1.setChecked(true);
P2.setChecked(true);
P3.setChecked(true);
P4.setChecked(true);
P5.setChecked(true);
}
}
public void run() {
this.setChecked(isChecked());
}
}
public static TaskListView getFromActivePerspective() {
IWorkbenchPage activePage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
if (activePage != null) {
IViewPart view = activePage.findView(ID);
if (view instanceof TaskListView) {
return (TaskListView) view;
}
}
return null;
}
public static TaskListView openInActivePerspective() {
try {
return (TaskListView) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(ID);
} catch (Exception e) {
return null;
}
}
public TaskListView() {
TasksUiPlugin.getTaskListManager().addActivityListener(TASK_ACTIVITY_LISTENER);
TasksUiPlugin.getTaskListManager().getTaskList().addChangeListener(TASK_REFERESH_LISTENER);
}
@Override
public void dispose() {
super.dispose();
TasksUiPlugin.getTaskListManager().getTaskList().removeChangeListener(TASK_REFERESH_LISTENER);
TasksUiPlugin.getTaskListManager().removeActivityListener(TASK_ACTIVITY_LISTENER);
final IThemeManager themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
if (themeManager != null) {
themeManager.removePropertyChangeListener(THEME_CHANGE_LISTENER);
}
}
/**
* TODO: should be updated when view mode switches to fast and vice-versa
*/
private void updateDescription(ITask task) {
if (getSite() == null || getSite().getPage() == null)
return;
IViewReference reference = getSite().getPage().findViewReference(ID);
boolean shouldSetDescription = false;
if (reference != null && reference.isFastView()) {
shouldSetDescription = true;
}
if (task != null) {
setTitleToolTip(PART_NAME + " (" + task.getDescription() + ")");
if (shouldSetDescription) {
setContentDescription(task.getDescription());
} else {
setContentDescription("");
}
} else {
setTitleToolTip(PART_NAME);
if (shouldSetDescription) {
setContentDescription(LABEL_NO_TASKS);
} else {
setContentDescription("");
}
}
}
class TaskListCellModifier implements ICellModifier {
public boolean canModify(Object element, String property) {
int columnIndex = Arrays.asList(columnNames).indexOf(property);
if (columnIndex == 0 && element instanceof ITaskListElement) {
return element instanceof ITask || element instanceof AbstractQueryHit;
} else if (columnIndex == 2 && element instanceof ITask) {
return !(element instanceof AbstractRepositoryTask);
} else if (element instanceof ITaskListElement && isInRenameAction) {
switch (columnIndex) {
case 4:
// return element instanceof TaskCategory || element
// instanceof AbstractRepositoryQuery
return element instanceof AbstractTaskContainer
|| (element instanceof ITask && !(element instanceof AbstractRepositoryTask));
}
}
return false;
}
public Object getValue(Object element, String property) {
try {
int columnIndex = Arrays.asList(columnNames).indexOf(property);
if (element instanceof ITaskListElement) {
final ITaskListElement taskListElement = (ITaskListElement) element;
ITask task = null;
if (taskListElement instanceof ITask) {
task = (ITask) taskListElement;
} else if (taskListElement instanceof AbstractQueryHit) {
if (((AbstractQueryHit) taskListElement).getCorrespondingTask() != null) {
task = ((AbstractQueryHit) taskListElement).getCorrespondingTask();
}
}
switch (columnIndex) {
case 0:
if (task == null) {
return Boolean.TRUE;
} else {
return Boolean.valueOf(task.isCompleted());
}
case 1:
return "";
case 2:
String priorityString = taskListElement.getPriority().substring(1);
int priorityInt = new Integer(priorityString);
return priorityInt - 1;
case 3:
return "";
case 4:
return taskListElement.getDescription();
}
} else if (element instanceof AbstractTaskContainer) {
AbstractTaskContainer cat = (AbstractTaskContainer) element;
switch (columnIndex) {
case 0:
return Boolean.FALSE;
case 1:
return "";
case 2:
return "";
case 3:
return cat.getDescription();
}
} else if (element instanceof AbstractRepositoryQuery) {
AbstractRepositoryQuery cat = (AbstractRepositoryQuery) element;
switch (columnIndex) {
case 0:
return Boolean.FALSE;
case 1:
return "";
case 2:
return "";
case 3:
return cat.getDescription();
}
}
} catch (Exception e) {
MylarStatusHandler.log(e, e.getMessage());
}
return "";
}
public void modify(Object element, String property, Object value) {
int columnIndex = -1;
try {
columnIndex = Arrays.asList(columnNames).indexOf(property);
if (((TreeItem) element).getData() instanceof AbstractTaskContainer) {
AbstractTaskContainer container = (AbstractTaskContainer) ((TreeItem) element).getData();
switch (columnIndex) {
case 0:
break;
case 1:
break;
case 2:
break;
case 4:
TasksUiPlugin.getTaskListManager().getTaskList().renameContainer(container,
((String) value).trim());
// container.setDescription(((String) value).trim());
break;
}
} else if (((TreeItem) element).getData() instanceof AbstractRepositoryQuery) {
AbstractRepositoryQuery query = (AbstractRepositoryQuery) ((TreeItem) element).getData();
switch (columnIndex) {
case 0:
break;
case 1:
break;
case 2:
break;
case 4:
TasksUiPlugin.getTaskListManager().getTaskList()
.renameContainer(query, ((String) value).trim());
// cat.setDescription(((String) value).trim());
break;
}
} else if (((TreeItem) element).getData() instanceof ITaskListElement) {
final ITaskListElement taskListElement = (ITaskListElement) ((TreeItem) element).getData();
ITask task = null;
if (taskListElement instanceof ITask) {
task = (ITask) taskListElement;
} else if (taskListElement instanceof AbstractQueryHit) {
if (((AbstractQueryHit) taskListElement).getCorrespondingTask() != null) {
task = ((AbstractQueryHit) taskListElement).getCorrespondingTask();
}
}
switch (columnIndex) {
case 0:
if (taskListElement instanceof AbstractQueryHit) {
task = ((AbstractQueryHit) taskListElement).getOrCreateCorrespondingTask();
}
if (task != null) {
if (task.isActive()) {
new TaskDeactivateAction().run(task);
// nextTaskAction.setEnabled(taskHistory.hasNext());
// previousTaskAction.setEnabled(TasksUiPlugin.getTaskListManager().getTaskActivationHistory().hasPrevious());
previousTaskAction.setButtonStatus();
} else {
new TaskActivateAction().run(task);
addTaskToHistory(task);
previousTaskAction.setButtonStatus();
}
}
break;
case 1:
break;
case 2:
if (!(task instanceof AbstractRepositoryTask)) {
Integer intVal = (Integer) value;
task.setPriority("P" + (intVal + 1));
TasksUiPlugin.getTaskListManager().getTaskList().notifyLocalInfoChanged(task);
}
break;
case 4:
if (!(task instanceof AbstractRepositoryTask)) {
TasksUiPlugin.getTaskListManager().getTaskList().renameTask((Task) task,
((String) value).trim());
}
break;
}
}
} catch (Exception e) {
MylarStatusHandler.fail(e, e.getMessage(), true);
}
getViewer().refresh();
}
}
public void addTaskToHistory(ITask task) {
if (!TasksUiPlugin.getDefault().isMultipleActiveTasksMode()) {
TasksUiPlugin.getTaskListManager().getTaskActivationHistory().addTask(task);
// nextTaskAction.setEnabled(taskHistory.hasNext());
// previousTaskAction.setEnabled(TasksUiPlugin.getTaskListManager().getTaskActivationHistory().hasPrevious());
}
}
//
// public void clearTaskHistory() {
// TasksUiPlugin.getTaskListManager().getTaskActivationHistory().clear();
// }
@Override
public void init(IViewSite site, IMemento memento) throws PartInitException {
init(site);
this.taskListMemento = memento;
}
@Override
public void saveState(IMemento memento) {
IMemento colMemento = memento.createChild(columnWidthIdentifier);
for (int i = 0; i < columnWidths.length; i++) {
IMemento m = colMemento.createChild("col" + i);
m.putInteger(MEMENTO_KEY_WIDTH, columnWidths[i]);
}
IMemento sorter = memento.createChild(tableSortIdentifier);
IMemento m = sorter.createChild(MEMENTO_KEY_SORTER);
m.putInteger(MEMENTO_KEY_SORT_INDEX, sortIndex);
m.putInteger(MEMENTO_KEY_SORT_DIRECTION, sortDirection);
// TODO: move to task list save policy
if (TasksUiPlugin.getDefault() != null && TasksUiPlugin.getDefault().getTaskListSaveManager() != null) {
TasksUiPlugin.getDefault().getTaskListSaveManager().createTaskListBackupFile();
TasksUiPlugin.getDefault().getTaskListSaveManager().saveTaskList(true);
}
}
private void restoreState() {
if (taskListMemento != null) {
IMemento taskListWidth = taskListMemento.getChild(columnWidthIdentifier);
if (taskListWidth != null) {
for (int i = 0; i < columnWidths.length; i++) {
IMemento m = taskListWidth.getChild("col" + i);
if (m != null) {
int width = m.getInteger(MEMENTO_KEY_WIDTH);
columnWidths[i] = width;
columns[i].setWidth(width);
}
}
}
IMemento sorterMemento = taskListMemento.getChild(tableSortIdentifier);
if (sorterMemento != null) {
IMemento m = sorterMemento.getChild(MEMENTO_KEY_SORTER);
if (m != null) {
sortIndex = m.getInteger(MEMENTO_KEY_SORT_INDEX);
Integer sortDirInt = m.getInteger(MEMENTO_KEY_SORT_DIRECTION);
if (sortDirInt != null) {
sortDirection = sortDirInt.intValue();
}
} else {
sortIndex = 2;
sortDirection = DEFAULT_SORT_DIRECTION;
}
} else {
sortIndex = 2; // default priority
sortDirection = DEFAULT_SORT_DIRECTION;
}
tableSorter.setColumn(columnNames[sortIndex]);
getViewer().refresh(false);
// getViewer().setSorter(new TaskListTableSorter(this,
// columnNames[sortIndex]));
}
addFilter(FILTER_PRIORITY);
// if (MylarTaskListPlugin.getDefault().isFilterInCompleteMode())
// MylarTaskListPlugin.getTaskListManager().getTaskList().addFilter(inCompleteFilter);
if (TasksUiPlugin.getDefault().getPreferenceStore().contains(TaskListPreferenceConstants.FILTER_COMPLETE_MODE))
addFilter(FILTER_COMPLETE);
if (TasksUiPlugin.getDefault().getPreferenceStore().contains(TaskListPreferenceConstants.FILTER_ARCHIVE_MODE))
addFilter(FILTER_ARCHIVE);
if (TasksUiPlugin.getDefault().isMultipleActiveTasksMode()) {
togglePreviousAction(false);
// toggleNextAction(false);
}
getViewer().refresh();
}
@Override
public void createPartControl(Composite parent) {
themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
themeManager.addPropertyChangeListener(THEME_CHANGE_LISTENER);
filteredTree = new TaskListFilteredTree(parent, SWT.MULTI | SWT.VERTICAL | SWT.H_SCROLL | SWT.V_SCROLL
| SWT.FULL_SELECTION | SWT.HIDE_SELECTION, new TaskListPatternFilter());
getViewer().getTree().setHeaderVisible(true);
getViewer().getTree().setLinesVisible(true);
getViewer().setColumnProperties(columnNames);
getViewer().setUseHashlookup(true);
columns = new TreeColumn[columnNames.length];
for (int i = 0; i < columnNames.length; i++) {
columns[i] = new TreeColumn(getViewer().getTree(), 0); // SWT.LEFT
columns[i].setText(columnNames[i]);
columns[i].setWidth(columnWidths[i]);
final int index = i;
columns[i].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sortIndex = index;
sortDirection *= DEFAULT_SORT_DIRECTION;
tableSorter.setColumn(columnNames[sortIndex]);
getViewer().refresh(false);
// getViewer().setSorter(new
// TaskListTableSorter(TaskListView.this,
// columnNames[sortIndex]));
}
});
columns[i].addControlListener(new ControlListener() {
public void controlResized(ControlEvent e) {
for (int j = 0; j < columnWidths.length; j++) {
if (columns[j].equals(e.getSource())) {
columnWidths[j] = columns[j].getWidth();
}
}
}
public void controlMoved(ControlEvent e) {
// don't care if the control is moved
}
});
}
IThemeManager themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
Color categoryBackground = themeManager.getCurrentTheme().getColorRegistry().get(
TaskListColorsAndFonts.THEME_COLOR_TASKLIST_CATEGORY);
taskListTableLabelProvider = new TaskListTableLabelProvider(new TaskElementLabelProvider(), PlatformUI
.getWorkbench().getDecoratorManager().getLabelDecorator(), categoryBackground, this);
CellEditor[] editors = new CellEditor[columnNames.length];
TextCellEditor textEditor = new TextCellEditor(getViewer().getTree());
((Text) textEditor.getControl()).setOrientation(SWT.LEFT_TO_RIGHT);
editors[0] = new CheckboxCellEditor();
- editors[1] = textEditor;
+ editors[1] = null;
editors[2] = new ComboBoxCellEditor(getViewer().getTree(), PRIORITY_LEVEL_DESCRIPTIONS, SWT.READ_ONLY);
- editors[3] = textEditor;
+ editors[3] = null;
editors[4] = textEditor;
getViewer().setCellEditors(editors);
getViewer().setCellModifier(new TaskListCellModifier());
tableSorter = new TaskListTableSorter(this, columnNames[sortIndex]);
getViewer().setSorter(tableSorter);
drillDownAdapter = new DrillDownAdapter(getViewer());
getViewer().setContentProvider(new TaskListContentProvider(this));
getViewer().setLabelProvider(taskListTableLabelProvider);
getViewer().setInput(getViewSite());
getViewer().getTree().addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.F2 && e.stateMask == 0) {
if (renameAction.isEnabled()) {
renameAction.run();
}
} else if (e.keyCode == 'c' && e.stateMask == SWT.MOD1) {
copyDetailsAction.run();
} else if (e.keyCode == SWT.DEL) {
deleteAction.run();
} else if (e.keyCode == SWT.INSERT) {
newLocalTaskAction.run();
} else if (e.keyCode == 'f' && e.stateMask == SWT.MOD1) {
filteredTree.getFilterControl().setFocus();
} else if (e.stateMask == 0) {
if (Character.isLetter((char)e.keyCode) || Character.isDigit((char)e.keyCode)) {
String string = new Character((char)e.keyCode).toString();
filteredTree.getFilterControl().setText(string);
filteredTree.getFilterControl().setSelection(1, 1);
filteredTree.getFilterControl().setFocus();
}
}
}
public void keyReleased(KeyEvent e) {
}
});
// HACK: shouldn't need to update explicitly
getViewer().addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
Object selectedObject = ((IStructuredSelection) getViewer().getSelection()).getFirstElement();
if (selectedObject instanceof ITaskListElement) {
updateActionEnablement(renameAction, (ITaskListElement) selectedObject);
}
}
});
makeActions();
hookContextMenu();
hookOpenAction();
contributeToActionBars();
TaskListToolTipHandler taskListToolTipHandler = new TaskListToolTipHandler(getViewer().getControl().getShell());
taskListToolTipHandler.activateHoverHelp(getViewer().getControl());
getViewer().getTree().setToolTipText(null);
initDragAndDrop(parent);
expandToActiveTasks();
restoreState();
List<ITask> activeTasks = TasksUiPlugin.getTaskListManager().getTaskList().getActiveTasks();
if (activeTasks.size() > 0) {
updateDescription(activeTasks.get(0));
}
getSite().setSelectionProvider(getViewer());
}
private void initDragAndDrop(Composite parent) {
Transfer[] dragTypes = new Transfer[] { TaskTransfer.getInstance(), TextTransfer.getInstance(),
FileTransfer.getInstance() };
Transfer[] dropTypes = new Transfer[] { TaskTransfer.getInstance(), TextTransfer.getInstance(),
FileTransfer.getInstance(), // PluginTransfer.getInstance(),
RTFTransfer.getInstance() };
getViewer().addDragSupport(DND.DROP_COPY | DND.DROP_MOVE, dragTypes, new TaskListDragSourceListener(this));
getViewer().addDropSupport(DND.DROP_COPY | DND.DROP_MOVE, dropTypes, new TaskListDropAdapter(getViewer()));
}
void expandToActiveTasks() {
final IWorkbench workbench = PlatformUI.getWorkbench();
workbench.getDisplay().asyncExec(new Runnable() {
public void run() {
List<ITask> activeTasks = TasksUiPlugin.getTaskListManager().getTaskList().getActiveTasks();
for (ITask t : activeTasks) {
getViewer().expandToLevel(t, 0);
}
}
});
}
private void hookContextMenu() {
MenuManager menuManager = new MenuManager("#PopupMenu");
menuManager.setRemoveAllWhenShown(true);
menuManager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
TaskListView.this.fillContextMenu(manager);
}
});
Menu menu = menuManager.createContextMenu(getViewer().getControl());
getViewer().getControl().setMenu(menu);
getSite().registerContextMenu(menuManager, getViewer());
}
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
fillLocalPullDown(bars.getMenuManager());
fillLocalToolBar(bars.getToolBarManager());
}
private void fillLocalPullDown(IMenuManager manager) {
updateDrillDownActions();
manager.add(goUpAction);
manager.add(collapseAll);
manager.add(expandAll);
manager.add(new Separator(SEPARATOR_FILTERS));
manager.add(filterCompleteTask);
manager.add(filterArchiveCategory);
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}
private void fillLocalToolBar(IToolBarManager manager) {
manager.add(new Separator(SEPARATOR_ID_REPORTS));
manager.add(newLocalTaskAction);
// manager.add(newCategoryAction);
// manager.add(new Separator());
manager.add(filterOnPriority);
manager.add(new Separator("navigation"));
// manager.add(new Separator(SEPARATOR_CONTEXT));
manager.add(previousTaskAction);
// manager.add(nextTaskAction);
manager.add(new Separator(SEPARATOR_CONTEXT));
// manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}
private void fillContextMenu(IMenuManager manager) {
updateDrillDownActions();
ITaskListElement element = null;
final Object firstSelectedObject = ((IStructuredSelection) getViewer().getSelection()).getFirstElement();
if (firstSelectedObject instanceof ITaskListElement) {
element = (ITaskListElement) firstSelectedObject;
}
List<ITaskListElement> selectedElements = new ArrayList<ITaskListElement>();
for (Iterator i = ((IStructuredSelection) getViewer().getSelection()).iterator(); i.hasNext();) {
Object object = i.next();
if (object instanceof ITaskListElement) {
selectedElements.add((ITaskListElement) object);
}
}
openWithBrowser.selectionChanged((StructuredSelection) getViewer().getSelection());
addAction(openTaskEditor, manager, element);
ITask task = null;
if ((element instanceof ITask) || (element instanceof AbstractQueryHit)) {
if (element instanceof AbstractQueryHit) {
task = ((AbstractQueryHit) element).getCorrespondingTask();
} else {
task = (ITask) element;
}
addAction(openWithBrowser, manager, element);
if (!(element instanceof AbstractRepositoryTask) || element instanceof AbstractTaskContainer) {
addAction(renameAction, manager, element);
}
addAction(copyDetailsAction, manager, element);
if (task != null) {
if (!(task instanceof AbstractRepositoryTask) || task instanceof WebTask) {
if (task.isCompleted()) {
addAction(markCompleteAction, manager, element);
} else {
addAction(markIncompleteAction, manager, element);
}
}
addAction(removeFromCategoryAction, manager, element);
addAction(deleteAction, manager, element);
if (task.isActive()) {
manager.add(deactivateAction);
} else {
manager.add(activateAction);
}
} else {
manager.add(activateAction);
}
} else if (element instanceof AbstractTaskContainer || element instanceof AbstractRepositoryQuery) {
addAction(openWithBrowser, manager, element);
addAction(copyDetailsAction, manager, element);
addAction(deleteAction, manager, element);
}
if (element instanceof AbstractTaskContainer) {
manager.add(goIntoAction);
}
if (drilledIntoCategory != null) {
manager.add(goUpAction);
}
manager.add(new Separator());
for (IDynamicSubMenuContributor contributor : TasksUiPlugin.getDefault().getDynamicMenuContributers()) {
MenuManager subMenuManager = contributor.getSubMenuManager(selectedElements);
if (subMenuManager != null)
addMenuManager(subMenuManager, manager, element);
}
manager.add(new Separator(SEPARATOR_LOCAL));
manager.add(newCategoryAction);
manager.add(newLocalTaskAction);
manager.add(new Separator(SEPARATOR_REPORTS));
manager.add(new Separator(SEPARATOR_CONTEXT));
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}
private void addMenuManager(IMenuManager menuToAdd, IMenuManager manager, ITaskListElement element) {
if (element instanceof ITask || element instanceof AbstractQueryHit) {
manager.add(menuToAdd);
}
}
private void addAction(Action action, IMenuManager manager, ITaskListElement element) {
manager.add(action);
if (element != null) {
// ITaskHandler handler =
// MylarTaskListPlugin.getDefault().getHandlerForElement(element);
// if (handler != null) {
// action.setEnabled(handler.enableAction(action, element));
// } else {
updateActionEnablement(action, element);
// }
}
}
/**
* Refactor out element
*/
private void updateActionEnablement(Action action, ITaskListElement element) {
if (element instanceof ITask) {
if (action instanceof OpenWithBrowserAction) {
if (((ITask) element).hasValidUrl()) {
action.setEnabled(true);
} else {
action.setEnabled(false);
}
} else if (action instanceof DeleteAction) {
action.setEnabled(true);
} else if (action instanceof NewLocalTaskAction) {
action.setEnabled(false);
} else if (action instanceof OpenTaskListElementAction) {
action.setEnabled(true);
} else if (action instanceof CopyDetailsAction) {
action.setEnabled(true);
} else if (action instanceof RenameAction) {
action.setEnabled(true);
}
} else if (element instanceof AbstractTaskContainer) {
if (action instanceof MarkTaskCompleteAction) {
action.setEnabled(false);
} else if (action instanceof MarkTaskIncompleteAction) {
action.setEnabled(false);
} else if (action instanceof DeleteAction) {
if (element instanceof TaskArchive)
action.setEnabled(false);
else
action.setEnabled(true);
} else if (action instanceof NewLocalTaskAction) {
if (element instanceof TaskArchive)
action.setEnabled(false);
else
action.setEnabled(true);
} else if (action instanceof GoIntoAction) {
TaskCategory cat = (TaskCategory) element;
if (cat.getChildren().size() > 0) {
action.setEnabled(true);
} else {
action.setEnabled(false);
}
} else if (action instanceof OpenTaskListElementAction) {
action.setEnabled(true);
} else if (action instanceof CopyDetailsAction) {
action.setEnabled(true);
} else if (action instanceof RenameAction) {
if (element instanceof TaskArchive)
action.setEnabled(false);
else
action.setEnabled(true);
}
} else {
action.setEnabled(true);
}
// if(!canEnableGoInto){
// goIntoAction.setEnabled(false);
// }
}
private void makeActions() {
copyDetailsAction = new CopyDetailsAction(this);
// workOffline = new WorkOfflineAction();
goIntoAction = new GoIntoAction();
goUpAction = new GoUpAction(drillDownAdapter);
newLocalTaskAction = new NewLocalTaskAction(this);
newCategoryAction = new NewCategoryAction(this);
removeFromCategoryAction = new RemoveFromCategoryAction(this);
renameAction = new RenameAction(this);
deleteAction = new DeleteAction();
collapseAll = new CollapseAllAction(this);
expandAll = new ExpandAllAction(this);
// autoClose = new ManageEditorsAction();
markIncompleteAction = new MarkTaskCompleteAction(this);
markCompleteAction = new MarkTaskIncompleteAction(this);
openTaskEditor = new OpenTaskListElementAction(this.getViewer());
openWithBrowser = new OpenWithBrowserAction();
filterCompleteTask = new FilterCompletedTasksAction(this);
filterArchiveCategory = new FilterArchiveContainerAction(this);
filterOnPriority = new PriorityDropDownAction();
previousTaskAction = new PreviousTaskDropDownAction(this, TasksUiPlugin.getTaskListManager()
.getTaskActivationHistory());
// nextTaskAction = new NextTaskDropDownAction(this,
// TasksUiPlugin.getTaskListManager().getTaskActivationHistory());
}
// public void toggleNextAction(boolean enable) {
// nextTaskAction.setEnabled(enable);
// }
// public NextTaskDropDownAction getNextTaskAction() {
// return nextTaskAction;
// }
public void togglePreviousAction(boolean enable) {
previousTaskAction.setEnabled(enable);
}
public PreviousTaskDropDownAction getPreviousTaskAction() {
return previousTaskAction;
}
/**
* Recursive function that checks for the occurrence of a certain task id.
* All children of the supplied node will be checked.
*
* @param task
* The <code>ITask</code> object that is to be searched.
* @param taskId
* The id that is being searched for.
* @return <code>true</code> if the id was found in the node or any of its
* children
*/
protected boolean lookForId(String taskId) {
return (TasksUiPlugin.getTaskListManager().getTaskList().getTask(taskId) == null);
// for (ITask task :
// MylarTaskListPlugin.getTaskListManager().getTaskList().getRootTasks())
// {
// if (task.getHandle().equals(taskId)) {
// return true;
// }
// }
// for (TaskCategory cat :
// MylarTaskListPlugin.getTaskListManager().getTaskList().getTaskCategories())
// {
// for (ITask task : cat.getChildren()) {
// if (task.getHandle().equals(taskId)) {
// return true;
// }
// }
// }
// return false;
}
private void hookOpenAction() {
getViewer().addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
if (TasksUiPlugin.getDefault().getPreferenceStore().getBoolean(
TaskListPreferenceConstants.ACTIVATE_ON_OPEN)) {
ITask selectedTask = TaskListView.getFromActivePerspective().getSelectedTask();
if (selectedTask != null) {
activateAction.run(selectedTask);
addTaskToHistory(selectedTask);
previousTaskAction.setButtonStatus();
}
}
openTaskEditor.run();
}
});
}
/**
* Passing the focus request to the viewer's control.
*/
@Override
public void setFocus() {
filteredTree.getViewer().getControl().setFocus();
}
public String getBugIdFromUser() {
InputDialog dialog = new InputDialog(getSite().getWorkbenchWindow().getShell(), "Enter Bugzilla ID",
"Enter the Bugzilla ID: ", "", null);
int dialogResult = dialog.open();
if (dialogResult == Window.OK) {
return dialog.getValue();
} else {
return null;
}
}
public void refreshAndFocus(boolean expand) {
getViewer().getControl().setRedraw(false);
getViewer().refresh();
if (expand) {
getViewer().expandAll();
}
selectedAndFocusTask(TasksUiPlugin.getTaskListManager().getTaskList().getActiveTask());
getViewer().getControl().setRedraw(true);
}
public TreeViewer getViewer() {
return filteredTree.getViewer();
}
public TaskCompletionFilter getCompleteFilter() {
return FILTER_COMPLETE;
}
public TaskPriorityFilter getPriorityFilter() {
return FILTER_PRIORITY;
}
public void addFilter(AbstractTaskListFilter filter) {
if (!filters.contains(filter)) {
filters.add(filter);
}
}
public void clearFilters(boolean preserveArchiveFilter) {
filters.clear();
if (preserveArchiveFilter) {
filters.add(FILTER_ARCHIVE);
}
}
public void removeFilter(AbstractTaskListFilter filter) {
filters.remove(filter);
}
public void updateDrillDownActions() {
if (drillDownAdapter.canGoBack()) {
goUpAction.setEnabled(true);
} else {
goUpAction.setEnabled(false);
}
}
/**
* HACK: This is used for the copy action
*/
public Composite getDummyComposite() {
return filteredTree;
}
private boolean isInRenameAction = false;
public void setInRenameAction(boolean b) {
isInRenameAction = b;
}
// /**
// * This method is for testing only
// */
// public TaskActivationHistory getTaskActivationHistory() {
// return TasksUiPlugin.getTaskListManager().getTaskActivationHistory();
// }
public void goIntoCategory() {
ISelection selection = getViewer().getSelection();
if (selection instanceof StructuredSelection) {
StructuredSelection structuredSelection = (StructuredSelection) selection;
Object element = structuredSelection.getFirstElement();
if (element instanceof AbstractTaskContainer) {
drilledIntoCategory = (AbstractTaskContainer) element;
drillDownAdapter.goInto();
updateDrillDownActions();
}
}
}
public void goUpToRoot() {
drilledIntoCategory = null;
drillDownAdapter.goBack();
updateDrillDownActions();
}
public ITask getSelectedTask() {
ISelection selection = getViewer().getSelection();
if (selection.isEmpty())
return null;
if (selection instanceof StructuredSelection) {
StructuredSelection structuredSelection = (StructuredSelection) selection;
Object element = structuredSelection.getFirstElement();
if (element instanceof ITask) {
return (ITask) structuredSelection.getFirstElement();
} else if (element instanceof AbstractQueryHit) {
return ((AbstractQueryHit) element).getOrCreateCorrespondingTask();
}
}
return null;
}
public static ITask getSelectedTask(ISelection selection) {
if (selection instanceof StructuredSelection) {
StructuredSelection structuredSelection = (StructuredSelection) selection;
if (structuredSelection.size() != 1) {
return null;
}
Object element = structuredSelection.getFirstElement();
if (element instanceof ITask) {
return (ITask) structuredSelection.getFirstElement();
} else if (element instanceof AbstractQueryHit) {
return ((AbstractQueryHit) element).getCorrespondingTask();
}
}
return null;
}
public void indicatePaused(boolean paused) {
isPaused = paused;
IStatusLineManager statusLineManager = getViewSite().getActionBars().getStatusLineManager();
if (isPaused) {
statusLineManager.setMessage(TaskListImages.getImage(TaskListImages.TASKLIST),
"Mylar context capture paused");
} else {
statusLineManager.setMessage("");
}
}
/**
* Show the shared data folder currently in use. Call with "" to turn off
* the indication. TODO: Need a better way to indicate paused and/or the
* shared folder
*/
public void indicateSharedFolder(String folderName) {
if (folderName.equals("")) {
if (isPaused) {
setPartName("(paused) " + PART_NAME);
} else {
setPartName(PART_NAME);
}
} else {
if (isPaused) {
setPartName("(paused) " + folderName + " " + PART_NAME);
} else {
setPartName(folderName + " " + PART_NAME);
}
}
}
public AbstractTaskContainer getDrilledIntoCategory() {
return drilledIntoCategory;
}
public TaskListFilteredTree getFilteredTree() {
return filteredTree;
}
public void selectedAndFocusTask(ITask task) {
if (task == null || getViewer().getControl().isDisposed()) {
return;
}
// StructuredSelection currentSelection = (StructuredSelection)
// getViewer().getSelection();
// ITask selectedTask = null;
// if (currentSelection.getFirstElement() instanceof ITask) {
// selectedTask = (ITask) currentSelection.getFirstElement();
// } else if (currentSelection.getFirstElement() instanceof
// AbstractQueryHit) {
// selectedTask = ((AbstractQueryHit)
// currentSelection.getFirstElement()).getCorrespondingTask();
// }
// if (!task.equals(selectedTask)) {
getViewer().setSelection(new StructuredSelection(task), true);
// if no task exists, select the query hit if exists
AbstractQueryHit hit = null;
if (getViewer().getSelection().isEmpty()
&& (hit = TasksUiPlugin.getTaskListManager().getTaskList().getQueryHitForHandle(
task.getHandleIdentifier())) != null) {
AbstractRepositoryQuery query = TasksUiPlugin.getTaskListManager().getTaskList().getQueryForHandle(
task.getHandleIdentifier());
getViewer().expandToLevel(query, 1);
getViewer().setSelection(new StructuredSelection(hit), true);
} else {
// if (task.getc() != null) {
// getViewer().expandToLevel(task.getContainer(), 1);
// }
// getViewer().setSelection(new StructuredSelection(hit), true);
}
// }
}
protected void refreshTask(ITask task) {
refresh(task);
AbstractTaskContainer rootCategory = TasksUiPlugin.getTaskListManager().getTaskList().getRootCategory();
if (task.getContainer() == null // || task.getContainer() instanceof
// TaskArchive
|| task.getContainer().equals(rootCategory)) {
refresh(null);
} else {
refresh(task.getContainer());
}
Set<AbstractQueryHit> hits = TasksUiPlugin.getTaskListManager().getTaskList().getQueryHitsForHandle(
task.getHandleIdentifier());
for (AbstractQueryHit hit : hits) {
refresh(hit);
}
}
private void refresh(final ITaskListElement element) {
if (PlatformUI.getWorkbench() != null && !PlatformUI.getWorkbench().getDisplay().isDisposed()) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
if (getViewer().getControl() != null && !getViewer().getControl().isDisposed()) {
if (element == null) {
// getViewer().refresh();
filteredTree.textChanged();
} else {
getViewer().refresh(element, true);
if (element instanceof AbstractTaskContainer
&& !((AbstractTaskContainer) element).equals(TasksUiPlugin.getTaskListManager()
.getTaskList().getArchiveContainer())) {
List visibleElements = Arrays.asList(getViewer().getVisibleExpandedElements());
if (!visibleElements.contains(element)) {
getViewer().refresh();
}
}
}
}
}
});
}
}
public Image[] getPirorityImages() {
Image[] images = new Image[Task.PriorityLevel.values().length];
for (int i = 0; i < Task.PriorityLevel.values().length; i++) {
images[i] = TaskUiUtil.getImageForPriority(Task.PriorityLevel.values()[i]);
}
return images;
}
public Set<AbstractTaskListFilter> getFilters() {
return filters;
}
public static String getCurrentPriorityLevel() {
if (TasksUiPlugin.getDefault().getPreferenceStore().contains(TaskListPreferenceConstants.SELECTED_PRIORITY)) {
return TasksUiPlugin.getDefault().getPreferenceStore().getString(
TaskListPreferenceConstants.SELECTED_PRIORITY);
} else {
return Task.PriorityLevel.P5.toString();
}
}
public TaskArchiveFilter getArchiveFilter() {
return FILTER_ARCHIVE;
}
public void setPriorityButtonEnabled(boolean enabled) {
filterOnPriority.setEnabled(enabled);
}
}
| false | true | public void createPartControl(Composite parent) {
themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
themeManager.addPropertyChangeListener(THEME_CHANGE_LISTENER);
filteredTree = new TaskListFilteredTree(parent, SWT.MULTI | SWT.VERTICAL | SWT.H_SCROLL | SWT.V_SCROLL
| SWT.FULL_SELECTION | SWT.HIDE_SELECTION, new TaskListPatternFilter());
getViewer().getTree().setHeaderVisible(true);
getViewer().getTree().setLinesVisible(true);
getViewer().setColumnProperties(columnNames);
getViewer().setUseHashlookup(true);
columns = new TreeColumn[columnNames.length];
for (int i = 0; i < columnNames.length; i++) {
columns[i] = new TreeColumn(getViewer().getTree(), 0); // SWT.LEFT
columns[i].setText(columnNames[i]);
columns[i].setWidth(columnWidths[i]);
final int index = i;
columns[i].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sortIndex = index;
sortDirection *= DEFAULT_SORT_DIRECTION;
tableSorter.setColumn(columnNames[sortIndex]);
getViewer().refresh(false);
// getViewer().setSorter(new
// TaskListTableSorter(TaskListView.this,
// columnNames[sortIndex]));
}
});
columns[i].addControlListener(new ControlListener() {
public void controlResized(ControlEvent e) {
for (int j = 0; j < columnWidths.length; j++) {
if (columns[j].equals(e.getSource())) {
columnWidths[j] = columns[j].getWidth();
}
}
}
public void controlMoved(ControlEvent e) {
// don't care if the control is moved
}
});
}
IThemeManager themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
Color categoryBackground = themeManager.getCurrentTheme().getColorRegistry().get(
TaskListColorsAndFonts.THEME_COLOR_TASKLIST_CATEGORY);
taskListTableLabelProvider = new TaskListTableLabelProvider(new TaskElementLabelProvider(), PlatformUI
.getWorkbench().getDecoratorManager().getLabelDecorator(), categoryBackground, this);
CellEditor[] editors = new CellEditor[columnNames.length];
TextCellEditor textEditor = new TextCellEditor(getViewer().getTree());
((Text) textEditor.getControl()).setOrientation(SWT.LEFT_TO_RIGHT);
editors[0] = new CheckboxCellEditor();
editors[1] = textEditor;
editors[2] = new ComboBoxCellEditor(getViewer().getTree(), PRIORITY_LEVEL_DESCRIPTIONS, SWT.READ_ONLY);
editors[3] = textEditor;
editors[4] = textEditor;
getViewer().setCellEditors(editors);
getViewer().setCellModifier(new TaskListCellModifier());
tableSorter = new TaskListTableSorter(this, columnNames[sortIndex]);
getViewer().setSorter(tableSorter);
drillDownAdapter = new DrillDownAdapter(getViewer());
getViewer().setContentProvider(new TaskListContentProvider(this));
getViewer().setLabelProvider(taskListTableLabelProvider);
getViewer().setInput(getViewSite());
getViewer().getTree().addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.F2 && e.stateMask == 0) {
if (renameAction.isEnabled()) {
renameAction.run();
}
} else if (e.keyCode == 'c' && e.stateMask == SWT.MOD1) {
copyDetailsAction.run();
} else if (e.keyCode == SWT.DEL) {
deleteAction.run();
} else if (e.keyCode == SWT.INSERT) {
newLocalTaskAction.run();
} else if (e.keyCode == 'f' && e.stateMask == SWT.MOD1) {
filteredTree.getFilterControl().setFocus();
} else if (e.stateMask == 0) {
if (Character.isLetter((char)e.keyCode) || Character.isDigit((char)e.keyCode)) {
String string = new Character((char)e.keyCode).toString();
filteredTree.getFilterControl().setText(string);
filteredTree.getFilterControl().setSelection(1, 1);
filteredTree.getFilterControl().setFocus();
}
}
}
public void keyReleased(KeyEvent e) {
}
});
// HACK: shouldn't need to update explicitly
getViewer().addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
Object selectedObject = ((IStructuredSelection) getViewer().getSelection()).getFirstElement();
if (selectedObject instanceof ITaskListElement) {
updateActionEnablement(renameAction, (ITaskListElement) selectedObject);
}
}
});
makeActions();
hookContextMenu();
hookOpenAction();
contributeToActionBars();
TaskListToolTipHandler taskListToolTipHandler = new TaskListToolTipHandler(getViewer().getControl().getShell());
taskListToolTipHandler.activateHoverHelp(getViewer().getControl());
getViewer().getTree().setToolTipText(null);
initDragAndDrop(parent);
expandToActiveTasks();
restoreState();
List<ITask> activeTasks = TasksUiPlugin.getTaskListManager().getTaskList().getActiveTasks();
if (activeTasks.size() > 0) {
updateDescription(activeTasks.get(0));
}
getSite().setSelectionProvider(getViewer());
}
| public void createPartControl(Composite parent) {
themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
themeManager.addPropertyChangeListener(THEME_CHANGE_LISTENER);
filteredTree = new TaskListFilteredTree(parent, SWT.MULTI | SWT.VERTICAL | SWT.H_SCROLL | SWT.V_SCROLL
| SWT.FULL_SELECTION | SWT.HIDE_SELECTION, new TaskListPatternFilter());
getViewer().getTree().setHeaderVisible(true);
getViewer().getTree().setLinesVisible(true);
getViewer().setColumnProperties(columnNames);
getViewer().setUseHashlookup(true);
columns = new TreeColumn[columnNames.length];
for (int i = 0; i < columnNames.length; i++) {
columns[i] = new TreeColumn(getViewer().getTree(), 0); // SWT.LEFT
columns[i].setText(columnNames[i]);
columns[i].setWidth(columnWidths[i]);
final int index = i;
columns[i].addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
sortIndex = index;
sortDirection *= DEFAULT_SORT_DIRECTION;
tableSorter.setColumn(columnNames[sortIndex]);
getViewer().refresh(false);
// getViewer().setSorter(new
// TaskListTableSorter(TaskListView.this,
// columnNames[sortIndex]));
}
});
columns[i].addControlListener(new ControlListener() {
public void controlResized(ControlEvent e) {
for (int j = 0; j < columnWidths.length; j++) {
if (columns[j].equals(e.getSource())) {
columnWidths[j] = columns[j].getWidth();
}
}
}
public void controlMoved(ControlEvent e) {
// don't care if the control is moved
}
});
}
IThemeManager themeManager = getSite().getWorkbenchWindow().getWorkbench().getThemeManager();
Color categoryBackground = themeManager.getCurrentTheme().getColorRegistry().get(
TaskListColorsAndFonts.THEME_COLOR_TASKLIST_CATEGORY);
taskListTableLabelProvider = new TaskListTableLabelProvider(new TaskElementLabelProvider(), PlatformUI
.getWorkbench().getDecoratorManager().getLabelDecorator(), categoryBackground, this);
CellEditor[] editors = new CellEditor[columnNames.length];
TextCellEditor textEditor = new TextCellEditor(getViewer().getTree());
((Text) textEditor.getControl()).setOrientation(SWT.LEFT_TO_RIGHT);
editors[0] = new CheckboxCellEditor();
editors[1] = null;
editors[2] = new ComboBoxCellEditor(getViewer().getTree(), PRIORITY_LEVEL_DESCRIPTIONS, SWT.READ_ONLY);
editors[3] = null;
editors[4] = textEditor;
getViewer().setCellEditors(editors);
getViewer().setCellModifier(new TaskListCellModifier());
tableSorter = new TaskListTableSorter(this, columnNames[sortIndex]);
getViewer().setSorter(tableSorter);
drillDownAdapter = new DrillDownAdapter(getViewer());
getViewer().setContentProvider(new TaskListContentProvider(this));
getViewer().setLabelProvider(taskListTableLabelProvider);
getViewer().setInput(getViewSite());
getViewer().getTree().addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.F2 && e.stateMask == 0) {
if (renameAction.isEnabled()) {
renameAction.run();
}
} else if (e.keyCode == 'c' && e.stateMask == SWT.MOD1) {
copyDetailsAction.run();
} else if (e.keyCode == SWT.DEL) {
deleteAction.run();
} else if (e.keyCode == SWT.INSERT) {
newLocalTaskAction.run();
} else if (e.keyCode == 'f' && e.stateMask == SWT.MOD1) {
filteredTree.getFilterControl().setFocus();
} else if (e.stateMask == 0) {
if (Character.isLetter((char)e.keyCode) || Character.isDigit((char)e.keyCode)) {
String string = new Character((char)e.keyCode).toString();
filteredTree.getFilterControl().setText(string);
filteredTree.getFilterControl().setSelection(1, 1);
filteredTree.getFilterControl().setFocus();
}
}
}
public void keyReleased(KeyEvent e) {
}
});
// HACK: shouldn't need to update explicitly
getViewer().addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
Object selectedObject = ((IStructuredSelection) getViewer().getSelection()).getFirstElement();
if (selectedObject instanceof ITaskListElement) {
updateActionEnablement(renameAction, (ITaskListElement) selectedObject);
}
}
});
makeActions();
hookContextMenu();
hookOpenAction();
contributeToActionBars();
TaskListToolTipHandler taskListToolTipHandler = new TaskListToolTipHandler(getViewer().getControl().getShell());
taskListToolTipHandler.activateHoverHelp(getViewer().getControl());
getViewer().getTree().setToolTipText(null);
initDragAndDrop(parent);
expandToActiveTasks();
restoreState();
List<ITask> activeTasks = TasksUiPlugin.getTaskListManager().getTaskList().getActiveTasks();
if (activeTasks.size() > 0) {
updateDescription(activeTasks.get(0));
}
getSite().setSelectionProvider(getViewer());
}
|
diff --git a/52n-sos-importer-feeder/src/test/java/org/n52/sos/importer/feeder/model/TimestampTest.java b/52n-sos-importer-feeder/src/test/java/org/n52/sos/importer/feeder/model/TimestampTest.java
index 16494080..050c0cbe 100644
--- a/52n-sos-importer-feeder/src/test/java/org/n52/sos/importer/feeder/model/TimestampTest.java
+++ b/52n-sos-importer-feeder/src/test/java/org/n52/sos/importer/feeder/model/TimestampTest.java
@@ -1,69 +1,70 @@
/**
* Copyright (C) 2013
* by 52 North Initiative for Geospatial Open Source Software GmbH
*
* Contact: Andreas Wytzisk
* 52 North Initiative for Geospatial Open Source Software GmbH
* Martin-Luther-King-Weg 24
* 48155 Muenster, Germany
* [email protected]
*
* This program is free software; you can redistribute and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
*
* This program is distributed WITHOUT ANY WARRANTY; even without 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 (see gnu-gpl v2.txt). If not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA or
* visit the Free Software Foundation web page, http://www.fsf.org.
*/
package org.n52.sos.importer.feeder.model;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.TimeZone;
import org.junit.Before;
import org.junit.Test;
/**
*
*/
public class TimestampTest {
private Timestamp timestamp;
private final int millisPerMinute = 1000 * 60;
private final int millisPerHour = millisPerMinute * 60;
@Before
public void createTimestamp() throws Exception
{
timestamp = new Timestamp();
}
@Test public void
shouldSetAllValuesViaSetLong() {
timestamp.set(86401000);
final TimeZone tz = TimeZone.getDefault();
String sign = "-";
- final int rawOffset = tz.getRawOffset();
+ int rawOffset = tz.getRawOffset();
if (rawOffset>= 0) {
sign = "+";
}
+ rawOffset = Math.abs(rawOffset);
final int hours = rawOffset / millisPerHour;
final int minutes = (rawOffset - (hours * millisPerHour)) / millisPerMinute;
final String minutesString = minutes < 10? "0"+minutes : minutes < 60? Integer.toString(minutes) : "00";
final String hoursString = hours < 10? "0"+hours : Integer.toString(hours);
final String asExpected = String.format("1970-01-02T01:00:01%s%s:%s",sign, hoursString, minutesString);
assertThat(timestamp.toString(),is(asExpected));
}
}
| false | true | @Test public void
shouldSetAllValuesViaSetLong() {
timestamp.set(86401000);
final TimeZone tz = TimeZone.getDefault();
String sign = "-";
final int rawOffset = tz.getRawOffset();
if (rawOffset>= 0) {
sign = "+";
}
final int hours = rawOffset / millisPerHour;
final int minutes = (rawOffset - (hours * millisPerHour)) / millisPerMinute;
final String minutesString = minutes < 10? "0"+minutes : minutes < 60? Integer.toString(minutes) : "00";
final String hoursString = hours < 10? "0"+hours : Integer.toString(hours);
final String asExpected = String.format("1970-01-02T01:00:01%s%s:%s",sign, hoursString, minutesString);
assertThat(timestamp.toString(),is(asExpected));
}
| @Test public void
shouldSetAllValuesViaSetLong() {
timestamp.set(86401000);
final TimeZone tz = TimeZone.getDefault();
String sign = "-";
int rawOffset = tz.getRawOffset();
if (rawOffset>= 0) {
sign = "+";
}
rawOffset = Math.abs(rawOffset);
final int hours = rawOffset / millisPerHour;
final int minutes = (rawOffset - (hours * millisPerHour)) / millisPerMinute;
final String minutesString = minutes < 10? "0"+minutes : minutes < 60? Integer.toString(minutes) : "00";
final String hoursString = hours < 10? "0"+hours : Integer.toString(hours);
final String asExpected = String.format("1970-01-02T01:00:01%s%s:%s",sign, hoursString, minutesString);
assertThat(timestamp.toString(),is(asExpected));
}
|
diff --git a/src/com/chess/genesis/GameState.java b/src/com/chess/genesis/GameState.java
index 48bf5fc..1be3419 100644
--- a/src/com/chess/genesis/GameState.java
+++ b/src/com/chess/genesis/GameState.java
@@ -1,652 +1,655 @@
package com.chess.genesis;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
class GameState
{
public static GameState self;
private final Context context;
private final Bundle settings;
private final NetworkClient net;
private final ProgressMsg progress;
private final ObjectArray<Move> history;
private final Board board;
private final IntArray callstack;
private final int ycol;
private final int type;
private int hindex = -1;
private final Handler handle = new Handler()
{
public void handleMessage(final Message msg)
{
try {
switch (msg.what) {
case NetworkClient.SUBMIT_MOVE:
JSONObject json = (JSONObject) msg.obj;
if (json.getString("result").equals("error")) {
progress.remove();
Toast.makeText(context, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
return;
}
progress.setText(json.getString("reason"));
net.game_status(settings.getString("gameid"));
(new Thread(net)).start();
break;
case ResignConfirm.MSG:
progress.setText("Sending resignation");
net.resign_game(settings.getString("gameid"));
(new Thread(net)).start();
break;
case NetworkClient.RESIGN_GAME:
json = (JSONObject) msg.obj;
if (json.getString("result").equals("error")) {
progress.remove();
Toast.makeText(context, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
return;
}
progress.setText("Resignation sent");
net.game_status(settings.getString("gameid"));
(new Thread(net)).run();
break;
case NetworkClient.GAME_STATUS:
json = (JSONObject) msg.obj;
if (json.getString("result").equals("error")) {
progress.remove();
Toast.makeText(context, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
return;
}
final String gameid = json.getString("gameid");
final String zfen = json.getString("zfen");
final String history = json.getString("history");
final int status = Enums.GameStatus(json.getString("status"));
final long stime = json.getLong("stime");
settings.putString("status", String.valueOf(status));
final GameDataDB db = new GameDataDB(context);
db.updateOnlineGame(gameid, status, stime, zfen, history);
db.close();
applyRemoteMove(history);
if (status != Enums.ACTIVE) {
if (Integer.valueOf(settings.getString("eventtype")) == Enums.INVITE) {
progress.remove();
json.put("yourcolor", ycol);
json.put("white_name", settings.getString("white"));
json.put("black_name", settings.getString("black"));
json.put("eventtype", settings.getString("eventtype"));
json.put("status", settings.getString("status"));
json.put("gametype", Enums.GameType(Integer.valueOf(settings.getString("gametype"))));
json.put("gameid", settings.getString("gameid"));
(new EndGameDialog(context, json)).show();
return;
}
progress.setText("Retrieving score");
settings.putString("status", String.valueOf(status));
net.game_score(settings.getString("gameid"));
(new Thread(net)).start();
+ } else {
+ progress.setText("Status Synced");
+ progress.remove();
}
break;
case NetworkClient.GAME_SCORE:
json = (JSONObject) msg.obj;
if (json.getString("result").equals("error")) {
progress.remove();
Toast.makeText(context, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
return;
}
progress.setText("Score loaded");
progress.remove();
json.put("yourcolor", ycol);
json.put("white_name", settings.getString("white"));
json.put("black_name", settings.getString("black"));
json.put("eventtype", settings.getString("eventtype"));
json.put("status", settings.getString("status"));
json.put("gametype", Enums.GameType(Integer.valueOf(settings.getString("gametype"))));
json.put("gameid", settings.getString("gameid"));
(new EndGameDialog(context, json)).show();
break;
case RematchConfirm.MSG:
Bundle data = (Bundle) msg.obj;
progress.setText("Sending newgame request");
final String opponent = data.getString("opp_name");
String color = Enums.ColorType(data.getInt("color"));
String gametype = Enums.GameType(data.getInt("gametype"));
net.new_game(opponent, gametype, color);
(new Thread(net)).start();
break;
case NetworkClient.NEW_GAME:
json = (JSONObject) msg.obj;
try {
if (json.getString("result").equals("error")) {
progress.remove();
Toast.makeText(context, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
return;
}
progress.setText(json.getString("reason"));
progress.remove();
} catch (JSONException e) {
e.printStackTrace();
throw new RuntimeException();
}
break;
}
} catch (JSONException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
};
private void check_endgame()
{
switch (type) {
case Enums.LOCAL_GAME:
return;
case Enums.ONLINE_GAME:
if (Integer.valueOf(settings.getString("status")) == Enums.ACTIVE) {
return;
} else if (Integer.valueOf(settings.getString("eventtype")) == Enums.INVITE) {
try {
final JSONObject json = new JSONObject();
json.put("yourcolor", ycol);
json.put("white_name", settings.getString("white"));
json.put("black_name", settings.getString("black"));
json.put("eventtype", settings.getString("eventtype"));
json.put("status", settings.getString("status"));
json.put("gametype", Enums.GameType(Integer.valueOf(settings.getString("gametype"))));
json.put("gameid", settings.getString("gameid"));
(new EndGameDialog(context, json)).show();
} catch (JSONException e) {
e.printStackTrace();
throw new RuntimeException();
}
} else {
progress.setText("Retrieving score");
net.game_score(settings.getString("gameid"));
(new Thread(net)).run();
}
break;
case Enums.ARCHIVE_GAME:
settings.putInt("yourcolor", ycol);
(new GameStatsDialog(context, settings)).show();
break;
}
}
public GameState(final Context _context, final Bundle _settings)
{
self = this;
context = _context;
settings = _settings;
callstack = new IntArray();
history = new ObjectArray<Move>();
board = new Board();
progress = new ProgressMsg(context);
type = settings.getInt("type", Enums.ONLINE_GAME);
switch (type) {
case Enums.LOCAL_GAME:
default:
net = null;
ycol = Piece.WHITE;
break;
case Enums.ONLINE_GAME:
net = new NetworkClient(context, handle);
ycol = settings.getString("username").equals(settings.getString("white"))? 1 : -1;
break;
case Enums.ARCHIVE_GAME:
net = null;
ycol = settings.getString("username").equals(settings.getString("white"))? 1 : -1;
break;
}
final String tmp = settings.getString("history");
if (tmp == null || tmp.length() < 3) {
setStm();
check_endgame();
return;
}
final String[] movehistory = tmp.trim().split(" +");
for (int i = 0; i < movehistory.length; i++) {
final Move move = new Move();
move.parse(movehistory[i]);
if (board.validMove(move) != Board.VALID_MOVE)
break;
board.make(move);
history.push(move);
hindex++;
}
setBoard();
check_endgame();
}
private void setBoard()
{
// set place piece counts
final int[] pieces = board.getPieceCounts();
for (int i = -6; i < 0; i++) {
final PlaceButton button = (PlaceButton) Game.self.findViewById(i + 100);
button.setCount(pieces[i + 6]);
}
for (int i = 1; i < 7; i++) {
final PlaceButton button = (PlaceButton) Game.self.findViewById(i + 100);
button.setCount(pieces[i + 6]);
}
// set board pieces
final int[] squares = board.getBoardArray();
for (int i = 0; i < 64; i++) {
final BoardButton button = (BoardButton) Game.self.findViewById(i);
button.setPiece(squares[i]);
}
// move caused check
if (board.incheck(board.getStm())) {
final int king = board.kingIndex(board.getStm());
final BoardButton kingI = (BoardButton) Game.self.findViewById(king);
kingI.setCheck(true);
}
setStm();
}
public final void setStm()
{
String check, wstr, bstr;
switch (board.isMate()) {
case Board.NOT_MATE:
default:
if (board.incheck(board.getStm()))
check = " (check)";
else
check = "";
break;
case Board.CHECK_MATE:
check = " (checkmate)";
break;
case Board.STALE_MATE:
check = " (stalemate)";
break;
}
if (type == Enums.LOCAL_GAME) {
wstr = "White";
bstr = "Black";
} else {
wstr = settings.getString("white");
bstr = settings.getString("black");
}
final TextView white = (TextView) Game.self.findViewById(R.id.white_name);
final TextView black = (TextView) Game.self.findViewById(R.id.black_name);
if (board.getStm() == Piece.WHITE) {
white.setText(wstr + check);
black.setText(bstr);
white.setTypeface(Typeface.DEFAULT_BOLD);
black.setTypeface(Typeface.DEFAULT);
} else {
white.setText(wstr);
black.setText(bstr + check);
white.setTypeface(Typeface.DEFAULT);
black.setTypeface(Typeface.DEFAULT_BOLD);
}
}
public void save(final Context context, final boolean exitgame)
{
switch (type) {
case Enums.LOCAL_GAME:
final GameDataDB db = new GameDataDB(context);
final int id = Integer.valueOf(settings.getString("id"));
if (history.size() < 1) {
db.deleteLocalGame(id);
db.close();
return;
}
if (exitgame) {
db.close();
return;
}
final long stime = (new Date()).getTime();
final String zfen = board.getPosition().printZfen();
final String hist = history.toString();
db.saveLocalGame(id, stime, zfen, hist);
db.close();
break;
case Enums.ONLINE_GAME:
if (exitgame)
return;
Game.self.displaySubmitMove();
case Enums.ARCHIVE_GAME:
break;
}
}
public void resign()
{
(new ResignConfirm(context, handle)).show();
}
public void rematch()
{
final String opp = settings.getString("username").equals(settings.getString("white"))?
settings.getString("black") : settings.getString("white");
(new RematchConfirm(context, handle, opp)).show();
}
public void resync()
{
progress.setText("Updating game state");
net.game_status(settings.getString("gameid"));
(new Thread(net)).run();
}
public void applyRemoteMove(final String hist)
{
if (hist == null || hist.length() < 3)
return;
final String[] movehistory = hist.trim().split(" +");
if (movehistory[movehistory.length - 1].equals(history.top().toString()))
return;
// must be on most current move to apply it
currentMove();
Toast.makeText(context, "New move loaded...", Toast.LENGTH_LONG).show();
final Move move = new Move();
move.parse(movehistory[movehistory.length - 1]);
if (board.validMove(move) != Board.VALID_MOVE)
return;
applyMove(move, true, false);
}
public void reset()
{
hindex = -1;
callstack.clear();
history.clear();
board.reset();
Game.self.reset();
}
public void backMove()
{
if (hindex < 0)
return;
final Move move = history.get(hindex);
revertMove(move);
}
public void forwardMove()
{
if (hindex + 1 >= history.size())
return;
final Move move = history.get(++hindex);
applyMove(move, false, true);
}
public void currentMove()
{
while (hindex + 1 < history.size()) {
final Move move = history.get(++hindex);
applyMove(move, false, true);
}
}
public void firstMove()
{
while (hindex > 0) {
final Move move = history.get(hindex);
revertMove(move);
}
}
public void undoMove()
{
if (hindex < 0)
return;
final Move move = history.get(hindex);
revertMove(move);
history.pop();
}
public void submitMove()
{
progress.setText("Sending move");
final String gameid = settings.getString("gameid");
final String move = history.top().toString();
net.submit_move(gameid, move);
(new Thread(net)).run();
}
private void handleMove()
{
switch (type) {
case Enums.ONLINE_GAME:
// you can't edit the past in online games
if (hindex + 1 < history.size()) {
callstack.pop();
return;
}
break;
case Enums.ARCHIVE_GAME:
return;
}
final Move move = new Move();
// create move
if (callstack.get(0) > 64) {
move.index = Math.abs(callstack.get(0) - 100);
move.from = Piece.PLACEABLE;
} else {
move.from = callstack.get(0);
}
move.to = callstack.get(1);
// return if move isn't valid
if (board.validMove(move) != Board.VALID_MOVE) {
callstack.pop();
return;
}
callstack.clear();
applyMove(move, true, true);
}
private void applyMove(final Move move, final boolean erase, final boolean localmove)
{
// legal move always ends with king not in check
if (hindex > 1) {
final int king = board.kingIndex(board.getStm());
final BoardButton kingI = (BoardButton) Game.self.findViewById(king);
kingI.setCheck(false);
}
if (move.from == Piece.PLACEABLE) {
final PlaceButton from = (PlaceButton) Game.self.findViewById(Board.pieceType[move.index] + 100);
final BoardButton to = (BoardButton) Game.self.findViewById(move.to);
from.setHighlight(false);
from.minusPiece();
to.setPiece(from.getPiece());
} else {
final BoardButton from = (BoardButton) Game.self.findViewById(move.from);
final BoardButton to = (BoardButton) Game.self.findViewById(move.to);
to.setPiece(from.getPiece());
from.setPiece(0);
from.setHighlight(false);
}
// apply move to board
board.make(move);
// update hindex, history
if (erase) {
hindex++;
if (hindex < history.size())
history.resize(hindex);
history.push(move);
if (localmove)
save(Game.self.game_board.getContext(), false);
}
// move caused check
if (board.incheck(board.getStm())) {
final int king = board.kingIndex(board.getStm());
final BoardButton kingI = (BoardButton) Game.self.findViewById(king);
kingI.setCheck(true);
}
setStm();
}
private void revertMove(final Move move)
{
// legal move always ends with king not in check
if (hindex > 1) {
final int king = board.kingIndex(board.getStm());
final BoardButton kingI = (BoardButton) Game.self.findViewById(king);
kingI.setCheck(false);
}
if (move.from == Piece.PLACEABLE) {
final PlaceButton from = (PlaceButton) Game.self.findViewById(Board.pieceType[move.index] + 100);
final BoardButton to = (BoardButton) Game.self.findViewById(move.to);
to.setPiece(0);
from.plusPiece();
} else {
final BoardButton from = (BoardButton) Game.self.findViewById(move.from);
final BoardButton to = (BoardButton) Game.self.findViewById(move.to);
from.setPiece(to.getPiece());
if (move.xindex == Piece.NONE)
to.setPiece(0);
else
to.setPiece(Board.pieceType[move.xindex]);
}
hindex--;
board.unmake(move);
// move caused check
if (board.incheck(board.getStm())) {
final int king = board.kingIndex(board.getStm());
final BoardButton kingI = (BoardButton) Game.self.findViewById(king);
kingI.setCheck(true);
}
setStm();
}
public void boardClick(final View v)
{
final BoardButton to = (BoardButton) v;
final int index = to.getIndex();
final int col = (type == Enums.ONLINE_GAME)? ycol : board.getStm();
if (callstack.size() == 0) {
// No active clicks
// first click must be non empty and your own
if (to.getPiece() * col <= 0)
return;
callstack.push(index);
to.setHighlight(true);
return;
} else if (callstack.get(0) == index) {
// clicking the same square
callstack.clear();
to.setHighlight(false);
return;
} else if (callstack.get(0) > 64) {
// Place piece action
// can't place on another piece
if (to.getPiece() * col < 0) {
return;
} else if (to.getPiece() * col > 0) {
final PlaceButton from = (PlaceButton) Game.self.findViewById(callstack.get(0));
from.setHighlight(false);
to.setHighlight(true);
callstack.set(0, index);
return;
}
} else {
// piece move action
final BoardButton from = (BoardButton) Game.self.findViewById(callstack.get(0));
// capturing your own piece (switch to piece)
if (from.getPiece() * to.getPiece() > 0) {
from.setHighlight(false);
to.setHighlight(true);
callstack.set(0, index);
return;
}
}
callstack.push(index);
handleMove();
}
public void placeClick(final View v)
{
final PlaceButton from = (PlaceButton) v;
final int col = (type == Enums.ONLINE_GAME)? ycol : board.getStm();
final int ptype = from.getPiece();
// only select your own pieces where count > 0
if (board.getStm() != col || ptype * board.getStm() < 0 || from.getCount() <= 0)
return;
if (callstack.size() == 0) {
// No active clicks
callstack.push(ptype + 100);
from.setHighlight(true);
} else if (callstack.get(0) < 64) {
// switching from board to place piece
final BoardButton to = (BoardButton) Game.self.findViewById(callstack.get(0));
to.setHighlight(false);
callstack.set(0, ptype + 100);
from.setHighlight(true);
} else if (callstack.get(0) == ptype + 100) {
// clicking the same square
callstack.clear();
from.setHighlight(false);
} else {
// switching to another place piece
final PlaceButton fromold = (PlaceButton) Game.self.findViewById(callstack.get(0));
fromold.setHighlight(false);
callstack.set(0, ptype + 100);
from.setHighlight(true);
}
Game.self.game_board.flip();
}
}
| true | true | public void handleMessage(final Message msg)
{
try {
switch (msg.what) {
case NetworkClient.SUBMIT_MOVE:
JSONObject json = (JSONObject) msg.obj;
if (json.getString("result").equals("error")) {
progress.remove();
Toast.makeText(context, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
return;
}
progress.setText(json.getString("reason"));
net.game_status(settings.getString("gameid"));
(new Thread(net)).start();
break;
case ResignConfirm.MSG:
progress.setText("Sending resignation");
net.resign_game(settings.getString("gameid"));
(new Thread(net)).start();
break;
case NetworkClient.RESIGN_GAME:
json = (JSONObject) msg.obj;
if (json.getString("result").equals("error")) {
progress.remove();
Toast.makeText(context, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
return;
}
progress.setText("Resignation sent");
net.game_status(settings.getString("gameid"));
(new Thread(net)).run();
break;
case NetworkClient.GAME_STATUS:
json = (JSONObject) msg.obj;
if (json.getString("result").equals("error")) {
progress.remove();
Toast.makeText(context, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
return;
}
final String gameid = json.getString("gameid");
final String zfen = json.getString("zfen");
final String history = json.getString("history");
final int status = Enums.GameStatus(json.getString("status"));
final long stime = json.getLong("stime");
settings.putString("status", String.valueOf(status));
final GameDataDB db = new GameDataDB(context);
db.updateOnlineGame(gameid, status, stime, zfen, history);
db.close();
applyRemoteMove(history);
if (status != Enums.ACTIVE) {
if (Integer.valueOf(settings.getString("eventtype")) == Enums.INVITE) {
progress.remove();
json.put("yourcolor", ycol);
json.put("white_name", settings.getString("white"));
json.put("black_name", settings.getString("black"));
json.put("eventtype", settings.getString("eventtype"));
json.put("status", settings.getString("status"));
json.put("gametype", Enums.GameType(Integer.valueOf(settings.getString("gametype"))));
json.put("gameid", settings.getString("gameid"));
(new EndGameDialog(context, json)).show();
return;
}
progress.setText("Retrieving score");
settings.putString("status", String.valueOf(status));
net.game_score(settings.getString("gameid"));
(new Thread(net)).start();
}
break;
case NetworkClient.GAME_SCORE:
json = (JSONObject) msg.obj;
if (json.getString("result").equals("error")) {
progress.remove();
Toast.makeText(context, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
return;
}
progress.setText("Score loaded");
progress.remove();
json.put("yourcolor", ycol);
json.put("white_name", settings.getString("white"));
json.put("black_name", settings.getString("black"));
json.put("eventtype", settings.getString("eventtype"));
json.put("status", settings.getString("status"));
json.put("gametype", Enums.GameType(Integer.valueOf(settings.getString("gametype"))));
json.put("gameid", settings.getString("gameid"));
(new EndGameDialog(context, json)).show();
break;
case RematchConfirm.MSG:
Bundle data = (Bundle) msg.obj;
progress.setText("Sending newgame request");
final String opponent = data.getString("opp_name");
String color = Enums.ColorType(data.getInt("color"));
String gametype = Enums.GameType(data.getInt("gametype"));
net.new_game(opponent, gametype, color);
(new Thread(net)).start();
break;
case NetworkClient.NEW_GAME:
json = (JSONObject) msg.obj;
try {
if (json.getString("result").equals("error")) {
progress.remove();
Toast.makeText(context, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
return;
}
progress.setText(json.getString("reason"));
progress.remove();
} catch (JSONException e) {
e.printStackTrace();
throw new RuntimeException();
}
break;
}
} catch (JSONException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
| public void handleMessage(final Message msg)
{
try {
switch (msg.what) {
case NetworkClient.SUBMIT_MOVE:
JSONObject json = (JSONObject) msg.obj;
if (json.getString("result").equals("error")) {
progress.remove();
Toast.makeText(context, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
return;
}
progress.setText(json.getString("reason"));
net.game_status(settings.getString("gameid"));
(new Thread(net)).start();
break;
case ResignConfirm.MSG:
progress.setText("Sending resignation");
net.resign_game(settings.getString("gameid"));
(new Thread(net)).start();
break;
case NetworkClient.RESIGN_GAME:
json = (JSONObject) msg.obj;
if (json.getString("result").equals("error")) {
progress.remove();
Toast.makeText(context, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
return;
}
progress.setText("Resignation sent");
net.game_status(settings.getString("gameid"));
(new Thread(net)).run();
break;
case NetworkClient.GAME_STATUS:
json = (JSONObject) msg.obj;
if (json.getString("result").equals("error")) {
progress.remove();
Toast.makeText(context, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
return;
}
final String gameid = json.getString("gameid");
final String zfen = json.getString("zfen");
final String history = json.getString("history");
final int status = Enums.GameStatus(json.getString("status"));
final long stime = json.getLong("stime");
settings.putString("status", String.valueOf(status));
final GameDataDB db = new GameDataDB(context);
db.updateOnlineGame(gameid, status, stime, zfen, history);
db.close();
applyRemoteMove(history);
if (status != Enums.ACTIVE) {
if (Integer.valueOf(settings.getString("eventtype")) == Enums.INVITE) {
progress.remove();
json.put("yourcolor", ycol);
json.put("white_name", settings.getString("white"));
json.put("black_name", settings.getString("black"));
json.put("eventtype", settings.getString("eventtype"));
json.put("status", settings.getString("status"));
json.put("gametype", Enums.GameType(Integer.valueOf(settings.getString("gametype"))));
json.put("gameid", settings.getString("gameid"));
(new EndGameDialog(context, json)).show();
return;
}
progress.setText("Retrieving score");
settings.putString("status", String.valueOf(status));
net.game_score(settings.getString("gameid"));
(new Thread(net)).start();
} else {
progress.setText("Status Synced");
progress.remove();
}
break;
case NetworkClient.GAME_SCORE:
json = (JSONObject) msg.obj;
if (json.getString("result").equals("error")) {
progress.remove();
Toast.makeText(context, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
return;
}
progress.setText("Score loaded");
progress.remove();
json.put("yourcolor", ycol);
json.put("white_name", settings.getString("white"));
json.put("black_name", settings.getString("black"));
json.put("eventtype", settings.getString("eventtype"));
json.put("status", settings.getString("status"));
json.put("gametype", Enums.GameType(Integer.valueOf(settings.getString("gametype"))));
json.put("gameid", settings.getString("gameid"));
(new EndGameDialog(context, json)).show();
break;
case RematchConfirm.MSG:
Bundle data = (Bundle) msg.obj;
progress.setText("Sending newgame request");
final String opponent = data.getString("opp_name");
String color = Enums.ColorType(data.getInt("color"));
String gametype = Enums.GameType(data.getInt("gametype"));
net.new_game(opponent, gametype, color);
(new Thread(net)).start();
break;
case NetworkClient.NEW_GAME:
json = (JSONObject) msg.obj;
try {
if (json.getString("result").equals("error")) {
progress.remove();
Toast.makeText(context, "ERROR:\n" + json.getString("reason"), Toast.LENGTH_LONG).show();
return;
}
progress.setText(json.getString("reason"));
progress.remove();
} catch (JSONException e) {
e.printStackTrace();
throw new RuntimeException();
}
break;
}
} catch (JSONException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
|
diff --git a/src/org/python/core/SyspathJavaLoader.java b/src/org/python/core/SyspathJavaLoader.java
index 93dc5e2c..255e60cd 100644
--- a/src/org/python/core/SyspathJavaLoader.java
+++ b/src/org/python/core/SyspathJavaLoader.java
@@ -1,189 +1,193 @@
// Copyright (c) Corporation for National Research Initiatives
// Copyright 2000 Samuele Pedroni
package org.python.core;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.StringTokenizer;
import java.util.zip.ZipEntry;
import javax.management.RuntimeErrorException;
import org.python.core.util.RelativeFile;
public class SyspathJavaLoader extends ClassLoader {
private static final char SLASH_CHAR = '/';
public SyspathJavaLoader(ClassLoader parent) {
super(parent);
}
/**
* Returns a byte[] with the contents read from an InputStream.
*
* The stream is closed after reading the bytes.
*
* @param input The input stream
* @param size The number of bytes to read
*
* @return an array of byte[size] with the contents read
* */
private byte[] getBytesFromInputStream(InputStream input, int size) {
try {
byte[] buffer = new byte[size];
int nread = 0;
while(nread < size) {
nread += input.read(buffer, nread, size - nread);
}
return buffer;
} catch (IOException exc) {
return null;
} finally {
try {
input.close();
} catch (IOException e) {
// Nothing to do
}
}
}
private byte[] getBytesFromDir(String dir, String name) {
try {
File file = getFile(dir, name);
if (file == null) {
return null;
}
return getBytesFromInputStream(new FileInputStream(file), (int)file.length());
} catch (FileNotFoundException e) {
return null;
} catch(SecurityException e) {
return null;
}
}
private byte[] getBytesFromArchive(SyspathArchive archive, String name) {
String entryname = name.replace('.', SLASH_CHAR) + ".class";
ZipEntry ze = archive.getEntry(entryname);
if (ze == null) {
return null;
}
try {
return getBytesFromInputStream(archive.getInputStream(ze),
(int)ze.getSize());
} catch (IOException e) {
return null;
}
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
PySystemState sys = Py.getSystemState();
ClassLoader sysClassLoader = sys.getClassLoader();
if (sysClassLoader != null) {
// sys.classLoader overrides this class loader!
return sysClassLoader.loadClass(name);
}
// Search the sys.path for a .class file matching the named class.
PyList path = sys.path;
for (int i = 0; i < path.__len__(); i++) {
byte[] buffer;
PyObject entry = replacePathItem(sys, i, path);
if (entry instanceof SyspathArchive) {
SyspathArchive archive = (SyspathArchive)entry;
buffer = getBytesFromArchive(archive, name);
} else {
String dir = entry.__str__().toString();
buffer = getBytesFromDir(dir, name);
}
if (buffer != null) {
return defineClass(name, buffer, 0, buffer.length);
}
}
// couldn't find the .class file on sys.path
throw new ClassNotFoundException(name);
}
@Override
protected URL findResource(String res) {
PySystemState sys = Py.getSystemState();
if (res.charAt(0) == SLASH_CHAR) {
res = res.substring(1);
}
String entryRes = res;
if (File.separatorChar != SLASH_CHAR) {
res = res.replace(SLASH_CHAR, File.separatorChar);
entryRes = entryRes.replace(File.separatorChar, SLASH_CHAR);
}
PyList path = sys.path;
for (int i = 0; i < path.__len__(); i++) {
PyObject entry = replacePathItem(sys, i, path);
if (entry instanceof SyspathArchive) {
SyspathArchive archive = (SyspathArchive) entry;
ZipEntry ze = archive.getEntry(entryRes);
if (ze != null) {
try {
- return new URL("jar:" + entry.__str__().toString() + "!/" + entryRes);
+ return new URL("jar:file:" + entry.__str__().toString() + "!/" + entryRes);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
continue;
}
String dir = sys.getPath(entry.__str__().toString());
try {
- return new File(dir, res).toURI().toURL();
+ File resource = new File(dir, res);
+ if (!resource.exists()) {
+ continue;
+ }
+ return resource.toURI().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
return null;
}
static PyObject replacePathItem(PySystemState sys, int idx, PyList paths) {
PyObject path = paths.__getitem__(idx);
if (path instanceof SyspathArchive) {
// already an archive
return path;
}
try {
// this has the side affect of adding the jar to the PackageManager during the
// initialization of the SyspathArchive
path = new SyspathArchive(sys.getPath(path.toString()));
} catch (Exception e) {
return path;
}
paths.__setitem__(idx, path);
return path;
}
private File getFile(String dir, String name) {
String accum = "";
boolean first = true;
for (StringTokenizer t = new StringTokenizer(name, "."); t
.hasMoreTokens();) {
String token = t.nextToken();
if (!first) {
accum += File.separator;
}
accum += token;
first = false;
}
return new RelativeFile(dir, accum + ".class");
}
}
| false | true | protected URL findResource(String res) {
PySystemState sys = Py.getSystemState();
if (res.charAt(0) == SLASH_CHAR) {
res = res.substring(1);
}
String entryRes = res;
if (File.separatorChar != SLASH_CHAR) {
res = res.replace(SLASH_CHAR, File.separatorChar);
entryRes = entryRes.replace(File.separatorChar, SLASH_CHAR);
}
PyList path = sys.path;
for (int i = 0; i < path.__len__(); i++) {
PyObject entry = replacePathItem(sys, i, path);
if (entry instanceof SyspathArchive) {
SyspathArchive archive = (SyspathArchive) entry;
ZipEntry ze = archive.getEntry(entryRes);
if (ze != null) {
try {
return new URL("jar:" + entry.__str__().toString() + "!/" + entryRes);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
continue;
}
String dir = sys.getPath(entry.__str__().toString());
try {
return new File(dir, res).toURI().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
return null;
}
| protected URL findResource(String res) {
PySystemState sys = Py.getSystemState();
if (res.charAt(0) == SLASH_CHAR) {
res = res.substring(1);
}
String entryRes = res;
if (File.separatorChar != SLASH_CHAR) {
res = res.replace(SLASH_CHAR, File.separatorChar);
entryRes = entryRes.replace(File.separatorChar, SLASH_CHAR);
}
PyList path = sys.path;
for (int i = 0; i < path.__len__(); i++) {
PyObject entry = replacePathItem(sys, i, path);
if (entry instanceof SyspathArchive) {
SyspathArchive archive = (SyspathArchive) entry;
ZipEntry ze = archive.getEntry(entryRes);
if (ze != null) {
try {
return new URL("jar:file:" + entry.__str__().toString() + "!/" + entryRes);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
continue;
}
String dir = sys.getPath(entry.__str__().toString());
try {
File resource = new File(dir, res);
if (!resource.exists()) {
continue;
}
return resource.toURI().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
return null;
}
|
diff --git a/src/org/eclipse/imp/box/builders/BoxBuilder.java b/src/org/eclipse/imp/box/builders/BoxBuilder.java
index 8573763..6a7cfb6 100644
--- a/src/org/eclipse/imp/box/builders/BoxBuilder.java
+++ b/src/org/eclipse/imp/box/builders/BoxBuilder.java
@@ -1,161 +1,160 @@
/*******************************************************************************
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Jurgen Vinju ([email protected]) - initial API and implementation
*******************************************************************************/
package org.eclipse.imp.box.builders;
import java.io.FileOutputStream;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.imp.box.Activator;
import org.eclipse.imp.box.parser.BoxParseController;
import org.eclipse.imp.builder.BuilderBase;
import org.eclipse.imp.builder.BuilderUtils;
import org.eclipse.imp.builder.MarkerCreator;
import org.eclipse.imp.language.Language;
import org.eclipse.imp.language.LanguageRegistry;
import org.eclipse.imp.model.ISourceProject;
import org.eclipse.imp.model.ModelFactory;
import org.eclipse.imp.model.ModelFactory.ModelException;
import org.eclipse.imp.parser.IParseController;
import org.eclipse.imp.runtime.PluginBase;
import org.eclipse.imp.utils.StreamUtils;
/**
* @author
*/
public class BoxBuilder extends BuilderBase {
public static final String BUILDER_ID = Activator.kPluginID
+ ".builder";
public static final String PROBLEM_MARKER_ID = Activator.kPluginID
+ ".problem";
public static final String LANGUAGE_NAME = "Box";
public static final Language LANGUAGE = LanguageRegistry
.findLanguage(LANGUAGE_NAME);
protected PluginBase getPlugin() {
return Activator.getInstance();
}
protected String getErrorMarkerID() {
return PROBLEM_MARKER_ID;
}
protected String getWarningMarkerID() {
return PROBLEM_MARKER_ID;
}
protected String getInfoMarkerID() {
return PROBLEM_MARKER_ID;
}
protected boolean isSourceFile(IFile file) {
IPath path = file.getRawLocation();
if (path == null)
return false;
String pathString = path.toString();
if (pathString.indexOf("/bin/") != -1)
return false;
return LANGUAGE.hasExtension(path.getFileExtension());
}
/**
* @return true iff the given file is a source file that this builder should scan
* for dependencies, but not compile as a top-level compilation unit.<br>
* <code>isNonRootSourceFile()</code> and <code>isSourceFile()</code> should never
* return true for the same file.
*/
protected boolean isNonRootSourceFile(IFile resource) {
return false;
}
/**
* Collects compilation-unit dependencies for the given file, and records
* them via calls to <code>fDependency.addDependency()</code>.
*/
protected void collectDependencies(IFile file) {
return;
}
protected boolean isOutputFolder(IResource resource) {
return resource.getFullPath().lastSegment().equals("bin");
}
protected void compile(final IFile file, IProgressMonitor monitor) {
try {
runParserForCompiler(file, monitor);
doRefresh(file.getParent());
String absPath = file.getLocation().toOSString();
String box = BoxFactory.box2text(StreamUtils.readStreamContents(file.getContents()));
FileOutputStream out = new FileOutputStream(absPath + ".fmt");
out.write(box.getBytes());
out.close();
doRefresh(file);
} catch (Exception e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
protected void runParserForCompiler(final IFile file,
IProgressMonitor monitor) {
try {
// Parse controller is the "compiler" here; parses and reports errors
IParseController parseController = new BoxParseController();
// Marker creator handles error messages from the parse controller (and
// uses the parse controller to get additional information about the errors)
- MarkerCreator markerCreator = new MarkerCreator(file,
- parseController, PROBLEM_MARKER_ID);
+ MarkerCreator markerCreator = new MarkerCreator(file, PROBLEM_MARKER_ID);
// If we have a kind of parser that might be receptive, tell it
// what types of problem marker the builder will create
parseController.getAnnotationTypeInfo().addProblemMarkerType(getErrorMarkerID());
// Need to tell the parse controller which file in which project to parse
// and also the message handler to which to report errors
IProject project = file.getProject();
ISourceProject sourceProject = null;
try {
sourceProject = ModelFactory.open(project);
} catch (ModelException me) {
System.err
.println("BoxParseController.runParserForComplier(..): Model exception:\n"
+ me.getMessage()
+ "\nReturning without parsing");
return;
}
parseController.initialize(file.getProjectRelativePath(),
sourceProject, markerCreator);
String contents = BuilderUtils.getFileContents(file);
// Finally parse it
parseController.parse(contents, monitor);
doRefresh(file.getParent());
} catch (Exception e) {
getPlugin().writeErrorMsg(e.getMessage());
e.printStackTrace();
}
}
}
| true | true | protected void runParserForCompiler(final IFile file,
IProgressMonitor monitor) {
try {
// Parse controller is the "compiler" here; parses and reports errors
IParseController parseController = new BoxParseController();
// Marker creator handles error messages from the parse controller (and
// uses the parse controller to get additional information about the errors)
MarkerCreator markerCreator = new MarkerCreator(file,
parseController, PROBLEM_MARKER_ID);
// If we have a kind of parser that might be receptive, tell it
// what types of problem marker the builder will create
parseController.getAnnotationTypeInfo().addProblemMarkerType(getErrorMarkerID());
// Need to tell the parse controller which file in which project to parse
// and also the message handler to which to report errors
IProject project = file.getProject();
ISourceProject sourceProject = null;
try {
sourceProject = ModelFactory.open(project);
} catch (ModelException me) {
System.err
.println("BoxParseController.runParserForComplier(..): Model exception:\n"
+ me.getMessage()
+ "\nReturning without parsing");
return;
}
parseController.initialize(file.getProjectRelativePath(),
sourceProject, markerCreator);
String contents = BuilderUtils.getFileContents(file);
// Finally parse it
parseController.parse(contents, monitor);
doRefresh(file.getParent());
} catch (Exception e) {
getPlugin().writeErrorMsg(e.getMessage());
e.printStackTrace();
}
}
| protected void runParserForCompiler(final IFile file,
IProgressMonitor monitor) {
try {
// Parse controller is the "compiler" here; parses and reports errors
IParseController parseController = new BoxParseController();
// Marker creator handles error messages from the parse controller (and
// uses the parse controller to get additional information about the errors)
MarkerCreator markerCreator = new MarkerCreator(file, PROBLEM_MARKER_ID);
// If we have a kind of parser that might be receptive, tell it
// what types of problem marker the builder will create
parseController.getAnnotationTypeInfo().addProblemMarkerType(getErrorMarkerID());
// Need to tell the parse controller which file in which project to parse
// and also the message handler to which to report errors
IProject project = file.getProject();
ISourceProject sourceProject = null;
try {
sourceProject = ModelFactory.open(project);
} catch (ModelException me) {
System.err
.println("BoxParseController.runParserForComplier(..): Model exception:\n"
+ me.getMessage()
+ "\nReturning without parsing");
return;
}
parseController.initialize(file.getProjectRelativePath(),
sourceProject, markerCreator);
String contents = BuilderUtils.getFileContents(file);
// Finally parse it
parseController.parse(contents, monitor);
doRefresh(file.getParent());
} catch (Exception e) {
getPlugin().writeErrorMsg(e.getMessage());
e.printStackTrace();
}
}
|
diff --git a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/widgets/wizard/PublicXMPPServerComposite.java b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/widgets/wizard/PublicXMPPServerComposite.java
index 48c51be3f..48820d285 100644
--- a/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/widgets/wizard/PublicXMPPServerComposite.java
+++ b/de.fu_berlin.inf.dpp/src/de/fu_berlin/inf/dpp/ui/widgets/wizard/PublicXMPPServerComposite.java
@@ -1,106 +1,107 @@
package de.fu_berlin.inf.dpp.ui.widgets.wizard;
import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Layout;
import org.picocontainer.annotations.Inject;
import de.fu_berlin.inf.dpp.SarosPluginContext;
import de.fu_berlin.inf.dpp.preferences.PreferenceUtils;
import de.fu_berlin.inf.dpp.ui.util.DialogUtils;
import de.fu_berlin.inf.dpp.ui.util.LayoutUtils;
import de.fu_berlin.inf.dpp.ui.widgets.explanation.note.NoteComposite;
import de.fu_berlin.inf.dpp.util.Utils;
public class PublicXMPPServerComposite extends NoteComposite {
private static final Logger log = Logger
.getLogger(PublicXMPPServerComposite.class);
public static final String LIST_OF_XMPP_SERVERS = "http://www.saros-project.org/InstallUsing#Using_Public_XMPP_Servers";
@Inject
PreferenceUtils preferenceUtils;
public PublicXMPPServerComposite(Composite parent, int style) {
super(parent, SWT.BORDER);
}
@Override
public Layout getContentLayout() {
return LayoutUtils.createGridLayout(0, 5);
}
@Override
public void createContent(Composite parent) {
SarosPluginContext.initComponent(this);
createQuickStart(parent);
createProfessionalUsage(parent);
createMoreInformation(parent);
}
protected void createQuickStart(Composite composite) {
StyledText quickStartText = new StyledText(composite, SWT.WRAP);
quickStartText.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING,
true, false));
+ quickStartText.setEnabled(false);
quickStartText.setForeground(this.getForeground());
quickStartText.setBackground(this.getBackground());
quickStartText
.setText("For a quick start we recommend to use Saros's Jabber server: "
+ preferenceUtils.getSarosXMPPServer());
StyleRange styleRange = new StyleRange();
styleRange.start = quickStartText.getText().length()
- preferenceUtils.getSarosXMPPServer().length();
styleRange.length = preferenceUtils.getSarosXMPPServer().length();
styleRange.fontStyle = SWT.BOLD;
quickStartText.setStyleRange(styleRange);
// Label quickStartLabel = new Label(composite, SWT.WRAP);
// this.configureLabel(quickStartLabel);
// quickStartLabel
// .setText("For a quick start we recommend to use Saros's Jabber server: "
// + "saros-con.imp.fu-berlin.de");
}
protected void createProfessionalUsage(Composite composite) {
Label otherServersLabel = new Label(composite, SWT.WRAP);
this.configureLabel(otherServersLabel);
otherServersLabel
.setText("You are free to use any other XMPP/Jabber server as well.");
}
protected void configureLabel(Label label) {
label.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
label.setForeground(this.getForeground());
label.setBackground(this.getBackground());
}
protected void createMoreInformation(Composite composite) {
Button moreInformationButton = new Button(composite, SWT.PUSH);
moreInformationButton.setLayoutData(new GridData(SWT.FILL,
SWT.BEGINNING, true, false));
moreInformationButton.setText("More Information...");
moreInformationButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (!Utils.openExternalBrowser(LIST_OF_XMPP_SERVERS)) {
log.error("Couldn't open link " + LIST_OF_XMPP_SERVERS
+ " in external browser.");
DialogUtils.openWarningMessageDialog(getShell(), "Warning",
"The list of Public XMPP/Jabbers server could not be opened.\n\n"
+ "Please open " + LIST_OF_XMPP_SERVERS
+ " manually in your browser.");
}
}
});
}
}
| true | true | protected void createQuickStart(Composite composite) {
StyledText quickStartText = new StyledText(composite, SWT.WRAP);
quickStartText.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING,
true, false));
quickStartText.setForeground(this.getForeground());
quickStartText.setBackground(this.getBackground());
quickStartText
.setText("For a quick start we recommend to use Saros's Jabber server: "
+ preferenceUtils.getSarosXMPPServer());
StyleRange styleRange = new StyleRange();
styleRange.start = quickStartText.getText().length()
- preferenceUtils.getSarosXMPPServer().length();
styleRange.length = preferenceUtils.getSarosXMPPServer().length();
styleRange.fontStyle = SWT.BOLD;
quickStartText.setStyleRange(styleRange);
// Label quickStartLabel = new Label(composite, SWT.WRAP);
// this.configureLabel(quickStartLabel);
// quickStartLabel
// .setText("For a quick start we recommend to use Saros's Jabber server: "
// + "saros-con.imp.fu-berlin.de");
}
| protected void createQuickStart(Composite composite) {
StyledText quickStartText = new StyledText(composite, SWT.WRAP);
quickStartText.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING,
true, false));
quickStartText.setEnabled(false);
quickStartText.setForeground(this.getForeground());
quickStartText.setBackground(this.getBackground());
quickStartText
.setText("For a quick start we recommend to use Saros's Jabber server: "
+ preferenceUtils.getSarosXMPPServer());
StyleRange styleRange = new StyleRange();
styleRange.start = quickStartText.getText().length()
- preferenceUtils.getSarosXMPPServer().length();
styleRange.length = preferenceUtils.getSarosXMPPServer().length();
styleRange.fontStyle = SWT.BOLD;
quickStartText.setStyleRange(styleRange);
// Label quickStartLabel = new Label(composite, SWT.WRAP);
// this.configureLabel(quickStartLabel);
// quickStartLabel
// .setText("For a quick start we recommend to use Saros's Jabber server: "
// + "saros-con.imp.fu-berlin.de");
}
|
diff --git a/common/logisticspipes/ticks/VersionChecker.java b/common/logisticspipes/ticks/VersionChecker.java
index ebe42747..52614a78 100644
--- a/common/logisticspipes/ticks/VersionChecker.java
+++ b/common/logisticspipes/ticks/VersionChecker.java
@@ -1,64 +1,66 @@
package logisticspipes.ticks;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import logisticspipes.LogisticsPipes;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
public class VersionChecker extends Thread {
public static boolean hasNewVersion = false;
public static String newVersion = "";
public static List<String> changeLog = new ArrayList<String>(0);
public VersionChecker() {
this.setDaemon(true);
this.start();
}
@SuppressWarnings({ "resource", "rawtypes", "unchecked" })
public void run() {
try {
if(LogisticsPipes.VERSION.equals("%"+"VERSION%:%DEBUG"+"%")) return;
if(LogisticsPipes.VERSION.contains("-")) return;
URL url = new URL("http://rs485.thezorro266.com/version/check.php?VERSION=" + LogisticsPipes.VERSION);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream inputStream = (InputStream) conn.getContent();
Scanner s = new Scanner(inputStream).useDelimiter("\\A");
String string = s.next();
s.close();
Gson gson = new Gson();
LinkedTreeMap part = gson.fromJson(string, LinkedTreeMap.class);
Boolean hasNew = (Boolean) part.get("new");
if(hasNew) {
VersionChecker.hasNewVersion = true;
VersionChecker.newVersion = Integer.toString(Double.valueOf(part.get("build").toString()).intValue());
LogisticsPipes.log.warning("New LogisticsPipes" + (LogisticsPipes.DEV_BUILD?"-Dev":"") + " version found: #" + Double.valueOf(part.get("build").toString()).intValue());
LinkedTreeMap changeLog = (LinkedTreeMap) part.get("changelog");
List<String> changeLogList = new ArrayList<String>();
- for(Object oVersion:changeLog.keySet()) {
- String build = oVersion.toString();
- changeLogList.add(new StringBuilder(build).append(": ").toString());
- List<String> sub = (List<String>) changeLog.get(build);
- for(String msg:sub) {
- changeLogList.add(msg);
+ if(changeLog != null) {
+ for(Object oVersion:changeLog.keySet()) {
+ String build = oVersion.toString();
+ changeLogList.add(new StringBuilder(build).append(": ").toString());
+ List<String> sub = (List<String>) changeLog.get(build);
+ for(String msg:sub) {
+ changeLogList.add(msg);
+ }
}
}
VersionChecker.changeLog = changeLogList;
}
} catch(MalformedURLException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
}
| true | true | public void run() {
try {
if(LogisticsPipes.VERSION.equals("%"+"VERSION%:%DEBUG"+"%")) return;
if(LogisticsPipes.VERSION.contains("-")) return;
URL url = new URL("http://rs485.thezorro266.com/version/check.php?VERSION=" + LogisticsPipes.VERSION);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream inputStream = (InputStream) conn.getContent();
Scanner s = new Scanner(inputStream).useDelimiter("\\A");
String string = s.next();
s.close();
Gson gson = new Gson();
LinkedTreeMap part = gson.fromJson(string, LinkedTreeMap.class);
Boolean hasNew = (Boolean) part.get("new");
if(hasNew) {
VersionChecker.hasNewVersion = true;
VersionChecker.newVersion = Integer.toString(Double.valueOf(part.get("build").toString()).intValue());
LogisticsPipes.log.warning("New LogisticsPipes" + (LogisticsPipes.DEV_BUILD?"-Dev":"") + " version found: #" + Double.valueOf(part.get("build").toString()).intValue());
LinkedTreeMap changeLog = (LinkedTreeMap) part.get("changelog");
List<String> changeLogList = new ArrayList<String>();
for(Object oVersion:changeLog.keySet()) {
String build = oVersion.toString();
changeLogList.add(new StringBuilder(build).append(": ").toString());
List<String> sub = (List<String>) changeLog.get(build);
for(String msg:sub) {
changeLogList.add(msg);
}
}
VersionChecker.changeLog = changeLogList;
}
} catch(MalformedURLException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
| public void run() {
try {
if(LogisticsPipes.VERSION.equals("%"+"VERSION%:%DEBUG"+"%")) return;
if(LogisticsPipes.VERSION.contains("-")) return;
URL url = new URL("http://rs485.thezorro266.com/version/check.php?VERSION=" + LogisticsPipes.VERSION);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream inputStream = (InputStream) conn.getContent();
Scanner s = new Scanner(inputStream).useDelimiter("\\A");
String string = s.next();
s.close();
Gson gson = new Gson();
LinkedTreeMap part = gson.fromJson(string, LinkedTreeMap.class);
Boolean hasNew = (Boolean) part.get("new");
if(hasNew) {
VersionChecker.hasNewVersion = true;
VersionChecker.newVersion = Integer.toString(Double.valueOf(part.get("build").toString()).intValue());
LogisticsPipes.log.warning("New LogisticsPipes" + (LogisticsPipes.DEV_BUILD?"-Dev":"") + " version found: #" + Double.valueOf(part.get("build").toString()).intValue());
LinkedTreeMap changeLog = (LinkedTreeMap) part.get("changelog");
List<String> changeLogList = new ArrayList<String>();
if(changeLog != null) {
for(Object oVersion:changeLog.keySet()) {
String build = oVersion.toString();
changeLogList.add(new StringBuilder(build).append(": ").toString());
List<String> sub = (List<String>) changeLog.get(build);
for(String msg:sub) {
changeLogList.add(msg);
}
}
}
VersionChecker.changeLog = changeLogList;
}
} catch(MalformedURLException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
|
diff --git a/common/src/main/java/com/vmware/bdd/apitypes/ClusterCreate.java b/common/src/main/java/com/vmware/bdd/apitypes/ClusterCreate.java
index a7e5bff5..3b7a3b17 100644
--- a/common/src/main/java/com/vmware/bdd/apitypes/ClusterCreate.java
+++ b/common/src/main/java/com/vmware/bdd/apitypes/ClusterCreate.java
@@ -1,222 +1,222 @@
/***************************************************************************
* Copyright (c) 2012 VMware, Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
package com.vmware.bdd.apitypes;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.vmware.bdd.spectypes.HadoopDistroMap;
import com.vmware.bdd.spectypes.VcCluster;
/**
* Cluster creation parameters
*/
public class ClusterCreate {
@Expose
private String name;
@Expose
@SerializedName("groups")
private NodeGroupCreate[] nodeGroups;
@Expose
private String distro;
private List<String> rpNames;
@Expose
@SerializedName("vc_clusters")
private List<VcCluster> vcClusters;
@Expose
@SerializedName("template_id")
private String templateId;
@Expose
@SerializedName("deploy_policy")
private String deployPolicy;
private List<String> dsNames;
private String networkName;
@Expose
private List<NetworkAdd> networking;
@Expose
@SerializedName("distro_map")
private HadoopDistroMap distroMap;
@Expose
@SerializedName("vc_shared_datastore_pattern")
private Set<String> sharedPattern;
@Expose
@SerializedName("vc_local_datastore_pattern")
private Set<String> localPattern;
@Expose
@SerializedName("cluster_configuration")
private Map<String, Object> configuration;
private boolean validateConfig = true;
public ClusterCreate() {
}
public ClusterCreate(ClusterCreate cluster) {
this.deployPolicy = cluster.deployPolicy;
this.distro = cluster.distro;
this.name = cluster.name;
this.networkName = cluster.networkName;
this.nodeGroups = cluster.nodeGroups;
this.rpNames = cluster.rpNames;
this.templateId = cluster.templateId;
this.vcClusters = cluster.vcClusters;
this.networking = cluster.networking;
this.configuration = cluster.configuration;
this.validateConfig = cluster.validateConfig;
}
public Map<String, Object> getConfiguration() {
return configuration;
}
public void setConfiguration(Map<String, Object> configuration) {
this.configuration = configuration;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDistro() {
return distro;
}
public void setDistro(String distro) {
this.distro = distro;
}
public List<String> getRpNames() {
return rpNames;
}
public void setRpNames(List<String> rpNames) {
this.rpNames = rpNames;
}
public String getNetworkName() {
return networkName;
}
public void setNetworkName(String networkName) {
this.networkName = networkName;
}
public NodeGroupCreate[] getNodeGroups() {
return nodeGroups;
}
public void setNodeGroups(NodeGroupCreate[] nodeGroups) {
this.nodeGroups = nodeGroups;
}
public List<String> getDsNames() {
return dsNames;
}
public void setDsNames(List<String> dsNames) {
this.dsNames = dsNames;
}
public List<VcCluster> getVcClusters() {
return vcClusters;
}
public void setVcClusters(List<VcCluster> vcClusters) {
this.vcClusters = vcClusters;
}
public String getTemplateId() {
return templateId;
}
public void setTemplateId(String templateId) {
this.templateId = templateId;
}
public String getDeployPolicy() {
return deployPolicy;
}
public void setDeployPolicy(String deployPolicy) {
this.deployPolicy = deployPolicy;
}
public List<NetworkAdd> getNetworking() {
return networking;
}
public void setNetworking(List<NetworkAdd> networking) {
this.networking = networking;
}
public HadoopDistroMap getDistroMap() {
return distroMap;
}
public void setDistroMap(HadoopDistroMap distroMap) {
this.distroMap = distroMap;
}
public Set<String> getSharedPattern() {
return sharedPattern;
}
public void setSharedPattern(Set<String> sharedPattern) {
this.sharedPattern = sharedPattern;
}
public Set<String> getLocalPattern() {
return localPattern;
}
public void setLocalPattern(Set<String> localPattern) {
this.localPattern = localPattern;
}
public boolean isValidateConfig() {
return validateConfig;
}
public void setValidateConfig(boolean validateConfig) {
this.validateConfig = validateConfig;
}
public boolean validateNodeGroupPlacementPolicies(List<String> failedMsgList) {
boolean valid = true;
Map<String, NodeGroupCreate> allGroups = new TreeMap<String, NodeGroupCreate>();
for (NodeGroupCreate nodeGroupCreate : getNodeGroups()) {
allGroups.put(nodeGroupCreate.getName(), nodeGroupCreate);
}
for (NodeGroupCreate ngc : getNodeGroups()) {
- if (ngc.validatePlacementPolicies(allGroups, failedMsgList)) {
+ if (!ngc.validatePlacementPolicies(allGroups, failedMsgList)) {
valid = false;
}
}
return valid;
}
}
| true | true | public boolean validateNodeGroupPlacementPolicies(List<String> failedMsgList) {
boolean valid = true;
Map<String, NodeGroupCreate> allGroups = new TreeMap<String, NodeGroupCreate>();
for (NodeGroupCreate nodeGroupCreate : getNodeGroups()) {
allGroups.put(nodeGroupCreate.getName(), nodeGroupCreate);
}
for (NodeGroupCreate ngc : getNodeGroups()) {
if (ngc.validatePlacementPolicies(allGroups, failedMsgList)) {
valid = false;
}
}
return valid;
}
| public boolean validateNodeGroupPlacementPolicies(List<String> failedMsgList) {
boolean valid = true;
Map<String, NodeGroupCreate> allGroups = new TreeMap<String, NodeGroupCreate>();
for (NodeGroupCreate nodeGroupCreate : getNodeGroups()) {
allGroups.put(nodeGroupCreate.getName(), nodeGroupCreate);
}
for (NodeGroupCreate ngc : getNodeGroups()) {
if (!ngc.validatePlacementPolicies(allGroups, failedMsgList)) {
valid = false;
}
}
return valid;
}
|
diff --git a/apps/lifelines/plugins/predictionModel/TableModel.java b/apps/lifelines/plugins/predictionModel/TableModel.java
index 6a024ea0d..e21f439da 100644
--- a/apps/lifelines/plugins/predictionModel/TableModel.java
+++ b/apps/lifelines/plugins/predictionModel/TableModel.java
@@ -1,667 +1,667 @@
package plugins.predictionModel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jxl.Sheet;
import org.molgenis.core.OntologyTerm;
import org.molgenis.framework.db.Database;
import org.molgenis.framework.db.DatabaseException;
import org.molgenis.framework.db.QueryRule;
import org.molgenis.framework.db.QueryRule.Operator;
import org.molgenis.organization.Investigation;
import org.molgenis.organization.InvestigationElement;
import org.molgenis.pheno.Category;
import org.molgenis.pheno.Measurement;
import org.molgenis.pheno.ObservationElement;
import org.molgenis.pheno.ObservationTarget;
import org.molgenis.pheno.ObservedValue;
import org.molgenis.protocol.Protocol;
import org.molgenis.util.Entity;
import org.molgenis.util.SimpleTuple;
import org.molgenis.util.Tuple;
import org.openqa.jetty.util.Observed;
import org.springframework.validation.DataBinder;
import com.googlecode.charts4j.Data;
import app.DatabaseFactory;
public class TableModel {
private Database db;
public int columnSize = 0;
public List<TableField> configuration;
public TableField field;
private int observationTarget = -1;
private String MeasurementDataType = "Not Matching";
private HashMap<String, String> InputToMolgenisDataType = new HashMap<String, String>();
private HashMap<Integer, Integer> protocolSubprotocolIndex = new HashMap<Integer, Integer>();
private HashMap<Integer, Integer> protocolSubProtocol = new HashMap<Integer, Integer>();
private HashMap<Integer, TableField> columnIndexToTableField = new HashMap<Integer, TableField>();
private HashMap<TableField, TableField> referenceField = new HashMap<TableField, TableField>();
// private int protocolIndex = -1;
//
// private int featureIndex = -1;
// private String protocolName = null;
//
// private String subProtocolName = null;
//
// private int unitsIndex = -1;
//
// private int temporalIndex = -1;
//
// private int measurementIndex = -1;
//
// private int categoryIndex = -1;
//
// private int missingCategoryIndex = -1;
private List<Integer> missingCategoryList = new ArrayList<Integer>();
private HashMap<Integer, List<Integer>> categoryAddToMeasurement = new HashMap<Integer, List<Integer>>();
//OntologyTerm Parameters
// private int ontologyTermIndex = -1;
//
// private int ontologyNameIndex = -1;
//
// private int ontologyTermAccessIndex = -1;
//
// private int ontologyDefinitionIndex = -1;
//
// private int ontologyTermPathIndex = -1;
private HashMap<Integer, List<Integer>> relationIndex = new HashMap<Integer, List<Integer>>();
private String[] updateMeasurementDatabaseRules = {Measurement.NAME, Measurement.DESCRIPTION,
Measurement.DATATYPE, Measurement.CATEGORIES_NAME, Measurement.UNIT_NAME,Measurement.INVESTIGATION_NAME};
private String[] updateProtocolDatabaseRules = {Protocol.NAME, Protocol.FEATURES_NAME, Protocol.SUBPROTOCOLS_NAME, Protocol.INVESTIGATION_NAME};
private String[] updateCategoryDatabaseRules = {Category.NAME, Category.CODE_STRING, Category.DESCRIPTION, Category.LABEL, Category.ISMISSING, Category.INVESTIGATION_NAME};
private String[] updateObservedValuesDatabaseRules = {ObservedValue.VALUE, ObservedValue.TARGET_NAME, ObservedValue.FEATURE_NAME, ObservedValue.INVESTIGATION_NAME};
private String investigationName = null;
private String excelDirection = "UploadFileByColumn";
public TableModel(int i, Database db) {
this.db = db;
this.columnSize = i;
configuration = new ArrayList<TableField>();
}
public void addField(String classType, String fieldName, int[] columnList, Boolean Vertical)
{
this.addField(classType, fieldName, columnList, Vertical, new SimpleTuple());
}
public void addField(String ClassType, String fieldName, int[] columnList, Boolean Vertical, Tuple defaults) {
for(int i = 0; i < columnList.length; i++){
this.addField( ClassType, fieldName, columnList[i], Vertical, defaults, -1);
}
}
public void addField(String ClassType, String fieldName, boolean Vertical, int dependedIndex, int... columnIndexes) {
List<Integer> columnList = new ArrayList<Integer>();
for(int i = 0; i < columnIndexes.length; i++)
{
if(columnIndexToTableField.containsKey(columnIndexes[i]))
{
columnIndexToTableField.get(columnIndexes[i]).setDependentColumnIndex(dependedIndex);
columnIndexToTableField.get(columnIndexes[i]).setRelation(fieldName);
}else{
this.addField(ClassType, fieldName, columnIndexes[i], Vertical, new SimpleTuple(), dependedIndex);
columnIndexToTableField.get(columnIndexes[i]).setRelation(fieldName);
}
columnList.add(columnIndexes[i]);
}
relationIndex.put(dependedIndex, columnList);
}
public void addField(String ClassType, String fieldName, int columnIndex, Boolean Vertical) {
this.addField( ClassType, fieldName, columnIndex, Vertical, new SimpleTuple(), -1);
}
public void addField(String ClassType, String fieldName, int columnIndex,
boolean Vertical, int... dependentColumnIndex) {
this.addField(ClassType, fieldName, columnIndex, Vertical, new SimpleTuple(), dependentColumnIndex);
}
public void addField(String ClassType, String fieldName, int columnIndex,
boolean Vertical, Tuple defaults) {
this.addField(ClassType, fieldName, columnIndex, Vertical, defaults, -1);
}
public void addField(String ClassType, String fieldName, int[] coHeaders,
int targetIndex, boolean Vertical) {
observationTarget = targetIndex;
this.addField(ClassType, fieldName, coHeaders, Vertical, new SimpleTuple());
observationTarget = -1;
}
public void addField(String ClassType, String fieldName, int columnIndex, Boolean Vertical, Tuple defaults, int... dependentColumnIndex){
try {
//create a tableField that will take care of loading columnIndex into 'name' property
field = new TableField(ClassType, fieldName, columnIndex, Vertical, defaults, dependentColumnIndex);
//add to the parser configuration
configuration.add(field);
columnIndexToTableField.put(columnIndex, field);
if(observationTarget != -1){
field.setObservationTarget(observationTarget);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(e);
}
}
public TableField getField(int columnIndex){
return configuration.get(columnIndex);
}
public List<TableField> getConfiguration(){
return configuration;
}
public void convertIntoPheno(Sheet sheet){
int row = sheet.getRows();
int column = sheet.getColumns();
List<ObservedValue> observedValueList = new ArrayList<ObservedValue>();
List<OntologyTerm> ontologyTermList = new ArrayList<OntologyTerm>();
if(excelDirection.equals("UploadFileByRow"))
{
row = sheet.getColumns();
column = sheet.getRows();
}
//three dimensional matrix of<colIndex, rowIndex, valueIndex>
//third dimension of valueIndex is to deal with multiple values in one cell
//we made colIndex key because not all colIndexes are used
Map<Integer,List<List<InvestigationElement>>> colValues = new LinkedHashMap<Integer,List<List<InvestigationElement>>>();
Map<Integer,Map<String, List<InvestigationElement>>> existingValues = new LinkedHashMap<Integer, Map<String, List<InvestigationElement>>>();
List<Measurement> headerMeasurements = new ArrayList<Measurement>();
try
{
for(int rowIndex = 0; rowIndex < row; rowIndex++){
for(int colIndex = 0; colIndex < column; colIndex++){
String cellValue;
if(excelDirection.equals("UploadFileByRow"))
cellValue = sheet.getCell(rowIndex, colIndex).getContents().replaceAll("'", "").trim().toLowerCase();
else
cellValue = sheet.getCell(colIndex, rowIndex).getContents().replaceAll("'", "").trim().toLowerCase();
System.out.println("The cell value is " + cellValue);
System.out.println("The size is =========== " + configuration.size());
TableField field = columnIndexToTableField.get(colIndex);
if(columnIndexToTableField.get(colIndex) != null && columnIndexToTableField.get(colIndex).getVertical() && rowIndex != 0){
//Keep track of the entities
if(!existingValues.containsKey(colIndex))
{
Map<String, List<InvestigationElement>> tempHolder = new LinkedHashMap<String, List<InvestigationElement>>();
existingValues.put(colIndex, tempHolder);
}
if(existingValues.get(colIndex).containsKey(cellValue))
{
if(colValues.get(colIndex).size() != rowIndex)
{
colValues.get(colIndex).add(new ArrayList<InvestigationElement>());
}
colValues.get(colIndex).get(rowIndex - 1).addAll(existingValues.get(colIndex).get(cellValue));
}else{
//we split on multivalue
String[] multiValue = cellValue.split(field.getValueSplitter());
for(int valueIndex = 0; valueIndex < multiValue.length; valueIndex++)
{
//If the fieldName is 'name', added as a new entity
if(field.getFieldName().equalsIgnoreCase("NAME")){
String value = multiValue[valueIndex];
InvestigationElement entity = null;
//check colIndex: if there is already a list for colIndex
if(colValues.get(colIndex) == null)
{
colValues.put(colIndex, new ArrayList<List<InvestigationElement>>());
}
//check rowIndex: if there is already a list values
if(colValues.get(colIndex).size() != rowIndex)
{
//create a list for our values (to deal with multivalue)
colValues.get(colIndex).add(new ArrayList<InvestigationElement>());
}
//check valueIndex: if there is already a value
//TODO Chao`s comment: should be multiValue.length instead of rowIndex
if(colValues.get(colIndex).get(rowIndex - 1).size() != multiValue.length)
{
//create the entity
entity = (InvestigationElement) DatabaseFactory.create().getClassForName(field.getClassType()).newInstance();
}
if(!value.equalsIgnoreCase("")){
if(field.getClassType().equals(Category.class.getSimpleName())){
//Category entity couldn`t have empty property in name, description, code_string, label
//therefore it`s separated from other entites.
entity.set(Category.NAME, value);
entity.set(Category.DESCRIPTION, value);
entity.set(Category.CODE_STRING, value);
entity.set(Category.LABEL, value);
if(field.getDefaults().getString(Category.ISMISSING) != null)
entity.set(Category.ISMISSING, field.getDefaults().getString(Category.ISMISSING));
}else{
//set the field as specified in getFieldName() = 'name' or 'missing' or 'dataType', etc
entity.set(field.getFieldName(), value);
}
if(investigationName != null)
entity.set("Investigation_name", investigationName);
colValues.get(colIndex).get(rowIndex - 1).add(entity);
//field.setEntity(entity);
}
}
}
}
if(field.getDependentColumnIndex()[0] != -1){
for(int index = 0; index < field.getDependentColumnIndex().length; index++){
int dependentColumn = field.getDependentColumnIndex()[index];
TableField dependendField = columnIndexToTableField.get(dependentColumn);
//InvestigationElement addingPropertyToEntity = dependendField.getEntity();
InvestigationElement addingPropertyToEntity = colValues.get(dependentColumn).get(rowIndex - 1).get(0);
String multipleValues[] = cellValue.split(dependendField.getValueSplitter());
List<Object> values = new ArrayList<Object>();
for(int i = 0; i < multipleValues.length; i++){
values.add(multipleValues[i].trim());
}
//Due to using generic method get() property of the Pheno Entity, so we don`t know which Object data
//the field would be. We need to check the field type first. It could be list, boolean, string
if(addingPropertyToEntity.get(field.getRelationString()) != null)
{
if(addingPropertyToEntity.get(field.getRelationString()).getClass().equals(ArrayList.class))
{
List<String> previousProperties = (List<String>) addingPropertyToEntity.get(field.getRelationString());
if(previousProperties != null && previousProperties.size() > 0)
{
for(String newValue : previousProperties)
{
if(!values.contains(newValue))
{
values.add(newValue);
}
}
}
}else if(addingPropertyToEntity.get(field.getRelationString()).getClass().equals(Boolean.class)){
values.clear();
if(field.getRelationString().equalsIgnoreCase(Measurement.TEMPORAL))
{
if(cellValue.equalsIgnoreCase("yes"))
{
values.add(true);
}else{
values.add(false);
}
}else{
if(cellValue.equalsIgnoreCase("yes"))
values.add(true);
}
}else if(addingPropertyToEntity.get(field.getRelationString()).getClass().equals(String.class)){
values.clear();
values.add(addingPropertyToEntity.get(field.getRelationString()));
}
if(field.getRelationString().equals(Measurement.DATATYPE)){
String dataType = adjustDataTypeValue(cellValue);
if(!dataType.equals(MeasurementDataType))
{
values.clear();
values.add(dataType);
}
}
}
if(field.getRelationString().equals(Measurement.UNIT_NAME)){
for(int i = 0; i < multipleValues.length; i++)
{
List<String> eachValues = new ArrayList<String>();
eachValues.add(multipleValues[i]);
List<OntologyTerm> existingOntologyTermList = db.find(OntologyTerm.class, new QueryRule(OntologyTerm.NAME, Operator.IN, eachValues));
if(existingOntologyTermList.size() == 0 && !multipleValues[i].equals("")){
OntologyTerm unitOntologyTerm = new OntologyTerm();
unitOntologyTerm.set(OntologyTerm.NAME, multipleValues[i]);
if(!ontologyTermList.contains(unitOntologyTerm)){
ontologyTermList.add(unitOntologyTerm);
}
}
}
}
if(values.size() == 1)
{
addingPropertyToEntity.set(field.getRelationString(), values.get(0));
}else{
addingPropertyToEntity.set(field.getRelationString(), values);
}
}
}
if(!existingValues.get(colIndex).containsKey(cellValue) && colValues.containsKey(colIndex))
{
existingValues.get(colIndex).put(cellValue, colValues.get(colIndex).get(rowIndex - 1));
}
}else{
//The header is measurement!
if(rowIndex == 0){
if(field.getClassType().equalsIgnoreCase(ObservedValue.class.getSimpleName())){
Measurement measurement = new Measurement();
measurement.setName(cellValue);
headerMeasurements.add(measurement);
if(investigationName != null)
measurement.set("Investigation_name", investigationName);
}
//The rest of the column is observedValue!
}else{
if(!cellValue.equals("") && cellValue != null && field.getObservationTarget() != -1){
ObservedValue observedValue = new ObservedValue();
String headerName = sheet.getCell(colIndex, 0).getContents().replaceAll("'", "").trim().toLowerCase();
String targetName = sheet.getCell(field.getObservationTarget(), rowIndex).getContents().replaceAll("'", "").trim().toLowerCase();
observedValue.setFeature_Name(headerName);
observedValue.setTarget_Name(targetName);
observedValue.setValue(cellValue);
observedValueList.add(observedValue);
if(investigationName != null)
observedValue.set("Investigation_name", investigationName);
}
}
}
}
}
//convert the columnValues into one list per column for the database
Map<Integer,List<InvestigationElement>> dataToAdd = new LinkedHashMap<Integer,List<InvestigationElement>>();
List<InvestigationElement> measurementList = new ArrayList<InvestigationElement>();
List<InvestigationElement> categoryList = new ArrayList<InvestigationElement>();
List<InvestigationElement> protocolList = new ArrayList<InvestigationElement>();
List<InvestigationElement> observationTargetList = new ArrayList<InvestigationElement>();
for(Integer colIndex: colValues.keySet())
{
//dataToAdd.put(colIndex, new ArrayList<InvestigationElement>());
List<InvestigationElement> addedList = new ArrayList<InvestigationElement>();
for(List<InvestigationElement> list: colValues.get(colIndex))
{
//addedList.addAll(list);
if(columnIndexToTableField.get(colIndex).getClassType().equals("Measurement"))
{
measurementList.addAll(list);
}
if(columnIndexToTableField.get(colIndex).getClassType().equals("Category"))
{
categoryList.addAll(list);
}
if(columnIndexToTableField.get(colIndex).getClassType().equals("Protocol"))
{
protocolList.addAll(list);
}
if(columnIndexToTableField.get(colIndex).getClassType().equals("ObservationTarget"))
{
observationTargetList.addAll(list);
}
}
}
- db.update(observationTargetList, Database.DatabaseAction.ADD_IGNORE_EXISTING, OntologyTerm.NAME);
+ db.update(observationTargetList, Database.DatabaseAction.ADD_IGNORE_EXISTING,ObservationTarget.NAME, ObservationTarget.INVESTIGATION_NAME);
- db.update(ontologyTermList, Database.DatabaseAction.ADD_IGNORE_EXISTING, ObservationTarget.NAME);
+ db.update(ontologyTermList, Database.DatabaseAction.ADD_IGNORE_EXISTING, OntologyTerm.NAME);
db.update(categoryList, Database.DatabaseAction.ADD_IGNORE_EXISTING, Category.NAME);
for(InvestigationElement m : measurementList){
List<String> categories_name = (List<String>) m.get(Measurement.CATEGORIES_NAME);
if(categories_name.size() > 0)
{
List<Category> categories = db.find(Category.class, new QueryRule(Category.NAME, Operator.IN, categories_name));
List<Integer> categoryId = new ArrayList<Integer>();
for(Category c : categories){
if(m.get(Measurement.NAME).equals(c.getName())){
c.setName(c.getName() + "_code");
db.update(c);
}
categoryId.add(c.getId());
}
m.set(Measurement.CATEGORIES, categoryId);
}
}
db.update(measurementList, Database.DatabaseAction.ADD_IGNORE_EXISTING, Measurement.NAME, Measurement.INVESTIGATION_NAME);
HashMap<String, List<String>> subProtocolAndProtocol = new HashMap<String, List<String>>();
for(InvestigationElement p : protocolList)
{
List<String> feature_names = (List<String>) p.get(Protocol.FEATURES_NAME);
if(feature_names.size() > 0)
{
List<Measurement> features = db.find(Measurement.class, new QueryRule(Measurement.NAME, Operator.IN, feature_names));
if(features.size() > 0)
{
List<Integer> featuresId = new ArrayList<Integer>();
for(Measurement m : features){
if(!featuresId.contains(m.getId()))
featuresId.add(m.getId());
}
p.set(Protocol.FEATURES, featuresId);
}
}
if(p.get(Protocol.SUBPROTOCOLS_NAME) != null){
if(!subProtocolAndProtocol.containsKey(p.getName())){
subProtocolAndProtocol.put(p.getName(), (List<String>) p.get(Protocol.SUBPROTOCOLS_NAME));
}
List<String> newList = new ArrayList<String>();
p.set(Protocol.SUBPROTOCOLS_NAME, newList);
}
}
db.update(protocolList, Database.DatabaseAction.ADD_IGNORE_EXISTING, Protocol.NAME, Protocol.INVESTIGATION_NAME);
List<InvestigationElement> subProtocols = new ArrayList<InvestigationElement>();
List<InvestigationElement> noneDuplicatedElements = new ArrayList<InvestigationElement>();
for(InvestigationElement p : protocolList)
{
if(!subProtocols.contains(p)){
List<String> subProtocol_names = subProtocolAndProtocol.get(p.getName());
if(subProtocol_names.size() > 0)
{
List<Protocol> subProtocolList = db.find(Protocol.class, new QueryRule(Protocol.NAME, Operator.IN, subProtocol_names));
if(subProtocolList.size() > 0)
{
List<Integer> subProtocolId = new ArrayList<Integer>();
for(Protocol subPro : subProtocolList){
if(!subProtocolId.contains(subPro.getId())){
subProtocolId.add(subPro.getId());
}
}
p.set(Protocol.SUBPROTOCOLS, subProtocolId);
}
}
if(p.getId() != null)
db.update(p);
}
}
- db.update(headerMeasurements, Database.DatabaseAction.ADD_IGNORE_EXISTING, Measurement.NAME, Measurement.CATEGORIES_NAME, Measurement.DATATYPE);
+ db.update(headerMeasurements, Database.DatabaseAction.ADD_IGNORE_EXISTING, Measurement.NAME, Measurement.INVESTIGATION_NAME);
- db.update(observedValueList, Database.DatabaseAction.ADD_IGNORE_EXISTING, ObservedValue.VALUE, ObservedValue.FEATURE_NAME, ObservedValue.TARGET_NAME);
+ db.update(observedValueList, Database.DatabaseAction.ADD_IGNORE_EXISTING, ObservedValue.INVESTIGATION_NAME, ObservedValue.VALUE, ObservedValue.FEATURE_NAME, ObservedValue.TARGET_NAME);
//put all in the database, using right order
//TODO
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String adjustDataTypeValue(String cellValue) {
for(String keySet : InputToMolgenisDataType.keySet())
{
Pattern p = Pattern.compile(keySet);
Matcher m = p.matcher(cellValue);
if(m.find()){
return InputToMolgenisDataType.get(keySet);
}
}
return MeasurementDataType;
}
public void setDataType(String dataTypeInput, String molgenisDataType) {
InputToMolgenisDataType.put(dataTypeInput.toLowerCase(), molgenisDataType);
}
public void setMissingCategoryIndex(int missingCategoryIndex) {
missingCategoryList.add(missingCategoryIndex);
}
public void setInvestigation(String investigationName) throws DatabaseException {
Investigation investigation = new Investigation();
if(investigationName != null && db.query(Investigation.class).eq(Investigation.NAME, investigationName).count() == 0){
investigation.setName(investigationName);
db.add(investigation);
}
if(investigationName != null)
{
this.investigationName = investigationName;
}
}
public void setDirection(String excelDirection) {
this.excelDirection = excelDirection;
}
}
| false | true | public void convertIntoPheno(Sheet sheet){
int row = sheet.getRows();
int column = sheet.getColumns();
List<ObservedValue> observedValueList = new ArrayList<ObservedValue>();
List<OntologyTerm> ontologyTermList = new ArrayList<OntologyTerm>();
if(excelDirection.equals("UploadFileByRow"))
{
row = sheet.getColumns();
column = sheet.getRows();
}
//three dimensional matrix of<colIndex, rowIndex, valueIndex>
//third dimension of valueIndex is to deal with multiple values in one cell
//we made colIndex key because not all colIndexes are used
Map<Integer,List<List<InvestigationElement>>> colValues = new LinkedHashMap<Integer,List<List<InvestigationElement>>>();
Map<Integer,Map<String, List<InvestigationElement>>> existingValues = new LinkedHashMap<Integer, Map<String, List<InvestigationElement>>>();
List<Measurement> headerMeasurements = new ArrayList<Measurement>();
try
{
for(int rowIndex = 0; rowIndex < row; rowIndex++){
for(int colIndex = 0; colIndex < column; colIndex++){
String cellValue;
if(excelDirection.equals("UploadFileByRow"))
cellValue = sheet.getCell(rowIndex, colIndex).getContents().replaceAll("'", "").trim().toLowerCase();
else
cellValue = sheet.getCell(colIndex, rowIndex).getContents().replaceAll("'", "").trim().toLowerCase();
System.out.println("The cell value is " + cellValue);
System.out.println("The size is =========== " + configuration.size());
TableField field = columnIndexToTableField.get(colIndex);
if(columnIndexToTableField.get(colIndex) != null && columnIndexToTableField.get(colIndex).getVertical() && rowIndex != 0){
//Keep track of the entities
if(!existingValues.containsKey(colIndex))
{
Map<String, List<InvestigationElement>> tempHolder = new LinkedHashMap<String, List<InvestigationElement>>();
existingValues.put(colIndex, tempHolder);
}
if(existingValues.get(colIndex).containsKey(cellValue))
{
if(colValues.get(colIndex).size() != rowIndex)
{
colValues.get(colIndex).add(new ArrayList<InvestigationElement>());
}
colValues.get(colIndex).get(rowIndex - 1).addAll(existingValues.get(colIndex).get(cellValue));
}else{
//we split on multivalue
String[] multiValue = cellValue.split(field.getValueSplitter());
for(int valueIndex = 0; valueIndex < multiValue.length; valueIndex++)
{
//If the fieldName is 'name', added as a new entity
if(field.getFieldName().equalsIgnoreCase("NAME")){
String value = multiValue[valueIndex];
InvestigationElement entity = null;
//check colIndex: if there is already a list for colIndex
if(colValues.get(colIndex) == null)
{
colValues.put(colIndex, new ArrayList<List<InvestigationElement>>());
}
//check rowIndex: if there is already a list values
if(colValues.get(colIndex).size() != rowIndex)
{
//create a list for our values (to deal with multivalue)
colValues.get(colIndex).add(new ArrayList<InvestigationElement>());
}
//check valueIndex: if there is already a value
//TODO Chao`s comment: should be multiValue.length instead of rowIndex
if(colValues.get(colIndex).get(rowIndex - 1).size() != multiValue.length)
{
//create the entity
entity = (InvestigationElement) DatabaseFactory.create().getClassForName(field.getClassType()).newInstance();
}
if(!value.equalsIgnoreCase("")){
if(field.getClassType().equals(Category.class.getSimpleName())){
//Category entity couldn`t have empty property in name, description, code_string, label
//therefore it`s separated from other entites.
entity.set(Category.NAME, value);
entity.set(Category.DESCRIPTION, value);
entity.set(Category.CODE_STRING, value);
entity.set(Category.LABEL, value);
if(field.getDefaults().getString(Category.ISMISSING) != null)
entity.set(Category.ISMISSING, field.getDefaults().getString(Category.ISMISSING));
}else{
//set the field as specified in getFieldName() = 'name' or 'missing' or 'dataType', etc
entity.set(field.getFieldName(), value);
}
if(investigationName != null)
entity.set("Investigation_name", investigationName);
colValues.get(colIndex).get(rowIndex - 1).add(entity);
//field.setEntity(entity);
}
}
}
}
if(field.getDependentColumnIndex()[0] != -1){
for(int index = 0; index < field.getDependentColumnIndex().length; index++){
int dependentColumn = field.getDependentColumnIndex()[index];
TableField dependendField = columnIndexToTableField.get(dependentColumn);
//InvestigationElement addingPropertyToEntity = dependendField.getEntity();
InvestigationElement addingPropertyToEntity = colValues.get(dependentColumn).get(rowIndex - 1).get(0);
String multipleValues[] = cellValue.split(dependendField.getValueSplitter());
List<Object> values = new ArrayList<Object>();
for(int i = 0; i < multipleValues.length; i++){
values.add(multipleValues[i].trim());
}
//Due to using generic method get() property of the Pheno Entity, so we don`t know which Object data
//the field would be. We need to check the field type first. It could be list, boolean, string
if(addingPropertyToEntity.get(field.getRelationString()) != null)
{
if(addingPropertyToEntity.get(field.getRelationString()).getClass().equals(ArrayList.class))
{
List<String> previousProperties = (List<String>) addingPropertyToEntity.get(field.getRelationString());
if(previousProperties != null && previousProperties.size() > 0)
{
for(String newValue : previousProperties)
{
if(!values.contains(newValue))
{
values.add(newValue);
}
}
}
}else if(addingPropertyToEntity.get(field.getRelationString()).getClass().equals(Boolean.class)){
values.clear();
if(field.getRelationString().equalsIgnoreCase(Measurement.TEMPORAL))
{
if(cellValue.equalsIgnoreCase("yes"))
{
values.add(true);
}else{
values.add(false);
}
}else{
if(cellValue.equalsIgnoreCase("yes"))
values.add(true);
}
}else if(addingPropertyToEntity.get(field.getRelationString()).getClass().equals(String.class)){
values.clear();
values.add(addingPropertyToEntity.get(field.getRelationString()));
}
if(field.getRelationString().equals(Measurement.DATATYPE)){
String dataType = adjustDataTypeValue(cellValue);
if(!dataType.equals(MeasurementDataType))
{
values.clear();
values.add(dataType);
}
}
}
if(field.getRelationString().equals(Measurement.UNIT_NAME)){
for(int i = 0; i < multipleValues.length; i++)
{
List<String> eachValues = new ArrayList<String>();
eachValues.add(multipleValues[i]);
List<OntologyTerm> existingOntologyTermList = db.find(OntologyTerm.class, new QueryRule(OntologyTerm.NAME, Operator.IN, eachValues));
if(existingOntologyTermList.size() == 0 && !multipleValues[i].equals("")){
OntologyTerm unitOntologyTerm = new OntologyTerm();
unitOntologyTerm.set(OntologyTerm.NAME, multipleValues[i]);
if(!ontologyTermList.contains(unitOntologyTerm)){
ontologyTermList.add(unitOntologyTerm);
}
}
}
}
if(values.size() == 1)
{
addingPropertyToEntity.set(field.getRelationString(), values.get(0));
}else{
addingPropertyToEntity.set(field.getRelationString(), values);
}
}
}
if(!existingValues.get(colIndex).containsKey(cellValue) && colValues.containsKey(colIndex))
{
existingValues.get(colIndex).put(cellValue, colValues.get(colIndex).get(rowIndex - 1));
}
}else{
//The header is measurement!
if(rowIndex == 0){
if(field.getClassType().equalsIgnoreCase(ObservedValue.class.getSimpleName())){
Measurement measurement = new Measurement();
measurement.setName(cellValue);
headerMeasurements.add(measurement);
if(investigationName != null)
measurement.set("Investigation_name", investigationName);
}
//The rest of the column is observedValue!
}else{
if(!cellValue.equals("") && cellValue != null && field.getObservationTarget() != -1){
ObservedValue observedValue = new ObservedValue();
String headerName = sheet.getCell(colIndex, 0).getContents().replaceAll("'", "").trim().toLowerCase();
String targetName = sheet.getCell(field.getObservationTarget(), rowIndex).getContents().replaceAll("'", "").trim().toLowerCase();
observedValue.setFeature_Name(headerName);
observedValue.setTarget_Name(targetName);
observedValue.setValue(cellValue);
observedValueList.add(observedValue);
if(investigationName != null)
observedValue.set("Investigation_name", investigationName);
}
}
}
}
}
//convert the columnValues into one list per column for the database
Map<Integer,List<InvestigationElement>> dataToAdd = new LinkedHashMap<Integer,List<InvestigationElement>>();
List<InvestigationElement> measurementList = new ArrayList<InvestigationElement>();
List<InvestigationElement> categoryList = new ArrayList<InvestigationElement>();
List<InvestigationElement> protocolList = new ArrayList<InvestigationElement>();
List<InvestigationElement> observationTargetList = new ArrayList<InvestigationElement>();
for(Integer colIndex: colValues.keySet())
{
//dataToAdd.put(colIndex, new ArrayList<InvestigationElement>());
List<InvestigationElement> addedList = new ArrayList<InvestigationElement>();
for(List<InvestigationElement> list: colValues.get(colIndex))
{
//addedList.addAll(list);
if(columnIndexToTableField.get(colIndex).getClassType().equals("Measurement"))
{
measurementList.addAll(list);
}
if(columnIndexToTableField.get(colIndex).getClassType().equals("Category"))
{
categoryList.addAll(list);
}
if(columnIndexToTableField.get(colIndex).getClassType().equals("Protocol"))
{
protocolList.addAll(list);
}
if(columnIndexToTableField.get(colIndex).getClassType().equals("ObservationTarget"))
{
observationTargetList.addAll(list);
}
}
}
db.update(observationTargetList, Database.DatabaseAction.ADD_IGNORE_EXISTING, OntologyTerm.NAME);
db.update(ontologyTermList, Database.DatabaseAction.ADD_IGNORE_EXISTING, ObservationTarget.NAME);
db.update(categoryList, Database.DatabaseAction.ADD_IGNORE_EXISTING, Category.NAME);
for(InvestigationElement m : measurementList){
List<String> categories_name = (List<String>) m.get(Measurement.CATEGORIES_NAME);
if(categories_name.size() > 0)
{
List<Category> categories = db.find(Category.class, new QueryRule(Category.NAME, Operator.IN, categories_name));
List<Integer> categoryId = new ArrayList<Integer>();
for(Category c : categories){
if(m.get(Measurement.NAME).equals(c.getName())){
c.setName(c.getName() + "_code");
db.update(c);
}
categoryId.add(c.getId());
}
m.set(Measurement.CATEGORIES, categoryId);
}
}
db.update(measurementList, Database.DatabaseAction.ADD_IGNORE_EXISTING, Measurement.NAME, Measurement.INVESTIGATION_NAME);
HashMap<String, List<String>> subProtocolAndProtocol = new HashMap<String, List<String>>();
for(InvestigationElement p : protocolList)
{
List<String> feature_names = (List<String>) p.get(Protocol.FEATURES_NAME);
if(feature_names.size() > 0)
{
List<Measurement> features = db.find(Measurement.class, new QueryRule(Measurement.NAME, Operator.IN, feature_names));
if(features.size() > 0)
{
List<Integer> featuresId = new ArrayList<Integer>();
for(Measurement m : features){
if(!featuresId.contains(m.getId()))
featuresId.add(m.getId());
}
p.set(Protocol.FEATURES, featuresId);
}
}
if(p.get(Protocol.SUBPROTOCOLS_NAME) != null){
if(!subProtocolAndProtocol.containsKey(p.getName())){
subProtocolAndProtocol.put(p.getName(), (List<String>) p.get(Protocol.SUBPROTOCOLS_NAME));
}
List<String> newList = new ArrayList<String>();
p.set(Protocol.SUBPROTOCOLS_NAME, newList);
}
}
db.update(protocolList, Database.DatabaseAction.ADD_IGNORE_EXISTING, Protocol.NAME, Protocol.INVESTIGATION_NAME);
List<InvestigationElement> subProtocols = new ArrayList<InvestigationElement>();
List<InvestigationElement> noneDuplicatedElements = new ArrayList<InvestigationElement>();
for(InvestigationElement p : protocolList)
{
if(!subProtocols.contains(p)){
List<String> subProtocol_names = subProtocolAndProtocol.get(p.getName());
if(subProtocol_names.size() > 0)
{
List<Protocol> subProtocolList = db.find(Protocol.class, new QueryRule(Protocol.NAME, Operator.IN, subProtocol_names));
if(subProtocolList.size() > 0)
{
List<Integer> subProtocolId = new ArrayList<Integer>();
for(Protocol subPro : subProtocolList){
if(!subProtocolId.contains(subPro.getId())){
subProtocolId.add(subPro.getId());
}
}
p.set(Protocol.SUBPROTOCOLS, subProtocolId);
}
}
if(p.getId() != null)
db.update(p);
}
}
db.update(headerMeasurements, Database.DatabaseAction.ADD_IGNORE_EXISTING, Measurement.NAME, Measurement.CATEGORIES_NAME, Measurement.DATATYPE);
db.update(observedValueList, Database.DatabaseAction.ADD_IGNORE_EXISTING, ObservedValue.VALUE, ObservedValue.FEATURE_NAME, ObservedValue.TARGET_NAME);
//put all in the database, using right order
//TODO
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| public void convertIntoPheno(Sheet sheet){
int row = sheet.getRows();
int column = sheet.getColumns();
List<ObservedValue> observedValueList = new ArrayList<ObservedValue>();
List<OntologyTerm> ontologyTermList = new ArrayList<OntologyTerm>();
if(excelDirection.equals("UploadFileByRow"))
{
row = sheet.getColumns();
column = sheet.getRows();
}
//three dimensional matrix of<colIndex, rowIndex, valueIndex>
//third dimension of valueIndex is to deal with multiple values in one cell
//we made colIndex key because not all colIndexes are used
Map<Integer,List<List<InvestigationElement>>> colValues = new LinkedHashMap<Integer,List<List<InvestigationElement>>>();
Map<Integer,Map<String, List<InvestigationElement>>> existingValues = new LinkedHashMap<Integer, Map<String, List<InvestigationElement>>>();
List<Measurement> headerMeasurements = new ArrayList<Measurement>();
try
{
for(int rowIndex = 0; rowIndex < row; rowIndex++){
for(int colIndex = 0; colIndex < column; colIndex++){
String cellValue;
if(excelDirection.equals("UploadFileByRow"))
cellValue = sheet.getCell(rowIndex, colIndex).getContents().replaceAll("'", "").trim().toLowerCase();
else
cellValue = sheet.getCell(colIndex, rowIndex).getContents().replaceAll("'", "").trim().toLowerCase();
System.out.println("The cell value is " + cellValue);
System.out.println("The size is =========== " + configuration.size());
TableField field = columnIndexToTableField.get(colIndex);
if(columnIndexToTableField.get(colIndex) != null && columnIndexToTableField.get(colIndex).getVertical() && rowIndex != 0){
//Keep track of the entities
if(!existingValues.containsKey(colIndex))
{
Map<String, List<InvestigationElement>> tempHolder = new LinkedHashMap<String, List<InvestigationElement>>();
existingValues.put(colIndex, tempHolder);
}
if(existingValues.get(colIndex).containsKey(cellValue))
{
if(colValues.get(colIndex).size() != rowIndex)
{
colValues.get(colIndex).add(new ArrayList<InvestigationElement>());
}
colValues.get(colIndex).get(rowIndex - 1).addAll(existingValues.get(colIndex).get(cellValue));
}else{
//we split on multivalue
String[] multiValue = cellValue.split(field.getValueSplitter());
for(int valueIndex = 0; valueIndex < multiValue.length; valueIndex++)
{
//If the fieldName is 'name', added as a new entity
if(field.getFieldName().equalsIgnoreCase("NAME")){
String value = multiValue[valueIndex];
InvestigationElement entity = null;
//check colIndex: if there is already a list for colIndex
if(colValues.get(colIndex) == null)
{
colValues.put(colIndex, new ArrayList<List<InvestigationElement>>());
}
//check rowIndex: if there is already a list values
if(colValues.get(colIndex).size() != rowIndex)
{
//create a list for our values (to deal with multivalue)
colValues.get(colIndex).add(new ArrayList<InvestigationElement>());
}
//check valueIndex: if there is already a value
//TODO Chao`s comment: should be multiValue.length instead of rowIndex
if(colValues.get(colIndex).get(rowIndex - 1).size() != multiValue.length)
{
//create the entity
entity = (InvestigationElement) DatabaseFactory.create().getClassForName(field.getClassType()).newInstance();
}
if(!value.equalsIgnoreCase("")){
if(field.getClassType().equals(Category.class.getSimpleName())){
//Category entity couldn`t have empty property in name, description, code_string, label
//therefore it`s separated from other entites.
entity.set(Category.NAME, value);
entity.set(Category.DESCRIPTION, value);
entity.set(Category.CODE_STRING, value);
entity.set(Category.LABEL, value);
if(field.getDefaults().getString(Category.ISMISSING) != null)
entity.set(Category.ISMISSING, field.getDefaults().getString(Category.ISMISSING));
}else{
//set the field as specified in getFieldName() = 'name' or 'missing' or 'dataType', etc
entity.set(field.getFieldName(), value);
}
if(investigationName != null)
entity.set("Investigation_name", investigationName);
colValues.get(colIndex).get(rowIndex - 1).add(entity);
//field.setEntity(entity);
}
}
}
}
if(field.getDependentColumnIndex()[0] != -1){
for(int index = 0; index < field.getDependentColumnIndex().length; index++){
int dependentColumn = field.getDependentColumnIndex()[index];
TableField dependendField = columnIndexToTableField.get(dependentColumn);
//InvestigationElement addingPropertyToEntity = dependendField.getEntity();
InvestigationElement addingPropertyToEntity = colValues.get(dependentColumn).get(rowIndex - 1).get(0);
String multipleValues[] = cellValue.split(dependendField.getValueSplitter());
List<Object> values = new ArrayList<Object>();
for(int i = 0; i < multipleValues.length; i++){
values.add(multipleValues[i].trim());
}
//Due to using generic method get() property of the Pheno Entity, so we don`t know which Object data
//the field would be. We need to check the field type first. It could be list, boolean, string
if(addingPropertyToEntity.get(field.getRelationString()) != null)
{
if(addingPropertyToEntity.get(field.getRelationString()).getClass().equals(ArrayList.class))
{
List<String> previousProperties = (List<String>) addingPropertyToEntity.get(field.getRelationString());
if(previousProperties != null && previousProperties.size() > 0)
{
for(String newValue : previousProperties)
{
if(!values.contains(newValue))
{
values.add(newValue);
}
}
}
}else if(addingPropertyToEntity.get(field.getRelationString()).getClass().equals(Boolean.class)){
values.clear();
if(field.getRelationString().equalsIgnoreCase(Measurement.TEMPORAL))
{
if(cellValue.equalsIgnoreCase("yes"))
{
values.add(true);
}else{
values.add(false);
}
}else{
if(cellValue.equalsIgnoreCase("yes"))
values.add(true);
}
}else if(addingPropertyToEntity.get(field.getRelationString()).getClass().equals(String.class)){
values.clear();
values.add(addingPropertyToEntity.get(field.getRelationString()));
}
if(field.getRelationString().equals(Measurement.DATATYPE)){
String dataType = adjustDataTypeValue(cellValue);
if(!dataType.equals(MeasurementDataType))
{
values.clear();
values.add(dataType);
}
}
}
if(field.getRelationString().equals(Measurement.UNIT_NAME)){
for(int i = 0; i < multipleValues.length; i++)
{
List<String> eachValues = new ArrayList<String>();
eachValues.add(multipleValues[i]);
List<OntologyTerm> existingOntologyTermList = db.find(OntologyTerm.class, new QueryRule(OntologyTerm.NAME, Operator.IN, eachValues));
if(existingOntologyTermList.size() == 0 && !multipleValues[i].equals("")){
OntologyTerm unitOntologyTerm = new OntologyTerm();
unitOntologyTerm.set(OntologyTerm.NAME, multipleValues[i]);
if(!ontologyTermList.contains(unitOntologyTerm)){
ontologyTermList.add(unitOntologyTerm);
}
}
}
}
if(values.size() == 1)
{
addingPropertyToEntity.set(field.getRelationString(), values.get(0));
}else{
addingPropertyToEntity.set(field.getRelationString(), values);
}
}
}
if(!existingValues.get(colIndex).containsKey(cellValue) && colValues.containsKey(colIndex))
{
existingValues.get(colIndex).put(cellValue, colValues.get(colIndex).get(rowIndex - 1));
}
}else{
//The header is measurement!
if(rowIndex == 0){
if(field.getClassType().equalsIgnoreCase(ObservedValue.class.getSimpleName())){
Measurement measurement = new Measurement();
measurement.setName(cellValue);
headerMeasurements.add(measurement);
if(investigationName != null)
measurement.set("Investigation_name", investigationName);
}
//The rest of the column is observedValue!
}else{
if(!cellValue.equals("") && cellValue != null && field.getObservationTarget() != -1){
ObservedValue observedValue = new ObservedValue();
String headerName = sheet.getCell(colIndex, 0).getContents().replaceAll("'", "").trim().toLowerCase();
String targetName = sheet.getCell(field.getObservationTarget(), rowIndex).getContents().replaceAll("'", "").trim().toLowerCase();
observedValue.setFeature_Name(headerName);
observedValue.setTarget_Name(targetName);
observedValue.setValue(cellValue);
observedValueList.add(observedValue);
if(investigationName != null)
observedValue.set("Investigation_name", investigationName);
}
}
}
}
}
//convert the columnValues into one list per column for the database
Map<Integer,List<InvestigationElement>> dataToAdd = new LinkedHashMap<Integer,List<InvestigationElement>>();
List<InvestigationElement> measurementList = new ArrayList<InvestigationElement>();
List<InvestigationElement> categoryList = new ArrayList<InvestigationElement>();
List<InvestigationElement> protocolList = new ArrayList<InvestigationElement>();
List<InvestigationElement> observationTargetList = new ArrayList<InvestigationElement>();
for(Integer colIndex: colValues.keySet())
{
//dataToAdd.put(colIndex, new ArrayList<InvestigationElement>());
List<InvestigationElement> addedList = new ArrayList<InvestigationElement>();
for(List<InvestigationElement> list: colValues.get(colIndex))
{
//addedList.addAll(list);
if(columnIndexToTableField.get(colIndex).getClassType().equals("Measurement"))
{
measurementList.addAll(list);
}
if(columnIndexToTableField.get(colIndex).getClassType().equals("Category"))
{
categoryList.addAll(list);
}
if(columnIndexToTableField.get(colIndex).getClassType().equals("Protocol"))
{
protocolList.addAll(list);
}
if(columnIndexToTableField.get(colIndex).getClassType().equals("ObservationTarget"))
{
observationTargetList.addAll(list);
}
}
}
db.update(observationTargetList, Database.DatabaseAction.ADD_IGNORE_EXISTING,ObservationTarget.NAME, ObservationTarget.INVESTIGATION_NAME);
db.update(ontologyTermList, Database.DatabaseAction.ADD_IGNORE_EXISTING, OntologyTerm.NAME);
db.update(categoryList, Database.DatabaseAction.ADD_IGNORE_EXISTING, Category.NAME);
for(InvestigationElement m : measurementList){
List<String> categories_name = (List<String>) m.get(Measurement.CATEGORIES_NAME);
if(categories_name.size() > 0)
{
List<Category> categories = db.find(Category.class, new QueryRule(Category.NAME, Operator.IN, categories_name));
List<Integer> categoryId = new ArrayList<Integer>();
for(Category c : categories){
if(m.get(Measurement.NAME).equals(c.getName())){
c.setName(c.getName() + "_code");
db.update(c);
}
categoryId.add(c.getId());
}
m.set(Measurement.CATEGORIES, categoryId);
}
}
db.update(measurementList, Database.DatabaseAction.ADD_IGNORE_EXISTING, Measurement.NAME, Measurement.INVESTIGATION_NAME);
HashMap<String, List<String>> subProtocolAndProtocol = new HashMap<String, List<String>>();
for(InvestigationElement p : protocolList)
{
List<String> feature_names = (List<String>) p.get(Protocol.FEATURES_NAME);
if(feature_names.size() > 0)
{
List<Measurement> features = db.find(Measurement.class, new QueryRule(Measurement.NAME, Operator.IN, feature_names));
if(features.size() > 0)
{
List<Integer> featuresId = new ArrayList<Integer>();
for(Measurement m : features){
if(!featuresId.contains(m.getId()))
featuresId.add(m.getId());
}
p.set(Protocol.FEATURES, featuresId);
}
}
if(p.get(Protocol.SUBPROTOCOLS_NAME) != null){
if(!subProtocolAndProtocol.containsKey(p.getName())){
subProtocolAndProtocol.put(p.getName(), (List<String>) p.get(Protocol.SUBPROTOCOLS_NAME));
}
List<String> newList = new ArrayList<String>();
p.set(Protocol.SUBPROTOCOLS_NAME, newList);
}
}
db.update(protocolList, Database.DatabaseAction.ADD_IGNORE_EXISTING, Protocol.NAME, Protocol.INVESTIGATION_NAME);
List<InvestigationElement> subProtocols = new ArrayList<InvestigationElement>();
List<InvestigationElement> noneDuplicatedElements = new ArrayList<InvestigationElement>();
for(InvestigationElement p : protocolList)
{
if(!subProtocols.contains(p)){
List<String> subProtocol_names = subProtocolAndProtocol.get(p.getName());
if(subProtocol_names.size() > 0)
{
List<Protocol> subProtocolList = db.find(Protocol.class, new QueryRule(Protocol.NAME, Operator.IN, subProtocol_names));
if(subProtocolList.size() > 0)
{
List<Integer> subProtocolId = new ArrayList<Integer>();
for(Protocol subPro : subProtocolList){
if(!subProtocolId.contains(subPro.getId())){
subProtocolId.add(subPro.getId());
}
}
p.set(Protocol.SUBPROTOCOLS, subProtocolId);
}
}
if(p.getId() != null)
db.update(p);
}
}
db.update(headerMeasurements, Database.DatabaseAction.ADD_IGNORE_EXISTING, Measurement.NAME, Measurement.INVESTIGATION_NAME);
db.update(observedValueList, Database.DatabaseAction.ADD_IGNORE_EXISTING, ObservedValue.INVESTIGATION_NAME, ObservedValue.VALUE, ObservedValue.FEATURE_NAME, ObservedValue.TARGET_NAME);
//put all in the database, using right order
//TODO
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
diff --git a/src/main/java/com/abudko/reseller/huuto/mvc/item/QueryItemController.java b/src/main/java/com/abudko/reseller/huuto/mvc/item/QueryItemController.java
index cb334e4..c06f91d 100644
--- a/src/main/java/com/abudko/reseller/huuto/mvc/item/QueryItemController.java
+++ b/src/main/java/com/abudko/reseller/huuto/mvc/item/QueryItemController.java
@@ -1,43 +1,43 @@
package com.abudko.reseller.huuto.mvc.item;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.abudko.reseller.huuto.order.ItemOrder;
import com.abudko.reseller.huuto.query.html.item.ItemResponse;
import com.abudko.reseller.huuto.query.service.item.QueryItemService;
@Controller
public class QueryItemController {
private Logger log = LoggerFactory.getLogger(getClass());
@Resource
private QueryItemService queryItemService;
@RequestMapping(value = "/item", method = RequestMethod.GET)
public String extractItem(@RequestParam String url, Model model) {
log.info(String.format("Handling item request with parameter %s", url));
ItemResponse response = queryItemService.extractItem(url);
ItemOrder order = createItemOrderFor(response);
model.addAttribute("itemOrder", order);
- return "order";
+ return "order/order";
}
private ItemOrder createItemOrderFor(ItemResponse response) {
ItemOrder order = new ItemOrder();
order.setItemResponse(response);
order.setNewPrice(response.getPrice());
return order;
}
}
| true | true | public String extractItem(@RequestParam String url, Model model) {
log.info(String.format("Handling item request with parameter %s", url));
ItemResponse response = queryItemService.extractItem(url);
ItemOrder order = createItemOrderFor(response);
model.addAttribute("itemOrder", order);
return "order";
}
| public String extractItem(@RequestParam String url, Model model) {
log.info(String.format("Handling item request with parameter %s", url));
ItemResponse response = queryItemService.extractItem(url);
ItemOrder order = createItemOrderFor(response);
model.addAttribute("itemOrder", order);
return "order/order";
}
|
diff --git a/svnkit/src/org/tmatesoft/svn/core/internal/wc/admin/SVNAdminAreaFactory.java b/svnkit/src/org/tmatesoft/svn/core/internal/wc/admin/SVNAdminAreaFactory.java
index 8b3e968ec..a17f9771b 100644
--- a/svnkit/src/org/tmatesoft/svn/core/internal/wc/admin/SVNAdminAreaFactory.java
+++ b/svnkit/src/org/tmatesoft/svn/core/internal/wc/admin/SVNAdminAreaFactory.java
@@ -1,324 +1,324 @@
/*
* ====================================================================
* Copyright (c) 2004-2009 TMate Software Ltd. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://svnkit.com/license.html
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
* ====================================================================
*/
package org.tmatesoft.svn.core.internal.wc.admin;
import java.io.File;
import java.util.Collection;
import java.util.Iterator;
import java.util.TreeSet;
import java.util.logging.Level;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.wc.SVNErrorManager;
import org.tmatesoft.svn.core.internal.wc.SVNEventFactory;
import org.tmatesoft.svn.core.internal.wc.SVNFileUtil;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.wc.ISVNEventHandler;
import org.tmatesoft.svn.core.wc.SVNEvent;
import org.tmatesoft.svn.core.wc.SVNEventAction;
import org.tmatesoft.svn.util.SVNLogType;
/**
* @version 1.3
* @author TMate Software Ltd.
*/
public abstract class SVNAdminAreaFactory implements Comparable {
public static final int WC_FORMAT_13 = 4;
public static final int WC_FORMAT_14 = 8;
public static final int WC_FORMAT_15 = 9;
public static final int WC_FORMAT_16 = 10;
private static final Collection ourFactories = new TreeSet();
private static boolean ourIsUpgradeEnabled = Boolean.valueOf(System.getProperty("svnkit.upgradeWC", System.getProperty("javasvn.upgradeWC", "true"))).booleanValue();
private static ISVNAdminAreaFactorySelector ourSelector;
private static ISVNAdminAreaFactorySelector ourDefaultSelector = new DefaultSelector();
static {
SVNAdminAreaFactory.registerFactory(new SVNAdminArea16Factory());
SVNAdminAreaFactory.registerFactory(new SVNAdminArea15Factory());
SVNAdminAreaFactory.registerFactory(new SVNAdminArea14Factory());
SVNAdminAreaFactory.registerFactory(new SVNXMLAdminAreaFactory());
}
public static void setUpgradeEnabled(boolean enabled) {
ourIsUpgradeEnabled = enabled;
}
public static boolean isUpgradeEnabled() {
return ourIsUpgradeEnabled;
}
public static void setSelector(ISVNAdminAreaFactorySelector selector) {
ourSelector = selector;
}
public static ISVNAdminAreaFactorySelector getSelector() {
return ourSelector != null ? ourSelector : ourDefaultSelector;
}
public static int checkWC(File path, boolean useSelector) throws SVNException {
return checkWC(path, useSelector, Level.FINE);
}
public static int checkWC(File path, boolean useSelector, Level logLevel) throws SVNException {
Collection enabledFactories = ourFactories;
if (useSelector) {
enabledFactories = getSelector().getEnabledFactories(path, enabledFactories, false);
}
SVNErrorMessage error = null;
int version = -1;
for(Iterator factories = enabledFactories.iterator(); factories.hasNext();) {
SVNAdminAreaFactory factory = (SVNAdminAreaFactory) factories.next();
try {
version = factory.doCheckWC(path, logLevel);
if (version == 0) {
return version;
}
if (version > factory.getSupportedVersion()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_UNSUPPORTED_FORMAT,
"This client is too old to work with working copy ''{0}''; please get a newer Subversion client",
path);
SVNErrorManager.error(err, SVNLogType.WC);
} else if (version < factory.getSupportedVersion()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_UNSUPPORTED_FORMAT,
"Working copy format of {0} is too old ({1}); please check out your working copy again",
new Object[] {path, new Integer(version)});
SVNErrorManager.error(err, SVNLogType.WC);
}
} catch (SVNException e) {
if (error != null) {
error.setChildErrorMessage(e.getErrorMessage());
} else {
error = e.getErrorMessage();
}
continue;
}
return version;
}
if (error == null) {
error = SVNErrorMessage.create(SVNErrorCode.WC_NOT_DIRECTORY, "''{0}'' is not a working copy", path);
}
SVNErrorManager.error(error, logLevel, SVNLogType.WC);
return 0;
}
public static SVNAdminArea open(File path, Level logLevel) throws SVNException {
SVNErrorMessage error = null;
int wcFormatVersion = -1;
Collection enabledFactories = getSelector().getEnabledFactories(path, ourFactories, false);
File adminDir = new File(path, SVNFileUtil.getAdminDirectoryName());
File entriesFile = new File(adminDir, "entries");
if (adminDir.isDirectory() && entriesFile.isFile()) {
for (Iterator factories = enabledFactories.iterator(); factories.hasNext();) {
SVNAdminAreaFactory factory = (SVNAdminAreaFactory) factories.next();
try {
wcFormatVersion = factory.getVersion(path);
if (wcFormatVersion > factory.getSupportedVersion()) {
- error = SVNErrorMessage.create(SVNErrorCode.WC_UNSUPPORTED_FORMAT,
+ SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_UNSUPPORTED_FORMAT,
"This client is too old to work with working copy ''{0}''; please get a newer Subversion client",
path);
- SVNErrorManager.error(error, SVNLogType.WC);
+ SVNErrorManager.error(err, SVNLogType.WC);
} else if (wcFormatVersion < factory.getSupportedVersion()) {
- error = SVNErrorMessage.create(SVNErrorCode.WC_UNSUPPORTED_FORMAT,
+ SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_UNSUPPORTED_FORMAT,
"Working copy format of {0} is too old ({1}); please check out your working copy again",
new Object[]{path, new Integer(wcFormatVersion)});
- SVNErrorManager.error(error, SVNLogType.WC);
+ SVNErrorManager.error(err, SVNLogType.WC);
}
} catch (SVNException e) {
if (error != null) {
error.setChildErrorMessage(e.getErrorMessage());
} else {
error = e.getErrorMessage();
}
continue;
}
SVNAdminArea adminArea = factory.doOpen(path, wcFormatVersion);
if (adminArea != null) {
adminArea.setWorkingCopyFormatVersion(wcFormatVersion);
return adminArea;
}
}
}
if (error == null) {
error = SVNErrorMessage.create(SVNErrorCode.WC_NOT_DIRECTORY, "''{0}'' is not a working copy", path);
}
SVNErrorManager.error(error, logLevel, SVNLogType.WC);
return null;
}
public static SVNAdminArea upgrade(SVNAdminArea area) throws SVNException {
if (isUpgradeEnabled() && !ourFactories.isEmpty()) {
Collection enabledFactories = getSelector().getEnabledFactories(area.getRoot(), ourFactories, true);
if (!enabledFactories.isEmpty()) {
SVNAdminAreaFactory newestFactory = (SVNAdminAreaFactory) enabledFactories.iterator().next();
SVNAdminArea newArea = newestFactory.doChangeWCFormat(area);
if (newArea != null && newArea != area && newArea.getWCAccess() != null) {
SVNEvent event = SVNEventFactory.createSVNEvent(newArea.getRoot(), SVNNodeKind.DIR, null, SVNRepository.INVALID_REVISION, SVNEventAction.UPGRADE, null, null, null);
newArea.getWCAccess().handleEvent(event, ISVNEventHandler.UNKNOWN);
}
area = newArea;
}
}
return area;
}
public static SVNAdminArea changeWCFormat(SVNAdminArea adminArea, int format) throws SVNException {
SVNAdminAreaFactory factory = getAdminAreaFactory(format);
SVNAdminArea newArea = factory.doChangeWCFormat(adminArea);
if (newArea != null && newArea != adminArea && newArea.getWCAccess() != null) {
SVNEvent event = SVNEventFactory.createSVNEvent(newArea.getRoot(), SVNNodeKind.DIR, null, SVNRepository.INVALID_REVISION, SVNEventAction.UPGRADE, null, null, null);
newArea.getWCAccess().handleEvent(event, ISVNEventHandler.UNKNOWN);
}
adminArea = newArea;
return adminArea;
}
private static SVNAdminAreaFactory getAdminAreaFactory(int wcFormat) throws SVNException {
if (wcFormat == SVNXMLAdminAreaFactory.WC_FORMAT) {
return new SVNXMLAdminAreaFactory();
}
if (wcFormat == SVNAdminArea14Factory.WC_FORMAT) {
return new SVNAdminArea14Factory();
}
if (wcFormat == SVNAdminArea15Factory.WC_FORMAT) {
return new SVNAdminArea15Factory();
}
if (wcFormat == SVNAdminArea16Factory.WC_FORMAT) {
return new SVNAdminArea16Factory();
}
SVNErrorManager.error(SVNErrorMessage.create(SVNErrorCode.WC_UNSUPPORTED_FORMAT), SVNLogType.DEFAULT);
return null;
}
private static int readFormatVersion(File adminDir) throws SVNException {
SVNErrorMessage error = null;
int version = -1;
Collection enabledFactories = getSelector().getEnabledFactories(adminDir.getParentFile(), ourFactories, false);
for(Iterator factories = enabledFactories.iterator(); factories.hasNext();) {
SVNAdminAreaFactory factory = (SVNAdminAreaFactory) factories.next();
try {
version = factory.getVersion(adminDir);
} catch (SVNException e) {
error = e.getErrorMessage();
continue;
}
return version;
}
if (error == null) {
error = SVNErrorMessage.create(SVNErrorCode.WC_NOT_DIRECTORY, "''{0}'' is not a working copy", adminDir);
}
SVNErrorManager.error(error, SVNLogType.WC);
return -1;
}
public static void createVersionedDirectory(File path, String url, String rootURL, String uuid, long revNumber, SVNDepth depth) throws SVNException {
if (!ourFactories.isEmpty()) {
if (!checkAdminAreaExists(path, url, revNumber)) {
Collection enabledFactories = getSelector().getEnabledFactories(path, ourFactories, true);
if (!enabledFactories.isEmpty()) {
SVNAdminAreaFactory newestFactory = (SVNAdminAreaFactory) enabledFactories.iterator().next();
newestFactory.doCreateVersionedDirectory(path, url, rootURL, uuid, revNumber, depth);
}
}
}
}
public static void createVersionedDirectory(File path, SVNURL url, SVNURL rootURL, String uuid, long revNumber, SVNDepth depth) throws SVNException {
createVersionedDirectory(path, url != null ? url.toString() : null, rootURL != null ? rootURL.toString() : null, uuid, revNumber, depth);
}
private static boolean checkAdminAreaExists(File dir, String url, long revision) throws SVNException {
File adminDir = new File(dir, SVNFileUtil.getAdminDirectoryName());
if (adminDir.exists() && !adminDir.isDirectory()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_OBSTRUCTED_UPDATE, "''{0}'' is not a directory", dir);
SVNErrorManager.error(err, SVNLogType.WC);
} else if (!adminDir.exists()) {
return false;
}
boolean wcExists = false;
try {
readFormatVersion(adminDir);
wcExists = true;
} catch (SVNException svne) {
return false;
}
if (wcExists) {
SVNWCAccess wcAccess = SVNWCAccess.newInstance(null);
SVNAdminArea adminArea = null;
SVNEntry entry = null;
try {
adminArea = wcAccess.open(dir, false, 0);
entry = adminArea.getVersionedEntry(adminArea.getThisDirName(), false);
} finally {
wcAccess.closeAdminArea(dir);
}
if (!entry.isScheduledForDeletion()) {
if (entry.getRevision() != revision) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_OBSTRUCTED_UPDATE, "Revision {0} doesn''t match existing revision {1} in ''{2}''", new Object[]{new Long(revision), new Long(entry.getRevision()), dir});
SVNErrorManager.error(err, SVNLogType.WC);
}
if (!url.equals(entry.getURL())) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_OBSTRUCTED_UPDATE, "URL ''{0}'' doesn''t match existing URL ''{1}'' in ''{2}''", new Object[]{url, entry.getURL(), dir});
SVNErrorManager.error(err, SVNLogType.WC);
}
}
}
return wcExists;
}
public abstract int getSupportedVersion();
protected abstract int getVersion(File path) throws SVNException;
protected abstract SVNAdminArea doOpen(File path, int version) throws SVNException;
protected abstract SVNAdminArea doChangeWCFormat(SVNAdminArea area) throws SVNException;
protected abstract void doCreateVersionedDirectory(File path, String url, String rootURL, String uuid, long revNumber, SVNDepth depth) throws SVNException;
protected abstract int doCheckWC(File path, Level logLevel) throws SVNException;
protected static void registerFactory(SVNAdminAreaFactory factory) {
if (factory != null) {
ourFactories.add(factory);
}
}
public int compareTo(Object o) {
if (o == null || !(o instanceof SVNAdminAreaFactory)) {
return -1;
}
int version = ((SVNAdminAreaFactory) o).getSupportedVersion();
return getSupportedVersion() > version ? -1 : (getSupportedVersion() < version) ? 1 : 0;
}
private static class DefaultSelector implements ISVNAdminAreaFactorySelector {
public Collection getEnabledFactories(File path, Collection factories, boolean writeAccess) throws SVNException {
return factories;
}
}
}
| false | true | public static SVNAdminArea open(File path, Level logLevel) throws SVNException {
SVNErrorMessage error = null;
int wcFormatVersion = -1;
Collection enabledFactories = getSelector().getEnabledFactories(path, ourFactories, false);
File adminDir = new File(path, SVNFileUtil.getAdminDirectoryName());
File entriesFile = new File(adminDir, "entries");
if (adminDir.isDirectory() && entriesFile.isFile()) {
for (Iterator factories = enabledFactories.iterator(); factories.hasNext();) {
SVNAdminAreaFactory factory = (SVNAdminAreaFactory) factories.next();
try {
wcFormatVersion = factory.getVersion(path);
if (wcFormatVersion > factory.getSupportedVersion()) {
error = SVNErrorMessage.create(SVNErrorCode.WC_UNSUPPORTED_FORMAT,
"This client is too old to work with working copy ''{0}''; please get a newer Subversion client",
path);
SVNErrorManager.error(error, SVNLogType.WC);
} else if (wcFormatVersion < factory.getSupportedVersion()) {
error = SVNErrorMessage.create(SVNErrorCode.WC_UNSUPPORTED_FORMAT,
"Working copy format of {0} is too old ({1}); please check out your working copy again",
new Object[]{path, new Integer(wcFormatVersion)});
SVNErrorManager.error(error, SVNLogType.WC);
}
} catch (SVNException e) {
if (error != null) {
error.setChildErrorMessage(e.getErrorMessage());
} else {
error = e.getErrorMessage();
}
continue;
}
SVNAdminArea adminArea = factory.doOpen(path, wcFormatVersion);
if (adminArea != null) {
adminArea.setWorkingCopyFormatVersion(wcFormatVersion);
return adminArea;
}
}
}
if (error == null) {
error = SVNErrorMessage.create(SVNErrorCode.WC_NOT_DIRECTORY, "''{0}'' is not a working copy", path);
}
SVNErrorManager.error(error, logLevel, SVNLogType.WC);
return null;
}
| public static SVNAdminArea open(File path, Level logLevel) throws SVNException {
SVNErrorMessage error = null;
int wcFormatVersion = -1;
Collection enabledFactories = getSelector().getEnabledFactories(path, ourFactories, false);
File adminDir = new File(path, SVNFileUtil.getAdminDirectoryName());
File entriesFile = new File(adminDir, "entries");
if (adminDir.isDirectory() && entriesFile.isFile()) {
for (Iterator factories = enabledFactories.iterator(); factories.hasNext();) {
SVNAdminAreaFactory factory = (SVNAdminAreaFactory) factories.next();
try {
wcFormatVersion = factory.getVersion(path);
if (wcFormatVersion > factory.getSupportedVersion()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_UNSUPPORTED_FORMAT,
"This client is too old to work with working copy ''{0}''; please get a newer Subversion client",
path);
SVNErrorManager.error(err, SVNLogType.WC);
} else if (wcFormatVersion < factory.getSupportedVersion()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.WC_UNSUPPORTED_FORMAT,
"Working copy format of {0} is too old ({1}); please check out your working copy again",
new Object[]{path, new Integer(wcFormatVersion)});
SVNErrorManager.error(err, SVNLogType.WC);
}
} catch (SVNException e) {
if (error != null) {
error.setChildErrorMessage(e.getErrorMessage());
} else {
error = e.getErrorMessage();
}
continue;
}
SVNAdminArea adminArea = factory.doOpen(path, wcFormatVersion);
if (adminArea != null) {
adminArea.setWorkingCopyFormatVersion(wcFormatVersion);
return adminArea;
}
}
}
if (error == null) {
error = SVNErrorMessage.create(SVNErrorCode.WC_NOT_DIRECTORY, "''{0}'' is not a working copy", path);
}
SVNErrorManager.error(error, logLevel, SVNLogType.WC);
return null;
}
|
diff --git a/frost-wot/source/frost/threads/requestThread.java b/frost-wot/source/frost/threads/requestThread.java
index 4621d356..564af54c 100644
--- a/frost-wot/source/frost/threads/requestThread.java
+++ b/frost-wot/source/frost/threads/requestThread.java
@@ -1,573 +1,573 @@
/*
requestThread.java / Frost
Copyright (C) 2001 Jan-Thomas Czornack <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package frost.threads;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import frost.*;
import frost.gui.DownloadTable;
import frost.gui.model.DownloadTableModel;
import frost.gui.objects.*;
import frost.FcpTools.*;
public class requestThread extends Thread
{
static java.util.ResourceBundle LangRes =
java.util.ResourceBundle.getBundle("res.LangRes") /*#BundleType=List*/;
public static final String KEYCOLL_INDICATOR = "ERROR: key collision";
final boolean DEBUG = true;
private String filename;
private Long size;
private String key;
private String SHA1;
private String batch;
private String owner;
private DownloadTable downloadTable;
private FrostBoardObject board;
private FrostDownloadItemObject downloadItem;
public void run()
{
// increase thread counter
synchronized (frame1.threadCountLock)
{
frame1.activeDownloadThreads++;
}
try
{
// some vars
final DownloadTableModel tableModel =
(DownloadTableModel)downloadTable.getModel();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd");
Date today = new Date();
String date = formatter.format(today);
File newFile =
new File(frame1.frostSettings.getValue("downloadDirectory") + filename);
boolean do_request = false;
// if we don't have the CHK, means the key was not inserted
// request it by SHA1
if (key == null)
{
Core.getOut().println("FILEDN: Requesting " + filename);
downloadItem.setState(FrostDownloadItemObject.STATE_REQUESTING);
tableModel.updateRow(downloadItem);
//request the file itself
try
{
request();
if (DEBUG)
Core.getOut().println(
"FILEDN: Uploaded request for " + filename);
}
catch (Throwable t)
{
Core.getOut().println(
"FILEDN: Uploading request failed for " + filename);
t.printStackTrace(Core.getOut());
}
downloadItem.setState(FrostDownloadItemObject.STATE_REQUESTED);
tableModel.updateRow(downloadItem);
synchronized (frame1.threadCountLock)
{
frame1.activeDownloadThreads--;
}
return;
}
//otherwise, proceed as usual
Core.getOut().println("FILEDN: Download of '" + filename + "' started.");
// Download file
boolean success = false;
try
{
success =
FcpRequest.getFile(
key,
size,
newFile,
25,
true, // doRedirect
false, // fastDownload
false, // createTempFile
downloadItem);
}
catch (Throwable t)
{
t.printStackTrace(Core.getOut());
} //please don't do like this { ; }--zab
// file might be erased from table during download...
boolean inTable = false;
for (int x = 0; x < tableModel.getRowCount(); x++)
{
FrostDownloadItemObject actItem =
(FrostDownloadItemObject)tableModel.getRow(x);
if (actItem.getKey() != null
&& actItem.getKey().equals(downloadItem.getKey()))
{
inTable = true;
break;
}
}
// download failed
if (!success)
{
downloadItem.setRetries(downloadItem.getRetries() + 1);
Core.getOut().println(
"FILEDN: Download of " + filename + " failed.");
if (inTable == true)
{
// Upload request to request stack
if (frame1
.frostSettings
.getBoolValue("downloadEnableRequesting")
&& downloadItem.getRetries()
>= frame1.frostSettings.getIntValue(
"downloadRequestAfterTries")
&& board != null
&& board.isFolder() == false)
{
if (DEBUG)
Core.getOut().println(
"FILEDN: Download failed, uploading request for "
+ filename);
downloadItem.setState(
FrostDownloadItemObject.STATE_REQUESTING);
tableModel.updateRow(downloadItem);
// We may not do the request here due to the synchronize
// -> no lock needed, using models
// doing it after this , the table states Waiting and there are threads running,
// so download seems to stall
try
{
request();
if (DEBUG)
Core.getOut().println(
"FILEDN: Uploaded request for " + filename);
}
catch (Throwable t)
{
Core.getOut().println(
"FILEDN: Uploading request failed for "
+ filename);
}
}
else
{
if (DEBUG)
Core.getOut().println(
"FILEDN: Download failed (file is NOT requested).");
}
// set new state -> failed or waiting for another try
if (downloadItem.getRetries()
> frame1.frostSettings.getIntValue("downloadMaxRetries"))
{
if (frame1
.frostSettings
.getBoolValue("downloadRestartFailedDownloads"))
{
downloadItem.setState(
FrostDownloadItemObject.STATE_WAITING);
downloadItem.setRetries(0);
}
else
{
downloadItem.setState(
FrostDownloadItemObject.STATE_FAILED);
}
}
else
{
downloadItem.setState(
FrostDownloadItemObject.STATE_WAITING);
}
tableModel.updateRow(downloadItem);
}
}
// download successfull
else
{
if (board != null && board.isFolder() == false)
{
// Add successful downloaded key to database
SharedFileObject newKey = new SharedFileObject(key);
newKey.setFilename(filename);
newKey.setSize(newFile.length());
newKey.setSHA1(SHA1);
newKey.setDate(date);
newKey.setExchange(false);
Index.addMine(newKey, board);
}
downloadItem.setFileSize(newFile.length());
downloadItem.setState(FrostDownloadItemObject.STATE_DONE);
downloadItem.setEnableDownload(Boolean.valueOf(false));
Core.getOut().println("FILEDN: Download of " + filename + " was successful.");
tableModel.updateRow(downloadItem);
}
}
catch (Throwable t)
{
Core.getOut().println("Oo. EXCEPTION in requestThread.run:");
t.printStackTrace(Core.getOut());
}
synchronized (frame1.threadCountLock)
{
frame1.activeDownloadThreads--;
}
downloadItem.setLastDownloadStopTimeMillis(System.currentTimeMillis());
}
// Request a certain file by SHA1
private void request()
{
int messageUploadHtl = frame1.frostSettings.getIntValue("tofUploadHtl");
boolean requested = false;
if (DEBUG)
Core.getOut().println(
"FILEDN: Uploading request for '"
+ filename
+ "' to board '"
+ board.toString()
+ "'");
String fileSeparator = System.getProperty("file.separator");
String destination =
new StringBuffer()
.append("requests")
.append(fileSeparator)
.append(mixed.makeFilename(owner))
.append("-")
.append(batch)
.append("-")
.append(DateFun.getDate())
.toString();
File checkDestination = new File(destination);
if (!checkDestination.isDirectory())
checkDestination.mkdirs();
// Check if file was already requested
// ++ check only in req files
File[] files = checkDestination.listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
if (name.endsWith(".req.sha"))
return true;
return false;
}
});
for (int i = 0; i < files.length; i++)
{
String content = (FileAccess.readFileRaw(files[i])).trim();
- if (content.equals(key))
+ if (content.equals(SHA1))
{
requested = true;
Core.getOut().println(
"FILEDN: File '" + filename + "' was already requested");
break;
}
}
if (!requested)
{
String date = DateFun.getDate();
String time = DateFun.getFullExtendedTime() + "GMT";
// Generate file to upload
File requestFile = null;
try
{
requestFile =
File.createTempFile(
"reqUpload_",
null,
new File(frame1.frostSettings.getValue("temp.dir")));
}
catch (Exception ex)
{
requestFile =
new File(
frame1.frostSettings.getValue("temp.dir")
+ System.currentTimeMillis()
+ ".tmp");
}
//TOTHINK: we can also encrypt the request
FileAccess.writeFile(SHA1, requestFile);
// Write requested key to disk
// Search empty slot
boolean success = false;
int index = 0;
String output = new String();
int tries = 0;
boolean error = false;
File testMe = null;
while (!success)
{
// Does this index already exist?
testMe =
new File(
new StringBuffer()
.append(destination)
.append(fileSeparator)
.append(index)
.append(".req.sha")
.toString());
if (testMe.length() > 0)
{ // already downloaded
index++;
//if( DEBUG ) Core.getOut().println("FILEDN: File exists, increasing index to " + index);
continue; // while
}
else
{
// probably empty, check if other threads currently try to insert to this index
File lockRequestIndex =
new File(testMe.getPath() + ".lock");
boolean lockFileCreated = false;
try
{
lockFileCreated = lockRequestIndex.createNewFile();
}
catch (IOException ex)
{
Core.getOut().println(
"ERROR: requestThread.request(): unexpected IOException, terminating thread ...");
ex.printStackTrace(Core.getOut());
return;
}
if (lockFileCreated == false)
{
// another thread tries to insert using this index, try next
index++;
if (DEBUG)
Core.getOut().println(
"FILEDN: Other thread tries this index, increasing index to "
+ index);
continue; // while
}
else
{
// we try this index
lockRequestIndex.deleteOnExit();
}
// try to insert
//TOTHINK: we could add the ability files from a specific user to be
//requested on separate channels - good protection vs.spam
String[] result = new String[2];
String upKey =
new StringBuffer()
.append("KSK@frost/request/")
.append(
frame1.frostSettings.getValue("messageBase"))
.append("/")
.append(owner)
.append("-")
.append(batch)
.append("-")
.append(date)
.append("-")
.append(index)
.append(".req.sha")
.toString();
if (DEBUG)
Core.getOut().println(upKey);
result =
FcpInsert.putFile(
upKey,
requestFile,
messageUploadHtl,
false); // doRedirect
Core.getOut().println(
"FcpInsert result[0] = "
+ result[0]
+ " result[1] = "
+ result[1]);
if (result[0] == null || result[1] == null)
{
result[0] = "Error";
result[1] = "Error";
}
if (result[0].equals("Success"))
{
success = true;
}
else if (result[0].equals("KeyCollision"))
{
// Check if the collided key is perhapes the requested one
File compareMe = null;
try
{
compareMe =
File.createTempFile(
"reqUploadCmpDnload_",
null,
new File(
frame1.frostSettings.getValue(
"temp.dir")));
}
catch (Exception ex)
{
compareMe =
new File(
frame1.frostSettings.getValue("temp.dir")
+ System.currentTimeMillis()
+ ".tmp");
}
compareMe.deleteOnExit();
String requestMe = upKey;
if (FcpRequest
.getFile(requestMe, null, compareMe, 25, false))
{
File numberOne = compareMe;
File numberTwo = requestFile;
String contentOne =
(FileAccess.readFileRaw(numberOne)).trim();
String contentTwo =
(FileAccess.readFileRaw(numberTwo)).trim();
//if( DEBUG ) Core.getOut().println(contentOne);
//if( DEBUG ) Core.getOut().println(contentTwo);
if (contentOne.equals(contentTwo))
{
if (DEBUG)
Core.getOut().println(
"FILEDN: Key Collision and file was already requested");
success = true;
}
else
{
index++;
Core.getOut().println(
"FILEDN: Request Upload collided, increasing index to "
+ index);
if (frame1
.frostSettings
.getBoolValue("disableRequests")
== true)
{
// uploading is disabled, therefore already existing requests are not
// written to disk, causing key collosions on every request insert.
// this write a .req file to inform others to not try this index again
// if user switches to uploading enabled, this dummy .req files should
// be silently deleted to enable receiving of new requests
FileAccess.writeFile(
KEYCOLL_INDICATOR,
testMe);
}
}
}
else
{
Core.getOut().println(
"FILEDN: Request upload failed ("
+ tries
+ "), retrying index "
+ index);
if (tries > 5)
{
success = true;
error = true;
}
tries++;
}
compareMe.delete();
}
// finally delete the index lock file
lockRequestIndex.delete();
}
}
if (!error)
{
requestFile.renameTo(testMe);
Core.getOut().println(
"*********************************************************************");
Core.getOut().println(
"Request for '"
+ filename
+ "' successfully uploaded to board '"
+ board
+ "'.");
Core.getOut().println(
"*********************************************************************");
}
else
{
Core.getOut().println(
"\nFILEDN: Error while uploading request for '"
+ filename
+ "' to board '"
+ board
+ "'.");
requestFile.delete();
}
Core.getOut().println("FILEDN: Request Upload Thread finished");
}
}
/**Constructor*/
public requestThread(
FrostDownloadItemObject dlItem,
DownloadTable downloadTable)
{
this.filename = dlItem.getFileName();
this.size = dlItem.getFileSize();
this.key = dlItem.getKey();
this.board = dlItem.getSourceBoard();
this.SHA1 = dlItem.getSHA1();
this.batch = dlItem.getBatch();
this.owner = dlItem.getOwner();
this.downloadItem = dlItem;
this.downloadTable = downloadTable;
}
}
| true | true | private void request()
{
int messageUploadHtl = frame1.frostSettings.getIntValue("tofUploadHtl");
boolean requested = false;
if (DEBUG)
Core.getOut().println(
"FILEDN: Uploading request for '"
+ filename
+ "' to board '"
+ board.toString()
+ "'");
String fileSeparator = System.getProperty("file.separator");
String destination =
new StringBuffer()
.append("requests")
.append(fileSeparator)
.append(mixed.makeFilename(owner))
.append("-")
.append(batch)
.append("-")
.append(DateFun.getDate())
.toString();
File checkDestination = new File(destination);
if (!checkDestination.isDirectory())
checkDestination.mkdirs();
// Check if file was already requested
// ++ check only in req files
File[] files = checkDestination.listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
if (name.endsWith(".req.sha"))
return true;
return false;
}
});
for (int i = 0; i < files.length; i++)
{
String content = (FileAccess.readFileRaw(files[i])).trim();
if (content.equals(key))
{
requested = true;
Core.getOut().println(
"FILEDN: File '" + filename + "' was already requested");
break;
}
}
if (!requested)
{
String date = DateFun.getDate();
String time = DateFun.getFullExtendedTime() + "GMT";
// Generate file to upload
File requestFile = null;
try
{
requestFile =
File.createTempFile(
"reqUpload_",
null,
new File(frame1.frostSettings.getValue("temp.dir")));
}
catch (Exception ex)
{
requestFile =
new File(
frame1.frostSettings.getValue("temp.dir")
+ System.currentTimeMillis()
+ ".tmp");
}
//TOTHINK: we can also encrypt the request
FileAccess.writeFile(SHA1, requestFile);
// Write requested key to disk
// Search empty slot
boolean success = false;
int index = 0;
String output = new String();
int tries = 0;
boolean error = false;
File testMe = null;
while (!success)
{
// Does this index already exist?
testMe =
new File(
new StringBuffer()
.append(destination)
.append(fileSeparator)
.append(index)
.append(".req.sha")
.toString());
if (testMe.length() > 0)
{ // already downloaded
index++;
//if( DEBUG ) Core.getOut().println("FILEDN: File exists, increasing index to " + index);
continue; // while
}
else
{
// probably empty, check if other threads currently try to insert to this index
File lockRequestIndex =
new File(testMe.getPath() + ".lock");
boolean lockFileCreated = false;
try
{
lockFileCreated = lockRequestIndex.createNewFile();
}
catch (IOException ex)
{
Core.getOut().println(
"ERROR: requestThread.request(): unexpected IOException, terminating thread ...");
ex.printStackTrace(Core.getOut());
return;
}
if (lockFileCreated == false)
{
// another thread tries to insert using this index, try next
index++;
if (DEBUG)
Core.getOut().println(
"FILEDN: Other thread tries this index, increasing index to "
+ index);
continue; // while
}
else
{
// we try this index
lockRequestIndex.deleteOnExit();
}
// try to insert
//TOTHINK: we could add the ability files from a specific user to be
//requested on separate channels - good protection vs.spam
String[] result = new String[2];
String upKey =
new StringBuffer()
.append("KSK@frost/request/")
.append(
frame1.frostSettings.getValue("messageBase"))
.append("/")
.append(owner)
.append("-")
.append(batch)
.append("-")
.append(date)
.append("-")
.append(index)
.append(".req.sha")
.toString();
if (DEBUG)
Core.getOut().println(upKey);
result =
FcpInsert.putFile(
upKey,
requestFile,
messageUploadHtl,
false); // doRedirect
Core.getOut().println(
"FcpInsert result[0] = "
+ result[0]
+ " result[1] = "
+ result[1]);
if (result[0] == null || result[1] == null)
{
result[0] = "Error";
result[1] = "Error";
}
if (result[0].equals("Success"))
{
success = true;
}
else if (result[0].equals("KeyCollision"))
{
// Check if the collided key is perhapes the requested one
File compareMe = null;
try
{
compareMe =
File.createTempFile(
"reqUploadCmpDnload_",
null,
new File(
frame1.frostSettings.getValue(
"temp.dir")));
}
catch (Exception ex)
{
compareMe =
new File(
frame1.frostSettings.getValue("temp.dir")
+ System.currentTimeMillis()
+ ".tmp");
}
compareMe.deleteOnExit();
String requestMe = upKey;
if (FcpRequest
.getFile(requestMe, null, compareMe, 25, false))
{
File numberOne = compareMe;
File numberTwo = requestFile;
String contentOne =
(FileAccess.readFileRaw(numberOne)).trim();
String contentTwo =
(FileAccess.readFileRaw(numberTwo)).trim();
//if( DEBUG ) Core.getOut().println(contentOne);
//if( DEBUG ) Core.getOut().println(contentTwo);
if (contentOne.equals(contentTwo))
{
if (DEBUG)
Core.getOut().println(
"FILEDN: Key Collision and file was already requested");
success = true;
}
else
{
index++;
Core.getOut().println(
"FILEDN: Request Upload collided, increasing index to "
+ index);
if (frame1
.frostSettings
.getBoolValue("disableRequests")
== true)
{
// uploading is disabled, therefore already existing requests are not
// written to disk, causing key collosions on every request insert.
// this write a .req file to inform others to not try this index again
// if user switches to uploading enabled, this dummy .req files should
// be silently deleted to enable receiving of new requests
FileAccess.writeFile(
KEYCOLL_INDICATOR,
testMe);
}
}
}
else
{
Core.getOut().println(
"FILEDN: Request upload failed ("
+ tries
+ "), retrying index "
+ index);
if (tries > 5)
{
success = true;
error = true;
}
tries++;
}
compareMe.delete();
}
// finally delete the index lock file
lockRequestIndex.delete();
}
}
if (!error)
{
requestFile.renameTo(testMe);
Core.getOut().println(
"*********************************************************************");
Core.getOut().println(
"Request for '"
+ filename
+ "' successfully uploaded to board '"
+ board
+ "'.");
Core.getOut().println(
"*********************************************************************");
}
else
{
Core.getOut().println(
"\nFILEDN: Error while uploading request for '"
+ filename
+ "' to board '"
+ board
+ "'.");
requestFile.delete();
}
Core.getOut().println("FILEDN: Request Upload Thread finished");
}
}
| private void request()
{
int messageUploadHtl = frame1.frostSettings.getIntValue("tofUploadHtl");
boolean requested = false;
if (DEBUG)
Core.getOut().println(
"FILEDN: Uploading request for '"
+ filename
+ "' to board '"
+ board.toString()
+ "'");
String fileSeparator = System.getProperty("file.separator");
String destination =
new StringBuffer()
.append("requests")
.append(fileSeparator)
.append(mixed.makeFilename(owner))
.append("-")
.append(batch)
.append("-")
.append(DateFun.getDate())
.toString();
File checkDestination = new File(destination);
if (!checkDestination.isDirectory())
checkDestination.mkdirs();
// Check if file was already requested
// ++ check only in req files
File[] files = checkDestination.listFiles(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
if (name.endsWith(".req.sha"))
return true;
return false;
}
});
for (int i = 0; i < files.length; i++)
{
String content = (FileAccess.readFileRaw(files[i])).trim();
if (content.equals(SHA1))
{
requested = true;
Core.getOut().println(
"FILEDN: File '" + filename + "' was already requested");
break;
}
}
if (!requested)
{
String date = DateFun.getDate();
String time = DateFun.getFullExtendedTime() + "GMT";
// Generate file to upload
File requestFile = null;
try
{
requestFile =
File.createTempFile(
"reqUpload_",
null,
new File(frame1.frostSettings.getValue("temp.dir")));
}
catch (Exception ex)
{
requestFile =
new File(
frame1.frostSettings.getValue("temp.dir")
+ System.currentTimeMillis()
+ ".tmp");
}
//TOTHINK: we can also encrypt the request
FileAccess.writeFile(SHA1, requestFile);
// Write requested key to disk
// Search empty slot
boolean success = false;
int index = 0;
String output = new String();
int tries = 0;
boolean error = false;
File testMe = null;
while (!success)
{
// Does this index already exist?
testMe =
new File(
new StringBuffer()
.append(destination)
.append(fileSeparator)
.append(index)
.append(".req.sha")
.toString());
if (testMe.length() > 0)
{ // already downloaded
index++;
//if( DEBUG ) Core.getOut().println("FILEDN: File exists, increasing index to " + index);
continue; // while
}
else
{
// probably empty, check if other threads currently try to insert to this index
File lockRequestIndex =
new File(testMe.getPath() + ".lock");
boolean lockFileCreated = false;
try
{
lockFileCreated = lockRequestIndex.createNewFile();
}
catch (IOException ex)
{
Core.getOut().println(
"ERROR: requestThread.request(): unexpected IOException, terminating thread ...");
ex.printStackTrace(Core.getOut());
return;
}
if (lockFileCreated == false)
{
// another thread tries to insert using this index, try next
index++;
if (DEBUG)
Core.getOut().println(
"FILEDN: Other thread tries this index, increasing index to "
+ index);
continue; // while
}
else
{
// we try this index
lockRequestIndex.deleteOnExit();
}
// try to insert
//TOTHINK: we could add the ability files from a specific user to be
//requested on separate channels - good protection vs.spam
String[] result = new String[2];
String upKey =
new StringBuffer()
.append("KSK@frost/request/")
.append(
frame1.frostSettings.getValue("messageBase"))
.append("/")
.append(owner)
.append("-")
.append(batch)
.append("-")
.append(date)
.append("-")
.append(index)
.append(".req.sha")
.toString();
if (DEBUG)
Core.getOut().println(upKey);
result =
FcpInsert.putFile(
upKey,
requestFile,
messageUploadHtl,
false); // doRedirect
Core.getOut().println(
"FcpInsert result[0] = "
+ result[0]
+ " result[1] = "
+ result[1]);
if (result[0] == null || result[1] == null)
{
result[0] = "Error";
result[1] = "Error";
}
if (result[0].equals("Success"))
{
success = true;
}
else if (result[0].equals("KeyCollision"))
{
// Check if the collided key is perhapes the requested one
File compareMe = null;
try
{
compareMe =
File.createTempFile(
"reqUploadCmpDnload_",
null,
new File(
frame1.frostSettings.getValue(
"temp.dir")));
}
catch (Exception ex)
{
compareMe =
new File(
frame1.frostSettings.getValue("temp.dir")
+ System.currentTimeMillis()
+ ".tmp");
}
compareMe.deleteOnExit();
String requestMe = upKey;
if (FcpRequest
.getFile(requestMe, null, compareMe, 25, false))
{
File numberOne = compareMe;
File numberTwo = requestFile;
String contentOne =
(FileAccess.readFileRaw(numberOne)).trim();
String contentTwo =
(FileAccess.readFileRaw(numberTwo)).trim();
//if( DEBUG ) Core.getOut().println(contentOne);
//if( DEBUG ) Core.getOut().println(contentTwo);
if (contentOne.equals(contentTwo))
{
if (DEBUG)
Core.getOut().println(
"FILEDN: Key Collision and file was already requested");
success = true;
}
else
{
index++;
Core.getOut().println(
"FILEDN: Request Upload collided, increasing index to "
+ index);
if (frame1
.frostSettings
.getBoolValue("disableRequests")
== true)
{
// uploading is disabled, therefore already existing requests are not
// written to disk, causing key collosions on every request insert.
// this write a .req file to inform others to not try this index again
// if user switches to uploading enabled, this dummy .req files should
// be silently deleted to enable receiving of new requests
FileAccess.writeFile(
KEYCOLL_INDICATOR,
testMe);
}
}
}
else
{
Core.getOut().println(
"FILEDN: Request upload failed ("
+ tries
+ "), retrying index "
+ index);
if (tries > 5)
{
success = true;
error = true;
}
tries++;
}
compareMe.delete();
}
// finally delete the index lock file
lockRequestIndex.delete();
}
}
if (!error)
{
requestFile.renameTo(testMe);
Core.getOut().println(
"*********************************************************************");
Core.getOut().println(
"Request for '"
+ filename
+ "' successfully uploaded to board '"
+ board
+ "'.");
Core.getOut().println(
"*********************************************************************");
}
else
{
Core.getOut().println(
"\nFILEDN: Error while uploading request for '"
+ filename
+ "' to board '"
+ board
+ "'.");
requestFile.delete();
}
Core.getOut().println("FILEDN: Request Upload Thread finished");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.